Author SHA1 Message Date
Muse 9cbabb9d71 Memory monitor app (Stage 2): Python implementation + screenshot 2026-12-05 20:08:26 +00:00
6 changed files with 281 additions and 293 deletions

No files matched your search

+33
View File
@@ -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`).
+248
View File
@@ -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())
Binary file not shown.

After

Width:  |  Height:  |  Size: 40 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