"""Shared helpers for the lightgui_rust data extractors. Every extractor reads the C++ sources in /opt/lightgui (read-only) and writes one JSON file under data/. Nothing here edits the C repo. Conventions: * LIGHTGUI_SRC env var (default /opt/lightgui) locates the C sources. * Every generated JSON file carries a "_provenance" object naming the source files, the source repo HEAD, and the exact command that regenerates it. No timestamps: regeneration is byte-identical unless a source changed. * Extractors VERIFY as they run (cross-checks against the on-disk component dirs, sections.py, gen_registry.py, registry.h, ...). Any mismatch is a hard failure, never a silent warning. """ import json import os import re import subprocess import sys SOURCE_REPO = "https://github.com/cnmcdee/lightgui" LIGHTGUI_SRC = os.environ.get("LIGHTGUI_SRC", "/opt/lightgui") RUST_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) DATA_DIR = os.path.join(RUST_ROOT, "data") TOOLS_DIR = os.path.dirname(os.path.abspath(__file__)) class ExtractError(Exception): """A source/derived-data mismatch. Generation must stop.""" def fail(msg): raise ExtractError(msg) def source_head(): """HEAD sha of the C repo (read-only git query).""" try: out = subprocess.run( ["git", "-C", LIGHTGUI_SRC, "rev-parse", "HEAD"], capture_output=True, text=True, timeout=30) if out.returncode == 0: return out.stdout.strip() except Exception: pass return "unknown" def provenance(source_files, generator): """Provenance block stamped into every generated JSON file.""" return { "source_repo": SOURCE_REPO, "source_head": source_head(), "source_files": sorted(source_files), "generated_by": generator, "regenerate": "make regen (or: %s)" % generator, "note": "Generated from the C++ sources — do not edit by hand.", } def write_json(path, data): os.makedirs(os.path.dirname(path), exist_ok=True) with open(path, "w") as f: json.dump(data, f, indent=2) f.write("\n") print("wrote %s" % path) def read_source(rel): with open(os.path.join(LIGHTGUI_SRC, rel)) as f: return f.read() # ---------------------------------------------------------------- C++ text def strip_line_comments(text): """Remove // comments, respecting double-quoted string literals.""" out = [] for line in text.splitlines(): buf = [] i = 0 in_str = False while i < len(line): c = line[i] if in_str: buf.append(c) if c == "\\" and i + 1 < len(line): buf.append(line[i + 1]) i += 2 continue if c == '"': in_str = False else: if c == '"': in_str = True buf.append(c) elif c == "/" and i + 1 < len(line) and line[i + 1] == "/": break else: buf.append(c) i += 1 out.append("".join(buf)) return "\n".join(out) def split_top_level(s): """Split on commas at depth 0, respecting double-quoted strings. Used for C++ braced initializer lists: {a, "b,c", {d, e}}. """ parts = [] buf = [] depth = 0 in_str = False i = 0 while i < len(s): c = s[i] if in_str: buf.append(c) if c == "\\" and i + 1 < len(s): buf.append(s[i + 1]) i += 2 continue if c == '"': in_str = False else: if c == '"': in_str = True buf.append(c) elif c in "{[(": depth += 1 buf.append(c) elif c in "}])": depth -= 1 buf.append(c) elif c == "," and depth == 0: parts.append("".join(buf)) buf = [] else: buf.append(c) i += 1 tail = "".join(buf).strip() if tail: parts.append(tail) return [p.strip() for p in parts] def braced_groups(body): """Top-level {...} groups inside a braced initializer body. Returns each group's inner text (without the outer braces). """ groups = [] i = 0 n = len(body) while i < n: if body[i] == "{": depth = 1 j = i + 1 in_str = False while j < n and depth > 0: c = body[j] if in_str: if c == "\\": j += 1 elif c == '"': in_str = False else: if c == '"': in_str = True elif c == "{": depth += 1 elif c == "}": depth -= 1 j += 1 groups.append(body[i + 1:j - 1]) i = j else: i += 1 return groups def table_body(text, decl_re): """Body of a `static const std::vector<...> name = { ... };` table. decl_re matches up to and including the opening brace; returns the text between that brace and its match. """ m = re.search(decl_re, text) if not m: return None start = m.end() # just past the opening brace depth = 1 j = start in_str = False while j < len(text) and depth > 0: c = text[j] if in_str: if c == "\\": j += 1 elif c == '"': in_str = False else: if c == '"': in_str = True elif c == "{": depth += 1 elif c == "}": depth -= 1 j += 1 return text[start:j - 1] def cpp_string(tok): """Decode one C++ double-quoted string literal (no concatenation).""" tok = tok.strip() if not (len(tok) >= 2 and tok.startswith('"') and tok.endswith('"')): fail("expected a C++ string literal, got: %r" % tok) body = tok[1:-1] return body.replace('\\"', '"').replace("\\\\", "\\") def cpp_string_concat(text): """Decode adjacent C++ string literals: "a" "b" -> "ab".""" parts = re.findall(r'"((?:[^"\\]|\\.)*)"', text) out = "".join(parts) return out.replace('\\"', '"').replace("\\\\", "\\") def parse_number(tok): tok = tok.strip() try: return int(tok) except ValueError: pass try: return float(tok) except ValueError: fail("expected a number, got: %r" % tok) def load_json(path): with open(path) as f: return json.load(f) def data_without_provenance(doc): return {k: v for k, v in doc.items() if k != "_provenance"} # ---------------------------------------------------------------- model.h def parse_ktypes(): """The 38 LightGUI designer types from src/model.h (kTypes). Each entry: key, palette button id (GtkBuilder id in ui/designer.ui), default width/height, phase1 flag. """ text = read_source("src/model.h") m = re.search(r"kTypes\[\] = \{(.*?)\};", text, re.S) if not m: fail("kTypes not found in src/model.h") entries = re.findall( r'\{\s*"([^"]+)",\s*"([^"]+)",\s*(\d+),\s*(\d+),\s*(true|false)\s*\}', m.group(1)) if not entries: fail("no kTypes entries parsed from src/model.h") out = [] for key, pal_id, w, h, phase1 in entries: out.append({ "key": key, "palette_id": pal_id, "default_w": int(w), "default_h": int(h), "phase1": phase1 == "true", }) if len(set(e["key"] for e in out)) != len(out): fail("duplicate keys in kTypes") if len(set(e["palette_id"] for e in out)) != len(out): fail("duplicate palette_ids in kTypes") return out