diff --git a/lightgui/model.py b/lightgui/model.py index 6043edf..6913d21 100644 --- a/lightgui/model.py +++ b/lightgui/model.py @@ -98,10 +98,16 @@ class Project: 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: - widget.set_prop("text", name) + 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 diff --git a/lightgui/props.py b/lightgui/props.py index 30e55e6..3cd2d31 100644 --- a/lightgui/props.py +++ b/lightgui/props.py @@ -36,10 +36,10 @@ EVENTS = ("OnClick", "OnChange", "OnKeyPress", "OnKeyDown", "OnKeyUp", "OnMouseD GENERIC_PROPS = ( PropDef("name", "Str", "", 0, 0, (), (), "Name", False), - PropDef("left", "Int", "0", 0, 100000, (), (), "Left", False), - PropDef("top", "Int", "0", 0, 100000, (), (), "Top", False), - PropDef("width", "Int", "100", 10, 100000, (), (), "Width", False), - PropDef("height", "Int", "30", 10, 100000, (), (), "Height", False), + PropDef("left", "Int", "0", 0, 0, (), (), "Left", False), + PropDef("top", "Int", "0", 0, 0, (), (), "Top", False), + PropDef("width", "Int", "100", 0, 0, (), (), "Width", False), + PropDef("height", "Int", "30", 0, 0, (), (), "Height", False), PropDef("background", "Color", "", 0, 0, (), (), "Color", False), PropDef("foreground", "Color", "", 0, 0, (), (), "Font.Color", False), PropDef("border-width", "Int", "0", 0, 100, (), (), "Border.Width", False), diff --git a/lightgui/xframe/canvas.py b/lightgui/xframe/canvas.py index 4bbcbbb..b91a089 100644 --- a/lightgui/xframe/canvas.py +++ b/lightgui/xframe/canvas.py @@ -102,9 +102,16 @@ class CanvasState: self._changed() # --- placement / mutation ---------------------------------------------- + def _wire(self, widget): + # Live-apply: a widget prop change notifies the canvas, which + # redraws (Widget.set_prop is state-only; the host redraws). + if widget is not None: + widget.on_change = self._changed + def place(self, kind, x, y, width=None, height=None): widget = self.project.add_widget(kind, x, y, width, height) if widget is not None: + self._wire(widget) self.handles_on = False self._changed() return widget @@ -172,6 +179,7 @@ class CanvasState: max(x - self._pending_default_w() // 2, 0), max(y - self._pending_default_h() // 2, 0)) if placed is not None: + self._wire(placed) self.handles_on = False self._changed() return True @@ -249,6 +257,8 @@ class Canvas(Gtk.DrawingArea): super().__init__() self.state = state if state is not None else CanvasState(project) self.state.on_change = self._on_state_change + for widget in self.state.project.widgets: + self.state._wire(widget) self.set_hexpand(True) self.set_vexpand(True) self.set_can_focus(True) @@ -336,6 +346,7 @@ class Canvas(Gtk.DrawingArea): cr.restore() for widget in self.state.project.widgets: widget.draw(cr) + widget.dirty = False selected = self.state.selected if selected is not None: cr.save() diff --git a/lightgui/xframe/core.py b/lightgui/xframe/core.py index 3f27716..830e744 100644 --- a/lightgui/xframe/core.py +++ b/lightgui/xframe/core.py @@ -15,13 +15,30 @@ never draw. The host (the canvas) redraws. Same convention as C/Rust. Draw dispatch is by archetype (the Rust port's model: a small set of archetype classes parameterised by ``kind``, not 547 widget classes). -Each archetype draws itself with Cairo on the canvas context. The -Phase 1 drawings are deliberately simple but recognisable — faithful -per-widget rendering is Phase 2/6 work. +Each archetype draws itself with Cairo on the canvas context. Phase 2 +drawings are faithful per-widget renderings ported from the Rust +archetypes (crates/xframe-widgets/src/archetypes.rs) and the C widget +draw() methods: buttons, entries, labels, toggles, combos, lists, +scrollbars, scales, text views, containers, images, progress bars, +spin edits, calendars, colour pickers, list/tree views, notebooks, +menus/toolbars/statusbar/splitter/shape, dialogs/windows. Pixel +parity with C is NOT required; drawings must be recognisable as the +widget. Stock / Instrumentation families keep the Phase 1 panel +drawing; their faithful rendering is Phase 6 work. + +Live-apply (Phase 2): ``Widget.set_prop`` validates against the +property table in :mod:`lightgui.props`, updates state, marks the +widget dirty and notifies the host (``on_change``) so the canvas +redraws. Widget-level setters (``set_items``, ``set_password``, +``set_direction``, ``set_cursor_visible``, ``set_lower``, +``set_page_increment``) are the same state-only setters the C work +added, built on ``set_prop``. """ import math +import re +from lightgui import props as _props from lightgui.xframe import palette as _palette # --- interaction constants (C xframe_canvas_core.cpp / Rust canvas.rs) --- @@ -43,11 +60,46 @@ HANDLE_RGB = (1.0, 127 / 255, 0.0) GRID_STEP = 24 +_NAMED_RGB = { + "black": (0.0, 0.0, 0.0), "white": (1.0, 1.0, 1.0), + "red": (0.85, 0.1, 0.2), "green": (0.0, 0.55, 0.15), + "blue": (0.1, 0.25, 0.8), "yellow": (0.95, 0.85, 0.1), + "orange": (0.95, 0.5, 0.05), "purple": (0.55, 0.2, 0.75), + "teal": (0.0, 0.6, 0.6), "magenta": (0.85, 0.2, 0.65), + "brown": (0.55, 0.35, 0.15), "gray": (0.5, 0.5, 0.5), + "grey": (0.5, 0.5, 0.5), "pink": (0.95, 0.6, 0.7), + "cyan": (0.0, 0.8, 0.8), "transparent": (0.0, 0.0, 0.0), +} + def _rgb(cr, rgb, alpha=1.0): cr.set_source_rgba(rgb[0], rgb[1], rgb[2], alpha) +def parse_color(text, default=None): + """Parse a prop colour (``rgb(r,g,b)``, ``#rrggbb``, ``#rgb`` or a + colour name) to an (r, g, b) tuple in 0..1, or *default*.""" + if text is None: + return default + text = str(text).strip() + if not text: + return default + match = re.match(r"rgb\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)", text) + if match: + return tuple(int(v) / 255.0 for v in match.groups()) + if text.startswith("#"): + digits = text[1:] + if len(digits) == 3 and all(c in "0123456789abcdefABCDEF" + for c in digits): + digits = "".join(c * 2 for c in digits) + if len(digits) == 6 and all(c in "0123456789abcdefABCDEF" + for c in digits): + return tuple(int(digits[i:i + 2], 16) / 255.0 + for i in (0, 2, 4)) + return default + return _NAMED_RGB.get(text.lower(), default) + + def _fit_text(cr, text, max_width): """Truncate *text* with an ellipsis so it fits *max_width*.""" if cr.text_extents(text)[2] <= max_width: @@ -57,6 +109,20 @@ def _fit_text(cr, text, max_width): return text + "..." if text else "" +def _apply_font(cr, widget, size=13, bold=None): + """Select the Cairo toy font from the widget's Font props.""" + name = widget.get_prop("font-name", "") or "Sans" + if bold is None: + bold = widget.get_prop("font-bold", "false") in ("true", "1") + italic = widget.get_prop("font-italic", "false") in ("true", "1") + try: + size = float(widget.get_prop("font-size", "")) or size + except ValueError: + pass + cr.select_font_face(name, 1 if italic else 0, 1 if bold else 0) + cr.set_font_size(max(size, 4)) + + def _text(cr, text, x, y, size=13, rgb=(0.12, 0.12, 0.12), align="left", max_width=None, bold=False): """Draw one line of text with the Cairo toy font API.""" @@ -79,6 +145,57 @@ def _text(cr, text, x, y, size=13, rgb=(0.12, 0.12, 0.12), align="left", cr.restore() +def _wtext(cr, widget, text, x, y, size=13, rgb=None, align="left", + max_width=None, bold=None): + """Draw one line of text honouring the widget's Font props and + ``foreground`` (font/text colour) prop.""" + if not text: + return + if rgb is None: + rgb = parse_color(widget.get_prop("foreground", ""), + (0.12, 0.12, 0.12)) + cr.save() + _apply_font(cr, widget, size=size, bold=bold) + if max_width is not None: + text = _fit_text(cr, text, max_width) + _rgb(cr, rgb) + if align == "center": + w = cr.text_extents(text)[2] + x -= w / 2 + elif align == "right": + w = cr.text_extents(text)[2] + x -= w + cr.move_to(x, y) + cr.show_text(text) + cr.restore() + + +def _text_width(cr, widget, text, size=13, bold=None): + cr.save() + _apply_font(cr, widget, size=size, bold=bold) + width = cr.text_extents(text)[2] + cr.restore() + return width + + +def _wrap_lines(cr, widget, text, max_width, size=13): + """Word-wrap *text* to lines fitting *max_width* (Cairo extents).""" + lines = [] + for paragraph in str(text).split("\n"): + words = paragraph.split(" ") if paragraph else [""] + current = "" + for word in words: + trial = (current + " " + word).strip() + if (_text_width(cr, widget, trial, size=size) <= max_width + or not current): + current = trial + else: + lines.append(current) + current = word + lines.append(current) + return lines + + def _box(cr, x, y, w, h, fill, stroke=(0.5, 0.5, 0.5), line_width=1.0): cr.save() cr.set_line_width(line_width) @@ -90,6 +207,127 @@ def _box(cr, x, y, w, h, fill, stroke=(0.5, 0.5, 0.5), line_width=1.0): cr.restore() +def _rounded_path(cr, x, y, w, h, radius): + radius = max(0.0, min(float(radius), min(w, h) / 2.0)) + if radius <= 0: + cr.rectangle(x, y, w, h) + return + cr.move_to(x + radius, y) + cr.line_to(x + w - radius, y) + cr.arc(x + w - radius, y + radius, radius, -math.pi / 2, 0) + cr.line_to(x + w, y + h - radius) + cr.arc(x + w - radius, y + h - radius, radius, 0, math.pi / 2) + cr.line_to(x + radius, y + h) + cr.arc(x + radius, y + h - radius, radius, math.pi / 2, math.pi) + cr.line_to(x, y + radius) + cr.arc(x + radius, y + radius, radius, math.pi, 3 * math.pi / 2) + cr.close_path() + + +def _rounded_box(cr, x, y, w, h, fill, stroke=(0.5, 0.5, 0.5), + line_width=1.0, radius=0): + cr.save() + cr.set_line_width(line_width) + _rounded_path(cr, x + 0.5, y + 0.5, w - 1, h - 1, radius) + _rgb(cr, fill) + cr.fill_preserve() + _rgb(cr, stroke) + cr.stroke() + cr.restore() + + +def _border_radius(widget, default=0): + try: + return max(int(widget.get_prop("border-radius", "0")), 0) + except ValueError: + return default + + +def _bg(cr, widget, default_fill, stroke=(0.5, 0.5, 0.5)): + """Outer fill for a widget: the ``background`` prop, else the + archetype default; the ``border-color``/``border-width`` props + replace the default stroke when set.""" + fill = parse_color(widget.get_prop("background", ""), default_fill) + width = 1.0 + try: + width = max(float(widget.get_prop("border-width", "0") or 0), 0) + except ValueError: + width = 1.0 + stroke = parse_color(widget.get_prop("border-color", ""), stroke) + _rounded_box(cr, 0, 0, widget.width, widget.height, fill, + stroke, line_width=width if width else 1.0, + radius=_border_radius(widget)) + + +def _triangle(cr, cx, cy, size, direction, rgb=(0.3, 0.3, 0.3)): + """Filled triangle: direction up/down/left/right.""" + half = size / 2.0 + cr.save() + _rgb(cr, rgb) + cr.move_to(cx, cy) + if direction == "down": + cr.move_to(cx - half, cy - half) + cr.line_to(cx + half, cy - half) + cr.line_to(cx, cy + half) + elif direction == "up": + cr.move_to(cx - half, cy + half) + cr.line_to(cx + half, cy + half) + cr.line_to(cx, cy - half) + elif direction == "left": + cr.move_to(cx + half, cy - half) + cr.line_to(cx + half, cy + half) + cr.line_to(cx - half, cy) + else: # right + cr.move_to(cx - half, cy - half) + cr.line_to(cx - half, cy + half) + cr.line_to(cx + half, cy) + cr.close_path() + cr.fill() + cr.restore() + + +def _checkmark(cr, cx, cy, size, rgb=(0.15, 0.15, 0.15)): + cr.save() + _rgb(cr, rgb) + cr.set_line_width(max(2.0, size / 6.0)) + cr.set_line_cap(1) # round + half = size / 2.0 + cr.move_to(cx - half, cy) + cr.line_to(cx - half / 3, cy + half * 0.6) + cr.line_to(cx + half, cy - half * 0.7) + cr.stroke() + cr.restore() + + +def _prop_bool(widget, name, default=False): + return widget.get_prop(name, "true" if default else "false") \ + in ("true", "1", "yes") + + +def _prop_float(widget, name, default=0.0): + try: + return float(widget.get_prop(name, "")) + except (TypeError, ValueError): + return default + + +def _prop_int(widget, name, default=0): + try: + return int(float(widget.get_prop(name, ""))) + except (TypeError, ValueError): + return default + + +def _range_frac(widget, value_name="value", lo_name="minimum", + hi_name="maximum", default_frac=0.5): + """Fraction of (value - lo) / (hi - lo), clamped to 0..1.""" + lo = _prop_float(widget, lo_name, 0.0) + hi = _prop_float(widget, hi_name, 100.0) + value = _prop_float(widget, value_name, (lo + hi) / 2.0) + if hi <= lo: + return default_frac + return max(0.0, min(1.0, (value - lo) / (hi - lo))) + class Widget: """One placed XFrame widget. @@ -118,8 +356,13 @@ class Widget: # Canvas-owned UI state (not saved in .fdj). self.selected = False self.handles_on = False + # Live-apply: set after any state change; the host clears it + # when it redraws. ``on_change`` is set by the canvas to its + # redraw hook (CanvasState._changed). + self.dirty = False + self.on_change = None - # --- archetype ------------------------------------------------------ + # --- archetype / property table --------------------------------------- @property def archetype(self): entry = _palette.find(self.kind) @@ -127,6 +370,18 @@ class Widget: return entry.archetype return self.ARCHETYPE + @property + def pkind(self): + """Palette kind (``"Button"`` for both GtkButton and TButton).""" + entry = _palette.find(self.kind) + return entry.kind if entry is not None else self.kind + + def prop_names(self): + return _props.prop_names(self.kind) + + def prop_def(self, name): + return _props.find_prop(self.kind, name) + @property def default_width(self): entry = _palette.find(self.kind) @@ -138,6 +393,11 @@ class Widget: return entry.default_h if entry is not None else 30 # --- state-only setters (the host redraws) ------------------------- + def _mark_dirty(self): + self.dirty = True + if self.on_change is not None: + self.on_change() + def set_bounds(self, x, y, width, height): """Canvas-side bounds set (handle drag): 24x16 minimum and x/y >= 0, mirroring C apply_handle_drag.""" @@ -145,25 +405,60 @@ class Widget: self.y = max(int(y), 0) self.width = max(int(width), MIN_WIDTH) self.height = max(int(height), MIN_HEIGHT) + self._mark_dirty() def move_to(self, x, y): self.x = max(int(x), 0) self.y = max(int(y), 0) + self._mark_dirty() def resize_to(self, width, height): # Model resize: 10px floor, the same as the C .fdj loader. self.width = max(int(width), 10) self.height = max(int(height), 10) + self._mark_dirty() def set_prop(self, name, value): - """Store a property value (as a string). No live apply here.""" - self.props[str(name)] = "" if value is None else str(value) + """Live-apply a property: validate against the property table + (raises ValueError for an unknown prop or a bad value), update + state, mark the widget dirty and notify the host so the canvas + redraws. Setters are state-only; the host redraws. + + ``name``/``left``/``top``/``width``/``height`` are the generic + Name/geometry props: they update the widget fields (geometry + with the same floors as move_to/resize_to), not ``props``. + """ + name = str(name) + canonical = _props.validate(self.kind, name, value) + if name == "name": + self.name = canonical + elif name == "left": + self.x = max(int(canonical), 0) + elif name == "top": + self.y = max(int(canonical), 0) + elif name == "width": + self.width = max(int(canonical), 10) + elif name == "height": + self.height = max(int(canonical), 10) + else: + self.props[name] = canonical + self._mark_dirty() + return canonical def get_prop(self, name, default=""): return self.props.get(str(name), default) def set_text(self, value): - self.set_prop("text", value) + """Set the caption/text prop (``text`` where the table has it, + else ``label``), like the Rust seed_defaults / set_text.""" + name = ("text" if "text" in self.prop_names() + else "label" if "label" in self.prop_names() + else "text") + if name in self.prop_names(): + self.set_prop(name, value) + else: + self.props[name] = "" if value is None else str(value) + self._mark_dirty() @property def text(self): @@ -171,6 +466,131 @@ class Widget: return (self.props.get("text") or self.props.get("label") or self.name) + # --- widget-level setters (C getter/setter pass, proposal SS4) ------- + def get_items(self): + """Items list (``items`` prop, ``|``-separated).""" + raw = self.get_prop("items", "") + return [item for item in raw.split("|") if item != ""] if raw \ + else [] + + def set_items(self, items): + """ComboBox/ListBox set_items, built ourselves (no GTK): + replaces the item list and drops checked-items that are no + longer present (CheckListBox). Live: marks the widget dirty.""" + if isinstance(items, str): + raw = items + else: + raw = "|".join(str(item) for item in items) + self.set_prop("items", raw) + checked = self.get_checked_items() + if checked: + kept = [c for c in checked if c in self.get_items()] + if kept != checked: + self.props["checked-items"] = "|".join(kept) + + def get_checked_items(self): + """CheckListBox per-item checked state (``checked-items``).""" + raw = self.get_prop("checked-items", "") + return [item for item in raw.split("|") if item != ""] if raw \ + else [] + + def set_checked_items(self, items): + """CheckListBox: replace the checked-item set. Items not in + the item list are ignored.""" + if isinstance(items, str): + wanted = [i for i in items.split("|") if i != ""] + else: + wanted = [str(i) for i in items] + have = self.get_items() + kept = [i for i in wanted if i in have] + self.set_prop("checked-items", "|".join(kept)) + + def set_item_checked(self, item, checked): + checked_items = self.get_checked_items() + if checked and item in self.get_items() \ + and item not in checked_items: + checked_items.append(item) + elif not checked and item in checked_items: + checked_items.remove(item) + else: + return + self.set_prop("checked-items", "|".join(checked_items)) + + def is_item_checked(self, item): + return item in self.get_checked_items() + + def set_password(self, enabled): + """Entry password (masked ``***`` by default; ShowPassword + reveals). Rust Entry has set_password; C did not (proposal + SS3.3/SS4.5).""" + self.set_prop("password", bool(enabled)) + + def get_password(self): + return _prop_bool(self, "password", False) + + def set_show_password(self, show): + self.set_prop("show-password", bool(show)) + + def get_show_password(self): + return _prop_bool(self, "show-password", False) + + def set_direction(self, direction): + """MenuButton direction (Up/Down/Left/Right/None, proposal + SS4.6): the arrow triangle points where the popup opens.""" + self.set_prop("direction", direction) + + def get_direction(self): + raw = self.get_prop("direction", "1") + try: + return int(raw) + except ValueError: + labels = ("Up", "Down", "Left", "Right", "None") + return labels.index(raw) if raw in labels else 1 + + def set_cursor_visible(self, visible): + """TextView cursor-visible (proposal SS4.7).""" + self.set_prop("cursor-visible", bool(visible)) + + def get_cursor_visible(self): + return _prop_bool(self, "cursor-visible", True) + + def set_lower(self, value): + """ScrollBar lower bound (proposal SS4.4; set_range covers + lower+upper in C/Rust, this exposes lower on its own).""" + self.set_prop("lower", value) + + def get_lower(self): + return _prop_float(self, "lower", 0.0) + + def set_page_increment(self, value): + """ScrollBar page-increment / LargeChange (proposal SS4.4).""" + self.set_prop("page-increment", value) + + def get_page_increment(self): + return _prop_float(self, "page-increment", 10.0) + + def set_value(self, value): + """Range value, clamped to minimum..maximum where the table + has them.""" + if "minimum" in self.prop_names() and "maximum" in self.prop_names(): + lo = _prop_float(self, "minimum", 0.0) + hi = _prop_float(self, "maximum", 100.0) + try: + value = max(lo, min(hi, float(value))) + except (TypeError, ValueError): + pass + self.set_prop("value", value) + + def get_value(self): + return _prop_float(self, "value", 0.0) + + def set_active(self, active): + """Toggle checked/active state.""" + self.set_prop("active", bool(active)) + + def get_active(self): + return _prop_bool(self, "active", False) + # --- hit-testing ---------------------------------------------------- def contains(self, px, py): return (self.x <= px <= self.x + self.width @@ -228,77 +648,326 @@ class Widget: # --- drawing -------------------------------------------------------- def draw(self, cr): - """Draw the widget at its bounds. Dispatches on archetype.""" + """Draw the widget at its bounds. Dispatches on archetype. + Invisible widgets draw nothing (Rust: visible check first in + every archetype draw); disabled widgets are dimmed.""" + if self.get_prop("visible", "true") in ("false", "0"): + return cr.save() cr.translate(self.x, self.y) cr.rectangle(0, 0, self.width, self.height) cr.clip() self._draw(cr) + if self.get_prop("enabled", "true") in ("false", "0"): + _rgb(cr, (1.0, 1.0, 1.0), 0.45) + cr.rectangle(0, 0, self.width, self.height) + cr.fill() cr.restore() def _draw(self, cr): _draw_display(cr, self) - # --- archetype widgets --------------------------------------------------- -# One class per Rust Archetype enum value. Phase 1 drawings are simple -# but recognisable; faithful per-widget rendering is later-phase work. +# One class per Rust Archetype enum value, parameterised by ``kind``. +# Drawings port the Rust archetypes (crates/xframe-widgets/src/ +# archetypes.rs) and the C widget draw() methods: a button is a +# rounded, top-lit body with centred caption; a checkbox is a square +# box with a checkmark; a radio button a ring with a dot; an entry a +# white inset field; and so on. Kind-specific branches live inside +# each archetype's _draw -- there are no 547 widget classes. + +import cairo as _cairo + + +def _button_body(cr, widget, fill_top=(0.98, 0.98, 0.98), + fill_bottom=(0.86, 0.86, 0.88), pressed=False): + """Raised-button body: rounded rect, light-top gradient, grey + outline (Rust draw_button_body). ``pressed`` inverts the light.""" + w, h = widget.width, widget.height + radius = _border_radius(widget, 4) + top = fill_bottom if pressed else fill_top + bottom = fill_top if pressed else fill_bottom + bg = parse_color(widget.get_prop("background", ""), None) + if bg is not None: + top, bottom = bg, bg + gradient = _cairo.LinearGradient(0, 0, 0, h) + gradient.add_color_stop_rgb(0, *top) + gradient.add_color_stop_rgb(1, *bottom) + cr.save() + _rounded_path(cr, 0.5, 0.5, w - 1, h - 1, radius) + cr.set_source(gradient) + cr.fill_preserve() + _rgb(cr, parse_color(widget.get_prop("border-color", ""), + (0.45, 0.45, 0.48))) + cr.set_line_width(max(float(widget.get_prop("border-width", "0") + or 0), 0) or 1.0) + cr.stroke() + cr.restore() + + +def _strip_accel(text, show_accel_char=True): + """Rust LabelWidget::display_text: a single '&' marks the + accelerator and is stripped; '&&' is a literal '&'.""" + if not show_accel_char: + return text + out = [] + i = 0 + while i < len(text): + ch = text[i] + if ch == "&" and i + 1 < len(text) and text[i + 1] == "&": + out.append("&") + i += 2 + elif ch == "&": + i += 1 + else: + out.append(ch) + i += 1 + return "".join(out) + class ButtonWidget(Widget): ARCHETYPE = "Button" def _draw(self, cr): - _box(cr, 0, 0, self.width, self.height, (0.92, 0.92, 0.92), - (0.45, 0.45, 0.45)) - cr.save() - _rgb(cr, (1.0, 1.0, 1.0), 0.6) - cr.rectangle(1, 1, self.width - 2, max(self.height / 2 - 1, 1)) + kind = self.pkind + if kind == "LinkButton": + # Blue underlined caption, no body (Rust: link style). + _wtext(cr, self, self.text, self.width / 2, + self.height / 2 + 5, align="center", + rgb=(0.1, 0.3, 0.85), max_width=self.width - 8) + cr.save() + _rgb(cr, (0.1, 0.3, 0.85)) + cr.set_line_width(1) + w = _text_width(cr, self, self.text) + x0 = self.width / 2 - w / 2 + cr.move_to(x0, self.height / 2 + 8) + cr.line_to(x0 + w, self.height / 2 + 8) + cr.stroke() + cr.restore() + return + _button_body(cr, self, + pressed=_prop_bool(self, "active", False) + and kind in ("ToggleToolButton",)) + if _prop_bool(self, "default", False): + # Default button: extra inner outline (Rust Button draw). + cr.save() + _rgb(cr, (0.25, 0.45, 0.75)) + cr.set_line_width(1.5) + cr.rectangle(2.5, 2.5, self.width - 5, self.height - 5) + cr.stroke() + cr.restore() + text_x = self.width / 2 + text_left = 8 + if kind in ("ColorButton", "ColorDialogButton"): + # Colour swatch on the left, caption beside it. + colour = parse_color(self.get_prop("color", ""), + (53 / 255, 132 / 255, 228 / 255)) + sw = min(22, self.height - 10) + _box(cr, 6, (self.height - sw) / 2, sw, sw, colour, + (0.4, 0.4, 0.4)) + text_left = 6 + sw + 8 + _wtext(cr, self, self.text, text_left, self.height / 2 + 5, + max_width=self.width - text_left - 6) + elif kind == "LockButton": + _draw_padlock(cr, 14, self.height / 2, 10) + _wtext(cr, self, self.text, 28, self.height / 2 + 5, + max_width=self.width - 34) + elif kind in ("FileChooserButton", "FontButton", "VolumeButton", + "ToolButton", "ToggleToolButton", "ModelButton", + "AppChooserButton", "EditButton", "BitBtn"): + _draw_button_glyph(cr, self, kind) + _wtext(cr, self, self.text, 30, self.height / 2 + 5, + max_width=self.width - 36) + else: + _wtext(cr, self, self.text, text_x, self.height / 2 + 5, + align="center", max_width=self.width - 12) + if kind == "MenuButton": + # Arrow on the side the popup opens toward (Rust Button + # draw: 0 Up, 2 Left, 3 Right, 4 None, else Down). + direction = self.get_direction() + cy = self.height / 2 + if direction == 0: + _triangle(cr, self.width - 12, cy, 9, "up") + elif direction == 2: + _triangle(cr, 12, cy, 9, "left") + elif direction == 3: + _triangle(cr, self.width - 12, cy, 9, "right") + elif direction != 4: + _triangle(cr, self.width - 12, cy, 9, "down") + + +def _draw_padlock(cr, cx, cy, size): + cr.save() + _rgb(cr, (0.25, 0.25, 0.25)) + cr.set_line_width(1.5) + cr.arc(cx, cy - size * 0.25, size * 0.45, math.pi, 2 * math.pi) + cr.stroke() + _rgb(cr, (0.85, 0.75, 0.25)) + cr.rectangle(cx - size / 2, cy - size * 0.2, size, size * 0.75) + cr.fill_preserve() + _rgb(cr, (0.25, 0.25, 0.25)) + cr.stroke() + cr.restore() + + +def _draw_button_glyph(cr, widget, kind): + """Small glyph in the 24px icon slot at the left of a button.""" + x, y = 6, (widget.height - 16) / 2 + cr.save() + if kind == "FileChooserButton": + _rgb(cr, (0.95, 0.85, 0.5)) + cr.rectangle(x, y + 3, 16, 12) + cr.fill_preserve() + _rgb(cr, (0.5, 0.4, 0.1)) + cr.stroke() + _rgb(cr, (0.95, 0.85, 0.5)) + cr.rectangle(x, y, 8, 4) cr.fill() - cr.restore() - _text(cr, self.text, self.width / 2, self.height / 2 + 5, - align="center", max_width=self.width - 12) + elif kind == "FontButton": + _text(cr, "A", x + 8, y + 13, size=14, align="center", + rgb=(0.15, 0.15, 0.15), bold=True) + elif kind == "VolumeButton": + _rgb(cr, (0.2, 0.2, 0.2)) + cr.move_to(x + 2, y + 8) + cr.line_to(x + 7, y + 8) + cr.line_to(x + 12, y + 3) + cr.line_to(x + 12, y + 13) + cr.line_to(x + 7, y + 8) + cr.close_path() + cr.fill() + elif kind == "BitBtn": + _rgb(cr, (0.3, 0.55, 0.85)) + cr.rectangle(x + 2, y + 2, 12, 12) + cr.fill_preserve() + _rgb(cr, (1.0, 1.0, 1.0)) + cr.set_line_width(1.5) + cr.move_to(x + 4, y + 8) + cr.line_to(x + 7, y + 11) + cr.line_to(x + 13, y + 5) + cr.stroke() + else: # ToolButton / ModelButton / AppChooserButton / EditButton + _rgb(cr, (0.35, 0.55, 0.8)) + cr.rectangle(x + 2, y + 2, 12, 12) + cr.fill_preserve() + _rgb(cr, (0.4, 0.4, 0.4)) + cr.stroke() + cr.restore() class ToggleWidget(Widget): ARCHETYPE = "Toggle" def _draw(self, cr): - if self.kind in ("GtkSwitch", "TSwitch"): + kind = self.pkind + if kind == "Switch": _draw_switch(cr, self) return - box = 14 - y = (self.height - box) / 2 - _box(cr, 4, y, box, box, (1.0, 1.0, 1.0), (0.4, 0.4, 0.4)) - if "Radio" in self.kind or "TRadio" in self.kind: - cr.save() - _rgb(cr, (0.2, 0.2, 0.2)) - cr.arc(4 + box / 2, y + box / 2, 3.5, 0, 2 * math.pi) - cr.fill() - cr.restore() - elif self.get_prop("checked", "false") in ("true", "1"): + if kind in ("RadioButton", "RadioMenuItem"): + self._draw_radio(cr, kind) + return + if kind == "CheckMenuItem": + self._draw_menu_check(cr, radio=False) + return + if kind == "RadioMenuItem": + self._draw_menu_check(cr, radio=True) + return + if kind in ("ToggleButton", "ToggleBox", "SpeedButton"): + self._draw_toggle_button(cr) + return + # CheckBox / CheckButton and the rest: square box + check. + self._draw_check(cr) + + def _box_x(self, size): + # Box position: alignment 0 = left, 1 = right (Rust Toggle). + if _prop_int(self, "alignment", 0) == 1: + return self.width - 6 - size + return 6 + + def _draw_check(self, cr): + size = min(16, self.height - 8) + x = self._box_x(size) + y = (self.height - size) / 2 + _box(cr, x, y, size, size, (1.0, 1.0, 1.0), (0.4, 0.4, 0.4)) + cy = self.height / 2 + if _prop_bool(self, "inconsistent", False): cr.save() _rgb(cr, (0.2, 0.2, 0.2)) cr.set_line_width(2) - cr.move_to(7, y + 7) - cr.line_to(10, y + 11) - cr.line_to(16, y + 4) + cr.move_to(x + 3, cy) + cr.line_to(x + size - 3, cy) cr.stroke() cr.restore() - _text(cr, self.text, 24, self.height / 2 + 5, - max_width=self.width - 28) + elif self.get_active(): + _checkmark(cr, x + size / 2, cy, size - 4) + text_x = x + size + 8 if _prop_int(self, "alignment", 0) == 0 \ + else 6 + _wtext(cr, self, self.text, text_x, cy + 5, + max_width=self.width - text_x - 6) + + def _draw_radio(self, cr, kind): + size = min(16, self.height - 8) + x = self._box_x(size) + cy = self.height / 2 + cr.save() + _rgb(cr, (1.0, 1.0, 1.0)) + cr.arc(x + size / 2, cy, size / 2, 0, 2 * math.pi) + cr.fill_preserve() + _rgb(cr, (0.4, 0.4, 0.4)) + cr.set_line_width(1) + cr.stroke() + if self.get_active(): + _rgb(cr, (0.2, 0.2, 0.2)) + cr.arc(x + size / 2, cy, size / 4, 0, 2 * math.pi) + cr.fill() + cr.restore() + text_x = x + size + 8 if _prop_int(self, "alignment", 0) == 0 \ + else 6 + _wtext(cr, self, self.text, text_x, cy + 5, + max_width=self.width - text_x - 6) + + def _draw_menu_check(self, cr, radio): + _bg(cr, self, (1.0, 1.0, 1.0), stroke=(0.85, 0.85, 0.85)) + if self.get_active(): + if radio: + cr.save() + _rgb(cr, (0.2, 0.2, 0.2)) + cr.arc(12, self.height / 2, 4, 0, 2 * math.pi) + cr.fill() + cr.restore() + else: + _checkmark(cr, 12, self.height / 2, 10) + _wtext(cr, self, self.text, 26, self.height / 2 + 5, + max_width=self.width - 32) + + def _draw_toggle_button(self, cr): + flat = _prop_bool(self, "flat", False) + active = self.get_active() + if flat and not active: + _wtext(cr, self, self.text, self.width / 2, + self.height / 2 + 5, align="center", + max_width=self.width - 12) + return + _button_body(cr, self, pressed=active) + _wtext(cr, self, self.text, self.width / 2, + self.height / 2 + 5, align="center", + max_width=self.width - 12) def _draw_switch(cr, widget): w, h = widget.width, widget.height track_h = min(20, h - 4) + track_w = min(w - 4, max(2 * track_h, 36)) + x = (w - track_w) / 2 y = (h - track_h) / 2 + on = widget.get_active() cr.save() - _rgb(cr, (0.75, 0.75, 0.75)) - cr.rectangle(2, y, w - 4, track_h) + _rounded_path(cr, x, y, track_w, track_h, track_h / 2) + _rgb(cr, (0.2, 0.55, 0.9) if on else (0.72, 0.72, 0.74)) cr.fill() + knob_r = track_h / 2 - 2 + knob_x = (x + track_w - knob_r - 2) if on else (x + knob_r + 2) _rgb(cr, (1.0, 1.0, 1.0)) - cr.arc(2 + track_h / 2, y + track_h / 2, track_h / 2 - 1, 0, - 2 * math.pi) + cr.arc(knob_x, y + track_h / 2, knob_r, 0, 2 * math.pi) cr.fill() cr.restore() @@ -307,93 +976,971 @@ class LabelWidget(Widget): ARCHETYPE = "Label" def _draw(self, cr): - _text(cr, self.text, 2, self.height / 2 + 5, - max_width=self.width - 4) + if parse_color(self.get_prop("background", ""), None) is not None \ + and not _prop_bool(self, "transparent", False): + _bg(cr, self, (1.0, 1.0, 1.0), stroke=(1.0, 1.0, 1.0)) + text = _strip_accel( + self.text, + _prop_bool(self, "show-accel-char", True)) + xalign = max(0.0, min(1.0, _prop_float(self, "xalign", 0.0))) + yalign = max(0.0, min(1.0, _prop_float(self, "yalign", 0.5))) + size = 13 + try: + size = float(self.get_prop("font-size", "")) or 13 + except ValueError: + pass + if _prop_bool(self, "wrap", False): + lines = _wrap_lines(cr, self, text, self.width - 4, size=size) + line_h = size + 5 + total = line_h * len(lines) + y = max(2, (self.height - total) * yalign) + size + for line in lines: + x = 2 + (self.width - 4 - _text_width(cr, self, line, + size=size)) * xalign + _wtext(cr, self, line, x, y, size=size) + y += line_h + return + width = _text_width(cr, self, text, size=size) + x = 2 + (self.width - 4 - width) * xalign + y = self.height * yalign + size * 0.5 + _wtext(cr, self, text, x, y, size=size, + max_width=self.width - 4 if xalign == 0 else None) class EntryWidget(Widget): ARCHETYPE = "Entry" def _draw(self, cr): - _box(cr, 0, 0, self.width, self.height, (1.0, 1.0, 1.0), - (0.55, 0.55, 0.55)) - _text(cr, self.text, 6, self.height / 2 + 5, - max_width=self.width - 12) + if self.pkind in ("TextView", "Memo"): + self._draw_textview(cr) + return + editable = _prop_bool(self, "editable", True) + fill = (0.96, 0.96, 0.96) if not editable else (1.0, 1.0, 1.0) + _bg(cr, self, fill, stroke=(0.55, 0.55, 0.55)) + # Inset top shadow line, like a GTK entry. + cr.save() + _rgb(cr, (0.8, 0.8, 0.8)) + cr.rectangle(1, 1, self.width - 2, 1) + cr.fill() + cr.restore() + text = self._display_text() + align = _prop_int(self, "alignment", 0) + x = 24 if self.pkind == "SearchEntry" else 6 + if align == 1: + width = _text_width(cr, self, text) + x = max(6, (self.width - width) / 2) + elif align == 2: + width = _text_width(cr, self, text) + x = max(6, self.width - width - 6) + if not text and self.get_prop("placeholder-text", ""): + _wtext(cr, self, self.get_prop("placeholder-text", ""), + 6, self.height / 2 + 5, rgb=(0.6, 0.6, 0.6), + max_width=self.width - 12) + elif text: + _wtext(cr, self, text, x, self.height / 2 + 5, + max_width=self.width - 12) + if self.pkind == "SearchEntry": + cr.save() + _rgb(cr, (0.45, 0.45, 0.45)) + cr.set_line_width(1.5) + cr.arc(12, self.height / 2, 4, 0, 2 * math.pi) + cr.stroke() + cr.move_to(15, self.height / 2 + 3) + cr.line_to(19, self.height / 2 + 7) + cr.stroke() + cr.restore() + if self.pkind in ("CalcEdit", "DateEdit", "DirectoryEdit", + "FileNameEdit"): + bw = 22 + _box(cr, self.width - bw - 2, 3, bw, self.height - 6, + (0.92, 0.92, 0.92), (0.55, 0.55, 0.55)) + _triangle(cr, self.width - bw / 2 - 2, self.height / 2, 8, + "down") + def _display_text(self): + text = self.props.get("text", "") or "" + if self.get_password() and not self.get_show_password(): + return "*" * len(text) + return text + + def _draw_textview(self, cr): + editable = _prop_bool(self, "editable", True) + fill = (0.96, 0.96, 0.96) if not editable else (1.0, 1.0, 1.0) + _bg(cr, self, fill, stroke=(0.55, 0.55, 0.55)) + scroll_bars = _prop_int(self, "scroll-bars", + 3 if self.pkind == "Memo" else 0) + text_area_w = self.width - (16 if scroll_bars in (2, 3) else 0) + text_area_h = self.height - (16 if scroll_bars in (1, 3) else 0) + wrap_mode = _prop_int(self, "wrap-mode", 0) + raw = self.props.get("text", "") or "" + lines = [] + if wrap_mode in (2, 3): + for paragraph in raw.split("\n"): + lines.extend(_wrap_lines(cr, self, paragraph, + max(20, text_area_w - 12))) + elif wrap_mode == 1: + for paragraph in raw.split("\n"): + lines.extend(_wrap_chars(cr, self, paragraph, + max(20, text_area_w - 12))) + else: + lines = raw.split("\n") + y = 16 + for line in lines: + if y > text_area_h + 4: + break + _wtext(cr, self, line, 6, y, size=12, + max_width=text_area_w - 12) + y += 17 + if self.get_cursor_visible() and editable: + last = lines[-1] if lines else "" + caret_x = 6 + _text_width(cr, self, last, size=12) + caret_y = y - 17 + cr.save() + _rgb(cr, (0.1, 0.1, 0.1)) + cr.set_line_width(1.5) + cr.move_to(caret_x + 1, caret_y - 3) + cr.line_to(caret_x + 1, caret_y + 12) + cr.stroke() + cr.restore() + if scroll_bars in (2, 3): + _box(cr, self.width - 15, 1, 14, text_area_h, + (0.93, 0.93, 0.93), (0.7, 0.7, 0.7)) + _box(cr, self.width - 14, 3, 12, max(20, text_area_h // 3), + (0.75, 0.75, 0.78), (0.55, 0.55, 0.55)) + if scroll_bars in (1, 3): + _box(cr, 1, self.height - 15, text_area_w, 14, + (0.93, 0.93, 0.93), (0.7, 0.7, 0.7)) + _box(cr, 3, self.height - 14, max(20, text_area_w // 3), 12, + (0.75, 0.75, 0.78), (0.55, 0.55, 0.55)) + + +def _wrap_chars(cr, widget, text, max_width, size=12): + lines = [] + current = "" + for ch in text: + if _text_width(cr, widget, current + ch, size=size) > max_width \ + and current: + lines.append(current) + current = ch + else: + current += ch + lines.append(current) + return lines class RangeWidget(Widget): ARCHETYPE = "Range" def _draw(self, cr): + kind = self.pkind + if kind == "ProgressBar": + self._draw_progress(cr) + elif kind in ("Scrollbar", "ScrollBar"): + self._draw_scrollbar(cr) + elif kind in ("SpinButton", "SpinEdit", "FloatSpinEdit", + "UpDown"): + self._draw_spin(cr) + elif kind == "ScaleButton": + self._draw_scale_button(cr) + elif kind == "LevelBar": + self._draw_level(cr) + else: + self._draw_scale(cr) + + def _draw_progress(self, cr): + frac = _prop_float(self, "fraction", -1) + if frac < 0: + frac = _range_frac(self, "position", "minimum", "maximum") + frac = max(0.0, min(1.0, frac)) + trough = parse_color(self.get_prop("trough-color", ""), + (0.88, 0.88, 0.88)) + bar = parse_color(self.get_prop("bar-color", ""), + (52 / 255, 101 / 255, 164 / 255)) + inverted = _prop_bool(self, "inverted", False) + _rounded_box(cr, 0, 0, self.width, self.height, trough, + (0.55, 0.55, 0.55), radius=3) + fill_w = max(0, (self.width - 2) * frac) + if fill_w > 0: + x = 1 if not inverted else self.width - 1 - fill_w + cr.save() + _rounded_path(cr, x, 1, fill_w, self.height - 2, 3) + _rgb(cr, bar if not _prop_bool(self, "pulsing", False) + else (0.45, 0.6, 0.85)) + cr.fill() + cr.restore() + if _prop_bool(self, "show-text", False): + label = self.props.get("text", "") + if not label: + label = "%d%%" % round(frac * 100) + _wtext(cr, self, label, self.width / 2, + self.height / 2 + 5, align="center", + rgb=(0.15, 0.15, 0.15), + max_width=self.width - 8) + + def _draw_scrollbar(self, cr): + vertical = _prop_int(self, "orientation", 0) == 1 + lo = _prop_float(self, "lower", 0.0) + hi = _prop_float(self, "upper", 100.0) + value = _prop_float(self, "value", 0.0) + page = _prop_float(self, "page-size", 10.0) + frac = 0.0 if hi <= lo else (value - lo) / (hi - lo) + thumb_frac = 0.2 if hi <= lo else max( + 0.08, min(0.9, page / (hi - lo + page))) + _bg(cr, self, (0.93, 0.93, 0.93), stroke=(0.65, 0.65, 0.65)) + if vertical: + arrow = 16 + _triangle(cr, self.width / 2, arrow / 2 + 1, 9, "up") + _triangle(cr, self.width / 2, self.height - arrow / 2 - 1, + 9, "down") + track_y, track_h = arrow, self.height - 2 * arrow + thumb_h = max(16, track_h * thumb_frac) + thumb_y = track_y + frac * max(0, track_h - thumb_h) + _rounded_box(cr, 2, thumb_y, self.width - 4, thumb_h, + (0.72, 0.72, 0.75), (0.5, 0.5, 0.5), radius=4) + else: + arrow = 16 + _triangle(cr, arrow / 2 + 1, self.height / 2, 9, "left") + _triangle(cr, self.width - arrow / 2 - 1, self.height / 2, + 9, "right") + track_x, track_w = arrow, self.width - 2 * arrow + thumb_w = max(16, track_w * thumb_frac) + thumb_x = track_x + frac * max(0, track_w - thumb_w) + _rounded_box(cr, thumb_x, 2, thumb_w, self.height - 4, + (0.72, 0.72, 0.75), (0.5, 0.5, 0.5), radius=4) + + def _draw_spin(self, cr): + _bg(cr, self, (1.0, 1.0, 1.0), stroke=(0.55, 0.55, 0.55)) + digits = _prop_int(self, "digits", 0) + value = _prop_float(self, "value", 0.0) + label = ("%.*f" % (digits, value)) if digits else str(int(value)) + _wtext(cr, self, label, 6, self.height / 2 + 5, + max_width=self.width - 30) + bw = 20 + bx = self.width - bw - 1 + _box(cr, bx, 1, bw, (self.height - 2) // 2, + (0.92, 0.92, 0.92), (0.55, 0.55, 0.55)) + _box(cr, bx, 1 + (self.height - 2) // 2, bw, + self.height - 2 - (self.height - 2) // 2, + (0.92, 0.92, 0.92), (0.55, 0.55, 0.55)) + _triangle(cr, bx + bw / 2, self.height / 4 + 1, 8, "up") + _triangle(cr, bx + bw / 2, 3 * self.height / 4 - 1, 8, "down") + + def _draw_scale_button(self, cr): + _button_body(cr, self) + _rgb(cr, (0.2, 0.2, 0.2)) + cr.save() + cr.move_to(10, self.height / 2) + cr.line_to(15, self.height / 2) + cr.line_to(20, self.height / 2 - 5) + cr.line_to(20, self.height / 2 + 5) + cr.line_to(15, self.height / 2) + cr.close_path() + cr.fill() + cr.restore() mid = self.height / 2 cr.save() _rgb(cr, (0.65, 0.65, 0.65)) cr.set_line_width(3) - cr.move_to(6, mid) - cr.line_to(self.width - 6, mid) + cr.move_to(26, mid) + cr.line_to(self.width - 8, mid) cr.stroke() - frac = 0.5 - try: - lo = float(self.get_prop("minimum", "0")) - hi = float(self.get_prop("maximum", "100")) - val = float(self.get_prop("value", "50")) - frac = 0.0 if hi <= lo else (val - lo) / (hi - lo) - except ValueError: - pass - thumb_x = 6 + frac * max(self.width - 12, 1) _rgb(cr, (0.92, 0.92, 0.92)) - cr.rectangle(thumb_x - 6, mid - 9, 12, 18) + cr.rectangle(self.width / 2 - 5, mid - 8, 10, 16) cr.fill_preserve() _rgb(cr, (0.45, 0.45, 0.45)) cr.stroke() cr.restore() + def _draw_level(self, cr): + frac = _range_frac(self, "value", "minimum", "maximum") + segments = 10 + filled = int(round(frac * segments)) + gap = 3 + seg_w = (self.width - gap * (segments - 1)) / segments + for i in range(segments): + colour = (0.2, 0.65, 0.25) if i < filled \ + else (0.88, 0.88, 0.88) + if i >= 8: + colour = (0.85, 0.25, 0.2) if i < filled \ + else (0.88, 0.88, 0.88) + _box(cr, i * (seg_w + gap), 3, seg_w, self.height - 6, + colour, (0.55, 0.55, 0.55)) + + def _draw_scale(self, cr): + vertical = _prop_int(self, "orientation", 0) == 1 + frac = _range_frac(self) + tick_marks = _prop_int(self, "tick-marks", 0) + freq = max(1, _prop_int(self, "frequency", 10)) + lo = _prop_float(self, "minimum", 0.0) + hi = _prop_float(self, "maximum", 100.0) + value = _prop_float(self, "value", 0.0) + if vertical: + self._draw_scale_vertical(cr, frac, tick_marks, freq) + return + mid = self.height / 2 + (6 if tick_marks else 0) + if _prop_bool(self, "show-sel-range", False): + sel_lo = _prop_float(self, "sel-start", lo) + sel_hi = _prop_float(self, "sel-end", hi) + if hi > lo: + x0 = 8 + (sel_lo - lo) / (hi - lo) * (self.width - 16) + x1 = 8 + (sel_hi - lo) / (hi - lo) * (self.width - 16) + cr.save() + _rgb(cr, (0.65, 0.8, 1.0), 0.7) + cr.rectangle(x0, mid - 3, max(0, x1 - x0), 6) + cr.fill() + cr.restore() + cr.save() + _rgb(cr, (0.65, 0.65, 0.65)) + cr.set_line_width(3) + cr.move_to(8, mid) + cr.line_to(self.width - 8, mid) + cr.stroke() + if tick_marks: + _rgb(cr, (0.5, 0.5, 0.5)) + cr.set_line_width(1) + span = hi - lo + step = (hi - lo) / freq if freq else span + v = lo + while v <= hi + 1e-9: + x = 8 + (0 if span == 0 else (v - lo) / span) \ + * (self.width - 16) + top = mid - 12 if tick_marks in (1, 3) else mid + 4 + bottom = mid - 4 if tick_marks in (1, 3) else mid + 12 + if tick_marks == 3: + top, bottom = mid - 12, mid + 12 + cr.move_to(x, top) + cr.line_to(x, bottom) + v += step if step else span + if step == 0: + break + cr.stroke() + cr.restore() + thumb_x = 8 + frac * max(self.width - 16, 1) + cr.save() + _rgb(cr, (0.92, 0.92, 0.92)) + cr.arc(thumb_x, mid, 8, 0, 2 * math.pi) + cr.fill_preserve() + _rgb(cr, (0.45, 0.45, 0.45)) + cr.set_line_width(1) + cr.stroke() + cr.restore() + if _prop_bool(self, "draw-value", True): + digits = _prop_int(self, "digits", 1) + label = "%.*f" % (digits, value) + _wtext(cr, self, label, thumb_x, 12, size=11, + align="center", max_width=60) + + def _draw_scale_vertical(self, cr, frac, tick_marks, freq): + mid_x = self.width / 2 + cr.save() + _rgb(cr, (0.65, 0.65, 0.65)) + cr.set_line_width(3) + cr.move_to(mid_x, 8) + cr.line_to(mid_x, self.height - 8) + cr.stroke() + cr.restore() + thumb_y = self.height - 8 - frac * max(self.height - 16, 1) + cr.save() + _rgb(cr, (0.92, 0.92, 0.92)) + cr.arc(mid_x, thumb_y, 8, 0, 2 * math.pi) + cr.fill_preserve() + _rgb(cr, (0.45, 0.45, 0.45)) + cr.set_line_width(1) + cr.stroke() + cr.restore() + class ListSelWidget(Widget): ARCHETYPE = "ListSel" - def _draw(self, cr): - _box(cr, 0, 0, self.width, self.height, (1.0, 1.0, 1.0), - (0.55, 0.55, 0.55)) - rows = [r for r in self.get_prop("items", "").split("|") if r] - if not rows: - rows = [self.text] - y = 18 - for i, row in enumerate(rows[: max((self.height - 8) // 20, 1)]): - if i == 0 and ("Combo" in self.kind or "DropDown" in self.kind): - _rgb(cr, (0.85, 0.88, 0.95)) - cr.rectangle(1, 1, self.width - 2, 20) - cr.fill() - _text(cr, row, 6, y, size=12, max_width=self.width - 12) - y += 20 - if "Combo" in self.kind or "DropDown" in self.kind: - cr.save() - _rgb(cr, (0.3, 0.3, 0.3)) - cx = self.width - 12 - cr.move_to(cx - 5, 8) - cr.line_to(cx + 5, 8) - cr.line_to(cx, 15) - cr.close_path() - cr.fill() - cr.restore() + ROW_H = 20 + def _draw(self, cr): + kind = self.pkind + if kind in ("ComboBox", "ComboBoxText", "ComboBoxEx", + "CheckComboBox", "FilterComboBox", "DropDown"): + self._draw_combo(cr) + elif kind in ("ColorBox", "ColorListBox"): + self._draw_colorbox(cr) + elif kind == "CheckListBox": + self._draw_checklist(cr) + elif kind in ("TreeView", "ShellTreeView"): + self._draw_tree(cr) + elif kind in ("ListView", "ShellListView", "ColumnView", + "GridView", "IconView"): + self._draw_listview(cr) + elif kind in ("MenuBar", "MainMenu"): + self._draw_menubar(cr) + elif kind in ("Menu", "PopupMenu"): + self._draw_menu(cr) + elif kind in ("Toolbar", "ToolBar", "ControlBar", "CoolBar", + "HeaderControl"): + self._draw_toolbar(cr) + elif kind in ("StackSidebar", "StackSwitcher", "TabControl"): + self._draw_stack_switcher(cr) + elif kind == "EntryCompletion": + self._draw_entry_completion(cr) + elif kind == "FlowBox": + self._draw_flowbox(cr) + else: + self._draw_listbox(cr) + + def _row_height(self): + return max(16, _prop_int(self, "item-height", 0) or self.ROW_H) + + def _draw_rows(self, cr, rows, selected, y0=1, height=None, + check=None): + """Rows with a highlighted *selected* index; *check* is an + optional set of checked row labels (CheckListBox).""" + rh = self._row_height() + height = self.height if height is None else height + y = y0 + for i, row in enumerate(rows): + if y + rh > height: + break + if i == selected: + _rgb(cr, (0.2, 0.45, 0.85)) + cr.rectangle(1, y, self.width - 2, rh) + cr.fill() + text_rgb = (1.0, 1.0, 1.0) if i == selected \ + else (0.12, 0.12, 0.12) + x = 6 + if check is not None: + box = 13 + _box(cr, 6, y + (rh - box) / 2, box, box, + (1.0, 1.0, 1.0), (0.4, 0.4, 0.4)) + if row in check: + _checkmark(cr, 6 + box / 2, y + rh / 2, box - 3) + x = 26 + _wtext(cr, self, row, x, y + rh / 2 + 4, size=12, + rgb=text_rgb, max_width=self.width - x - 6) + y += rh + + def _draw_combo(self, cr): + _bg(cr, self, (1.0, 1.0, 1.0), stroke=(0.55, 0.55, 0.55)) + rows = self.get_items() + active = _prop_int(self, "active", 0) + shown = self.props.get("text", "") + if not shown and 0 <= active < len(rows): + shown = rows[active] + if not shown: + shown = self.text if self.text != self.name else "" + bw = 22 + _box(cr, self.width - bw - 1, 1, bw, self.height - 2, + (0.9, 0.9, 0.92), (0.55, 0.55, 0.55)) + _triangle(cr, self.width - bw / 2 - 1, self.height / 2, 9, + "down") + _wtext(cr, self, shown, 6, self.height / 2 + 5, + max_width=self.width - bw - 10) + if _prop_int(self, "style", 0) == 1 and rows: + # Simple style: the list is always visible below. + y0 = self.height + rh = self._row_height() + for i, row in enumerate(rows[:4]): + if i == active: + _rgb(cr, (0.2, 0.45, 0.85)) + cr.rectangle(1, y0, self.width - 2, rh) + cr.fill() + _wtext(cr, self, row, 6, y0 + rh / 2 + 4, size=12, + rgb=(1.0, 1.0, 1.0) if i == active + else (0.12, 0.12, 0.12), + max_width=self.width - 12) + y0 += rh + + def _draw_colorbox(self, cr): + _bg(cr, self, (1.0, 1.0, 1.0), stroke=(0.55, 0.55, 0.55)) + colour = parse_color(self.get_prop("color", ""), + (53 / 255, 132 / 255, 228 / 255)) + _box(cr, 6, (self.height - 18) / 2, 26, 18, colour, + (0.4, 0.4, 0.4)) + _wtext(cr, self, self.get_prop("color", "") or "Blue", + 38, self.height / 2 + 5, max_width=self.width - 64) + _triangle(cr, self.width - 12, self.height / 2, 9, "down") + + def _draw_listbox(self, cr): + _bg(cr, self, (1.0, 1.0, 1.0), stroke=(0.55, 0.55, 0.55)) + rows = self.get_items() or [self.text] + selected = _prop_int(self, "item-index", -1) + self._draw_rows(cr, rows, selected) + + def _draw_checklist(self, cr): + _bg(cr, self, (1.0, 1.0, 1.0), stroke=(0.55, 0.55, 0.55)) + rows = self.get_items() or [self.text] + selected = _prop_int(self, "item-index", -1) + self._draw_rows(cr, rows, selected, + check=set(self.get_checked_items())) + + def _draw_tree(self, cr): + _bg(cr, self, (1.0, 1.0, 1.0), stroke=(0.55, 0.55, 0.55)) + header_h = _prop_int(self, "header-height", 22) + y = 1 + if _prop_bool(self, "headers-visible", True): + _box(cr, 1, 1, self.width - 2, header_h, + (0.92, 0.92, 0.94), (0.6, 0.6, 0.6)) + _wtext(cr, self, "Name", 8, 1 + header_h / 2 + 4, size=12, + bold=True, max_width=self.width - 16) + y = 1 + header_h + raw = self.get_prop("items", "") + rows = [r for r in raw.split(";") if r] or ["Root/Child 1", + "Root/Child 2"] + rh = self._row_height() + indent = _prop_int(self, "indent", 16) + selected = _prop_int(self, "item-index", -1) + grid = _prop_bool(self, "grid-lines", False) + for i, path in enumerate(rows): + if y + rh > self.height: + break + parts = path.split("/") + depth = len(parts) - 1 + if i == selected: + _rgb(cr, (0.2, 0.45, 0.85)) + cr.rectangle(1, y, self.width - 2, rh) + cr.fill() + x = 6 + depth * indent + if _prop_bool(self, "show-buttons", True) and depth == 0 \ + and len(rows) > 1: + _triangle(cr, x + 4, y + rh / 2, 8, + "down" if i == 0 else "right") + x += 12 + if _prop_bool(self, "show-lines", True) and depth: + cr.save() + _rgb(cr, (0.75, 0.75, 0.75)) + cr.set_line_width(1) + cr.move_to(6 + (depth - 1) * indent + 4, y) + cr.line_to(6 + (depth - 1) * indent + 4, y + rh) + cr.stroke() + cr.restore() + _wtext(cr, self, parts[-1], x, y + rh / 2 + 4, size=12, + rgb=(1.0, 1.0, 1.0) if i == selected + else (0.12, 0.12, 0.12), + max_width=self.width - x - 6) + if grid: + cr.save() + _rgb(cr, (0.85, 0.85, 0.85)) + cr.move_to(0, y + rh) + cr.line_to(self.width, y + rh) + cr.stroke() + cr.restore() + y += rh + + def _draw_listview(self, cr): + _bg(cr, self, (1.0, 1.0, 1.0), stroke=(0.55, 0.55, 0.55)) + style = _prop_int(self, "view-style", 0) + columns = [c for c in self.get_prop("columns", "Name|Value") + .split("|") if c] + raw = self.get_prop("items", "") + rows = [r for r in raw.split(";") if r] or \ + ["Row 1,Value 1", "Row 2,Value 2"] + if style in (1, 2): # Icon / SmallIcon: icon grid. + cell = 64 if style == 1 else 48 + x, y = 8, 8 + for row in rows: + label = row.split(",")[0] + _box(cr, x, y, cell - 16, cell - 16, + (0.85, 0.9, 0.97), (0.5, 0.55, 0.65)) + _wtext(cr, self, label, x + (cell - 16) / 2, y + cell, + size=11, align="center", max_width=cell) + x += cell + if x + cell > self.width: + x, y = 8, y + cell + 14 + return + header_h = 22 + y = 1 + if _prop_bool(self, "headers-visible", True): + _box(cr, 1, 1, self.width - 2, header_h, + (0.92, 0.92, 0.94), (0.6, 0.6, 0.6)) + col_w = max(40, (self.width - 2) / max(len(columns), 1)) + for i, col in enumerate(columns): + _wtext(cr, self, col, 6 + i * col_w, + 1 + header_h / 2 + 4, size=12, bold=True, + max_width=col_w - 8) + y = 1 + header_h + rh = self._row_height() + selected = _prop_int(self, "item-index", -1) + col_w = max(40, (self.width - 2) / max(len(columns), 1)) + grid = _prop_bool(self, "grid-lines", False) + for i, row in enumerate(rows): + if y + rh > self.height: + break + if i == selected: + _rgb(cr, (0.2, 0.45, 0.85)) + cr.rectangle(1, y, self.width - 2, rh) + cr.fill() + cells = row.split(",") + for j, cell in enumerate(cells[:len(columns)]): + _wtext(cr, self, cell, 6 + j * col_w, y + rh / 2 + 4, + size=12, + rgb=(1.0, 1.0, 1.0) if i == selected + else (0.12, 0.12, 0.12), + max_width=col_w - 8) + if grid: + cr.save() + _rgb(cr, (0.85, 0.85, 0.85)) + cr.move_to(0, y + rh) + cr.line_to(self.width, y + rh) + cr.stroke() + cr.restore() + y += rh + + def _draw_menubar(self, cr): + _bg(cr, self, (0.94, 0.94, 0.94), stroke=(0.7, 0.7, 0.7)) + menus = [m for m in self.get_prop("menus", "File|Edit|Help") + .split("|") if m] + x = 8 + for menu in menus: + _wtext(cr, self, menu, x, self.height / 2 + 5, + max_width=120) + x += _text_width(cr, self, menu) + 22 + + def _draw_menu(self, cr): + _bg(cr, self, (1.0, 1.0, 1.0), stroke=(0.55, 0.55, 0.55)) + menus = [m for m in self.get_prop("menus", "File|Edit|Help") + .split("|") if m] + rows = self.get_items() or menus + self._draw_rows(cr, rows, 0) + + def _draw_toolbar(self, cr): + _bg(cr, self, (0.94, 0.94, 0.94), stroke=(0.7, 0.7, 0.7)) + items = self.get_items() or ["New", "Open", "Save"] + show_captions = _prop_bool(self, "show-captions", True) + flat = _prop_bool(self, "flat", False) + x = 4 + for item in items: + w = (_text_width(cr, self, item) + 16) if show_captions \ + else 30 + if x + w > self.width - 4: + break + if not flat: + _rounded_box(cr, x, 4, w, self.height - 8, + (0.97, 0.97, 0.97), (0.6, 0.6, 0.6), + radius=3) + if show_captions: + _wtext(cr, self, item, x + w / 2, self.height / 2 + 5, + size=12, align="center", max_width=w - 6) + else: + _box(cr, x + 8, (self.height - 14) / 2, 14, 14, + (0.5, 0.65, 0.85), (0.4, 0.4, 0.4)) + x += w + 4 + + def _draw_stack_switcher(self, cr): + _bg(cr, self, (0.97, 0.97, 0.97), stroke=(0.6, 0.6, 0.6)) + rows = self.get_items() or ["Page 1", "Page 2"] + vertical = self.pkind in ("StackSidebar", "TabControl") + if vertical: + self._draw_rows(cr, rows, 0) + else: + x = 6 + for i, row in enumerate(rows): + w = _text_width(cr, self, row) + 18 + if i == 0: + _rgb(cr, (0.85, 0.88, 0.95)) + cr.rectangle(x - 4, 3, w, self.height - 6) + cr.fill() + _wtext(cr, self, row, x, self.height / 2 + 5, + max_width=w) + x += w + 10 + + def _draw_entry_completion(self, cr): + _bg(cr, self, (1.0, 1.0, 1.0), stroke=(0.55, 0.55, 0.55)) + _wtext(cr, self, self.props.get("text", ""), 6, + 16, max_width=self.width - 12) + rows = self.get_items() or ["Item 1", "Item 2"] + self._draw_rows(cr, rows, 0, y0=22) + + def _draw_flowbox(self, cr): + _bg(cr, self, (0.97, 0.97, 0.97), stroke=(0.6, 0.6, 0.6)) + rows = self.get_items() or ["A", "B", "C", "D"] + x, y = 8, 8 + for row in rows: + w = _text_width(cr, self, row) + 20 + if x + w > self.width - 8: + x, y = 8, y + 34 + _rounded_box(cr, x, y, w, 26, (1.0, 1.0, 1.0), + (0.55, 0.55, 0.55), radius=4) + _wtext(cr, self, row, x + w / 2, y + 18, size=12, + align="center", max_width=w - 6) + x += w + 8 class ContainerWidget(Widget): ARCHETYPE = "Container" def _draw(self, cr): - _box(cr, 0, 0, self.width, self.height, (0.97, 0.97, 0.97), - (0.6, 0.6, 0.6)) - _text(cr, self.text, 8, 14, size=12, rgb=(0.35, 0.35, 0.35), - max_width=self.width - 16) + kind = self.pkind + if kind in ("Calendar", "DateTimePicker"): + self._draw_calendar(cr) + elif kind in ("Notebook", "PageControl", "TabControl"): + self._draw_notebook(cr) + elif kind in ("Frame", "GroupBox", "Panel", "AspectFrame", + "ButtonPanel"): + self._draw_frame(cr) + elif kind in ("Splitter", "PairSplitter", "Paned"): + self._draw_splitter(cr) + elif kind == "ScrolledWindow": + self._draw_scrolled(cr) + elif kind in ("HeaderBar", "ActionBar"): + self._draw_headerbar(cr) + elif kind in ("Statusbar", "StatusBar"): + self._draw_statusbar(cr) + elif kind in ("Window", "Form", "ApplicationWindow"): + self._draw_window(cr) + elif kind == "Expander": + self._draw_expander(cr) + elif kind == "ScrollBox": + self._draw_frame(cr) + else: + _bg(cr, self, (0.97, 0.97, 0.97), stroke=(0.6, 0.6, 0.6)) + _wtext(cr, self, self.text if self.text != self.name else kind, + 8, 14, size=12, rgb=(0.35, 0.35, 0.35), + max_width=self.width - 16) + + def _draw_frame(self, cr): + shadow = _prop_int(self, "shadow-type", 3) + label = self.props.get("label", "") + inset = _prop_int(self, "inset", 8) + top_inset = _prop_int(self, "top-inset", 14) + _bg(cr, self, (0.98, 0.98, 0.98), stroke=(0.55, 0.55, 0.6)) + if shadow == 3 or shadow == 4: # Etched in/out: double border. + cr.save() + _rgb(cr, (0.7, 0.7, 0.7)) + cr.set_line_width(1) + cr.rectangle(3.5, 3.5, self.width - 7, self.height - 7) + cr.stroke() + cr.restore() + if label: + xalign = max(0.0, min(1.0, _prop_float(self, "label-xalign", + 0.0))) + text_w = _text_width(cr, self, label, size=12) + x = 8 + (self.width - 16 - text_w) * xalign + cr.save() + _rgb(cr, (0.98, 0.98, 0.98)) + cr.rectangle(x - 4, 1, text_w + 8, 12) + cr.fill() + cr.restore() + _wtext(cr, self, label, x, 12, size=12, + max_width=self.width - 16) + elif self.text != self.name: + _wtext(cr, self, self.text, 8 + inset, 12 + top_inset, + size=12, rgb=(0.35, 0.35, 0.35), + max_width=self.width - 16) + + def _draw_notebook(self, cr): + pages = [p for p in self.get_prop("pages", "Tab 1|Tab 2|Tab 3") + .split("|") if p] + active = _prop_int(self, "page", 0) + tab_h = max(18, _prop_int(self, "tab-height", 26)) + tab_pos = _prop_int(self, "tab-position", 0) + tab_w = _prop_int(self, "tab-width", 0) + _bg(cr, self, (0.97, 0.97, 0.97), stroke=(0.55, 0.55, 0.55)) + x = 6 + tab_ys = [] + for i, page in enumerate(pages): + w = tab_w or (int(_text_width(cr, self, page, size=12)) + 22) + if tab_pos == 1: # Bottom tabs + y = self.height - tab_h - 2 + else: + y = 2 + tab_ys.append((x, y, w)) + if i == active: + _rounded_box(cr, x, y, w, tab_h, (1.0, 1.0, 1.0), + (0.55, 0.55, 0.55), radius=4) + else: + _rounded_box(cr, x, y + (3 if tab_pos != 1 else 0), + w, tab_h - 3, (0.88, 0.88, 0.9), + (0.6, 0.6, 0.6), radius=4) + _wtext(cr, self, page, x + w / 2, + y + tab_h / 2 + 4, size=12, align="center", + max_width=w - 6) + x += w + 2 + if pages and 0 <= active < len(pages): + page_y = tab_h + 2 if tab_pos != 1 else 2 + page_h = self.height - tab_h - 4 + _wtext(cr, self, pages[active], 10, page_y + 20, size=12, + rgb=(0.4, 0.4, 0.4), max_width=self.width - 20) + + def _draw_calendar(self, cr): + from datetime import date as _date + raw = self.get_prop("date", "") + try: + parts = [int(v) for v in raw.split("-")] + selected = _date(parts[0], parts[1], parts[2]) \ + if len(parts) == 3 else _date.today() + except (ValueError, TypeError): + selected = _date.today() + today = _date.today() + year, month = selected.year, selected.month + first = _date(year, month, 1) + # Monday-start grid (ISO week). + start_col = first.weekday() + if month == 12: + days = 31 + else: + days = (_date(year, month + 1, 1) - first).days + grid_colour = parse_color(self.get_prop("grid-color", ""), + (0.8, 0.8, 0.8)) + sel_fill = parse_color(self.get_prop("selected-fill-color", ""), + (52 / 255, 101 / 255, 164 / 255)) + sel_text = parse_color(self.get_prop("selected-text-color", ""), + (1.0, 1.0, 1.0)) + today_colour = parse_color(self.get_prop("today-color", ""), + (0.78, 0.2, 0.2)) + dim_text = parse_color(self.get_prop("dim-text-color", ""), + (0.43, 0.43, 0.43)) + weekend_colour = parse_color(self.get_prop("weekends-color", ""), + (0.67, 0.24, 0.24)) + _bg(cr, self, (1.0, 1.0, 1.0), stroke=(0.55, 0.55, 0.55)) + y = 2 + if _prop_bool(self, "show-heading", True): + _box(cr, 1, 1, self.width - 2, 24, + (0.92, 0.92, 0.94), (0.6, 0.6, 0.6)) + title = "%s %d" % (first.strftime("%B"), year) + _wtext(cr, self, title, self.width / 2, 18, size=12, + align="center", bold=True, max_width=self.width - 40) + _triangle(cr, 12, 13, 8, "left") + _triangle(cr, self.width - 12, 13, 8, "right") + y = 26 + show_week = _prop_bool(self, "show-week-numbers", False) + col_w = (self.width - (28 if show_week else 0)) / 7.0 + x0 = 28 if show_week else 0 + if _prop_bool(self, "show-day-names", True): + for i, name in enumerate(("Mo", "Tu", "We", "Th", "Fr", + "Sa", "Su")): + _wtext(cr, self, name, x0 + i * col_w + col_w / 2, + y + 12, size=11, align="center", + rgb=(0.4, 0.4, 0.4), bold=True) + y += 16 + row_h = max(14, (self.height - y - 2) / 6.0) + for row in range(6): + for col in range(7): + day = row * 7 + col - start_col + 1 + cx = x0 + col * col_w + cy = y + row * row_h + if 1 <= day <= days: + is_weekend = col >= 5 + is_today = (selected.year == today.year + and selected.month == today.month + and day == today.day) + is_selected = day == selected.day + if is_selected: + _rgb(cr, sel_fill) + cr.rectangle(cx + 1, cy + 1, col_w - 2, + row_h - 2) + cr.fill() + rgb = sel_text if is_selected else ( + today_colour if is_today else ( + weekend_colour if is_weekend + else (0.12, 0.12, 0.12))) + _wtext(cr, self, str(day), cx + col_w / 2, + cy + row_h / 2 + 4, size=11, align="center", + rgb=rgb) + else: + _wtext(cr, self, + str(day if day > 0 else days + day), + cx + col_w / 2, cy + row_h / 2 + 4, size=11, + align="center", rgb=dim_text) + cr.save() + _rgb(cr, grid_colour) + cr.set_line_width(0.5) + cr.rectangle(cx + 0.5, cy + 0.5, col_w - 1, row_h - 1) + cr.stroke() + cr.restore() + + def _draw_splitter(self, cr): + _bg(cr, self, (0.97, 0.97, 0.97), stroke=(0.6, 0.6, 0.6)) + vertical = _prop_int(self, "orientation", 0) == 1 + pos = _prop_int(self, "position", 100) + if vertical: + pos = max(10, min(self.height - 10, pos)) + _box(cr, 0, pos - 3, self.width, 6, + (0.85, 0.85, 0.88), (0.6, 0.6, 0.6)) + for gx in (self.width / 2 - 12, self.width / 2 + 6): + _box(cr, gx, pos - 1, 6, 2, (0.5, 0.5, 0.5), + (0.5, 0.5, 0.5)) + else: + pos = max(10, min(self.width - 10, pos)) + _box(cr, pos - 3, 0, 6, self.height, + (0.85, 0.85, 0.88), (0.6, 0.6, 0.6)) + for gy in (self.height / 2 - 12, self.height / 2 + 6): + _box(cr, pos - 1, gy, 2, 6, (0.5, 0.5, 0.5), + (0.5, 0.5, 0.5)) + + def _draw_scrolled(self, cr): + _bg(cr, self, (1.0, 1.0, 1.0), stroke=(0.55, 0.55, 0.55)) + _box(cr, self.width - 15, 1, 14, self.height - 2, + (0.93, 0.93, 0.93), (0.7, 0.7, 0.7)) + _box(cr, self.width - 14, 3, 12, max(20, self.height // 3), + (0.75, 0.75, 0.78), (0.55, 0.55, 0.55)) + _wtext(cr, self, self.text if self.text != self.name else "", + 8, 16, size=12, rgb=(0.4, 0.4, 0.4), + max_width=self.width - 28) + + def _draw_headerbar(self, cr): + _bg(cr, self, (0.25, 0.35, 0.5), stroke=(0.2, 0.25, 0.35)) + _wtext(cr, self, self.text, self.width / 2, + self.height / 2 + 5, size=13, rgb=(1.0, 1.0, 1.0), + align="center", bold=True, max_width=self.width - 60) + _rounded_box(cr, 8, (self.height - 22) / 2, 52, 22, + (0.35, 0.45, 0.6), (0.5, 0.55, 0.65), radius=4) + _wtext(cr, self, "Back", 34, self.height / 2 + 5, size=11, + rgb=(1.0, 1.0, 1.0), align="center") + + def _draw_statusbar(self, cr): + _bg(cr, self, (0.93, 0.93, 0.93), stroke=(0.65, 0.65, 0.65)) + panels = [p for p in self.get_prop("panels", "").split("|") + if p] + text = self.props.get("text", "") + if panels: + col_w = self.width / len(panels) + for i, panel in enumerate(panels): + _wtext(cr, self, panel, 6 + i * col_w, + self.height / 2 + 5, size=12, + max_width=col_w - 12) + if i: + cr.save() + _rgb(cr, (0.7, 0.7, 0.7)) + cr.move_to(i * col_w, 3) + cr.line_to(i * col_w, self.height - 3) + cr.stroke() + cr.restore() + elif text: + _wtext(cr, self, text, 6, self.height / 2 + 5, size=12, + max_width=self.width - 30) + if _prop_bool(self, "size-grip", True): + cr.save() + _rgb(cr, (0.55, 0.55, 0.55)) + for i in range(3): + cr.move_to(self.width - 4 - i * 6, self.height - 4) + cr.line_to(self.width - 4, self.height - 4 - i * 6) + cr.stroke() + cr.restore() + + def _draw_window(self, cr): + _bg(cr, self, (0.95, 0.95, 0.95), stroke=(0.4, 0.4, 0.4)) + title = self.get_prop("title", "") or self.text + _box(cr, 1, 1, self.width - 2, 26, + (0.35, 0.45, 0.65), (0.3, 0.35, 0.5)) + _wtext(cr, self, title, 10, 19, size=12, + rgb=(1.0, 1.0, 1.0), bold=True, + max_width=self.width - 60) + for i, colour in enumerate(((0.95, 0.4, 0.35), + (0.95, 0.8, 0.3), + (0.35, 0.8, 0.4))): + cr.save() + _rgb(cr, colour) + cr.arc(self.width - 14 - i * 18, 14, 5, 0, 2 * math.pi) + cr.fill() + cr.restore() + + def _draw_expander(self, cr): + _bg(cr, self, (0.97, 0.97, 0.97), stroke=(0.6, 0.6, 0.6)) + _triangle(cr, 14, 13, 9, "down") + _wtext(cr, self, self.text, 26, 17, size=12, bold=True, + max_width=self.width - 32) class ChartWidget(Widget): ARCHETYPE = "Chart" def _draw(self, cr): - _box(cr, 0, 0, self.width, self.height, (1.0, 1.0, 1.0), - (0.55, 0.55, 0.55)) + _bg(cr, self, (1.0, 1.0, 1.0), stroke=(0.55, 0.55, 0.55)) cr.save() _rgb(cr, (0.75, 0.75, 0.75)) cr.set_line_width(1) @@ -401,18 +1948,67 @@ class ChartWidget(Widget): cr.line_to(24, self.height - 18) cr.line_to(self.width - 6, self.height - 18) cr.stroke() - _rgb(cr, (0.15, 0.35, 0.75)) - cr.set_line_width(1.5) - pts = [(30, self.height - 40), (self.width * 0.35, self.height - 55), - (self.width * 0.6, self.height - 30), - (self.width - 12, self.height - 48)] - cr.move_to(*pts[0]) - for p in pts[1:]: - cr.line_to(*p) - cr.stroke() cr.restore() - _text(cr, self.kind, 6, 14, size=11, rgb=(0.45, 0.45, 0.45), - max_width=self.width - 12) + kind = self.pkind + if "Volume" in kind: + self._draw_bars(cr) + elif "Candlestick" in kind or "OHLC" in kind \ + or "HeikinAshi" in kind: + self._draw_candles(cr) + else: + cr.save() + _rgb(cr, (0.15, 0.35, 0.75)) + cr.set_line_width(1.5) + pts = [(30, self.height - 40), + (self.width * 0.35, self.height - 55), + (self.width * 0.6, self.height - 30), + (self.width - 12, self.height - 48)] + cr.move_to(*pts[0]) + for p in pts[1:]: + cr.line_to(*p) + cr.stroke() + cr.restore() + _wtext(cr, self, kind, 6, 14, size=11, + rgb=(0.45, 0.45, 0.45), max_width=self.width - 12) + + def _series(self, count): + values = [] + for i in range(count): + values.append(0.5 + 0.3 * math.sin(i * 0.9) + + 0.12 * math.sin(i * 2.3)) + return values + + def _draw_bars(self, cr): + values = self._series(12) + plot_w = self.width - 36 + plot_h = self.height - 30 + bar_w = plot_w / len(values) * 0.6 + for i, value in enumerate(values): + h = value * plot_h + x = 28 + i * (plot_w / len(values)) + 2 + _rgb(cr, (0.2, 0.45, 0.8)) + cr.rectangle(x, self.height - 18 - h, bar_w, h) + cr.fill() + + def _draw_candles(self, cr): + values = self._series(10) + plot_w = self.width - 36 + plot_h = self.height - 30 + step = plot_w / len(values) + for i, value in enumerate(values): + cx = 28 + i * step + step / 2 + open_v = value - 0.08 + close_v = value + 0.08 + top = self.height - 18 - max(open_v, close_v) * plot_h + bottom = self.height - 18 - min(open_v, close_v) * plot_h + up = close_v >= open_v + _rgb(cr, (0.15, 0.6, 0.25) if up else (0.85, 0.2, 0.2)) + cr.set_line_width(1) + cr.move_to(cx, self.height - 18 - (value + 0.14) * plot_h) + cr.line_to(cx, self.height - 18 - (value - 0.14) * plot_h) + cr.stroke() + cr.rectangle(cx - 3, top, 6, max(2, bottom - top)) + cr.fill() class IndicatorWidget(Widget): @@ -442,45 +2038,255 @@ class InstrumentWidget(Widget): def _draw_panel(cr, widget): - _box(cr, 0, 0, widget.width, widget.height, (0.96, 0.97, 0.99), - (0.5, 0.55, 0.65)) - _text(cr, widget.kind, widget.width / 2, widget.height / 2 - 2, - size=12, align="center", max_width=widget.width - 12) - _text(cr, widget.text if widget.text != widget.name else "", - widget.width / 2, widget.height / 2 + 14, size=11, - rgb=(0.45, 0.45, 0.45), align="center", - max_width=widget.width - 12) + _bg(cr, widget, (0.96, 0.97, 0.99), stroke=(0.5, 0.55, 0.65)) + _wtext(cr, widget, widget.pkind, widget.width / 2, + widget.height / 2 - 2, size=12, align="center", + max_width=widget.width - 12) + caption = widget.text if widget.text != widget.name else "" + if caption: + _wtext(cr, widget, caption, widget.width / 2, + widget.height / 2 + 14, size=11, + rgb=(0.45, 0.45, 0.45), align="center", + max_width=widget.width - 12) class DialogWidget(Widget): ARCHETYPE = "Dialog" def _draw(self, cr): - _box(cr, 0, 0, self.width, self.height, (0.95, 0.95, 0.95), - (0.4, 0.4, 0.4)) - cr.save() - _rgb(cr, (0.25, 0.45, 0.75)) - cr.rectangle(1, 1, self.width - 2, 24) - cr.fill() - cr.restore() - _text(cr, self.text, 8, 18, size=12, rgb=(1.0, 1.0, 1.0), - bold=True, max_width=self.width - 16) + _bg(cr, self, (0.95, 0.95, 0.95), stroke=(0.4, 0.4, 0.4)) + title = self.get_prop("title", "") or self.text + _box(cr, 1, 1, self.width - 2, 26, + (0.25, 0.45, 0.75), (0.2, 0.35, 0.6)) + _wtext(cr, self, title, 10, 19, size=12, + rgb=(1.0, 1.0, 1.0), bold=True, + max_width=self.width - 30) + _wtext(cr, self, "×", self.width - 16, 19, size=14, + rgb=(1.0, 1.0, 1.0), align="center") + if self.pkind in ("FileChooserDialog", "OpenDialog", + "SaveDialog"): + _box(cr, 10, 36, self.width - 20, + max(20, self.height - 90), (1.0, 1.0, 1.0), + (0.6, 0.6, 0.6)) + for i, name in enumerate(("Documents", "Downloads", + "Pictures")): + _wtext(cr, self, name, 16, 54 + i * 18, size=12, + max_width=self.width - 32) + elif self.pkind in ("ColorDialog", "ColorChooserDialog"): + colour = parse_color(self.get_prop("color", ""), + (53 / 255, 132 / 255, 228 / 255)) + _box(cr, 10, 36, self.width - 20, + max(20, self.height - 90), colour, (0.5, 0.5, 0.5)) + elif self.pkind == "AboutDialog": + _wtext(cr, self, "LightGUI", self.width / 2, + self.height / 2 - 6, size=14, align="center", + bold=True, max_width=self.width - 20) + _wtext(cr, self, "Version 1.0", self.width / 2, + self.height / 2 + 14, size=12, align="center", + rgb=(0.45, 0.45, 0.45), max_width=self.width - 20) bw, bh = 64, 22 bx = self.width - bw - 10 by = self.height - bh - 10 if self.width > 150 and self.height > 70: - _box(cr, bx, by, bw, bh, (0.92, 0.92, 0.92), - (0.45, 0.45, 0.45)) - _text(cr, "OK", bx + bw / 2, by + 16, size=12, - align="center") + _rounded_box(cr, bx, by, bw, bh, (0.92, 0.92, 0.92), + (0.45, 0.45, 0.45), radius=4) + _wtext(cr, self, "OK", bx + bw / 2, by + 16, size=12, + align="center") + if self.width > 240: + _rounded_box(cr, bx - bw - 8, by, bw, bh, + (0.92, 0.92, 0.92), (0.45, 0.45, 0.45), + radius=4) + _wtext(cr, self, "Cancel", bx - bw / 2 - 8, by + 16, + size=12, align="center") def _draw_display(cr, widget): - _box(cr, 0, 0, widget.width, widget.height, (1.0, 1.0, 1.0), - (0.55, 0.55, 0.55)) - _text(cr, widget.kind, widget.width / 2, widget.height / 2 + 5, - size=12, rgb=(0.4, 0.4, 0.4), align="center", - max_width=widget.width - 12) + kind = widget.pkind + if kind in ("Image", "Picture"): + _draw_image_scene(cr, widget) + elif kind == "Shape": + _draw_shape(cr, widget) + elif kind in ("Separator", "SeparatorMenuItem"): + cr.save() + _rgb(cr, (0.6, 0.6, 0.6)) + cr.set_line_width(1) + if widget.width >= widget.height: + cr.move_to(2, widget.height / 2) + cr.line_to(widget.width - 2, widget.height / 2) + else: + cr.move_to(widget.width / 2, 2) + cr.line_to(widget.width / 2, widget.height - 2) + cr.stroke() + cr.restore() + elif kind == "Spinner": + cx, cy = widget.width / 2, widget.height / 2 + r = min(widget.width, widget.height) / 2 - 4 + cr.save() + _rgb(cr, (0.25, 0.45, 0.8)) + cr.set_line_width(3) + cr.arc(cx, cy, max(r, 2), -math.pi / 2, math.pi * 0.75) + cr.stroke() + cr.restore() + elif kind in ("Video", "MediaControls"): + _box(cr, 0, 0, widget.width, widget.height, + (0.1, 0.1, 0.12), (0.05, 0.05, 0.05)) + _triangle(cr, widget.width / 2, widget.height / 2 - 6, 22, + "right", rgb=(1.0, 1.0, 1.0)) + _box(cr, 0, widget.height - 18, widget.width, 18, + (0.25, 0.25, 0.28), (0.1, 0.1, 0.1)) + _box(cr, 6, widget.height - 12, (widget.width - 12) // 2, 5, + (0.85, 0.2, 0.2), (0.85, 0.2, 0.2)) + elif kind in ("DrawingArea", "GLArea", "PaintBox"): + _bg(cr, widget, (0.98, 0.98, 0.98), stroke=(0.6, 0.6, 0.6)) + cr.save() + _rgb(cr, (0.8, 0.8, 0.8)) + cr.set_line_width(1) + cr.move_to(0, 0) + cr.line_to(widget.width, widget.height) + cr.move_to(widget.width, 0) + cr.line_to(0, widget.height) + cr.stroke() + cr.restore() + _wtext(cr, widget, kind, widget.width / 2, + widget.height / 2 + 5, size=12, align="center", + rgb=(0.45, 0.45, 0.45), max_width=widget.width - 12) + elif kind == "CellView": + _bg(cr, widget, (1.0, 1.0, 1.0), stroke=(0.55, 0.55, 0.55)) + _box(cr, 6, (widget.height - 16) / 2, 16, 16, + (0.85, 0.9, 0.97), (0.5, 0.55, 0.65)) + _wtext(cr, widget, widget.text, 28, widget.height / 2 + 5, + max_width=widget.width - 34) + elif kind == "Arrow": + _triangle(cr, widget.width / 2, widget.height / 2, + min(widget.width, widget.height) - 8, "up", + rgb=(0.3, 0.3, 0.3)) + elif kind == "Bevel": + cr.save() + _rgb(cr, (0.9, 0.9, 0.9)) + cr.rectangle(0, 0, widget.width, widget.height) + cr.fill() + _rgb(cr, (1.0, 1.0, 1.0)) + cr.set_line_width(2) + cr.move_to(1, widget.height - 1) + cr.line_to(1, 1) + cr.line_to(widget.width - 1, 1) + cr.stroke() + _rgb(cr, (0.55, 0.55, 0.55)) + cr.move_to(widget.width - 1, 1) + cr.line_to(widget.width - 1, widget.height - 1) + cr.line_to(1, widget.height - 1) + cr.stroke() + cr.restore() + else: + _bg(cr, widget, (1.0, 1.0, 1.0), stroke=(0.55, 0.55, 0.55)) + _wtext(cr, widget, kind, widget.width / 2, + widget.height / 2 + 5, size=12, + rgb=(0.4, 0.4, 0.4), align="center", + max_width=widget.width - 12) + + +def _draw_image_scene(cr, widget): + """Demo scene like the C GtkImage draw: sky, sun, mountains.""" + w, h = widget.width, widget.height + gradient = _cairo.LinearGradient(0, 0, 0, h) + gradient.add_color_stop_rgb(0, 0.55, 0.75, 0.95) + gradient.add_color_stop_rgb(1, 0.85, 0.92, 0.98) + cr.save() + cr.rectangle(0, 0, w, h) + cr.set_source(gradient) + cr.fill() + _rgb(cr, (0.98, 0.85, 0.3)) + cr.arc(w * 0.78, h * 0.22, min(w, h) * 0.11, 0, 2 * math.pi) + cr.fill() + _rgb(cr, (0.35, 0.55, 0.3)) + cr.move_to(0, h * 0.75) + cr.line_to(w * 0.35, h * 0.35) + cr.line_to(w * 0.7, h * 0.75) + cr.close_path() + cr.fill() + _rgb(cr, (0.55, 0.45, 0.3)) + cr.move_to(w * 0.45, h * 0.75) + cr.line_to(w * 0.75, h * 0.45) + cr.line_to(w, h * 0.75) + cr.close_path() + cr.fill() + _rgb(cr, (0.3, 0.5, 0.25)) + cr.rectangle(0, h * 0.75, w, h * 0.25) + cr.fill() + cr.restore() + _rgb(cr, (0.5, 0.5, 0.5)) + cr.set_line_width(1) + cr.rectangle(0.5, 0.5, w - 1, h - 1) + cr.stroke() + filename = widget.get_prop("file", "") + if filename: + _wtext(cr, widget, filename, w / 2, h - 6, size=11, + align="center", rgb=(0.2, 0.2, 0.2), + max_width=w - 8) + + +def _draw_shape(cr, widget): + shape = _prop_int(widget, "shape", 0) + fill = parse_color(widget.get_prop("fill-color", ""), + (70 / 255, 130 / 255, 200 / 255)) + pen = parse_color(widget.get_prop("pen-color", ""), + (20 / 255, 40 / 255, 80 / 255)) + pen_width = max(1, _prop_int(widget, "pen-width", 2)) + w, h = widget.width, widget.height + cx, cy = w / 2, h / 2 + cr.save() + _rgb(cr, fill) + cr.set_line_width(pen_width) + if shape in (0, 1): # Rectangle / Square + if shape == 1: + side = min(w, h) - 4 + cr.rectangle((w - side) / 2, (h - side) / 2, side, side) + else: + cr.rectangle(2, 2, w - 4, h - 4) + elif shape in (2, 3): # RoundRect / RoundSquare + if shape == 3: + side = min(w, h) - 4 + _rounded_path(cr, (w - side) / 2, (h - side) / 2, + side, side, 12) + else: + _rounded_path(cr, 2, 2, w - 4, h - 4, 12) + elif shape in (4, 5): # Ellipse / Circle + rx = (w - 4) / 2 if shape == 4 else min(w, h) / 2 - 2 + ry = (h - 4) / 2 if shape == 4 else min(w, h) / 2 - 2 + cr.save() + cr.translate(cx, cy) + cr.scale(max(rx, 1), max(ry, 1)) + cr.arc(0, 0, 1, 0, 2 * math.pi) + cr.restore() + elif shape == 6: # Triangle + cr.move_to(cx, 2) + cr.line_to(w - 2, h - 2) + cr.line_to(2, h - 2) + cr.close_path() + elif shape == 7: # Diamond + cr.move_to(cx, 2) + cr.line_to(w - 2, cy) + cr.line_to(cx, h - 2) + cr.line_to(2, cy) + cr.close_path() + elif shape == 8: # Pentagon + for i in range(5): + angle = -math.pi / 2 + i * 2 * math.pi / 5 + x = cx + (min(w, h) / 2 - 2) * math.cos(angle) + y = cy + (min(w, h) / 2 - 2) * math.sin(angle) + cr.line_to(x, y) if i else cr.move_to(x, y) + cr.close_path() + else: # Hexagon + for i in range(6): + angle = -math.pi / 2 + i * 2 * math.pi / 6 + x = cx + (min(w, h) / 2 - 2) * math.cos(angle) + y = cy + (min(w, h) / 2 - 2) * math.sin(angle) + cr.line_to(x, y) if i else cr.move_to(x, y) + cr.close_path() + cr.fill_preserve() + _rgb(cr, pen) + cr.stroke() + cr.restore() class DisplayWidget(Widget): @@ -498,21 +2304,42 @@ class SpreadsheetWidget(Widget): ARCHETYPE = "Spreadsheet" def _draw(self, cr): - _box(cr, 0, 0, self.width, self.height, (1.0, 1.0, 1.0), - (0.55, 0.55, 0.55)) + _bg(cr, self, (1.0, 1.0, 1.0), stroke=(0.55, 0.55, 0.55)) + rows = max(1, _prop_int(self, "rows", 5)) + cols = max(1, _prop_int(self, "columns", 4)) + col_w = _prop_int(self, "default-col-width", 84) + row_h = _prop_int(self, "default-row-height", 20) + header_h = row_h if _prop_bool(self, "headers-visible", True) \ + else 0 cr.save() _rgb(cr, (0.8, 0.8, 0.8)) cr.set_line_width(1) - x = 48 - while x < self.width: - cr.move_to(x, 0) - cr.line_to(x, self.height) - x += 48 - y = 20 - while y < self.height: + if header_h: + _rgb(cr, (0.92, 0.92, 0.94)) + cr.rectangle(0, 0, self.width, header_h) + cr.fill() + _rgb(cr, (0.8, 0.8, 0.8)) + for c in range(cols + 1): + x = c * col_w + if x > self.width: + break + cr.move_to(x, 0) + cr.line_to(x, self.height) + for c in range(cols): + label = chr(ord("A") + c) if c < 26 else "A%d" % c + _wtext(cr, self, label, c * col_w + col_w / 2, + header_h / 2 + 4, size=11, align="center", + bold=True) + y = header_h + r = 0 + while y < self.height and r < rows: cr.move_to(0, y) cr.line_to(self.width, y) - y += 20 + if header_h: + _wtext(cr, self, str(r + 1), 4, y + row_h / 2 + 4, + size=11, rgb=(0.45, 0.45, 0.45)) + y += row_h + r += 1 cr.stroke() cr.restore() diff --git a/tests/test_core.py b/tests/test_core.py index 1f9adb6..076da74 100644 --- a/tests/test_core.py +++ b/tests/test_core.py @@ -44,9 +44,11 @@ class WidgetStateTests(unittest.TestCase): self.assertEqual((self.widget.x, self.widget.y, self.widget.width, self.widget.height), (5, 6, 200, 40)) - self.widget.set_prop("text", "Hello") + # Phase 2: set_prop validates against the property table; + # a Button's caption prop is "label" (proposal SS2.1). + self.widget.set_prop("label", "Hello") self.assertEqual(self.widget.text, "Hello") - self.assertEqual(self.widget.get_prop("text"), "Hello") + self.assertEqual(self.widget.get_prop("label"), "Hello") def test_set_bounds_clamps(self): self.widget.set_bounds(-10, -5, 5, 3) diff --git a/tests/test_draw.py b/tests/test_draw.py new file mode 100644 index 0000000..885d015 --- /dev/null +++ b/tests/test_draw.py @@ -0,0 +1,206 @@ +"""Headless render smoke tests (Phase 2). + +Every palette kind is drawn to an offscreen Cairo surface to catch +draw crashes, plus targeted draws for the prop-driven branches +(password entries, combos, checklists, scrollbars, notebooks, +calendars, shapes, progress bars, trees, list views, menu buttons). +No display is needed: cairo.ImageSurface only. Recognisability is +verified visually under Xvfb (showcase screenshots), not here. +""" + +import unittest + +import cairo + +from lightgui.xframe import core +from lightgui.xframe import palette + + +def _draw(widget, width=None, height=None): + """Draw *widget* on a fresh white surface; return the surface.""" + surface = cairo.ImageSurface( + cairo.FORMAT_ARGB32, + max(widget.width + 4, width or 0), + max(widget.height + 4, height or 0)) + cr = cairo.Context(surface) + cr.set_source_rgb(1, 1, 1) + cr.paint() + widget.draw(cr) + return surface + + +def _non_white_pixels(surface): + data = surface.get_data() + stride = surface.get_stride() + count = 0 + for y in range(surface.get_height()): + row = data[y * stride:(y + 1) * stride] + for x in range(0, len(row), 4): + b, g, r = row[x], row[x + 1], row[x + 2] + if (r, g, b) != (255, 255, 255): + count += 1 + return count + + +class RenderSmokeTests(unittest.TestCase): + def test_every_kind_draws_without_crashing(self): + for entry in palette.PALETTE: + widget = core.create(entry.name, entry.name + "_001") + self.assertIsNotNone(widget, entry.name) + try: + _draw(widget) + except Exception as exc: # noqa: BLE001 - report the kind + self.fail("%s draw crashed: %r" % (entry.name, exc)) + + def test_every_kind_draws_something(self): + # A visible widget must paint at least one non-white pixel + # (its border, text, or fill) at its default size. + blank = [] + for entry in palette.PALETTE: + widget = core.create(entry.name, entry.name + "_001") + surface = _draw(widget) + if _non_white_pixels(surface) == 0: + blank.append(entry.name) + self.assertFalse(blank, "kinds drawing nothing: %s" % blank[:10]) + + def test_invisible_widget_draws_nothing(self): + widget = core.create("GtkButton", "GtkButton_001") + widget.set_prop("visible", "false") + surface = _draw(widget) + self.assertEqual(_non_white_pixels(surface), 0) + + def test_disabled_widget_still_draws(self): + widget = core.create("GtkButton", "GtkButton_001") + widget.set_prop("enabled", "false") + surface = _draw(widget) + self.assertGreater(_non_white_pixels(surface), 0) + + +class PropDrivenDrawTests(unittest.TestCase): + def _widget(self, kind, width=200, height=120, **props): + widget = core.create(kind, kind + "_001", 0, 0, width, height) + for name, value in props.items(): + widget.set_prop(name, value) + return widget + + def test_password_entry_masks_text(self): + entry = self._widget("GtkEntry", text="secret", password=True) + _draw(entry) + entry.set_prop("show-password", "true") + _draw(entry) + + def test_combo_with_items_and_styles(self): + combo = self._widget("GtkComboBox", items="Red|Green|Blue", + active=1, text="Green") + _draw(combo) + combo.set_prop("style", "Simple") + _draw(combo) + + def test_checklistbox_checked_rows(self): + check = self._widget("TCheckListBox", width=200, height=120, + items="A|B|C") + check.set_checked_items(["A", "C"]) + _draw(check) + + def test_scrollbar_orientations(self): + for orientation in (0, 1): + bar = self._widget("GtkScrollbar", width=200, height=30, + **{"value": 30, "lower": 0, "upper": 100, + "page-size": 20, + "orientation": orientation}) + _draw(bar) + + def test_scale_variants(self): + for kind, extra in ( + ("GtkScale", {"value": 70, "tick-marks": 3, + "frequency": 10, "draw-value": True}), + ("TTrackBar", {"orientation": 1, "value": 40}), + ("GtkProgressBar", {"fraction": 0.45, + "show-text": True}), + ("GtkSpinButton", {"value": 42, "digits": 2}), + ("GtkLevelBar", {"value": 80})): + _draw(self._widget(kind, width=200, height=40, **extra)) + + def test_notebook_and_calendar(self): + notebook = self._widget("GtkNotebook", width=260, height=180, + pages="One|Two|Three", page=1, + **{"tab-position": 0}) + _draw(notebook) + notebook.set_prop("tab-position", "Bottom") + _draw(notebook) + calendar = self._widget("GtkCalendar", width=220, height=180, + date="2026-11-30", + **{"show-week-numbers": True}) + _draw(calendar) + calendar.set_prop("show-heading", "false") + _draw(calendar) + + def test_tree_and_list_views(self): + tree = self._widget("GtkTreeView", width=260, height=180, + items="Root/Child 1;Root/Child 2;Other", + **{"grid-lines": True, "item-index": 1}) + _draw(tree) + view = self._widget("GtkListView", width=260, height=180, + columns="Name|Value", + items="Row 1,Value 1;Row 2,Value 2", + **{"view-style": 0, "grid-lines": True}) + _draw(view) + view.set_prop("view-style", "Icon") + _draw(view) + + def test_shapes(self): + for shape in range(10): + widget = self._widget("TShape", width=120, height=90, + shape=shape) + _draw(widget) + + def test_menubutton_directions(self): + for direction in ("Up", "Down", "Left", "Right", "None"): + button = self._widget("GtkMenuButton", direction=direction) + _draw(button) + + def test_textview_wrap_and_scrollbars(self): + view = self._widget("GtkTextView", width=260, height=180, + text="First line\nSecond line of text here", + **{"wrap-mode": "Word", + "scroll-bars": "Both", + "cursor-visible": True}) + _draw(view) + view.set_prop("wrap-mode", "None") + view.set_cursor_visible(False) + _draw(view) + + def test_buttons_and_toggles(self): + for kind, extra in ( + ("GtkButton", {"default": True}), + ("GtkLinkButton", {}), + ("GtkColorButton", {"color": "rgb(200,30,30)"}), + ("GtkLockButton", {}), + ("GtkCheckButton", {"active": True}), + ("GtkCheckButton", {"inconsistent": True, + "allow-grayed": True}), + ("GtkRadioButton", {"active": True}), + ("GtkSwitch", {"active": True}), + ("GtkToggleButton", {"active": True, "flat": True}), + ("GtkLabel", {"xalign": 1, "wrap": True}), + ("GtkImage", {"file": "photo.png"}), + ("GtkStatusbar", {"text": "Ready", + "size-grip": True}), + ("GtkStatusbar", {"panels": "A|B|C"}), + ("GtkFrame", {"label": "Group", "label-xalign": 0.5}), + ("GtkDialog", {"title": "Confirm"})): + _draw(self._widget(kind, **extra)) + + def test_background_border_and_font_props_change_pixels(self): + plain = self._widget("GtkButton") + styled = self._widget("GtkButton", background="#336699", + foreground="#ffffff", + **{"font-size": 18, "font-bold": True, + "border-radius": 10}) + self.assertNotEqual( + _non_white_pixels(_draw(plain)), + _non_white_pixels(_draw(styled))) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_model.py b/tests/test_model.py index 27cedb0..c0bec2d 100644 --- a/tests/test_model.py +++ b/tests/test_model.py @@ -28,7 +28,9 @@ class ProjectModelTests(unittest.TestCase): project = Project() widget = project.add_widget("GtkButton", 10, 10) self.assertIs(project.selected, widget) - self.assertEqual(widget.get_prop("text"), "GtkButton_001") + # Phase 2: a Button's caption prop is "label" (SS2.1). + self.assertEqual(widget.get_prop("label"), "GtkButton_001") + self.assertEqual(widget.text, "GtkButton_001") def test_remove_clears_selection(self): project = Project() @@ -62,7 +64,7 @@ class FdjTests(unittest.TestCase): project.title = "My App" project.add_widget("GtkButton", 10, 20) project.add_widget("GtkLabel", 200, 30, 180, 30) - project.widgets[1].set_prop("text", "Hello") + project.widgets[1].set_prop("label", "Hello") project.widgets[1].signals.append("clicked") loaded = Project.load_text(project.save_text()) self.assertEqual(loaded.title, "My App") @@ -70,7 +72,7 @@ class FdjTests(unittest.TestCase): self.assertEqual((loaded.win_width, loaded.win_height), (800, 600)) self.assertEqual(len(loaded.widgets), 2) self.assertEqual(loaded.widgets[0].name, "GtkButton_001") - self.assertEqual(loaded.widgets[1].get_prop("text"), "Hello") + self.assertEqual(loaded.widgets[1].get_prop("label"), "Hello") self.assertEqual(loaded.widgets[1].signals, ["clicked"]) self.assertEqual(loaded.save_text(), project.save_text()) @@ -88,10 +90,13 @@ class FdjTests(unittest.TestCase): def test_load_is_valid_json_with_sorted_props(self): project = Project() widget = project.add_widget("GtkButton", 0, 0) - widget.set_prop("zeta", "1") - widget.set_prop("alpha", "2") + # Phase 2: set_prop only accepts table props; the saved + # props dict is still sorted by key (seeded "label" included). + widget.set_prop("glyph", "1") + widget.set_prop("foreground", "red") data = json.loads(project.save_text()) - self.assertEqual(list(data["widgets"][0]["props"]), ["alpha", "text", "zeta"]) + self.assertEqual(list(data["widgets"][0]["props"]), + ["foreground", "glyph", "label"]) def test_load_rejects_bad_format_and_version(self): with self.assertRaises(ValueError): @@ -141,9 +146,9 @@ class FdjTests(unittest.TestCase): def test_string_escaping_round_trip(self): project = Project() widget = project.add_widget("GtkLabel", 0, 0) - widget.set_prop("text", 'quote " backslash \\ newline\n tab\t') + widget.set_prop("label", 'quote " backslash \\ newline\n tab\t') loaded = Project.load_text(project.save_text()) - self.assertEqual(loaded.widgets[0].get_prop("text"), + self.assertEqual(loaded.widgets[0].get_prop("label"), 'quote " backslash \\ newline\n tab\t') diff --git a/tests/test_props.py b/tests/test_props.py new file mode 100644 index 0000000..6cd0659 --- /dev/null +++ b/tests/test_props.py @@ -0,0 +1,325 @@ +"""Tests for lightgui.props and Phase 2 live-apply plumbing. + +Covers: every one of the 547 kinds has a property table with the +generic set present; per-widget tables match the proposal SS2.1-SS2.10 +lists; set_prop validation rejects unknown props; live-apply changes +widget state and marks the canvas dirty; set_items / password / +direction / cursor-visible behaviour; model-only props are flagged. +""" + +import unittest + +from lightgui import props +from lightgui.xframe import core +from lightgui.xframe import palette +from lightgui.xframe.canvas import CanvasState + +# Proposal SS1 generic set (internal C names): Name, geometry, Color, +# Font (+ sub-props), Border (+ sub-props), Enabled, Visible, Hint, +# ShowHint, Cursor, TabOrder, TabStop, Constraints, BorderSpacing, +# AutoSize, Tag, Align, Anchors. +GENERIC_REQUIRED = { + "name", "left", "top", "width", "height", + "background", "foreground", + "font-name", "font-size", "font-bold", "font-italic", + "font-underline", "font-strikeout", + "border-width", "border-color", "border-radius", + "enabled", "visible", "hint", "show-hint", "cursor", + "tab-order", "tab-stop", + "min-width", "min-height", "max-width", "max-height", + "margin-left", "margin-top", "margin-right", "margin-bottom", + "margin-around", "autosize", "tag", "align", + "anchor-top", "anchor-left", "anchor-right", "anchor-bottom", +} + +# Proposal SS2.1-SS2.10 per-widget lists (internal C names). +PER_WIDGET = { + "Button": ["label", "default", "cancel", "kind", "layout", "glyph", + "modal-result"], + "Entry": ["text", "editable", "max-length", "placeholder-text", + "password", "alignment", "char-case", "numbers-only", + "hide-selection", "auto-select"], + "Label": ["label", "xalign", "yalign", "wrap", "selectable", + "transparent", "focus-control", "show-accel-char"], + "CheckBox": ["label", "active", "inconsistent", "allow-grayed", + "alignment", "value-checked", "value-unchecked"], + "RadioButton": ["label", "active", "group"], + "ComboBox": ["items", "active", "text", "style", "drop-down-count", + "drop-down-width", "sorted", "read-only", "max-length"], + "ListBox": ["items", "selection-mode", "item-index", "sorted", + "columns", "item-height", "integral-height"], + "CheckListBox": ["items", "checked-items", "item-index", + "item-height", "sorted"], + "ScrollBar": ["value", "lower", "upper", "step-increment", + "page-increment", "page-size", "orientation", + "large-change"], + "TrackBar": ["value", "minimum", "maximum", "step", "page-step", + "draw-value", "tick-marks", "frequency"], + "TextView": ["text", "editable", "cursor-visible", "wrap-mode", + "max-length", "scroll-bars", "want-tabs", + "want-returns", "hide-selection", "alignment"], + "Memo": ["text", "editable", "cursor-visible", "wrap-mode", + "max-length", "scroll-bars", "want-tabs", "want-returns", + "hide-selection", "alignment"], +} + + +class GenericSetTests(unittest.TestCase): + def test_every_kind_has_generic_set(self): + self.assertEqual(len(palette.PALETTE), 547) + for entry in palette.PALETTE: + names = props.prop_names(entry.name) + missing = GENERIC_REQUIRED - names + self.assertFalse(missing, + "%s missing generic props: %s" + % (entry.name, sorted(missing))) + + def test_generic_set_is_same_for_all_kinds(self): + for entry in palette.PALETTE: + self.assertEqual(props.GENERIC_NAMES, + props.GENERIC_NAMES + & props.prop_names(entry.name)) + + def test_registry_names_resolve_like_kinds(self): + self.assertEqual(props.props_for("GtkButton"), + props.props_for("Button")) + self.assertEqual(props.props_for("TCheckBox"), + props.props_for("CheckBox")) + self.assertEqual(props.props_for("GtkNoSuchWidget"), + tuple(props.GENERIC_PROPS)) + + def test_stock_and_instrument_kinds_generic_only_for_now(self): + # Phase 6 adds their tables; Phase 2 gives them the generic + # set only (plus nothing custom). + self.assertEqual(props.custom_props_for("IndRSI"), ()) + self.assertEqual(props.custom_props_for("InstLedRed"), ()) + self.assertEqual(props.custom_props_for("StockLineChart"), ()) + + +class PerWidgetTests(unittest.TestCase): + def test_proposal_sections_2_1_to_2_10(self): + for kind, required in PER_WIDGET.items(): + names = props.prop_names(kind) + for name in required: + self.assertIn(name, names, + "%s table missing %s" % (kind, name)) + + def test_button_kind_enum_labels_match_c(self): + prop = props.find_prop("Button", "kind") + self.assertEqual(prop.enum_labels, + ("None", "OK", "Cancel", "Yes", "No", "Close", + "Help", "Retry", "Ignore", "Abort")) + self.assertEqual(prop.enum_values, + (0, 1, 2, 3, 4, 5, 6, 7, 8, 9)) + + def test_events_use_lazarus_names(self): + for event in ("OnClick", "OnChange", "OnKeyPress", "OnMouseDown", + "OnMouseUp", "OnMouseMove", "OnDblClick"): + self.assertIn(event, props.EVENTS) + + +class ModelOnlyTests(unittest.TestCase): + def test_model_only_props_flagged(self): + for name in ("font-underline", "font-strikeout", "cursor", + "tab-order", "tab-stop", "tag", "align", + "anchor-top", "hint", "show-hint", "glyph", + "autosize", "margin-left"): + self.assertTrue(props.is_model_only("GtkButton", name), + name) + + def test_live_props_not_model_only(self): + for name in ("background", "foreground", "border-width", + "font-name", "font-size", "font-bold", "enabled", + "visible", "label", "value", "items", "active", + "password", "direction", "cursor-visible", + "lower", "page-increment"): + kind = ("GtkScrollbar" if name in ("lower", "page-increment") + else "GtkMenuButton" if name == "direction" + else "GtkTextView" if name == "cursor-visible" + else "GtkEntry" if name == "password" + else "GtkButton") + self.assertFalse(props.is_model_only(kind, name), name) + + def test_register_custom_table_hook(self): + # Phase 6 hook: a Stock kind gains a custom table, then the + # hook is undone so other tests see the Phase 2 state. + try: + props.register_custom_table( + "IndRSI", (props.PropDef( + "period", "Int", "14", 1, 100, (), (), + "Period", False),)) + self.assertIn("period", props.prop_names("IndRSI")) + finally: + props.register_custom_table("IndRSI", ()) + + +class ValidateTests(unittest.TestCase): + def test_unknown_prop_rejected(self): + with self.assertRaises(ValueError): + props.validate("GtkButton", "no-such-prop", "x") + + def test_bool_canonicalisation(self): + self.assertEqual(props.validate("GtkButton", "enabled", "yes"), + "true") + self.assertEqual(props.validate("GtkButton", "enabled", False), + "false") + with self.assertRaises(ValueError): + props.validate("GtkButton", "enabled", "maybe") + + def test_int_range(self): + self.assertEqual( + props.validate("GtkButton", "modal-result", 5), "5") + with self.assertRaises(ValueError): + props.validate("GtkButton", "modal-result", 500) + + def test_enum_label_and_value(self): + self.assertEqual(props.validate("GtkButton", "kind", "OK"), "1") + self.assertEqual(props.validate("GtkButton", "kind", 2), "2") + with self.assertRaises(ValueError): + props.validate("GtkButton", "kind", "Nope") + + def test_color_canonicalisation(self): + self.assertEqual( + props.validate("GtkButton", "background", "#FF0000"), + "#ff0000") + self.assertEqual( + props.validate("GtkButton", "background", "rgb(1, 2, 3)"), + "rgb(1,2,3)") + with self.assertRaises(ValueError): + props.validate("GtkButton", "background", "not-a-color") + + +class LiveApplyTests(unittest.TestCase): + def setUp(self): + self.button = core.create("GtkButton", "GtkButton_001", 0, 0) + + def test_set_prop_rejects_unknown(self): + with self.assertRaises(ValueError): + self.button.set_prop("no-such-prop", "x") + with self.assertRaises(ValueError): + self.button.set_prop("modal-result", 500) + + def test_set_prop_updates_state_and_marks_dirty(self): + self.assertFalse(self.button.dirty) + self.button.set_prop("label", "Hello") + self.assertEqual(self.button.get_prop("label"), "Hello") + self.assertEqual(self.button.text, "Hello") + self.assertTrue(self.button.dirty) + + def test_set_prop_notifies_host(self): + calls = [] + self.button.on_change = lambda: calls.append(1) + self.button.set_prop("label", "Hi") + self.assertEqual(calls, [1]) + + def test_set_prop_geometry_updates_fields(self): + self.button.set_prop("left", 12) + self.button.set_prop("top", 34) + self.button.set_prop("width", 200) + self.button.set_prop("height", 50) + self.assertEqual((self.button.x, self.button.y, + self.button.width, self.button.height), + (12, 34, 200, 50)) + self.button.set_prop("left", -5) + self.button.set_prop("width", 3) + self.assertEqual(self.button.x, 0) + self.assertEqual(self.button.width, 10) + self.button.set_prop("name", "Renamed") + self.assertEqual(self.button.name, "Renamed") + + def test_canvas_state_wiring_marks_canvas_dirty(self): + state = CanvasState() + state.place("GtkButton", 0, 0) + widget = state.project.widgets[0] + calls = [] + state.on_change = lambda: calls.append(1) + calls.clear() + widget.set_prop("label", "Placed") + self.assertTrue(calls, "canvas on_change not called") + self.assertTrue(widget.dirty) + + def test_set_text_uses_canonical_prop(self): + checkbox = core.create("GtkCheckButton", "GtkCheckButton_001") + checkbox.set_text("Tick me") + self.assertEqual(checkbox.get_prop("label"), "Tick me") + self.assertEqual(checkbox.text, "Tick me") + + +class WidgetSetterTests(unittest.TestCase): + def test_set_items_list_and_string(self): + combo = core.create("GtkComboBox", "GtkComboBox_001") + combo.set_items(["Red", "Green", "Blue"]) + self.assertEqual(combo.get_items(), ["Red", "Green", "Blue"]) + self.assertEqual(combo.get_prop("items"), "Red|Green|Blue") + self.assertTrue(combo.dirty) + combo.set_items("One|Two") + self.assertEqual(combo.get_items(), ["One", "Two"]) + + def test_set_items_prunes_checked_items(self): + check = core.create("TCheckListBox", "TCheckListBox_001") + check.set_items(["A", "B", "C"]) + check.set_checked_items(["A", "C"]) + check.set_items(["A", "B"]) + self.assertEqual(check.get_checked_items(), ["A"]) + + def test_checklistbox_checked_state(self): + check = core.create("TCheckListBox", "TCheckListBox_001") + check.set_items(["A", "B", "C"]) + check.set_item_checked("B", True) + self.assertTrue(check.is_item_checked("B")) + self.assertEqual(check.get_checked_items(), ["B"]) + check.set_item_checked("B", False) + self.assertFalse(check.is_item_checked("B")) + # Items not in the list cannot be checked. + check.set_checked_items(["Z", "A"]) + self.assertEqual(check.get_checked_items(), ["A"]) + + def test_entry_password_masked_by_default(self): + entry = core.create("GtkEntry", "GtkEntry_001") + entry.set_prop("text", "secret") + self.assertFalse(entry.get_password()) + entry.set_password(True) + self.assertTrue(entry.get_password()) + self.assertEqual(entry._display_text(), "******") + entry.set_show_password(True) + self.assertEqual(entry._display_text(), "secret") + entry.set_show_password(False) + self.assertEqual(entry._display_text(), "******") + + def test_menubutton_direction(self): + button = core.create("GtkMenuButton", "GtkMenuButton_001") + self.assertEqual(button.get_direction(), 1) # Down default + button.set_direction("Left") + self.assertEqual(button.get_direction(), 2) + self.assertEqual(button.get_prop("direction"), "2") + button.set_direction(0) + self.assertEqual(button.get_direction(), 0) + + def test_textview_cursor_visible(self): + view = core.create("GtkTextView", "GtkTextView_001") + self.assertTrue(view.get_cursor_visible()) + view.set_cursor_visible(False) + self.assertFalse(view.get_cursor_visible()) + self.assertEqual(view.get_prop("cursor-visible"), "false") + + def test_scrollbar_lower_and_page_increment(self): + bar = core.create("GtkScrollbar", "GtkScrollbar_001") + bar.set_lower(-50) + self.assertEqual(bar.get_lower(), -50.0) + bar.set_page_increment(25) + self.assertEqual(bar.get_page_increment(), 25.0) + self.assertEqual(bar.get_prop("lower"), "-50") + self.assertEqual(bar.get_prop("page-increment"), "25") + + def test_range_value_clamped(self): + scale = core.create("GtkScale", "GtkScale_001") + scale.set_prop("minimum", "0") + scale.set_prop("maximum", "100") + scale.set_value(150) + self.assertEqual(scale.get_value(), 100.0) + scale.set_value(-10) + self.assertEqual(scale.get_value(), 0.0) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/gen_props.py b/tools/gen_props.py index 4e51448..81e8198 100644 --- a/tools/gen_props.py +++ b/tools/gen_props.py @@ -501,13 +501,13 @@ def main(): {"name": "name", "kind": "Str", "default": "", "lo": 0.0, "hi": 0.0, "labels": None, "values": None}, {"name": "left", "kind": "Int", "default": "0", "lo": 0.0, - "hi": 100000.0, "labels": None, "values": None}, + "hi": 0.0, "labels": None, "values": None}, {"name": "top", "kind": "Int", "default": "0", "lo": 0.0, - "hi": 100000.0, "labels": None, "values": None}, - {"name": "width", "kind": "Int", "default": "100", "lo": 10.0, - "hi": 100000.0, "labels": None, "values": None}, - {"name": "height", "kind": "Int", "default": "30", "lo": 10.0, - "hi": 100000.0, "labels": None, "values": None}, + "hi": 0.0, "labels": None, "values": None}, + {"name": "width", "kind": "Int", "default": "100", "lo": 0.0, + "hi": 0.0, "labels": None, "values": None}, + {"name": "height", "kind": "Int", "default": "30", "lo": 0.0, + "hi": 0.0, "labels": None, "values": None}, ] generic.extend(tables["common"]) for name, kind, default, lo, hi, labels in GENERIC_EXTRAS: