Medlar/crates/app/tests/visuals.rs
2026-11-25 01:52:47 -06:00

404 lines
17 KiB
Rust

//! The progress widgets: no broken numbers, nothing outside its place, no frames at rest, the tick once.
//!
//! MEDLAR_SEQUENCE=dir cargo test -p medlar --test visuals sequence saves frames of a split and of finishing
//! cargo test --release -p medlar --test visuals -- --ignored --nocapture what 200 bars cost
#[path = "visuals/gallery.rs"]
mod gallery;
use eframe::egui::{self, Color32, Context, Id, Rect, Shape, Ui, pos2, vec2};
use egui_kittest::Harness;
use gallery::{MB, Sim, part};
use medlar_app::app::App;
use medlar_app::desktop::Sources;
use medlar_app::theme::Theme;
use medlar_app::ui::graph::{self, History};
use medlar_app::ui::odometer;
use medlar_app::ui::parts::{self, Block};
use medlar_app::ui::shape::{self, Kind};
use medlar_app::ui::wave::{self, Bar, Look};
use medlar_core::model::Part;
use medlar_core::settings::{Appearance, Motion, Settings};
use std::time::Duration;
const LOOKS: [Look; 6] = [Look::Waiting, Look::Running, Look::Paused, Look::Checking, Look::Failed, Look::Done];
fn settings(motion: Motion) -> Settings {
Settings { motion, appearance: Appearance::Light, desktop_colors: Some(false), ..Settings::default() }
}
/// A context that is driven by hand.
struct Stage {
ctx: Context,
app: App,
time: f64,
}
impl Stage {
fn new(motion: Motion) -> Stage {
let ctx = Context::default();
let nowhere = Sources { caelestia: "/nonexistent".into(), kde: "/nonexistent".into() };
let app = App::new(&ctx, settings(motion), nowhere);
let mut s = Stage { ctx, app, time: 0.0 };
s.frame(|_, _| {});
s
}
fn frame(&mut self, draw: impl Fn(&Theme, &mut Ui)) -> egui::FullOutput {
self.time += 1.0 / 60.0;
let input = egui::RawInput {
screen_rect: Some(Rect::from_min_size(pos2(0.0, 0.0), vec2(1000.0, 1000.0))),
time: Some(self.time),
predicted_dt: 1.0 / 60.0,
..Default::default()
};
let app = &mut self.app;
let mut out = self.ctx.run_ui(input, |ui| app.frame(ui, |app, ui| draw(&app.theme.clone(), ui)));
out.textures_delta.clear();
out
}
/// Frames until it rests. Returns how many it took.
fn rest(&mut self, draw: impl Fn(&Theme, &mut Ui)) -> usize {
for i in 0..600 {
if !asks_now(&self.frame(&draw)) {
return i;
}
}
panic!("never rests");
}
}
/// Does it want the next frame at once?
fn asks_now(out: &egui::FullOutput) -> bool {
out.viewport_output.values().any(|v| v.repaint_delay < Duration::from_millis(1))
}
/// All drawn points are numbers, and inside `bounds`.
fn check(out: &egui::FullOutput, bounds: Rect, what: &str) {
let mut seen = 0;
for s in &out.shapes {
walk(&s.shape, &mut |p: egui::Pos2| {
assert!(p.x.is_finite() && p.y.is_finite(), "{what}: {p:?}");
assert!(bounds.contains(p), "{what}: {p:?} outside {bounds:?}");
seen += 1;
});
}
assert!(seen > 0, "{what}: nothing drawn");
}
fn walk(s: &Shape, f: &mut impl FnMut(egui::Pos2)) {
if let Shape::Mesh(m) = s {
assert!(m.is_valid());
m.vertices.iter().for_each(|v| f(v.pos));
}
}
fn sample_parts() -> Vec<(&'static str, Option<u64>, Vec<Part>)> {
let m = MB;
vec![
("none", Some(400 * m), vec![]),
("zero", Some(400 * m), vec![part(0, 400 * m, 0)]),
("one byte", Some(400 * m), vec![part(0, 400 * m, 1)]),
("almost", Some(400 * m), vec![part(0, 400 * m, 400 * m - 1)]),
("full", Some(400 * m), vec![part(0, 400 * m, 400 * m)]),
("empty file", Some(0), vec![part(0, 0, 0)]),
("split", Some(400 * m), vec![part(0, 100 * m, 100 * m), part(100 * m, 101 * m, 5), part(101 * m, 400 * m, 80 * m)]),
("sixty", Some(6000), (0..60).map(|i| part(i * 100, i * 100 + 100, i)).collect()),
("thousands", Some(500_000), (0..5000).map(|i| part(i * 100, i * 100 + 100, 50)).collect()),
("unknown", None, vec![Part { start: 0, end: None, done: 7 * m }]),
("too much", Some(10), vec![part(0, 10, 99)]),
]
}
#[test]
fn bars_rings_and_maps_stay_in_their_place() {
for motion in [Motion::Off, Motion::Reduced, Motion::Normal, Motion::Expressive] {
let mut s = Stage::new(motion);
for (name, size, parts) in sample_parts() {
for look in LOOKS {
for (speed, checked) in [(0.0, 0.0), (1e4, 0.003), (1e12, 1.0), (f64::NAN, f32::NAN), (f64::INFINITY, 2.0)] {
for w in [1.0, 6.0, 40.0, 333.3] {
let bar = Rect::from_min_size(pos2(50.0, 50.0), vec2(w, wave::HEIGHT));
// The wide strip of nothing keeps "nothing drawn" for the checks that matter.
for _ in 0..2 {
let b = Bar { look, size, parts: &parts, speed, checked };
let out = s.frame(|t, ui| wave::bar(ui, t, Id::unique("bar"), bar, &b));
if w > wave::STROKE {
check(&out, bar.expand(0.6), &format!("bar {name} {look:?} {speed} {w} {motion:?}"));
}
}
}
let ring = Rect::from_min_size(pos2(50.0, 50.0), vec2(24.0, 24.0));
let share = size.map(|s| parts.iter().map(|p| p.done).sum::<u64>() as f32 / s as f32);
let out = s.frame(|t, ui| wave::ring(ui, t, Id::unique("ring"), ring, look, share, speed));
check(&out, ring.expand(0.6), &format!("ring {name} {look:?}"));
}
}
}
}
}
#[test]
fn shapes_graph_and_digits_stay_in_their_place() {
let mut s = Stage::new(Motion::Expressive);
let r = Rect::from_min_size(pos2(50.0, 50.0), vec2(48.0, 48.0));
for i in 0..400 {
let look = LOOKS[(i / 7) % LOOKS.len()];
let kind = Kind::ALL[(i / 11) % Kind::ALL.len()];
let out = s.frame(|t, ui| {
shape::badge(ui, t, Id::unique("badge"), r, kind, look);
shape::loading(ui, t, Id::unique("load"), r);
});
check(&out, r.expand(r.width() * 0.3), "shapes");
}
let r = Rect::from_min_size(pos2(50.0, 50.0), vec2(300.0, 80.0));
let mut h = History::new(20);
for v in [0.0, f64::NAN, 1e15, 3.0, 0.0, 1e6] {
for _ in 0..12 {
h.push(v);
// Samples beyond the edges are cut off by the clip.
let out = s.frame(|t, ui| { graph::graph(ui, t, Id::unique("graph"), r, &h, Some(v)); });
for c in &out.shapes {
walk(&c.shape, &mut |p| assert!(p.x.is_finite() && p.y >= r.top() - 2.0 && p.y <= r.bottom() + 2.0, "{p:?}"));
}
let at = s.frame(|_, ui| { odometer::odometer(ui, Id::unique("odo"), pos2(60.0, 60.0), &odometer::rate(v), medlar_app::fonts::semi(45.0), Color32::WHITE); });
assert!(!at.shapes.is_empty());
}
}
}
#[test]
fn still_things_draw_no_frames() {
for motion in [Motion::Off, Motion::Reduced, Motion::Normal, Motion::Expressive] {
let mut s = Stage::new(motion);
let parts = [part(0, 100, 60), part(100, 400, 10)];
let draw = |look: Look, speed: f64| {
move |t: &Theme, ui: &mut Ui| {
let r = Rect::from_min_size(pos2(50.0, 50.0), vec2(300.0, wave::HEIGHT));
let b = Bar { look, size: Some(400), parts: &parts, speed, checked: 0.5 };
wave::bar(ui, t, Id::unique("bar"), r, &b);
wave::ring(ui, t, Id::unique("ring"), r.translate(vec2(0.0, 40.0)), look, Some(0.3), speed);
let blocks = parts.map(|part| Block { part, speed, server: None, failed: false });
parts::map(ui, t, Id::unique("map"), r.translate(vec2(0.0, 80.0)), 400, &blocks);
odometer::speed(ui, t, Id::unique("speed"), pos2(50.0, 200.0), speed);
}
};
for (look, speed) in [(Look::Running, 0.0), (Look::Paused, 5e6), (Look::Waiting, 0.0), (Look::Failed, 0.0), (Look::Checking, 0.0), (Look::Done, 0.0)] {
// From a lively start.
for _ in 0..90 {
s.frame(draw(Look::Running, 2e7));
}
let moving = asks_now(&s.frame(draw(Look::Running, 2e7)));
assert_eq!(moving, matches!(motion, Motion::Normal | Motion::Expressive), "{motion:?} at speed, before {look:?}: {:?}", s.ctx.repaint_causes());
s.rest(draw(look, speed));
// At rest it stays at rest.
for _ in 0..5 {
assert!(!asks_now(&s.frame(draw(look, speed))), "{motion:?} {look:?}");
}
}
}
}
#[test]
fn a_still_bar_is_flat() {
let r = Rect::from_min_size(pos2(50.0, 50.0), vec2(300.0, wave::HEIGHT));
let height = |motion, speed| {
let mut s = Stage::new(motion);
let parts = [part(0, 400, 300)];
let out = s.frame(|t, ui| wave::bar(ui, t, Id::unique("bar"), r, &Bar { look: Look::Running, size: Some(400), parts: &parts, speed, checked: 0.0 }));
let mut ys = egui::Rangef::NOTHING;
for c in &out.shapes {
walk(&c.shape, &mut |p| ys = egui::Rangef::new(ys.min.min(p.y), ys.max.max(p.y)));
}
ys.span()
};
let flat = height(Motion::Normal, 0.0);
assert!(flat <= wave::STROKE + 1.1, "{flat}");
assert_eq!(height(Motion::Reduced, 1e8), flat);
assert_eq!(height(Motion::Off, 1e8), flat);
assert!(height(Motion::Normal, 1e4) > flat + 1.0 && height(Motion::Normal, 1e8) > height(Motion::Normal, 1e4) + 1.0);
}
#[test]
fn the_tick_plays_once_and_can_be_interrupted() {
let r = Rect::from_min_size(pos2(50.0, 50.0), vec2(48.0, 48.0));
// The tick leaves out the corner of the square.
let corner = |out: &egui::FullOutput| {
let mut far = f32::MAX;
for c in &out.shapes {
walk(&c.shape, &mut |p| far = far.min(p.distance(r.left_top())));
}
far
};
let mut s = Stage::new(Motion::Normal);
let draw = |look| move |t: &Theme, ui: &mut Ui| shape::badge(ui, t, Id::unique("badge"), r, Kind::Video, look);
let frames = |s: &mut Stage, look, n| (0..n).map(|_| corner(&s.frame(draw(look)))).last().unwrap();
// Already done when it comes into view: no tick.
let plain = frames(&mut s, Look::Done, 60);
let mut s = Stage::new(Motion::Normal);
assert!((frames(&mut s, Look::Running, 30) - plain).abs() < 0.5);
let tick = frames(&mut s, Look::Done, 70);
assert!(tick > plain + 2.0, "a tick: {tick} {plain}");
assert!((frames(&mut s, Look::Done, 200) - plain).abs() < 0.5, "once");
assert_eq!(s.rest(draw(Look::Done)), 0);
frames(&mut s, Look::Running, 60);
frames(&mut s, Look::Done, 40);
assert!((frames(&mut s, Look::Waiting, 60) - plain).abs() < 0.5, "interrupted");
}
#[test]
fn a_split_moves_smoothly() {
let mut s = Stage::new(Motion::Normal);
let mut sim = Sim::default();
let r = Rect::from_min_size(pos2(50.0, 50.0), vec2(400.0, wave::HEIGHT));
let bar = |s: &mut Stage, sim: &Sim| s.frame(|t, ui| wave::bar(ui, t, Id::unique("bar"), r, &Bar { look: Look::Paused, size: Some(sim.size), parts: &sim.parts, speed: 0.0, checked: 0.0 }));
bar(&mut s, &sim);
assert!(!asks_now(&bar(&mut s, &sim)));
sim.split();
assert!(asks_now(&bar(&mut s, &sim)), "glides");
for _ in 0..300 {
check(&bar(&mut s, &sim), r.expand(0.6), "split");
}
assert!(!asks_now(&bar(&mut s, &sim)));
sim.hand_over();
sim.hand_over();
sim.merge();
for _ in 0..300 {
check(&bar(&mut s, &sim), r.expand(0.6), "merge");
}
assert!(!asks_now(&bar(&mut s, &sim)));
}
#[test]
fn the_slider_follows_pointer_and_keys() {
let mut app = None;
let mut h = Harness::builder().with_size(vec2(400.0, 100.0)).build_ui_state(
move |ui, v: &mut f32| {
let app = app.get_or_insert_with(|| App::new(ui.ctx(), settings(Motion::Normal), Sources { caelestia: "/x".into(), kde: "/x".into() }));
app.frame(ui, |app, ui| { wave::slider(ui, &app.theme.clone(), 208.0, v, 0.0, "Limit"); });
},
0.5,
);
h.run_steps(60);
use egui_kittest::kittest::Queryable;
let r = h.get_by_label("Limit").rect();
let at = |share: f32| pos2(r.left() + 4.0 + share * 200.0, r.center().y);
h.drag_at(at(0.5));
h.run_steps(2);
h.hover_at(at(0.75));
h.run_steps(2);
assert!((h.state() - 0.75).abs() < 0.01, "{}", h.state());
h.hover_at(pos2(2000.0, 0.0));
h.run_steps(2);
assert_eq!(*h.state(), 1.0);
h.drop_at(pos2(2000.0, 0.0));
h.run_steps(60);
h.key_press(egui::Key::ArrowLeft);
h.run_steps(60);
assert!((h.state() - 0.98).abs() < 1e-4, "{}", h.state());
// A press elsewhere jumps there.
h.drag_at(at(0.2));
h.run_steps(2);
assert!((h.state() - 0.2).abs() < 0.01, "{}", h.state());
}
#[test]
fn the_gallery_draws() {
let mut s = Stage::new(Motion::Normal);
let input = || egui::RawInput { screen_rect: Some(Rect::from_min_size(pos2(0.0, 0.0), vec2(800.0, 700.0))), ..Default::default() };
for draw in [gallery::gallery, gallery::states] {
let mut out = s.ctx.run_ui(input(), |ui| s.app.frame(ui, draw));
out.textures_delta.clear();
assert!(out.shapes.len() > 20);
}
}
#[test]
fn sequence() {
let Ok(dir) = std::env::var("MEDLAR_SEQUENCE") else { return };
std::fs::create_dir_all(&dir).unwrap();
let mut app = None;
let mut h = Harness::builder().with_size(vec2(360.0, 150.0)).with_step_dt(1.0 / 60.0).wgpu().build_ui_state(
move |ui, sim: &mut Sim| {
if app.is_none() {
app = Some(App::new(ui.ctx(), settings(Motion::Normal), Sources { caelestia: "/x".into(), kde: "/x".into() }));
return ui.ctx().request_repaint();
}
app.as_mut().unwrap().frame(ui, |app, ui| {
let t = app.theme.clone();
sim.tick(1.0 / 60.0);
let r = Rect::from_min_size(pos2(16.0, 16.0), vec2(328.0, wave::HEIGHT));
let b = Bar { look: sim.look, size: Some(sim.size), parts: &sim.parts, speed: sim.speed(), checked: sim.checked };
wave::bar(ui, &t, Id::unique("bar"), r, &b);
let blocks: Vec<Block> = sim.parts.iter().map(|p| Block { part: *p, speed: sim.speed(), server: None, failed: false }).collect();
parts::map(ui, &t, Id::unique("map"), r.translate(vec2(0.0, 24.0)).with_max_y(72.0), sim.size, &blocks);
let at = Rect::from_min_size(pos2(16.0, 88.0), vec2(48.0, 48.0));
shape::badge(ui, &t, Id::unique("badge"), at, Kind::Archive, sim.look);
odometer::speed(ui, &t, Id::unique("speed"), pos2(80.0, 112.0), sim.speed());
});
},
Sim::default(),
);
h.run_steps(30);
let mut n = 0;
let mut play = |h: &mut Harness<Sim>, frames: usize, every: usize| {
for i in 0..frames {
h.step();
if i % every == 0 {
h.render().unwrap().save(format!("{dir}/{n:03}.png")).unwrap();
n += 1;
}
}
};
h.state_mut().split();
play(&mut h, 18, 3);
h.state_mut().split();
h.state_mut().scrub = 0.9;
play(&mut h, 12, 3);
h.state_mut().hand_over();
play(&mut h, 18, 3);
h.state_mut().finish();
play(&mut h, 60, 6);
play(&mut h, 70, 14);
}
/// CPU time of this thread in ms, whatever else the PC is doing. It steps by about 1 ms: good for sums.
fn cpu() -> f64 {
let stat = std::fs::read_to_string("/proc/thread-self/schedstat").unwrap();
stat.split(' ').next().unwrap().parse::<f64>().unwrap() / 1e6
}
/// 200 lively bars of eight parts each.
#[test]
#[ignore = "measures: run it in release"]
fn cost() {
let mut s = Stage::new(Motion::Normal);
let mut parts: Vec<Part> = (0..8).map(|i| part(i * 1000, i * 1000 + 1000, 200 + i * 50)).collect();
const FRAMES: usize = 600;
let (mut all, mut ours) = (0.0, 0.0);
for i in 0..FRAMES + 30 {
parts.iter_mut().for_each(|p| p.done = (p.done + 1).min(990));
let begin = cpu();
let out = s.frame(|t, ui| {
for i in 0..200 {
let at = pos2(10.0 + (i % 2) as f32 * 490.0, 10.0 + (i / 2) as f32 * 9.8);
let b = Bar { look: Look::Running, size: Some(8000), parts: &parts, speed: 2e7, checked: 0.0 };
wave::bar(ui, t, Id::unique(("bar", i)), Rect::from_min_size(at, vec2(480.0, wave::HEIGHT)), &b);
}
});
let made = cpu();
let drawn = s.ctx.tessellate(out.shapes, 1.0);
assert!(!drawn.is_empty());
// The first frames warm up.
if i >= 30 {
all += cpu() - begin;
ours += made - begin;
}
}
let per = |sum: f64| sum / FRAMES as f64;
println!("200 bars: {:.2} ms CPU per frame, {:.2} without egui's tessellation", per(all), per(ours));
if !cfg!(debug_assertions) {
assert!(per(all) < 4.0);
}
}