Compare commits
5
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
52035bf3fb | ||
|
|
cd818f9a23 | ||
|
|
7feeac848d | ||
|
|
7995eac6ac | ||
|
|
77d9446d2a |
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",
|
||||
|
||||
@@ -64,6 +64,19 @@ impl DrawTarget for CtxTarget<'_> {
|
||||
|
||||
fn set_font(&mut self, metrics: FontMetrics) {
|
||||
self.font_metrics = Some(metrics);
|
||||
// Rebind the regular font: a scaled draw may have left a
|
||||
// different font in the GC.
|
||||
self.ctx.bind_font();
|
||||
}
|
||||
|
||||
fn set_scaled_font(&mut self, px: i32, bold: bool) -> bool {
|
||||
match self.ctx.bind_scaled_font(px, bold) {
|
||||
Some(metrics) => {
|
||||
self.font_metrics = Some(metrics);
|
||||
true
|
||||
}
|
||||
None => false,
|
||||
}
|
||||
}
|
||||
|
||||
fn fill_rect(&mut self, x: i32, y: i32, w: i32, h: i32) {
|
||||
|
||||
@@ -8,6 +8,7 @@ use x11rb::connection::Connection;
|
||||
use x11rb::protocol::xproto::*;
|
||||
use x11rb::rust_connection::RustConnection;
|
||||
use x11rb::COPY_FROM_PARENT;
|
||||
use xframe_core::font::FontMetrics;
|
||||
|
||||
pub type Conn = RustConnection;
|
||||
|
||||
@@ -555,6 +556,13 @@ pub struct DrawCtx<'a> {
|
||||
pub gc: Gcontext,
|
||||
pub font: Font,
|
||||
colors: RefCell<HashMap<(u8, u8, u8), u32>>,
|
||||
/// Scaled fonts opened by `bind_scaled_font`, keyed by
|
||||
/// (pixel size, bold). Process-lifetime, like the C++ cache.
|
||||
scaled_fonts: RefCell<HashMap<(i32, bool), (Font, FontMetrics)>>,
|
||||
/// The font currently bound into the GC (starts as `font`).
|
||||
/// `text_width` measures with this font, so it stays correct
|
||||
/// after a scaled draw.
|
||||
current_font: RefCell<Font>,
|
||||
}
|
||||
|
||||
impl<'a> DrawCtx<'a> {
|
||||
@@ -565,6 +573,8 @@ impl<'a> DrawCtx<'a> {
|
||||
gc,
|
||||
font,
|
||||
colors: RefCell::new(HashMap::new()),
|
||||
scaled_fonts: RefCell::new(HashMap::new()),
|
||||
current_font: RefCell::new(font),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -731,7 +741,7 @@ impl<'a> DrawCtx<'a> {
|
||||
}
|
||||
|
||||
pub fn text_width(&self, text: &str) -> i32 {
|
||||
self.x.text_width(self.font, text)
|
||||
self.x.text_width(*self.current_font.borrow(), text)
|
||||
}
|
||||
|
||||
/// Draw text with the GC font; the GC font must be set by the caller
|
||||
@@ -771,6 +781,74 @@ impl<'a> DrawCtx<'a> {
|
||||
.x
|
||||
.conn
|
||||
.change_gc(self.gc, &ChangeGCAux::new().font(self.font));
|
||||
*self.current_font.borrow_mut() = self.font;
|
||||
}
|
||||
|
||||
/// Bind a scaled font (`px` pixels, bold when `bold`) into the GC
|
||||
/// and return its metrics. The misc-fixed XLFD is scalable, so the
|
||||
/// requested size loads exactly; bitmap fallbacks (the only sizes
|
||||
/// the server has: bold 13/14/15/18/20, medium 13/18/20) and
|
||||
/// `fixed` cover a server without the scalable face. Results are
|
||||
/// cached per (px, bold). `None` when nothing loads, in which case
|
||||
/// the previously bound font stays active.
|
||||
pub fn bind_scaled_font(&self, px: i32, bold: bool) -> Option<FontMetrics> {
|
||||
if let Some(&(font, metrics)) =
|
||||
self.scaled_fonts.borrow().get(&(px, bold))
|
||||
{
|
||||
let _ = self
|
||||
.x
|
||||
.conn
|
||||
.change_gc(self.gc, &ChangeGCAux::new().font(font));
|
||||
*self.current_font.borrow_mut() = font;
|
||||
return Some(metrics);
|
||||
}
|
||||
let weight = if bold { "bold" } else { "medium" };
|
||||
let mut candidates: Vec<String> = vec![format!(
|
||||
"-misc-fixed-{weight}-r-normal--{px}-*-75-75-c-*-iso8859-1"
|
||||
)];
|
||||
let bitmaps: &[i32] = if bold {
|
||||
&[18, 20, 15, 14, 13]
|
||||
} else {
|
||||
&[20, 18, 13]
|
||||
};
|
||||
for size in bitmaps {
|
||||
candidates.push(format!(
|
||||
"-misc-fixed-{weight}-r-normal--{size}-120-100-100-c-60-iso8859-1"
|
||||
));
|
||||
}
|
||||
candidates.push("fixed".to_string());
|
||||
for name in &candidates {
|
||||
let Ok(fid) = self.x.conn.generate_id() else {
|
||||
continue;
|
||||
};
|
||||
let Ok(cookie) = self.x.conn.open_font(fid, name.as_bytes()) else {
|
||||
continue;
|
||||
};
|
||||
if cookie.check().is_err() {
|
||||
continue;
|
||||
}
|
||||
let Ok(reply) = self.x.conn.query_font(fid) else {
|
||||
continue;
|
||||
};
|
||||
let Ok(reply) = reply.reply() else {
|
||||
continue;
|
||||
};
|
||||
let metrics = FontMetrics {
|
||||
ascent: reply.font_ascent as i32,
|
||||
descent: reply.font_descent as i32,
|
||||
char_width: reply.max_bounds.character_width as i32,
|
||||
};
|
||||
let _ = self
|
||||
.x
|
||||
.conn
|
||||
.change_gc(self.gc, &ChangeGCAux::new().font(fid));
|
||||
self.scaled_fonts
|
||||
.borrow_mut()
|
||||
.insert((px, bold), (fid, metrics));
|
||||
*self.current_font.borrow_mut() = fid;
|
||||
return Some(metrics);
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
pub fn put_rgba(&self, dst_x: i16, dst_y: i16, rgba: &[u8], w: u16, h: u16) {
|
||||
|
||||
@@ -21,6 +21,16 @@ pub trait DrawTarget {
|
||||
fn set_line_width(&mut self, width: u32);
|
||||
/// Install a font for subsequent `draw_string` calls.
|
||||
fn set_font(&mut self, metrics: FontMetrics);
|
||||
/// Install a scaled font (pixel size `px`, bold when `bold`) for
|
||||
/// subsequent `draw_string` calls. Returns true when a font at
|
||||
/// (approximately) that size was bound. Default: no-op returning
|
||||
/// false — the caller then draws with the current font (the
|
||||
/// Canvas / test targets have no X server to open fonts on).
|
||||
/// Live targets (CtxTarget) bind a scalable misc-fixed XLFD,
|
||||
/// falling back to the nearest bitmap size.
|
||||
fn set_scaled_font(&mut self, _px: i32, _bold: bool) -> bool {
|
||||
false
|
||||
}
|
||||
/// Fill a rectangle (top-left `x, y`, size `w` x `h`).
|
||||
fn fill_rect(&mut self, x: i32, y: i32, w: i32, h: i32);
|
||||
/// Draw a rectangle outline.
|
||||
@@ -63,6 +73,43 @@ pub fn set_line_width(target: &mut (impl DrawTarget + ?Sized), line_width: i32)
|
||||
target.set_line_width(line_width.max(1) as u32);
|
||||
}
|
||||
|
||||
/// Clamp a font size derived from a widget dimension to `[lo, hi]`
|
||||
/// (sane minimum 11 px so text never shrinks to unreadable).
|
||||
/// Mirrors `xframe::clamp_font_px` in C++ and `_fpx` in Python.
|
||||
pub fn clamp_font_px(value: i32, lo: i32, hi: i32) -> i32 {
|
||||
value.max(lo).min(hi)
|
||||
}
|
||||
|
||||
/// Draw `text` at baseline `(x, y)` in a scaled font (`px`, `bold`),
|
||||
/// falling back to the current font on targets without scaled fonts.
|
||||
/// The caller sets the foreground colour first.
|
||||
pub fn draw_text_scaled(
|
||||
target: &mut (impl DrawTarget + ?Sized),
|
||||
px: i32,
|
||||
bold: bool,
|
||||
x: i32,
|
||||
y: i32,
|
||||
text: &str,
|
||||
) {
|
||||
if text.is_empty() {
|
||||
return;
|
||||
}
|
||||
let _ = target.set_scaled_font(px, bold);
|
||||
target.draw_string(x, y, text);
|
||||
}
|
||||
|
||||
/// Width of `text` in a scaled font (`px`, `bold`), or in the current
|
||||
/// font on targets without scaled fonts.
|
||||
pub fn text_width_scaled(
|
||||
target: &mut (impl DrawTarget + ?Sized),
|
||||
px: i32,
|
||||
bold: bool,
|
||||
text: &str,
|
||||
) -> i32 {
|
||||
let _ = target.set_scaled_font(px, bold);
|
||||
target.text_width(text)
|
||||
}
|
||||
|
||||
/// C++ `xf::fill_rounded_rect`: the Part 4 rounded body — Rectangle A +
|
||||
/// Rectangle B + 4 fill arcs. Degenerate radii fall back to a plain fill.
|
||||
pub fn fill_rounded_rect(
|
||||
|
||||
@@ -14,4 +14,3 @@ xframe-common = { path = "../xframe-common" }
|
||||
xframe-core = { path = "../xframe-core" }
|
||||
xframe-widgets = { path = "../xframe-widgets" }
|
||||
x11rb = "0.13"
|
||||
libc = "0.2"
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
}
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 14 KiB |
@@ -1,204 +0,0 @@
|
||||
//! 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)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,42 +0,0 @@
|
||||
# Process Manager — monitor (Rust)
|
||||
|
||||
A btop-style process manager in one 1024x768 window, built only from
|
||||
LightGUI XFrame widgets: `XProcessList` (live `/proc` table, sortable
|
||||
columns, click a row to select it), `GtkEntry` (filter by name or pid),
|
||||
and three `GtkButton`s — **Terminate**, **Kill**, **Refresh**.
|
||||
|
||||
## What it shows
|
||||
|
||||
- **Processes** — pid, program, CPU% and memory for the live
|
||||
processes on this machine (top 12 by CPU), refreshed every 2 seconds.
|
||||
Click a column header to sort by it (click again to reverse); click a
|
||||
body row to select it (highlighted).
|
||||
- **Filter** — type a name or pid substring; the list re-scans `/proc`
|
||||
and shows only matching rows.
|
||||
- **Terminate** — sends `SIGTERM` to the selected process.
|
||||
- **Kill** — sends `SIGKILL` to the selected process.
|
||||
- **Refresh** — re-scans `/proc` immediately.
|
||||
|
||||
Safety: Terminate/Kill act on the selected row's pid only, and refuse
|
||||
pid ≤ 1 and the manager's own pid.
|
||||
|
||||
## Build and run
|
||||
|
||||
```sh
|
||||
cargo run -p xframe-demo --example monitor_process_manager
|
||||
# Esc or close the window to quit
|
||||
```
|
||||
|
||||
## Source
|
||||
|
||||
- App: `crates/xframe-demo/examples/monitor_process_manager.rs` in
|
||||
[lightgui_rust](https://github.com/cnmcdee/lightgui_rust)
|
||||
- Widgets: `XProcessList` (`MonitorWidget`), `GtkButton`
|
||||
(`ButtonWidget`), `GtkEntry` (`EntryWidget`) — this app adds a
|
||||
name/pid filter to `MonitorWidget` (additive only; the widget demo
|
||||
and `XMonitorGrid` behaviour are unchanged)
|
||||
|
||||
The same app exists in
|
||||
[C](https://github.com/cnmcdee/lightgui) and
|
||||
[Python](https://github.com/cnmcdee/lightgui_python) — see the
|
||||
[walkthrough](https://www.lightgui.com/monitor-process-manager/).
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 4.7 KiB |
@@ -108,9 +108,14 @@ pub fn run_widget_with_csv(
|
||||
};
|
||||
widget.set_bounds(gx as i32, gy as i32, gw as i32, gh as i32);
|
||||
// Label text: the registry `kind` approximates the C++ constructor's
|
||||
// default text (see the module docs of the binary).
|
||||
let kind = widget.kind().to_string();
|
||||
widget.set_text(&kind);
|
||||
// default text (see the module docs of the binary) -- but only when
|
||||
// the widget did not seed its own text (e.g. the monitor demos seed
|
||||
// a value name such as "CPU" / "Disk"; overwriting it with the kind
|
||||
// would show the class name instead of the value name).
|
||||
if widget.state().text.is_empty() {
|
||||
let kind = widget.kind().to_string();
|
||||
widget.set_text(&kind);
|
||||
}
|
||||
if let Some(text) = &csv {
|
||||
if let Err(e) = widget.load_csv_data(text) {
|
||||
eprintln!("xframe-demo: --csv: {}", e);
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
Reference in new issue
Block a user