449 lines
18 KiB
Python
449 lines
18 KiB
Python
"""Show engine: workspace XML, spec validation, animations, and the agent tools."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import json
|
|
import subprocess
|
|
import sys
|
|
import unittest
|
|
import xml.etree.ElementTree as ET
|
|
from pathlib import Path
|
|
|
|
from showfile import Show, midi_note
|
|
from showfile.play import load_show
|
|
from showfile.tools import list_fixtures, sample_animation, show_schema, validate_show, write_show
|
|
|
|
ROOT = Path(__file__).resolve().parents[1]
|
|
NS = {"q": "http://www.qlcplus.org/Workspace"}
|
|
|
|
|
|
def _xml(spec: dict) -> ET.Element:
|
|
show = Show.from_spec(spec)
|
|
return ET.fromstring(show.xml())
|
|
|
|
|
|
def _text(root: ET.Element, path: str) -> list[str]:
|
|
return [el.text or "" for el in root.findall(path, NS)]
|
|
|
|
|
|
class ShowFileTest(unittest.TestCase):
|
|
def spec(self) -> dict:
|
|
return {
|
|
"author": "Jimmy",
|
|
"universes": [
|
|
{
|
|
"id": 0,
|
|
"name": "Universe 1",
|
|
"output": {
|
|
"plugin": "ArtNet",
|
|
"uid": "192.168.1.92",
|
|
"ip": "192.168.1.228",
|
|
"universe": 0,
|
|
"line": 7,
|
|
},
|
|
}
|
|
],
|
|
"fixtures": [
|
|
{
|
|
"key": "m1",
|
|
"manufacturer": "Small Eye 7",
|
|
"model": "Mover",
|
|
"mode": "43 Channel",
|
|
"name": "Small Eye 7 #1",
|
|
"address": 0,
|
|
},
|
|
{
|
|
"key": "m2",
|
|
"manufacturer": "Small Eye 7",
|
|
"model": "Mover",
|
|
"mode": "43 Channel",
|
|
"name": "Small Eye 7 #2",
|
|
"address": 44,
|
|
},
|
|
{
|
|
"key": "can1",
|
|
"manufacturer": "beamZ",
|
|
"model": "BCC145",
|
|
"mode": "8 Channel",
|
|
"address": 87,
|
|
},
|
|
],
|
|
"functions": [
|
|
{
|
|
"key": "eight",
|
|
"type": "efx",
|
|
"name": "Figure of 8",
|
|
"algorithm": "Eight",
|
|
"fixtures": ["m1", "m2"],
|
|
"width": 40,
|
|
"height": 30,
|
|
"x_offset": 128,
|
|
"y_offset": 140,
|
|
"duration_ms": 8000,
|
|
},
|
|
{
|
|
"key": "rel",
|
|
"type": "efx",
|
|
"name": "Rel",
|
|
"algorithm": "Circle",
|
|
"fixtures": ["m1"],
|
|
"width": 20,
|
|
"height": 0,
|
|
"relative": True,
|
|
"homes": {"m1": [100, 140]},
|
|
"duration_ms": 4000,
|
|
},
|
|
{
|
|
"key": "focus",
|
|
"type": "sequence",
|
|
"name": "Colour Focus",
|
|
"run_order": "SingleShot",
|
|
"steps": [
|
|
{"fade_ms": 100, "values": {"m1": {"10": 0}}},
|
|
{"fade_ms": 100, "values": {"m1": {"10": 255}}},
|
|
],
|
|
},
|
|
{
|
|
"key": "sweep",
|
|
"type": "path",
|
|
"name": "Sweep",
|
|
"closed": False,
|
|
"fixtures": [{"fixture": "m2", "mirror_pan": True}],
|
|
"points": [
|
|
{"pan": 80, "tilt": 160, "fade_ms": 1000},
|
|
{"pan": 180, "tilt": 40, "fade_ms": 1000},
|
|
],
|
|
},
|
|
{"key": "red", "type": "scene", "name": "Red", "values": {"can1": {"2": 255, "4": 0}}},
|
|
{"key": "blue", "type": "scene", "name": "Blue", "values": {"can1": {"2": 0, "4": 255}}},
|
|
{
|
|
"key": "collapse",
|
|
"type": "chaser",
|
|
"name": "Ring Collapse",
|
|
"run_order": "SingleShot",
|
|
"steps": [
|
|
{"function": "red", "fade_ms": 100, "hold_ms": 0},
|
|
{"function": "blue", "fade_ms": 100, "hold_ms": 0},
|
|
],
|
|
},
|
|
{
|
|
"key": "cols",
|
|
"type": "colour_chase",
|
|
"name": "Can Chase",
|
|
"fixtures": ["can1"],
|
|
"channels": {"r": 2, "g": 3, "b": 4},
|
|
"fade_ms": 0,
|
|
"hold_ms": 100,
|
|
"frames": [[[255, 0, 0]], [[0, 0, 255]]],
|
|
},
|
|
],
|
|
"vc": [
|
|
{
|
|
"type": "slider",
|
|
"caption": "Dim",
|
|
"channels": [["can1", 0]],
|
|
"x": 10,
|
|
"y": 28,
|
|
"w": 44,
|
|
"h": 240,
|
|
"value": 255,
|
|
"fg": [255, 255, 255],
|
|
},
|
|
{
|
|
"type": "button",
|
|
"caption": "Red",
|
|
"function": "red",
|
|
"x": 20,
|
|
"y": 300,
|
|
"w": 110,
|
|
"h": 60,
|
|
"bg": [255, 0, 0],
|
|
"input": {"universe": 1, "note": [9, 36]},
|
|
},
|
|
{
|
|
"type": "xypad",
|
|
"caption": "M1",
|
|
"fixture": "m1",
|
|
"x": 10,
|
|
"y": 28,
|
|
"w": 240,
|
|
"h": 240,
|
|
},
|
|
{
|
|
"type": "solo",
|
|
"caption": "Looks",
|
|
"x": 0,
|
|
"y": 400,
|
|
"w": 200,
|
|
"h": 80,
|
|
"children": [
|
|
{
|
|
"type": "button",
|
|
"caption": "Blue",
|
|
"function": "blue",
|
|
"x": 4,
|
|
"y": 24,
|
|
"w": 60,
|
|
"h": 40,
|
|
}
|
|
],
|
|
},
|
|
],
|
|
"run": ["eight"],
|
|
}
|
|
|
|
def test_workspace_xml_has_patch_widgets_and_animations(self):
|
|
show = Show.from_spec(self.spec())
|
|
root = ET.fromstring(show.xml())
|
|
addresses = [int(el.text or "0") for el in root.findall(".//q:Fixture/q:Address", NS)]
|
|
self.assertEqual(addresses, [0, 44, 87])
|
|
output = root.find(".//q:Output", NS)
|
|
self.assertEqual(output.get("Plugin"), "ArtNet")
|
|
self.assertEqual(output.get("Line"), "7")
|
|
self.assertEqual(output.find("q:PluginParameters", NS).get("outputIP"), "192.168.1.228")
|
|
self.assertEqual(_text(root, ".//q:Algorithm"), ["Eight", "Circle"])
|
|
self.assertEqual(_text(root, ".//q:IsRelative"), ["0", "1"])
|
|
self.assertIn("127", _text(root, ".//q:Axis/q:Offset"))
|
|
self.assertIn("0,100", "".join(_text(root, ".//q:FixtureVal")))
|
|
steps = root.findall(".//q:Function[@Type='Sequence']/q:Step", NS)
|
|
joined = " ".join(step.text or "" for step in steps)
|
|
self.assertIn("0,175", joined)
|
|
self.assertIn("10,255", joined)
|
|
chaser = root.find(".//q:Function[@Name='Ring Collapse']", NS)
|
|
self.assertEqual(
|
|
[step.text for step in chaser.findall("q:Step", NS)],
|
|
[str(show.functions_by_key["red"].id), str(show.functions_by_key["blue"].id)],
|
|
)
|
|
self.assertEqual(show.summary()["functions"]["rel"]["type"], "Collection")
|
|
self.assertIsNotNone(root.find(".//q:SoloFrame", NS))
|
|
button = root.find(".//q:Button[@Caption='Red']", NS)
|
|
self.assertEqual(button.find("q:Input", NS).get("Channel"), str(midi_note(9, 36)))
|
|
self.assertEqual(button.find("q:Function", NS).get("ID"), str(show.functions_by_key["red"].id))
|
|
slider = root.find(".//q:Slider", NS)
|
|
self.assertEqual(slider.find("q:Level", NS).get("Value"), "255")
|
|
self.assertEqual(slider.find("q:Level/q:Channel", NS).text, "0")
|
|
|
|
def test_playback_moves_and_fades(self):
|
|
show = Show.from_spec(self.spec())
|
|
pans = {show_frame(show, t, ["eight"])["m1"][0] for t in range(0, 8000, 500)}
|
|
self.assertGreater(len(pans), 1)
|
|
self.assertEqual(show_frame(show, 0, ["eight"])["m1"][8], 255)
|
|
relative = {show_frame(show, t, ["rel"])["m1"][0] for t in range(0, 4000, 250)}
|
|
self.assertIn(100, relative)
|
|
self.assertGreater(len(relative), 1)
|
|
self.assertEqual(show_frame(show, 0, ["collapse"])["can1"][2], 0)
|
|
self.assertEqual(show_frame(show, 100, ["collapse"])["can1"][2], 255)
|
|
self.assertEqual(show_frame(show, 150, ["collapse"])["can1"], {2: 128, 4: 128})
|
|
self.assertEqual(show_frame(show, 200, ["collapse"])["can1"], {2: 0, 4: 255})
|
|
self.assertEqual(show_frame(show, 0, ["cols"])["can1"][2], 255)
|
|
self.assertEqual(show_frame(show, 100, ["cols"])["can1"][2], 0)
|
|
self.assertEqual(show_frame(show, 50, ["focus"])["m1"][10], 0)
|
|
self.assertEqual(show_frame(show, 150, ["focus"])["m1"][10], 128)
|
|
|
|
def test_validation_names_the_key_and_write_stays_inside_the_project(self):
|
|
result = validate_show(
|
|
{
|
|
"fixtures": [
|
|
{"key": "can1", "manufacturer": "beamZ", "model": "BCC145", "mode": "nope", "address": 0}
|
|
],
|
|
"functions": [{"key": "eight", "type": "efx", "name": "E", "fixtures": ["missing"]}],
|
|
}
|
|
)
|
|
self.assertFalse(result["ok"])
|
|
self.assertIn("fixtures.can1.mode", [item["path"] for item in result["errors"]])
|
|
self.assertIn("functions.eight.fixtures", [item["path"] for item in result["errors"]])
|
|
refused = write_show({}, "/tmp/showfile-outside.qxw")
|
|
self.assertFalse(refused["ok"])
|
|
self.assertFalse(Path("/tmp/showfile-outside.qxw").exists())
|
|
|
|
def test_tools_list_schema_sample_and_write(self):
|
|
fixtures = list_fixtures()
|
|
bcc = next(item for item in fixtures["fixtures"] if item["model"] == "BCC145")
|
|
mode = next(item for item in bcc["modes"] if item["name"] == "8 Channel")
|
|
self.assertEqual(mode["channels"][0]["name"], "Dimmer")
|
|
self.assertIn("fixtures", show_schema()["properties"])
|
|
sample = sample_animation(
|
|
{
|
|
"type": "efx",
|
|
"algorithm": "Eight",
|
|
"fixtures": ["m1", "m2"],
|
|
"width": 40,
|
|
"height": 30,
|
|
"duration_ms": 8000,
|
|
"relative": True,
|
|
"homes": {"m1": [128, 140], "m2": [100, 140]},
|
|
},
|
|
steps=8,
|
|
)
|
|
self.assertTrue(sample["ok"])
|
|
self.assertEqual([track["key"] for track in sample["tracks"]], ["m1", "m2"])
|
|
self.assertGreater(len({point[0] for point in sample["tracks"][0]["points"]}), 1)
|
|
target = ROOT / "shows" / "_showfile_test.qxw"
|
|
try:
|
|
written = write_show(self.spec(), "shows/_showfile_test.qxw")
|
|
self.assertTrue(written["ok"])
|
|
self.assertEqual(written["fixtures"]["can1"]["address"], 87)
|
|
self.assertEqual(written["functions"]["eight"]["type"], "EFX")
|
|
self.assertEqual(written["functions"]["rel"]["type"], "Collection")
|
|
self.assertTrue(target.is_file())
|
|
finally:
|
|
target.unlink(missing_ok=True)
|
|
|
|
def test_animation_script_dry_run(self):
|
|
show = load_show(ROOT / "scripts" / "anim_eight.py")
|
|
frames = [show_frame(show, t) for t in (0, 2000)]
|
|
self.assertNotEqual(frames[0]["m1"][2], frames[1]["m1"][2])
|
|
self.assertEqual(frames[0]["m1"][8], 255)
|
|
completed = subprocess.run(
|
|
[sys.executable, "-m", "showfile", "run", "scripts/anim_eight.py", "--seconds", "0.1"],
|
|
cwd=ROOT,
|
|
check=False,
|
|
capture_output=True,
|
|
text=True,
|
|
)
|
|
self.assertEqual(completed.returncode, 0, completed.stderr)
|
|
payload = json.loads(completed.stdout)
|
|
self.assertTrue(payload["ok"])
|
|
self.assertEqual(payload["functions"], ["eight"])
|
|
self.assertGreaterEqual(len(payload["samples"]), 1)
|
|
|
|
def test_simple_board_matches_the_stage_patch(self):
|
|
spec = json.loads((ROOT / "shows" / "simple.show.json").read_text(encoding="utf-8"))
|
|
show = Show.from_spec(spec)
|
|
root = ET.fromstring(show.xml())
|
|
addresses = [int(el.text or "0") for el in root.findall(".//q:Fixture/q:Address", NS)]
|
|
self.assertEqual(addresses, [87, 95, 103, 111, 119, 127, 135, 143, 0, 44])
|
|
captions = [el.get("Caption") for el in root.findall(".//q:XYPad", NS)]
|
|
self.assertEqual(captions, ["M1 Position", "M2 Position"])
|
|
sliders = root.findall(".//q:Slider", NS)
|
|
self.assertEqual(len(sliders), 50)
|
|
dim = next(el for el in sliders if el.get("Caption") == "C Dim")
|
|
self.assertEqual(dim.find("q:Level", NS).get("Value"), "255")
|
|
self.assertEqual(len(dim.findall("q:Level/q:Channel", NS)), 8)
|
|
self.assertEqual(
|
|
[el.get("Caption") for el in root.findall(".//q:Frame", NS) if el.get("Caption")],
|
|
["Cans individual RGBW", "Movers individual RGBW"],
|
|
)
|
|
size = root.find(".//q:Properties/q:Size", NS)
|
|
self.assertEqual((size.get("Width"), size.get("Height")), ("1654", "480"))
|
|
|
|
def test_stage_map_drives_the_whole_rig(self):
|
|
stage = json.loads((ROOT / "stage" / "map.json").read_text(encoding="utf-8"))
|
|
show = load_show(ROOT / "scripts" / "anim_stage.py")
|
|
self.assertEqual([fx.key for fx in show.fixtures], list(stage["fixtures"]))
|
|
for key, raw in stage["fixtures"].items():
|
|
fixture = show.fixtures_by_key[key]
|
|
self.assertEqual(fixture.address, raw["address"])
|
|
self.assertEqual(fixture.x, raw["x"])
|
|
self.assertEqual(fixture.y, raw["y"])
|
|
if "direction" in raw:
|
|
self.assertEqual(fixture.direction, raw["direction"])
|
|
if "zero" in raw:
|
|
self.assertEqual(fixture.zero, raw["zero"])
|
|
self.assertEqual(show.fixtures_by_key["#1"].channel("Red"), 2)
|
|
self.assertEqual(len(show.fixtures_by_key["M1"].named("Red")), 7)
|
|
self.assertEqual([group.name for group in show.groups], ["Cans", "Movers"])
|
|
from showfile.play import dmx_frames
|
|
|
|
frame = show_frame(show, 100)
|
|
dmx = dmx_frames(show, frame)
|
|
self.assertEqual(dmx[0][87], 255)
|
|
self.assertEqual(dmx[0][300 + 8], 255)
|
|
self.assertEqual(frame["M1"][show.fixtures_by_key["M1"].channel("Zoom")], 40)
|
|
colour = sum(
|
|
frame[key][2] + frame[key][3] + frame[key][4]
|
|
for key, raw in stage["fixtures"].items()
|
|
if raw["kind"] == "can"
|
|
)
|
|
self.assertGreater(colour, 0)
|
|
tracks = []
|
|
for key in ("M1", "M3"):
|
|
tracks.append([(show_frame(show, t)[key][0], show_frame(show, t)[key][2]) for t in range(0, 3000, 250)])
|
|
self.assertGreater(len(set(tracks[0])), 1)
|
|
self.assertNotEqual(tracks[0], tracks[1])
|
|
spec = Show.from_spec({"stage": "stage/map.json", "run": []})
|
|
self.assertEqual(spec.fixtures_by_key["M4"].address, 300)
|
|
self.assertEqual(spec.fixtures_by_key["#15"].address, 199)
|
|
missing = validate_show({"stage": "stage/no-such.json"})
|
|
self.assertFalse(missing["ok"])
|
|
self.assertEqual(missing["errors"][0]["path"], "stage")
|
|
outside = validate_show({"stage": "/etc/passwd"})
|
|
self.assertFalse(outside["ok"])
|
|
completed = subprocess.run(
|
|
[sys.executable, "-m", "showfile", "run", "scripts/anim_stage.py", "--seconds", "0.1"],
|
|
cwd=ROOT,
|
|
check=False,
|
|
capture_output=True,
|
|
text=True,
|
|
)
|
|
self.assertEqual(completed.returncode, 0, completed.stderr)
|
|
payload = json.loads(completed.stdout)
|
|
self.assertTrue(payload["ok"])
|
|
self.assertEqual(payload["functions"], ["stage"])
|
|
|
|
def test_mcp_lists_and_calls_a_tool(self):
|
|
proc = subprocess.Popen(
|
|
[sys.executable, "-m", "showfile.mcp"],
|
|
cwd=ROOT,
|
|
stdin=subprocess.PIPE,
|
|
stdout=subprocess.PIPE,
|
|
)
|
|
assert proc.stdin and proc.stdout
|
|
try:
|
|
_mcp(proc, {"jsonrpc": "2.0", "id": 1, "method": "initialize", "params": {}})
|
|
_mcp(proc, {"jsonrpc": "2.0", "method": "notifications/initialized"})
|
|
listed = _mcp(proc, {"jsonrpc": "2.0", "id": 2, "method": "tools/list"})
|
|
names = [tool["name"] for tool in listed["result"]["tools"]]
|
|
self.assertEqual(
|
|
names,
|
|
["list_fixtures", "show_schema", "validate_show", "write_show", "sample_animation", "run_animation"],
|
|
)
|
|
called = _mcp(
|
|
proc,
|
|
{
|
|
"jsonrpc": "2.0",
|
|
"id": 3,
|
|
"method": "tools/call",
|
|
"params": {"name": "list_fixtures", "arguments": {}},
|
|
},
|
|
)
|
|
body = json.loads(called["result"]["content"][0]["text"])
|
|
self.assertIn("BCC145", [item["model"] for item in body["fixtures"]])
|
|
finally:
|
|
if proc.stdin:
|
|
proc.stdin.close()
|
|
try:
|
|
proc.wait(timeout=2)
|
|
except subprocess.TimeoutExpired:
|
|
proc.kill()
|
|
proc.wait(timeout=5)
|
|
if proc.stdout:
|
|
proc.stdout.close()
|
|
|
|
|
|
def show_frame(show: Show, elapsed: float, keys: list[str] | None = None) -> dict:
|
|
from showfile import frame_at
|
|
|
|
return frame_at(show, elapsed, keys)
|
|
|
|
|
|
def _mcp(proc: subprocess.Popen, message: dict) -> dict:
|
|
data = json.dumps(message).encode()
|
|
assert proc.stdin and proc.stdout
|
|
proc.stdin.write(f"Content-Length: {len(data)}\r\n\r\n".encode() + data)
|
|
proc.stdin.flush()
|
|
if "id" not in message:
|
|
return {}
|
|
headers = {}
|
|
while True:
|
|
line = proc.stdout.readline()
|
|
if line in (b"\r\n", b"\n"):
|
|
break
|
|
key, _, value = line.decode().partition(":")
|
|
headers[key.strip().lower()] = value.strip()
|
|
return json.loads(proc.stdout.read(int(headers["content-length"])))
|
|
|
|
|
|
if __name__ == "__main__":
|
|
unittest.main()
|