Skip to main content

frus_test/
lib.rs

1//! `frus-test` — the framework's test tooling (§13 of the design notes).
2//!
3//! Three levels, from the least integrated to the most:
4//!
5//! 1. **Pure `update`**: nothing to supply — the Elm architecture makes state
6//!    testable with neither GPU nor window (`assert_eq!` on the struct after a
7//!    message). This crate plays no part.
8//! 2. **Scene and widget snapshots**: [`render_scene`] and [`render_widget`]
9//!    render offscreen, through the same pipeline as the window, and return a
10//!    [`Snapshot`] that can be queried pixel by pixel.
11//! 3. **Goldens**: [`Snapshot::assert_golden`] compares against a reference PNG on
12//!    disk. When it is missing, it is created — read it over, then commit it;
13//!    `FRUS_UPDATE_GOLDENS=1` regenerates it.
14//! 4. **A frame loop**: [`Stage`] holds the retained state and steps it the way the
15//!    shell does, for the widgets whose picture is a gesture in flight — a swipe
16//!    half-done, a pull past the top, a page between two pages — rather than a
17//!    function of their arguments.
18//!
19//! Goldens depend on the rasteriser, text antialiasing varying from one GPU to
20//! another, so generate and compare them **in the same environment** — here,
21//! llvmpipe under WSL, which is deterministic. With no GPU adapter the render
22//! functions return `None` and the tests skip cleanly.
23
24#![deny(missing_docs)]
25
26// The README's example is compiled by `cargo test --doc`, so it cannot rot.
27#[cfg(doctest)]
28#[doc = include_str!("../README.md")]
29pub struct ReadmeDoctests;
30
31use std::path::Path;
32
33use frus_core::{Color, Scene, Size};
34use frus_widgets::{build_deferred, build_ui, Runtime, Theme, Ui, Widget};
35
36/// A rendered frame: sRGB RGBA bytes, origin at the top left.
37pub struct Snapshot {
38    /// The frame's width, in pixels.
39    pub width: u32,
40    /// The frame's height, in pixels.
41    pub height: u32,
42    /// The pixel data, four bytes per pixel, row-major from the top-left corner.
43    pub rgba: Vec<u8>,
44}
45
46/// Renders a [`Scene`] offscreen on a `clear` background. `None` with no GPU.
47pub fn render_scene(scene: &Scene, width: u32, height: u32, clear: Color) -> Option<Snapshot> {
48    let frame = frus_gpu::render_offscreen(scene, width, height, clear)?;
49    Some(Snapshot {
50        width: frame.width,
51        height: frame.height,
52        rgba: frame.rgba,
53    })
54}
55
56/// Builds and renders a **widget tree** the way the shell would: layout through
57/// taffy, then painting with the given theme, on a `theme.background` background, in
58/// a virtual `width`×`height` window. The retained state is neutral: no hover, no
59/// focus, scroll at zero. `None` with no GPU.
60pub fn render_widget<Msg: Clone + 'static>(
61    root: &dyn Widget<Msg>,
62    width: u32,
63    height: u32,
64    theme: &Theme,
65) -> Option<Snapshot> {
66    let mut stage = Stage::new(width, height).theme(theme.clone());
67    stage.settle(root);
68    stage.render(root)
69}
70
71/// A frame-by-frame harness: the retained state the shell holds, plus a way to step
72/// it forward the way the shell's loop does.
73///
74/// [`render_widget`] renders one settled frame, which is the right picture for a
75/// widget whose appearance follows from its arguments. It is the wrong picture — or
76/// no picture at all — for the ones whose appearance follows from **a gesture in
77/// flight**: a swipe half-done, a pull past the top edge, a glow where a list hit its
78/// end. None of that is in the widget; it is in the [`Runtime`], and the shell is
79/// what puts it there.
80///
81/// A `Stage` puts it there instead, through the same entry points the shell uses
82/// (`refresh_pull`, `dismiss_drag`, `glow_pull`, …), so a widget can be caught
83/// mid-motion and photographed:
84///
85/// ```ignore
86/// let mut stage = Stage::new(300, 200);
87/// let id = stage.build(&root).scroll_regions()[0].id;
88/// stage.runtime.glow_pull(id, Some(OverscrollIndicator::Glow), GlowEdge::Top, 60.0, 200.0, 0.0, 300.0);
89/// stage.advance(&root, 1.0 / 60.0);
90/// stage.render(&root).unwrap().assert_golden(path);
91/// ```
92pub struct Stage {
93    /// The retained state. Every field on it is public, so a test that needs a state
94    /// no method here reaches can set it by hand — that is the escape hatch, not the
95    /// first resort.
96    pub runtime: Runtime,
97    /// The theme every frame is built and painted with.
98    pub theme: Theme,
99    width: u32,
100    height: u32,
101}
102
103impl Stage {
104    /// A stage for a `width`×`height` window, on the dark theme, under the scroll
105    /// behaviour an application has unless it says otherwise — put at the root, as the
106    /// shell puts the application's.
107    pub fn new(width: u32, height: u32) -> Self {
108        frus_widgets::ScrollConfiguration::set_root(frus_widgets::ScrollBehavior::material());
109        Self {
110            runtime: Runtime::default(),
111            theme: Theme::dark().with_platform(frus_core::TargetPlatform::Linux),
112            width,
113            height,
114        }
115    }
116
117    /// Paints on `theme` instead.
118    pub fn theme(mut self, theme: Theme) -> Self {
119        self.theme = theme;
120        self
121    }
122
123    /// The window size, in logical pixels.
124    pub fn size(&self) -> Size {
125        Size::new(self.width as f32, self.height as f32)
126    }
127
128    /// Builds the tree against the current retained state — the way to reach a
129    /// widget's identity (`scroll_regions`, `dismissables`, `refresh_areas`) before
130    /// putting a gesture on it.
131    pub fn build<'a, Msg: Clone + 'static>(&'a self, root: &'a dyn Widget<Msg>) -> Ui<Msg> {
132        // The steps the shell takes around a build, so a tree with components in it — an
133        // application made of them — is laid out as it would be in a window: the components
134        // marked as reached and built before anything asks for their children, and the ones
135        // no longer reached let go.
136        self.runtime.states.begin_build();
137        build_deferred(root, &self.theme, &self.runtime);
138        let ui = build_ui(root, self.size(), &self.runtime, &self.theme);
139        self.runtime.states.end_frame();
140        ui
141    }
142
143    /// One turn of the shell's loop: builds the tree, then advances every family of
144    /// retained motion by `dt`. Returns whether anything is still moving, which is
145    /// what the shell asks to decide if it needs another frame.
146    ///
147    /// `dt` of zero is not a no-op — it is the **first frame**, where a widget seen
148    /// for the first time adopts its target rather than sliding in from zero. See
149    /// [`Stage::settle`].
150    pub fn advance<Msg: Clone + 'static>(&mut self, root: &dyn Widget<Msg>, dt: f32) -> bool {
151        let (regions, refresh_areas, dismissables, interactive, sheets) = {
152            let ui = self.build(root);
153            (
154                ui.scroll_regions().to_vec(),
155                ui.refresh_areas().to_vec(),
156                ui.dismissables().to_vec(),
157                ui.interactive_bounds(),
158                ui.sheets().to_vec(),
159            )
160        };
161        self.runtime.time += dt;
162        self.runtime.sync_pages(&regions);
163        let (dismiss_moving, _dismissed) = self.runtime.advance_dismiss(&dismissables, dt);
164        let (sheets_moving, _closed) = self.runtime.advance_sheets(&sheets, dt);
165        // A throw that carried a sheet to full height goes on into its list, as the shell
166        // does it.
167        let mut handed = false;
168        for (list, velocity) in self.runtime.take_sheet_handovers() {
169            if let Some(area) = regions.iter().find(|area| area.id == list) {
170                handed |= self
171                    .runtime
172                    .fling_scroll(*area, area.physics, (0.0, velocity));
173            }
174        }
175        // `|` and not `||`: every family must be stepped, whatever an earlier one
176        // answered. This is the shell's own list, in the shell's own order.
177        self.runtime.advance(dt)
178            | self.runtime.advance_leaving(dt)
179            | self.runtime.advance_switchers(root, dt)
180            | self.runtime.advance_values(root, dt)
181            | self.runtime.advance_colors(root, dt)
182            | self.runtime.advance_sizes(root, dt)
183            | self.runtime.advance_radii(root, dt)
184            | self.runtime.advance_paddings(root, dt)
185            | self.runtime.advance_offsets(root, dt)
186            | self.runtime.advance_pins(root, dt)
187            | self.runtime.advance_fractions(root, dt)
188            | self.runtime.advance_text_styles(root, dt)
189            | self.runtime.advance_transforms(root, dt)
190            | self.runtime.advance_scroll(&regions, dt)
191            | self.runtime.advance_glow(dt)
192            | self.runtime.advance_refresh(&refresh_areas, dt)
193            | self.runtime.advance_interactive(&interactive, dt)
194            | dismiss_moving
195            | sheets_moving
196            | handed
197    }
198
199    /// The shell's **first** frame: every implicit animation adopts its target with
200    /// no transition. A switch that is on is drawn on, a drawer declared open is
201    /// drawn open.
202    pub fn settle<Msg: Clone + 'static>(&mut self, root: &dyn Widget<Msg>) {
203        self.advance(root, 0.0);
204    }
205
206    /// Advances by `dt` `steps` times — a gesture playing out rather than a jump to
207    /// its end, which is the point of having a frame loop at all.
208    pub fn advance_by<Msg: Clone + 'static>(
209        &mut self,
210        root: &dyn Widget<Msg>,
211        dt: f32,
212        steps: usize,
213    ) {
214        for _ in 0..steps {
215            self.advance(root, dt);
216        }
217    }
218
219    /// Renders the current frame. `None` with no GPU adapter, so a test can skip.
220    pub fn render<Msg: Clone + 'static>(&self, root: &dyn Widget<Msg>) -> Option<Snapshot> {
221        let ui = self.build(root);
222        render_scene(ui.scene(), self.width, self.height, self.theme.background)
223    }
224}
225
226impl Snapshot {
227    /// The pixel at `(x, y)`, in RGBA.
228    pub fn pixel(&self, x: u32, y: u32) -> [u8; 4] {
229        assert!(x < self.width && y < self.height, "pixel out of frame");
230        let i = ((y * self.width + x) * 4) as usize;
231        [
232            self.rgba[i],
233            self.rgba[i + 1],
234            self.rgba[i + 2],
235            self.rgba[i + 3],
236        ]
237    }
238
239    /// How many pixels have at least one RGB channel above `threshold` — that is,
240    /// "something is drawn here".
241    pub fn lit_pixels(&self, threshold: u8) -> usize {
242        self.rgba
243            .as_chunks::<4>()
244            .0
245            .iter()
246            .filter(|px| px[0] > threshold || px[1] > threshold || px[2] > threshold)
247            .count()
248    }
249
250    /// How many pixels differ from `other` by more than `channel_tolerance` on at
251    /// least one RGBA channel. Panics when the sizes differ.
252    pub fn diff_count(&self, other: &Snapshot, channel_tolerance: u8) -> usize {
253        assert_eq!(
254            (self.width, self.height),
255            (other.width, other.height),
256            "the snapshots have different sizes"
257        );
258        self.rgba
259            .as_chunks::<4>()
260            .0
261            .iter()
262            .zip(other.rgba.as_chunks::<4>().0.iter())
263            .filter(|(a, b)| {
264                a.iter()
265                    .zip(b.iter())
266                    .any(|(ca, cb)| ca.abs_diff(*cb) > channel_tolerance)
267            })
268            .count()
269    }
270
271    /// Writes the frame to `path` as a PNG, creating the folder if it is missing.
272    ///
273    /// The goldens use this internally; it is public because a rendered frame is
274    /// useful outside a test too — the pictures in the README are made this way, so
275    /// that they can be regenerated rather than re-photographed.
276    pub fn write_png(&self, path: impl AsRef<Path>) {
277        write_png(path.as_ref(), self);
278    }
279
280    /// Compares against the golden at `path`, a PNG whose path is typically built
281    /// with `concat!(env!("CARGO_MANIFEST_DIR"), "/tests/goldens/…")`.
282    ///
283    /// - a missing golden is **created** — read it over, then commit it;
284    /// - `FRUS_UPDATE_GOLDENS=1` rewrites it;
285    /// - a difference beyond (`channel_tolerance` per channel, `max_diff_pixels`
286    ///   pixels) panics, writing `<name>.actual.png` alongside for visual
287    ///   comparison.
288    pub fn assert_golden(&self, path: impl AsRef<Path>) {
289        self.assert_golden_with(path, 2, 0);
290    }
291
292    /// The parameterised variant of [`Snapshot::assert_golden`].
293    pub fn assert_golden_with(
294        &self,
295        path: impl AsRef<Path>,
296        channel_tolerance: u8,
297        max_diff_pixels: usize,
298    ) {
299        let path = path.as_ref();
300        let update = std::env::var_os("FRUS_UPDATE_GOLDENS").is_some_and(|v| v == "1");
301        if update || !path.exists() {
302            write_png(path, self);
303            if !update {
304                eprintln!(
305                    "golden created: {} — read it over, then commit it",
306                    path.display()
307                );
308            }
309            return;
310        }
311
312        let golden = read_png(path);
313        if (golden.width, golden.height) != (self.width, self.height) {
314            let actual = actual_path(path);
315            write_png(&actual, self);
316            panic!(
317                "golden {}: size {}×{} ≠ rendered {}×{} (the rendering was written to {})",
318                path.display(),
319                golden.width,
320                golden.height,
321                self.width,
322                self.height,
323                actual.display()
324            );
325        }
326        let diff = self.diff_count(&golden, channel_tolerance);
327        if diff > max_diff_pixels {
328            let actual = actual_path(path);
329            write_png(&actual, self);
330            panic!(
331                "golden {}: {diff} pixel(s) differ (tolerance {max_diff_pixels}) — the \
332                 rendering was written to {}; rerun with FRUS_UPDATE_GOLDENS=1 to accept it",
333                path.display(),
334                actual.display()
335            );
336        }
337    }
338}
339
340/// `<folder>/<name>.actual.png`, alongside the golden.
341fn actual_path(golden: &Path) -> std::path::PathBuf {
342    golden.with_extension("actual.png")
343}
344
345fn write_png(path: &Path, snapshot: &Snapshot) {
346    if let Some(parent) = path.parent() {
347        std::fs::create_dir_all(parent).expect("creating the goldens folder");
348    }
349    let file =
350        std::fs::File::create(path).unwrap_or_else(|e| panic!("creating {}: {e}", path.display()));
351    let mut encoder = png::Encoder::new(
352        std::io::BufWriter::new(file),
353        snapshot.width,
354        snapshot.height,
355    );
356    encoder.set_color(png::ColorType::Rgba);
357    encoder.set_depth(png::BitDepth::Eight);
358    let mut writer = encoder.write_header().expect("PNG header");
359    writer
360        .write_image_data(&snapshot.rgba)
361        .expect("writing the PNG");
362}
363
364fn read_png(path: &Path) -> Snapshot {
365    let file =
366        std::fs::File::open(path).unwrap_or_else(|e| panic!("reading {}: {e}", path.display()));
367    let decoder = png::Decoder::new(std::io::BufReader::new(file));
368    let mut reader = decoder.read_info().expect("PNG info");
369    let mut buf = vec![0; reader.output_buffer_size()];
370    let info = reader.next_frame(&mut buf).expect("PNG frame");
371    assert_eq!(
372        info.color_type,
373        png::ColorType::Rgba,
374        "the golden is not RGBA"
375    );
376    buf.truncate(info.buffer_size());
377    Snapshot {
378        width: info.width,
379        height: info.height,
380        rgba: buf,
381    }
382}
383
384#[cfg(test)]
385mod tests {
386    use frus_core::Size;
387    use frus_widgets::{
388        build_ui, button, row, text, Align, Card, Checkbox, Container, Flex, Icon, Icons, Runtime,
389        Theme, Widget,
390    };
391
392    /// Batching has to survive contact with a real widget tree, or the fix for
393    /// milestone 291 would have traded a rendering bug for a frame-time one.
394    ///
395    /// This is a screen shaped like the ones frus draws: a card, rows, buttons with
396    /// icons — rectangles and paths alternating all the way down. If the planner is
397    /// sound, near enough all of them share two draw calls, because a button's
398    /// background does not cover the previous button's icon. If it ever needs one per
399    /// widget, this test says so long before a phone does.
400    #[test]
401    fn a_real_screen_still_batches() {
402        let mut rows: Vec<Box<dyn Widget<()>>> = Vec::new();
403        for i in 0..12 {
404            rows.push(Box::new(
405                row![
406                    Checkbox::new(i % 2 == 0),
407                    text(format!("Task number {i}")).size(15.0),
408                    Container::new().flex(1.0),
409                    Icon::new(Icons::CLOSE).size(16.0),
410                    button("Open", ()),
411                ]
412                .gap(12.0)
413                .align(Align::Center)
414                .height(48.0),
415            ));
416        }
417        let mut list = Flex::column().gap(8.0);
418        for r in rows {
419            list = list.child_boxed(r);
420        }
421        let screen = Container::new()
422            .width(400.0)
423            .height(800.0)
424            .padding(16.0)
425            .child(Card::new().padding(12.0).child(list));
426
427        let ui = build_ui(
428            &screen,
429            Size::new(400.0, 800.0),
430            &Runtime::default(),
431            &Theme::default().with_platform(frus_core::TargetPlatform::Linux),
432        );
433        let calls = frus_gpu::draw_calls(ui.scene());
434        let primitives = ui.scene().primitives().len();
435        // Three today — the card's rectangles, the ticks and icons above them, and
436        // the buttons above those. The bound has a little room so that an honest
437        // extra level does not fail the build, and none at all for one call a widget.
438        assert!(
439            calls <= 4,
440            "{calls} draw calls for {primitives} primitives: batching broke down"
441        );
442    }
443}