Files
lightgui_rust/crates/xframe-widgets/generator/gen_data.py
T
Muse 76fad722d9 Add 15 XFrame monitor widgets (registry 547 -> 562)
New Archetype::Monitor (MonitorWidget, kind-dispatched draw) for
XHistoryGraph, XCoreGrid, XNetGraph, XTempHistory, XUsageBar,
XStackBar, XVerticalBar, XTachometer, XArcGauge, XDonutGauge,
XProcessList, XLoadBadge, XMonitorButton, XMonitorGrid, XSysBox.

- data/registry.json + data/palette.json: 15 entries, registry kept
  in sorted order (the C extractor requires it); palette Misc/X
  group re-sorted, other sections untouched, registry_index
  refreshed (XGraph 545->548, XSpreadsheet 546->555).
- crates/xframe-widgets/src/monitor.rs: stdlib-only live checks
  (/proc scan, systemctl is-active, TcpStream::connect_timeout),
  poll()/update() with a 2s staleness guard, deterministic demo
  seeding; unit tests incl. headless Canvas draw for all kinds.
- Placeholder 16x16 icons (assets/PROVENANCE.md notes they are
  placeholders pending the C port) + 15 demo examples + README
  monitor-family section (547 -> 562).
- xframe-common ico test tolerates the 15 monitor icons as
  pending until the C icons land (matched by name, not index).

cargo build --workspace: clean, warning-free. xframe-common lib
8/8, xframe-widgets lib 28/28, widget_tests 24/24, demo smoke
3/3, designer palette/seam 4/4 + 4/4 pass.
2026-12-05 17:30:17 +00:00

391 lines
18 KiB
Python

#!/usr/bin/env python3
"""Generate the xframe-widgets data tables from data/*.json.
Reads registry.json / props.json / events.json (the data agent's
extracts of lightgui eb0b5fc) and emits:
src/registry_gen.rs — the 547-entry registry + factory
src/props_gen.rs — enum tables + common props + per-type prop tables
src/events_gen.rs — per-type signal tables
Classification: each of the 562 widgets maps to one ARCHETYPE
(Button/Toggle/Label/Entry/Range/ListSel/Container/Chart/Indicator/
Instrument/Dialog/Display/Graph/Spreadsheet/Monitor) plus a `kind` string the
archetype uses to specialise its draw/behaviour. Rules are name-based
(GTK/Lazarus names ARE the semantic kind); family Ind is always
Indicator, family X is the two outliers. Run:
python3 generator/gen_data.py <data-dir> <src-dir>
"""
import json, os, re, sys
DATA = sys.argv[1] if len(sys.argv) > 1 else "/opt/lightgui_rust/data"
OUT = sys.argv[2] if len(sys.argv) > 2 else "/opt/lightgui_rust/crates/xframe-widgets/src"
reg = json.load(open(os.path.join(DATA, "registry.json")))
props = json.load(open(os.path.join(DATA, "props.json")))
events = json.load(open(os.path.join(DATA, "events.json")))
indicators = json.load(open(os.path.join(DATA, "indicators.json")))
# Widget -> [def name, line index] (or null when the widget has no fdi
# equivalent — see map_ind.py for how this was derived).
IND_MAP = json.load(open(os.path.join(os.path.dirname(os.path.abspath(__file__)), "ind_map.json")))
# ---------------------------------------------------------------- registry
# Ind widget name -> indicator def name: strip "Ind", then match the def
# name with spaces removed ("Bollinger Bands" -> "BollingerBands").
DEF_BY_CAMEL = {}
for d in indicators["indicators"]:
DEF_BY_CAMEL[d["name"].replace(" ", "")] = d["name"]
def rust_str(s):
return '"' + s.replace("\\", "\\\\").replace('"', '\\"') + '"'
def classify(w):
"""Return (archetype, kind, line) for a registry widget. `kind` is the
archetype's specialisation tag; for Indicator widgets it is the fdi
def name (or the widget's own stem when it has no fdi equivalent —
see ind_map.json), and `line` is the def line this widget displays
(None = all lines)."""
name, fam = w["name"], w["family"]
if fam == "Ind":
m = IND_MAP[name]
if m is None:
# No fdi equivalent: kind is the widget's own stem; the
# IndicatorWidget will have no def (bars + view only).
stem = re.sub(r"(?<!^)(?=[A-Z])", "_", name[3:]).lower()
return ("Indicator", stem, None)
return ("Indicator", m[0], m[1])
if name == "XGraph":
return ("Graph", "XGraph", None)
if name == "XSpreadsheet":
return ("Spreadsheet", "XSpreadsheet", None)
if name in (
"XHistoryGraph", "XCoreGrid", "XNetGraph", "XTempHistory",
"XUsageBar", "XStackBar", "XVerticalBar", "XTachometer",
"XArcGauge", "XDonutGauge", "XProcessList", "XLoadBadge",
"XMonitorButton", "XMonitorGrid", "XSysBox",
):
# The 15 btop-family monitor widgets (own module `monitor.rs`,
# one `MonitorWidget` struct, kind-dispatched like Instrument).
return ("Monitor", name[1:], None)
if fam == "Stock":
if name == "StockPriceLabel":
return ("Label", "Price", None)
return ("Chart", name[5:], None)
if fam == "Inst":
s = name[4:]
if s in ("PushButton", "EmergencyStop", "LampTestButton"):
return ("Button", s, None)
if s in ("PushButtonLatching", "ToggleSwitch",
"ToggleSwitchIlluminated", "SlideSwitch", "RockerSwitch",
"RockerSwitchDouble", "RockerSwitchIlluminated",
"KeySwitch", "CircuitBreaker"):
return ("Toggle", s, None)
if s == "RotarySelector":
return ("Range", "Rotary", None)
if s == "Nameplate":
return ("Label", "Nameplate", None)
if s in ("ControlPanel", "PanelPlate", "Bezel"):
return ("Container", s, None)
return ("Instrument", s, None)
if fam == "Gtk":
s = name[3:]
if s in ("AboutDialog", "AppChooserDialog", "ColorChooserDialog",
"Dialog", "FileChooserDialog", "FontChooserDialog",
"MessageDialog", "PrintUnixDialog", "ShortcutsWindow",
"Assistant"):
return ("Dialog", s, None)
if s in ("Button", "LinkButton", "LockButton", "MenuButton",
"ModelButton", "VolumeButton", "ToolButton",
"ToggleToolButton", "ColorButton", "FontButton",
"FileChooserButton", "AppChooserButton",
"ColorDialogButton"):
return ("Button", s, None)
if s in ("CheckButton", "ToggleButton", "Switch", "RadioButton",
"CheckMenuItem", "RadioMenuItem"):
return ("Toggle", s, None)
if s in ("Label", "AccelLabel", "Inscription"):
return ("Label", s, None)
if s in ("Entry", "SearchEntry", "PasswordEntry", "EditableLabel",
"TextView"):
return ("Entry", s, None)
if s in ("Scale", "Scrollbar", "ProgressBar", "LevelBar",
"ScaleButton", "SpinButton"):
return ("Range", s, None)
if s in ("ComboBox", "ComboBoxText", "DropDown", "ListBox",
"ListView", "TreeView", "ColumnView", "GridView",
"IconView", "FlowBox", "EntryCompletion", "MenuBar",
"Menu", "MenuItem", "StackSwitcher", "StackSidebar",
"Toolbar"):
return ("ListSel", s, None)
if s in ("Box", "Grid", "Fixed", "Frame", "Notebook", "Paned",
"Stack", "Overlay", "ScrolledWindow", "Viewport",
"Expander", "AspectFrame", "CenterBox", "ButtonBox",
"HeaderBar", "ActionBar", "InfoBar", "SearchBar",
"Statusbar", "Revealer", "EventBox", "Layout", "Window",
"ApplicationWindow", "PlacesSidebar", "Popover",
"Calendar", "AppChooserWidget", "ColorChooserWidget",
"FontChooserWidget", "FileChooserWidget"):
return ("Container", s, None)
if s in ("DrawingArea", "Image", "Picture", "Separator",
"SeparatorMenuItem", "Spinner", "Video", "GLArea",
"MediaControls", "CellView", "Invisible"):
return ("Display", s, None)
raise SystemExit(f"unclassified Gtk widget {name}")
if fam == "T":
s = name[1:]
if s in ("CalculatorDialog", "CalendarDialog", "FindDialog",
"ReplaceDialog", "OpenDialog", "SaveDialog",
"PrintDialog", "PrinterSetupDialog", "PageSetupDialog",
"ColorDialog", "FontDialog", "SelectDirectoryDialog",
"OpenPictureDialog", "SavePictureDialog", "TaskDialog"):
return ("Dialog", s, None)
if s in ("Button", "BitBtn", "SpeedButton", "EditButton",
"ColorButton"):
return ("Button", s, None)
if s in ("CheckBox", "RadioButton", "ToggleBox"):
return ("Toggle", s, None)
if s in ("Label", "StaticText"):
return ("Label", s, None)
if s in ("Edit", "MaskEdit", "CalcEdit", "DateEdit", "TimeEdit",
"DirectoryEdit", "FileNameEdit", "LabeledEdit", "Memo"):
return ("Entry", s, None)
if s in ("TrackBar", "ScrollBar", "ProgressBar", "UpDown",
"FloatSpinEdit", "SpinEdit"):
return ("Range", s, None)
if s in ("ListBox", "ComboBox", "ComboBoxEx", "CheckListBox",
"CheckGroup", "RadioGroup", "CheckComboBox",
"ColorListBox", "FileListBox", "ListView", "TreeView",
"ShellListView", "ShellTreeView", "ColorBox",
"MainMenu", "PopupMenu", "HeaderControl", "TabControl",
"FilterComboBox", "ValueListEditor"):
return ("ListSel", s, None)
if s in ("Form", "Panel", "GroupBox", "Frame", "FlowPanel",
"ControlBar", "CoolBar", "ScrollBox", "Splitter",
"PairSplitter", "ToolBar", "ButtonPanel", "Notebook",
"PageControl", "DrawGrid", "StringGrid", "StatusBar",
"Calendar", "DateTimePicker"):
return ("Container", s, None)
if s in ("Image", "ImageList", "Arrow", "Bevel", "Shape",
"PaintBox", "TrayIcon", "Timer", "ActionList",
"ApplicationProperties", "PopupNotifier"):
return ("Display", s, None)
raise SystemExit(f"unclassified T widget {name}")
raise SystemExit(f"unclassified {name} ({fam})")
def rust_ident(s):
return re.sub(r"[^A-Za-z0-9_]", "_", s)
# Task 3 — content minimum sizes (w, h) per widget type, measured from
# the widget's fixed content (drawn text rows, columns, grids, action bars).
# Placement uses max(registry default, content minimum) so the outer border
# encloses the contents at placement time. Same values as the C repo's
# widgets/tools/gen_registry.py MIN_SIZES.
MIN_SIZES = {
"GtkAboutDialog": (520, 260),
"GtkAssistant": (320, 280),
"GtkColorChooserDialog": (340, 240),
"GtkFileChooserDialog": (360, 240),
"GtkFontChooserDialog": (340, 240),
"GtkPrintUnixDialog": (360, 300),
"GtkShortcutsWindow": (320, 300),
"TCalendarDialog": (320, 280),
"TColorDialog": (520, 300),
"TFindDialog": (380, 260),
"TFontDialog": (320, 420),
"TOpenPictureDialog": (480, 240),
"TPageSetupDialog": (320, 400),
"TPrintDialog": (320, 300),
"TReplaceDialog": (360, 260),
"TSavePictureDialog": (480, 240),
"TSelectDirectoryDialog": (360, 260),
"TTaskDialog": (340, 280),
"GtkCalendar": (260, 200),
"TCalendar": (260, 200),
"GtkTreeView": (320, 200),
"TListView": (320, 200),
"TStringGrid": (360, 200),
"GtkAppChooserWidget": (320, 240),
"GtkColorChooserWidget": (340, 260),
"GtkFileChooserWidget": (340, 260),
"GtkFontChooserWidget": (340, 260),
}
entries = []
counts = {}
for w in reg["widgets"]:
# Task 3: placement size is max(registry default, content minimum).
mn = MIN_SIZES.get(w["name"])
if mn:
w["default_w"] = max(w["default_w"], mn[0])
w["default_h"] = max(w["default_h"], mn[1])
arch, kind, line = classify(w)
counts[arch] = counts.get(arch, 0) + 1
entries.append((w, arch, kind, line))
print("archetype counts:", dict(sorted(counts.items())))
print("total:", len(entries))
assert len(entries) == 562, len(entries)
# factory arm per archetype: the constructor each archetype uses.
FACTORY = {
"Button": "ButtonWidget::new",
"Toggle": "ToggleWidget::new",
"Label": "LabelWidget::new",
"Entry": "EntryWidget::new",
"Range": "RangeWidget::new",
"ListSel": "ListSelWidget::new",
"Container": "ContainerWidget::new",
"Chart": "ChartWidget::new",
"Indicator": "IndicatorWidget::new",
"Instrument": "InstrumentWidget::new",
"Dialog": "DialogWidget::new",
"Display": "DisplayWidget::new",
"Graph": "XGraph::new_widget",
"Spreadsheet": "XSpreadsheet::new_widget",
"Monitor": "MonitorWidget::new",
}
with open(os.path.join(OUT, "registry_gen.rs"), "w") as f:
f.write("//! Generated registry — DO NOT EDIT BY HAND.\n")
f.write("//! Generated by `generator/gen_data.py` from `data/registry.json`\n")
f.write("//! (lightgui eb0b5fc) plus the archetype classification in that\n")
f.write("//! script. Regenerate: `python3 generator/gen_data.py`.\n\n")
f.write("use crate::archetypes::*;\n")
f.write("use crate::graph::XGraph;\n")
f.write("use crate::spreadsheet::XSpreadsheet;\n")
f.write("use crate::monitor::MonitorWidget;\n")
f.write("use crate::widget::{Archetype, Widget};\n\n")
f.write("/// One of the 562 widgets: its registry row plus the archetype\n")
f.write("/// and kind the factory constructs.\n")
f.write("#[derive(Debug, Clone, Copy)]\n")
f.write("pub struct RegistryEntry {\n")
f.write(" pub index: usize,\n")
f.write(" pub name: &'static str,\n")
f.write(" pub family: &'static str,\n")
f.write(" pub section: &'static str,\n")
f.write(" pub section_index: usize,\n")
f.write(" pub default_w: i32,\n")
f.write(" pub default_h: i32,\n")
f.write(" pub archetype: Archetype,\n")
f.write(" pub kind: &'static str,\n")
f.write(" /// Def line this widget displays (multi-line defs only).\n")
f.write(" pub line: Option<usize>,\n")
f.write("}\n\n")
f.write("/// All 562 widgets, in registry order.\n")
f.write("pub static REGISTRY: &[RegistryEntry] = &[\n")
for w, arch, kind, line in entries:
line_s = "None" if line is None else f"Some({line})"
f.write(
f" RegistryEntry {{ index: {w['index']}, name: {rust_str(w['name'])}, "
f"family: {rust_str(w['family'])}, section: {rust_str(w['section'])}, "
f"section_index: {w['section_index']}, default_w: {w['default_w']}, "
f"default_h: {w['default_h']}, archetype: Archetype::{arch}, "
f"kind: {rust_str(kind)}, line: {line_s} }},\n"
)
f.write("];\n\n")
f.write("/// Look a widget up by exact name (case-sensitive, as in C++).\n")
f.write("pub fn find(name: &str) -> Option<&'static RegistryEntry> {\n")
f.write(" REGISTRY.iter().find(|e| e.name == name)\n")
f.write("}\n\n")
f.write("/// Construct a widget by name, at its registry default size.\n")
f.write("/// Returns `None` for an unknown name.\n")
f.write("pub fn create(name: &str) -> Option<Box<dyn Widget>> {\n")
f.write(" let e = find(name)?;\n")
f.write(" Some(match e.archetype {\n")
for arch in sorted(set(a for _, a, _, _ in entries)):
if arch == "Indicator":
# The registry line index is applied to the inner indicator
# widget after construction (it selects one line of a
# multi-line def, e.g. Donchian Upper=0).
f.write(" Archetype::Indicator => { let mut w = IndicatorWidget::new(e.name, e.kind, 0, 0, e.default_w, e.default_h); w.inner.line = e.line; Box::new(w) },\n")
continue
ctor = FACTORY[arch]
f.write(f" Archetype::{arch} => Box::new({ctor}(e.name, e.kind, 0, 0, e.default_w, e.default_h)),\n")
f.write(" })\n")
f.write("}\n")
# ---------------------------------------------------------------- props
def opt_f(v):
return "None" if v is None else f"Some({v})"
with open(os.path.join(OUT, "props_gen.rs"), "w") as f:
f.write("//! Generated property tables — DO NOT EDIT BY HAND.\n")
f.write("//! Generated by `generator/gen_data.py` from `data/props.json`\n")
f.write("//! (lightgui eb0b5fc). Regenerate: `python3 generator/gen_data.py`.\n\n")
f.write("use crate::props::{PropDef, PropKind};\n\n")
f.write("/// The 9 enum value tables (`kReliefValues`, ...): (name, values, labels).\n")
f.write("pub static ENUM_TABLES: &[(&str, &[i32], &[&str])] = &[\n")
for name, tab in props["enum_tables"].items():
labels = [x.strip() for x in tab["comment"].split(",")]
vals = ", ".join(str(v) for v in tab["values"])
labs = ", ".join(rust_str(x) for x in labels)
f.write(f" ({rust_str(name)}, &[{vals}], &[{labs}]),\n")
f.write("];\n\n")
f.write("/// Properties every widget has (background / foreground / tooltip).\n")
f.write("pub static COMMON_PROPS: &[PropDef] = &[\n")
for p in props["common_props"]:
f.write(f" PropDef::new({rust_str(p['name'])}, PropKind::{p['kind']}, {rust_str(p.get('default', ''))}),\n")
f.write("];\n\n")
def emit_prop(f, p):
kind = p["kind"]
lo = opt_f(p.get("lo"))
hi = opt_f(p.get("hi"))
tab = p.get("enum_values_table")
tab_s = "None" if tab is None else f"Some({rust_str(tab)})"
labs = p.get("enum_labels")
labs_s = "None" if labs is None else "&[" + ", ".join(rust_str(x) for x in labs) + "]"
labs_s = f"Some({labs_s})" if labs is not None else "None"
vals = p.get("enum_values")
vals_s = "None" if vals is None else "Some(&[" + ", ".join(str(v) for v in vals) + "])"
f.write(
f" PropDef {{ name: {rust_str(p['name'])}, kind: PropKind::{kind}, "
f"default: {rust_str(str(p.get('default', '')))}, lo: {lo}, hi: {hi}, "
f"enum_table: {tab_s}, enum_labels: {labs_s}, enum_values: {vals_s} }},\n"
)
f.write("/// Per-type property tables (35 types have one; Canvas has none).\n")
f.write("pub fn props_for(type_name: &str) -> &'static [PropDef] {\n")
f.write(" match type_name {\n")
for tname, plist in props["types"].items():
f.write(f" {rust_str(tname)} => &[\n")
for p in plist:
emit_prop(f, p)
f.write(" ],\n")
f.write(" _ => &[],\n")
f.write(" }\n")
f.write("}\n")
# ---------------------------------------------------------------- events
with open(os.path.join(OUT, "events_gen.rs"), "w") as f:
f.write("//! Generated signal tables — DO NOT EDIT BY HAND.\n")
f.write("//! Generated by `generator/gen_data.py` from `data/events.json`\n")
f.write("//! (lightgui eb0b5fc). Regenerate: `python3 generator/gen_data.py`.\n\n")
f.write("use crate::events::{EventKind, SignalDef};\n\n")
f.write("/// Per-type GTK signals (27 types have one).\n")
f.write("pub fn signals_for(type_name: &str) -> &'static [SignalDef] {\n")
f.write(" match type_name {\n")
for tname, slist in events["types"].items():
f.write(f" {rust_str(tname)} => &[\n")
for s in slist:
f.write(
f" SignalDef {{ signal: {rust_str(s['signal'])}, handler: {rust_str(s['handler'])}, "
f"label: {rust_str(s['label'])}, kind: EventKind::{s['kind']}, builtin: {str(s['builtin']).lower()} }},\n"
)
f.write(" ],\n")
f.write(" _ => &[],\n")
f.write(" }\n")
f.write("}\n\n")
f.write("/// Types with no widget-specific signal, and why.\n")
f.write("pub static TYPES_WITHOUT_EVENTS: &[(&str, &str)] = &[\n")
for tname, why in events["types_without_events"].items():
f.write(f" ({rust_str(tname)}, {rust_str(why)}),\n")
f.write("];\n")
print("wrote registry_gen.rs, props_gen.rs, events_gen.rs ->", OUT)