"""Python code generator: turn a Project into a runnable Python script. Mirrors the C generator (src/generator.cpp) in structure — header comment, imports, event-handler stubs, helpers, main() that creates the window, creates one widget per placed widget, applies its props, wires its events and runs the loop — but emits Python using the Python XFrame widgets (lightgui.xframe.core) instead of C++/XFrame. The generated script is deterministic: generating twice from the same project produces byte-identical output (sorted props, fixed ordering, no timestamps). It runs under plain ``python3`` with the LightGUI Python package on ``PYTHONPATH`` (the IDE's Run flow sets that to the repo root; see lightgui/build.py). The generated app draws the widgets on a Gtk.DrawingArea with Cairo, exactly like the designer canvas. Anchor layout (proposal SS4 / Flag 1, C effective_anchors): ``align`` maps to an anchor set (Top -> top+left+right, Bottom -> bottom+left+right, Left -> left+top+bottom, Right -> right+top+bottom, Client -> all four); align None (0) leaves the four anchor bools in charge (default top+left). The generated script records the design geometry in ``_ANCHORS`` and repositions widgets from it on every resize, so the layout is minimal and idempotent. Per-widget Font (Flag 2) needs no helper here: font-name/size/bold/ italic are ordinary props, applied with set_prop and honoured by the XFrame draw code at draw time. Model-only props (Flag: props.py ``model_only``) have no XFrame setter, so they are emitted as a ``# NOTE (model-only, ...)`` comment, like the C generator — except ``anchor-*``/``align``, which are consumed by the anchors table. """ import re from lightgui import props as _props # Events the generated app can actually dispatch at run time (a # button press / release on the drawing area). Other Lazarus events # still get a stub, kept for hand-wiring, with a NOTE and no wiring — # the same rule as the C generator. RUNTIME_EVENTS = ("OnClick", "OnDblClick", "OnMouseDown", "OnMouseUp") # Height of the generated menu bar, in px (C: menubar_h = 28). MENUBAR_HEIGHT = 28 _IDENT_RE = re.compile(r"[^A-Za-z0-9_]") def sanitize_ident(name): """Make *name* safe as a Python identifier (C sanitize_ident).""" text = _IDENT_RE.sub("_", str(name)) if not text: return "widget" if text[0].isdigit(): text = "_" + text return text def effective_anchors(widget): """(top, left, right, bottom) for *widget*, mirroring the C generator's effective_anchors (align wins over the anchor bools). """ try: align = int(widget.get_prop("align", "0") or 0) except ValueError: align = 0 if align == 1: return (True, True, True, False) if align == 2: return (False, True, True, True) if align == 3: return (True, True, False, True) if align == 4: return (True, False, True, True) if align == 5: return (True, True, True, True) def _bool(name, default): return widget.get_prop(name, "true" if default else "false") \ in ("true", "1") return (_bool("anchor-top", True), _bool("anchor-left", True), _bool("anchor-right", False), _bool("anchor-bottom", False)) def parse_menubar(text): """Parse the project menubar spec (``"File: New | Open\\nHelp: About"``) into [(label, [items, ...]), ...]. ``"-"`` items are separators with no XFrame equivalent and are dropped, like C. """ menus = [] for line in (text or "").splitlines(): line = line.strip() if not line: continue if ":" in line: label, rest = line.split(":", 1) items = [item.strip() for item in rest.split("|")] else: label, items = line, [] items = [item for item in items if item and item != "-"] menus.append((label.strip(), items)) return menus def iter_events(widget): """(event, handler) pairs stored on *widget.signals* as ``"OnClick=handler"`` strings, in stored order. Empty handlers are dropped (Inspector removes them on save); unknown event names are kept — the generator still emits their stub. """ events = [] for signal in widget.signals: if "=" not in signal: continue event, handler = signal.split("=", 1) event = event.strip() handler = handler.strip() if event and handler: events.append((event, handler)) return events def stub_name(widget, event): """Handler stub name for (*widget*, *event*) in generated code.""" return "on_%s_%s" % (sanitize_ident(widget.name), sanitize_ident(event)) def default_filename(project): """Generated script filename for *project* (C names it after the window class).""" base = sanitize_ident(project.class_name or "MyWindow") return base + ".py" # --- emission helpers ----------------------------------------------------- def _prop_lines(widget): """Emission for one widget's stored props: a list of code lines (set_prop calls) plus a list of model-only note fragments. Only props whose value differs from the table default are emitted; geometry/name ride on the create() call. Anchor props are not listed here — the anchors table carries them. """ lines = [] notes = [] for name in sorted(widget.props): if name in ("name", "left", "top", "width", "height", "anchor-top", "anchor-left", "anchor-right", "anchor-bottom", "align"): continue value = widget.props[name] prop = _props.find_prop(widget.kind, name) if prop is None: notes.append("unknown prop %r skipped" % name) continue if prop.model_only: notes.append("%s=%r" % (name, value)) continue if value == prop.default: continue lines.append(" widget.set_prop(%r, %r)" % (name, value)) return lines, notes def _emit_stubs(lines, project, menus): """Event-handler stubs (free functions, wired below).""" for widget in project.widgets: for event, _handler in iter_events(widget): name = stub_name(widget, event) lines.append("def %s(widget):" % name) lines.append(" print(\"EVENT %s %s\" % (widget.name, " + repr(event) + "))") lines.append("") if event not in RUNTIME_EVENTS: lines.append("# NOTE: %s has no runtime wiring in the " "generated app; kept for hand-wiring." % event) lines.append("") for label, _items in menus: ident = sanitize_ident(label) lines.append("def on_menubar_activate_%s():" % ident) lines.append(" print(\"EVENT menubar %s\")" % repr(label)) lines.append("") def _emit_anchors(lines, project): """The _ANCHORS table: name -> (top, left, right, bottom, x, y, w, h) at design time, plus the resize handler that repositions anchored widgets from it (Flag 1, minimal anchor layout).""" lines.append("# Design-time geometry + effective anchors per widget:") lines.append("# name -> (top, left, right, bottom, x, y, width, height)") lines.append("_ANCHORS = {") for widget in project.widgets: top, left, right, bottom = effective_anchors(widget) lines.append(" %r: (%r, %r, %r, %r, %d, %d, %d, %d)," % (widget.name, top, left, right, bottom, widget.x, widget.y, widget.width, widget.height)) lines.append("}") lines.append("") lines.append("") lines.append("def _apply_anchors(widgets, width, height):") lines.append(" \"\"\"Reposition anchored widgets for a drawing area of") lines.append(" *width* x *height* (Flag 1: minimal anchor layout).") lines.append(" Computed from the design geometry every time, so a") lines.append(" resize is idempotent — no drift across resizes.\"\"\"") lines.append(" design_w, design_h = _DESIGN_SIZE") lines.append(" dx = width - design_w") lines.append(" dy = height - design_h") lines.append(" for widget in widgets:") lines.append(" top, left, right, bottom, ox, oy, ow, oh = \\") lines.append(" _ANCHORS[widget.name]") lines.append(" x, y, w, h = ox, oy, ow, oh") lines.append(" if right and not left:") lines.append(" x = ox + dx") lines.append(" elif right and left:") lines.append(" w = ow + dx") lines.append(" if bottom and not top:") lines.append(" y = oy + dy") lines.append(" elif bottom and top:") lines.append(" h = oh + dy") lines.append(" widget.move_to(x, y)") lines.append(" widget.resize_to(w, h)") lines.append("") def _emit_build(lines, project): """The _build_widgets() factory: one create() per placed widget, then its props, then its model-only NOTE comment.""" lines.append("def _build_widgets():") lines.append(" \"\"\"Create every placed widget with its props.\"\"\"") lines.append(" widgets = []") for widget in project.widgets: lines.append(" widget = create(%r, %r, %d, %d, %d, %d)" % (widget.kind, widget.name, widget.x, widget.y, widget.width, widget.height)) prop_lines, notes = _prop_lines(widget) lines.extend(prop_lines) if notes: lines.append(" # NOTE (model-only, no XFrame setter): %s" % ", ".join(notes)) lines.append(" widgets.append(widget)") lines.append(" return widgets") lines.append("") def _emit_runtime(lines, project, menus): """The generated app's runtime: window, menu bar, drawing area, draw/click/resize handlers, main().""" win_w = project.win_width if project.win_width > 0 else 800 win_h = project.win_height if project.win_height > 0 else 600 menubar_h = MENUBAR_HEIGHT if menus else 0 lines.append("_DESIGN_SIZE = (%d, %d)" % (win_w, win_h - menubar_h)) lines.append("_BACKGROUND = %r" % (project.background or "",)) lines.append("_WIDGETS = []") lines.append("_LAST_SIZE = [None]") lines.append("_PRESSED = [None] # Task 4: widget that got the ButtonPress") lines.append("") lines.append("") lines.append("def _hit_widget(widgets, x, y):") lines.append(" \"\"\"Topmost visible widget containing (*x*, *y*).\"\"\"") lines.append(" for widget in reversed(widgets):") lines.append(" if widget.get_prop(\"visible\", \"true\") in " "(\"false\", \"0\"):") lines.append(" continue") lines.append(" if widget.contains(x, y):") lines.append(" return widget") lines.append(" return None") lines.append("") lines.append("") lines.append("def _dispatch_to(widget, event):") lines.append(" \"\"\"Call the *event* handler of *widget* (already chosen).\"\"\"") lines.append(" if widget is None:") lines.append(" return") lines.append(" if widget.get_prop(\"enabled\", \"true\") in (\"false\", \"0\"):") lines.append(" return") lines.append(" handler = _HANDLERS.get((widget.name, event))") lines.append(" if handler is not None:") lines.append(" handler(widget)") lines.append("") lines.append("") lines.append("def _dispatch(widgets, x, y, event):") lines.append(" \"\"\"Call the *event* handler of the widget at (*x*, *y*),") lines.append(" if it has one wired.\"\"\"") lines.append(" _dispatch_to(_hit_widget(widgets, x, y), event)") lines.append("") lines.append("") lines.append("def _on_draw(area, cr):") lines.append(" bg = parse_color(_BACKGROUND, None)") lines.append(" if bg is None:") lines.append(" bg = (1.0, 1.0, 1.0)") lines.append(" cr.set_source_rgb(*bg)") lines.append(" cr.paint()") lines.append(" for widget in _WIDGETS:") lines.append(" widget.draw(cr)") lines.append(" return False") lines.append("") lines.append("") lines.append("def _on_button_press(area, event):") lines.append(" if event.type == Gdk.EventType.DOUBLE_BUTTON_PRESS:") lines.append(" _dispatch(_WIDGETS, event.x, event.y, \"OnDblClick\")") lines.append(" elif event.type == Gdk.EventType.BUTTON_PRESS:") lines.append(" _dispatch(_WIDGETS, event.x, event.y, \"OnMouseDown\")") lines.append(" _dispatch(_WIDGETS, event.x, event.y, \"OnClick\")") lines.append(" # Task 4: remember the pressed widget; release goes there.") lines.append(" _PRESSED[0] = _hit_widget(_WIDGETS, event.x, event.y)") lines.append(" return False") lines.append("") lines.append("") lines.append("def _on_button_release(area, event):") lines.append(" # Task 4: release goes to the widget that got the press,") lines.append(" # even if the pointer moved off it.") lines.append(" widget = _PRESSED[0]") lines.append(" _PRESSED[0] = None") lines.append(" _dispatch_to(widget, \"OnMouseUp\")") lines.append(" return False") lines.append("") lines.append("") lines.append("def _on_area_resize(area, allocation):") lines.append(" size = (allocation.width, allocation.height)") lines.append(" if size == _LAST_SIZE[0]:") lines.append(" return False") lines.append(" _LAST_SIZE[0] = size") lines.append(" _apply_anchors(_WIDGETS, size[0], size[1])") lines.append(" area.queue_draw()") lines.append(" return False") lines.append("") lines.append("") lines.append("def main():") lines.append(" window = Gtk.Window(title=%r)" % (project.title,)) lines.append(" window.set_default_size(%d, %d)" % (win_w, win_h)) lines.append(" window.connect(\"destroy\", Gtk.main_quit)") lines.append(" vbox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL,") lines.append(" spacing=0)") lines.append(" window.add(vbox)") if menus: lines.append(" menubar = Gtk.MenuBar()") for label, items in menus: var = "menu_%s" % sanitize_ident(label) lines.append(" %s = Gtk.Menu()" % var) lines.append(" _mi = Gtk.MenuItem(label=%r)" % label) lines.append(" _mi.set_submenu(%s)" % var) lines.append(" menubar.append(_mi)") for item in items: lines.append(" _item = Gtk.MenuItem(label=%r)" % item) lines.append(" _item.connect(\"activate\", lambda _mi: " "on_menubar_activate_%s())" % sanitize_ident(label)) lines.append(" %s.append(_item)" % var) lines.append(" vbox.pack_start(menubar, False, False, 0)") lines.append(" area = Gtk.DrawingArea()") lines.append(" area.set_hexpand(True)") lines.append(" area.set_vexpand(True)") lines.append(" area.add_events(Gdk.EventMask.BUTTON_PRESS_MASK |") lines.append(" Gdk.EventMask.BUTTON_RELEASE_MASK)") lines.append(" area.connect(\"draw\", _on_draw)") lines.append(" area.connect(\"button-press-event\", _on_button_press)") lines.append(" area.connect(\"button-release-event\", " "_on_button_release)") lines.append(" area.connect(\"size-allocate\", _on_area_resize)") lines.append(" vbox.pack_start(area, True, True, 0)") lines.append(" _WIDGETS.extend(_build_widgets())") lines.append(" window.show_all()") lines.append(" Gtk.main()") lines.append(" return 0") lines.append("") # --- public API ------------------------------------------------------------- def generate(project): """Generate the Python script for *project* (deterministic).""" menus = parse_menubar(project.menubar) win_w = project.win_width if project.win_width > 0 else 800 win_h = project.win_height if project.win_height > 0 else 600 lines = [] lines.append("#!/usr/bin/env python3") lines.append("# Generated by LightGUI (Python/XFrame).") lines.append("# A plain Python/GTK program: no CMake. Run with:") lines.append("# python3 %s" % default_filename(project)) lines.append("# with the LightGUI Python package on PYTHONPATH") lines.append("# (the designer sets it when it runs this script).") lines.append("#") lines.append("# The window is %r (%dx%d) with %d widget(s)." % (project.title, win_w, win_h, len(project.widgets))) lines.append("") lines.append("import sys") lines.append("") lines.append("import gi") lines.append("") lines.append("gi.require_version(\"Gtk\", \"3.0\")") lines.append("gi.require_version(\"Gdk\", \"3.0\")") lines.append("") lines.append("from gi.repository import Gdk, Gtk # noqa: E402") lines.append("from lightgui.xframe.core import create, parse_color " "# noqa: E402") lines.append("") lines.append("") _emit_stubs(lines, project, menus) lines.append("# Event handlers, wired to the widgets in main():") lines.append("_HANDLERS = {") for widget in project.widgets: for event, _handler in iter_events(widget): if event in RUNTIME_EVENTS: lines.append(" (%r, %r): %s," % (widget.name, event, stub_name(widget, event))) lines.append("}") lines.append("") lines.append("") _emit_anchors(lines, project) _emit_build(lines, project) lines.append("") _emit_runtime(lines, project, menus) lines.append("") lines.append("if __name__ == \"__main__\":") lines.append(" sys.exit(main())") lines.append("") return "\n".join(lines) def generate_to_file(project, path): """Write the generated script for *project* to *path*.""" with open(path, "w", encoding="utf-8") as handle: handle.write(generate(project)) return path