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,245 @@
|
|
|
1
|
+
"""Elementbaum: Identität, Layoutposition und Datenbindung sind getrennt."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections.abc import Iterable, Iterator
|
|
6
|
+
from dataclasses import dataclass, field
|
|
7
|
+
from fnmatch import fnmatchcase
|
|
8
|
+
from typing import Any
|
|
9
|
+
|
|
10
|
+
from .common import UNSET
|
|
11
|
+
from .conditions import Condition
|
|
12
|
+
from .datatypes import Constraints
|
|
13
|
+
|
|
14
|
+
ROOT_ID = "root"
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
@dataclass(frozen=True)
|
|
18
|
+
class Binding:
|
|
19
|
+
"""Zuordnung zu einem Wert eines Adapters – unabhängig von der Layoutposition."""
|
|
20
|
+
|
|
21
|
+
adapter: str
|
|
22
|
+
key: str
|
|
23
|
+
|
|
24
|
+
def __str__(self) -> str:
|
|
25
|
+
return f"{self.adapter}:{self.key}"
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
@dataclass(frozen=True)
|
|
29
|
+
class ScopeRef:
|
|
30
|
+
"""Berechtigung ``scope`` beim Adapter ``adapter``."""
|
|
31
|
+
|
|
32
|
+
adapter: str
|
|
33
|
+
scope: str
|
|
34
|
+
|
|
35
|
+
def __str__(self) -> str:
|
|
36
|
+
return f"{self.adapter}:{self.scope}"
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
@dataclass(frozen=True)
|
|
40
|
+
class ActionRef:
|
|
41
|
+
"""Adapteraktion oder – ohne Adapter – eine in der Anwendung registrierte Aktion."""
|
|
42
|
+
|
|
43
|
+
adapter: str | None
|
|
44
|
+
name: str
|
|
45
|
+
params: dict[str, Any] = field(default_factory=dict)
|
|
46
|
+
params_from: dict[str, str] = field(default_factory=dict)
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
@dataclass(frozen=True)
|
|
50
|
+
class AuthField:
|
|
51
|
+
name: str
|
|
52
|
+
label: str
|
|
53
|
+
secret: bool = True
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
@dataclass(frozen=True)
|
|
57
|
+
class AuthSpec:
|
|
58
|
+
scope: ScopeRef
|
|
59
|
+
mode: str = "credentials" # credentials | external
|
|
60
|
+
locked_display: str = "disabled" # disabled | hidden | read_only
|
|
61
|
+
fields: tuple[AuthField, ...] = (AuthField("key", "Schlüssel"),)
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
@dataclass(frozen=True)
|
|
65
|
+
class Guard:
|
|
66
|
+
"""Ein einzelner Sperrgrund. Sperren werden vereinigt, nie ersetzt."""
|
|
67
|
+
|
|
68
|
+
kind: str # scope | enabled | read_only
|
|
69
|
+
payload: Any # ScopeRef bzw. Bedingung
|
|
70
|
+
owner: str
|
|
71
|
+
display: str = "disabled"
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
@dataclass(frozen=True)
|
|
75
|
+
class ChoicesSource:
|
|
76
|
+
adapter: str
|
|
77
|
+
list_name: str
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
@dataclass(frozen=True)
|
|
81
|
+
class CatchAll:
|
|
82
|
+
"""Auffanggruppe für Adapterparameter ohne eigene lokale Darstellung."""
|
|
83
|
+
|
|
84
|
+
adapter: str
|
|
85
|
+
include: tuple[str, ...] = ("*",)
|
|
86
|
+
|
|
87
|
+
def matches(self, binding: Binding) -> bool:
|
|
88
|
+
return binding.adapter == self.adapter and any(fnmatchcase(binding.key, p) for p in self.include)
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
@dataclass(eq=False)
|
|
92
|
+
class Element:
|
|
93
|
+
id: str
|
|
94
|
+
name: str
|
|
95
|
+
type: str
|
|
96
|
+
family: str
|
|
97
|
+
label: str = ""
|
|
98
|
+
description: str = ""
|
|
99
|
+
help: str = ""
|
|
100
|
+
order: float | None = None
|
|
101
|
+
visible: Condition = True
|
|
102
|
+
enabled: Condition = True
|
|
103
|
+
read_only: Condition = False
|
|
104
|
+
permission: ScopeRef | None = None
|
|
105
|
+
options: dict[str, Any] = field(default_factory=dict)
|
|
106
|
+
children: list["Element"] = field(default_factory=list)
|
|
107
|
+
parent: "Element | None" = None
|
|
108
|
+
# Einstellung
|
|
109
|
+
datatype: str = ""
|
|
110
|
+
widget: str = ""
|
|
111
|
+
bind: Binding | None = None
|
|
112
|
+
constraints: Constraints = field(default_factory=Constraints)
|
|
113
|
+
default: Any = UNSET
|
|
114
|
+
choices_from: ChoicesSource | None = None
|
|
115
|
+
apply: str = "manual" # manual | immediate | explicit
|
|
116
|
+
effect: str = ""
|
|
117
|
+
actions: dict[str, ActionRef] = field(default_factory=dict)
|
|
118
|
+
# Aktion / Information / Schutz / Auffanggruppe
|
|
119
|
+
action: ActionRef | None = None
|
|
120
|
+
confirm: str = ""
|
|
121
|
+
text: str = ""
|
|
122
|
+
source: dict[str, Any] | None = None
|
|
123
|
+
auth: AuthSpec | None = None
|
|
124
|
+
catch_all: CatchAll | None = None
|
|
125
|
+
# Herkunft und Sperren (vom Baum berechnet)
|
|
126
|
+
origin: str = "base" # base | override | metadata
|
|
127
|
+
note: str = ""
|
|
128
|
+
guards: list[Guard] = field(default_factory=list)
|
|
129
|
+
base_guards: list[Guard] = field(default_factory=list)
|
|
130
|
+
presentation: dict[str, Any] = field(default_factory=dict)
|
|
131
|
+
|
|
132
|
+
@property
|
|
133
|
+
def path(self) -> str:
|
|
134
|
+
parts: list[str] = []
|
|
135
|
+
node: Element | None = self
|
|
136
|
+
while node is not None and node.parent is not None:
|
|
137
|
+
parts.append(node.name)
|
|
138
|
+
node = node.parent
|
|
139
|
+
return "/" + "/".join(reversed(parts))
|
|
140
|
+
|
|
141
|
+
@property
|
|
142
|
+
def title(self) -> str:
|
|
143
|
+
return self.label or self.name
|
|
144
|
+
|
|
145
|
+
@property
|
|
146
|
+
def is_container(self) -> bool:
|
|
147
|
+
return self.family == "container"
|
|
148
|
+
|
|
149
|
+
@property
|
|
150
|
+
def is_setting(self) -> bool:
|
|
151
|
+
return self.family == "setting"
|
|
152
|
+
|
|
153
|
+
def ancestors(self) -> Iterator["Element"]:
|
|
154
|
+
node = self.parent
|
|
155
|
+
while node is not None:
|
|
156
|
+
yield node
|
|
157
|
+
node = node.parent
|
|
158
|
+
|
|
159
|
+
def walk(self) -> Iterator["Element"]:
|
|
160
|
+
yield self
|
|
161
|
+
for child in self.children:
|
|
162
|
+
yield from child.walk()
|
|
163
|
+
|
|
164
|
+
def own_guards(self) -> list[Guard]:
|
|
165
|
+
"""Sperren, die dieses Element für sich und seine Nachfahren setzt."""
|
|
166
|
+
out: list[Guard] = []
|
|
167
|
+
if self.permission is not None:
|
|
168
|
+
out.append(Guard("scope", self.permission, self.id))
|
|
169
|
+
if self.enabled is not True:
|
|
170
|
+
out.append(Guard("enabled", self.enabled, self.id))
|
|
171
|
+
if self.read_only is not False:
|
|
172
|
+
out.append(Guard("read_only", self.read_only, self.id))
|
|
173
|
+
return out
|
|
174
|
+
|
|
175
|
+
def content_guards(self) -> list[Guard]:
|
|
176
|
+
"""Sperre des geschützten Inhalts (gilt nicht für den Authentifizierungsbereich selbst)."""
|
|
177
|
+
if self.type == "protected_group" and self.auth is not None:
|
|
178
|
+
return [Guard("scope", self.auth.scope, self.id, self.auth.locked_display)]
|
|
179
|
+
return []
|
|
180
|
+
|
|
181
|
+
def action_refs(self) -> list[ActionRef]:
|
|
182
|
+
return ([self.action] if self.action else []) + list(self.actions.values())
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
def sort_children(element: Element) -> None:
|
|
186
|
+
"""Stabile Reihenfolge: ``order`` oder, falls nicht angegeben, (Listenindex + 1) · 10."""
|
|
187
|
+
indexed = list(enumerate(element.children))
|
|
188
|
+
indexed.sort(key=lambda pair: (pair[1].order if pair[1].order is not None else (pair[0] + 1) * 10, pair[0]))
|
|
189
|
+
element.children = [child for _, child in indexed]
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
def add_guards(target: list[Guard], extra: Iterable[Guard]) -> None:
|
|
193
|
+
for guard in extra:
|
|
194
|
+
if guard not in target:
|
|
195
|
+
target.append(guard)
|
|
196
|
+
|
|
197
|
+
|
|
198
|
+
class SettingsTree:
|
|
199
|
+
"""Indizierter Elementbaum einer geladenen Definition."""
|
|
200
|
+
|
|
201
|
+
def __init__(self, root: Element, *, title: str, adapters: dict[str, str], default_adapter: str | None,
|
|
202
|
+
presentation: dict[str, Any] | None = None) -> None:
|
|
203
|
+
self.root = root
|
|
204
|
+
self.title = title
|
|
205
|
+
self.adapters = adapters
|
|
206
|
+
self.default_adapter = default_adapter
|
|
207
|
+
self.presentation = {} if presentation is None else presentation
|
|
208
|
+
self.by_id: dict[str, Element] = {}
|
|
209
|
+
self.by_path: dict[str, Element] = {}
|
|
210
|
+
self.by_binding: dict[Binding, list[Element]] = {}
|
|
211
|
+
self.reindex()
|
|
212
|
+
|
|
213
|
+
def reindex(self) -> None:
|
|
214
|
+
self.by_id.clear()
|
|
215
|
+
self.by_path.clear()
|
|
216
|
+
self.by_binding.clear()
|
|
217
|
+
for element in self.root.walk():
|
|
218
|
+
self.by_id[element.id] = element
|
|
219
|
+
self.by_path[element.path] = element
|
|
220
|
+
if element.bind is not None:
|
|
221
|
+
self.by_binding.setdefault(element.bind, []).append(element)
|
|
222
|
+
self.compute_guards()
|
|
223
|
+
|
|
224
|
+
def compute_guards(self) -> None:
|
|
225
|
+
def visit(element: Element, inherited: list[Guard]) -> None:
|
|
226
|
+
guards = list(inherited)
|
|
227
|
+
add_guards(guards, element.own_guards())
|
|
228
|
+
add_guards(guards, element.base_guards)
|
|
229
|
+
element.guards = guards
|
|
230
|
+
below = list(guards)
|
|
231
|
+
add_guards(below, element.content_guards())
|
|
232
|
+
for child in element.children:
|
|
233
|
+
visit(child, below)
|
|
234
|
+
|
|
235
|
+
visit(self.root, [])
|
|
236
|
+
|
|
237
|
+
def walk(self) -> Iterator[Element]:
|
|
238
|
+
return self.root.walk()
|
|
239
|
+
|
|
240
|
+
def find(self, reference: str) -> Element | None:
|
|
241
|
+
"""Sucht über Layoutpfad (``/a/b``) oder Identität."""
|
|
242
|
+
return self.by_path.get(reference) if reference.startswith("/") else self.by_id.get(reference)
|
|
243
|
+
|
|
244
|
+
def settings(self) -> Iterator[Element]:
|
|
245
|
+
return (e for e in self.walk() if e.bind is not None)
|
|
@@ -0,0 +1,353 @@
|
|
|
1
|
+
"""Darstellungs-Overrides: gezielte Operationen auf einer Kopie der Basisdefinition.
|
|
2
|
+
|
|
3
|
+
Ein Override wird vollständig oder gar nicht angewendet. Fachliche Grenzen,
|
|
4
|
+
Bindungen und Berechtigungen der Basis können nur verschärft werden.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import copy
|
|
10
|
+
from typing import Any
|
|
11
|
+
|
|
12
|
+
from . import conditions
|
|
13
|
+
from .datatypes import CONSTRAINT_FIELDS, weakened
|
|
14
|
+
from .diagnostics import Diagnostics
|
|
15
|
+
from .model import Element, Guard, SettingsTree, add_guards
|
|
16
|
+
from .parser import check_header, default_name, parse_document
|
|
17
|
+
from .registry import TypeRegistry
|
|
18
|
+
|
|
19
|
+
OVERRIDE_FORMAT = "dynamic-settings-override"
|
|
20
|
+
|
|
21
|
+
_OPERATIONS: dict[str, tuple[set[str], set[str]]] = {
|
|
22
|
+
# op: (Pflichtfelder, optionale Felder)
|
|
23
|
+
"update": ({"target", "set"}, set()),
|
|
24
|
+
"add": ({"parent", "element"}, {"before", "after", "index"}),
|
|
25
|
+
"move": ({"target"}, {"parent", "before", "after", "index", "name"}),
|
|
26
|
+
"hide": ({"target"}, set()),
|
|
27
|
+
"show": ({"target"}, set()),
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
#: Diese Felder bestimmen Bedeutung, Datenfluss oder Schutz und sind unveränderlich.
|
|
31
|
+
_PROTECTED_FIELDS = {
|
|
32
|
+
"id", "children", "bind", "datatype", "auth", "permission", "action", "actions",
|
|
33
|
+
"catch_all", "choices_from", "source",
|
|
34
|
+
} # fmt: skip
|
|
35
|
+
|
|
36
|
+
#: Fachliche Regeln innerhalb von ``options`` (erlaubte Protokolle, Konfliktprüfung …).
|
|
37
|
+
_PROTECTED_OPTIONS = {
|
|
38
|
+
"schemes", "default_scheme", "endpoints", "allow_path", "conflict_policy",
|
|
39
|
+
"require_modifier", "reserved", "conflicts_from", "revealable",
|
|
40
|
+
}
|
|
41
|
+
#: Pfadprüfung darf per Override nur verschärft werden (none < warn < require).
|
|
42
|
+
_CHECK_RANK = {"none": 0, "warn": 1, "require": 2}
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
class _OverrideError(Exception):
|
|
46
|
+
def __init__(self, code: str, message: str) -> None:
|
|
47
|
+
self.code = code
|
|
48
|
+
super().__init__(message)
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
class _Document:
|
|
52
|
+
"""Arbeitskopie der Rohdefinition mit Adressierung über ID oder Pfad."""
|
|
53
|
+
|
|
54
|
+
def __init__(self, raw: dict[str, Any]) -> None:
|
|
55
|
+
self.raw = copy.deepcopy(raw)
|
|
56
|
+
self.raw["root"].setdefault("id", "root")
|
|
57
|
+
self.index()
|
|
58
|
+
|
|
59
|
+
def index(self) -> None:
|
|
60
|
+
self.parents: dict[str, dict[str, Any] | None] = {}
|
|
61
|
+
self.nodes: dict[str, dict[str, Any]] = {}
|
|
62
|
+
self.paths: dict[str, str] = {}
|
|
63
|
+
|
|
64
|
+
def visit(node: dict[str, Any], parent: dict[str, Any] | None, path: str) -> None:
|
|
65
|
+
self.nodes[node["id"]] = node
|
|
66
|
+
self.parents[node["id"]] = parent
|
|
67
|
+
self.paths[path or "/"] = node["id"]
|
|
68
|
+
for child in node.get("children", []):
|
|
69
|
+
visit(child, node, f"{path}/{child.get('name', default_name(child['id']))}")
|
|
70
|
+
|
|
71
|
+
visit(self.raw["root"], None, "")
|
|
72
|
+
|
|
73
|
+
def resolve(self, reference: Any, what: str) -> dict[str, Any]:
|
|
74
|
+
if not isinstance(reference, str) or not reference:
|
|
75
|
+
raise _OverrideError("reference", f"„{what}“ muss eine ID oder ein Layoutpfad sein")
|
|
76
|
+
element_id = self.paths.get(reference.rstrip("/") or "/") if reference.startswith("/") else reference
|
|
77
|
+
if element_id is None or element_id not in self.nodes:
|
|
78
|
+
raise _OverrideError("reference", f"„{what}“ {reference!r} existiert nicht")
|
|
79
|
+
return self.nodes[element_id]
|
|
80
|
+
|
|
81
|
+
def path_of(self, node: dict[str, Any]) -> str:
|
|
82
|
+
return next(p for p, i in self.paths.items() if i == node["id"])
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def _merge_patch(target: dict[str, Any], patch: dict[str, Any]) -> None:
|
|
86
|
+
"""JSON Merge Patch (RFC 7396): ``null`` entfernt, Objekte werden vertieft zusammengeführt."""
|
|
87
|
+
for key, value in patch.items():
|
|
88
|
+
if value is None:
|
|
89
|
+
target.pop(key, None)
|
|
90
|
+
elif isinstance(value, dict) and key in ("options", "presentation", "by_datatype", "by_widget"):
|
|
91
|
+
if not isinstance(target.get(key), dict):
|
|
92
|
+
target[key] = {}
|
|
93
|
+
_merge_patch(target[key], value)
|
|
94
|
+
else:
|
|
95
|
+
target[key] = copy.deepcopy(value)
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def _materialize_order(parent: dict[str, Any]) -> list[dict[str, Any]]:
|
|
99
|
+
"""Überführt ``order``-Angaben in die Listenreihenfolge (vor gezieltem Einfügen)."""
|
|
100
|
+
children = parent.setdefault("children", [])
|
|
101
|
+
keyed = [(c.get("order") if c.get("order") is not None else (i + 1) * 10, i, c) for i, c in enumerate(children)]
|
|
102
|
+
keyed.sort(key=lambda item: item[:2])
|
|
103
|
+
children[:] = [c for _, _, c in keyed]
|
|
104
|
+
for child in children:
|
|
105
|
+
child.pop("order", None)
|
|
106
|
+
return children
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def _insert(doc: _Document, parent: dict[str, Any], node: dict[str, Any], op: dict[str, Any]) -> None:
|
|
110
|
+
anchors = [k for k in ("before", "after", "index") if k in op]
|
|
111
|
+
if len(anchors) > 1:
|
|
112
|
+
raise _OverrideError("position", "Nur eines von before, after, index ist erlaubt")
|
|
113
|
+
if not anchors:
|
|
114
|
+
parent.setdefault("children", []).append(node)
|
|
115
|
+
return
|
|
116
|
+
children = _materialize_order(parent)
|
|
117
|
+
node.pop("order", None)
|
|
118
|
+
if anchors == ["index"]:
|
|
119
|
+
index = op["index"]
|
|
120
|
+
if not isinstance(index, int) or isinstance(index, bool) or not 0 <= index <= len(children):
|
|
121
|
+
raise _OverrideError("position", f"„index“ muss zwischen 0 und {len(children)} liegen")
|
|
122
|
+
children.insert(index, node)
|
|
123
|
+
return
|
|
124
|
+
anchor = doc.resolve(op[anchors[0]], anchors[0])
|
|
125
|
+
for position, child in enumerate(children):
|
|
126
|
+
if child is anchor:
|
|
127
|
+
children.insert(position + (anchors[0] == "after"), node)
|
|
128
|
+
return
|
|
129
|
+
raise _OverrideError("position", f"„{anchors[0]}“ {op[anchors[0]]!r} liegt nicht im Zielcontainer")
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def _apply(doc: _Document, op: Any, base: SettingsTree) -> None:
|
|
133
|
+
if not isinstance(op, dict) or op.get("op") not in _OPERATIONS:
|
|
134
|
+
name = op.get("op") if isinstance(op, dict) else op
|
|
135
|
+
raise _OverrideError("operation", f"Unbekannte Operation {name!r} (bekannt: {', '.join(_OPERATIONS)})")
|
|
136
|
+
kind = op["op"]
|
|
137
|
+
required, optional = _OPERATIONS[kind]
|
|
138
|
+
fields = {k for k in op if not k.startswith("x-")} - {"op"}
|
|
139
|
+
if missing := required - fields:
|
|
140
|
+
raise _OverrideError("operation", f"„{kind}“ benötigt {', '.join(sorted(missing))}")
|
|
141
|
+
if extra := fields - required - optional:
|
|
142
|
+
raise _OverrideError("operation", f"„{kind}“ kennt die Felder {', '.join(sorted(extra))} nicht")
|
|
143
|
+
|
|
144
|
+
if kind == "add":
|
|
145
|
+
parent = doc.resolve(op["parent"], "parent")
|
|
146
|
+
node = copy.deepcopy(op["element"])
|
|
147
|
+
pending = [node]
|
|
148
|
+
new_ids: set[str] = set()
|
|
149
|
+
while pending:
|
|
150
|
+
item = pending.pop()
|
|
151
|
+
if not isinstance(item, dict) or not isinstance(item.get("id"), str):
|
|
152
|
+
raise _OverrideError("element", "Jedes neue Element benötigt eine „id“")
|
|
153
|
+
if item["id"] in doc.nodes or item["id"] in new_ids:
|
|
154
|
+
raise _OverrideError("duplicate-id", f"Die ID „{item['id']}“ ist bereits vergeben")
|
|
155
|
+
new_ids.add(item["id"])
|
|
156
|
+
children = item.get("children", [])
|
|
157
|
+
if not isinstance(children, list):
|
|
158
|
+
raise _OverrideError("element", "„children“ muss eine Liste sein")
|
|
159
|
+
pending.extend(children)
|
|
160
|
+
_insert(doc, parent, node, op)
|
|
161
|
+
doc.index()
|
|
162
|
+
return
|
|
163
|
+
|
|
164
|
+
node = doc.resolve(op["target"], "target")
|
|
165
|
+
if kind == "update":
|
|
166
|
+
patch = op["set"]
|
|
167
|
+
if not isinstance(patch, dict) or not patch:
|
|
168
|
+
raise _OverrideError("operation", "„set“ muss ein nicht leeres Objekt sein")
|
|
169
|
+
if node["id"] in base.by_id and (locked := _PROTECTED_FIELDS & patch.keys()):
|
|
170
|
+
raise _OverrideError(
|
|
171
|
+
"protected-field",
|
|
172
|
+
f"{', '.join(sorted(locked))} von „{node['id']}“ ist fachlich verbindlich und nicht überschreibbar",
|
|
173
|
+
)
|
|
174
|
+
before = copy.deepcopy(node.get("options", {}))
|
|
175
|
+
_merge_patch(node, patch)
|
|
176
|
+
if node["id"] in base.by_id:
|
|
177
|
+
after = node.get("options", {})
|
|
178
|
+
for name in sorted(_PROTECTED_OPTIONS):
|
|
179
|
+
if isinstance(after, dict) and before.get(name) != after.get(name):
|
|
180
|
+
raise _OverrideError(
|
|
181
|
+
"protected-field", f"Option „{name}“ von „{node['id']}“ ist fachlich verbindlich und nicht überschreibbar"
|
|
182
|
+
)
|
|
183
|
+
if isinstance(after, dict):
|
|
184
|
+
was, now = before.get("check", "none"), after.get("check", "none")
|
|
185
|
+
if isinstance(now, str) and isinstance(was, str) and _CHECK_RANK.get(now, 0) < _CHECK_RANK.get(was, 0):
|
|
186
|
+
raise _OverrideError(
|
|
187
|
+
"protected-field", f"Pfadprüfung „{was}“ von „{node['id']}“ kann nur verschärft werden, nicht zu „{now}“"
|
|
188
|
+
)
|
|
189
|
+
elif kind in ("hide", "show"):
|
|
190
|
+
if kind == "show":
|
|
191
|
+
base_element = base.by_id.get(node["id"])
|
|
192
|
+
if base_element and conditions.mentions_permission(base_element.visible):
|
|
193
|
+
raise _OverrideError("protected-field", "Die Sichtbarkeit hängt in der Basis von einer Berechtigung ab")
|
|
194
|
+
node.pop("visible", None)
|
|
195
|
+
else:
|
|
196
|
+
node["visible"] = False
|
|
197
|
+
elif kind == "move":
|
|
198
|
+
old_parent = doc.parents[node["id"]]
|
|
199
|
+
if old_parent is None:
|
|
200
|
+
raise _OverrideError("hierarchy", "Das Wurzelelement kann nicht verschoben werden")
|
|
201
|
+
parent = doc.resolve(op["parent"], "parent") if "parent" in op else old_parent
|
|
202
|
+
ancestor: dict[str, Any] | None = parent
|
|
203
|
+
while ancestor is not None:
|
|
204
|
+
if ancestor is node:
|
|
205
|
+
raise _OverrideError("hierarchy", "Ein Element kann nicht in sich selbst verschoben werden")
|
|
206
|
+
ancestor = doc.parents[ancestor["id"]]
|
|
207
|
+
old_parent["children"] = [c for c in old_parent["children"] if c is not node]
|
|
208
|
+
if "name" in op:
|
|
209
|
+
node["name"] = op["name"]
|
|
210
|
+
_insert(doc, parent, node, op)
|
|
211
|
+
doc.index()
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
def _check_not_weakened(base: SettingsTree, merged: SettingsTree, registry: TypeRegistry, diag: Diagnostics) -> None:
|
|
215
|
+
err = diag.error
|
|
216
|
+
base_actions: dict[tuple[str | None, str], list[Guard]] = {}
|
|
217
|
+
for element in base.walk():
|
|
218
|
+
for ref in element.action_refs():
|
|
219
|
+
add_guards(base_actions.setdefault((ref.adapter, ref.name), []), element.guards)
|
|
220
|
+
catch_alls = [e for e in base.walk() if e.catch_all]
|
|
221
|
+
|
|
222
|
+
for element in merged.walk():
|
|
223
|
+
origin = base.by_id.get(element.id)
|
|
224
|
+
if origin is None:
|
|
225
|
+
element.origin = "override"
|
|
226
|
+
_inherit_guards(element, base, base_actions, catch_alls)
|
|
227
|
+
_check_new_element(element, base, err)
|
|
228
|
+
continue
|
|
229
|
+
# Alle Sperren der Basisposition gelten weiter, auch nach Verschieben.
|
|
230
|
+
element.base_guards = list(origin.guards)
|
|
231
|
+
if element.type != origin.type:
|
|
232
|
+
both_plain = origin.is_container and element.is_container and "protected_group" not in (origin.type, element.type)
|
|
233
|
+
if not both_plain:
|
|
234
|
+
err("protected-field", f"Typwechsel {origin.type!r} → {element.type!r} ist nicht zulässig", element.path)
|
|
235
|
+
if conditions.mentions_permission(origin.visible) and element.visible not in (origin.visible, False):
|
|
236
|
+
err("protected-field", "Eine an Berechtigungen gebundene Sichtbarkeit ist nicht überschreibbar", element.path)
|
|
237
|
+
if origin.confirm and not element.confirm:
|
|
238
|
+
err("protected-field", "Eine Sicherheitsabfrage („confirm“) darf nicht entfernt werden", element.path)
|
|
239
|
+
if origin.apply != element.apply and "explicit" in (origin.apply, element.apply):
|
|
240
|
+
err("protected-field", "Die Übernahmepolitik „explicit“ ist nicht überschreibbar", element.path)
|
|
241
|
+
for name, neutral in (("enabled", True), ("read_only", False)):
|
|
242
|
+
if getattr(origin, name) != neutral and getattr(origin, name) != getattr(element, name):
|
|
243
|
+
diag.info("base-guard", f"„{name}“ der Basis gilt zusätzlich weiter", element.path)
|
|
244
|
+
if origin.bind is not None and origin.is_setting:
|
|
245
|
+
loosened = weakened(origin.constraints, element.constraints)
|
|
246
|
+
if loosened:
|
|
247
|
+
err(
|
|
248
|
+
"weakened",
|
|
249
|
+
f"Fachliche Grenzen dürfen nur verschärft werden ({', '.join(loosened)})",
|
|
250
|
+
element.path,
|
|
251
|
+
)
|
|
252
|
+
merged.compute_guards()
|
|
253
|
+
|
|
254
|
+
|
|
255
|
+
def _inherit_guards(
|
|
256
|
+
element: Element,
|
|
257
|
+
base: SettingsTree,
|
|
258
|
+
base_actions: dict[tuple[str | None, str], list[Guard]],
|
|
259
|
+
catch_alls: list[Element],
|
|
260
|
+
) -> None:
|
|
261
|
+
"""Neue Elemente erben alle Sperren, die die Basis für Bindung bzw. Aktion festlegt."""
|
|
262
|
+
if element.bind is not None:
|
|
263
|
+
owners = base.by_binding.get(element.bind)
|
|
264
|
+
if owners:
|
|
265
|
+
for owner in owners:
|
|
266
|
+
add_guards(element.base_guards, owner.guards)
|
|
267
|
+
else:
|
|
268
|
+
for container in catch_alls:
|
|
269
|
+
if container.catch_all.matches(element.bind):
|
|
270
|
+
add_guards(element.base_guards, container.guards)
|
|
271
|
+
add_guards(element.base_guards, container.content_guards())
|
|
272
|
+
for ref in element.action_refs():
|
|
273
|
+
add_guards(element.base_guards, base_actions.get((ref.adapter, ref.name), []))
|
|
274
|
+
|
|
275
|
+
|
|
276
|
+
def _check_new_element(element: Element, base: SettingsTree, err: Any) -> None:
|
|
277
|
+
if element.catch_all and any(e.catch_all and e.catch_all.adapter == element.catch_all.adapter for e in base.walk()):
|
|
278
|
+
err("protected-field", "Für diesen Adapter legt die Basis bereits eine Auffanggruppe fest", element.path)
|
|
279
|
+
if not element.is_setting or element.bind is None:
|
|
280
|
+
return
|
|
281
|
+
for owner in base.by_binding.get(element.bind, []):
|
|
282
|
+
if not owner.is_setting:
|
|
283
|
+
continue
|
|
284
|
+
loosened = weakened(owner.constraints, element.constraints)
|
|
285
|
+
if loosened:
|
|
286
|
+
err(
|
|
287
|
+
"weakened",
|
|
288
|
+
f"Weitere Darstellung von {element.bind} darf die Grenzen von „{owner.id}“ nicht lockern "
|
|
289
|
+
f"({', '.join(loosened)})",
|
|
290
|
+
element.path,
|
|
291
|
+
)
|
|
292
|
+
|
|
293
|
+
|
|
294
|
+
def _inherit_constraints(doc: _Document, base: SettingsTree) -> None:
|
|
295
|
+
"""Fehlende Grenzen neuer Darstellungen werden aus der Basis ergänzt."""
|
|
296
|
+
raw_by_id = {}
|
|
297
|
+
|
|
298
|
+
def visit(node: dict[str, Any]) -> None:
|
|
299
|
+
raw_by_id[node["id"]] = node
|
|
300
|
+
for child in node.get("children", []):
|
|
301
|
+
visit(child)
|
|
302
|
+
|
|
303
|
+
visit(doc.raw["root"])
|
|
304
|
+
base_raw_by_binding: dict[Any, dict[str, Any]] = {}
|
|
305
|
+
for binding, owners in base.by_binding.items():
|
|
306
|
+
for owner in owners:
|
|
307
|
+
if owner.is_setting and owner.id in raw_by_id:
|
|
308
|
+
base_raw_by_binding.setdefault((binding.adapter, binding.key), raw_by_id[owner.id])
|
|
309
|
+
for node_id, node in raw_by_id.items():
|
|
310
|
+
if node_id in base.by_id or node.get("type") != "setting":
|
|
311
|
+
continue
|
|
312
|
+
bind = node.get("bind")
|
|
313
|
+
if isinstance(bind, str):
|
|
314
|
+
bind = {"key": bind}
|
|
315
|
+
if not isinstance(bind, dict):
|
|
316
|
+
continue
|
|
317
|
+
owner_raw = base_raw_by_binding.get((bind.get("adapter", base.default_adapter), bind.get("key")))
|
|
318
|
+
if owner_raw is None:
|
|
319
|
+
continue
|
|
320
|
+
inherit = (CONSTRAINT_FIELDS | {"choices_from", "effect"}) - {"optional"}
|
|
321
|
+
for name in inherit & owner_raw.keys():
|
|
322
|
+
node.setdefault(name, copy.deepcopy(owner_raw[name]))
|
|
323
|
+
if "optional" in owner_raw:
|
|
324
|
+
node.setdefault("optional", owner_raw["optional"])
|
|
325
|
+
|
|
326
|
+
|
|
327
|
+
def apply_override(
|
|
328
|
+
base_raw: dict[str, Any], override: Any, base: SettingsTree, registry: TypeRegistry, source: str
|
|
329
|
+
) -> tuple[dict[str, Any], SettingsTree, Diagnostics]:
|
|
330
|
+
"""Wendet einen Override an; wirft bei jedem Fehler, ohne etwas zu verändern."""
|
|
331
|
+
diag = Diagnostics(source)
|
|
332
|
+
if not check_header(override, OVERRIDE_FORMAT, diag):
|
|
333
|
+
diag.raise_if_errors()
|
|
334
|
+
for key in override.keys() - {"$schema", "format", "version", "description", "operations"}:
|
|
335
|
+
if not key.startswith("x-"):
|
|
336
|
+
diag.error("unknown-field", f"Unbekanntes Feld „{key}“ im Override")
|
|
337
|
+
operations = override.get("operations")
|
|
338
|
+
if not isinstance(operations, list):
|
|
339
|
+
diag.error("operations", "„operations“ muss eine Liste sein")
|
|
340
|
+
diag.raise_if_errors()
|
|
341
|
+
doc = _Document(base_raw)
|
|
342
|
+
for number, op in enumerate(operations, start=1):
|
|
343
|
+
try:
|
|
344
|
+
_apply(doc, op, base)
|
|
345
|
+
except _OverrideError as exc:
|
|
346
|
+
diag.error(exc.code, str(exc), f"Operation {number}")
|
|
347
|
+
diag.raise_if_errors()
|
|
348
|
+
_inherit_constraints(doc, base)
|
|
349
|
+
merged, parsed = parse_document(doc.raw, registry, source)
|
|
350
|
+
diag.items.extend(i for i in parsed.items if i not in diag.items)
|
|
351
|
+
_check_not_weakened(base, merged, registry, diag)
|
|
352
|
+
diag.raise_if_errors()
|
|
353
|
+
return doc.raw, merged, diag
|