monitor/cpu-dashboard (Rust): btop-style CPU dashboard app

XCoreGrid + XTachometer + XHistoryGraph + XLoadBadge + XUsageBar in one
1024x768 window, live /proc/stat + /proc/loadavg sampled every 500 ms.
Seeded demo series cleared at startup and primed with the first live
sample. Widget titles are the widget names (the Rust draw path uses
state.name for the header).
This commit is contained in:
Muse committed 2026-12-05 19:56:49 +00:00
1 parent 9e6f882575
commit 91e1f79176
3 files changed
+351

No files matched your search

@@ -0,0 +1,35 @@
# 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
@@ -0,0 +1,316 @@
//! 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.

After

Width:  |  Height:  |  Size: 8.5 KiB