//! Main window: four I/O gauges + per-device breakdown + process table. use std::time::{Duration, Instant}; use eframe::egui::{self, RichText, Vec2}; use vidya::{ apply, body, card, central_page, compact_card, dim_label, grid_cols, grid_cols_with, lead_trail, title, title_2, ColSpec, GridOpts, Theme, }; use crate::gauge::{arc_gauge, heat_color, mini_bar, PeakScale}; use crate::io::{format_bps, format_local_hms, top_reader, top_writer, IoSampler, IoSnapshot}; const SAMPLE_EVERY: Duration = Duration::from_millis(500); /// Gauge fill at/above this of the *previous* scale counts as abnormal. const ABNORMAL_FRAC: f64 = 0.80; /// Ignore tiny rates so idle noise never latches an anomaly. const ABNORMAL_MIN_BPS: f64 = 2.0 * 1024.0 * 1024.0; // 2 MiB/s /// Cap list length so the gauge card stays usable (never auto-expired). const ANOMALY_MAX: usize = 32; /// One process that drove an abnormal disk gauge reading. #[derive(Debug, Clone)] struct AnomalyHit { proc_name: String, rate_bps: f64, stamp: String, at: Instant, } pub struct UsageApp { sampler: IoSampler, snap: IoSnapshot, last_sample: Instant, disk_read_scale: PeakScale, disk_write_scale: PeakScale, net_rx_scale: PeakScale, net_tx_scale: PeakScale, /// History of abnormal Disk Read attributions (newest last). disk_read_anomalies: Vec, /// History of abnormal Disk Write attributions (newest last). disk_write_anomalies: Vec, } impl UsageApp { pub fn new(cc: &eframe::CreationContext<'_>) -> Self { let theme = Theme::dark(); apply(&cc.egui_ctx, &theme); let mut sampler = IoSampler::new(); // Prime so the second sample yields real rates quickly. let _ = sampler.sample(); let snap = sampler.sample(); Self { sampler, snap, last_sample: Instant::now(), // Floor ~1 MiB/s so idle gauges aren't pegged by noise. disk_read_scale: PeakScale::new(1024.0 * 1024.0), disk_write_scale: PeakScale::new(1024.0 * 1024.0), net_rx_scale: PeakScale::new(256.0 * 1024.0), net_tx_scale: PeakScale::new(256.0 * 1024.0), disk_read_anomalies: Vec::new(), disk_write_anomalies: Vec::new(), } } fn tick(&mut self) { if self.last_sample.elapsed() >= SAMPLE_EVERY { self.snap = self.sampler.sample(); self.last_sample = Instant::now(); let d = &self.snap.disk_total; let n = &self.snap.net_total; // Compare against previous scale *before* observing so a new peak // still registers as abnormal relative to the old ceiling. let dr_prev = self.disk_read_scale.current(); let dw_prev = self.disk_write_scale.current(); if is_abnormal(d.read_bps, dr_prev) { if let Some(p) = top_reader(&self.snap.processes) { push_anomaly( &mut self.disk_read_anomalies, AnomalyHit { proc_name: p.name.clone(), rate_bps: d.read_bps, stamp: format_local_hms(), at: Instant::now(), }, ); } } if is_abnormal(d.write_bps, dw_prev) { if let Some(p) = top_writer(&self.snap.processes) { push_anomaly( &mut self.disk_write_anomalies, AnomalyHit { proc_name: p.name.clone(), rate_bps: d.write_bps, stamp: format_local_hms(), at: Instant::now(), }, ); } } self.disk_read_scale.observe(d.read_bps); self.disk_write_scale.observe(d.write_bps); self.net_rx_scale.observe(n.read_bps); self.net_tx_scale.observe(n.write_bps); } } } fn is_abnormal(rate: f64, prev_scale: f64) -> bool { if rate < ABNORMAL_MIN_BPS || prev_scale <= 0.0 { return false; } (rate / prev_scale) >= ABNORMAL_FRAC } /// Append a hit; skip duplicate of the same process within a short window. /// Entries are never timed out — only capped by [`ANOMALY_MAX`]. fn push_anomaly(list: &mut Vec, hit: AnomalyHit) { // Don't spam the same name on consecutive samples — refresh stamp/rate instead. if let Some(last) = list.last_mut() { if last.proc_name == hit.proc_name && last.at.elapsed() < Duration::from_secs(3) { last.rate_bps = hit.rate_bps; last.stamp = hit.stamp; last.at = hit.at; return; } } list.push(hit); while list.len() > ANOMALY_MAX { list.remove(0); } } impl eframe::App for UsageApp { fn update(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) { self.tick(); let th = Theme::dark(); apply(ctx, &th); // Keep sampling while idle. ctx.request_repaint_after(SAMPLE_EVERY); egui::TopBottomPanel::top("header") .frame(th.header_frame()) .show(ctx, |ui| { ui.vertical(|ui| { title(ui, &th, "I/O Usage"); dim_label(ui, &th, "Disk & network throughput"); }); }); // Top-level application UI is grid-only (Vidya enforces via central_page). central_page(ctx, &th, "usage_main", |g| { g.section(|ui| self.gauges_row(ui, &th)); if !self.disk_read_anomalies.is_empty() || !self.disk_write_anomalies.is_empty() { g.section(|ui| self.anomaly_section(ui, &th)); } g.section(|ui| self.proc_table(ui, &th)); g.section(|ui| self.breakdown(ui, &th)); }); } } impl UsageApp { fn gauges_row(&self, ui: &mut egui::Ui, th: &Theme) { // One grid row of equal flex columns — single baseline, fits viewport. const GAUGE_SIZE_MAX: f32 = 148.0; let disk_r = self.snap.disk_total.read_bps; let disk_w = self.snap.disk_total.write_bps; let net_r = self.snap.net_total.read_bps; let net_w = self.snap.net_total.write_bps; let dr_max = self.disk_read_scale.current(); let dw_max = self.disk_write_scale.current(); let nr_max = self.net_rx_scale.current(); let nw_max = self.net_tx_scale.current(); let cards: [(&str, f64, f64, &str); 4] = [ ("Disk read", disk_r, dr_max, "Disk Read"), ("Disk write", disk_w, dw_max, "Disk Write"), ("Network down", net_r, nr_max, "Net Down"), ("Network up", net_w, nw_max, "Net Up"), ]; grid_cols( ui, th, "io_gauges", &[ ColSpec::Flex, ColSpec::Flex, ColSpec::Flex, ColSpec::Flex, ], |g| { g.row(|r| { for &(caption, value, max, label) in &cards { r.cell(|ui| { // Cell width is the grid budget; scale gauge to fit. let cell_w = ui.available_width().max(1.0); let pad = th.spacing.md * 2.0; let gauge_size = (cell_w - pad).clamp(72.0, GAUGE_SIZE_MAX); gauge_tile( ui, th, cell_w, gauge_size, caption, value, max, label, ); }); } }); }, ); } /// Compact Process | Time | Usage tables for abnormal disk I/O. fn anomaly_section(&self, ui: &mut egui::Ui, th: &Theme) { let read = &self.disk_read_anomalies; let write = &self.disk_write_anomalies; // Wide enough for Process (flex) + Time (fixed stamp) + Usage (MetricBps). const CARD_W: f32 = 450.0; let has_read = !read.is_empty(); let has_write = !write.is_empty(); if !has_read && !has_write { return; } // Side-by-side when both present; single cell otherwise — always grid DSL. if has_read && has_write { grid_cols( ui, th, "anomaly_pair", &[ColSpec::Fixed(CARD_W), ColSpec::Fixed(CARD_W)], |g| { g.row(|r| { r.cell(|ui| { compact_card(ui, th, CARD_W, |ui| { title_2(ui, th, "Abnormal disk read"); anomaly_table(ui, th, read, "anomaly_read"); }); }); r.cell(|ui| { compact_card(ui, th, CARD_W, |ui| { title_2(ui, th, "Abnormal disk write"); anomaly_table(ui, th, write, "anomaly_write"); }); }); }); }, ); } else if has_read { grid_cols(ui, th, "anomaly_read_only", &[ColSpec::Fixed(CARD_W)], |g| { g.row(|r| { r.cell(|ui| { compact_card(ui, th, CARD_W, |ui| { title_2(ui, th, "Abnormal disk read"); anomaly_table(ui, th, read, "anomaly_read"); }); }); }); }); } else { grid_cols(ui, th, "anomaly_write_only", &[ColSpec::Fixed(CARD_W)], |g| { g.row(|r| { r.cell(|ui| { compact_card(ui, th, CARD_W, |ui| { title_2(ui, th, "Abnormal disk write"); anomaly_table(ui, th, write, "anomaly_write"); }); }); }); }); } } fn breakdown(&self, ui: &mut egui::Ui, th: &Theme) { // Disks | Interfaces as one grid row. grid_cols( ui, th, "device_breakdown", &[ColSpec::Flex, ColSpec::Flex], |g| { g.row(|r| { r.cell(|ui| { device_card( ui, th, "Disks", &self.snap.disks, self.disk_read_scale .current() .max(self.disk_write_scale.current()), true, ); }); r.cell(|ui| { device_card( ui, th, "Interfaces", &self.snap.nets, self.net_rx_scale.current().max(self.net_tx_scale.current()), false, ); }); }); }, ); } fn proc_table(&self, ui: &mut egui::Ui, th: &Theme) { vidya::card(ui, th, |ui| { lead_trail( ui, |ui| title_2(ui, th, "Processes"), |ui| { dim_label( ui, th, &format!("{} readable", self.snap.processes.len()), ); }, ); dim_label( ui, th, "Disk write rate and write syscall frequency (from /proc/[pid]/io)", ); if self.snap.processes.is_empty() { dim_label(ui, th, "No process I/O readable (try running as root)"); return; } let active: Vec<_> = self .snap .processes .iter() .filter(|p| p.write_bps > 0.0 || p.write_freq > 0.0) .collect(); let rows: Vec<_> = if active.is_empty() { self.snap.processes.iter().take(24).collect() } else { active.into_iter().take(40).collect() }; // Grid DSL: columns + rows (no hand-rolled egui::Grid). grid_cols( ui, th, "process_io_table", &[ ColSpec::Flex, ColSpec::Flex, ColSpec::MetricBps, ColSpec::MetricRate, ], |g| { g.row(|r| { r.heading("Name"); r.heading("Path"); r.heading("Write"); r.heading("Write freq"); }); for p in &rows { g.row(|r| { r.text(&truncate_chars(&p.name, 28)); let path_show = if p.path.is_empty() { "—".to_string() } else { truncate_middle(&p.path, 64) }; r.dim(&path_show); r.metric_bps(p.write_bps); r.metric_rate(p.write_freq); }); } }, ); }); } } /// One compact gauge card (used inside the gauges grid row). fn gauge_tile( ui: &mut egui::Ui, th: &Theme, card_w: f32, gauge_size: f32, caption: &str, value: f64, max: f64, label: &str, ) { let frac = if max > 0.0 { (value / max) as f32 } else { 0.0 }; let color = heat_color(th, frac); compact_card(ui, th, card_w, |ui| { ui.vertical_centered(|ui| { dim_label(ui, th, caption); arc_gauge( ui, th, gauge_size, frac, &format_bps(value), label, color, ); dim_label(ui, th, &format!("scale {}", format_bps(max))); }); }); } /// Abnormal I/O list via vidya grid DSL. fn anomaly_table(ui: &mut egui::Ui, th: &Theme, hits: &[AnomalyHit], id: &str) { // Pin Time to stamp width so Process flex absorbs leftover (avoids equal-flex // squeeze that jammed names against timestamps). let time_w = th.type_scale.caption * 0.65 * 11.0 + th.spacing.md; grid_cols_with( ui, th, id, &[ColSpec::Flex, ColSpec::Fixed(time_w), ColSpec::MetricBps], GridOpts { striped: true, spacing: Vec2::new(th.spacing.lg, 2.0), }, |g| { g.row(|r| { r.heading("Process"); r.heading("Time"); r.heading("Usage"); }); for hit in hits.iter().rev() { g.row(|r| { r.warn(&truncate_chars(&hit.proc_name, 28)); r.dim(&hit.stamp); r.metric_bps(hit.rate_bps); }); } }, ); } fn truncate_chars(s: &str, max_chars: usize) -> String { let count = s.chars().count(); if count <= max_chars { s.to_string() } else { let t: String = s.chars().take(max_chars.saturating_sub(1)).collect(); format!("{t}…") } } /// Keep start and end of a long path: `/very/long/…/file`. fn truncate_middle(s: &str, max_chars: usize) -> String { let count = s.chars().count(); if count <= max_chars { return s.to_string(); } if max_chars < 8 { return truncate_chars(s, max_chars); } let head = (max_chars - 1) / 2; let tail = max_chars - 1 - head; let start: String = s.chars().take(head).collect(); let end: String = s .chars() .rev() .take(tail) .collect::() .chars() .rev() .collect(); format!("{start}…{end}") } fn device_card( ui: &mut egui::Ui, th: &Theme, heading: &str, devices: &[crate::io::DeviceIo], scale: f64, is_disk: bool, ) { card(ui, th, |ui| { title_2(ui, th, heading); if devices.is_empty() { dim_label( ui, th, if is_disk { "No block devices" } else { "No interfaces" }, ); return; } let max_rows = 8; let shown: Vec<&crate::io::DeviceIo> = devices.iter().take(max_rows).collect(); // Each device: name+total on one grid row of bars via nested grid. for d in &shown { lead_trail( ui, |ui| body(ui, th, &d.name), |ui| { ui.label( RichText::new(format_bps(d.rates.read_bps + d.rates.write_bps)) .size(th.type_scale.caption) .color(th.palette.text_secondary), ); }, ); grid_cols( ui, th, ("dev_bars", d.name.as_str()), &[ColSpec::Flex, ColSpec::Flex], |g| { g.row(|r| { r.cell(|ui| { dim_label(ui, th, &format!("↓ {}", format_bps(d.rates.read_bps))); let f = if scale > 0.0 { (d.rates.read_bps / scale) as f32 } else { 0.0 }; let w = ui.available_width().max(40.0); mini_bar(ui, th, f, th.palette.accent, w); }); r.cell(|ui| { dim_label(ui, th, &format!("↑ {}", format_bps(d.rates.write_bps))); let f = if scale > 0.0 { (d.rates.write_bps / scale) as f32 } else { 0.0 }; let w = ui.available_width().max(40.0); mini_bar(ui, th, f, th.palette.success, w); }); }); }, ); } if devices.len() > max_rows { dim_label( ui, th, &format!("+{} more", devices.len() - max_rows), ); } }); } /// Consumer: top-level page is grid-enforced; multi-column surfaces use `grid_cols`. #[cfg(test)] mod layout_dsl_consumer { fn app_src() -> &'static str { include_str!("app.rs") } fn section<'a>(src: &'a str, start_pat: &str, end_pat: &str) -> &'a str { let start = src.find(start_pat).unwrap_or_else(|| panic!("missing {start_pat}")); let rest = &src[start..]; let end = rest.find(end_pat).unwrap_or(rest.len()); &rest[..end] } #[test] fn top_level_ui_uses_central_page_grid() { let src = app_src(); let prod = src .split("mod layout_dsl_consumer") .next() .expect("production src"); assert!( prod.contains("central_page("), "app root must use Vidya central_page (grid-enforced shell)" ); assert!( prod.contains("g.section(") || prod.contains(".section(|"), "top-level page sections must go through GridCtx::section" ); // Free-form page_body(ui, |ui|) is gone from the public path; apps // must not hand-roll CentralPanel + free stack for main content. assert!( !prod.contains("page_scroll("), "usage must not bypass the grid shell with page_scroll" ); let update = section(prod, "fn update(", "\nimpl UsageApp"); assert!( !update.contains("page_body(") || update.contains("central_page"), "update() should use central_page, not free-form page_body" ); assert!( !update.contains("CentralPanel"), "central content must go through central_page, not raw CentralPanel" ); } #[test] fn gauges_use_grid_cols_not_pack() { let body = section(app_src(), "fn gauges_row(", "\n fn anomaly_section("); assert!(body.contains("grid_cols")); assert!(body.contains("g.row") || body.contains(".row(|")); assert!( !body.contains("pack("), "gauges must not use pack for multi-tile row" ); assert!(!body.contains("horizontal_wrapped")); } #[test] fn anomaly_section_uses_grid_cols_not_pack_or_columns() { let body = section(app_src(), "fn anomaly_section(", "\n fn breakdown("); assert!(body.contains("grid_cols")); assert!(body.contains("g.row") || body.contains(".row(|")); assert!( !body.contains("pack("), "anomaly multi-column layout must not use pack" ); assert!(!body.contains("ui.columns(")); assert!(body.contains("compact_card")); } #[test] fn breakdown_uses_grid_cols_not_ui_columns() { let body = section(app_src(), "fn breakdown(", "\n fn proc_table("); assert!(body.contains("grid_cols")); assert!(body.contains("device_breakdown") || body.contains("ColSpec::Flex")); assert!( !body.contains("ui.columns("), "breakdown must not use raw Ui::columns" ); } #[test] fn process_table_uses_grid_cols_metrics() { let body = section(app_src(), "fn proc_table(", "\nfn gauge_tile("); assert!(body.contains("grid_cols")); assert!(body.contains("ColSpec::MetricBps") && body.contains("ColSpec::MetricRate")); assert!(body.contains("metric_bps") && body.contains("metric_rate")); assert!(!body.contains("max_write") && !body.contains("bar_w")); } #[test] fn anomaly_table_uses_grid_row_dsl() { let body = section(app_src(), "fn anomaly_table(", "\nfn truncate_chars("); assert!(body.contains("grid_cols_with") || body.contains("grid_cols")); assert!(body.contains("ColSpec::Fixed")); assert!(body.contains(".warn(") || body.contains("r.warn")); assert!(body.contains("metric_bps")); } #[test] fn no_raw_multi_column_helpers_for_main_surfaces() { // Production code only (exclude this test module's string literals). let src = app_src(); let prod = src .split("mod layout_dsl_consumer") .next() .expect("production src"); for forbidden in ["ui.columns(", "horizontal_wrapped(", "pack("] { assert!( !prod.contains(forbidden), "shipped app production code must not use {forbidden}" ); } } #[test] fn shipped_vidya_grid_policy() { assert!(vidya::side_by_side(800.0, 160.0, 12.0)); assert!(!vidya::side_by_side(200.0, 160.0, 12.0)); let th = vidya::Theme::dark(); assert!(vidya::ColSpec::MetricBps.px(&th).unwrap() > 40.0); } }