Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8fb940582e | ||
|
|
16ebfd719b | ||
|
|
da3a9d3343 | ||
|
|
66ba965206 | ||
|
|
a6b084e214 | ||
|
|
512fdd5ecf | ||
|
|
7d512cf5af | ||
|
|
9bb8f27603 | ||
|
|
0934970206 | ||
|
|
00ea2f43af | ||
|
|
b197a366ec | ||
|
|
fc040ef4b2 | ||
|
|
11f7dd70e6 | ||
|
|
b4add9ba7b | ||
|
|
9cbabb9d71 | ||
|
|
05b1b0f7c1 | ||
|
|
38f91c57eb | ||
|
|
e1da839538 | ||
|
|
1c33577bb9 |
No files matched your search
@@ -0,0 +1,30 @@
|
|||||||
|
# CPU Dashboard — monitor (Python)
|
||||||
|
|
||||||
|
A btop-style CPU dashboard in one 1024x768 window, built only from
|
||||||
|
LightGUI XFrame monitor widgets:
|
||||||
|
|
||||||
|
- **XCoreGrid** — per-core mini history graphs
|
||||||
|
- **XTachometer** — big total-CPU % gauge (redline 80%)
|
||||||
|
- **XHistoryGraph** — total CPU % over the last 60 s
|
||||||
|
- **XLoadBadge** — load average 1/5/15 min + uptime
|
||||||
|
- **XUsageBar** — total CPU % bar
|
||||||
|
|
||||||
|
Live data comes from `/proc/stat` (per-core busy %, via
|
||||||
|
`XCoreGrid.refresh_cores()`) and `/proc/loadavg` (via
|
||||||
|
`XLoadBadge.refresh_load()`), sampled every 500 ms. Pushing live
|
||||||
|
samples starts fresh series, so the deterministic demo data is
|
||||||
|
replaced on the first live sample.
|
||||||
|
|
||||||
|
## Run
|
||||||
|
|
||||||
|
```sh
|
||||||
|
PYTHONPATH=. python3 examples/monitor_cpu_dashboard/main.py
|
||||||
|
```
|
||||||
|
|
||||||
|
Esc, `q`, or closing the window quits.
|
||||||
|
|
||||||
|
## Source
|
||||||
|
|
||||||
|
- App: `examples/monitor_cpu_dashboard/main.py`
|
||||||
|
- Widgets: `lightgui/xframe/monitor.py`
|
||||||
|
- Repo: https://github.com/cnmcdee/lightgui_python
|
||||||
@@ -0,0 +1,138 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""CPU Dashboard - monitor (Python).
|
||||||
|
|
||||||
|
A btop-style CPU dashboard in one 1024x768 window, built only from
|
||||||
|
LightGUI XFrame monitor widgets (XCoreGrid, XTachometer,
|
||||||
|
XHistoryGraph, XLoadBadge, XUsageBar). Live data from /proc/stat
|
||||||
|
(per-core busy %, via XCoreGrid.refresh_cores()) and /proc/loadavg
|
||||||
|
(via XLoadBadge.refresh_load()), sampled every 500 ms. The
|
||||||
|
deterministic demo data each widget draws with no data pushed is
|
||||||
|
replaced on the first live sample: push() / push_core() start fresh
|
||||||
|
series, and the histories are primed with the first live value.
|
||||||
|
|
||||||
|
Run with:
|
||||||
|
PYTHONPATH=/root/monitor-wt/cpu-dashboard/lightgui_python python3 \\
|
||||||
|
examples/monitor_cpu_dashboard/main.py
|
||||||
|
(or from the repo root with PYTHONPATH=. )
|
||||||
|
"""
|
||||||
|
|
||||||
|
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
|
||||||
|
|
||||||
|
_TITLE = "CPU Dashboard - monitor"
|
||||||
|
_DESIGN_SIZE = (1024, 768)
|
||||||
|
_BACKGROUND = ""
|
||||||
|
_WIDGETS = []
|
||||||
|
_AREA = []
|
||||||
|
_PRIMED = [False]
|
||||||
|
|
||||||
|
|
||||||
|
def _build_widgets():
|
||||||
|
"""Create every placed widget with its props."""
|
||||||
|
widgets = []
|
||||||
|
|
||||||
|
badge = create("XLoadBadge", "LoadBadge_001", 16, 16, 320, 84)
|
||||||
|
badge.set_prop("label", "Load avg")
|
||||||
|
badge.refresh_load()
|
||||||
|
widgets.append(badge)
|
||||||
|
|
||||||
|
bar = create("XUsageBar", "UsageBar_001", 352, 16, 656, 84)
|
||||||
|
bar.set_prop("label", "Total CPU")
|
||||||
|
bar.set_prop("minimum", "0")
|
||||||
|
bar.set_prop("maximum", "100")
|
||||||
|
widgets.append(bar)
|
||||||
|
|
||||||
|
grid = create("XCoreGrid", "CoreGrid_001", 16, 116, 640, 300)
|
||||||
|
grid.set_prop("label", "CPU cores")
|
||||||
|
grid.set_prop("cores", "8")
|
||||||
|
widgets.append(grid)
|
||||||
|
|
||||||
|
tacho = create("XTachometer", "Tachometer_001", 672, 116, 336, 300)
|
||||||
|
tacho.set_prop("label", "CPU %")
|
||||||
|
tacho.set_prop("minimum", "0")
|
||||||
|
tacho.set_prop("maximum", "100")
|
||||||
|
tacho.set_prop("redline", "80")
|
||||||
|
tacho.set_prop("unit", "%")
|
||||||
|
widgets.append(tacho)
|
||||||
|
|
||||||
|
hist = create("XHistoryGraph", "HistoryGraph_001", 16, 432, 992, 320)
|
||||||
|
hist.set_prop("label", "Total CPU history")
|
||||||
|
hist.set_prop("window", "60")
|
||||||
|
hist.set_prop("minimum", "0")
|
||||||
|
hist.set_prop("maximum", "100")
|
||||||
|
hist.set_prop("series-names", "CPU")
|
||||||
|
widgets.append(hist)
|
||||||
|
|
||||||
|
return widgets
|
||||||
|
|
||||||
|
|
||||||
|
def _tick():
|
||||||
|
"""500 ms tick: feed live samples, then redraw."""
|
||||||
|
badge, bar, grid, tacho, hist = _WIDGETS
|
||||||
|
values = grid.refresh_cores()
|
||||||
|
if values:
|
||||||
|
total = sum(values) / len(values)
|
||||||
|
if not _PRIMED[0]:
|
||||||
|
# First live sample: prime the histories with it so no
|
||||||
|
# seeded demo data is visible (60 = window capacity).
|
||||||
|
for core, value in enumerate(values):
|
||||||
|
for _ in range(59):
|
||||||
|
grid.push_core(core, value)
|
||||||
|
for _ in range(60):
|
||||||
|
hist.push(total)
|
||||||
|
_PRIMED[0] = True
|
||||||
|
else:
|
||||||
|
hist.push(total)
|
||||||
|
tacho.set_value(total)
|
||||||
|
bar.set_value(total)
|
||||||
|
badge.refresh_load()
|
||||||
|
if _AREA:
|
||||||
|
_AREA[0].queue_draw()
|
||||||
|
return True
|
||||||
|
|
||||||
|
|
||||||
|
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:
|
||||||
|
widget.draw(cr)
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
def _on_key_press(window, event):
|
||||||
|
if event.keyval in (Gdk.KEY_Escape, Gdk.KEY_q):
|
||||||
|
Gtk.main_quit()
|
||||||
|
return True
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
window = Gtk.Window(title=_TITLE)
|
||||||
|
window.set_default_size(*_DESIGN_SIZE)
|
||||||
|
window.set_resizable(False)
|
||||||
|
window.connect("destroy", Gtk.main_quit)
|
||||||
|
window.connect("key-press-event", _on_key_press)
|
||||||
|
area = Gtk.DrawingArea()
|
||||||
|
area.set_hexpand(True)
|
||||||
|
area.set_vexpand(True)
|
||||||
|
area.connect("draw", _on_draw)
|
||||||
|
window.add(area)
|
||||||
|
_WIDGETS.extend(_build_widgets())
|
||||||
|
_AREA.append(area)
|
||||||
|
GLib.timeout_add(500, _tick)
|
||||||
|
window.show_all()
|
||||||
|
Gtk.main()
|
||||||
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
import sys
|
||||||
|
sys.exit(main())
|
||||||
|
After Width: | Height: | Size: 48 KiB |
@@ -0,0 +1,47 @@
|
|||||||
|
# Disk Monitor — Python (XFrame)
|
||||||
|
|
||||||
|
A live disk monitor in one 1024x768 window: per-mount usage bars,
|
||||||
|
a Used / Free stack bar for the largest mount, and a read/write
|
||||||
|
throughput history graph. All data is live — `/proc/mounts` +
|
||||||
|
`os.statvfs` for usage, `/proc/diskstats` (sectors differenced once
|
||||||
|
a second) for MB/s. Refreshes every second via `GLib.timeout_add`;
|
||||||
|
close the window to quit.
|
||||||
|
|
||||||
|
## Widgets used
|
||||||
|
|
||||||
|
| Widget | Role |
|
||||||
|
| --- | --- |
|
||||||
|
| XUsageBar | One per disk mount: usage % with total size |
|
||||||
|
| XStackBar | Largest mount split into Used / Free (GiB) |
|
||||||
|
| XHistoryGraph | Read MB/s + Write MB/s history, 60 s window |
|
||||||
|
|
||||||
|
Seeded demo series/segments are replaced by live data on the first
|
||||||
|
tick (`push()` / `set_segments()` start fresh own data, never the
|
||||||
|
demo). The harness background is the widgets' near-black panel color
|
||||||
|
— XStackBar paints no panel of its own, so a white background would
|
||||||
|
wash its light-grey legend out. Note the Python XStackBar draws no
|
||||||
|
title (its draw ignores the `label` prop); the C/Rust ports show
|
||||||
|
"/ disk usage" there.
|
||||||
|
|
||||||
|
**Why no XSysBox:** it has no clear-history API and its
|
||||||
|
constructor seeds 60 demo samples, so it cannot show live disk data
|
||||||
|
without the seeded demo leaking into the history.
|
||||||
|
|
||||||
|
## Build & run
|
||||||
|
|
||||||
|
```sh
|
||||||
|
PYTHONPATH=/root/monitor-wt/disk-monitor/lightgui_python python3 examples/monitor_disk_monitor/main.py
|
||||||
|
```
|
||||||
|
|
||||||
|
## Screenshot
|
||||||
|
|
||||||
|

|
||||||
|
|
||||||
|
## Source
|
||||||
|
|
||||||
|
- App: `examples/monitor_disk_monitor/main.py`
|
||||||
|
- Repo: https://github.com/cnmcdee/lightgui_python
|
||||||
|
- C port: `examples/monitor/disk-monitor/main.cpp`
|
||||||
|
in https://github.com/cnmcdee/lightgui
|
||||||
|
- Rust port: `crates/xframe-demo/examples/monitor_disk_monitor/main.rs`
|
||||||
|
in https://github.com/cnmcdee/lightgui_rust
|
||||||
@@ -0,0 +1,197 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
# Disk Monitor - monitor (Python/XFrame).
|
||||||
|
#
|
||||||
|
# One 1024x768 window: a live XUsageBar per disk mount (/proc/mounts
|
||||||
|
# + os.statvfs), an XStackBar splitting the largest mount into
|
||||||
|
# Used / Free (GiB), and an XHistoryGraph of disk read/write
|
||||||
|
# throughput in MB/s (/proc/diskstats, sectors differenced once a
|
||||||
|
# second). Refreshes every second; close the window to quit.
|
||||||
|
# Seeded demo series/segments are replaced by live data on the first
|
||||||
|
# tick (push()/set_segments() start fresh own data, never the demo).
|
||||||
|
#
|
||||||
|
# XSysBox is deliberately NOT used: it has no clear-history API and
|
||||||
|
# its constructor seeds 60 demo samples, so it cannot show live disk
|
||||||
|
# data without the seeded demo leaking into the history.
|
||||||
|
#
|
||||||
|
# Run with:
|
||||||
|
# PYTHONPATH=/root/monitor-wt/disk-monitor/lightgui_python \
|
||||||
|
# python3 examples/monitor_disk_monitor/main.py
|
||||||
|
# (or from the repo root with PYTHONPATH=.)
|
||||||
|
|
||||||
|
import os
|
||||||
|
import sys
|
||||||
|
|
||||||
|
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 # noqa: E402
|
||||||
|
|
||||||
|
WIN_W, WIN_H = 1024, 768
|
||||||
|
MARGIN = 16
|
||||||
|
BAR_H, BAR_GAP = 44, 8
|
||||||
|
STACK_H = 170
|
||||||
|
REAL_FS = ("ext4", "xfs", "btrfs")
|
||||||
|
GIB = 1024.0 ** 3
|
||||||
|
|
||||||
|
_WIDGETS = []
|
||||||
|
_AREA = []
|
||||||
|
_MOUNTS = [] # dicts: dev/point/base/total/used/free/pct
|
||||||
|
_PREV_IO = [None] # (read_sectors, write_sectors)
|
||||||
|
|
||||||
|
|
||||||
|
def _base_device(dev):
|
||||||
|
"""Strip a partition suffix: sda2 -> sda, nvme0n1p2 -> nvme0n1."""
|
||||||
|
name = dev.rsplit("/", 1)[-1]
|
||||||
|
while name and name[-1].isdigit():
|
||||||
|
name = name[:-1]
|
||||||
|
if len(name) >= 2 and name[-1] == "p" and name[-2].isdigit():
|
||||||
|
name = name[:-1]
|
||||||
|
return name
|
||||||
|
|
||||||
|
|
||||||
|
def _read_mounts():
|
||||||
|
mounts = []
|
||||||
|
try:
|
||||||
|
with open("/proc/mounts") as f:
|
||||||
|
lines = f.read().splitlines()
|
||||||
|
except OSError:
|
||||||
|
return mounts
|
||||||
|
for line in lines:
|
||||||
|
parts = line.split()
|
||||||
|
if len(parts) < 3 or parts[2] not in REAL_FS:
|
||||||
|
continue
|
||||||
|
point = parts[1]
|
||||||
|
if any(m["point"] == point for m in mounts):
|
||||||
|
continue
|
||||||
|
try:
|
||||||
|
sv = os.statvfs(point)
|
||||||
|
except OSError:
|
||||||
|
continue
|
||||||
|
total = sv.f_blocks * sv.f_frsize
|
||||||
|
free = sv.f_bfree * sv.f_frsize
|
||||||
|
used = total - free
|
||||||
|
mounts.append({
|
||||||
|
"dev": parts[0], "point": point,
|
||||||
|
"base": _base_device(parts[0]),
|
||||||
|
"total": total / GIB, "used": used / GIB,
|
||||||
|
"free": free / GIB,
|
||||||
|
"pct": used / total * 100.0 if total else 0.0,
|
||||||
|
})
|
||||||
|
if len(mounts) >= 4:
|
||||||
|
break
|
||||||
|
return mounts
|
||||||
|
|
||||||
|
|
||||||
|
def _read_io():
|
||||||
|
"""(read_sectors, write_sectors) summed over the backing disks."""
|
||||||
|
bases = {m["base"] for m in _MOUNTS}
|
||||||
|
rd = wr = 0
|
||||||
|
ok = False
|
||||||
|
try:
|
||||||
|
with open("/proc/diskstats") as f:
|
||||||
|
lines = f.read().splitlines()
|
||||||
|
except OSError:
|
||||||
|
return None
|
||||||
|
for line in lines:
|
||||||
|
parts = line.split()
|
||||||
|
if len(parts) < 10 or parts[2] not in bases:
|
||||||
|
continue
|
||||||
|
rd += int(parts[5])
|
||||||
|
wr += int(parts[9])
|
||||||
|
ok = True
|
||||||
|
return (rd, wr) if ok else None
|
||||||
|
|
||||||
|
|
||||||
|
def _build_widgets():
|
||||||
|
widgets = []
|
||||||
|
n = len(_MOUNTS)
|
||||||
|
stack_y = MARGIN + n * (BAR_H + BAR_GAP) + 8
|
||||||
|
hist_y = stack_y + STACK_H + 8
|
||||||
|
hist_h = WIN_H - MARGIN - hist_y
|
||||||
|
col_w = WIN_W - 2 * MARGIN
|
||||||
|
for i, m in enumerate(_MOUNTS):
|
||||||
|
w = create("XUsageBar", "XUsageBar_%03d" % (i + 1),
|
||||||
|
MARGIN, MARGIN + i * (BAR_H + BAR_GAP), col_w, BAR_H)
|
||||||
|
w.set_prop("label", "%s %.0f GiB" % (m["point"], m["total"]))
|
||||||
|
w.set_value(m["pct"])
|
||||||
|
widgets.append(w)
|
||||||
|
stack = create("XStackBar", "XStackBar_001",
|
||||||
|
MARGIN, stack_y, col_w, STACK_H)
|
||||||
|
stack.set_prop("label", "%s disk usage" % _MOUNTS[0]["point"])
|
||||||
|
stack.set_segments([("Used", _MOUNTS[0]["used"], (0.0, 0.59, 0.24)),
|
||||||
|
("Free", _MOUNTS[0]["free"], (0.78, 0.78, 0.78))])
|
||||||
|
widgets.append(stack)
|
||||||
|
hist = create("XHistoryGraph", "XHistoryGraph_001",
|
||||||
|
MARGIN, hist_y, col_w, hist_h)
|
||||||
|
hist.set_prop("label", "Disk IO - MB/s (read / write)")
|
||||||
|
hist.set_prop("series-count", "2")
|
||||||
|
hist.set_prop("series-names", "Read MB/s|Write MB/s")
|
||||||
|
widgets.append(hist)
|
||||||
|
return widgets
|
||||||
|
|
||||||
|
|
||||||
|
def _tick():
|
||||||
|
live = _read_mounts()
|
||||||
|
for i, m in enumerate(_MOUNTS):
|
||||||
|
if i >= len(live):
|
||||||
|
break
|
||||||
|
m.update(live[i])
|
||||||
|
_WIDGETS[i].set_value(m["pct"])
|
||||||
|
stack = _WIDGETS[len(_MOUNTS)]
|
||||||
|
stack.set_segments([("Used", _MOUNTS[0]["used"], (0.0, 0.59, 0.24)),
|
||||||
|
("Free", _MOUNTS[0]["free"], (0.78, 0.78, 0.78))])
|
||||||
|
hist = _WIDGETS[len(_MOUNTS) + 1]
|
||||||
|
io = _read_io()
|
||||||
|
# 1 s tick, 512-byte sectors -> MB/s.
|
||||||
|
if io is not None and _PREV_IO[0] is not None:
|
||||||
|
hist.push((io[0] - _PREV_IO[0][0]) * 512.0 / 1e6, series=0)
|
||||||
|
hist.push((io[1] - _PREV_IO[0][1]) * 512.0 / 1e6, series=1)
|
||||||
|
_PREV_IO[0] = io
|
||||||
|
if _AREA:
|
||||||
|
_AREA[0].queue_draw()
|
||||||
|
return True
|
||||||
|
|
||||||
|
|
||||||
|
def _on_draw(area, cr):
|
||||||
|
# Dark btop-style harness background (0.07, 0.07, 0.09): the
|
||||||
|
# monitor widgets draw light-grey text on near-black panels, and
|
||||||
|
# XStackBar paints no panel of its own, so a white background
|
||||||
|
# would wash its legend out.
|
||||||
|
cr.set_source_rgb(0.07, 0.07, 0.09)
|
||||||
|
cr.paint()
|
||||||
|
for widget in _WIDGETS:
|
||||||
|
widget.draw(cr)
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
_MOUNTS.extend(_read_mounts())
|
||||||
|
if not _MOUNTS:
|
||||||
|
_MOUNTS.append({"dev": "?", "point": "/", "base": "",
|
||||||
|
"total": 0.0, "used": 0.0, "free": 0.0,
|
||||||
|
"pct": 0.0})
|
||||||
|
_PREV_IO[0] = _read_io()
|
||||||
|
window = Gtk.Window(title="Disk Monitor - monitor")
|
||||||
|
window.set_default_size(WIN_W, WIN_H)
|
||||||
|
window.set_resizable(False)
|
||||||
|
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.connect("draw", _on_draw)
|
||||||
|
vbox.pack_start(area, True, True, 0)
|
||||||
|
_WIDGETS.extend(_build_widgets())
|
||||||
|
_AREA.append(area)
|
||||||
|
GLib.timeout_add(1000, _tick)
|
||||||
|
window.show_all()
|
||||||
|
Gtk.main()
|
||||||
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
sys.exit(main())
|
||||||
|
After Width: | Height: | Size: 33 KiB |
@@ -0,0 +1,33 @@
|
|||||||
|
# Memory Monitor — Python
|
||||||
|
|
||||||
|
A btop-style memory monitor in one 1024x768 window, built from the new
|
||||||
|
XFrame monitor widgets (Stage 2 of the btop-widget project). All data is
|
||||||
|
live from `/proc/meminfo`, refreshed every 500 ms.
|
||||||
|
|
||||||
|
## What it shows
|
||||||
|
|
||||||
|
- **XSysBox "MEMORY"** — big used-% number, mini history graph, usage bar;
|
||||||
|
the title carries the live total and available figures
|
||||||
|
- **XDonutGauge "Memory used" / "Swap used"** — ring gauges (swap is 0%
|
||||||
|
on machines with no swap configured); the label under each ring shows
|
||||||
|
the GiB figures
|
||||||
|
- **XStackBar** — used / cached / buffers / free in GiB, with legend
|
||||||
|
- **XHistoryGraph** — used % and cached % over the last 60 seconds
|
||||||
|
- **XUsageBar x3** — Memory used, Cached, Swap used
|
||||||
|
|
||||||
|
"Used" follows the `free` convention: total − free − buffers − cached.
|
||||||
|
|
||||||
|
## Run
|
||||||
|
|
||||||
|
```sh
|
||||||
|
PYTHONPATH=/root/monitor-wt/memory-monitor/lightgui_python \
|
||||||
|
python3 examples/monitor_memory_monitor/main.py
|
||||||
|
```
|
||||||
|
|
||||||
|
(run from the repo root; close the window to quit)
|
||||||
|
|
||||||
|
## Widgets used
|
||||||
|
|
||||||
|
XSysBox, XDonutGauge, XStackBar, XHistoryGraph, XUsageBar — all from the
|
||||||
|
LightGUI registry (562 widgets: 547 + 15 monitor widgets), driven through
|
||||||
|
`MonitorWidget` (`set_value` / `push` / `set_segments` / `set_prop`).
|
||||||
@@ -0,0 +1,248 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
# Memory Monitor - monitor (Stage 2, btop-widget project).
|
||||||
|
#
|
||||||
|
# One 1024x768 window of live memory data from /proc/meminfo, refreshed
|
||||||
|
# every 500 ms. Every visible element is one of the new XFrame monitor
|
||||||
|
# widgets: XSysBox (big used %), XDonutGauge x2 (memory / swap used),
|
||||||
|
# XStackBar (used / cached / buffers / free), XHistoryGraph (used % and
|
||||||
|
# cached % over the last 60 s), XUsageBar x3 (memory used / cached /
|
||||||
|
# swap used). No raw Cairo drawing for UI elements: the shell only
|
||||||
|
# paints the window background and calls each widget's draw(cr).
|
||||||
|
#
|
||||||
|
# Run with:
|
||||||
|
# PYTHONPATH=/root/monitor-wt/memory-monitor/lightgui_python \
|
||||||
|
# python3 examples/monitor_memory_monitor/main.py
|
||||||
|
# (the designer sets PYTHONPATH when it runs this script; run it by hand
|
||||||
|
# with the PYTHONPATH above from the repo root.)
|
||||||
|
|
||||||
|
import sys
|
||||||
|
|
||||||
|
import gi
|
||||||
|
|
||||||
|
gi.require_version("Gtk", "3.0")
|
||||||
|
gi.require_version("Gdk", "3.0")
|
||||||
|
|
||||||
|
from gi.repository import GLib, Gtk # noqa: E402
|
||||||
|
from lightgui.xframe.core import create, parse_color # noqa: E402
|
||||||
|
|
||||||
|
|
||||||
|
# Design-time geometry + effective anchors per widget:
|
||||||
|
# name -> (top, left, right, bottom, x, y, width, height)
|
||||||
|
_ANCHORS = {
|
||||||
|
'XSysBox_001': (True, True, False, False, 16, 16, 500, 190),
|
||||||
|
'XDonutGauge_001': (True, True, False, False, 532, 16, 230, 190),
|
||||||
|
'XDonutGauge_002': (True, True, False, False, 778, 16, 230, 190),
|
||||||
|
'XStackBar_001': (True, True, False, False, 16, 222, 992, 60),
|
||||||
|
'XHistoryGraph_001': (True, True, False, False, 16, 298, 992, 310),
|
||||||
|
'XUsageBar_001': (True, True, False, False, 16, 624, 992, 36),
|
||||||
|
'XUsageBar_002': (True, True, False, False, 16, 664, 992, 36),
|
||||||
|
'XUsageBar_003': (True, True, False, False, 16, 704, 992, 36),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _apply_anchors(widgets, width, height):
|
||||||
|
"""Reposition anchored widgets for a drawing area of
|
||||||
|
*width* x *height* (Flag 1: minimal anchor layout).
|
||||||
|
Computed from the design geometry every time, so a
|
||||||
|
resize is idempotent — no drift across resizes."""
|
||||||
|
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)
|
||||||
|
|
||||||
|
|
||||||
|
def _read_meminfo():
|
||||||
|
"""Live memory figures from /proc/meminfo. 'Used' follows the
|
||||||
|
`free` convention: total - free - buffers - cached. Returns a
|
||||||
|
dict of GiB figures and percentages, or None when unavailable."""
|
||||||
|
try:
|
||||||
|
with open("/proc/meminfo") as f:
|
||||||
|
vals = {}
|
||||||
|
for line in f:
|
||||||
|
parts = line.split()
|
||||||
|
if len(parts) >= 2:
|
||||||
|
vals[parts[0].rstrip(":")] = float(parts[1])
|
||||||
|
except OSError:
|
||||||
|
return None
|
||||||
|
total = vals.get("MemTotal", 0.0)
|
||||||
|
if total <= 0:
|
||||||
|
return None
|
||||||
|
gib = 1024.0 * 1024.0
|
||||||
|
total_gib = total / gib
|
||||||
|
free_gib = vals.get("MemFree", 0.0) / gib
|
||||||
|
avail_gib = vals.get("MemAvailable", 0.0) / gib
|
||||||
|
cached_gib = vals.get("Cached", 0.0) / gib
|
||||||
|
buffers_gib = vals.get("Buffers", 0.0) / gib
|
||||||
|
used_gib = max(0.0, total_gib - free_gib - buffers_gib - cached_gib)
|
||||||
|
swap_total = vals.get("SwapTotal", 0.0) / gib
|
||||||
|
swap_used = max(0.0, swap_total - vals.get("SwapFree", 0.0) / gib)
|
||||||
|
return {
|
||||||
|
"total": total_gib,
|
||||||
|
"free": free_gib,
|
||||||
|
"avail": avail_gib,
|
||||||
|
"cached": cached_gib,
|
||||||
|
"buffers": buffers_gib,
|
||||||
|
"used": used_gib,
|
||||||
|
"used_pct": used_gib / total_gib * 100.0,
|
||||||
|
"cached_pct": cached_gib / total_gib * 100.0,
|
||||||
|
"swap_total": swap_total,
|
||||||
|
"swap_used": swap_used,
|
||||||
|
"swap_pct": swap_used / swap_total * 100.0 if swap_total > 0 else 0.0,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _build_widgets():
|
||||||
|
"""Create every placed widget with its props."""
|
||||||
|
widgets = []
|
||||||
|
|
||||||
|
sysbox = create('XSysBox', 'XSysBox_001', 16, 16, 500, 190)
|
||||||
|
sysbox.set_prop("label", "MEMORY")
|
||||||
|
sysbox.set_prop("unit", "%")
|
||||||
|
sysbox.set_prop("minimum", "0")
|
||||||
|
sysbox.set_prop("maximum", "100")
|
||||||
|
widgets.append(sysbox)
|
||||||
|
|
||||||
|
donut_mem = create('XDonutGauge', 'XDonutGauge_001', 532, 16, 230, 190)
|
||||||
|
donut_mem.set_prop("label", "Memory used")
|
||||||
|
donut_mem.set_prop("unit", "used")
|
||||||
|
widgets.append(donut_mem)
|
||||||
|
|
||||||
|
donut_swap = create('XDonutGauge', 'XDonutGauge_002', 778, 16, 230, 190)
|
||||||
|
donut_swap.set_prop("label", "Swap used")
|
||||||
|
donut_swap.set_prop("unit", "swap")
|
||||||
|
widgets.append(donut_swap)
|
||||||
|
|
||||||
|
stack = create('XStackBar', 'XStackBar_001', 16, 222, 992, 60)
|
||||||
|
stack.set_prop("label", "Memory")
|
||||||
|
stack.set_segments([
|
||||||
|
("Used", 0.0, (0.13, 0.77, 0.37)),
|
||||||
|
("Cached", 0.0, (0.95, 0.75, 0.20)),
|
||||||
|
("Buffers", 0.0, (0.20, 0.75, 0.85)),
|
||||||
|
("Free", 0.0, (0.78, 0.78, 0.78)),
|
||||||
|
])
|
||||||
|
widgets.append(stack)
|
||||||
|
|
||||||
|
history = create('XHistoryGraph', 'XHistoryGraph_001', 16, 298, 992, 310)
|
||||||
|
history.set_prop("label", "Memory history")
|
||||||
|
history.set_prop("series-count", "2")
|
||||||
|
history.set_prop("series-names", "Used %|Cached %")
|
||||||
|
history.set_prop("minimum", "0")
|
||||||
|
history.set_prop("maximum", "100")
|
||||||
|
widgets.append(history)
|
||||||
|
|
||||||
|
bar_mem = create('XUsageBar', 'XUsageBar_001', 16, 624, 992, 36)
|
||||||
|
bar_mem.set_prop("label", "Memory used")
|
||||||
|
widgets.append(bar_mem)
|
||||||
|
|
||||||
|
bar_cached = create('XUsageBar', 'XUsageBar_002', 16, 664, 992, 36)
|
||||||
|
bar_cached.set_prop("label", "Cached")
|
||||||
|
widgets.append(bar_cached)
|
||||||
|
|
||||||
|
bar_swap = create('XUsageBar', 'XUsageBar_003', 16, 704, 992, 36)
|
||||||
|
bar_swap.set_prop("label", "Swap used")
|
||||||
|
widgets.append(bar_swap)
|
||||||
|
|
||||||
|
return widgets
|
||||||
|
|
||||||
|
|
||||||
|
_DESIGN_SIZE = (1024, 768)
|
||||||
|
_BACKGROUND = ''
|
||||||
|
_WIDGETS = []
|
||||||
|
_LAST_SIZE = [None]
|
||||||
|
_AREA = []
|
||||||
|
|
||||||
|
|
||||||
|
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:
|
||||||
|
widget.draw(cr)
|
||||||
|
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 _tick():
|
||||||
|
"""Feed one live /proc/meminfo sample into every widget (500 ms)."""
|
||||||
|
m = _read_meminfo()
|
||||||
|
if m is not None and len(_WIDGETS) == 8:
|
||||||
|
sysbox, donut_mem, donut_swap, stack, history, \
|
||||||
|
bar_mem, bar_cached, bar_swap = _WIDGETS
|
||||||
|
sysbox.set_prop(
|
||||||
|
"label",
|
||||||
|
"MEMORY \u2014 total %.1f GiB \u00b7 avail %.1f GiB"
|
||||||
|
% (m["total"], m["avail"]))
|
||||||
|
sysbox.set_value(m["used_pct"])
|
||||||
|
sysbox.push(m["used_pct"])
|
||||||
|
donut_mem.set_prop("unit", "used %.1f GiB" % m["used"])
|
||||||
|
donut_mem.set_value(m["used_pct"])
|
||||||
|
donut_swap.set_prop(
|
||||||
|
"unit", "swap %.1f / %.1f GiB" % (m["swap_used"], m["swap_total"]))
|
||||||
|
donut_swap.set_value(m["swap_pct"])
|
||||||
|
stack.set_segments([
|
||||||
|
("Used", m["used"], (0.13, 0.77, 0.37)),
|
||||||
|
("Cached", m["cached"], (0.95, 0.75, 0.20)),
|
||||||
|
("Buffers", m["buffers"], (0.20, 0.75, 0.85)),
|
||||||
|
("Free", m["free"], (0.78, 0.78, 0.78)),
|
||||||
|
])
|
||||||
|
history.set_prop(
|
||||||
|
"label",
|
||||||
|
"Memory history \u2014 used %.1f GiB" % m["used"])
|
||||||
|
history.push(m["used_pct"], series=0)
|
||||||
|
history.push(m["cached_pct"], series=1)
|
||||||
|
bar_mem.set_value(m["used_pct"])
|
||||||
|
bar_cached.set_value(m["cached_pct"])
|
||||||
|
bar_swap.set_value(m["swap_pct"])
|
||||||
|
if _AREA:
|
||||||
|
_AREA[0].queue_draw()
|
||||||
|
return True
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
window = Gtk.Window(title='Memory Monitor - monitor')
|
||||||
|
window.set_default_size(1024, 768)
|
||||||
|
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.connect("draw", _on_draw)
|
||||||
|
area.connect("size-allocate", _on_area_resize)
|
||||||
|
vbox.pack_start(area, True, True, 0)
|
||||||
|
_WIDGETS.extend(_build_widgets())
|
||||||
|
_AREA.append(area)
|
||||||
|
_tick()
|
||||||
|
GLib.timeout_add(500, _tick)
|
||||||
|
window.show_all()
|
||||||
|
Gtk.main()
|
||||||
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
sys.exit(main())
|
||||||
|
After Width: | Height: | Size: 40 KiB |
@@ -0,0 +1,50 @@
|
|||||||
|
# Network Monitor — monitor (Python)
|
||||||
|
|
||||||
|
A live network monitor in one 1024x768 window, built only from the
|
||||||
|
LightGUI XFrame monitor widgets (Stage 2 of the btop-widget project).
|
||||||
|
|
||||||
|
## What it shows
|
||||||
|
|
||||||
|
Live traffic for the main interface (`enp3s0` on hot_dallas, otherwise
|
||||||
|
the first non-loopback interface with traffic), read from
|
||||||
|
`/proc/net/dev` and differenced once a second:
|
||||||
|
|
||||||
|
- **XNetGraph** (top) — up/down graph in bytes/s, current rates plus
|
||||||
|
session totals in the legend.
|
||||||
|
- **XSysBox** (middle, x2) — Download / Upload big-number boxes in
|
||||||
|
KiB/s, each with its own history sparkline and usage bar. The range
|
||||||
|
tracks the session peak (x1.15, floor 100 KiB/s).
|
||||||
|
- **XHistoryGraph** — down/up rate history in KiB/s, 60 s window,
|
||||||
|
current / min / max / average per series.
|
||||||
|
- **XUsageBar** (bottom) — total throughput as a percentage of the
|
||||||
|
link speed (from `/sys/class/net/<iface>/speed`, 1 Gb/s fallback).
|
||||||
|
|
||||||
|
## Live data, not demo data
|
||||||
|
|
||||||
|
The widgets draw deterministic demo data until live samples are
|
||||||
|
pushed; `push()` / `push_net()` start a fresh live series (the demo
|
||||||
|
is never extended), so everything on screen after the first tick is
|
||||||
|
measured traffic. The 1 s tick matches `push_net()`, which
|
||||||
|
accumulates one second of totals per push.
|
||||||
|
|
||||||
|
## Run
|
||||||
|
|
||||||
|
```sh
|
||||||
|
PYTHONPATH=. python3 examples/monitor_network_monitor/main.py
|
||||||
|
# quit by closing the window
|
||||||
|
```
|
||||||
|
|
||||||
|
## Tests
|
||||||
|
|
||||||
|
```sh
|
||||||
|
DISPLAY=:99 python3 -m unittest discover -s tests
|
||||||
|
```
|
||||||
|
|
||||||
|
## Source
|
||||||
|
|
||||||
|
- C: `examples/monitor/network-monitor/main.cpp` in
|
||||||
|
[lightgui](https://github.com/cnmcdee/lightgui)
|
||||||
|
- Rust: `crates/xframe-demo/examples/monitor_network_monitor/main.rs` in
|
||||||
|
[lightgui_rust](https://github.com/cnmcdee/lightgui_rust)
|
||||||
|
- Python: `examples/monitor_network_monitor/main.py` in
|
||||||
|
[lightgui_python](https://github.com/cnmcdee/lightgui_python)
|
||||||
@@ -0,0 +1,223 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Network Monitor - monitor (Stage 2, btop-widget project).
|
||||||
|
|
||||||
|
One 1024x768 window showing LIVE traffic for the main interface
|
||||||
|
(enp3s0 on hot_dallas, else the first non-loopback interface with
|
||||||
|
traffic), read from /proc/net/dev and differenced once a second:
|
||||||
|
|
||||||
|
XNetGraph up/down graph, current rates + session totals
|
||||||
|
XSysBox x2 Download / Upload big-number boxes (KiB/s + history)
|
||||||
|
XHistoryGraph rate history, down/up in KiB/s (60 s window)
|
||||||
|
XUsageBar total throughput as % of the link speed
|
||||||
|
|
||||||
|
The widgets draw deterministic demo data until live samples are
|
||||||
|
pushed; push()/push_net() start a fresh live series (the demo is
|
||||||
|
never extended), so everything on screen after the first tick is
|
||||||
|
measured traffic. The 1 s tick matches push_net(), which accumulates
|
||||||
|
one second of totals per push.
|
||||||
|
|
||||||
|
Run with:
|
||||||
|
PYTHONPATH=/root/monitor-wt/network-monitor/lightgui_python \\
|
||||||
|
python3 examples/monitor_network_monitor/main.py
|
||||||
|
(or from the repo root with PYTHONPATH=.)
|
||||||
|
|
||||||
|
Quit: close the window.
|
||||||
|
"""
|
||||||
|
|
||||||
|
import os
|
||||||
|
import sys
|
||||||
|
|
||||||
|
import gi
|
||||||
|
|
||||||
|
gi.require_version("Gtk", "3.0")
|
||||||
|
gi.require_version("Gdk", "3.0")
|
||||||
|
|
||||||
|
from gi.repository import GLib, Gtk # noqa: E402
|
||||||
|
from lightgui.xframe.core import create, parse_color # noqa: E402
|
||||||
|
|
||||||
|
TITLE = "Network Monitor - monitor"
|
||||||
|
WIN_W, WIN_H = 1024, 768
|
||||||
|
|
||||||
|
|
||||||
|
def read_counters(iface):
|
||||||
|
"""(rx_bytes, tx_bytes) for iface from /proc/net/dev, or None."""
|
||||||
|
try:
|
||||||
|
with open("/proc/net/dev") as f:
|
||||||
|
lines = f.readlines()
|
||||||
|
except OSError:
|
||||||
|
return None
|
||||||
|
for line in lines:
|
||||||
|
if ":" not in line:
|
||||||
|
continue
|
||||||
|
name, rest = line.split(":", 1)
|
||||||
|
if name.strip() != iface:
|
||||||
|
continue
|
||||||
|
fields = rest.split()
|
||||||
|
if len(fields) < 9:
|
||||||
|
return None
|
||||||
|
try:
|
||||||
|
return (int(fields[0]), int(fields[8]))
|
||||||
|
except ValueError:
|
||||||
|
return None
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def pick_iface():
|
||||||
|
"""Prefer enp3s0; else the first non-loopback interface with traffic."""
|
||||||
|
if read_counters("enp3s0") is not None:
|
||||||
|
return "enp3s0"
|
||||||
|
try:
|
||||||
|
with open("/proc/net/dev") as f:
|
||||||
|
lines = f.readlines()
|
||||||
|
except OSError:
|
||||||
|
return "enp3s0"
|
||||||
|
fallback = "enp3s0"
|
||||||
|
for line in lines:
|
||||||
|
if ":" not in line:
|
||||||
|
continue
|
||||||
|
name, rest = line.split(":", 1)
|
||||||
|
name = name.strip()
|
||||||
|
if not name or name == "lo":
|
||||||
|
continue
|
||||||
|
if fallback == "enp3s0":
|
||||||
|
fallback = name
|
||||||
|
fields = rest.split()
|
||||||
|
try:
|
||||||
|
rx = int(fields[0]) if fields else 0
|
||||||
|
tx = int(fields[8]) if len(fields) > 8 else 0
|
||||||
|
except ValueError:
|
||||||
|
continue
|
||||||
|
if rx > 0 or tx > 0:
|
||||||
|
return name
|
||||||
|
return fallback
|
||||||
|
|
||||||
|
|
||||||
|
def link_speed_bps(iface):
|
||||||
|
"""Link speed in bits/s from /sys/class/net/<iface>/speed (Mbit/s)."""
|
||||||
|
try:
|
||||||
|
with open("/sys/class/net/%s/speed" % iface) as f:
|
||||||
|
mbps = int(f.read().strip())
|
||||||
|
if mbps > 0:
|
||||||
|
return mbps * 1e6
|
||||||
|
except (OSError, ValueError):
|
||||||
|
pass
|
||||||
|
return 1e9 # unknown: assume 1 Gb/s
|
||||||
|
|
||||||
|
|
||||||
|
IFACE = pick_iface()
|
||||||
|
LINK_BPS = link_speed_bps(IFACE)
|
||||||
|
|
||||||
|
_WIDGETS = []
|
||||||
|
_AREA = []
|
||||||
|
_PREV = [None, None] # (rx, tx) counters from the previous tick
|
||||||
|
_PEAK = [100.0, 100.0] # peak down/up KiB/s (floor 100), tracks x1.15
|
||||||
|
|
||||||
|
|
||||||
|
def _build_widgets():
|
||||||
|
"""Create the five monitor widgets with live-data props."""
|
||||||
|
widgets = []
|
||||||
|
net = create("XNetGraph", "NetworkMonitor_001", 12, 12, 1000, 300)
|
||||||
|
net.set_prop("label", "Network - %s" % IFACE)
|
||||||
|
widgets.append(net)
|
||||||
|
|
||||||
|
down = create("XSysBox", "NetworkMonitor_002", 12, 324, 492, 180)
|
||||||
|
down.set_prop("label", "Download - %s" % IFACE)
|
||||||
|
down.set_prop("unit", " KiB/s")
|
||||||
|
down.set_prop("minimum", "0")
|
||||||
|
down.set_prop("maximum", "100")
|
||||||
|
down.set_prop("value", "0")
|
||||||
|
widgets.append(down)
|
||||||
|
|
||||||
|
up = create("XSysBox", "NetworkMonitor_003", 520, 324, 492, 180)
|
||||||
|
up.set_prop("label", "Upload - %s" % IFACE)
|
||||||
|
up.set_prop("unit", " KiB/s")
|
||||||
|
up.set_prop("minimum", "0")
|
||||||
|
up.set_prop("maximum", "100")
|
||||||
|
up.set_prop("value", "0")
|
||||||
|
widgets.append(up)
|
||||||
|
|
||||||
|
hist = create("XHistoryGraph", "NetworkMonitor_004", 12, 516, 1000, 172)
|
||||||
|
hist.set_prop("label", "Rate history (KiB/s)")
|
||||||
|
hist.set_prop("series-names", "Down KiB/s|Up KiB/s")
|
||||||
|
hist.set_prop("minimum", "0")
|
||||||
|
hist.set_prop("maximum", "100")
|
||||||
|
widgets.append(hist)
|
||||||
|
|
||||||
|
usage = create("XUsageBar", "NetworkMonitor_005", 12, 700, 1000, 44)
|
||||||
|
usage.set_prop("label", "Link use - %s (%.0f Gb/s)"
|
||||||
|
% (IFACE, LINK_BPS / 1e9))
|
||||||
|
usage.set_prop("minimum", "0")
|
||||||
|
usage.set_prop("maximum", "100")
|
||||||
|
usage.set_prop("value", "0")
|
||||||
|
widgets.append(usage)
|
||||||
|
return widgets
|
||||||
|
|
||||||
|
|
||||||
|
def _on_draw(area, cr):
|
||||||
|
bg = parse_color("", None)
|
||||||
|
if bg is None:
|
||||||
|
bg = (1.0, 1.0, 1.0)
|
||||||
|
cr.set_source_rgb(*bg)
|
||||||
|
cr.paint()
|
||||||
|
for widget in _WIDGETS:
|
||||||
|
widget.draw(cr)
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
def _tick():
|
||||||
|
"""One live sample per second: difference /proc/net/dev, push, redraw."""
|
||||||
|
now = read_counters(IFACE)
|
||||||
|
if now is None:
|
||||||
|
return True
|
||||||
|
prev = _PREV[0]
|
||||||
|
_PREV[0] = now
|
||||||
|
if prev is None:
|
||||||
|
return True
|
||||||
|
down_bps = float(now[0] - prev[0]) if now[0] >= prev[0] else 0.0
|
||||||
|
up_bps = float(now[1] - prev[1]) if now[1] >= prev[1] else 0.0
|
||||||
|
down_kb = down_bps / 1024.0
|
||||||
|
up_kb = up_bps / 1024.0
|
||||||
|
_PEAK[0] = max(_PEAK[0], down_kb * 1.15)
|
||||||
|
_PEAK[1] = max(_PEAK[1], up_kb * 1.15)
|
||||||
|
|
||||||
|
net, down, up, hist, usage = _WIDGETS
|
||||||
|
net.push_net(down_bps, up_bps)
|
||||||
|
down.set_prop("maximum", "%.1f" % _PEAK[0])
|
||||||
|
down.set_prop("value", "%.1f" % down_kb)
|
||||||
|
down.push(down_kb)
|
||||||
|
up.set_prop("maximum", "%.1f" % _PEAK[1])
|
||||||
|
up.set_prop("value", "%.1f" % up_kb)
|
||||||
|
up.push(up_kb)
|
||||||
|
hist.set_prop("maximum", "%.1f" % max(_PEAK[0], _PEAK[1]))
|
||||||
|
hist.push(down_kb, series=0)
|
||||||
|
hist.push(up_kb, series=1)
|
||||||
|
usage.set_prop("value", "%.1f"
|
||||||
|
% min(100.0, (down_bps + up_bps) / LINK_BPS * 100.0))
|
||||||
|
if _AREA:
|
||||||
|
_AREA[0].queue_draw()
|
||||||
|
return True
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
window = Gtk.Window(title=TITLE)
|
||||||
|
window.set_default_size(WIN_W, WIN_H)
|
||||||
|
window.set_resizable(False)
|
||||||
|
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.connect("draw", _on_draw)
|
||||||
|
vbox.pack_start(area, True, True, 0)
|
||||||
|
_WIDGETS.extend(_build_widgets())
|
||||||
|
_AREA.append(area)
|
||||||
|
_PREV[0] = read_counters(IFACE) # baseline; first tick differences it
|
||||||
|
GLib.timeout_add(1000, _tick)
|
||||||
|
window.show_all()
|
||||||
|
Gtk.main()
|
||||||
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
sys.exit(main())
|
||||||
|
After Width: | Height: | Size: 46 KiB |
@@ -0,0 +1,41 @@
|
|||||||
|
# Process Manager — monitor (Python)
|
||||||
|
|
||||||
|
A btop-style process manager in one 1024x768 window, built only from
|
||||||
|
LightGUI XFrame widgets: `XProcessList` (live `/proc` table, sortable
|
||||||
|
columns, click a row to select it), `GtkEntry` (filter by name or pid),
|
||||||
|
and three `GtkButton`s — **Terminate**, **Kill**, **Refresh**.
|
||||||
|
|
||||||
|
## What it shows
|
||||||
|
|
||||||
|
- **Processes** — pid, program, user, memory and CPU% for the live
|
||||||
|
processes on this machine, refreshed every 2 seconds. Click a column
|
||||||
|
header to sort by it (click again to reverse); click a body row to
|
||||||
|
select it (highlighted). CPU% is per-core with an in-cell bar.
|
||||||
|
- **Filter** — click the entry, type a name or pid substring; the list
|
||||||
|
shows only matching rows.
|
||||||
|
- **Terminate** — sends `SIGTERM` to the selected process.
|
||||||
|
- **Kill** — sends `SIGKILL` to the selected process.
|
||||||
|
- **Refresh** — re-scans `/proc` immediately.
|
||||||
|
|
||||||
|
Safety: Terminate/Kill act on the selected row's pid only, and refuse
|
||||||
|
pid ≤ 1 and the manager's own pid.
|
||||||
|
|
||||||
|
## Build and run
|
||||||
|
|
||||||
|
```sh
|
||||||
|
PYTHONPATH=/root/pm-work/lightgui_python python3 examples/monitor_process_manager/main.py
|
||||||
|
# Esc or close the window to quit
|
||||||
|
```
|
||||||
|
|
||||||
|
## Source
|
||||||
|
|
||||||
|
- App: `examples/monitor_process_manager/main.py` in
|
||||||
|
[lightgui_python](https://github.com/cnmcdee/lightgui_python)
|
||||||
|
- Widgets: `XProcessList` (`MonitorWidget`), `GtkButton`, `GtkEntry`
|
||||||
|
— this app adds row-selection and a name/pid filter to
|
||||||
|
`MonitorWidget` (additive only; the widget demo is unchanged)
|
||||||
|
|
||||||
|
The same app exists in
|
||||||
|
[C](https://github.com/cnmcdee/lightgui) and
|
||||||
|
[Rust](https://github.com/cnmcdee/lightgui_rust) — see the
|
||||||
|
[walkthrough](https://www.lightgui.com/monitor-process-manager/).
|
||||||
@@ -0,0 +1,240 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
# Process Manager - monitor (Python/XFrame).
|
||||||
|
#
|
||||||
|
# A plain Python/GTK program: no CMake. Run with:
|
||||||
|
# PYTHONPATH=/root/pm-work/lightgui_python python3 \
|
||||||
|
# examples/monitor_process_manager/main.py
|
||||||
|
# with the LightGUI Python package on PYTHONPATH.
|
||||||
|
#
|
||||||
|
# One 1024x768 window: a live XProcessList (/proc, sortable columns,
|
||||||
|
# click a row to select it), a GtkEntry filter (name or pid substring),
|
||||||
|
# and GtkButton Terminate / Kill / Refresh. Terminate sends SIGTERM and
|
||||||
|
# Kill sends SIGKILL to the SELECTED row's pid only -- never anything
|
||||||
|
# else (pid <= 1 and our own pid are refused outright).
|
||||||
|
# Esc or close the window to quit.
|
||||||
|
|
||||||
|
import os
|
||||||
|
import signal
|
||||||
|
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
|
||||||
|
|
||||||
|
|
||||||
|
def _signal_selected(sig):
|
||||||
|
"""Signal the selected row's pid only; refresh afterwards."""
|
||||||
|
widget = _WIDGETS[0]
|
||||||
|
pid = widget.selected_pid()
|
||||||
|
if pid is None or pid <= 1 or pid == os.getpid():
|
||||||
|
return
|
||||||
|
try:
|
||||||
|
os.kill(pid, sig)
|
||||||
|
except (ProcessLookupError, PermissionError):
|
||||||
|
return
|
||||||
|
widget.refresh_processes()
|
||||||
|
if _AREA:
|
||||||
|
_AREA[0].queue_draw()
|
||||||
|
|
||||||
|
|
||||||
|
def on_Terminate_001_OnClick(widget):
|
||||||
|
_signal_selected(signal.SIGTERM)
|
||||||
|
|
||||||
|
|
||||||
|
def on_Kill_001_OnClick(widget):
|
||||||
|
_signal_selected(signal.SIGKILL)
|
||||||
|
|
||||||
|
|
||||||
|
def on_Refresh_001_OnClick(widget):
|
||||||
|
_WIDGETS[0].refresh_processes()
|
||||||
|
if _AREA:
|
||||||
|
_AREA[0].queue_draw()
|
||||||
|
|
||||||
|
|
||||||
|
# Event handlers, wired to the widgets in main():
|
||||||
|
_HANDLERS = {
|
||||||
|
('Terminate_001', 'OnClick'): on_Terminate_001_OnClick,
|
||||||
|
('Kill_001', 'OnClick'): on_Kill_001_OnClick,
|
||||||
|
('Refresh_001', 'OnClick'): on_Refresh_001_OnClick,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _build_widgets():
|
||||||
|
"""Create every placed widget with its props."""
|
||||||
|
widgets = []
|
||||||
|
plist = create('XProcessList', 'XProcessList_001', 16, 58, 992, 694)
|
||||||
|
plist.set_prop("label", "Processes")
|
||||||
|
# Two samples 0.25 s apart so CPU% is real, not 0.0, on first paint.
|
||||||
|
plist.refresh_processes()
|
||||||
|
time.sleep(0.25)
|
||||||
|
plist.refresh_processes()
|
||||||
|
widgets.append(plist)
|
||||||
|
entry = create('GtkEntry', 'Filter_001', 16, 16, 300, 30)
|
||||||
|
entry.set_text("")
|
||||||
|
entry.set_prop("placeholder-text", "Filter: name or pid")
|
||||||
|
widgets.append(entry)
|
||||||
|
for name, label, x in (('Terminate_001', 'Terminate', 336),
|
||||||
|
('Kill_001', 'Kill', 466),
|
||||||
|
('Refresh_001', 'Refresh', 596)):
|
||||||
|
btn = create('GtkButton', name, x, 16, 120, 30)
|
||||||
|
btn.set_text(label)
|
||||||
|
widgets.append(btn)
|
||||||
|
return widgets
|
||||||
|
|
||||||
|
|
||||||
|
_DESIGN_SIZE = (1024, 768)
|
||||||
|
_BACKGROUND = ''
|
||||||
|
_WIDGETS = []
|
||||||
|
_LAST_SIZE = [None]
|
||||||
|
_PRESSED = [None] # Task 4: widget that got the ButtonPress
|
||||||
|
_FOCUSED = [None] # GtkEntry with keyboard focus (None = none)
|
||||||
|
_AREA = []
|
||||||
|
|
||||||
|
|
||||||
|
def _hit_widget(widgets, x, y):
|
||||||
|
"""Topmost visible widget containing (*x*, *y*)."""
|
||||||
|
for widget in reversed(widgets):
|
||||||
|
if widget.get_prop("visible", "true") in ("false", "0"):
|
||||||
|
continue
|
||||||
|
if widget.contains(x, y):
|
||||||
|
return widget
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def _dispatch_to(widget, event):
|
||||||
|
"""Call the *event* handler of *widget* (already chosen)."""
|
||||||
|
if widget is None:
|
||||||
|
return
|
||||||
|
if widget.get_prop("enabled", "true") in ("false", "0"):
|
||||||
|
return
|
||||||
|
handler = _HANDLERS.get((widget.name, event))
|
||||||
|
if handler is not None:
|
||||||
|
handler(widget)
|
||||||
|
|
||||||
|
|
||||||
|
def _dispatch(widgets, x, y, event):
|
||||||
|
"""Call the *event* handler of the widget at (*x*, *y*),
|
||||||
|
if it has one wired."""
|
||||||
|
_dispatch_to(_hit_widget(widgets, x, y), event)
|
||||||
|
|
||||||
|
|
||||||
|
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:
|
||||||
|
widget.draw(cr)
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
def _on_button_press(area, event):
|
||||||
|
widget = _hit_widget(_WIDGETS, event.x, event.y)
|
||||||
|
if widget is not None and widget.kind == "XProcessList":
|
||||||
|
# Widget-relative click: header sorts, body row selects.
|
||||||
|
widget.select_at(event.x - widget.x, event.y - widget.y)
|
||||||
|
_FOCUSED[0] = None
|
||||||
|
area.queue_draw()
|
||||||
|
elif widget is not None and widget.kind == "GtkEntry":
|
||||||
|
_FOCUSED[0] = widget
|
||||||
|
else:
|
||||||
|
_FOCUSED[0] = None
|
||||||
|
if event.type == Gdk.EventType.DOUBLE_BUTTON_PRESS:
|
||||||
|
_dispatch(_WIDGETS, event.x, event.y, "OnDblClick")
|
||||||
|
elif event.type == Gdk.EventType.BUTTON_PRESS:
|
||||||
|
_dispatch(_WIDGETS, event.x, event.y, "OnMouseDown")
|
||||||
|
_dispatch(_WIDGETS, event.x, event.y, "OnClick")
|
||||||
|
# Task 4: remember the pressed widget; release goes there.
|
||||||
|
_PRESSED[0] = widget
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
def _on_button_release(area, event):
|
||||||
|
# Task 4: release goes to the widget that got the press,
|
||||||
|
# even if the pointer moved off it.
|
||||||
|
widget = _PRESSED[0]
|
||||||
|
_PRESSED[0] = None
|
||||||
|
_dispatch_to(widget, "OnMouseUp")
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
def _on_key(window, event):
|
||||||
|
"""Forward typing to the focused filter entry; Esc quits."""
|
||||||
|
if event.keyval == Gdk.KEY_Escape:
|
||||||
|
Gtk.main_quit()
|
||||||
|
return True
|
||||||
|
entry = _FOCUSED[0]
|
||||||
|
if entry is None:
|
||||||
|
return False
|
||||||
|
text = entry.text or ""
|
||||||
|
if event.keyval == Gdk.KEY_BackSpace:
|
||||||
|
text = text[:-1]
|
||||||
|
elif event.keyval == Gdk.KEY_Return:
|
||||||
|
return True
|
||||||
|
else:
|
||||||
|
ch = Gdk.keyval_to_unicode(event.keyval)
|
||||||
|
if ch == 0 or ch < 0x20 or ch >= 0x7f:
|
||||||
|
return False
|
||||||
|
text += chr(ch)
|
||||||
|
entry.set_text(text)
|
||||||
|
_WIDGETS[0].set_filter(text)
|
||||||
|
if _AREA:
|
||||||
|
_AREA[0].queue_draw()
|
||||||
|
return True
|
||||||
|
|
||||||
|
|
||||||
|
def _on_area_resize(area, allocation):
|
||||||
|
size = (allocation.width, allocation.height)
|
||||||
|
if size == _LAST_SIZE[0]:
|
||||||
|
return False
|
||||||
|
_LAST_SIZE[0] = size
|
||||||
|
area.queue_draw()
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
# --- live demo ------------------------------------------------------------
|
||||||
|
# The list shows live data: _tick() re-scans /proc every 2000 ms and
|
||||||
|
# redraws the drawing area.
|
||||||
|
def _tick():
|
||||||
|
_WIDGETS[0].refresh_processes()
|
||||||
|
if _AREA:
|
||||||
|
_AREA[0].queue_draw()
|
||||||
|
return True
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
window = Gtk.Window(title='Process Manager - monitor')
|
||||||
|
window.set_default_size(1024, 768)
|
||||||
|
window.connect("destroy", Gtk.main_quit)
|
||||||
|
window.connect("key-press-event", _on_key)
|
||||||
|
vbox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL,
|
||||||
|
spacing=0)
|
||||||
|
window.add(vbox)
|
||||||
|
area = Gtk.DrawingArea()
|
||||||
|
area.set_hexpand(True)
|
||||||
|
area.set_vexpand(True)
|
||||||
|
area.set_can_focus(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)
|
||||||
|
GLib.timeout_add(2000, _tick)
|
||||||
|
window.show_all()
|
||||||
|
area.grab_focus()
|
||||||
|
Gtk.main()
|
||||||
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
sys.exit(main())
|
||||||
|
After Width: | Height: | Size: 77 KiB |
@@ -0,0 +1,55 @@
|
|||||||
|
# Service Dashboard — monitor app (Python)
|
||||||
|
|
||||||
|
A service/port dashboard in one window (1024×768): a single
|
||||||
|
`XMonitorGrid` of illuminator buttons for the services that actually
|
||||||
|
run on this host (hot_dallas). Each button polls its live check every
|
||||||
|
2 seconds and glows green when up, red when down, dim when unknown.
|
||||||
|
Click anywhere on the grid to re-poll every cell now.
|
||||||
|
|
||||||
|
## What it monitors
|
||||||
|
|
||||||
|
| Button | Kind | Check |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| SSH :22 | Port | TCP connect to localhost:22 |
|
||||||
|
| HTTP :80 | Port | TCP connect to localhost:80 (nginx) |
|
||||||
|
| HTTPS :443 | Port | TCP connect to localhost:443 (nginx) |
|
||||||
|
| NPM admin :81 | Port | TCP connect to localhost:81 |
|
||||||
|
| ThinkMelt :2368 | Port | TCP connect to localhost:2368 |
|
||||||
|
| Ghost :5000 | Port | TCP connect to localhost:5000 |
|
||||||
|
| lightgui.com :5009 | Port | TCP connect to localhost:5009 |
|
||||||
|
| Traffic stats :7888 | Port | TCP connect to localhost:7888 (GoAccess) |
|
||||||
|
| dockerd | Process | `/proc/<pid>/comm` == `dockerd` |
|
||||||
|
| containerd | Process | `/proc/<pid>/comm` == `containerd` |
|
||||||
|
| docker.service | Unit | `systemctl is-active docker.service` == `active` |
|
||||||
|
| ssh.service | Unit | `systemctl is-active ssh.service` == `active` |
|
||||||
|
|
||||||
|
No mock or static data: every cell is a live `XMonitorButton` check
|
||||||
|
(`poll_all()` on a 2 s `GLib.timeout_add` timer).
|
||||||
|
|
||||||
|
## Widgets used
|
||||||
|
|
||||||
|
- `XMonitorGrid` — the panel; one shared `poll_all()` timer.
|
||||||
|
- `XMonitorButton` — one cell per service (kinds port / process /
|
||||||
|
unit, via `set_monitors`).
|
||||||
|
|
||||||
|
## Build and run
|
||||||
|
|
||||||
|
```sh
|
||||||
|
# from the lightgui_python checkout
|
||||||
|
PYTHONPATH=/root/monitor-wt/service-dashboard/lightgui_python python3 examples/monitor_service_dashboard/main.py
|
||||||
|
```
|
||||||
|
|
||||||
|
## Tests
|
||||||
|
|
||||||
|
```sh
|
||||||
|
DISPLAY=:99 python3 -m unittest discover -s tests
|
||||||
|
```
|
||||||
|
|
||||||
|
## Source
|
||||||
|
|
||||||
|
- Python: `examples/monitor_service_dashboard/main.py` in
|
||||||
|
[lightgui_python](https://github.com/cnmcdee/lightgui_python)
|
||||||
|
- C++: `examples/monitor/service-dashboard/main.cpp` in
|
||||||
|
[lightgui](https://github.com/cnmcdee/lightgui)
|
||||||
|
- Rust: `crates/xframe-demo/examples/monitor_service_dashboard/main.rs`
|
||||||
|
in [lightgui_rust](https://github.com/cnmcdee/lightgui_rust)
|
||||||
@@ -0,0 +1,131 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Service Dashboard -- monitor app.
|
||||||
|
|
||||||
|
One 1024x768 window holding a single XMonitorGrid of illuminator
|
||||||
|
buttons for the services that actually run on this host
|
||||||
|
(hot_dallas): TCP ports (sshd, nginx, NPM, ThinkMelt, Ghost blogs,
|
||||||
|
traffic stats), processes (dockerd, containerd) and systemd units
|
||||||
|
(docker.service, ssh.service). Every cell is a live check, re-polled
|
||||||
|
on a shared 2 s timer; green when up, red when down. Click a cell
|
||||||
|
to re-check it now.
|
||||||
|
|
||||||
|
Run with the LightGUI Python package on PYTHONPATH:
|
||||||
|
PYTHONPATH=/root/monitor-wt/service-dashboard/lightgui_python python3 examples/monitor_service_dashboard/main.py
|
||||||
|
"""
|
||||||
|
|
||||||
|
import sys
|
||||||
|
|
||||||
|
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
|
||||||
|
|
||||||
|
# (check_type, target, label) -- check_type is "port" (TCP connect to
|
||||||
|
# localhost), "process" (/proc/<pid>/comm match) or "unit"
|
||||||
|
# (systemctl is-active == active). All of these run on this host.
|
||||||
|
SERVICES = [
|
||||||
|
("port", "22", "SSH :22"),
|
||||||
|
("port", "80", "HTTP :80"),
|
||||||
|
("port", "443", "HTTPS :443"),
|
||||||
|
("port", "81", "NPM admin :81"),
|
||||||
|
("port", "2368", "ThinkMelt :2368"),
|
||||||
|
("port", "5000", "Ghost :5000"),
|
||||||
|
("port", "5009", "lightgui.com :5009"),
|
||||||
|
("port", "7888", "Traffic stats :7888"),
|
||||||
|
("process", "dockerd", "dockerd"),
|
||||||
|
("process", "containerd", "containerd"),
|
||||||
|
("unit", "docker.service", "docker.service"),
|
||||||
|
("unit", "ssh.service", "ssh.service"),
|
||||||
|
]
|
||||||
|
|
||||||
|
_DESIGN_SIZE = (1024, 768)
|
||||||
|
_BACKGROUND = ""
|
||||||
|
_WIDGETS = []
|
||||||
|
_LAST_SIZE = [None]
|
||||||
|
_AREA = []
|
||||||
|
|
||||||
|
|
||||||
|
def _build_widgets():
|
||||||
|
"""Create the grid and wire the real services (no demo data)."""
|
||||||
|
widgets = []
|
||||||
|
widget = create("XMonitorGrid", "ServiceGrid_001", 16, 16, 992, 736)
|
||||||
|
widget.set_prop("label", "Services -- hot_dallas")
|
||||||
|
# set_monitors replaces the grid cells wholesale (the widget
|
||||||
|
# starts with none); each cell is a live XMonitorButton check.
|
||||||
|
widget.set_monitors(SERVICES)
|
||||||
|
widget.poll_all()
|
||||||
|
widgets.append(widget)
|
||||||
|
return widgets
|
||||||
|
|
||||||
|
|
||||||
|
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:
|
||||||
|
widget.draw(cr)
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
def _on_button_press(area, event):
|
||||||
|
# Click anywhere on the grid re-polls every cell now (the grid
|
||||||
|
# has no per-cell click API in Python; the 2 s timer does the
|
||||||
|
# same check anyway).
|
||||||
|
for widget in _WIDGETS:
|
||||||
|
widget.poll_all()
|
||||||
|
area.queue_draw()
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
def _on_area_resize(area, allocation):
|
||||||
|
size = (allocation.width, allocation.height)
|
||||||
|
if size == _LAST_SIZE[0]:
|
||||||
|
return False
|
||||||
|
_LAST_SIZE[0] = size
|
||||||
|
for widget in _WIDGETS:
|
||||||
|
widget.move_to(16, 16)
|
||||||
|
widget.resize_to(max(100, size[0] - 32), max(100, size[1] - 32))
|
||||||
|
area.queue_draw()
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
def _tick():
|
||||||
|
"""Shared 2 s poll: re-check every cell, then redraw."""
|
||||||
|
for widget in _WIDGETS:
|
||||||
|
widget.poll_all()
|
||||||
|
if _AREA:
|
||||||
|
_AREA[0].queue_draw()
|
||||||
|
return True
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
window = Gtk.Window(title="Service Dashboard - monitor")
|
||||||
|
window.set_default_size(1024, 768)
|
||||||
|
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("size-allocate", _on_area_resize)
|
||||||
|
vbox.pack_start(area, True, True, 0)
|
||||||
|
_WIDGETS.extend(_build_widgets())
|
||||||
|
_AREA.append(area)
|
||||||
|
GLib.timeout_add(2000, _tick)
|
||||||
|
window.show_all()
|
||||||
|
Gtk.main()
|
||||||
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
sys.exit(main())
|
||||||
|
After Width: | Height: | Size: 34 KiB |
@@ -0,0 +1,37 @@
|
|||||||
|
# System Overview — monitor app
|
||||||
|
|
||||||
|
A system overview in one 1024x768 window, in the btop style: four
|
||||||
|
`XSysBox` composite boxes (CPU / MEM / NET / DISK), one `XLoadBadge`
|
||||||
|
(live load averages + uptime), two `XDonutGauge`s (CPU, Disk) and three
|
||||||
|
`XUsageBar`s (Memory, Disk, Network). All values are read live from
|
||||||
|
`/proc` (`stat`, `meminfo`, `net/dev`, `loadavg`, `uptime`) and
|
||||||
|
`statvfs("/")`, refreshed every 500 ms. No seeded demo data is shown:
|
||||||
|
the SysBox history graphs are flushed with live ticks before the
|
||||||
|
screenshot is taken (60 samples at 500 ms ≈ 30 s of run time).
|
||||||
|
|
||||||
|
Window title: `System Overview - monitor`.
|
||||||
|
|
||||||
|
## Widgets used
|
||||||
|
|
||||||
|
- `XSysBox` × 4 — CPU, MEM, NET (KB/s), DISK /
|
||||||
|
- `XLoadBadge` × 1 — 1 / 5 / 15 min load averages + uptime
|
||||||
|
- `XDonutGauge` × 2 — CPU, Disk /
|
||||||
|
- `XUsageBar` × 3 — Memory, Disk /, Network KB/s
|
||||||
|
|
||||||
|
## Build and run
|
||||||
|
|
||||||
|
```sh
|
||||||
|
make # builds ./system-overview
|
||||||
|
./system-overview # needs an X display; Esc / q / window-close quits
|
||||||
|
```
|
||||||
|
|
||||||
|
## Source
|
||||||
|
|
||||||
|
- C: `examples/monitor/system-overview/main.cpp` in
|
||||||
|
https://github.com/cnmcdee/lightgui
|
||||||
|
- Rust: `crates/xframe-demo/examples/monitor_system_overview.rs` in
|
||||||
|
https://github.com/cnmcdee/lightgui_rust
|
||||||
|
- Python: `examples/monitor_system_overview/main.py` in
|
||||||
|
https://github.com/cnmcdee/lightgui_python
|
||||||
|
|
||||||
|
Walkthrough: https://www.lightgui.com/monitor-system-overview/
|
||||||
@@ -0,0 +1,256 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""System Overview - monitor app (Stage 2, btop-widget project).
|
||||||
|
|
||||||
|
One 1024x768 window: four XSysBox composites (CPU / MEM / NET / DISK),
|
||||||
|
one XLoadBadge (live load averages + uptime), two XDonutGauges (CPU,
|
||||||
|
Disk) and three XUsageBars (Memory, Disk, Network). All values are read
|
||||||
|
live from /proc (stat, meminfo, net/dev, loadavg, uptime) and
|
||||||
|
shutil.disk_usage("/"), refreshed every 500 ms. push() starts a fresh
|
||||||
|
series, so the SysBox graphs show live ticks only -- no seeded demo
|
||||||
|
data.
|
||||||
|
|
||||||
|
Run with the LightGUI Python package on PYTHONPATH:
|
||||||
|
PYTHONPATH=/root/monitor-wt/system-overview/lightgui_python \
|
||||||
|
python3 examples/monitor_system_overview/main.py
|
||||||
|
Press Esc / q or close the window to quit.
|
||||||
|
"""
|
||||||
|
|
||||||
|
import os
|
||||||
|
import shutil
|
||||||
|
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
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# Live data from /proc
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
class Sampler:
|
||||||
|
def __init__(self):
|
||||||
|
self.prev_idle = 0
|
||||||
|
self.prev_total = 0
|
||||||
|
self.prev_rx = 0
|
||||||
|
self.prev_t = None
|
||||||
|
|
||||||
|
def cpu(self):
|
||||||
|
try:
|
||||||
|
with open("/proc/stat") as f:
|
||||||
|
fields = f.readline().split()[1:9]
|
||||||
|
nums = [int(v) for v in fields]
|
||||||
|
except (OSError, ValueError):
|
||||||
|
return None
|
||||||
|
idle = nums[3] + nums[4]
|
||||||
|
total = sum(nums)
|
||||||
|
if self.prev_total == 0:
|
||||||
|
self.prev_idle, self.prev_total = idle, total
|
||||||
|
return None
|
||||||
|
d_total = total - self.prev_total
|
||||||
|
d_idle = idle - self.prev_idle
|
||||||
|
self.prev_idle, self.prev_total = idle, total
|
||||||
|
if d_total == 0:
|
||||||
|
return None
|
||||||
|
return 100.0 * (1.0 - d_idle / d_total)
|
||||||
|
|
||||||
|
def mem(self):
|
||||||
|
total = avail = 0
|
||||||
|
try:
|
||||||
|
with open("/proc/meminfo") as f:
|
||||||
|
for line in f:
|
||||||
|
parts = line.split()
|
||||||
|
if parts[0] == "MemTotal:":
|
||||||
|
total = int(parts[1])
|
||||||
|
elif parts[0] == "MemAvailable:":
|
||||||
|
avail = int(parts[1])
|
||||||
|
except (OSError, ValueError):
|
||||||
|
return None
|
||||||
|
if total == 0:
|
||||||
|
return None
|
||||||
|
return 100.0 * (1.0 - avail / total)
|
||||||
|
|
||||||
|
def net_kbps(self):
|
||||||
|
rx_total = 0
|
||||||
|
try:
|
||||||
|
with open("/proc/net/dev") as f:
|
||||||
|
lines = f.readlines()[2:]
|
||||||
|
for line in lines:
|
||||||
|
iface, rest = line.split(":", 1)
|
||||||
|
if iface.strip() == "lo":
|
||||||
|
continue
|
||||||
|
rx_total += int(rest.split()[0])
|
||||||
|
except (OSError, ValueError):
|
||||||
|
return None
|
||||||
|
now = time.time()
|
||||||
|
if self.prev_t is None:
|
||||||
|
self.prev_rx, self.prev_t = rx_total, now
|
||||||
|
return None
|
||||||
|
dt = now - self.prev_t
|
||||||
|
delta = rx_total - self.prev_rx
|
||||||
|
self.prev_rx, self.prev_t = rx_total, now
|
||||||
|
if dt <= 0:
|
||||||
|
return None
|
||||||
|
return delta / dt / 1024.0
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def disk():
|
||||||
|
try:
|
||||||
|
du = shutil.disk_usage("/")
|
||||||
|
except OSError:
|
||||||
|
return None
|
||||||
|
if du.total == 0:
|
||||||
|
return None
|
||||||
|
return 100.0 * (1.0 - du.free / du.total)
|
||||||
|
|
||||||
|
|
||||||
|
SAMPLER = Sampler()
|
||||||
|
DATA = {"cpu": 0.0, "mem": 0.0, "net": 0.0, "disk": 0.0}
|
||||||
|
|
||||||
|
|
||||||
|
def sample():
|
||||||
|
v = SAMPLER.cpu()
|
||||||
|
if v is not None:
|
||||||
|
DATA["cpu"] = v
|
||||||
|
v = SAMPLER.mem()
|
||||||
|
if v is not None:
|
||||||
|
DATA["mem"] = v
|
||||||
|
v = SAMPLER.net_kbps()
|
||||||
|
if v is not None:
|
||||||
|
DATA["net"] = v
|
||||||
|
v = SAMPLER.disk()
|
||||||
|
if v is not None:
|
||||||
|
DATA["disk"] = v
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# App shell (same pattern as the generated widget examples: GTK window +
|
||||||
|
# DrawingArea, widgets drawn via widget.draw(cr))
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
_DESIGN_SIZE = (1024, 768)
|
||||||
|
_BACKGROUND = ""
|
||||||
|
_WIDGETS = []
|
||||||
|
_AREA = []
|
||||||
|
|
||||||
|
|
||||||
|
def _build_widgets():
|
||||||
|
widgets = []
|
||||||
|
badge = create("XLoadBadge", "badge", 16, 12, 992, 84)
|
||||||
|
widgets.append(badge)
|
||||||
|
cpu = create("XSysBox", "cpu", 16, 108, 488, 200)
|
||||||
|
cpu.set_prop("label", "CPU")
|
||||||
|
cpu.set_prop("unit", "%")
|
||||||
|
cpu.set_prop("maximum", "100")
|
||||||
|
widgets.append(cpu)
|
||||||
|
mem = create("XSysBox", "mem", 520, 108, 488, 200)
|
||||||
|
mem.set_prop("label", "MEM")
|
||||||
|
mem.set_prop("unit", "%")
|
||||||
|
mem.set_prop("maximum", "100")
|
||||||
|
widgets.append(mem)
|
||||||
|
net = create("XSysBox", "net", 16, 320, 488, 200)
|
||||||
|
net.set_prop("label", "NET")
|
||||||
|
net.set_prop("unit", " KB/s")
|
||||||
|
net.set_prop("maximum", "1000")
|
||||||
|
widgets.append(net)
|
||||||
|
disk = create("XSysBox", "disk", 520, 320, 488, 200)
|
||||||
|
disk.set_prop("label", "DISK /")
|
||||||
|
disk.set_prop("unit", "%")
|
||||||
|
disk.set_prop("maximum", "100")
|
||||||
|
widgets.append(disk)
|
||||||
|
donut_cpu = create("XDonutGauge", "donut_cpu", 16, 532, 180, 180)
|
||||||
|
donut_cpu.set_prop("label", "CPU")
|
||||||
|
donut_cpu.set_prop("unit", "CPU")
|
||||||
|
widgets.append(donut_cpu)
|
||||||
|
donut_disk = create("XDonutGauge", "donut_disk", 212, 532, 180, 180)
|
||||||
|
donut_disk.set_prop("label", "Disk /")
|
||||||
|
donut_disk.set_prop("unit", "Disk /")
|
||||||
|
widgets.append(donut_disk)
|
||||||
|
bar_mem = create("XUsageBar", "bar_mem", 408, 532, 600, 44)
|
||||||
|
bar_mem.set_prop("label", "Memory")
|
||||||
|
bar_mem.set_prop("maximum", "100")
|
||||||
|
widgets.append(bar_mem)
|
||||||
|
bar_disk = create("XUsageBar", "bar_disk", 408, 596, 600, 44)
|
||||||
|
bar_disk.set_prop("label", "Disk /")
|
||||||
|
bar_disk.set_prop("maximum", "100")
|
||||||
|
widgets.append(bar_disk)
|
||||||
|
# UsageBar prints its raw value with a "%" sign, so feed it the
|
||||||
|
# percent-of-1000-KB/s-max, with maximum 100, to keep text + fill true.
|
||||||
|
bar_net = create("XUsageBar", "bar_net", 408, 660, 600, 44)
|
||||||
|
bar_net.set_prop("label", "Network KB/s")
|
||||||
|
bar_net.set_prop("maximum", "100")
|
||||||
|
widgets.append(bar_net)
|
||||||
|
return widgets
|
||||||
|
|
||||||
|
|
||||||
|
def _push(widgets):
|
||||||
|
by_name = {w.name: w for w in widgets}
|
||||||
|
by_name["badge"].refresh_load()
|
||||||
|
for name, key in (("cpu", "cpu"), ("mem", "mem"),
|
||||||
|
("net", "net"), ("disk", "disk")):
|
||||||
|
w = by_name[name]
|
||||||
|
w.push(DATA[key])
|
||||||
|
w.set_value(DATA[key])
|
||||||
|
by_name["donut_cpu"].set_value(DATA["cpu"])
|
||||||
|
by_name["donut_disk"].set_value(DATA["disk"])
|
||||||
|
by_name["bar_mem"].set_value(DATA["mem"])
|
||||||
|
by_name["bar_disk"].set_value(DATA["disk"])
|
||||||
|
by_name["bar_net"].set_value(DATA["net"] / 10.0)
|
||||||
|
|
||||||
|
|
||||||
|
def _tick():
|
||||||
|
sample()
|
||||||
|
_push(_WIDGETS)
|
||||||
|
if _AREA:
|
||||||
|
_AREA[0].queue_draw()
|
||||||
|
return True
|
||||||
|
|
||||||
|
|
||||||
|
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:
|
||||||
|
widget.draw(cr)
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
def _on_key_press(window, event):
|
||||||
|
key = Gdk.keyval_name(event.keyval)
|
||||||
|
if key in ("Escape", "q", "Q"):
|
||||||
|
Gtk.main_quit()
|
||||||
|
return True
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
window = Gtk.Window(title="System Overview - monitor")
|
||||||
|
window.set_default_size(1024, 768)
|
||||||
|
window.connect("destroy", Gtk.main_quit)
|
||||||
|
window.connect("key-press-event", _on_key_press)
|
||||||
|
vbox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=0)
|
||||||
|
window.add(vbox)
|
||||||
|
area = Gtk.DrawingArea()
|
||||||
|
area.set_hexpand(True)
|
||||||
|
area.set_vexpand(True)
|
||||||
|
area.connect("draw", _on_draw)
|
||||||
|
vbox.pack_start(area, True, True, 0)
|
||||||
|
_WIDGETS.extend(_build_widgets())
|
||||||
|
_AREA.append(area)
|
||||||
|
sample()
|
||||||
|
_push(_WIDGETS)
|
||||||
|
GLib.timeout_add(500, _tick)
|
||||||
|
window.show_all()
|
||||||
|
Gtk.main()
|
||||||
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
sys.exit(main())
|
||||||
|
After Width: | Height: | Size: 49 KiB |
@@ -0,0 +1,50 @@
|
|||||||
|
# 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).
|
||||||
@@ -0,0 +1,472 @@
|
|||||||
|
#!/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())
|
||||||
|
After Width: | Height: | Size: 73 KiB |
|
After Width: | Height: | Size: 74 KiB |
@@ -0,0 +1,32 @@
|
|||||||
|
# Temperature Monitor — monitor (Python)
|
||||||
|
|
||||||
|
A btop-style temperature monitor in one 1024x768 window, built only
|
||||||
|
from LightGUI XFrame monitor widgets:
|
||||||
|
|
||||||
|
- **XTempHistory** — temperature history of the first thermal zone,
|
||||||
|
with an 80 C threshold line (readings above it draw red)
|
||||||
|
|
||||||
|
Live data comes from `/sys/class/thermal/thermal_zone*/temp` and
|
||||||
|
`/sys/class/hwmon/hwmon*/temp*_input`, re-scanned every 2 s. On a
|
||||||
|
machine with sensors the history fills with live readings; on this
|
||||||
|
machine (hot_dallas, a VPS with no thermal sensors at all — only
|
||||||
|
cooling devices under `/sys/class/thermal/`, no `thermal_zone*/temp`
|
||||||
|
files, an empty `/sys/class/hwmon/`) the app shows the widget's
|
||||||
|
honest empty state: an empty graph, "no data" in the legend, and a
|
||||||
|
title that says no thermal zones were found. No mock or demo
|
||||||
|
temperatures: the deterministic demo data is dropped at startup with
|
||||||
|
`MonitorWidget.clear()`.
|
||||||
|
|
||||||
|
## Run
|
||||||
|
|
||||||
|
```sh
|
||||||
|
PYTHONPATH=. python3 examples/monitor_temperature_monitor/main.py
|
||||||
|
```
|
||||||
|
|
||||||
|
Esc, `q`, or closing the window quits.
|
||||||
|
|
||||||
|
## Source
|
||||||
|
|
||||||
|
- App: `examples/monitor_temperature_monitor/main.py`
|
||||||
|
- Widget: `lightgui/xframe/monitor.py`
|
||||||
|
- Repo: https://github.com/cnmcdee/lightgui_python
|
||||||
@@ -0,0 +1,168 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Temperature Monitor - monitor (Python).
|
||||||
|
|
||||||
|
A btop-style temperature monitor in one 1024x768 window, built only
|
||||||
|
from LightGUI XFrame monitor widgets (XTempHistory): the first
|
||||||
|
thermal zone's temperature history with an 80 C threshold line,
|
||||||
|
re-scanned every 2 s from /sys/class/thermal/thermal_zone*/temp and
|
||||||
|
/sys/class/hwmon/hwmon*/temp*_input.
|
||||||
|
|
||||||
|
On this machine (hot_dallas, a VPS) there are NO thermal sensors at
|
||||||
|
all: /sys/class/thermal/ holds only cooling devices, there are no
|
||||||
|
thermal_zone*/temp files, /sys/class/hwmon/ is empty and `sensors`
|
||||||
|
is not installed. So the app shows the widget's honest empty state
|
||||||
|
("no data", no line, no fake 0.0 C reading) and says so in the
|
||||||
|
title. No mock or demo temperatures, ever: the deterministic demo
|
||||||
|
data is dropped at startup with MonitorWidget.clear(). If sensors
|
||||||
|
ever appear (e.g. on a machine that has them) the rescan picks them
|
||||||
|
up and the history starts filling with live readings.
|
||||||
|
|
||||||
|
Run with:
|
||||||
|
PYTHONPATH=/root/monitor-wt/temperature-monitor/lightgui_python python3 \\
|
||||||
|
examples/monitor_temperature_monitor/main.py
|
||||||
|
(or from the repo root with PYTHONPATH=. )
|
||||||
|
"""
|
||||||
|
|
||||||
|
import glob
|
||||||
|
import os
|
||||||
|
|
||||||
|
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
|
||||||
|
|
||||||
|
_TITLE = "Temperature Monitor - monitor"
|
||||||
|
_DESIGN_SIZE = (1024, 768)
|
||||||
|
_BACKGROUND = ""
|
||||||
|
_WIDGETS = []
|
||||||
|
_AREA = []
|
||||||
|
_HAD_ZONES = [False]
|
||||||
|
_NO_ZONES_TITLE = "Temperature history -- no thermal zones found"
|
||||||
|
|
||||||
|
|
||||||
|
def _read_first_line(path):
|
||||||
|
try:
|
||||||
|
with open(path) as f:
|
||||||
|
return f.readline().strip()
|
||||||
|
except (OSError, ValueError):
|
||||||
|
return ""
|
||||||
|
|
||||||
|
|
||||||
|
def _read_temp_c(path):
|
||||||
|
try:
|
||||||
|
return int(_read_first_line(path)) / 1000.0
|
||||||
|
except (OSError, ValueError):
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def _scan_zones():
|
||||||
|
"""All temperature inputs the kernel exposes, thermal zones first.
|
||||||
|
|
||||||
|
Each zone is (name, temp-path). Millidegree files that do not
|
||||||
|
parse are skipped, so a half-populated sysfs still yields the
|
||||||
|
zones that do read.
|
||||||
|
"""
|
||||||
|
zones = []
|
||||||
|
for temp_path in sorted(glob.glob("/sys/class/thermal/thermal_zone*/temp")):
|
||||||
|
if _read_temp_c(temp_path) is None:
|
||||||
|
continue
|
||||||
|
base = os.path.dirname(temp_path)
|
||||||
|
label = _read_first_line(os.path.join(base, "type"))
|
||||||
|
zones.append((label or os.path.basename(base), temp_path))
|
||||||
|
for temp_path in sorted(glob.glob("/sys/class/hwmon/hwmon*/temp*_input")):
|
||||||
|
if _read_temp_c(temp_path) is None:
|
||||||
|
continue
|
||||||
|
base = os.path.dirname(temp_path)
|
||||||
|
chip = _read_first_line(os.path.join(base, "name")) or \
|
||||||
|
os.path.basename(base)
|
||||||
|
stem = os.path.basename(temp_path)[:-len("_input")]
|
||||||
|
label = _read_first_line(os.path.join(base, stem + "_label"))
|
||||||
|
zones.append((("%s %s" % (chip, label)) if label else chip,
|
||||||
|
temp_path))
|
||||||
|
return zones
|
||||||
|
|
||||||
|
|
||||||
|
def _build_widgets():
|
||||||
|
"""Create every placed widget with its props."""
|
||||||
|
temp = create("XTempHistory", "TempHistory_001", 16, 16, 992, 736)
|
||||||
|
temp.set_prop("label", _NO_ZONES_TITLE)
|
||||||
|
temp.set_prop("threshold", "80")
|
||||||
|
# Drop the deterministic demo data: with no live source the
|
||||||
|
# honest state is an empty graph, not a fake warm-up curve.
|
||||||
|
temp.clear()
|
||||||
|
return [temp]
|
||||||
|
|
||||||
|
|
||||||
|
def _apply_scan():
|
||||||
|
"""Re-scan sysfs and feed the first zone's live reading (if any)."""
|
||||||
|
(temp,) = _WIDGETS
|
||||||
|
zones = _scan_zones()
|
||||||
|
if not zones:
|
||||||
|
if _HAD_ZONES[0]:
|
||||||
|
_HAD_ZONES[0] = False
|
||||||
|
temp.clear()
|
||||||
|
temp.set_prop("label", _NO_ZONES_TITLE)
|
||||||
|
return
|
||||||
|
name, path = zones[0]
|
||||||
|
if not _HAD_ZONES[0]:
|
||||||
|
_HAD_ZONES[0] = True
|
||||||
|
temp.set_prop("label", "Temperature history -- %s" % name)
|
||||||
|
value = _read_temp_c(path)
|
||||||
|
if value is not None:
|
||||||
|
temp.push(value)
|
||||||
|
|
||||||
|
|
||||||
|
def _tick():
|
||||||
|
"""2 s tick: re-scan sysfs, then redraw."""
|
||||||
|
_apply_scan()
|
||||||
|
if _AREA:
|
||||||
|
_AREA[0].queue_draw()
|
||||||
|
return True
|
||||||
|
|
||||||
|
|
||||||
|
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:
|
||||||
|
widget.draw(cr)
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
def _on_key_press(window, event):
|
||||||
|
if event.keyval in (Gdk.KEY_Escape, Gdk.KEY_q):
|
||||||
|
Gtk.main_quit()
|
||||||
|
return True
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
window = Gtk.Window(title=_TITLE)
|
||||||
|
window.set_default_size(*_DESIGN_SIZE)
|
||||||
|
window.set_resizable(False)
|
||||||
|
window.connect("destroy", Gtk.main_quit)
|
||||||
|
window.connect("key-press-event", _on_key_press)
|
||||||
|
area = Gtk.DrawingArea()
|
||||||
|
area.set_hexpand(True)
|
||||||
|
area.set_vexpand(True)
|
||||||
|
area.connect("draw", _on_draw)
|
||||||
|
window.add(area)
|
||||||
|
_WIDGETS.extend(_build_widgets())
|
||||||
|
_AREA.append(area)
|
||||||
|
# First scan before the first paint, so the title already tells
|
||||||
|
# the truth on screen one.
|
||||||
|
_apply_scan()
|
||||||
|
GLib.timeout_add(2000, _tick)
|
||||||
|
window.show_all()
|
||||||
|
Gtk.main()
|
||||||
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
import sys
|
||||||
|
sys.exit(main())
|
||||||
|
After Width: | Height: | Size: 8.8 KiB |
@@ -153,16 +153,58 @@ 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()]
|
||||||
@@ -177,20 +219,9 @@ 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])
|
||||||
with open("/proc/%s/status" % pid) as handle:
|
starttime = int(rest[19])
|
||||||
uid = None
|
mem_kb = int(rest[21]) * _PAGE_KB
|
||||||
mem_kb = 0
|
user = _user_for(pid, starttime)
|
||||||
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,
|
||||||
@@ -440,6 +471,10 @@ class MonitorWidget(Widget):
|
|||||||
self._segments = None
|
self._segments = None
|
||||||
# Process rows for XProcessList: None = demo rows.
|
# Process rows for XProcessList: None = demo rows.
|
||||||
self._rows = None
|
self._rows = None
|
||||||
|
# Row selection (pid; None = none) + substring filter on
|
||||||
|
# name (case-insensitive) or pid (empty = show all).
|
||||||
|
self._selected_pid = None
|
||||||
|
self._filter = ""
|
||||||
self._prev_proc = None
|
self._prev_proc = None
|
||||||
self._prev_times = None
|
self._prev_times = None
|
||||||
# /proc/stat snapshot for XCoreGrid.refresh().
|
# /proc/stat snapshot for XCoreGrid.refresh().
|
||||||
@@ -501,6 +536,19 @@ class MonitorWidget(Widget):
|
|||||||
return list(self._series[series])
|
return list(self._series[series])
|
||||||
return list(self._plot_series()[series])
|
return list(self._plot_series()[series])
|
||||||
|
|
||||||
|
def clear(self):
|
||||||
|
"""Drop every sample from the history series (and reset the
|
||||||
|
peak hold), keeping the series slots: a host app that found
|
||||||
|
no live data yet shows the widget's honest empty state
|
||||||
|
("no data") instead of the deterministic demo series.
|
||||||
|
Later push() calls fill the kept slots again as usual."""
|
||||||
|
if self._series is not None:
|
||||||
|
self._series = [[] for _ in self._series]
|
||||||
|
else:
|
||||||
|
self._series = [[]]
|
||||||
|
self._peak = 0.0
|
||||||
|
self._mark_dirty()
|
||||||
|
|
||||||
def series_count(self):
|
def series_count(self):
|
||||||
"""Number of series this widget plots."""
|
"""Number of series this widget plots."""
|
||||||
if self._series is not None:
|
if self._series is not None:
|
||||||
@@ -656,8 +704,66 @@ class MonitorWidget(Widget):
|
|||||||
if column in keys:
|
if column in keys:
|
||||||
self.set_prop("sort-by", labels[keys.index(column)])
|
self.set_prop("sort-by", labels[keys.index(column)])
|
||||||
|
|
||||||
|
def set_filter(self, text):
|
||||||
|
"""Substring filter on process name (case-insensitive) or
|
||||||
|
pid. Applied when the rows are sorted for display, so it
|
||||||
|
never drops the loaded rows; the next refresh re-applies it."""
|
||||||
|
self._filter = (text or "").strip().lower()
|
||||||
|
self._mark_dirty()
|
||||||
|
|
||||||
|
def get_filter(self):
|
||||||
|
"""The current filter text (lowercased, stripped)."""
|
||||||
|
return self._filter
|
||||||
|
|
||||||
|
def selected_pid(self):
|
||||||
|
"""Pid of the selected row, or None when the selection is
|
||||||
|
gone (e.g. the process exited)."""
|
||||||
|
if self._selected_pid is None:
|
||||||
|
return None
|
||||||
|
if any(r["pid"] == self._selected_pid for r in self.get_rows()):
|
||||||
|
return self._selected_pid
|
||||||
|
return None
|
||||||
|
|
||||||
|
def select_at(self, px, py):
|
||||||
|
"""Widget-relative click: a header click sorts (toggling
|
||||||
|
direction on the same column), a body click selects the row
|
||||||
|
(stored as a pid, so a refresh keeps it). Returns True when
|
||||||
|
the click landed on the list."""
|
||||||
|
indexes = {"cpu": 0, "mem": 1, "pid": 2, "name": 3}
|
||||||
|
if py < 40:
|
||||||
|
if px < 62:
|
||||||
|
col = "pid"
|
||||||
|
elif px < 196:
|
||||||
|
col = "name"
|
||||||
|
elif px < 244:
|
||||||
|
col = "name"
|
||||||
|
elif px < 296:
|
||||||
|
col = "mem"
|
||||||
|
else:
|
||||||
|
col = "cpu"
|
||||||
|
if _prop_int(self, "sort-by", 0) == indexes[col]:
|
||||||
|
self.set_prop("sort-desc",
|
||||||
|
"false" if _prop_bool(self, "sort-desc", True)
|
||||||
|
else "true")
|
||||||
|
else:
|
||||||
|
self.sort_by(col)
|
||||||
|
self.set_prop("sort-desc",
|
||||||
|
"true" if col in ("cpu", "mem") else "false")
|
||||||
|
return True
|
||||||
|
rows = self._sorted_rows()
|
||||||
|
row = (py - 40) // 18
|
||||||
|
if 0 <= row < len(rows):
|
||||||
|
self._selected_pid = rows[row]["pid"]
|
||||||
|
self._mark_dirty()
|
||||||
|
return True
|
||||||
|
return False
|
||||||
|
|
||||||
def _sorted_rows(self):
|
def _sorted_rows(self):
|
||||||
rows = self.get_rows()
|
rows = self.get_rows()
|
||||||
|
if self._filter:
|
||||||
|
f = self._filter
|
||||||
|
rows = [r for r in rows
|
||||||
|
if f in r["name"].lower() or f in str(r["pid"])]
|
||||||
col = _prop_int(self, "sort-by", 0)
|
col = _prop_int(self, "sort-by", 0)
|
||||||
key = {0: "cpu", 1: "mem_kb", 2: "pid", 3: "name"}.get(col, "cpu")
|
key = {0: "cpu", 1: "mem_kb", 2: "pid", 3: "name"}.get(col, "cpu")
|
||||||
reverse = _prop_bool(self, "sort-desc", True)
|
reverse = _prop_bool(self, "sort-desc", True)
|
||||||
@@ -983,10 +1089,15 @@ class MonitorWidget(Widget):
|
|||||||
threshold = _prop_float(self, "threshold", 80.0)
|
threshold = _prop_float(self, "threshold", 80.0)
|
||||||
values = self._single_series(58.0, 24.0, 0.0, 120.0)
|
values = self._single_series(58.0, 24.0, 0.0, 120.0)
|
||||||
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
|
if values:
|
||||||
cur_rgb = _RED if cur > threshold else _TEXT
|
cur = values[-1]
|
||||||
_wtext(cr, self, "%.1f C" % cur, self.width - 8, 15, size=14,
|
cur_rgb = _RED if cur > threshold else _TEXT
|
||||||
rgb=cur_rgb, align="right", bold=True)
|
_wtext(cr, self, "%.1f C" % cur, self.width - 8, 15, size=14,
|
||||||
|
rgb=cur_rgb, align="right", bold=True)
|
||||||
|
else:
|
||||||
|
# Honest empty state: no samples, no reading to show.
|
||||||
|
_wtext(cr, self, "no data", self.width - 8, 15, size=14,
|
||||||
|
rgb=_DIM, align="right", bold=True)
|
||||||
plot_x, plot_y = 34, top + 2
|
plot_x, plot_y = 34, top + 2
|
||||||
plot_w = max(1, self.width - 40)
|
plot_w = max(1, self.width - 40)
|
||||||
plot_h = max(1, self.height - plot_y - 20)
|
plot_h = max(1, self.height - plot_y - 20)
|
||||||
@@ -1193,6 +1304,7 @@ class MonitorWidget(Widget):
|
|||||||
ly = cy + (r - 26) * math.sin(ang) + 3
|
ly = cy + (r - 26) * math.sin(ang) + 3
|
||||||
_wtext(cr, self, label, lx, ly, size=9, rgb=_TEXT,
|
_wtext(cr, self, label, lx, ly, size=9, rgb=_TEXT,
|
||||||
align="center")
|
align="center")
|
||||||
|
cr.restore()
|
||||||
# Peak-hold tick.
|
# Peak-hold tick.
|
||||||
cr.save()
|
cr.save()
|
||||||
_rgb(cr, _WHITE)
|
_rgb(cr, _WHITE)
|
||||||
@@ -1274,16 +1386,29 @@ class MonitorWidget(Widget):
|
|||||||
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()
|
||||||
cols = ((6, 52, "PID", "left"), (62, 130, "Program", "left"),
|
# Column x-offsets as fractions of the inner width (same
|
||||||
(196, 44, "User", "left"), (244, 48, "Mem", "right"),
|
# fractions as the C++ widget: PID / Program / User / Mem /
|
||||||
(296, 56, "CPU%", "right"))
|
# CPU%). The old fixed offsets were drawn for the 360px demo
|
||||||
|
# widget and left a wide widget mostly empty.
|
||||||
|
iw = max(60, self.width - 12)
|
||||||
|
xs = [6 + int(iw * f) for f in (0.0, 0.14, 0.52, 0.68, 0.82, 1.0)]
|
||||||
|
# (x, label, sort key): sort keys follow _sorted_rows
|
||||||
|
# (0 cpu, 1 mem, 2 pid, 3 name); User has no sort key.
|
||||||
|
sort_col = _prop_int(self, "sort-by", 0)
|
||||||
|
sort_desc = _prop_bool(self, "sort-desc", True)
|
||||||
|
headers = [(xs[0], "PID", 2, "left"), (xs[1], "Program", 3, "left"),
|
||||||
|
(xs[2], "User", None, "left"), (xs[4], "Mem", 1, "right"),
|
||||||
|
(xs[5], "CPU%", 0, "right")]
|
||||||
header_y = top + 13
|
header_y = top + 13
|
||||||
for x, _w, name, align in cols:
|
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, name, x + _w, header_y, size=10,
|
_wtext(cr, self, label, x - 4, header_y, size=10,
|
||||||
rgb=_DIM, align="right", bold=True)
|
rgb=_DIM, align="right", bold=True)
|
||||||
else:
|
else:
|
||||||
_wtext(cr, self, name, x, header_y, size=10,
|
_wtext(cr, self, label, x, header_y, size=10,
|
||||||
rgb=_DIM, bold=True)
|
rgb=_DIM, bold=True)
|
||||||
row_h = 18
|
row_h = 18
|
||||||
y0 = top + 18
|
y0 = top + 18
|
||||||
@@ -1299,17 +1424,22 @@ 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"]), 6, y + 13, size=10,
|
if (self._selected_pid is not None
|
||||||
|
and row["pid"] == self._selected_pid):
|
||||||
|
_rgb(cr, (0.86, 0.92, 0.99))
|
||||||
|
cr.rectangle(0, y, self.width, row_h)
|
||||||
|
cr.fill()
|
||||||
|
_wtext(cr, self, str(row["pid"]), xs[0], y + 13, size=10,
|
||||||
rgb=_TEXT)
|
rgb=_TEXT)
|
||||||
_wtext(cr, self, row["name"], 62, y + 13, size=10,
|
_wtext(cr, self, row["name"], xs[1], y + 13, size=10,
|
||||||
rgb=_TEXT,
|
rgb=_TEXT,
|
||||||
max_width=128)
|
max_width=xs[2] - xs[1] - 6)
|
||||||
_wtext(cr, self, row["user"], 196, y + 13, size=10,
|
_wtext(cr, self, row["user"], xs[2], y + 13, size=10,
|
||||||
rgb=_TEXT, max_width=44)
|
rgb=_TEXT, max_width=xs[3] - xs[2] - 6)
|
||||||
_wtext(cr, self, _fmt_bytes(row["mem_kb"] * 1024), 292,
|
_wtext(cr, self, _fmt_bytes(row["mem_kb"] * 1024), xs[4] - 4,
|
||||||
y + 13, size=10, rgb=_TEXT, align="right")
|
y + 13, size=10, rgb=_TEXT, align="right")
|
||||||
# In-cell CPU% bar behind the number.
|
# In-cell CPU% bar behind the number.
|
||||||
bar_x, bar_w = 300, 52
|
bar_x, bar_w = xs[4] + 2, xs[5] - xs[4] - 6
|
||||||
_box(cr, bar_x, y + 3, bar_w, 12, (0.20, 0.20, 0.23),
|
_box(cr, bar_x, y + 3, 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))
|
||||||
|
|||||||
@@ -162,6 +162,19 @@ class HistoryDataTests(unittest.TestCase):
|
|||||||
graph.push(42.0)
|
graph.push(42.0)
|
||||||
self.assertEqual(graph.get_series(0), [42.0])
|
self.assertEqual(graph.get_series(0), [42.0])
|
||||||
|
|
||||||
|
def test_clear_drops_demo_series(self):
|
||||||
|
# clear() empties the history so a widget with no live source
|
||||||
|
# shows its honest empty state instead of the demo series.
|
||||||
|
temp = core.create("XTempHistory", "XTempHistory_001")
|
||||||
|
self.assertEqual(
|
||||||
|
len(temp._single_series(58.0, 24.0, 0.0, 120.0)), 60)
|
||||||
|
temp.clear()
|
||||||
|
self.assertEqual(temp._single_series(58.0, 24.0, 0.0, 120.0), [])
|
||||||
|
_draw(temp) # empty state draws without error
|
||||||
|
temp.push(42.0)
|
||||||
|
self.assertEqual(
|
||||||
|
temp._single_series(58.0, 24.0, 0.0, 120.0), [42.0])
|
||||||
|
|
||||||
def test_push_trims_to_window(self):
|
def test_push_trims_to_window(self):
|
||||||
graph = core.create("XHistoryGraph", "XHistoryGraph_001")
|
graph = core.create("XHistoryGraph", "XHistoryGraph_001")
|
||||||
graph.set_prop("window", 5)
|
graph.set_prop("window", 5)
|
||||||
@@ -413,3 +426,49 @@ class PropsTests(unittest.TestCase):
|
|||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
unittest.main()
|
unittest.main()
|
||||||
|
|
||||||
|
|
||||||
|
class ProcessListFilterSelectionTests(unittest.TestCase):
|
||||||
|
"""Filter + row selection added for the Process Manager app."""
|
||||||
|
|
||||||
|
def _procs(self):
|
||||||
|
procs = core.create("XProcessList", "XProcessList_001")
|
||||||
|
procs.set_rows([
|
||||||
|
{"pid": 9, "name": "btop", "user": "root", "mem_kb": 10,
|
||||||
|
"cpu": 1.0},
|
||||||
|
{"pid": 3, "name": "alpha", "user": "root", "mem_kb": 20,
|
||||||
|
"cpu": 9.0},
|
||||||
|
{"pid": 5, "name": "beta", "user": "root", "mem_kb": 30,
|
||||||
|
"cpu": 5.0},
|
||||||
|
])
|
||||||
|
return procs
|
||||||
|
|
||||||
|
def test_filter_by_name_and_pid(self):
|
||||||
|
procs = self._procs()
|
||||||
|
procs.set_filter("alp")
|
||||||
|
self.assertEqual([r["pid"] for r in procs._sorted_rows()], [3])
|
||||||
|
procs.set_filter("9")
|
||||||
|
self.assertEqual([r["pid"] for r in procs._sorted_rows()], [9])
|
||||||
|
procs.set_filter("")
|
||||||
|
self.assertEqual(len(procs._sorted_rows()), 3)
|
||||||
|
|
||||||
|
def test_select_at_body_row_and_header_sort(self):
|
||||||
|
procs = self._procs()
|
||||||
|
# Default sort is CPU desc: alpha(9), beta(5), btop(1).
|
||||||
|
# Body click on the first row (y=40 is row 0) selects pid 3.
|
||||||
|
self.assertTrue(procs.select_at(100, 40))
|
||||||
|
self.assertEqual(procs.selected_pid(), 3)
|
||||||
|
# Header click on the PID column sorts by pid ascending.
|
||||||
|
self.assertTrue(procs.select_at(10, 30))
|
||||||
|
self.assertEqual([r["pid"] for r in procs._sorted_rows()],
|
||||||
|
[3, 5, 9])
|
||||||
|
# Selection survives the re-sort (stored as a pid).
|
||||||
|
self.assertEqual(procs.selected_pid(), 3)
|
||||||
|
|
||||||
|
def test_selected_pid_none_when_row_gone(self):
|
||||||
|
procs = self._procs()
|
||||||
|
procs.select_at(100, 40)
|
||||||
|
self.assertEqual(procs.selected_pid(), 3)
|
||||||
|
procs.set_rows([{"pid": 9, "name": "btop", "user": "root",
|
||||||
|
"mem_kb": 10, "cpu": 1.0}])
|
||||||
|
self.assertIsNone(procs.selected_pid())
|
||||||