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,902 @@
1
+ """The source editor: design a definition, watch it run, write it out.
2
+
3
+ Three columns, and the middle one is the point. On the left the definition is
4
+ described; in the middle its parameters are built up; on the right it renders on
5
+ the actual device while you do it.
6
+
7
+ The rule the whole page is built on: **nothing invalid can be entered.** Not
8
+ "is rejected on save" — cannot be entered. Which companion fields a parameter
9
+ type accepts is decided by the type, so the rest are disabled rather than
10
+ ignored. Reserved names come with their fixed type and range already filled in.
11
+ The combinations no single field can see — a coloured definition without
12
+ brightness, an animated one without speed, a finite one without its duration —
13
+ are checked by constructing the real definition on every keystroke, and the
14
+ Save button is simply off while that fails.
15
+
16
+ Every number box is bounded, generously but finitely. The schema will accept a
17
+ duration of four hours; a form that offers it invites a typo nobody notices.
18
+ """
19
+
20
+ from __future__ import annotations
21
+
22
+ import logging
23
+ from pathlib import Path
24
+ from typing import Any
25
+
26
+ from PySide6.QtCore import Qt, Signal
27
+ from PySide6.QtGui import QFont
28
+ from PySide6.QtWidgets import (
29
+ QCheckBox,
30
+ QComboBox,
31
+ QDoubleSpinBox,
32
+ QFileDialog,
33
+ QFormLayout,
34
+ QGroupBox,
35
+ QHBoxLayout,
36
+ QLabel,
37
+ QLineEdit,
38
+ QListWidget,
39
+ QListWidgetItem,
40
+ QMessageBox,
41
+ QPlainTextEdit,
42
+ QPushButton,
43
+ QScrollArea,
44
+ QSpinBox,
45
+ QSplitter,
46
+ QToolButton,
47
+ QVBoxLayout,
48
+ QWidget,
49
+ )
50
+
51
+ from lefx.effect_creation import SourceError
52
+ from lefx.sdk import (
53
+ ColorModel,
54
+ CompositionMode,
55
+ DefinitionKind,
56
+ DurationField,
57
+ InputMode,
58
+ ParamType,
59
+ StateSlot,
60
+ )
61
+
62
+ from .blueprint import (
63
+ BOUND_LIMIT,
64
+ COLOR_LIST_LIMIT,
65
+ DURATION_LIMIT_MS,
66
+ PRIORITY_LIMIT,
67
+ TYPE_SUPPORT,
68
+ VERSION_LIMIT,
69
+ EffectBlueprint,
70
+ ParameterBlueprint,
71
+ build_package,
72
+ compile_blueprint,
73
+ default_for,
74
+ reserved_blueprint,
75
+ starting_blueprint,
76
+ )
77
+ from .catalogue import KIND_LABELS
78
+ from .parameters import editor_for
79
+ from .ring import RingMonitor
80
+ from .session import STUDIO_CHANNEL, StudioSession
81
+
82
+ logger = logging.getLogger("lefx.effect_creation.studio.source_editor")
83
+
84
+ PREVIEW_ID_PREFIX = "studio_preview"
85
+
86
+
87
+ def _chosen(combo: QComboBox, enum_class):
88
+ """The enum a combo box is on.
89
+
90
+ Qt stores item data as a QVariant, and every enum in the schema is a
91
+ ``str`` subclass — so what comes back out is a plain string that compares
92
+ equal to the member and hashes like it, but has no ``.value`` and is not an
93
+ instance of anything. That is a bug that hides until the one line that asks
94
+ the enum for something, so the conversion happens here, once.
95
+ """
96
+ return enum_class(combo.currentData())
97
+
98
+
99
+ class ParameterEditorRow(QWidget):
100
+ """One parameter's whole declaration, with the fields its type does not have
101
+ switched off rather than left to be filled in wrongly."""
102
+
103
+ changed = Signal()
104
+ removed = Signal()
105
+
106
+ def __init__(self, blueprint: ParameterBlueprint, *, runtime: bool = False,
107
+ parent: QWidget | None = None) -> None:
108
+ super().__init__(parent)
109
+ self.blueprint = blueprint
110
+ self.runtime = runtime
111
+ self._building = True
112
+ self._build()
113
+ self._load()
114
+ self._building = False
115
+
116
+ def _build(self) -> None:
117
+ box = QGroupBox()
118
+ outer = QVBoxLayout(self)
119
+ outer.setContentsMargins(0, 0, 0, 0)
120
+ outer.addWidget(box)
121
+ layout = QFormLayout(box)
122
+
123
+ head = QHBoxLayout()
124
+ self.name = QLineEdit()
125
+ self.name.setPlaceholderText("name")
126
+ self.name.textEdited.connect(self._on_name_edited)
127
+ self.type_box = QComboBox()
128
+ for kind in ParamType:
129
+ self.type_box.addItem(kind.value, kind)
130
+ self.type_box.currentIndexChanged.connect(self._on_type_changed)
131
+ self.drop = QToolButton()
132
+ self.drop.setText("✕")
133
+ self.drop.setToolTip("Parameter entfernen")
134
+ self.drop.clicked.connect(self.removed.emit)
135
+ head.addWidget(self.name, stretch=2)
136
+ head.addWidget(self.type_box, stretch=1)
137
+ head.addWidget(self.drop)
138
+ holder = QWidget()
139
+ holder.setLayout(head)
140
+ layout.addRow(holder)
141
+
142
+ self.reserved_note = QLabel("")
143
+ self.reserved_note.setWordWrap(True)
144
+ self.reserved_note.setStyleSheet("color: #d9a441;")
145
+ layout.addRow(self.reserved_note)
146
+
147
+ self.default_host = QWidget()
148
+ self.default_layout = QVBoxLayout(self.default_host)
149
+ self.default_layout.setContentsMargins(0, 0, 0, 0)
150
+ self.default_editor: Any = None
151
+ layout.addRow("Vorgabe", self.default_host)
152
+
153
+ bounds = QHBoxLayout()
154
+ self.has_minimum = QCheckBox("min")
155
+ self.has_minimum.toggled.connect(self._announce)
156
+ self.minimum = QDoubleSpinBox()
157
+ self.minimum.setRange(-BOUND_LIMIT, BOUND_LIMIT)
158
+ self.minimum.setDecimals(3)
159
+ self.minimum.valueChanged.connect(self._announce)
160
+ self.has_maximum = QCheckBox("max")
161
+ self.has_maximum.toggled.connect(self._announce)
162
+ self.maximum = QDoubleSpinBox()
163
+ self.maximum.setRange(-BOUND_LIMIT, BOUND_LIMIT)
164
+ self.maximum.setDecimals(3)
165
+ self.maximum.valueChanged.connect(self._announce)
166
+ for widget in (self.has_minimum, self.minimum, self.has_maximum, self.maximum):
167
+ bounds.addWidget(widget)
168
+ self.bounds_host = QWidget()
169
+ self.bounds_host.setLayout(bounds)
170
+ layout.addRow("Grenzen", self.bounds_host)
171
+
172
+ self.unit = QComboBox()
173
+ self.unit.currentIndexChanged.connect(self._announce)
174
+ layout.addRow("Einheit", self.unit)
175
+
176
+ self.enum_values = QLineEdit()
177
+ self.enum_values.setPlaceholderText("a, b, c")
178
+ self.enum_values.textEdited.connect(self._announce)
179
+ layout.addRow("Werte", self.enum_values)
180
+
181
+ flags = QHBoxLayout()
182
+ self.nullable = QCheckBox("nullable")
183
+ self.nullable.toggled.connect(self._announce)
184
+ self.required = QCheckBox("required")
185
+ self.required.toggled.connect(self._announce)
186
+ flags.addWidget(self.nullable)
187
+ flags.addWidget(self.required)
188
+ flags.addStretch(1)
189
+ self.flags_host = QWidget()
190
+ self.flags_host.setLayout(flags)
191
+ layout.addRow("", self.flags_host)
192
+
193
+ self.description = QLineEdit()
194
+ self.description.textEdited.connect(self._announce)
195
+ layout.addRow("Beschreibung", self.description)
196
+
197
+ self.problem = QLabel("")
198
+ self.problem.setWordWrap(True)
199
+ self.problem.setStyleSheet("color: #d76;")
200
+ layout.addRow(self.problem)
201
+
202
+ # -- moving values in and out ------------------------------------------
203
+
204
+ def _load(self) -> None:
205
+ blueprint = self.blueprint
206
+ self.name.setText(blueprint.name)
207
+ self.type_box.setCurrentIndex(self.type_box.findData(blueprint.type))
208
+ self.description.setText(blueprint.description)
209
+ self.nullable.setChecked(blueprint.nullable)
210
+ self.required.setChecked(blueprint.required)
211
+ self.has_minimum.setChecked(blueprint.minimum is not None)
212
+ self.minimum.setValue(blueprint.minimum or 0.0)
213
+ self.has_maximum.setChecked(blueprint.maximum is not None)
214
+ self.maximum.setValue(blueprint.maximum if blueprint.maximum is not None else 1.0)
215
+ self.enum_values.setText(", ".join(blueprint.enum_values))
216
+ self._rebuild_default_editor()
217
+ self._apply_type_rules()
218
+
219
+ def _rebuild_default_editor(self) -> None:
220
+ """The default is edited with the same widget the player would use.
221
+
222
+ Which means a colour default is picked from a colour dialog and a
223
+ duration is typed in milliseconds — and it is already canonical when it
224
+ reaches the generated source.
225
+ """
226
+ while self.default_layout.count():
227
+ widget = self.default_layout.takeAt(0).widget()
228
+ if widget is not None:
229
+ widget.setParent(None)
230
+ widget.deleteLater()
231
+
232
+ blueprint = self.blueprint
233
+ probe = ParameterBlueprint(
234
+ name=blueprint.name or "value",
235
+ type=blueprint.type,
236
+ default=blueprint.default,
237
+ enum_values=blueprint.enum_values or ("a",),
238
+ nullable=blueprint.nullable,
239
+ )
240
+ try:
241
+ self.default_editor = editor_for(probe.build())
242
+ except Exception:
243
+ # A half-declared parameter has no editable default yet; the row
244
+ # already says what is missing.
245
+ self.default_editor = None
246
+ return
247
+ try:
248
+ self.default_editor.set_value(
249
+ blueprint.default if blueprint.default is not None else default_for(blueprint.type)
250
+ )
251
+ except Exception:
252
+ self.default_editor.set_value(default_for(blueprint.type))
253
+ self.default_editor.changed.connect(self._announce)
254
+ self.default_layout.addWidget(self.default_editor)
255
+
256
+ def _apply_type_rules(self) -> None:
257
+ """Grey out what this type does not have. The schema's matrix, as a form."""
258
+ support = TYPE_SUPPORT[self.blueprint.type]
259
+ self.bounds_host.setEnabled(support.bounds)
260
+ self.minimum.setDecimals(0 if support.integral_bounds else 3)
261
+ self.maximum.setDecimals(0 if support.integral_bounds else 3)
262
+ if self.blueprint.type is ParamType.DURATION_MS:
263
+ self.minimum.setRange(0, DURATION_LIMIT_MS)
264
+ self.maximum.setRange(0, DURATION_LIMIT_MS)
265
+ elif self.blueprint.type is ParamType.COLOR_LIST:
266
+ self.minimum.setRange(0, COLOR_LIST_LIMIT)
267
+ self.maximum.setRange(0, COLOR_LIST_LIMIT)
268
+ else:
269
+ self.minimum.setRange(-BOUND_LIMIT, BOUND_LIMIT)
270
+ self.maximum.setRange(-BOUND_LIMIT, BOUND_LIMIT)
271
+
272
+ self.unit.setEnabled(support.unit_allowed)
273
+ current = self.unit.currentText()
274
+ self.unit.blockSignals(True)
275
+ self.unit.clear()
276
+ self.unit.addItem("—", None)
277
+ for unit in support.units:
278
+ self.unit.addItem(unit, unit)
279
+ index = self.unit.findText(current)
280
+ self.unit.setCurrentIndex(max(0, index))
281
+ self.unit.blockSignals(False)
282
+
283
+ self.enum_values.setEnabled(support.enum_values)
284
+ # nullable and required are only meaningful for a runtime input: a
285
+ # configuration field must always resolve, so it always has a default.
286
+ self.nullable.setEnabled(self.runtime)
287
+ self.required.setEnabled(self.runtime)
288
+
289
+ reserved = self.blueprint.reserved
290
+ self.type_box.setEnabled(not reserved)
291
+ self.reserved_note.setVisible(reserved)
292
+ if reserved:
293
+ self.reserved_note.setText(
294
+ f"„{self.blueprint.name}“ ist ein reservierter Name: Typ und Bereich sind "
295
+ "systemweit festgelegt und werden hier nicht zur Wahl gestellt."
296
+ )
297
+ self.bounds_host.setEnabled(False)
298
+
299
+ def collect(self) -> None:
300
+ """Read the form back into the blueprint."""
301
+ blueprint = self.blueprint
302
+ blueprint.name = self.name.text().strip()
303
+ blueprint.type = _chosen(self.type_box, ParamType)
304
+ blueprint.description = self.description.text().strip()
305
+ support = TYPE_SUPPORT[blueprint.type]
306
+ blueprint.minimum = (
307
+ float(self.minimum.value()) if support.bounds and self.has_minimum.isChecked() else None
308
+ )
309
+ blueprint.maximum = (
310
+ float(self.maximum.value()) if support.bounds and self.has_maximum.isChecked() else None
311
+ )
312
+ blueprint.unit = self.unit.currentData() if support.unit_allowed else None
313
+ blueprint.enum_values = (
314
+ tuple(part.strip() for part in self.enum_values.text().split(",") if part.strip())
315
+ if support.enum_values
316
+ else ()
317
+ )
318
+ blueprint.nullable = self.runtime and self.nullable.isChecked()
319
+ blueprint.required = self.runtime and self.required.isChecked()
320
+ if self.default_editor is not None and not blueprint.required:
321
+ blueprint.default = self.default_editor.value()
322
+
323
+ def show_problem(self) -> None:
324
+ self.problem.setText(self.blueprint.problem() or "")
325
+
326
+ # -- reacting ----------------------------------------------------------
327
+
328
+ def _on_name_edited(self, text: str) -> None:
329
+ name = text.strip()
330
+ if name in {"brightness", "speed", "reverse", "progress", "direction_deg",
331
+ "duration_ms", "total_ms", "color", "secondary_color",
332
+ "background_color", "colors", "gradient", "color_range", "random_seed"}:
333
+ # Typing a reserved name adopts its fixed declaration rather than
334
+ # letting a wrong type be entered and rejected afterwards.
335
+ fixed = reserved_blueprint(name)
336
+ fixed.description = self.blueprint.description
337
+ self.blueprint = fixed
338
+ self._building = True
339
+ self._load()
340
+ self._building = False
341
+ self._announce()
342
+
343
+ def _on_type_changed(self) -> None:
344
+ if self._building:
345
+ return
346
+ self.blueprint.type = _chosen(self.type_box, ParamType)
347
+ self.blueprint.default = default_for(self.blueprint.type)
348
+ self._apply_type_rules()
349
+ self._rebuild_default_editor()
350
+ self._announce()
351
+
352
+ def _announce(self, *_: Any) -> None:
353
+ if self._building:
354
+ return
355
+ self.collect()
356
+ self.show_problem()
357
+ self.changed.emit()
358
+
359
+
360
+ class SourceEditorPage(QWidget):
361
+ """Design a definition, render it on the device, write it out and pack it."""
362
+
363
+ frame_received = Signal(tuple)
364
+
365
+ def __init__(self, session: StudioSession, parent: QWidget | None = None) -> None:
366
+ super().__init__(parent)
367
+ self.session = session
368
+ self.blueprint = starting_blueprint(DefinitionKind.STATE)
369
+ self.rows: list[ParameterEditorRow] = []
370
+ self.input_rows: list[ParameterEditorRow] = []
371
+ self.written: Path | None = None
372
+ self._loading = False
373
+
374
+ self._build()
375
+ self.frame_received.connect(self.monitor.set_colors)
376
+ self._load_blueprint()
377
+
378
+ # -- construction -------------------------------------------------------
379
+
380
+ def _build(self) -> None:
381
+ splitter = QSplitter(Qt.Orientation.Horizontal)
382
+ splitter.addWidget(self._build_identity())
383
+ splitter.addWidget(self._build_parameters())
384
+ splitter.addWidget(self._build_output())
385
+ splitter.setStretchFactor(0, 2)
386
+ splitter.setStretchFactor(1, 3)
387
+ splitter.setStretchFactor(2, 3)
388
+ layout = QVBoxLayout(self)
389
+ layout.addWidget(splitter)
390
+
391
+ def _build_identity(self) -> QWidget:
392
+ panel = QWidget()
393
+ layout = QVBoxLayout(panel)
394
+
395
+ box = QGroupBox("Definition")
396
+ form = QFormLayout(box)
397
+
398
+ self.kind_box = QComboBox()
399
+ for kind in DefinitionKind:
400
+ self.kind_box.addItem(KIND_LABELS[kind], kind)
401
+ self.kind_box.currentIndexChanged.connect(self._on_kind_changed)
402
+ form.addRow("Form", self.kind_box)
403
+
404
+ self.effect_id = QLineEdit()
405
+ self.effect_id.setPlaceholderText("mein_effekt")
406
+ self.effect_id.textEdited.connect(self._on_edited)
407
+ form.addRow("Id", self.effect_id)
408
+
409
+ self.title = QLineEdit()
410
+ self.title.textEdited.connect(self._on_edited)
411
+ form.addRow("Titel", self.title)
412
+
413
+ self.description = QPlainTextEdit()
414
+ self.description.setMaximumHeight(64)
415
+ self.description.textChanged.connect(self._on_edited)
416
+ form.addRow("Beschreibung", self.description)
417
+
418
+ self.source_id = QLineEdit("my-set")
419
+ self.source_id.textEdited.connect(self._on_edited)
420
+ form.addRow("Set", self.source_id)
421
+
422
+ self.tags = QLineEdit()
423
+ self.tags.setPlaceholderText("core, overlay")
424
+ self.tags.textEdited.connect(self._on_edited)
425
+ form.addRow("Tags", self.tags)
426
+
427
+ self.version = QSpinBox()
428
+ self.version.setRange(1, VERSION_LIMIT)
429
+ self.version.valueChanged.connect(self._on_edited)
430
+ form.addRow("Version", self.version)
431
+ layout.addWidget(box)
432
+
433
+ visual = QGroupBox("Darstellung")
434
+ vform = QFormLayout(visual)
435
+ self.color_model = QComboBox()
436
+ for model in ColorModel:
437
+ self.color_model.addItem(model.value, model)
438
+ self.color_model.currentIndexChanged.connect(self._on_structure_changed)
439
+ vform.addRow("Farbmodell", self.color_model)
440
+
441
+ self.composition = QComboBox()
442
+ for mode in CompositionMode:
443
+ self.composition.addItem(mode.value, mode)
444
+ self.composition.currentIndexChanged.connect(self._on_edited)
445
+ vform.addRow("Komposition", self.composition)
446
+
447
+ self.animated = QCheckBox("animiert (verlangt speed)")
448
+ self.animated.toggled.connect(self._on_structure_changed)
449
+ self.directional = QCheckBox("gerichtet (verlangt reverse)")
450
+ self.directional.toggled.connect(self._on_structure_changed)
451
+ vform.addRow("", self.animated)
452
+ vform.addRow("", self.directional)
453
+ layout.addWidget(visual)
454
+
455
+ self.form_box = QGroupBox("Formspezifisch")
456
+ self.form_layout = QFormLayout(self.form_box)
457
+ self._build_form_specific()
458
+ layout.addWidget(self.form_box)
459
+ layout.addStretch(1)
460
+ return panel
461
+
462
+ def _build_form_specific(self) -> None:
463
+ self.slot_primary = QCheckBox("primary")
464
+ self.slot_primary.setChecked(True)
465
+ self.slot_primary.toggled.connect(self._on_edited)
466
+ self.slot_background = QCheckBox("background")
467
+ self.slot_background.toggled.connect(self._on_edited)
468
+ self.restorable = QCheckBox("restorable (nur mit background)")
469
+ self.restorable.toggled.connect(self._on_edited)
470
+ slots = QHBoxLayout()
471
+ slots.addWidget(self.slot_primary)
472
+ slots.addWidget(self.slot_background)
473
+ self.slots_host = QWidget()
474
+ self.slots_host.setLayout(slots)
475
+ self.form_layout.addRow("Plätze", self.slots_host)
476
+ self.form_layout.addRow("", self.restorable)
477
+
478
+ self.duration_field = QComboBox()
479
+ for field in DurationField:
480
+ self.duration_field.addItem(field.value, field)
481
+ self.duration_field.currentIndexChanged.connect(self._on_structure_changed)
482
+ self.form_layout.addRow("Längenfeld", self.duration_field)
483
+
484
+ self.duration_override = QCheckBox("Länge beim Auslösen überschreibbar")
485
+ self.duration_override.toggled.connect(self._on_edited)
486
+ self.form_layout.addRow("", self.duration_override)
487
+
488
+ self.has_priority = QCheckBox("Standardpriorität")
489
+ self.has_priority.toggled.connect(self._on_edited)
490
+ self.priority = QSpinBox()
491
+ self.priority.setRange(-PRIORITY_LIMIT, PRIORITY_LIMIT)
492
+ self.priority.valueChanged.connect(self._on_edited)
493
+ priority = QHBoxLayout()
494
+ priority.addWidget(self.has_priority)
495
+ priority.addWidget(self.priority)
496
+ self.priority_host = QWidget()
497
+ self.priority_host.setLayout(priority)
498
+ self.form_layout.addRow("", self.priority_host)
499
+
500
+ self.sampling_mode = QComboBox()
501
+ for mode in InputMode:
502
+ self.sampling_mode.addItem(mode.value, mode)
503
+ self.sampling_mode.currentIndexChanged.connect(self._on_edited)
504
+ self.form_layout.addRow("Eingaben", self.sampling_mode)
505
+
506
+ self.provider_id = QLineEdit()
507
+ self.provider_id.setPlaceholderText("doa")
508
+ self.provider_id.textEdited.connect(self._on_edited)
509
+ self.form_layout.addRow("Capability", self.provider_id)
510
+
511
+ self.interval_ms = QSpinBox()
512
+ self.interval_ms.setRange(0, 60_000)
513
+ self.interval_ms.setSuffix(" ms")
514
+ self.interval_ms.valueChanged.connect(self._on_edited)
515
+ self.form_layout.addRow("Abtastintervall", self.interval_ms)
516
+
517
+ def _build_parameters(self) -> QWidget:
518
+ panel = QWidget()
519
+ layout = QVBoxLayout(panel)
520
+
521
+ header = QHBoxLayout()
522
+ header.addWidget(QLabel("<b>Parameter</b>"))
523
+ header.addStretch(1)
524
+ self.fill_button = QPushButton("Pflichtfelder ergänzen")
525
+ self.fill_button.setToolTip(
526
+ "Fügt hinzu, was Farbmodell, Flags und Form verlangen — korrekt typisiert"
527
+ )
528
+ self.fill_button.clicked.connect(self._fill_required)
529
+ add = QPushButton("+ Parameter")
530
+ add.clicked.connect(lambda: self._add_row(ParameterBlueprint(), runtime=False))
531
+ header.addWidget(self.fill_button)
532
+ header.addWidget(add)
533
+ layout.addLayout(header)
534
+
535
+ self.scroll = QScrollArea()
536
+ self.scroll.setWidgetResizable(True)
537
+ self.rows_host = QWidget()
538
+ self.rows_layout = QVBoxLayout(self.rows_host)
539
+ self.rows_layout.setAlignment(Qt.AlignmentFlag.AlignTop)
540
+ self.scroll.setWidget(self.rows_host)
541
+ layout.addWidget(self.scroll, stretch=3)
542
+
543
+ self.inputs_header = QHBoxLayout()
544
+ self.inputs_label = QLabel("<b>Runtime-Eingaben</b>")
545
+ self.inputs_header.addWidget(self.inputs_label)
546
+ self.inputs_header.addStretch(1)
547
+ self.add_input = QPushButton("+ Eingabe")
548
+ self.add_input.clicked.connect(
549
+ lambda: self._add_row(ParameterBlueprint(nullable=True, required=True), runtime=True)
550
+ )
551
+ self.inputs_header.addWidget(self.add_input)
552
+ layout.addLayout(self.inputs_header)
553
+
554
+ self.inputs_scroll = QScrollArea()
555
+ self.inputs_scroll.setWidgetResizable(True)
556
+ self.inputs_host = QWidget()
557
+ self.inputs_layout = QVBoxLayout(self.inputs_host)
558
+ self.inputs_layout.setAlignment(Qt.AlignmentFlag.AlignTop)
559
+ self.inputs_scroll.setWidget(self.inputs_host)
560
+ layout.addWidget(self.inputs_scroll, stretch=2)
561
+ return panel
562
+
563
+ def _build_output(self) -> QWidget:
564
+ panel = QWidget()
565
+ layout = QVBoxLayout(panel)
566
+
567
+ self.monitor = RingMonitor(self.session.led_count)
568
+ self.monitor.setMinimumHeight(200)
569
+ layout.addWidget(self.monitor, stretch=2)
570
+
571
+ code_box = QGroupBox("render()")
572
+ code_layout = QVBoxLayout(code_box)
573
+ self.code = QPlainTextEdit()
574
+ self.code.setFont(QFont("Consolas, Menlo, monospace"))
575
+ self.code.setTabStopDistance(32)
576
+ self.code.textChanged.connect(self._on_edited)
577
+ code_layout.addWidget(self.code)
578
+ layout.addWidget(code_box, stretch=3)
579
+
580
+ self.status = QLabel("")
581
+ self.status.setWordWrap(True)
582
+ layout.addWidget(self.status)
583
+
584
+ buttons = QHBoxLayout()
585
+ self.preview_button = QPushButton("Vorschau")
586
+ self.preview_button.setToolTip("Auf dem gewählten Gerät abspielen")
587
+ self.preview_button.clicked.connect(self._preview)
588
+ self.save_button = QPushButton("Quelle schreiben …")
589
+ self.save_button.clicked.connect(self._write)
590
+ self.pack_button = QPushButton("Als .lefx bauen …")
591
+ self.pack_button.clicked.connect(self._pack)
592
+ self.pack_button.setEnabled(False)
593
+ buttons.addWidget(self.preview_button)
594
+ buttons.addStretch(1)
595
+ buttons.addWidget(self.save_button)
596
+ buttons.addWidget(self.pack_button)
597
+ layout.addLayout(buttons)
598
+
599
+ source_box = QGroupBox("effect.py — erzeugt, nicht getippt")
600
+ source_layout = QVBoxLayout(source_box)
601
+ self.preview_source = QPlainTextEdit()
602
+ self.preview_source.setReadOnly(True)
603
+ self.preview_source.setFont(QFont("Consolas, Menlo, monospace"))
604
+ source_layout.addWidget(self.preview_source)
605
+ layout.addWidget(source_box, stretch=3)
606
+ return panel
607
+
608
+ # -- moving the blueprint in and out ------------------------------------
609
+
610
+ def _load_blueprint(self) -> None:
611
+ self._loading = True
612
+ blueprint = self.blueprint
613
+ self.kind_box.setCurrentIndex(self.kind_box.findData(blueprint.kind))
614
+ self.effect_id.setText(blueprint.effect_id)
615
+ self.title.setText(blueprint.title)
616
+ self.description.setPlainText(blueprint.description)
617
+ self.source_id.setText(blueprint.source_id)
618
+ self.tags.setText(", ".join(blueprint.tags))
619
+ self.version.setValue(blueprint.version)
620
+ self.color_model.setCurrentIndex(self.color_model.findData(blueprint.color_model))
621
+ self.composition.setCurrentIndex(self.composition.findData(blueprint.composition))
622
+ self.animated.setChecked(blueprint.animated)
623
+ self.directional.setChecked(blueprint.directional)
624
+ self.slot_primary.setChecked(StateSlot.PRIMARY in blueprint.slots)
625
+ self.slot_background.setChecked(StateSlot.BACKGROUND in blueprint.slots)
626
+ self.restorable.setChecked(blueprint.restorable)
627
+ self.duration_field.setCurrentIndex(self.duration_field.findData(blueprint.duration_field))
628
+ self.duration_override.setChecked(blueprint.supports_duration_override)
629
+ self.has_priority.setChecked(blueprint.default_priority is not None)
630
+ self.priority.setValue(blueprint.default_priority or 0)
631
+ self.sampling_mode.setCurrentIndex(self.sampling_mode.findData(blueprint.sampling_mode))
632
+ self.provider_id.setText(blueprint.provider_id or "")
633
+ self.interval_ms.setValue(blueprint.interval_ms)
634
+ self.code.setPlainText(blueprint.render_body)
635
+ self._rebuild_rows()
636
+ self._loading = False
637
+ self._refresh()
638
+
639
+ def _rebuild_rows(self) -> None:
640
+ for rows, layout in ((self.rows, self.rows_layout), (self.input_rows, self.inputs_layout)):
641
+ for row in rows:
642
+ row.setParent(None)
643
+ row.deleteLater()
644
+ rows.clear()
645
+ while layout.count():
646
+ item = layout.takeAt(0)
647
+ widget = item.widget()
648
+ if widget is not None:
649
+ widget.setParent(None)
650
+ for parameter in self.blueprint.parameters:
651
+ self._attach_row(parameter, runtime=False)
652
+ for parameter in self.blueprint.runtime_inputs:
653
+ self._attach_row(parameter, runtime=True)
654
+
655
+ def _attach_row(self, parameter: ParameterBlueprint, *, runtime: bool) -> ParameterEditorRow:
656
+ row = ParameterEditorRow(parameter, runtime=runtime)
657
+ row.changed.connect(self._on_edited)
658
+ row.removed.connect(lambda r=row: self._remove_row(r))
659
+ if runtime:
660
+ self.input_rows.append(row)
661
+ self.inputs_layout.addWidget(row)
662
+ else:
663
+ self.rows.append(row)
664
+ self.rows_layout.addWidget(row)
665
+ return row
666
+
667
+ def _add_row(self, parameter: ParameterBlueprint, *, runtime: bool) -> None:
668
+ target = self.blueprint.runtime_inputs if runtime else self.blueprint.parameters
669
+ target.append(parameter)
670
+ self._attach_row(parameter, runtime=runtime)
671
+ self._refresh()
672
+
673
+ def _remove_row(self, row: ParameterEditorRow) -> None:
674
+ target = self.blueprint.runtime_inputs if row.runtime else self.blueprint.parameters
675
+ if row.blueprint in target:
676
+ target.remove(row.blueprint)
677
+ rows = self.input_rows if row.runtime else self.rows
678
+ if row in rows:
679
+ rows.remove(row)
680
+ row.setParent(None)
681
+ row.deleteLater()
682
+ self._refresh()
683
+
684
+ def collect(self) -> None:
685
+ blueprint = self.blueprint
686
+ blueprint.kind = _chosen(self.kind_box, DefinitionKind)
687
+ blueprint.effect_id = self.effect_id.text().strip()
688
+ blueprint.title = self.title.text().strip()
689
+ blueprint.description = self.description.toPlainText().strip()
690
+ blueprint.source_id = self.source_id.text().strip()
691
+ blueprint.tags = tuple(
692
+ part.strip() for part in self.tags.text().split(",") if part.strip()
693
+ )
694
+ blueprint.version = self.version.value()
695
+ blueprint.color_model = _chosen(self.color_model, ColorModel)
696
+ blueprint.composition = _chosen(self.composition, CompositionMode)
697
+ blueprint.animated = self.animated.isChecked()
698
+ blueprint.directional = self.directional.isChecked()
699
+ slots = []
700
+ if self.slot_primary.isChecked():
701
+ slots.append(StateSlot.PRIMARY)
702
+ if self.slot_background.isChecked():
703
+ slots.append(StateSlot.BACKGROUND)
704
+ blueprint.slots = tuple(slots)
705
+ blueprint.restorable = self.restorable.isChecked()
706
+ blueprint.duration_field = _chosen(self.duration_field, DurationField)
707
+ blueprint.supports_duration_override = self.duration_override.isChecked()
708
+ blueprint.default_priority = self.priority.value() if self.has_priority.isChecked() else None
709
+ blueprint.sampling_mode = _chosen(self.sampling_mode, InputMode)
710
+ blueprint.provider_id = self.provider_id.text().strip() or None
711
+ blueprint.interval_ms = self.interval_ms.value()
712
+ blueprint.render_body = self.code.toPlainText()
713
+ for row in [*self.rows, *self.input_rows]:
714
+ row.collect()
715
+
716
+ # -- reacting -----------------------------------------------------------
717
+
718
+ def _on_kind_changed(self) -> None:
719
+ if self._loading:
720
+ return
721
+ kind = _chosen(self.kind_box, DefinitionKind)
722
+ keep_id = self.effect_id.text().strip()
723
+ keep_source = self.source_id.text().strip() or "my-set"
724
+ # Switching form changes which parameters are mandatory and which are
725
+ # forbidden, so the blueprint is started again rather than patched into
726
+ # a shape that would need untangling.
727
+ self.blueprint = starting_blueprint(kind, effect_id=keep_id, source_id=keep_source)
728
+ self.blueprint.title = self.title.text().strip()
729
+ self.blueprint.description = self.description.toPlainText().strip()
730
+ self._load_blueprint()
731
+
732
+ def _on_structure_changed(self) -> None:
733
+ if self._loading:
734
+ return
735
+ self.collect()
736
+ self._refresh()
737
+
738
+ def _on_edited(self) -> None:
739
+ if self._loading:
740
+ return
741
+ self.collect()
742
+ self._refresh()
743
+
744
+ def _fill_required(self) -> None:
745
+ self.collect()
746
+ added = self.blueprint.add_missing_parameters()
747
+ for name in added:
748
+ parameter = next(p for p in self.blueprint.parameters if p.name == name)
749
+ self._attach_row(parameter, runtime=False)
750
+ if not added:
751
+ self.status.setText("Es fehlt nichts.")
752
+ self._refresh()
753
+
754
+ def _refresh(self) -> None:
755
+ blueprint = self.blueprint
756
+ controlled = blueprint.kind is DefinitionKind.CONTROLLED_OVERLAY
757
+ state = blueprint.kind is DefinitionKind.STATE
758
+
759
+ self.slots_host.setVisible(state)
760
+ self.restorable.setVisible(state)
761
+ self.restorable.setEnabled(state and self.slot_background.isChecked())
762
+ self.duration_field.setVisible(blueprint.finite)
763
+ self.duration_override.setVisible(blueprint.finite)
764
+ self.priority_host.setVisible(blueprint.kind is DefinitionKind.EVENT)
765
+ self.sampling_mode.setVisible(controlled)
766
+ self.provider_id.setVisible(controlled)
767
+ self.provider_id.setEnabled(controlled and blueprint.sampling_mode is InputMode.PULL)
768
+ self.interval_ms.setVisible(controlled)
769
+ for index in range(self.form_layout.rowCount()):
770
+ label = self.form_layout.itemAt(index, QFormLayout.ItemRole.LabelRole)
771
+ field = self.form_layout.itemAt(index, QFormLayout.ItemRole.FieldRole)
772
+ if label is not None and field is not None and field.widget() is not None:
773
+ label.widget().setVisible(field.widget().isVisible())
774
+
775
+ self.inputs_label.setVisible(controlled)
776
+ self.add_input.setVisible(controlled)
777
+ self.inputs_scroll.setVisible(controlled)
778
+
779
+ missing = blueprint.required_parameters()
780
+ forbidden = blueprint.forbidden_parameters()
781
+ self.fill_button.setEnabled(bool(missing))
782
+
783
+ for row in [*self.rows, *self.input_rows]:
784
+ row.show_problem()
785
+
786
+ problems = blueprint.problems()
787
+ if forbidden:
788
+ problems.insert(0, "Nicht erlaubt bei dieser Wahl: " + ", ".join(forbidden))
789
+ if missing:
790
+ problems.insert(0, "Es fehlen: " + ", ".join(missing))
791
+
792
+ self.save_button.setEnabled(not problems)
793
+ self.preview_button.setEnabled(not problems)
794
+ if problems:
795
+ self.status.setText("• " + "\n• ".join(problems[:6]))
796
+ self.status.setStyleSheet("color: #d76;")
797
+ self.preview_source.setPlainText("")
798
+ return
799
+
800
+ self.status.setText("Gültig — kann geschrieben und gebaut werden.")
801
+ self.status.setStyleSheet("color: #4c9;")
802
+ try:
803
+ self.preview_source.setPlainText(blueprint.source_code())
804
+ except Exception as exc: # pragma: no cover — problems() already passed
805
+ self.preview_source.setPlainText(f"# {exc}")
806
+
807
+ # -- doing something with it -------------------------------------------
808
+
809
+ def _preview(self) -> None:
810
+ """Render the definition being written, on the device that is attached.
811
+
812
+ Built in memory and registered under a throwaway id, so previewing does
813
+ not collide with a catalogue entry of the same name and leaves nothing
814
+ behind when the page is closed.
815
+ """
816
+ self.collect()
817
+ if self.blueprint.problems() or self.session.service is None:
818
+ return
819
+ try:
820
+ effect_class = compile_blueprint(self.blueprint)
821
+ except Exception as exc:
822
+ self.status.setText(f"render() lässt sich nicht laden: {exc}")
823
+ self.status.setStyleSheet("color: #d76;")
824
+ return
825
+
826
+ service = self.session.service
827
+ try:
828
+ from lefx.engine import build_registry
829
+
830
+ merged = list(service.library.registry.list_effects())
831
+ classes = [entry.effect_class for entry in merged]
832
+ service.library._registry = build_registry( # noqa: SLF001
833
+ [*classes, effect_class], source_id="studio-preview"
834
+ )
835
+ service.runtime.set_registry(service.library.registry)
836
+
837
+ definition = effect_class.definition
838
+ config = {name: p.default for name, p in definition.parameter_schema.items()}
839
+ if definition.kind is DefinitionKind.STATE:
840
+ self.session.play_state(definition.id, config)
841
+ elif definition.kind is DefinitionKind.EVENT:
842
+ self.session.emit(definition.id, config)
843
+ else:
844
+ inputs = {
845
+ name: p.default
846
+ for name, p in definition.runtime_input_schema.items()
847
+ if p.has_default
848
+ }
849
+ self.session.play_overlay(
850
+ definition.id,
851
+ config,
852
+ inputs,
853
+ channel=STUDIO_CHANNEL if definition.runtime_input_schema else None,
854
+ )
855
+ self.status.setText(f"{definition.id} läuft auf {self.session.output_name}.")
856
+ self.status.setStyleSheet("color: #4c9;")
857
+ except Exception as exc:
858
+ self.status.setText(f"Vorschau fehlgeschlagen: {exc}")
859
+ self.status.setStyleSheet("color: #d76;")
860
+
861
+ def _write(self) -> None:
862
+ self.collect()
863
+ parent = QFileDialog.getExistingDirectory(
864
+ self, "Wohin soll das Quellverzeichnis?", str(Path.cwd())
865
+ )
866
+ if not parent:
867
+ return
868
+ try:
869
+ self.written = self.blueprint.write(parent)
870
+ except SourceError as exc:
871
+ QMessageBox.critical(self, "Nicht geschrieben", str(exc))
872
+ return
873
+ self.pack_button.setEnabled(True)
874
+ self.status.setText(f"Geschrieben nach {self.written}")
875
+ self.status.setStyleSheet("color: #4c9;")
876
+
877
+ def _pack(self) -> None:
878
+ if self.written is None:
879
+ return
880
+ target, _ = QFileDialog.getSaveFileName(
881
+ self, "Paket speichern", f"{self.blueprint.effect_id}.lefx", "LEFX (*.lefx)"
882
+ )
883
+ if not target:
884
+ return
885
+ try:
886
+ report = build_package(self.written, target)
887
+ except SourceError as exc:
888
+ QMessageBox.critical(self, "Build fehlgeschlagen", str(exc))
889
+ return
890
+ QMessageBox.information(
891
+ self,
892
+ "Gebaut",
893
+ f"{report['effect_id']} → {target}\n{report['size_bytes']} Bytes",
894
+ )
895
+ self.status.setText(f"Gebaut: {target}")
896
+
897
+ def refresh(self) -> None:
898
+ self.monitor.set_led_count(self.session.led_count)
899
+ self._refresh()
900
+
901
+
902
+ __all__ = ["PREVIEW_ID_PREFIX", "ParameterEditorRow", "SourceEditorPage"]