Add Pattern Studio, SMC-PAD MIDI helpers, and the current venue workspaces.
Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
1 parent
55a38478db
commit
12420bec93
19 files changed
+8954
No files matched your search
@@ -0,0 +1,272 @@
|
||||
"""Local HTTP server: static UI + small JSON API. Standard library only."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import mimetypes
|
||||
import re
|
||||
import traceback
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
from urllib.parse import parse_qs, urlparse
|
||||
|
||||
from .artnet import LivePreview
|
||||
from .efx import pattern_from_dict
|
||||
from .fixturedefs import FixtureLibrary
|
||||
from .qxw import Workspace, export_pattern
|
||||
|
||||
STATIC_DIR = Path(__file__).parent / "static"
|
||||
_SAFE_NAME = re.compile(r"[^A-Za-z0-9 _().#+-]+")
|
||||
|
||||
|
||||
class ApiError(Exception):
|
||||
def __init__(self, message: str, status: int = 400):
|
||||
super().__init__(message)
|
||||
self.status = status
|
||||
|
||||
|
||||
class Studio:
|
||||
"""Application state shared by all requests."""
|
||||
|
||||
def __init__(self, root: Path, shows_dir: str = "shows", patterns_dir: str = "patterns"):
|
||||
self.root = root.resolve()
|
||||
self.shows_dir = self.root / shows_dir
|
||||
self.patterns_dir = self.root / patterns_dir
|
||||
self.library = FixtureLibrary(self.root)
|
||||
self.live = LivePreview()
|
||||
|
||||
# -- helpers ---------------------------------------------------------------
|
||||
|
||||
def resolve(self, rel: str) -> Path:
|
||||
p = (self.root / rel).resolve()
|
||||
if self.root not in p.parents and p != self.root:
|
||||
raise ApiError("path is outside the project", 403)
|
||||
return p
|
||||
|
||||
def workspace(self, rel: str) -> Workspace:
|
||||
p = self.resolve(rel)
|
||||
if not p.is_file() or p.suffix != ".qxw":
|
||||
raise ApiError(f"not a workspace: {rel}", 404)
|
||||
return Workspace.load(p, self.library)
|
||||
|
||||
# -- API -------------------------------------------------------------------
|
||||
|
||||
def list_workspaces(self) -> dict[str, Any]:
|
||||
items = []
|
||||
if self.shows_dir.is_dir():
|
||||
for p in sorted(self.shows_dir.rglob("*.qxw"), key=lambda p: (len(p.parts), str(p).lower())):
|
||||
items.append({"path": str(p.relative_to(self.root)), "name": p.name, "folder": str(p.parent.relative_to(self.root))})
|
||||
return {"workspaces": items}
|
||||
|
||||
def get_workspace(self, q: dict[str, list[str]]) -> dict[str, Any]:
|
||||
return self.workspace(_one(q, "path")).to_dict()
|
||||
|
||||
def get_function(self, q: dict[str, list[str]]) -> dict[str, Any]:
|
||||
ws = self.workspace(_one(q, "path"))
|
||||
pat = ws.pattern_from_function(int(_one(q, "id")))
|
||||
if pat is None:
|
||||
raise ApiError("function is not an EFX or a pan/tilt Sequence", 404)
|
||||
return {"pattern": pat}
|
||||
|
||||
def sample(self, body: dict[str, Any]) -> dict[str, Any]:
|
||||
try:
|
||||
return pattern_from_dict(body["pattern"]).sample()
|
||||
except (KeyError, ValueError, TypeError) as exc:
|
||||
raise ApiError(f"bad pattern: {exc}") from exc
|
||||
|
||||
def export(self, body: dict[str, Any]) -> dict[str, Any]:
|
||||
ws = self.workspace(body["path"])
|
||||
out_rel = body.get("out_path")
|
||||
out_path = self.resolve(out_rel) if out_rel else None
|
||||
if out_path is not None and out_path.suffix != ".qxw":
|
||||
raise ApiError("out_path must end in .qxw")
|
||||
try:
|
||||
res = export_pattern(
|
||||
ws,
|
||||
body["pattern"],
|
||||
name=body.get("name") or body["pattern"].get("name") or "Mover Pattern",
|
||||
overwrite=bool(body.get("overwrite", True)),
|
||||
add_button=bool(body.get("add_button", False)),
|
||||
button_xy=tuple(body["button_xy"]) if body.get("button_xy") else None,
|
||||
out_path=out_path,
|
||||
backup=bool(body.get("backup", True)),
|
||||
)
|
||||
except (ValueError, KeyError) as exc:
|
||||
raise ApiError(str(exc)) from exc
|
||||
d = res.to_dict()
|
||||
d["path"] = str(res.path.relative_to(self.root))
|
||||
return d
|
||||
|
||||
# -- pattern library ---------------------------------------------------------
|
||||
|
||||
def list_patterns(self) -> dict[str, Any]:
|
||||
items = []
|
||||
if self.patterns_dir.is_dir():
|
||||
for p in sorted(self.patterns_dir.glob("*.json")):
|
||||
try:
|
||||
data = json.loads(p.read_text(encoding="utf-8"))
|
||||
except (OSError, json.JSONDecodeError):
|
||||
continue
|
||||
items.append({"file": p.name, "name": data.get("name", p.stem), "type": data.get("type", "efx"), "pattern": data})
|
||||
return {"patterns": items}
|
||||
|
||||
def save_pattern(self, body: dict[str, Any]) -> dict[str, Any]:
|
||||
pat = body["pattern"]
|
||||
name = (body.get("name") or pat.get("name") or "pattern").strip()
|
||||
pat["name"] = name
|
||||
pattern_from_dict(pat) # validate
|
||||
self.patterns_dir.mkdir(parents=True, exist_ok=True)
|
||||
fn = _SAFE_NAME.sub("", name).strip().replace(" ", "_") or "pattern"
|
||||
p = self.patterns_dir / f"{fn}.json"
|
||||
p.write_text(json.dumps(pat, indent=1) + "\n", encoding="utf-8")
|
||||
return {"file": p.name}
|
||||
|
||||
def delete_pattern(self, q: dict[str, list[str]]) -> dict[str, Any]:
|
||||
fn = Path(_one(q, "file")).name
|
||||
p = self.patterns_dir / fn
|
||||
if p.suffix != ".json" or not p.is_file():
|
||||
raise ApiError("no such pattern", 404)
|
||||
p.unlink()
|
||||
return {"deleted": fn}
|
||||
|
||||
# -- live Art-Net -------------------------------------------------------------
|
||||
|
||||
def live_start(self, body: dict[str, Any]) -> dict[str, Any]:
|
||||
ws = self.workspace(body["path"])
|
||||
try:
|
||||
pat = pattern_from_dict(body["pattern"])
|
||||
except (KeyError, ValueError, TypeError) as exc:
|
||||
raise ApiError(f"bad pattern: {exc}") from exc
|
||||
movers = {f.id for f in ws.fixtures if f.is_mover}
|
||||
for fx in pat.fixtures:
|
||||
if fx.id not in movers:
|
||||
raise ApiError(f"fixture {fx.id} is not a mover")
|
||||
if not pat.fixtures:
|
||||
raise ApiError("pattern has no fixtures")
|
||||
ip = body.get("ip") or next((a["ip"] for a in ws.artnet.values() if a.get("ip")), None)
|
||||
if not ip:
|
||||
raise ApiError("no Art-Net IP configured")
|
||||
uni = int(body.get("universe", next((a["universe"] for a in ws.artnet.values()), 0)))
|
||||
self.live.start(ws, pat, ip, uni)
|
||||
return self.live.status
|
||||
|
||||
def live_stop(self) -> dict[str, Any]:
|
||||
self.live.stop()
|
||||
return self.live.status
|
||||
|
||||
|
||||
def _one(q: dict[str, list[str]], key: str) -> str:
|
||||
v = q.get(key)
|
||||
if not v:
|
||||
raise ApiError(f"missing query parameter {key!r}")
|
||||
return v[0]
|
||||
|
||||
|
||||
class Handler(BaseHTTPRequestHandler):
|
||||
studio: Studio # set by make_server
|
||||
|
||||
server_version = "PatternStudio/0.1"
|
||||
|
||||
def log_message(self, fmt: str, *args: Any) -> None: # quieter default log
|
||||
if self.path.startswith("/api/sample"):
|
||||
return
|
||||
super().log_message(fmt, *args)
|
||||
|
||||
# -- plumbing ----------------------------------------------------------------
|
||||
|
||||
def _json(self, status: int, data: Any) -> None:
|
||||
raw = json.dumps(data).encode("utf-8")
|
||||
self.send_response(status)
|
||||
self.send_header("Content-Type", "application/json; charset=utf-8")
|
||||
self.send_header("Content-Length", str(len(raw)))
|
||||
self.send_header("Cache-Control", "no-store")
|
||||
self.end_headers()
|
||||
self.wfile.write(raw)
|
||||
|
||||
def _body(self) -> dict[str, Any]:
|
||||
n = int(self.headers.get("Content-Length") or 0)
|
||||
if n <= 0:
|
||||
return {}
|
||||
try:
|
||||
return json.loads(self.rfile.read(n).decode("utf-8"))
|
||||
except json.JSONDecodeError as exc:
|
||||
raise ApiError(f"invalid JSON: {exc}") from exc
|
||||
|
||||
def _static(self, rel: str) -> None:
|
||||
rel = rel.lstrip("/") or "index.html"
|
||||
p = (STATIC_DIR / rel).resolve()
|
||||
if STATIC_DIR.resolve() not in p.parents or not p.is_file():
|
||||
self.send_error(404)
|
||||
return
|
||||
ctype = mimetypes.guess_type(p.name)[0] or "application/octet-stream"
|
||||
raw = p.read_bytes()
|
||||
self.send_response(200)
|
||||
self.send_header("Content-Type", ctype if not ctype.startswith("text/") else f"{ctype}; charset=utf-8")
|
||||
self.send_header("Content-Length", str(len(raw)))
|
||||
self.send_header("Cache-Control", "no-store")
|
||||
self.end_headers()
|
||||
self.wfile.write(raw)
|
||||
|
||||
def _dispatch(self, method: str) -> None:
|
||||
url = urlparse(self.path)
|
||||
q = parse_qs(url.query)
|
||||
s = self.studio
|
||||
try:
|
||||
if not url.path.startswith("/api/"):
|
||||
if method != "GET":
|
||||
self.send_error(405)
|
||||
return
|
||||
if url.path == "/favicon.ico":
|
||||
self.send_response(204)
|
||||
self.end_headers()
|
||||
return
|
||||
self._static(url.path)
|
||||
return
|
||||
route = (method, url.path)
|
||||
if route == ("GET", "/api/workspaces"):
|
||||
self._json(200, s.list_workspaces())
|
||||
elif route == ("GET", "/api/workspace"):
|
||||
self._json(200, s.get_workspace(q))
|
||||
elif route == ("GET", "/api/function"):
|
||||
self._json(200, s.get_function(q))
|
||||
elif route == ("POST", "/api/sample"):
|
||||
self._json(200, s.sample(self._body()))
|
||||
elif route == ("POST", "/api/export"):
|
||||
self._json(200, s.export(self._body()))
|
||||
elif route == ("GET", "/api/patterns"):
|
||||
self._json(200, s.list_patterns())
|
||||
elif route == ("POST", "/api/patterns"):
|
||||
self._json(200, s.save_pattern(self._body()))
|
||||
elif route == ("DELETE", "/api/patterns"):
|
||||
self._json(200, s.delete_pattern(q))
|
||||
elif route == ("POST", "/api/live/start"):
|
||||
self._json(200, s.live_start(self._body()))
|
||||
elif route == ("POST", "/api/live/stop"):
|
||||
self._json(200, s.live_stop())
|
||||
elif route == ("GET", "/api/live/status"):
|
||||
self._json(200, s.live.status)
|
||||
else:
|
||||
self._json(404, {"error": f"no route {method} {url.path}"})
|
||||
except ApiError as exc:
|
||||
self._json(exc.status, {"error": str(exc)})
|
||||
except Exception as exc: # noqa: BLE001 — surface anything else to the UI
|
||||
traceback.print_exc()
|
||||
self._json(500, {"error": f"{type(exc).__name__}: {exc}"})
|
||||
|
||||
def do_GET(self) -> None: # noqa: N802
|
||||
self._dispatch("GET")
|
||||
|
||||
def do_POST(self) -> None: # noqa: N802
|
||||
self._dispatch("POST")
|
||||
|
||||
def do_DELETE(self) -> None: # noqa: N802
|
||||
self._dispatch("DELETE")
|
||||
|
||||
|
||||
def make_server(root: Path, host: str = "127.0.0.1", port: int = 8765) -> ThreadingHTTPServer:
|
||||
studio = Studio(root)
|
||||
handler = type("BoundHandler", (Handler,), {"studio": studio})
|
||||
server = ThreadingHTTPServer((host, port), handler)
|
||||
server.studio = studio # type: ignore[attr-defined]
|
||||
return server
|
||||
Reference in new issue
Block a user