Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
da8e6d4f28 |
No files matched your search
@@ -64,19 +64,6 @@ 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,7 +8,6 @@ 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;
|
||||
|
||||
@@ -556,13 +555,6 @@ 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> {
|
||||
@@ -573,8 +565,6 @@ impl<'a> DrawCtx<'a> {
|
||||
gc,
|
||||
font,
|
||||
colors: RefCell::new(HashMap::new()),
|
||||
scaled_fonts: RefCell::new(HashMap::new()),
|
||||
current_font: RefCell::new(font),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -741,7 +731,7 @@ impl<'a> DrawCtx<'a> {
|
||||
}
|
||||
|
||||
pub fn text_width(&self, text: &str) -> i32 {
|
||||
self.x.text_width(*self.current_font.borrow(), text)
|
||||
self.x.text_width(self.font, text)
|
||||
}
|
||||
|
||||
/// Draw text with the GC font; the GC font must be set by the caller
|
||||
@@ -781,74 +771,6 @@ 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,16 +21,6 @@ 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.
|
||||
@@ -73,43 +63,6 @@ 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(
|
||||
|
||||
@@ -1,35 +0,0 @@
|
||||
# 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
|
||||
@@ -1,316 +0,0 @@
|
||||
//! CPU Dashboard — monitor (Rust).
|
||||
//!
|
||||
//! A btop-style CPU dashboard in one 1024x768 window, built only from
|
||||
//! LightGUI XFrame monitor widgets (`XCoreGrid`, `XTachometer`,
|
||||
//! `XHistoryGraph`, `XLoadBadge`, `XUsageBar`). Live data from
|
||||
//! `/proc/stat` (per-core busy %) and `/proc/loadavg`, sampled every
|
||||
//! 500 ms. The seeded demo series each widget preloads are cleared at
|
||||
//! startup and primed with the first live sample.
|
||||
//!
|
||||
//! Run it from the workspace root:
|
||||
//! cargo run -p xframe-demo --example monitor_cpu_dashboard
|
||||
//! Pass a hold time in seconds to exit on its own (screenshots):
|
||||
//! cargo run -p xframe-demo --example monitor_cpu_dashboard -- 8
|
||||
//! Esc / `q` / window-close quits.
|
||||
|
||||
use std::fs;
|
||||
use std::process::ExitCode;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use x11rb::connection::Connection;
|
||||
use x11rb::protocol::xproto::*;
|
||||
use x11rb::protocol::Event;
|
||||
use xframe_common::style::FONT_DEFAULT;
|
||||
use xframe_common::target::CtxTarget;
|
||||
use xframe_common::x11::{DrawCtx, X11};
|
||||
use xframe_core::StyleManager;
|
||||
use xframe_widgets::monitor::read_loadavg;
|
||||
use xframe_widgets::{MonitorWidget, Widget};
|
||||
|
||||
const WIN_W: u16 = 1024;
|
||||
const WIN_H: u16 = 768;
|
||||
const KEY_ESCAPE: u32 = 0xff1b;
|
||||
|
||||
/// One /proc/stat snapshot: (idle, total) per core, plus the aggregate.
|
||||
struct CpuSnap {
|
||||
cores: Vec<(u64, u64)>,
|
||||
total: (u64, u64),
|
||||
}
|
||||
|
||||
fn read_cpu() -> Option<CpuSnap> {
|
||||
let text = fs::read_to_string("/proc/stat").ok()?;
|
||||
let mut cores: Vec<(u64, u64)> = Vec::new();
|
||||
let mut total = (0u64, 0u64);
|
||||
for line in text.lines() {
|
||||
if !line.starts_with("cpu") {
|
||||
continue;
|
||||
}
|
||||
let rest = &line[3..];
|
||||
let is_total = rest.starts_with(' ');
|
||||
let first = rest.chars().next()?;
|
||||
if !is_total && !first.is_ascii_digit() {
|
||||
continue;
|
||||
}
|
||||
let nums: Vec<u64> = rest
|
||||
.split_whitespace()
|
||||
.filter_map(|t| t.parse::<u64>().ok())
|
||||
.collect();
|
||||
if nums.len() < 4 {
|
||||
continue;
|
||||
}
|
||||
let tot: u64 = nums.iter().sum();
|
||||
let idle = nums[3] + nums.get(4).copied().unwrap_or(0);
|
||||
if is_total {
|
||||
total = (idle, tot);
|
||||
} else {
|
||||
cores.push((idle, tot));
|
||||
}
|
||||
}
|
||||
if cores.is_empty() {
|
||||
return None;
|
||||
}
|
||||
Some(CpuSnap { cores, total })
|
||||
}
|
||||
|
||||
/// Per-core busy % between two snapshots, plus the aggregate busy %.
|
||||
fn busy(prev: &CpuSnap, now: &CpuSnap) -> (Vec<f64>, f64) {
|
||||
let pct = |p: (u64, u64), n: (u64, u64)| -> f64 {
|
||||
let dt = n.1.saturating_sub(p.1);
|
||||
let di = n.0.saturating_sub(p.0);
|
||||
if dt == 0 {
|
||||
return 0.0;
|
||||
}
|
||||
(100.0 * (1.0 - di as f64 / dt as f64)).clamp(0.0, 100.0)
|
||||
};
|
||||
let per_core: Vec<f64> = prev
|
||||
.cores
|
||||
.iter()
|
||||
.zip(now.cores.iter())
|
||||
.map(|(p, n)| pct(*p, *n))
|
||||
.collect();
|
||||
let total = if per_core.is_empty() {
|
||||
0.0
|
||||
} else {
|
||||
per_core.iter().sum::<f64>() / per_core.len() as f64
|
||||
};
|
||||
let _ = pct(prev.total, now.total);
|
||||
(per_core, total)
|
||||
}
|
||||
|
||||
fn main() -> ExitCode {
|
||||
let hold = std::env::args()
|
||||
.nth(1)
|
||||
.and_then(|a| a.parse::<u64>().ok());
|
||||
|
||||
let x = match X11::connect() {
|
||||
Ok(x) => x,
|
||||
Err(e) => {
|
||||
eprintln!("monitor_cpu_dashboard: {}", e);
|
||||
return ExitCode::from(1);
|
||||
}
|
||||
};
|
||||
let font = match x.open_font(&[FONT_DEFAULT, "fixed"]) {
|
||||
Ok(f) => f,
|
||||
Err(e) => {
|
||||
eprintln!("monitor_cpu_dashboard: {}", e);
|
||||
return ExitCode::from(1);
|
||||
}
|
||||
};
|
||||
let title = "CPU Dashboard - monitor";
|
||||
let event_mask = EventMask::EXPOSURE
|
||||
| EventMask::KEY_PRESS
|
||||
| EventMask::STRUCTURE_NOTIFY
|
||||
| EventMask::BUTTON_PRESS
|
||||
| EventMask::BUTTON_RELEASE
|
||||
| EventMask::POINTER_MOTION;
|
||||
let (win, gc) = match x.create_window(100, 100, WIN_W, WIN_H, title, event_mask) {
|
||||
Ok(v) => v,
|
||||
Err(e) => {
|
||||
eprintln!("monitor_cpu_dashboard: {}", e);
|
||||
return ExitCode::from(1);
|
||||
}
|
||||
};
|
||||
|
||||
let mut styles = StyleManager::new();
|
||||
xframe_demo::register_styles(&mut styles);
|
||||
|
||||
let ncores = std::thread::available_parallelism()
|
||||
.map(|n| n.get())
|
||||
.unwrap_or(8)
|
||||
.clamp(1, 16);
|
||||
|
||||
let mut badge = MonitorWidget::new("Load avg", "LoadBadge", 16, 16, 320, 84);
|
||||
badge.set_text("Load avg");
|
||||
|
||||
let mut bar = MonitorWidget::new("Total CPU", "UsageBar", 352, 16, 656, 84);
|
||||
bar.set_text("Total CPU");
|
||||
bar.state.min = 0.0;
|
||||
bar.state.max = 100.0;
|
||||
bar.peak = 0.0;
|
||||
|
||||
let mut grid = MonitorWidget::new("CPU cores", "CoreGrid", 16, 116, 640, 300);
|
||||
grid.set_text("CPU cores");
|
||||
grid.series.clear();
|
||||
for c in 0..ncores {
|
||||
grid.add_series(&format!("CPU{}", c));
|
||||
}
|
||||
|
||||
let mut tacho = MonitorWidget::new("CPU %", "Tachometer", 672, 116, 336, 300);
|
||||
tacho.set_text("CPU %");
|
||||
tacho.state.min = 0.0;
|
||||
tacho.state.max = 100.0;
|
||||
tacho.redline_frac = 0.8;
|
||||
tacho.unit = "%".to_string();
|
||||
tacho.peak = 0.0;
|
||||
|
||||
let mut hist = MonitorWidget::new("Total CPU history", "HistoryGraph", 16, 432, 992, 320);
|
||||
hist.set_text("Total CPU history");
|
||||
hist.series.clear();
|
||||
hist.add_series("CPU %");
|
||||
hist.state.min = 0.0;
|
||||
hist.state.max = 100.0;
|
||||
|
||||
let ctx = DrawCtx::new(&x, win, gc, font);
|
||||
ctx.bind_font();
|
||||
let mut target = CtxTarget::new(&ctx);
|
||||
if !styles.resolve_font("default", &mut target)
|
||||
&& !styles.resolve_font("dark", &mut target)
|
||||
{
|
||||
eprintln!("monitor_cpu_dashboard: warning: no font resolved, labels will be blank");
|
||||
}
|
||||
|
||||
let redraw = |badge: &MonitorWidget,
|
||||
bar: &MonitorWidget,
|
||||
grid: &MonitorWidget,
|
||||
tacho: &MonitorWidget,
|
||||
hist: &MonitorWidget,
|
||||
ctx: &DrawCtx,
|
||||
target: &mut CtxTarget,
|
||||
styles: &mut StyleManager| {
|
||||
ctx.clear(255, 255, 255, WIN_W, WIN_H);
|
||||
badge.draw(target, styles);
|
||||
bar.draw(target, styles);
|
||||
grid.draw(target, styles);
|
||||
tacho.draw(target, styles);
|
||||
hist.draw(target, styles);
|
||||
ctx.flush();
|
||||
};
|
||||
|
||||
// Prime with one live sample so the seeded demo series are gone
|
||||
// before the first paint.
|
||||
let mut prev = read_cpu();
|
||||
if let Some(p) = &prev {
|
||||
std::thread::sleep(Duration::from_millis(100));
|
||||
if let Some(now) = read_cpu() {
|
||||
if now.cores.len() == p.cores.len() {
|
||||
let (per_core, total) = busy(p, &now);
|
||||
for _ in 0..48 {
|
||||
grid.push_samples(&per_core);
|
||||
}
|
||||
for _ in 0..90 {
|
||||
hist.push_value(total);
|
||||
}
|
||||
tacho.set_value_peak(total);
|
||||
tacho.reset_peak();
|
||||
bar.set_value_peak(total);
|
||||
prev = Some(now);
|
||||
}
|
||||
}
|
||||
}
|
||||
redraw(&badge, &bar, &grid, &tacho, &hist, &ctx, &mut target, &mut styles);
|
||||
|
||||
let deadline = hold.map(|s| Instant::now() + Duration::from_secs(s));
|
||||
let mut last_tick = Instant::now();
|
||||
loop {
|
||||
if let Some(d) = deadline {
|
||||
if Instant::now() >= d {
|
||||
break;
|
||||
}
|
||||
}
|
||||
match x.conn.poll_for_event() {
|
||||
Ok(Some(ev)) => {
|
||||
let mut handled = false;
|
||||
match ev {
|
||||
Event::Expose(_) => {
|
||||
redraw(&badge, &bar, &grid, &tacho, &hist, &ctx, &mut target, &mut styles);
|
||||
}
|
||||
Event::ButtonPress(ev) => {
|
||||
handled = badge.on_button_press(ev.event_x as i32, ev.event_y as i32, ev.detail as u32)
|
||||
|| bar.on_button_press(ev.event_x as i32, ev.event_y as i32, ev.detail as u32)
|
||||
|| grid.on_button_press(ev.event_x as i32, ev.event_y as i32, ev.detail as u32)
|
||||
|| tacho.on_button_press(ev.event_x as i32, ev.event_y as i32, ev.detail as u32)
|
||||
|| hist.on_button_press(ev.event_x as i32, ev.event_y as i32, ev.detail as u32);
|
||||
}
|
||||
Event::ButtonRelease(ev) => {
|
||||
handled = badge.on_button_release(ev.event_x as i32, ev.event_y as i32, ev.detail as u32)
|
||||
|| bar.on_button_release(ev.event_x as i32, ev.event_y as i32, ev.detail as u32)
|
||||
|| grid.on_button_release(ev.event_x as i32, ev.event_y as i32, ev.detail as u32)
|
||||
|| tacho.on_button_release(ev.event_x as i32, ev.event_y as i32, ev.detail as u32)
|
||||
|| hist.on_button_release(ev.event_x as i32, ev.event_y as i32, ev.detail as u32);
|
||||
}
|
||||
Event::MotionNotify(ev) => {
|
||||
handled = badge.on_motion(ev.event_x as i32, ev.event_y as i32)
|
||||
|| bar.on_motion(ev.event_x as i32, ev.event_y as i32)
|
||||
|| grid.on_motion(ev.event_x as i32, ev.event_y as i32)
|
||||
|| tacho.on_motion(ev.event_x as i32, ev.event_y as i32)
|
||||
|| hist.on_motion(ev.event_x as i32, ev.event_y as i32);
|
||||
}
|
||||
Event::KeyPress(ev) => {
|
||||
let keysym = x.keysym_for_keycode(ev.detail);
|
||||
if keysym == KEY_ESCAPE || keysym == b'q' as u32 {
|
||||
break;
|
||||
}
|
||||
let text = if (0x20..0x7f).contains(&keysym) {
|
||||
Some(keysym as u8 as char)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let key = xframe_widgets::Key::from_keysym(keysym, text);
|
||||
handled = badge.on_key(key, text)
|
||||
|| bar.on_key(key, text)
|
||||
|| grid.on_key(key, text)
|
||||
|| tacho.on_key(key, text)
|
||||
|| hist.on_key(key, text);
|
||||
}
|
||||
Event::ClientMessage(ev)
|
||||
if ev.type_ == x.wm_protocols && ev.data.as_data32()[0] == x.wm_delete =>
|
||||
{
|
||||
break;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
if handled {
|
||||
redraw(&badge, &bar, &grid, &tacho, &hist, &ctx, &mut target, &mut styles);
|
||||
}
|
||||
}
|
||||
Ok(None) => {
|
||||
std::thread::sleep(Duration::from_millis(10));
|
||||
}
|
||||
Err(e) => {
|
||||
eprintln!("monitor_cpu_dashboard: {}", e);
|
||||
return ExitCode::from(1);
|
||||
}
|
||||
}
|
||||
// 500 ms tick: live sample from /proc/stat + /proc/loadavg.
|
||||
if last_tick.elapsed() >= Duration::from_millis(500) {
|
||||
last_tick = Instant::now();
|
||||
if let Some(p) = &prev {
|
||||
if let Some(now) = read_cpu() {
|
||||
if now.cores.len() == p.cores.len() {
|
||||
let (per_core, total) = busy(p, &now);
|
||||
grid.push_samples(&per_core);
|
||||
hist.push_value(total);
|
||||
tacho.set_value_peak(total);
|
||||
bar.set_value_peak(total);
|
||||
prev = Some(now);
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some((loads, up)) = read_loadavg() {
|
||||
badge.set_loads(loads, up);
|
||||
}
|
||||
redraw(&badge, &bar, &grid, &tacho, &hist, &ctx, &mut target, &mut styles);
|
||||
}
|
||||
}
|
||||
ExitCode::from(0)
|
||||
}
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 14 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)
|
||||
}
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 4.8 KiB |
@@ -108,14 +108,9 @@ 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) -- 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);
|
||||
}
|
||||
// default text (see the module docs of the binary).
|
||||
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