Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
921fed5ea0 | ||
|
|
f67c39a07b |
No files matched your search
Generated
+1
@@ -900,6 +900,7 @@ dependencies = [
|
||||
name = "xframe-demo"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"x11rb",
|
||||
"xframe-common",
|
||||
"xframe-core",
|
||||
|
||||
@@ -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"
|
||||
@@ -1,35 +0,0 @@
|
||||
# CPU Dashboard — monitor (Rust)
|
||||
|
||||
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 %) and
|
||||
`/proc/loadavg`, sampled every 500 ms. The seeded demo series each
|
||||
widget preloads are cleared at startup and primed with the first
|
||||
live sample.
|
||||
|
||||
## Run
|
||||
|
||||
```sh
|
||||
cargo run -p xframe-demo --example monitor_cpu_dashboard
|
||||
```
|
||||
|
||||
Pass a hold time in seconds to exit on its own (screenshots):
|
||||
|
||||
```sh
|
||||
cargo run -p xframe-demo --example monitor_cpu_dashboard -- 8
|
||||
```
|
||||
|
||||
Esc, `q`, or closing the window quits.
|
||||
|
||||
## Source
|
||||
|
||||
- App: `crates/xframe-demo/examples/monitor_cpu_dashboard.rs`
|
||||
- Widgets: `crates/xframe-widgets/src/monitor.rs`
|
||||
- Repo: https://github.com/cnmcdee/lightgui_rust
|
||||
@@ -1,316 +0,0 @@
|
||||
//! CPU Dashboard — monitor (Rust).
|
||||
//!
|
||||
//! 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 %) and `/proc/loadavg`, sampled every
|
||||
//! 500 ms. The seeded demo series each widget preloads are cleared at
|
||||
//! startup and primed with the first live sample.
|
||||
//!
|
||||
//! Run it from the workspace root:
|
||||
//! cargo run -p xframe-demo --example monitor_cpu_dashboard
|
||||
//! Pass a hold time in seconds to exit on its own (screenshots):
|
||||
//! cargo run -p xframe-demo --example monitor_cpu_dashboard -- 8
|
||||
//! Esc / `q` / window-close quits.
|
||||
|
||||
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::StyleManager;
|
||||
use xframe_widgets::monitor::read_loadavg;
|
||||
use xframe_widgets::{MonitorWidget, Widget};
|
||||
|
||||
const WIN_W: u16 = 1024;
|
||||
const WIN_H: u16 = 768;
|
||||
const KEY_ESCAPE: u32 = 0xff1b;
|
||||
|
||||
/// One /proc/stat snapshot: (idle, total) per core, plus the aggregate.
|
||||
struct CpuSnap {
|
||||
cores: Vec<(u64, u64)>,
|
||||
total: (u64, u64),
|
||||
}
|
||||
|
||||
fn read_cpu() -> Option<CpuSnap> {
|
||||
let text = fs::read_to_string("/proc/stat").ok()?;
|
||||
let mut cores: Vec<(u64, u64)> = Vec::new();
|
||||
let mut total = (0u64, 0u64);
|
||||
for line in text.lines() {
|
||||
if !line.starts_with("cpu") {
|
||||
continue;
|
||||
}
|
||||
let rest = &line[3..];
|
||||
let is_total = rest.starts_with(' ');
|
||||
let first = rest.chars().next()?;
|
||||
if !is_total && !first.is_ascii_digit() {
|
||||
continue;
|
||||
}
|
||||
let nums: Vec<u64> = rest
|
||||
.split_whitespace()
|
||||
.filter_map(|t| t.parse::<u64>().ok())
|
||||
.collect();
|
||||
if nums.len() < 4 {
|
||||
continue;
|
||||
}
|
||||
let tot: u64 = nums.iter().sum();
|
||||
let idle = nums[3] + nums.get(4).copied().unwrap_or(0);
|
||||
if is_total {
|
||||
total = (idle, tot);
|
||||
} else {
|
||||
cores.push((idle, tot));
|
||||
}
|
||||
}
|
||||
if cores.is_empty() {
|
||||
return None;
|
||||
}
|
||||
Some(CpuSnap { cores, total })
|
||||
}
|
||||
|
||||
/// Per-core busy % between two snapshots, plus the aggregate busy %.
|
||||
fn busy(prev: &CpuSnap, now: &CpuSnap) -> (Vec<f64>, f64) {
|
||||
let pct = |p: (u64, u64), n: (u64, u64)| -> f64 {
|
||||
let dt = n.1.saturating_sub(p.1);
|
||||
let di = n.0.saturating_sub(p.0);
|
||||
if dt == 0 {
|
||||
return 0.0;
|
||||
}
|
||||
(100.0 * (1.0 - di as f64 / dt as f64)).clamp(0.0, 100.0)
|
||||
};
|
||||
let per_core: Vec<f64> = prev
|
||||
.cores
|
||||
.iter()
|
||||
.zip(now.cores.iter())
|
||||
.map(|(p, n)| pct(*p, *n))
|
||||
.collect();
|
||||
let total = if per_core.is_empty() {
|
||||
0.0
|
||||
} else {
|
||||
per_core.iter().sum::<f64>() / per_core.len() as f64
|
||||
};
|
||||
let _ = pct(prev.total, now.total);
|
||||
(per_core, total)
|
||||
}
|
||||
|
||||
fn main() -> ExitCode {
|
||||
let hold = std::env::args()
|
||||
.nth(1)
|
||||
.and_then(|a| a.parse::<u64>().ok());
|
||||
|
||||
let x = match X11::connect() {
|
||||
Ok(x) => x,
|
||||
Err(e) => {
|
||||
eprintln!("monitor_cpu_dashboard: {}", e);
|
||||
return ExitCode::from(1);
|
||||
}
|
||||
};
|
||||
let font = match x.open_font(&[FONT_DEFAULT, "fixed"]) {
|
||||
Ok(f) => f,
|
||||
Err(e) => {
|
||||
eprintln!("monitor_cpu_dashboard: {}", e);
|
||||
return ExitCode::from(1);
|
||||
}
|
||||
};
|
||||
let title = "CPU Dashboard - monitor";
|
||||
let event_mask = EventMask::EXPOSURE
|
||||
| EventMask::KEY_PRESS
|
||||
| EventMask::STRUCTURE_NOTIFY
|
||||
| EventMask::BUTTON_PRESS
|
||||
| EventMask::BUTTON_RELEASE
|
||||
| EventMask::POINTER_MOTION;
|
||||
let (win, gc) = match x.create_window(100, 100, WIN_W, WIN_H, title, event_mask) {
|
||||
Ok(v) => v,
|
||||
Err(e) => {
|
||||
eprintln!("monitor_cpu_dashboard: {}", e);
|
||||
return ExitCode::from(1);
|
||||
}
|
||||
};
|
||||
|
||||
let mut styles = StyleManager::new();
|
||||
xframe_demo::register_styles(&mut styles);
|
||||
|
||||
let ncores = std::thread::available_parallelism()
|
||||
.map(|n| n.get())
|
||||
.unwrap_or(8)
|
||||
.clamp(1, 16);
|
||||
|
||||
let mut badge = MonitorWidget::new("Load avg", "LoadBadge", 16, 16, 320, 84);
|
||||
badge.set_text("Load avg");
|
||||
|
||||
let mut bar = MonitorWidget::new("Total CPU", "UsageBar", 352, 16, 656, 84);
|
||||
bar.set_text("Total CPU");
|
||||
bar.state.min = 0.0;
|
||||
bar.state.max = 100.0;
|
||||
bar.peak = 0.0;
|
||||
|
||||
let mut grid = MonitorWidget::new("CPU cores", "CoreGrid", 16, 116, 640, 300);
|
||||
grid.set_text("CPU cores");
|
||||
grid.series.clear();
|
||||
for c in 0..ncores {
|
||||
grid.add_series(&format!("CPU{}", c));
|
||||
}
|
||||
|
||||
let mut tacho = MonitorWidget::new("CPU %", "Tachometer", 672, 116, 336, 300);
|
||||
tacho.set_text("CPU %");
|
||||
tacho.state.min = 0.0;
|
||||
tacho.state.max = 100.0;
|
||||
tacho.redline_frac = 0.8;
|
||||
tacho.unit = "%".to_string();
|
||||
tacho.peak = 0.0;
|
||||
|
||||
let mut hist = MonitorWidget::new("Total CPU history", "HistoryGraph", 16, 432, 992, 320);
|
||||
hist.set_text("Total CPU history");
|
||||
hist.series.clear();
|
||||
hist.add_series("CPU %");
|
||||
hist.state.min = 0.0;
|
||||
hist.state.max = 100.0;
|
||||
|
||||
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_cpu_dashboard: warning: no font resolved, labels will be blank");
|
||||
}
|
||||
|
||||
let redraw = |badge: &MonitorWidget,
|
||||
bar: &MonitorWidget,
|
||||
grid: &MonitorWidget,
|
||||
tacho: &MonitorWidget,
|
||||
hist: &MonitorWidget,
|
||||
ctx: &DrawCtx,
|
||||
target: &mut CtxTarget,
|
||||
styles: &mut StyleManager| {
|
||||
ctx.clear(255, 255, 255, WIN_W, WIN_H);
|
||||
badge.draw(target, styles);
|
||||
bar.draw(target, styles);
|
||||
grid.draw(target, styles);
|
||||
tacho.draw(target, styles);
|
||||
hist.draw(target, styles);
|
||||
ctx.flush();
|
||||
};
|
||||
|
||||
// Prime with one live sample so the seeded demo series are gone
|
||||
// before the first paint.
|
||||
let mut prev = read_cpu();
|
||||
if let Some(p) = &prev {
|
||||
std::thread::sleep(Duration::from_millis(100));
|
||||
if let Some(now) = read_cpu() {
|
||||
if now.cores.len() == p.cores.len() {
|
||||
let (per_core, total) = busy(p, &now);
|
||||
for _ in 0..48 {
|
||||
grid.push_samples(&per_core);
|
||||
}
|
||||
for _ in 0..90 {
|
||||
hist.push_value(total);
|
||||
}
|
||||
tacho.set_value_peak(total);
|
||||
tacho.reset_peak();
|
||||
bar.set_value_peak(total);
|
||||
prev = Some(now);
|
||||
}
|
||||
}
|
||||
}
|
||||
redraw(&badge, &bar, &grid, &tacho, &hist, &ctx, &mut target, &mut styles);
|
||||
|
||||
let deadline = hold.map(|s| Instant::now() + Duration::from_secs(s));
|
||||
let mut last_tick = Instant::now();
|
||||
loop {
|
||||
if let Some(d) = deadline {
|
||||
if Instant::now() >= d {
|
||||
break;
|
||||
}
|
||||
}
|
||||
match x.conn.poll_for_event() {
|
||||
Ok(Some(ev)) => {
|
||||
let mut handled = false;
|
||||
match ev {
|
||||
Event::Expose(_) => {
|
||||
redraw(&badge, &bar, &grid, &tacho, &hist, &ctx, &mut target, &mut styles);
|
||||
}
|
||||
Event::ButtonPress(ev) => {
|
||||
handled = badge.on_button_press(ev.event_x as i32, ev.event_y as i32, ev.detail as u32)
|
||||
|| bar.on_button_press(ev.event_x as i32, ev.event_y as i32, ev.detail as u32)
|
||||
|| grid.on_button_press(ev.event_x as i32, ev.event_y as i32, ev.detail as u32)
|
||||
|| tacho.on_button_press(ev.event_x as i32, ev.event_y as i32, ev.detail as u32)
|
||||
|| hist.on_button_press(ev.event_x as i32, ev.event_y as i32, ev.detail as u32);
|
||||
}
|
||||
Event::ButtonRelease(ev) => {
|
||||
handled = badge.on_button_release(ev.event_x as i32, ev.event_y as i32, ev.detail as u32)
|
||||
|| bar.on_button_release(ev.event_x as i32, ev.event_y as i32, ev.detail as u32)
|
||||
|| grid.on_button_release(ev.event_x as i32, ev.event_y as i32, ev.detail as u32)
|
||||
|| tacho.on_button_release(ev.event_x as i32, ev.event_y as i32, ev.detail as u32)
|
||||
|| hist.on_button_release(ev.event_x as i32, ev.event_y as i32, ev.detail as u32);
|
||||
}
|
||||
Event::MotionNotify(ev) => {
|
||||
handled = badge.on_motion(ev.event_x as i32, ev.event_y as i32)
|
||||
|| bar.on_motion(ev.event_x as i32, ev.event_y as i32)
|
||||
|| grid.on_motion(ev.event_x as i32, ev.event_y as i32)
|
||||
|| tacho.on_motion(ev.event_x as i32, ev.event_y as i32)
|
||||
|| hist.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 || keysym == b'q' as u32 {
|
||||
break;
|
||||
}
|
||||
let text = if (0x20..0x7f).contains(&keysym) {
|
||||
Some(keysym as u8 as char)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let key = xframe_widgets::Key::from_keysym(keysym, text);
|
||||
handled = badge.on_key(key, text)
|
||||
|| bar.on_key(key, text)
|
||||
|| grid.on_key(key, text)
|
||||
|| tacho.on_key(key, text)
|
||||
|| hist.on_key(key, text);
|
||||
}
|
||||
Event::ClientMessage(ev)
|
||||
if ev.type_ == x.wm_protocols && ev.data.as_data32()[0] == x.wm_delete =>
|
||||
{
|
||||
break;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
if handled {
|
||||
redraw(&badge, &bar, &grid, &tacho, &hist, &ctx, &mut target, &mut styles);
|
||||
}
|
||||
}
|
||||
Ok(None) => {
|
||||
std::thread::sleep(Duration::from_millis(10));
|
||||
}
|
||||
Err(e) => {
|
||||
eprintln!("monitor_cpu_dashboard: {}", e);
|
||||
return ExitCode::from(1);
|
||||
}
|
||||
}
|
||||
// 500 ms tick: live sample from /proc/stat + /proc/loadavg.
|
||||
if last_tick.elapsed() >= Duration::from_millis(500) {
|
||||
last_tick = Instant::now();
|
||||
if let Some(p) = &prev {
|
||||
if let Some(now) = read_cpu() {
|
||||
if now.cores.len() == p.cores.len() {
|
||||
let (per_core, total) = busy(p, &now);
|
||||
grid.push_samples(&per_core);
|
||||
hist.push_value(total);
|
||||
tacho.set_value_peak(total);
|
||||
bar.set_value_peak(total);
|
||||
prev = Some(now);
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some((loads, up)) = read_loadavg() {
|
||||
badge.set_loads(loads, up);
|
||||
}
|
||||
redraw(&badge, &bar, &grid, &tacho, &hist, &ctx, &mut target, &mut styles);
|
||||
}
|
||||
}
|
||||
ExitCode::from(0)
|
||||
}
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 8.5 KiB |
@@ -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 |
@@ -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);
|
||||
@@ -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
|
||||
|
||||
Reference in new issue
Block a user