"""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 time 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 # (pid, starttime) -> user name, so a rescan only opens /proc//status # for processes it has never seen (a recycled pid has a new starttime, # so the cache cannot go stale). Opening status for every process on # every scan cost ~40% of the scan on a 400-process box; the stat file # alone carries everything else (rss is field 24, in pages). _UID_CACHE = {} _PAGE_KB = 4 # overridden below from sysconf when available try: _PAGE_KB = os.sysconf("SC_PAGE_SIZE") // 1024 except (AttributeError, ValueError, OSError): pass def _user_for(pid, starttime): """User name for a process, reading /proc//status only on a cache miss. Returns "" when the process is gone.""" key = (pid, starttime) user = _UID_CACHE.get(key) if user is not None: return user if len(_UID_CACHE) > 4096: _UID_CACHE.clear() user = "" try: import pwd except ImportError: # pragma: no cover - non-Unix pwd = None try: with open("/proc/%s/status" % pid) as handle: for line in handle: if line.startswith("Uid:"): uid = int(line.split()[1]) user = str(uid) if pwd is not None: try: user = pwd.getpwuid(uid).pw_name except KeyError: pass break except (OSError, ValueError, IndexError): pass _UID_CACHE[key] = user return user def _read_processes(): """Live process rows from /proc: dicts with pid, name, user, mem_kb, utime, stime -- plus an internal ``t`` (monotonic time the stat was read, used for per-process CPU% denominators and stripped before the rows reach the widget). Returns None when /proc is unavailable. """ 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]) starttime = int(rest[19]) mem_kb = int(rest[21]) * _PAGE_KB user = _user_for(pid, starttime) rows.append({"pid": int(pid), "name": comm, "user": user, "mem_kb": mem_kb, "utime": utime, "stime": stime, "cpu": 0.0, "t": time.monotonic()}) 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)) def _arc_stroke(cr, cx, cy, r, a0, a1, color, width, cap=0): """Stroke one arc as its own sub-path. A bare cr.arc() draws a connecting line from the *current* point to the arc start -- and _wtext() leaves a current point (move_to + show_text), so arcs drawn after a title grew a stray diagonal in the gauge widgets. new_path() first: the arc is then exactly the arc.""" cr.save() _rgb(cr, color) cr.set_line_width(width) cr.set_line_cap(cap) cr.new_path() cr.arc(cx, cy, r, a0, a1) cr.stroke() cr.restore() # --- 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 # Row selection (pid; None = none) + substring filter on # name (case-insensitive) or pid (empty = show all). self._selected_pid = None self._filter = "" self._prev_proc = None self._prev_times = 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 clear(self): """Drop every sample from the history series (and reset the peak hold), keeping the series slots: a host app that found no live data yet shows the widget's honest empty state ("no data") instead of the deterministic demo series. Later push() calls fill the kept slots again as usual.""" if self._series is not None: self._series = [[] for _ in self._series] else: self._series = [[]] self._peak = 0.0 self._mark_dirty() 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 set_filter(self, text): """Substring filter on process name (case-insensitive) or pid. Applied when the rows are sorted for display, so it never drops the loaded rows; the next refresh re-applies it.""" self._filter = (text or "").strip().lower() self._mark_dirty() def get_filter(self): """The current filter text (lowercased, stripped).""" return self._filter def selected_pid(self): """Pid of the selected row, or None when the selection is gone (e.g. the process exited).""" if self._selected_pid is None: return None if any(r["pid"] == self._selected_pid for r in self.get_rows()): return self._selected_pid return None def select_at(self, px, py): """Widget-relative click: a header click sorts (toggling direction on the same column), a body click selects the row (stored as a pid, so a refresh keeps it). Returns True when the click landed on the list.""" indexes = {"cpu": 0, "mem": 1, "pid": 2, "name": 3} if py < 40: if px < 62: col = "pid" elif px < 196: col = "name" elif px < 244: col = "name" elif px < 296: col = "mem" else: col = "cpu" if _prop_int(self, "sort-by", 0) == indexes[col]: self.set_prop("sort-desc", "false" if _prop_bool(self, "sort-desc", True) else "true") else: self.sort_by(col) self.set_prop("sort-desc", "true" if col in ("cpu", "mem") else "false") return True rows = self._sorted_rows() row = (py - 40) // 18 if 0 <= row < len(rows): self._selected_pid = rows[row]["pid"] self._mark_dirty() return True return False def _sorted_rows(self): rows = self.get_rows() if self._filter: f = self._filter rows = [r for r in rows if f in r["name"].lower() or f in str(r["pid"])] 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. CPU% is per-core (top/btop semantics: 100% = one core) and is computed against WALL time, not the /proc/stat total: on this VPS the stat total advances at only ~320 jiffies/s for 8 cores (host vCPU scheduling), so the stat denominator inflates a single-threaded busy loop to ~240% -- wall time gives the correct ~96%. The denominator is per-process: each row carries the monotonic time its stat was read, so a scan that slows down between samples cannot inflate late PIDs or deflate early ones.""" rows = _read_processes() if rows is None: return None prev = None prev_times = None if self._prev_proc is not None and self._prev_times is not None: prev = {r["pid"]: r["utime"] + r["stime"] for r in self._prev_proc} prev_times = self._prev_times try: hz = os.sysconf("SC_CLK_TCK") except (AttributeError, ValueError, OSError): hz = 100 ncores = os.cpu_count() or 1 now_times = {} for row in rows: now_times[row["pid"]] = row["t"] old = prev.get(row["pid"]) if prev else None old_t = prev_times.get(row["pid"]) if prev_times else None if old is not None and old_t is not None: dt = row["t"] - old_t if dt > 0: row["cpu"] = max( 0.0, min(100.0 * ncores, 100.0 * (row["utime"] + row["stime"] - old) / (dt * hz))) del row["t"] self._prev_proc = rows self._prev_times = now_times 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) if values: cur = values[-1] 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) else: # Honest empty state: no samples, no reading to show. _wtext(cr, self, "no data", self.width - 8, 15, size=14, rgb=_DIM, 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 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 _box(cr, lx, ly - 8, 8, 8, color, color) _wtext(cr, self, text, lx + 12, ly, size=10, rgb=_TEXT) lx += tw 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 (round caps). _arc_stroke(cr, cx, cy, r, start, start + sweep, (0.25, 0.25, 0.28), 10, cap=1) _arc_stroke(cr, cx, cy, r, _angle(red_frac), start + sweep, _RED, 10, cap=1) _arc_stroke(cr, cx, cy, r, start, _angle(frac), _CYAN, 10, cap=1) # 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") cr.restore() # 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() cr.new_path() _rgb(cr, (0.6, 0.6, 0.65)) cr.arc(cx, cy, 6, 0, 2 * math.pi) cr.fill() cr.restore() # Digital readout: below the hub, clear of the 0/max tick # labels at the bottom of the dial. unit = self.get_prop("unit", "") _wtext(cr, self, "%.0f" % value, cx, cy + r * 0.80, size=20, rgb=_WHITE, align="center", bold=True) if unit: _wtext(cr, self, unit, cx, cy + r * 0.80 + 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)) _arc_stroke(cr, cx, cy, r, math.pi, 2 * math.pi, (0.25, 0.25, 0.28), 12) for f0, f1, color in zones: _arc_stroke(cr, cx, cy, r, math.pi + f0 * math.pi, math.pi + f1 * math.pi, color, 12) _arc_stroke(cr, cx, cy, r, math.pi, math.pi + frac * math.pi, _WHITE, 12) _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 _arc_stroke(cr, cx, cy, r, 0, 2 * math.pi, (0.25, 0.25, 0.28), 14, cap=1) _arc_stroke(cr, cx, cy, r, -math.pi / 2, -math.pi / 2 + frac * 2 * math.pi, _GREEN, 14, cap=1) _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() # Column x-offsets as fractions of the inner width (same # fractions as the C++ widget: PID / Program / User / Mem / # CPU%). The old fixed offsets were drawn for the 360px demo # widget and left a wide widget mostly empty. iw = max(60, self.width - 12) xs = [6 + int(iw * f) for f in (0.0, 0.14, 0.52, 0.68, 0.82, 1.0)] # (x, label, sort key): sort keys follow _sorted_rows # (0 cpu, 1 mem, 2 pid, 3 name); User has no sort key. sort_col = _prop_int(self, "sort-by", 0) sort_desc = _prop_bool(self, "sort-desc", True) headers = [(xs[0], "PID", 2, "left"), (xs[1], "Program", 3, "left"), (xs[2], "User", None, "left"), (xs[4], "Mem", 1, "right"), (xs[5], "CPU%", 0, "right")] header_y = top + 13 for x, name, key, align in headers: label = name if key is not None and key == sort_col: label += " v" if sort_desc else " ^" if align == "right": _wtext(cr, self, label, x - 4, header_y, size=10, rgb=_DIM, align="right", bold=True) else: _wtext(cr, self, label, 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() if (self._selected_pid is not None and row["pid"] == self._selected_pid): _rgb(cr, (0.86, 0.92, 0.99)) cr.rectangle(0, y, self.width, row_h) cr.fill() _wtext(cr, self, str(row["pid"]), xs[0], y + 13, size=10, rgb=_TEXT) _wtext(cr, self, row["name"], xs[1], y + 13, size=10, rgb=_TEXT, max_width=xs[2] - xs[1] - 6) _wtext(cr, self, row["user"], xs[2], y + 13, size=10, rgb=_TEXT, max_width=xs[3] - xs[2] - 6) _wtext(cr, self, _fmt_bytes(row["mem_kb"] * 1024), xs[4] - 4, y + 13, size=10, rgb=_TEXT, align="right") # In-cell CPU% bar behind the number. bar_x, bar_w = xs[4] + 2, xs[5] - xs[4] - 6 _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)