Files
lightgui_python/lightgui/model.py
cnmcdee 7717194cbd Phase 2: faithful generic drawings + live-apply plumbing + tests
core.py: per-widget Cairo drawing inside the 14 archetypes, ported
from Rust archetypes.rs / C widget draws -- buttons (incl. link,
colour-swatch, lock, glyph, MenuButton direction arrow), toggles
(check/radio/switch/toggle-button/menu-check), labels (xalign/yalign,
wrap, accel stripping), entries (password masking, placeholder,
alignment, search/calc variants), text views (wrap modes, scrollbars,
cursor), ranges (scale with ticks/sel-range, scrollbar with thumb +
arrows, progress, spin, level bar), lists (combo, colour box, listbox,
checklistbox, tree, listview incl. icon style, menubar/menu, toolbar,
stack switcher), containers (frame/groupbox, notebook, calendar grid,
splitter, scrolled window, header/action bar, statusbar, window),
display (image scene, shape 0-9, separator, spinner, video,
drawing area), dialogs (title bar, file/color/about variants),
charts (line/bars/candles), spreadsheet grid. Drawings honour
background/foreground/border/font props; invisible draws nothing,
disabled dims. Pixel parity with C is NOT required.

Live-apply: Widget.set_prop validates against lightgui.props
(raises ValueError on unknown/bad/out-of-range props), updates
Name/geometry fields or props, marks the widget dirty and calls
on_change; CanvasState wires widget.on_change and clears dirty
after drawing. Widget setters: set_items (ComboBox/ListBox, prunes
CheckListBox checked-items), get/set_checked_items,
set_item_checked, set_password/set_show_password (masked until
revealed), set_direction (MenuButton), set_cursor_visible
(TextView), set_lower/set_page_increment (ScrollBar), set_value
(clamped), set_active, set_text (canonical caption prop).

model.py: caption seeding now uses the table's canonical prop
(label for Button/CheckBox, text for Entry); kinds with neither
get no seed.

tests: test_props.py (generic set on all 547 kinds, SS2.1-SS2.10
lists, validation, live-apply/dirty, setters, model-only flags)
and test_draw.py (headless Cairo smoke: every kind draws without
crashing and paints something; prop-driven branches). Five Phase 1
tests updated to the Phase 2 set_prop contract (label, not text,
for Button/Label; no arbitrary props). Full suite: 107 tests OK.
2026-12-01 02:42:21 +00:00

381 lines
14 KiB
Python

"""Project model: placed-widget list, selection, and the .fdj file format.
The .fdj format is the C designer's JSON format (src/project_io.cpp,
format version 1), which the Rust port is byte-compatible with:
{ "format": "lightgui", "version": 1,
"window": { "title", "class_name", "width", "height", "background",
"menubar", "border_style", "icon", "position",
"window_state" },
"widgets": [ { "name", "type", "x", "y", "width", "height",
"props": {...}, "signals": [...] } ] }
``save_text`` reproduces the C writer's output byte for byte (same key
order, indentation, and escaping) so files written here load in the C
and Rust designers unchanged. Loading is tolerant of unknown keys and
missing fields but strict about the format tag and version, like the
C loader; widgets whose type is not a known XFrame kind are skipped
(XFrame-only .fdj: legacy GTK widgets are dropped, never converted).
"""
import json
from lightgui.xframe import core as _core
FORMAT = "lightgui"
FORMAT_VERSION = 1
DEFAULT_TITLE = "Main Window"
DEFAULT_CLASS_NAME = "MyWindow"
DEFAULT_WIDTH = 800
DEFAULT_HEIGHT = 600
_MIN_WINDOW = 50
_MAX_WINDOW = 20000
_MIN_WIDGET = 10
def _clamp_window_size(value, default):
try:
value = int(value)
except (TypeError, ValueError):
return default
if value < _MIN_WINDOW or value > _MAX_WINDOW:
return default
return value
def _clamp_range(value, low, high, default):
try:
value = int(value)
except (TypeError, ValueError):
return default
if value < low or value > high:
return default
return value
class Project:
"""The designed window as data: window settings + placed widgets."""
def __init__(self, title=DEFAULT_TITLE, class_name=DEFAULT_CLASS_NAME,
win_width=DEFAULT_WIDTH, win_height=DEFAULT_HEIGHT):
self.title = title
self.class_name = class_name
self.win_width = win_width
self.win_height = win_height
self.background = ""
self.menubar = ""
self.border_style = 0
self.icon = ""
self.position = 0
self.window_state = 0
self.widgets = [] # list[core.Widget], placement order
self.selected_id = None # id of the selected widget, or None
self.skipped = [] # type names skipped by the last load
self._next_id = 1
self._counters = {} # kind -> count, for unique names
# --- naming -----------------------------------------------------------
def next_name(self, kind):
n = self._counters.get(kind, 0) + 1
self._counters[kind] = n
return "%s_%03d" % (kind, n)
# --- placed-widget list ------------------------------------------------
def add_widget(self, kind, x=0, y=0, width=None, height=None,
name=None, props=None, signals=None):
"""Place a widget of registry *kind*; returns it, or None if the
kind is unknown. The new widget is selected. Label/text props
are seeded to the instance name, like the Rust designer."""
if name is None:
name = self.next_name(kind)
widget = _core.create(kind, name, x, y, width, height,
props=props, signals=signals,
widget_id=self._next_id)
if widget is None:
return None
self._next_id += 1
self.widgets.append(widget)
# Seed label/text to the instance name (Rust seed_defaults).
# The canonical caption prop differs per table ("text" for
# Button/Entry, "label" for CheckBox/RadioButton); kinds with
# neither (Calendar, Notebook, Window, ...) get no seed.
if widget.archetype in ("Button", "Label", "Toggle", "Entry",
"Container", "Dialog", "Display"):
if "text" not in widget.props and "label" not in widget.props:
text_prop = ("text" if "text" in widget.prop_names()
else "label")
if text_prop in widget.prop_names():
widget.set_prop(text_prop, name)
self.select(widget.id)
return widget
def find(self, widget_id):
for widget in self.widgets:
if widget.id == widget_id:
return widget
return None
def find_by_name(self, name):
for widget in self.widgets:
if widget.name == name:
return widget
return None
def remove_widget(self, widget_id):
widget = self.find(widget_id)
if widget is None:
return False
self.widgets.remove(widget)
if self.selected_id == widget_id:
self.selected_id = None
return True
def move_widget(self, widget_id, x, y):
widget = self.find(widget_id)
if widget is None:
return False
widget.move_to(x, y)
return True
def resize_widget(self, widget_id, width, height):
widget = self.find(widget_id)
if widget is None:
return False
widget.resize_to(width, height)
return True
# --- selection ----------------------------------------------------------
def select(self, widget_id):
if widget_id is None:
self.selected_id = None
for widget in self.widgets:
widget.selected = False
return True
widget = self.find(widget_id)
if widget is None:
return False
for other in self.widgets:
other.selected = other is widget
self.selected_id = widget_id
return True
def clear_selection(self):
self.select(None)
@property
def selected(self):
if self.selected_id is None:
return None
return self.find(self.selected_id)
def hit_test(self, px, py):
"""Topmost widget containing (px, py), or None."""
for widget in reversed(self.widgets):
if widget.contains(px, py):
return widget
return None
# --- .fdj serialisation -------------------------------------------------
def to_dict(self):
return {
"format": FORMAT,
"version": FORMAT_VERSION,
"window": {
"title": self.title,
"class_name": self.class_name,
"width": self.win_width,
"height": self.win_height,
"background": self.background,
"menubar": self.menubar,
"border_style": self.border_style,
"icon": self.icon,
"position": self.position,
"window_state": self.window_state,
},
"widgets": [
{
"name": w.name,
"type": w.kind,
"x": w.x,
"y": w.y,
"width": w.width,
"height": w.height,
"props": dict(w.props),
"signals": list(w.signals),
}
for w in self.widgets
],
}
@classmethod
def from_dict(cls, data):
"""Build a Project from parsed .fdj data. Raises ValueError on a
bad format tag, unsupported version, or non-object root."""
if not isinstance(data, dict):
raise ValueError("project file root is not an object")
if data.get("format") != FORMAT:
raise ValueError("not a lightgui project file")
if data.get("version") != FORMAT_VERSION:
raise ValueError("unsupported format version: %r"
% (data.get("version"),))
project = cls()
win = data.get("window")
if isinstance(win, dict):
project.title = win.get("title", project.title) or project.title
project.class_name = (win.get("class_name", project.class_name)
or project.class_name)
project.win_width = _clamp_window_size(
win.get("width", project.win_width), DEFAULT_WIDTH)
project.win_height = _clamp_window_size(
win.get("height", project.win_height), DEFAULT_HEIGHT)
project.background = win.get("background", "") or ""
project.menubar = win.get("menubar", "") or ""
project.border_style = _clamp_range(
win.get("border_style", 0), 0, 3, 0)
project.icon = win.get("icon", "") or ""
project.position = _clamp_range(win.get("position", 0), 0, 4, 0)
project.window_state = _clamp_range(
win.get("window_state", 0), 0, 3, 0)
widgets = data.get("widgets")
if isinstance(widgets, list):
for entry in widgets:
if not isinstance(entry, dict):
continue
name = entry.get("name") or ""
kind = entry.get("type") or ""
if not name or not kind:
continue
if not _core.is_known_kind(kind):
project.skipped.append(kind)
continue
try:
x = int(entry.get("x", 0))
y = int(entry.get("y", 0))
width = max(int(entry.get("width", 100)), _MIN_WIDGET)
height = max(int(entry.get("height", 30)), _MIN_WIDGET)
except (TypeError, ValueError):
continue
raw_props = entry.get("props")
props = ({str(k): str(v) for k, v in raw_props.items()
if isinstance(v, str)}
if isinstance(raw_props, dict) else {})
raw_signals = entry.get("signals")
signals = ([str(s) for s in raw_signals
if isinstance(s, str)]
if isinstance(raw_signals, list) else [])
widget = _core.create(kind, name, x, y, width, height,
props=props, signals=signals,
widget_id=project._next_id)
if widget is None:
project.skipped.append(kind)
continue
project._next_id += 1
project.widgets.append(widget)
# Keep the per-kind name counter past loaded names so a
# later add does not collide (e.g. GtkButton_001 loaded,
# next add is GtkButton_002).
suffix = name.rsplit("_", 1)[-1]
if (name.startswith(kind + "_") and suffix.isdigit()
and int(suffix) > project._counters.get(kind, 0)):
project._counters[kind] = int(suffix)
return project
def save_text(self):
"""Serialise to .fdj text, byte-identical in layout to the C
writer (same key order, indentation, and string escaping)."""
lines = []
lines.append("{")
lines.append(' "format": "lightgui",')
lines.append(' "version": 1,')
lines.append(' "window": {')
lines.append(' "title": %s,' % _json_str(self.title))
lines.append(' "class_name": %s,' % _json_str(self.class_name))
lines.append(' "width": %d,' % self.win_width)
lines.append(' "height": %d,' % self.win_height)
lines.append(' "background": %s,' % _json_str(self.background))
lines.append(' "menubar": %s,' % _json_str(self.menubar))
lines.append(' "border_style": %d,' % self.border_style)
lines.append(' "icon": %s,' % _json_str(self.icon))
lines.append(' "position": %d,' % self.position)
lines.append(' "window_state": %d' % self.window_state)
lines.append(' },')
lines.append(' "widgets": [')
for i, w in enumerate(self.widgets):
lines.append(" {")
lines.append(' "name": %s,' % _json_str(w.name))
lines.append(' "type": %s,' % _json_str(w.kind))
lines.append(' "x": %d, "y": %d, "width": %d, "height": %d,'
% (w.x, w.y, w.width, w.height))
if w.props:
lines.append(' "props": {')
keys = sorted(w.props)
for j, key in enumerate(keys):
comma = "," if j < len(keys) - 1 else ""
lines.append(' %s: %s%s'
% (_json_str(key), _json_str(w.props[key]),
comma))
lines.append(' },')
else:
lines.append(' "props": {},')
sigs = ", ".join(_json_str(s) for s in w.signals)
lines.append(' "signals": [%s]' % sigs)
lines.append(" }%s" % ("," if i < len(self.widgets) - 1
else ""))
if self.widgets:
lines.append(" ]")
else:
lines[-1] = ' "widgets": []'
lines.append("}")
return "\n".join(lines) + "\n"
@classmethod
def load_text(cls, text, path="<string>"):
"""Parse .fdj text. Raises ValueError with a C-style message."""
try:
data = json.loads(text)
except json.JSONDecodeError as exc:
raise ValueError("invalid JSON in %s: %s" % (path, exc))
try:
return cls.from_dict(data)
except ValueError as exc:
raise ValueError("%s: %s" % (path, exc))
def save_file(self, path):
with open(path, "w", encoding="utf-8") as handle:
handle.write(self.save_text())
@classmethod
def load_file(cls, path):
try:
with open(path, encoding="utf-8") as handle:
text = handle.read()
except OSError as exc:
raise ValueError("cannot open %s: %s" % (path, exc))
return cls.load_text(text, path)
def _json_str(value):
"""Escape one string the way the C writer does (json_escape):
raw UTF-8, \" \\\\ \\n \\r \\t, other control chars as \\u00xx."""
out = ['"']
for ch in str(value):
code = ord(ch)
if ch == '"':
out.append('\\"')
elif ch == "\\":
out.append("\\\\")
elif ch == "\n":
out.append("\\n")
elif ch == "\r":
out.append("\\r")
elif ch == "\t":
out.append("\\t")
elif code < 0x20:
out.append("\\u%04x" % code)
else:
out.append(ch)
out.append('"')
return "".join(out)