Author SHA1 Message Date
Muse b197a366ec Disk Monitor app (Stage 2): live per-mount usage bars, Used/Free stack bar, read/write IO history graph
1024x768 window, 1 s refresh from /proc/mounts + os.statvfs and
/proc/diskstats. XUsageBar + XStackBar + XHistoryGraph; seeded demo
data replaced on first tick (push/set_segments start fresh own
data). Harness background is the widgets near-black panel color
(XStackBar paints no panel of its own). XSysBox deliberately unused
(no clear-history API, constructor seeds 60 demo samples).
Screenshot verified 1024x768 on :116. Tests: 363 OK.
2026-12-05 20:13:54 +00:00
6 changed files with 244 additions and 293 deletions

No files matched your search

+47
View File
@@ -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
![Disk Monitor (Python)](screenshot.png)
## 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
+197
View File
@@ -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())
Binary file not shown.

After

Width:  |  Height:  |  Size: 33 KiB

@@ -1,37 +0,0 @@
# 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/
-256
View File
@@ -1,256 +0,0 @@
#!/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())
Binary file not shown.

Before

Width:  |  Height:  |  Size: 49 KiB