- Graphs (History/Net/Temp): dynamic left margin from the widest Y
label (fixes Y labels overflowing the plot), legend on top, 5 Y
labels, humanised units in NetGraph, TempHistory threshold label
above the line ("80 C limit"), top/bottom Y labels hang clear of
the title and the strip below the plot. History gains -60s/now.
- XTachometer: numerals 7.5% of dial diameter bold just inside the
tick ring, RPM bold centred in-dial below the top numerals (its
baseline hangs below the top numeral so it cannot collide with
the 3200/4800 numerals on small dials), readout "value (peak N)"
enlarged below the hub, redline numerals in red.
- All 14 audit widgets: font sizes derived from widget dimensions
per the proportions audit (titles 16px bold, hero values 24-48px
bold, body/legend 13-16px, min 11px); CoreGrid keeps 4x2; UsageBar
labels outside the bar on a dark panel; StackBar title+total
header (adaptive: omitted at 48px where it would push the legend
out) with centred block; VerticalBar value inside the bar, peak
label with shrink-to-fit; ArcGauge centre 40-48px + endpoints;
DonutGauge centre 36-44px, ring 8-10% of diameter, duplicate
title dropped, centre label is the value name; ProcessList 13px
rows, bold header with sort indicator, "N procs"; LoadBadge
centred two-line block with scaled values; MonitorButton scaled
label/dot/status + detail line; MonitorGrid ceil(sqrt(n)) columns,
name+status+detail design with wrapped detail; SysBox hero
28-32px + max + bar %.
- New _fpx() clamp helper; XStackBar gains the "unit" prop
(props_monitor.py) for its "total <sum> <unit>" header.
- Demos: button/grid labels "SSH :22" -> "sshd :22", tach label
"Engine" -> "RPM", stackbar demo 320x48 -> 320x120 (title+bar+
legend cannot fit in 48px), verticalbar demo 60 -> 160 wide
(the "peak 82" label cannot fit in a 60px widget).
- Deviations from the audit spec: UsageBar label capped at 40px
(the literal 0.45x rule gives 209px in a 464px-tall bar); SysBox
hero uses 10% of height clamped 20-32px (spec 6-7% conflicts
with the audited-correct PY value of 10.3%); PY LoadBadge gets
no 1/5/15 sub-labels (the audit calls the PY layout correct;
the sub-labels were directed at Rust).
Full suite: 363 tests OK (44 skipped). All 15 demos shot + verified.
1683 lines
65 KiB
Python
1683 lines
65 KiB
Python
"""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,
|
|
_wrap_lines,
|
|
_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 _fpx(value, lo, hi):
|
|
"""Font size derived from a widget dimension, clamped to [lo, hi]
|
|
(sane minimum 11px so text never shrinks to unreadable)."""
|
|
return max(lo, min(hi, value))
|
|
|
|
|
|
def _peak_fit(cr, widget, peak, bar_x, bar_w):
|
|
"""Peak-label size: 14px bold, shrinking to 11px when the bar is
|
|
too narrow for the label to fit inside the frame."""
|
|
text = "peak %.0f" % peak
|
|
avail = bar_x + bar_w - 2 - 8
|
|
for size in (14, 13, 12, 11):
|
|
if _text_width(cr, widget, text, size=size, bold=True) <= avail:
|
|
return size
|
|
return 11
|
|
|
|
|
|
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_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."""
|
|
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,
|
|
"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, 17, size=16, rgb=_TITLE, bold=True,
|
|
max_width=widget.width - 16)
|
|
return 24
|
|
return 6
|
|
|
|
|
|
def _plot_frame(cr, x, y, w, h, lo, hi, labels=True, label_size=14,
|
|
fmt=None):
|
|
"""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. *fmt* formats
|
|
the tick values (humanised rates for the net graph)."""
|
|
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 i in range(5):
|
|
frac = i / 4.0
|
|
value = lo + frac * (hi - lo)
|
|
label = fmt(value) if fmt is not None else "%.0f" % value
|
|
gy = y + h - frac * h
|
|
# Top label hangs below its gridline (clear of the title),
|
|
# bottom label sits above its gridline (clear of the strip
|
|
# below the plot); middle labels are centred on the line.
|
|
if i == 4:
|
|
ybase = gy + label_size * 0.75
|
|
elif i == 0:
|
|
ybase = gy - 2
|
|
else:
|
|
ybase = gy + label_size * 0.35
|
|
_ylabel(cr, label, x - 4, ybase, size=label_size)
|
|
|
|
|
|
def _ylabel(cr, text, x, y, size=8):
|
|
"""Small dim right-aligned y-axis label (baseline *y*)."""
|
|
cr.save()
|
|
cr.select_font_face("Sans", 0, 0)
|
|
cr.set_font_size(size)
|
|
_rgb(cr, _DIM)
|
|
w = cr.text_extents(text)[2]
|
|
cr.move_to(x - w, y)
|
|
cr.show_text(text)
|
|
cr.restore()
|
|
|
|
|
|
def _y_axis_width(cr, widget, lo, hi, size, fmt=None):
|
|
"""Left margin for a plot: widest of the 5 Y labels + 10px."""
|
|
widest = 0.0
|
|
for i in range(5):
|
|
value = lo + (i / 4.0) * (hi - lo)
|
|
label = fmt(value) if fmt is not None else "%.0f" % value
|
|
widest = max(widest, _text_width(cr, widget, label, size=size))
|
|
return widest + 10
|
|
|
|
|
|
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
|
|
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 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.
|
|
|
|
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."""
|
|
count = max(1, len(self._monitors))
|
|
cols = max(1, math.ceil(math.sqrt(count)))
|
|
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 - 10, 10, 10, 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, 24, y, size=14, rgb=_TEXT,
|
|
max_width=self.width - 30)
|
|
y += 18
|
|
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)
|
|
body_px = _fpx(0.032 * self.height, 11, 16)
|
|
legend_h = 18 * len(series) if show_legend else 0
|
|
legend_y = top + 13
|
|
if show_legend:
|
|
self._legend(cr, legend_y, series, names)
|
|
plot_x = _y_axis_width(cr, self, lo, hi, body_px)
|
|
plot_y = top + legend_h + 4
|
|
plot_w = max(1, self.width - plot_x - 8)
|
|
plot_h = max(1, self.height - plot_y - 22)
|
|
_plot_frame(cr, plot_x, plot_y, plot_w, plot_h, lo, hi,
|
|
label_size=body_px)
|
|
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)])
|
|
# Time axis: "-60s" left, "now" right.
|
|
time_px = _fpx(0.028 * self.height, 11, 14)
|
|
_wtext(cr, self, "-60s", plot_x, self.height - 5, size=time_px,
|
|
rgb=_DIM)
|
|
_wtext(cr, self, "now", plot_x + plot_w, self.height - 5,
|
|
size=time_px, rgb=_DIM, align="right")
|
|
|
|
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
|
|
cell_px = _fpx(0.10 * ch, 11, 16)
|
|
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 + cell_px + 2,
|
|
size=cell_px, rgb=_DIM, bold=True)
|
|
_wtext(cr, self, "%.0f%%" % cur, x + cw - 6,
|
|
y + cell_px + 2, size=cell_px, rgb=color,
|
|
align="right", bold=True)
|
|
if ch > 26:
|
|
_series_line(cr, values, x + 3, y + cell_px + 7, cw - 6,
|
|
ch - cell_px - 10, 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)
|
|
body_px = _fpx(0.032 * self.height, 11, 16)
|
|
# Legend on top: one line per direction, split into rate /
|
|
# total lines when the full line would clip at the right edge.
|
|
legend = []
|
|
for color, name, series, total in (
|
|
(_GREEN, "Down", down, self._total_down),
|
|
(_CYAN, "Up", up, self._total_up)):
|
|
full = "%s %s Total %s" % (
|
|
name, _fmt_rate(series[-1] if series else 0.0),
|
|
_fmt_bytes(total))
|
|
if _text_width(cr, self, full, size=body_px) \
|
|
<= self.width - 30:
|
|
legend.append((color, [full]))
|
|
else:
|
|
legend.append((color, [
|
|
"%s %s" % (name, _fmt_rate(
|
|
series[-1] if series else 0.0)),
|
|
"Total %s" % _fmt_bytes(total)]))
|
|
legend_h = 18 * sum(len(lines) for _c, lines in legend)
|
|
legend_y = top + 13
|
|
for color, lines in legend:
|
|
for line in lines:
|
|
_box(cr, 8, legend_y - 10, 10, 10, color, color)
|
|
_wtext(cr, self, line, 24, legend_y, size=body_px,
|
|
rgb=_TEXT, max_width=self.width - 30)
|
|
legend_y += 18
|
|
plot_x = _y_axis_width(cr, self, 0.0, hi, body_px, fmt=_fmt_rate)
|
|
plot_y = top + legend_h + 4
|
|
plot_w = max(1, self.width - plot_x - 8)
|
|
plot_h = max(1, self.height - plot_y - 6)
|
|
_plot_frame(cr, plot_x, plot_y, plot_w, plot_h, 0.0, hi,
|
|
label_size=body_px, fmt=_fmt_rate)
|
|
_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)
|
|
|
|
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
|
|
body_px = _fpx(0.032 * self.height, 11, 16)
|
|
_wtext(cr, self, "%.1f C" % cur, self.width - 8, 17,
|
|
size=_fpx(0.032 * self.height, 11, 16), rgb=cur_rgb,
|
|
align="right", bold=True)
|
|
plot_x = _y_axis_width(cr, self, lo, hi, body_px,
|
|
fmt=lambda v: "%.0f C" % v)
|
|
plot_y = top + 2
|
|
plot_w = max(1, self.width - plot_x - 8)
|
|
plot_h = max(1, self.height - plot_y - 20)
|
|
_plot_frame(cr, plot_x, plot_y, plot_w, plot_h, lo, hi,
|
|
label_size=body_px, fmt=lambda v: "%.0f C" % v)
|
|
# Threshold line (dashed red) + label above the line.
|
|
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 limit" % threshold,
|
|
plot_x + plot_w - 2, thr_y - 6, size=14, 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 + 14, size=13, 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)
|
|
label = self.get_prop("label", "") or self.kind
|
|
value = _prop_float(self, "value", 0.0)
|
|
# Dark panel first: the labels sit outside the bar, and
|
|
# without it they are white text on the window background.
|
|
_panel(cr, self)
|
|
# The 0.45x rule is capped at 40px: the literal rule gives a
|
|
# 209px label in the 464px-tall demo bar.
|
|
bar_h = self.height - 16
|
|
label_px = _fpx(0.45 * bar_h, 11, 40)
|
|
label_w = _text_width(cr, self, label, size=label_px, bold=True)
|
|
value_text = "%.0f%%" % value
|
|
value_w = _text_width(cr, self, value_text, size=label_px,
|
|
bold=True)
|
|
bar_x = 8 + label_w + 12
|
|
bar_w = max(1, self.width - bar_x - value_w - 20)
|
|
self._gradient_bar(cr, bar_x, 8, bar_w, bar_h, frac)
|
|
mid = self.height / 2 + label_px * 0.35
|
|
_wtext(cr, self, label, 8, mid, size=label_px, rgb=_WHITE,
|
|
bold=True, max_width=bar_x - 12)
|
|
_wtext(cr, self, value_text, self.width - 8, mid,
|
|
size=label_px, 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
|
|
legend_px = _fpx(0.032 * self.height, 11, 16)
|
|
head_px = _fpx(0.033 * self.height, 11, 16)
|
|
row_h = 1.6 * legend_px
|
|
# Legend rows (flow left to right, wrap when the width runs out).
|
|
rows = []
|
|
lx = 6
|
|
row = []
|
|
for label, value, color in segments:
|
|
text = "%s %.0f%%" % (label, 100.0 * value / total)
|
|
tw = _text_width(cr, self, text, size=legend_px) + 16
|
|
if lx + tw > self.width - 4 and row:
|
|
rows.append(row)
|
|
lx, row = 6, []
|
|
row.append((label, value, color, text, tw))
|
|
lx += tw
|
|
if row:
|
|
rows.append(row)
|
|
bar_h = _fpx(1.5 * legend_px, 8, 0.30 * self.height)
|
|
block_h = bar_h + 8 + row_h * len(rows)
|
|
# Title + total header (C style) when the widget is tall
|
|
# enough to hold it; at palette-default height (48px) the
|
|
# header would push the legend out of the widget, so the
|
|
# bar+legend block takes the space instead.
|
|
show_title = (self.height - 24) >= block_h
|
|
top = _panel(cr, self, self._title() if show_title else None)
|
|
if show_title:
|
|
# Total header (C style): the raw segment sum, with the
|
|
# unit prop appended when the host sets one (demo: GiB).
|
|
unit = self.get_prop("unit", "")
|
|
total_text = ("total %.1f %s" % (total, unit)) if unit \
|
|
else "total %.1f" % total
|
|
_wtext(cr, self, total_text, self.width - 8, 17,
|
|
size=head_px, rgb=_TEXT, align="right")
|
|
avail = self.height - top
|
|
bar_y = top + max(0, (avail - block_h) / 2)
|
|
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
|
|
ly = bar_y + bar_h + 8 + legend_px
|
|
for row in rows:
|
|
lx = 6
|
|
for label, value, color, text, tw in row:
|
|
_box(cr, lx, ly - legend_px * 0.7, legend_px * 0.7,
|
|
legend_px * 0.7, color, color)
|
|
_wtext(cr, self, text, lx + legend_px, ly,
|
|
size=legend_px, rgb=_TEXT)
|
|
lx += tw
|
|
ly += row_h
|
|
|
|
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)
|
|
top = _panel(cr, self, self._title())
|
|
body_px = _fpx(0.03 * self.height, 11, 16)
|
|
# Dynamic scale width from the widest Y label.
|
|
scale_w = 0.0
|
|
for f in (0.0, 0.25, 0.5, 0.75, 1.0):
|
|
label = "%.0f" % (lo + f * (hi - lo))
|
|
scale_w = max(scale_w, _text_width(cr, self, label,
|
|
size=body_px))
|
|
bar_x = int(scale_w) + 10
|
|
bar_w = self.width - bar_x - 8
|
|
bar_y, bar_h = top + 2, self.height - top - 10
|
|
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
|
|
if f == 1.0:
|
|
ybase = gy + body_px * 0.75
|
|
elif f == 0.0:
|
|
ybase = gy - 2
|
|
else:
|
|
ybase = gy + body_px * 0.35
|
|
_ylabel(cr, "%.0f" % (lo + f * (hi - lo)), bar_x - 4,
|
|
ybase, size=body_px)
|
|
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 + label (bold, above the line, inset from
|
|
# the frame edge).
|
|
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, "peak %.0f" % peak, bar_x + bar_w - 2,
|
|
py - 6, size=_peak_fit(cr, self, peak, bar_x, bar_w),
|
|
rgb=_RED, align="right", bold=True)
|
|
# Value INSIDE the bar at the bottom (PY style), white on the
|
|
# fill, dark when the fill is too short to hold it.
|
|
fill_h = bar_h * frac
|
|
value_px = _fpx(0.033 * self.height, 11, 16)
|
|
value_rgb = _WHITE if fill_h >= value_px + 8 else _TEXT
|
|
_wtext(cr, self, "%.0f%%" % value, bar_x + bar_w / 2,
|
|
bar_y + bar_h - 8, size=value_px, rgb=value_rgb,
|
|
align="center", bold=True)
|
|
|
|
def _draw_tachometer(self, cr):
|
|
top = _panel(cr, self)
|
|
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: numerals ~7.5% of the dial diameter, bold,
|
|
# just inside the major tick ring; redline numerals in red.
|
|
numeral_px = _fpx(0.075 * 2 * r, 13, 28)
|
|
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) \
|
|
+ numeral_px * 0.35
|
|
rgb = _RED if f >= red_frac else _TEXT
|
|
_wtext(cr, self, label, lx, ly, size=numeral_px,
|
|
rgb=rgb, align="center", bold=True)
|
|
# 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()
|
|
# Title bold and centred inside the dial, below the top
|
|
# numerals: its baseline hangs below the top numeral's bottom
|
|
# edge, so it cannot collide with the 3200/4800 numerals on
|
|
# small dials (a fixed cy - r*0.55 put it on top of them).
|
|
title_px = _fpx(numeral_px - 4, 13, 24)
|
|
title_base = cy - (r - 26) + numeral_px * 0.75 + title_px + 4
|
|
_wtext(cr, self, self._title(), cx, title_base,
|
|
size=title_px, rgb=_WHITE, align="center", bold=True)
|
|
readout_px = _fpx(0.05 * 2 * r, 13, 20)
|
|
_wtext(cr, self, "%.0f (peak %.0f)" % (value, peak),
|
|
cx, cy + r * 0.80, size=readout_px, rgb=_WHITE,
|
|
align="center", bold=True)
|
|
unit = self.get_prop("unit", "")
|
|
if unit:
|
|
_wtext(cr, self, unit, cx, cy + r * 0.80 + 16, size=12,
|
|
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 - 32
|
|
r = min(self.width / 2 - 12, self.height - top - 40)
|
|
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)
|
|
centre_px = _fpx(0.10 * 2 * r, 16, 48)
|
|
_wtext(cr, self, "%.0f%%" % value, cx, cy - r * 0.45,
|
|
size=centre_px, rgb=_WHITE, align="center", bold=True)
|
|
label = self.get_prop("unit", "") or "usage"
|
|
_wtext(cr, self, label, cx, cy - r * 0.45 + centre_px * 0.75,
|
|
size=_fpx(0.04 * 2 * r, 11, 16), rgb=_DIM,
|
|
align="center")
|
|
# Endpoints under the arc ends.
|
|
end_px = _fpx(0.04 * 2 * r, 11, 18)
|
|
_wtext(cr, self, "0", cx - r, cy + end_px + 4, size=end_px,
|
|
rgb=_DIM, align="center")
|
|
_wtext(cr, self, "100", cx + r, cy + end_px + 4, size=end_px,
|
|
rgb=_DIM, align="center")
|
|
|
|
def _draw_donut_gauge(self, cr):
|
|
# No top-left title: the centre label carries the value name
|
|
# (the title would duplicate it).
|
|
top = _panel(cr, self)
|
|
frac = _range_frac(self)
|
|
value = _prop_float(self, "value", 0.0)
|
|
cx = self.width / 2
|
|
cy = top + (self.height - top) / 2
|
|
r0 = min(self.width, self.height - top) / 2 - 12
|
|
if r0 <= 0:
|
|
return
|
|
thick = _fpx(0.09 * 2 * r0, 8, 48)
|
|
# The ring stroke extends thick/2 past r: shrink r so the
|
|
# outer edge stays inside the frame.
|
|
r = r0 - thick / 2
|
|
_arc_stroke(cr, cx, cy, r, 0, 2 * math.pi,
|
|
(0.25, 0.25, 0.28), thick, cap=1)
|
|
_arc_stroke(cr, cx, cy, r, -math.pi / 2,
|
|
-math.pi / 2 + frac * 2 * math.pi, _GREEN, thick,
|
|
cap=1)
|
|
centre_px = _fpx(0.10 * 2 * r, 16, 44)
|
|
_wtext(cr, self, "%.0f%%" % value, cx, cy + centre_px * 0.35,
|
|
size=centre_px, rgb=_WHITE, align="center", bold=True)
|
|
label = self.get_prop("label", "") or self.kind
|
|
_wtext(cr, self, label, cx, cy + centre_px * 0.35 + 22,
|
|
size=_fpx(0.04 * 2 * r, 11, 18), 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()
|
|
_wtext(cr, self, "%d procs" % len(rows), self.width - 8, 17,
|
|
size=13, rgb=_DIM, align="right")
|
|
cols = ((6, 52, "PID", "left"), (62, 130, "Program", "left"),
|
|
(196, 44, "User", "left"), (248, 52, "Mem", "right"),
|
|
(308, 48, "CPU%", "right"))
|
|
sort_col = _prop_int(self, "sort-by", 0)
|
|
sort_key = {0: "CPU%", 1: "Mem", 2: "PID", 3: "Program"}.get(
|
|
sort_col, "CPU%")
|
|
sort_desc = _prop_bool(self, "sort-desc", True)
|
|
header_y = top + 15
|
|
for x, _w, name, align in cols:
|
|
if name == sort_key:
|
|
name = name + (" \u25bc" if sort_desc else " \u25b2")
|
|
if align == "right":
|
|
_wtext(cr, self, name, x + _w, header_y, size=13,
|
|
rgb=_DIM, align="right", bold=True)
|
|
else:
|
|
_wtext(cr, self, name, x, header_y, size=13,
|
|
rgb=_DIM, bold=True)
|
|
row_h = 23
|
|
y0 = top + 24
|
|
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 + 16, size=13,
|
|
rgb=_TEXT)
|
|
_wtext(cr, self, row["name"], 62, y + 16, size=13,
|
|
rgb=_TEXT,
|
|
max_width=128)
|
|
_wtext(cr, self, row["user"], 196, y + 16, size=13,
|
|
rgb=_TEXT, max_width=44)
|
|
_wtext(cr, self, _fmt_bytes(row["mem_kb"] * 1024), 300,
|
|
y + 16, size=13, rgb=_TEXT, align="right")
|
|
# In-cell CPU% bar behind the number (colour-coded).
|
|
bar_x, bar_w = 308, 48
|
|
_box(cr, bar_x, y + 5, 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 + 5, fill, 12, color, color)
|
|
_wtext(cr, self, "%.1f" % cpu, bar_x + bar_w - 3, y + 16,
|
|
size=13, 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
|
|
# Two-line layout, value block vertically centred. (No 1/5/15
|
|
# sub-labels: the audit calls the PY layout correct as-is;
|
|
# the sub-labels were directed at the Rust port.)
|
|
val_px = _fpx(0.055 * self.height, 13, 28)
|
|
title_px = _fpx(0.033 * self.height, 11, 16)
|
|
val_base = self.height / 2 - 6
|
|
_wtext(cr, self, "Load", 8, val_base, size=title_px, rgb=_DIM,
|
|
bold=True)
|
|
x = 8 + _text_width(cr, self, "Load", size=title_px,
|
|
bold=True) + 16
|
|
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, val_base, size=val_px,
|
|
rgb=color, bold=True)
|
|
x += _text_width(cr, self, text, size=val_px,
|
|
bold=True) + 12
|
|
_wtext(cr, self, "%s %d cores" % (_fmt_uptime(uptime), ncores),
|
|
8, val_base + 28, size=14, 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)
|
|
dot_d = _fpx(0.10 * self.height, 12, 30)
|
|
dot_r = dot_d / 2
|
|
dot_cx = 10 + dot_r
|
|
mid_y = self.height / 2
|
|
_rgb(cr, color)
|
|
cr.arc(dot_cx, mid_y, dot_r, 0, 2 * math.pi)
|
|
cr.fill()
|
|
if status == "up":
|
|
_rgb(cr, _WHITE)
|
|
cr.arc(dot_cx, mid_y, dot_r * 0.35, 0, 2 * math.pi)
|
|
cr.fill()
|
|
label = self.get_prop("label", "") or self.get_prop("target", "") \
|
|
or self.kind
|
|
status_text = _STATUS_LABELS[status]
|
|
label_px = _fpx(0.10 * self.height, 13, 24)
|
|
status_px = _fpx(0.09 * self.height, 12, 20)
|
|
detail_px = _fpx(0.06 * self.height, 11, 14)
|
|
sw = _text_width(cr, self, status_text, size=status_px,
|
|
bold=True)
|
|
label_x = dot_cx + dot_r + 10
|
|
max_w = self.width - label_x - sw - 16
|
|
if self._detail:
|
|
_wtext(cr, self, label, label_x, mid_y - 2, size=label_px,
|
|
rgb=_WHITE, bold=True, max_width=max_w)
|
|
_wtext(cr, self, self._detail, label_x,
|
|
mid_y + detail_px + 2, size=detail_px, rgb=_DIM,
|
|
max_width=max_w)
|
|
else:
|
|
_wtext(cr, self, label, label_x, mid_y + label_px * 0.35,
|
|
size=label_px, rgb=_WHITE, bold=True,
|
|
max_width=max_w)
|
|
_wtext(cr, self, status_text, self.width - 8,
|
|
mid_y + status_px * 0.35, size=status_px, 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
|
|
# Summary, bold, top-right (e.g. "3/4 up").
|
|
n_up = sum(1 for m in self._monitors
|
|
if m["status"] == "up")
|
|
summary = "%d/%d up" % (n_up, len(self._monitors))
|
|
_wtext(cr, self, summary, self.width - 8, 17,
|
|
size=_fpx(0.033 * self.height, 11, 16), rgb=_TITLE,
|
|
align="right", bold=True)
|
|
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)
|
|
dot_d = _fpx(0.11 * h, 10, 24)
|
|
dot_r = dot_d / 2
|
|
dot_cx = x + 10 + dot_r
|
|
mid_y = y + h / 2
|
|
_rgb(cr, color)
|
|
cr.arc(dot_cx, mid_y, dot_r, 0, 2 * math.pi)
|
|
cr.fill()
|
|
label_px = _fpx(0.10 * h, 13, 20)
|
|
status_px = _fpx(0.09 * h, 12, 18)
|
|
detail_px = _fpx(0.06 * h, 11, 14)
|
|
label_x = dot_cx + dot_r + 10
|
|
status_text = _STATUS_LABELS[monitor["status"]]
|
|
sw = _text_width(cr, self, status_text, size=status_px,
|
|
bold=True)
|
|
_wtext(cr, self, monitor["label"], label_x, mid_y - 2,
|
|
size=label_px, rgb=_WHITE, bold=True,
|
|
max_width=w - (label_x - x) - sw - 12)
|
|
_wtext(cr, self, status_text, x + w - 8,
|
|
mid_y + status_px * 0.35, size=status_px, rgb=color,
|
|
align="right", bold=True)
|
|
# Detail on its own line, wrapped to two lines rather
|
|
# than truncated ("DOWN - clos..." bug).
|
|
detail = monitor["detail"]
|
|
lines = _wrap_lines(cr, self, detail,
|
|
w - (label_x - x) - 8, size=detail_px)
|
|
dy = mid_y + detail_px + 4
|
|
for line in lines[:2]:
|
|
_wtext(cr, self, line, label_x, dy, size=detail_px,
|
|
rgb=_DIM)
|
|
dy += detail_px + 4
|
|
|
|
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
|
|
hero_px = _fpx(0.10 * self.height, 20, 32)
|
|
_wtext(cr, self, "%.0f" % value, 8, top + hero_px,
|
|
size=hero_px, rgb=_WHITE, bold=True)
|
|
_wtext(cr, self, unit, 8 + _text_width(cr, self, "%.0f" % value,
|
|
size=hero_px,
|
|
bold=True) + 6,
|
|
top + hero_px, size=14, rgb=_DIM)
|
|
_wtext(cr, self, "max %.0f%s" % (hi, unit), self.width - 8,
|
|
top + hero_px, size=13, rgb=_DIM, align="right")
|
|
values = self._single_series(55.0, 28.0, lo, hi)
|
|
graph_y = top + hero_px + 10
|
|
bar_h = _fpx(0.055 * self.height, 20, 28)
|
|
graph_h = max(1, self.height - graph_y - bar_h - 16)
|
|
_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)))
|
|
bar_y = self.height - 8 - bar_h
|
|
self._gradient_bar(cr, 8, bar_y, self.width - 16, bar_h, frac)
|
|
_wtext(cr, self, "%.0f%%" % (frac * 100.0), self.width - 12,
|
|
bar_y + bar_h / 2 + 5, size=14, 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)
|