863 lines
38 KiB
Python
863 lines
38 KiB
Python
"""JSON show spec: schema, validation, and Show.from_spec."""
|
||
|
||
from __future__ import annotations
|
||
|
||
import json
|
||
from pathlib import Path
|
||
from typing import Any
|
||
|
||
from patternstudio.efx import ALGORITHMS, DIRECTIONS, PROPAGATIONS, RUN_ORDERS
|
||
from patternstudio.fixturedefs import FixtureLibrary
|
||
|
||
from .model import ArtNetOutput, MidiBinding, MidiInput, Show, midi_cc, midi_note
|
||
|
||
PROJECT_ROOT = Path(__file__).resolve().parents[1]
|
||
|
||
|
||
class SpecError(Exception):
|
||
def __init__(self, errors: list[dict[str, str]]):
|
||
self.errors = errors
|
||
detail = "; ".join(f"{item['path']}: {item['message']}" for item in errors)
|
||
super().__init__(detail or "invalid show spec")
|
||
|
||
|
||
def show_schema() -> dict[str, Any]:
|
||
"""JSON Schema for the document accepted by validate_show and write_show."""
|
||
return {
|
||
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
||
"$id": "qlcplus://show",
|
||
"title": "QLC+ show",
|
||
"type": "object",
|
||
"description": (
|
||
"A QLC+ workspace. Fixture, function, and widget ids are assigned on write. "
|
||
"Refer to fixtures and functions by their string keys. Channel numbers come from list_fixtures. "
|
||
"Addresses are 0-based, matching QLC+ (address 87 is DMX channel 88). "
|
||
"Set stage to a stage map path to patch that rig; fixture keys are the map ids."
|
||
),
|
||
"properties": {
|
||
"stage": {
|
||
"type": "string",
|
||
"description": "Stage map inside the project, for example stage/map.json. Patches every fixture before fixtures.",
|
||
},
|
||
"author": {"type": "string"},
|
||
"vc_size": {
|
||
"type": "array",
|
||
"items": {"type": "integer"},
|
||
"minItems": 2,
|
||
"maxItems": 2,
|
||
"description": "Virtual console width and height. Omitted means fit the widgets plus a 16px margin.",
|
||
},
|
||
"run": {
|
||
"type": "array",
|
||
"items": {"type": "string"},
|
||
"description": "Function keys to play when the show is run as a script. Defaults to every top-level function.",
|
||
},
|
||
"universes": {"type": "array", "items": {"$ref": "#/$defs/universe"}},
|
||
"fixtures": {"type": "array", "items": {"$ref": "#/$defs/fixture"}},
|
||
"groups": {"type": "array", "items": {"$ref": "#/$defs/group"}},
|
||
"functions": {"type": "array", "items": {"$ref": "#/$defs/function"}},
|
||
"vc": {"type": "array", "items": {"$ref": "#/$defs/widget"}},
|
||
},
|
||
"$defs": {
|
||
"universe": {
|
||
"type": "object",
|
||
"required": ["id"],
|
||
"properties": {
|
||
"id": {"type": "integer", "minimum": 0},
|
||
"name": {"type": "string"},
|
||
"output": {
|
||
"type": "object",
|
||
"required": ["uid", "ip"],
|
||
"properties": {
|
||
"plugin": {"const": "ArtNet"},
|
||
"uid": {"type": "string"},
|
||
"ip": {"type": "string"},
|
||
"universe": {"type": "integer"},
|
||
"line": {"type": "integer"},
|
||
},
|
||
},
|
||
"input": {
|
||
"type": "object",
|
||
"required": ["uid", "profile"],
|
||
"properties": {
|
||
"plugin": {"const": "MIDI"},
|
||
"uid": {"type": "string"},
|
||
"profile": {"type": "string"},
|
||
"channel": {"type": "integer", "description": "QLC+ MIDI plugin channel. 16 is omni."},
|
||
"line": {"type": "integer"},
|
||
},
|
||
},
|
||
},
|
||
},
|
||
"fixture": {
|
||
"type": "object",
|
||
"required": ["key", "manufacturer", "model", "mode", "address"],
|
||
"properties": {
|
||
"key": {"type": "string"},
|
||
"manufacturer": {"type": "string"},
|
||
"model": {"type": "string"},
|
||
"mode": {"type": "string"},
|
||
"name": {"type": "string"},
|
||
"universe": {"type": "integer"},
|
||
"address": {"type": "integer", "minimum": 0},
|
||
"channels": {"type": "integer", "minimum": 1, "description": "Required only when the fixture is not in the library."},
|
||
},
|
||
},
|
||
"group": {
|
||
"type": "object",
|
||
"required": ["name", "fixtures"],
|
||
"properties": {
|
||
"name": {"type": "string"},
|
||
"fixtures": {"type": "array", "items": {"type": "string"}},
|
||
"columns": {"type": "integer", "minimum": 1},
|
||
},
|
||
},
|
||
"function": {
|
||
"type": "object",
|
||
"required": ["key", "type", "name"],
|
||
"description": "type is scene, efx, sequence, path, chaser, colour_chase, or collection.",
|
||
"properties": {
|
||
"key": {"type": "string"},
|
||
"type": {"enum": ["scene", "efx", "sequence", "path", "chaser", "colour_chase", "collection"]},
|
||
"name": {"type": "string"},
|
||
},
|
||
},
|
||
"widget": {
|
||
"type": "object",
|
||
"required": ["type", "caption", "x", "y", "w", "h"],
|
||
"properties": {
|
||
"type": {"enum": ["slider", "button", "xypad", "frame", "solo"]},
|
||
"caption": {"type": "string"},
|
||
"x": {"type": "integer"},
|
||
"y": {"type": "integer"},
|
||
"w": {"type": "integer"},
|
||
"h": {"type": "integer"},
|
||
"fg": {"$ref": "#/$defs/colour"},
|
||
"bg": {"$ref": "#/$defs/colour"},
|
||
"function": {"type": "string", "description": "Function key for a button."},
|
||
"fixture": {"type": "string", "description": "Fixture key for an XY pad."},
|
||
"channels": {
|
||
"type": "array",
|
||
"items": {
|
||
"type": "array",
|
||
"prefixItems": [{"type": "string"}, {"type": "integer"}],
|
||
"minItems": 2,
|
||
"maxItems": 2,
|
||
},
|
||
},
|
||
"input": {
|
||
"type": "object",
|
||
"properties": {
|
||
"universe": {"type": "integer"},
|
||
"note": {"type": "array", "items": {"type": "integer"}, "minItems": 2, "maxItems": 2},
|
||
"cc": {"type": "array", "items": {"type": "integer"}, "minItems": 2, "maxItems": 2},
|
||
"channel": {"type": "integer"},
|
||
},
|
||
},
|
||
},
|
||
},
|
||
"colour": {
|
||
"description": "[r, g, b], or the string Default, or a QLC+ ARGB decimal.",
|
||
"oneOf": [
|
||
{"type": "array", "items": {"type": "integer"}, "minItems": 3, "maxItems": 3},
|
||
{"type": "string"},
|
||
{"type": "integer"},
|
||
],
|
||
},
|
||
},
|
||
}
|
||
|
||
|
||
def validate(data: Any, *, root: Path | None = None) -> None:
|
||
errors = collect_errors(data, root=root)
|
||
if errors:
|
||
raise SpecError(errors)
|
||
|
||
|
||
def collect_errors(data: Any, *, root: Path | None = None) -> list[dict[str, str]]:
|
||
errors: list[dict[str, str]] = []
|
||
if not isinstance(data, dict):
|
||
return [{"path": "", "message": "show spec must be an object"}]
|
||
project = root or PROJECT_ROOT
|
||
library = FixtureLibrary(project)
|
||
_check_universes(data.get("universes", []), errors)
|
||
fixtures = _check_stage(data.get("stage", None), project, library, errors)
|
||
for key, info in _check_fixtures(data.get("fixtures", []), library, errors).items():
|
||
if key in fixtures:
|
||
_err(errors, f"fixtures.{key}", "duplicate fixture key")
|
||
else:
|
||
fixtures[key] = info
|
||
keys = set(fixtures)
|
||
_check_groups(data.get("groups", []), keys, errors)
|
||
functions = data.get("functions", [])
|
||
fn_keys = _check_functions(functions, fixtures, errors)
|
||
_check_widgets(data.get("vc", []), keys, fn_keys, fixtures, errors, "vc")
|
||
run = data.get("run", [])
|
||
if run is not None and not isinstance(run, list):
|
||
_err(errors, "run", "must be a list of function keys")
|
||
elif isinstance(run, list):
|
||
for index, key in enumerate(run):
|
||
if key not in fn_keys:
|
||
_err(errors, f"run.{index}", f"unknown function {key!r}")
|
||
if "vc_size" in data:
|
||
size = data["vc_size"]
|
||
if not (isinstance(size, list) and len(size) == 2 and all(isinstance(n, int) for n in size)):
|
||
_err(errors, "vc_size", "must be [width, height]")
|
||
return errors
|
||
|
||
|
||
def from_spec(data: dict[str, Any], *, root: Path | None = None) -> Show:
|
||
validate(data, root=root)
|
||
try:
|
||
return _build(data, root=root)
|
||
except SpecError:
|
||
raise
|
||
except (ValueError, KeyError) as exc:
|
||
raise SpecError([{"path": "", "message": str(exc)}]) from exc
|
||
|
||
|
||
def _build(data: dict[str, Any], *, root: Path | None) -> Show:
|
||
show = Show(author=str(data.get("author") or "Jimmy"), root=root)
|
||
if "vc_size" in data:
|
||
show.vc_size = (int(data["vc_size"][0]), int(data["vc_size"][1]))
|
||
universes = data.get("universes")
|
||
if not universes:
|
||
for index in range(4):
|
||
show.universe(index, f"Universe {index + 1}")
|
||
else:
|
||
for uni in universes:
|
||
output = None
|
||
midi = None
|
||
if uni.get("output"):
|
||
out = uni["output"]
|
||
output = ArtNetOutput(
|
||
uid=str(out["uid"]),
|
||
ip=str(out["ip"]),
|
||
universe=int(out.get("universe", 0)),
|
||
line=int(out.get("line", 0)),
|
||
)
|
||
if uni.get("input"):
|
||
inp = uni["input"]
|
||
midi = MidiInput(
|
||
uid=str(inp["uid"]),
|
||
profile=str(inp["profile"]),
|
||
channel=int(inp.get("channel", 0)),
|
||
line=int(inp.get("line", 0)),
|
||
)
|
||
show.universe(int(uni["id"]), uni.get("name"), output=output, midi=midi)
|
||
if data.get("stage"):
|
||
show.patch_stage(data["stage"])
|
||
for fx in data.get("fixtures", []):
|
||
show.patch(
|
||
fx["manufacturer"],
|
||
fx["model"],
|
||
fx["mode"],
|
||
address=int(fx["address"]),
|
||
name=fx.get("name"),
|
||
universe=int(fx.get("universe", 0)),
|
||
channels=int(fx["channels"]) if "channels" in fx else None,
|
||
key=fx["key"],
|
||
)
|
||
for group in data.get("groups", []):
|
||
show.group(group["name"], list(group["fixtures"]), columns=group.get("columns"))
|
||
pending = []
|
||
for fn in data.get("functions", []):
|
||
if fn["type"] in ("chaser", "collection"):
|
||
pending.append(fn)
|
||
else:
|
||
_add_function(show, fn)
|
||
while pending:
|
||
ready = [fn for fn in pending if _refs_ready(show, fn)]
|
||
if not ready:
|
||
missing = pending[0]
|
||
raise SpecError([{"path": f"functions.{missing['key']}", "message": "references a function that is not defined"}])
|
||
for fn in ready:
|
||
_add_function(show, fn)
|
||
pending = [fn for fn in pending if fn not in ready]
|
||
_add_widgets(show, show.vc, data.get("vc", []))
|
||
if data.get("run"):
|
||
show.run(*data["run"])
|
||
return show
|
||
|
||
|
||
Show.from_spec = staticmethod(from_spec) # type: ignore[method-assign]
|
||
|
||
|
||
def _refs_ready(show: Show, fn: dict[str, Any]) -> bool:
|
||
if fn["type"] == "collection":
|
||
return all(key in show.functions_by_key for key in fn.get("members", []))
|
||
return all(step["function"] in show.functions_by_key for step in fn.get("steps", []))
|
||
|
||
|
||
def _add_function(show: Show, fn: dict[str, Any]) -> None:
|
||
kind = fn["type"]
|
||
key = fn["key"]
|
||
name = fn["name"]
|
||
if kind == "scene":
|
||
show.scene(name, fn.get("values") or {}, key=key, fade_in=int(fn.get("fade_in", 0)), fade_out=int(fn.get("fade_out", 0)), duration=int(fn.get("duration", 0)))
|
||
elif kind == "efx":
|
||
show.efx(name, fn.get("fixtures") or [], key=key, **_efx_kwargs(fn))
|
||
elif kind == "sequence":
|
||
show.sequence(name, fn.get("steps") or [], key=key, direction=fn.get("direction", "Forward"), run_order=fn.get("run_order", "Loop"))
|
||
elif kind == "path":
|
||
show.path_sequence(
|
||
name,
|
||
fn.get("fixtures") or [],
|
||
fn.get("points") or [],
|
||
key=key,
|
||
smooth=bool(fn.get("smooth", False)),
|
||
subdivisions=int(fn.get("subdivisions", 6)),
|
||
closed=bool(fn.get("closed", True)),
|
||
direction=fn.get("direction", "Forward"),
|
||
run_order=fn.get("run_order", "Loop"),
|
||
)
|
||
elif kind == "colour_chase":
|
||
show.colour_chase(
|
||
name,
|
||
fn.get("fixtures") or [],
|
||
fn.get("channels") or {},
|
||
fn.get("frames") or [],
|
||
key=key,
|
||
fade_ms=int(fn.get("fade_ms", 0)),
|
||
hold_ms=int(fn.get("hold_ms", 0)),
|
||
run_order=fn.get("run_order", "Loop"),
|
||
)
|
||
elif kind == "chaser":
|
||
show.chaser(name, fn.get("steps") or [], key=key, direction=fn.get("direction", "Forward"), run_order=fn.get("run_order", "Loop"))
|
||
elif kind == "collection":
|
||
show.collection(name, list(fn.get("members") or []), key=key)
|
||
|
||
|
||
def _efx_kwargs(fn: dict[str, Any]) -> dict[str, Any]:
|
||
fields = (
|
||
"algorithm", "width", "height", "rotation", "start_offset",
|
||
"x_offset", "y_offset", "x_frequency", "y_frequency", "x_phase", "y_phase",
|
||
"duration_ms", "fade_in_ms", "fade_out_ms", "direction", "run_order", "propagation",
|
||
"relative", "homes",
|
||
)
|
||
return {field: fn[field] for field in fields if field in fn}
|
||
|
||
|
||
def _add_widgets(show: Show, frame: Any, widgets: list[dict[str, Any]]) -> None:
|
||
for widget in widgets:
|
||
kind = widget["type"]
|
||
box = dict(x=int(widget["x"]), y=int(widget["y"]), w=int(widget["w"]), h=int(widget["h"]))
|
||
binding = _binding(widget["input"]) if widget.get("input") else None
|
||
if kind == "slider":
|
||
frame.slider(
|
||
widget["caption"],
|
||
[(pair[0], int(pair[1])) for pair in widget.get("channels", [])],
|
||
value=int(widget.get("value", 0)),
|
||
fg=widget.get("fg", "Default"),
|
||
cng=str(widget.get("cng", "None")),
|
||
inverted=bool(widget.get("inverted", False)),
|
||
input=binding,
|
||
**box,
|
||
)
|
||
elif kind == "button":
|
||
frame.button(
|
||
widget["caption"],
|
||
widget["function"],
|
||
fg=widget.get("fg", "4294967295"),
|
||
bg=widget.get("bg", "Default"),
|
||
action=str(widget.get("action", "Toggle")),
|
||
input=binding,
|
||
**box,
|
||
)
|
||
elif kind == "xypad":
|
||
frame.xypad(
|
||
widget["caption"],
|
||
widget["fixture"],
|
||
reverse_pan=bool(widget.get("reverse_pan", False)),
|
||
reverse_tilt=bool(widget.get("reverse_tilt", False)),
|
||
pan=int(widget.get("pan", 128)),
|
||
tilt=int(widget.get("tilt", 128)),
|
||
input=binding,
|
||
**box,
|
||
)
|
||
else:
|
||
child = frame.frame(
|
||
widget["caption"],
|
||
solo=kind == "solo" or bool(widget.get("solo", False)),
|
||
header=bool(widget.get("header", True)),
|
||
**box,
|
||
)
|
||
_add_widgets(show, child, widget.get("children") or [])
|
||
|
||
|
||
def _binding(raw: dict[str, Any]) -> MidiBinding:
|
||
if "channel" in raw:
|
||
channel = int(raw["channel"])
|
||
elif "note" in raw:
|
||
channel = midi_note(int(raw["note"][0]), int(raw["note"][1]))
|
||
else:
|
||
channel = midi_cc(int(raw["cc"][0]), int(raw["cc"][1]))
|
||
return MidiBinding(int(raw["universe"]), channel)
|
||
|
||
|
||
def _check_universes(universes: Any, errors: list[dict[str, str]]) -> None:
|
||
if not isinstance(universes, list):
|
||
_err(errors, "universes", "must be a list")
|
||
return
|
||
for index, uni in enumerate(universes):
|
||
path = f"universes.{index}"
|
||
if not isinstance(uni, dict) or not isinstance(uni.get("id"), int):
|
||
_err(errors, path, "must be an object with an integer id")
|
||
continue
|
||
output = uni.get("output")
|
||
if output is not None:
|
||
if not isinstance(output, dict) or "uid" not in output or "ip" not in output:
|
||
_err(errors, f"{path}.output", "Art-Net output needs uid and ip")
|
||
midi = uni.get("input")
|
||
if midi is not None:
|
||
if not isinstance(midi, dict) or "uid" not in midi or "profile" not in midi:
|
||
_err(errors, f"{path}.input", "MIDI input needs uid and profile")
|
||
|
||
|
||
def _check_stage(
|
||
stage: Any,
|
||
root: Path,
|
||
library: FixtureLibrary,
|
||
errors: list[dict[str, str]],
|
||
) -> dict[str, dict[str, Any]]:
|
||
found: dict[str, dict[str, Any]] = {}
|
||
if stage is None:
|
||
return found
|
||
if not isinstance(stage, str) or not stage.strip():
|
||
_err(errors, "stage", "must be a path to a stage map")
|
||
return found
|
||
target = _stage_file(stage, root, errors)
|
||
if target is None:
|
||
return found
|
||
try:
|
||
document = json.loads(target.read_text(encoding="utf-8"))
|
||
except json.JSONDecodeError as exc:
|
||
_err(errors, "stage", f"invalid JSON: {exc}")
|
||
return found
|
||
if not isinstance(document, dict):
|
||
_err(errors, "stage", "stage map must be an object")
|
||
return found
|
||
definitions = document.get("definitions")
|
||
fixtures = document.get("fixtures")
|
||
if not isinstance(definitions, dict) or not isinstance(fixtures, dict):
|
||
_err(errors, "stage", "stage map needs definitions and fixtures")
|
||
return found
|
||
for key, raw in fixtures.items():
|
||
path = f"stage.fixtures.{key}"
|
||
if not isinstance(raw, dict):
|
||
_err(errors, path, "must be an object")
|
||
continue
|
||
defin = definitions.get(raw.get("def"))
|
||
if not isinstance(defin, dict):
|
||
_err(errors, f"{path}.def", "unknown definition")
|
||
continue
|
||
if not isinstance(raw.get("address"), int) or raw["address"] < 0:
|
||
_err(errors, f"{path}.address", "must be an address of 0 or more")
|
||
continue
|
||
manufacturer = defin.get("manufacturer")
|
||
model = defin.get("model")
|
||
mode = defin.get("mode")
|
||
if not all(isinstance(item, str) and item for item in (manufacturer, model, mode)):
|
||
_err(errors, f"{path}.def", "definition needs manufacturer, model, and mode")
|
||
continue
|
||
definition = library.find(manufacturer, model)
|
||
mode_info = definition.mode(mode) if definition is not None else None
|
||
if mode_info is None:
|
||
_err(errors, path, f"unknown fixture {manufacturer} {model} mode {mode!r}")
|
||
continue
|
||
count = len(mode_info.channels)
|
||
if raw["address"] + count > 512:
|
||
_err(errors, f"{path}.address", "fixture extends past DMX channel 512")
|
||
if key in found:
|
||
_err(errors, path, "duplicate fixture key")
|
||
continue
|
||
found[key] = {"channels": count, "mover": mode_info.is_mover}
|
||
return found
|
||
|
||
|
||
def _stage_file(stage: str, root: Path, errors: list[dict[str, str]]) -> Path | None:
|
||
candidate = Path(stage)
|
||
base = root.resolve()
|
||
target = candidate.resolve() if candidate.is_absolute() else (base / candidate).resolve()
|
||
if target != base and base not in target.parents:
|
||
_err(errors, "stage", f"{stage} is outside the project")
|
||
return None
|
||
if not target.is_file():
|
||
_err(errors, "stage", f"stage map not found: {stage}")
|
||
return None
|
||
return target
|
||
|
||
|
||
def _check_fixtures(fixtures: Any, library: FixtureLibrary, errors: list[dict[str, str]]) -> dict[str, dict[str, Any]]:
|
||
found: dict[str, dict[str, Any]] = {}
|
||
if not isinstance(fixtures, list):
|
||
_err(errors, "fixtures", "must be a list")
|
||
return found
|
||
for index, fx in enumerate(fixtures):
|
||
path = f"fixtures.{index}"
|
||
if not isinstance(fx, dict):
|
||
_err(errors, path, "must be an object")
|
||
continue
|
||
key = fx.get("key")
|
||
if not isinstance(key, str) or not key:
|
||
_err(errors, f"{path}.key", "must be a non-empty string")
|
||
continue
|
||
path = f"fixtures.{key}"
|
||
if key in found:
|
||
_err(errors, path, "duplicate fixture key")
|
||
continue
|
||
for field in ("manufacturer", "model", "mode"):
|
||
if not isinstance(fx.get(field), str) or not fx[field]:
|
||
_err(errors, f"{path}.{field}", "must be a non-empty string")
|
||
if not isinstance(fx.get("address"), int) or fx["address"] < 0:
|
||
_err(errors, f"{path}.address", "must be an address of 0 or more")
|
||
continue
|
||
definition = None
|
||
if isinstance(fx.get("manufacturer"), str) and isinstance(fx.get("model"), str):
|
||
definition = library.find(fx["manufacturer"], fx["model"])
|
||
mode_info = definition.mode(fx["mode"]) if definition is not None and isinstance(fx.get("mode"), str) else None
|
||
if definition is None and "channels" not in fx:
|
||
_err(errors, path, "unknown fixture; add it under fixtures/ or set channels")
|
||
elif definition is not None and mode_info is None:
|
||
_err(errors, f"{path}.mode", f"unknown mode {fx.get('mode')!r}")
|
||
count = None
|
||
if mode_info is not None:
|
||
count = len(mode_info.channels)
|
||
if "channels" in fx and fx["channels"] != count:
|
||
_err(errors, f"{path}.channels", f"mode {fx['mode']} has {count} channels")
|
||
elif isinstance(fx.get("channels"), int) and fx["channels"] > 0:
|
||
count = fx["channels"]
|
||
elif "channels" in fx:
|
||
_err(errors, f"{path}.channels", "must be a positive integer")
|
||
if count is not None and fx["address"] + count > 512:
|
||
_err(errors, f"{path}.address", "fixture extends past DMX channel 512")
|
||
mover = bool(mode_info and mode_info.pan_msb is not None and mode_info.tilt_msb is not None)
|
||
found[key] = {"channels": count or 0, "mover": mover}
|
||
return found
|
||
|
||
|
||
def _check_groups(groups: Any, fixtures: set[str], errors: list[dict[str, str]]) -> None:
|
||
if not isinstance(groups, list):
|
||
_err(errors, "groups", "must be a list")
|
||
return
|
||
for index, group in enumerate(groups):
|
||
path = f"groups.{index}"
|
||
if not isinstance(group, dict) or not isinstance(group.get("name"), str):
|
||
_err(errors, path, "must be an object with a name")
|
||
continue
|
||
members = group.get("fixtures")
|
||
if not isinstance(members, list) or not members:
|
||
_err(errors, f"{path}.fixtures", "must list fixture keys")
|
||
continue
|
||
for member in members:
|
||
if member not in fixtures:
|
||
_err(errors, f"{path}.fixtures", f"unknown fixture {member!r}")
|
||
|
||
|
||
def _check_functions(
|
||
functions: Any,
|
||
fixtures: dict[str, dict[str, Any]],
|
||
errors: list[dict[str, str]],
|
||
) -> set[str]:
|
||
keys: set[str] = set()
|
||
if not isinstance(functions, list):
|
||
_err(errors, "functions", "must be a list")
|
||
return keys
|
||
for index, fn in enumerate(functions):
|
||
path = f"functions.{index}"
|
||
if not isinstance(fn, dict):
|
||
_err(errors, path, "must be an object")
|
||
continue
|
||
key = fn.get("key")
|
||
if not isinstance(key, str) or not key:
|
||
_err(errors, f"{path}.key", "must be a non-empty string")
|
||
continue
|
||
path = f"functions.{key}"
|
||
if key in keys:
|
||
_err(errors, path, "duplicate function key")
|
||
continue
|
||
keys.add(key)
|
||
kind = fn.get("type")
|
||
if kind not in ("scene", "efx", "sequence", "path", "chaser", "colour_chase", "collection"):
|
||
_err(errors, f"{path}.type", "must be scene, efx, sequence, path, chaser, colour_chase, or collection")
|
||
continue
|
||
if not isinstance(fn.get("name"), str) or not fn["name"]:
|
||
_err(errors, f"{path}.name", "must be a non-empty string")
|
||
if kind == "scene":
|
||
_check_values(fn.get("values") or {}, fixtures, errors, f"{path}.values")
|
||
elif kind == "efx":
|
||
_check_efx(fn, fixtures, errors, path)
|
||
elif kind == "sequence":
|
||
_check_sequence(fn, fixtures, errors, path)
|
||
elif kind == "path":
|
||
_check_path(fn, fixtures, errors, path)
|
||
elif kind == "colour_chase":
|
||
_check_chase(fn, fixtures, errors, path)
|
||
elif kind == "chaser":
|
||
_check_chaser_steps(fn.get("steps"), errors, path)
|
||
elif kind == "collection":
|
||
members = fn.get("members")
|
||
if not isinstance(members, list) or not members:
|
||
_err(errors, f"{path}.members", "must list function keys")
|
||
for fn in functions if isinstance(functions, list) else []:
|
||
if not isinstance(fn, dict) or fn.get("type") not in ("chaser", "collection"):
|
||
continue
|
||
path = f"functions.{fn.get('key')}"
|
||
if fn["type"] == "collection":
|
||
for member in fn.get("members") or []:
|
||
if member not in keys:
|
||
_err(errors, f"{path}.members", f"unknown function {member!r}")
|
||
else:
|
||
for index, step in enumerate(fn.get("steps") or []):
|
||
if isinstance(step, dict) and step.get("function") not in keys:
|
||
_err(errors, f"{path}.steps.{index}.function", f"unknown function {step.get('function')!r}")
|
||
return keys
|
||
|
||
|
||
def _check_values(values: Any, fixtures: dict[str, dict[str, Any]], errors: list[dict[str, str]], path: str) -> None:
|
||
if not isinstance(values, dict):
|
||
_err(errors, path, "must map fixture keys to channel values")
|
||
return
|
||
for key, channels in values.items():
|
||
if key not in fixtures:
|
||
_err(errors, f"{path}.{key}", f"unknown fixture {key!r}")
|
||
continue
|
||
if not isinstance(channels, dict):
|
||
_err(errors, f"{path}.{key}", "must map channel numbers to values")
|
||
continue
|
||
count = fixtures[key]["channels"]
|
||
for ch, val in channels.items():
|
||
try:
|
||
index = int(ch)
|
||
number = int(val)
|
||
except (TypeError, ValueError):
|
||
_err(errors, f"{path}.{key}.{ch}", "channel and value must be integers")
|
||
continue
|
||
if count and not 0 <= index < count:
|
||
_err(errors, f"{path}.{key}.{ch}", f"channel {index} is outside 0–{count - 1}")
|
||
if not 0 <= number <= 255:
|
||
_err(errors, f"{path}.{key}.{ch}", "value must be 0–255")
|
||
|
||
|
||
def _check_efx(fn: dict[str, Any], fixtures: dict[str, dict[str, Any]], errors: list[dict[str, str]], path: str) -> None:
|
||
entries = fn.get("fixtures")
|
||
if not isinstance(entries, list) or not entries:
|
||
_err(errors, f"{path}.fixtures", "must list fixture keys")
|
||
return
|
||
for item in entries:
|
||
key = item if isinstance(item, str) else item.get("fixture") if isinstance(item, dict) else None
|
||
if key not in fixtures:
|
||
_err(errors, f"{path}.fixtures", f"unknown fixture {key!r}")
|
||
elif not fixtures[key]["mover"]:
|
||
_err(errors, f"{path}.fixtures", f"{key} has no pan/tilt in this mode")
|
||
algorithm = fn.get("algorithm", "Circle")
|
||
if algorithm not in ALGORITHMS:
|
||
_err(errors, f"{path}.algorithm", f"must be one of {', '.join(ALGORITHMS)}")
|
||
_choice(errors, fn, "direction", DIRECTIONS, path, "Forward")
|
||
_choice(errors, fn, "run_order", RUN_ORDERS, path, "Loop")
|
||
_choice(errors, fn, "propagation", PROPAGATIONS, path, "Parallel")
|
||
_range(errors, fn, "width", 0, 127, path)
|
||
_range(errors, fn, "height", 0, 127, path)
|
||
_range(errors, fn, "x_offset", 0, 255, path)
|
||
_range(errors, fn, "y_offset", 0, 255, path)
|
||
_range(errors, fn, "x_frequency", 0, 5, path)
|
||
_range(errors, fn, "y_frequency", 0, 5, path)
|
||
if "duration_ms" in fn and (not isinstance(fn["duration_ms"], int) or fn["duration_ms"] < 20):
|
||
_err(errors, f"{path}.duration_ms", "must be at least 20")
|
||
homes = fn.get("homes") or {}
|
||
if homes and not isinstance(homes, dict):
|
||
_err(errors, f"{path}.homes", "must map fixture keys to [pan, tilt]")
|
||
elif isinstance(homes, dict):
|
||
for key, home in homes.items():
|
||
if key not in fixtures:
|
||
_err(errors, f"{path}.homes.{key}", f"unknown fixture {key!r}")
|
||
elif not (isinstance(home, list) and len(home) == 2 and all(isinstance(n, int) and 0 <= n <= 255 for n in home)):
|
||
_err(errors, f"{path}.homes.{key}", "must be [pan, tilt] in 0–255")
|
||
|
||
|
||
def _check_sequence(fn: dict[str, Any], fixtures: dict[str, dict[str, Any]], errors: list[dict[str, str]], path: str) -> None:
|
||
steps = fn.get("steps")
|
||
if not isinstance(steps, list) or not steps:
|
||
_err(errors, f"{path}.steps", "must be a list of steps")
|
||
return
|
||
_choice(errors, fn, "direction", DIRECTIONS, path, "Forward")
|
||
_choice(errors, fn, "run_order", RUN_ORDERS, path, "Loop")
|
||
for index, step in enumerate(steps):
|
||
if not isinstance(step, dict):
|
||
_err(errors, f"{path}.steps.{index}", "must be an object")
|
||
continue
|
||
_check_values(step.get("values") or {}, fixtures, errors, f"{path}.steps.{index}.values")
|
||
for field in ("fade_ms", "hold_ms", "fade_out_ms"):
|
||
if field in step and (not isinstance(step[field], int) or step[field] < 0):
|
||
_err(errors, f"{path}.steps.{index}.{field}", "must be 0 or more")
|
||
|
||
|
||
def _check_path(fn: dict[str, Any], fixtures: dict[str, dict[str, Any]], errors: list[dict[str, str]], path: str) -> None:
|
||
entries = fn.get("fixtures")
|
||
points = fn.get("points")
|
||
if not isinstance(entries, list) or not entries:
|
||
_err(errors, f"{path}.fixtures", "must list fixtures")
|
||
else:
|
||
for item in entries:
|
||
key = item if isinstance(item, str) else item.get("fixture") if isinstance(item, dict) else None
|
||
if key not in fixtures:
|
||
_err(errors, f"{path}.fixtures", f"unknown fixture {key!r}")
|
||
elif not fixtures[key]["mover"]:
|
||
_err(errors, f"{path}.fixtures", f"{key} has no pan/tilt in this mode")
|
||
if not isinstance(points, list) or not points:
|
||
_err(errors, f"{path}.points", "must list pan/tilt points")
|
||
else:
|
||
for index, point in enumerate(points):
|
||
if not isinstance(point, dict) or "pan" not in point or "tilt" not in point:
|
||
_err(errors, f"{path}.points.{index}", "must have pan and tilt")
|
||
_choice(errors, fn, "direction", DIRECTIONS, path, "Forward")
|
||
_choice(errors, fn, "run_order", RUN_ORDERS, path, "Loop")
|
||
|
||
|
||
def _check_chase(fn: dict[str, Any], fixtures: dict[str, dict[str, Any]], errors: list[dict[str, str]], path: str) -> None:
|
||
members = fn.get("fixtures")
|
||
frames = fn.get("frames")
|
||
channels = fn.get("channels")
|
||
if not isinstance(members, list) or not members:
|
||
_err(errors, f"{path}.fixtures", "must list fixture keys")
|
||
members = []
|
||
else:
|
||
for key in members:
|
||
if key not in fixtures:
|
||
_err(errors, f"{path}.fixtures", f"unknown fixture {key!r}")
|
||
if not isinstance(channels, dict) or not channels:
|
||
_err(errors, f"{path}.channels", "must map names such as r, g, b to channel numbers")
|
||
channels = {}
|
||
if not isinstance(frames, list) or not frames:
|
||
_err(errors, f"{path}.frames", "must list colour frames")
|
||
return
|
||
for index, frame in enumerate(frames):
|
||
if not isinstance(frame, list) or len(frame) != len(members):
|
||
_err(errors, f"{path}.frames.{index}", f"must have one colour for each of {len(members)} fixtures")
|
||
continue
|
||
for colour in frame:
|
||
if isinstance(colour, dict):
|
||
continue
|
||
if not isinstance(colour, list) or len(colour) != len(channels):
|
||
_err(errors, f"{path}.frames.{index}", f"colour must have {len(channels)} values")
|
||
break
|
||
if any(not isinstance(n, int) or not 0 <= n <= 255 for n in colour):
|
||
_err(errors, f"{path}.frames.{index}", "colour values must be 0–255")
|
||
|
||
|
||
def _check_chaser_steps(steps: Any, errors: list[dict[str, str]], path: str) -> None:
|
||
if not isinstance(steps, list) or not steps:
|
||
_err(errors, f"{path}.steps", "must list steps")
|
||
return
|
||
for index, step in enumerate(steps):
|
||
if not isinstance(step, dict) or not isinstance(step.get("function"), str):
|
||
_err(errors, f"{path}.steps.{index}.function", "must name a function key")
|
||
for field in ("fade_ms", "hold_ms", "fade_out_ms"):
|
||
if isinstance(step, dict) and field in step and (not isinstance(step[field], int) or step[field] < 0):
|
||
_err(errors, f"{path}.steps.{index}.{field}", "must be 0 or more")
|
||
|
||
|
||
def _check_widgets(
|
||
widgets: Any,
|
||
fixtures: set[str],
|
||
functions: set[str],
|
||
fixture_info: dict[str, dict[str, Any]],
|
||
errors: list[dict[str, str]],
|
||
path: str,
|
||
) -> None:
|
||
if not isinstance(widgets, list):
|
||
_err(errors, path, "must be a list")
|
||
return
|
||
for index, widget in enumerate(widgets):
|
||
here = f"{path}.{index}"
|
||
if not isinstance(widget, dict):
|
||
_err(errors, here, "must be an object")
|
||
continue
|
||
kind = widget.get("type")
|
||
if kind not in ("slider", "button", "xypad", "frame", "solo"):
|
||
_err(errors, f"{here}.type", "must be slider, button, xypad, frame, or solo")
|
||
continue
|
||
if not isinstance(widget.get("caption"), str):
|
||
_err(errors, f"{here}.caption", "must be a string")
|
||
for field in ("x", "y", "w", "h"):
|
||
if not isinstance(widget.get(field), int):
|
||
_err(errors, f"{here}.{field}", "must be an integer")
|
||
if kind == "slider":
|
||
channels = widget.get("channels")
|
||
if not isinstance(channels, list) or not channels:
|
||
_err(errors, f"{here}.channels", "must list [fixture, channel] pairs")
|
||
else:
|
||
for pair in channels:
|
||
if not (isinstance(pair, list) and len(pair) == 2 and isinstance(pair[1], int)):
|
||
_err(errors, f"{here}.channels", "each entry is [fixture key, channel]")
|
||
continue
|
||
if pair[0] not in fixtures:
|
||
_err(errors, f"{here}.channels", f"unknown fixture {pair[0]!r}")
|
||
elif fixture_info[pair[0]]["channels"] and not 0 <= pair[1] < fixture_info[pair[0]]["channels"]:
|
||
_err(errors, f"{here}.channels", f"channel {pair[1]} is outside {pair[0]}")
|
||
elif kind == "button":
|
||
if widget.get("function") not in functions:
|
||
_err(errors, f"{here}.function", f"unknown function {widget.get('function')!r}")
|
||
if "action" in widget and widget["action"] not in ("Toggle", "Flash"):
|
||
_err(errors, f"{here}.action", "must be Toggle or Flash")
|
||
elif kind == "xypad":
|
||
if widget.get("fixture") not in fixtures:
|
||
_err(errors, f"{here}.fixture", f"unknown fixture {widget.get('fixture')!r}")
|
||
elif not fixture_info[widget["fixture"]]["mover"]:
|
||
_err(errors, f"{here}.fixture", f"{widget['fixture']} has no pan/tilt in this mode")
|
||
else:
|
||
_check_widgets(widget.get("children") or [], fixtures, functions, fixture_info, errors, f"{here}.children")
|
||
if "input" in widget:
|
||
_check_input(widget["input"], errors, f"{here}.input")
|
||
for field in ("fg", "bg"):
|
||
if field in widget:
|
||
_check_colour(widget[field], errors, f"{here}.{field}")
|
||
|
||
|
||
def _check_input(raw: Any, errors: list[dict[str, str]], path: str) -> None:
|
||
if not isinstance(raw, dict) or not isinstance(raw.get("universe"), int):
|
||
_err(errors, path, "must have a universe")
|
||
return
|
||
kinds = [name for name in ("note", "cc", "channel") if name in raw]
|
||
if len(kinds) != 1:
|
||
_err(errors, path, "set one of note, cc, or channel")
|
||
return
|
||
if "note" in raw:
|
||
pair = raw["note"]
|
||
if not (isinstance(pair, list) and len(pair) == 2 and all(isinstance(n, int) for n in pair)):
|
||
_err(errors, f"{path}.note", "must be [channel 0–15, note 0–127]")
|
||
elif not 0 <= pair[0] <= 15 or not 0 <= pair[1] <= 127:
|
||
_err(errors, f"{path}.note", "must be [channel 0–15, note 0–127]")
|
||
elif "cc" in raw:
|
||
pair = raw["cc"]
|
||
if not (isinstance(pair, list) and len(pair) == 2 and all(isinstance(n, int) for n in pair)):
|
||
_err(errors, f"{path}.cc", "must be [channel 0–15, cc 0–127]")
|
||
elif not 0 <= pair[0] <= 15 or not 0 <= pair[1] <= 127:
|
||
_err(errors, f"{path}.cc", "must be [channel 0–15, cc 0–127]")
|
||
|
||
|
||
def _check_colour(value: Any, errors: list[dict[str, str]], path: str) -> None:
|
||
if isinstance(value, str) or isinstance(value, int):
|
||
return
|
||
if isinstance(value, list) and len(value) == 3 and all(isinstance(n, int) and 0 <= n <= 255 for n in value):
|
||
return
|
||
_err(errors, path, "must be [r, g, b], Default, or an ARGB decimal")
|
||
|
||
|
||
def _choice(errors: list[dict[str, str]], fn: dict[str, Any], field: str, allowed: tuple[str, ...], path: str, default: str) -> None:
|
||
value = fn.get(field, default)
|
||
if value not in allowed:
|
||
_err(errors, f"{path}.{field}", f"must be one of {', '.join(allowed)}")
|
||
|
||
|
||
def _range(errors: list[dict[str, str]], fn: dict[str, Any], field: str, lo: int, hi: int, path: str) -> None:
|
||
if field not in fn:
|
||
return
|
||
value = fn[field]
|
||
if not isinstance(value, int) or not lo <= value <= hi:
|
||
_err(errors, f"{path}.{field}", f"must be {lo}–{hi}")
|
||
|
||
|
||
def _err(errors: list[dict[str, str]], path: str, message: str) -> None:
|
||
errors.append({"path": path, "message": message})
|