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,759 @@
1
+ """An effect being designed, before it is a file.
2
+
3
+ The whole idea here is one move: **build the real definition first, emit the
4
+ source afterwards**. A blueprint is turned into an actual ``StateDefinition`` or
5
+ ``EventDefinition`` — which validates itself in ``__post_init__`` — and only a
6
+ definition that survived that is ever written to disk. So the editor cannot
7
+ produce an ``effect.py`` the schema rejects, not because it checks carefully but
8
+ because the thing it prints was already constructed.
9
+
10
+ That inverts the usual arrangement, where a generator writes text and a
11
+ validator complains about it later, in another process, after a build.
12
+
13
+ What is *not* generated is the body of ``render``. That is the part with the
14
+ idea in it, and it is typed by a person; the editor imports the module to run
15
+ it, which is also how it finds out whether it works.
16
+
17
+ No Qt: this decides what a source says, and the page collects it.
18
+ """
19
+
20
+ from __future__ import annotations
21
+
22
+ import keyword
23
+ import re
24
+ from dataclasses import dataclass, field, replace
25
+ from pathlib import Path
26
+ from typing import Any, Mapping
27
+
28
+ from lefx.effect_creation import SourceError, pack_effect, smoke_render, validate_effect_source
29
+ from lefx.sdk import (
30
+ MISSING,
31
+ RESERVED_PARAMETERS,
32
+ ColorModel,
33
+ CompositionMode,
34
+ ControlledOverlayDefinition,
35
+ DefinitionBase,
36
+ DefinitionKind,
37
+ DurationField,
38
+ EventDefinition,
39
+ InputMode,
40
+ InputSamplingPolicy,
41
+ ParamDefinition,
42
+ ParamType,
43
+ SchemaError,
44
+ StateDefinition,
45
+ StateSlot,
46
+ TimedOverlayDefinition,
47
+ )
48
+
49
+ DEFINITION_CLASSES: Mapping[DefinitionKind, type[DefinitionBase]] = {
50
+ DefinitionKind.STATE: StateDefinition,
51
+ DefinitionKind.CONTROLLED_OVERLAY: ControlledOverlayDefinition,
52
+ DefinitionKind.TIMED_OVERLAY: TimedOverlayDefinition,
53
+ DefinitionKind.EVENT: EventDefinition,
54
+ }
55
+ """One class per lifecycle form. A test asserts this covers every kind, so a
56
+ form added to the SDK cannot quietly become one the editor cannot produce."""
57
+
58
+ MANIFEST_NAME = "effect.yaml"
59
+ SOURCE_NAME = "effect.py"
60
+
61
+
62
+ # -- what each parameter type accepts ---------------------------------------
63
+
64
+
65
+ @dataclass(slots=True, frozen=True)
66
+ class TypeSupport:
67
+ """Which companion fields a type accepts, so the form can grey out the rest.
68
+
69
+ A restatement of the SDK's own matrix, kept here because a form has to know
70
+ it *before* a value is entered rather than after it is rejected.
71
+ ``tests/studio/test_blueprint.py`` probes the SDK for every row, so the two
72
+ cannot drift apart without a failure.
73
+ """
74
+
75
+ bounds: bool = False
76
+ integral_bounds: bool = False
77
+ enum_values: bool = False
78
+ units: tuple[str, ...] = ()
79
+
80
+ @property
81
+ def unit_allowed(self) -> bool:
82
+ return bool(self.units)
83
+
84
+
85
+ TYPE_SUPPORT: Mapping[ParamType, TypeSupport] = {
86
+ ParamType.BOOL: TypeSupport(),
87
+ ParamType.INT: TypeSupport(
88
+ bounds=True, integral_bounds=True,
89
+ units=("ms", "deg", "px", "count", "index", "ratio", "multiplier", "percent"),
90
+ ),
91
+ ParamType.FLOAT: TypeSupport(
92
+ bounds=True,
93
+ units=("ms", "deg", "px", "count", "ratio", "multiplier", "percent", "hz"),
94
+ ),
95
+ ParamType.DURATION_MS: TypeSupport(bounds=True, integral_bounds=True, units=("ms",)),
96
+ ParamType.ANGLE_DEG: TypeSupport(units=("deg",)),
97
+ ParamType.ENUM: TypeSupport(enum_values=True),
98
+ ParamType.COLOR: TypeSupport(),
99
+ ParamType.COLOR_LIST: TypeSupport(bounds=True, integral_bounds=True, units=("count",)),
100
+ ParamType.GRADIENT: TypeSupport(),
101
+ ParamType.COLOR_RANGE: TypeSupport(),
102
+ }
103
+
104
+ # Ranges the *editor's* own number boxes offer. Wide enough that nothing
105
+ # reasonable is out of reach, narrow enough that a slip of the finger does not
106
+ # produce a duration of four hours. These bound the form, never the schema.
107
+ BOUND_LIMIT = 1_000_000.0
108
+ DURATION_LIMIT_MS = 600_000
109
+ """Ten minutes. Longer than any effect in the catalogue by two orders of
110
+ magnitude, and short enough that a stray digit is visible as one."""
111
+
112
+ COLOR_LIST_LIMIT = 64
113
+ PRIORITY_LIMIT = 1_000
114
+ VERSION_LIMIT = 999
115
+
116
+ DEFAULT_COLOR = "#3399FF"
117
+
118
+
119
+ def default_for(kind: ParamType) -> Any:
120
+ """A value of the right shape to start an editor from."""
121
+ return {
122
+ ParamType.BOOL: False,
123
+ ParamType.INT: 0,
124
+ ParamType.FLOAT: 0.0,
125
+ ParamType.DURATION_MS: 1000,
126
+ ParamType.ANGLE_DEG: 0.0,
127
+ ParamType.ENUM: "first",
128
+ ParamType.COLOR: DEFAULT_COLOR,
129
+ ParamType.COLOR_LIST: [DEFAULT_COLOR, "#FF9F1A"],
130
+ ParamType.GRADIENT: [{"at": 0.0, "color": "#000000"}, {"at": 1.0, "color": DEFAULT_COLOR}],
131
+ ParamType.COLOR_RANGE: {
132
+ "hue": [0.0, 360.0], "saturation": [0.4, 1.0], "brightness": [0.4, 1.0],
133
+ },
134
+ }[kind]
135
+
136
+
137
+ # -- a single parameter -----------------------------------------------------
138
+
139
+
140
+ @dataclass(slots=True)
141
+ class ParameterBlueprint:
142
+ """One field of a configuration or runtime input schema, as being edited."""
143
+
144
+ name: str = ""
145
+ type: ParamType = ParamType.FLOAT
146
+ default: Any = None
147
+ description: str = ""
148
+ minimum: float | None = None
149
+ maximum: float | None = None
150
+ unit: str | None = None
151
+ enum_values: tuple[str, ...] = ()
152
+ aliases: tuple[str, ...] = ()
153
+ nullable: bool = False
154
+ required: bool = False
155
+
156
+ @property
157
+ def support(self) -> TypeSupport:
158
+ return TYPE_SUPPORT[self.type]
159
+
160
+ @property
161
+ def reserved(self) -> bool:
162
+ return self.name in RESERVED_PARAMETERS
163
+
164
+ def build(self) -> ParamDefinition:
165
+ """The real thing, which refuses to exist if it is wrong."""
166
+ support = self.support
167
+ return ParamDefinition(
168
+ name=self.name,
169
+ type=self.type,
170
+ default=MISSING if self.required else self.default,
171
+ required=self.required,
172
+ description=self.description,
173
+ minimum=self.minimum if support.bounds else None,
174
+ maximum=self.maximum if support.bounds else None,
175
+ unit=self.unit if support.unit_allowed else None,
176
+ enum_values=self.enum_values if support.enum_values else (),
177
+ aliases=self.aliases,
178
+ nullable=self.nullable,
179
+ )
180
+
181
+ def problem(self) -> str | None:
182
+ """Why this parameter cannot be built, in one sentence, or ``None``."""
183
+ if not self.name:
184
+ return "Ein Parameter braucht einen Namen."
185
+ if not _is_identifier(self.name):
186
+ return f"{self.name!r}: nur Kleinbuchstaben, Ziffern und Unterstriche, kein führender."
187
+ try:
188
+ self.build()
189
+ except (SchemaError, ValueError, TypeError) as exc:
190
+ return f"{self.name}: {exc}"
191
+ return None
192
+
193
+ def code(self) -> str:
194
+ """The parameter as it appears in the generated source."""
195
+ parts = [f'name="{self.name}"', f"type=ParamType.{self.type.name}"]
196
+ if self.required:
197
+ parts.append("required=True")
198
+ else:
199
+ parts.append(f"default={_literal(self.default)}")
200
+ support = self.support
201
+ if support.bounds and self.minimum is not None:
202
+ parts.append(f"minimum={_number(self.minimum, support.integral_bounds)}")
203
+ if support.bounds and self.maximum is not None:
204
+ parts.append(f"maximum={_number(self.maximum, support.integral_bounds)}")
205
+ if support.enum_values and self.enum_values:
206
+ parts.append(f"enum_values={_literal(tuple(self.enum_values))}")
207
+ if support.unit_allowed and self.unit:
208
+ parts.append(f'unit="{self.unit}"')
209
+ if self.nullable:
210
+ parts.append("nullable=True")
211
+ if self.aliases:
212
+ parts.append(f"aliases={_literal(tuple(self.aliases))}")
213
+ if self.description:
214
+ parts.append(f"description={_literal(self.description)}")
215
+ body = ",\n ".join(parts)
216
+ return f'"{self.name}": ParamDefinition(\n {body},\n )'
217
+
218
+
219
+ def reserved_blueprint(name: str) -> ParameterBlueprint:
220
+ """A reserved parameter, pre-filled the only way it is allowed to look.
221
+
222
+ ``brightness`` is a float from zero to one everywhere in the system; there
223
+ is nothing to decide about it, so the editor does not ask.
224
+ """
225
+ rule = RESERVED_PARAMETERS[name]
226
+ blueprint = ParameterBlueprint(name=name, type=rule.type, default=default_for(rule.type))
227
+ if rule.exact_minimum is not None:
228
+ blueprint.minimum = rule.exact_minimum
229
+ if rule.exact_maximum is not None:
230
+ blueprint.maximum = rule.exact_maximum
231
+ if rule.minimum_at_least is not None:
232
+ blueprint.minimum = float(rule.minimum_at_least)
233
+ if rule.minimum_above_zero:
234
+ blueprint.minimum = 0.1
235
+ blueprint.maximum = 8.0
236
+ if name == "secondary_color":
237
+ # A contrasting default, so a two-colour definition looks like one the
238
+ # first time it renders rather than like a single-colour one.
239
+ blueprint.default = "#FF9F1A"
240
+ blueprint.description = "Zweite Farbe."
241
+ elif name == "background_color":
242
+ blueprint.default = "#000000"
243
+ blueprint.description = "Hintergrundfarbe."
244
+ elif name == "brightness":
245
+ blueprint.default = 1.0
246
+ blueprint.description = "Helligkeitsfaktor."
247
+ elif name == "speed":
248
+ blueprint.default = 1.0
249
+ blueprint.description = "Geschwindigkeit."
250
+ elif name == "reverse":
251
+ blueprint.default = False
252
+ blueprint.description = "Richtung umkehren."
253
+ elif name in ("duration_ms", "total_ms"):
254
+ blueprint.default = 1000
255
+ blueprint.maximum = float(DURATION_LIMIT_MS)
256
+ blueprint.description = "Laufzeit."
257
+ elif name == "progress":
258
+ blueprint.default = 0.0
259
+ blueprint.description = "Fortschritt in Prozent."
260
+ return blueprint
261
+
262
+
263
+ # -- the effect -------------------------------------------------------------
264
+
265
+
266
+ @dataclass(slots=True)
267
+ class EffectBlueprint:
268
+ """Everything a source directory needs, before it is one."""
269
+
270
+ kind: DefinitionKind = DefinitionKind.STATE
271
+ effect_id: str = ""
272
+ title: str = ""
273
+ description: str = ""
274
+ source_id: str = "my-set"
275
+ color_model: ColorModel = ColorModel.MONO
276
+ composition: CompositionMode = CompositionMode.OPAQUE
277
+ animated: bool = False
278
+ directional: bool = False
279
+ tags: tuple[str, ...] = ()
280
+ version: int = 1
281
+
282
+ parameters: list[ParameterBlueprint] = field(default_factory=list)
283
+ runtime_inputs: list[ParameterBlueprint] = field(default_factory=list)
284
+
285
+ slots: tuple[StateSlot, ...] = (StateSlot.PRIMARY,)
286
+ restorable: bool = False
287
+
288
+ duration_field: DurationField = DurationField.DURATION_MS
289
+ supports_duration_override: bool = False
290
+ default_priority: int | None = None
291
+
292
+ sampling_mode: InputMode = InputMode.PUSH
293
+ provider_id: str | None = None
294
+ interval_ms: int = 0
295
+
296
+ render_body: str = ""
297
+
298
+ # -- identity -----------------------------------------------------------
299
+
300
+ @property
301
+ def class_name(self) -> str:
302
+ return "".join(part.capitalize() for part in self.effect_id.split("_")) or "Effect"
303
+
304
+ @property
305
+ def folder(self) -> str:
306
+ """States, overlays and events live in their own folders in a set."""
307
+ return {
308
+ DefinitionKind.STATE: "states",
309
+ DefinitionKind.CONTROLLED_OVERLAY: "overlays",
310
+ DefinitionKind.TIMED_OVERLAY: "overlays",
311
+ DefinitionKind.EVENT: "events",
312
+ }[self.kind]
313
+
314
+ @property
315
+ def finite(self) -> bool:
316
+ return self.kind in (DefinitionKind.TIMED_OVERLAY, DefinitionKind.EVENT)
317
+
318
+ # -- what the schema demands -------------------------------------------
319
+
320
+ def required_parameters(self) -> list[str]:
321
+ """Config fields this combination of choices makes mandatory.
322
+
323
+ Derived from the same rules the definition enforces, so the editor can
324
+ offer to add them instead of waiting for the constructor to complain.
325
+ """
326
+ needed: list[str] = []
327
+ model_fields = {
328
+ ColorModel.NONE: [],
329
+ ColorModel.MONO: ["color"],
330
+ ColorModel.DUAL: ["color", "secondary_color"],
331
+ ColorModel.PALETTE: ["colors"],
332
+ ColorModel.GRADIENT: ["gradient"],
333
+ ColorModel.RANDOM_RANGE: ["color_range", "random_seed"],
334
+ }[self.color_model]
335
+ needed.extend(model_fields)
336
+ if self.color_model is not ColorModel.NONE:
337
+ needed.append("brightness")
338
+ if self.animated:
339
+ needed.append("speed")
340
+ if self.directional:
341
+ needed.append("reverse")
342
+ if self.finite:
343
+ needed.append(self.duration_field.value)
344
+ return [name for name in needed if name not in {p.name for p in self.parameters}]
345
+
346
+ def forbidden_parameters(self) -> list[str]:
347
+ """Fields present that this combination of choices does not allow."""
348
+ names = {p.name for p in self.parameters}
349
+ wrong: list[str] = []
350
+ if self.color_model is ColorModel.NONE:
351
+ wrong.extend(sorted(names & {"color", "secondary_color", "colors", "gradient",
352
+ "color_range", "random_seed", "brightness"}))
353
+ if not self.animated and "speed" in names:
354
+ wrong.append("speed")
355
+ if not self.directional and "reverse" in names:
356
+ wrong.append("reverse")
357
+ if self.kind is DefinitionKind.STATE:
358
+ wrong.extend(sorted(names & {"duration_ms", "total_ms"}))
359
+ if self.finite:
360
+ other = "total_ms" if self.duration_field is DurationField.DURATION_MS else "duration_ms"
361
+ if other in names:
362
+ wrong.append(other)
363
+ return wrong
364
+
365
+ def add_missing_parameters(self) -> list[str]:
366
+ """Fill in what the schema demands, correctly typed. Returns what it added."""
367
+ added = self.required_parameters()
368
+ for name in added:
369
+ self.parameters.append(reserved_blueprint(name))
370
+ return added
371
+
372
+ # -- becoming real ------------------------------------------------------
373
+
374
+ def definition(self) -> DefinitionBase:
375
+ """Construct the actual definition. Raises if anything is wrong."""
376
+ common: dict[str, Any] = {
377
+ "id": self.effect_id,
378
+ "title": self.title,
379
+ "description": self.description,
380
+ "parameter_schema": {p.name: p.build() for p in self.parameters},
381
+ "color_model": self.color_model,
382
+ "composition": self.composition,
383
+ "animated": self.animated,
384
+ "directional": self.directional,
385
+ "tags": tuple(self.tags),
386
+ "version": self.version,
387
+ }
388
+ if self.kind is DefinitionKind.STATE:
389
+ common.update(slots=tuple(self.slots), restorable=self.restorable)
390
+ elif self.kind is DefinitionKind.CONTROLLED_OVERLAY:
391
+ common.update(
392
+ runtime_inputs={p.name: p.build() for p in self.runtime_inputs},
393
+ sampling=InputSamplingPolicy(
394
+ mode=self.sampling_mode,
395
+ provider_id=self.provider_id if self.sampling_mode is InputMode.PULL else None,
396
+ interval_ms=self.interval_ms,
397
+ ),
398
+ )
399
+ else:
400
+ common.update(
401
+ duration_field=self.duration_field,
402
+ supports_duration_override=self.supports_duration_override,
403
+ )
404
+ if self.kind is DefinitionKind.EVENT:
405
+ common.update(default_priority=self.default_priority)
406
+ return DEFINITION_CLASSES[self.kind](**common)
407
+
408
+ def problems(self) -> list[str]:
409
+ """Everything standing between this blueprint and a valid source."""
410
+ found: list[str] = []
411
+ if not self.effect_id:
412
+ found.append("Die Definition braucht eine Id.")
413
+ elif not _is_identifier(self.effect_id):
414
+ found.append(
415
+ f"Id {self.effect_id!r}: nur Kleinbuchstaben, Ziffern und Unterstriche."
416
+ )
417
+ if not self.title.strip():
418
+ found.append("Die Definition braucht einen Titel.")
419
+ if not self.description.strip():
420
+ found.append("Die Definition braucht eine Beschreibung.")
421
+ if not _is_source_id(self.source_id):
422
+ found.append("Die Set-Kennung darf nur Buchstaben, Ziffern und Bindestriche enthalten.")
423
+
424
+ seen: set[str] = set()
425
+ for parameter in [*self.parameters, *self.runtime_inputs]:
426
+ problem = parameter.problem()
427
+ if problem:
428
+ found.append(problem)
429
+ if parameter.name in seen:
430
+ found.append(f"{parameter.name!r} ist doppelt deklariert.")
431
+ seen.add(parameter.name)
432
+
433
+ if not self.render_body.strip():
434
+ found.append("render() hat noch keinen Rumpf.")
435
+
436
+ if not found:
437
+ # Only now: the constructor sees combinations no single field can.
438
+ try:
439
+ self.definition()
440
+ except (SchemaError, ValueError, TypeError) as exc:
441
+ found.append(str(exc))
442
+
443
+ if not found:
444
+ problem = self.render_problem()
445
+ if problem is not None:
446
+ found.append(problem)
447
+ return found
448
+
449
+ def render_problem(self) -> str | None:
450
+ """Whether the body actually runs, asked the way the validator asks it.
451
+
452
+ Without this, a definition whose ``render`` throws would be perfectly
453
+ "valid" right up to the moment it is written — and then be refused by
454
+ the source validator, after the dialog had closed over it. The same
455
+ smoke render happens here instead, while the body is still on screen.
456
+
457
+ It renders at three ring sizes because that is what the validator does,
458
+ and a body that only works at twelve is a bug worth finding now.
459
+ """
460
+ try:
461
+ effect_class = compile_blueprint(self)
462
+ except SyntaxError as exc:
463
+ return f"render() ist kein gültiges Python: Zeile {exc.lineno}: {exc.msg}"
464
+ except Exception as exc:
465
+ return f"Die Definition lässt sich nicht laden: {exc}"
466
+
467
+ try:
468
+ smoke_render(effect_class)
469
+ except Exception as exc:
470
+ return str(exc)
471
+ return None
472
+
473
+ @property
474
+ def valid(self) -> bool:
475
+ return not self.problems()
476
+
477
+ # -- becoming a file ----------------------------------------------------
478
+
479
+ def source_code(self) -> str:
480
+ """The ``effect.py`` text. Only reachable once the definition is real."""
481
+ definition = self.definition() # never emit what would not construct
482
+ del definition
483
+
484
+ imports = self._imports()
485
+ lines = [
486
+ "from lefx.sdk import (",
487
+ *(f" {name}," for name in imports),
488
+ ")",
489
+ "",
490
+ "",
491
+ f"class {self.class_name}(BaseEffect):",
492
+ f' """{self.title}',
493
+ "",
494
+ *(f" {line}" for line in _wrap(self.description)),
495
+ ' """',
496
+ "",
497
+ f" definition = {type(self.definition()).__name__}(",
498
+ f' id="{self.effect_id}",',
499
+ f" title={_literal(self.title)},",
500
+ f" description={_literal(self.description)},",
501
+ ]
502
+ if self.parameters:
503
+ lines.append(" parameter_schema={")
504
+ for parameter in self.parameters:
505
+ lines.append(f" {parameter.code()},")
506
+ lines.append(" },")
507
+ if self.kind is DefinitionKind.CONTROLLED_OVERLAY and self.runtime_inputs:
508
+ lines.append(" runtime_inputs={")
509
+ for parameter in self.runtime_inputs:
510
+ lines.append(f" {parameter.code()},")
511
+ lines.append(" },")
512
+
513
+ lines.append(f" color_model=ColorModel.{self.color_model.name},")
514
+ lines.append(f" composition=CompositionMode.{self.composition.name},")
515
+ if self.animated:
516
+ lines.append(" animated=True,")
517
+ if self.directional:
518
+ lines.append(" directional=True,")
519
+ if self.kind is DefinitionKind.STATE:
520
+ slots = ", ".join(f"StateSlot.{slot.name}" for slot in self.slots)
521
+ lines.append(f" slots=({slots},)," if len(self.slots) == 1
522
+ else f" slots=({slots}),")
523
+ if self.restorable:
524
+ lines.append(" restorable=True,")
525
+ if self.kind is DefinitionKind.CONTROLLED_OVERLAY:
526
+ policy = [f"mode=InputMode.{self.sampling_mode.name}"]
527
+ if self.sampling_mode is InputMode.PULL and self.provider_id:
528
+ policy.append(f'provider_id="{self.provider_id}"')
529
+ policy.append(f"interval_ms={self.interval_ms}")
530
+ lines.append(f" sampling=InputSamplingPolicy({', '.join(policy)}),")
531
+ if self.finite:
532
+ lines.append(f" duration_field=DurationField.{self.duration_field.name},")
533
+ if self.supports_duration_override:
534
+ lines.append(" supports_duration_override=True,")
535
+ if self.kind is DefinitionKind.EVENT and self.default_priority is not None:
536
+ lines.append(f" default_priority={self.default_priority},")
537
+ if self.tags:
538
+ lines.append(f" tags={_literal(tuple(self.tags))},")
539
+ if self.version != 1:
540
+ lines.append(f" version={self.version},")
541
+ lines.append(" )")
542
+ lines.append("")
543
+ lines.append(" def render(self, ctx: RenderContext) -> list[int | None]:")
544
+ for line in self.render_body.rstrip().splitlines() or [" return ctx.transparent_frame()"]:
545
+ lines.append(line.rstrip())
546
+ lines.append("")
547
+ return "\n".join(lines)
548
+
549
+ def _imports(self) -> list[str]:
550
+ """Only what the generated source actually mentions.
551
+
552
+ An unused import would be noise in a file meant to be read as an
553
+ example, and the studio writes these to be read.
554
+ """
555
+ names = {"BaseEffect", "ColorModel", "CompositionMode", "RenderContext"}
556
+ names.add(type(self.definition()).__name__)
557
+ if self.parameters or self.runtime_inputs:
558
+ names |= {"ParamDefinition", "ParamType"}
559
+ if self.kind is DefinitionKind.STATE:
560
+ names.add("StateSlot")
561
+ if self.kind is DefinitionKind.CONTROLLED_OVERLAY:
562
+ names |= {"InputMode", "InputSamplingPolicy"}
563
+ if self.finite:
564
+ names.add("DurationField")
565
+ body = self.render_body
566
+ for helper in ("parse_color", "scale_color", "blend", "position_for_angle",
567
+ "positions_for_angle", "sector_for_angle", "evenly_spaced_positions",
568
+ "segment_lengths", "rgb"):
569
+ if re.search(rf"\b{helper}\b", body):
570
+ names.add(helper)
571
+ return sorted(names)
572
+
573
+ def manifest_text(self) -> str:
574
+ return (
575
+ "# The class in effect.py is the source of truth for the contract. This\n"
576
+ "# manifest only says where the definition belongs and where to find it.\n"
577
+ f"source_id: {self.source_id}\n"
578
+ "entry_file: effect.py\n"
579
+ f"entry_class: {self.class_name}\n"
580
+ )
581
+
582
+ def write(self, parent: str | Path, *, force: bool = False) -> Path:
583
+ """Write the source directory. Refuses to overwrite unless told to."""
584
+ problems = self.problems()
585
+ if problems:
586
+ raise SourceError("; ".join(problems))
587
+
588
+ root = Path(parent).expanduser().resolve() / self.effect_id
589
+ source = root / SOURCE_NAME
590
+ if source.exists() and not force:
591
+ raise SourceError(f"{source} existiert bereits.")
592
+
593
+ root.mkdir(parents=True, exist_ok=True)
594
+ source.write_text(self.source_code(), encoding="utf-8")
595
+ (root / MANIFEST_NAME).write_text(self.manifest_text(), encoding="utf-8")
596
+
597
+ report = validate_effect_source(root)
598
+ if not report.ok:
599
+ # Written and then judged by the tool that will judge it later. The
600
+ # files stay so the errors can be read against them, but the caller
601
+ # is told rather than left to find out at build time.
602
+ raise SourceError(
603
+ f"{self.effect_id} wurde geschrieben, validiert aber nicht: "
604
+ + "; ".join(report.errors)
605
+ )
606
+ return root
607
+
608
+
609
+ def compile_blueprint(blueprint: "EffectBlueprint"):
610
+ """Turn a blueprint's generated source into a class, without touching disk.
611
+
612
+ The same import the loader performs, minus the packaging — so a body that
613
+ would not load fails here, while it is still being typed. The module is
614
+ anonymous and thrown away; nothing is registered by looking.
615
+ """
616
+ import types
617
+
618
+ module = types.ModuleType(f"_lefx_studio_{blueprint.effect_id or 'draft'}")
619
+ code = compile(blueprint.source_code(), f"<{blueprint.effect_id or 'draft'}>", "exec")
620
+ exec(code, module.__dict__) # noqa: S102 — running what the author just wrote is the point
621
+ return getattr(module, blueprint.class_name)
622
+
623
+
624
+ def build_package(source_dir: str | Path, output: str | Path) -> dict[str, Any]:
625
+ """Pack one validated source into a single ``.lefx``."""
626
+ root = Path(source_dir).expanduser().resolve()
627
+ report = validate_effect_source(root)
628
+ if not report.ok:
629
+ raise SourceError("; ".join(report.errors))
630
+ target = Path(output).expanduser().resolve()
631
+ target.parent.mkdir(parents=True, exist_ok=True)
632
+ return pack_effect(root, target)
633
+
634
+
635
+ # -- starting points --------------------------------------------------------
636
+
637
+ _BODIES: Mapping[DefinitionKind, str] = {
638
+ DefinitionKind.STATE: (
639
+ ' color = scale_color(parse_color(ctx.params["color"]), ctx.params["brightness"])\n'
640
+ " return [color] * ctx.led_count"
641
+ ),
642
+ DefinitionKind.CONTROLLED_OVERLAY: (
643
+ " frame = ctx.transparent_frame()\n"
644
+ ' color = scale_color(parse_color(ctx.params["color"]), ctx.params["brightness"])\n'
645
+ " frame[0] = color\n"
646
+ " return frame"
647
+ ),
648
+ # The finite forms know how long they have: their declared duration and
649
+ # ctx.elapsed. Fading over that is the smallest body that shows the shape.
650
+ DefinitionKind.TIMED_OVERLAY: (
651
+ ' total = ctx.params["duration_ms"] / 1000.0\n'
652
+ " fade = max(0.0, 1.0 - (ctx.elapsed / total if total > 0 else 1.0))\n"
653
+ ' color = scale_color(parse_color(ctx.params["color"]),\n'
654
+ ' ctx.params["brightness"] * fade)\n'
655
+ " return [color] * ctx.led_count"
656
+ ),
657
+ DefinitionKind.EVENT: (
658
+ ' total = ctx.params["duration_ms"] / 1000.0\n'
659
+ " fade = max(0.0, 1.0 - (ctx.elapsed / total if total > 0 else 1.0))\n"
660
+ ' color = scale_color(parse_color(ctx.params["color"]),\n'
661
+ ' ctx.params["brightness"] * fade)\n'
662
+ " return [color] * ctx.led_count"
663
+ ),
664
+ }
665
+
666
+
667
+ def starting_blueprint(kind: DefinitionKind, *, effect_id: str = "", source_id: str = "my-set"):
668
+ """A blueprint that is already valid, so the editor opens on something that runs."""
669
+ blueprint = EffectBlueprint(
670
+ kind=kind,
671
+ effect_id=effect_id,
672
+ title=effect_id.replace("_", " ").title() if effect_id else "",
673
+ description="",
674
+ source_id=source_id,
675
+ composition=(
676
+ CompositionMode.OPAQUE
677
+ if kind is DefinitionKind.STATE
678
+ else CompositionMode.TRANSPARENT
679
+ ),
680
+ render_body=_BODIES[kind],
681
+ )
682
+ blueprint.add_missing_parameters()
683
+ if kind is DefinitionKind.CONTROLLED_OVERLAY:
684
+ blueprint.runtime_inputs.append(
685
+ replace(
686
+ reserved_blueprint("progress"),
687
+ required=False,
688
+ default=0.0,
689
+ description="Wert, der zur Laufzeit geliefert wird.",
690
+ )
691
+ )
692
+ return blueprint
693
+
694
+
695
+ # -- helpers ----------------------------------------------------------------
696
+
697
+
698
+ def _is_identifier(value: str) -> bool:
699
+ return (
700
+ bool(value)
701
+ and value.isidentifier()
702
+ and not value.startswith("_")
703
+ and value == value.lower()
704
+ and not keyword.iskeyword(value)
705
+ )
706
+
707
+
708
+ def _is_source_id(value: str) -> bool:
709
+ return bool(re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9._-]*", value or ""))
710
+
711
+
712
+ def _number(value: float, integral: bool) -> str:
713
+ return str(int(value)) if integral else repr(float(value))
714
+
715
+
716
+ def _literal(value: Any) -> str:
717
+ """A Python literal for a value that came out of a form.
718
+
719
+ Double quotes where they are available, because that is how the rest of the
720
+ catalogue is written and these files are meant to be read next to it.
721
+ """
722
+ if isinstance(value, str) and '"' not in value and "\\" not in value:
723
+ return f'"{value}"'
724
+ if isinstance(value, tuple):
725
+ inner = ", ".join(_literal(item) for item in value)
726
+ return f"({inner},)" if len(value) == 1 else f"({inner})"
727
+ if isinstance(value, list):
728
+ return "[" + ", ".join(_literal(item) for item in value) + "]"
729
+ if isinstance(value, dict):
730
+ inner = ", ".join(f"{_literal(k)}: {_literal(v)}" for k, v in value.items())
731
+ return "{" + inner + "}"
732
+ return repr(value)
733
+
734
+
735
+ def _wrap(text: str, width: int = 72) -> list[str]:
736
+ import textwrap
737
+
738
+ return textwrap.wrap(text.strip(), width=width) or [""]
739
+
740
+
741
+ __all__ = [
742
+ "BOUND_LIMIT",
743
+ "COLOR_LIST_LIMIT",
744
+ "DEFAULT_COLOR",
745
+ "DURATION_LIMIT_MS",
746
+ "MANIFEST_NAME",
747
+ "PRIORITY_LIMIT",
748
+ "SOURCE_NAME",
749
+ "TYPE_SUPPORT",
750
+ "VERSION_LIMIT",
751
+ "EffectBlueprint",
752
+ "ParameterBlueprint",
753
+ "TypeSupport",
754
+ "build_package",
755
+ "compile_blueprint",
756
+ "default_for",
757
+ "reserved_blueprint",
758
+ "starting_blueprint",
759
+ ]