837 lines
32 KiB
Python
837 lines
32 KiB
Python
"""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,
|
|
on_change=None):
|
|
self.project = project
|
|
self.canvas_state = canvas_state
|
|
self.on_status = on_status
|
|
# Called whenever an edit changes project data (prop, event,
|
|
# bulk, colour, root) so the app can mark the project dirty.
|
|
# The canvas redraw itself still goes through widget.on_change
|
|
# / CanvasState._changed, as before.
|
|
self.on_change = on_change
|
|
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)
|
|
# One shared side margin for the whole box: the grid rows
|
|
# already fill the width, and the Bulk / Colour sections
|
|
# below used to butt against the window edge (their hint text
|
|
# was clipped).
|
|
self.props_box.set_margin_start(6)
|
|
self.props_box.set_margin_end(6)
|
|
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_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_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)
|
|
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()
|
|
self._notify_change()
|
|
|
|
def _notify_change(self):
|
|
if self.on_change is not None:
|
|
self.on_change()
|
|
|
|
# --- 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("<b>%s</b>" % 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)
|
|
self._notify_change()
|
|
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
|
|
self._notify_change()
|
|
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())
|
|
self._notify_change()
|
|
|
|
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("<b>Bulk parameter</b>")
|
|
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("<b>Colour palette</b>")
|
|
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()
|