From 2bb49685ed4b6583765e6919ec8f3465ca84460b Mon Sep 17 00:00:00 2001 From: Muse Date: Sat, 5 Dec 2026 20:05:36 +0000 Subject: [PATCH] Disk Monitor app (Stage 2): live per-mount usage bars, Used/Free stack bar, read/write IO history graph 1024x768 window, 1 s refresh from /proc/mounts + statvfs (libc) and /proc/diskstats. MonitorWidget kinds UsageBar / StackBar / HistoryGraph; seeded demo series cleared, titles passed as widget names (StackBar/HistoryGraph headers draw state.name), history auto-ranges (state.max == state.min). XSysBox deliberately unused (no clear-history API, constructor seeds 60 demo samples). Screenshot verified 1024x768 on :116. --- Cargo.lock | 1 + crates/xframe-demo/Cargo.toml | 1 + .../examples/monitor_disk_monitor/README.md | 42 +++ .../examples/monitor_disk_monitor/main.rs | 326 ++++++++++++++++++ .../monitor_disk_monitor/screenshot.png | Bin 0 -> 6837 bytes 5 files changed, 370 insertions(+) create mode 100644 crates/xframe-demo/examples/monitor_disk_monitor/README.md create mode 100644 crates/xframe-demo/examples/monitor_disk_monitor/main.rs create mode 100644 crates/xframe-demo/examples/monitor_disk_monitor/screenshot.png diff --git a/Cargo.lock b/Cargo.lock index 1de74de..dcdb02c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -900,6 +900,7 @@ dependencies = [ name = "xframe-demo" version = "0.1.0" dependencies = [ + "libc", "x11rb", "xframe-common", "xframe-core", diff --git a/crates/xframe-demo/Cargo.toml b/crates/xframe-demo/Cargo.toml index 1ab337e..0e7876e 100644 --- a/crates/xframe-demo/Cargo.toml +++ b/crates/xframe-demo/Cargo.toml @@ -14,3 +14,4 @@ xframe-common = { path = "../xframe-common" } xframe-core = { path = "../xframe-core" } xframe-widgets = { path = "../xframe-widgets" } x11rb = "0.13" +libc = { workspace = true } # monitor_disk_monitor: statvfs for live mount sizes diff --git a/crates/xframe-demo/examples/monitor_disk_monitor/README.md b/crates/xframe-demo/examples/monitor_disk_monitor/README.md new file mode 100644 index 0000000..d9b86dc --- /dev/null +++ b/crates/xframe-demo/examples/monitor_disk_monitor/README.md @@ -0,0 +1,42 @@ +# Disk Monitor — Rust (XFrame) + +A live disk monitor in one 1024x768 window: per-mount usage bars, +a Used / Free stack bar for the largest mount, and a read/write +throughput history graph. All data is live — `/proc/mounts` + +`statvfs` for usage, `/proc/diskstats` (sectors differenced once a +second) for MB/s. Refreshes every second; Esc / `q` / window-close +quits. + +## Widgets used + +| Widget | Role | +| --- | --- | +| XUsageBar (`MonitorWidget`, kind `UsageBar`) | One per disk mount: usage % with total size | +| XStackBar (kind `StackBar`) | Largest mount split into Used / Free (GiB) | +| XHistoryGraph (kind `HistoryGraph`) | Read MB/s + Write MB/s history, 60 s window | + +Seeded demo series/segments are cleared on construction +(`series.clear()`, `set_segments(...)`) so only live data is shown. + +**Why no XSysBox:** it has no clear-history API and its +constructor seeds 60 demo samples, so it cannot show live disk data +without the seeded demo leaking into the history. + +## Build & run + +```sh +bash -lc "cargo run -p xframe-demo --example monitor_disk_monitor" +``` + +## Screenshot + +![Disk Monitor (Rust)](screenshot.png) + +## Source + +- App: `crates/xframe-demo/examples/monitor_disk_monitor/main.rs` +- Repo: https://github.com/cnmcdee/lightgui_rust +- C port: `examples/monitor/disk-monitor/main.cpp` + in https://github.com/cnmcdee/lightgui +- Python port: `examples/monitor_disk_monitor/main.py` + in https://github.com/cnmcdee/lightgui_python diff --git a/crates/xframe-demo/examples/monitor_disk_monitor/main.rs b/crates/xframe-demo/examples/monitor_disk_monitor/main.rs new file mode 100644 index 0000000..74f9ee6 --- /dev/null +++ b/crates/xframe-demo/examples/monitor_disk_monitor/main.rs @@ -0,0 +1,326 @@ +//! Disk Monitor — monitor (Rust / XFrame, `xframe-demo` example). +//! +//! Run it from the workspace root: +//! cargo run -p xframe-demo --example monitor_disk_monitor +//! +//! One 1024x768 window: a live `MonitorWidget` UsageBar per disk +//! mount (`/proc/mounts` + `statvfs`), a StackBar splitting the +//! largest mount into Used / Free (GiB), and a HistoryGraph of disk +//! read/write throughput in MB/s (`/proc/diskstats`, sectors +//! differenced once a second). Refreshes every second; Esc / `q` / +//! window-close quits. Seeded demo series/segments are cleared on +//! construction so only live data is shown. +//! +//! XSysBox is deliberately NOT used: it has no clear-history API and +//! its constructor seeds 60 demo samples, so it cannot show live +//! disk data without the seeded demo leaking into the history. + +use std::collections::HashSet; +use std::ffi::CString; +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::{MonitorWidget, Segment, Widget}; + +const WIN_W: u16 = 1024; +const WIN_H: u16 = 768; +const KEY_ESCAPE: u32 = 0xff1b; + +struct Mount { + point: String, + base: String, + total_gib: f64, + used_gib: f64, + free_gib: f64, + pct: f64, +} + +/// Strip a partition suffix: sda2 -> sda, nvme0n1p2 -> nvme0n1. +fn base_device(dev: &str) -> String { + let mut name = dev.rsplit('/').next().unwrap_or(dev).to_string(); + while name.ends_with(|c: char| c.is_ascii_digit()) { + name.pop(); + } + if name.ends_with('p') + && name.len() >= 2 + && name.as_bytes()[name.len() - 2].is_ascii_digit() + { + name.pop(); + } + name +} + +fn real_fs(fs: &str) -> bool { + matches!(fs, "ext4" | "xfs" | "btrfs") +} + +fn statvfs_gib(point: &str) -> Option<(f64, f64, f64)> { + let c = CString::new(point).ok()?; + let mut sv: libc::statvfs = unsafe { std::mem::zeroed() }; + if unsafe { libc::statvfs(c.as_ptr(), &mut sv) } != 0 { + return None; + } + let total = sv.f_blocks as f64 * sv.f_frsize as f64; + let free = sv.f_bfree as f64 * sv.f_frsize as f64; + let gib = 1_073_741_824.0; + Some((total / gib, (total - free) / gib, free / gib)) +} + +/// Live mounts (real on-disk filesystems, max 4), with statvfs sizes. +fn read_mounts() -> Vec { + let mut mounts = Vec::new(); + let Ok(text) = fs::read_to_string("/proc/mounts") else { + return mounts; + }; + for line in text.lines() { + let f: Vec<&str> = line.split_whitespace().collect(); + if f.len() < 3 || !real_fs(f[2]) { + continue; + } + if mounts.iter().any(|m: &Mount| m.point == f[1]) { + continue; + } + let Some((total, used, free)) = statvfs_gib(f[1]) else { + continue; + }; + mounts.push(Mount { + point: f[1].to_string(), + base: base_device(f[0]), + total_gib: total, + used_gib: used, + free_gib: free, + pct: if total > 0.0 { used / total * 100.0 } else { 0.0 }, + }); + if mounts.len() >= 4 { + break; + } + } + mounts +} + +/// (read_sectors, write_sectors) summed over the backing disks. +fn read_io(mounts: &[Mount]) -> Option<(u64, u64)> { + let text = fs::read_to_string("/proc/diskstats").ok()?; + let bases: HashSet<&str> = mounts.iter().map(|m| m.base.as_str()).collect(); + let (mut rd, mut wr) = (0u64, 0u64); + let mut ok = false; + for line in text.lines() { + let f: Vec<&str> = line.split_whitespace().collect(); + if f.len() < 10 || !bases.contains(f[2]) { + continue; + } + rd += f[5].parse::().unwrap_or(0); + wr += f[9].parse::().unwrap_or(0); + ok = true; + } + if ok { + Some((rd, wr)) + } else { + None + } +} + +fn main() -> ExitCode { + match run() { + Ok(code) => ExitCode::from(code as u8), + Err(e) => { + eprintln!("monitor_disk_monitor: {}", e); + ExitCode::from(1) + } + } +} + +fn run() -> Result> { + let x = X11::connect()?; + let font = x.open_font(&[FONT_DEFAULT, "fixed"])?; + let title = "Disk Monitor - 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(); + register_styles(&mut styles); + + // Live mount list (fixed at startup; mounts rarely change). + let mut mounts = read_mounts(); + if mounts.is_empty() { + mounts.push(Mount { + point: "/".into(), + base: String::new(), + total_gib: 0.0, + used_gib: 0.0, + free_gib: 0.0, + pct: 0.0, + }); + } + let n = mounts.len(); + + // Layout: usage bars on top, stack bar, history graph fills the rest. + let margin = 16i32; + let bar_h = 44i32; + let bar_gap = 8i32; + let stack_h = 170i32; + let stack_y = margin + n as i32 * (bar_h + bar_gap) + 8; + let hist_y = stack_y + stack_h + 8; + let hist_h = WIN_H as i32 - margin - hist_y; + let col_w = WIN_W as i32 - 2 * margin; + + let mut bars: Vec = Vec::new(); + for (i, m) in mounts.iter().enumerate() { + let mut b = MonitorWidget::new( + &format!("UsageBar_{}", i), + "UsageBar", + margin, + margin + i as i32 * (bar_h + bar_gap), + col_w, + bar_h, + ); + b.set_text(&format!("{} {:.0} GiB", m.point, m.total_gib)); + b.set_value(m.pct); + bars.push(b); + } + + // NOTE: HistoryGraph/StackBar headers draw state.name (not + // state.text — only UsageBar prefers text), so the title goes in + // the construction name. state.max == state.min selects the + // history graph's auto-range from the data (the seed is 0..100, + // which would clip IO spikes above 100 MB/s). + let mut stack = MonitorWidget::new("/ disk usage", "StackBar", margin, stack_y, col_w, stack_h); + stack.set_segments(vec![ + Segment { + label: "Used", + value: mounts[0].used_gib, + color: Srgb::new(0, 150, 60), + }, + Segment { + label: "Free", + value: mounts[0].free_gib, + color: Srgb::new(200, 200, 200), + }, + ]); + + let mut hist = MonitorWidget::new( + "Disk IO - MB/s (read / write)", + "HistoryGraph", + margin, + hist_y, + col_w, + hist_h, + ); + hist.state.min = 0.0; + hist.state.max = 0.0; // auto-range from the data + hist.series.clear(); // drop the constructor's seeded demo series + hist.add_series("Read MB/s"); + hist.add_series("Write MB/s"); + + 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_disk_monitor: warning: no font resolved, labels will be blank"); + } + + let redraw = |bars: &mut [MonitorWidget], + stack: &MonitorWidget, + hist: &MonitorWidget, + ctx: &DrawCtx, + target: &mut CtxTarget, + styles: &mut StyleManager| { + ctx.clear(255, 255, 255, WIN_W, WIN_H); + for b in bars.iter() { + b.draw(target, styles); + } + stack.draw(target, styles); + hist.draw(target, styles); + ctx.flush(); + }; + + let mut prev_io = read_io(&mounts); + let refresh = |bars: &mut [MonitorWidget], + stack: &mut MonitorWidget, + hist: &mut MonitorWidget, + mounts: &mut [Mount], + prev_io: &mut Option<(u64, u64)>| { + let live = read_mounts(); + for (i, m) in mounts.iter_mut().enumerate() { + if i >= live.len() { + break; + } + m.total_gib = live[i].total_gib; + m.used_gib = live[i].used_gib; + m.free_gib = live[i].free_gib; + m.pct = live[i].pct; + bars[i].set_value(m.pct); + } + stack.set_segments(vec![ + Segment { + label: "Used", + value: mounts[0].used_gib, + color: Srgb::new(0, 150, 60), + }, + Segment { + label: "Free", + value: mounts[0].free_gib, + color: Srgb::new(200, 200, 200), + }, + ]); + // 1 s tick, 512-byte sectors -> MB/s. + if let Some((rd, wr)) = read_io(mounts) { + if let Some((prd, pwr)) = *prev_io { + hist.push_sample(0, (rd.wrapping_sub(prd)) as f64 * 512.0 / 1e6); + hist.push_sample(1, (wr.wrapping_sub(pwr)) as f64 * 512.0 / 1e6); + } + *prev_io = Some((rd, wr)); + } + }; + + refresh(&mut bars, &mut stack, &mut hist, &mut mounts, &mut prev_io); + redraw(&mut bars, &stack, &hist, &ctx, &mut target, &mut styles); + + let mut last_tick = Instant::now(); + loop { + let ev = match x.conn.poll_for_event()? { + Some(ev) => ev, + None => { + std::thread::sleep(Duration::from_millis(10)); + if last_tick.elapsed() >= Duration::from_secs(1) { + last_tick = Instant::now(); + refresh(&mut bars, &mut stack, &mut hist, &mut mounts, &mut prev_io); + redraw(&mut bars, &stack, &hist, &ctx, &mut target, &mut styles); + } + continue; + } + }; + match ev { + Event::Expose(_) => { + redraw(&mut bars, &stack, &hist, &ctx, &mut target, &mut styles); + } + Event::KeyPress(ev) => { + let keysym = x.keysym_for_keycode(ev.detail); + if keysym == KEY_ESCAPE || keysym == b'q' as u32 { + break; + } + } + Event::ClientMessage(ev) + if ev.type_ == x.wm_protocols && ev.data.as_data32()[0] == x.wm_delete => + { + break; + } + _ => {} + } + } + Ok(0) +} diff --git a/crates/xframe-demo/examples/monitor_disk_monitor/screenshot.png b/crates/xframe-demo/examples/monitor_disk_monitor/screenshot.png new file mode 100644 index 0000000000000000000000000000000000000000..10968527454f8da9918c78b89e0e2a33a6f35031 GIT binary patch literal 6837 zcmb_g2UJtp*53Cf5PDHiL`ob{bWn<-AT8H|z<`L@uu#--a73w6lt8YI3Nwl#GYTrr zkrB`lP*Ivf1RX3i1wpBa2th;=2uMxxPSlxk-v8G6*IVn|mE3br+2!p0?S0CRZmtf> z3fc+)pzP$h${m1;J}DqaK}FoRT?|yvcR9MR0XQ@lfIJE?j+)3GfKXF_ULOFfB!KCG z$;InzP)DSj%LaRiM53Xg!R2xzA|k$e=w(vwVZ&bUbkB8DiPNsaRY7;`qHirbaljH z_)ov9J=2}uFA1Mqo6zhx4eR#q^#GyC5+iafQ4T;JARdYSSkUDm0rGCAC8%8A2hpPI z49k%ip17w~pY_3zCmw1|OPLUcum)avr%qf8VMX-^*iE#Au)_QKwW5k5)?{B=jYwF; zS~ilKCTb~SF-G)xVqq)aZX!2C64lSD5%G&UoHrs*A+bQB|L2c9dD1j!yhCi9JTV?B zP_1AbYe@sTt|~k9b$JEbOVWao@8V-}S<07lbtNW1d_!UH??pYSzM(R(UdS4I8h8Qc zJkte7c}%X;Nh#4uDbp4T{d79&uwu8(Y&4k4uH^LY%vvXn#AtN7@Qj@2;HdS^u@x^}83Y_z#`y6nI z&it^!2eQ_~-DvbN&Y|3CYFZ>?hHZ~h&sY-`*}R609;EYWHjd(ydD!ACp?ufpjkU1#*) z(P&L__XR3AMnRwjw;yv%!PQn+O3aS(8OL&2DxD@OiL9BEi$k(85t7pAY0KB-tGNFh28Xv zD$UkLrEhWF z!mYmd!3^qYSb!vKkWM^N{C7+Lo8kY9DvEOy?Jm_Qmz}?w5*o*eea1sRxu^v z6A5_-TzI(Y!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