led-controller-version-3-effect-creation 3.0.2__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.
@@ -0,0 +1,196 @@
1
+ """Writing what the studio produced back into a source tree.
2
+
3
+ The studio plays *built* packages — that is what the engine loads — but a preset
4
+ worth keeping belongs in the source the package was built from, or it survives
5
+ only until the next build. So the one thing this has to do is find its way back:
6
+ from an effect id in a loaded catalogue to the directory its source lives in.
7
+
8
+ That link is not recorded anywhere, because nothing in the running system needs
9
+ it. It is recovered by looking: a source directory is named after the definition
10
+ it contains, and the catalogue tests enforce that. Where the search finds
11
+ nothing, the studio asks rather than guesses.
12
+
13
+ No Qt here. Deciding what to write and writing it are separable from the dialog
14
+ that collects it, and only the dialog needs a toolkit.
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ import re
20
+ from dataclasses import dataclass
21
+ from pathlib import Path
22
+ from typing import Any, Iterable, Mapping
23
+
24
+ import yaml
25
+
26
+ from lefx.effect_creation import SourceError, load_effect_source, validate_effect_source
27
+ from lefx.sdk import DefinitionBase, resolve_configuration
28
+
29
+ DEFAULT_SOURCE_ROOTS = ("effects",)
30
+ """Only a fallback. The studio passes the project's own roots, because a
31
+ standalone build has no useful working directory to be relative to."""
32
+ PRESET_FILE = "presets.yaml"
33
+
34
+ _SLUG = re.compile(r"[^a-z0-9]+")
35
+
36
+
37
+ def slugify(text: str) -> str:
38
+ return _SLUG.sub("_", text.strip().casefold()).strip("_")
39
+
40
+
41
+ def suggest_preset_id(effect_id: str, label: str) -> str:
42
+ """A preset id derived from a human label.
43
+
44
+ Prefixed with the definition's id because presets share one namespace with
45
+ every other source's, and a preset called ``warm`` would be a collision
46
+ waiting for the second catalogue that has one.
47
+ """
48
+ slug = slugify(label)
49
+ if not slug:
50
+ return effect_id
51
+ return slug if slug.startswith(f"{effect_id}_") or slug == effect_id else f"{effect_id}_{slug}"
52
+
53
+
54
+ def find_source_dir(
55
+ effect_id: str, roots: Iterable[str | Path] = DEFAULT_SOURCE_ROOTS
56
+ ) -> Path | None:
57
+ """Where the source for this definition lives, if it can be found.
58
+
59
+ Matched on the directory name and then confirmed by loading the manifest, so
60
+ a directory that merely happens to share a name is not mistaken for it.
61
+ """
62
+ for root in roots:
63
+ base = Path(root).expanduser()
64
+ if not base.is_dir():
65
+ continue
66
+ for candidate in sorted(base.rglob(f"sources/**/{effect_id}")):
67
+ if not candidate.is_dir():
68
+ continue
69
+ try:
70
+ load_effect_source(candidate)
71
+ except SourceError:
72
+ continue
73
+ return candidate
74
+ return None
75
+
76
+
77
+ @dataclass(slots=True, frozen=True)
78
+ class PresetDraft:
79
+ """A preset as the studio has it, before it is written anywhere."""
80
+
81
+ effect_id: str
82
+ preset_id: str
83
+ title: str
84
+ description: str
85
+ params: Mapping[str, Any]
86
+
87
+ def to_entry(self) -> dict[str, Any]:
88
+ entry: dict[str, Any] = {"params": dict(self.params)}
89
+ if self.title:
90
+ entry["title"] = self.title
91
+ if self.description:
92
+ entry["description"] = self.description
93
+ return entry
94
+
95
+
96
+ def check_draft(definition: DefinitionBase, draft: PresetDraft) -> list[str]:
97
+ """Everything wrong with a draft, in the words a person can act on.
98
+
99
+ Checked here rather than left to the build, because the build happens later
100
+ and somewhere else. The rules are the ones the source validator applies —
101
+ stated twice, but the second statement is the one that catches it while the
102
+ values are still on screen.
103
+ """
104
+ problems: list[str] = []
105
+ if not draft.preset_id:
106
+ problems.append("Ein Preset braucht eine Kennung.")
107
+ elif not draft.preset_id.startswith(definition.id):
108
+ problems.append(
109
+ f"Die Kennung muss mit {definition.id!r} beginnen — Presets teilen sich "
110
+ "einen Namensraum über alle Quellen hinweg."
111
+ )
112
+ elif draft.preset_id != slugify(draft.preset_id):
113
+ problems.append("Nur Kleinbuchstaben, Ziffern und Unterstriche.")
114
+
115
+ try:
116
+ resolve_configuration(definition, preset=dict(draft.params))
117
+ except Exception as exc:
118
+ problems.append(f"Die Werte passen nicht zum Schema: {exc}")
119
+ return problems
120
+
121
+
122
+ def read_presets(source_dir: str | Path) -> dict[str, Any]:
123
+ return load_effect_source(source_dir).presets()
124
+
125
+
126
+ def write_preset(source_dir: str | Path, draft: PresetDraft, *, overwrite: bool = False) -> Path:
127
+ """Merge one preset into a source's ``presets.yaml``, leaving the rest alone.
128
+
129
+ Rewritten wholesale from the parsed content rather than appended to, so the
130
+ file stays a valid document whatever it looked like before. What that costs
131
+ is comment formatting in a file nobody hand-edits often; what it buys is
132
+ that a half-written append can never produce one that will not load.
133
+ """
134
+ root = Path(source_dir).expanduser().resolve()
135
+ source = load_effect_source(root)
136
+ existing = source.presets()
137
+
138
+ if draft.preset_id in existing and not overwrite:
139
+ raise SourceError(f"{draft.preset_id!r} already exists in {root}")
140
+
141
+ existing[draft.preset_id] = draft.to_entry()
142
+ target = source.presets_path or (root / PRESET_FILE)
143
+ target.write_text(
144
+ yaml.safe_dump({"presets": dict(sorted(existing.items()))}, allow_unicode=True,
145
+ sort_keys=False, default_flow_style=False),
146
+ encoding="utf-8",
147
+ )
148
+ return target
149
+
150
+
151
+ def write_preset_checked(
152
+ definition: DefinitionBase,
153
+ source_dir: str | Path,
154
+ draft: PresetDraft,
155
+ *,
156
+ overwrite: bool = False,
157
+ ) -> Path:
158
+ """Write it, then hold the whole source to the validator it will face later.
159
+
160
+ A source that stops validating is worse than a preset that was never
161
+ written, so if the result does not pass, the file goes back the way it was.
162
+ """
163
+ root = Path(source_dir).expanduser().resolve()
164
+ source = load_effect_source(root)
165
+ target = source.presets_path or (root / PRESET_FILE)
166
+ before = target.read_text(encoding="utf-8") if target.is_file() else None
167
+
168
+ problems = check_draft(definition, draft)
169
+ if problems:
170
+ raise SourceError("; ".join(problems))
171
+
172
+ write_preset(root, draft, overwrite=overwrite)
173
+ report = validate_effect_source(root)
174
+ if not report.ok:
175
+ if before is None:
176
+ target.unlink(missing_ok=True)
177
+ else:
178
+ target.write_text(before, encoding="utf-8")
179
+ raise SourceError(
180
+ f"{root.name} would no longer validate: " + "; ".join(report.errors)
181
+ )
182
+ return target
183
+
184
+
185
+ __all__ = [
186
+ "DEFAULT_SOURCE_ROOTS",
187
+ "PRESET_FILE",
188
+ "PresetDraft",
189
+ "check_draft",
190
+ "find_source_dir",
191
+ "read_presets",
192
+ "slugify",
193
+ "suggest_preset_id",
194
+ "write_preset",
195
+ "write_preset_checked",
196
+ ]