Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e11daf6d4e | ||
|
|
5321a98ec5 | ||
|
|
8fe131c1ee | ||
|
|
696579530b | ||
|
|
d098e756dd | ||
|
|
2eca0e813c | ||
|
|
2b6a114900 | ||
|
|
cc04741431 | ||
|
|
5f13083fd7 | ||
|
|
e7192f0b7b | ||
|
|
2bb49685ed | ||
|
|
69e9c23878 | ||
|
|
6b79ef3e6d | ||
|
|
77d9446d2a | ||
|
|
921fed5ea0 | ||
|
|
f67c39a07b | ||
|
|
91e1f79176 | ||
|
|
da8e6d4f28 |
No files matched your search
@@ -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"
|
||||
@@ -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)
|
||||
}
|
||||
|
After Width: | Height: | Size: 8.5 KiB |
@@ -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
|
||||
|
||||

|
||||
|
||||
## 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
|
||||
@@ -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<Mount> {
|
||||
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::<u64>().unwrap_or(0);
|
||||
wr += f[9].parse::<u64>().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<i32, Box<dyn std::error::Error>> {
|
||||
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<MonitorWidget> = 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)
|
||||
}
|
||||
|
After Width: | Height: | Size: 6.7 KiB |
@@ -0,0 +1,32 @@
|
||||
# Memory Monitor — Rust
|
||||
|
||||
A btop-style memory monitor in one 1024x768 window, built from the new
|
||||
XFrame monitor widgets (Stage 2 of the btop-widget project). All data is
|
||||
live from `/proc/meminfo`, refreshed every 500 ms.
|
||||
|
||||
## What it shows
|
||||
|
||||
- **XSysBox "MEMORY"** — big used-% number, mini history graph, usage bar
|
||||
- **XDonutGauge "Memory used" / "Swap used"** — ring gauges (swap is 0%
|
||||
on machines with no swap configured)
|
||||
- **XStackBar** — used / cached / buffers / free in GiB, with legend;
|
||||
the header carries the live available figure
|
||||
- **XHistoryGraph** — used % and cached % over the last 60 seconds
|
||||
- **XUsageBar x3** — Memory used, Cached, Swap used
|
||||
|
||||
"Used" follows the `free` convention: total − free − buffers − cached.
|
||||
|
||||
## Build and run
|
||||
|
||||
```sh
|
||||
cargo run -p xframe-demo --example monitor_memory_monitor
|
||||
```
|
||||
|
||||
Quit with `q`, `Esc`, or the window close button.
|
||||
|
||||
## Widgets used
|
||||
|
||||
XSysBox, XDonutGauge, XStackBar, XHistoryGraph, XUsageBar — all from the
|
||||
LightGUI registry (562 widgets: 547 + 15 monitor widgets), driven through
|
||||
`MonitorWidget` (`set_value` / `push_value` / `push_sample` /
|
||||
`set_segments`).
|
||||
@@ -0,0 +1,339 @@
|
||||
//! Memory Monitor — monitor (Stage 2, btop-widget project).
|
||||
//!
|
||||
//! One 1024x768 window of live memory data from `/proc/meminfo`,
|
||||
//! refreshed every 500 ms. Every visible element is one of the new
|
||||
//! XFrame monitor widgets: `XSysBox` (big used %), `XDonutGauge` x2
|
||||
//! (memory / swap used), `XStackBar` (used / cached / buffers / free),
|
||||
//! `XHistoryGraph` (used % and cached % over the last 60 s),
|
||||
//! `XUsageBar` x3 (memory used / cached / swap used). No raw x11rb
|
||||
//! drawing for UI elements: the shell only opens the window, clears it
|
||||
//! and calls each widget's `draw()`.
|
||||
//!
|
||||
//! Run it from the workspace root:
|
||||
//! cargo run -p xframe-demo --example monitor_memory_monitor
|
||||
//! Quit with Esc / `q` or the window close button.
|
||||
|
||||
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;
|
||||
|
||||
const GREEN: Srgb = Srgb::new(34, 197, 94);
|
||||
const BLUE: Srgb = Srgb::new(59, 130, 246);
|
||||
const CYAN: Srgb = Srgb::new(34, 211, 238);
|
||||
const GREY_DIM: Srgb = Srgb::new(200, 200, 200);
|
||||
|
||||
/// Live memory figures from /proc/meminfo. "Used" follows the `free`
|
||||
/// convention: total - free - buffers - cached.
|
||||
#[derive(Default, Clone, Copy)]
|
||||
struct MemInfo {
|
||||
free_gib: f64,
|
||||
avail_gib: f64,
|
||||
cached_gib: f64,
|
||||
buffers_gib: f64,
|
||||
used_gib: f64,
|
||||
used_pct: f64,
|
||||
cached_pct: f64,
|
||||
swap_pct: f64,
|
||||
}
|
||||
|
||||
fn read_meminfo() -> Option<MemInfo> {
|
||||
let text = fs::read_to_string("/proc/meminfo").ok()?;
|
||||
let mut total = 0f64;
|
||||
let mut free_kb = 0f64;
|
||||
let mut avail = 0f64;
|
||||
let mut cached = 0f64;
|
||||
let mut buffers = 0f64;
|
||||
let mut swap_total = 0f64;
|
||||
let mut swap_free = 0f64;
|
||||
for line in text.lines() {
|
||||
let mut parts = line.split_whitespace();
|
||||
let key = parts.next().unwrap_or("");
|
||||
let val: f64 = parts.next().and_then(|v| v.parse().ok()).unwrap_or(0.0);
|
||||
match key {
|
||||
"MemTotal:" => total = val,
|
||||
"MemFree:" => free_kb = val,
|
||||
"MemAvailable:" => avail = val,
|
||||
"Cached:" => cached = val,
|
||||
"Buffers:" => buffers = val,
|
||||
"SwapTotal:" => swap_total = val,
|
||||
"SwapFree:" => swap_free = val,
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
if total <= 0.0 {
|
||||
return None;
|
||||
}
|
||||
let gib = 1024.0 * 1024.0;
|
||||
let used_gib = ((total - free_kb - buffers - cached) / gib).max(0.0);
|
||||
let total_gib = total / gib;
|
||||
let swap_used_gib = ((swap_total - swap_free) / gib).max(0.0);
|
||||
Some(MemInfo {
|
||||
free_gib: free_kb / gib,
|
||||
avail_gib: avail / gib,
|
||||
cached_gib: cached / gib,
|
||||
buffers_gib: buffers / gib,
|
||||
used_gib,
|
||||
used_pct: used_gib / total_gib * 100.0,
|
||||
cached_pct: cached / gib / total_gib * 100.0,
|
||||
swap_pct: if swap_total > 0.0 {
|
||||
swap_used_gib / (swap_total / gib) * 100.0
|
||||
} else {
|
||||
0.0
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
fn main() -> ExitCode {
|
||||
match run() {
|
||||
Ok(code) => ExitCode::from(code as u8),
|
||||
Err(e) => {
|
||||
eprintln!("monitor_memory_monitor: {}", 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 = "Memory 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);
|
||||
|
||||
// -- widgets (live setters only; seeded demo data is replaced) --
|
||||
let mut sysbox = MonitorWidget::new("MEMORY", "SysBox", 16, 16, 500, 190);
|
||||
sysbox.title = "MEMORY".to_string();
|
||||
sysbox.unit = "%".to_string();
|
||||
sysbox.set_range(0.0, 100.0);
|
||||
sysbox.series.clear();
|
||||
sysbox.add_series("Memory %");
|
||||
|
||||
let mut donut_mem = MonitorWidget::new("Memory used", "DonutGauge", 532, 16, 230, 190);
|
||||
donut_mem.set_range(0.0, 100.0);
|
||||
let mut donut_swap = MonitorWidget::new("Swap used", "DonutGauge", 778, 16, 230, 190);
|
||||
donut_swap.set_range(0.0, 100.0);
|
||||
|
||||
let mut stack = MonitorWidget::new("Memory", "StackBar", 16, 222, 992, 170);
|
||||
|
||||
let mut history = MonitorWidget::new("Memory history", "HistoryGraph", 16, 408, 992, 200);
|
||||
history.set_range(0.0, 100.0);
|
||||
history.series.clear();
|
||||
history.add_series("Used %");
|
||||
history.add_series("Cached %");
|
||||
|
||||
let mut bar_mem = MonitorWidget::new("Memory used", "UsageBar", 16, 624, 992, 36);
|
||||
bar_mem.set_text("Memory used");
|
||||
bar_mem.set_range(0.0, 100.0);
|
||||
let mut bar_cached = MonitorWidget::new("Cached", "UsageBar", 16, 664, 992, 36);
|
||||
bar_cached.set_text("Cached");
|
||||
bar_cached.set_range(0.0, 100.0);
|
||||
let mut bar_swap = MonitorWidget::new("Swap used", "UsageBar", 16, 704, 992, 36);
|
||||
bar_swap.set_text("Swap used");
|
||||
bar_swap.set_range(0.0, 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_memory_monitor: warning: no font resolved, labels will be blank");
|
||||
}
|
||||
|
||||
// -- live tick: feed /proc/meminfo into every widget, then redraw --
|
||||
let tick = |sysbox: &mut MonitorWidget,
|
||||
donut_mem: &mut MonitorWidget,
|
||||
donut_swap: &mut MonitorWidget,
|
||||
stack: &mut MonitorWidget,
|
||||
history: &mut MonitorWidget,
|
||||
bar_mem: &mut MonitorWidget,
|
||||
bar_cached: &mut MonitorWidget,
|
||||
bar_swap: &mut MonitorWidget,
|
||||
ctx: &DrawCtx,
|
||||
target: &mut CtxTarget,
|
||||
styles: &mut StyleManager| {
|
||||
let Some(m) = read_meminfo() else {
|
||||
return;
|
||||
};
|
||||
sysbox.set_value(m.used_pct);
|
||||
sysbox.push_value(m.used_pct);
|
||||
donut_mem.set_value(m.used_pct);
|
||||
donut_swap.set_value(m.swap_pct);
|
||||
stack.set_segments(vec![
|
||||
Segment { label: "used", value: m.used_gib, color: GREEN },
|
||||
Segment { label: "cached", value: m.cached_gib, color: BLUE },
|
||||
Segment { label: "buffers", value: m.buffers_gib, color: CYAN },
|
||||
Segment { label: "free", value: m.free_gib, color: GREY_DIM },
|
||||
]);
|
||||
stack.state.name = format!("Memory - avail {:.1} GiB", m.avail_gib);
|
||||
history.push_sample(0, m.used_pct);
|
||||
history.push_sample(1, m.cached_pct);
|
||||
bar_mem.set_value(m.used_pct);
|
||||
bar_cached.set_value(m.cached_pct);
|
||||
bar_swap.set_value(m.swap_pct);
|
||||
ctx.clear(255, 255, 255, WIN_W, WIN_H);
|
||||
sysbox.draw(target, styles);
|
||||
donut_mem.draw(target, styles);
|
||||
donut_swap.draw(target, styles);
|
||||
stack.draw(target, styles);
|
||||
history.draw(target, styles);
|
||||
bar_mem.draw(target, styles);
|
||||
bar_cached.draw(target, styles);
|
||||
bar_swap.draw(target, styles);
|
||||
ctx.flush();
|
||||
};
|
||||
|
||||
// First live sample, then flush the SysBox's seeded demo history
|
||||
// (60 samples) with the live value so the mini-graph is real data
|
||||
// from the first paint, not the demo sine wave.
|
||||
if let Some(m) = read_meminfo() {
|
||||
for _ in 0..60 {
|
||||
sysbox.set_value(m.used_pct);
|
||||
sysbox.push_value(m.used_pct);
|
||||
}
|
||||
}
|
||||
tick(
|
||||
&mut sysbox,
|
||||
&mut donut_mem,
|
||||
&mut donut_swap,
|
||||
&mut stack,
|
||||
&mut history,
|
||||
&mut bar_mem,
|
||||
&mut bar_cached,
|
||||
&mut bar_swap,
|
||||
&ctx,
|
||||
&mut target,
|
||||
&mut styles,
|
||||
);
|
||||
|
||||
let mut last_tick = Instant::now();
|
||||
loop {
|
||||
if last_tick.elapsed() >= Duration::from_millis(500) {
|
||||
tick(
|
||||
&mut sysbox,
|
||||
&mut donut_mem,
|
||||
&mut donut_swap,
|
||||
&mut stack,
|
||||
&mut history,
|
||||
&mut bar_mem,
|
||||
&mut bar_cached,
|
||||
&mut bar_swap,
|
||||
&ctx,
|
||||
&mut target,
|
||||
&mut styles,
|
||||
);
|
||||
last_tick = Instant::now();
|
||||
}
|
||||
let ev = match x.conn.poll_for_event()? {
|
||||
Some(ev) => ev,
|
||||
None => {
|
||||
std::thread::sleep(Duration::from_millis(10));
|
||||
continue;
|
||||
}
|
||||
};
|
||||
let mut handled = false;
|
||||
match ev {
|
||||
Event::Expose(_) => {
|
||||
ctx.clear(255, 255, 255, WIN_W, WIN_H);
|
||||
sysbox.draw(&mut target, &mut styles);
|
||||
donut_mem.draw(&mut target, &mut styles);
|
||||
donut_swap.draw(&mut target, &mut styles);
|
||||
stack.draw(&mut target, &mut styles);
|
||||
history.draw(&mut target, &mut styles);
|
||||
bar_mem.draw(&mut target, &mut styles);
|
||||
bar_cached.draw(&mut target, &mut styles);
|
||||
bar_swap.draw(&mut target, &mut styles);
|
||||
ctx.flush();
|
||||
}
|
||||
Event::ButtonPress(ev) => {
|
||||
handled = sysbox.on_button_press(ev.event_x as i32, ev.event_y as i32, ev.detail as u32)
|
||||
|| donut_mem.on_button_press(ev.event_x as i32, ev.event_y as i32, ev.detail as u32)
|
||||
|| donut_swap.on_button_press(ev.event_x as i32, ev.event_y as i32, ev.detail as u32)
|
||||
|| stack.on_button_press(ev.event_x as i32, ev.event_y as i32, ev.detail as u32)
|
||||
|| history.on_button_press(ev.event_x as i32, ev.event_y as i32, ev.detail as u32)
|
||||
|| bar_mem.on_button_press(ev.event_x as i32, ev.event_y as i32, ev.detail as u32)
|
||||
|| bar_cached.on_button_press(ev.event_x as i32, ev.event_y as i32, ev.detail as u32)
|
||||
|| bar_swap.on_button_press(ev.event_x as i32, ev.event_y as i32, ev.detail as u32);
|
||||
}
|
||||
Event::ButtonRelease(ev) => {
|
||||
handled = sysbox.on_button_release(ev.event_x as i32, ev.event_y as i32, ev.detail as u32)
|
||||
|| donut_mem.on_button_release(ev.event_x as i32, ev.event_y as i32, ev.detail as u32)
|
||||
|| donut_swap.on_button_release(ev.event_x as i32, ev.event_y as i32, ev.detail as u32)
|
||||
|| stack.on_button_release(ev.event_x as i32, ev.event_y as i32, ev.detail as u32)
|
||||
|| history.on_button_release(ev.event_x as i32, ev.event_y as i32, ev.detail as u32)
|
||||
|| bar_mem.on_button_release(ev.event_x as i32, ev.event_y as i32, ev.detail as u32)
|
||||
|| bar_cached.on_button_release(ev.event_x as i32, ev.event_y as i32, ev.detail as u32)
|
||||
|| bar_swap.on_button_release(ev.event_x as i32, ev.event_y as i32, ev.detail as u32);
|
||||
}
|
||||
Event::MotionNotify(ev) => {
|
||||
handled = sysbox.on_motion(ev.event_x as i32, ev.event_y as i32)
|
||||
|| donut_mem.on_motion(ev.event_x as i32, ev.event_y as i32)
|
||||
|| donut_swap.on_motion(ev.event_x as i32, ev.event_y as i32)
|
||||
|| stack.on_motion(ev.event_x as i32, ev.event_y as i32)
|
||||
|| history.on_motion(ev.event_x as i32, ev.event_y as i32)
|
||||
|| bar_mem.on_motion(ev.event_x as i32, ev.event_y as i32)
|
||||
|| bar_cached.on_motion(ev.event_x as i32, ev.event_y as i32)
|
||||
|| bar_swap.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
|
||||
};
|
||||
handled = sysbox.on_key(xframe_widgets::Key::from_keysym(keysym, text), text)
|
||||
|| donut_mem.on_key(xframe_widgets::Key::from_keysym(keysym, text), text)
|
||||
|| donut_swap.on_key(xframe_widgets::Key::from_keysym(keysym, text), text)
|
||||
|| stack.on_key(xframe_widgets::Key::from_keysym(keysym, text), text)
|
||||
|| history.on_key(xframe_widgets::Key::from_keysym(keysym, text), text)
|
||||
|| bar_mem.on_key(xframe_widgets::Key::from_keysym(keysym, text), text)
|
||||
|| bar_cached.on_key(xframe_widgets::Key::from_keysym(keysym, text), text)
|
||||
|| bar_swap.on_key(xframe_widgets::Key::from_keysym(keysym, text), text);
|
||||
}
|
||||
Event::ClientMessage(ev)
|
||||
if ev.type_ == x.wm_protocols && ev.data.as_data32()[0] == x.wm_delete =>
|
||||
{
|
||||
break;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
if handled {
|
||||
ctx.clear(255, 255, 255, WIN_W, WIN_H);
|
||||
sysbox.draw(&mut target, &mut styles);
|
||||
donut_mem.draw(&mut target, &mut styles);
|
||||
donut_swap.draw(&mut target, &mut styles);
|
||||
stack.draw(&mut target, &mut styles);
|
||||
history.draw(&mut target, &mut styles);
|
||||
bar_mem.draw(&mut target, &mut styles);
|
||||
bar_cached.draw(&mut target, &mut styles);
|
||||
bar_swap.draw(&mut target, &mut styles);
|
||||
ctx.flush();
|
||||
}
|
||||
}
|
||||
Ok(0)
|
||||
}
|
||||
|
After Width: | Height: | Size: 6.4 KiB |
@@ -0,0 +1,41 @@
|
||||
# Network Monitor — monitor (Rust)
|
||||
|
||||
A live network monitor in one 1024x768 window, built only from the
|
||||
LightGUI XFrame monitor widgets (Stage 2 of the btop-widget project).
|
||||
|
||||
## What it shows
|
||||
|
||||
Live traffic for the main interface (`enp3s0` on hot_dallas, otherwise
|
||||
the first non-loopback interface with traffic), read from
|
||||
`/proc/net/dev` and differenced every 500 ms:
|
||||
|
||||
- **XNetGraph** (top) — up/down graph in KB/s, current rates plus
|
||||
session totals in the legend.
|
||||
- **XSysBox** (middle, x2) — Download / Upload big-number boxes in
|
||||
KB/s, each with its own history sparkline and usage bar. The range
|
||||
tracks the session peak (x1.15, floor 100 KB/s).
|
||||
- **XHistoryGraph** — down/up rate history in KB/s, 60 s window.
|
||||
- **XUsageBar** (bottom) — total throughput as a percentage of the
|
||||
link speed (from `/sys/class/net/<iface>/speed`, 1 Gb/s fallback).
|
||||
|
||||
## Live data, not demo data
|
||||
|
||||
The widgets seed deterministic demo series in the constructor. The
|
||||
app clears them (`series.clear()` + `add_series`) before the first
|
||||
draw, so everything on screen is measured traffic.
|
||||
|
||||
## Build and run
|
||||
|
||||
```sh
|
||||
bash -lc "cargo run -p xframe-demo --example monitor_network_monitor"
|
||||
# quit with q, Escape, or window close
|
||||
```
|
||||
|
||||
## Source
|
||||
|
||||
- C: `examples/monitor/network-monitor/main.cpp` in
|
||||
[lightgui](https://github.com/cnmcdee/lightgui)
|
||||
- Rust: `crates/xframe-demo/examples/monitor_network_monitor/main.rs` in
|
||||
[lightgui_rust](https://github.com/cnmcdee/lightgui_rust)
|
||||
- Python: `examples/monitor_network_monitor/main.py` in
|
||||
[lightgui_python](https://github.com/cnmcdee/lightgui_python)
|
||||
@@ -0,0 +1,430 @@
|
||||
//! Network Monitor - monitor (Stage 2, btop-widget project).
|
||||
//!
|
||||
//! One 1024x768 window showing LIVE traffic for the main interface
|
||||
//! (`enp3s0` on hot_dallas, else the first non-loopback interface with
|
||||
//! traffic), read from `/proc/net/dev` and differenced every 500 ms:
|
||||
//!
|
||||
//! * `XNetGraph` (top) — up/down graph, current rates + session totals.
|
||||
//! * `XSysBox` (middle, x2) — Download / Upload big-number boxes in
|
||||
//! KB/s, each with its own history sparkline and usage bar.
|
||||
//! * `XHistoryGraph` — down/up rate history in KB/s, 60 s window.
|
||||
//! * `XUsageBar` (bottom) — total throughput as % of the link speed.
|
||||
//!
|
||||
//! The widgets seed deterministic demo series in the constructor;
|
||||
//! the app clears them (`series.clear()` + `add_series`) before the
|
||||
//! first draw, so everything on screen is measured traffic.
|
||||
//!
|
||||
//! Run from the workspace root:
|
||||
//! cargo run -p xframe-demo --example monitor_network_monitor
|
||||
//! Quit: Esc / `q` / window close.
|
||||
|
||||
use std::fs;
|
||||
use std::process::ExitCode;
|
||||
use std::thread;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use x11rb::connection::Connection;
|
||||
use x11rb::protocol::xproto::EventMask;
|
||||
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_demo::register_styles;
|
||||
use xframe_widgets::monitor::MonitorWidget;
|
||||
use xframe_widgets::Widget;
|
||||
|
||||
const WIN_W: u16 = 1024;
|
||||
const WIN_H: u16 = 768;
|
||||
const KEY_ESCAPE: u32 = 0xff1b;
|
||||
|
||||
/// (rx_bytes, tx_bytes) for `iface` from /proc/net/dev.
|
||||
fn read_counters(iface: &str) -> Option<(u64, u64)> {
|
||||
let text = fs::read_to_string("/proc/net/dev").ok()?;
|
||||
for line in text.lines() {
|
||||
let Some((name, rest)) = line.split_once(':') else {
|
||||
continue;
|
||||
};
|
||||
if name.trim() != iface {
|
||||
continue;
|
||||
}
|
||||
let f: Vec<&str> = rest.split_whitespace().collect();
|
||||
if f.len() < 9 {
|
||||
return None;
|
||||
}
|
||||
return Some((f[0].parse().ok()?, f[8].parse().ok()?));
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// Prefer enp3s0; else the first non-loopback interface with traffic.
|
||||
fn pick_iface() -> String {
|
||||
if read_counters("enp3s0").is_some() {
|
||||
return "enp3s0".to_string();
|
||||
}
|
||||
if let Ok(text) = fs::read_to_string("/proc/net/dev") {
|
||||
let mut fallback = "enp3s0".to_string();
|
||||
for line in text.lines() {
|
||||
let Some((name, rest)) = line.split_once(':') else {
|
||||
continue;
|
||||
};
|
||||
let name = name.trim();
|
||||
if name == "lo" || name.is_empty() {
|
||||
continue;
|
||||
}
|
||||
if fallback == "enp3s0" {
|
||||
fallback = name.to_string();
|
||||
}
|
||||
let f: Vec<&str> = rest.split_whitespace().collect();
|
||||
let rx: u64 = f.first().and_then(|v| v.parse().ok()).unwrap_or(0);
|
||||
let tx: u64 = f.get(8).and_then(|v| v.parse().ok()).unwrap_or(0);
|
||||
if rx > 0 || tx > 0 {
|
||||
return name.to_string();
|
||||
}
|
||||
}
|
||||
return fallback;
|
||||
}
|
||||
"enp3s0".to_string()
|
||||
}
|
||||
|
||||
/// Link speed in bits/s from /sys/class/net/<iface>/speed (Mbit/s);
|
||||
/// unknown/unreadable -> assume 1 Gbit/s.
|
||||
fn link_speed_bps(iface: &str) -> f64 {
|
||||
let path = format!("/sys/class/net/{}/speed", iface);
|
||||
if let Ok(s) = fs::read_to_string(path) {
|
||||
if let Ok(mbps) = s.trim().parse::<i64>() {
|
||||
if mbps > 0 {
|
||||
return mbps as f64 * 1e6;
|
||||
}
|
||||
}
|
||||
}
|
||||
1e9
|
||||
}
|
||||
|
||||
fn run() -> Result<(), Box<dyn std::error::Error>> {
|
||||
let iface = pick_iface();
|
||||
let link_bps = link_speed_bps(&iface);
|
||||
|
||||
let x = X11::connect()?;
|
||||
let font = x.open_font(&[FONT_DEFAULT, "fixed"])?;
|
||||
let title = "Network Monitor - 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);
|
||||
|
||||
// Widgets: seeded demo series are cleared below before first draw.
|
||||
let mut net = MonitorWidget::new(
|
||||
&format!("Network - {}", iface),
|
||||
"NetGraph",
|
||||
12,
|
||||
12,
|
||||
1000,
|
||||
300,
|
||||
);
|
||||
net.series.clear();
|
||||
net.add_series("Down");
|
||||
net.add_series("Up");
|
||||
net.unit = "KB/s".to_string();
|
||||
net.totals = (0.0, 0.0);
|
||||
net.state.min = 0.0;
|
||||
net.state.max = 0.0; // auto-range from the data
|
||||
|
||||
let mut down_box = MonitorWidget::new(
|
||||
"Download",
|
||||
"SysBox",
|
||||
12,
|
||||
324,
|
||||
492,
|
||||
180,
|
||||
);
|
||||
down_box.title = format!("Download - {}", iface);
|
||||
down_box.unit = " KB/s".to_string();
|
||||
down_box.state.min = 0.0;
|
||||
down_box.state.max = 100.0;
|
||||
down_box.series.clear();
|
||||
down_box.add_series("Download");
|
||||
|
||||
let mut up_box = MonitorWidget::new("Upload", "SysBox", 520, 324, 492, 180);
|
||||
up_box.title = format!("Upload - {}", iface);
|
||||
up_box.unit = " KB/s".to_string();
|
||||
up_box.state.min = 0.0;
|
||||
up_box.state.max = 100.0;
|
||||
up_box.series.clear();
|
||||
up_box.add_series("Upload");
|
||||
|
||||
let mut hist = MonitorWidget::new("Rate history (KB/s)", "HistoryGraph", 12, 516, 1000, 172);
|
||||
hist.series.clear();
|
||||
hist.add_series("Down KB/s");
|
||||
hist.add_series("Up KB/s");
|
||||
hist.state.min = 0.0;
|
||||
hist.state.max = 0.0; // auto-range from the data
|
||||
|
||||
let mut usage = MonitorWidget::new("Link use", "UsageBar", 12, 700, 1000, 44);
|
||||
usage.set_text(&format!(
|
||||
"Link use - {} ({:.0} Gb/s)",
|
||||
iface,
|
||||
link_bps / 1e9
|
||||
));
|
||||
usage.state.min = 0.0;
|
||||
usage.state.max = 100.0;
|
||||
usage.state.value = 0.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_network_monitor: warning: no font resolved, labels will be blank");
|
||||
}
|
||||
|
||||
// First live rate (two reads 500 ms apart).
|
||||
let (rx0, tx0) = read_counters(&iface).unwrap_or((0, 0));
|
||||
thread::sleep(Duration::from_millis(500));
|
||||
let (mut prev_rx, mut prev_tx) = read_counters(&iface).unwrap_or((rx0, tx0));
|
||||
let mut prev_time = Instant::now();
|
||||
let mut down_bps = if prev_rx >= rx0 {
|
||||
(prev_rx - rx0) as f64 / 0.5
|
||||
} else {
|
||||
0.0
|
||||
};
|
||||
let mut up_bps = if prev_tx >= tx0 {
|
||||
(prev_tx - tx0) as f64 / 0.5
|
||||
} else {
|
||||
0.0
|
||||
};
|
||||
let mut peak_down = (down_bps / 1024.0 * 1.15).max(100.0);
|
||||
let mut peak_up = (up_bps / 1024.0 * 1.15).max(100.0);
|
||||
|
||||
// Feed one live sample into every widget, then draw.
|
||||
let push_sample = |net: &mut MonitorWidget,
|
||||
down_box: &mut MonitorWidget,
|
||||
up_box: &mut MonitorWidget,
|
||||
hist: &mut MonitorWidget,
|
||||
usage: &mut MonitorWidget,
|
||||
down_bps: f64,
|
||||
up_bps: f64,
|
||||
dt: f64,
|
||||
peak_down: f64,
|
||||
peak_up: f64,
|
||||
link_bps: f64| {
|
||||
let down_kb = down_bps / 1024.0;
|
||||
let up_kb = up_bps / 1024.0;
|
||||
net.push_samples(&[down_kb, up_kb]);
|
||||
net.totals.0 += down_bps * dt;
|
||||
net.totals.1 += up_bps * dt;
|
||||
hist.push_samples(&[down_kb, up_kb]);
|
||||
down_box.state.max = peak_down;
|
||||
up_box.state.max = peak_up;
|
||||
down_box.state.value = down_kb;
|
||||
up_box.state.value = up_kb;
|
||||
down_box.push_value(down_kb);
|
||||
up_box.push_value(up_kb);
|
||||
usage.state.value = ((down_bps + up_bps) / link_bps * 100.0).min(100.0);
|
||||
};
|
||||
push_sample(
|
||||
&mut net,
|
||||
&mut down_box,
|
||||
&mut up_box,
|
||||
&mut hist,
|
||||
&mut usage,
|
||||
down_bps,
|
||||
up_bps,
|
||||
0.5,
|
||||
peak_down,
|
||||
peak_up,
|
||||
link_bps,
|
||||
);
|
||||
|
||||
let redraw = |net: &MonitorWidget,
|
||||
down_box: &MonitorWidget,
|
||||
up_box: &MonitorWidget,
|
||||
hist: &MonitorWidget,
|
||||
usage: &MonitorWidget,
|
||||
ctx: &DrawCtx,
|
||||
target: &mut CtxTarget,
|
||||
styles: &mut StyleManager| {
|
||||
ctx.clear(255, 255, 255, WIN_W, WIN_H);
|
||||
net.draw(target, styles);
|
||||
down_box.draw(target, styles);
|
||||
up_box.draw(target, styles);
|
||||
hist.draw(target, styles);
|
||||
usage.draw(target, styles);
|
||||
ctx.flush();
|
||||
};
|
||||
redraw(
|
||||
&net, &down_box, &up_box, &hist, &usage, &ctx, &mut target, &mut styles,
|
||||
);
|
||||
|
||||
let mut last_tick = Instant::now();
|
||||
loop {
|
||||
match x.conn.poll_for_event()? {
|
||||
Some(ev) => {
|
||||
let mut handled = false;
|
||||
match ev {
|
||||
Event::Expose(_) => {
|
||||
redraw(
|
||||
&net, &down_box, &up_box, &hist, &usage, &ctx, &mut target,
|
||||
&mut styles,
|
||||
);
|
||||
}
|
||||
Event::ButtonPress(ev) => {
|
||||
handled = net.on_button_press(
|
||||
ev.event_x as i32,
|
||||
ev.event_y as i32,
|
||||
ev.detail as u32,
|
||||
) || down_box.on_button_press(
|
||||
ev.event_x as i32,
|
||||
ev.event_y as i32,
|
||||
ev.detail as u32,
|
||||
) || up_box.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,
|
||||
) || usage.on_button_press(
|
||||
ev.event_x as i32,
|
||||
ev.event_y as i32,
|
||||
ev.detail as u32,
|
||||
);
|
||||
}
|
||||
Event::ButtonRelease(ev) => {
|
||||
handled = net.on_button_release(
|
||||
ev.event_x as i32,
|
||||
ev.event_y as i32,
|
||||
ev.detail as u32,
|
||||
) || down_box.on_button_release(
|
||||
ev.event_x as i32,
|
||||
ev.event_y as i32,
|
||||
ev.detail as u32,
|
||||
) || up_box.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,
|
||||
) || usage.on_button_release(
|
||||
ev.event_x as i32,
|
||||
ev.event_y as i32,
|
||||
ev.detail as u32,
|
||||
);
|
||||
}
|
||||
Event::MotionNotify(ev) => {
|
||||
handled = net.on_motion(ev.event_x as i32, ev.event_y as i32)
|
||||
|| down_box.on_motion(ev.event_x as i32, ev.event_y as i32)
|
||||
|| up_box.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)
|
||||
|| usage.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
|
||||
};
|
||||
handled = net.on_key(
|
||||
xframe_widgets::Key::from_keysym(keysym, text),
|
||||
text,
|
||||
) || down_box.on_key(
|
||||
xframe_widgets::Key::from_keysym(keysym, text),
|
||||
text,
|
||||
) || up_box.on_key(
|
||||
xframe_widgets::Key::from_keysym(keysym, text),
|
||||
text,
|
||||
) || hist.on_key(
|
||||
xframe_widgets::Key::from_keysym(keysym, text),
|
||||
text,
|
||||
) || usage.on_key(
|
||||
xframe_widgets::Key::from_keysym(keysym, text),
|
||||
text,
|
||||
);
|
||||
}
|
||||
Event::ClientMessage(ev)
|
||||
if ev.type_ == x.wm_protocols
|
||||
&& ev.data.as_data32()[0] == x.wm_delete =>
|
||||
{
|
||||
break;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
if handled {
|
||||
redraw(
|
||||
&net, &down_box, &up_box, &hist, &usage, &ctx, &mut target,
|
||||
&mut styles,
|
||||
);
|
||||
}
|
||||
}
|
||||
None => {
|
||||
thread::sleep(Duration::from_millis(10));
|
||||
}
|
||||
}
|
||||
// Live tick every 500 ms.
|
||||
if last_tick.elapsed() >= Duration::from_millis(500) {
|
||||
last_tick = Instant::now();
|
||||
let now = Instant::now();
|
||||
if let Some((rx, tx)) = read_counters(&iface) {
|
||||
let dt = now.duration_since(prev_time).as_secs_f64();
|
||||
prev_time = now;
|
||||
if dt > 0.0 {
|
||||
down_bps = if rx >= prev_rx {
|
||||
(rx - prev_rx) as f64 / dt
|
||||
} else {
|
||||
0.0
|
||||
};
|
||||
up_bps = if tx >= prev_tx {
|
||||
(tx - prev_tx) as f64 / dt
|
||||
} else {
|
||||
0.0
|
||||
};
|
||||
prev_rx = rx;
|
||||
prev_tx = tx;
|
||||
peak_down = peak_down.max(down_bps / 1024.0 * 1.15);
|
||||
peak_up = peak_up.max(up_bps / 1024.0 * 1.15);
|
||||
push_sample(
|
||||
&mut net,
|
||||
&mut down_box,
|
||||
&mut up_box,
|
||||
&mut hist,
|
||||
&mut usage,
|
||||
down_bps,
|
||||
up_bps,
|
||||
dt,
|
||||
peak_down,
|
||||
peak_up,
|
||||
link_bps,
|
||||
);
|
||||
redraw(
|
||||
&net, &down_box, &up_box, &hist, &usage, &ctx, &mut target,
|
||||
&mut styles,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn main() -> ExitCode {
|
||||
match run() {
|
||||
Ok(()) => ExitCode::SUCCESS,
|
||||
Err(e) => {
|
||||
eprintln!("monitor_network_monitor: {}", e);
|
||||
ExitCode::from(1)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
After Width: | Height: | Size: 7.2 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/).
|
||||
|
After Width: | Height: | Size: 4.7 KiB |
@@ -0,0 +1,52 @@
|
||||
# Service Dashboard — monitor app (Rust)
|
||||
|
||||
A service/port dashboard in one window (1024×768): a single
|
||||
`MonitorWidget` (`XMonitorGrid`) of illuminator buttons for the
|
||||
services that actually run on this host (hot_dallas). Each button
|
||||
polls its live check every 2 seconds and glows green when up, red
|
||||
when down, dim when unknown. Click a button to re-check it now.
|
||||
|
||||
## What it monitors
|
||||
|
||||
| Button | Kind | Check |
|
||||
| --- | --- | --- |
|
||||
| SSH :22 | Port | TCP connect to localhost:22 |
|
||||
| HTTP :80 | Port | TCP connect to localhost:80 (nginx) |
|
||||
| HTTPS :443 | Port | TCP connect to localhost:443 (nginx) |
|
||||
| NPM admin :81 | Port | TCP connect to localhost:81 |
|
||||
| ThinkMelt :2368 | Port | TCP connect to localhost:2368 |
|
||||
| Ghost :5000 | Port | TCP connect to localhost:5000 |
|
||||
| lightgui.com :5009 | Port | TCP connect to localhost:5009 |
|
||||
| Traffic stats :7888 | Port | TCP connect to localhost:7888 (GoAccess) |
|
||||
| dockerd | Process | `/proc/<pid>/comm` == `dockerd` |
|
||||
| containerd | Process | `/proc/<pid>/comm` == `containerd` |
|
||||
| docker.service | Unit | `systemctl is-active docker.service` == `active` |
|
||||
| ssh.service | Unit | `systemctl is-active ssh.service` == `active` |
|
||||
|
||||
No mock or static data: every cell is a live `MonitorButtonState`
|
||||
check (`poll_all()` on a 2 s timer).
|
||||
|
||||
## Widgets used
|
||||
|
||||
- `XMonitorGrid` (`MonitorWidget`) — the panel; one shared
|
||||
`poll_all()` timer.
|
||||
- `XMonitorButton` (`MonitorButtonState`) — one cell per service
|
||||
(kinds `TcpPort` / `Process` / `Unit`).
|
||||
|
||||
## Build and run
|
||||
|
||||
```sh
|
||||
# from the lightgui_rust checkout
|
||||
cargo run -p xframe-demo --example monitor_service_dashboard
|
||||
```
|
||||
|
||||
Close the window (or press Esc / `q`) to quit.
|
||||
|
||||
## Source
|
||||
|
||||
- Rust: `crates/xframe-demo/examples/monitor_service_dashboard/main.rs`
|
||||
in [lightgui_rust](https://github.com/cnmcdee/lightgui_rust)
|
||||
- C++: `examples/monitor/service-dashboard/main.cpp` in
|
||||
[lightgui](https://github.com/cnmcdee/lightgui)
|
||||
- Python: `examples/monitor_service_dashboard/main.py` in
|
||||
[lightgui_python](https://github.com/cnmcdee/lightgui_python)
|
||||
@@ -0,0 +1,171 @@
|
||||
//! Service Dashboard — monitor app.
|
||||
//!
|
||||
//! One 1024x768 window holding a single `XMonitorGrid` of illuminator
|
||||
//! buttons for the services that actually run on this host
|
||||
//! (hot_dallas): TCP ports (sshd, nginx, NPM, ThinkMelt, Ghost blogs,
|
||||
//! traffic stats), processes (dockerd, containerd) and systemd units
|
||||
//! (docker.service, ssh.service). Every cell is a live
|
||||
//! `MonitorButtonState` check, re-polled on a shared 2 s timer; green
|
||||
//! when up, red when down. Click a cell to re-check it now.
|
||||
//!
|
||||
//! Run from the workspace root:
|
||||
//! cargo run -p xframe-demo --example monitor_service_dashboard
|
||||
//! Close the window (or press Esc / `q`) to quit.
|
||||
|
||||
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::{Key, MonitorButtonState, MonitorTarget, MonitorWidget, Widget};
|
||||
|
||||
const WIN_W: u16 = 1024;
|
||||
const WIN_H: u16 = 768;
|
||||
const KEY_ESCAPE: u32 = 0xff1b;
|
||||
|
||||
/// (label, target) for every real service on this host.
|
||||
fn services() -> Vec<(&'static str, MonitorTarget)> {
|
||||
vec![
|
||||
("SSH :22", MonitorTarget::TcpPort(22)),
|
||||
("HTTP :80", MonitorTarget::TcpPort(80)),
|
||||
("HTTPS :443", MonitorTarget::TcpPort(443)),
|
||||
("NPM admin :81", MonitorTarget::TcpPort(81)),
|
||||
("ThinkMelt :2368", MonitorTarget::TcpPort(2368)),
|
||||
("Ghost :5000", MonitorTarget::TcpPort(5000)),
|
||||
("lightgui.com :5009", MonitorTarget::TcpPort(5009)),
|
||||
("Traffic stats :7888", MonitorTarget::TcpPort(7888)),
|
||||
("dockerd", MonitorTarget::Process("dockerd".to_string())),
|
||||
("containerd", MonitorTarget::Process("containerd".to_string())),
|
||||
("docker.service", MonitorTarget::Unit("docker.service".to_string())),
|
||||
("ssh.service", MonitorTarget::Unit("ssh.service".to_string())),
|
||||
]
|
||||
}
|
||||
|
||||
fn main() -> ExitCode {
|
||||
match run() {
|
||||
Ok(code) => ExitCode::from(code as u8),
|
||||
Err(e) => {
|
||||
eprintln!("monitor_service_dashboard: {}", 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 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,
|
||||
"Service Dashboard - monitor",
|
||||
event_mask,
|
||||
)?;
|
||||
|
||||
let mut styles = StyleManager::new();
|
||||
xframe_demo::register_styles(&mut styles);
|
||||
|
||||
// The grid constructor seeds demo monitors (incl. docker :2375,
|
||||
// which is not a listening port here); replace them with the
|
||||
// services that actually run on this host, then poll live.
|
||||
let mut grid = MonitorWidget::new("Service Dashboard", "MonitorGrid", 16, 16, 992, 736);
|
||||
let services = services();
|
||||
grid.buttons = services
|
||||
.iter()
|
||||
.map(|(label, target)| MonitorButtonState::new(label, target.clone()))
|
||||
.collect();
|
||||
grid.poll_all();
|
||||
|
||||
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_service_dashboard: warning: no font resolved, labels will be blank");
|
||||
}
|
||||
|
||||
let redraw = |grid: &MonitorWidget,
|
||||
ctx: &DrawCtx,
|
||||
target: &mut CtxTarget,
|
||||
styles: &mut StyleManager| {
|
||||
ctx.clear(255, 255, 255, WIN_W, WIN_H);
|
||||
grid.draw(target, styles);
|
||||
ctx.flush();
|
||||
};
|
||||
redraw(&grid, &ctx, &mut target, &mut styles);
|
||||
|
||||
let mut last_poll = Instant::now();
|
||||
loop {
|
||||
// 2 s shared poll timer, checked on every loop pass.
|
||||
if last_poll.elapsed() >= Duration::from_secs(2) {
|
||||
last_poll = Instant::now();
|
||||
grid.poll_all();
|
||||
redraw(&grid, &ctx, &mut target, &mut styles);
|
||||
}
|
||||
let ev = match x.conn.poll_for_event()? {
|
||||
Some(ev) => ev,
|
||||
None => {
|
||||
std::thread::sleep(Duration::from_millis(10));
|
||||
continue;
|
||||
}
|
||||
};
|
||||
let mut handled = false;
|
||||
match ev {
|
||||
Event::Expose(_) => {
|
||||
redraw(&grid, &ctx, &mut target, &mut styles);
|
||||
}
|
||||
Event::ButtonPress(ev) => {
|
||||
handled = grid.on_button_press(
|
||||
ev.event_x as i32,
|
||||
ev.event_y as i32,
|
||||
ev.detail as u32,
|
||||
);
|
||||
}
|
||||
Event::ButtonRelease(ev) => {
|
||||
handled = grid.on_button_release(
|
||||
ev.event_x as i32,
|
||||
ev.event_y as i32,
|
||||
ev.detail as u32,
|
||||
);
|
||||
}
|
||||
Event::MotionNotify(ev) => {
|
||||
handled = grid.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
|
||||
};
|
||||
handled = grid.on_key(Key::from_keysym(keysym, text), text);
|
||||
}
|
||||
Event::ClientMessage(ev)
|
||||
if ev.type_ == x.wm_protocols && ev.data.as_data32()[0] == x.wm_delete =>
|
||||
{
|
||||
break;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
if handled {
|
||||
redraw(&grid, &ctx, &mut target, &mut styles);
|
||||
}
|
||||
}
|
||||
Ok(0)
|
||||
}
|
||||
|
After Width: | Height: | Size: 4.8 KiB |
@@ -0,0 +1,44 @@
|
||||
# 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).
|
||||
@@ -0,0 +1,473 @@
|
||||
//! 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)
|
||||
}
|
||||
|
After Width: | Height: | Size: 11 KiB |
|
After Width: | Height: | Size: 4.8 KiB |
@@ -0,0 +1,38 @@
|
||||
# Temperature Monitor — monitor (Rust)
|
||||
|
||||
A btop-style temperature monitor in one 1024x768 window, built only
|
||||
from LightGUI XFrame monitor widgets:
|
||||
|
||||
- **XTempHistory** — temperature history of the first thermal zone,
|
||||
with an 80 °C threshold line (readings above it draw red)
|
||||
|
||||
Live data comes from `/sys/class/thermal/thermal_zone*/temp` and
|
||||
`/sys/class/hwmon/hwmon*/temp*_input`, re-scanned every 2 s. On a
|
||||
machine with sensors the history fills with live readings; on this
|
||||
machine (hot_dallas, a VPS with no thermal sensors at all — only
|
||||
cooling devices under `/sys/class/thermal/`, no `thermal_zone*/temp`
|
||||
files, an empty `/sys/class/hwmon/`) the app shows the widget's
|
||||
honest empty state: an empty graph, "no data" in the legend, and a
|
||||
title that says no thermal zones were found. No mock or demo
|
||||
temperatures: the seeded demo series is dropped at startup with
|
||||
`MonitorWidget::clear()`.
|
||||
|
||||
## Run
|
||||
|
||||
```sh
|
||||
cargo run -p xframe-demo --example monitor_temperature_monitor
|
||||
```
|
||||
|
||||
Pass a hold time in seconds to exit on its own (screenshots):
|
||||
|
||||
```sh
|
||||
cargo run -p xframe-demo --example monitor_temperature_monitor -- 8
|
||||
```
|
||||
|
||||
Esc, `q`, or closing the window quits.
|
||||
|
||||
## Source
|
||||
|
||||
- App: `crates/xframe-demo/examples/monitor_temperature_monitor/main.rs`
|
||||
- Widget: `crates/xframe-widgets/src/monitor.rs`
|
||||
- Repo: https://github.com/cnmcdee/lightgui_rust
|
||||
@@ -0,0 +1,290 @@
|
||||
//! Temperature Monitor — monitor (Rust).
|
||||
//!
|
||||
//! A btop-style temperature monitor in one 1024x768 window, built
|
||||
//! only from LightGUI XFrame monitor widgets (`XTempHistory`):
|
||||
//! the first thermal zone's temperature history with an 80 °C
|
||||
//! threshold line, re-scanned every 2 s from
|
||||
//! `/sys/class/thermal/thermal_zone*/temp` and
|
||||
//! `/sys/class/hwmon/hwmon*/temp*_input`.
|
||||
//!
|
||||
//! On this machine (hot_dallas, a VPS) there are NO thermal sensors
|
||||
//! at all: `/sys/class/thermal/` holds only cooling devices, there
|
||||
//! are no `thermal_zone*/temp` files, `/sys/class/hwmon/` is empty
|
||||
//! and `sensors` is not installed. So the app shows the widget's
|
||||
//! honest empty state ("no data", no line, no fake 0.0 °C reading)
|
||||
//! and says so in the title. No mock or demo temperatures, ever:
|
||||
//! the seeded demo series is dropped at startup with
|
||||
//! `MonitorWidget::clear()`. If sensors ever appear (e.g. on a
|
||||
//! machine that has them) the rescan picks them up and the history
|
||||
//! starts filling with live readings.
|
||||
//!
|
||||
//! Run it from the workspace root:
|
||||
//! cargo run -p xframe-demo --example monitor_temperature_monitor
|
||||
//! Pass a hold time in seconds to exit on its own (screenshots):
|
||||
//! cargo run -p xframe-demo --example monitor_temperature_monitor -- 8
|
||||
//! Esc / `q` / window-close quits.
|
||||
|
||||
use std::fs;
|
||||
use std::path::{Path, PathBuf};
|
||||
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::{MonitorWidget, Widget};
|
||||
|
||||
const WIN_W: u16 = 1024;
|
||||
const WIN_H: u16 = 768;
|
||||
const KEY_ESCAPE: u32 = 0xff1b;
|
||||
const NO_ZONES_TITLE: &str = "Temperature history -- no thermal zones found";
|
||||
|
||||
/// One temperature input the kernel exposes.
|
||||
struct Zone {
|
||||
name: String,
|
||||
path: PathBuf,
|
||||
}
|
||||
|
||||
fn read_first_line(path: &Path) -> Option<String> {
|
||||
fs::read_to_string(path)
|
||||
.ok()?
|
||||
.lines()
|
||||
.next()
|
||||
.map(|s| s.trim().to_string())
|
||||
}
|
||||
|
||||
fn read_temp_c(path: &Path) -> Option<f64> {
|
||||
read_first_line(path)?.parse::<f64>().ok().map(|m| m / 1000.0)
|
||||
}
|
||||
|
||||
/// All temperature inputs the kernel exposes, thermal zones first.
|
||||
fn scan_zones() -> Vec<Zone> {
|
||||
let mut zones = Vec::new();
|
||||
if let Ok(thermal) = fs::read_dir("/sys/class/thermal") {
|
||||
for ent in thermal.flatten() {
|
||||
let name = ent.file_name().to_string_lossy().into_owned();
|
||||
if !name.starts_with("thermal_zone") {
|
||||
continue;
|
||||
}
|
||||
let base = ent.path();
|
||||
let temp_path = base.join("temp");
|
||||
if read_temp_c(&temp_path).is_none() {
|
||||
continue;
|
||||
}
|
||||
let label = read_first_line(&base.join("type")).unwrap_or(name.clone());
|
||||
zones.push(Zone {
|
||||
name: if label.is_empty() { name } else { label },
|
||||
path: temp_path,
|
||||
});
|
||||
}
|
||||
}
|
||||
if let Ok(hwmon) = fs::read_dir("/sys/class/hwmon") {
|
||||
for ent in hwmon.flatten() {
|
||||
let name = ent.file_name().to_string_lossy().into_owned();
|
||||
if !name.starts_with("hwmon") {
|
||||
continue;
|
||||
}
|
||||
let base = ent.path();
|
||||
let chip = read_first_line(&base.join("name")).unwrap_or(name.clone());
|
||||
let chip = if chip.is_empty() { name } else { chip };
|
||||
if let Ok(dir) = fs::read_dir(&base) {
|
||||
for f in dir.flatten() {
|
||||
let fname = f.file_name().to_string_lossy().into_owned();
|
||||
if !fname.starts_with("temp") || !fname.ends_with("_input") {
|
||||
continue;
|
||||
}
|
||||
let temp_path = f.path();
|
||||
if read_temp_c(&temp_path).is_none() {
|
||||
continue;
|
||||
}
|
||||
let stem = fname.trim_end_matches("_input");
|
||||
let label = read_first_line(&base.join(format!("{}_label", stem)))
|
||||
.unwrap_or_default();
|
||||
zones.push(Zone {
|
||||
name: if label.is_empty() {
|
||||
chip.clone()
|
||||
} else {
|
||||
format!("{} {}", chip, label)
|
||||
},
|
||||
path: temp_path,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
zones
|
||||
}
|
||||
|
||||
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_temperature_monitor: {}", e);
|
||||
return ExitCode::from(1);
|
||||
}
|
||||
};
|
||||
let font = match x.open_font(&[FONT_DEFAULT, "fixed"]) {
|
||||
Ok(f) => f,
|
||||
Err(e) => {
|
||||
eprintln!("monitor_temperature_monitor: {}", e);
|
||||
return ExitCode::from(1);
|
||||
}
|
||||
};
|
||||
let title = "Temperature 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) = match x.create_window(100, 100, WIN_W, WIN_H, title, event_mask) {
|
||||
Ok(v) => v,
|
||||
Err(e) => {
|
||||
eprintln!("monitor_temperature_monitor: {}", e);
|
||||
return ExitCode::from(1);
|
||||
}
|
||||
};
|
||||
|
||||
let mut styles = StyleManager::new();
|
||||
xframe_demo::register_styles(&mut styles);
|
||||
|
||||
let mut temp = MonitorWidget::new(NO_ZONES_TITLE, "TempHistory", 16, 16, 992, 736);
|
||||
temp.set_text(NO_ZONES_TITLE);
|
||||
temp.threshold = 80.0;
|
||||
// Drop the seeded demo series: with no live source the honest
|
||||
// state is an empty graph, not a fake warm-up curve.
|
||||
temp.clear();
|
||||
|
||||
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_temperature_monitor: warning: no font resolved, labels will be blank");
|
||||
}
|
||||
|
||||
let redraw = |temp: &MonitorWidget,
|
||||
ctx: &DrawCtx,
|
||||
target: &mut CtxTarget,
|
||||
styles: &mut StyleManager| {
|
||||
ctx.clear(255, 255, 255, WIN_W, WIN_H);
|
||||
temp.draw(target, styles);
|
||||
ctx.flush();
|
||||
};
|
||||
|
||||
// First scan before the first paint, so the title already tells
|
||||
// the truth on screen one.
|
||||
let mut zones = scan_zones();
|
||||
let mut had_zones = false;
|
||||
if let Some(z) = zones.first() {
|
||||
had_zones = true;
|
||||
let t = format!("Temperature history -- {}", z.name);
|
||||
temp.state.name = t.clone();
|
||||
temp.set_text(&t);
|
||||
if let Some(v) = read_temp_c(&z.path) {
|
||||
temp.push_value(v);
|
||||
}
|
||||
}
|
||||
redraw(&temp, &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(&temp, &ctx, &mut target, &mut styles);
|
||||
}
|
||||
Event::ButtonPress(ev) => {
|
||||
handled = temp.on_button_press(
|
||||
ev.event_x as i32,
|
||||
ev.event_y as i32,
|
||||
ev.detail as u32,
|
||||
);
|
||||
}
|
||||
Event::ButtonRelease(ev) => {
|
||||
handled = temp.on_button_release(
|
||||
ev.event_x as i32,
|
||||
ev.event_y as i32,
|
||||
ev.detail as u32,
|
||||
);
|
||||
}
|
||||
Event::MotionNotify(ev) => {
|
||||
handled = temp.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 = temp.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(&temp, &ctx, &mut target, &mut styles);
|
||||
}
|
||||
}
|
||||
Ok(None) => {
|
||||
std::thread::sleep(Duration::from_millis(10));
|
||||
}
|
||||
Err(e) => {
|
||||
eprintln!("monitor_temperature_monitor: {}", e);
|
||||
return ExitCode::from(1);
|
||||
}
|
||||
}
|
||||
// 2 s tick: re-scan sysfs (sensors can appear on other
|
||||
// machines) and push the first zone's live reading.
|
||||
if last_tick.elapsed() >= Duration::from_secs(2) {
|
||||
last_tick = Instant::now();
|
||||
zones = scan_zones();
|
||||
if zones.is_empty() {
|
||||
if had_zones {
|
||||
had_zones = false;
|
||||
temp.clear();
|
||||
temp.state.name = NO_ZONES_TITLE.to_string();
|
||||
temp.set_text(NO_ZONES_TITLE);
|
||||
}
|
||||
} else if let Some(z) = zones.first() {
|
||||
if !had_zones {
|
||||
had_zones = true;
|
||||
let t = format!("Temperature history -- {}", z.name);
|
||||
temp.state.name = t.clone();
|
||||
temp.set_text(&t);
|
||||
}
|
||||
if let Some(v) = read_temp_c(&z.path) {
|
||||
temp.push_value(v);
|
||||
}
|
||||
}
|
||||
redraw(&temp, &ctx, &mut target, &mut styles);
|
||||
}
|
||||
}
|
||||
ExitCode::from(0)
|
||||
}
|
||||
|
After Width: | Height: | Size: 2.1 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(),
|
||||
@@ -658,6 +662,18 @@ impl MonitorWidget {
|
||||
self.push_sample(0, v);
|
||||
}
|
||||
|
||||
/// Drop every sample from every history series (and reset the
|
||||
/// peak hold), keeping the series slots: a host app that found
|
||||
/// no live data yet shows the widget's honest empty state
|
||||
/// ("no data") instead of the seeded demo series. Later
|
||||
/// push_* calls fill the kept slots again as usual.
|
||||
pub fn clear(&mut self) {
|
||||
for s in &mut self.series {
|
||||
s.values.clear();
|
||||
}
|
||||
self.peak = f64::NEG_INFINITY;
|
||||
}
|
||||
|
||||
// -- stack bar -----------------------------------------------------------
|
||||
|
||||
pub fn set_segments(&mut self, segments: Vec<Segment>) {
|
||||
@@ -675,12 +691,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);
|
||||
@@ -1051,11 +1100,22 @@ impl MonitorWidget {
|
||||
// under-measures the ° glyph and the label clips at the border.
|
||||
let tlabel = format!("{:.0}°C limit", self.threshold);
|
||||
draw_text_colored(target, style, plot.x + 4, ty - 2, &tlabel, RED);
|
||||
// Current value, red when over the threshold.
|
||||
let cur = self.series.first().map(|s| s.last()).unwrap_or(0.0);
|
||||
let col = if cur > self.threshold { RED } else { INK };
|
||||
let line = format!("now {:.1}°C threshold {:.0}°C", cur, self.threshold);
|
||||
draw_text_colored(target, style, b.x + 6, b.y + b.h - 8, &line, col);
|
||||
// Current value, red when over the threshold. Empty (no
|
||||
// samples pushed, e.g. no thermal zones found): say so
|
||||
// honestly instead of a 0.0 °C reading that never happened.
|
||||
let has_data = self
|
||||
.series
|
||||
.first()
|
||||
.map(|s| !s.values.is_empty())
|
||||
.unwrap_or(false);
|
||||
if has_data {
|
||||
let cur = self.series.first().map(|s| s.last()).unwrap_or(0.0);
|
||||
let col = if cur > self.threshold { RED } else { INK };
|
||||
let line = format!("now {:.1}°C threshold {:.0}°C", cur, self.threshold);
|
||||
draw_text_colored(target, style, b.x + 6, b.y + b.h - 8, &line, col);
|
||||
} else {
|
||||
draw_text_colored(target, style, b.x + 6, b.y + b.h - 8, "no data", INK);
|
||||
}
|
||||
}
|
||||
|
||||
fn draw_usage_bar(&self, target: &mut dyn DrawTarget, style: &Style) {
|
||||
@@ -1348,14 +1408,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 + 52;
|
||||
let x_name = x_pid + 64;
|
||||
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 { " ▼" } else { " ▲" });
|
||||
text.push_str(if self.sort_desc { " v" } else { " ^" });
|
||||
}
|
||||
draw_text_at(target, style, x, y + 11, &text);
|
||||
}
|
||||
@@ -1579,7 +1639,7 @@ monitor_impl!(
|
||||
let hy = b.y + 20;
|
||||
if y < hy + 17 {
|
||||
let x_pid = b.x + 6;
|
||||
let x_name = x_pid + 52;
|
||||
let x_name = x_pid + 64;
|
||||
let x_cpu = b.x + b.w - 170;
|
||||
let x_mem = b.x + b.w - 66;
|
||||
let col = if x < x_name {
|
||||
@@ -1809,6 +1869,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
|
||||
@@ -1847,6 +1930,19 @@ mod tests {
|
||||
assert!(m.over_temp());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn temp_clear_drops_demo_series() {
|
||||
let mut m = MonitorWidget::new("TempHistory", "TempHistory", 0, 0, 320, 200);
|
||||
assert!(!m.series.is_empty());
|
||||
assert!(!m.series[0].values.is_empty()); // seeded demo
|
||||
m.clear();
|
||||
assert!(m.series[0].values.is_empty());
|
||||
assert!(!m.over_temp());
|
||||
// A later live sample still lands in the kept series slot.
|
||||
m.push_value(42.0);
|
||||
assert_eq!(m.series[0].last(), 42.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn monitor_grid_polls_all_buttons() {
|
||||
let m = MonitorWidget::new("MonitorGrid", "MonitorGrid", 0, 0, 420, 200);
|
||||
|
||||