Author SHA1 Message Date
Muse 73ac7e16f2 Merge fix/inst-proportions into main 2026-12-05 23:33:00 +00:00
Muse 53429a87e6 Inst*: proportions fix (audit Dec 2026) — buttons, switches, panels
Rocker I ON / O OFF (UP / DOWN double) 16 px bold, illuminated
lamp window scaled with ON/OFF inside; toggle/slide state 16 px
bold, slide knob bigger with grip; rotary numerals 16 px bold +
POS n / N readout inside the plate; push-button face label white
on the coloured face 18 px bold with title at the foot; E-STOP
white on red 18 px bold on the mushroom; breaker ON 16 px bold;
bezel GAUGE 14-16 px; panel/control headers taller with 18-20 px
bold titles, grid labels 14 px bold. Drive-bys found while
shooting: _color now falls back to the per-kind PropDef default
(LedBlue/PanelLampBlue rendered red); Rotary plate arc joined a
stray chord from the last numeral (cr.new_path before arc).
2026-12-05 22:53:17 +00:00
Muse 34ff1da9e7 Inst*: proportions fix (audit Dec 2026) — lamps + LEDs
LED block scales with the widget; label 12-15% of LED diameter
bold with leads ending above it; panel-lamp disc shrunk so the
16-18 px bold label clears below it; RGB swatches 24 px with 14 px
R/G/B labels; Beacon bar lowered, dome clear of it, FLASH rate in
white on the bar, BEACON 16 px bold below; StackLight title 16 px
bold plus R/A/G segment letters 24 px bold, white on lit / light
grey on unlit; LampTestButton text 16 px bold. Default word labels
via _label() (C constructor defaults, G2).
2026-12-05 22:45:07 +00:00
Muse 80a1698f7a Inst*: proportions fix (audit Dec 2026) — worst offenders + level gauges
Seg14/16 + LedDigits fill widget (dark face so dim segments read
faint, diagonals thinned); DigitalReadout off-segments slightly
more visible; dial numerals 7-8% of diameter bold just inside the
tick ring with titles inside below top numerals; NeedleVu numerals
4% of width bold, red in red zone, VU below arc centre; tank scale
16 / alarms 14 bold / % 18 bold with clearance; horizontal tank
capsule ends inside widget with alarm labels above; sight-glass
tube widened; KeySwitch NO KEY light-on-dark with position
numerals, slot at the current position; Nameplate engraving fit to
45% of plate width. Scaled-font helpers _cap_size/_fs/_fit_size
(cap-height convention, as C inst_cap_font).
2026-12-05 22:43:12 +00:00
Muse b657b6c360 XTachometer: place numerals by per-label radial extent
Same radial-extent inset as C/Rust: the glyph box farthest corner
in the radial direction stays inside the tick ring (inner end r-16)
with 4 px clearance, so a wide 4-digit label never crosses the dial
rim. Verified by re-shoot; full suite still 363 tests OK.
2026-12-05 22:27:40 +00:00
Muse f93dbb8c84 Merge fix/monitor-widget-proportions: dynamic graph margins, scaled fonts, tach numerals 2026-12-05 21:32:44 +00:00
Muse 81a9693d71 Fix monitor-widget proportions: dynamic graph margins, scaled fonts, tach numerals
- 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.
2026-12-05 21:32:36 +00:00
12 changed files with 928 additions and 907 deletions

No files matched your search

-50
View File
@@ -1,50 +0,0 @@
# Task Manager — monitor app (Python)
A Windows-style Task Manager clone in one 1024x768 window, tabbed
with `TPageControl`. Built with the LightGUI XFrame widgets (Python
port) and live `/proc` data — no seeded demo data survives the
first tick.
## What it shows
* **Processes tab** — `XProcessList` with live processes from
`/proc` (PID / Program / User / Mem / CPU%). Click a column
header to sort (clicking the current column toggles the
direction); rows refresh every 2 s. CPU% is per-core (100% = one
core), computed from wall-time deltas between scans.
* **Performance tab** — `XHistoryGraph` (60 s CPU + memory),
`XCoreGrid` (per-core busy %), `XUsageBar` (Memory, Disk /,
Swap), `XStackBar` (memory breakdown: Used / Cached / Buffers /
Free) and `XNetGraph` (live down/up rates from `/proc/net/dev`
with accumulated totals).
## Run
```sh
PYTHONPATH=/root/monitor-wt/task-manager/lightgui_python \
python3 examples/monitor_task_manager/main.py
```
Data is sampled every 500 ms (GLib timeout); the window repaints
every 2 s (a full redraw is ~38 process rows x 5 text calls plus the
graphs, and repainting every tick burned ~40% of a core). Close the
window to quit. The Python monitor widgets draw dark btop-style
panels, so the window background is dark (`#1a1a1e`).
## Notes
* The `TPageControl` draws its tabs itself but tab clicks need
app-level hit handling (fixed `tab-width` 140, so the hit math is
deterministic); the `XProcessList` sort also needs app-level
header hit handling, using the same column fractions as the
widget's draw.
* The `XProcessList` columns are width-relative (same fractions as
the C++ widget) — the widget fix lives in
`lightgui/xframe/monitor.py` on this branch: the old fixed
offsets were drawn for the 360px demo widget and left a wide
widget mostly empty; the header also now shows the sort column
with a `v`/`^` marker.
* `refresh_processes()` needs two samples before CPU% is real, so
the app primes it twice at startup; the graphs are primed with
60 live samples (the net graph is primed with `push()`, not
`push_net()`, so priming does not inflate the totals).
-472
View File
@@ -1,472 +0,0 @@
#!/usr/bin/env python3
# Task Manager - monitor app (Stage 2, btop-widget project).
#
# A Windows-style Task Manager clone in one 1024x768 window, tabbed
# with TPageControl: the Processes tab is a live XProcessList from
# /proc (sortable PID / Program / User / Mem / CPU% columns), and the
# Performance tab is XHistoryGraph (60 s CPU + memory), XCoreGrid
# (per-core), XUsageBar (Memory, Disk /, Swap), XStackBar (memory
# breakdown) and XNetGraph (live /proc/net/dev rates). All data is
# live: no seeded demo data survives the first tick.
#
# Run with:
# PYTHONPATH=<lightgui_python> python3 examples/monitor_task_manager/main.py
# Close the window to quit. Data is sampled every 500 ms; the
# window repaints every 2 s and the process list refreshes then.
#
# Widgets used (all from the LightGUI registry; no raw Cairo drawing
# for UI elements — the only direct drawing here is the harness
# background paint, as in the generated examples):
# TPageControl, XProcessList, XHistoryGraph, XCoreGrid, XUsageBar,
# XStackBar, XNetGraph.
#
# The TPageControl draws its tabs itself but tab clicks need
# app-level hit handling (fixed tab-width 140, so the hit math is
# deterministic); the XProcessList sort also needs app-level header
# hit handling (same column fractions as the widget's draw).
import os
import sys
import time
import gi
gi.require_version("Gtk", "3.0")
gi.require_version("Gdk", "3.0")
from gi.repository import Gdk, GLib, Gtk # noqa: E402
from lightgui.xframe.core import create, parse_color # noqa: E402
# --- design geometry -------------------------------------------------------
_DESIGN_SIZE = (1024, 768)
_BACKGROUND = "#1a1a1e"
_WIDGETS = []
_LAST_SIZE = [None]
_PRESSED = [None]
_AREA = []
# Page widgets (drawn after the tab control, only the active page):
_PAGE = [0]
_PAGE_WIDGETS = [[], []]
# Live-data state:
_TICK = [0]
_PREV_CPU = [None] # (idle, total) for the aggregate cpu line
_PREV_NET = [None] # (rx_bytes, tx_bytes)
_SORT_KEYS = ("cpu", "mem", "pid", "name")
def _build_widgets():
"""Create every placed widget with its props."""
widgets = []
tabs = create("TPageControl", "TPageControl_001", 8, 8, 1008, 752,
props={"pages": "Processes|Performance", "page": "0",
"tab-width": "140"})
widgets.append(tabs)
proc = create("XProcessList", "XProcessList_001", 14, 38, 996, 712,
props={"label": "Processes"})
widgets.append(proc)
hist = create("XHistoryGraph", "XHistoryGraph_001", 14, 38, 630, 300,
props={"label": "CPU + Memory (60 s)", "minimum": "0",
"maximum": "100", "window": "60",
"series-count": "2",
"series-names": "CPU %|Memory %"})
widgets.append(hist)
cores = create("XCoreGrid", "XCoreGrid_001", 652, 38, 354, 300,
props={"label": "CPU cores", "window": "60"})
widgets.append(cores)
membar = create("XUsageBar", "XUsageBar_Mem", 14, 346, 640, 34,
props={"label": "Memory", "minimum": "0",
"maximum": "100"})
widgets.append(membar)
memstack = create("XStackBar", "XStackBar_Mem", 14, 388, 640, 60,
props={"label": "Memory"})
widgets.append(memstack)
diskbar = create("XUsageBar", "XUsageBar_Disk", 662, 346, 344, 34,
props={"label": "Disk /", "minimum": "0",
"maximum": "100"})
widgets.append(diskbar)
swapbar = create("XUsageBar", "XUsageBar_Swap", 662, 388, 344, 34,
props={"label": "Swap", "minimum": "0",
"maximum": "100"})
widgets.append(swapbar)
net = create("XNetGraph", "XNetGraph_001", 14, 456, 992, 294,
props={"label": "Network", "window": "60"})
widgets.append(net)
_PAGE_WIDGETS[0] = [proc]
_PAGE_WIDGETS[1] = [hist, cores, membar, memstack, diskbar, swapbar,
net]
return widgets
_ANCHORS = {
"TPageControl_001": (True, True, False, False, 8, 8, 1008, 752),
"XProcessList_001": (True, True, False, False, 14, 38, 996, 712),
"XHistoryGraph_001": (True, True, False, False, 14, 38, 630, 300),
"XCoreGrid_001": (True, True, False, False, 652, 38, 354, 300),
"XUsageBar_Mem": (True, True, False, False, 14, 346, 640, 34),
"XStackBar_Mem": (True, True, False, False, 14, 388, 640, 60),
"XUsageBar_Disk": (True, True, False, False, 662, 346, 344, 34),
"XUsageBar_Swap": (True, True, False, False, 662, 388, 344, 34),
"XNetGraph_001": (True, True, False, False, 14, 456, 992, 294),
}
def _by_name(name):
for widget in _WIDGETS:
if widget.name == name:
return widget
return None
def _apply_anchors(widgets, width, height):
"""Reposition anchored widgets for a drawing area of
*width* x *height* (Flag 1: minimal anchor layout)."""
design_w, design_h = _DESIGN_SIZE
dx = width - design_w
dy = height - design_h
for widget in widgets:
top, left, right, bottom, ox, oy, ow, oh = \
_ANCHORS[widget.name]
x, y, w, h = ox, oy, ow, oh
if right and not left:
x = ox + dx
elif right and left:
w = ow + dx
if bottom and not top:
y = oy + dy
elif bottom and top:
h = oh + dy
widget.move_to(x, y)
widget.resize_to(w, h)
# --- live /proc data ---------------------------------------------------------
def _read_cpu():
"""(aggregate (idle, total), {core: (idle, total)}) from /proc/stat."""
total = None
cores = {}
try:
with open("/proc/stat") as f:
for line in f:
if not line.startswith("cpu"):
continue
parts = line.split()
if not parts[0][3:].isdigit() and parts[0] != "cpu":
continue
vals = [int(v) for v in parts[1:]]
tot = sum(vals)
idle = vals[3] + (vals[4] if len(vals) > 4 else 0)
if parts[0] == "cpu":
total = (idle, tot)
else:
cores[int(parts[0][3:])] = (idle, tot)
except OSError:
return None, {}
return total, cores
def _cpu_pct(prev, cur):
"""Busy % between two (idle, total) samples."""
if prev is None or cur is None:
return 0.0
d_total = cur[1] - prev[1]
d_idle = cur[0] - prev[0]
if d_total <= 0:
return 0.0
return max(0.0, min(100.0, 100.0 * (1.0 - d_idle / d_total)))
def _read_mem():
"""(total, avail, free, buffers, cached, swap_total, swap_free) kB."""
fields = {}
try:
with open("/proc/meminfo") as f:
for line in f:
key, rest = line.split(":", 1)
fields[key.strip()] = int(rest.split()[0])
except (OSError, ValueError):
return None
return (fields.get("MemTotal", 0), fields.get("MemAvailable", 0),
fields.get("MemFree", 0), fields.get("Buffers", 0),
fields.get("Cached", 0), fields.get("SwapTotal", 0),
fields.get("SwapFree", 0))
def _read_net():
"""(rx_bytes, tx_bytes) summed over non-loopback interfaces."""
rx = tx = 0
try:
with open("/proc/net/dev") as f:
for line in f:
if ":" not in line:
continue
iface, rest = line.split(":", 1)
if iface.strip() == "lo":
continue
vals = rest.split()
if len(vals) < 16:
continue
rx += int(vals[0])
tx += int(vals[8])
except (OSError, ValueError):
return None
return (rx, tx)
def _disk_pct():
"""Used % of the root filesystem."""
try:
st = os.statvfs("/")
total = st.f_blocks * st.f_frsize
free = st.f_bavail * st.f_frsize
if total <= 0:
return 0.0
return 100.0 * (1.0 - free / total)
except OSError:
return 0.0
def _prime():
"""Two CPU samples 100 ms apart, then fill every series with the
first live values so no seeded demo data is ever shown."""
total, _cores = _read_cpu()
_PREV_CPU[0] = total
time.sleep(0.1)
total2, _cores2 = _read_cpu()
cpu = _cpu_pct(_PREV_CPU[0], total2)
_PREV_CPU[0] = total2
mem = _read_mem()
if mem is not None:
total_kb, avail_kb = mem[0], mem[1]
mem_pct = (100.0 * (1.0 - avail_kb / total_kb)
if total_kb else 0.0)
else:
mem_pct = 0.0
hist = _by_name("XHistoryGraph_001")
for _ in range(60):
hist.push(cpu, series=0)
hist.push(mem_pct, series=1)
cores = _by_name("XCoreGrid_001")
values = cores.refresh_cores()
if values:
for i, value in enumerate(values):
for _ in range(60):
cores.push_core(i, value)
net = _by_name("XNetGraph_001")
_PREV_NET[0] = _read_net()
time.sleep(0.1)
now = _read_net()
down = up = 0.0
if _PREV_NET[0] is not None and now is not None:
dt = 0.1
down = max(0.0, (now[0] - _PREV_NET[0][0]) / dt)
up = max(0.0, (now[1] - _PREV_NET[0][1]) / dt)
_PREV_NET[0] = now
# push(), not push_net(): priming must not inflate the totals.
for _ in range(60):
net.push(down, series=0)
net.push(up, series=1)
proc = _by_name("XProcessList_001")
proc.refresh_processes()
time.sleep(0.1)
proc.refresh_processes()
def _tick():
_TICK[0] += 1
total, _cores = _read_cpu()
cpu = _cpu_pct(_PREV_CPU[0], total)
_PREV_CPU[0] = total
mem = _read_mem()
mem_pct = 0.0
if mem is not None:
total_kb, avail_kb, free_kb, buf_kb, cache_kb, \
swap_total, swap_free = mem
mem_pct = (100.0 * (1.0 - avail_kb / total_kb)
if total_kb else 0.0)
used_gb = max(0.0, (total_kb - free_kb - buf_kb - cache_kb)
/ 1048576.0)
stack = _by_name("XStackBar_Mem")
gb = 1048576.0
stack.set_segments([
("Used", used_gb, (0.20, 0.60, 0.90)),
("Cached", cache_kb / gb, (0.90, 0.60, 0.10)),
("Buffers", buf_kb / gb, (0.20, 0.50, 0.90)),
("Free", free_kb / gb, (0.40, 0.40, 0.45)),
])
swap = _by_name("XUsageBar_Swap")
swap.set_value(100.0 * (1.0 - swap_free / swap_total)
if swap_total else 0.0)
else:
stack = None
hist = _by_name("XHistoryGraph_001")
hist.push(cpu, series=0)
hist.push(mem_pct, series=1)
cores = _by_name("XCoreGrid_001")
cores.refresh_cores()
_by_name("XUsageBar_Mem").set_value(mem_pct)
_by_name("XUsageBar_Disk").set_value(_disk_pct())
now = _read_net()
if _PREV_NET[0] is not None and now is not None:
dt = 0.5
down = max(0.0, (now[0] - _PREV_NET[0][0]) / dt)
up = max(0.0, (now[1] - _PREV_NET[0][1]) / dt)
_by_name("XNetGraph_001").push_net(down, up)
_PREV_NET[0] = now
if _TICK[0] % 4 == 0:
_by_name("XProcessList_001").refresh_processes()
# Data is sampled every 500 ms, but the window repaints every
# 2 s (every 4th tick): a full redraw is ~38 process rows x 5
# text calls plus the graphs, and repainting every tick burned
# ~40% of a core. Tab switches and header sorts repaint at once.
if _TICK[0] % 4 == 0 and _AREA:
_AREA[0].queue_draw()
return True
# --- drawing / events -------------------------------------------------------
def _on_draw(area, cr):
bg = parse_color(_BACKGROUND, None)
if bg is None:
bg = (1.0, 1.0, 1.0)
cr.set_source_rgb(*bg)
cr.paint()
for widget in _WIDGETS:
if widget.name == "TPageControl_001":
widget.draw(cr)
for widget in _PAGE_WIDGETS[_PAGE[0]]:
widget.draw(cr)
return False
def _set_page(page):
if page == _PAGE[0]:
return
_PAGE[0] = page
_by_name("TPageControl_001").set_prop("page", str(page))
if _AREA:
_AREA[0].queue_draw()
def _on_tab_click(x, y):
"""Tab strip hit test (TPageControl at (8,8), tab-width 140):
tab 0 x 14..154, tab 1 x 156..296, strip y 10..36. Returns
True when the click was on a tab."""
if 10 <= y < 36:
if 14 <= x < 154:
_set_page(0)
return True
if 156 <= x < 296:
_set_page(1)
return True
return False
def _on_proc_header_click(x, y):
"""Process-list header sort: same column fractions as the
widget's draw (PID 0.14 / Program 0.52 / User 0.68 / Mem 0.82 /
CPU%). Clicking the current column toggles the direction."""
proc = _by_name("XProcessList_001")
lx, ly = x - 14, y - 38
if not (22 <= ly < 40 and 6 <= lx < 990):
return False
iw = 996 - 12
xs = [6 + int(iw * f) for f in (0.0, 0.14, 0.52, 0.68, 0.82, 1.0)]
keys = ["pid", "name", None, "mem", "cpu"]
key = None
for i in range(5):
if xs[i] <= lx < xs[i + 1]:
key = keys[i]
break
if key is None:
return False
idx = _SORT_KEYS.index(key)
cur = int(float(proc.get_prop("sort-by", "0") or "0"))
if idx == cur:
desc = proc.get_prop("sort-desc", "true") != "true"
proc.set_prop("sort-desc", "true" if desc else "false")
else:
proc.sort_by(key)
proc.set_prop("sort-desc",
"true" if key in ("cpu", "mem") else "false")
if _AREA:
_AREA[0].queue_draw()
return True
def _on_button_press(area, event):
if event.type == Gdk.EventType.BUTTON_PRESS:
x, y = event.x, event.y
if _on_tab_click(x, y):
return False
if _PAGE[0] == 0 and _on_proc_header_click(x, y):
return False
return False
def _on_button_release(area, event):
return False
def _on_area_resize(area, allocation):
size = (allocation.width, allocation.height)
if size == _LAST_SIZE[0]:
return False
_LAST_SIZE[0] = size
_apply_anchors(_WIDGETS, size[0], size[1])
area.queue_draw()
return False
def main():
window = Gtk.Window(title="Task Manager - monitor")
window.set_default_size(1024, 768)
window.move(100, 100)
window.connect("destroy", Gtk.main_quit)
vbox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=0)
window.add(vbox)
area = Gtk.DrawingArea()
area.set_hexpand(True)
area.set_vexpand(True)
area.add_events(Gdk.EventMask.BUTTON_PRESS_MASK |
Gdk.EventMask.BUTTON_RELEASE_MASK)
area.connect("draw", _on_draw)
area.connect("button-press-event", _on_button_press)
area.connect("button-release-event", _on_button_release)
area.connect("size-allocate", _on_area_resize)
vbox.pack_start(area, True, True, 0)
_WIDGETS.extend(_build_widgets())
_AREA.append(area)
_prime()
GLib.timeout_add(500, _tick)
window.show_all()
Gtk.main()
return 0
if __name__ == "__main__":
sys.exit(main())
Binary file not shown.

Before

Width:  |  Height:  |  Size: 73 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 74 KiB

+1 -1
View File
@@ -62,7 +62,7 @@ def _build_widgets():
"""Create every placed widget with its props.""" """Create every placed widget with its props."""
widgets = [] widgets = []
widget = create('XMonitorButton', 'XMonitorButton_001', 16, 16, 200, 48) widget = create('XMonitorButton', 'XMonitorButton_001', 16, 16, 200, 48)
widget.set_prop("label", "SSH :22") widget.set_prop("label", "sshd :22")
widget.set_prop("check-type", "Port") widget.set_prop("check-type", "Port")
widget.set_prop("target", "22") widget.set_prop("target", "22")
# Live data: poll the check now; the timer re-polls. # Live data: poll the check now; the timer re-polls.
+1 -1
View File
@@ -67,7 +67,7 @@ def _build_widgets():
# closed port (shows the red/down state). # closed port (shows the red/down state).
widget.add_monitor("process", "python3", "Python") widget.add_monitor("process", "python3", "Python")
widget.add_monitor("unit", "sshd", "sshd unit") widget.add_monitor("unit", "sshd", "sshd unit")
widget.add_monitor("port", "22", "SSH :22") widget.add_monitor("port", "22", "sshd :22")
widget.add_monitor("port", "9999", "Port 9999") widget.add_monitor("port", "9999", "Port 9999")
widget.poll_all() widget.poll_all()
widgets.append(widget) widgets.append(widget)
+6 -5
View File
@@ -30,7 +30,7 @@ _HANDLERS = {
# Design-time geometry + effective anchors per widget: # Design-time geometry + effective anchors per widget:
# name -> (top, left, right, bottom, x, y, width, height) # name -> (top, left, right, bottom, x, y, width, height)
_ANCHORS = { _ANCHORS = {
'XStackBar_001': (True, True, False, False, 16, 16, 320, 48), 'XStackBar_001': (True, True, False, False, 16, 16, 320, 120),
} }
@@ -60,14 +60,15 @@ def _apply_anchors(widgets, width, height):
def _build_widgets(): def _build_widgets():
"""Create every placed widget with its props.""" """Create every placed widget with its props."""
widgets = [] widgets = []
widget = create('XStackBar', 'XStackBar_001', 16, 16, 320, 48) widget = create('XStackBar', 'XStackBar_001', 16, 16, 320, 120)
widget.set_prop("label", "Memory") widget.set_prop("label", "Memory")
widget.set_prop("segments", "used=45|cached=25|buffers=10|free=20") widget.set_prop("segments", "used=11.7|cached=15.5|buffers=1.2|free=1.9")
widget.set_prop("unit", "GiB")
widgets.append(widget) widgets.append(widget)
return widgets return widgets
_DESIGN_SIZE = (352, 80) _DESIGN_SIZE = (352, 152)
_BACKGROUND = '' _BACKGROUND = ''
_WIDGETS = [] _WIDGETS = []
_LAST_SIZE = [None] _LAST_SIZE = [None]
@@ -144,7 +145,7 @@ def _on_area_resize(area, allocation):
def main(): def main():
window = Gtk.Window(title='XStackBar example') window = Gtk.Window(title='XStackBar example')
window.set_default_size(352, 80) window.set_default_size(352, 152)
window.connect("destroy", Gtk.main_quit) window.connect("destroy", Gtk.main_quit)
vbox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, vbox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL,
spacing=0) spacing=0)
+1 -1
View File
@@ -62,7 +62,7 @@ def _build_widgets():
"""Create every placed widget with its props.""" """Create every placed widget with its props."""
widgets = [] widgets = []
widget = create('XTachometer', 'XTachometer_001', 16, 16, 220, 180) widget = create('XTachometer', 'XTachometer_001', 16, 16, 220, 180)
widget.set_prop("label", "Engine") widget.set_prop("label", "RPM")
widget.set_prop("value", "3200") widget.set_prop("value", "3200")
widget.set_prop("maximum", "8000") widget.set_prop("maximum", "8000")
widget.set_prop("redline", "6500") widget.set_prop("redline", "6500")
+4 -4
View File
@@ -31,7 +31,7 @@ _HANDLERS = {
# Design-time geometry + effective anchors per widget: # Design-time geometry + effective anchors per widget:
# name -> (top, left, right, bottom, x, y, width, height) # name -> (top, left, right, bottom, x, y, width, height)
_ANCHORS = { _ANCHORS = {
'XVerticalBar_001': (True, True, False, False, 16, 16, 60, 200), 'XVerticalBar_001': (True, True, False, False, 16, 16, 160, 200),
} }
@@ -61,7 +61,7 @@ def _apply_anchors(widgets, width, height):
def _build_widgets(): def _build_widgets():
"""Create every placed widget with its props.""" """Create every placed widget with its props."""
widgets = [] widgets = []
widget = create('XVerticalBar', 'XVerticalBar_001', 16, 16, 60, 200) widget = create('XVerticalBar', 'XVerticalBar_001', 16, 16, 160, 200)
widget.set_prop("label", "CPU") widget.set_prop("label", "CPU")
# Seed the peak-hold marker: 82, then back to 65. # Seed the peak-hold marker: 82, then back to 65.
widget.set_value(65) widget.set_value(65)
@@ -71,7 +71,7 @@ def _build_widgets():
return widgets return widgets
_DESIGN_SIZE = (92, 232) _DESIGN_SIZE = (192, 232)
_BACKGROUND = '' _BACKGROUND = ''
_WIDGETS = [] _WIDGETS = []
_LAST_SIZE = [None] _LAST_SIZE = [None]
@@ -166,7 +166,7 @@ def _tick():
def main(): def main():
window = Gtk.Window(title='XVerticalBar example') window = Gtk.Window(title='XVerticalBar example')
window.set_default_size(92, 232) window.set_default_size(192, 232)
window.connect("destroy", Gtk.main_quit) window.connect("destroy", Gtk.main_quit)
vbox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, vbox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL,
spacing=0) spacing=0)
+2
View File
@@ -83,6 +83,8 @@ MONITOR_TABLES = {
_label(), _label(),
PropDef("segments", "Str", "", 0, 0, (), (), PropDef("segments", "Str", "", 0, 0, (), (),
"Segments", False), "Segments", False),
# Unit for the "total <sum> <unit>" header (e.g. GiB).
_unit(),
), ),
"XVerticalBar": ( "XVerticalBar": (
_label(), _label(),
File diff suppressed because it is too large. Load diff
+420 -225
View File
@@ -39,6 +39,7 @@ from lightgui.xframe.core import (
_rounded_box, _rounded_box,
_rounded_path, _rounded_path,
_text_width, _text_width,
_wrap_lines,
_wtext, _wtext,
parse_color, parse_color,
) )
@@ -105,6 +106,23 @@ def _fmt_bytes(nbytes):
return "%.1f TiB" % value 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): def _fmt_uptime(seconds):
"""'up 2d 14:21' from a seconds count.""" """'up 2d 14:21' from a seconds count."""
seconds = max(0, int(seconds)) seconds = max(0, int(seconds))
@@ -153,58 +171,16 @@ def _read_cpu_times():
return None return None
# (pid, starttime) -> user name, so a rescan only opens /proc/<pid>/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/<pid>/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(): def _read_processes():
"""Live process rows from /proc: dicts with pid, name, user, """Live process rows from /proc: dicts with pid, name, user,
mem_kb, utime, stime -- plus an internal ``t`` (monotonic time mem_kb, utime, stime -- plus an internal ``t`` (monotonic time
the stat was read, used for per-process CPU% denominators and the stat was read, used for per-process CPU% denominators and
stripped before the rows reach the widget). Returns None when stripped before the rows reach the widget). Returns None when
/proc is unavailable. /proc is unavailable."""
""" try:
import pwd
except ImportError: # pragma: no cover - non-Unix
pwd = None
rows = [] rows = []
try: try:
pids = [d for d in os.listdir("/proc") if d.isdigit()] pids = [d for d in os.listdir("/proc") if d.isdigit()]
@@ -219,9 +195,20 @@ def _read_processes():
rest = data[rparen + 2:].split() rest = data[rparen + 2:].split()
utime = int(rest[11]) utime = int(rest[11])
stime = int(rest[12]) stime = int(rest[12])
starttime = int(rest[19]) with open("/proc/%s/status" % pid) as handle:
mem_kb = int(rest[21]) * _PAGE_KB uid = None
user = _user_for(pid, starttime) 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, rows.append({"pid": int(pid), "name": comm, "user": user,
"mem_kb": mem_kb, "utime": utime, "mem_kb": mem_kb, "utime": utime,
"stime": stime, "cpu": 0.0, "stime": stime, "cpu": 0.0,
@@ -323,16 +310,18 @@ def _panel(cr, widget, title=None):
_rounded_box(cr, 0, 0, widget.width, widget.height, _PANEL, _rounded_box(cr, 0, 0, widget.width, widget.height, _PANEL,
_PANEL_EDGE, line_width=1.0, radius=4) _PANEL_EDGE, line_width=1.0, radius=4)
if title: if title:
_wtext(cr, widget, title, 8, 15, size=12, rgb=_TITLE, bold=True, _wtext(cr, widget, title, 8, 17, size=16, rgb=_TITLE, bold=True,
max_width=widget.width - 16) max_width=widget.width - 16)
return 22 return 24
return 6 return 6
def _plot_frame(cr, x, y, w, h, lo, hi, labels=True): 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 """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 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.""" 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: if w <= 0 or h <= 0:
return return
_box(cr, x, y, w, h, _PANEL_INNER, _GRID) _box(cr, x, y, w, h, _PANEL_INNER, _GRID)
@@ -347,16 +336,28 @@ def _plot_frame(cr, x, y, w, h, lo, hi, labels=True):
cr.restore() cr.restore()
if not labels: if not labels:
return return
for frac, label in ((0.0, "%.0f" % lo), (0.5, "%.0f" % ((lo + hi) / 2)), for i in range(5):
(1.0, "%.0f" % hi)): frac = i / 4.0
_ylabel(cr, label, x - 2, y + h - frac * h + 3) 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): def _ylabel(cr, text, x, y, size=8):
"""Small dim right-aligned y-axis label.""" """Small dim right-aligned y-axis label (baseline *y*)."""
cr.save() cr.save()
cr.select_font_face("Sans", 0, 0) cr.select_font_face("Sans", 0, 0)
cr.set_font_size(8) cr.set_font_size(size)
_rgb(cr, _DIM) _rgb(cr, _DIM)
w = cr.text_extents(text)[2] w = cr.text_extents(text)[2]
cr.move_to(x - w, y) cr.move_to(x - w, y)
@@ -364,6 +365,16 @@ def _ylabel(cr, text, x, y):
cr.restore() 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, def _series_line(cr, values, x, y, w, h, lo, hi, color, width=1.5,
fill=False): fill=False):
"""Polyline for *values* (oldest left, newest right) in the """Polyline for *values* (oldest left, newest right) in the
@@ -883,8 +894,8 @@ class MonitorWidget(Widget):
def _cell_layout(self): def _cell_layout(self):
"""(x, y, w, h) per grid cell inside the widget.""" """(x, y, w, h) per grid cell inside the widget."""
cols = 2 if self.width < 300 else 3
count = max(1, len(self._monitors)) count = max(1, len(self._monitors))
cols = max(1, math.ceil(math.sqrt(count)))
rows = (count + cols - 1) // cols rows = (count + cols - 1) // cols
pad, gap = 8, 6 pad, gap = 8, 6
top = 26 top = 26
@@ -924,15 +935,15 @@ class MonitorWidget(Widget):
for i, values in enumerate(series): for i, values in enumerate(series):
cur, mn, mx, avg = _stats(values) cur, mn, mx, avg = _stats(values)
color = _SERIES_COLORS[i % len(_SERIES_COLORS)] color = _SERIES_COLORS[i % len(_SERIES_COLORS)]
_box(cr, 8, y - 8, 8, 8, color, color) _box(cr, 8, y - 10, 10, 10, color, color)
if cur is None: if cur is None:
line = "%s --" % names[i] line = "%s --" % names[i]
else: else:
line = "%s %.1f%s min %.1f max %.1f avg %.1f" % ( line = "%s %.1f%s min %.1f max %.1f avg %.1f" % (
names[i], cur, unit, mn, mx, avg) names[i], cur, unit, mn, mx, avg)
_wtext(cr, self, line, 22, y, size=10, rgb=_TEXT, _wtext(cr, self, line, 24, y, size=14, rgb=_TEXT,
max_width=self.width - 28) max_width=self.width - 30)
y += 14 y += 18
return y return y
def _draw_history_graph(self, cr): def _draw_history_graph(self, cr):
@@ -944,16 +955,26 @@ class MonitorWidget(Widget):
series = self._plot_series() series = self._plot_series()
names = self._series_names() names = self._series_names()
show_legend = _prop_bool(self, "show-legend", True) show_legend = _prop_bool(self, "show-legend", True)
legend_h = 14 * len(series) if show_legend else 0 body_px = _fpx(0.032 * self.height, 11, 16)
plot_x, plot_y = 34, top + 2 legend_h = 18 * len(series) if show_legend else 0
plot_w = max(1, self.width - 40) legend_y = top + 13
plot_h = max(1, self.height - plot_y - legend_h - 6) if show_legend:
_plot_frame(cr, plot_x, plot_y, plot_w, plot_h, lo, hi) 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): for i, values in enumerate(series):
_series_line(cr, values, plot_x, plot_y, plot_w, plot_h, _series_line(cr, values, plot_x, plot_y, plot_w, plot_h,
lo, hi, _SERIES_COLORS[i % len(_SERIES_COLORS)]) lo, hi, _SERIES_COLORS[i % len(_SERIES_COLORS)])
if show_legend: # Time axis: "-60s" left, "now" right.
self._legend(cr, plot_y + plot_h + 12, series, names) 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): def _draw_core_grid(self, cr):
top = _panel(cr, self, self._title()) top = _panel(cr, self, self._title())
@@ -964,6 +985,7 @@ class MonitorWidget(Widget):
pad, gap = 6, 4 pad, gap = 6, 4
cw = (self.width - 2 * pad - (cols - 1) * gap) / cols cw = (self.width - 2 * pad - (cols - 1) * gap) / cols
ch = (self.height - top - pad - (rows - 1) * gap) / rows ch = (self.height - top - pad - (rows - 1) * gap) / rows
cell_px = _fpx(0.10 * ch, 11, 16)
for i, values in enumerate(series): for i, values in enumerate(series):
r, c = divmod(i, cols) r, c = divmod(i, cols)
x = pad + c * (cw + gap) x = pad + c * (cw + gap)
@@ -972,14 +994,15 @@ class MonitorWidget(Widget):
radius=3) radius=3)
color = _SERIES_COLORS[i % len(_SERIES_COLORS)] color = _SERIES_COLORS[i % len(_SERIES_COLORS)]
cur = values[-1] if values else 0.0 cur = values[-1] if values else 0.0
_wtext(cr, self, "C%d" % i, x + 6, y + 13, size=10, _wtext(cr, self, "C%d" % i, x + 6, y + cell_px + 2,
rgb=_DIM, bold=True) size=cell_px, rgb=_DIM, bold=True)
_wtext(cr, self, "%.0f%%" % cur, x + cw - 6, y + 13, _wtext(cr, self, "%.0f%%" % cur, x + cw - 6,
size=10, rgb=color, align="right", bold=True) y + cell_px + 2, size=cell_px, rgb=color,
align="right", bold=True)
if ch > 26: if ch > 26:
_series_line(cr, values, x + 3, y + 17, cw - 6, _series_line(cr, values, x + 3, y + cell_px + 7, cw - 6,
ch - 20, 0.0, 100.0, color, width=1.0, ch - cell_px - 10, 0.0, 100.0, color,
fill=True) width=1.0, fill=True)
def _draw_net_graph(self, cr): def _draw_net_graph(self, cr):
top = _panel(cr, self, self._title()) top = _panel(cr, self, self._title())
@@ -987,27 +1010,42 @@ class MonitorWidget(Widget):
peak = max(max(down) if down else 0.0, peak = max(max(down) if down else 0.0,
max(up) if up else 0.0) max(up) if up else 0.0)
hi = max(1.0, peak * 1.15) hi = max(1.0, peak * 1.15)
plot_x, plot_y = 34, top + 2 body_px = _fpx(0.032 * self.height, 11, 16)
plot_w = max(1, self.width - 40) # Legend on top: one line per direction, split into rate /
plot_h = max(1, self.height - plot_y - 34) # total lines when the full line would clip at the right edge.
_plot_frame(cr, plot_x, plot_y, plot_w, plot_h, 0.0, hi) 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, _series_line(cr, down, plot_x, plot_y, plot_w, plot_h, 0.0, hi,
_GREEN) _GREEN)
_series_line(cr, up, plot_x, plot_y, plot_w, plot_h, 0.0, hi, _series_line(cr, up, plot_x, plot_y, plot_w, plot_h, 0.0, hi,
_CYAN) _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): def _draw_temp_history(self, cr):
top = _panel(cr, self, self._title()) top = _panel(cr, self, self._title())
@@ -1016,13 +1054,18 @@ class MonitorWidget(Widget):
lo, hi = 0.0, max(100.0, threshold + 20.0) lo, hi = 0.0, max(100.0, threshold + 20.0)
cur = values[-1] if values else 0.0 cur = values[-1] if values else 0.0
cur_rgb = _RED if cur > threshold else _TEXT cur_rgb = _RED if cur > threshold else _TEXT
_wtext(cr, self, "%.1f C" % cur, self.width - 8, 15, size=14, body_px = _fpx(0.032 * self.height, 11, 16)
rgb=cur_rgb, align="right", bold=True) _wtext(cr, self, "%.1f C" % cur, self.width - 8, 17,
plot_x, plot_y = 34, top + 2 size=_fpx(0.032 * self.height, 11, 16), rgb=cur_rgb,
plot_w = max(1, self.width - 40) 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_h = max(1, self.height - plot_y - 20)
_plot_frame(cr, plot_x, plot_y, plot_w, plot_h, lo, hi) _plot_frame(cr, plot_x, plot_y, plot_w, plot_h, lo, hi,
# Threshold line (dashed red) + label. 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 thr_y = plot_y + plot_h - (threshold - lo) / (hi - lo) * plot_h
cr.save() cr.save()
_rgb(cr, _RED) _rgb(cr, _RED)
@@ -1032,8 +1075,9 @@ class MonitorWidget(Widget):
cr.line_to(plot_x + plot_w, thr_y) cr.line_to(plot_x + plot_w, thr_y)
cr.stroke() cr.stroke()
cr.restore() cr.restore()
_wtext(cr, self, "%.0f C" % threshold, plot_x + plot_w - 2, _wtext(cr, self, "%.0f C limit" % threshold,
thr_y - 3, size=9, rgb=_RED, align="right") 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, _series_line(cr, values, plot_x, plot_y, plot_w, plot_h, lo, hi,
_CYAN) _CYAN)
# Red overlay where the line runs over the threshold. # Red overlay where the line runs over the threshold.
@@ -1064,7 +1108,7 @@ class MonitorWidget(Widget):
_wtext(cr, self, "min %.1f max %.1f avg %.1f" _wtext(cr, self, "min %.1f max %.1f avg %.1f"
% (min(values), max(values), % (min(values), max(values),
sum(values) / len(values)), sum(values) / len(values)),
8, plot_y + plot_h + 13, size=10, rgb=_DIM) 8, plot_y + plot_h + 14, size=13, rgb=_DIM)
def _gradient_bar(self, cr, x, y, w, h, frac, horizontal=True): def _gradient_bar(self, cr, x, y, w, h, frac, horizontal=True):
"""Trough + green->yellow->red gradient fill to *frac*.""" """Trough + green->yellow->red gradient fill to *frac*."""
@@ -1098,19 +1142,66 @@ class MonitorWidget(Widget):
def _draw_usage_bar(self, cr): def _draw_usage_bar(self, cr):
frac = _range_frac(self) frac = _range_frac(self)
self._gradient_bar(cr, 0, 0, self.width, self.height, frac)
label = self.get_prop("label", "") or self.kind label = self.get_prop("label", "") or self.kind
value = _prop_float(self, "value", 0.0) value = _prop_float(self, "value", 0.0)
_wtext(cr, self, label, 8, self.height / 2 + 5, size=12, # Dark panel first: the labels sit outside the bar, and
rgb=_WHITE, bold=True, max_width=self.width / 2) # without it they are white text on the window background.
_wtext(cr, self, "%.0f%%" % value, self.width - 8, _panel(cr, self)
self.height / 2 + 5, size=12, rgb=_WHITE, align="right", # 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) 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): def _draw_stack_bar(self, cr):
segments = self.get_segments() segments = self.get_segments()
total = sum(v for _label, v, _c in segments) or 1.0 total = sum(v for _label, v, _c in segments) or 1.0
bar_y, bar_h = 4, 16 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 x = 0.0
for label, value, color in segments: for label, value, color in segments:
seg_w = self.width * value / total seg_w = self.width * value / total
@@ -1118,18 +1209,16 @@ class MonitorWidget(Widget):
continue continue
_box(cr, x, bar_y, max(0, seg_w - 1), bar_h, color, color) _box(cr, x, bar_y, max(0, seg_w - 1), bar_h, color, color)
x += seg_w x += seg_w
# Legend: color chip + "label 45%" flowing left to right, ly = bar_y + bar_h + 8 + legend_px
# wrapping to a second row when the width runs out. for row in rows:
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 lx = 6
ly += 14 for label, value, color, text, tw in row:
_box(cr, lx, ly - 8, 8, 8, color, color) _box(cr, lx, ly - legend_px * 0.7, legend_px * 0.7,
_wtext(cr, self, text, lx + 12, ly, size=10, rgb=_TEXT) legend_px * 0.7, color, color)
_wtext(cr, self, text, lx + legend_px, ly,
size=legend_px, rgb=_TEXT)
lx += tw lx += tw
ly += row_h
def _draw_vertical_bar(self, cr): def _draw_vertical_bar(self, cr):
frac = _range_frac(self) frac = _range_frac(self)
@@ -1142,15 +1231,30 @@ class MonitorWidget(Widget):
self._peak = peak self._peak = peak
lo = _prop_float(self, "minimum", 0.0) lo = _prop_float(self, "minimum", 0.0)
hi = _prop_float(self, "maximum", 100.0) hi = _prop_float(self, "maximum", 100.0)
_panel(cr, self) top = _panel(cr, self, self._title())
bar_x, bar_w = 26, self.width - 34 body_px = _fpx(0.03 * self.height, 11, 16)
bar_y, bar_h = 10, self.height - 34 # 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, self._gradient_bar(cr, bar_x, bar_y, bar_w, bar_h, frac,
horizontal=False) horizontal=False)
# Scale labels + ticks on the left. # Scale labels + ticks on the left.
for f in (0.0, 0.25, 0.5, 0.75, 1.0): for f in (0.0, 0.25, 0.5, 0.75, 1.0):
gy = bar_y + bar_h - f * bar_h gy = bar_y + bar_h - f * bar_h
_ylabel(cr, "%.0f" % (lo + f * (hi - lo)), bar_x - 4, gy + 3) 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() cr.save()
_rgb(cr, _GRID) _rgb(cr, _GRID)
cr.set_line_width(1) cr.set_line_width(1)
@@ -1158,7 +1262,8 @@ class MonitorWidget(Widget):
cr.line_to(bar_x, gy) cr.line_to(bar_x, gy)
cr.stroke() cr.stroke()
cr.restore() cr.restore()
# Peak-hold marker. # Peak-hold marker + label (bold, above the line, inset from
# the frame edge).
if peak > lo: if peak > lo:
py = bar_y + bar_h - (peak - lo) / (hi - lo) * bar_h \ py = bar_y + bar_h - (peak - lo) / (hi - lo) * bar_h \
if hi > lo else bar_y if hi > lo else bar_y
@@ -1169,12 +1274,20 @@ class MonitorWidget(Widget):
cr.line_to(bar_x + bar_w + 2, py) cr.line_to(bar_x + bar_w + 2, py)
cr.stroke() cr.stroke()
cr.restore() cr.restore()
_wtext(cr, self, "%.0f%%" % value, self.width / 2, _wtext(cr, self, "peak %.0f" % peak, bar_x + bar_w - 2,
self.height - 8, size=11, rgb=_TEXT, align="center", py - 6, size=_peak_fit(cr, self, peak, bar_x, bar_w),
bold=True) 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): def _draw_tachometer(self, cr):
top = _panel(cr, self, self._title()) top = _panel(cr, self)
lo = _prop_float(self, "minimum", 0.0) lo = _prop_float(self, "minimum", 0.0)
hi = _prop_float(self, "maximum", 8000.0) hi = _prop_float(self, "maximum", 8000.0)
if hi <= lo: if hi <= lo:
@@ -1203,7 +1316,9 @@ class MonitorWidget(Widget):
_RED, 10, cap=1) _RED, 10, cap=1)
_arc_stroke(cr, cx, cy, r, start, _angle(frac), _CYAN, 10, _arc_stroke(cr, cx, cy, r, start, _angle(frac), _CYAN, 10,
cap=1) cap=1)
# Ticks + numbers. # 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() cr.save()
for i in range(11): for i in range(11):
f = i / 10.0 f = i / 10.0
@@ -1220,10 +1335,20 @@ class MonitorWidget(Widget):
cr.restore() cr.restore()
if major: if major:
label = "%.0f" % (lo + f * (hi - lo)) label = "%.0f" % (lo + f * (hi - lo))
lx = cx + (r - 26) * math.cos(ang) # Numeral centre radius: the glyph box's farthest
ly = cy + (r - 26) * math.sin(ang) + 3 # corner in the radial direction must stay inside the
_wtext(cr, self, label, lx, ly, size=9, rgb=_TEXT, # tick ring (inner end r-16) with 4 px clearance, so a
align="center") # wide 4-digit label never crosses the dial rim.
lw = _text_width(cr, self, label, size=numeral_px, bold=True)
extent = (lw / 2) * abs(math.cos(ang)) \
+ (numeral_px / 2) * abs(math.sin(ang))
lr = max(8.0, r - 16 - extent - 4)
lx = cx + lr * math.cos(ang)
ly = cy + lr * 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. # Peak-hold tick.
cr.save() cr.save()
_rgb(cr, _WHITE) _rgb(cr, _WHITE)
@@ -1249,13 +1374,21 @@ class MonitorWidget(Widget):
cr.arc(cx, cy, 6, 0, 2 * math.pi) cr.arc(cx, cy, 6, 0, 2 * math.pi)
cr.fill() cr.fill()
cr.restore() cr.restore()
# Digital readout: below the hub, clear of the 0/max tick # Title bold and centred inside the dial, below the top
# labels at the bottom of the dial. # 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", "") 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: if unit:
_wtext(cr, self, unit, cx, cy + r * 0.80 + 14, size=10, _wtext(cr, self, unit, cx, cy + r * 0.80 + 16, size=12,
rgb=_DIM, align="center") rgb=_DIM, align="center")
def _draw_arc_gauge(self, cr): def _draw_arc_gauge(self, cr):
@@ -1263,8 +1396,8 @@ class MonitorWidget(Widget):
frac = _range_frac(self) frac = _range_frac(self)
value = _prop_float(self, "value", 0.0) value = _prop_float(self, "value", 0.0)
cx = self.width / 2 cx = self.width / 2
cy = self.height - 14 cy = self.height - 32
r = min(self.width / 2 - 12, self.height - top - 22) r = min(self.width / 2 - 12, self.height - top - 40)
if r <= 0: if r <= 0:
return return
zones = ((0.0, 0.6, _GREEN), (0.6, 0.8, _YELLOW), zones = ((0.0, 0.6, _GREEN), (0.6, 0.8, _YELLOW),
@@ -1276,61 +1409,72 @@ class MonitorWidget(Widget):
math.pi + f1 * math.pi, color, 12) math.pi + f1 * math.pi, color, 12)
_arc_stroke(cr, cx, cy, r, math.pi, math.pi + frac * math.pi, _arc_stroke(cr, cx, cy, r, math.pi, math.pi + frac * math.pi,
_WHITE, 12) _WHITE, 12)
_wtext(cr, self, "%.0f%%" % value, cx, cy - r * 0.45, size=22, centre_px = _fpx(0.10 * 2 * r, 16, 48)
rgb=_WHITE, align="center", bold=True) _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" label = self.get_prop("unit", "") or "usage"
_wtext(cr, self, label, cx, cy - r * 0.45 + 16, size=10, _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") rgb=_DIM, align="center")
def _draw_donut_gauge(self, cr): def _draw_donut_gauge(self, cr):
top = _panel(cr, self, self._title()) # No top-left title: the centre label carries the value name
# (the title would duplicate it).
top = _panel(cr, self)
frac = _range_frac(self) frac = _range_frac(self)
value = _prop_float(self, "value", 0.0) value = _prop_float(self, "value", 0.0)
cx = self.width / 2 cx = self.width / 2
cy = top + (self.height - top) / 2 cy = top + (self.height - top) / 2
r = min(self.width, self.height - top) / 2 - 12 r0 = min(self.width, self.height - top) / 2 - 12
if r <= 0: if r0 <= 0:
return 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, _arc_stroke(cr, cx, cy, r, 0, 2 * math.pi,
(0.25, 0.25, 0.28), 14, cap=1) (0.25, 0.25, 0.28), thick, cap=1)
_arc_stroke(cr, cx, cy, r, -math.pi / 2, _arc_stroke(cr, cx, cy, r, -math.pi / 2,
-math.pi / 2 + frac * 2 * math.pi, _GREEN, 14, -math.pi / 2 + frac * 2 * math.pi, _GREEN, thick,
cap=1) cap=1)
_wtext(cr, self, "%.0f%%" % value, cx, cy + 7, size=20, centre_px = _fpx(0.10 * 2 * r, 16, 44)
rgb=_WHITE, align="center", bold=True) _wtext(cr, self, "%.0f%%" % value, cx, cy + centre_px * 0.35,
label = self.get_prop("unit", "") or self.kind size=centre_px, rgb=_WHITE, align="center", bold=True)
_wtext(cr, self, label, cx, cy + 24, size=10, rgb=_DIM, 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) align="center", max_width=self.width - 16)
def _draw_process_list(self, cr): def _draw_process_list(self, cr):
top = _panel(cr, self, self._title()) top = _panel(cr, self, self._title())
rows = self._sorted_rows() rows = self._sorted_rows()
# Column x-offsets as fractions of the inner width (same _wtext(cr, self, "%d procs" % len(rows), self.width - 8, 17,
# fractions as the C++ widget: PID / Program / User / Mem / size=13, rgb=_DIM, align="right")
# CPU%). The old fixed offsets were drawn for the 360px demo cols = ((6, 52, "PID", "left"), (62, 130, "Program", "left"),
# widget and left a wide widget mostly empty. (196, 44, "User", "left"), (248, 52, "Mem", "right"),
iw = max(60, self.width - 12) (308, 48, "CPU%", "right"))
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_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) sort_desc = _prop_bool(self, "sort-desc", True)
headers = [(xs[0], "PID", 2, "left"), (xs[1], "Program", 3, "left"), header_y = top + 15
(xs[2], "User", None, "left"), (xs[4], "Mem", 1, "right"), for x, _w, name, align in cols:
(xs[5], "CPU%", 0, "right")] if name == sort_key:
header_y = top + 13 name = name + (" \u25bc" if sort_desc else " \u25b2")
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": if align == "right":
_wtext(cr, self, label, x - 4, header_y, size=10, _wtext(cr, self, name, x + _w, header_y, size=13,
rgb=_DIM, align="right", bold=True) rgb=_DIM, align="right", bold=True)
else: else:
_wtext(cr, self, label, x, header_y, size=10, _wtext(cr, self, name, x, header_y, size=13,
rgb=_DIM, bold=True) rgb=_DIM, bold=True)
row_h = 18 row_h = 23
y0 = top + 18 y0 = top + 24
visible = max(0, (self.height - y0) // row_h) visible = max(0, (self.height - y0) // row_h)
for i, row in enumerate(rows[:visible]): for i, row in enumerate(rows[:visible]):
y = y0 + i * row_h y = y0 + i * row_h
@@ -1343,42 +1487,52 @@ class MonitorWidget(Widget):
_rgb(cr, _AMBER, 0.12) _rgb(cr, _AMBER, 0.12)
cr.rectangle(0, y, self.width, row_h) cr.rectangle(0, y, self.width, row_h)
cr.fill() cr.fill()
_wtext(cr, self, str(row["pid"]), xs[0], y + 13, size=10, _wtext(cr, self, str(row["pid"]), 6, y + 16, size=13,
rgb=_TEXT) rgb=_TEXT)
_wtext(cr, self, row["name"], xs[1], y + 13, size=10, _wtext(cr, self, row["name"], 62, y + 16, size=13,
rgb=_TEXT, rgb=_TEXT,
max_width=xs[2] - xs[1] - 6) max_width=128)
_wtext(cr, self, row["user"], xs[2], y + 13, size=10, _wtext(cr, self, row["user"], 196, y + 16, size=13,
rgb=_TEXT, max_width=xs[3] - xs[2] - 6) rgb=_TEXT, max_width=44)
_wtext(cr, self, _fmt_bytes(row["mem_kb"] * 1024), xs[4] - 4, _wtext(cr, self, _fmt_bytes(row["mem_kb"] * 1024), 300,
y + 13, size=10, rgb=_TEXT, align="right") y + 16, size=13, rgb=_TEXT, align="right")
# In-cell CPU% bar behind the number. # In-cell CPU% bar behind the number (colour-coded).
bar_x, bar_w = xs[4] + 2, xs[5] - xs[4] - 6 bar_x, bar_w = 308, 48
_box(cr, bar_x, y + 3, bar_w, 12, (0.20, 0.20, 0.23), _box(cr, bar_x, y + 5, bar_w, 12, (0.20, 0.20, 0.23),
(0.20, 0.20, 0.23)) (0.20, 0.20, 0.23))
fill = max(0, bar_w * min(1.0, cpu / 100.0)) fill = max(0, bar_w * min(1.0, cpu / 100.0))
if fill > 0: if fill > 0:
color = _GREEN if cpu < 50 else \ color = _GREEN if cpu < 50 else \
_AMBER if cpu < 80 else _RED _AMBER if cpu < 80 else _RED
_box(cr, bar_x, y + 3, fill, 12, color, color) _box(cr, bar_x, y + 5, fill, 12, color, color)
_wtext(cr, self, "%.1f" % cpu, bar_x + bar_w - 3, y + 13, _wtext(cr, self, "%.1f" % cpu, bar_x + bar_w - 3, y + 16,
size=10, rgb=_WHITE, align="right", bold=True) size=13, rgb=_WHITE, align="right", bold=True)
def _draw_load_badge(self, cr): def _draw_load_badge(self, cr):
_panel(cr, self) _panel(cr, self)
load1, load5, load15, uptime = self._load_values() load1, load5, load15, uptime = self._load_values()
ncores = os.cpu_count() or 1 ncores = os.cpu_count() or 1
_wtext(cr, self, "Load", 8, 24, size=13, rgb=_DIM, bold=True) # Two-line layout, value block vertically centred. (No 1/5/15
x = 52 # 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): for load in (load1, load5, load15):
per_core = load / ncores per_core = load / ncores
color = _GREEN if per_core < 0.7 else \ color = _GREEN if per_core < 0.7 else \
_AMBER if per_core < 1.0 else _RED _AMBER if per_core < 1.0 else _RED
text = "%.2f" % load text = "%.2f" % load
_wtext(cr, self, text, x, 24, size=13, rgb=color, bold=True) _wtext(cr, self, text, x, val_base, size=val_px,
x += _text_width(cr, self, text, size=13, bold=True) + 12 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), _wtext(cr, self, "%s %d cores" % (_fmt_uptime(uptime), ncores),
8, 46, size=11, rgb=_TEXT) 8, val_base + 28, size=14, rgb=_TEXT)
def _draw_monitor_button(self, cr): def _draw_monitor_button(self, cr):
status = self._status status = self._status
@@ -1395,31 +1549,40 @@ class MonitorWidget(Widget):
cr.restore() cr.restore()
_rounded_box(cr, 0, 0, self.width, self.height, _PANEL_INNER, _rounded_box(cr, 0, 0, self.width, self.height, _PANEL_INNER,
color, line_width=1.5, radius=6) 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) _rgb(cr, color)
cr.arc(18, self.height / 2, 7, 0, 2 * math.pi) cr.arc(dot_cx, mid_y, dot_r, 0, 2 * math.pi)
cr.fill() cr.fill()
if status == "up": if status == "up":
_rgb(cr, _WHITE) _rgb(cr, _WHITE)
cr.arc(18, self.height / 2, 2.5, 0, 2 * math.pi) cr.arc(dot_cx, mid_y, dot_r * 0.35, 0, 2 * math.pi)
cr.fill() cr.fill()
label = self.get_prop("label", "") or self.get_prop("target", "") \ label = self.get_prop("label", "") or self.get_prop("target", "") \
or self.kind or self.kind
status_text = _STATUS_LABELS[status] status_text = _STATUS_LABELS[status]
sw = _text_width(cr, self, status_text, size=12, bold=True) label_px = _fpx(0.10 * self.height, 13, 24)
mid_y = self.height / 2 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: if self._detail:
_wtext(cr, self, label, 32, mid_y - 1, size=13, rgb=_WHITE, _wtext(cr, self, label, label_x, mid_y - 2, size=label_px,
bold=True, rgb=_WHITE, bold=True, max_width=max_w)
max_width=self.width - 40 - sw - 8) _wtext(cr, self, self._detail, label_x,
_wtext(cr, self, self._detail, 32, mid_y + 14, size=10, mid_y + detail_px + 2, size=detail_px, rgb=_DIM,
rgb=_DIM, max_width=max_w)
max_width=self.width - 40 - sw - 8)
else: else:
_wtext(cr, self, label, 32, mid_y + 5, size=13, rgb=_WHITE, _wtext(cr, self, label, label_x, mid_y + label_px * 0.35,
bold=True, size=label_px, rgb=_WHITE, bold=True,
max_width=self.width - 40 - sw - 8) max_width=max_w)
_wtext(cr, self, status_text, self.width - 8, mid_y + 5, _wtext(cr, self, status_text, self.width - 8,
size=12, rgb=color, align="right", bold=True) mid_y + status_px * 0.35, size=status_px, rgb=color,
align="right", bold=True)
def _draw_monitor_grid(self, cr): def _draw_monitor_grid(self, cr):
top = _panel(cr, self, self._title()) top = _panel(cr, self, self._title())
@@ -1428,6 +1591,13 @@ class MonitorWidget(Widget):
self.width / 2, self.height / 2 + 5, size=11, self.width / 2, self.height / 2 + 5, size=11,
rgb=_DIM, align="center") rgb=_DIM, align="center")
return 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()): for i, (x, y, w, h) in enumerate(self._cell_layout()):
if i >= len(self._monitors): if i >= len(self._monitors):
break break
@@ -1435,16 +1605,36 @@ class MonitorWidget(Widget):
color = _STATUS_COLORS[monitor["status"]] color = _STATUS_COLORS[monitor["status"]]
_rounded_box(cr, x, y, w, h, _PANEL_INNER, color, _rounded_box(cr, x, y, w, h, _PANEL_INNER, color,
line_width=1.0, radius=4) 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) _rgb(cr, color)
cr.arc(x + 12, y + h / 2, 5, 0, 2 * math.pi) cr.arc(dot_cx, mid_y, dot_r, 0, 2 * math.pi)
cr.fill() cr.fill()
label = monitor["label"] label_px = _fpx(0.10 * h, 13, 20)
_wtext(cr, self, label, x + 24, y + h / 2 - 1, size=11, status_px = _fpx(0.09 * h, 12, 18)
rgb=_WHITE, bold=True, max_width=w - 30) detail_px = _fpx(0.06 * h, 11, 14)
status_text = "%s - %s" % ( label_x = dot_cx + dot_r + 10
_STATUS_LABELS[monitor["status"]], monitor["detail"]) status_text = _STATUS_LABELS[monitor["status"]]
_wtext(cr, self, status_text, x + 24, y + h / 2 + 13, sw = _text_width(cr, self, status_text, size=status_px,
size=9, rgb=_DIM, max_width=w - 30) 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): def _draw_sys_box(self, cr):
top = _panel(cr, self, self._title()) top = _panel(cr, self, self._title())
@@ -1454,24 +1644,29 @@ class MonitorWidget(Widget):
hi = _prop_float(self, "maximum", 100.0) hi = _prop_float(self, "maximum", 100.0)
if hi <= lo: if hi <= lo:
hi = lo + 100.0 hi = lo + 100.0
_wtext(cr, self, "%.0f" % value, 8, top + 26, size=26, hero_px = _fpx(0.10 * self.height, 20, 32)
rgb=_WHITE, bold=True) _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, _wtext(cr, self, unit, 8 + _text_width(cr, self, "%.0f" % value,
size=26, bold=True) + 6, size=hero_px,
top + 26, size=12, rgb=_DIM) 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) values = self._single_series(55.0, 28.0, lo, hi)
graph_y = top + 34 graph_y = top + hero_px + 10
graph_h = max(1, self.height - graph_y - 26) 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, _plot_frame(cr, 8, graph_y, self.width - 16, graph_h, lo, hi,
labels=False) labels=False)
_series_line(cr, values, 8, graph_y, self.width - 16, graph_h, _series_line(cr, values, 8, graph_y, self.width - 16, graph_h,
lo, hi, _GREEN) lo, hi, _GREEN)
frac = max(0.0, min(1.0, (value - lo) / (hi - lo))) frac = max(0.0, min(1.0, (value - lo) / (hi - lo)))
self._gradient_bar(cr, 8, self.height - 20, self.width - 16, bar_y = self.height - 8 - bar_h
12, frac) self._gradient_bar(cr, 8, bar_y, self.width - 16, bar_h, frac)
_wtext(cr, self, "%.0f%%" % (frac * 100.0), self.width - 12, _wtext(cr, self, "%.0f%%" % (frac * 100.0), self.width - 12,
self.height - 10, size=9, rgb=_WHITE, align="right", bar_y + bar_h / 2 + 5, size=14, rgb=_WHITE,
bold=True) align="right", bold=True)
_MONITOR_DRAW = { _MONITOR_DRAW = {