From 0cd61a357825c5ddeb0fb59c2cd5e3f54ad72303 Mon Sep 17 00:00:00 2001 From: cnmcdee Date: Tue, 1 Dec 2026 02:51:36 +0000 Subject: [PATCH] Phase 3: Object Inspector window + properties + font picker + bulk parameter Inspector in its own window (LightGUI - Object Inspector, ~340px), opened on startup beside the designer; closing hides it, palette pane button reopens it. Scrolled grid: geometry spins, generic set, custom props, Events group (OnClick etc. as editable text props, stored as Event=handler in signals). Rows hexpand to fill the panel width (b96e545/29751be fix); model-only rows flagged with *. Editors by type: entry, spin -/+, checkbox, enum dropdown, colour entry + Pick button, font-name entry + Pick button opening a Gtk.FontChooserDialog (55daf32/6a7c4c7). Live-apply via set_prop. Selection tracking via CanvasState.on_selection_change (fires only when the selection moves, so typing never rebuilds the grid). Bulk parameter (Set all / selected / filtered / Clear param) and 16-swatch colour palette (selected widget, or window background). Canvas now paints project.background so a root swatch is visible. Tests: 144 total, all pass under Xvfb. --- lightgui/app.py | 40 +- lightgui/inspector.py | 820 ++++++++++++++++++++++++++++++++++++++ lightgui/xframe/canvas.py | 14 +- tests/test_inspector.py | 373 +++++++++++++++++ 4 files changed, 1245 insertions(+), 2 deletions(-) create mode 100644 lightgui/inspector.py create mode 100644 tests/test_inspector.py diff --git a/lightgui/app.py b/lightgui/app.py index 954f14b..1f40cfb 100644 --- a/lightgui/app.py +++ b/lightgui/app.py @@ -14,6 +14,7 @@ gi.require_version("Gdk", "3.0") from gi.repository import Gdk, Gtk # noqa: E402 from lightgui import __version__ # noqa: E402 +from lightgui.inspector import Inspector # noqa: E402 from lightgui.model import Project # noqa: E402 from lightgui.xframe import palette as palette_data # noqa: E402 from lightgui.xframe.canvas import Canvas # noqa: E402 @@ -34,9 +35,16 @@ class Application: paned.set_position(280) vbox.pack_start(paned, True, True, 0) - paned.pack1(self._build_palette_pane(), False, False) self.canvas = Canvas(self.project) self.canvas.state.on_change = self._on_canvas_change + # Phase 3: the Object Inspector opens as its own window + # alongside the designer (C behaviour) and follows canvas + # selection. + self.inspector = Inspector( + self.project, canvas_state=self.canvas.state, + on_status=self.set_status) + self.canvas.state.on_selection_change = self.inspector.refresh + paned.pack1(self._build_palette_pane(), False, False) paned.pack2(self.canvas, True, False) self.statusbar = Gtk.Label(label="Ready", xalign=0) @@ -84,6 +92,17 @@ class Application: hint.set_margin_start(6) hint.set_margin_top(4) pane.pack_start(hint, False, False, 0) + # Reopen the Inspector after closing it (it only hides; the + # C designer uses View -> Object Inspector — this app has no + # menu bar yet, so the palette pane carries the toggle). + insp_button = Gtk.Button(label="Object Inspector") + insp_button.connect("clicked", + lambda _b: self.inspector.toggle()) + insp_button.set_margin_start(6) + insp_button.set_margin_end(6) + insp_button.set_margin_top(6) + insp_button.set_margin_bottom(6) + pane.pack_start(insp_button, False, False, 0) return pane def _palette_visible(self, model, tree_iter, _data): @@ -129,6 +148,9 @@ class Application: self.canvas.grab_focus() # --- canvas / status ------------------------------------------------------ + def set_status(self, text): + self.statusbar.set_text(text) + def _on_canvas_change(self): self._update_status() self.canvas.queue_draw() @@ -158,6 +180,22 @@ class Application: def run(self): self.window.show_all() + # Park the Inspector to the right of the designer (C parks + # it beside the main window; left if there is no room). + self.inspector.show() + while Gtk.events_pending(): + Gtk.main_iteration() + try: + x, y = self.window.get_position() + width, _h = self.window.get_size() + iw, _ih = self.inspector.window.get_size() + screen_w = self.window.get_screen().get_width() + ix = x + width + 12 + if ix + iw > screen_w: + ix = max(x - iw - 12, 0) + self.inspector.window.move(ix, y) + except Exception: + pass Gtk.main() return 0 diff --git a/lightgui/inspector.py b/lightgui/inspector.py new file mode 100644 index 0000000..6b2b581 --- /dev/null +++ b/lightgui/inspector.py @@ -0,0 +1,820 @@ +"""Object Inspector — the property editor in its own top-level window. + +Phase 3. Ports the C designer's Inspector (``src/main.cpp``: +``refresh_props()`` / ``make_prop_editor()`` / ``build_bulk_ui()`` / +``build_colour_ui()``) and the Rust port +(``crates/lightgui-designer/src/inspector.rs`` and ``bulk.rs``): + +- its own window, "LightGUI — Object Inspector", ~340px wide, opened + on startup next to the designer; closing it only hides it +- a scrolled properties grid whose rows EXPAND to fill the panel + width (the C b96e545 / Rust 29751be fix: every control gets + hexpand, like the Bulk parameter fields below the grid) +- geometry spins at the top (x, y, width, height), then the generic + set, then the widget's custom props, then an Events group +- row editors by prop type: text entry, spin buttons with -/+ for + numbers, checkbox for bools, dropdown for enums, entry + "Pick..." + button for colours, and font-name entry WITH a font picker button + beside it (the C 55daf32 / Rust 6a7c4c7 feature) opening a + Gtk.FontChooserDialog +- model-only props are shown but flagged with " *" (greyed label): + they are stored, not live-drawn +- selection tracking: refreshes when the canvas selection changes + (``CanvasState.on_selection_change``); with nothing selected it + shows the root window rows ("Window (Root)") +- live-apply: editing a row calls ``Widget.set_prop`` immediately, + so the canvas updates without any Apply button +- Bulk parameter section + Colour palette section at the bottom + +Events are editable text props: the handler name for an event is +stored in ``widget.signals`` as ``"OnClick=handler_name"`` (empty +removes it). This differs from C/Rust, where events are checkbuttons +toggling a GTK signal name — the Phase 3 brief asks for editable +text props, and the ``"Event=handler"`` strings round-trip through +.fdj ``signals`` unchanged. + +The display-free helpers (``row_specs_for``, ``bulk_match``, +``bulk_set``, ``bulk_clear``, ``apply_colour``, ``event_handler`` / +``set_event_handler``) carry the logic so it is unit-testable +without a display; :class:`Inspector` is the thin GTK shell. +""" + +import gi + +gi.require_version("Gtk", "3.0") +gi.require_version("Gdk", "3.0") + +from gi.repository import Gdk, Gtk # noqa: E402 + +from lightgui import props as _props # noqa: E402 +from lightgui.model import Project # noqa: E402 +from lightgui.xframe import core as _core # noqa: E402 +from lightgui.xframe import palette as _palette # noqa: E402 + +INSPECTOR_TITLE = "LightGUI — Object Inspector" +DEFAULT_WIDTH = 340 +DEFAULT_HEIGHT = 700 + +# Events shown as editable text props (Lazarus names; the Phase 3 +# brief's list, a subset of props.EVENTS). +EVENTS = ("OnClick", "OnChange", "OnKeyPress", "OnMouseDown", + "OnMouseUp", "OnMouseMove", "OnDblClick") + +GEOMETRY_NAMES = ("left", "top", "width", "height") +GEOMETRY_LABELS = {"left": "x", "top": "y", + "width": "width", "height": "height"} + +# Standard 16-colour palette grid (C build_colour_ui / Rust bulk.rs). +COLOUR_PALETTE = ( + "#000000", "#ffffff", "#c0c0c0", "#808080", "#ff0000", "#ff8000", + "#ffff00", "#00ff00", "#00ffff", "#0000ff", "#ff00ff", "#800080", + "#008080", "#000080", "#808000", "#800000", +) +COLOUR_TARGETS = (("background", "Background"), + ("foreground", "Foreground")) + +# Root-window rows, mirroring the Rust root Inspector (section 2.20 +# window props): title, class name, size, background, border style, +# icon, position, window state. These are Project fields, not widget +# props. +ROOT_PROPS = ( + _props.PropDef("title", "Str", "Main Window", 0, 0, (), (), + "Title", False), + _props.PropDef("class_name", "Str", "MyWindow", 0, 0, (), (), + "Class name", False), + _props.PropDef("width", "Int", "800", 50, 20000, (), (), + "Width", False), + _props.PropDef("height", "Int", "600", 50, 20000, (), (), + "Height", False), + _props.PropDef("background", "Color", "", 0, 0, (), (), + "Background", False), + _props.PropDef("border-style", "Enum", "0", 0, 0, + ("Default", "None", "Single", "Dialog"), + (0, 1, 2, 3), "Border style", False), + _props.PropDef("icon", "Str", "", 0, 0, (), (), "Icon", False), + _props.PropDef("position", "Enum", "0", 0, 0, + ("Default", "Center", "ScreenCenter", + "MainFormCenter", "Designed"), + (0, 1, 2, 3, 4), "Position", False), + _props.PropDef("window-state", "Enum", "0", 0, 0, + ("Normal", "Minimized", "Maximized", "Fullscreen"), + (0, 1, 2, 3), "Window state", False), +) + +_GENERIC_NAMES = frozenset(p.name for p in _props.GENERIC_PROPS) + + +def row_specs_for(kind_or_name=None): + """Row plan for the grid: a list of ``(tag, value)`` tuples. + + ``tag`` is ``"group"`` (section header label), ``"prop"`` (a + PropDef) or ``"event"`` (a Lazarus event name). ``None`` gives the + root-window rows; any palette kind (registry name like + ``"GtkButton"`` or kind name like ``"Button"``) gives geometry, + generic props, custom props, then events. Every one of the 547 + kinds produces a non-empty plan. + """ + if kind_or_name is None: + return [("group", "Window")] + [ + ("prop", prop) for prop in ROOT_PROPS] + all_props = _props.props_for(kind_or_name) + by_name = {prop.name: prop for prop in all_props} + custom = _props.custom_props_for(kind_or_name) + custom_names = {prop.name for prop in custom} + specs = [("group", "Geometry")] + for name in GEOMETRY_NAMES: + specs.append(("prop", by_name[name])) + specs.append(("group", "Properties")) + for prop in all_props: + if prop.name in GEOMETRY_NAMES or prop.name in custom_names: + continue + specs.append(("prop", prop)) + if custom: + specs.append(("group", "Custom properties")) + specs.extend(("prop", prop) for prop in custom) + specs.append(("group", "Events")) + specs.extend(("event", event) for event in EVENTS) + return specs + + +# --- events: handler storage on widget.signals --------------------------- + +def event_handler(widget, event): + """Handler name stored for *event* on *widget*, or "".""" + prefix = "%s=" % event + for signal in widget.signals: + if signal.startswith(prefix): + return signal[len(prefix):] + return "" + + +def set_event_handler(widget, event, handler): + """Store *handler* for *event*; an empty handler removes it.""" + prefix = "%s=" % event + widget.signals = [s for s in widget.signals + if not s.startswith(prefix)] + handler = (handler or "").strip() + if handler: + widget.signals.append(prefix + handler) + return handler + + +# --- bulk parameter operations (C bulk_set / bulk_clear / bulk_match) ---- + +def bulk_match(widget, project, mode, filter_text=""): + """True when *widget* is a bulk target for *mode*. + + ``"all"`` matches everything; ``"selected"`` matches only the + selected widget; ``"filtered"`` matches when the filter text + occurs (case-insensitive) in the widget's type or name — an + empty filter matches everything, as in C. + """ + if mode == "all": + return True + if mode == "selected": + return project.selected is widget + if mode == "filtered": + needle = (filter_text or "").strip().lower() + return (needle in widget.kind.lower() + or needle in widget.pkind.lower() + or needle in widget.name.lower()) + raise ValueError("unknown bulk mode %r" % (mode,)) + + +def bulk_set(project, param, value, mode, filter_text=""): + """Set *param* to *value* on every matching widget that supports + it (``Widget.set_prop``, so it live-applies). Returns the number + of widgets changed. Raises ValueError on the first invalid value, + like C's bulk_set returning -1 (widgets already changed stay + changed).""" + count = 0 + for widget in list(project.widgets): + if not bulk_match(widget, project, mode, filter_text): + continue + if _props.find_prop(widget.kind, param) is None: + continue + widget.set_prop(param, value) + count += 1 + return count + + +def bulk_clear(project, param): + """Remove *param* everywhere and restore its default live. + + Geometry props are reset to their table default (they are widget + fields, not stored props); other props are dropped from the + widget's stored props when present, which restores the default + the canvas falls back to. Returns the number of widgets changed. + ``"name"`` cannot be cleared (it is the widget identity). + """ + count = 0 + for widget in list(project.widgets): + prop = _props.find_prop(widget.kind, param) + if prop is None or param == "name": + continue + if param in GEOMETRY_NAMES: + widget.set_prop(param, prop.default) + count += 1 + elif param in widget.props: + del widget.props[param] + widget._mark_dirty() + count += 1 + return count + + +def apply_colour(project, hex_value, which="background"): + """Apply a palette colour: to the selected widget's *which* + prop, or to the window background when nothing is selected + (background only — foreground needs a widget). Returns True when + applied; invalid colours are ignored, like C/Rust. + """ + hex_value = (hex_value or "").strip() + if not hex_value: + return False + if _core.parse_color(hex_value, None) is None: + return False + selected = project.selected + if selected is not None: + if _props.find_prop(selected.kind, which) is None: + return False + selected.set_prop(which, hex_value) + return True + if which == "background": + project.background = hex_value + return True + return False + + +def bulk_param_names(): + """Sorted unique prop names over all 547 kinds (bulk dropdown).""" + names = set(_props.GENERIC_NAMES) + for entry in _palette.PALETTE: + names.update(_props.prop_names(entry.name)) + return sorted(names) + + +class Inspector: + """The Object Inspector window. + + ``project`` is the designed project; ``canvas_state`` (a + :class:`lightgui.xframe.canvas.CanvasState`, optional) is notified + when a root-window change needs a canvas redraw (window + background). ``on_status`` is called with short status strings + for bulk / colour actions. Wire ``canvas_state.on_selection_change + = inspector.refresh`` so the Inspector follows canvas selection. + """ + + def __init__(self, project, canvas_state=None, on_status=None): + self.project = project + self.canvas_state = canvas_state + self.on_status = on_status + self._syncing = False + # prop name -> editor widget (entry/spin/check/combo, or the + # HBox holding one for font/colour props). + self.rows = {} + # prop name -> the text Entry inside a Str/Color editor. + self._entries = {} + # event name -> text Entry. + self.event_rows = {} + # Grid control widgets, in row order (hexpand test hook). + self.controls = [] + # hex colour -> swatch button. + self.colour_swatches = {} + + self.window = Gtk.Window(title=INSPECTOR_TITLE) + self.window.set_default_size(DEFAULT_WIDTH, DEFAULT_HEIGHT) + self.window.connect("delete-event", self._on_delete) + + self.props_box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, + spacing=0) + scrolled = Gtk.ScrolledWindow() + scrolled.set_policy(Gtk.PolicyType.NEVER, + Gtk.PolicyType.AUTOMATIC) + scrolled.add(self.props_box) + self.window.add(scrolled) + + self.selected_label = Gtk.Label(label="Window (Root)", xalign=0) + self.selected_label.set_margin_start(6) + self.selected_label.set_margin_top(4) + self.props_box.pack_start(self.selected_label, False, False, 0) + + self.grid = Gtk.Grid() + self.grid.set_column_spacing(6) + self.grid.set_row_spacing(4) + self.grid.set_margin_start(6) + self.grid.set_margin_end(6) + self.grid.set_margin_top(4) + self.grid.set_hexpand(True) + self.props_box.pack_start(self.grid, False, False, 0) + + footnote = Gtk.Label( + label="* model-only: stored, not live-drawn", xalign=0) + footnote.set_margin_start(6) + self.props_box.pack_start(footnote, False, False, 2) + + self._build_bulk_ui() + self._build_colour_ui() + self.refresh() + + # --- window ----------------------------------------------------------- + def _on_delete(self, _window, _event): + # Close button hides the inspector instead of destroying it, + # so it can be reopened (C on_inspector_window_delete). + self.hide() + return True + + def show(self): + self.window.show_all() + self.window.present() + + def hide(self): + self.window.hide() + + def toggle(self): + if self.window.get_visible(): + self.hide() + else: + self.show() + + def is_visible(self): + return self.window.get_visible() + + def _status(self, text): + if self.on_status is not None: + self.on_status(text) + + def _notify_canvas(self): + # A root-window change (e.g. window background) needs a + # canvas redraw; CanvasState._changed does that, and only + # fires the selection hook when the selection actually moved. + if self.canvas_state is not None: + self.canvas_state._changed() + + # --- refresh / selection tracking -------------------------------------- + def refresh(self): + """Rebuild the grid for the current selection (or the root).""" + self._syncing = True + try: + for child in list(self.grid.get_children()): + self.grid.remove(child) + self.rows = {} + self._entries = {} + self.event_rows = {} + self.controls = [] + widget = self.project.selected + if widget is None: + self.selected_label.set_text("Window (Root)") + self._build_rows(row_specs_for(None), None) + else: + self.selected_label.set_text( + "%s (%s)" % (widget.name, widget.pkind)) + self._build_rows(row_specs_for(widget.kind), widget) + self.grid.show_all() + finally: + self._syncing = False + + def on_selection_change(self): + """CanvasState selection callback — refresh the rows.""" + self.refresh() + + def _build_rows(self, specs, target): + row = 0 + for tag, value in specs: + if tag == "group": + header = Gtk.Label() + header.set_markup("%s" % value) + header.set_halign(Gtk.Align.START) + self.grid.attach(header, 0, row, 2, 1) + row += 1 + continue + if tag == "event": + editor = self._make_event_editor(target, value) + self._add_row(row, value, editor, False) + self.event_rows[value] = editor + row += 1 + continue + prop = value + editor = self._make_editor(prop, target) + if prop.name in GEOMETRY_LABELS: + label_text = GEOMETRY_LABELS[prop.name] + else: + label_text = prop.display + if prop.model_only: + label_text += " *" + self._add_row(row, label_text, editor, prop.model_only) + self.rows[prop.name] = editor + row += 1 + + def _add_row(self, row, label_text, control, model_only): + """One grid row; the control expands to fill the panel width + (the b96e545/29751be fix).""" + label = Gtk.Label(label=label_text, xalign=0) + label.set_halign(Gtk.Align.START) + if model_only: + label.set_opacity(0.55) + label.set_tooltip_text( + "Model-only: stored, not live-drawn") + self.grid.attach(label, 0, row, 1, 1) + control.set_hexpand(True) + self.grid.attach(control, 1, row, 1, 1) + self.controls.append(control) + + # --- current values / applying edits ------------------------------------ + def _current(self, prop, target): + """Current string value of *prop* for *target* (or the root).""" + if target is None: + project = self.project + root = { + "title": project.title, + "class_name": project.class_name, + "width": str(project.win_width), + "height": str(project.win_height), + "background": project.background, + "border-style": str(project.border_style), + "icon": project.icon, + "position": str(project.position), + "window-state": str(project.window_state), + } + return root.get(prop.name, prop.default) + if prop.name == "name": + return target.name + if prop.name == "left": + return str(target.x) + if prop.name == "top": + return str(target.y) + if prop.name == "width": + return str(target.width) + if prop.name == "height": + return str(target.height) + return target.get_prop(prop.name, prop.default) + + def _apply(self, prop, text): + """Live-apply one edited value (no Apply button).""" + if self._syncing: + return + target = self.project.selected + if target is None: + self._apply_root(prop, text) + return + try: + target.set_prop(prop.name, text) + except ValueError: + # Intermediate/invalid typing (e.g. a half-typed colour) + # is ignored; the last valid value stands. + return + if prop.name == "name": + self.selected_label.set_text( + "%s (%s)" % (target.name, target.pkind)) + + def _apply_root(self, prop, text): + """Live-apply one edited root-window value.""" + if self._syncing: + return + project = self.project + name = prop.name + if name == "title": + project.title = text + elif name == "class_name": + project.class_name = text + elif name == "icon": + project.icon = text + elif name == "background": + if text == "" or _core.parse_color(text, None) is not None: + project.background = text + self._notify_canvas() + elif name in ("width", "height"): + try: + value = int(text) + except ValueError: + return + value = max(50, min(20000, value)) + if name == "width": + project.win_width = value + else: + project.win_height = value + elif prop.kind == "Enum": + # The editor passes the label; map it to the stored value. + if text in prop.enum_labels: + index = prop.enum_labels.index(text) + value = (prop.enum_values[index] + if prop.enum_values else index) + else: + try: + value = int(text) + except ValueError: + return + if name == "border-style": + project.border_style = value + elif name == "position": + project.position = value + elif name == "window-state": + project.window_state = value + + # --- row editors --------------------------------------------------------- + def _spin_range(self, prop, target): + """(lo, hi) for a numeric editor. Geometry spins use the Rust + ranges (x/y -100..5000, w/h 10..5000); table ranges win next; + a 0..0 table range means unbounded.""" + if target is not None and prop.name in ("left", "top"): + return (-100.0, 5000.0) + if target is not None and prop.name in ("width", "height"): + return (10.0, 5000.0) + if prop.lo != 0 or prop.hi != 0: + return (float(prop.lo), float(prop.hi)) + return (-1000000.0, 1000000.0) + + def _make_editor(self, prop, target): + current = self._current(prop, target) + kind = prop.kind + if kind == "Str": + entry = Gtk.Entry() + entry.set_text(current) + entry.set_hexpand(True) + entry.connect("changed", + lambda e, p=prop: self._apply(p, e.get_text())) + self._entries[prop.name] = entry + if prop.name == "font-name": + # Font picker button beside the font-name entry + # (C 55daf32 / Rust 6a7c4c7). + box = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, + spacing=4) + pick = Gtk.Button(label="Pick…") + pick.connect("clicked", + lambda _b, e=entry: self.open_font_picker(e)) + box.pack_start(entry, True, True, 0) + box.pack_start(pick, False, False, 0) + return box + return entry + if kind == "Color": + entry = Gtk.Entry() + entry.set_text(current) + entry.set_hexpand(True) + entry.connect("changed", + lambda e, p=prop: self._apply(p, e.get_text())) + self._entries[prop.name] = entry + box = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, + spacing=4) + pick = Gtk.Button(label="Pick…") + pick.connect("clicked", + lambda _b, e=entry: self.open_colour_picker(e)) + box.pack_start(entry, True, True, 0) + box.pack_start(pick, False, False, 0) + return box + if kind == "Bool": + check = Gtk.CheckButton() + check.set_active(current == "true") + check.connect( + "toggled", + lambda b, p=prop: self._apply( + p, "true" if b.get_active() else "false")) + return check + if kind == "Int": + lo, hi = self._spin_range(prop, target) + spin = Gtk.SpinButton.new_with_range(lo, hi, 1.0) + try: + spin.set_value(float(current)) + except ValueError: + spin.set_value(0.0) + spin.connect( + "value-changed", + lambda s, p=prop: self._apply(p, str(int(s.get_value())))) + return spin + if kind == "Double": + lo, hi = self._spin_range(prop, target) + step = 0.05 if hi <= 1.0 else 1.0 + spin = Gtk.SpinButton.new_with_range(lo, hi, step) + spin.set_digits(2) + try: + spin.set_value(float(current)) + except ValueError: + spin.set_value(0.0) + spin.connect( + "value-changed", + lambda s, p=prop: self._apply(p, "%g" % s.get_value())) + return spin + if kind == "Enum": + combo = Gtk.ComboBoxText() + active = 0 + for index, label in enumerate(prop.enum_labels): + combo.append_text(label) + if prop.enum_values: + try: + if prop.enum_values[index] == int(current): + active = index + except (ValueError, IndexError): + pass + elif label == current: + active = index + combo.set_active(active) + combo.connect( + "changed", + lambda c, p=prop: self._apply( + p, c.get_active_text() or "")) + return combo + return Gtk.Label(label="") + + def _make_event_editor(self, target, event): + entry = Gtk.Entry() + if target is not None: + entry.set_text(event_handler(target, event)) + + def _on_changed(entry_widget, ev=event): + if self._syncing: + return + widget = self.project.selected + if widget is not None: + set_event_handler(widget, ev, entry_widget.get_text()) + + entry.connect("changed", _on_changed) + entry.set_hexpand(True) + return entry + + def entry_for(self, name): + """The text Entry for a Str/Color prop (tests / callers).""" + return self._entries.get(name) + + def editor_for(self, name): + """The editor widget built for *name* (or None).""" + return self.rows.get(name) + + # --- font / colour pickers ---------------------------------------------- + def make_font_dialog(self, current_font=""): + """A Gtk.FontChooserDialog for *current_font* (construction + only — the caller runs it). The family alone is stored, so a + bare family name gets a default size for the chooser.""" + dialog = Gtk.FontChooserDialog(title="Pick a font", + parent=self.window) + family = (current_font or "").strip() + if family: + dialog.set_font(family if " " in family + else "%s 13" % family) + else: + dialog.set_font("Sans 13") + return dialog + + def open_font_picker(self, entry): + """Show the font picker; the chosen family live-applies + through the entry's changed handler.""" + dialog = self.make_font_dialog(entry.get_text()) + if dialog.run() == Gtk.ResponseType.OK: + desc = dialog.get_font_desc() + if desc is not None: + family = desc.get_family() + if family: + entry.set_text(family) + dialog.destroy() + + def make_colour_dialog(self, current=""): + """A Gtk.ColorChooserDialog preset to *current* (if valid).""" + dialog = Gtk.ColorChooserDialog(title="Pick colour", + parent=self.window) + if current: + rgba = Gdk.RGBA() + if rgba.parse(current): + dialog.set_rgba(rgba) + return dialog + + def open_colour_picker(self, entry): + """Show the colour picker; the chosen #rrggbb live-applies + through the entry's changed handler.""" + dialog = self.make_colour_dialog(entry.get_text()) + if dialog.run() == Gtk.ResponseType.OK: + rgba = dialog.get_rgba() + entry.set_text("#%02x%02x%02x" % ( + int(rgba.red * 255), int(rgba.green * 255), + int(rgba.blue * 255))) + dialog.destroy() + + # --- bulk parameter ------------------------------------------------------ + def _build_bulk_ui(self): + sep = Gtk.Separator(orientation=Gtk.Orientation.HORIZONTAL) + self.props_box.pack_start(sep, False, False, 6) + header = Gtk.Label() + header.set_markup("Bulk parameter") + header.set_halign(Gtk.Align.START) + self.props_box.pack_start(header, False, False, 0) + + self.bulk_param = Gtk.ComboBoxText.new_with_entry() + for name in bulk_param_names(): + self.bulk_param.append_text(name) + self.props_box.pack_start(self.bulk_param, False, False, 0) + + self.bulk_value = Gtk.Entry() + self.bulk_value.set_placeholder_text("value") + self.props_box.pack_start(self.bulk_value, False, False, 0) + + self.bulk_filter = Gtk.Entry() + self.bulk_filter.set_placeholder_text( + "filter: type or name contains…") + self.props_box.pack_start(self.bulk_filter, False, False, 0) + + grid = Gtk.Grid() + grid.set_row_spacing(4) + grid.set_column_spacing(4) + self.bulk_buttons = {} + for index, (label, mode) in enumerate(( + ("Set all", "all"), + ("Set selected", "selected"), + ("Set filtered", "filtered"))): + button = Gtk.Button(label=label) + button.connect("clicked", + lambda _b, m=mode: self._on_bulk_set(m)) + grid.attach(button, index % 2, index // 2, 1, 1) + self.bulk_buttons[mode] = button + clear = Gtk.Button(label="Clear param") + clear.connect("clicked", lambda _b: self._on_bulk_clear()) + grid.attach(clear, 1, 1, 1, 1) + self.bulk_buttons["clear"] = clear + self.props_box.pack_start(grid, False, False, 0) + + def _bulk_param_text(self): + child = self.bulk_param.get_child() + if child is not None and isinstance(child, Gtk.Entry): + return child.get_text().strip() + return (self.bulk_param.get_active_text() or "").strip() + + def _on_bulk_set(self, mode): + param = self._bulk_param_text() + if not param: + self._status("Bulk: type a parameter name first") + return + if mode == "selected" and self.project.selected is None: + self._status("Bulk: nothing selected") + return + try: + count = bulk_set(self.project, param, + self.bulk_value.get_text(), mode, + self.bulk_filter.get_text()) + except ValueError as exc: + self._status("Bulk not applied — %s" % exc) + return + self._status("Bulk: set %s on %d widget(s)" % (param, count)) + self.refresh() + self._notify_canvas() + + def _on_bulk_clear(self): + param = self._bulk_param_text() + if not param: + self._status("Bulk: type a parameter name first") + return + count = bulk_clear(self.project, param) + self._status("Bulk: cleared %s on %d widget(s)" % (param, count)) + self.refresh() + self._notify_canvas() + + # --- colour palette ------------------------------------------------------- + def _build_colour_ui(self): + sep = Gtk.Separator(orientation=Gtk.Orientation.HORIZONTAL) + self.props_box.pack_start(sep, False, False, 6) + header = Gtk.Label() + header.set_markup("Colour palette") + header.set_halign(Gtk.Align.START) + self.props_box.pack_start(header, False, False, 0) + + self.colour_target = Gtk.ComboBoxText() + for target_id, label in COLOUR_TARGETS: + self.colour_target.append(target_id, label) + self.colour_target.set_active_id("background") + self.props_box.pack_start(self.colour_target, False, False, 0) + + grid = Gtk.Grid() + grid.set_row_spacing(3) + grid.set_column_spacing(3) + for index, hex_value in enumerate(COLOUR_PALETTE): + button = Gtk.Button() + button.set_size_request(24, 24) + css = Gtk.CssProvider() + css.load_from_data( + ("button { background: %s; }" % hex_value).encode()) + button.get_style_context().add_provider( + css, Gtk.STYLE_PROVIDER_PRIORITY_USER) + button.connect( + "clicked", + lambda _b, h=hex_value: self._on_swatch(h)) + grid.attach(button, index % 8, index // 8, 1, 1) + self.colour_swatches[hex_value] = button + self.props_box.pack_start(grid, False, False, 0) + + hint = Gtk.Label( + label="Applies to the selected widget,\n" + "or the window background if none.", + xalign=0) + self.props_box.pack_start(hint, False, False, 0) + + def _on_swatch(self, hex_value): + which = self.colour_target.get_active_id() or "background" + if not apply_colour(self.project, hex_value, which): + if self.project.selected is None and which != "background": + self._status("Select a widget first to set its " + "foreground") + else: + self._status("Colour: '%s' is not a colour" % hex_value) + return + selected = self.project.selected + if selected is not None: + self._status("%s of %s set to %s" + % (which, selected.name, hex_value)) + else: + self._status("Window background set to %s" % hex_value) + self.refresh() + self._notify_canvas() diff --git a/lightgui/xframe/canvas.py b/lightgui/xframe/canvas.py index b91a089..1f6d4e8 100644 --- a/lightgui/xframe/canvas.py +++ b/lightgui/xframe/canvas.py @@ -73,6 +73,11 @@ class CanvasState: self.last_press_id = -1 self.last_press_ms = 0.0 self.on_change = None # called after any state change + # Phase 3: called only when the selection actually changes + # (the Inspector refreshes on it; prop edits and drags do + # not rebuild the Inspector, or typing would lose focus). + self.on_selection_change = None + self._last_selected_id = None # --- selection -------------------------------------------------------- @property @@ -248,6 +253,11 @@ class CanvasState: widget.handles_on = (widget is selected and self.handles_on) if self.on_change is not None: self.on_change() + selected_id = self.project.selected_id + if selected_id != self._last_selected_id: + self._last_selected_id = selected_id + if self.on_selection_change is not None: + self.on_selection_change() class Canvas(Gtk.DrawingArea): @@ -331,7 +341,9 @@ class Canvas(Gtk.DrawingArea): alloc = self.get_allocation() width, height = alloc.width, alloc.height cr.save() - cr.set_source_rgb(*BACKGROUND_RGB) + cr.set_source_rgb( + *_core.parse_color(self.state.project.background, + BACKGROUND_RGB)) cr.paint() # Dotted grid, one dot every 24px (Rust redraw_canvas). cr.set_source_rgb(*GRID_RGB) diff --git a/tests/test_inspector.py b/tests/test_inspector.py new file mode 100644 index 0000000..d6d7b01 --- /dev/null +++ b/tests/test_inspector.py @@ -0,0 +1,373 @@ +"""Tests for lightgui.inspector (Phase 3). + +Display-free logic (row specs, bulk ops, colour apply, event +handlers) runs anywhere. GTK widget tests need a display and are +skipped when Gtk cannot initialise (run them under Xvfb, :99). +""" + +import unittest + +from lightgui import props +from lightgui.model import Project +from lightgui.xframe import core +from lightgui.xframe import palette +from lightgui.xframe.canvas import CanvasState + +try: + import gi + gi.require_version("Gtk", "3.0") + from gi.repository import Gtk + _GTK_OK = Gtk.init_check()[0] +except Exception: + Gtk = None + _GTK_OK = False + +# The inspector module imports fine headless (only constructing +# GTK widgets needs a display); only the Inspector class tests are +# display-gated below. +from lightgui.inspector import ( + Inspector, apply_colour, bulk_clear, bulk_match, bulk_set, + bulk_param_names, event_handler, row_specs_for, + set_event_handler) + + +def _project_with(*kinds): + project = Project() + widgets = [project.add_widget(kind, 10, 10, 150, 36) + for kind in kinds] + project.clear_selection() + return project, widgets + + +class RowSpecTests(unittest.TestCase): + def test_every_kind_produces_nonempty_grid(self): + self.assertEqual(len(palette.PALETTE), 547) + for entry in palette.PALETTE: + specs = row_specs_for(entry.name) + prop_specs = [s for s in specs if s[0] == "prop"] + self.assertTrue(prop_specs, + "%s produced no prop rows" % entry.name) + groups = [v for t, v in specs if t == "group"] + self.assertEqual(groups[0], "Geometry") + self.assertIn("Properties", groups) + self.assertEqual(groups[-1], "Events") + + def test_geometry_rows_come_first(self): + specs = row_specs_for("GtkButton") + prop_names = [v.name for t, v in specs if t == "prop"] + self.assertEqual(prop_names[:4], + ["left", "top", "width", "height"]) + + def test_generic_then_custom_then_events(self): + specs = row_specs_for("GtkButton") + tags = [(t, v.name if t == "prop" else v) for t, v in specs] + groups = [v for t, v in tags if t == "group"] + self.assertEqual(groups, + ["Geometry", "Properties", + "Custom properties", "Events"]) + events = [v for t, v in specs if t == "event"] + self.assertEqual(events, ["OnClick", "OnChange", "OnKeyPress", + "OnMouseDown", "OnMouseUp", + "OnMouseMove", "OnDblClick"]) + + def test_kind_without_custom_props_has_no_custom_group(self): + # Stock kinds get the generic set only in Phase 2/3. + specs = row_specs_for("IndRSI") + groups = [v for t, v in specs if t == "group"] + self.assertEqual(groups, ["Geometry", "Properties", "Events"]) + + def test_root_specs_are_window_rows(self): + specs = row_specs_for(None) + self.assertEqual(specs[0], ("group", "Window")) + names = [v.name for t, v in specs if t == "prop"] + self.assertEqual(names, ["title", "class_name", "width", + "height", "background", "border-style", + "icon", "position", "window-state"]) + self.assertFalse([s for s in specs if s[0] == "event"]) + + def test_model_only_props_flagged_in_table(self): + specs = row_specs_for("GtkButton") + flagged = {v.name for t, v in specs + if t == "prop" and v.model_only} + self.assertIn("hint", flagged) + self.assertIn("tab-order", flagged) + self.assertNotIn("label", flagged) + self.assertNotIn("font-size", flagged) + + +class EventHandlerTests(unittest.TestCase): + def test_event_handler_round_trip(self): + project, (widget,) = _project_with("GtkButton") + self.assertEqual(event_handler(widget, "OnClick"), "") + set_event_handler(widget, "OnClick", "on_button_click") + self.assertEqual(event_handler(widget, "OnClick"), + "on_button_click") + self.assertIn("OnClick=on_button_click", widget.signals) + set_event_handler(widget, "OnClick", " ") + self.assertEqual(event_handler(widget, "OnClick"), "") + self.assertNotIn("OnClick=on_button_click", widget.signals) + + def test_events_do_not_clobber_each_other(self): + project, (widget,) = _project_with("GtkButton") + set_event_handler(widget, "OnClick", "a") + set_event_handler(widget, "OnDblClick", "b") + self.assertEqual(event_handler(widget, "OnClick"), "a") + self.assertEqual(event_handler(widget, "OnDblClick"), "b") + + +class BulkTests(unittest.TestCase): + def setUp(self): + self.project, self.widgets = _project_with( + "GtkButton", "GtkLabel", "GtkButton") + self.button1, self.label, self.button2 = self.widgets + + def test_bulk_match_modes(self): + self.project.select(self.button1.id) + self.assertTrue(bulk_match(self.button1, self.project, "all")) + self.assertTrue(bulk_match(self.button1, self.project, + "selected")) + self.assertFalse(bulk_match(self.label, self.project, + "selected")) + self.assertTrue(bulk_match(self.button1, self.project, + "filtered", "butt")) + self.assertFalse(bulk_match(self.label, self.project, + "filtered", "butt")) + self.assertTrue(bulk_match(self.label, self.project, + "filtered", "GtkLabel_001")) + self.assertTrue(bulk_match(self.label, self.project, + "filtered", "")) + + def test_bulk_set_all(self): + count = bulk_set(self.project, "label", "Bulk", "all") + self.assertEqual(count, 3) + for widget in self.widgets: + self.assertEqual(widget.get_prop("label"), "Bulk") + + def test_bulk_set_selected_only(self): + self.project.select(self.label.id) + count = bulk_set(self.project, "label", "Sel", "selected") + self.assertEqual(count, 1) + self.assertEqual(self.label.get_prop("label"), "Sel") + self.assertNotEqual(self.button1.get_prop("label"), "Sel") + + def test_bulk_set_filtered(self): + count = bulk_set(self.project, "label", "Filt", "filtered", + "Button") + self.assertEqual(count, 2) + self.assertEqual(self.button1.get_prop("label"), "Filt") + self.assertEqual(self.button2.get_prop("label"), "Filt") + self.assertNotEqual(self.label.get_prop("label"), "Filt") + + def test_bulk_set_skips_unsupported_props(self): + # "items" is not in the Button/Label tables. + count = bulk_set(self.project, "items", "a|b", "all") + self.assertEqual(count, 0) + + def test_bulk_set_invalid_value_raises(self): + with self.assertRaises(ValueError): + bulk_set(self.project, "font-size", "not-a-number", "all") + + def test_bulk_clear_restores_default(self): + bulk_set(self.project, "label", "Temp", "all") + count = bulk_clear(self.project, "label") + self.assertEqual(count, 3) + for widget in self.widgets: + self.assertNotIn("label", widget.props) + self.assertEqual(bulk_clear(self.project, "label"), 0) + + def test_bulk_clear_geometry_resets_to_default(self): + self.button1.set_prop("width", 250) + count = bulk_clear(self.project, "width") + self.assertEqual(count, 3) + self.assertEqual(self.button1.width, 100) + + def test_bulk_param_names_cover_tables(self): + names = bulk_param_names() + self.assertIn("label", names) + self.assertIn("font-name", names) + self.assertIn("background", names) + self.assertEqual(names, sorted(names)) + + +class ApplyColourTests(unittest.TestCase): + def test_apply_to_selected_widget(self): + project, (widget,) = _project_with("GtkButton") + project.select(widget.id) + self.assertTrue(apply_colour(project, "#ff0000", "background")) + self.assertEqual(widget.get_prop("background"), "#ff0000") + + def test_apply_to_window_background_when_none_selected(self): + project, _ = _project_with("GtkButton") + self.assertTrue(apply_colour(project, "#00ff00", "background")) + self.assertEqual(project.background, "#00ff00") + + def test_foreground_needs_a_widget(self): + project, _ = _project_with("GtkButton") + self.assertFalse(apply_colour(project, "#0000ff", "foreground")) + self.assertEqual(project.background, "") + + def test_invalid_colour_ignored(self): + project, (widget,) = _project_with("GtkButton") + project.select(widget.id) + self.assertFalse(apply_colour(project, "not-a-colour", + "background")) + self.assertEqual(widget.get_prop("background"), "") + + +@unittest.skipUnless(_GTK_OK, "needs a display (run under Xvfb :99)") +class InspectorGtkTests(unittest.TestCase): + def setUp(self): + self.project, self.widgets = _project_with("GtkButton") + self.button = self.widgets[0] + self.project.select(self.button.id) + self.inspector = Inspector(self.project) + + def tearDown(self): + self.inspector.window.destroy() + while Gtk.events_pending(): + Gtk.main_iteration() + + def test_window_title_and_root_header(self): + self.assertEqual(self.inspector.window.get_title(), + "LightGUI — Object Inspector") + self.project.clear_selection() + self.inspector.refresh() + self.assertEqual(self.inspector.selected_label.get_text(), + "Window (Root)") + self.assertIn("title", self.inspector.rows) + self.assertIn("background", self.inspector.rows) + + def test_selected_header_shows_name_and_kind(self): + self.assertEqual(self.inspector.selected_label.get_text(), + "GtkButton_001 (Button)") + + def test_rows_expand_to_fill_panel_width(self): + # The b96e545/29751be fix: every grid control hexpands. + self.assertTrue(self.inspector.controls) + for control in self.inspector.controls: + self.assertTrue(control.get_hexpand(), + "%r does not hexpand" % (control,)) + self.assertTrue(self.inspector.grid.get_hexpand()) + + def test_all_rows_present_for_button(self): + for name in ("left", "top", "width", "height", "name", + "label", "background", "font-name", "font-size", + "font-bold", "enabled"): + self.assertIn(name, self.inspector.rows, name) + for event in ("OnClick", "OnChange", "OnKeyPress", + "OnMouseDown", "OnMouseUp", "OnMouseMove", + "OnDblClick"): + self.assertIn(event, self.inspector.event_rows, event) + + def test_model_only_row_is_flagged(self): + labels = [c for c in self.inspector.grid.get_children() + if isinstance(c, Gtk.Label)] + texts = [label.get_text() for label in labels] + self.assertTrue(any(t.endswith(" *") for t in texts), + "no model-only row flagged: %r" % (texts,)) + + def test_editing_label_row_live_applies(self): + entry = self.inspector.entry_for("label") + entry.set_text("Hello Inspector") + self.assertEqual(self.button.get_prop("label"), + "Hello Inspector") + self.assertTrue(self.button.dirty) + + def test_geometry_spin_live_applies(self): + spin = self.inspector.editor_for("left") + self.assertIsInstance(spin, Gtk.SpinButton) + spin.set_value(42) + self.assertEqual(self.button.x, 42) + spin = self.inspector.editor_for("width") + spin.set_value(200) + self.assertEqual(self.button.width, 200) + + def test_bool_and_enum_rows_live_apply(self): + check = self.inspector.editor_for("enabled") + check.set_active(False) + self.assertEqual(self.button.get_prop("enabled"), "false") + combo = self.inspector.editor_for("align") + self.assertIsInstance(combo, Gtk.ComboBoxText) + combo.set_active(1) + self.assertEqual(self.button.get_prop("align"), "1") + + def test_font_picker_button_and_dialog(self): + editor = self.inspector.editor_for("font-name") + buttons = [c for c in editor.get_children() + if isinstance(c, Gtk.Button)] + self.assertEqual(len(buttons), 1) + self.assertEqual(buttons[0].get_label(), "Pick…") + dialog = self.inspector.make_font_dialog("Sans") + self.assertIsInstance(dialog, Gtk.FontChooserDialog) + dialog.destroy() + + def test_font_size_spin_has_steppers(self): + spin = self.inspector.editor_for("font-size") + self.assertIsInstance(spin, Gtk.SpinButton) + spin.set_value(20) + self.assertEqual(self.button.get_prop("font-size"), "20") + + def test_event_row_stores_handler(self): + entry = self.inspector.event_rows["OnClick"] + entry.set_text("on_button_click") + self.assertEqual(event_handler(self.button, "OnClick"), + "on_button_click") + + def test_selection_change_refresh_swaps_rows(self): + state = CanvasState(self.project) + state.on_selection_change = self.inspector.refresh + self.assertNotIn("wrap", self.inspector.rows) + label = self.project.add_widget("GtkLabel", 300, 10, 180, 30) + state.select(label.id) + self.assertEqual(self.inspector.selected_label.get_text(), + "GtkLabel_001 (Label)") + self.assertIn("wrap", self.inspector.rows) + state.key("Escape") + self.assertEqual(self.inspector.selected_label.get_text(), + "Window (Root)") + + def test_bulk_buttons_apply_to_right_widgets(self): + label = self.project.add_widget("GtkLabel", 300, 10, 180, 30) + self.project.clear_selection() + self.inspector.refresh() + child = self.inspector.bulk_param.get_child() + child.set_text("label") + self.inspector.bulk_value.set_text("Bulked") + self.inspector.bulk_buttons["all"].clicked() + self.assertEqual(self.button.get_prop("label"), "Bulked") + self.assertEqual(label.get_prop("label"), "Bulked") + self.inspector.bulk_value.set_text("Cleared?") + self.inspector.bulk_buttons["clear"].clicked() + self.assertNotIn("label", self.button.props) + + def test_colour_swatch_applies_to_selected_widget(self): + self.project.select(self.button.id) + self.inspector.refresh() + self.inspector.colour_swatches["#ff0000"].clicked() + self.assertEqual(self.button.get_prop("background"), "#ff0000") + + def test_colour_swatch_applies_to_window_when_none_selected(self): + self.project.clear_selection() + self.inspector.refresh() + self.inspector.colour_swatches["#0000ff"].clicked() + self.assertEqual(self.project.background, "#0000ff") + + def test_spot_check_grids_for_representative_kinds(self): + for kind in ("GtkLabel", "GtkEntry", "GtkComboBox", + "GtkCalendar", "GtkCheckButton", "GtkTextView", + "GtkScale", "GtkNotebook", "GtkImage", + "GtkProgressBar"): + widget = self.project.add_widget(kind, 10, 10) + self.project.select(widget.id) + self.inspector.refresh() + self.assertTrue(self.inspector.controls, + "%s built no rows" % kind) + for control in self.inspector.controls: + self.assertTrue(control.get_hexpand()) + self.project.remove_widget(widget.id) + self.project.clear_selection() + self.inspector.refresh() + + +if __name__ == "__main__": + unittest.main()