dynamic-settings-widget 2.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (90) hide show
  1. dynamic_settings_widget/__init__.py +56 -0
  2. dynamic_settings_widget/adapters/__init__.py +42 -0
  3. dynamic_settings_widget/adapters/base.py +179 -0
  4. dynamic_settings_widget/adapters/memory.py +201 -0
  5. dynamic_settings_widget/adapters/runner.py +63 -0
  6. dynamic_settings_widget/core/__init__.py +1 -0
  7. dynamic_settings_widget/core/catalog.py +201 -0
  8. dynamic_settings_widget/core/common.py +214 -0
  9. dynamic_settings_widget/core/conditions.py +146 -0
  10. dynamic_settings_widget/core/datatypes.py +414 -0
  11. dynamic_settings_widget/core/diagnostics.py +69 -0
  12. dynamic_settings_widget/core/loader.py +101 -0
  13. dynamic_settings_widget/core/model.py +245 -0
  14. dynamic_settings_widget/core/overrides.py +353 -0
  15. dynamic_settings_widget/core/parser.py +552 -0
  16. dynamic_settings_widget/core/presentation.py +68 -0
  17. dynamic_settings_widget/core/registry.py +258 -0
  18. dynamic_settings_widget/core/state.py +314 -0
  19. dynamic_settings_widget/data/example_catalog.json +23 -0
  20. dynamic_settings_widget/data/example_layout.json +23 -0
  21. dynamic_settings_widget/data/settings_catalog.schema.json +388 -0
  22. dynamic_settings_widget/data/settings_definition.schema.json +1041 -0
  23. dynamic_settings_widget/data/settings_layout.schema.json +701 -0
  24. dynamic_settings_widget/data/settings_override.schema.json +406 -0
  25. dynamic_settings_widget/py.typed +0 -0
  26. dynamic_settings_widget/session.py +1537 -0
  27. dynamic_settings_widget/standalone/__init__.py +67 -0
  28. dynamic_settings_widget/standalone/action_button.py +200 -0
  29. dynamic_settings_widget/standalone/auth_widget.py +377 -0
  30. dynamic_settings_widget/standalone/check_box_editor.py +233 -0
  31. dynamic_settings_widget/standalone/choice_buttons_editor.py +394 -0
  32. dynamic_settings_widget/standalone/color_editor.py +316 -0
  33. dynamic_settings_widget/standalone/dropdown_editor.py +356 -0
  34. dynamic_settings_widget/standalone/editable_label.py +428 -0
  35. dynamic_settings_widget/standalone/float_spin_box.py +621 -0
  36. dynamic_settings_widget/standalone/font_editor.py +348 -0
  37. dynamic_settings_widget/standalone/hotkey_editor.py +681 -0
  38. dynamic_settings_widget/standalone/info_label.py +190 -0
  39. dynamic_settings_widget/standalone/int_spin_box.py +627 -0
  40. dynamic_settings_widget/standalone/multi_choice_editor.py +428 -0
  41. dynamic_settings_widget/standalone/password_editor.py +348 -0
  42. dynamic_settings_widget/standalone/path_editor.py +615 -0
  43. dynamic_settings_widget/standalone/protected_group_box.py +287 -0
  44. dynamic_settings_widget/standalone/server_connection_editor.py +642 -0
  45. dynamic_settings_widget/standalone/slider_spin_box.py +840 -0
  46. dynamic_settings_widget/standalone/sound_selection_widget.py +710 -0
  47. dynamic_settings_widget/standalone/status_label.py +148 -0
  48. dynamic_settings_widget/standalone/switch_editor.py +293 -0
  49. dynamic_settings_widget/standalone/text_editor.py +265 -0
  50. dynamic_settings_widget/testlab/__init__.py +1 -0
  51. dynamic_settings_widget/testlab/__main__.py +5 -0
  52. dynamic_settings_widget/testlab/app.py +699 -0
  53. dynamic_settings_widget/testlab/assets/extra_sounds/Signal.wav +0 -0
  54. dynamic_settings_widget/testlab/assets/sounds/Benachrichtigung.wav +0 -0
  55. dynamic_settings_widget/testlab/assets/sounds/feedback/Signal.wav +0 -0
  56. dynamic_settings_widget/testlab/definitions/broken_base.json +25 -0
  57. dynamic_settings_widget/testlab/definitions/demo.json +634 -0
  58. dynamic_settings_widget/testlab/definitions/gallery.json +255 -0
  59. dynamic_settings_widget/testlab/definitions/override_example.json +41 -0
  60. dynamic_settings_widget/testlab/definitions/override_invalid.json +11 -0
  61. dynamic_settings_widget/testlab/definitions/override_syntax_error.json +5 -0
  62. dynamic_settings_widget/testlab/definitions/override_weaken.json +10 -0
  63. dynamic_settings_widget/testlab/definitions/voice_v2/01_left_top.json +1190 -0
  64. dynamic_settings_widget/testlab/definitions/voice_v2/catalog.json +1930 -0
  65. dynamic_settings_widget/testlab/definitions/voice_v2/models.json +141 -0
  66. dynamic_settings_widget/testlab/definitions/voice_v2/wakewords.json +161 -0
  67. dynamic_settings_widget/testlab/dummy.py +353 -0
  68. dynamic_settings_widget/testlab/extensions.py +149 -0
  69. dynamic_settings_widget/testlab/gallery.py +223 -0
  70. dynamic_settings_widget/testlab/http_adapter.py +430 -0
  71. dynamic_settings_widget/testlab/http_server.py +493 -0
  72. dynamic_settings_widget/testlab/voice_v2.py +251 -0
  73. dynamic_settings_widget/ui/__init__.py +23 -0
  74. dynamic_settings_widget/ui/base.py +63 -0
  75. dynamic_settings_widget/ui/builders.py +226 -0
  76. dynamic_settings_widget/ui/containers.py +441 -0
  77. dynamic_settings_widget/ui/dialog.py +231 -0
  78. dynamic_settings_widget/ui/editing.py +51 -0
  79. dynamic_settings_widget/ui/row.py +810 -0
  80. dynamic_settings_widget/ui/view.py +248 -0
  81. dynamic_settings_widget/widgets/__init__.py +74 -0
  82. dynamic_settings_widget/widgets/base.py +145 -0
  83. dynamic_settings_widget/widgets/bridge.py +222 -0
  84. dynamic_settings_widget/widgets/theme.py +107 -0
  85. dynamic_settings_widget-2.0.0.dist-info/METADATA +237 -0
  86. dynamic_settings_widget-2.0.0.dist-info/RECORD +90 -0
  87. dynamic_settings_widget-2.0.0.dist-info/WHEEL +5 -0
  88. dynamic_settings_widget-2.0.0.dist-info/entry_points.txt +5 -0
  89. dynamic_settings_widget-2.0.0.dist-info/licenses/LICENSE +21 -0
  90. dynamic_settings_widget-2.0.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,316 @@
1
+ # MIT License
2
+ #
3
+ # Copyright (c) 2026 marcosudau-vps
4
+ #
5
+ # Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ # of this software and associated documentation files (the "Software"), to deal
7
+ # in the Software without restriction, including without limitation the rights
8
+ # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ # copies of the Software, and to permit persons to whom the Software is
10
+ # furnished to do so, subject to the following conditions:
11
+ #
12
+ # The above copyright notice and this permission notice shall be included in all
13
+ # copies or substantial portions of the Software.
14
+ #
15
+ # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ # SOFTWARE.
22
+
23
+ """ColorEditor – Farbwert als Text (#RRGGBB) mit Vorschau und Farbdialog.
24
+
25
+ Autarke Einzeldatei: benötigt nur Python ≥ 3.11 und PySide6 (Essentials).
26
+
27
+ Beispiel::
28
+
29
+ from color_editor import ColorEditor
30
+
31
+ color = ColorEditor()
32
+ color.configure(alpha=True) # erlaubt zusätzlich #AARRGGBB
33
+ color.set_value("#33AA77")
34
+ color.value_edited.connect(print)
35
+
36
+ Ungültige Eingaben werden nicht umgewandelt: ``value()`` liefert den Text,
37
+ ``input_error()`` nennt das erwartete Format. Optionen (``configure``): ``optional``, ``alpha``.
38
+ """
39
+
40
+ from __future__ import annotations
41
+
42
+ import re
43
+ from contextlib import contextmanager
44
+ from typing import Any
45
+
46
+ from PySide6.QtCore import QSize, Signal
47
+ from PySide6.QtGui import QBrush, QColor, QIcon, QPainter, QPalette, QPixmap
48
+ from PySide6.QtWidgets import QColorDialog, QHBoxLayout, QLineEdit, QPushButton, QWidget
49
+
50
+ __all__ = ["ColorEditor"]
51
+
52
+ _HEX = re.compile(r"#[0-9A-Fa-f]{6}")
53
+ _HEX_ALPHA = re.compile(r"#(?:[0-9A-Fa-f]{6}|[0-9A-Fa-f]{8})")
54
+
55
+
56
+ # ── Wertbasis ─ identisch in allen Editor-Dateien (bewusst kopiert, Test prüft Gleichheit) ──
57
+ def _same(a: Any, b: Any) -> bool:
58
+ """Gleichheit ohne Pythons ``True == 1``-Vermischung."""
59
+ if a is b:
60
+ return True
61
+ if isinstance(a, bool) != isinstance(b, bool):
62
+ return False
63
+ if isinstance(a, list) and isinstance(b, list):
64
+ return len(a) == len(b) and all(_same(x, y) for x, y in zip(a, b))
65
+ if isinstance(a, dict) and isinstance(b, dict):
66
+ return a.keys() == b.keys() and all(_same(a[k], b[k]) for k in a)
67
+ try:
68
+ return bool(a == b)
69
+ except Exception: # noqa: BLE001 – fremde Typen ohne Vergleich
70
+ return False
71
+
72
+
73
+ class _ValueWidget(QWidget):
74
+ """Gemeinsamer Vertrag aller Editoren.
75
+
76
+ * ``value()`` / ``set_value(v)`` – ``None`` bedeutet „nicht gesetzt“; ein Wert falschen
77
+ Typs löst ``ValueError`` aus und wird nie still umgewandelt.
78
+ * ``value_changed(object)`` – jede Wertänderung, auch programmatisch.
79
+ * ``value_edited(object)`` – nur Änderungen durch den Benutzer.
80
+ * ``configure(**optionen)`` – Schlüssel aus ``OPTIONS``; unbekannte → ``TypeError``.
81
+ * ``set_read_only(bool)``, ``input_error()`` / ``input_error_changed(str)``, ``commit()``.
82
+ """
83
+
84
+ value_changed = Signal(object)
85
+ value_edited = Signal(object)
86
+ input_error_changed = Signal(str)
87
+
88
+ #: Schlüssel, die ``configure()`` annimmt.
89
+ OPTIONS: tuple[str, ...] = ("optional",)
90
+
91
+ def __init__(self, parent: QWidget | None = None) -> None:
92
+ super().__init__(parent)
93
+ self._optional = False
94
+ self._read_only = False
95
+ self._silent = 0
96
+ self._last_error = ""
97
+
98
+ # -- von Unterklassen bereitzustellen ------------------------------------------------
99
+ def value(self) -> Any:
100
+ raise NotImplementedError
101
+
102
+ def _apply_value(self, value: Any) -> None:
103
+ raise NotImplementedError
104
+
105
+ def _apply_options(self) -> None:
106
+ """Darstellung nach ``configure()`` nachführen."""
107
+
108
+ def _apply_read_only(self, read_only: bool) -> None:
109
+ self.setEnabled(not read_only)
110
+
111
+ def input_error(self) -> str:
112
+ """Grund, warum die aktuelle Eingabe keinen gültigen Wert ergibt (sonst leer)."""
113
+ return ""
114
+
115
+ def commit(self) -> None:
116
+ """Schließt eine angefangene Eingabe ab."""
117
+
118
+ # -- öffentliche Schnittstelle --------------------------------------------------------
119
+ def set_value(self, value: Any) -> None:
120
+ """Setzt den Wert programmatisch (ohne ``value_edited``)."""
121
+ old = self.value()
122
+ with self._programmatic():
123
+ self._apply_value(value)
124
+ new = self.value()
125
+ if not _same(old, new):
126
+ self.value_changed.emit(new)
127
+ self._check_error()
128
+
129
+ def configure(self, **options: Any) -> None:
130
+ """Setzt mehrere Optionen auf einmal, z. B. ``configure(optional=True)``."""
131
+ unknown = sorted(set(options) - set(self.OPTIONS))
132
+ if unknown:
133
+ raise TypeError(f"{type(self).__name__}: unbekannte Option(en) {', '.join(unknown)}")
134
+ for key, value in options.items():
135
+ self._set_option(key, value)
136
+ with self._programmatic():
137
+ self._apply_options()
138
+ self._check_error()
139
+
140
+ def options(self) -> dict[str, Any]:
141
+ """Aktuelle Optionen."""
142
+ return {key: getattr(self, f"_{key}") for key in self.OPTIONS}
143
+
144
+ def _set_option(self, key: str, value: Any) -> None:
145
+ if key == "optional":
146
+ value = bool(value)
147
+ setattr(self, f"_{key}", value)
148
+
149
+ def set_optional(self, optional: bool) -> None:
150
+ self.configure(optional=optional)
151
+
152
+ def is_optional(self) -> bool:
153
+ return self._optional
154
+
155
+ def set_read_only(self, read_only: bool) -> None:
156
+ self._read_only = bool(read_only)
157
+ self._apply_read_only(self._read_only)
158
+
159
+ def is_read_only(self) -> bool:
160
+ return self._read_only
161
+
162
+ # -- Hilfen für Unterklassen ----------------------------------------------------------
163
+ @contextmanager
164
+ def _programmatic(self):
165
+ self._silent += 1
166
+ try:
167
+ yield
168
+ finally:
169
+ self._silent -= 1
170
+
171
+ def _user_changed(self, *_: Any) -> None:
172
+ """Nach einer echten Benutzereingabe aufzurufen."""
173
+ if self._silent:
174
+ return
175
+ value = self.value()
176
+ self._check_error()
177
+ self.value_changed.emit(value)
178
+ self.value_edited.emit(value)
179
+
180
+ def _check_error(self) -> None:
181
+ error = self.input_error()
182
+ if error != self._last_error:
183
+ self._last_error = error
184
+ self.input_error_changed.emit(error)
185
+ # ── Ende Wertbasis ──
186
+
187
+
188
+ class ColorEditor(_ValueWidget):
189
+ """Farbwert mit Vorschau und Auswahldialog."""
190
+
191
+ OPTIONS = ("optional", "alpha")
192
+
193
+ def __init__(self, parent: QWidget | None = None) -> None:
194
+ super().__init__(parent)
195
+ self._null = False
196
+ self._alpha = False
197
+ layout = QHBoxLayout(self)
198
+ layout.setContentsMargins(0, 0, 0, 0)
199
+ layout.setSpacing(6)
200
+ self._swatch = QPushButton(self)
201
+ self._swatch.setFixedSize(38, 24)
202
+ self._swatch.setIconSize(QSize(28, 14))
203
+ self._swatch.setAutoDefault(False)
204
+ self._swatch.setToolTip("Farbe auswählen")
205
+ self._swatch.setAccessibleName("Farbe auswählen")
206
+ self._swatch.clicked.connect(self._pick)
207
+ self._edit = QLineEdit("#000000", self)
208
+ self._edit.setMaximumWidth(120)
209
+ self._edit.setMinimumWidth(80)
210
+ self._edit.textEdited.connect(self._on_text)
211
+ layout.addWidget(self._swatch)
212
+ layout.addWidget(self._edit)
213
+ layout.addStretch(1)
214
+ self.setFocusProxy(self._edit)
215
+ self._apply_options()
216
+
217
+ @property
218
+ def line_edit(self) -> QLineEdit:
219
+ return self._edit
220
+
221
+ def _pattern(self) -> re.Pattern[str]:
222
+ return _HEX_ALPHA if self._alpha else _HEX
223
+
224
+ def input_error(self) -> str:
225
+ text = self._edit.text().strip()
226
+ if not text and (self._null or self._optional):
227
+ return ""
228
+ if self._pattern().fullmatch(text):
229
+ return ""
230
+ return "Farbe im Format #RRGGBB" + (" oder #AARRGGBB" if self._alpha else "") + " eingeben"
231
+
232
+ def value(self) -> str | None:
233
+ """Gültiger Farbwert oder der eingegebene Text (siehe ``input_error``)."""
234
+ text = self._edit.text().strip()
235
+ if not text and (self._null or self._optional):
236
+ return None
237
+ return text
238
+
239
+ def _on_text(self, *_: Any) -> None:
240
+ self._null = False
241
+ self._paint_swatch()
242
+ self._user_changed()
243
+
244
+ def choose(self, current: QColor) -> QColor:
245
+ """Öffnet den Farbdialog (in Tests ersetzbar)."""
246
+ options = QColorDialog.ColorDialogOption(0)
247
+ if self._alpha:
248
+ options = QColorDialog.ColorDialogOption.ShowAlphaChannel
249
+ return QColorDialog.getColor(current, self, "Farbe auswählen", options)
250
+
251
+ def _pick(self) -> None:
252
+ if self._read_only:
253
+ return
254
+ visible = self.isVisible()
255
+ chosen = self.choose(QColor(self._edit.text()))
256
+ if chosen.isValid() and not self._read_only and (not visible or self.isVisible()):
257
+ hex_format = QColor.NameFormat.HexArgb if self._alpha and chosen.alpha() < 255 else QColor.NameFormat.HexRgb
258
+ self._edit.setText(chosen.name(hex_format).upper())
259
+ self._on_text()
260
+
261
+ def _apply_value(self, value: Any) -> None:
262
+ if value is not None and (not isinstance(value, str) or not _HEX_ALPHA.fullmatch(value)):
263
+ raise ValueError("Farbe im Format #RRGGBB erwartet")
264
+ self._null = value is None
265
+ self._edit.setText(value or "")
266
+ self._paint_swatch()
267
+
268
+ def _apply_options(self) -> None:
269
+ self._edit.setPlaceholderText("nicht gesetzt" if self._optional else "#RRGGBB")
270
+ self._paint_swatch()
271
+
272
+ def _paint_swatch(self) -> None:
273
+ pixmap = QPixmap(28, 14)
274
+ palette = self.palette()
275
+ pixmap.fill(palette.color(QPalette.ColorRole.Base))
276
+ painter = QPainter(pixmap)
277
+ color = QColor(self._edit.text().strip())
278
+ if color.isValid():
279
+ if color.alpha() < 255: # Schachbrett zeigt Transparenz
280
+ for x in range(0, 28, 7):
281
+ for y in range(0, 14, 7):
282
+ if (x + y) // 7 % 2:
283
+ painter.fillRect(x, y, 7, 7, QColor("#c8c8c8"))
284
+ painter.fillRect(pixmap.rect(), QBrush(color))
285
+ else:
286
+ painter.setPen(palette.color(QPalette.ColorRole.WindowText))
287
+ painter.drawLine(0, 13, 27, 0)
288
+ painter.setPen(palette.color(QPalette.ColorRole.Mid))
289
+ painter.drawRect(0, 0, 27, 13)
290
+ painter.end()
291
+ self._swatch.setIcon(QIcon(pixmap))
292
+
293
+ def changeEvent(self, event) -> None:
294
+ super().changeEvent(event)
295
+ if event.type() == event.Type.PaletteChange and hasattr(self, "_swatch"):
296
+ self._paint_swatch()
297
+
298
+ def _apply_read_only(self, read_only: bool) -> None:
299
+ self._edit.setReadOnly(read_only)
300
+ self._swatch.setEnabled(not read_only)
301
+
302
+
303
+ def _demo() -> None: # pragma: no cover – python color_editor.py
304
+ from PySide6.QtWidgets import QApplication
305
+
306
+ app = QApplication.instance() or QApplication([])
307
+ color = ColorEditor()
308
+ color.configure(alpha=True)
309
+ color.set_value("#33AA77")
310
+ color.value_edited.connect(print)
311
+ color.show()
312
+ app.exec()
313
+
314
+
315
+ if __name__ == "__main__":
316
+ _demo()
@@ -0,0 +1,356 @@
1
+ # MIT License
2
+ #
3
+ # Copyright (c) 2026 marcosudau-vps
4
+ #
5
+ # Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ # of this software and associated documentation files (the "Software"), to deal
7
+ # in the Software without restriction, including without limitation the rights
8
+ # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ # copies of the Software, and to permit persons to whom the Software is
10
+ # furnished to do so, subject to the following conditions:
11
+ #
12
+ # The above copyright notice and this permission notice shall be included in all
13
+ # copies or substantial portions of the Software.
14
+ #
15
+ # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ # SOFTWARE.
22
+
23
+ """DropdownEditor – Auswahl genau eines beschrifteten Werts aus einer Liste.
24
+
25
+ Autarke Einzeldatei: benötigt nur Python ≥ 3.11 und PySide6 (Essentials).
26
+
27
+ Beispiel::
28
+
29
+ from dropdown_editor import DropdownEditor
30
+
31
+ combo = DropdownEditor(placeholder="Bitte wählen")
32
+ combo.set_choices([("de", "Deutsch"), ("en", "Englisch"), {"value": "fr", "label": "Französisch"}])
33
+ combo.set_value("de")
34
+ combo.value_edited.connect(print)
35
+
36
+ Werte dürfen Text, Zahl oder Wahrheitswert sein und behalten ihren Typ (``True`` bleibt
37
+ ``True``, nicht ``1``). Ist der aktuelle Wert nicht (mehr) in der Liste, bleibt er als
38
+ „⚠ … (nicht verfügbar)“ sichtbar, statt still ersetzt zu werden. Das Mausrad wirkt nur
39
+ mit Fokus. Optionen (``configure``): ``optional`` (Eintrag „— nicht gesetzt —“), ``placeholder``.
40
+ """
41
+
42
+ from __future__ import annotations
43
+
44
+ import math
45
+ from contextlib import contextmanager
46
+ from collections.abc import Iterable
47
+ from typing import Any
48
+
49
+ from PySide6.QtCore import QEvent, QObject, Qt, Signal
50
+ from PySide6.QtWidgets import QComboBox, QHBoxLayout, QWidget
51
+
52
+ __all__ = ["DropdownEditor"]
53
+
54
+ _VALUE = Qt.ItemDataRole.UserRole
55
+
56
+
57
+ # ── Wertbasis ─ identisch in allen Editor-Dateien (bewusst kopiert, Test prüft Gleichheit) ──
58
+ def _same(a: Any, b: Any) -> bool:
59
+ """Gleichheit ohne Pythons ``True == 1``-Vermischung."""
60
+ if a is b:
61
+ return True
62
+ if isinstance(a, bool) != isinstance(b, bool):
63
+ return False
64
+ if isinstance(a, list) and isinstance(b, list):
65
+ return len(a) == len(b) and all(_same(x, y) for x, y in zip(a, b))
66
+ if isinstance(a, dict) and isinstance(b, dict):
67
+ return a.keys() == b.keys() and all(_same(a[k], b[k]) for k in a)
68
+ try:
69
+ return bool(a == b)
70
+ except Exception: # noqa: BLE001 – fremde Typen ohne Vergleich
71
+ return False
72
+
73
+
74
+ class _ValueWidget(QWidget):
75
+ """Gemeinsamer Vertrag aller Editoren.
76
+
77
+ * ``value()`` / ``set_value(v)`` – ``None`` bedeutet „nicht gesetzt“; ein Wert falschen
78
+ Typs löst ``ValueError`` aus und wird nie still umgewandelt.
79
+ * ``value_changed(object)`` – jede Wertänderung, auch programmatisch.
80
+ * ``value_edited(object)`` – nur Änderungen durch den Benutzer.
81
+ * ``configure(**optionen)`` – Schlüssel aus ``OPTIONS``; unbekannte → ``TypeError``.
82
+ * ``set_read_only(bool)``, ``input_error()`` / ``input_error_changed(str)``, ``commit()``.
83
+ """
84
+
85
+ value_changed = Signal(object)
86
+ value_edited = Signal(object)
87
+ input_error_changed = Signal(str)
88
+
89
+ #: Schlüssel, die ``configure()`` annimmt.
90
+ OPTIONS: tuple[str, ...] = ("optional",)
91
+
92
+ def __init__(self, parent: QWidget | None = None) -> None:
93
+ super().__init__(parent)
94
+ self._optional = False
95
+ self._read_only = False
96
+ self._silent = 0
97
+ self._last_error = ""
98
+
99
+ # -- von Unterklassen bereitzustellen ------------------------------------------------
100
+ def value(self) -> Any:
101
+ raise NotImplementedError
102
+
103
+ def _apply_value(self, value: Any) -> None:
104
+ raise NotImplementedError
105
+
106
+ def _apply_options(self) -> None:
107
+ """Darstellung nach ``configure()`` nachführen."""
108
+
109
+ def _apply_read_only(self, read_only: bool) -> None:
110
+ self.setEnabled(not read_only)
111
+
112
+ def input_error(self) -> str:
113
+ """Grund, warum die aktuelle Eingabe keinen gültigen Wert ergibt (sonst leer)."""
114
+ return ""
115
+
116
+ def commit(self) -> None:
117
+ """Schließt eine angefangene Eingabe ab."""
118
+
119
+ # -- öffentliche Schnittstelle --------------------------------------------------------
120
+ def set_value(self, value: Any) -> None:
121
+ """Setzt den Wert programmatisch (ohne ``value_edited``)."""
122
+ old = self.value()
123
+ with self._programmatic():
124
+ self._apply_value(value)
125
+ new = self.value()
126
+ if not _same(old, new):
127
+ self.value_changed.emit(new)
128
+ self._check_error()
129
+
130
+ def configure(self, **options: Any) -> None:
131
+ """Setzt mehrere Optionen auf einmal, z. B. ``configure(optional=True)``."""
132
+ unknown = sorted(set(options) - set(self.OPTIONS))
133
+ if unknown:
134
+ raise TypeError(f"{type(self).__name__}: unbekannte Option(en) {', '.join(unknown)}")
135
+ for key, value in options.items():
136
+ self._set_option(key, value)
137
+ with self._programmatic():
138
+ self._apply_options()
139
+ self._check_error()
140
+
141
+ def options(self) -> dict[str, Any]:
142
+ """Aktuelle Optionen."""
143
+ return {key: getattr(self, f"_{key}") for key in self.OPTIONS}
144
+
145
+ def _set_option(self, key: str, value: Any) -> None:
146
+ if key == "optional":
147
+ value = bool(value)
148
+ setattr(self, f"_{key}", value)
149
+
150
+ def set_optional(self, optional: bool) -> None:
151
+ self.configure(optional=optional)
152
+
153
+ def is_optional(self) -> bool:
154
+ return self._optional
155
+
156
+ def set_read_only(self, read_only: bool) -> None:
157
+ self._read_only = bool(read_only)
158
+ self._apply_read_only(self._read_only)
159
+
160
+ def is_read_only(self) -> bool:
161
+ return self._read_only
162
+
163
+ # -- Hilfen für Unterklassen ----------------------------------------------------------
164
+ @contextmanager
165
+ def _programmatic(self):
166
+ self._silent += 1
167
+ try:
168
+ yield
169
+ finally:
170
+ self._silent -= 1
171
+
172
+ def _user_changed(self, *_: Any) -> None:
173
+ """Nach einer echten Benutzereingabe aufzurufen."""
174
+ if self._silent:
175
+ return
176
+ value = self.value()
177
+ self._check_error()
178
+ self.value_changed.emit(value)
179
+ self.value_edited.emit(value)
180
+
181
+ def _check_error(self) -> None:
182
+ error = self.input_error()
183
+ if error != self._last_error:
184
+ self._last_error = error
185
+ self.input_error_changed.emit(error)
186
+ # ── Ende Wertbasis ──
187
+
188
+
189
+ # ── Mausrad-Schutz ─ identisch in allen Dateien mit Rad-empfindlichen Feldern (bewusst kopiert) ──
190
+ class _WheelGuard(QObject):
191
+ """Verhindert versehentliche Wertänderungen beim Scrollen einer Seite (nur mit Fokus)."""
192
+
193
+ def eventFilter(self, obj: QObject, event: QEvent) -> bool:
194
+ if event.type() == QEvent.Type.Wheel and isinstance(obj, QWidget) and not obj.hasFocus():
195
+ event.ignore()
196
+ return True
197
+ return False
198
+
199
+
200
+ def _guard_wheel(widget: QWidget) -> None:
201
+ guard = widget.findChild(_WheelGuard, "_wheel_guard")
202
+ if guard is None:
203
+ guard = _WheelGuard(widget)
204
+ guard.setObjectName("_wheel_guard")
205
+ widget.setFocusPolicy(Qt.FocusPolicy.StrongFocus)
206
+ widget.installEventFilter(guard)
207
+ # ── Ende Mausrad-Schutz ──
208
+
209
+
210
+ # ── Auswahloptionen ─ identisch in allen Dateien mit Auswahllisten (bewusst kopiert) ──
211
+ def _is_scalar(value: Any) -> bool:
212
+ return isinstance(value, (str, int, float, bool)) and not (isinstance(value, float) and not math.isfinite(value))
213
+
214
+
215
+ class _Choice:
216
+ """Ein auswählbarer Wert mit Beschriftung (intern; nimmt Qt-Umwandlungen wie bool↔int aus dem Spiel)."""
217
+
218
+ __slots__ = ("value", "label", "description", "available", "unavailable_reason")
219
+
220
+ def __init__(self, value: Any, label: str, description: str = "",
221
+ available: bool = True, unavailable_reason: str = "") -> None:
222
+ self.value, self.label, self.description = value, label, description
223
+ self.available, self.unavailable_reason = available, unavailable_reason
224
+
225
+ @classmethod
226
+ def parse(cls, raw: Any) -> "_Choice":
227
+ """Akzeptiert Skalar, ``(value, label[, description])``, ``{"value", "label", "description"}``
228
+ oder ein Objekt mit den Attributen ``value``/``label``/``description``."""
229
+ available, reason = True, ""
230
+ if isinstance(raw, dict):
231
+ if "value" not in raw or set(raw) - {"value", "label", "description", "available", "unavailable_reason"}:
232
+ raise ValueError(f"Auswahloption {raw!r}: erwartet value, label, description")
233
+ value, label, description = raw["value"], raw.get("label", str(raw["value"])), raw.get("description", "")
234
+ available, reason = raw.get("available", True), raw.get("unavailable_reason", "")
235
+ elif isinstance(raw, (tuple, list)):
236
+ if not 1 <= len(raw) <= 3:
237
+ raise ValueError(f"Auswahloption {raw!r}: erwartet (value, label[, description])")
238
+ value, label, description = raw[0], (raw[1] if len(raw) > 1 else str(raw[0])), (raw[2] if len(raw) > 2 else "")
239
+ elif _is_scalar(raw):
240
+ value, label, description = raw, str(raw), ""
241
+ elif hasattr(raw, "value") and hasattr(raw, "label"):
242
+ value, label, description = raw.value, raw.label, getattr(raw, "description", "") or ""
243
+ available, reason = getattr(raw, "available", True), getattr(raw, "unavailable_reason", "")
244
+ else:
245
+ raise ValueError(f"Auswahloption {raw!r} nicht lesbar")
246
+ if not _is_scalar(value):
247
+ raise ValueError(f"Auswahlwert {value!r} muss Text, Zahl oder Wahrheitswert sein")
248
+ if not isinstance(label, str) or not isinstance(description, str):
249
+ raise ValueError(f"Auswahloption {value!r}: label/description müssen Text sein")
250
+ if type(available) is not bool or not isinstance(reason, str):
251
+ raise ValueError("available muss boolesch und unavailable_reason Text sein")
252
+ return cls(value, label, description, available, reason)
253
+ # ── Ende Auswahloptionen ──
254
+
255
+
256
+ class DropdownEditor(_ValueWidget):
257
+ """Auswahl aus beschrifteten Werten."""
258
+
259
+ OPTIONS = ("optional", "placeholder")
260
+
261
+ def __init__(self, parent: QWidget | None = None, *, placeholder: str = "Bitte auswählen") -> None:
262
+ super().__init__(parent)
263
+ self._options: list[_Choice] = []
264
+ self._current: Any = None
265
+ self._placeholder = placeholder
266
+ layout = QHBoxLayout(self)
267
+ layout.setContentsMargins(0, 0, 0, 0)
268
+ self._combo = QComboBox(self)
269
+ self._combo.setSizeAdjustPolicy(QComboBox.SizeAdjustPolicy.AdjustToMinimumContentsLengthWithIcon)
270
+ self._combo.setMinimumContentsLength(10)
271
+ _guard_wheel(self._combo)
272
+ self._combo.activated.connect(self._on_activated)
273
+ layout.addWidget(self._combo)
274
+ self.setFocusProxy(self._combo)
275
+ self._apply_options()
276
+
277
+ @property
278
+ def combo_box(self) -> QComboBox:
279
+ return self._combo
280
+
281
+ def set_choices(self, choices: Iterable[Any]) -> None:
282
+ """Neue Auswahlliste; der aktuelle Wert bleibt erhalten (ggf. als „nicht verfügbar“)."""
283
+ self._options = [_Choice.parse(c) for c in choices]
284
+ with self._programmatic():
285
+ self._rebuild()
286
+
287
+ def choices(self) -> list[dict[str, Any]]:
288
+ return [
289
+ {"value": o.value, "label": o.label, "description": o.description,
290
+ **({"available": False} if not o.available else {}),
291
+ **({"unavailable_reason": o.unavailable_reason} if o.unavailable_reason else {})}
292
+ for o in self._options
293
+ ]
294
+
295
+ def _on_activated(self, index: int) -> None:
296
+ box = self._combo.itemData(index, _VALUE)
297
+ if box is None or not box.available or self._read_only:
298
+ with self._programmatic():
299
+ self._rebuild()
300
+ return
301
+ if _same(box.value, self._current):
302
+ return
303
+ self._current = box.value
304
+ with self._programmatic():
305
+ self._rebuild()
306
+ self._user_changed()
307
+
308
+ def value(self) -> Any:
309
+ return self._current
310
+
311
+ def _apply_value(self, value: Any) -> None:
312
+ if value is not None and not _is_scalar(value):
313
+ raise ValueError("Skalarer Auswahlwert erwartet")
314
+ self._current = value
315
+ self._rebuild()
316
+
317
+ def _apply_options(self) -> None:
318
+ self._combo.setPlaceholderText(self._placeholder)
319
+ self._rebuild()
320
+
321
+ def _rebuild(self) -> None:
322
+ self._combo.clear()
323
+ if self._optional:
324
+ self._combo.addItem("— nicht gesetzt —", _Choice(None, ""))
325
+ options = list(self._options)
326
+ if self._current is not None and not any(_same(self._current, o.value) for o in self._options):
327
+ options.append(_Choice(self._current, str(self._current), available=False))
328
+ for option in options:
329
+ label = option.label if option.available else f"⚠ {option.label} (nicht verfügbar)"
330
+ self._combo.addItem(label, option)
331
+ index = self._combo.count() - 1
332
+ tooltip = "\n".join(filter(None, (option.description, option.unavailable_reason)))
333
+ if tooltip:
334
+ self._combo.setItemData(index, tooltip, Qt.ItemDataRole.ToolTipRole)
335
+ if not option.available:
336
+ self._combo.model().item(index).setEnabled(False)
337
+ index = -1
338
+ for position in range(self._combo.count()):
339
+ if _same(self._combo.itemData(position, _VALUE).value, self._current):
340
+ index = position
341
+ self._combo.setCurrentIndex(index)
342
+
343
+
344
+ def _demo() -> None: # pragma: no cover – python dropdown_editor.py
345
+ from PySide6.QtWidgets import QApplication
346
+
347
+ app = QApplication.instance() or QApplication([])
348
+ combo = DropdownEditor()
349
+ combo.set_choices([("de", "Deutsch"), ("en", "Englisch")])
350
+ combo.value_edited.connect(print)
351
+ combo.show()
352
+ app.exec()
353
+
354
+
355
+ if __name__ == "__main__":
356
+ _demo()