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,710 @@
|
|
|
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
|
+
"""Autarke Sound-Auswahl und lokale Vorschau (Standardbibliothek und PySide6).
|
|
24
|
+
|
|
25
|
+
Relative Quellen beziehen sich auf den übergebenen absoluten resource_root,
|
|
26
|
+
sonst auf den Ordner dieser kopierten Datei. Die Auswahl funktioniert mit
|
|
27
|
+
PySide6-Essentials. Wiedergabe benötigt zusätzlich QtMultimedia.
|
|
28
|
+
"""
|
|
29
|
+
|
|
30
|
+
from __future__ import annotations
|
|
31
|
+
|
|
32
|
+
import os
|
|
33
|
+
import re
|
|
34
|
+
import stat
|
|
35
|
+
import threading
|
|
36
|
+
from collections import Counter
|
|
37
|
+
from concurrent.futures import Future
|
|
38
|
+
from dataclasses import dataclass
|
|
39
|
+
from pathlib import Path
|
|
40
|
+
from queue import SimpleQueue
|
|
41
|
+
from typing import Any
|
|
42
|
+
|
|
43
|
+
from PySide6.QtCore import QAbstractListModel, QEvent, QModelIndex, QObject, Qt, QTimer, QUrl, Signal
|
|
44
|
+
from PySide6.QtGui import QIcon, QPainter, QPainterPath, QPalette, QPixmap
|
|
45
|
+
from PySide6.QtWidgets import QComboBox, QGridLayout, QLabel, QToolButton, QWidget
|
|
46
|
+
|
|
47
|
+
try:
|
|
48
|
+
from PySide6.QtMultimedia import QAudioOutput, QMediaPlayer
|
|
49
|
+
except (ImportError, OSError):
|
|
50
|
+
QAudioOutput = QMediaPlayer = None
|
|
51
|
+
|
|
52
|
+
__all__ = ["SoundSelectionWidget"]
|
|
53
|
+
|
|
54
|
+
_UNSELECTED = object()
|
|
55
|
+
_FILTER = re.compile(r"\.?[^\s./\\:\x00]+")
|
|
56
|
+
_NO_AUDIO = "Vorschau benötigt QtMultimedia (PySide6-Addons)."
|
|
57
|
+
_DEFAULTS = {
|
|
58
|
+
"bundled_path": None, "resource_root": None, "additional_paths": (), "env_variable": None,
|
|
59
|
+
"auto_play": False, "show_play_button": True, "allow_none": True, "recursive": True,
|
|
60
|
+
"volume": 0.8, "extensions": (".wav", ".mp3", ".ogg"),
|
|
61
|
+
}
|
|
62
|
+
_SOURCE_OPTIONS = ("bundled_path", "resource_root", "additional_paths", "env_variable", "recursive", "extensions")
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def _option(name: str, value: Any) -> Any:
|
|
66
|
+
if name in ("bundled_path", "resource_root"):
|
|
67
|
+
if value is None:
|
|
68
|
+
return None
|
|
69
|
+
value = _path_text(value)
|
|
70
|
+
if name == "resource_root" and not Path(value).is_absolute():
|
|
71
|
+
raise ValueError("resource_root muss ein absoluter Pfad sein")
|
|
72
|
+
elif name == "env_variable":
|
|
73
|
+
if value is not None and (not isinstance(value, str) or not value.strip() or "=" in value or "\0" in value):
|
|
74
|
+
raise ValueError("env_variable erwartet einen Umgebungsvariablennamen")
|
|
75
|
+
elif name == "additional_paths":
|
|
76
|
+
if not isinstance(value, (list, tuple)):
|
|
77
|
+
raise ValueError("additional_paths erwartet eine Liste von Pfaden")
|
|
78
|
+
value = tuple(_path_text(path) for path in value)
|
|
79
|
+
elif name == "extensions":
|
|
80
|
+
if not isinstance(value, (list, tuple)) or not value or not all(
|
|
81
|
+
isinstance(ext, str) and _FILTER.fullmatch(ext) for ext in value
|
|
82
|
+
):
|
|
83
|
+
raise ValueError("extensions erwartet eine nicht leere Liste von Dateiendungen")
|
|
84
|
+
value = tuple("." + ext.lstrip(".").casefold() for ext in value)
|
|
85
|
+
elif name == "volume":
|
|
86
|
+
if type(value) not in (int, float) or not 0 <= value <= 1:
|
|
87
|
+
raise ValueError("volume muss zwischen 0 und 1 liegen")
|
|
88
|
+
value = float(value)
|
|
89
|
+
elif type(value) is not bool:
|
|
90
|
+
raise ValueError(f"{name} erwartet true/false")
|
|
91
|
+
return value
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def _path_text(value: Any) -> str:
|
|
95
|
+
if isinstance(value, os.PathLike):
|
|
96
|
+
value = os.fspath(value)
|
|
97
|
+
if not isinstance(value, str) or not value.strip() or "\0" in value:
|
|
98
|
+
raise ValueError("Ein nicht leerer Pfad wird erwartet")
|
|
99
|
+
return value
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def _source_path(value: str, root: Path | None) -> Path | None:
|
|
103
|
+
path = Path(value)
|
|
104
|
+
if path.is_absolute():
|
|
105
|
+
return path
|
|
106
|
+
# Auch laufwerksrelative Pfade (C:ordner, \ordner) würden unter Windows vom CWD abhängen.
|
|
107
|
+
return root / path if root is not None and not path.anchor else None
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def _environment_paths(name: str | None) -> list[str]:
|
|
111
|
+
paths = []
|
|
112
|
+
for part in os.environ.get(name, "").split(os.pathsep) if name else ():
|
|
113
|
+
part = part.strip()
|
|
114
|
+
if len(part) >= 2 and part[0] == part[-1] and part[0] in "\"'":
|
|
115
|
+
part = part[1:-1]
|
|
116
|
+
if part.strip():
|
|
117
|
+
paths.append(part)
|
|
118
|
+
return paths
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def _reference_key(value: str) -> str:
|
|
122
|
+
if value.startswith("external:"):
|
|
123
|
+
path = Path(value.removeprefix("external:"))
|
|
124
|
+
if path.is_absolute():
|
|
125
|
+
return "external:" + os.path.normcase(os.path.normpath(path))
|
|
126
|
+
return value
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def _valid_reference(value: str) -> bool:
|
|
130
|
+
scheme, _, path = value.partition(":")
|
|
131
|
+
if not path or "\0" in path:
|
|
132
|
+
return False
|
|
133
|
+
if scheme == "bundled":
|
|
134
|
+
return not (":" in path or "\\" in path or set(path.split("/")) & {"", ".", ".."})
|
|
135
|
+
return scheme == "external" and Path(path).is_absolute()
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def _preview_icon(palette: QPalette, stop: bool, scale: float) -> QIcon:
|
|
139
|
+
shape = QPainterPath()
|
|
140
|
+
if stop:
|
|
141
|
+
shape.addRect(3.0, 3.0, 10.0, 10.0)
|
|
142
|
+
else:
|
|
143
|
+
shape.moveTo(4.0, 2.0)
|
|
144
|
+
shape.lineTo(13.0, 8.0)
|
|
145
|
+
shape.lineTo(4.0, 14.0)
|
|
146
|
+
shape.closeSubpath()
|
|
147
|
+
icon = QIcon()
|
|
148
|
+
for group, mode in ((QPalette.ColorGroup.Active, QIcon.Mode.Normal),
|
|
149
|
+
(QPalette.ColorGroup.Disabled, QIcon.Mode.Disabled)):
|
|
150
|
+
pixmap = QPixmap(round(16 * scale), round(16 * scale))
|
|
151
|
+
pixmap.setDevicePixelRatio(scale)
|
|
152
|
+
pixmap.fill(Qt.GlobalColor.transparent)
|
|
153
|
+
painter = QPainter(pixmap)
|
|
154
|
+
painter.setRenderHint(QPainter.RenderHint.Antialiasing)
|
|
155
|
+
painter.fillPath(shape, palette.color(group, QPalette.ColorRole.ButtonText))
|
|
156
|
+
painter.end()
|
|
157
|
+
icon.addPixmap(pixmap, mode)
|
|
158
|
+
return icon
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
@dataclass(frozen=True)
|
|
162
|
+
class _Sound:
|
|
163
|
+
reference: str
|
|
164
|
+
path: Path
|
|
165
|
+
source: Path
|
|
166
|
+
root: Path
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
@dataclass(frozen=True)
|
|
170
|
+
class _Catalog:
|
|
171
|
+
rows: tuple[tuple[str, _Sound], ...]
|
|
172
|
+
indices: dict[str, int]
|
|
173
|
+
unavailable: int = 0
|
|
174
|
+
|
|
175
|
+
def index(self, value: object) -> int | None:
|
|
176
|
+
return self.indices.get(_reference_key(value)) if isinstance(value, str) else None
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
_EMPTY = _Catalog((), {})
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
def _walk(root: Path, recursive: bool, extensions: tuple[str, ...], cancelled: threading.Event):
|
|
183
|
+
pending = [root]
|
|
184
|
+
while pending and not cancelled.is_set():
|
|
185
|
+
directory = pending.pop()
|
|
186
|
+
try:
|
|
187
|
+
with os.scandir(directory) as entries:
|
|
188
|
+
for entry in entries:
|
|
189
|
+
if cancelled.is_set():
|
|
190
|
+
return
|
|
191
|
+
try:
|
|
192
|
+
if entry.is_dir(follow_symlinks=False):
|
|
193
|
+
if recursive and not (
|
|
194
|
+
getattr(entry.stat(follow_symlinks=False), "st_file_attributes", 0)
|
|
195
|
+
& stat.FILE_ATTRIBUTE_REPARSE_POINT
|
|
196
|
+
):
|
|
197
|
+
pending.append(Path(entry.path))
|
|
198
|
+
elif entry.is_file(follow_symlinks=False) and Path(entry.name).suffix.casefold() in extensions:
|
|
199
|
+
yield Path(entry.path)
|
|
200
|
+
except OSError:
|
|
201
|
+
yield None
|
|
202
|
+
except OSError:
|
|
203
|
+
yield None
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
def _scan(options: dict[str, Any], cancelled: threading.Event) -> _Catalog:
|
|
207
|
+
root = Path(options["resource_root"]) if options["resource_root"] else None
|
|
208
|
+
sources = [(False, path) for path in (*options["additional_paths"], *_environment_paths(options["env_variable"]))]
|
|
209
|
+
if options["bundled_path"] is not None:
|
|
210
|
+
sources.insert(0, (True, options["bundled_path"]))
|
|
211
|
+
sounds: dict[Path, _Sound] = {}
|
|
212
|
+
scanned: set[Path] = set()
|
|
213
|
+
unavailable = 0
|
|
214
|
+
for bundled, raw in sources:
|
|
215
|
+
if cancelled.is_set():
|
|
216
|
+
return _EMPTY
|
|
217
|
+
source = _source_path(raw, root)
|
|
218
|
+
if source is None:
|
|
219
|
+
unavailable += 1
|
|
220
|
+
continue
|
|
221
|
+
try:
|
|
222
|
+
directory = source.resolve(strict=True)
|
|
223
|
+
except (OSError, ValueError, RuntimeError):
|
|
224
|
+
unavailable += 1
|
|
225
|
+
continue
|
|
226
|
+
if options["recursive"] and directory.parent == directory:
|
|
227
|
+
unavailable += 1
|
|
228
|
+
continue
|
|
229
|
+
if directory in scanned:
|
|
230
|
+
continue
|
|
231
|
+
scanned.add(directory)
|
|
232
|
+
for path in _walk(directory, options["recursive"], options["extensions"], cancelled):
|
|
233
|
+
if path is None:
|
|
234
|
+
unavailable += 1
|
|
235
|
+
continue
|
|
236
|
+
try:
|
|
237
|
+
actual = path.resolve(strict=True)
|
|
238
|
+
except (OSError, ValueError, RuntimeError):
|
|
239
|
+
unavailable += 1
|
|
240
|
+
continue
|
|
241
|
+
if actual != path or not actual.is_relative_to(directory):
|
|
242
|
+
continue
|
|
243
|
+
if bundled:
|
|
244
|
+
relative = path.relative_to(directory).as_posix()
|
|
245
|
+
if ":" in relative or "\\" in relative:
|
|
246
|
+
continue
|
|
247
|
+
reference = f"bundled:{relative}"
|
|
248
|
+
else:
|
|
249
|
+
reference = f"external:{actual.as_posix()}"
|
|
250
|
+
sounds.setdefault(actual, _Sound(reference, path, source, directory))
|
|
251
|
+
ordered = sorted(sounds.values(), key=lambda s: (s.path.stem.casefold(), s.reference.casefold(), s.reference))
|
|
252
|
+
counts = Counter(sound.path.stem.casefold() for sound in ordered)
|
|
253
|
+
rows = tuple(
|
|
254
|
+
(sound.path.stem if counts[sound.path.stem.casefold()] == 1 else
|
|
255
|
+
f"{sound.path.stem} — {sound.reference}", sound)
|
|
256
|
+
for sound in ordered
|
|
257
|
+
)
|
|
258
|
+
return _Catalog(rows, {_reference_key(sound.reference): i for i, (_, sound) in enumerate(rows)}, unavailable)
|
|
259
|
+
|
|
260
|
+
|
|
261
|
+
def _preview_path(sound: _Sound) -> Path | None:
|
|
262
|
+
"""Erneute Prüfung außerhalb des GUI-Threads, falls sich ein Pfad inzwischen geändert hat."""
|
|
263
|
+
try:
|
|
264
|
+
if (sound.source.resolve(strict=True) == sound.root
|
|
265
|
+
and sound.path.resolve(strict=True) == sound.path
|
|
266
|
+
and sound.path.is_file()):
|
|
267
|
+
return sound.path
|
|
268
|
+
except (OSError, ValueError, RuntimeError):
|
|
269
|
+
pass
|
|
270
|
+
return None
|
|
271
|
+
|
|
272
|
+
|
|
273
|
+
# Maximal zwei Dateisystemabfragen, auch wenn mehrere Editoren gleichzeitig aufgebaut werden.
|
|
274
|
+
# Daemon-Threads enthalten keine Qt-Objekte und halten den Prozess bei blockiertem I/O nicht offen.
|
|
275
|
+
_JOBS: SimpleQueue = SimpleQueue()
|
|
276
|
+
_workers_started = False
|
|
277
|
+
|
|
278
|
+
|
|
279
|
+
def _worker() -> None:
|
|
280
|
+
while True:
|
|
281
|
+
future, function, args = _JOBS.get()
|
|
282
|
+
if future.set_running_or_notify_cancel():
|
|
283
|
+
try:
|
|
284
|
+
future.set_result(function(*args))
|
|
285
|
+
except Exception as exc:
|
|
286
|
+
future.set_exception(exc)
|
|
287
|
+
del future, function, args
|
|
288
|
+
|
|
289
|
+
|
|
290
|
+
def _submit(function, *args) -> Future:
|
|
291
|
+
global _workers_started
|
|
292
|
+
if not _workers_started:
|
|
293
|
+
_workers_started = True # Aufruf ausschließlich aus dem Qt-GUI-Thread
|
|
294
|
+
for index in range(2):
|
|
295
|
+
threading.Thread(target=_worker, name=f"sound-files-{index}", daemon=True).start()
|
|
296
|
+
future = Future()
|
|
297
|
+
_JOBS.put((future, function, args))
|
|
298
|
+
return future
|
|
299
|
+
|
|
300
|
+
|
|
301
|
+
class _SoundModel(QAbstractListModel):
|
|
302
|
+
"""Modell-Reset in konstanter Zeit, keine einzelnen Qt-Items pro Audiodatei."""
|
|
303
|
+
|
|
304
|
+
def __init__(self, parent: QObject) -> None:
|
|
305
|
+
super().__init__(parent)
|
|
306
|
+
self.catalog = _EMPTY
|
|
307
|
+
self.header: list[tuple[str, str | None]] = []
|
|
308
|
+
|
|
309
|
+
def reset(self, catalog: _Catalog, header: list[tuple[str, str | None]]) -> None:
|
|
310
|
+
self.beginResetModel()
|
|
311
|
+
self.catalog, self.header = catalog, header
|
|
312
|
+
self.endResetModel()
|
|
313
|
+
|
|
314
|
+
def rowCount(self, parent: QModelIndex = QModelIndex()) -> int:
|
|
315
|
+
return 0 if parent.isValid() else len(self.header) + len(self.catalog.rows)
|
|
316
|
+
|
|
317
|
+
def data(self, index: QModelIndex, role: int = Qt.ItemDataRole.DisplayRole) -> Any:
|
|
318
|
+
row = index.row()
|
|
319
|
+
if not index.isValid() or not 0 <= row < self.rowCount():
|
|
320
|
+
return None
|
|
321
|
+
if row < len(self.header):
|
|
322
|
+
label, reference = self.header[row]
|
|
323
|
+
else:
|
|
324
|
+
label, sound = self.catalog.rows[row - len(self.header)]
|
|
325
|
+
reference = sound.reference
|
|
326
|
+
if role in (Qt.ItemDataRole.DisplayRole, Qt.ItemDataRole.AccessibleTextRole):
|
|
327
|
+
return label
|
|
328
|
+
if role in (Qt.ItemDataRole.UserRole, Qt.ItemDataRole.ToolTipRole):
|
|
329
|
+
return reference
|
|
330
|
+
return None
|
|
331
|
+
|
|
332
|
+
|
|
333
|
+
class SoundSelectionWidget(QWidget):
|
|
334
|
+
"""Wählt eine lokale Soundreferenz und spielt sie auf ausdrückliche Anforderung vor.
|
|
335
|
+
|
|
336
|
+
Konstruktoroptionen und configure(): bundled_path, resource_root, additional_paths,
|
|
337
|
+
env_variable, auto_play, show_play_button, allow_none (Alias optional), recursive,
|
|
338
|
+
volume und extensions. value_edited wird nur nach geänderter Benutzerauswahl gesendet.
|
|
339
|
+
"""
|
|
340
|
+
|
|
341
|
+
value_changed = Signal(object)
|
|
342
|
+
value_edited = Signal(object)
|
|
343
|
+
input_error_changed = Signal(str)
|
|
344
|
+
_default_root = Path(__file__).parent
|
|
345
|
+
_initial_value = None
|
|
346
|
+
|
|
347
|
+
def __init__(self, parent: QWidget | None = None, **options: Any) -> None:
|
|
348
|
+
super().__init__(parent)
|
|
349
|
+
self._options = {**_DEFAULTS, "resource_root": self._default_root}
|
|
350
|
+
self._current: object = self._initial_value
|
|
351
|
+
self._read_only = False
|
|
352
|
+
self._closed = False
|
|
353
|
+
self._catalog = _EMPTY
|
|
354
|
+
self._catalog_error = ""
|
|
355
|
+
self._last_error = ""
|
|
356
|
+
self._play_error = ""
|
|
357
|
+
self._scan_job: Future | None = None
|
|
358
|
+
self._scan_cancel = threading.Event()
|
|
359
|
+
self._cancel_on_destroy = [self._scan_cancel]
|
|
360
|
+
self._preview_job: Future | None = None
|
|
361
|
+
self._player = None
|
|
362
|
+
self._starting = False
|
|
363
|
+
|
|
364
|
+
self.combo_box = QComboBox(self)
|
|
365
|
+
self.combo_box.setAccessibleName("Soundauswahl")
|
|
366
|
+
self.combo_box.setPlaceholderText("Sound auswählen")
|
|
367
|
+
self.combo_box.setSizeAdjustPolicy(QComboBox.SizeAdjustPolicy.AdjustToMinimumContentsLengthWithIcon)
|
|
368
|
+
self.combo_box.setMinimumContentsLength(12)
|
|
369
|
+
self.combo_box.setFocusPolicy(Qt.FocusPolicy.StrongFocus)
|
|
370
|
+
self.combo_box.installEventFilter(self)
|
|
371
|
+
self._model = _SoundModel(self.combo_box)
|
|
372
|
+
self.combo_box.setModel(self._model)
|
|
373
|
+
self.combo_box.activated.connect(self._selected)
|
|
374
|
+
self.setFocusProxy(self.combo_box)
|
|
375
|
+
|
|
376
|
+
self.play_button = QToolButton(self)
|
|
377
|
+
self.play_button.setFocusPolicy(Qt.FocusPolicy.StrongFocus)
|
|
378
|
+
self.play_button.clicked.connect(self._toggle_preview)
|
|
379
|
+
self._status = QLabel(self)
|
|
380
|
+
self._status.setTextFormat(Qt.TextFormat.PlainText)
|
|
381
|
+
self._status.setWordWrap(True)
|
|
382
|
+
self._status.setMinimumWidth(1)
|
|
383
|
+
layout = QGridLayout(self)
|
|
384
|
+
layout.setContentsMargins(0, 0, 0, 0)
|
|
385
|
+
layout.setHorizontalSpacing(4)
|
|
386
|
+
layout.setVerticalSpacing(2)
|
|
387
|
+
layout.addWidget(self.combo_box, 0, 0)
|
|
388
|
+
layout.addWidget(self.play_button, 0, 1)
|
|
389
|
+
layout.addWidget(self._status, 1, 0, 1, 2)
|
|
390
|
+
layout.setColumnStretch(0, 1)
|
|
391
|
+
|
|
392
|
+
self._poll = QTimer(self, interval=25)
|
|
393
|
+
self._poll.timeout.connect(self._completed_jobs)
|
|
394
|
+
self._start_timeout = QTimer(self, interval=8000, singleShot=True)
|
|
395
|
+
self._start_timeout.timeout.connect(self._preview_timeout)
|
|
396
|
+
cancel_on_destroy = self._cancel_on_destroy
|
|
397
|
+
self.destroyed.connect(lambda: cancel_on_destroy[0].set())
|
|
398
|
+
self.configure(**options)
|
|
399
|
+
if self._scan_job is None:
|
|
400
|
+
self.refresh_sounds()
|
|
401
|
+
|
|
402
|
+
def configure(self, **options: Any) -> None:
|
|
403
|
+
"""Ändert Optionen atomar. Quellenänderungen starten eine Hintergrundsuche."""
|
|
404
|
+
if "optional" in options:
|
|
405
|
+
options["allow_none"] = options.pop("optional")
|
|
406
|
+
unknown = options.keys() - _DEFAULTS.keys()
|
|
407
|
+
if unknown:
|
|
408
|
+
raise TypeError(f"Unbekannte Soundoption(en): {', '.join(sorted(unknown))}")
|
|
409
|
+
updated = {**self._options, **{key: _option(key, value) for key, value in options.items()}}
|
|
410
|
+
if updated == self._options:
|
|
411
|
+
return
|
|
412
|
+
rescan = any(updated[key] != self._options[key] for key in _SOURCE_OPTIONS)
|
|
413
|
+
self._options = updated
|
|
414
|
+
if self._player is not None and self._player.audioOutput() is not None:
|
|
415
|
+
self._player.audioOutput().setVolume(updated["volume"])
|
|
416
|
+
if rescan:
|
|
417
|
+
self.refresh_sounds()
|
|
418
|
+
else:
|
|
419
|
+
self._rebuild()
|
|
420
|
+
|
|
421
|
+
def options(self) -> dict[str, Any]:
|
|
422
|
+
return dict(self._options)
|
|
423
|
+
|
|
424
|
+
def set_constraints(self, *, optional: bool) -> None:
|
|
425
|
+
"""Legt fest, ob die explizite Auswahl „Kein Sound“ erlaubt ist."""
|
|
426
|
+
self.configure(allow_none=optional)
|
|
427
|
+
|
|
428
|
+
def set_optional(self, optional: bool) -> None:
|
|
429
|
+
self.configure(allow_none=optional)
|
|
430
|
+
|
|
431
|
+
def is_optional(self) -> bool:
|
|
432
|
+
return self._options["allow_none"]
|
|
433
|
+
|
|
434
|
+
def value(self) -> str | None:
|
|
435
|
+
return self._current if isinstance(self._current, str) else None
|
|
436
|
+
|
|
437
|
+
def set_value(self, value: str | None) -> None:
|
|
438
|
+
"""Wert ohne Benutzersignal oder Vorschau setzen, auch wenn die Datei fehlt."""
|
|
439
|
+
if value is not None and not isinstance(value, str):
|
|
440
|
+
raise ValueError("Soundreferenz als Text oder None erwartet")
|
|
441
|
+
self._set_current(value)
|
|
442
|
+
|
|
443
|
+
def _set_current(self, value: object) -> None:
|
|
444
|
+
if self._current == value:
|
|
445
|
+
return
|
|
446
|
+
self.stop()
|
|
447
|
+
self._current = value
|
|
448
|
+
self._play_error = ""
|
|
449
|
+
self._rebuild()
|
|
450
|
+
self.value_changed.emit(self.value())
|
|
451
|
+
|
|
452
|
+
def _selected(self, row: int) -> None:
|
|
453
|
+
if not self._editable() or self._scan_job is not None or not 0 <= row < self.combo_box.count():
|
|
454
|
+
self._rebuild()
|
|
455
|
+
return
|
|
456
|
+
reference = self.combo_box.itemData(row)
|
|
457
|
+
if reference == self._current or (reference is None and not self.is_optional()):
|
|
458
|
+
return
|
|
459
|
+
if reference is not None and self._catalog.index(reference) is None:
|
|
460
|
+
return
|
|
461
|
+
self._set_current(reference)
|
|
462
|
+
self.value_edited.emit(reference)
|
|
463
|
+
if self._options["auto_play"] and self._current == reference and self._editable():
|
|
464
|
+
self.play()
|
|
465
|
+
|
|
466
|
+
def set_read_only(self, read_only: bool) -> None:
|
|
467
|
+
self._read_only = bool(read_only)
|
|
468
|
+
if self._read_only:
|
|
469
|
+
self.stop()
|
|
470
|
+
self._update_ui()
|
|
471
|
+
|
|
472
|
+
def is_read_only(self) -> bool:
|
|
473
|
+
return self._read_only
|
|
474
|
+
|
|
475
|
+
def input_error(self) -> str:
|
|
476
|
+
if self._current is None and not self.is_optional():
|
|
477
|
+
return "Ein Sound ist erforderlich."
|
|
478
|
+
if isinstance(self._current, str) and not _valid_reference(self._current):
|
|
479
|
+
return "Ungültige Soundreferenz."
|
|
480
|
+
return ""
|
|
481
|
+
|
|
482
|
+
def commit(self) -> None:
|
|
483
|
+
"""Die nicht editierbare Auswahlliste übernimmt bestätigte Auswahlen sofort."""
|
|
484
|
+
|
|
485
|
+
def refresh_sounds(self) -> None:
|
|
486
|
+
"""Liest die konfigurierten Quellen erneut. Der gewählte Wert bleibt erhalten."""
|
|
487
|
+
if self._closed:
|
|
488
|
+
return
|
|
489
|
+
self._cancel_scan()
|
|
490
|
+
self.stop()
|
|
491
|
+
self._play_error = self._catalog_error = ""
|
|
492
|
+
self._scan_cancel = threading.Event()
|
|
493
|
+
self._cancel_on_destroy[0] = self._scan_cancel
|
|
494
|
+
self._scan_job = _submit(_scan, self.options(), self._scan_cancel)
|
|
495
|
+
self._poll.start()
|
|
496
|
+
self._rebuild()
|
|
497
|
+
|
|
498
|
+
def _cancel_scan(self) -> None:
|
|
499
|
+
self._scan_cancel.set()
|
|
500
|
+
if self._scan_job is not None:
|
|
501
|
+
self._scan_job.cancel()
|
|
502
|
+
self._scan_job = None
|
|
503
|
+
|
|
504
|
+
def _completed_jobs(self) -> None:
|
|
505
|
+
if self._scan_job is not None and self._scan_job.done():
|
|
506
|
+
job, self._scan_job = self._scan_job, None
|
|
507
|
+
try:
|
|
508
|
+
self._catalog = job.result()
|
|
509
|
+
except Exception:
|
|
510
|
+
self._catalog = _EMPTY
|
|
511
|
+
self._catalog_error = "Soundkatalog konnte nicht gelesen werden."
|
|
512
|
+
self._rebuild()
|
|
513
|
+
if self._preview_job is not None and self._preview_job.done():
|
|
514
|
+
job, self._preview_job = self._preview_job, None
|
|
515
|
+
try:
|
|
516
|
+
path = job.result()
|
|
517
|
+
except Exception:
|
|
518
|
+
path = None
|
|
519
|
+
if path is None:
|
|
520
|
+
self._play_error = "Sounddatei nicht verfügbar. Bitte Katalog aktualisieren."
|
|
521
|
+
self._update_ui()
|
|
522
|
+
elif self._editable() and self.isVisible():
|
|
523
|
+
self._start_player(path)
|
|
524
|
+
if self._scan_job is None and self._preview_job is None:
|
|
525
|
+
self._poll.stop()
|
|
526
|
+
|
|
527
|
+
def _rebuild(self) -> None:
|
|
528
|
+
header = [("Kein Sound", None)] if self.is_optional() else []
|
|
529
|
+
current = self._catalog.index(self._current)
|
|
530
|
+
if current is not None:
|
|
531
|
+
index = current + len(header)
|
|
532
|
+
elif isinstance(self._current, str):
|
|
533
|
+
index = len(header)
|
|
534
|
+
text = "Suche läuft …" if self._scan_job is not None else "nicht verfügbar"
|
|
535
|
+
header.append((f"{self._current} ({text})", self._current))
|
|
536
|
+
else:
|
|
537
|
+
index = 0 if self._current is None and header else -1
|
|
538
|
+
self._model.reset(self._catalog, header)
|
|
539
|
+
self.combo_box.setCurrentIndex(index)
|
|
540
|
+
self._update_ui()
|
|
541
|
+
error = self.input_error()
|
|
542
|
+
if error != self._last_error:
|
|
543
|
+
self._last_error = error
|
|
544
|
+
self.input_error_changed.emit(error)
|
|
545
|
+
|
|
546
|
+
def _editable(self) -> bool:
|
|
547
|
+
return not self._closed and not self._read_only and self.isEnabled()
|
|
548
|
+
|
|
549
|
+
def _preview_active(self) -> bool:
|
|
550
|
+
return self._preview_job is not None or self._starting or (
|
|
551
|
+
self._player is not None and self._player.playbackState() == QMediaPlayer.PlaybackState.PlayingState
|
|
552
|
+
)
|
|
553
|
+
|
|
554
|
+
def _update_ui(self) -> None:
|
|
555
|
+
active = self._preview_active()
|
|
556
|
+
self.combo_box.setEnabled(self._editable() and self._scan_job is None)
|
|
557
|
+
self.play_button.setVisible(self._options["show_play_button"])
|
|
558
|
+
previewable = self._scan_job is None and self._catalog.index(self._current) is not None
|
|
559
|
+
self.play_button.setEnabled(self._editable() and QMediaPlayer is not None and (active or previewable))
|
|
560
|
+
text = "Vorschau stoppen" if active else "Vorschau abspielen"
|
|
561
|
+
self.play_button.setAccessibleName(text)
|
|
562
|
+
self.play_button.setToolTip(_NO_AUDIO if QMediaPlayer is None else text)
|
|
563
|
+
self.play_button.setIcon(_preview_icon(self.palette(), active, self.devicePixelRatioF()))
|
|
564
|
+
issues = []
|
|
565
|
+
current_issue = (self._play_error or self._catalog_error
|
|
566
|
+
or ("Soundkatalog wird geladen …" if self._scan_job is not None else self.input_error()))
|
|
567
|
+
if current_issue:
|
|
568
|
+
issues.append(current_issue)
|
|
569
|
+
elif isinstance(self._current, str) and not previewable:
|
|
570
|
+
issues.append("Der ausgewählte Sound ist im Katalog nicht verfügbar.")
|
|
571
|
+
elif not self._catalog.rows:
|
|
572
|
+
issues.append("Keine Sounds gefunden.")
|
|
573
|
+
if self._scan_job is None and self._catalog.unavailable:
|
|
574
|
+
issues.append(f"Einige Suchpfade sind nicht verfügbar ({self._catalog.unavailable}).")
|
|
575
|
+
if QMediaPlayer is None and (self._options["show_play_button"] or self._options["auto_play"]):
|
|
576
|
+
issues.append(_NO_AUDIO)
|
|
577
|
+
self._status.setText(" ".join(issues))
|
|
578
|
+
self._status.setVisible(bool(issues))
|
|
579
|
+
|
|
580
|
+
def play(self) -> bool:
|
|
581
|
+
"""Fordert die Vorschau an. True bestätigt nur den Auftrag, nicht die Wiedergabe."""
|
|
582
|
+
if not self._editable() or not self.isVisible() or self._scan_job is not None:
|
|
583
|
+
return False
|
|
584
|
+
index = self._catalog.index(self._current)
|
|
585
|
+
if QMediaPlayer is None or index is None:
|
|
586
|
+
return False
|
|
587
|
+
if self._preview_active():
|
|
588
|
+
return True
|
|
589
|
+
self.stop()
|
|
590
|
+
self._play_error = ""
|
|
591
|
+
self._preview_job = _submit(_preview_path, self._catalog.rows[index][1])
|
|
592
|
+
self._poll.start()
|
|
593
|
+
self._update_ui()
|
|
594
|
+
return True
|
|
595
|
+
|
|
596
|
+
def _toggle_preview(self) -> None:
|
|
597
|
+
if self._preview_active():
|
|
598
|
+
self.stop()
|
|
599
|
+
else:
|
|
600
|
+
self.play()
|
|
601
|
+
|
|
602
|
+
def _start_player(self, path: Path) -> None:
|
|
603
|
+
try:
|
|
604
|
+
player = self._player = QMediaPlayer(self)
|
|
605
|
+
audio = QAudioOutput(player)
|
|
606
|
+
if audio.device().isNull():
|
|
607
|
+
self._fail_preview("Kein Audiogerät für die Vorschau verfügbar.")
|
|
608
|
+
return
|
|
609
|
+
audio.setVolume(self._options["volume"])
|
|
610
|
+
player.setAudioOutput(audio)
|
|
611
|
+
player.playbackStateChanged.connect(self._player_changed)
|
|
612
|
+
player.mediaStatusChanged.connect(self._player_changed)
|
|
613
|
+
player.errorOccurred.connect(self._player_error)
|
|
614
|
+
self._starting = True
|
|
615
|
+
self._start_timeout.start()
|
|
616
|
+
player.setSource(QUrl.fromLocalFile(os.fspath(path)))
|
|
617
|
+
if self._player is player: # setSource kann den Fehler bereits synchron melden
|
|
618
|
+
player.play()
|
|
619
|
+
except (OSError, RuntimeError):
|
|
620
|
+
self._fail_preview("Die Audiovorschau konnte nicht gestartet werden.")
|
|
621
|
+
self._update_ui()
|
|
622
|
+
|
|
623
|
+
def _player_changed(self, _state) -> None:
|
|
624
|
+
player = self.sender()
|
|
625
|
+
if player is not self._player:
|
|
626
|
+
return
|
|
627
|
+
status = player.mediaStatus()
|
|
628
|
+
if status == QMediaPlayer.MediaStatus.InvalidMedia:
|
|
629
|
+
self._fail_preview(player.errorString() or "Sounddatei oder Codec wird nicht unterstützt.")
|
|
630
|
+
elif status == QMediaPlayer.MediaStatus.EndOfMedia:
|
|
631
|
+
self.stop()
|
|
632
|
+
else:
|
|
633
|
+
if player.playbackState() == QMediaPlayer.PlaybackState.PlayingState:
|
|
634
|
+
self._starting = False
|
|
635
|
+
self._start_timeout.stop()
|
|
636
|
+
self._update_ui()
|
|
637
|
+
|
|
638
|
+
def _player_error(self, _error, text: str) -> None:
|
|
639
|
+
if self.sender() is self._player:
|
|
640
|
+
self._fail_preview(text or "Sounddatei, Codec oder Audiogerät ist nicht verfügbar.")
|
|
641
|
+
|
|
642
|
+
def _preview_timeout(self) -> None:
|
|
643
|
+
self._fail_preview("Audiovorschau konnte nicht rechtzeitig gestartet werden.")
|
|
644
|
+
|
|
645
|
+
def _fail_preview(self, message: str) -> None:
|
|
646
|
+
self._play_error = message
|
|
647
|
+
self.stop()
|
|
648
|
+
|
|
649
|
+
def stop(self) -> None:
|
|
650
|
+
"""Bricht eine angeforderte oder laufende Vorschau ab und gibt das Audiogerät frei."""
|
|
651
|
+
if self._preview_job is not None:
|
|
652
|
+
self._preview_job.cancel()
|
|
653
|
+
self._preview_job = None
|
|
654
|
+
self._start_timeout.stop()
|
|
655
|
+
self._starting = False
|
|
656
|
+
player, self._player = self._player, None
|
|
657
|
+
if player is not None:
|
|
658
|
+
player.stop()
|
|
659
|
+
player.setSource(QUrl())
|
|
660
|
+
player.setAudioOutput(None)
|
|
661
|
+
player.deleteLater()
|
|
662
|
+
self._update_ui()
|
|
663
|
+
|
|
664
|
+
def eventFilter(self, watched: QObject, event: QEvent) -> bool:
|
|
665
|
+
if watched is getattr(self, "combo_box", None) and event.type() == QEvent.Type.Wheel and not self.combo_box.hasFocus():
|
|
666
|
+
event.ignore()
|
|
667
|
+
return True
|
|
668
|
+
return super().eventFilter(watched, event)
|
|
669
|
+
|
|
670
|
+
def changeEvent(self, event: QEvent) -> None:
|
|
671
|
+
super().changeEvent(event)
|
|
672
|
+
if hasattr(self, "_start_timeout"):
|
|
673
|
+
if event.type() == QEvent.Type.EnabledChange:
|
|
674
|
+
if not self.isEnabled():
|
|
675
|
+
self.stop()
|
|
676
|
+
else:
|
|
677
|
+
self._update_ui()
|
|
678
|
+
elif event.type() in (QEvent.Type.PaletteChange, QEvent.Type.StyleChange):
|
|
679
|
+
self._update_ui()
|
|
680
|
+
|
|
681
|
+
def hideEvent(self, event) -> None:
|
|
682
|
+
super().hideEvent(event)
|
|
683
|
+
if hasattr(self, "_start_timeout"):
|
|
684
|
+
self.stop()
|
|
685
|
+
|
|
686
|
+
def closeEvent(self, event) -> None:
|
|
687
|
+
self._closed = True
|
|
688
|
+
self._cancel_scan()
|
|
689
|
+
self.stop()
|
|
690
|
+
self._poll.stop()
|
|
691
|
+
super().closeEvent(event)
|
|
692
|
+
|
|
693
|
+
def showEvent(self, event) -> None:
|
|
694
|
+
super().showEvent(event)
|
|
695
|
+
if self._closed:
|
|
696
|
+
self._closed = False
|
|
697
|
+
self.refresh_sounds()
|
|
698
|
+
|
|
699
|
+
|
|
700
|
+
if __name__ == "__main__":
|
|
701
|
+
import sys
|
|
702
|
+
|
|
703
|
+
from PySide6.QtWidgets import QApplication
|
|
704
|
+
|
|
705
|
+
app = QApplication(sys.argv)
|
|
706
|
+
sounds = SoundSelectionWidget(bundled_path=sys.argv[1] if len(sys.argv) > 1 else None)
|
|
707
|
+
sounds.value_edited.connect(print)
|
|
708
|
+
sounds.setWindowTitle("Soundauswahl")
|
|
709
|
+
sounds.show()
|
|
710
|
+
sys.exit(app.exec())
|