Compare commits
3
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
460d44c1da | ||
|
|
c121816bb9 | ||
|
|
696579530b |
No files matched your search
Generated
-1
@@ -900,7 +900,6 @@ dependencies = [
|
||||
name = "xframe-demo"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"x11rb",
|
||||
"xframe-common",
|
||||
"xframe-core",
|
||||
|
||||
@@ -14,4 +14,3 @@ xframe-common = { path = "../xframe-common" }
|
||||
xframe-core = { path = "../xframe-core" }
|
||||
xframe-widgets = { path = "../xframe-widgets" }
|
||||
x11rb = "0.13"
|
||||
libc = { workspace = true } # monitor_disk_monitor: statvfs for live mount sizes
|
||||
@@ -1,42 +0,0 @@
|
||||
# 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
|
||||
@@ -1,326 +0,0 @@
|
||||
//! 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)
|
||||
}
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 6.7 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)
|
||||
}
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 11 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 5.2 KiB |
@@ -1650,8 +1650,7 @@ impl MonitorWidget {
|
||||
for (x, label, col) in headers {
|
||||
let mut text = label.to_string();
|
||||
if self.sort_col == col {
|
||||
// Sort indicator, padded >=4 px from the label.
|
||||
text.push_str(if self.sort_desc { " ▼" } else { " ▲" });
|
||||
text.push_str(if self.sort_desc { " v" } else { " ^" });
|
||||
}
|
||||
draw_scaled_at(target, head_px, true, x, y + head_px + 2, &text, INK);
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user