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,642 @@
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
+ """ServerConnectionEditor – Serveradresse und Endpunkt mit URL-Vorschau, Test und getrennter Übernahme.
24
+
25
+ Autarke Einzeldatei: benötigt nur Python ≥ 3.11 und PySide6 (Essentials). Enthält
26
+ außerdem ``compose_url()`` und ``ConnectionInputError`` (auch ohne Widget nutzbar).
27
+
28
+ Beispiel::
29
+
30
+ from server_connection_editor import ServerConnectionEditor, compose_url
31
+
32
+ editor = ServerConnectionEditor(schemes=["https", "http"], endpoints=["/api/v1", "/api/v2"])
33
+ editor.set_value({"address": "localhost:8765", "endpoint": "/api/v1"})
34
+ editor.test_requested.connect(lambda p: editor.show_result(True, "erreichbar")) # p: address, endpoint, url
35
+ editor.apply_requested.connect(lambda p: print("verbinden mit", p["url"]))
36
+ compose_url("example.org", "/api") # → "http://example.org/api"
37
+
38
+ Ein Test ändert nichts; die Übernahme ist eine eigene Aktion. Das Widget baut selbst
39
+ keine Verbindung auf – das übernimmt die Anwendung über die beiden Signale und meldet
40
+ mit ``set_busy()``/``show_result()`` zurück. Ergebnisse zu inzwischen geänderten Eingaben
41
+ werden als „vorherige Eingabe“ gekennzeichnet. Zugangsdaten in der Adresse werden abgelehnt.
42
+ Optionen (``configure``): ``optional``. Endpunkte: Konstruktor oder ``set_choices()``.
43
+ """
44
+
45
+ from __future__ import annotations
46
+
47
+ import ipaddress
48
+ import math
49
+ import re
50
+ from collections.abc import Iterable
51
+ from contextlib import contextmanager
52
+ from typing import Any
53
+ from urllib.parse import urlsplit
54
+
55
+ from PySide6.QtCore import QEvent, QObject, Qt, QTimer, Signal
56
+ from PySide6.QtGui import QColor, QGuiApplication, QPalette
57
+ from PySide6.QtWidgets import QComboBox, QGridLayout, QHBoxLayout, QLabel, QLineEdit, QPushButton, QWidget
58
+
59
+ __all__ = ["ServerConnectionEditor", "ConnectionInputError", "compose_url"]
60
+
61
+
62
+ # ── Statustext ─ identisch in allen Dateien mit Statusanzeige (bewusst kopiert, Test prüft Gleichheit) ──
63
+ _ROLE_COLORS = {
64
+ # Rolle: (hell, dunkel) – Kontrast ≥ 4,5:1 auf Standardhintergründen
65
+ "accent": ("#1f6feb", "#5aa2ff"),
66
+ "muted": ("#5f6773", "#a3abb8"),
67
+ "success": ("#1a7a37", "#6fd08c"),
68
+ "warning": ("#8a5a00", "#f0b44c"),
69
+ "error": ("#b3261e", "#ff8f87"),
70
+ "busy": ("#1f5fbf", "#7db4ff"),
71
+ "locked": ("#5f6773", "#a3abb8"),
72
+ }
73
+ _ROLE_SYMBOLS = {"success": "✔", "error": "✖", "warning": "⚠", "busy": "⟳", "info": "ℹ", "locked": "🔒", "plain": ""}
74
+
75
+
76
+ def _base_palette(widget: QWidget) -> QPalette:
77
+ """Ausdrücklich gesetzte Fensterpalette, sonst die der Anwendung (Stylesheets verfälschen die eigene)."""
78
+ window = widget.window()
79
+ return window.palette() if window.testAttribute(Qt.WidgetAttribute.WA_SetPalette) else QGuiApplication.palette()
80
+
81
+
82
+ def _role_color(widget: QWidget, role: str) -> QColor:
83
+ light, dark = _ROLE_COLORS.get(role, _ROLE_COLORS["muted"])
84
+ return QColor(dark if _base_palette(widget).color(QPalette.ColorRole.Window).lightness() < 128 else light)
85
+
86
+
87
+ class _StatusText(QLabel):
88
+ """Einzeiliger oder umbrechender Statustext: ``show_message(text, role)``."""
89
+
90
+ _role = "plain" # Klassenwert: Qt kann Ereignisse schon während der Konstruktion liefern
91
+
92
+ def __init__(self, parent: QWidget | None = None) -> None:
93
+ super().__init__(parent)
94
+ self._role = "plain"
95
+ self.setTextFormat(Qt.TextFormat.PlainText)
96
+ self.setWordWrap(True)
97
+ hints = QGuiApplication.styleHints()
98
+ if hasattr(hints, "colorSchemeChanged"):
99
+ hints.colorSchemeChanged.connect(self._scheme_changed)
100
+
101
+ def _scheme_changed(self, *_: object) -> None:
102
+ # Paletten werden je nach Stil verzögert aktualisiert; deshalb zweimal abgleichen.
103
+ for delay in (0, 150):
104
+ QTimer.singleShot(delay, self, self._recolor)
105
+
106
+ def show_message(self, text: str, role: str = "plain") -> None:
107
+ symbol = _ROLE_SYMBOLS.get(role, "")
108
+ self.setText(f"{symbol} {text}".strip() if text else "")
109
+ self._role = role
110
+ self._recolor()
111
+
112
+ def role(self) -> str:
113
+ return self._role
114
+
115
+ def _recolor(self) -> None:
116
+ sheet = ""
117
+ if self._role not in ("plain", ""):
118
+ sheet = f"color: {_role_color(self, 'accent' if self._role == 'info' else self._role).name()};"
119
+ if sheet != self.styleSheet():
120
+ self.setStyleSheet(sheet)
121
+
122
+ def changeEvent(self, event: QEvent) -> None:
123
+ super().changeEvent(event)
124
+ if event.type() == QEvent.Type.PaletteChange:
125
+ self._recolor()
126
+
127
+ def showEvent(self, event: QEvent) -> None:
128
+ super().showEvent(event)
129
+ self._recolor()
130
+ # ── Ende Statustext ──
131
+
132
+
133
+ # ── Wertbasis ─ identisch in allen Editor-Dateien (bewusst kopiert, Test prüft Gleichheit) ──
134
+ def _same(a: Any, b: Any) -> bool:
135
+ """Gleichheit ohne Pythons ``True == 1``-Vermischung."""
136
+ if a is b:
137
+ return True
138
+ if isinstance(a, bool) != isinstance(b, bool):
139
+ return False
140
+ if isinstance(a, list) and isinstance(b, list):
141
+ return len(a) == len(b) and all(_same(x, y) for x, y in zip(a, b))
142
+ if isinstance(a, dict) and isinstance(b, dict):
143
+ return a.keys() == b.keys() and all(_same(a[k], b[k]) for k in a)
144
+ try:
145
+ return bool(a == b)
146
+ except Exception: # noqa: BLE001 – fremde Typen ohne Vergleich
147
+ return False
148
+
149
+
150
+ class _ValueWidget(QWidget):
151
+ """Gemeinsamer Vertrag aller Editoren.
152
+
153
+ * ``value()`` / ``set_value(v)`` – ``None`` bedeutet „nicht gesetzt“; ein Wert falschen
154
+ Typs löst ``ValueError`` aus und wird nie still umgewandelt.
155
+ * ``value_changed(object)`` – jede Wertänderung, auch programmatisch.
156
+ * ``value_edited(object)`` – nur Änderungen durch den Benutzer.
157
+ * ``configure(**optionen)`` – Schlüssel aus ``OPTIONS``; unbekannte → ``TypeError``.
158
+ * ``set_read_only(bool)``, ``input_error()`` / ``input_error_changed(str)``, ``commit()``.
159
+ """
160
+
161
+ value_changed = Signal(object)
162
+ value_edited = Signal(object)
163
+ input_error_changed = Signal(str)
164
+
165
+ #: Schlüssel, die ``configure()`` annimmt.
166
+ OPTIONS: tuple[str, ...] = ("optional",)
167
+
168
+ def __init__(self, parent: QWidget | None = None) -> None:
169
+ super().__init__(parent)
170
+ self._optional = False
171
+ self._read_only = False
172
+ self._silent = 0
173
+ self._last_error = ""
174
+
175
+ # -- von Unterklassen bereitzustellen ------------------------------------------------
176
+ def value(self) -> Any:
177
+ raise NotImplementedError
178
+
179
+ def _apply_value(self, value: Any) -> None:
180
+ raise NotImplementedError
181
+
182
+ def _apply_options(self) -> None:
183
+ """Darstellung nach ``configure()`` nachführen."""
184
+
185
+ def _apply_read_only(self, read_only: bool) -> None:
186
+ self.setEnabled(not read_only)
187
+
188
+ def input_error(self) -> str:
189
+ """Grund, warum die aktuelle Eingabe keinen gültigen Wert ergibt (sonst leer)."""
190
+ return ""
191
+
192
+ def commit(self) -> None:
193
+ """Schließt eine angefangene Eingabe ab."""
194
+
195
+ # -- öffentliche Schnittstelle --------------------------------------------------------
196
+ def set_value(self, value: Any) -> None:
197
+ """Setzt den Wert programmatisch (ohne ``value_edited``)."""
198
+ old = self.value()
199
+ with self._programmatic():
200
+ self._apply_value(value)
201
+ new = self.value()
202
+ if not _same(old, new):
203
+ self.value_changed.emit(new)
204
+ self._check_error()
205
+
206
+ def configure(self, **options: Any) -> None:
207
+ """Setzt mehrere Optionen auf einmal, z. B. ``configure(optional=True)``."""
208
+ unknown = sorted(set(options) - set(self.OPTIONS))
209
+ if unknown:
210
+ raise TypeError(f"{type(self).__name__}: unbekannte Option(en) {', '.join(unknown)}")
211
+ for key, value in options.items():
212
+ self._set_option(key, value)
213
+ with self._programmatic():
214
+ self._apply_options()
215
+ self._check_error()
216
+
217
+ def options(self) -> dict[str, Any]:
218
+ """Aktuelle Optionen."""
219
+ return {key: getattr(self, f"_{key}") for key in self.OPTIONS}
220
+
221
+ def _set_option(self, key: str, value: Any) -> None:
222
+ if key == "optional":
223
+ value = bool(value)
224
+ setattr(self, f"_{key}", value)
225
+
226
+ def set_optional(self, optional: bool) -> None:
227
+ self.configure(optional=optional)
228
+
229
+ def is_optional(self) -> bool:
230
+ return self._optional
231
+
232
+ def set_read_only(self, read_only: bool) -> None:
233
+ self._read_only = bool(read_only)
234
+ self._apply_read_only(self._read_only)
235
+
236
+ def is_read_only(self) -> bool:
237
+ return self._read_only
238
+
239
+ # -- Hilfen für Unterklassen ----------------------------------------------------------
240
+ @contextmanager
241
+ def _programmatic(self):
242
+ self._silent += 1
243
+ try:
244
+ yield
245
+ finally:
246
+ self._silent -= 1
247
+
248
+ def _user_changed(self, *_: Any) -> None:
249
+ """Nach einer echten Benutzereingabe aufzurufen."""
250
+ if self._silent:
251
+ return
252
+ value = self.value()
253
+ self._check_error()
254
+ self.value_changed.emit(value)
255
+ self.value_edited.emit(value)
256
+
257
+ def _check_error(self) -> None:
258
+ error = self.input_error()
259
+ if error != self._last_error:
260
+ self._last_error = error
261
+ self.input_error_changed.emit(error)
262
+ # ── Ende Wertbasis ──
263
+
264
+
265
+ # ── Mausrad-Schutz ─ identisch in allen Dateien mit Rad-empfindlichen Feldern (bewusst kopiert) ──
266
+ class _WheelGuard(QObject):
267
+ """Verhindert versehentliche Wertänderungen beim Scrollen einer Seite (nur mit Fokus)."""
268
+
269
+ def eventFilter(self, obj: QObject, event: QEvent) -> bool:
270
+ if event.type() == QEvent.Type.Wheel and isinstance(obj, QWidget) and not obj.hasFocus():
271
+ event.ignore()
272
+ return True
273
+ return False
274
+
275
+
276
+ def _guard_wheel(widget: QWidget) -> None:
277
+ guard = widget.findChild(_WheelGuard, "_wheel_guard")
278
+ if guard is None:
279
+ guard = _WheelGuard(widget)
280
+ guard.setObjectName("_wheel_guard")
281
+ widget.setFocusPolicy(Qt.FocusPolicy.StrongFocus)
282
+ widget.installEventFilter(guard)
283
+ # ── Ende Mausrad-Schutz ──
284
+
285
+
286
+ # ── Auswahloptionen ─ identisch in allen Dateien mit Auswahllisten (bewusst kopiert) ──
287
+ def _is_scalar(value: Any) -> bool:
288
+ return isinstance(value, (str, int, float, bool)) and not (isinstance(value, float) and not math.isfinite(value))
289
+
290
+
291
+ class _Choice:
292
+ """Ein auswählbarer Wert mit Beschriftung (intern; nimmt Qt-Umwandlungen wie bool↔int aus dem Spiel)."""
293
+
294
+ __slots__ = ("value", "label", "description", "available", "unavailable_reason")
295
+
296
+ def __init__(self, value: Any, label: str, description: str = "",
297
+ available: bool = True, unavailable_reason: str = "") -> None:
298
+ self.value, self.label, self.description = value, label, description
299
+ self.available, self.unavailable_reason = available, unavailable_reason
300
+
301
+ @classmethod
302
+ def parse(cls, raw: Any) -> "_Choice":
303
+ """Akzeptiert Skalar, ``(value, label[, description])``, ``{"value", "label", "description"}``
304
+ oder ein Objekt mit den Attributen ``value``/``label``/``description``."""
305
+ available, reason = True, ""
306
+ if isinstance(raw, dict):
307
+ if "value" not in raw or set(raw) - {"value", "label", "description", "available", "unavailable_reason"}:
308
+ raise ValueError(f"Auswahloption {raw!r}: erwartet value, label, description")
309
+ value, label, description = raw["value"], raw.get("label", str(raw["value"])), raw.get("description", "")
310
+ available, reason = raw.get("available", True), raw.get("unavailable_reason", "")
311
+ elif isinstance(raw, (tuple, list)):
312
+ if not 1 <= len(raw) <= 3:
313
+ raise ValueError(f"Auswahloption {raw!r}: erwartet (value, label[, description])")
314
+ value, label, description = raw[0], (raw[1] if len(raw) > 1 else str(raw[0])), (raw[2] if len(raw) > 2 else "")
315
+ elif _is_scalar(raw):
316
+ value, label, description = raw, str(raw), ""
317
+ elif hasattr(raw, "value") and hasattr(raw, "label"):
318
+ value, label, description = raw.value, raw.label, getattr(raw, "description", "") or ""
319
+ available, reason = getattr(raw, "available", True), getattr(raw, "unavailable_reason", "")
320
+ else:
321
+ raise ValueError(f"Auswahloption {raw!r} nicht lesbar")
322
+ if not _is_scalar(value):
323
+ raise ValueError(f"Auswahlwert {value!r} muss Text, Zahl oder Wahrheitswert sein")
324
+ if not isinstance(label, str) or not isinstance(description, str):
325
+ raise ValueError(f"Auswahloption {value!r}: label/description müssen Text sein")
326
+ if type(available) is not bool or not isinstance(reason, str):
327
+ raise ValueError("available muss boolesch und unavailable_reason Text sein")
328
+ return cls(value, label, description, available, reason)
329
+ # ── Ende Auswahloptionen ──
330
+
331
+
332
+ _LABEL = re.compile(r"(?!-)[A-Za-z0-9_-]{1,63}(?<!-)")
333
+
334
+
335
+ class ConnectionInputError(ValueError):
336
+ """Verständlich beschriebene fehlerhafte Verbindungseingabe."""
337
+
338
+
339
+ def _check_host(host: str) -> None:
340
+ if ":" in host:
341
+ try:
342
+ ipaddress.IPv6Address(host.split("%", 1)[0])
343
+ except ValueError:
344
+ raise ConnectionInputError(f"„{host}“ ist keine gültige IPv6-Adresse") from None
345
+ return
346
+ if re.fullmatch(r"[\d.]+", host):
347
+ try:
348
+ ipaddress.IPv4Address(host)
349
+ except ValueError:
350
+ raise ConnectionInputError(f"„{host}“ ist keine gültige IPv4-Adresse") from None
351
+ return
352
+ try:
353
+ ascii_host = host.encode("idna").decode("ascii") if not host.isascii() else host
354
+ except UnicodeError:
355
+ raise ConnectionInputError(f"„{host}“ ist kein gültiger Hostname") from None
356
+ if len(ascii_host) > 253 or not all(_LABEL.fullmatch(part) for part in ascii_host.rstrip(".").split(".")):
357
+ raise ConnectionInputError(f"„{host}“ ist kein gültiger Hostname")
358
+
359
+
360
+ def compose_url(
361
+ address: str,
362
+ endpoint: str,
363
+ *,
364
+ schemes: Iterable[str] = ("http", "https"),
365
+ default_scheme: str | None = None,
366
+ allow_path: bool = False,
367
+ ) -> str:
368
+ """Setzt Adresse und Endpunkt zu einer URL zusammen oder wirft :class:`ConnectionInputError`."""
369
+ allowed = list(schemes)
370
+ text = address.strip()
371
+ if not text:
372
+ raise ConnectionInputError("Bitte eine Adresse eingeben")
373
+ if re.search(r"\s", text) or any(ord(c) < 32 for c in text) or "\\" in text:
374
+ raise ConnectionInputError("Die Adresse enthält unzulässige Zeichen")
375
+ if "://" not in text:
376
+ text = f"{default_scheme or allowed[0]}://{text}"
377
+ try:
378
+ parts = urlsplit(text)
379
+ port = parts.port
380
+ host = parts.hostname
381
+ except ValueError:
382
+ raise ConnectionInputError("Adresse oder Port ist ungültig (Port 1–65535)") from None
383
+ if parts.scheme not in allowed:
384
+ raise ConnectionInputError(f"Protokoll „{parts.scheme}“ ist nicht erlaubt (erlaubt: {', '.join(allowed)})")
385
+ if parts.username is not None or parts.password is not None or "@" in parts.netloc:
386
+ raise ConnectionInputError("Zugangsdaten dürfen nicht Teil der Adresse sein")
387
+ if not host:
388
+ raise ConnectionInputError("Der Hostname fehlt")
389
+ if port == 0 or parts.netloc.endswith(":"):
390
+ raise ConnectionInputError("Adresse oder Port ist ungültig (Port 1–65535)")
391
+ _check_host(host)
392
+ if parts.query or parts.fragment or "?" in text or "#" in text:
393
+ raise ConnectionInputError("Die Adresse darf keine Abfrage (?) und kein Fragment (#) enthalten")
394
+ path = parts.path.rstrip("/")
395
+ if path and not allow_path:
396
+ raise ConnectionInputError("Die Adresse darf keinen Pfad enthalten – dafür gibt es den Endpunkt")
397
+ suffix = endpoint if not endpoint or endpoint.startswith("/") else f"/{endpoint}"
398
+ shown_host = f"[{host}]" if ":" in host else host
399
+ return f"{parts.scheme}://{shown_host}{f':{port}' if port is not None else ''}{path}{suffix}"
400
+
401
+
402
+ class ServerConnectionEditor(_ValueWidget):
403
+ """Allgemeines Verbindungswidget.
404
+
405
+ ``test_requested``/``apply_requested`` übergeben ``{"address", "endpoint", "url"}``.
406
+ Ein Test ändert nichts; die Übernahme ist eine eigene Aktion. Ergebnisse werden
407
+ mit :meth:`show_result` angezeigt und nach weiterer Bearbeitung als überholt behandelt.
408
+ """
409
+
410
+ test_requested = Signal(dict)
411
+ apply_requested = Signal(dict)
412
+
413
+ def __init__(
414
+ self,
415
+ parent: QWidget | None = None,
416
+ *,
417
+ schemes: Iterable[str] = ("http", "https"),
418
+ default_scheme: str | None = None,
419
+ endpoints: Iterable[Any] = (),
420
+ allow_path: bool = False,
421
+ placeholder: str = "server.example:8080",
422
+ ) -> None:
423
+ super().__init__(parent)
424
+ self._schemes = list(schemes)
425
+ self._default_scheme = default_scheme
426
+ self._allow_path = allow_path
427
+ self._endpoint = ""
428
+ self._options: list[_Choice] = [_Choice.parse(e) for e in endpoints]
429
+ self._busy = ""
430
+ self._busy_value: dict[str, str] | None = None
431
+ self._result_value: dict[str, str] | None = None
432
+ self._null = False
433
+
434
+ grid = QGridLayout(self)
435
+ grid.setContentsMargins(0, 0, 0, 0)
436
+ grid.setHorizontalSpacing(8)
437
+ grid.setVerticalSpacing(4)
438
+ self._address = QLineEdit(self)
439
+ self._address.setPlaceholderText(placeholder)
440
+ self._address.setMinimumWidth(80)
441
+ self._address.setAccessibleName("Adresse")
442
+ self._address.textEdited.connect(self._edited)
443
+ self._combo = QComboBox(self)
444
+ self._combo.setSizeAdjustPolicy(QComboBox.SizeAdjustPolicy.AdjustToMinimumContentsLengthWithIcon)
445
+ self._combo.setMinimumContentsLength(10)
446
+ self._combo.setAccessibleName("Endpunkt")
447
+ _guard_wheel(self._combo)
448
+ self._combo.activated.connect(self._on_endpoint)
449
+ self._url = QLabel(self)
450
+ self._url.setTextInteractionFlags(Qt.TextInteractionFlag.TextSelectableByMouse)
451
+ self._url.setWordWrap(True)
452
+ self._url.setMinimumWidth(1)
453
+ self._url.setTextFormat(Qt.TextFormat.PlainText)
454
+ self._test = QPushButton("Testen", self)
455
+ self._test.setToolTip("Prüft die Verbindung, ohne etwas zu übernehmen")
456
+ self._apply = QPushButton("Übernehmen && Verbinden", self)
457
+ for button, handler in ((self._test, self._on_test), (self._apply, self._on_apply)):
458
+ button.setAutoDefault(False)
459
+ button.clicked.connect(handler)
460
+ self._result = _StatusText(self)
461
+ for row, (text, widget) in enumerate((("Adresse", self._address), ("Endpunkt", self._combo), ("URL", self._url))):
462
+ label = QLabel(text, self)
463
+ label.setBuddy(widget)
464
+ grid.addWidget(label, row, 0)
465
+ grid.addWidget(widget, row, 1)
466
+ bar = QHBoxLayout()
467
+ bar.addWidget(self._test)
468
+ bar.addWidget(self._apply)
469
+ bar.addStretch(1)
470
+ grid.addLayout(bar, 3, 0, 1, 2)
471
+ grid.addWidget(self._result, 4, 0, 1, 2)
472
+ grid.setColumnStretch(1, 1)
473
+ self.setFocusProxy(self._address)
474
+ with self._programmatic():
475
+ self._apply_choices(self._options)
476
+ if self._options and not self._endpoint:
477
+ self._endpoint = str(self._options[0].value)
478
+ self._apply_choices(self._options)
479
+
480
+ # -- Wert -------------------------------------------------------------------------------
481
+ def value(self) -> dict[str, str] | None:
482
+ if self._null:
483
+ return None
484
+ return {"address": self._address.text().strip(), "endpoint": self._endpoint}
485
+
486
+ def url(self) -> str:
487
+ return compose_url(
488
+ self._address.text(),
489
+ self._endpoint,
490
+ schemes=self._schemes,
491
+ default_scheme=self._default_scheme,
492
+ allow_path=self._allow_path,
493
+ )
494
+
495
+ def input_error(self) -> str:
496
+ if self._null:
497
+ return ""
498
+ try:
499
+ self.url()
500
+ except ConnectionInputError as exc:
501
+ return str(exc)
502
+ if self._options and not any(str(o.value) == self._endpoint for o in self._options):
503
+ return "Bitte einen erlaubten Endpunkt auswählen"
504
+ return ""
505
+
506
+ def _apply_value(self, value: Any) -> None:
507
+ if value is not None and (
508
+ not isinstance(value, dict)
509
+ or set(value) != {"address", "endpoint"}
510
+ or not all(isinstance(v, str) for v in value.values())
511
+ ):
512
+ raise ValueError("Verbindung mit address und endpoint erwartet")
513
+ self._null = value is None
514
+ value = value or {"address": "", "endpoint": ""}
515
+ if self._address.text().strip() != value["address"]:
516
+ self._address.setText(value["address"])
517
+ self._endpoint = value["endpoint"]
518
+ self._apply_choices(self._options)
519
+
520
+ def set_choices(self, choices: Iterable[Any]) -> None:
521
+ """Erlaubte Endpunkte (Text oder ``(wert, beschriftung)``); ein anderer Endpunkt gilt als Fehler."""
522
+ with self._programmatic():
523
+ self._apply_choices([_Choice.parse(c) for c in choices])
524
+ self._check_error()
525
+
526
+ def choices(self) -> list[dict[str, Any]]:
527
+ return [
528
+ {"value": o.value, "label": o.label, "description": o.description,
529
+ **({"available": False} if not o.available else {}),
530
+ **({"unavailable_reason": o.unavailable_reason} if o.unavailable_reason else {})}
531
+ for o in self._options
532
+ ]
533
+
534
+ def _apply_choices(self, choices: list[_Choice]) -> None:
535
+ self._options = choices
536
+ self._combo.clear()
537
+ for option in choices:
538
+ label = option.label if option.available else f"⚠ {option.label} (nicht verfügbar)"
539
+ self._combo.addItem(label, str(option.value))
540
+ index = self._combo.count() - 1
541
+ self._combo.setItemData(index, option.unavailable_reason or option.description, Qt.ItemDataRole.ToolTipRole)
542
+ if not option.available:
543
+ self._combo.model().item(index).setEnabled(False)
544
+ index = self._combo.findData(self._endpoint)
545
+ if index < 0 and self._endpoint:
546
+ self._combo.addItem(f"⚠ {self._endpoint} (nicht erlaubt)", self._endpoint)
547
+ index = self._combo.count() - 1
548
+ self._combo.model().item(index).setEnabled(False)
549
+ self._combo.setCurrentIndex(index)
550
+ self._combo.setVisible(bool(choices) or bool(self._endpoint))
551
+ self._refresh()
552
+
553
+ def _on_endpoint(self, index: int) -> None:
554
+ if self._read_only or index < 0 or not self._combo.model().item(index).isEnabled():
555
+ self._combo.setCurrentIndex(self._combo.findData(self._endpoint))
556
+ return
557
+ endpoint = self._combo.itemData(index)
558
+ if endpoint != self._endpoint:
559
+ self._endpoint = endpoint
560
+ self._edited()
561
+
562
+ def _edited(self, *_: Any) -> None:
563
+ self._null = False
564
+ self._refresh()
565
+ self._user_changed()
566
+
567
+ # -- Aktionen ---------------------------------------------------------------------------
568
+ def _payload(self) -> dict[str, str] | None:
569
+ error = self.input_error()
570
+ if error:
571
+ self._result.show_message(error, "error")
572
+ return None
573
+ return {**(self.value() or {}), "url": self.url()}
574
+
575
+ def _on_test(self) -> None:
576
+ if payload := self._payload():
577
+ self.test_requested.emit(payload)
578
+
579
+ def _on_apply(self) -> None:
580
+ if payload := self._payload():
581
+ self.apply_requested.emit(payload)
582
+
583
+ def set_busy(self, kind: str, message: str = "") -> None:
584
+ """``kind``: ``"test"``, ``"apply"`` oder ``""`` (fertig)."""
585
+ self._busy = kind
586
+ if kind:
587
+ self._busy_value = self.value()
588
+ self._result.show_message(message or ("Verbindung wird getestet …" if kind == "test" else "Verbinden …"), "busy")
589
+ self._refresh()
590
+
591
+ def show_result(self, ok: bool, message: str) -> None:
592
+ """Zeigt ein Ergebnis; bezieht es sich auf inzwischen geänderte Eingaben, wird das kenntlich gemacht."""
593
+ outdated = self._busy_value is not None and self._busy_value != self.value()
594
+ kind, self._busy = self._busy, ""
595
+ prefix = "Test: " if kind == "test" else ""
596
+ if outdated:
597
+ self._result.show_message(f"{prefix}Ergebnis gilt für vorherige Eingabe: {message}", "warning")
598
+ self._result_value = None
599
+ else:
600
+ self._result.show_message(prefix + message, "success" if ok else "error")
601
+ self._result_value = self.value()
602
+ self._busy_value = None
603
+ self._refresh()
604
+
605
+ def result_text(self) -> str:
606
+ return self._result.text()
607
+
608
+ # -- Darstellung ---------------------------------------------------------------------------
609
+ def _refresh(self) -> None:
610
+ error = self.input_error()
611
+ if error and not self._null:
612
+ self._url.setText(f"✖ {error}")
613
+ else:
614
+ self._url.setText("" if self._null else self.url())
615
+ if self._result_value is not None and self._result_value != self.value():
616
+ self._result_value = None
617
+ self._result.show_message("")
618
+ self._address.setReadOnly(self._read_only)
619
+ self._combo.setEnabled(not self._read_only)
620
+ usable = not self._read_only and not self._busy and not error and not self._null
621
+ self._test.setEnabled(usable)
622
+ self._apply.setEnabled(usable)
623
+
624
+ def _apply_read_only(self, read_only: bool) -> None:
625
+ self._refresh()
626
+
627
+
628
+ def _demo() -> None: # pragma: no cover – python server_connection_editor.py
629
+ from PySide6.QtWidgets import QApplication
630
+
631
+ app = QApplication.instance() or QApplication([])
632
+ editor = ServerConnectionEditor(endpoints=["/api/v1", "/api/v2"])
633
+ editor.set_value({"address": "localhost:8765", "endpoint": "/api/v1"})
634
+ editor.test_requested.connect(lambda p: editor.show_result(True, f"{p['url']} – Test simuliert"))
635
+ editor.apply_requested.connect(lambda p: editor.show_result(True, "Übernahme simuliert"))
636
+ editor.resize(460, 160)
637
+ editor.show()
638
+ app.exec()
639
+
640
+
641
+ if __name__ == "__main__":
642
+ _demo()