6 changed files with 308 additions and 0 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

+60
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);
@@ -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