Files
Muse 54c60188f0 X* monitor family (15 widgets): MonitorWidget + palette 547 -> 562
New btop-style live monitor widgets (registry 547-561, archetype
Monitor, family X, section Misc / X): XHistoryGraph, XCoreGrid,
XNetGraph, XTempHistory, XUsageBar, XStackBar, XVerticalBar,
XTachometer, XArcGauge, XDonutGauge, XProcessList, XLoadBadge,
XMonitorButton, XMonitorGrid, XSysBox. Drawn with Cairo on a
Gtk.DrawingArea like the rest of the set; sample data is runtime
state only (demo sine data until push()/refresh()/poll() feeds
real data). Checks are stdlib only: /proc scan, systemctl
is-active, socket to localhost. 35 new tests; full suite 363 green.
2026-12-05 16:48:47 +00:00

2667 lines
101 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""XFrame core: widget base class, registry, draw dispatch, hit-testing.
Ports the interaction constants and geometry of the C designer
(src/xframe_canvas_core.cpp) and the Rust designer
(crates/lightgui-designer/src/canvas.rs):
- handles are 13px, hit-tested with an 8px pad on every side
- double-click: two presses within 450ms on the same widget show the
handles, regardless of a small jiggle between the presses
- drag threshold: 8px — sub-8px motion must not move the widget
- resize handles clamp to a 24x16 minimum and to x/y >= 0
Setters are state-only: they update the widget's geometry/props and
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 562 widget classes).
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 draw in their own modules
(lightgui/xframe/stock.py and instruments.py, Phase 6); the generic
panel drawing survives only as a fallback in those modules.
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) ---
HANDLE_SIZE = 13
HANDLE_HIT_PAD = 8
DRAG_THRESHOLD = 8
DBLCLICK_MS = 450
MIN_WIDTH = 24
MIN_HEIGHT = 16
HANDLE_COUNT = 8
# Handle order: NW, N, NE, E, SE, S, SW, W (same as C/Rust).
HANDLE_NAMES = ("NW", "N", "NE", "E", "SE", "S", "SW", "W")
# Selection outline colour (Rust: 37, 99, 235) and handle fill
# (C/Rust: 255, 127, 0).
SELECT_RGB = (37 / 255, 99 / 255, 235 / 255)
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:
return text
while text and cr.text_extents(text + "...")[2] > max_width:
text = text[:-1]
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."""
if not text:
return
cr.save()
cr.select_font_face("Sans", 0, 1 if bold else 0)
cr.set_font_size(size)
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 _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)
_rgb(cr, fill)
cr.rectangle(x + 0.5, y + 0.5, w - 1, h - 1)
cr.fill_preserve()
_rgb(cr, stroke)
cr.stroke()
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.
``kind`` is the registry name (e.g. ``"GtkButton"``); ``name`` is the
instance name (e.g. ``"GtkButton_001"``). Geometry and ``props`` are
plain state; ``set_*`` methods never draw.
"""
ARCHETYPE = "Display"
def __init__(self, kind, name, x=0, y=0, width=100, height=30,
props=None, signals=None, widget_id=-1):
self.kind = kind
self.name = name
self.x = int(x)
self.y = int(y)
# Model state only needs a positive size; the 24x16 floor is a
# canvas interaction minimum (see set_bounds), not a model one,
# so a .fdj file holding a 10x10 widget loads as 10x10, like
# the C loader (which clamps to 10).
self.width = max(int(width), 1)
self.height = max(int(height), 1)
self.props = dict(props) if props else {}
self.signals = list(signals) if signals else []
self.id = widget_id
# 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 / property table ---------------------------------------
@property
def archetype(self):
entry = _palette.find(self.kind)
if entry is not None:
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)
return entry.default_w if entry is not None else 100
@property
def default_height(self):
entry = _palette.find(self.kind)
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."""
self.x = max(int(x), 0)
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):
"""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):
"""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):
"""Display text: the text/label prop, else the instance name."""
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
and self.y <= py <= self.y + self.height)
def handle_centre(self, index):
"""Centre of handle *index* (0=NW .. 7=W); corners sit on the
widget corners, edge handles on the edge midpoints."""
cx = self.x + self.width // 2
cy = self.y + self.height // 2
xs = [self.x, cx, self.x + self.width, self.x + self.width,
self.x + self.width, cx, self.x, self.x]
ys = [self.y, self.y, self.y, cy,
self.y + self.height, self.y + self.height,
self.y + self.height, cy]
return xs[index], ys[index]
def handle_rect(self, index):
cx, cy = self.handle_centre(index)
return (cx - HANDLE_SIZE // 2, cy - HANDLE_SIZE // 2,
HANDLE_SIZE, HANDLE_SIZE)
def handle_at(self, px, py):
"""Handle index at (px, py), or -1. Only when handles are on."""
if not self.handles_on:
return -1
for i in range(HANDLE_COUNT):
hx, hy, hw, hh = self.handle_rect(i)
if (hx - HANDLE_HIT_PAD <= px <= hx + hw + HANDLE_HIT_PAD
and hy - HANDLE_HIT_PAD <= py <= hy + hh + HANDLE_HIT_PAD):
return i
return -1
def apply_handle_drag(self, index, dx, dy):
"""Resize/move by dragging handle *index* by (dx, dy).
Mirrors C apply_handle_drag / Rust apply_handle_drag."""
x, y, w, h = self.x, self.y, self.width, self.height
if index == 0: # NW
x += dx; y += dy; w -= dx; h -= dy
elif index == 1: # N
y += dy; h -= dy
elif index == 2: # NE
y += dy; w += dx; h -= dy
elif index == 3: # E
w += dx
elif index == 4: # SE
w += dx; h += dy
elif index == 5: # S
h += dy
elif index == 6: # SW
x += dx; w -= dx; h += dy
else: # W
x += dx; w -= dx
self.set_bounds(x, y, w, h)
# --- drawing --------------------------------------------------------
def draw(self, cr):
"""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, 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 562 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):
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()
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):
kind = self.pkind
if kind == "Switch":
_draw_switch(cr, self)
return
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(x + 3, cy)
cr.line_to(x + size - 3, cy)
cr.stroke()
cr.restore()
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()
_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(knob_x, y + track_h / 2, knob_r, 0, 2 * math.pi)
cr.fill()
cr.restore()
class LabelWidget(Widget):
ARCHETYPE = "Label"
def _draw(self, cr):
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):
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(26, mid)
cr.line_to(self.width - 8, mid)
cr.stroke()
_rgb(cr, (0.92, 0.92, 0.92))
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"
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
has_children = (i + 1 < len(rows)
and rows[i + 1].startswith(path + "/"))
if _prop_bool(self, "show-buttons", True) and has_children:
_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):
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):
if show_week:
from datetime import timedelta as _td
monday = first + _td(days=row * 7 - start_col)
_wtext(cr, self, str(monday.isocalendar()[1]),
14, y + row * row_h + row_h / 2 + 4, size=10,
align="center", rgb=(0.5, 0.5, 0.5))
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):
_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)
cr.move_to(24, 6)
cr.line_to(24, self.height - 18)
cr.line_to(self.width - 6, self.height - 18)
cr.stroke()
cr.restore()
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):
"""One of the 250 Ind* indicators (archetype Indicator).
Draws the indicator's computed lines from OHLCV bars. The bars
come from the widget's own series when set (``set_series`` /
``load_csv`` / ``populate``), else from the built-in deterministic
demo series -- the same fallback the StockWidget chart widgets
use. The series is runtime state only, never saved in .fdj.
The lines themselves are computed by
``lightgui.xframe.indicators.compute_lines`` (transpiled from the
C component ``ind_*`` functions; see tools/transpile_indicators.py
and lightgui/xframe/indicators.py), so every kind recomputes from
the loaded data instead of the built-in demo lines.
"""
ARCHETYPE = "Indicator"
# Plot palette: the 14 line colours from the Rust
# xframe-indicators plot.rs PLOT_PALETTE, in order. Line j of a
# kind uses _PLOT_PALETTE[j % 14].
_PLOT_PALETTE = (
(0.13, 0.35, 0.85), # blue
(0.95, 0.55, 0.10), # orange
(0.55, 0.25, 0.80), # purple
(0.00, 0.60, 0.60), # teal
(0.85, 0.20, 0.55), # magenta
(0.55, 0.35, 0.15), # brown
(0.20, 0.65, 0.25), # green
(0.80, 0.15, 0.15), # red
(0.10, 0.55, 0.80), # steel blue
(0.65, 0.65, 0.10), # olive
(0.35, 0.35, 0.35), # grey
(0.90, 0.70, 0.10), # gold
(0.25, 0.25, 0.70), # indigo
(0.60, 0.20, 0.20), # brick
)
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
# Own series: None means "use the built-in demo series";
# a list (possibly empty) is data the user fed in.
self._series = None
# --- data ingestion (mirrors StockWidget, single slot) --------------
def set_series(self, bars):
"""Replace the series this indicator computes from.
*bars* is a list of (open, high, low, close, volume) tuples
(or dicts with those keys), or None to revert to the built-in
demo series. The indicator recomputes its lines from the new
data on the next draw. Marks the widget dirty so the host
redraws.
"""
self._series = _stock_mod._validate_bars(bars)
self._mark_dirty()
def populate(self, bars):
"""Alias for ``set_series``: fill the indicator with *bars*.
The clear/populate pair: ``widget.clear()`` empties the
series, ``widget.populate(bars)`` (or ``set_series``) refills
it.
"""
self.set_series(bars)
def get_series(self):
"""The bars this indicator currently plots: the widget's own
series when set, else the built-in demo series. Returns a
copy, so callers cannot mutate the plotted data.
"""
return list(_ind_mod._bars(self))
def add_point(self, bar):
"""Append one (open, high, low, close, volume) bar to the
series and return the new bar count.
If no own series was set yet, this starts a fresh series
(it does NOT extend the demo series).
"""
bar = _stock_mod._validate_bars([bar], what="add_point")[0]
if self._series is None:
self._series = []
self._series.append(bar)
self._mark_dirty()
return len(self._series)
def clear(self):
"""Empty the series. A cleared widget draws the no-data
placeholder until ``populate`` / ``set_series`` refills it
(or ``set_series(None)`` restores the demo series).
"""
self._series = []
self._mark_dirty()
def load_csv(self, source):
"""Load OHLCV bars from a CSV file into this indicator.
*source* is a path or a file-like object; see
``lightgui.xframe.stock.load_csv`` for the format (the same
``date,open,high,low,close,volume`` spec the chart widgets
use). Returns the number of bars loaded. Raises ValueError
naming the offending row on bad data, and leaves the previous
series untouched in that case.
"""
bars = _stock_mod.load_csv(source)
self.set_series(bars)
return len(bars)
def item_count(self):
"""Number of bars this indicator currently plots."""
return len(_ind_mod._bars(self))
def get_lines(self, params=None):
"""The plotted lines for the current series, as a list of
float lists (one per bar, NaN where the indicator has no
value yet), in plot order. *params* overrides the kind's
default parameters positionally. An empty list means the
series was cleared; a kind this widget does not know returns
the panel fallback (no lines).
"""
kind = self._ind_kind()
if kind is None:
return []
bars = _ind_mod._bars(self)
if not bars:
return []
return _ind_mod.compute_lines(kind, bars, params)
def _ind_kind(self):
"""Registry name (``IndRSI``) for this widget's kind, or None
when the kind is not one of the 250 indicators."""
kind = self.kind
if kind in _ind_mod.INDICATOR_INFO:
return kind
if ("Ind" + kind) in _ind_mod.INDICATOR_INFO:
return "Ind" + kind
return None
def _draw(self, cr):
# A cleared series draws the no-data placeholder instead of
# lines: compute_lines would index into an empty series.
if self._series is not None and len(self._series) == 0:
_stock_mod._no_data(cr, self)
return
kind = self._ind_kind()
if kind is None:
_draw_panel(cr, self)
return
bars = _ind_mod._bars(self)
lines = _ind_mod.compute_lines(kind, bars)
_bg(cr, self, (1.0, 1.0, 1.0), stroke=(0.55, 0.55, 0.55))
_wtext(cr, self, self.pkind, self.width / 2, 16, size=12,
align="center", rgb=(0.4, 0.4, 0.4),
max_width=self.width - 12)
# Plot area below the header.
px, py = 6, 24
pw, ph = max(1, self.width - 12), max(1, self.height - 30)
n = len(bars)
if n == 0 or ph <= 0:
return
lo, hi = None, None
for values in lines:
for v in values:
if v is None or v != v:
continue
lo = v if lo is None else min(lo, v)
hi = v if hi is None else max(hi, v)
if lo is None:
return
if hi <= lo:
hi = lo + 1.0
pad = (hi - lo) * 0.05 or 0.5
lo -= pad
hi += pad
def _x(i):
return px + (i + 0.5) * pw / n
def _y(v):
return py + ph - (v - lo) / (hi - lo) * ph
for j, values in enumerate(lines):
colour = self._PLOT_PALETTE[j % len(self._PLOT_PALETTE)]
cr.save()
_rgb(cr, colour)
cr.set_line_width(2.0)
started = False
for i in range(min(n, len(values))):
v = values[i]
if v is None or v != v:
started = False
continue
if not started:
cr.move_to(_x(i), _y(v))
started = True
else:
cr.line_to(_x(i), _y(v))
cr.stroke()
cr.restore()
# Isolated finite points (pattern/marker kinds such as
# FractalUp/Down and ZigZag, whose values are single-bar
# pivots) would otherwise draw nothing: a move_to with no
# line_to leaves no mark. Draw them as filled dots.
cr.save()
_rgb(cr, colour)
for i in range(min(n, len(values))):
v = values[i]
if v is None or v != v:
continue
prev_nan = i == 0 or values[i - 1] is None \
or values[i - 1] != values[i - 1]
next_nan = i + 1 >= len(values) or values[i + 1] is None \
or values[i + 1] != values[i + 1]
if prev_nan and next_nan:
cr.arc(_x(i), _y(v), 3, 0, 2 * math.pi)
cr.fill()
cr.restore()
class InstrumentWidget(Widget):
ARCHETYPE = "Instrument"
def _draw(self, cr):
_draw_panel(cr, self)
# Simple gauge needle, centred.
cx, cy = self.width / 2, self.height * 0.62
r = min(self.width, self.height) * 0.32
cr.save()
_rgb(cr, (0.2, 0.2, 0.2))
cr.set_line_width(1.5)
cr.arc(cx, cy, r, math.pi, 2 * math.pi)
cr.stroke()
cr.move_to(cx, cy)
cr.line_to(cx + r * 0.6, cy - r * 0.6)
cr.stroke()
cr.restore()
def _draw_panel(cr, widget):
_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):
_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:
_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):
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):
ARCHETYPE = "Display"
class GraphWidget(Widget):
ARCHETYPE = "Graph"
def _draw(self, cr):
ChartWidget._draw(self, cr)
class SpreadsheetWidget(Widget):
ARCHETYPE = "Spreadsheet"
def _draw(self, cr):
_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)
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)
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()
ARCHETYPE_CLASSES = {
"Button": ButtonWidget,
"Toggle": ToggleWidget,
"Label": LabelWidget,
"Entry": EntryWidget,
"Range": RangeWidget,
"ListSel": ListSelWidget,
"Container": ContainerWidget,
"Chart": ChartWidget,
"Indicator": IndicatorWidget,
"Instrument": InstrumentWidget,
"Dialog": DialogWidget,
"Display": DisplayWidget,
"Graph": GraphWidget,
"Spreadsheet": SpreadsheetWidget,
}
# --- registry -------------------------------------------------------------
# kind (registry name) -> archetype class. Every one of the 562 palette
# kinds resolves through the palette table; unknown kinds fall back to
# the generic Display drawing so a hand-edited .fdj cannot break the
# canvas (the .fdj loader skips unknown kinds before this point).
def lookup(kind):
"""Archetype class for a registry *kind*, or None if unknown."""
entry = _palette.find(kind)
if entry is None:
return None
# Phase 6: the Stock (37) + Instrumentation (66) registry names
# draw in their own modules (stock.py / instruments.py), not in
# the generic archetype classes. Dispatch is on the registry
# NAME, not the palette kind: kinds are shared across families
# (kind "VWAP" is IndAnchoredVWAP, IndVWAP and StockVWAP; kind
# "Arrow" is StockArrow and TArrow), so kind-keyed dispatch
# would hijack the Ind*/T* entries into the Phase 6 classes.
cls = _KIND_CLASSES.get(entry.name)
if cls is not None:
return cls
return ARCHETYPE_CLASSES[entry.archetype]
def create(kind, name, x=0, y=0, width=None, height=None, props=None,
signals=None, widget_id=-1):
"""Build a widget of registry *kind*. Returns None if unknown.
``width``/``height`` default to the registry default size.
"""
cls = lookup(kind)
if cls is None:
return None
entry = _palette.find(kind)
if width is None:
width = entry.default_w
if height is None:
height = entry.default_h
return cls(kind, name, x, y, width, height, props=props,
signals=signals, widget_id=widget_id)
def is_known_kind(kind):
return _palette.find(kind) is not None
# --- Phase 6: Stock + Instrumentation --------------------------------------
# The two family modules live beside core.py; they import the Widget
# base + draw helpers from here, so they are imported at the bottom
# (after every name they need exists) rather than at the top, which
# would be circular. Their registry-name -> class map overrides the
# archetype dispatch in lookup() above. props_phase6 registers the 103
# property tables on import, so set_prop validation and the
# generator's model-only comments work in the designer and in
# generated apps (which import only this module).
_KIND_CLASSES = {}
from lightgui.xframe import stock as _stock_mod
from lightgui.xframe import indicators as _ind_mod
from lightgui.xframe import instruments as _inst_mod
# Keyed by registry NAME (see lookup()): the Stock* names draw in
# StockWidget, the Inst* names in InstWidget. Everything else keeps
# the archetype dispatch -- in particular IndVWAP/IndAnchoredVWAP
# (kind "VWAP") stay IndicatorWidget and TArrow (kind "Arrow")
# stays a Button.
for _entry in _palette.PALETTE:
if _entry.name.startswith("Stock"):
_KIND_CLASSES[_entry.name] = _stock_mod.StockWidget
elif _entry.name.startswith("Inst"):
_KIND_CLASSES[_entry.name] = _inst_mod.InstWidget
from lightgui import props_phase6 # noqa: F401
# --- Monitor family (15 X* widgets) ----------------------------------
# The Monitor archetype lives in its own module (monitor.py),
# like the Phase 6 families. Unlike Stock/Inst it needs no
# _KIND_CLASSES override: its palette archetype is "Monitor",
# unique to the family, so the archetype dispatch in lookup()
# finds it directly.
from lightgui.xframe import monitor as _mon_mod
ARCHETYPE_CLASSES["Monitor"] = _mon_mod.MonitorWidget
from lightgui import props_monitor # noqa: F401