Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e1da839538 |
No files matched your search
@@ -1,33 +0,0 @@
|
||||
# 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`).
|
||||
@@ -1,248 +0,0 @@
|
||||
#!/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.
|
Before Width: | Height: | Size: 40 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())
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 77 KiB |
@@ -440,6 +440,10 @@ class MonitorWidget(Widget):
|
||||
self._segments = None
|
||||
# Process rows for XProcessList: None = demo rows.
|
||||
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_times = None
|
||||
# /proc/stat snapshot for XCoreGrid.refresh().
|
||||
@@ -656,8 +660,66 @@ class MonitorWidget(Widget):
|
||||
if column in keys:
|
||||
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):
|
||||
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)
|
||||
key = {0: "cpu", 1: "mem_kb", 2: "pid", 3: "name"}.get(col, "cpu")
|
||||
reverse = _prop_bool(self, "sort-desc", True)
|
||||
@@ -1299,6 +1361,11 @@ class MonitorWidget(Widget):
|
||||
_rgb(cr, _AMBER, 0.12)
|
||||
cr.rectangle(0, y, self.width, row_h)
|
||||
cr.fill()
|
||||
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"]), 6, y + 13, size=10,
|
||||
rgb=_TEXT)
|
||||
_wtext(cr, self, row["name"], 62, y + 13, size=10,
|
||||
|
||||
@@ -413,3 +413,49 @@ class PropsTests(unittest.TestCase):
|
||||
|
||||
if __name__ == "__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())
|
||||
Reference in new issue
Block a user