diff --git a/lightgui/props_monitor.py b/lightgui/props_monitor.py new file mode 100644 index 0000000..6b679bc --- /dev/null +++ b/lightgui/props_monitor.py @@ -0,0 +1,147 @@ +"""Property tables for the X* monitor family (15 widgets). + +Hand-written (there is no C source for these widgets to generate +from): each kind's own props below, registered with +register_custom_table -- the same hook Phase 6 uses for the Stock / +Instrumentation families. Generic set first (from +lightgui.props.props_for), then each widget's own props. Every prop +here is honoured by the draw code in lightgui/xframe/monitor.py +and live-applies; none is model-only. +""" + +from lightgui.props import PropDef, register_custom_table + + +def _label(default=""): + return PropDef("label", "Str", default, 0, 0, (), (), + "Caption", False) + + +def _value(default="0"): + return PropDef("value", "Double", default, 0, 0, (), (), + "Value", False) + + +def _minimum(default="0"): + return PropDef("minimum", "Double", default, 0, 0, (), (), + "Minimum", False) + + +def _maximum(default="100"): + return PropDef("maximum", "Double", default, 0, 0, (), (), + "Maximum", False) + + +def _window(default="60"): + return PropDef("window", "Int", default, 0, 0, (), (), + "Window", False) + + +def _unit(default=""): + return PropDef("unit", "Str", default, 0, 0, (), (), "Unit", False) + + +# kind (registry name) -> custom props. +MONITOR_TABLES = { + "XHistoryGraph": ( + _label(), + _window(), + _minimum(), + _maximum(), + PropDef("series-count", "Int", "2", 0, 0, (), (), + "SeriesCount", False), + PropDef("series-names", "Str", "", 0, 0, (), (), + "SeriesNames", False), + PropDef("show-legend", "Bool", "true", 0, 0, (), (), + "ShowLegend", False), + ), + "XCoreGrid": ( + _label(), + _window(), + PropDef("cores", "Int", "0", 0, 0, (), (), + "Cores", False), + ), + "XNetGraph": ( + _label(), + _window(), + ), + "XTempHistory": ( + _label(), + _window(), + _minimum(), + _maximum(), + PropDef("threshold", "Double", "80", 0, 0, (), (), + "Threshold", False), + ), + "XUsageBar": ( + _label(), + _value(), + _minimum(), + _maximum(), + ), + "XStackBar": ( + _label(), + PropDef("segments", "Str", "", 0, 0, (), (), + "Segments", False), + ), + "XVerticalBar": ( + _label(), + _value(), + _minimum(), + _maximum(), + ), + "XTachometer": ( + _label(), + _value(), + _minimum(), + _maximum("8000"), + PropDef("redline", "Double", "6400", 0, 0, (), (), + "Redline", False), + _unit(), + ), + "XArcGauge": ( + _label(), + _value(), + _minimum(), + _maximum(), + _unit("usage"), + ), + "XDonutGauge": ( + _label(), + _value(), + _minimum(), + _maximum(), + _unit(), + ), + "XProcessList": ( + _label(), + PropDef("sort-by", "Enum", "0", 0, 0, + ("CPU", "Memory", "PID", "Name"), (0, 1, 2, 3), + "SortBy", False), + PropDef("sort-desc", "Bool", "true", 0, 0, (), (), + "SortDesc", False), + ), + "XLoadBadge": ( + _label(), + ), + "XMonitorButton": ( + _label(), + PropDef("check-type", "Enum", "0", 0, 0, + ("Process", "Unit", "Port"), (0, 1, 2), + "CheckType", False), + PropDef("target", "Str", "", 0, 0, (), (), "Target", False), + ), + "XMonitorGrid": ( + _label(), + ), + "XSysBox": ( + _label(), + _value(), + _minimum(), + _maximum(), + _unit("%"), + ), +} + +for _kind, _props in MONITOR_TABLES.items(): + register_custom_table(_kind, _props) diff --git a/lightgui/xframe/core.py b/lightgui/xframe/core.py index 32caf07..020a849 100644 --- a/lightgui/xframe/core.py +++ b/lightgui/xframe/core.py @@ -14,7 +14,7 @@ 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 547 widget classes). +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 @@ -675,7 +675,7 @@ class Widget: # 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. +# each archetype's _draw -- there are no 562 widget classes. import cairo as _cairo @@ -2584,7 +2584,7 @@ ARCHETYPE_CLASSES = { # --- registry ------------------------------------------------------------- -# kind (registry name) -> archetype class. Every one of the 547 palette +# 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). @@ -2654,3 +2654,13 @@ for _entry in _palette.PALETTE: 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 diff --git a/lightgui/xframe/monitor.py b/lightgui/xframe/monitor.py new file mode 100644 index 0000000..c0c4f64 --- /dev/null +++ b/lightgui/xframe/monitor.py @@ -0,0 +1,1440 @@ +"""Monitor widgets (15): btop-style live system-monitor XFrame widgets. + +New X* family (registry 547-561), drawn with Cairo on a Gtk.DrawingArea +like the rest of the set -- no GTK widget calls inside the widgets. +Dark btop-style panels: near-black background, green/cyan/amber/red +accents, live sample data pushed in by the host (or read from /proc +by the refresh()/poll() helpers, stdlib only). + +Data model (same convention as StockWidget / IndicatorWidget): +sample data is runtime state only, never saved in .fdj. A widget with +no data pushed yet draws deterministic demo data (sine-based) so a +freshly placed widget reads as its kind in the designer; push() / +set_series() / refresh() replace the demo data with real data. +``push`` starts a fresh series -- it does NOT extend the demo series. + +Checks (XMonitorButton / XMonitorGrid, stdlib only): +process by name via a /proc scan (comm), systemd unit via +``systemctl is-active``, TCP port via socket.create_connection to +localhost. ``poll()`` / ``poll_all()`` run the checks; the host +(the demo) calls them on a timer. +""" + +import math +import os +import socket +import subprocess + +import cairo as _cairo + +from lightgui.xframe.core import ( + Widget, + _box, + _prop_bool, + _prop_float, + _prop_int, + _range_frac, + _rgb, + _rounded_box, + _rounded_path, + _text_width, + _wtext, + parse_color, +) + +# --- btop-style palette ---------------------------------------------------- +_PANEL = (0.07, 0.07, 0.09) # near-black panel fill +_PANEL_EDGE = (0.32, 0.32, 0.38) # panel border +_PANEL_INNER = (0.11, 0.11, 0.13) # inner plot / trough fill +_GRID = (0.22, 0.22, 0.26) # plot grid lines +_TITLE = (0.88, 0.88, 0.88) # title text +_TEXT = (0.82, 0.82, 0.82) # body text +_DIM = (0.55, 0.55, 0.58) # dim text / scale labels +_GREEN = (0.30, 0.85, 0.40) +_CYAN = (0.20, 0.75, 0.85) +_YELLOW = (0.95, 0.75, 0.20) +_AMBER = (0.95, 0.62, 0.12) +_RED = (0.90, 0.25, 0.25) +_MAGENTA = (0.85, 0.35, 0.75) +_WHITE = (1.0, 1.0, 1.0) + +_SERIES_COLORS = ( + _GREEN, _CYAN, _YELLOW, _MAGENTA, _AMBER, + (0.35, 0.55, 0.95), (0.75, 0.45, 0.90), _RED, +) + +_STATUS_COLORS = { + "up": _GREEN, + "degraded": _AMBER, + "down": _RED, + "unknown": (0.45, 0.45, 0.50), +} + +_STATUS_LABELS = { + "up": "UP", + "degraded": "DEGRADED", + "down": "DOWN", + "unknown": "UNKNOWN", +} + + +# --- formatting helpers ---------------------------------------------------- + +def _fmt_rate(bytes_per_s): + """Human-readable byte rate: 18.8 KiB/s, 204 Kibps-style short.""" + value = float(bytes_per_s) + for unit in ("B/s", "KiB/s", "MiB/s", "GiB/s"): + if abs(value) < 1024.0 or unit == "GiB/s": + if unit == "B/s": + return "%d %s" % (value, unit) + return "%.1f %s" % (value, unit) + value /= 1024.0 + return "%.1f GiB/s" % value + + +def _fmt_bytes(nbytes): + """Human-readable byte total: 22.4 GiB, 959 MiB, 512 KiB.""" + value = float(nbytes) + for unit in ("B", "KiB", "MiB", "GiB", "TiB"): + if abs(value) < 1024.0 or unit == "TiB": + if unit == "B": + return "%d %s" % (value, unit) + return "%.1f %s" % (value, unit) + value /= 1024.0 + return "%.1f TiB" % value + + +def _fmt_uptime(seconds): + """'up 2d 14:21' from a seconds count.""" + seconds = max(0, int(seconds)) + days, rem = divmod(seconds, 86400) + hours, rem = divmod(rem, 3600) + minutes = rem // 60 + if days: + return "up %dd %02d:%02d" % (days, hours, minutes) + return "up %d:%02d" % (hours, minutes) + + +# --- deterministic demo data ------------------------------------------------ + +def _demo_values(n, seed, base, amp, period=47.0): + """Deterministic sine-based demo samples (no random module).""" + out = [] + for i in range(n): + v = (base + + amp * math.sin((i + seed * 13) * 2 * math.pi / period + + seed) + + 0.35 * amp * math.sin((i + seed * 7) * 2 * math.pi / 13.0)) + out.append(v) + return out + + +def _clamp(values, lo, hi): + return [max(lo, min(hi, v)) for v in values] + + +# --- /proc readers (stdlib only; None when unavailable) ---------------------- + +def _read_cpu_times(): + """{core_index: (idle, total)} from /proc/stat, or None.""" + try: + with open("/proc/stat") as handle: + out = {} + for line in handle: + if line.startswith("cpu") and line[3:4].isdigit(): + parts = line.split() + nums = [int(v) for v in parts[1:]] + total = sum(nums) + idle = nums[3] + (nums[4] if len(nums) > 4 else 0) + out[int(parts[0][3:])] = (idle, total) + return out or None + except (OSError, ValueError): + return None + + +def _read_total_jiffies(): + try: + with open("/proc/stat") as handle: + parts = handle.readline().split() + return sum(int(v) for v in parts[1:]) + except (OSError, ValueError): + return None + + +def _read_processes(): + """Live process rows from /proc: dicts with pid, name, user, + mem_kb, utime, stime. Returns None when /proc is unavailable.""" + try: + import pwd + except ImportError: # pragma: no cover - non-Unix + pwd = None + rows = [] + try: + pids = [d for d in os.listdir("/proc") if d.isdigit()] + except OSError: + return None + for pid in pids: + try: + with open("/proc/%s/stat" % pid) as handle: + data = handle.read() + rparen = data.rfind(")") + comm = data[data.find("(") + 1:rparen] + rest = data[rparen + 2:].split() + utime = int(rest[11]) + stime = int(rest[12]) + with open("/proc/%s/status" % pid) as handle: + uid = None + mem_kb = 0 + for line in handle: + if line.startswith("Uid:"): + uid = int(line.split()[1]) + elif line.startswith("VmRSS:"): + mem_kb = int(line.split()[1]) + user = str(uid) if uid is None else str(uid) + if pwd is not None and uid is not None: + try: + user = pwd.getpwuid(uid).pw_name + except KeyError: + pass + rows.append({"pid": int(pid), "name": comm, "user": user, + "mem_kb": mem_kb, "utime": utime, + "stime": stime, "cpu": 0.0}) + except (OSError, ValueError, IndexError): + continue + return rows + + +def _read_loads(): + """(load1, load5, load15, uptime_seconds), or None.""" + try: + load1, load5, load15 = os.getloadavg() + except (AttributeError, OSError): + return None + uptime = 0.0 + try: + with open("/proc/uptime") as handle: + uptime = float(handle.read().split()[0]) + except (OSError, ValueError, IndexError): + pass + return (load1, load5, load15, uptime) + + +# --- monitor checks (stdlib only) ------------------------------------------- + +def _check_process(name): + """(status, detail) for a process running under *name* (comm).""" + try: + pids = [d for d in os.listdir("/proc") if d.isdigit()] + except OSError: + return ("unknown", "no /proc") + for pid in pids: + try: + with open("/proc/%s/comm" % pid) as handle: + if handle.read().strip() == name: + return ("up", "pid %s" % pid) + except OSError: + continue + return ("down", "not running") + + +def _check_unit(unit): + """(status, detail) for a systemd unit via systemctl is-active.""" + try: + proc = subprocess.run( + ["systemctl", "is-active", unit], + capture_output=True, text=True, timeout=5) + except FileNotFoundError: + return ("unknown", "no systemctl") + except subprocess.TimeoutExpired: + return ("unknown", "timeout") + state = proc.stdout.strip() + if state == "active": + return ("up", "active") + if state == "activating": + return ("degraded", "activating") + if state in ("failed", "inactive", "deactivating"): + return ("down", state) + return ("down", state or "inactive") + + +def _check_port(port): + """(status, detail) for a TCP port on localhost.""" + try: + port = int(port) + except (TypeError, ValueError): + return ("unknown", "bad port") + sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + try: + sock.settimeout(1.0) + sock.connect(("127.0.0.1", port)) + return ("up", "open") + except ConnectionRefusedError: + return ("down", "closed") + except socket.timeout: + return ("down", "timeout") + except OSError: + return ("unknown", "error") + finally: + sock.close() + + +def check_monitor(check_type, target): + """(status, detail) for a monitor spec: check_type 0 = process + by name, 1 = systemd unit, 2 = TCP port on localhost.""" + if check_type == 1: + return _check_unit(target) + if check_type == 2: + return _check_port(target) + return _check_process(target) + + +# --- shared draw helpers ------------------------------------------------------ + +def _panel(cr, widget, title=None): + """Dark btop-style panel: rounded fill + border; title at top + left when given. Returns the plot top (y just below the title).""" + _rounded_box(cr, 0, 0, widget.width, widget.height, _PANEL, + _PANEL_EDGE, line_width=1.0, radius=4) + if title: + _wtext(cr, widget, title, 8, 15, size=12, rgb=_TITLE, bold=True, + max_width=widget.width - 16) + return 22 + return 6 + + +def _plot_frame(cr, x, y, w, h, lo, hi, labels=True): + """Plot area: dark inner fill, horizontal grid lines + y labels + at 0/25/50/75/100% of the range. *labels* is False when the plot + starts too close to the left edge for labels to fit.""" + if w <= 0 or h <= 0: + return + _box(cr, x, y, w, h, _PANEL_INNER, _GRID) + cr.save() + _rgb(cr, _GRID) + cr.set_line_width(1) + for frac in (0.25, 0.5, 0.75): + gy = y + h - frac * h + cr.move_to(x, gy) + cr.line_to(x + w, gy) + cr.stroke() + cr.restore() + if not labels: + return + for frac, label in ((0.0, "%.0f" % lo), (0.5, "%.0f" % ((lo + hi) / 2)), + (1.0, "%.0f" % hi)): + _ylabel(cr, label, x - 2, y + h - frac * h + 3) + + +def _ylabel(cr, text, x, y): + """Small dim right-aligned y-axis label.""" + cr.save() + cr.select_font_face("Sans", 0, 0) + cr.set_font_size(8) + _rgb(cr, _DIM) + w = cr.text_extents(text)[2] + cr.move_to(x - w, y) + cr.show_text(text) + cr.restore() + + +def _series_line(cr, values, x, y, w, h, lo, hi, color, width=1.5, + fill=False): + """Polyline for *values* (oldest left, newest right) in the + rect (x, y, w, h), scaled to [lo, hi].""" + if not values or w <= 0 or h <= 0 or hi <= lo: + return + n = len(values) + step = w / max(1, n - 1) if n > 1 else w + + def _px(i): + return x + i * step + + def _py(v): + return y + h - (v - lo) / (hi - lo) * h + + cr.save() + _rgb(cr, color) + cr.set_line_width(width) + cr.set_line_join(1) # round joins + cr.move_to(_px(0), _py(values[0])) + for i in range(1, n): + cr.line_to(_px(i), _py(values[i])) + cr.stroke() + if fill: + cr.line_to(_px(n - 1), y + h) + cr.line_to(_px(0), y + h) + cr.close_path() + _rgb(cr, color, 0.15) + cr.fill() + cr.restore() + + +def _stats(values): + """(current, min, max, avg) of a sample list, or Nones.""" + if not values: + return (None, None, None, None) + return (values[-1], min(values), max(values), + sum(values) / len(values)) + + +# --- the widget ---------------------------------------------------------------- + +_DEMO_PROCESSES = ( + # (pid, name, user, mem_kb, cpu) -- shown until refresh() reads /proc. + (1384034, "bash", "root", 3796, 16.2), + (1384035, "bash", "root", 3796, 16.1), + (1384040, "btop", "root", 7987, 0.7), + (1383999, "Xvfb", "root", 78000, 0.4), + (28000, "mysqld", "mysql", 96665, 0.8), + (24896, "dockerd", "root", 93184, 1.5), + (1109473, "node", "node", 145408, 0.1), + (15, "rcu_preempt", "root", 0, 0.4), +) + +_DEMO_SEGMENTS = ( + ("used", 45.0, _GREEN), + ("cached", 25.0, _YELLOW), + ("buffers", 10.0, _CYAN), + ("free", 20.0, (0.45, 0.45, 0.50)), +) + + +class MonitorWidget(Widget): + """One of the 15 X* monitor widgets (archetype Monitor). + + Draw dispatch is on ``kind`` (registry name), like StockWidget: + one class, kind-specific branches in _draw. Sample data is + runtime state (never saved in .fdj); with no data pushed yet a + widget draws deterministic demo data. + """ + + ARCHETYPE = "Monitor" + + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + # History series: None = demo data; a list of per-series + # float lists once push()/set_series() has been called. + self._series = None + # Per-core series for XCoreGrid (list per core, or None). + self._core_series = None + # Totals for XNetGraph (bytes, accumulated 1s per push). + self._total_down = 0.0 + self._total_up = 0.0 + # Peak-hold value for the bar / gauge kinds. + self._peak = 0.0 + # Stack segments for XStackBar: None = demo defaults. + self._segments = None + # Process rows for XProcessList: None = demo rows. + self._rows = None + self._prev_proc = None + self._prev_total = None + # /proc/stat snapshot for XCoreGrid.refresh(). + self._prev_cpu = None + # (load1, load5, load15, uptime_seconds) for XLoadBadge. + self._loads = None + # Monitor specs for XMonitorGrid: dicts with check/target/ + # label/status/detail. + self._monitors = [] + # Live status for XMonitorButton. + self._status = "unknown" + self._detail = "" + + # --- history data API -------------------------------------------------- + def _capacity(self): + return max(2, _prop_int(self, "window", 60)) + + def push(self, value, series=0): + """Append one sample to series *series* (default 0) and + return the new sample count. Starts a fresh series when no + own series was set yet (does NOT extend the demo series).""" + if self._series is None: + self._series = [] + while len(self._series) <= series: + self._series.append([]) + self._series[series].append(float(value)) + cap = self._capacity() + if len(self._series[series]) > cap: + del self._series[series][:-cap] + if float(value) > self._peak: + self._peak = float(value) + self._mark_dirty() + return len(self._series[series]) + + def push_series(self, index, value): + """Alias for push(value, series=index).""" + return self.push(value, series=index) + + def set_series(self, values, series=0): + """Replace series *series* with *values* (a list of floats).""" + if self._series is None: + self._series = [] + while len(self._series) <= series: + self._series.append([]) + cap = self._capacity() + self._series[series] = [float(v) for v in values][-cap:] + if self._series[series]: + self._peak = max(self._peak, max(self._series[series])) + self._mark_dirty() + + def get_series(self, series=0): + """The samples this widget currently plots (own series, else + the deterministic demo series). Returns a copy. An own + series that is empty (e.g. only another series was set) + also falls back to the demo series, so the widget never + plots a blank line for want of data.""" + if self._series is not None and series < len(self._series) \ + and self._series[series]: + return list(self._series[series]) + return list(self._plot_series()[series]) + + def series_count(self): + """Number of series this widget plots.""" + if self._series is not None: + return len(self._series) + return max(1, _prop_int(self, "series-count", 2)) + + def _demo_series_for(self, index): + """Deterministic demo data for series *index*.""" + n = self._capacity() + base = 55.0 - index * 12.0 + return _clamp(_demo_values(n, index, base, 28.0), 0.0, 100.0) + + def _plot_series(self): + """Series to plot: own data, else deterministic demo data. + An own series that is empty (only another series was set) + plots its demo data, so the widget never shows a blank line + for want of data.""" + if self._series is not None: + return [self._series[s] if self._series[s] + else self._demo_series_for(s) + for s in range(len(self._series))] + return [self._demo_series_for(s) + for s in range(self.series_count())] + + def _series_names(self): + raw = self.get_prop("series-names", "") + names = [n for n in raw.split("|") if n != ""] if raw else [] + count = self.series_count() + return [(names[i] if i < len(names) else "S%d" % (i + 1)) + for i in range(count)] + + # --- scalar value + peak ------------------------------------------------ + def set_value(self, value): + """Range value (clamped to minimum..maximum) that also + updates the peak-hold marker.""" + super().set_value(value) + try: + if float(value) > self._peak: + self._peak = float(value) + except (TypeError, ValueError): + pass + + def reset_peak(self): + """Clear the peak-hold marker (peak restarts at the current + value on the next draw).""" + self._peak = 0.0 + self._mark_dirty() + + def get_peak(self): + """Peak-hold value (max of the pushed/set values so far).""" + return self._peak + + # --- net graph API --------------------------------------------------------- + def push_net(self, down_bytes_per_s, up_bytes_per_s): + """Append one down/up sample pair (bytes/s) to XNetGraph and + accumulate the totals (one second per push).""" + self.push(float(down_bytes_per_s), series=0) + self.push(float(up_bytes_per_s), series=1) + self._total_down += float(down_bytes_per_s) + self._total_up += float(up_bytes_per_s) + + def get_totals(self): + """(total_down_bytes, total_up_bytes) accumulated by push_net.""" + return (self._total_down, self._total_up) + + def _net_series(self): + """(down, up) series: own data, else demo traffic.""" + if self._series is not None and len(self._series) >= 2: + return self._series[0], self._series[1] + n = self._capacity() + down = _demo_values(n, 0, 18000.0, 14000.0, period=53.0) + up = _demo_values(n, 1, 3000.0, 2400.0, period=31.0) + return ([max(0.0, v) for v in down], + [max(0.0, v) for v in up]) + + # --- core grid API --------------------------------------------------------- + def push_core(self, core, value): + """Append one sample for core *core* (XCoreGrid).""" + if self._core_series is None: + self._core_series = [] + while len(self._core_series) <= core: + self._core_series.append([]) + self._core_series[core].append(float(value)) + cap = self._capacity() + if len(self._core_series[core]) > cap: + del self._core_series[core][:-cap] + self._mark_dirty() + + def core_count(self): + """Number of cores: the ``cores`` prop, else the live CPU + count, else 8.""" + prop = _prop_int(self, "cores", 0) + if prop > 0: + return prop + return os.cpu_count() or 8 + + def _core_plot_series(self): + """Per-core series: own data, else deterministic demo data.""" + if self._core_series is not None: + return self._core_series + n = self._capacity() + return [_clamp(_demo_values(n, c, 42.0, 38.0, period=41.0 + c * 3), + 0.0, 100.0) + for c in range(self.core_count())] + + def refresh_cores(self): + """Refresh XCoreGrid from /proc/stat deltas (Linux). Returns + the per-core busy % list, or None when /proc is unavailable + (the widget keeps its demo data).""" + now = _read_cpu_times() + if now is None: + return None + prev = self._prev_cpu + self._prev_cpu = now + if prev is None: + return None + values = [] + for core in sorted(now): + if core not in prev: + continue + idle0, total0 = prev[core] + idle1, total1 = now[core] + d_total = total1 - total0 + d_idle = idle1 - idle0 + busy = 0.0 if d_total <= 0 else \ + 100.0 * (1.0 - d_idle / d_total) + values.append(max(0.0, min(100.0, busy))) + for i, value in enumerate(values): + self.push_core(i, value) + return values + + # --- process list API ------------------------------------------------------ + def set_rows(self, rows): + """Replace the XProcessList rows: dicts with pid, name, user, + mem_kb, cpu. Marks the widget dirty.""" + self._rows = [dict(r) for r in rows] + self._mark_dirty() + + def get_rows(self): + """The rows this widget currently shows (own rows, else the + deterministic demo rows). Returns a copy.""" + if self._rows is not None: + return [dict(r) for r in self._rows] + return [{"pid": pid, "name": name, "user": user, + "mem_kb": mem_kb, "cpu": cpu} + for pid, name, user, mem_kb, cpu in _DEMO_PROCESSES] + + def sort_by(self, column): + """Sort column for XProcessList: 'cpu', 'mem', 'pid' or + 'name' (also sets the sort-by prop).""" + labels = ("CPU", "Memory", "PID", "Name") + keys = ("cpu", "mem", "pid", "name") + if column in keys: + self.set_prop("sort-by", labels[keys.index(column)]) + + def _sorted_rows(self): + rows = self.get_rows() + col = _prop_int(self, "sort-by", 0) + key = {0: "cpu", 1: "mem_kb", 2: "pid", 3: "name"}.get(col, "cpu") + reverse = _prop_bool(self, "sort-desc", True) + return sorted(rows, key=lambda r: r[key], reverse=reverse) + + def refresh_processes(self): + """Refresh XProcessList from /proc (Linux). Returns the row + count, or None when /proc is unavailable (the widget keeps + its demo rows). CPU% needs two samples: the first refresh + reports 0.0 for every row.""" + rows = _read_processes() + total = _read_total_jiffies() + if rows is None or total is None: + return None + if self._prev_proc is not None and self._prev_total: + d_total = total - self._prev_total + prev = {r["pid"]: r["utime"] + r["stime"] + for r in self._prev_proc} + if d_total > 0: + for row in rows: + old = prev.get(row["pid"]) + if old is not None: + row["cpu"] = max( + 0.0, min(100.0, 100.0 + * (row["utime"] + row["stime"] + - old) / d_total)) + self._prev_proc = rows + self._prev_total = total + self.set_rows(rows) + return len(rows) + + # --- load badge API ---------------------------------------------------------- + def refresh_load(self): + """Refresh XLoadBadge from os.getloadavg() + /proc/uptime. + Returns (load1, load5, load15, uptime_s), or None when + unavailable (the widget keeps its demo values).""" + loads = _read_loads() + if loads is None: + return None + self._loads = loads + self._mark_dirty() + return loads + + def _load_values(self): + """(load1, load5, load15, uptime_s): live, else demo.""" + if self._loads is not None: + return self._loads + return (2.09, 1.85, 1.60, 2 * 86400 + 14 * 3600 + 21 * 60) + + # --- stack bar API ----------------------------------------------------------- + def set_segments(self, segments): + """Replace the XStackBar segments: (label, value, color) + triples; *color* is an (r, g, b) tuple or a color string. + Marks the widget dirty.""" + parsed = [] + for label, value, color in segments: + if isinstance(color, str): + color = parse_color(color, (0.5, 0.5, 0.5)) + parsed.append((str(label), float(value), tuple(color))) + self._segments = parsed + self._mark_dirty() + + def get_segments(self): + """(label, value, color) triples: the ``segments`` prop when + set (``label=value|...``), else the runtime segments, else + the demo defaults.""" + raw = self.get_prop("segments", "") + if raw: + out = [] + for i, part in enumerate(raw.split("|")): + if "=" not in part: + continue + label, value = part.split("=", 1) + try: + value = float(value) + except ValueError: + continue + out.append((label.strip(), value, + _SERIES_COLORS[i % len(_SERIES_COLORS)])) + if out: + return out + if self._segments is not None: + return list(self._segments) + return list(_DEMO_SEGMENTS) + + # --- monitor button / grid API ------------------------------------------------ + @property + def status(self): + """Live status of an XMonitorButton: up / degraded / down / + unknown (set by poll()).""" + return self._status + + @property + def detail(self): + """Detail text for the last poll (e.g. 'pid 1234', 'active', + 'open', 'not running').""" + return self._detail + + def poll(self): + """Run this XMonitorButton's check (process / unit / port, + from the check-type + target props) and store the status. + Returns the new status. Never raises: a failed check is + 'unknown'.""" + try: + check = _prop_int(self, "check-type", 0) + target = self.get_prop("target", "") + status, detail = check_monitor(check, target) + except Exception: # noqa: BLE001 - a failed check is unknown + status, detail = ("unknown", "error") + self._status = status + self._detail = detail + self._mark_dirty() + return status + + def update(self): + """Alias for poll(): the demo calls update() on its timer.""" + return self.poll() + + def add_monitor(self, check_type, target, label=None): + """Add one cell to an XMonitorGrid: check_type 0 = process, + 1 = systemd unit, 2 = TCP port; *target* is the process name, + unit name or port. Returns the cell index.""" + if isinstance(check_type, str): + check_type = {"process": 0, "unit": 1, "port": 2}.get( + check_type.lower(), 0) + self._monitors.append({ + "check": int(check_type), "target": str(target), + "label": label or str(target), + "status": "unknown", "detail": ""}) + self._mark_dirty() + return len(self._monitors) - 1 + + def set_monitors(self, monitors): + """Replace the XMonitorGrid cells: (check_type, target, + label) triples.""" + self._monitors = [] + for spec in monitors: + check_type, target = spec[0], spec[1] + label = spec[2] if len(spec) > 2 else None + self.add_monitor(check_type, target, label) + + def get_monitors(self): + """The grid cells (copies): dicts with check/target/label/ + status/detail.""" + return [dict(m) for m in self._monitors] + + def poll_all(self): + """Run every XMonitorGrid cell's check (one shared poll). + Returns the list of statuses.""" + statuses = [] + for monitor in self._monitors: + try: + status, detail = check_monitor( + monitor["check"], monitor["target"]) + except Exception: # noqa: BLE001 - failed check is unknown + status, detail = ("unknown", "error") + monitor["status"] = status + monitor["detail"] = detail + statuses.append(status) + self._mark_dirty() + return statuses + + def cell_at(self, px, py): + """Grid cell index at widget-relative (px, py), or None. + Used by the demo's click handler.""" + cells = self._cell_layout() + for i, (x, y, w, h) in enumerate(cells): + if x <= px <= x + w and y <= py <= y + h: + return i + return None + + def _cell_layout(self): + """(x, y, w, h) per grid cell inside the widget.""" + cols = 2 if self.width < 300 else 3 + count = max(1, len(self._monitors)) + rows = (count + cols - 1) // cols + pad, gap = 8, 6 + top = 26 + cw = (self.width - 2 * pad - (cols - 1) * gap) / cols + ch = (self.height - top - pad - (rows - 1) * gap) / rows + out = [] + for i in range(count): + r, c = divmod(i, cols) + out.append((pad + c * (cw + gap), top + r * (ch + gap), + cw, ch)) + return out + + # --- drawing -------------------------------------------------------- + def _draw(self, cr): + method = _MONITOR_DRAW.get(self.kind) + if method is not None: + getattr(self, method)(cr) + return + _panel(cr, self, self.text) + _wtext(cr, self, self.kind, self.width / 2, + self.height / 2 + 5, size=12, align="center", rgb=_DIM, + max_width=self.width - 12) + + def _title(self): + return self.get_prop("label", "") or self.kind + + def _single_series(self, base, amp, lo, hi): + """One series to plot (own series 0, else demo data).""" + if self._series is not None and self._series: + return self._series[0] + return _clamp(_demo_values(self._capacity(), 0, base, amp), + lo, hi) + + def _legend(self, cr, y, series, names, unit=""): + """Per-series legend lines: color chip + name + cur/min/max/ + avg. Returns the y below the last line.""" + for i, values in enumerate(series): + cur, mn, mx, avg = _stats(values) + color = _SERIES_COLORS[i % len(_SERIES_COLORS)] + _box(cr, 8, y - 8, 8, 8, color, color) + if cur is None: + line = "%s --" % names[i] + else: + line = "%s %.1f%s min %.1f max %.1f avg %.1f" % ( + names[i], cur, unit, mn, mx, avg) + _wtext(cr, self, line, 22, y, size=10, rgb=_TEXT, + max_width=self.width - 28) + y += 14 + return y + + def _draw_history_graph(self, cr): + top = _panel(cr, self, self._title()) + lo = _prop_float(self, "minimum", 0.0) + hi = _prop_float(self, "maximum", 100.0) + if hi <= lo: + hi = lo + 100.0 + series = self._plot_series() + names = self._series_names() + show_legend = _prop_bool(self, "show-legend", True) + legend_h = 14 * len(series) if show_legend else 0 + plot_x, plot_y = 34, top + 2 + plot_w = max(1, self.width - 40) + plot_h = max(1, self.height - plot_y - legend_h - 6) + _plot_frame(cr, plot_x, plot_y, plot_w, plot_h, lo, hi) + for i, values in enumerate(series): + _series_line(cr, values, plot_x, plot_y, plot_w, plot_h, + lo, hi, _SERIES_COLORS[i % len(_SERIES_COLORS)]) + if show_legend: + self._legend(cr, plot_y + plot_h + 12, series, names) + + def _draw_core_grid(self, cr): + top = _panel(cr, self, self._title()) + series = self._core_plot_series() + n = len(series) + cols = 4 if n > 4 else 2 + rows = (n + cols - 1) // cols + pad, gap = 6, 4 + cw = (self.width - 2 * pad - (cols - 1) * gap) / cols + ch = (self.height - top - pad - (rows - 1) * gap) / rows + for i, values in enumerate(series): + r, c = divmod(i, cols) + x = pad + c * (cw + gap) + y = top + r * (ch + gap) + _rounded_box(cr, x, y, cw, ch, _PANEL_INNER, _GRID, + radius=3) + color = _SERIES_COLORS[i % len(_SERIES_COLORS)] + cur = values[-1] if values else 0.0 + _wtext(cr, self, "C%d" % i, x + 6, y + 13, size=10, + rgb=_DIM, bold=True) + _wtext(cr, self, "%.0f%%" % cur, x + cw - 6, y + 13, + size=10, rgb=color, align="right", bold=True) + if ch > 26: + _series_line(cr, values, x + 3, y + 17, cw - 6, + ch - 20, 0.0, 100.0, color, width=1.0, + fill=True) + + def _draw_net_graph(self, cr): + top = _panel(cr, self, self._title()) + down, up = self._net_series() + peak = max(max(down) if down else 0.0, + max(up) if up else 0.0) + hi = max(1.0, peak * 1.15) + plot_x, plot_y = 34, top + 2 + plot_w = max(1, self.width - 40) + plot_h = max(1, self.height - plot_y - 34) + _plot_frame(cr, plot_x, plot_y, plot_w, plot_h, 0.0, hi) + _series_line(cr, down, plot_x, plot_y, plot_w, plot_h, 0.0, hi, + _GREEN) + _series_line(cr, up, plot_x, plot_y, plot_w, plot_h, 0.0, hi, + _CYAN) + legend_y = plot_y + plot_h + 12 + _box(cr, 8, legend_y - 8, 8, 8, _GREEN, _GREEN) + _wtext(cr, self, "Down %s Total %s" + % (_fmt_rate(down[-1] if down else 0.0), + _fmt_bytes(self._total_down)), + 22, legend_y, size=10, rgb=_TEXT, + max_width=self.width - 28) + _box(cr, 8, legend_y + 6, 8, 8, _CYAN, _CYAN) + _wtext(cr, self, "Up %s Total %s" + % (_fmt_rate(up[-1] if up else 0.0), + _fmt_bytes(self._total_up)), + 22, legend_y + 14, size=10, rgb=_TEXT, + max_width=self.width - 28) + + def _draw_temp_history(self, cr): + top = _panel(cr, self, self._title()) + threshold = _prop_float(self, "threshold", 80.0) + values = self._single_series(58.0, 24.0, 0.0, 120.0) + lo, hi = 0.0, max(100.0, threshold + 20.0) + cur = values[-1] if values else 0.0 + cur_rgb = _RED if cur > threshold else _TEXT + _wtext(cr, self, "%.1f C" % cur, self.width - 8, 15, size=14, + rgb=cur_rgb, align="right", bold=True) + plot_x, plot_y = 34, top + 2 + plot_w = max(1, self.width - 40) + plot_h = max(1, self.height - plot_y - 20) + _plot_frame(cr, plot_x, plot_y, plot_w, plot_h, lo, hi) + # Threshold line (dashed red) + label. + thr_y = plot_y + plot_h - (threshold - lo) / (hi - lo) * plot_h + cr.save() + _rgb(cr, _RED) + cr.set_line_width(1) + cr.set_dash([4, 3]) + cr.move_to(plot_x, thr_y) + cr.line_to(plot_x + plot_w, thr_y) + cr.stroke() + cr.restore() + _wtext(cr, self, "%.0f C" % threshold, plot_x + plot_w - 2, + thr_y - 3, size=9, rgb=_RED, align="right") + _series_line(cr, values, plot_x, plot_y, plot_w, plot_h, lo, hi, + _CYAN) + # Red overlay where the line runs over the threshold. + if len(values) > 1: + step = plot_w / (len(values) - 1) + + def _px(i): + return plot_x + i * step + + def _py(v): + return plot_y + plot_h - (v - lo) / (hi - lo) * plot_h + + cr.save() + _rgb(cr, _RED) + cr.set_line_width(2.0) + started = False + for i in range(len(values) - 1): + if values[i] > threshold or values[i + 1] > threshold: + if not started: + cr.move_to(_px(i), _py(values[i])) + started = True + cr.line_to(_px(i + 1), _py(values[i + 1])) + else: + started = False + cr.stroke() + cr.restore() + if values: + _wtext(cr, self, "min %.1f max %.1f avg %.1f" + % (min(values), max(values), + sum(values) / len(values)), + 8, plot_y + plot_h + 13, size=10, rgb=_DIM) + + def _gradient_bar(self, cr, x, y, w, h, frac, horizontal=True): + """Trough + green->yellow->red gradient fill to *frac*.""" + _rounded_box(cr, x, y, w, h, _PANEL_INNER, _PANEL_EDGE, + radius=3) + if frac <= 0 or w <= 2 or h <= 2: + return + if horizontal: + grad = _cairo.LinearGradient(x, y, x + w, y) + grad.add_color_stop_rgb(0, *_GREEN) + grad.add_color_stop_rgb(0.6, *_YELLOW) + grad.add_color_stop_rgb(1, *_RED) + fill_w = max(0, (w - 2) * frac) + cr.save() + _rounded_path(cr, x + 1, y + 1, fill_w, h - 2, 3) + cr.set_source(grad) + cr.fill() + cr.restore() + else: + grad = _cairo.LinearGradient(0, y + h, 0, y) + grad.add_color_stop_rgb(0, *_GREEN) + grad.add_color_stop_rgb(0.6, *_YELLOW) + grad.add_color_stop_rgb(1, *_RED) + fill_h = max(0, (h - 2) * frac) + cr.save() + _rounded_path(cr, x + 1, y + h - 1 - fill_h, w - 2, fill_h, + 3) + cr.set_source(grad) + cr.fill() + cr.restore() + + def _draw_usage_bar(self, cr): + frac = _range_frac(self) + self._gradient_bar(cr, 0, 0, self.width, self.height, frac) + label = self.get_prop("label", "") or self.kind + value = _prop_float(self, "value", 0.0) + _wtext(cr, self, label, 8, self.height / 2 + 5, size=12, + rgb=_WHITE, bold=True, max_width=self.width / 2) + _wtext(cr, self, "%.0f%%" % value, self.width - 8, + self.height / 2 + 5, size=12, rgb=_WHITE, align="right", + bold=True) + + def _draw_stack_bar(self, cr): + segments = self.get_segments() + total = sum(v for _label, v, _c in segments) or 1.0 + bar_y, bar_h = 4, 16 + x = 0.0 + for label, value, color in segments: + seg_w = self.width * value / total + if seg_w <= 0: + continue + _box(cr, x, bar_y, max(0, seg_w - 1), bar_h, color, color) + x += seg_w + # Legend: color chip + "label 45%" flowing left to right, + # wrapping to a second row when the width runs out. + lx, ly = 6, bar_y + bar_h + 15 + line1 = True + for label, value, color in segments: + text = "%s %.0f%%" % (label, 100.0 * value / total) + tw = _text_width(cr, self, text, size=10) + 16 + if lx + tw > self.width - 4 and lx > 6: + lx = 6 + ly += 14 + line1 = False + _box(cr, lx, ly - 8, 8, 8, color, color) + _wtext(cr, self, text, lx + 12, ly, size=10, rgb=_TEXT) + lx += tw + if line1: + _wtext(cr, self, "total %s" % _fmt_bytes(total), + self.width - 6, bar_y + bar_h + 15, size=10, + rgb=_DIM, align="right") + + def _draw_vertical_bar(self, cr): + frac = _range_frac(self) + value = _prop_float(self, "value", 0.0) + # Peak-hold: the marker tracks the largest value seen; the + # draw stores it because values can arrive via set_prop + # (Inspector) as well as push()/set_value(). _peak is runtime + # state only, never saved in .fdj. + peak = max(self._peak, value) + self._peak = peak + lo = _prop_float(self, "minimum", 0.0) + hi = _prop_float(self, "maximum", 100.0) + _panel(cr, self) + bar_x, bar_w = 26, self.width - 34 + bar_y, bar_h = 10, self.height - 34 + self._gradient_bar(cr, bar_x, bar_y, bar_w, bar_h, frac, + horizontal=False) + # Scale labels + ticks on the left. + for f in (0.0, 0.25, 0.5, 0.75, 1.0): + gy = bar_y + bar_h - f * bar_h + _ylabel(cr, "%.0f" % (lo + f * (hi - lo)), bar_x - 4, gy + 3) + cr.save() + _rgb(cr, _GRID) + cr.set_line_width(1) + cr.move_to(bar_x - 2, gy) + cr.line_to(bar_x, gy) + cr.stroke() + cr.restore() + # Peak-hold marker. + if peak > lo: + py = bar_y + bar_h - (peak - lo) / (hi - lo) * bar_h \ + if hi > lo else bar_y + cr.save() + _rgb(cr, _WHITE) + cr.set_line_width(2) + cr.move_to(bar_x - 2, py) + cr.line_to(bar_x + bar_w + 2, py) + cr.stroke() + cr.restore() + _wtext(cr, self, "%.0f%%" % value, self.width / 2, + self.height - 8, size=11, rgb=_TEXT, align="center", + bold=True) + + def _draw_tachometer(self, cr): + top = _panel(cr, self, self._title()) + lo = _prop_float(self, "minimum", 0.0) + hi = _prop_float(self, "maximum", 8000.0) + if hi <= lo: + hi = lo + 100.0 + value = _prop_float(self, "value", 0.0) + frac = max(0.0, min(1.0, (value - lo) / (hi - lo))) + redline = _prop_float(self, "redline", 0.8 * hi) + red_frac = max(0.0, min(1.0, (redline - lo) / (hi - lo))) + peak = max(self._peak, value) + # Draw-time peak store: see _draw_vertical_bar. + self._peak = peak + peak_frac = max(0.0, min(1.0, (peak - lo) / (hi - lo))) + cx = self.width / 2 + cy = top + (self.height - top) * 0.52 + r = min(self.width / 2 - 12, (self.height - top) * 0.42) + start = 0.75 * math.pi + sweep = 1.5 * math.pi + + def _angle(f): + return start + f * sweep + + # Track, redline zone, value arc. + cr.save() + cr.set_line_width(10) + cr.set_line_cap(1) + _rgb(cr, (0.25, 0.25, 0.28)) + cr.arc(cx, cy, r, start, start + sweep) + cr.stroke() + _rgb(cr, _RED) + cr.arc(cx, cy, r, _angle(red_frac), start + sweep) + cr.stroke() + _rgb(cr, _CYAN) + cr.arc(cx, cy, r, start, _angle(frac)) + cr.stroke() + cr.restore() + # Ticks + numbers. + cr.save() + for i in range(11): + f = i / 10.0 + ang = _angle(f) + major = i % 2 == 0 + r0 = r - (16 if major else 12) + cr.save() + _rgb(cr, _DIM if not major else _TEXT) + cr.set_line_width(1.5 if major else 1.0) + cr.move_to(cx + r0 * math.cos(ang), cy + r0 * math.sin(ang)) + cr.line_to(cx + (r - 8) * math.cos(ang), + cy + (r - 8) * math.sin(ang)) + cr.stroke() + cr.restore() + if major: + label = "%.0f" % (lo + f * (hi - lo)) + lx = cx + (r - 26) * math.cos(ang) + ly = cy + (r - 26) * math.sin(ang) + 3 + _wtext(cr, self, label, lx, ly, size=9, rgb=_TEXT, + align="center") + # Peak-hold tick. + cr.save() + _rgb(cr, _WHITE) + cr.set_line_width(3) + pang = _angle(peak_frac) + cr.move_to(cx + (r - 18) * math.cos(pang), + cy + (r - 18) * math.sin(pang)) + cr.line_to(cx + (r - 6) * math.cos(pang), + cy + (r - 6) * math.sin(pang)) + cr.stroke() + cr.restore() + # Needle + hub. + nang = _angle(frac) + cr.save() + _rgb(cr, _WHITE) + cr.set_line_width(2.5) + cr.move_to(cx, cy) + cr.line_to(cx + (r - 18) * math.cos(nang), + cy + (r - 18) * math.sin(nang)) + cr.stroke() + _rgb(cr, (0.6, 0.6, 0.65)) + cr.arc(cx, cy, 6, 0, 2 * math.pi) + cr.fill() + cr.restore() + # Digital readout. + unit = self.get_prop("unit", "") + _wtext(cr, self, "%.0f" % value, cx, cy + r * 0.62, size=20, + rgb=_WHITE, align="center", bold=True) + if unit: + _wtext(cr, self, unit, cx, cy + r * 0.62 + 14, size=10, + rgb=_DIM, align="center") + + def _draw_arc_gauge(self, cr): + top = _panel(cr, self, self._title()) + frac = _range_frac(self) + value = _prop_float(self, "value", 0.0) + cx = self.width / 2 + cy = self.height - 14 + r = min(self.width / 2 - 12, self.height - top - 22) + if r <= 0: + return + zones = ((0.0, 0.6, _GREEN), (0.6, 0.8, _YELLOW), + (0.8, 1.0, _RED)) + cr.save() + cr.set_line_width(12) + cr.set_line_cap(0) + _rgb(cr, (0.25, 0.25, 0.28)) + cr.arc(cx, cy, r, math.pi, 2 * math.pi) + cr.stroke() + for f0, f1, color in zones: + _rgb(cr, color) + cr.arc(cx, cy, r, math.pi + f0 * math.pi, + math.pi + f1 * math.pi) + cr.stroke() + _rgb(cr, _WHITE) + cr.arc(cx, cy, r, math.pi, math.pi + frac * math.pi) + cr.stroke() + cr.restore() + _wtext(cr, self, "%.0f%%" % value, cx, cy - r * 0.45, size=22, + rgb=_WHITE, align="center", bold=True) + label = self.get_prop("unit", "") or "usage" + _wtext(cr, self, label, cx, cy - r * 0.45 + 16, size=10, + rgb=_DIM, align="center") + + def _draw_donut_gauge(self, cr): + top = _panel(cr, self, self._title()) + frac = _range_frac(self) + value = _prop_float(self, "value", 0.0) + cx = self.width / 2 + cy = top + (self.height - top) / 2 + r = min(self.width, self.height - top) / 2 - 12 + if r <= 0: + return + cr.save() + cr.set_line_width(14) + cr.set_line_cap(1) + _rgb(cr, (0.25, 0.25, 0.28)) + cr.arc(cx, cy, r, 0, 2 * math.pi) + cr.stroke() + _rgb(cr, _GREEN) + cr.arc(cx, cy, r, -math.pi / 2, -math.pi / 2 + frac * 2 * math.pi) + cr.stroke() + cr.restore() + _wtext(cr, self, "%.0f%%" % value, cx, cy + 7, size=20, + rgb=_WHITE, align="center", bold=True) + label = self.get_prop("unit", "") or self.kind + _wtext(cr, self, label, cx, cy + 24, size=10, rgb=_DIM, + align="center", max_width=self.width - 16) + + def _draw_process_list(self, cr): + top = _panel(cr, self, self._title()) + rows = self._sorted_rows() + cols = ((6, 52, "PID", "left"), (62, 130, "Program", "left"), + (196, 44, "User", "left"), (244, 48, "Mem", "right"), + (296, 56, "CPU%", "right")) + header_y = top + 13 + for x, _w, name, align in cols: + if align == "right": + _wtext(cr, self, name, x + _w, header_y, size=10, + rgb=_DIM, align="right", bold=True) + else: + _wtext(cr, self, name, x, header_y, size=10, + rgb=_DIM, bold=True) + row_h = 18 + y0 = top + 18 + visible = max(0, (self.height - y0) // row_h) + for i, row in enumerate(rows[:visible]): + y = y0 + i * row_h + cpu = row["cpu"] + if cpu >= 50: + _rgb(cr, _RED, 0.18) + cr.rectangle(0, y, self.width, row_h) + cr.fill() + elif cpu >= 20: + _rgb(cr, _AMBER, 0.12) + cr.rectangle(0, y, self.width, row_h) + cr.fill() + _wtext(cr, self, str(row["pid"]), 6, y + 13, size=10, + rgb=_TEXT) + _wtext(cr, self, row["name"], 62, y + 13, size=10, + rgb=_TEXT, + max_width=128) + _wtext(cr, self, row["user"], 196, y + 13, size=10, + rgb=_TEXT, max_width=44) + _wtext(cr, self, _fmt_bytes(row["mem_kb"] * 1024), 292, + y + 13, size=10, rgb=_TEXT, align="right") + # In-cell CPU% bar behind the number. + bar_x, bar_w = 300, 52 + _box(cr, bar_x, y + 3, bar_w, 12, (0.20, 0.20, 0.23), + (0.20, 0.20, 0.23)) + fill = max(0, bar_w * min(1.0, cpu / 100.0)) + if fill > 0: + color = _GREEN if cpu < 50 else \ + _AMBER if cpu < 80 else _RED + _box(cr, bar_x, y + 3, fill, 12, color, color) + _wtext(cr, self, "%.1f" % cpu, bar_x + bar_w - 3, y + 13, + size=10, rgb=_WHITE, align="right", bold=True) + + def _draw_load_badge(self, cr): + _panel(cr, self) + load1, load5, load15, uptime = self._load_values() + ncores = os.cpu_count() or 1 + _wtext(cr, self, "Load", 8, 24, size=13, rgb=_DIM, bold=True) + x = 52 + for load in (load1, load5, load15): + per_core = load / ncores + color = _GREEN if per_core < 0.7 else \ + _AMBER if per_core < 1.0 else _RED + text = "%.2f" % load + _wtext(cr, self, text, x, 24, size=13, rgb=color, bold=True) + x += _text_width(cr, self, text, size=13, bold=True) + 12 + _wtext(cr, self, "%s %d cores" % (_fmt_uptime(uptime), ncores), + 8, 46, size=11, rgb=_TEXT) + + def _draw_monitor_button(self, cr): + status = self._status + color = _STATUS_COLORS[status] + # Glow: soft outer rings in the status color, then the body. + cr.save() + for inset, alpha in ((3, 0.15), (2, 0.30)): + _rounded_path(cr, inset + 0.5, inset + 0.5, + self.width - 2 * inset - 1, + self.height - 2 * inset - 1, 6) + _rgb(cr, color, alpha) + cr.set_line_width(2) + cr.stroke() + cr.restore() + _rounded_box(cr, 0, 0, self.width, self.height, _PANEL_INNER, + color, line_width=1.5, radius=6) + _rgb(cr, color) + cr.arc(18, self.height / 2, 7, 0, 2 * math.pi) + cr.fill() + if status == "up": + _rgb(cr, _WHITE) + cr.arc(18, self.height / 2, 2.5, 0, 2 * math.pi) + cr.fill() + label = self.get_prop("label", "") or self.get_prop("target", "") \ + or self.kind + status_text = _STATUS_LABELS[status] + sw = _text_width(cr, self, status_text, size=12, bold=True) + mid_y = self.height / 2 + if self._detail: + _wtext(cr, self, label, 32, mid_y - 1, size=13, rgb=_WHITE, + bold=True, + max_width=self.width - 40 - sw - 8) + _wtext(cr, self, self._detail, 32, mid_y + 14, size=10, + rgb=_DIM, + max_width=self.width - 40 - sw - 8) + else: + _wtext(cr, self, label, 32, mid_y + 5, size=13, rgb=_WHITE, + bold=True, + max_width=self.width - 40 - sw - 8) + _wtext(cr, self, status_text, self.width - 8, mid_y + 5, + size=12, rgb=color, align="right", bold=True) + + def _draw_monitor_grid(self, cr): + top = _panel(cr, self, self._title()) + if not self._monitors: + _wtext(cr, self, "No monitors -- add_monitor()", + self.width / 2, self.height / 2 + 5, size=11, + rgb=_DIM, align="center") + return + for i, (x, y, w, h) in enumerate(self._cell_layout()): + if i >= len(self._monitors): + break + monitor = self._monitors[i] + color = _STATUS_COLORS[monitor["status"]] + _rounded_box(cr, x, y, w, h, _PANEL_INNER, color, + line_width=1.0, radius=4) + _rgb(cr, color) + cr.arc(x + 12, y + h / 2, 5, 0, 2 * math.pi) + cr.fill() + label = monitor["label"] + _wtext(cr, self, label, x + 24, y + h / 2 - 1, size=11, + rgb=_WHITE, bold=True, max_width=w - 30) + status_text = "%s - %s" % ( + _STATUS_LABELS[monitor["status"]], monitor["detail"]) + _wtext(cr, self, status_text, x + 24, y + h / 2 + 13, + size=9, rgb=_DIM, max_width=w - 30) + + def _draw_sys_box(self, cr): + top = _panel(cr, self, self._title()) + value = _prop_float(self, "value", 0.0) + unit = self.get_prop("unit", "%") + lo = _prop_float(self, "minimum", 0.0) + hi = _prop_float(self, "maximum", 100.0) + if hi <= lo: + hi = lo + 100.0 + _wtext(cr, self, "%.0f" % value, 8, top + 26, size=26, + rgb=_WHITE, bold=True) + _wtext(cr, self, unit, 8 + _text_width(cr, self, "%.0f" % value, + size=26, bold=True) + 6, + top + 26, size=12, rgb=_DIM) + values = self._single_series(55.0, 28.0, lo, hi) + graph_y = top + 34 + graph_h = max(1, self.height - graph_y - 26) + _plot_frame(cr, 8, graph_y, self.width - 16, graph_h, lo, hi, + labels=False) + _series_line(cr, values, 8, graph_y, self.width - 16, graph_h, + lo, hi, _GREEN) + frac = max(0.0, min(1.0, (value - lo) / (hi - lo))) + self._gradient_bar(cr, 8, self.height - 20, self.width - 16, + 12, frac) + _wtext(cr, self, "%.0f%%" % (frac * 100.0), self.width - 12, + self.height - 10, size=9, rgb=_WHITE, align="right", + bold=True) + + +_MONITOR_DRAW = { + "XHistoryGraph": "_draw_history_graph", + "XCoreGrid": "_draw_core_grid", + "XNetGraph": "_draw_net_graph", + "XTempHistory": "_draw_temp_history", + "XUsageBar": "_draw_usage_bar", + "XStackBar": "_draw_stack_bar", + "XVerticalBar": "_draw_vertical_bar", + "XTachometer": "_draw_tachometer", + "XArcGauge": "_draw_arc_gauge", + "XDonutGauge": "_draw_donut_gauge", + "XProcessList": "_draw_process_list", + "XLoadBadge": "_draw_load_badge", + "XMonitorButton": "_draw_monitor_button", + "XMonitorGrid": "_draw_monitor_grid", + "XSysBox": "_draw_sys_box", +} + +MONITOR_KINDS = tuple(_MONITOR_DRAW) diff --git a/lightgui/xframe/palette.py b/lightgui/xframe/palette.py index 948c6f1..baf7430 100644 --- a/lightgui/xframe/palette.py +++ b/lightgui/xframe/palette.py @@ -1,4 +1,4 @@ -"""Palette data: all 547 XFrame widgets in their 11 section groups. +"""Palette data: all 562 XFrame widgets in their 11 section groups. GENERATED -- do not edit by hand. Derived on the server by parsing /opt/lightgui_rust/crates/xframe-widgets/src/registry_gen.rs @@ -8,14 +8,20 @@ Cross-checked against /opt/lightgui/src/xframe_palette.h: the sources, so this table is the C palette as well as the Rust one. NOTE on the count: the Phase 1 brief said "583 entries (547 widgets)". -That 583 is the total in /opt/lightgui_rust/data/palette.json: +That 583 was the total in /opt/lightgui_rust/data/palette.json: 547 XFrame widgets plus 36 legacy "lightgui" type keys (the old C model.h kTypes table: Button, Label, Entry, ... Plot). The legacy 36 are NOT XFrame widgets -- they are the pre-XFrame model types, and the C/Rust .fdj loaders drop non-XFrame types on load. -The placeable palette itself is the 547 XFrame entries below +The placeable palette itself is the 562 XFrame entries below (the Rust designer main.rs calls it "the XFrame-only 547-entry -palette", and the C header says kXFramePaletteCount = 547). +palette", and the C header says kXFramePaletteCount = 547 -- +both predate the 15 hand-added X* monitor entries, 547-561). +Entries 547-561 are the hand-added X* monitor family +(btop-style live widgets, Dec 2026): they have no C/Rust +registry counterpart yet, so they are NOT regenerated from +registry_gen.rs -- keep them in sync with +lightgui/xframe/monitor.py by hand. The 36 legacy keys are recorded separately as LEGACY_TYPES at the end of this module, for reference only. """ @@ -589,6 +595,21 @@ PALETTE = ( PaletteEntry(544, 'TValueListEditor', 'T', 'Text & Entry', 4, 180, 30, 'ListSel', 'ValueListEditor'), PaletteEntry(545, 'XGraph', 'X', 'Misc / X', 8, 320, 200, 'Graph', 'XGraph'), PaletteEntry(546, 'XSpreadsheet', 'X', 'Misc / X', 8, 320, 200, 'Spreadsheet', 'XSpreadsheet'), + PaletteEntry(547, 'XHistoryGraph', 'X', 'Misc / X', 8, 320, 200, 'Monitor', 'XHistoryGraph'), + PaletteEntry(548, 'XCoreGrid', 'X', 'Misc / X', 8, 320, 200, 'Monitor', 'XCoreGrid'), + PaletteEntry(549, 'XNetGraph', 'X', 'Misc / X', 8, 320, 200, 'Monitor', 'XNetGraph'), + PaletteEntry(550, 'XTempHistory', 'X', 'Misc / X', 8, 320, 200, 'Monitor', 'XTempHistory'), + PaletteEntry(551, 'XUsageBar', 'X', 'Misc / X', 8, 320, 36, 'Monitor', 'XUsageBar'), + PaletteEntry(552, 'XStackBar', 'X', 'Misc / X', 8, 320, 48, 'Monitor', 'XStackBar'), + PaletteEntry(553, 'XVerticalBar', 'X', 'Misc / X', 8, 60, 200, 'Monitor', 'XVerticalBar'), + PaletteEntry(554, 'XTachometer', 'X', 'Misc / X', 8, 220, 180, 'Monitor', 'XTachometer'), + PaletteEntry(555, 'XArcGauge', 'X', 'Misc / X', 8, 200, 140, 'Monitor', 'XArcGauge'), + PaletteEntry(556, 'XDonutGauge', 'X', 'Misc / X', 8, 160, 160, 'Monitor', 'XDonutGauge'), + PaletteEntry(557, 'XProcessList', 'X', 'Misc / X', 8, 360, 220, 'Monitor', 'XProcessList'), + PaletteEntry(558, 'XLoadBadge', 'X', 'Misc / X', 8, 220, 60, 'Monitor', 'XLoadBadge'), + PaletteEntry(559, 'XMonitorButton', 'X', 'Misc / X', 8, 200, 48, 'Monitor', 'XMonitorButton'), + PaletteEntry(560, 'XMonitorGrid', 'X', 'Misc / X', 8, 320, 200, 'Monitor', 'XMonitorGrid'), + PaletteEntry(561, 'XSysBox', 'X', 'Misc / X', 8, 320, 200, 'Monitor', 'XSysBox'), ) BY_NAME = {e.name: e for e in PALETTE} diff --git a/tests/test_inspector.py b/tests/test_inspector.py index 7ed6d40..028c2f8 100644 --- a/tests/test_inspector.py +++ b/tests/test_inspector.py @@ -41,7 +41,7 @@ def _project_with(*kinds): class RowSpecTests(unittest.TestCase): def test_every_kind_produces_nonempty_grid(self): - self.assertEqual(len(palette.PALETTE), 547) + self.assertEqual(len(palette.PALETTE), 562) for entry in palette.PALETTE: specs = row_specs_for(entry.name) prop_specs = [s for s in specs if s[0] == "prop"] diff --git a/tests/test_monitor.py b/tests/test_monitor.py new file mode 100644 index 0000000..4ba2756 --- /dev/null +++ b/tests/test_monitor.py @@ -0,0 +1,413 @@ +"""Tests for the X* monitor family (15 widgets, registry 547-561). + +Display-free: widgets draw to offscreen Cairo surfaces (the +test_draw.py pattern). Live /proc checks run only where /proc +exists; where a check can legitimately return None the test +accepts it and checks the demo fallback instead. +""" + +import socket +import unittest + +import cairo + +from lightgui import props +from lightgui.xframe import core +from lightgui.xframe import monitor as monitor_mod +from lightgui.xframe import palette + +MONITOR_KINDS = ( + "XHistoryGraph", "XCoreGrid", "XNetGraph", "XTempHistory", + "XUsageBar", "XStackBar", "XVerticalBar", "XTachometer", + "XArcGauge", "XDonutGauge", "XProcessList", "XLoadBadge", + "XMonitorButton", "XMonitorGrid", "XSysBox", +) + +# (kind, default_w, default_h) -- must match palette.py. +MONITOR_SIZES = { + "XHistoryGraph": (320, 200), + "XCoreGrid": (320, 200), + "XNetGraph": (320, 200), + "XTempHistory": (320, 200), + "XUsageBar": (320, 36), + "XStackBar": (320, 48), + "XVerticalBar": (60, 200), + "XTachometer": (220, 180), + "XArcGauge": (200, 140), + "XDonutGauge": (160, 160), + "XProcessList": (360, 220), + "XLoadBadge": (220, 60), + "XMonitorButton": (200, 48), + "XMonitorGrid": (320, 200), + "XSysBox": (320, 200), +} + + +def _draw(widget): + """Draw *widget* on a fresh white surface; return the surface.""" + surface = cairo.ImageSurface( + cairo.FORMAT_ARGB32, widget.width + 4, widget.height + 4) + 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 + + +def _closed_port(): + """A localhost TCP port nothing is listening on right now.""" + sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + sock.bind(("127.0.0.1", 0)) + port = sock.getsockname()[1] + sock.close() + return port + + +class RegistryTests(unittest.TestCase): + def test_15_monitor_kinds_in_palette(self): + for kind in MONITOR_KINDS: + entry = palette.find(kind) + self.assertIsNotNone(entry, kind) + self.assertEqual(entry.family, "X") + self.assertEqual(entry.section, "Misc / X") + self.assertEqual(entry.archetype, "Monitor") + self.assertEqual(entry.kind, kind) + self.assertEqual((entry.default_w, entry.default_h), + MONITOR_SIZES[kind], kind) + + def test_indices_are_547_to_561(self): + indices = sorted(palette.find(k).index for k in MONITOR_KINDS) + self.assertEqual(indices, list(range(547, 562))) + + def test_lookup_returns_monitor_widget(self): + for kind in MONITOR_KINDS: + cls = core.lookup(kind) + self.assertIs(cls, monitor_mod.MonitorWidget, kind) + self.assertEqual(cls.ARCHETYPE, "Monitor") + widget = core.create(kind, kind + "_001") + self.assertIsNotNone(widget, kind) + self.assertEqual((widget.width, widget.height), + MONITOR_SIZES[kind], kind) + + def test_monitor_archetype_in_archetype_classes(self): + self.assertIn("Monitor", core.ARCHETYPE_CLASSES) + self.assertIs(core.ARCHETYPE_CLASSES["Monitor"], + monitor_mod.MonitorWidget) + + +class DrawTests(unittest.TestCase): + def test_every_monitor_draws_without_crashing(self): + for kind in MONITOR_KINDS: + widget = core.create(kind, kind + "_001") + try: + _draw(widget) + except Exception as exc: # noqa: BLE001 - report the kind + self.fail("%s draw crashed: %r" % (kind, exc)) + + def test_every_monitor_draws_something(self): + for kind in MONITOR_KINDS: + widget = core.create(kind, kind + "_001") + surface = _draw(widget) + self.assertGreater(_non_white_pixels(surface), 0, kind) + + def test_every_monitor_draws_with_live_data(self): + # Exercise the push paths in draw, not just the demo data. + graph = core.create("XHistoryGraph", "XHistoryGraph_001") + for i in range(70): + graph.push(50 + 20 * (i % 2), series=i % 3) + _draw(graph) + cores = core.create("XCoreGrid", "XCoreGrid_001") + for c in range(8): + for i in range(10): + cores.push_core(c, 10 + c * 5) + _draw(cores) + net = core.create("XNetGraph", "XNetGraph_001") + net.push_net(18000, 3000) + _draw(net) + temp = core.create("XTempHistory", "XTempHistory_001") + temp.push(90.0) # over the 80C threshold + _draw(temp) + stack = core.create("XStackBar", "XStackBar_001") + stack.set_segments([("used", 60, "red"), ("free", 40, "green")]) + _draw(stack) + procs = core.create("XProcessList", "XProcessList_001") + procs.set_rows([{"pid": 1, "name": "init", "user": "root", + "mem_kb": 1024, "cpu": 75.0}]) + _draw(procs) + grid = core.create("XMonitorGrid", "XMonitorGrid_001") + grid.add_monitor("process", "python3", "Python") + _draw(grid) + + +class HistoryDataTests(unittest.TestCase): + def test_push_starts_fresh_series(self): + # Demo data is shown until the first push; push() does NOT + # extend the demo series (IndicatorWidget convention). + graph = core.create("XHistoryGraph", "XHistoryGraph_001") + demo = graph.get_series(0) + self.assertEqual(len(demo), 60) + graph.push(42.0) + self.assertEqual(graph.get_series(0), [42.0]) + + def test_push_trims_to_window(self): + graph = core.create("XHistoryGraph", "XHistoryGraph_001") + graph.set_prop("window", 5) + for i in range(8): + graph.push(float(i)) + self.assertEqual(graph.get_series(0), [3.0, 4.0, 5.0, 6.0, 7.0]) + + def test_set_series_replaces(self): + graph = core.create("XHistoryGraph", "XHistoryGraph_001") + graph.set_series([1.0, 2.0, 3.0], series=1) + self.assertEqual(graph.get_series(1), [1.0, 2.0, 3.0]) + self.assertEqual(len(graph.get_series(0)), 60) # demo + + def test_push_net_accumulates_totals(self): + net = core.create("XNetGraph", "XNetGraph_001") + net.push_net(1000, 500) + net.push_net(2000, 500) + self.assertEqual(net.get_totals(), (3000.0, 1000.0)) + self.assertEqual(net.get_series(0), [1000.0, 2000.0]) + + def test_series_names_default(self): + graph = core.create("XHistoryGraph", "XHistoryGraph_001") + self.assertEqual(graph._series_names(), ["S1", "S2"]) + graph.set_prop("series-names", "CPU|MEM") + self.assertEqual(graph._series_names(), ["CPU", "MEM"]) + + +class PeakTests(unittest.TestCase): + def test_set_value_tracks_peak(self): + bar = core.create("XVerticalBar", "XVerticalBar_001") + bar.set_value(65) + bar.set_value(82) + bar.set_value(40) + self.assertEqual(bar.get_peak(), 82.0) + bar.reset_peak() + self.assertEqual(bar.get_peak(), 0.0) + + def test_push_tracks_peak(self): + graph = core.create("XHistoryGraph", "XHistoryGraph_001") + graph.push(30) + graph.push(91) + self.assertEqual(graph.get_peak(), 91.0) + + +class StackBarTests(unittest.TestCase): + def test_set_segments(self): + bar = core.create("XStackBar", "XStackBar_001") + bar.set_segments([("used", 60, (1.0, 0.0, 0.0)), + ("free", 40, "green")]) + segments = bar.get_segments() + self.assertEqual(segments[0][:2], ("used", 60.0)) + self.assertEqual(segments[1][0], "free") + + def test_segments_prop_parses(self): + bar = core.create("XStackBar", "XStackBar_001") + bar.set_prop("segments", "used=45|cached=25|free=30") + segments = bar.get_segments() + self.assertEqual([s[0] for s in segments], + ["used", "cached", "free"]) + self.assertEqual([s[1] for s in segments], [45.0, 25.0, 30.0]) + + def test_demo_segments_when_empty(self): + bar = core.create("XStackBar", "XStackBar_001") + self.assertEqual([s[0] for s in bar.get_segments()], + ["used", "cached", "buffers", "free"]) + + +class ProcessListTests(unittest.TestCase): + def test_demo_rows_present(self): + procs = core.create("XProcessList", "XProcessList_001") + rows = procs.get_rows() + self.assertGreater(len(rows), 0) + self.assertIn("pid", rows[0]) + self.assertIn("cpu", rows[0]) + + def test_sort_by_cpu_desc_default(self): + procs = core.create("XProcessList", "XProcessList_001") + procs.set_rows([ + {"pid": 1, "name": "a", "user": "root", "mem_kb": 10, + "cpu": 5.0}, + {"pid": 2, "name": "b", "user": "root", "mem_kb": 20, + "cpu": 50.0}, + {"pid": 3, "name": "c", "user": "root", "mem_kb": 30, + "cpu": 1.0}, + ]) + self.assertEqual([r["pid"] for r in procs._sorted_rows()], + [2, 1, 3]) + procs.sort_by("mem") + self.assertEqual([r["pid"] for r in procs._sorted_rows()], + [3, 2, 1]) + + def test_refresh_reads_proc_when_available(self): + procs = core.create("XProcessList", "XProcessList_001") + count = procs.refresh_processes() + if count is None: + self.skipTest("/proc unavailable here") + self.assertGreater(count, 0) + rows = procs.get_rows() + self.assertGreater(len(rows), 0) + # Second refresh computes real CPU% values. + procs.refresh_processes() + self.assertTrue(all(0.0 <= r["cpu"] <= 100.0 + for r in procs.get_rows())) + + +class CoreGridTests(unittest.TestCase): + def test_core_count_positive(self): + grid = core.create("XCoreGrid", "XCoreGrid_001") + self.assertGreater(grid.core_count(), 0) + grid.set_prop("cores", 4) + self.assertEqual(grid.core_count(), 4) + + def test_refresh_cores_two_samples(self): + grid = core.create("XCoreGrid", "XCoreGrid_001") + first = grid.refresh_cores() + if first is None and grid._prev_cpu is None: + self.skipTest("/proc/stat unavailable here") + self.assertIsNone(first) # first sample has no delta yet + values = grid.refresh_cores() + self.assertIsNotNone(values) + self.assertEqual(len(values), grid.core_count()) + self.assertTrue(all(0.0 <= v <= 100.0 for v in values)) + + +class LoadBadgeTests(unittest.TestCase): + def test_load_values_always_4_tuple(self): + badge = core.create("XLoadBadge", "XLoadBadge_001") + values = badge._load_values() + self.assertEqual(len(values), 4) + self.assertTrue(all(v >= 0 for v in values[:3])) + + def test_refresh_load(self): + badge = core.create("XLoadBadge", "XLoadBadge_001") + values = badge.refresh_load() + if values is None: + self.skipTest("getloadavg unavailable here") + self.assertEqual(len(values), 4) + + +class MonitorButtonTests(unittest.TestCase): + def test_process_check_finds_python3(self): + button = core.create("XMonitorButton", "XMonitorButton_001") + button.set_prop("check-type", "Process") + button.set_prop("target", "python3") + button.set_prop("label", "Python") + # The test runner itself is python3, so this must be up. + self.assertEqual(button.poll(), "up") + self.assertTrue(button.detail.startswith("pid ")) + + def test_closed_port_is_down(self): + button = core.create("XMonitorButton", "XMonitorButton_001") + button.set_prop("check-type", "Port") + button.set_prop("target", str(_closed_port())) + self.assertEqual(button.poll(), "down") + self.assertEqual(button.detail, "closed") + + def test_bad_port_is_unknown(self): + button = core.create("XMonitorButton", "XMonitorButton_001") + button.set_prop("check-type", "Port") + button.set_prop("target", "not-a-port") + self.assertEqual(button.poll(), "unknown") + + def test_update_alias(self): + button = core.create("XMonitorButton", "XMonitorButton_001") + button.set_prop("check-type", "Process") + button.set_prop("target", "python3") + self.assertEqual(button.update(), "up") + self.assertEqual(button.status, "up") + + def test_check_monitor_helpers(self): + self.assertEqual(monitor_mod.check_monitor(0, "python3")[0], + "up") + status, _detail = monitor_mod.check_monitor( + 2, str(_closed_port())) + self.assertEqual(status, "down") + self.assertEqual(monitor_mod.check_monitor(2, "xx")[0], + "unknown") + + +class MonitorGridTests(unittest.TestCase): + def test_add_and_poll(self): + grid = core.create("XMonitorGrid", "XMonitorGrid_001") + grid.add_monitor("process", "python3", "Python") + grid.add_monitor("port", str(_closed_port()), "Closed port") + self.assertEqual(len(grid.get_monitors()), 2) + statuses = grid.poll_all() + self.assertEqual(statuses, ["up", "down"]) + monitors = grid.get_monitors() + self.assertEqual(monitors[0]["status"], "up") + self.assertTrue(monitors[0]["detail"].startswith("pid ")) + + def test_set_monitors(self): + grid = core.create("XMonitorGrid", "XMonitorGrid_001") + grid.set_monitors([(0, "python3", "Python"), + (2, "22", "SSH")]) + self.assertEqual([m["label"] for m in grid.get_monitors()], + ["Python", "SSH"]) + + def test_cell_at(self): + grid = core.create("XMonitorGrid", "XMonitorGrid_001") + grid.add_monitor("process", "python3", "Python") + grid.add_monitor("process", "python3", "Python 2") + cells = grid._cell_layout() + self.assertEqual(len(cells), 2) + x, y, w, h = cells[0] + self.assertEqual(grid.cell_at(x + 2, y + 2), 0) + self.assertIsNone(grid.cell_at(1, 1)) # title area + self.assertIsNone(grid.cell_at(grid.width - 1, + grid.height - 1)) + + +class PropsTests(unittest.TestCase): + def test_monitor_kinds_have_generic_set(self): + # Same check as test_props.py's generic-set test, applied + # to the 15 new kinds. + for kind in MONITOR_KINDS: + self.assertEqual(props.GENERIC_NAMES, + props.GENERIC_NAMES + & props.prop_names(kind), kind) + + def test_custom_props_present(self): + self.assertIn("series-count", + props.prop_names("XHistoryGraph")) + self.assertIn("threshold", props.prop_names("XTempHistory")) + self.assertIn("redline", props.prop_names("XTachometer")) + self.assertIn("check-type", + props.prop_names("XMonitorButton")) + self.assertIn("target", props.prop_names("XMonitorButton")) + self.assertIn("sort-by", props.prop_names("XProcessList")) + self.assertIn("segments", props.prop_names("XStackBar")) + self.assertIn("cores", props.prop_names("XCoreGrid")) + self.assertIn("value", props.prop_names("XUsageBar")) + self.assertIn("unit", props.prop_names("XSysBox")) + + def test_set_prop_validation(self): + bar = core.create("XUsageBar", "XUsageBar_001") + bar.set_prop("value", 65) + self.assertEqual(bar.get_value(), 65.0) + with self.assertRaises(ValueError): + bar.set_prop("no-such-prop", "x") + button = core.create("XMonitorButton", "XMonitorButton_001") + button.set_prop("check-type", "Port") + self.assertEqual(button.get_prop("check-type"), "2") + with self.assertRaises(ValueError): + button.set_prop("check-type", "Nope") + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_palette.py b/tests/test_palette.py index 1fcf995..e52b5d8 100644 --- a/tests/test_palette.py +++ b/tests/test_palette.py @@ -1,4 +1,4 @@ -"""Tests for lightgui.xframe.palette: 547 widgets, 11 sections, 36 legacy.""" +"""Tests for lightgui.xframe.palette: 562 widgets, 11 sections, 36 legacy.""" import unittest @@ -13,15 +13,15 @@ EXPECTED_SECTIONS = { "Choosers": 10, "Views & Lists": 17, "Menus & Toolbars": 16, - "Misc / X": 4, + "Misc / X": 19, "Stock Market": 287, "Instrumentation": 66, } class PaletteTests(unittest.TestCase): - def test_547_entries(self): - self.assertEqual(len(palette.PALETTE), 547) + def test_562_entries(self): + self.assertEqual(len(palette.PALETTE), 562) def test_11_sections_in_c_palette_order(self): self.assertEqual(list(palette.SECTIONS), @@ -33,13 +33,13 @@ class PaletteTests(unittest.TestCase): self.assertEqual(len(palette.by_section(section)), count, section) - def test_indices_are_0_to_546(self): + def test_indices_are_0_to_561(self): self.assertEqual(sorted(e.index for e in palette.PALETTE), - list(range(547))) + list(range(562))) def test_names_unique(self): names = [e.name for e in palette.PALETTE] - self.assertEqual(len(set(names)), 547) + self.assertEqual(len(set(names)), 562) def test_default_sizes_positive(self): for entry in palette.PALETTE: @@ -69,9 +69,9 @@ class PaletteTests(unittest.TestCase): self.assertIsNone(palette.find(key), "legacy key must not be a registry kind") - def test_total_entries_583(self): + def test_total_entries_598(self): self.assertEqual(len(palette.PALETTE) + len(palette.LEGACY_TYPES), - 583) + 598) if __name__ == "__main__": diff --git a/tests/test_props.py b/tests/test_props.py index 1d15f5a..b17a6da 100644 --- a/tests/test_props.py +++ b/tests/test_props.py @@ -1,6 +1,6 @@ """Tests for lightgui.props and Phase 2 live-apply plumbing. -Covers: every one of the 547 kinds has a property table with the +Covers: every one of the 562 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 / @@ -66,7 +66,7 @@ PER_WIDGET = { class GenericSetTests(unittest.TestCase): def test_every_kind_has_generic_set(self): - self.assertEqual(len(palette.PALETTE), 547) + self.assertEqual(len(palette.PALETTE), 562) for entry in palette.PALETTE: names = props.prop_names(entry.name) missing = GENERIC_REQUIRED - names