use egui::Context;
use std::time::Duration;
pub fn painted_text(ctx: &Context, body: impl FnMut(&mut egui::Ui)) -> Vec<String> {
painted_text_sized(ctx, DEFAULT_VIEWPORT, body)
}
pub const DEFAULT_VIEWPORT: egui::Vec2 = egui::Vec2::new(1600.0, 1200.0);
pub fn painted_text_sized(
ctx: &Context,
size: egui::Vec2,
mut body: impl FnMut(&mut egui::Ui),
) -> Vec<String> {
let input = egui::RawInput {
screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, size)),
..Default::default()
};
let mut run_frame = || {
ctx.run(input.clone(), |ctx| {
egui::CentralPanel::default().show(ctx, |ui| body(ui));
})
};
let _warmup = run_frame();
let settled = run_frame();
let mut out = Vec::new();
for clipped in &settled.shapes {
collect_shape_text(&clipped.shape, &mut out);
}
out
}
pub fn painted_text_until<T>(
ctx: &Context,
deadline: std::time::Duration,
state: &mut T,
mut pump: impl FnMut(&mut T, &Context),
mut settled: impl FnMut(&T, &[String]) -> bool,
mut body: impl FnMut(&mut T, &mut egui::Ui),
) -> Vec<String> {
let start = std::time::Instant::now();
let mut last = painted_text(ctx, |ui| body(state, ui));
while !settled(state, &last) && start.elapsed() < deadline {
std::thread::sleep(std::time::Duration::from_millis(50));
pump(state, ctx);
last = painted_text(ctx, |ui| body(state, ui));
}
if settled(state, &last) {
return last;
}
pump(state, ctx);
let final_pass = painted_text(ctx, |ui| body(state, ui));
if final_pass.is_empty() {
last
} else {
final_pass
}
}
pub fn frame_is_still_loading(lines: &[String]) -> bool {
lines.iter().any(|l| l.trim_start().starts_with("Loading"))
}
pub fn painted_blob(ctx: &Context, body: impl FnMut(&mut egui::Ui)) -> String {
painted_text(ctx, body).join("\n")
}
pub fn painted_text_rects_sized(
ctx: &Context,
size: egui::Vec2,
mut body: impl FnMut(&mut egui::Ui),
) -> Vec<(String, egui::Rect)> {
let input = egui::RawInput {
screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, size)),
..Default::default()
};
let mut run_frame = || {
ctx.run(input.clone(), |ctx| {
egui::CentralPanel::default().show(ctx, |ui| body(ui));
})
};
let _warmup = run_frame();
let settled = run_frame();
let mut out = Vec::new();
for clipped in &settled.shapes {
collect_shape_text_rects(&clipped.shape, &mut out);
}
out
}
pub fn horizontal_overflow(
ctx: &Context,
size: egui::Vec2,
body: impl FnMut(&mut egui::Ui),
) -> Vec<(String, f32)> {
painted_text_rects_sized(ctx, size, body)
.into_iter()
.filter(|(text, rect)| !text.trim().is_empty() && rect.max.x > size.x)
.map(|(text, rect)| (text, rect.max.x - size.x))
.collect()
}
pub fn settle(app: &mut crate::gui::app::IronMonitorApp, ctx: &Context, budget: Duration) -> bool {
let deadline = std::time::Instant::now() + budget;
while std::time::Instant::now() < deadline {
app.pump_background_loaders(ctx);
app.sync_snapshot();
if app.has_real_snapshot() && !app.has_pending_load() {
return true;
}
std::thread::sleep(Duration::from_millis(20));
}
false
}
pub fn painted_extent(
ctx: &Context,
canvas: egui::Vec2,
body: impl FnMut(&mut egui::Ui),
) -> egui::Vec2 {
let mut extent = egui::Vec2::ZERO;
for (text, rect) in painted_text_rects_sized(ctx, canvas, body) {
if text.trim().is_empty() {
continue;
}
extent.x = extent.x.max(rect.max.x);
extent.y = extent.y.max(rect.max.y);
}
extent
}
pub fn painted_shape_rects(
ctx: &Context,
size: egui::Vec2,
mut body: impl FnMut(&mut egui::Ui),
) -> Vec<(&'static str, egui::Rect)> {
let input = egui::RawInput {
screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, size)),
..Default::default()
};
let mut run_frame = || {
ctx.run(input.clone(), |ctx| {
egui::CentralPanel::default().show(ctx, |ui| body(ui));
})
};
let _warmup = run_frame();
let settled = run_frame();
let mut out = Vec::new();
for clipped in &settled.shapes {
collect_shape_rects(&clipped.shape, &mut out);
}
out
}
fn shape_kind(shape: &egui::Shape) -> &'static str {
match shape {
egui::Shape::Noop => "noop",
egui::Shape::Vec(_) => "vec",
egui::Shape::Circle(_) => "circle",
egui::Shape::Ellipse(_) => "ellipse",
egui::Shape::LineSegment { .. } => "line",
egui::Shape::Path(_) => "path",
egui::Shape::Rect(_) => "rect",
egui::Shape::Text(_) => "text",
egui::Shape::Mesh(_) => "mesh",
egui::Shape::QuadraticBezier(_) => "quadratic",
egui::Shape::CubicBezier(_) => "cubic",
egui::Shape::Callback(_) => "callback",
}
}
fn collect_shape_rects(shape: &egui::Shape, out: &mut Vec<(&'static str, egui::Rect)>) {
if let egui::Shape::Vec(shapes) = shape {
for s in shapes {
collect_shape_rects(s, out);
}
return;
}
let rect = shape.visual_bounding_rect();
if rect.is_finite() && rect.is_positive() {
out.push((shape_kind(shape), rect));
}
}
pub fn widest_overflowing_shapes(
ctx: &Context,
size: egui::Vec2,
body: impl FnMut(&mut egui::Ui),
) -> Vec<(&'static str, egui::Rect, f32)> {
let mut over: Vec<(&'static str, egui::Rect, f32)> = painted_shape_rects(ctx, size, body)
.into_iter()
.filter(|(_, rect)| rect.max.x > size.x)
.map(|(kind, rect)| (kind, rect, rect.max.x - size.x))
.collect();
over.sort_by(|a, b| b.2.total_cmp(&a.2));
over
}
fn collect_shape_text_rects(shape: &egui::Shape, out: &mut Vec<(String, egui::Rect)>) {
match shape {
egui::Shape::Text(text) => {
let s = text.galley.text();
if !s.is_empty() {
out.push((s.to_string(), shape.visual_bounding_rect()));
}
}
egui::Shape::Vec(shapes) => {
for s in shapes {
collect_shape_text_rects(s, out);
}
}
_ => {}
}
}
fn collect_shape_text(shape: &egui::Shape, out: &mut Vec<String>) {
match shape {
egui::Shape::Text(text) => {
let s = text.galley.text();
if !s.trim().is_empty() {
out.push(s.to_string());
}
}
egui::Shape::Vec(shapes) => {
for s in shapes {
collect_shape_text(s, out);
}
}
_ => {}
}
}
pub fn themed_context() -> Context {
let ctx = Context::default();
super::theme::apply_cyber_theme(&ctx);
ctx
}
#[cfg(test)]
mod tests {
use super::*;
use egui::RichText;
#[test]
fn the_harness_sees_text_that_was_painted() {
let ctx = themed_context();
let blob = painted_blob(&ctx, |ui| {
ui.label("a plain label");
ui.label(RichText::new("a strong label").strong());
});
assert!(blob.contains("a plain label"), "got: {blob}");
assert!(blob.contains("a strong label"), "got: {blob}");
}
#[test]
fn the_harness_sees_text_nested_inside_widgets() {
let ctx = themed_context();
let blob = painted_blob(&ctx, |ui| {
egui::CollapsingHeader::new("outer heading")
.default_open(true)
.show(ui, |ui| {
ui.label("nested body text");
});
});
assert!(blob.contains("outer heading"), "got: {blob}");
assert!(blob.contains("nested body text"), "got: {blob}");
}
#[test]
fn the_harness_does_not_invent_text() {
let ctx = themed_context();
let blob = painted_blob(&ctx, |ui| {
ui.label("only this");
});
assert!(!blob.contains("not drawn"), "got: {blob}");
}
#[test]
fn invisible_text_is_still_painted_text() {
let ctx = themed_context();
let panel_fill = ctx.style().visuals.panel_fill;
let blob = painted_blob(&ctx, |ui| {
ui.label(RichText::new("camouflaged").color(panel_fill));
});
assert!(
blob.contains("camouflaged"),
"the harness should see text regardless of its colour, so that a \
contrast bug is diagnosable as distinct from a missing-widget bug"
);
}
}
#[cfg(test)]
mod app_tab_tests {
use super::*;
use crate::gui::app::IronMonitorApp;
fn app_and_ctx() -> (IronMonitorApp, egui::Context) {
let ctx = egui::Context::default();
let app = IronMonitorApp::with_context(&ctx);
(app, ctx)
}
#[test]
fn header_controls_do_not_overlap_or_leave_the_window() {
let (mut app, ctx) = app_and_ctx();
for width in [800.0, 1100.0, 1400.0] {
let input = egui::RawInput {
screen_rect: Some(egui::Rect::from_min_size(
egui::Pos2::ZERO,
egui::vec2(width, 600.0),
)),
..Default::default()
};
let _ = ctx.run(input.clone(), |ctx| app.draw_top_panel(ctx));
let output = ctx.run(input, |ctx| app.draw_top_panel(ctx));
let mut labels = Vec::new();
for clipped in &output.shapes {
collect_shape_text_rects(&clipped.shape, &mut labels);
}
assert!(labels.iter().any(|(text, _)| text.contains('@')));
assert!(labels.iter().any(|(text, _)| text.ends_with(" AI")));
let settings = labels
.iter()
.find(|(text, _)| text == "⚙")
.expect("Settings control");
assert!(
settings.1.max.x > width - 40.0,
"Settings should stay at the right edge"
);
for (index, (text, rect)) in labels.iter().enumerate() {
assert!(
rect.min.x >= 0.0 && rect.max.x <= width,
"header label {text:?} is outside a {width}px window: {rect:?}"
);
for (other, other_rect) in &labels[index + 1..] {
assert!(
!rect.intersects(*other_rect),
"header labels {text:?} and {other:?} overlap at {width}px: \
{rect:?} and {other_rect:?}"
);
}
}
}
}
#[test]
fn the_ai_tab_renders_its_controls() {
let (mut app, ctx) = app_and_ctx();
let first = painted_blob(&ctx, |ui| {
app.draw_ai_assistant_tab(ui);
});
assert!(
first.contains("Detecting AI backends"),
"expected the detection notice on the first frame, got: {first}"
);
std::thread::sleep(std::time::Duration::from_millis(3200));
let settled = painted_blob(&ctx, |ui| {
app.draw_ai_assistant_tab(ui);
});
assert!(
settled.contains("AI System Assistant"),
"past the detection budget the AI tab should paint its header and \
controls, got: {settled}"
);
assert!(
settled.contains("Model:") || settled.contains("Select model"),
"the AI tab painted its header but not its model selector: {settled}"
);
assert!(
settled
.lines()
.any(|l| l.contains("Ollama") || l.contains("IronWorks") || l.contains("backend")),
"the AI tab offered no backend at all: {settled}"
);
}
#[test]
fn the_overview_ask_bar_renders_and_explains_itself() {
let (mut app, ctx) = app_and_ctx();
let blob = painted_blob(&ctx, |ui| {
app.draw_overview_chat_bar(ui);
});
assert!(
blob.contains("Ask"),
"the ask bar is missing its label: {blob}"
);
if !app.agent_can_answer() {
assert!(
blob.contains("no model selected"),
"with no model available the bar should say so, got: {blob}"
);
}
}
#[test]
fn shared_chat_composer_is_visible_at_the_top_on_small_and_large_pages() {
let (mut app, ctx) = app_and_ctx();
for width in [320.0, 800.0, 1400.0] {
let size = egui::vec2(width, 700.0);
painted_text_rects_sized(&ctx, size, |ui| {
let full_width = ui.available_width();
let fonts = ui.style().text_styles.clone();
app.draw_agent_composer(ui);
assert!((ui.available_width() - full_width).abs() < 1.0);
assert_eq!(ui.style().text_styles, fonts);
let dashboard = ui.add(crate::gui::widgets::QuickLookPanel::new(
None, None, None, None,
));
assert!((dashboard.rect.width() - full_width).abs() < 1.0);
assert_eq!(dashboard.rect.height(), 48.0);
});
for ai_page in [false, true] {
let text = painted_text_rects_sized(&ctx, size, |ui| {
if ai_page {
app.draw_ai_assistant_tab(ui);
} else {
app.draw_overview(ui);
}
});
assert!(!text.iter().any(|(text, _)| text == "Ask IronMonitor"));
let (_, input) = text
.iter()
.find(|(text, _)| text.starts_with("Ask "))
.expect("composer input");
assert!(input.min.y < 30.0, "{input:?}");
let (_, send) = text
.iter()
.find(|(text, _)| text == "Send")
.expect("send control");
assert!(send.max.x <= width && send.max.y < 200.0, "{send:?}");
assert!(send.min.x > input.max.x, "input: {input:?}, send: {send:?}");
assert!(
(send.center().y - input.center().y).abs() < 1.0,
"input: {input:?}, send: {send:?}"
);
let output = ctx.run(
egui::RawInput {
screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, size)),
..Default::default()
},
|ctx| {
egui::CentralPanel::default().show(ctx, |ui| {
if ai_page {
app.draw_ai_assistant_tab(ui);
} else {
app.draw_overview(ui);
}
});
},
);
let composer = output
.shapes
.iter()
.find_map(|shape| match &shape.shape {
egui::epaint::Shape::Rect(rect)
if rect.fill == super::super::theme::CyberColors::BACKGROUND_DARK
&& rect.rect.contains(send.center())
&& rect.rect.contains(input.center()) =>
{
Some(rect.rect)
}
_ => None,
})
.expect("dark composer background");
assert!((composer.height() - 32.0).abs() < 1.0, "{composer:?}");
assert!(
(composer.center().x - width * 0.5).abs() < 2.0,
"{composer:?}"
);
let expected_width = (width - 16.0) * (2.0 / 3.0);
assert!(
(composer.width() - expected_width).abs() < 2.0,
"{composer:?}"
);
}
}
}
#[test]
fn the_profiles_tab_paints_readable_headings() {
let (mut app, ctx) = app_and_ctx();
let blob = painted_blob(&ctx, |ui| {
app.draw_profiles_tab(ui);
});
assert!(
blob.contains("Hardware Profile Inspector"),
"the Profiles tab did not paint its header: {blob}"
);
let visuals = ctx.style().visuals.clone();
let strong = visuals.strong_text_color();
let panel = visuals.panel_fill;
let distance = (strong.r() as i32 - panel.r() as i32).abs()
+ (strong.g() as i32 - panel.g() as i32).abs()
+ (strong.b() as i32 - panel.b() as i32).abs();
assert!(
distance > 60,
"Profiles headings are painted in {strong:?} on a {panel:?} panel — the \
original failure, where all 19 groups rendered and none could be read"
);
}
#[test]
fn tabs_do_not_paint_glyphs_the_bundled_fonts_lack() {
let (mut app, ctx) = app_and_ctx();
let blob = painted_blob(&ctx, |ui| {
app.draw_profiles_tab(ui);
});
for glyph in ['\u{25BE}', '\u{25B8}'] {
assert!(
!blob.contains(glyph),
"U+{:04X} is back in the Profiles tab; NotoEmoji does not cover \
Geometric Shapes, so it renders as a tofu box",
glyph as u32
);
}
}
}
#[cfg(test)]
mod ontology_binding_tests {
use super::*;
use crate::gui::widgets::{domain_section_title, SectionHeader};
use crate::ontology::labels;
#[test]
fn section_headings_paint_the_ontology_domain_spelling() {
let ctx = themed_context();
let title = domain_section_title("gpu", "Utilization");
let blob = painted_blob(&ctx, |ui| {
ui.add(SectionHeader::new(&title));
});
assert!(
blob.contains("GPU Utilization"),
"expected the ontology spelling in painted output, got: {blob}"
);
assert!(labels::is_known_domain("gpu"));
}
#[test]
fn painted_labels_resolve_to_entity_ids() {
let ctx = themed_context();
let label = labels::short_label("memory.total");
let blob = painted_blob(&ctx, |ui| {
ui.label(&label);
});
assert!(blob.contains("Total"), "got: {blob}");
let ids = labels::ids_for_label(&label);
assert!(
ids.iter().any(|id| id == "memory.total"),
"the label the GUI painted does not map back to memory.total: {ids:?}"
);
}
#[test]
fn strong_headings_are_both_painted_and_legible() {
let ctx = themed_context();
let blob = painted_blob(&ctx, |ui| {
ui.label(egui::RichText::new("Group Heading").strong());
});
assert!(
blob.contains("Group Heading"),
"strong text was not painted at all: {blob}"
);
let visuals = ctx.style().visuals.clone();
let strong = visuals.strong_text_color();
let panel = visuals.panel_fill;
let distance = (strong.r() as i32 - panel.r() as i32).abs()
+ (strong.g() as i32 - panel.g() as i32).abs()
+ (strong.b() as i32 - panel.b() as i32).abs();
assert!(
distance > 60,
"strong text {strong:?} is painted but indistinguishable from the panel \
{panel:?} — the Profiles failure mode"
);
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Step {
Goto(String),
Capture,
Assert(String),
Refute(String),
}
#[derive(Debug, Default)]
pub struct ScriptResult {
pub captures: Vec<String>,
pub failures: Vec<String>,
}
pub fn parse_script(text: &str) -> Result<Vec<Step>, String> {
let mut steps = Vec::new();
for (n, raw) in text.lines().enumerate() {
let line = raw.split('#').next().unwrap_or("").trim();
if line.is_empty() {
continue;
}
let (verb, rest) = match line.split_once(char::is_whitespace) {
Some((v, r)) => (v, r.trim()),
None => (line, ""),
};
let step = match verb.to_ascii_lowercase().as_str() {
"goto" if !rest.is_empty() => Step::Goto(rest.to_string()),
"capture" => Step::Capture,
"assert" if !rest.is_empty() => Step::Assert(rest.to_string()),
"refute" if !rest.is_empty() => Step::Refute(rest.to_string()),
other => {
return Err(format!(
"line {}: unknown or incomplete step {other:?}. Steps: goto <tab>, \
capture, assert <text>, refute <text>. The GUI has no `key` step \
— tabs are addressable by name, so there is no navigation state \
to drive.",
n + 1
))
}
};
steps.push(step);
}
Ok(steps)
}
pub const SETTLE_DEADLINE: std::time::Duration = std::time::Duration::from_secs(30);
pub fn settled_tab_text(app: &mut super::app::IronMonitorApp, ctx: &Context) -> String {
app.agents.wait_for_scan(std::time::Duration::from_secs(5));
painted_text_until(
ctx,
SETTLE_DEADLINE,
app,
|app, ctx| app.pump_background_loaders(ctx),
|app, lines| !frame_is_still_loading(lines) && !app.has_pending_load(),
|app, ui| app.draw_current_tab(ui),
)
.join("\n")
}
pub fn run_script(
app: &mut super::app::IronMonitorApp,
ctx: &Context,
steps: &[Step],
) -> ScriptResult {
let mut result = ScriptResult::default();
let mut frame = settled_tab_text(app, ctx);
for (i, step) in steps.iter().enumerate() {
match step {
Step::Goto(target) => match app.select_tab_by_name(target) {
Ok(()) => {
frame = settled_tab_text(app, ctx);
}
Err(available) => result.failures.push(format!(
"step {}: unknown tab {target:?}; available: {available:?}",
i + 1
)),
},
Step::Capture => result.captures.push(frame.clone()),
Step::Assert(needle) => {
if !frame.contains(needle.as_str()) {
result.failures.push(format!(
"step {}: expected {needle:?} in the painted text, not found",
i + 1
));
}
}
Step::Refute(needle) => {
if frame.contains(needle.as_str()) {
result.failures.push(format!(
"step {}: {needle:?} should not be painted, but is",
i + 1
));
}
}
}
}
result
}
#[cfg(test)]
mod script_tests {
use super::*;
use crate::gui::app::IronMonitorApp;
fn app_and_ctx() -> (IronMonitorApp, Context) {
let ctx = themed_context();
let app = IronMonitorApp::with_context(&ctx);
(app, ctx)
}
#[test]
fn scripts_parse_with_comments_and_blank_lines() {
let steps = parse_script("# go\ngoto profiles\n\ncapture # snap\nassert Inspector\n")
.expect("should parse");
assert_eq!(
steps,
vec![
Step::Goto("profiles".into()),
Step::Capture,
Step::Assert("Inspector".into()),
]
);
}
#[test]
fn a_key_step_is_rejected_with_the_reason() {
let err = parse_script("key 3").expect_err("the GUI has no key step");
assert!(err.contains("key"), "got: {err}");
assert!(
err.contains("addressable by name"),
"the error should say why, got: {err}"
);
}
#[test]
fn goto_changes_what_is_painted() {
let (mut app, ctx) = app_and_ctx();
let steps = parse_script("goto profiles\nassert Hardware Profile Inspector").unwrap();
let result = run_script(&mut app, &ctx, &steps);
assert!(result.failures.is_empty(), "{:?}", result.failures);
}
#[test]
fn assertions_and_refutations_report_rather_than_panic() {
let (mut app, ctx) = app_and_ctx();
let steps =
parse_script("goto profiles\nassert not-painted-anywhere\nrefute Inspector").unwrap();
let result = run_script(&mut app, &ctx, &steps);
assert_eq!(
result.failures.len(),
2,
"both the failed assert and the failed refute should report: {:?}",
result.failures
);
}
#[test]
fn an_unknown_tab_lists_the_available_ones() {
let (mut app, ctx) = app_and_ctx();
let steps = parse_script("goto nonsense").unwrap();
let result = run_script(&mut app, &ctx, &steps);
assert_eq!(result.failures.len(), 1);
assert!(
result.failures[0].contains("overview"),
"should name the alternatives: {:?}",
result.failures
);
}
#[test]
fn capture_records_the_frame_after_navigation() {
let (mut app, ctx) = app_and_ctx();
let steps = parse_script("goto profiles\ncapture").unwrap();
let result = run_script(&mut app, &ctx, &steps);
assert_eq!(result.captures.len(), 1);
assert!(result.captures[0].contains("Hardware Profile Inspector"));
}
}
#[cfg(test)]
mod overflow_tests {
use super::*;
const TABS: [&str; 14] = [
"inference",
"overview",
"cpu",
"accelerators",
"memory",
"disk",
"processes",
"network",
"tools",
"connections",
"system",
"peripherals",
"profiles",
"ai",
];
const KNOWN_OVERFLOWING: [&str; 0] = [];
#[test]
fn no_tab_paints_text_past_the_right_edge() {
let ctx = themed_context();
let mut app = crate::gui::app::IronMonitorApp::with_context(&ctx);
let mut offenders = Vec::new();
let mut unexpectedly_clean = Vec::new();
let mut still_loading = Vec::new();
for tab in TABS {
if app.select_tab_by_name(tab).is_err() {
continue;
}
if !settle(&mut app, &ctx, Duration::from_secs(30)) {
still_loading.push(tab);
continue;
}
let pinned = KNOWN_OVERFLOWING.contains(&tab);
let mut any = false;
for width in [1400.0_f32, 800.0] {
let size = egui::Vec2::new(width, 900.0);
for (text, past) in horizontal_overflow(&ctx, size, |ui| app.draw_current_tab(ui)) {
any = true;
if !pinned {
offenders.push(format!(
"{tab} @ {width:.0}px wide: {text:?} runs {past:.0}px past the edge"
));
}
}
}
if pinned && !any {
unexpectedly_clean.push(tab);
}
}
assert!(
offenders.is_empty(),
"text painted outside the window, which a reader sees as clipped or missing:
{}",
offenders.join(
"
"
)
);
if !still_loading.is_empty() {
eprintln!("skipped, still loading after 5s: {still_loading:?}");
}
assert!(
unexpectedly_clean.is_empty(),
"pinned as overflowing but no longer overflowing: {unexpectedly_clean:?}. Remove them from KNOWN_OVERFLOWING so the guard covers them."
);
}
}
#[cfg(test)]
mod overview_extent {
use super::*;
#[test]
fn the_fit_waits_for_the_overview_to_finish_loading() {
let ctx = themed_context();
let mut app = crate::gui::app::IronMonitorApp::with_context(&ctx);
app.select_tab_by_name("overview")
.expect("overview is a tab");
assert!(
!app.has_real_snapshot(),
"a freshly constructed app has applied no snapshot, warm-up or otherwise"
);
assert!(
!app.autofit_to_overview_once(&ctx),
"the window must not be fitted to an Overview that has not loaded its data"
);
assert!(
settle(&mut app, &ctx, Duration::from_secs(30)),
"the Overview did not finish loading, so there is nothing trustworthy to measure"
);
assert!(
!app.autofit_to_overview_once(&ctx),
"loaded but never drawn: there is no shortfall recorded to fit to"
);
let _ = painted_extent(&ctx, egui::Vec2::new(1400.0, 900.0), |ui| {
app.draw_current_tab(ui)
});
assert!(
app.autofit_to_overview_once(&ctx),
"once everything has loaded and been drawn, the fit must run"
);
assert!(
!app.autofit_to_overview_once(&ctx),
"and it must run only once, or every frame resizes the user's window"
);
}
#[test]
fn the_fit_measures_paint_rather_than_canvas() {
let ctx = themed_context();
let mut app = crate::gui::app::IronMonitorApp::with_context(&ctx);
app.select_tab_by_name("overview")
.expect("overview is a tab");
assert!(settle(&mut app, &ctx, Duration::from_secs(30)));
let extent = painted_extent(&ctx, egui::Vec2::new(1400.0, 4000.0), |ui| {
app.draw_current_tab(ui)
});
assert!(
extent.y > 300.0 && extent.y < 3000.0,
"the Overview should paint a windowful, not nothing and not the whole 4000 px canvas; got {:.1}",
extent.y
);
}
#[test]
fn the_overview_takes_whatever_width_it_is_given() {
let ctx = themed_context();
let mut app = crate::gui::app::IronMonitorApp::with_context(&ctx);
app.select_tab_by_name("overview")
.expect("overview is a tab");
let wide = painted_extent(&ctx, egui::Vec2::new(1400.0, 4000.0), |ui| {
app.draw_current_tab(ui)
});
let narrow = painted_extent(&ctx, egui::Vec2::new(1100.0, 4000.0), |ui| {
app.draw_current_tab(ui)
});
assert!(
wide.x > narrow.x + 200.0,
"elastic layout: a 300 px wider canvas should paint wider, got {:.0} vs {:.0}",
wide.x,
narrow.x
);
assert!(
(wide.y - narrow.y).abs() < 2.0,
"height must not depend on width: {:.1} at 1400 vs {:.1} at 1100",
wide.y,
narrow.y
);
}
}
#[cfg(test)]
mod monochrome_tests {
use super::*;
use crate::gui::{
app::ColorTheme,
theme,
widgets::{CyberProgressBar, MetricCard, SparklineChart, ThresholdLegend},
};
fn assert_grayscale(ctx: &Context, output: egui::FullOutput, label: &str) {
let primitives = ctx.tessellate(output.shapes, output.pixels_per_point);
let mut vertices = 0;
for primitive in primitives {
if let egui::epaint::Primitive::Mesh(mesh) = primitive.primitive {
for vertex in mesh.vertices {
let color = vertex.color;
vertices += 1;
assert!(
color.r() == color.g() && color.g() == color.b(),
"{label} painted a colored vertex: {color:?}"
);
}
}
}
assert!(vertices > 0, "{label} painted nothing");
}
#[test]
fn dark_monochrome_covers_every_tab_and_custom_charts() {
let ctx = themed_context();
let mut app = crate::gui::app::IronMonitorApp::with_context(&ctx);
theme::apply_theme(&ctx, ColorTheme::Monochrome);
let input = egui::RawInput {
screen_rect: Some(egui::Rect::from_min_size(
egui::Pos2::ZERO,
egui::vec2(1400.0, 900.0),
)),
..Default::default()
};
for tab in [
"inference",
"overview",
"cpu",
"accelerators",
"memory",
"disk",
"processes",
"network",
"tools",
"connections",
"system",
"peripherals",
"profiles",
"ai",
] {
app.select_tab_by_name(tab).unwrap();
if !settle(&mut app, &ctx, Duration::from_secs(30)) {
eprintln!("{tab}: hardware still loading; checking loading-state colors");
}
let mut output = None;
for _ in 0..2 {
output = Some(ctx.run(input.clone(), |ctx| {
egui::CentralPanel::default().show(ctx, |ui| app.draw_current_tab(ui));
}));
}
assert_grayscale(&ctx, output.unwrap(), tab);
}
let output = ctx.run(input, |ctx| {
egui::CentralPanel::default().show(ctx, |ui| {
ui.add(CyberProgressBar::new(0.85).with_threshold_color());
ui.add(MetricCard::new("Metric", "42").color(theme::CyberColors::NEON_GREEN));
ui.add(
SparklineChart::new(vec![10.0, 30.0, 20.0, 40.0])
.color(theme::CyberColors::MAGENTA),
);
ui.add(ThresholdLegend);
});
});
assert_grayscale(&ctx, output, "custom charts and widgets");
}
}
#[cfg(test)]
mod laptop_fit_tests {
use super::*;
const LAPTOP_WIDTH: f32 = 1264.0;
fn header_height(app: &mut crate::gui::app::IronMonitorApp, ctx: &Context, width: f32) -> f32 {
let input = egui::RawInput {
screen_rect: Some(egui::Rect::from_min_size(
egui::Pos2::ZERO,
egui::vec2(width, 720.0),
)),
..Default::default()
};
let _ = ctx.run(input.clone(), |ctx| app.draw_top_panel(ctx));
let mut top = 0.0;
let _ = ctx.run(input, |ctx| {
app.draw_top_panel(ctx);
top = ctx.available_rect().min.y;
});
top
}
#[test]
fn the_tab_strip_is_one_row_on_a_13_inch_laptop() {
let ctx = themed_context();
let mut app = crate::gui::app::IronMonitorApp::with_context(&ctx);
let laptop = header_height(&mut app, &ctx, LAPTOP_WIDTH);
let wide = header_height(&mut app, &ctx, 1600.0);
let narrow = header_height(&mut app, &ctx, 800.0);
assert!(
narrow > wide + 10.0,
"at 800 px the strip should wrap: {narrow:.0} vs {wide:.0} at 1600"
);
assert!(
(laptop - wide).abs() < 1.0,
"the strip wraps at {LAPTOP_WIDTH} px: {laptop:.0} px tall against {wide:.0} at 1600"
);
}
fn overview_bottom(
app: &mut crate::gui::app::IronMonitorApp,
ctx: &Context,
size: egui::Vec2,
) -> f32 {
for _ in 0..3 {
let _ = painted_shape_rects(ctx, size, |ui| app.draw_current_tab(ui));
}
painted_shape_rects(ctx, size, |ui| app.draw_current_tab(ui))
.into_iter()
.filter(|(kind, _)| matches!(*kind, "text" | "path" | "line" | "mesh"))
.map(|(_, rect)| rect.max.y)
.fold(0.0, f32::max)
}
#[test]
fn the_overview_charts_shrink_to_the_room_and_no_further() {
let ctx = themed_context();
let mut app = crate::gui::app::IronMonitorApp::with_context(&ctx);
app.select_tab_by_name("overview")
.expect("overview is a tab");
assert!(settle(&mut app, &ctx, Duration::from_secs(30)));
let natural = overview_bottom(&mut app, &ctx, egui::vec2(LAPTOP_WIDTH, 4000.0));
assert!(
natural > 300.0 && natural < 3000.0,
"the Overview should paint a windowful; got {natural:.0}"
);
let room = natural - 40.0;
let fitted = overview_bottom(&mut app, &ctx, egui::vec2(LAPTOP_WIDTH, room));
assert!(
fitted <= room + 4.0,
"the charts did not shrink to fit: painted to {fitted:.0} in a {room:.0} px room"
);
assert!(
fitted > room - 30.0,
"the charts shrank further than the room required: painted to {fitted:.0} in {room:.0}"
);
let restored = overview_bottom(&mut app, &ctx, egui::vec2(LAPTOP_WIDTH, 4000.0));
assert!(
(restored - natural).abs() < 1.0,
"charts did not regrow: {restored:.0} against {natural:.0}"
);
}
}
#[cfg(test)]
mod data_label_tests {
use super::*;
use crate::gui::theme::{CyberColors, DATA_LABEL_MIN_SIZE};
use crate::gui::widgets::{
CyberProgressBar, MetricCard, QuickLookPanel, SparklineChart, ThresholdLegend,
};
fn painted_sections(
ctx: &Context,
body: impl FnMut(&mut egui::Ui),
) -> Vec<(String, egui::FontId, egui::Color32)> {
let mut body = body;
let input = egui::RawInput {
screen_rect: Some(egui::Rect::from_min_size(
egui::Pos2::ZERO,
egui::vec2(1400.0, 4000.0),
)),
..Default::default()
};
let mut run = || {
ctx.run(input.clone(), |ctx| {
egui::CentralPanel::default().show(ctx, |ui| body(ui));
})
};
let _warmup = run();
let output = run();
fn walk(shape: &egui::Shape, out: &mut Vec<(String, egui::FontId, egui::Color32)>) {
match shape {
egui::Shape::Text(text) => {
let job = &text.galley.job;
for section in &job.sections {
let s = job.text[section.byte_range.clone()].trim().to_string();
if !s.is_empty() {
let color = if section.format.color == egui::Color32::PLACEHOLDER {
text.fallback_color
} else {
section.format.color
};
out.push((s, section.format.font_id.clone(), color));
}
}
}
egui::Shape::Vec(shapes) => shapes.iter().for_each(|s| walk(s, out)),
_ => {}
}
}
let mut out = Vec::new();
for clipped in &output.shapes {
walk(&clipped.shape, &mut out);
}
out
}
fn contrast(a: egui::Color32, b: egui::Color32) -> f32 {
fn luminance(c: egui::Color32) -> f32 {
let channel = |v: u8| {
let v = v as f32 / 255.0;
if v <= 0.03928 {
v / 12.92
} else {
((v + 0.055) / 1.055).powf(2.4)
}
};
0.2126 * channel(c.r()) + 0.7152 * channel(c.g()) + 0.0722 * channel(c.b())
}
let (hi, lo) = {
let (x, y) = (luminance(a), luminance(b));
(x.max(y), x.min(y))
};
(hi + 0.05) / (lo + 0.05)
}
fn draw_data_widgets(ui: &mut egui::Ui) {
ui.add(MetricCard::new("GPU 0 Temp", 63).unit("°C"));
ui.add(
SparklineChart::new(vec![10.0, 40.0, 90.0, 20.0])
.title("CPU Usage")
.unit("%")
.max_value(100.0)
.show_scale(true)
.show_min_max(true)
.height(80.0),
);
ui.add(QuickLookPanel::new(
Some(42.0),
Some(63.0),
Some(5.0),
Some(1.5),
));
ui.add(ThresholdLegend);
ui.add(CyberProgressBar::new(0.42).label("Used"));
}
#[test]
fn data_labels_are_bold_sized_and_legible_in_every_base_theme() {
let surfaces = [
("cyber", None, CyberColors::SURFACE),
("light", Some(()), crate::gui::theme::LightColors::SURFACE),
];
for (name, light, surface) in surfaces {
let ctx = Context::default();
if light.is_some() {
crate::gui::theme::apply_light_theme(&ctx);
} else {
crate::gui::theme::apply_cyber_theme(&ctx);
}
let sections = painted_sections(&ctx, draw_data_widgets);
for expected in ["63 °C", "CPU Usage", "42%", "CAREFUL", "90%+"] {
assert!(
sections.iter().any(|(text, ..)| text.contains(expected)),
"{name}: {expected:?} was not painted: {:?}",
sections.iter().map(|(t, ..)| t).collect::<Vec<_>>()
);
}
for (text, font, color) in §ions {
assert_eq!(
font.family,
egui::FontFamily::Name("data".into()),
"{name}: data label {text:?} is not in the bold data face"
);
assert!(
font.size >= DATA_LABEL_MIN_SIZE,
"{name}: data label {text:?} is {} px",
font.size
);
if color.a() < 255 {
continue;
}
let ratio = contrast(*color, surface);
assert!(
ratio >= 3.0,
"{name}: data label {text:?} in {color:?} is {ratio:.2}:1 against {surface:?}"
);
}
}
}
#[test]
fn data_labels_paint_on_an_unthemed_context_rather_than_panicking() {
let ctx = Context::default();
let sections = painted_sections(&ctx, draw_data_widgets);
assert!(sections.iter().any(|(text, ..)| text.contains("63 °C")));
}
#[test]
fn overview_reading_rows_are_bold_and_legible() {
for light in [false, true] {
let ctx = themed_context();
let mut app = crate::gui::app::IronMonitorApp::with_context(&ctx);
let surface = if light {
crate::gui::theme::apply_light_theme(&ctx);
crate::gui::theme::LightColors::SURFACE
} else {
CyberColors::SURFACE
};
app.select_tab_by_name("overview")
.expect("overview is a tab");
assert!(settle(&mut app, &ctx, Duration::from_secs(30)));
let sections = painted_sections(&ctx, |ui| app.draw_current_tab(ui));
let readings: Vec<_> = sections
.iter()
.filter(|(text, ..)| {
text.starts_with("Tasks:")
|| text.starts_with("Capacity:")
|| text.starts_with("Space used:")
})
.collect();
assert!(
readings.iter().any(|(text, ..)| text.starts_with("Tasks:")),
"light={light}: the Overview status row was not painted"
);
for (text, font, color) in readings {
assert_eq!(
font.family,
egui::FontFamily::Name("data".into()),
"light={light}: Overview reading {text:?} is not in the bold data face"
);
let ratio = contrast(*color, surface);
assert!(
ratio >= 3.0,
"light={light}: Overview reading {text:?} in {color:?} is {ratio:.2}:1"
);
}
}
}
}