Files
lightgui/widgets/tools/layout_to_lightgui.py
cnmcdee c31b4b6a8b Step 5: cut .fdj to XFrame-only, drop the GTK palette (547 XFrame entries)
Palette is XFrame-only: the 36 GTK widgets are gone from designer.ui
and main.cpp (547 entries from xframe_palette.h). .fdj holds only
XFrame widgets; on load a GTK/unknown type is skipped with a clear
message, never migrated. snapshot/load now go through the embedded
XFrame canvas; the GTK Item machinery stays only as selftest
scaffolding (legacy_gtk_snapshot) until it is removed in a follow-up.
Selftest phases 3-8 rewritten for the step-4 XFrame generator (4
files, lg::Holder markers, file-level + XFrame round-trips, GTK skip
rule, bad-file rejection). Palette/converter tests updated to 547;
xframe_palette.h regenerated (one stale comment line). Docs updated.
Also: selftest cleans scratch generation dirs first, and the cleanup
call assigns its return value (void cast does not silence
-Wunused-result for system() on this toolchain).
2026-11-30 00:42:10 +00:00

142 lines
5.1 KiB
Python
Executable File

#!/usr/bin/env python3
"""Convert a LightGUI layout file into a LightGUI project (.fdj).
The layout tool saves placed XFrame widgets as one line each:
<XFrameName> <x> <y> <width> <height>
(e.g. `GtkButton 40 40 120 30`, written by the old `lightgui_layout`
on `s` or by its SAVE script command). This converter writes a .fdj
project that the designer opens with File -> Open project. From there
the normal designer flow applies: File -> Generate C++ (XFrame),
Build with CMake, and debug with the stepping debugger (code window +
auto variables).
Step 5 (Nov 29, 2026): .fdj is XFrame-only, so the mapping is the
identity — the .fdj carries the XFrame class name as the widget type,
and the generated app instantiates the XFrame classes directly. Names
that are not in the registry (widgets/common/registry.h) are reported
and skipped, never forced into a wrong type. (The old GTK mapping —
136 of the 547 widgets to a nearest GTK counterpart — is gone with
the GTK palette.)
Usage:
layout_to_lightgui.py [--class-name Name] [--title Title]
<layout.txt> <out.fdj>
Exit codes: 0 = at least one widget mapped; 1 = usage/input error;
2 = layout parsed but nothing mapped.
"""
import argparse
import json
import os
import sys
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from widget_count import registry_names
REGISTRY = set(registry_names())
def parse_layout(path):
"""Return (entries, errors): entries are (name, x, y, w, h)."""
entries, errors = [], []
with open(path) as f:
for lineno, raw in enumerate(f, 1):
line = raw.strip()
if not line or line.startswith("#"):
continue
parts = line.split()
if len(parts) < 5:
errors.append(f"line {lineno}: expected 5 fields, got {len(parts)}: {line!r}")
continue
name = parts[0]
try:
x, y, w, h = (int(p) for p in parts[1:5])
except ValueError:
errors.append(f"line {lineno}: non-integer geometry: {line!r}")
continue
entries.append((name, x, y, max(1, w), max(1, h)))
return entries, errors
def convert(entries, class_name, title):
"""Build the .fdj dict; return (project, mapped, unmapped)."""
counters = {}
widgets = []
mapped, unmapped = [], []
max_right, max_bottom = 0, 0
for name, x, y, w, h in entries:
if name not in REGISTRY:
unmapped.append(name)
continue
counters[name] = counters.get(name, 0) + 1
wname = f"{name}_{counters[name]:03d}"
widgets.append({
"name": wname,
"type": name,
"x": x, "y": y, "width": w, "height": h,
# The label keeps the XFrame origin visible in the designer
# and in the generated code (the generator emits set_text
# for a "label" prop on most widget types).
"props": {"label": name},
"signals": [],
})
mapped.append(name)
max_right = max(max_right, x + w)
max_bottom = max(max_bottom, y + h)
project = {
"format": "lightgui",
"version": 1,
"window": {
"title": title,
"class_name": class_name,
"width": max(800, max_right + 20),
"height": max(600, max_bottom + 20),
"background": "",
"menubar": "",
},
"widgets": widgets,
}
return project, mapped, unmapped
def main(argv=None):
ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])
ap.add_argument("layout", help="layout file saved by lightgui_layout")
ap.add_argument("out", help="output .fdj project file")
ap.add_argument("--class-name", default="XFrameLayout",
help="generated window class name (default: XFrameLayout)")
ap.add_argument("--title", default="XFrame Layout",
help="window title (default: XFrame Layout)")
args = ap.parse_args(argv)
try:
entries, errors = parse_layout(args.layout)
except OSError as e:
print(f"layout_to_lightgui: cannot read {args.layout}: {e}", file=sys.stderr)
return 1
for e in errors:
print(f"layout_to_lightgui: warning: {e}", file=sys.stderr)
if not entries:
print("layout_to_lightgui: no widget entries found", file=sys.stderr)
return 1
project, mapped, unmapped = convert(entries, args.class_name, args.title)
with open(args.out, "w") as f:
json.dump(project, f, indent=2)
f.write("\n")
print(f"layout_to_lightgui: {len(entries)} entries, "
f"{len(mapped)} mapped to {len(project['widgets'])} XFrame widgets, "
f"{len(unmapped)} unmapped")
if unmapped:
print("unmapped (not XFrame widget names -- skipped, not forced):")
for name in sorted(set(unmapped)):
print(f" {name}")
print(f"wrote {args.out} "
f"(window {project['window']['width']}x{project['window']['height']})")
return 0 if mapped else 2
if __name__ == "__main__":
sys.exit(main())