10 changed files with 311 additions and 520 deletions

No files matched your search

Generated
+1
View File
@@ -900,6 +900,7 @@ dependencies = [
name = "xframe-demo"
version = "0.1.0"
dependencies = [
"libc",
"x11rb",
"xframe-common",
"xframe-core",
+1
View File
@@ -14,3 +14,4 @@ xframe-common = { path = "../xframe-common" }
xframe-core = { path = "../xframe-core" }
xframe-widgets = { path = "../xframe-widgets" }
x11rb = "0.13"
libc = "0.2"
@@ -0,0 +1,204 @@
//! Process Manager — monitor (Rust / XFrame).
//!
//! Run it from the workspace root:
//! cargo run -p xframe-demo --example monitor_process_manager
//! It opens a 1024x768 window ("Process Manager - monitor") with 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 (pid <= 1 and our own pid are
//! refused). Press Esc or close the window to quit.
//!
//! The widgets are the real `xframe-widgets` implementations, created
//! directly (`MonitorWidget::new`, `ButtonWidget::new`,
//! `EntryWidget::new`) — the same code path the `xframe-demo` binary
//! uses for single-widget examples, with a multi-widget event loop
//! modelled on `xframe_demo::run_widget`.
use std::process::ExitCode;
use std::time::{Duration, Instant};
use x11rb::connection::Connection;
use x11rb::protocol::xproto::*;
use x11rb::protocol::Event;
use xframe_common::style::FONT_DEFAULT;
use xframe_common::target::CtxTarget;
use xframe_common::x11::{DrawCtx, X11};
use xframe_core::StyleManager;
use xframe_widgets::{ButtonWidget, EntryWidget, Key, MonitorWidget, Widget};
const WIN_W: u16 = 1024;
const WIN_H: u16 = 768;
const KEY_ESCAPE: u32 = 0xff1b;
/// Send `sig` to `pid`; false (and no signal) for pid <= 1 or our own pid.
fn signal_pid(pid: u32, sig: libc::c_int) -> bool {
if pid <= 1 || pid == std::process::id() {
return false;
}
unsafe { libc::kill(pid as libc::pid_t, sig) == 0 }
}
fn redraw(
list: &MonitorWidget,
entry: &EntryWidget,
buttons: &[&ButtonWidget; 3],
ctx: &DrawCtx,
target: &mut CtxTarget,
styles: &mut StyleManager,
) {
ctx.clear(255, 255, 255, WIN_W, WIN_H);
list.draw(target, styles);
entry.draw(target, styles);
for b in buttons {
b.draw(target, styles);
}
ctx.flush();
}
fn run() -> Result<i32, Box<dyn std::error::Error>> {
let x = X11::connect()?;
let font = x.open_font(&[FONT_DEFAULT, "fixed"])?;
let title = "Process Manager - monitor";
let event_mask = EventMask::EXPOSURE
| EventMask::KEY_PRESS
| EventMask::STRUCTURE_NOTIFY
| EventMask::BUTTON_PRESS
| EventMask::BUTTON_RELEASE
| EventMask::POINTER_MOTION;
let (win, gc) = x.create_window(100, 100, WIN_W, WIN_H, title, event_mask)?;
let mut styles = StyleManager::new();
xframe_demo::register_styles(&mut styles);
let mut list = MonitorWidget::new("Processes", "ProcessList", 16, 58, 992, 694);
list.refresh_processes();
let mut entry = EntryWidget::new("Filter", "Entry", 16, 16, 300, 30);
entry.set_text("");
let mut btn_term = ButtonWidget::new("Terminate", "Button", 336, 16, 120, 30);
btn_term.set_text("Terminate");
let mut btn_kill = ButtonWidget::new("Kill", "Button", 466, 16, 120, 30);
btn_kill.set_text("Kill");
let mut btn_refresh = ButtonWidget::new("Refresh", "Button", 596, 16, 120, 30);
btn_refresh.set_text("Refresh");
let ctx = DrawCtx::new(&x, win, gc, font);
ctx.bind_font();
let mut target = CtxTarget::new(&ctx);
if !styles.resolve_font("default", &mut target) && !styles.resolve_font("dark", &mut target) {
eprintln!("monitor_process_manager: warning: no font resolved, labels will be blank");
}
redraw(&list, &entry, &[&btn_term, &btn_kill, &btn_refresh], &ctx, &mut target, &mut styles);
let mut last_poll = Instant::now();
let mut last_filter = String::new();
loop {
let ev = match x.conn.poll_for_event()? {
Some(ev) => ev,
None => {
std::thread::sleep(Duration::from_millis(10));
if last_poll.elapsed() >= Duration::from_secs(2) {
last_poll = Instant::now();
list.refresh_processes();
redraw(&list, &entry, &[&btn_term, &btn_kill, &btn_refresh], &ctx, &mut target, &mut styles);
}
continue;
}
};
let mut handled = false;
match ev {
Event::Expose(_) => {
redraw(&list, &entry, &[&btn_term, &btn_kill, &btn_refresh], &ctx, &mut target, &mut styles);
}
Event::ButtonPress(ev) => {
let (px, py) = (ev.event_x as i32, ev.event_y as i32);
if entry.on_button_press(px, py, ev.detail as u32) {
handled = true;
} else {
entry.set_focused(false);
handled = btn_term.on_button_press(px, py, ev.detail as u32)
|| btn_kill.on_button_press(px, py, ev.detail as u32)
|| btn_refresh.on_button_press(px, py, ev.detail as u32)
|| list.on_button_press(px, py, ev.detail as u32);
}
}
Event::ButtonRelease(ev) => {
let (px, py) = (ev.event_x as i32, ev.event_y as i32);
let (c_term, c_kill, c_ref) =
(btn_term.click_count(), btn_kill.click_count(), btn_refresh.click_count());
handled = btn_term.on_button_release(px, py, ev.detail as u32)
|| btn_kill.on_button_release(px, py, ev.detail as u32)
|| btn_refresh.on_button_release(px, py, ev.detail as u32)
|| list.on_button_release(px, py, ev.detail as u32);
if btn_term.click_count() != c_term {
if let Some(pid) = list.selected_pid() {
if signal_pid(pid, libc::SIGTERM) {
list.refresh_processes();
}
}
} else if btn_kill.click_count() != c_kill {
if let Some(pid) = list.selected_pid() {
if signal_pid(pid, libc::SIGKILL) {
list.refresh_processes();
}
}
} else if btn_refresh.click_count() != c_ref {
list.refresh_processes();
}
}
Event::MotionNotify(ev) => {
handled = entry.on_motion(ev.event_x as i32, ev.event_y as i32)
|| btn_term.on_motion(ev.event_x as i32, ev.event_y as i32)
|| btn_kill.on_motion(ev.event_x as i32, ev.event_y as i32)
|| btn_refresh.on_motion(ev.event_x as i32, ev.event_y as i32)
|| list.on_motion(ev.event_x as i32, ev.event_y as i32);
}
Event::KeyPress(ev) => {
let keysym = x.keysym_for_keycode(ev.detail);
if keysym == KEY_ESCAPE {
break;
}
let text = if (0x20..0x7f).contains(&keysym) {
Some(keysym as u8 as char)
} else {
None
};
handled = entry.on_key(Key::from_keysym(keysym, text), text);
if handled {
let f = entry.text().to_string();
if f != last_filter {
last_filter = f.clone();
list.set_filter(&f);
list.refresh_processes();
}
}
}
Event::ClientMessage(ev)
if ev.type_ == x.wm_protocols && ev.data.as_data32()[0] == x.wm_delete =>
{
break;
}
_ => {}
}
if handled {
redraw(&list, &entry, &[&btn_term, &btn_kill, &btn_refresh], &ctx, &mut target, &mut styles);
}
if last_poll.elapsed() >= Duration::from_secs(2) {
last_poll = Instant::now();
list.refresh_processes();
redraw(&list, &entry, &[&btn_term, &btn_kill, &btn_refresh], &ctx, &mut target, &mut styles);
}
}
Ok(0)
}
fn main() -> ExitCode {
match run() {
Ok(code) => ExitCode::from(code as u8),
Err(e) => {
eprintln!("monitor_process_manager: {}", e);
ExitCode::from(1)
}
}
}
@@ -0,0 +1,42 @@
# Process Manager — monitor (Rust)
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, CPU% and memory for the live
processes on this machine (top 12 by CPU), refreshed every 2 seconds.
Click a column header to sort by it (click again to reverse); click a
body row to select it (highlighted).
- **Filter** — type a name or pid substring; the list re-scans `/proc`
and 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
cargo run -p xframe-demo --example monitor_process_manager
# Esc or close the window to quit
```
## Source
- App: `crates/xframe-demo/examples/monitor_process_manager.rs` in
[lightgui_rust](https://github.com/cnmcdee/lightgui_rust)
- Widgets: `XProcessList` (`MonitorWidget`), `GtkButton`
(`ButtonWidget`), `GtkEntry` (`EntryWidget`) — this app adds a
name/pid filter to `MonitorWidget` (additive only; the widget demo
and `XMonitorGrid` behaviour are unchanged)
The same app exists in
[C](https://github.com/cnmcdee/lightgui) and
[Python](https://github.com/cnmcdee/lightgui_python) — see the
[walkthrough](https://www.lightgui.com/monitor-process-manager/).
Binary file not shown.

After

Width:  |  Height:  |  Size: 4.7 KiB

@@ -1,44 +0,0 @@
# Task Manager — monitor app (Rust)
A Windows-style Task Manager clone in one 1024×768 window, built from
the LightGUI XFrame monitor widgets (Stage 2 of the btop-widget
project).
## Tabs
- **Processes** — `XProcessList`: live `/proc` table, columns PID /
NAME / CPU% / MEM, click a column header to sort (click again to
reverse), click a row to select it. Refreshes every 2 s.
- **Performance** — `XHistoryGraph` (60 s CPU + memory),
`XCoreGrid` (one mini history graph per CPU core), `XUsageBar`
(Memory), `XStackBar` (memory Used / Cached / Buffers / Free in
GiB), `XNetGraph` (live download / upload from `/proc/net/dev`).
All graphs refresh every 500 ms from live `/proc` data
(`/proc/stat`, `/proc/meminfo`, `/proc/net/dev`).
The tab strip is two `GtkButton` widgets: the Rust
`ContainerWidget` (`TPageControl`) draws a plain panel + children
and no tab strip, so the tabs are registry buttons and the app
routes their clicks (same pattern as the Python app's app-level tab
hit handling).
## Build and run
```sh
cargo run -p xframe-demo --example monitor_task_manager
```
Close the window (or press `q` / Esc) to quit.
## Widgets used
`TPageControl`, `GtkButton`, `XProcessList`, `XHistoryGraph`,
`XCoreGrid`, `XUsageBar`, `XStackBar`, `XNetGraph` — all from the
LightGUI registry. No raw x11rb drawing for UI elements: the only
raw X11 here is the window shell and the event loop, as in
`xframe_demo::run_widget`. Rust colours go through
`Srgb::to_pixel`, so colours cost no `XAllocColor` round trips
(unlike the C++ style manager) — but the text helpers measure with
`query_text_extents`, one server round trip per call, so the window
repaints every 2 s rather than every 500 ms tick (data is still
sampled every 500 ms).
@@ -1,473 +0,0 @@
//! Task Manager - monitor app (Stage 2, btop-widget project).
//!
//! A Windows-style Task Manager clone in one 1024x768 window: a
//! `TPageControl` body panel with two `GtkButton` tabs (the Rust
//! `ContainerWidget` draws a plain panel + children, no tab strip,
//! so the tabs are registry buttons and the app routes their clicks).
//! The Processes tab is a live `XProcessList` from `/proc` (sortable
//! PID / NAME / CPU% / MEM columns, click a header to sort). The
//! Performance tab is `XHistoryGraph` (60 s CPU + memory),
//! `XCoreGrid` (one mini history graph per CPU core), `XUsageBar`
//! (Memory), `XStackBar` (memory Used / Cached / Buffers / Free in
//! GiB) and `XNetGraph` (live download / upload from `/proc/net/dev`).
//!
//! Every visible UI element is a LightGUI registry widget; the only
//! raw X11 here is the window shell and the event loop, exactly like
//! `xframe_demo::run_widget`.
//!
//! Run from the workspace root:
//! cargo run -p xframe-demo --example monitor_task_manager
//! Close the window (or press Esc / `q`) to quit. Data is sampled
//! from live `/proc` every 500 ms; the window repaints every 2 s (the
//! Rust text helpers measure with `query_text_extents`, one server
//! round trip per call, and a full repaint issues hundreds of them —
//! repainting every tick would never catch up).
use std::fs;
use std::process::ExitCode;
use std::time::{Duration, Instant};
use x11rb::connection::Connection;
use x11rb::protocol::xproto::*;
use x11rb::protocol::Event;
use xframe_common::style::FONT_DEFAULT;
use xframe_common::target::CtxTarget;
use xframe_common::x11::{DrawCtx, X11};
use xframe_core::{Srgb, StyleManager};
use xframe_demo::register_styles;
use xframe_widgets::archetypes::{ButtonWidget, ContainerWidget};
use xframe_widgets::monitor::{MonitorWidget, Segment};
use xframe_widgets::Widget;
const WIN_W: u16 = 1024;
const WIN_H: u16 = 768;
const KEY_ESCAPE: u32 = 0xff1b;
// ---------------------------------------------------------------------------
// Live /proc readers (same sources as the C app)
// ---------------------------------------------------------------------------
#[derive(Clone, Copy, Default)]
struct CpuTimes {
idle: u64,
total: u64,
}
fn read_cpu() -> Option<(CpuTimes, Vec<CpuTimes>)> {
let text = fs::read_to_string("/proc/stat").ok()?;
let mut total = None;
let mut cores = Vec::new();
for line in text.lines() {
let mut parts = line.split_whitespace();
let label = parts.next()?;
if !label.starts_with("cpu") {
break;
}
let nums: Vec<u64> = parts.filter_map(|s| s.parse().ok()).collect();
if nums.len() < 5 {
continue;
}
let t = CpuTimes {
idle: nums[3] + nums[4],
total: nums.iter().sum(),
};
if label == "cpu" {
total = Some(t);
} else {
cores.push(t);
}
}
Some((total?, cores))
}
fn cpu_pct(prev: CpuTimes, cur: CpuTimes) -> f64 {
let d_total = cur.total.saturating_sub(prev.total);
let d_idle = cur.idle.saturating_sub(prev.idle);
if d_total == 0 {
return 0.0;
}
(100.0 * (1.0 - d_idle as f64 / d_total as f64)).clamp(0.0, 100.0)
}
struct MemInfo {
used_gb: f64,
used_pct: f64,
cached_gb: f64,
buffers_gb: f64,
free_gb: f64,
}
fn read_mem() -> Option<MemInfo> {
let text = fs::read_to_string("/proc/meminfo").ok()?;
let get = |key: &str| -> u64 {
for line in text.lines() {
if let Some(rest) = line.strip_prefix(key) {
return rest
.split_whitespace()
.next()
.and_then(|v| v.parse().ok())
.unwrap_or(0);
}
}
0
};
let total_kb = get("MemTotal:") as f64;
if total_kb <= 0.0 {
return None;
}
let free_kb = get("MemFree:") as f64;
let buf_kb = get("Buffers:") as f64;
let cache_kb = get("Cached:") as f64;
let gb = 1024.0 * 1024.0;
let used_gb = ((total_kb - free_kb - buf_kb - cache_kb) / gb).max(0.0);
Some(MemInfo {
used_gb,
used_pct: 100.0 * used_gb / (total_kb / gb),
cached_gb: cache_kb / gb,
buffers_gb: buf_kb / gb,
free_gb: free_kb / gb,
})
}
#[derive(Clone, Copy, Default)]
struct NetBytes {
rx: u64,
tx: u64,
}
fn read_net() -> Option<NetBytes> {
let text = fs::read_to_string("/proc/net/dev").ok()?;
let mut out = NetBytes::default();
for line in text.lines().skip(2) {
let (iface, rest) = line.split_once(':')?;
if iface.trim() == "lo" {
continue;
}
let f: Vec<u64> = rest.split_whitespace().filter_map(|s| s.parse().ok()).collect();
if f.len() > 8 {
out.rx += f[0];
out.tx += f[8];
}
}
Some(out)
}
// ---------------------------------------------------------------------------
// App
// ---------------------------------------------------------------------------
struct App {
tab_proc: ButtonWidget,
tab_perf: ButtonWidget,
pages: ContainerWidget,
proc_list: MonitorWidget,
hist: MonitorWidget,
cores: MonitorWidget,
membar: MonitorWidget,
memstack: MonitorWidget,
net: MonitorWidget,
active_page: usize,
tick: u64,
prev_total: CpuTimes,
prev_cores: Vec<CpuTimes>,
prev_net: NetBytes,
net_totals: (f64, f64),
}
impl App {
fn new() -> App {
let mut tab_proc = ButtonWidget::new("GtkButton", "Button", 10, 8, 130, 30);
tab_proc.set_text("Processes");
let mut tab_perf = ButtonWidget::new("GtkButton", "Button", 142, 8, 130, 30);
tab_perf.set_text("Performance");
let mut pages = ContainerWidget::new("TPageControl", "PageControl", 8, 42, 1008, 718);
pages.set_text("");
pages.items = vec!["Processes".to_string(), "Performance".to_string()];
let proc_list = MonitorWidget::new("Processes", "ProcessList", 14, 48, 996, 706);
let mut hist = MonitorWidget::new("CPU + Memory (60 s)", "HistoryGraph", 14, 48, 630, 300);
hist.series.clear();
hist.add_series("CPU %");
hist.add_series("Memory %");
let cores = MonitorWidget::new("CPU cores", "CoreGrid", 652, 48, 354, 300);
let mut membar = MonitorWidget::new("Memory", "UsageBar", 14, 356, 992, 34);
membar.set_text("Memory");
let mut memstack = MonitorWidget::new("Memory", "StackBar", 14, 398, 992, 60);
memstack.set_text("Memory");
let mut net = MonitorWidget::new("Network", "NetGraph", 14, 466, 992, 288);
net.series.clear();
net.add_series("Down");
net.add_series("Up");
net.totals = (0.0, 0.0);
let (prev_total, prev_cores) = read_cpu().unwrap_or_default();
let prev_net = read_net().unwrap_or_default();
App {
tab_proc,
tab_perf,
pages,
proc_list,
hist,
cores,
membar,
memstack,
net,
active_page: 0,
tick: 0,
prev_total,
prev_cores,
prev_net,
net_totals: (0.0, 0.0),
}
}
/// Prime live data: two /proc/stat samples 100 ms apart give the
/// first real CPU/net rates; the history widgets are then filled
/// with that live value so no seeded demo data shows.
fn prime(&mut self) {
std::thread::sleep(Duration::from_millis(100));
let (cur_total, cur_cores) = match read_cpu() {
Some(v) => v,
None => return,
};
let cur_net = read_net().unwrap_or_default();
let mem = read_mem();
let cpu0 = cpu_pct(self.prev_total, cur_total);
let ncores = cur_cores.len();
// Rebuild the core series for the live core count, then fill
// each core's history with the live value.
self.cores.series.clear();
for c in 0..ncores {
self.cores.add_series(&format!("CPU{}", c));
}
let mut per_core = vec![0.0; ncores];
for (i, c) in cur_cores.iter().enumerate() {
if i < self.prev_cores.len() {
per_core[i] = cpu_pct(self.prev_cores[i], *c);
}
}
for _ in 0..60 {
self.cores.push_samples(&per_core);
}
if let Some(m) = &mem {
self.hist.push_samples(&[cpu0, m.used_pct]);
self.membar.set_value(m.used_pct);
self.set_mem_segments(m);
}
let down0 = (cur_net.rx - self.prev_net.rx) as f64 * 10.0 / 1024.0;
let up0 = (cur_net.tx - self.prev_net.tx) as f64 * 10.0 / 1024.0;
for _ in 0..120 {
self.net.push_samples(&[down0, up0]);
}
self.prev_total = cur_total;
self.prev_cores = cur_cores;
self.prev_net = cur_net;
}
fn set_mem_segments(&mut self, m: &MemInfo) {
self.memstack.set_segments(vec![
Segment { label: "Used", value: m.used_gb, color: Srgb::new(34, 197, 94) },
Segment { label: "Cached", value: m.cached_gb, color: Srgb::new(245, 158, 11) },
Segment { label: "Buffers", value: m.buffers_gb, color: Srgb::new(59, 130, 246) },
Segment { label: "Free", value: m.free_gb, color: Srgb::new(200, 200, 200) },
]);
}
fn set_page(&mut self, page: usize) {
self.active_page = page;
self.pages.set_active_page(page);
}
/// One 500 ms tick: sample live data, push it into the widgets.
fn on_tick(&mut self) {
self.tick += 1;
let (cur_total, cur_cores) = match read_cpu() {
Some(v) => v,
None => return,
};
let cur_net = read_net().unwrap_or_default();
let cpu = cpu_pct(self.prev_total, cur_total);
let mut per_core = vec![0.0; cur_cores.len()];
for (i, c) in cur_cores.iter().enumerate() {
if i < self.prev_cores.len() {
per_core[i] = cpu_pct(self.prev_cores[i], *c);
}
}
if let Some(m) = read_mem() {
self.hist.push_samples(&[cpu, m.used_pct]);
self.membar.set_value(m.used_pct);
self.set_mem_segments(&m);
}
self.cores.push_samples(&per_core);
let dt = 0.5; // 500 ms tick
let down = (cur_net.rx - self.prev_net.rx) as f64 / dt / 1024.0;
let up = (cur_net.tx - self.prev_net.tx) as f64 / dt / 1024.0;
self.net.push_samples(&[down, up]);
self.net_totals.0 += (cur_net.rx - self.prev_net.rx) as f64;
self.net_totals.1 += (cur_net.tx - self.prev_net.tx) as f64;
self.net.totals = self.net_totals;
self.prev_total = cur_total;
self.prev_cores = cur_cores;
self.prev_net = cur_net;
if self.tick % 4 == 0 {
self.proc_list.refresh_processes();
}
}
fn draw(&mut self, ctx: &DrawCtx, target: &mut CtxTarget, styles: &mut StyleManager) {
ctx.clear(255, 255, 255, WIN_W, WIN_H);
self.tab_proc.draw(target, styles);
self.tab_perf.draw(target, styles);
self.pages.draw(target, styles);
if self.active_page == 0 {
self.proc_list.draw(target, styles);
} else {
self.hist.draw(target, styles);
self.cores.draw(target, styles);
self.membar.draw(target, styles);
self.memstack.draw(target, styles);
self.net.draw(target, styles);
}
ctx.flush();
}
/// Returns true when the click was handled (caller redraws).
fn on_button_press(&mut self, x: i32, y: i32, button: u32) -> bool {
if self.tab_proc.contains(x, y) {
self.tab_proc.on_button_press(x, y, button);
self.set_page(0);
return true;
}
if self.tab_perf.contains(x, y) {
self.tab_perf.on_button_press(x, y, button);
self.set_page(1);
return true;
}
if self.active_page == 0 {
self.proc_list.on_button_press(x, y, button)
} else {
// Graphs take no clicks; forward anyway for focus state.
let mut handled = false;
handled |= self.hist.on_button_press(x, y, button);
handled |= self.cores.on_button_press(x, y, button);
handled |= self.membar.on_button_press(x, y, button);
handled |= self.memstack.on_button_press(x, y, button);
handled |= self.net.on_button_press(x, y, button);
handled
}
}
fn on_button_release(&mut self, x: i32, y: i32, button: u32) -> bool {
let mut handled = false;
handled |= self.tab_proc.on_button_release(x, y, button);
handled |= self.tab_perf.on_button_release(x, y, button);
if self.active_page == 0 {
handled |= self.proc_list.on_button_release(x, y, button);
}
handled
}
}
fn main() -> ExitCode {
match run() {
Ok(code) => ExitCode::from(code as u8),
Err(e) => {
eprintln!("monitor_task_manager: {}", e);
ExitCode::from(1)
}
}
}
fn run() -> Result<i32, Box<dyn std::error::Error>> {
let x = X11::connect()?;
let font = x.open_font(&[FONT_DEFAULT, "fixed"])?;
let title = "Task Manager - monitor".to_string();
let event_mask = EventMask::EXPOSURE
| EventMask::KEY_PRESS
| EventMask::STRUCTURE_NOTIFY
| EventMask::BUTTON_PRESS
| EventMask::BUTTON_RELEASE
| EventMask::POINTER_MOTION;
let (win, gc) = x.create_window(100, 100, WIN_W, WIN_H, &title, event_mask)?;
let mut styles = StyleManager::new();
register_styles(&mut styles);
styles.set_active_style_by_name("default");
let mut app = App::new();
app.prime();
let ctx = DrawCtx::new(&x, win, gc, font);
ctx.bind_font();
let mut target = CtxTarget::new(&ctx);
if !styles.resolve_font("default", &mut target) && !styles.resolve_font("dark", &mut target) {
eprintln!("monitor_task_manager: warning: no font resolved, labels will be blank");
}
app.draw(&ctx, &mut target, &mut styles);
let mut last_tick = Instant::now();
loop {
let ev = match x.conn.poll_for_event()? {
Some(ev) => ev,
None => {
if last_tick.elapsed() >= Duration::from_millis(500) {
last_tick = Instant::now();
app.on_tick();
// Data is sampled every 500 ms, but repainting is
// every 2 s (every 4th tick): the Rust text helpers
// measure with `query_text_extents`, one server
// round trip per call, and a full repaint issues
// hundreds of them (~0.2-0.5 s wall on this Xvfb).
// Repainting every tick would never catch up and
// screenshots would catch the paint mid-draw; at
// 2 s each repaint completes inside its interval
// and the graphs still advance live.
if app.tick % 4 == 0 {
app.draw(&ctx, &mut target, &mut styles);
}
}
std::thread::sleep(Duration::from_millis(10));
continue;
}
};
let mut handled = false;
match ev {
Event::Expose(_) => {
handled = true;
}
Event::ButtonPress(ev) => {
handled =
app.on_button_press(ev.event_x as i32, ev.event_y as i32, ev.detail as u32);
}
Event::ButtonRelease(ev) => {
handled =
app.on_button_release(ev.event_x as i32, ev.event_y as i32, ev.detail as u32);
}
Event::MotionNotify(_) => {}
Event::KeyPress(ev) => {
let keysym = x.keysym_for_keycode(ev.detail);
if keysym == KEY_ESCAPE || keysym == b'q' as u32 {
break;
}
handled = app.proc_list.on_key(
xframe_widgets::Key::from_keysym(keysym, None),
None,
);
}
Event::ClientMessage(ev)
if ev.type_ == x.wm_protocols && ev.data.as_data32()[0] == x.wm_delete =>
{
break;
}
_ => {}
}
if handled {
app.draw(&ctx, &mut target, &mut styles);
}
}
Ok(0)
}
Binary file not shown.

Before

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 4.8 KiB

+63 -3
View File
@@ -417,6 +417,9 @@ pub struct MonitorWidget {
pub sort_desc: bool,
/// Selected process row, if any.
pub selected: Option<usize>,
/// Substring filter on process name (case-insensitive) or pid
/// (empty = show all). Re-applied on every refresh.
pub filter: String,
/// Load averages 1/5/15 min (`XLoadBadge`).
pub loads: [f64; 3],
/// Uptime, seconds (`XLoadBadge`).
@@ -456,6 +459,7 @@ impl MonitorWidget {
sort_col: 2,
sort_desc: true,
selected: None,
filter: String::new(),
loads: [0.0; 3],
uptime_secs: 0,
buttons: Vec::new(),
@@ -675,12 +679,45 @@ impl MonitorWidget {
pub fn refresh_processes(&mut self) -> usize {
let rows = read_processes(12);
if !rows.is_empty() {
// Keep the selection by pid across the re-sort + filter.
let sel_pid = self.selected_pid();
self.rows = rows;
self.sort_rows();
self.apply_filter();
self.selected = sel_pid.and_then(|pid| self.rows.iter().position(|r| r.pid == pid));
}
self.rows.len()
}
/// Substring filter on process name (case-insensitive) or pid.
/// Applies to the rows currently loaded; the next refresh reloads
/// from /proc and re-applies it, so a host app that wants the
/// filter to take effect immediately should call
/// `refresh_processes` right after `set_filter`.
pub fn set_filter(&mut self, text: &str) {
self.filter = text.to_string();
self.apply_filter();
}
pub fn get_filter(&self) -> &str {
&self.filter
}
/// Pid of the selected row, if the selection is still valid.
pub fn selected_pid(&self) -> Option<u32> {
self.selected.and_then(|i| self.rows.get(i)).map(|r| r.pid)
}
fn apply_filter(&mut self) {
if self.filter.is_empty() {
return;
}
let f = self.filter.to_lowercase();
let needle = self.filter.clone();
self.rows
.retain(|r| r.name.to_lowercase().contains(&f) || r.pid.to_string().contains(&needle));
}
/// Sort rows by the current sort column/direction.
pub fn sort_rows(&mut self) {
let (col, desc) = (self.sort_col, self.sort_desc);
@@ -1348,14 +1385,14 @@ impl MonitorWidget {
let y = self.header(target, style, &self.state.name);
// Columns: PID 52 | NAME flex | CPU 96 (bar) | MEM 64.
let x_pid = b.x + 6;
let x_name = x_pid + 64;
let x_name = x_pid + 52;
let x_cpu = b.x + b.w - 170;
let x_mem = b.x + b.w - 66;
let headers = [(x_pid, "PID", 0usize), (x_name, "NAME", 1), (x_cpu, "CPU%", 2), (x_mem, "MEM", 3)];
for (x, label, col) in headers {
let mut text = label.to_string();
if self.sort_col == col {
text.push_str(if self.sort_desc { " v" } else { " ^" });
text.push_str(if self.sort_desc { " ▼" } else { " ▲" });
}
draw_text_at(target, style, x, y + 11, &text);
}
@@ -1579,7 +1616,7 @@ monitor_impl!(
let hy = b.y + 20;
if y < hy + 17 {
let x_pid = b.x + 6;
let x_name = x_pid + 64;
let x_name = x_pid + 52;
let x_cpu = b.x + b.w - 170;
let x_mem = b.x + b.w - 66;
let col = if x < x_name {
@@ -1809,6 +1846,29 @@ mod tests {
assert!(!m.rows.is_empty());
}
#[test]
fn process_list_filter_and_selection() {
let mut m = MonitorWidget::new("ProcessList", "ProcessList", 0, 0, 480, 260);
m.rows = vec![
ProcRow { pid: 9, name: "btop".into(), cpu: 1.0, mem_mb: 5.0 },
ProcRow { pid: 3, name: "alpha".into(), cpu: 9.0, mem_mb: 1.0 },
ProcRow { pid: 5, name: "beta".into(), cpu: 5.0, mem_mb: 9.0 },
];
m.set_filter("alp");
assert_eq!(m.rows.len(), 1);
assert_eq!(m.rows[0].pid, 3);
// Re-seed: an empty filter does not restore rows dropped by an
// earlier filter (the next refresh reloads them from /proc).
m.rows = vec![
ProcRow { pid: 9, name: "btop".into(), cpu: 1.0, mem_mb: 5.0 },
ProcRow { pid: 3, name: "alpha".into(), cpu: 9.0, mem_mb: 1.0 },
];
m.selected = Some(1);
assert_eq!(m.selected_pid(), Some(3));
m.selected = Some(99);
assert_eq!(m.selected_pid(), None);
}
#[test]
fn all_kinds_draw_non_blank() {
// Every kind draws *something* on a headless canvas (a file