Compare commits
4
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
eb794c83cc | ||
|
|
9cdf8a3102 | ||
|
|
11f7dd70e6 | ||
|
|
b4add9ba7b |
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())
|
||||||
Binary file not shown.
|
After Width: | Height: | Size: 85 KiB |
@@ -1,50 +0,0 @@
|
|||||||
# Task Manager — monitor app (Python)
|
|
||||||
|
|
||||||
A Windows-style Task Manager clone in one 1024x768 window, tabbed
|
|
||||||
with `TPageControl`. Built with the LightGUI XFrame widgets (Python
|
|
||||||
port) and live `/proc` data — no seeded demo data survives the
|
|
||||||
first tick.
|
|
||||||
|
|
||||||
## What it shows
|
|
||||||
|
|
||||||
* **Processes tab** — `XProcessList` with live processes from
|
|
||||||
`/proc` (PID / Program / User / Mem / CPU%). Click a column
|
|
||||||
header to sort (clicking the current column toggles the
|
|
||||||
direction); rows refresh every 2 s. CPU% is per-core (100% = one
|
|
||||||
core), computed from wall-time deltas between scans.
|
|
||||||
* **Performance tab** — `XHistoryGraph` (60 s CPU + memory),
|
|
||||||
`XCoreGrid` (per-core busy %), `XUsageBar` (Memory, Disk /,
|
|
||||||
Swap), `XStackBar` (memory breakdown: Used / Cached / Buffers /
|
|
||||||
Free) and `XNetGraph` (live down/up rates from `/proc/net/dev`
|
|
||||||
with accumulated totals).
|
|
||||||
|
|
||||||
## Run
|
|
||||||
|
|
||||||
```sh
|
|
||||||
PYTHONPATH=/root/monitor-wt/task-manager/lightgui_python \
|
|
||||||
python3 examples/monitor_task_manager/main.py
|
|
||||||
```
|
|
||||||
|
|
||||||
Data is sampled every 500 ms (GLib timeout); the window repaints
|
|
||||||
every 2 s (a full redraw is ~38 process rows x 5 text calls plus the
|
|
||||||
graphs, and repainting every tick burned ~40% of a core). Close the
|
|
||||||
window to quit. The Python monitor widgets draw dark btop-style
|
|
||||||
panels, so the window background is dark (`#1a1a1e`).
|
|
||||||
|
|
||||||
## Notes
|
|
||||||
|
|
||||||
* The `TPageControl` draws its tabs itself but tab clicks need
|
|
||||||
app-level hit handling (fixed `tab-width` 140, so the hit math is
|
|
||||||
deterministic); the `XProcessList` sort also needs app-level
|
|
||||||
header hit handling, using the same column fractions as the
|
|
||||||
widget's draw.
|
|
||||||
* The `XProcessList` columns are width-relative (same fractions as
|
|
||||||
the C++ widget) — the widget fix lives in
|
|
||||||
`lightgui/xframe/monitor.py` on this branch: the old fixed
|
|
||||||
offsets were drawn for the 360px demo widget and left a wide
|
|
||||||
widget mostly empty; the header also now shows the sort column
|
|
||||||
with a `v`/`^` marker.
|
|
||||||
* `refresh_processes()` needs two samples before CPU% is real, so
|
|
||||||
the app primes it twice at startup; the graphs are primed with
|
|
||||||
60 live samples (the net graph is primed with `push()`, not
|
|
||||||
`push_net()`, so priming does not inflate the totals).
|
|
||||||
@@ -1,472 +0,0 @@
|
|||||||
#!/usr/bin/env python3
|
|
||||||
# Task Manager - monitor app (Stage 2, btop-widget project).
|
|
||||||
#
|
|
||||||
# A Windows-style Task Manager clone in one 1024x768 window, tabbed
|
|
||||||
# with TPageControl: the Processes tab is a live XProcessList from
|
|
||||||
# /proc (sortable PID / Program / User / Mem / CPU% columns), and the
|
|
||||||
# Performance tab is XHistoryGraph (60 s CPU + memory), XCoreGrid
|
|
||||||
# (per-core), XUsageBar (Memory, Disk /, Swap), XStackBar (memory
|
|
||||||
# breakdown) and XNetGraph (live /proc/net/dev rates). All data is
|
|
||||||
# live: no seeded demo data survives the first tick.
|
|
||||||
#
|
|
||||||
# Run with:
|
|
||||||
# PYTHONPATH=<lightgui_python> python3 examples/monitor_task_manager/main.py
|
|
||||||
# Close the window to quit. Data is sampled every 500 ms; the
|
|
||||||
# window repaints every 2 s and the process list refreshes then.
|
|
||||||
#
|
|
||||||
# Widgets used (all from the LightGUI registry; no raw Cairo drawing
|
|
||||||
# for UI elements — the only direct drawing here is the harness
|
|
||||||
# background paint, as in the generated examples):
|
|
||||||
# TPageControl, XProcessList, XHistoryGraph, XCoreGrid, XUsageBar,
|
|
||||||
# XStackBar, XNetGraph.
|
|
||||||
#
|
|
||||||
# The TPageControl draws its tabs itself but tab clicks need
|
|
||||||
# app-level hit handling (fixed tab-width 140, so the hit math is
|
|
||||||
# deterministic); the XProcessList sort also needs app-level header
|
|
||||||
# hit handling (same column fractions as the widget's draw).
|
|
||||||
|
|
||||||
import os
|
|
||||||
import sys
|
|
||||||
import time
|
|
||||||
|
|
||||||
import gi
|
|
||||||
|
|
||||||
gi.require_version("Gtk", "3.0")
|
|
||||||
gi.require_version("Gdk", "3.0")
|
|
||||||
|
|
||||||
from gi.repository import Gdk, GLib, Gtk # noqa: E402
|
|
||||||
from lightgui.xframe.core import create, parse_color # noqa: E402
|
|
||||||
|
|
||||||
# --- design geometry -------------------------------------------------------
|
|
||||||
_DESIGN_SIZE = (1024, 768)
|
|
||||||
_BACKGROUND = "#1a1a1e"
|
|
||||||
_WIDGETS = []
|
|
||||||
_LAST_SIZE = [None]
|
|
||||||
_PRESSED = [None]
|
|
||||||
_AREA = []
|
|
||||||
|
|
||||||
# Page widgets (drawn after the tab control, only the active page):
|
|
||||||
_PAGE = [0]
|
|
||||||
_PAGE_WIDGETS = [[], []]
|
|
||||||
|
|
||||||
# Live-data state:
|
|
||||||
_TICK = [0]
|
|
||||||
_PREV_CPU = [None] # (idle, total) for the aggregate cpu line
|
|
||||||
_PREV_NET = [None] # (rx_bytes, tx_bytes)
|
|
||||||
_SORT_KEYS = ("cpu", "mem", "pid", "name")
|
|
||||||
|
|
||||||
|
|
||||||
def _build_widgets():
|
|
||||||
"""Create every placed widget with its props."""
|
|
||||||
widgets = []
|
|
||||||
tabs = create("TPageControl", "TPageControl_001", 8, 8, 1008, 752,
|
|
||||||
props={"pages": "Processes|Performance", "page": "0",
|
|
||||||
"tab-width": "140"})
|
|
||||||
widgets.append(tabs)
|
|
||||||
|
|
||||||
proc = create("XProcessList", "XProcessList_001", 14, 38, 996, 712,
|
|
||||||
props={"label": "Processes"})
|
|
||||||
widgets.append(proc)
|
|
||||||
|
|
||||||
hist = create("XHistoryGraph", "XHistoryGraph_001", 14, 38, 630, 300,
|
|
||||||
props={"label": "CPU + Memory (60 s)", "minimum": "0",
|
|
||||||
"maximum": "100", "window": "60",
|
|
||||||
"series-count": "2",
|
|
||||||
"series-names": "CPU %|Memory %"})
|
|
||||||
widgets.append(hist)
|
|
||||||
|
|
||||||
cores = create("XCoreGrid", "XCoreGrid_001", 652, 38, 354, 300,
|
|
||||||
props={"label": "CPU cores", "window": "60"})
|
|
||||||
widgets.append(cores)
|
|
||||||
|
|
||||||
membar = create("XUsageBar", "XUsageBar_Mem", 14, 346, 640, 34,
|
|
||||||
props={"label": "Memory", "minimum": "0",
|
|
||||||
"maximum": "100"})
|
|
||||||
widgets.append(membar)
|
|
||||||
|
|
||||||
memstack = create("XStackBar", "XStackBar_Mem", 14, 388, 640, 60,
|
|
||||||
props={"label": "Memory"})
|
|
||||||
widgets.append(memstack)
|
|
||||||
|
|
||||||
diskbar = create("XUsageBar", "XUsageBar_Disk", 662, 346, 344, 34,
|
|
||||||
props={"label": "Disk /", "minimum": "0",
|
|
||||||
"maximum": "100"})
|
|
||||||
widgets.append(diskbar)
|
|
||||||
|
|
||||||
swapbar = create("XUsageBar", "XUsageBar_Swap", 662, 388, 344, 34,
|
|
||||||
props={"label": "Swap", "minimum": "0",
|
|
||||||
"maximum": "100"})
|
|
||||||
widgets.append(swapbar)
|
|
||||||
|
|
||||||
net = create("XNetGraph", "XNetGraph_001", 14, 456, 992, 294,
|
|
||||||
props={"label": "Network", "window": "60"})
|
|
||||||
widgets.append(net)
|
|
||||||
|
|
||||||
_PAGE_WIDGETS[0] = [proc]
|
|
||||||
_PAGE_WIDGETS[1] = [hist, cores, membar, memstack, diskbar, swapbar,
|
|
||||||
net]
|
|
||||||
return widgets
|
|
||||||
|
|
||||||
|
|
||||||
_ANCHORS = {
|
|
||||||
"TPageControl_001": (True, True, False, False, 8, 8, 1008, 752),
|
|
||||||
"XProcessList_001": (True, True, False, False, 14, 38, 996, 712),
|
|
||||||
"XHistoryGraph_001": (True, True, False, False, 14, 38, 630, 300),
|
|
||||||
"XCoreGrid_001": (True, True, False, False, 652, 38, 354, 300),
|
|
||||||
"XUsageBar_Mem": (True, True, False, False, 14, 346, 640, 34),
|
|
||||||
"XStackBar_Mem": (True, True, False, False, 14, 388, 640, 60),
|
|
||||||
"XUsageBar_Disk": (True, True, False, False, 662, 346, 344, 34),
|
|
||||||
"XUsageBar_Swap": (True, True, False, False, 662, 388, 344, 34),
|
|
||||||
"XNetGraph_001": (True, True, False, False, 14, 456, 992, 294),
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
def _by_name(name):
|
|
||||||
for widget in _WIDGETS:
|
|
||||||
if widget.name == name:
|
|
||||||
return widget
|
|
||||||
return None
|
|
||||||
|
|
||||||
|
|
||||||
def _apply_anchors(widgets, width, height):
|
|
||||||
"""Reposition anchored widgets for a drawing area of
|
|
||||||
*width* x *height* (Flag 1: minimal anchor layout)."""
|
|
||||||
design_w, design_h = _DESIGN_SIZE
|
|
||||||
dx = width - design_w
|
|
||||||
dy = height - design_h
|
|
||||||
for widget in widgets:
|
|
||||||
top, left, right, bottom, ox, oy, ow, oh = \
|
|
||||||
_ANCHORS[widget.name]
|
|
||||||
x, y, w, h = ox, oy, ow, oh
|
|
||||||
if right and not left:
|
|
||||||
x = ox + dx
|
|
||||||
elif right and left:
|
|
||||||
w = ow + dx
|
|
||||||
if bottom and not top:
|
|
||||||
y = oy + dy
|
|
||||||
elif bottom and top:
|
|
||||||
h = oh + dy
|
|
||||||
widget.move_to(x, y)
|
|
||||||
widget.resize_to(w, h)
|
|
||||||
|
|
||||||
|
|
||||||
# --- live /proc data ---------------------------------------------------------
|
|
||||||
|
|
||||||
def _read_cpu():
|
|
||||||
"""(aggregate (idle, total), {core: (idle, total)}) from /proc/stat."""
|
|
||||||
total = None
|
|
||||||
cores = {}
|
|
||||||
try:
|
|
||||||
with open("/proc/stat") as f:
|
|
||||||
for line in f:
|
|
||||||
if not line.startswith("cpu"):
|
|
||||||
continue
|
|
||||||
parts = line.split()
|
|
||||||
if not parts[0][3:].isdigit() and parts[0] != "cpu":
|
|
||||||
continue
|
|
||||||
vals = [int(v) for v in parts[1:]]
|
|
||||||
tot = sum(vals)
|
|
||||||
idle = vals[3] + (vals[4] if len(vals) > 4 else 0)
|
|
||||||
if parts[0] == "cpu":
|
|
||||||
total = (idle, tot)
|
|
||||||
else:
|
|
||||||
cores[int(parts[0][3:])] = (idle, tot)
|
|
||||||
except OSError:
|
|
||||||
return None, {}
|
|
||||||
return total, cores
|
|
||||||
|
|
||||||
|
|
||||||
def _cpu_pct(prev, cur):
|
|
||||||
"""Busy % between two (idle, total) samples."""
|
|
||||||
if prev is None or cur is None:
|
|
||||||
return 0.0
|
|
||||||
d_total = cur[1] - prev[1]
|
|
||||||
d_idle = cur[0] - prev[0]
|
|
||||||
if d_total <= 0:
|
|
||||||
return 0.0
|
|
||||||
return max(0.0, min(100.0, 100.0 * (1.0 - d_idle / d_total)))
|
|
||||||
|
|
||||||
|
|
||||||
def _read_mem():
|
|
||||||
"""(total, avail, free, buffers, cached, swap_total, swap_free) kB."""
|
|
||||||
fields = {}
|
|
||||||
try:
|
|
||||||
with open("/proc/meminfo") as f:
|
|
||||||
for line in f:
|
|
||||||
key, rest = line.split(":", 1)
|
|
||||||
fields[key.strip()] = int(rest.split()[0])
|
|
||||||
except (OSError, ValueError):
|
|
||||||
return None
|
|
||||||
return (fields.get("MemTotal", 0), fields.get("MemAvailable", 0),
|
|
||||||
fields.get("MemFree", 0), fields.get("Buffers", 0),
|
|
||||||
fields.get("Cached", 0), fields.get("SwapTotal", 0),
|
|
||||||
fields.get("SwapFree", 0))
|
|
||||||
|
|
||||||
|
|
||||||
def _read_net():
|
|
||||||
"""(rx_bytes, tx_bytes) summed over non-loopback interfaces."""
|
|
||||||
rx = tx = 0
|
|
||||||
try:
|
|
||||||
with open("/proc/net/dev") as f:
|
|
||||||
for line in f:
|
|
||||||
if ":" not in line:
|
|
||||||
continue
|
|
||||||
iface, rest = line.split(":", 1)
|
|
||||||
if iface.strip() == "lo":
|
|
||||||
continue
|
|
||||||
vals = rest.split()
|
|
||||||
if len(vals) < 16:
|
|
||||||
continue
|
|
||||||
rx += int(vals[0])
|
|
||||||
tx += int(vals[8])
|
|
||||||
except (OSError, ValueError):
|
|
||||||
return None
|
|
||||||
return (rx, tx)
|
|
||||||
|
|
||||||
|
|
||||||
def _disk_pct():
|
|
||||||
"""Used % of the root filesystem."""
|
|
||||||
try:
|
|
||||||
st = os.statvfs("/")
|
|
||||||
total = st.f_blocks * st.f_frsize
|
|
||||||
free = st.f_bavail * st.f_frsize
|
|
||||||
if total <= 0:
|
|
||||||
return 0.0
|
|
||||||
return 100.0 * (1.0 - free / total)
|
|
||||||
except OSError:
|
|
||||||
return 0.0
|
|
||||||
|
|
||||||
|
|
||||||
def _prime():
|
|
||||||
"""Two CPU samples 100 ms apart, then fill every series with the
|
|
||||||
first live values so no seeded demo data is ever shown."""
|
|
||||||
total, _cores = _read_cpu()
|
|
||||||
_PREV_CPU[0] = total
|
|
||||||
time.sleep(0.1)
|
|
||||||
total2, _cores2 = _read_cpu()
|
|
||||||
cpu = _cpu_pct(_PREV_CPU[0], total2)
|
|
||||||
_PREV_CPU[0] = total2
|
|
||||||
|
|
||||||
mem = _read_mem()
|
|
||||||
if mem is not None:
|
|
||||||
total_kb, avail_kb = mem[0], mem[1]
|
|
||||||
mem_pct = (100.0 * (1.0 - avail_kb / total_kb)
|
|
||||||
if total_kb else 0.0)
|
|
||||||
else:
|
|
||||||
mem_pct = 0.0
|
|
||||||
|
|
||||||
hist = _by_name("XHistoryGraph_001")
|
|
||||||
for _ in range(60):
|
|
||||||
hist.push(cpu, series=0)
|
|
||||||
hist.push(mem_pct, series=1)
|
|
||||||
|
|
||||||
cores = _by_name("XCoreGrid_001")
|
|
||||||
values = cores.refresh_cores()
|
|
||||||
if values:
|
|
||||||
for i, value in enumerate(values):
|
|
||||||
for _ in range(60):
|
|
||||||
cores.push_core(i, value)
|
|
||||||
|
|
||||||
net = _by_name("XNetGraph_001")
|
|
||||||
_PREV_NET[0] = _read_net()
|
|
||||||
time.sleep(0.1)
|
|
||||||
now = _read_net()
|
|
||||||
down = up = 0.0
|
|
||||||
if _PREV_NET[0] is not None and now is not None:
|
|
||||||
dt = 0.1
|
|
||||||
down = max(0.0, (now[0] - _PREV_NET[0][0]) / dt)
|
|
||||||
up = max(0.0, (now[1] - _PREV_NET[0][1]) / dt)
|
|
||||||
_PREV_NET[0] = now
|
|
||||||
# push(), not push_net(): priming must not inflate the totals.
|
|
||||||
for _ in range(60):
|
|
||||||
net.push(down, series=0)
|
|
||||||
net.push(up, series=1)
|
|
||||||
|
|
||||||
proc = _by_name("XProcessList_001")
|
|
||||||
proc.refresh_processes()
|
|
||||||
time.sleep(0.1)
|
|
||||||
proc.refresh_processes()
|
|
||||||
|
|
||||||
|
|
||||||
def _tick():
|
|
||||||
_TICK[0] += 1
|
|
||||||
total, _cores = _read_cpu()
|
|
||||||
cpu = _cpu_pct(_PREV_CPU[0], total)
|
|
||||||
_PREV_CPU[0] = total
|
|
||||||
|
|
||||||
mem = _read_mem()
|
|
||||||
mem_pct = 0.0
|
|
||||||
if mem is not None:
|
|
||||||
total_kb, avail_kb, free_kb, buf_kb, cache_kb, \
|
|
||||||
swap_total, swap_free = mem
|
|
||||||
mem_pct = (100.0 * (1.0 - avail_kb / total_kb)
|
|
||||||
if total_kb else 0.0)
|
|
||||||
used_gb = max(0.0, (total_kb - free_kb - buf_kb - cache_kb)
|
|
||||||
/ 1048576.0)
|
|
||||||
stack = _by_name("XStackBar_Mem")
|
|
||||||
gb = 1048576.0
|
|
||||||
stack.set_segments([
|
|
||||||
("Used", used_gb, (0.20, 0.60, 0.90)),
|
|
||||||
("Cached", cache_kb / gb, (0.90, 0.60, 0.10)),
|
|
||||||
("Buffers", buf_kb / gb, (0.20, 0.50, 0.90)),
|
|
||||||
("Free", free_kb / gb, (0.40, 0.40, 0.45)),
|
|
||||||
])
|
|
||||||
swap = _by_name("XUsageBar_Swap")
|
|
||||||
swap.set_value(100.0 * (1.0 - swap_free / swap_total)
|
|
||||||
if swap_total else 0.0)
|
|
||||||
else:
|
|
||||||
stack = None
|
|
||||||
|
|
||||||
hist = _by_name("XHistoryGraph_001")
|
|
||||||
hist.push(cpu, series=0)
|
|
||||||
hist.push(mem_pct, series=1)
|
|
||||||
|
|
||||||
cores = _by_name("XCoreGrid_001")
|
|
||||||
cores.refresh_cores()
|
|
||||||
|
|
||||||
_by_name("XUsageBar_Mem").set_value(mem_pct)
|
|
||||||
_by_name("XUsageBar_Disk").set_value(_disk_pct())
|
|
||||||
|
|
||||||
now = _read_net()
|
|
||||||
if _PREV_NET[0] is not None and now is not None:
|
|
||||||
dt = 0.5
|
|
||||||
down = max(0.0, (now[0] - _PREV_NET[0][0]) / dt)
|
|
||||||
up = max(0.0, (now[1] - _PREV_NET[0][1]) / dt)
|
|
||||||
_by_name("XNetGraph_001").push_net(down, up)
|
|
||||||
_PREV_NET[0] = now
|
|
||||||
|
|
||||||
if _TICK[0] % 4 == 0:
|
|
||||||
_by_name("XProcessList_001").refresh_processes()
|
|
||||||
|
|
||||||
# Data is sampled every 500 ms, but the window repaints every
|
|
||||||
# 2 s (every 4th tick): a full redraw is ~38 process rows x 5
|
|
||||||
# text calls plus the graphs, and repainting every tick burned
|
|
||||||
# ~40% of a core. Tab switches and header sorts repaint at once.
|
|
||||||
if _TICK[0] % 4 == 0 and _AREA:
|
|
||||||
_AREA[0].queue_draw()
|
|
||||||
return True
|
|
||||||
|
|
||||||
|
|
||||||
# --- drawing / events -------------------------------------------------------
|
|
||||||
|
|
||||||
def _on_draw(area, cr):
|
|
||||||
bg = parse_color(_BACKGROUND, None)
|
|
||||||
if bg is None:
|
|
||||||
bg = (1.0, 1.0, 1.0)
|
|
||||||
cr.set_source_rgb(*bg)
|
|
||||||
cr.paint()
|
|
||||||
for widget in _WIDGETS:
|
|
||||||
if widget.name == "TPageControl_001":
|
|
||||||
widget.draw(cr)
|
|
||||||
for widget in _PAGE_WIDGETS[_PAGE[0]]:
|
|
||||||
widget.draw(cr)
|
|
||||||
return False
|
|
||||||
|
|
||||||
|
|
||||||
def _set_page(page):
|
|
||||||
if page == _PAGE[0]:
|
|
||||||
return
|
|
||||||
_PAGE[0] = page
|
|
||||||
_by_name("TPageControl_001").set_prop("page", str(page))
|
|
||||||
if _AREA:
|
|
||||||
_AREA[0].queue_draw()
|
|
||||||
|
|
||||||
|
|
||||||
def _on_tab_click(x, y):
|
|
||||||
"""Tab strip hit test (TPageControl at (8,8), tab-width 140):
|
|
||||||
tab 0 x 14..154, tab 1 x 156..296, strip y 10..36. Returns
|
|
||||||
True when the click was on a tab."""
|
|
||||||
if 10 <= y < 36:
|
|
||||||
if 14 <= x < 154:
|
|
||||||
_set_page(0)
|
|
||||||
return True
|
|
||||||
if 156 <= x < 296:
|
|
||||||
_set_page(1)
|
|
||||||
return True
|
|
||||||
return False
|
|
||||||
|
|
||||||
|
|
||||||
def _on_proc_header_click(x, y):
|
|
||||||
"""Process-list header sort: same column fractions as the
|
|
||||||
widget's draw (PID 0.14 / Program 0.52 / User 0.68 / Mem 0.82 /
|
|
||||||
CPU%). Clicking the current column toggles the direction."""
|
|
||||||
proc = _by_name("XProcessList_001")
|
|
||||||
lx, ly = x - 14, y - 38
|
|
||||||
if not (22 <= ly < 40 and 6 <= lx < 990):
|
|
||||||
return False
|
|
||||||
iw = 996 - 12
|
|
||||||
xs = [6 + int(iw * f) for f in (0.0, 0.14, 0.52, 0.68, 0.82, 1.0)]
|
|
||||||
keys = ["pid", "name", None, "mem", "cpu"]
|
|
||||||
key = None
|
|
||||||
for i in range(5):
|
|
||||||
if xs[i] <= lx < xs[i + 1]:
|
|
||||||
key = keys[i]
|
|
||||||
break
|
|
||||||
if key is None:
|
|
||||||
return False
|
|
||||||
idx = _SORT_KEYS.index(key)
|
|
||||||
cur = int(float(proc.get_prop("sort-by", "0") or "0"))
|
|
||||||
if idx == cur:
|
|
||||||
desc = proc.get_prop("sort-desc", "true") != "true"
|
|
||||||
proc.set_prop("sort-desc", "true" if desc else "false")
|
|
||||||
else:
|
|
||||||
proc.sort_by(key)
|
|
||||||
proc.set_prop("sort-desc",
|
|
||||||
"true" if key in ("cpu", "mem") else "false")
|
|
||||||
if _AREA:
|
|
||||||
_AREA[0].queue_draw()
|
|
||||||
return True
|
|
||||||
|
|
||||||
|
|
||||||
def _on_button_press(area, event):
|
|
||||||
if event.type == Gdk.EventType.BUTTON_PRESS:
|
|
||||||
x, y = event.x, event.y
|
|
||||||
if _on_tab_click(x, y):
|
|
||||||
return False
|
|
||||||
if _PAGE[0] == 0 and _on_proc_header_click(x, y):
|
|
||||||
return False
|
|
||||||
return False
|
|
||||||
|
|
||||||
|
|
||||||
def _on_button_release(area, event):
|
|
||||||
return False
|
|
||||||
|
|
||||||
|
|
||||||
def _on_area_resize(area, allocation):
|
|
||||||
size = (allocation.width, allocation.height)
|
|
||||||
if size == _LAST_SIZE[0]:
|
|
||||||
return False
|
|
||||||
_LAST_SIZE[0] = size
|
|
||||||
_apply_anchors(_WIDGETS, size[0], size[1])
|
|
||||||
area.queue_draw()
|
|
||||||
return False
|
|
||||||
|
|
||||||
|
|
||||||
def main():
|
|
||||||
window = Gtk.Window(title="Task Manager - monitor")
|
|
||||||
window.set_default_size(1024, 768)
|
|
||||||
window.move(100, 100)
|
|
||||||
window.connect("destroy", Gtk.main_quit)
|
|
||||||
vbox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=0)
|
|
||||||
window.add(vbox)
|
|
||||||
area = Gtk.DrawingArea()
|
|
||||||
area.set_hexpand(True)
|
|
||||||
area.set_vexpand(True)
|
|
||||||
area.add_events(Gdk.EventMask.BUTTON_PRESS_MASK |
|
|
||||||
Gdk.EventMask.BUTTON_RELEASE_MASK)
|
|
||||||
area.connect("draw", _on_draw)
|
|
||||||
area.connect("button-press-event", _on_button_press)
|
|
||||||
area.connect("button-release-event", _on_button_release)
|
|
||||||
area.connect("size-allocate", _on_area_resize)
|
|
||||||
vbox.pack_start(area, True, True, 0)
|
|
||||||
_WIDGETS.extend(_build_widgets())
|
|
||||||
_AREA.append(area)
|
|
||||||
_prime()
|
|
||||||
GLib.timeout_add(500, _tick)
|
|
||||||
window.show_all()
|
|
||||||
Gtk.main()
|
|
||||||
return 0
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
|
||||||
sys.exit(main())
|
|
||||||
Binary file not shown.
|
Before Width: | Height: | Size: 73 KiB |
Binary file not shown.
|
Before Width: | Height: | Size: 68 KiB |
+148
-493
File diff suppressed because it is too large.
Load diff
+43
-78
@@ -171,58 +171,16 @@ def _read_cpu_times():
|
|||||||
return None
|
return None
|
||||||
|
|
||||||
|
|
||||||
# (pid, starttime) -> user name, so a rescan only opens /proc/<pid>/status
|
|
||||||
# for processes it has never seen (a recycled pid has a new starttime,
|
|
||||||
# so the cache cannot go stale). Opening status for every process on
|
|
||||||
# every scan cost ~40% of the scan on a 400-process box; the stat file
|
|
||||||
# alone carries everything else (rss is field 24, in pages).
|
|
||||||
_UID_CACHE = {}
|
|
||||||
_PAGE_KB = 4 # overridden below from sysconf when available
|
|
||||||
try:
|
|
||||||
_PAGE_KB = os.sysconf("SC_PAGE_SIZE") // 1024
|
|
||||||
except (AttributeError, ValueError, OSError):
|
|
||||||
pass
|
|
||||||
|
|
||||||
|
|
||||||
def _user_for(pid, starttime):
|
|
||||||
"""User name for a process, reading /proc/<pid>/status only on
|
|
||||||
a cache miss. Returns "" when the process is gone."""
|
|
||||||
key = (pid, starttime)
|
|
||||||
user = _UID_CACHE.get(key)
|
|
||||||
if user is not None:
|
|
||||||
return user
|
|
||||||
if len(_UID_CACHE) > 4096:
|
|
||||||
_UID_CACHE.clear()
|
|
||||||
user = ""
|
|
||||||
try:
|
|
||||||
import pwd
|
|
||||||
except ImportError: # pragma: no cover - non-Unix
|
|
||||||
pwd = None
|
|
||||||
try:
|
|
||||||
with open("/proc/%s/status" % pid) as handle:
|
|
||||||
for line in handle:
|
|
||||||
if line.startswith("Uid:"):
|
|
||||||
uid = int(line.split()[1])
|
|
||||||
user = str(uid)
|
|
||||||
if pwd is not None:
|
|
||||||
try:
|
|
||||||
user = pwd.getpwuid(uid).pw_name
|
|
||||||
except KeyError:
|
|
||||||
pass
|
|
||||||
break
|
|
||||||
except (OSError, ValueError, IndexError):
|
|
||||||
pass
|
|
||||||
_UID_CACHE[key] = user
|
|
||||||
return user
|
|
||||||
|
|
||||||
|
|
||||||
def _read_processes():
|
def _read_processes():
|
||||||
"""Live process rows from /proc: dicts with pid, name, user,
|
"""Live process rows from /proc: dicts with pid, name, user,
|
||||||
mem_kb, utime, stime -- plus an internal ``t`` (monotonic time
|
mem_kb, utime, stime -- plus an internal ``t`` (monotonic time
|
||||||
the stat was read, used for per-process CPU% denominators and
|
the stat was read, used for per-process CPU% denominators and
|
||||||
stripped before the rows reach the widget). Returns None when
|
stripped before the rows reach the widget). Returns None when
|
||||||
/proc is unavailable.
|
/proc is unavailable."""
|
||||||
"""
|
try:
|
||||||
|
import pwd
|
||||||
|
except ImportError: # pragma: no cover - non-Unix
|
||||||
|
pwd = None
|
||||||
rows = []
|
rows = []
|
||||||
try:
|
try:
|
||||||
pids = [d for d in os.listdir("/proc") if d.isdigit()]
|
pids = [d for d in os.listdir("/proc") if d.isdigit()]
|
||||||
@@ -237,9 +195,20 @@ def _read_processes():
|
|||||||
rest = data[rparen + 2:].split()
|
rest = data[rparen + 2:].split()
|
||||||
utime = int(rest[11])
|
utime = int(rest[11])
|
||||||
stime = int(rest[12])
|
stime = int(rest[12])
|
||||||
starttime = int(rest[19])
|
with open("/proc/%s/status" % pid) as handle:
|
||||||
mem_kb = int(rest[21]) * _PAGE_KB
|
uid = None
|
||||||
user = _user_for(pid, starttime)
|
mem_kb = 0
|
||||||
|
for line in handle:
|
||||||
|
if line.startswith("Uid:"):
|
||||||
|
uid = int(line.split()[1])
|
||||||
|
elif line.startswith("VmRSS:"):
|
||||||
|
mem_kb = int(line.split()[1])
|
||||||
|
user = str(uid) if uid is None else str(uid)
|
||||||
|
if pwd is not None and uid is not None:
|
||||||
|
try:
|
||||||
|
user = pwd.getpwuid(uid).pw_name
|
||||||
|
except KeyError:
|
||||||
|
pass
|
||||||
rows.append({"pid": int(pid), "name": comm, "user": user,
|
rows.append({"pid": int(pid), "name": comm, "user": user,
|
||||||
"mem_kb": mem_kb, "utime": utime,
|
"mem_kb": mem_kb, "utime": utime,
|
||||||
"stime": stime, "cpu": 0.0,
|
"stime": stime, "cpu": 0.0,
|
||||||
@@ -1380,6 +1349,7 @@ class MonitorWidget(Widget):
|
|||||||
rgb = _RED if f >= red_frac else _TEXT
|
rgb = _RED if f >= red_frac else _TEXT
|
||||||
_wtext(cr, self, label, lx, ly, size=numeral_px,
|
_wtext(cr, self, label, lx, ly, size=numeral_px,
|
||||||
rgb=rgb, align="center", bold=True)
|
rgb=rgb, align="center", bold=True)
|
||||||
|
cr.restore()
|
||||||
# Peak-hold tick.
|
# Peak-hold tick.
|
||||||
cr.save()
|
cr.save()
|
||||||
_rgb(cr, _WHITE)
|
_rgb(cr, _WHITE)
|
||||||
@@ -1485,29 +1455,24 @@ 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()
|
||||||
# Column x-offsets as fractions of the inner width (same
|
_wtext(cr, self, "%d procs" % len(rows), self.width - 8, 17,
|
||||||
# fractions as the C++ widget: PID / Program / User / Mem /
|
size=13, rgb=_DIM, align="right")
|
||||||
# CPU%). The old fixed offsets were drawn for the 360px demo
|
cols = ((6, 52, "PID", "left"), (62, 130, "Program", "left"),
|
||||||
# widget and left a wide widget mostly empty.
|
(196, 44, "User", "left"), (248, 52, "Mem", "right"),
|
||||||
iw = max(60, self.width - 12)
|
(308, 48, "CPU%", "right"))
|
||||||
xs = [6 + int(iw * f) for f in (0.0, 0.14, 0.52, 0.68, 0.82, 1.0)]
|
|
||||||
# (x, label, sort key): sort keys follow _sorted_rows
|
|
||||||
# (0 cpu, 1 mem, 2 pid, 3 name); User has no sort key.
|
|
||||||
sort_col = _prop_int(self, "sort-by", 0)
|
sort_col = _prop_int(self, "sort-by", 0)
|
||||||
|
sort_key = {0: "CPU%", 1: "Mem", 2: "PID", 3: "Program"}.get(
|
||||||
|
sort_col, "CPU%")
|
||||||
sort_desc = _prop_bool(self, "sort-desc", True)
|
sort_desc = _prop_bool(self, "sort-desc", True)
|
||||||
headers = [(xs[0], "PID", 2, "left"), (xs[1], "Program", 3, "left"),
|
header_y = top + 15
|
||||||
(xs[2], "User", None, "left"), (xs[4], "Mem", 1, "right"),
|
for x, _w, name, align in cols:
|
||||||
(xs[5], "CPU%", 0, "right")]
|
if name == sort_key:
|
||||||
header_y = top + 13
|
name = name + (" \u25bc" if sort_desc else " \u25b2")
|
||||||
for x, name, key, align in headers:
|
|
||||||
label = name
|
|
||||||
if key is not None and key == sort_col:
|
|
||||||
label += " v" if sort_desc else " ^"
|
|
||||||
if align == "right":
|
if align == "right":
|
||||||
_wtext(cr, self, label, x - 4, header_y, size=10,
|
_wtext(cr, self, name, x + _w, header_y, size=13,
|
||||||
rgb=_DIM, align="right", bold=True)
|
rgb=_DIM, align="right", bold=True)
|
||||||
else:
|
else:
|
||||||
_wtext(cr, self, label, x, header_y, size=10,
|
_wtext(cr, self, name, x, header_y, size=13,
|
||||||
rgb=_DIM, bold=True)
|
rgb=_DIM, bold=True)
|
||||||
row_h = 23
|
row_h = 23
|
||||||
y0 = top + 24
|
y0 = top + 24
|
||||||
@@ -1523,18 +1488,18 @@ class MonitorWidget(Widget):
|
|||||||
_rgb(cr, _AMBER, 0.12)
|
_rgb(cr, _AMBER, 0.12)
|
||||||
cr.rectangle(0, y, self.width, row_h)
|
cr.rectangle(0, y, self.width, row_h)
|
||||||
cr.fill()
|
cr.fill()
|
||||||
_wtext(cr, self, str(row["pid"]), xs[0], y + 13, size=10,
|
_wtext(cr, self, str(row["pid"]), 6, y + 16, size=13,
|
||||||
rgb=_TEXT)
|
rgb=_TEXT)
|
||||||
_wtext(cr, self, row["name"], xs[1], y + 13, size=10,
|
_wtext(cr, self, row["name"], 62, y + 16, size=13,
|
||||||
rgb=_TEXT,
|
rgb=_TEXT,
|
||||||
max_width=xs[2] - xs[1] - 6)
|
max_width=128)
|
||||||
_wtext(cr, self, row["user"], xs[2], y + 13, size=10,
|
_wtext(cr, self, row["user"], 196, y + 16, size=13,
|
||||||
rgb=_TEXT, max_width=xs[3] - xs[2] - 6)
|
rgb=_TEXT, max_width=44)
|
||||||
_wtext(cr, self, _fmt_bytes(row["mem_kb"] * 1024), xs[4] - 4,
|
_wtext(cr, self, _fmt_bytes(row["mem_kb"] * 1024), 300,
|
||||||
y + 13, size=10, rgb=_TEXT, align="right")
|
y + 16, size=13, rgb=_TEXT, align="right")
|
||||||
# In-cell CPU% bar behind the number.
|
# In-cell CPU% bar behind the number (colour-coded).
|
||||||
bar_x, bar_w = xs[4] + 2, xs[5] - xs[4] - 6
|
bar_x, bar_w = 308, 48
|
||||||
_box(cr, bar_x, y + 3, bar_w, 12, (0.20, 0.20, 0.23),
|
_box(cr, bar_x, y + 5, bar_w, 12, (0.20, 0.20, 0.23),
|
||||||
(0.20, 0.20, 0.23))
|
(0.20, 0.20, 0.23))
|
||||||
fill = max(0, bar_w * min(1.0, cpu / 100.0))
|
fill = max(0, bar_w * min(1.0, cpu / 100.0))
|
||||||
if fill > 0:
|
if fill > 0:
|
||||||
|
|||||||
Reference in new issue
Block a user