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.
- dynamic_settings_widget/__init__.py +56 -0
- dynamic_settings_widget/adapters/__init__.py +42 -0
- dynamic_settings_widget/adapters/base.py +179 -0
- dynamic_settings_widget/adapters/memory.py +201 -0
- dynamic_settings_widget/adapters/runner.py +63 -0
- dynamic_settings_widget/core/__init__.py +1 -0
- dynamic_settings_widget/core/catalog.py +201 -0
- dynamic_settings_widget/core/common.py +214 -0
- dynamic_settings_widget/core/conditions.py +146 -0
- dynamic_settings_widget/core/datatypes.py +414 -0
- dynamic_settings_widget/core/diagnostics.py +69 -0
- dynamic_settings_widget/core/loader.py +101 -0
- dynamic_settings_widget/core/model.py +245 -0
- dynamic_settings_widget/core/overrides.py +353 -0
- dynamic_settings_widget/core/parser.py +552 -0
- dynamic_settings_widget/core/presentation.py +68 -0
- dynamic_settings_widget/core/registry.py +258 -0
- dynamic_settings_widget/core/state.py +314 -0
- dynamic_settings_widget/data/example_catalog.json +23 -0
- dynamic_settings_widget/data/example_layout.json +23 -0
- dynamic_settings_widget/data/settings_catalog.schema.json +388 -0
- dynamic_settings_widget/data/settings_definition.schema.json +1041 -0
- dynamic_settings_widget/data/settings_layout.schema.json +701 -0
- dynamic_settings_widget/data/settings_override.schema.json +406 -0
- dynamic_settings_widget/py.typed +0 -0
- dynamic_settings_widget/session.py +1537 -0
- dynamic_settings_widget/standalone/__init__.py +67 -0
- dynamic_settings_widget/standalone/action_button.py +200 -0
- dynamic_settings_widget/standalone/auth_widget.py +377 -0
- dynamic_settings_widget/standalone/check_box_editor.py +233 -0
- dynamic_settings_widget/standalone/choice_buttons_editor.py +394 -0
- dynamic_settings_widget/standalone/color_editor.py +316 -0
- dynamic_settings_widget/standalone/dropdown_editor.py +356 -0
- dynamic_settings_widget/standalone/editable_label.py +428 -0
- dynamic_settings_widget/standalone/float_spin_box.py +621 -0
- dynamic_settings_widget/standalone/font_editor.py +348 -0
- dynamic_settings_widget/standalone/hotkey_editor.py +681 -0
- dynamic_settings_widget/standalone/info_label.py +190 -0
- dynamic_settings_widget/standalone/int_spin_box.py +627 -0
- dynamic_settings_widget/standalone/multi_choice_editor.py +428 -0
- dynamic_settings_widget/standalone/password_editor.py +348 -0
- dynamic_settings_widget/standalone/path_editor.py +615 -0
- dynamic_settings_widget/standalone/protected_group_box.py +287 -0
- dynamic_settings_widget/standalone/server_connection_editor.py +642 -0
- dynamic_settings_widget/standalone/slider_spin_box.py +840 -0
- dynamic_settings_widget/standalone/sound_selection_widget.py +710 -0
- dynamic_settings_widget/standalone/status_label.py +148 -0
- dynamic_settings_widget/standalone/switch_editor.py +293 -0
- dynamic_settings_widget/standalone/text_editor.py +265 -0
- dynamic_settings_widget/testlab/__init__.py +1 -0
- dynamic_settings_widget/testlab/__main__.py +5 -0
- dynamic_settings_widget/testlab/app.py +699 -0
- dynamic_settings_widget/testlab/assets/extra_sounds/Signal.wav +0 -0
- dynamic_settings_widget/testlab/assets/sounds/Benachrichtigung.wav +0 -0
- dynamic_settings_widget/testlab/assets/sounds/feedback/Signal.wav +0 -0
- dynamic_settings_widget/testlab/definitions/broken_base.json +25 -0
- dynamic_settings_widget/testlab/definitions/demo.json +634 -0
- dynamic_settings_widget/testlab/definitions/gallery.json +255 -0
- dynamic_settings_widget/testlab/definitions/override_example.json +41 -0
- dynamic_settings_widget/testlab/definitions/override_invalid.json +11 -0
- dynamic_settings_widget/testlab/definitions/override_syntax_error.json +5 -0
- dynamic_settings_widget/testlab/definitions/override_weaken.json +10 -0
- dynamic_settings_widget/testlab/definitions/voice_v2/01_left_top.json +1190 -0
- dynamic_settings_widget/testlab/definitions/voice_v2/catalog.json +1930 -0
- dynamic_settings_widget/testlab/definitions/voice_v2/models.json +141 -0
- dynamic_settings_widget/testlab/definitions/voice_v2/wakewords.json +161 -0
- dynamic_settings_widget/testlab/dummy.py +353 -0
- dynamic_settings_widget/testlab/extensions.py +149 -0
- dynamic_settings_widget/testlab/gallery.py +223 -0
- dynamic_settings_widget/testlab/http_adapter.py +430 -0
- dynamic_settings_widget/testlab/http_server.py +493 -0
- dynamic_settings_widget/testlab/voice_v2.py +251 -0
- dynamic_settings_widget/ui/__init__.py +23 -0
- dynamic_settings_widget/ui/base.py +63 -0
- dynamic_settings_widget/ui/builders.py +226 -0
- dynamic_settings_widget/ui/containers.py +441 -0
- dynamic_settings_widget/ui/dialog.py +231 -0
- dynamic_settings_widget/ui/editing.py +51 -0
- dynamic_settings_widget/ui/row.py +810 -0
- dynamic_settings_widget/ui/view.py +248 -0
- dynamic_settings_widget/widgets/__init__.py +74 -0
- dynamic_settings_widget/widgets/base.py +145 -0
- dynamic_settings_widget/widgets/bridge.py +222 -0
- dynamic_settings_widget/widgets/theme.py +107 -0
- dynamic_settings_widget-2.0.0.dist-info/METADATA +237 -0
- dynamic_settings_widget-2.0.0.dist-info/RECORD +90 -0
- dynamic_settings_widget-2.0.0.dist-info/WHEEL +5 -0
- dynamic_settings_widget-2.0.0.dist-info/entry_points.txt +5 -0
- dynamic_settings_widget-2.0.0.dist-info/licenses/LICENSE +21 -0
- dynamic_settings_widget-2.0.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,615 @@
|
|
|
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
|
+
"""PathEditor – Pfadeingabe mit Auswahlknopf für Datei, Speicherort oder Ordner und optionaler Prüfung.
|
|
24
|
+
|
|
25
|
+
Autarke Einzeldatei: benötigt nur Python ≥ 3.11 und PySide6 (Essentials).
|
|
26
|
+
|
|
27
|
+
Beispiel::
|
|
28
|
+
|
|
29
|
+
from path_editor import PathEditor
|
|
30
|
+
|
|
31
|
+
log_dir = PathEditor(mode="directory", placeholder="Protokollordner")
|
|
32
|
+
log_dir.configure(check="require") # Ordner muss existieren, sonst input_error()
|
|
33
|
+
log_dir.value_edited.connect(print)
|
|
34
|
+
|
|
35
|
+
export = PathEditor(mode="save", filter="CSV (*.csv)")
|
|
36
|
+
export.configure(check="warn", start_dir="C:/Daten") # nur Hinweis, blockiert nichts
|
|
37
|
+
|
|
38
|
+
Modi: ``open`` (vorhandene Datei), ``save`` (neue oder vorhandene Datei in einem
|
|
39
|
+
vorhandenen Ordner), ``directory`` (Ordner). Der Knopf zeigt je Modus ein eigenes Symbol.
|
|
40
|
+
Die manuelle Eingabe bleibt immer möglich. Abbrechen im Dialog ändert nichts.
|
|
41
|
+
|
|
42
|
+
Prüfung (``check``): ``none`` (Standard), ``warn`` (Hinweis), ``require`` (``input_error()``
|
|
43
|
+
meldet das Problem). Geprüft werden nur lokale absolute Pfade: Netzwerkpfade
|
|
44
|
+
(``\\\\server\\…``, verbundene Netzlaufwerke), URLs und relative Pfade werden bewusst nicht
|
|
45
|
+
angefasst. Wechselmedien und unbekannte Laufwerke werden außerhalb des GUI-Threads geprüft.
|
|
46
|
+
Das Widget liest weder Dateiinhalte noch legt es Dateien an.
|
|
47
|
+
|
|
48
|
+
Optionen (``configure``): ``optional``, ``mode``, ``filter``, ``placeholder``, ``start_dir``, ``check``.
|
|
49
|
+
"""
|
|
50
|
+
|
|
51
|
+
from __future__ import annotations
|
|
52
|
+
|
|
53
|
+
import os
|
|
54
|
+
import re
|
|
55
|
+
import sys
|
|
56
|
+
import threading
|
|
57
|
+
from contextlib import contextmanager
|
|
58
|
+
from typing import Any
|
|
59
|
+
|
|
60
|
+
from PySide6.QtCore import QByteArray, QEvent, QObject, QTimer, Qt, Signal
|
|
61
|
+
from PySide6.QtGui import QColor, QGuiApplication, QIcon, QPainter, QPalette, QPixmap
|
|
62
|
+
from PySide6.QtSvg import QSvgRenderer
|
|
63
|
+
from PySide6.QtWidgets import QFileDialog, QHBoxLayout, QLabel, QLineEdit, QToolButton, QVBoxLayout, QWidget
|
|
64
|
+
|
|
65
|
+
__all__ = ["PathEditor", "check_path"]
|
|
66
|
+
|
|
67
|
+
_ICONS = {
|
|
68
|
+
"open": '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><path d="M3.5 1.5h6l3 3v10h-9z" fill="none" '
|
|
69
|
+
'stroke="currentColor" stroke-width="1.3" stroke-linejoin="round"/><path d="M9.5 1.5v3h3" fill="none" '
|
|
70
|
+
'stroke="currentColor" stroke-width="1.3" stroke-linejoin="round"/><path d="M5.5 8.5h5M5.5 11h5" '
|
|
71
|
+
'stroke="currentColor" stroke-width="1.2"/></svg>',
|
|
72
|
+
"save": '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><path d="M3.5 1.5h6l3 3v10h-9z" fill="none" '
|
|
73
|
+
'stroke="currentColor" stroke-width="1.3" stroke-linejoin="round"/><path d="M8 6v6M5.6 9.8 8 12.2l2.4-2.4" '
|
|
74
|
+
'fill="none" stroke="currentColor" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round"/></svg>',
|
|
75
|
+
"directory": '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><path d="M1.5 3.5h4.2l1.5 1.5h7.3v8.5h-13z" '
|
|
76
|
+
'fill="none" stroke="currentColor" stroke-width="1.3" stroke-linejoin="round"/><path d="M1.5 6.5h13" '
|
|
77
|
+
'stroke="currentColor" stroke-width="1.1"/></svg>',
|
|
78
|
+
}
|
|
79
|
+
_TITLES = {"open": "Datei auswählen", "save": "Speicherort wählen", "directory": "Ordner auswählen"}
|
|
80
|
+
_URL = re.compile(r"^[A-Za-z][A-Za-z0-9+.-]+://")
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
# ── Symbole ─ identisch in allen Dateien mit eingebetteten Symbolen (bewusst kopiert) ──
|
|
84
|
+
def _svg_icon(svg: str, widget: QWidget, size: int = 16) -> QIcon:
|
|
85
|
+
"""Färbt ein eingebettetes SVG (``currentColor``) mit der Palette ein, auch für „deaktiviert“."""
|
|
86
|
+
icon = QIcon()
|
|
87
|
+
ratio = max(1.0, widget.devicePixelRatioF())
|
|
88
|
+
palette = widget.palette()
|
|
89
|
+
for mode, group in ((QIcon.Mode.Normal, QPalette.ColorGroup.Active), (QIcon.Mode.Disabled, QPalette.ColorGroup.Disabled)):
|
|
90
|
+
color = palette.color(group, QPalette.ColorRole.ButtonText).name()
|
|
91
|
+
renderer = QSvgRenderer(QByteArray(svg.replace("currentColor", color).encode()))
|
|
92
|
+
pixmap = QPixmap(int(size * ratio), int(size * ratio))
|
|
93
|
+
pixmap.fill(Qt.GlobalColor.transparent)
|
|
94
|
+
painter = QPainter(pixmap)
|
|
95
|
+
renderer.render(painter)
|
|
96
|
+
painter.end()
|
|
97
|
+
pixmap.setDevicePixelRatio(ratio)
|
|
98
|
+
icon.addPixmap(pixmap, mode)
|
|
99
|
+
return icon
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
class _SchemeFollower(QObject):
|
|
103
|
+
"""Ruft ``callback`` nach einem Wechsel des Farbschemas erneut auf.
|
|
104
|
+
|
|
105
|
+
Paletten werden je nach Stil verzögert aktualisiert, deshalb zweimal (sofort und nach
|
|
106
|
+
150 ms). Als Kindobjekt mit gebundener Methode verbunden: Nach dem Löschen des Widgets
|
|
107
|
+
wird nichts mehr aufgerufen.
|
|
108
|
+
"""
|
|
109
|
+
|
|
110
|
+
def __init__(self, parent: QWidget, callback) -> None:
|
|
111
|
+
super().__init__(parent)
|
|
112
|
+
self._callback = callback
|
|
113
|
+
hints = QGuiApplication.styleHints()
|
|
114
|
+
if hasattr(hints, "colorSchemeChanged"):
|
|
115
|
+
hints.colorSchemeChanged.connect(self._changed)
|
|
116
|
+
|
|
117
|
+
def _changed(self, *_: object) -> None:
|
|
118
|
+
for delay in (0, 150):
|
|
119
|
+
QTimer.singleShot(delay, self, self._callback)
|
|
120
|
+
# ── Ende Symbole ──
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
# ── Statustext ─ identisch in allen Dateien mit Statusanzeige (bewusst kopiert, Test prüft Gleichheit) ──
|
|
124
|
+
_ROLE_COLORS = {
|
|
125
|
+
# Rolle: (hell, dunkel) – Kontrast ≥ 4,5:1 auf Standardhintergründen
|
|
126
|
+
"accent": ("#1f6feb", "#5aa2ff"),
|
|
127
|
+
"muted": ("#5f6773", "#a3abb8"),
|
|
128
|
+
"success": ("#1a7a37", "#6fd08c"),
|
|
129
|
+
"warning": ("#8a5a00", "#f0b44c"),
|
|
130
|
+
"error": ("#b3261e", "#ff8f87"),
|
|
131
|
+
"busy": ("#1f5fbf", "#7db4ff"),
|
|
132
|
+
"locked": ("#5f6773", "#a3abb8"),
|
|
133
|
+
}
|
|
134
|
+
_ROLE_SYMBOLS = {"success": "✔", "error": "✖", "warning": "⚠", "busy": "⟳", "info": "ℹ", "locked": "🔒", "plain": ""}
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def _base_palette(widget: QWidget) -> QPalette:
|
|
138
|
+
"""Ausdrücklich gesetzte Fensterpalette, sonst die der Anwendung (Stylesheets verfälschen die eigene)."""
|
|
139
|
+
window = widget.window()
|
|
140
|
+
return window.palette() if window.testAttribute(Qt.WidgetAttribute.WA_SetPalette) else QGuiApplication.palette()
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def _role_color(widget: QWidget, role: str) -> QColor:
|
|
144
|
+
light, dark = _ROLE_COLORS.get(role, _ROLE_COLORS["muted"])
|
|
145
|
+
return QColor(dark if _base_palette(widget).color(QPalette.ColorRole.Window).lightness() < 128 else light)
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
class _StatusText(QLabel):
|
|
149
|
+
"""Einzeiliger oder umbrechender Statustext: ``show_message(text, role)``."""
|
|
150
|
+
|
|
151
|
+
_role = "plain" # Klassenwert: Qt kann Ereignisse schon während der Konstruktion liefern
|
|
152
|
+
|
|
153
|
+
def __init__(self, parent: QWidget | None = None) -> None:
|
|
154
|
+
super().__init__(parent)
|
|
155
|
+
self._role = "plain"
|
|
156
|
+
self.setTextFormat(Qt.TextFormat.PlainText)
|
|
157
|
+
self.setWordWrap(True)
|
|
158
|
+
hints = QGuiApplication.styleHints()
|
|
159
|
+
if hasattr(hints, "colorSchemeChanged"):
|
|
160
|
+
hints.colorSchemeChanged.connect(self._scheme_changed)
|
|
161
|
+
|
|
162
|
+
def _scheme_changed(self, *_: object) -> None:
|
|
163
|
+
# Paletten werden je nach Stil verzögert aktualisiert; deshalb zweimal abgleichen.
|
|
164
|
+
for delay in (0, 150):
|
|
165
|
+
QTimer.singleShot(delay, self, self._recolor)
|
|
166
|
+
|
|
167
|
+
def show_message(self, text: str, role: str = "plain") -> None:
|
|
168
|
+
symbol = _ROLE_SYMBOLS.get(role, "")
|
|
169
|
+
self.setText(f"{symbol} {text}".strip() if text else "")
|
|
170
|
+
self._role = role
|
|
171
|
+
self._recolor()
|
|
172
|
+
|
|
173
|
+
def role(self) -> str:
|
|
174
|
+
return self._role
|
|
175
|
+
|
|
176
|
+
def _recolor(self) -> None:
|
|
177
|
+
sheet = ""
|
|
178
|
+
if self._role not in ("plain", ""):
|
|
179
|
+
sheet = f"color: {_role_color(self, 'accent' if self._role == 'info' else self._role).name()};"
|
|
180
|
+
if sheet != self.styleSheet():
|
|
181
|
+
self.setStyleSheet(sheet)
|
|
182
|
+
|
|
183
|
+
def changeEvent(self, event: QEvent) -> None:
|
|
184
|
+
super().changeEvent(event)
|
|
185
|
+
if event.type() == QEvent.Type.PaletteChange:
|
|
186
|
+
self._recolor()
|
|
187
|
+
|
|
188
|
+
def showEvent(self, event: QEvent) -> None:
|
|
189
|
+
super().showEvent(event)
|
|
190
|
+
self._recolor()
|
|
191
|
+
# ── Ende Statustext ──
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
# ── Wertbasis ─ identisch in allen Editor-Dateien (bewusst kopiert, Test prüft Gleichheit) ──
|
|
195
|
+
def _same(a: Any, b: Any) -> bool:
|
|
196
|
+
"""Gleichheit ohne Pythons ``True == 1``-Vermischung."""
|
|
197
|
+
if a is b:
|
|
198
|
+
return True
|
|
199
|
+
if isinstance(a, bool) != isinstance(b, bool):
|
|
200
|
+
return False
|
|
201
|
+
if isinstance(a, list) and isinstance(b, list):
|
|
202
|
+
return len(a) == len(b) and all(_same(x, y) for x, y in zip(a, b))
|
|
203
|
+
if isinstance(a, dict) and isinstance(b, dict):
|
|
204
|
+
return a.keys() == b.keys() and all(_same(a[k], b[k]) for k in a)
|
|
205
|
+
try:
|
|
206
|
+
return bool(a == b)
|
|
207
|
+
except Exception: # noqa: BLE001 – fremde Typen ohne Vergleich
|
|
208
|
+
return False
|
|
209
|
+
|
|
210
|
+
|
|
211
|
+
class _ValueWidget(QWidget):
|
|
212
|
+
"""Gemeinsamer Vertrag aller Editoren.
|
|
213
|
+
|
|
214
|
+
* ``value()`` / ``set_value(v)`` – ``None`` bedeutet „nicht gesetzt“; ein Wert falschen
|
|
215
|
+
Typs löst ``ValueError`` aus und wird nie still umgewandelt.
|
|
216
|
+
* ``value_changed(object)`` – jede Wertänderung, auch programmatisch.
|
|
217
|
+
* ``value_edited(object)`` – nur Änderungen durch den Benutzer.
|
|
218
|
+
* ``configure(**optionen)`` – Schlüssel aus ``OPTIONS``; unbekannte → ``TypeError``.
|
|
219
|
+
* ``set_read_only(bool)``, ``input_error()`` / ``input_error_changed(str)``, ``commit()``.
|
|
220
|
+
"""
|
|
221
|
+
|
|
222
|
+
value_changed = Signal(object)
|
|
223
|
+
value_edited = Signal(object)
|
|
224
|
+
input_error_changed = Signal(str)
|
|
225
|
+
|
|
226
|
+
#: Schlüssel, die ``configure()`` annimmt.
|
|
227
|
+
OPTIONS: tuple[str, ...] = ("optional",)
|
|
228
|
+
|
|
229
|
+
def __init__(self, parent: QWidget | None = None) -> None:
|
|
230
|
+
super().__init__(parent)
|
|
231
|
+
self._optional = False
|
|
232
|
+
self._read_only = False
|
|
233
|
+
self._silent = 0
|
|
234
|
+
self._last_error = ""
|
|
235
|
+
|
|
236
|
+
# -- von Unterklassen bereitzustellen ------------------------------------------------
|
|
237
|
+
def value(self) -> Any:
|
|
238
|
+
raise NotImplementedError
|
|
239
|
+
|
|
240
|
+
def _apply_value(self, value: Any) -> None:
|
|
241
|
+
raise NotImplementedError
|
|
242
|
+
|
|
243
|
+
def _apply_options(self) -> None:
|
|
244
|
+
"""Darstellung nach ``configure()`` nachführen."""
|
|
245
|
+
|
|
246
|
+
def _apply_read_only(self, read_only: bool) -> None:
|
|
247
|
+
self.setEnabled(not read_only)
|
|
248
|
+
|
|
249
|
+
def input_error(self) -> str:
|
|
250
|
+
"""Grund, warum die aktuelle Eingabe keinen gültigen Wert ergibt (sonst leer)."""
|
|
251
|
+
return ""
|
|
252
|
+
|
|
253
|
+
def commit(self) -> None:
|
|
254
|
+
"""Schließt eine angefangene Eingabe ab."""
|
|
255
|
+
|
|
256
|
+
# -- öffentliche Schnittstelle --------------------------------------------------------
|
|
257
|
+
def set_value(self, value: Any) -> None:
|
|
258
|
+
"""Setzt den Wert programmatisch (ohne ``value_edited``)."""
|
|
259
|
+
old = self.value()
|
|
260
|
+
with self._programmatic():
|
|
261
|
+
self._apply_value(value)
|
|
262
|
+
new = self.value()
|
|
263
|
+
if not _same(old, new):
|
|
264
|
+
self.value_changed.emit(new)
|
|
265
|
+
self._check_error()
|
|
266
|
+
|
|
267
|
+
def configure(self, **options: Any) -> None:
|
|
268
|
+
"""Setzt mehrere Optionen auf einmal, z. B. ``configure(optional=True)``."""
|
|
269
|
+
unknown = sorted(set(options) - set(self.OPTIONS))
|
|
270
|
+
if unknown:
|
|
271
|
+
raise TypeError(f"{type(self).__name__}: unbekannte Option(en) {', '.join(unknown)}")
|
|
272
|
+
for key, value in options.items():
|
|
273
|
+
self._set_option(key, value)
|
|
274
|
+
with self._programmatic():
|
|
275
|
+
self._apply_options()
|
|
276
|
+
self._check_error()
|
|
277
|
+
|
|
278
|
+
def options(self) -> dict[str, Any]:
|
|
279
|
+
"""Aktuelle Optionen."""
|
|
280
|
+
return {key: getattr(self, f"_{key}") for key in self.OPTIONS}
|
|
281
|
+
|
|
282
|
+
def _set_option(self, key: str, value: Any) -> None:
|
|
283
|
+
if key == "optional":
|
|
284
|
+
value = bool(value)
|
|
285
|
+
setattr(self, f"_{key}", value)
|
|
286
|
+
|
|
287
|
+
def set_optional(self, optional: bool) -> None:
|
|
288
|
+
self.configure(optional=optional)
|
|
289
|
+
|
|
290
|
+
def is_optional(self) -> bool:
|
|
291
|
+
return self._optional
|
|
292
|
+
|
|
293
|
+
def set_read_only(self, read_only: bool) -> None:
|
|
294
|
+
self._read_only = bool(read_only)
|
|
295
|
+
self._apply_read_only(self._read_only)
|
|
296
|
+
|
|
297
|
+
def is_read_only(self) -> bool:
|
|
298
|
+
return self._read_only
|
|
299
|
+
|
|
300
|
+
# -- Hilfen für Unterklassen ----------------------------------------------------------
|
|
301
|
+
@contextmanager
|
|
302
|
+
def _programmatic(self):
|
|
303
|
+
self._silent += 1
|
|
304
|
+
try:
|
|
305
|
+
yield
|
|
306
|
+
finally:
|
|
307
|
+
self._silent -= 1
|
|
308
|
+
|
|
309
|
+
def _user_changed(self, *_: Any) -> None:
|
|
310
|
+
"""Nach einer echten Benutzereingabe aufzurufen."""
|
|
311
|
+
if self._silent:
|
|
312
|
+
return
|
|
313
|
+
value = self.value()
|
|
314
|
+
self._check_error()
|
|
315
|
+
self.value_changed.emit(value)
|
|
316
|
+
self.value_edited.emit(value)
|
|
317
|
+
|
|
318
|
+
def _check_error(self) -> None:
|
|
319
|
+
error = self.input_error()
|
|
320
|
+
if error != self._last_error:
|
|
321
|
+
self._last_error = error
|
|
322
|
+
self.input_error_changed.emit(error)
|
|
323
|
+
# ── Ende Wertbasis ──
|
|
324
|
+
|
|
325
|
+
|
|
326
|
+
# -- Pfadprüfung (ohne Qt, auch einzeln nutzbar) ------------------------------------------
|
|
327
|
+
def _drive_type(path: str) -> int:
|
|
328
|
+
"""Windows-Laufwerkstyp (2 Wechselmedium, 3 Festplatte, 4 Netzwerk, 5 CD, 6 RAM); sonst 3."""
|
|
329
|
+
if sys.platform != "win32":
|
|
330
|
+
return 3
|
|
331
|
+
import ctypes # Standardbibliothek; nur unter Windows benötigt
|
|
332
|
+
|
|
333
|
+
drive = os.path.splitdrive(path)[0]
|
|
334
|
+
if not drive:
|
|
335
|
+
return 3
|
|
336
|
+
return int(ctypes.windll.kernel32.GetDriveTypeW(drive + "\\"))
|
|
337
|
+
|
|
338
|
+
|
|
339
|
+
def _classify(path: str) -> str:
|
|
340
|
+
"""``remote``, ``relative``, ``slow`` (außerhalb des GUI-Threads prüfen) oder ``local``."""
|
|
341
|
+
if path.startswith(("\\\\", "//")) or _URL.match(path):
|
|
342
|
+
return "remote"
|
|
343
|
+
if not os.path.isabs(path):
|
|
344
|
+
return "relative"
|
|
345
|
+
kind = _drive_type(path)
|
|
346
|
+
if kind == 4:
|
|
347
|
+
return "remote"
|
|
348
|
+
return "local" if kind in (3, 6) else "slow"
|
|
349
|
+
|
|
350
|
+
|
|
351
|
+
def check_path(path: str, mode: str) -> tuple[str, str]:
|
|
352
|
+
"""Prüft einen lokalen Pfad für ``mode`` und liefert ``(ergebnis, text)``.
|
|
353
|
+
|
|
354
|
+
``ergebnis``: ``ok``, ``problem``, ``skipped``. Es wird nichts angelegt oder geöffnet.
|
|
355
|
+
"""
|
|
356
|
+
kind = _classify(path)
|
|
357
|
+
if kind == "remote":
|
|
358
|
+
return "skipped", "Netzwerk- oder Remote-Pfad – wird nicht lokal geprüft"
|
|
359
|
+
if kind == "relative":
|
|
360
|
+
return "skipped", "Relativer Pfad – wird nicht geprüft"
|
|
361
|
+
if mode == "directory":
|
|
362
|
+
if os.path.isdir(path):
|
|
363
|
+
return "ok", "Ordner vorhanden"
|
|
364
|
+
return "problem", "Das ist eine Datei, kein Ordner" if os.path.exists(path) else "Ordner nicht gefunden"
|
|
365
|
+
if mode == "open":
|
|
366
|
+
if os.path.isfile(path):
|
|
367
|
+
return "ok", "Datei vorhanden"
|
|
368
|
+
return "problem", "Das ist ein Ordner, keine Datei" if os.path.isdir(path) else "Datei nicht gefunden"
|
|
369
|
+
# save: neue Datei in vorhandenem Ordner oder vorhandene Datei (wird beim Speichern ersetzt)
|
|
370
|
+
if os.path.isdir(path):
|
|
371
|
+
return "problem", "Das ist ein Ordner – bitte einen Dateinamen angeben"
|
|
372
|
+
if os.path.isfile(path):
|
|
373
|
+
return "ok", "Datei vorhanden – wird beim Speichern ersetzt"
|
|
374
|
+
parent = os.path.dirname(path.rstrip("\\/")) or path
|
|
375
|
+
if os.path.isdir(parent):
|
|
376
|
+
return "ok", "Neue Datei im vorhandenen Ordner"
|
|
377
|
+
return "problem", "Zielordner existiert nicht"
|
|
378
|
+
|
|
379
|
+
|
|
380
|
+
class _CheckRelay(QObject):
|
|
381
|
+
"""Bringt Ergebnisse aus dem Prüf-Thread in den GUI-Thread (Qt-Warteschlange)."""
|
|
382
|
+
|
|
383
|
+
done = Signal(int, str, str)
|
|
384
|
+
|
|
385
|
+
|
|
386
|
+
class PathEditor(_ValueWidget):
|
|
387
|
+
"""Pfadeingabe mit Auswahldialog und optionaler lokaler Prüfung."""
|
|
388
|
+
|
|
389
|
+
OPTIONS = ("optional", "mode", "filter", "placeholder", "start_dir", "check")
|
|
390
|
+
#: Rückmeldung bei erfolgreicher Prüfung anzeigen
|
|
391
|
+
SHOW_OK = True
|
|
392
|
+
|
|
393
|
+
def __init__(
|
|
394
|
+
self, parent: QWidget | None = None, *, mode: str = "open", filter: str = "", placeholder: str = ""
|
|
395
|
+
) -> None:
|
|
396
|
+
super().__init__(parent)
|
|
397
|
+
if mode not in _TITLES:
|
|
398
|
+
raise ValueError(f"Unbekannter Modus {mode!r}")
|
|
399
|
+
self._mode = mode
|
|
400
|
+
self._filter = filter
|
|
401
|
+
self._placeholder = placeholder
|
|
402
|
+
self._start_dir = ""
|
|
403
|
+
self._check = "none"
|
|
404
|
+
self._null = False
|
|
405
|
+
self._generation = 0
|
|
406
|
+
self._result: tuple[str, str] = ("", "")
|
|
407
|
+
self._pending = False
|
|
408
|
+
self._relay = _CheckRelay(self)
|
|
409
|
+
self._relay.done.connect(self._on_checked)
|
|
410
|
+
layout = QVBoxLayout(self)
|
|
411
|
+
layout.setContentsMargins(0, 0, 0, 0)
|
|
412
|
+
layout.setSpacing(2)
|
|
413
|
+
row = QHBoxLayout()
|
|
414
|
+
row.setSpacing(4)
|
|
415
|
+
self._edit = QLineEdit(self)
|
|
416
|
+
self._edit.setMinimumWidth(80)
|
|
417
|
+
self._edit.setClearButtonEnabled(False)
|
|
418
|
+
self._edit.textEdited.connect(self._on_text)
|
|
419
|
+
row.addWidget(self._edit, 1)
|
|
420
|
+
self._button = QToolButton(self)
|
|
421
|
+
self._button.clicked.connect(self._browse)
|
|
422
|
+
row.addWidget(self._button)
|
|
423
|
+
layout.addLayout(row)
|
|
424
|
+
self._status = _StatusText(self)
|
|
425
|
+
self._status.hide()
|
|
426
|
+
layout.addWidget(self._status)
|
|
427
|
+
self.setFocusProxy(self._edit)
|
|
428
|
+
_SchemeFollower(self, self._update_icon)
|
|
429
|
+
self._apply_options()
|
|
430
|
+
|
|
431
|
+
@property
|
|
432
|
+
def line_edit(self) -> QLineEdit:
|
|
433
|
+
return self._edit
|
|
434
|
+
|
|
435
|
+
@property
|
|
436
|
+
def browse_button(self) -> QToolButton:
|
|
437
|
+
return self._button
|
|
438
|
+
|
|
439
|
+
# -- Optionen -----------------------------------------------------------------------
|
|
440
|
+
def _set_option(self, key: str, value: Any) -> None:
|
|
441
|
+
if key == "mode" and value not in _TITLES:
|
|
442
|
+
raise ValueError(f"Unbekannter Modus {value!r}")
|
|
443
|
+
if key == "check" and value not in ("none", "warn", "require"):
|
|
444
|
+
raise ValueError("check: 'none', 'warn' oder 'require' erwartet")
|
|
445
|
+
if key in ("filter", "placeholder", "start_dir"):
|
|
446
|
+
value = "" if value is None else str(value)
|
|
447
|
+
super()._set_option(key, value)
|
|
448
|
+
|
|
449
|
+
def _apply_options(self) -> None:
|
|
450
|
+
title = _TITLES[self._mode]
|
|
451
|
+
self._button.setToolTip(f"{title} …")
|
|
452
|
+
self._button.setAccessibleName(title)
|
|
453
|
+
self._edit.setPlaceholderText(self._placeholder)
|
|
454
|
+
self._update_icon()
|
|
455
|
+
self._start_check()
|
|
456
|
+
|
|
457
|
+
def _update_icon(self) -> None:
|
|
458
|
+
self._button.setIcon(_svg_icon(_ICONS[self._mode], self))
|
|
459
|
+
|
|
460
|
+
def changeEvent(self, event: QEvent) -> None:
|
|
461
|
+
super().changeEvent(event)
|
|
462
|
+
if event.type() in (QEvent.Type.PaletteChange, QEvent.Type.StyleChange) and hasattr(self, "_button"):
|
|
463
|
+
self._update_icon()
|
|
464
|
+
|
|
465
|
+
# -- Dialog -----------------------------------------------------------------------------
|
|
466
|
+
def choose(self) -> str:
|
|
467
|
+
"""Öffnet den Auswahldialog und liefert den Pfad (leer bei Abbruch)."""
|
|
468
|
+
title = _TITLES[self._mode]
|
|
469
|
+
start = self._edit.text() or self._start_dir
|
|
470
|
+
if self._mode == "directory":
|
|
471
|
+
return QFileDialog.getExistingDirectory(self, title, start)
|
|
472
|
+
if self._mode == "save":
|
|
473
|
+
return QFileDialog.getSaveFileName(self, title, start, self._filter)[0]
|
|
474
|
+
return QFileDialog.getOpenFileName(self, title, start, self._filter)[0]
|
|
475
|
+
|
|
476
|
+
def _browse(self) -> None:
|
|
477
|
+
if self._read_only:
|
|
478
|
+
return
|
|
479
|
+
visible = self.isVisible()
|
|
480
|
+
path = self.choose()
|
|
481
|
+
if path and not self._read_only and (not visible or self.isVisible()):
|
|
482
|
+
self._edit.setText(path)
|
|
483
|
+
self._on_text()
|
|
484
|
+
|
|
485
|
+
# -- Wert ----------------------------------------------------------------------------
|
|
486
|
+
def _on_text(self, *_: Any) -> None:
|
|
487
|
+
self._null = False
|
|
488
|
+
self._start_check()
|
|
489
|
+
self._user_changed()
|
|
490
|
+
|
|
491
|
+
def value(self) -> str | None:
|
|
492
|
+
text = self._edit.text()
|
|
493
|
+
if not text and (self._null or self._optional):
|
|
494
|
+
return None
|
|
495
|
+
return text
|
|
496
|
+
|
|
497
|
+
def _apply_value(self, value: Any) -> None:
|
|
498
|
+
if value is not None and not isinstance(value, str):
|
|
499
|
+
raise ValueError("Pfad als Text erwartet")
|
|
500
|
+
self._null = value is None
|
|
501
|
+
if self._edit.text() != (value or ""):
|
|
502
|
+
self._edit.setText(value or "")
|
|
503
|
+
self._start_check()
|
|
504
|
+
|
|
505
|
+
def _apply_read_only(self, read_only: bool) -> None:
|
|
506
|
+
self._edit.setReadOnly(read_only)
|
|
507
|
+
self._button.setEnabled(not read_only)
|
|
508
|
+
if read_only:
|
|
509
|
+
self.cancel_activity()
|
|
510
|
+
elif self.isVisible() and self._pending:
|
|
511
|
+
self._start_check()
|
|
512
|
+
|
|
513
|
+
def cancel_activity(self) -> None:
|
|
514
|
+
"""Macht eine ausstehende Pfadprüfung ungültig, bis der Editor wieder sichtbar ist."""
|
|
515
|
+
if self._pending:
|
|
516
|
+
self._generation += 1
|
|
517
|
+
|
|
518
|
+
def hideEvent(self, event) -> None:
|
|
519
|
+
super().hideEvent(event)
|
|
520
|
+
self.cancel_activity()
|
|
521
|
+
|
|
522
|
+
def showEvent(self, event) -> None:
|
|
523
|
+
super().showEvent(event)
|
|
524
|
+
if self._pending and not self._read_only:
|
|
525
|
+
self._start_check()
|
|
526
|
+
|
|
527
|
+
# -- Prüfung ---------------------------------------------------------------------------
|
|
528
|
+
def check_result(self) -> tuple[str, str]:
|
|
529
|
+
"""Letztes Prüfergebnis ``(ergebnis, text)``; ``("pending", …)`` während der Prüfung."""
|
|
530
|
+
return ("pending", "Wird geprüft …") if self._pending else self._result
|
|
531
|
+
|
|
532
|
+
def is_checking(self) -> bool:
|
|
533
|
+
return self._pending
|
|
534
|
+
|
|
535
|
+
def input_error(self) -> str:
|
|
536
|
+
if self._check != "require":
|
|
537
|
+
return ""
|
|
538
|
+
if self._pending:
|
|
539
|
+
return "Pfad wird noch geprüft"
|
|
540
|
+
outcome, text = self._result
|
|
541
|
+
return text if outcome == "problem" else ""
|
|
542
|
+
|
|
543
|
+
def _start_check(self) -> None:
|
|
544
|
+
self._generation += 1
|
|
545
|
+
path = self._edit.text().strip()
|
|
546
|
+
if self._check == "none" or not path:
|
|
547
|
+
self._pending = False
|
|
548
|
+
self._result = ("", "")
|
|
549
|
+
self._show_result()
|
|
550
|
+
return
|
|
551
|
+
kind = _classify(path)
|
|
552
|
+
if kind == "slow":
|
|
553
|
+
self._pending = True
|
|
554
|
+
self._show_result()
|
|
555
|
+
generation, mode = self._generation, self._mode
|
|
556
|
+
threading.Thread(target=self._check_in_thread, args=(generation, path, mode), daemon=True).start()
|
|
557
|
+
return
|
|
558
|
+
self._pending = False
|
|
559
|
+
self._result = check_path(path, self._mode)
|
|
560
|
+
self._show_result()
|
|
561
|
+
|
|
562
|
+
def _check_in_thread(self, generation: int, path: str, mode: str) -> None:
|
|
563
|
+
try:
|
|
564
|
+
outcome, text = check_path(path, mode)
|
|
565
|
+
except OSError as exc: # pragma: no cover – Laufwerksfehler
|
|
566
|
+
outcome, text = "problem", f"Nicht prüfbar: {exc.strerror or exc}"
|
|
567
|
+
try:
|
|
568
|
+
self._relay.done.emit(generation, outcome, text)
|
|
569
|
+
except RuntimeError: # Widget inzwischen gelöscht
|
|
570
|
+
pass
|
|
571
|
+
|
|
572
|
+
def _on_checked(self, generation: int, outcome: str, text: str) -> None:
|
|
573
|
+
if generation != self._generation:
|
|
574
|
+
return # Ergebnis gehört zu einer älteren Eingabe
|
|
575
|
+
self._pending = False
|
|
576
|
+
self._result = (outcome, text)
|
|
577
|
+
self._show_result()
|
|
578
|
+
self._check_error()
|
|
579
|
+
|
|
580
|
+
def _show_result(self) -> None:
|
|
581
|
+
if self._pending:
|
|
582
|
+
self._status.show_message("Wird geprüft …", "busy")
|
|
583
|
+
else:
|
|
584
|
+
outcome, text = self._result
|
|
585
|
+
role = {"ok": "success", "skipped": "info", "problem": "error" if self._check == "require" else "warning"}.get(outcome, "plain")
|
|
586
|
+
if outcome == "ok" and not self.SHOW_OK:
|
|
587
|
+
text = ""
|
|
588
|
+
self._status.show_message(text, role)
|
|
589
|
+
self._status.setVisible(bool(self._status.text()))
|
|
590
|
+
|
|
591
|
+
|
|
592
|
+
def _demo() -> None: # pragma: no cover – python path_editor.py
|
|
593
|
+
from PySide6.QtWidgets import QApplication, QFormLayout
|
|
594
|
+
|
|
595
|
+
app = QApplication.instance() or QApplication([])
|
|
596
|
+
host = QWidget()
|
|
597
|
+
form = QFormLayout(host)
|
|
598
|
+
editors = (
|
|
599
|
+
("Datei öffnen (warn)", PathEditor(mode="open", filter="Text (*.txt);;Alle Dateien (*)")),
|
|
600
|
+
("Speichern unter (require)", PathEditor(mode="save")),
|
|
601
|
+
("Ordner (require)", PathEditor(mode="directory")),
|
|
602
|
+
)
|
|
603
|
+
editors[0][1].configure(check="warn")
|
|
604
|
+
editors[1][1].configure(check="require")
|
|
605
|
+
editors[2][1].configure(check="require")
|
|
606
|
+
for label, editor in editors:
|
|
607
|
+
editor.value_edited.connect(lambda v, n=label, e=editor: print(n, v, e.input_error()))
|
|
608
|
+
form.addRow(label, editor)
|
|
609
|
+
host.resize(560, 200)
|
|
610
|
+
host.show()
|
|
611
|
+
app.exec()
|
|
612
|
+
|
|
613
|
+
|
|
614
|
+
if __name__ == "__main__":
|
|
615
|
+
_demo()
|