Extract widget registry (547 widgets) from lightgui sources
Data, not hand-written code: tools/extract_registry.py reads widgets/common/registry.h and cross-checks it three ways - the on-disk widgets/components/ dirs, widgets/tools/sections.py, and the default_size() rule from gen_registry.py - failing on any drift. Re-derived counts (lightgui eb0b5fc): 547 widgets, 11 sections; families Gtk 102, Ind 250, Inst 66, Stock 37, T 90, X 2. The survey Stock 38 / Inst 67 counted the shared non-widget headers StockData.h / InstData.h; XGraph/XSpreadsheet form a sixth family X (2) the survey family table omitted. Includes the extraction harness: tools/common.py, extract_all.py, check.py (make check re-derives tables from the C++ sources and fails on drift), tools/README.md, and the top-level Makefile.
This commit is contained in:
1 parent
d8e45c82c2
commit
fb152b6e39
7 files changed
+6377
No files matched your search
@@ -0,0 +1,37 @@
|
||||
# lightgui_rust — generated data tables
|
||||
# The widget registry, palette, property/event tables and indicator
|
||||
# catalog are DATA extracted from the C++ sources in /opt/lightgui
|
||||
# (repo https://github.com/cnmcdee/lightgui, HEAD eb0b5fc). They are
|
||||
# never hand-edited: regenerate them with `make regen` and verify them
|
||||
# against the sources with `make check`.
|
||||
#
|
||||
# make regen — re-run every extractor, rewriting data/*.json
|
||||
# make check — re-derive every table from the C++ sources and fail
|
||||
# if any data/*.json disagrees (drift detection)
|
||||
# make check-<name> — check one table (registry|palette|props|events|indicators)
|
||||
|
||||
LIGHTGUI_SRC ?= /opt/lightgui
|
||||
PY ?= python3
|
||||
|
||||
.PHONY: regen check check-registry check-palette check-props check-events check-indicators
|
||||
|
||||
regen:
|
||||
LIGHTGUI_SRC=$(LIGHTGUI_SRC) $(PY) tools/extract_all.py
|
||||
|
||||
check:
|
||||
LIGHTGUI_SRC=$(LIGHTGUI_SRC) $(PY) tools/check.py
|
||||
|
||||
check-registry:
|
||||
LIGHTGUI_SRC=$(LIGHTGUI_SRC) $(PY) tools/check.py registry
|
||||
|
||||
check-palette:
|
||||
LIGHTGUI_SRC=$(LIGHTGUI_SRC) $(PY) tools/check.py palette
|
||||
|
||||
check-props:
|
||||
LIGHTGUI_SRC=$(LIGHTGUI_SRC) $(PY) tools/check.py props
|
||||
|
||||
check-events:
|
||||
LIGHTGUI_SRC=$(LIGHTGUI_SRC) $(PY) tools/check.py events
|
||||
|
||||
check-indicators:
|
||||
LIGHTGUI_SRC=$(LIGHTGUI_SRC) $(PY) tools/check.py indicators
|
||||
+5609
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,70 @@
|
||||
# tools/ — data extraction from the C++ sources
|
||||
|
||||
The widget catalog is DATA, not hand-written Rust. These Python scripts
|
||||
read the C++ sources in `/opt/lightgui` (read-only) and generate the
|
||||
JSON tables under `data/` that the Rust port builds from. Python is
|
||||
tooling here, not the product.
|
||||
|
||||
## Regenerate / verify
|
||||
|
||||
```sh
|
||||
make regen # re-run every extractor, rewriting data/*.json
|
||||
make check # re-derive every table from the C++ sources; exit 1 on drift
|
||||
```
|
||||
|
||||
`make check` requires all five tables to exist (the full state). While
|
||||
landing the tables one piece at a time, check one table instead:
|
||||
|
||||
```sh
|
||||
make check-registry | check-palette | check-props | check-events | check-indicators
|
||||
```
|
||||
|
||||
`LIGHTGUI_SRC` overrides the C source location (default `/opt/lightgui`).
|
||||
|
||||
## Extractors
|
||||
|
||||
| Script | Source(s) | Output | Contents |
|
||||
|---|---|---|---|
|
||||
| `extract_registry.py` | `widgets/common/registry.h`, `widgets/components/`, `widgets/tools/sections.py`, `widgets/tools/gen_registry.py` | `data/registry.json` | 547 widgets: name, family, section, default size, header path |
|
||||
| `extract_palette.py` | `src/xframe_palette.h`, `src/model.h`, `data/registry.json` | `data/palette.json` | 583 palette entries: 36 LightGUI + 547 XFrame |
|
||||
| `extract_props.py` | `src/props.h`, `src/model.h` | `data/props.json` | 6 PropKinds, 9 enum tables, 35 per-type tables (99 props), common props |
|
||||
| `extract_events.py` | `src/events.h`, `src/model.h` | `data/events.json` | 10 EventKinds, 27 per-type tables (32 events), 9 no-events notes |
|
||||
| `extract_indicators.py` | `src/indicators.h` | `data/indicators.json` | 250 indicator catalog entries (name, group, plot kind, style, colour, defaults, function) |
|
||||
|
||||
`common.py` holds the shared C++ parsing helpers (braced-initializer
|
||||
splitting, string literals, provenance stamping) and `parse_ktypes()`
|
||||
for the 36 LightGUI types in `src/model.h`. `extract_all.py` runs the
|
||||
five extractors in dependency order. `check.py` re-derives each table
|
||||
fresh and deep-compares it against the committed JSON.
|
||||
|
||||
## Guarantees
|
||||
|
||||
- **No hand edits.** Every generated file carries a `_provenance`
|
||||
block (source repo + HEAD, source files, regenerating command).
|
||||
Regeneration is byte-identical unless a source changed (no timestamps).
|
||||
- **Three-way cross-checks.** The registry extractor derives the same
|
||||
numbers from `registry.h`, the on-disk component directories,
|
||||
`sections.py`, and the `default_size()` rule, and fails if they
|
||||
disagree. The palette extractor verifies every entry against the
|
||||
registry (name set, index, section). Props/events verify full
|
||||
coverage of the 36 `kTypes` keys. Indicators verify every referenced
|
||||
compute function is defined in the header.
|
||||
- **Counts are derived, never hard-coded.** The scripts fail loudly
|
||||
on any mismatch instead of warning.
|
||||
|
||||
## Re-derived counts (lightgui eb0b5fc)
|
||||
|
||||
- Widgets: **547** — families Gtk 102, Ind 250, Inst 66, Stock 37,
|
||||
T 90, X 2. (The survey's Stock 38 / Inst 67 counted the shared
|
||||
non-widget headers `StockData.h` / `InstData.h`; the X family —
|
||||
XGraph, XSpreadsheet — was omitted from its family table.)
|
||||
- Sections: 11 — Windows & Dialogs 28, Containers & Layout 34,
|
||||
Buttons 24, Display 33, Text & Entry 28, Choosers 10, Views &
|
||||
Lists 17, Menus & Toolbars 16, Misc / X 4, Stock Market 287,
|
||||
Instrumentation 66.
|
||||
- Palette: **583** = 36 LightGUI + 547 XFrame.
|
||||
- PropKinds: 6. EventKinds: **10**, not 11 as the survey stated
|
||||
(Simple, SwitchPage, RowActivated, RowSelected, BufferChanged,
|
||||
DeleteEvent, Draw, ItemClicked, ItemActivate, CellChanged).
|
||||
- Indicators: **250** — averages 32, bands 28, momentum 52, volume 20,
|
||||
volatility 43, patterns 66, final 9.
|
||||
+128
@@ -0,0 +1,128 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Drift check: re-derive every data table from the C++ sources and
|
||||
fail if any data/*.json disagrees.
|
||||
|
||||
Each extractor already cross-checks the sources as it runs; this
|
||||
script additionally proves the committed JSON files are exactly what
|
||||
the current sources produce — so a hand-edit to a JSON file, or a
|
||||
change in the C repo that nobody regenerated for, is caught here.
|
||||
|
||||
Usage:
|
||||
python3 tools/check.py — check all five tables
|
||||
python3 tools/check.py registry — check one table
|
||||
make check — check all five tables
|
||||
|
||||
Exit code 0 = all present tables match the sources.
|
||||
Exit code 1 = a table is missing or disagrees (details printed).
|
||||
"""
|
||||
|
||||
import importlib
|
||||
import os
|
||||
import sys
|
||||
|
||||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||
from common import DATA_DIR, data_without_provenance, load_json
|
||||
|
||||
# name -> (extractor module, data file, expected provenance generator)
|
||||
CHECKS = {
|
||||
"registry": ("extract_registry", "registry.json",
|
||||
"python3 tools/extract_registry.py"),
|
||||
"palette": ("extract_palette", "palette.json",
|
||||
"python3 tools/extract_palette.py"),
|
||||
"props": ("extract_props", "props.json",
|
||||
"python3 tools/extract_props.py"),
|
||||
"events": ("extract_events", "events.json",
|
||||
"python3 tools/extract_events.py"),
|
||||
"indicators": ("extract_indicators", "indicators.json",
|
||||
"python3 tools/extract_indicators.py"),
|
||||
}
|
||||
|
||||
|
||||
def diff_paths(a, b, path=""):
|
||||
"""Yield human-readable paths where two JSON structures differ."""
|
||||
if type(a) is not type(b):
|
||||
yield "%s: type %s vs %s" % (path or "(root)",
|
||||
type(a).__name__, type(b).__name__)
|
||||
return
|
||||
if isinstance(a, dict):
|
||||
for k in sorted(set(a) | set(b)):
|
||||
if k not in a:
|
||||
yield "%s.%s: missing in fresh derivation" % (path, k)
|
||||
elif k not in b:
|
||||
yield "%s.%s: missing in committed file" % (path, k)
|
||||
else:
|
||||
yield from diff_paths(a[k], b[k], "%s.%s" % (path, k))
|
||||
elif isinstance(a, list):
|
||||
if len(a) != len(b):
|
||||
yield "%s: length %d (fresh) vs %d (committed)" % (
|
||||
path or "(root)", len(a), len(b))
|
||||
return
|
||||
for i, (x, y) in enumerate(zip(a, b)):
|
||||
yield from diff_paths(x, y, "%s[%d]" % (path, i))
|
||||
elif a != b:
|
||||
yield "%s: %r (fresh) vs %r (committed)" % (path, a, b)
|
||||
|
||||
|
||||
def check_one(name):
|
||||
module_name, data_file, generator = CHECKS[name]
|
||||
path = os.path.join(DATA_DIR, data_file)
|
||||
if not os.path.isfile(path):
|
||||
return ["%s: MISSING data file %s" % (name, path)]
|
||||
try:
|
||||
module = importlib.import_module(module_name)
|
||||
except ImportError as e:
|
||||
return ["%s: cannot import %s: %s" % (name, module_name, e)]
|
||||
try:
|
||||
fresh = module.build()
|
||||
except Exception as e:
|
||||
return ["%s: re-derivation failed: %s: %s"
|
||||
% (name, type(e).__name__, e)]
|
||||
committed = load_json(path)
|
||||
problems = []
|
||||
prov = committed.get("_provenance", {})
|
||||
if prov.get("generated_by") != generator:
|
||||
problems.append("%s: _provenance.generated_by is %r, expected %r"
|
||||
% (name, prov.get("generated_by"), generator))
|
||||
if sorted(prov.get("source_files", [])) != sorted(
|
||||
fresh["_provenance"]["source_files"]):
|
||||
problems.append("%s: _provenance.source_files changed: %r vs %r"
|
||||
% (name, prov.get("source_files"),
|
||||
fresh["_provenance"]["source_files"]))
|
||||
diffs = list(diff_paths(data_without_provenance(fresh),
|
||||
data_without_provenance(committed)))
|
||||
if diffs:
|
||||
problems.append("%s: %d difference(s) vs committed %s:"
|
||||
% (name, len(diffs), data_file))
|
||||
problems.extend(" " + d for d in diffs[:20])
|
||||
if len(diffs) > 20:
|
||||
problems.append(" ... and %d more" % (len(diffs) - 20))
|
||||
return problems
|
||||
|
||||
|
||||
def main():
|
||||
names = sys.argv[1:] or list(CHECKS)
|
||||
unknown = [n for n in names if n not in CHECKS]
|
||||
if unknown:
|
||||
print("check: unknown table(s): %s (valid: %s)"
|
||||
% (", ".join(unknown), ", ".join(CHECKS)), file=sys.stderr)
|
||||
return 2
|
||||
all_problems = []
|
||||
for name in names:
|
||||
problems = check_one(name)
|
||||
if problems:
|
||||
all_problems.extend(problems)
|
||||
print("check: %s: FAIL" % name)
|
||||
else:
|
||||
print("check: %s: OK" % name)
|
||||
if all_problems:
|
||||
print("\n".join(all_problems), file=sys.stderr)
|
||||
print("check: FAILED — regenerate with `make regen` "
|
||||
"or fix the drift above", file=sys.stderr)
|
||||
return 1
|
||||
print("check: all %d table(s) match the C++ sources"
|
||||
% len(names))
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
+283
@@ -0,0 +1,283 @@
|
||||
"""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 36 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
|
||||
@@ -0,0 +1,39 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Regenerate every data table from the C++ sources (data/*.json).
|
||||
|
||||
Runs the five extractors in dependency order:
|
||||
registry -> palette, props, events, indicators
|
||||
(palette cross-checks the registry; the others are independent but
|
||||
run after it for a stable order).
|
||||
|
||||
Usage: python3 tools/extract_all.py (or: make regen)
|
||||
"""
|
||||
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
HERE = os.path.dirname(os.path.abspath(__file__))
|
||||
EXTRACTORS = [
|
||||
"extract_registry.py",
|
||||
"extract_palette.py",
|
||||
"extract_props.py",
|
||||
"extract_events.py",
|
||||
"extract_indicators.py",
|
||||
]
|
||||
|
||||
|
||||
def main():
|
||||
env = dict(os.environ)
|
||||
for name in EXTRACTORS:
|
||||
r = subprocess.run([sys.executable, os.path.join(HERE, name)],
|
||||
env=env)
|
||||
if r.returncode != 0:
|
||||
print("extract_all: %s FAILED" % name, file=sys.stderr)
|
||||
return r.returncode
|
||||
print("extract_all: all data tables regenerated")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,211 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Extract the XFrame widget registry from the C++ sources into data/registry.json.
|
||||
|
||||
Sources (read-only, /opt/lightgui):
|
||||
- widgets/common/registry.h — canonical names, section index, default sizes
|
||||
- widgets/components/ — on-disk widget dirs (cross-check)
|
||||
- widgets/tools/sections.py — section assignment + accent colours
|
||||
- widgets/tools/gen_registry.py — default_size() rule (cross-check)
|
||||
|
||||
The registry is the single source of truth for the palette and layout
|
||||
apps: names are in sorted order and the index is the identity the
|
||||
palette -> layout selection file carries. This extractor derives the
|
||||
same numbers three independent ways (registry.h arrays, the component
|
||||
directories, sections.py + the default_size rule) and fails if they
|
||||
disagree — a stale registry.h must never silently ship.
|
||||
|
||||
Usage: python3 tools/extract_registry.py
|
||||
"""
|
||||
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
|
||||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||
from common import (DATA_DIR, LIGHTGUI_SRC, ExtractError, fail, provenance,
|
||||
read_source, write_json)
|
||||
|
||||
REGISTRY_H = "widgets/common/registry.h"
|
||||
GENERATOR = "python3 tools/extract_registry.py"
|
||||
|
||||
# Family by name prefix. Order matters: check the long prefixes first.
|
||||
# Gtk* — GTK-named controls re-implemented as hand-drawn X11 widgets
|
||||
# Ind* — stock-market indicators (each a widget + a formula)
|
||||
# Stock*— stock charts / drawing tools
|
||||
# Inst* — instrumentation (gauges, lamps, LEDs, tanks, switches, ...)
|
||||
# T* — Lazarus/Delphi-style controls
|
||||
# X* — XFrame-native extras (XGraph, XSpreadsheet)
|
||||
FAMILY_PREFIXES = ("Gtk", "Ind", "Stock", "Inst")
|
||||
|
||||
|
||||
def family_of(name):
|
||||
for p in FAMILY_PREFIXES:
|
||||
if name.startswith(p):
|
||||
return p
|
||||
if name.startswith("T"):
|
||||
return "T"
|
||||
if name.startswith("X"):
|
||||
return "X"
|
||||
fail("widget %r matches no known family prefix" % name)
|
||||
|
||||
|
||||
def is_widget_dir(name):
|
||||
d = os.path.join(LIGHTGUI_SRC, "widgets", "components", name)
|
||||
return (os.path.isdir(d)
|
||||
and os.path.isfile(os.path.join(d, name + ".h")))
|
||||
|
||||
|
||||
def component_names():
|
||||
cdir = os.path.join(LIGHTGUI_SRC, "widgets", "components")
|
||||
return sorted(n for n in os.listdir(cdir) if is_widget_dir(n))
|
||||
|
||||
|
||||
def parse_registry_h():
|
||||
text = read_source(REGISTRY_H)
|
||||
m = re.search(r"kWidgetCount\s*=\s*(\d+)", text)
|
||||
declared = int(m.group(1)) if m else None
|
||||
m = re.search(r"kWidgetNames\[kWidgetCount\] = \{(.*?)\};", text, re.S)
|
||||
if not m:
|
||||
fail("kWidgetNames not found in %s" % REGISTRY_H)
|
||||
names = re.findall(r'"([^"]+)"', m.group(1))
|
||||
m = re.search(r"kSectionNames\[kSectionCount\] = \{(.*?)\};", text, re.S)
|
||||
if not m:
|
||||
fail("kSectionNames not found in %s" % REGISTRY_H)
|
||||
sections = re.findall(r'"([^"]+)"', m.group(1))
|
||||
m = re.search(r"kWidgetSection\[kWidgetCount\] = \{(.*?)\};", text, re.S)
|
||||
if not m:
|
||||
fail("kWidgetSection not found in %s" % REGISTRY_H)
|
||||
wsec = [int(x) for x in re.findall(r"\d+", m.group(1))]
|
||||
m = re.search(r"kWidgetDefaultW\[kWidgetCount\] = \{([^}]*)\};", text)
|
||||
if not m:
|
||||
fail("kWidgetDefaultW not found in %s" % REGISTRY_H)
|
||||
defw = [int(x) for x in m.group(1).split(",") if x.strip()]
|
||||
m = re.search(r"kWidgetDefaultH\[kWidgetCount\] = \{([^}]*)\};", text)
|
||||
if not m:
|
||||
fail("kWidgetDefaultH not found in %s" % REGISTRY_H)
|
||||
defh = [int(x) for x in m.group(1).split(",") if x.strip()]
|
||||
return declared, names, sections, wsec, defw, defh
|
||||
|
||||
|
||||
def load_sections_module():
|
||||
"""Import the C repo's own sections.py + gen_registry.py (read-only).
|
||||
|
||||
This reuses the authoritative section assignment and default-size
|
||||
rule instead of duplicating them by hand.
|
||||
"""
|
||||
tools_dir = os.path.join(LIGHTGUI_SRC, "widgets", "tools")
|
||||
if tools_dir not in sys.path:
|
||||
sys.path.insert(0, tools_dir)
|
||||
import sections as secmod # noqa: E402
|
||||
import gen_registry as genmod # noqa: E402
|
||||
return secmod, genmod
|
||||
|
||||
|
||||
def build():
|
||||
declared, names, section_names, wsec, defw, defh = parse_registry_h()
|
||||
n = len(names)
|
||||
if declared != n:
|
||||
fail("kWidgetCount=%s but kWidgetNames has %d entries"
|
||||
% (declared, n))
|
||||
if not (len(wsec) == len(defw) == len(defh) == n):
|
||||
fail("registry arrays disagree: names=%d sections=%d W=%d H=%d"
|
||||
% (n, len(wsec), len(defw), len(defh)))
|
||||
if len(set(names)) != n:
|
||||
fail("duplicate widget names in registry.h")
|
||||
if names != sorted(names):
|
||||
fail("kWidgetNames is not in sorted order")
|
||||
|
||||
# Cross-check 1: the on-disk component directories.
|
||||
comps = component_names()
|
||||
if comps != names:
|
||||
only_disk = [c for c in comps if c not in set(names)]
|
||||
only_reg = [c for c in names if c not in set(comps)]
|
||||
fail("registry.h != components/ on disk: only-on-disk=%s only-in-registry=%s"
|
||||
% (only_disk[:10], only_reg[:10]))
|
||||
for name in names:
|
||||
hdr = os.path.join(LIGHTGUI_SRC, "widgets", "components",
|
||||
name, name + ".h")
|
||||
if not os.path.isfile(hdr):
|
||||
fail("missing header for %s: %s" % (name, hdr))
|
||||
|
||||
# Cross-check 2: section assignment from the C repo's sections.py.
|
||||
secmod, genmod = load_sections_module()
|
||||
errs = secmod.validate(names)
|
||||
if errs:
|
||||
fail("sections.py validation failed: %s" % errs[:10])
|
||||
if list(secmod.SECTIONS) != section_names:
|
||||
fail("section order differs: sections.py=%s registry.h=%s"
|
||||
% (secmod.SECTIONS, section_names))
|
||||
for i, name in enumerate(names):
|
||||
want = secmod.SECTIONS.index(secmod.section_of(name))
|
||||
if wsec[i] != want:
|
||||
fail("section mismatch for %s: registry=%d sections.py=%d (%s)"
|
||||
% (name, wsec[i], want, secmod.section_of(name)))
|
||||
|
||||
# Cross-check 3: default sizes from the C repo's default_size() rule.
|
||||
for i, name in enumerate(names):
|
||||
w, h = genmod.default_size(name)
|
||||
if (w, h) != (defw[i], defh[i]):
|
||||
fail("default size mismatch for %s: registry=%dx%d rule=%dx%d"
|
||||
% (name, defw[i], defh[i], w, h))
|
||||
|
||||
families = {}
|
||||
widgets = []
|
||||
for i, name in enumerate(names):
|
||||
fam = family_of(name)
|
||||
families[fam] = families.get(fam, 0) + 1
|
||||
widgets.append({
|
||||
"index": i,
|
||||
"name": name,
|
||||
"family": fam,
|
||||
"section": section_names[wsec[i]],
|
||||
"section_index": wsec[i],
|
||||
"default_w": defw[i],
|
||||
"default_h": defh[i],
|
||||
"header": "widgets/components/%s/%s.h" % (name, name),
|
||||
})
|
||||
|
||||
sections = []
|
||||
for si, sname in enumerate(section_names):
|
||||
count = sum(1 for w in widgets if w["section_index"] == si)
|
||||
color = secmod.SECTION_COLORS.get(sname)
|
||||
sections.append({
|
||||
"index": si,
|
||||
"name": sname,
|
||||
"color_rgb": list(color) if color else None,
|
||||
"count": count,
|
||||
})
|
||||
|
||||
data = {
|
||||
"_provenance": provenance(
|
||||
[REGISTRY_H, "widgets/tools/sections.py",
|
||||
"widgets/tools/gen_registry.py",
|
||||
"widgets/tools/widget_count.py"],
|
||||
GENERATOR),
|
||||
"widget_count": n,
|
||||
"section_count": len(section_names),
|
||||
"sections": sections,
|
||||
"families": dict(sorted(families.items())),
|
||||
"widgets": widgets,
|
||||
}
|
||||
if sum(families.values()) != n:
|
||||
fail("family counts sum to %d, expected %d"
|
||||
% (sum(families.values()), n))
|
||||
return data
|
||||
|
||||
|
||||
def main():
|
||||
try:
|
||||
data = build()
|
||||
except ExtractError as e:
|
||||
print("extract_registry: ERROR: %s" % e, file=sys.stderr)
|
||||
return 1
|
||||
write_json(os.path.join(DATA_DIR, "registry.json"), data)
|
||||
fams = ", ".join("%s %d" % kv for kv in sorted(data["families"].items()))
|
||||
print("registry: %d widgets (%s), %d sections"
|
||||
% (data["widget_count"], fams, data["section_count"]))
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
Reference in new issue
Block a user