"""Locate and read QLC+ fixture definitions (.qxf) and work out which channels in a mode are pan / tilt / dimmer / shutter / colour. """ from __future__ import annotations import os import re import xml.etree.ElementTree as ET from dataclasses import dataclass, field from functools import lru_cache from pathlib import Path NS = {"q": "http://www.qlcplus.org/FixtureDefinition"} DIMMER_PRESETS = {"IntensityMasterDimmer", "IntensityDimmer"} WHITE_PRESETS = {"IntensityWhite"} RGB_PRESETS = ("IntensityRed", "IntensityGreen", "IntensityBlue") @dataclass class ChannelInfo: index: int name: str preset: str | None group: str | None byte: int shutter_open: int | None = None # DMX value that opens the shutter, if a shutter channel @dataclass class ModeInfo: name: str channels: list[ChannelInfo] pan_msb: int | None = None pan_lsb: int | None = None tilt_msb: int | None = None tilt_lsb: int | None = None dimmers: list[int] = field(default_factory=list) shutters: list[tuple[int, int]] = field(default_factory=list) # (channel, open value) whites: list[int] = field(default_factory=list) reds: list[int] = field(default_factory=list) greens: list[int] = field(default_factory=list) blues: list[int] = field(default_factory=list) @property def is_mover(self) -> bool: return self.pan_msb is not None and self.tilt_msb is not None def preview_channels(self) -> dict[int, int]: """Channel values that make the head visibly lit (white, open, full).""" ch: dict[int, int] = {} for d in self.dimmers: ch[d] = 255 for s, v in self.shutters: ch[s] = v if self.whites: for w in self.whites: ch[w] = 255 else: for c in self.reds + self.greens + self.blues: ch[c] = 255 if not self.dimmers and not self.whites and not self.reds: # Nothing we recognise as intensity — fall back to every Intensity-group channel. for c in self.channels: if c.group == "Intensity" or (c.preset or "").startswith("Intensity"): ch[c.index] = 255 return ch def to_dict(self) -> dict: return { "name": self.name, "channel_count": len(self.channels), "pan_msb": self.pan_msb, "pan_lsb": self.pan_lsb, "tilt_msb": self.tilt_msb, "tilt_lsb": self.tilt_lsb, "dimmers": self.dimmers, "channels": [{"index": c.index, "name": c.name, "preset": c.preset, "group": c.group} for c in self.channels], } @dataclass class FixtureDef: path: Path manufacturer: str model: str type: str pan_max: int tilt_max: int modes: dict[str, ModeInfo] def mode(self, name: str) -> ModeInfo | None: if name in self.modes: return self.modes[name] # QLC+ sometimes stores "43 Channel" vs "43 Channel Mode" etc. — be lenient. key = name.strip().lower() for k, v in self.modes.items(): if k.strip().lower() == key: return v return None # ----------------------------------------------------------------------------- parse def _text(el: ET.Element | None, default: str = "") -> str: return (el.text or default) if el is not None else default def _parse_channel(el: ET.Element) -> ChannelInfo: name = el.get("Name", "") preset = el.get("Preset") group_el = el.find("q:Group", NS) group = _text(group_el) if group_el is not None else None byte = int(group_el.get("Byte", "0")) if group_el is not None else 0 if preset and group is None: # Presets imply the group; the ones we care about: if preset.startswith("Position"): group = "Pan" if "Pan" in preset else "Tilt" elif preset.startswith("Intensity"): group = "Intensity" elif preset.startswith("Shutter") or preset.startswith("Strobe"): group = "Shutter" if preset.endswith("Fine"): byte = 1 shutter_open = None if group == "Shutter" or (preset or "").startswith("Shutter"): caps = el.findall("q:Capability", NS) if (preset or "").startswith("Shutter") and not caps: shutter_open = 0 # QLC+ built-in shutter presets all start with "Open" for cap in caps: cp = cap.get("Preset", "") label = (cap.text or "").strip().lower() if cp == "ShutterOpen" or (not cp and label in ("open", "shutter open", "no function")): shutter_open = int(cap.get("Min", "0")) break return ChannelInfo(index=-1, name=name, preset=preset, group=group, byte=byte, shutter_open=shutter_open) def _resolve_mode(name: str, chans: list[ChannelInfo]) -> ModeInfo: m = ModeInfo(name=name, channels=chans) for c in chans: p = c.preset or "" if c.group == "Pan" or p in ("PositionPan", "PositionPanFine"): if c.byte == 1 or p.endswith("Fine"): m.pan_lsb = m.pan_lsb if m.pan_lsb is not None else c.index else: m.pan_msb = m.pan_msb if m.pan_msb is not None else c.index elif c.group == "Tilt" or p in ("PositionTilt", "PositionTiltFine"): if c.byte == 1 or p.endswith("Fine"): m.tilt_lsb = m.tilt_lsb if m.tilt_lsb is not None else c.index else: m.tilt_msb = m.tilt_msb if m.tilt_msb is not None else c.index elif p in DIMMER_PRESETS: m.dimmers.append(c.index) elif p in WHITE_PRESETS: m.whites.append(c.index) elif p == RGB_PRESETS[0]: m.reds.append(c.index) elif p == RGB_PRESETS[1]: m.greens.append(c.index) elif p == RGB_PRESETS[2]: m.blues.append(c.index) elif c.group == "Intensity" and not p: lname = c.name.lower() if "dimmer" in lname or "master" in lname or "bright" in lname: m.dimmers.append(c.index) if c.shutter_open is not None: m.shutters.append((c.index, c.shutter_open)) return m @lru_cache(maxsize=256) def load_fixture_def(path: str) -> FixtureDef: root = ET.parse(path).getroot() channels: dict[str, ChannelInfo] = {} for el in root.findall("q:Channel", NS): ci = _parse_channel(el) channels[ci.name] = ci phys = root.find("q:Physical", NS) focus = phys.find("q:Focus", NS) if phys is not None else None pan_max = int(focus.get("PanMax", "0")) if focus is not None else 0 tilt_max = int(focus.get("TiltMax", "0")) if focus is not None else 0 modes: dict[str, ModeInfo] = {} for mode_el in root.findall("q:Mode", NS): name = mode_el.get("Name", "") chans: list[ChannelInfo] = [] for ch_el in mode_el.findall("q:Channel", NS): base = channels.get((ch_el.text or "").strip()) if base is None: continue ci = ChannelInfo(**{**base.__dict__, "index": int(ch_el.get("Number", len(chans)))}) chans.append(ci) chans.sort(key=lambda c: c.index) modes[name] = _resolve_mode(name, chans) return FixtureDef( path=Path(path), manufacturer=_text(root.find("q:Manufacturer", NS)), model=_text(root.find("q:Model", NS)), type=_text(root.find("q:Type", NS)), pan_max=pan_max, tilt_max=tilt_max, modes=modes, ) # ----------------------------------------------------------------------------- locate _HEAD_RE = re.compile( rb"(.*?).*?(.*?)", re.S ) class FixtureLibrary: """Index of (manufacturer, model) → .qxf path across the usual search dirs.""" def __init__(self, project_root: Path, extra_dirs: list[Path] | None = None): self.dirs: list[Path] = [project_root / "fixtures"] self.dirs += extra_dirs or [] self.dirs.append(Path.home() / ".qlcplus" / "fixtures") for d in ("/usr/share/qlcplus/fixtures", "/usr/local/share/qlcplus/fixtures"): self.dirs.append(Path(d)) self._index: dict[tuple[str, str], Path] | None = None def _build_index(self) -> dict[tuple[str, str], Path]: idx: dict[tuple[str, str], Path] = {} for d in self.dirs: if not d.is_dir(): continue for dirpath, _dirs, files in os.walk(d): for fn in files: if not fn.endswith(".qxf"): continue p = Path(dirpath) / fn try: with open(p, "rb") as fh: head = fh.read(4096) except OSError: continue m = _HEAD_RE.search(head) if not m: continue key = (_unesc(m.group(1)).strip().lower(), _unesc(m.group(2)).strip().lower()) idx.setdefault(key, p) # first dir wins (project fixtures override system) return idx def find(self, manufacturer: str, model: str) -> FixtureDef | None: if self._index is None: self._index = self._build_index() p = self._index.get((manufacturer.strip().lower(), model.strip().lower())) if p is None: return None try: return load_fixture_def(str(p)) except ET.ParseError: return None def _unesc(b: bytes) -> str: s = b.decode("utf-8", "replace") return s.replace("&", "&").replace("<", "<").replace(">", ">").replace(""", '"').replace("'", "'")