icedwright 0.0.1

The icedwright test harness: run an iced 0.14 program headlessly on virtual time
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
//! Visual snapshots on the harness: rendering with the caret hidden, waiting for a stable
//! frame, cropping, masking and comparing with the baseline.

use std::path::{Path, PathBuf};

use iced_core::{Event, theme, window};
use icedwright_check::actionability::visible_part;
use icedwright_check::snapshot::{PixelMask, Rgba, crop_to_node, mask};
use icedwright_locator::{AnyRole, Locator, RoleKind};
use icedwright_probe::CaretClock;
use icedwright_semantics::{Kind, Node, OperationKind, SemanticTree, Value};
use icedwright_types::role::Capabilities;
use icedwright_types::units::{Logical, Physical};
use icedwright_types::{Frame, Point, Rect};

use super::baseline::{Finish, Target, judge, read_baseline, writes};
use super::env::SnapshotEnv;
use super::png::{PngMetadata, encode_png};
use super::{Caret, RenderOptions, Screenshot, SnapshotError};
use crate::error::{HarnessError, Result};
use crate::harness::{DiagnosticKind, Handle, Harness, Severity, TestProgram};

/// How many frames a render may keep changing before the snapshot gives up.
pub(crate) const STABLE_FRAMES: u32 = 120;

/// How a focused field's caret can be kept out of a snapshot.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum CaretKind {
    /// The caret follows the virtual clock, so it is the same on every run.
    VirtualClock,
    /// An iced text input or editor, which draws no caret while the window is unfocused.
    Unfocus,
    /// A widget the unfocus trick is not known to reach, which is masked instead.
    Unknown,
}

/// How a focused field's caret is handled, from what the tree knows of it.
pub(crate) fn caret_kind(node: &Node) -> CaretKind {
    if node.props.get(CaretClock::PROP).map(String::as_str) == Some(CaretClock::Probe.as_str()) {
        return CaretKind::VirtualClock;
    }
    let built_in = matches!(
        node.kind,
        Kind::Inferred(OperationKind::TextInput | OperationKind::Focusable)
    ) || (matches!(node.kind, Kind::Annotated(_))
        && node.sources.inferred
        && !node.sources.component);
    if built_in {
        CaretKind::Unfocus
    } else {
        CaretKind::Unknown
    }
}

/// Focused nodes that take text, which are the ones with a caret.
pub(crate) fn focused_fields(tree: &SemanticTree) -> impl Iterator<Item = &Node> {
    tree.iter().filter(|node| {
        node.states.focused == Some(true)
            && node.role.capabilities().contains(Capabilities::EDITABLE)
    })
}

/// What a caret setting does to one window's render: whether to send the unfocus events, which
/// regions to mask with a note for each, or why the render is refused.
#[derive(Debug, Clone, PartialEq)]
pub(crate) struct CaretPlan {
    pub unfocus: bool,
    pub masks: Vec<(Logical<Rect>, String)>,
}

pub(crate) fn caret_plan(tree: &SemanticTree, caret: Caret) -> Result<CaretPlan, SnapshotError> {
    let mut plan = CaretPlan {
        unfocus: false,
        masks: Vec::new(),
    };
    for node in focused_fields(tree) {
        match (caret, caret_kind(node)) {
            (_, CaretKind::VirtualClock) => {}
            (Caret::Show, _) => {
                return Err(SnapshotError::CaretOnRealClock {
                    node: node.path.to_string(),
                });
            }
            (Caret::Hide, CaretKind::Unfocus) => plan.unfocus = true,
            (Caret::Hide, CaretKind::Unknown) => {
                if let Some(bounds) = visible_part(node) {
                    plan.masks.push((
                        Logical(bounds),
                        format!(
                            "{} is focused and its caret may read the real clock, so it was masked",
                            node.path
                        ),
                    ));
                }
            }
        }
    }
    Ok(plan)
}

/// A frame with its masks painted in, and what the report should say about it.
#[derive(Debug, Clone)]
pub(crate) struct Shot {
    pub frame: Frame,
    pub mask: PixelMask,
    pub notes: Vec<String>,
    pub metadata: PngMetadata,
}

/// The region `clip` covers in whole physical pixels, as `Frame::crop` cuts it, as its corner.
fn clip_origin(frame: &Frame, clip: Logical<Rect>) -> (Physical<Point<u32>>, bool) {
    let rect = clip.get();
    let scale = frame.scale().get();
    let size = frame.size().get();
    let left = (rect.x * scale).floor();
    let top = (rect.y * scale).floor();
    let right = ((rect.x + rect.width) * scale).ceil();
    let bottom = ((rect.y + rect.height) * scale).ceil();
    let clamped =
        left < 0.0 || top < 0.0 || right > size.width as f32 || bottom > size.height as f32;
    let origin = Point::new(
        left.clamp(0.0, size.width as f32) as u32,
        top.clamp(0.0, size.height as f32) as u32,
    );
    (Physical::new(origin), clamped)
}

/// The frame with a one-pixel outline around `region`, for full-frame element screenshots.
pub(crate) fn outline(frame: &Frame, region: Logical<Rect>, colour: Rgba) -> Result<Frame> {
    let rect = region.get();
    let scale = frame.scale().get();
    let size = frame.size().get();
    let (width, height) = (size.width, size.height);
    if width == 0 || height == 0 {
        return Ok(frame.clone());
    }
    let clamp_x = |v: f32| (v.max(0.0) as u32).min(width - 1);
    let clamp_y = |v: f32| (v.max(0.0) as u32).min(height - 1);
    let left = clamp_x((rect.x * scale).floor());
    let top = clamp_y((rect.y * scale).floor());
    let right = clamp_x(((rect.x + rect.width) * scale).ceil() - 1.0);
    let bottom = clamp_y(((rect.y + rect.height) * scale).ceil() - 1.0);
    let mut rgba = frame.rgba().to_vec();
    let mut paint = |x: u32, y: u32| {
        let at = (y as usize * width as usize + x as usize) * 4;
        if let Some(pixel) = rgba.get_mut(at..at + 4) {
            pixel.copy_from_slice(&colour.0);
        }
    };
    for x in left..=right {
        paint(x, top);
        paint(x, bottom);
    }
    for y in top..=bottom {
        paint(left, y);
        paint(right, y);
    }
    Ok(Frame::new(rgba, frame.size(), frame.scale())?)
}

fn theme_name(mode: theme::Mode) -> &'static str {
    match mode {
        theme::Mode::Light => "light",
        theme::Mode::Dark => "dark",
        theme::Mode::None => "none",
    }
}

/// Where a snapshot taken without a name writes the frames that never settled.
fn unnamed_failure_dir(env: &SnapshotEnv) -> PathBuf {
    let mut dir = env.out_dir.join("snapshots-failed").join(&env.crate_name);
    for part in env.test.as_deref().unwrap_or("unknown").split("::") {
        dir.push(part);
    }
    dir.push("screenshot");
    dir
}

/// Every name and text value in the tree, which is the text the window draws.
pub(crate) fn tree_text(tree: &SemanticTree) -> String {
    let mut text = String::new();
    for node in tree.iter() {
        for part in [
            &node.name,
            &node.placeholder,
            &node.tooltip,
            &node.description,
        ]
        .into_iter()
        .flatten()
        {
            text.push_str(part);
            text.push(' ');
        }
        if let Some(Value::Text(value)) = &node.value {
            text.push_str(value);
            text.push(' ');
        }
    }
    text
}

/// The report's note when the process draws with the machine's fonts.
pub(crate) fn font_mode_note(mode: super::fonts::FontMode) -> Option<String> {
    mode.is_unreliable().then(|| {
        "unreliable: the font database holds this machine's fonts (system_fonts, or no bundled-fonts feature), so this snapshot can differ between machines".to_owned()
    })
}

fn write_png(path: &Path, frame: &Frame) -> Result<()> {
    if let Some(parent) = path.parent() {
        std::fs::create_dir_all(parent)?;
    }
    std::fs::write(path, encode_png(frame, &PngMetadata::new())?)?;
    Ok(())
}

impl<P: TestProgram> Harness<P> {
    /// Draws the window as [`render`](Self::render) does, with the caret hidden unless
    /// `options` shows it. Hiding sends `Unfocused` to the window's widgets before drawing and
    /// `Focused` after, which iced's text inputs and editors answer by drawing no caret, and
    /// which costs one extra frame, the same on every run.
    pub fn render_with(&mut self, window: window::Id, options: &RenderOptions) -> Result<Frame> {
        if options.caret == Caret::Show {
            return self.render_frame_at(window, false, options.scale);
        }
        let tree = self.tree_of(window)?;
        let unfocus = focused_fields(&tree).any(|node| caret_kind(node) == CaretKind::Unfocus);
        if !unfocus {
            return self.render_frame_at(window, false, options.scale);
        }
        self.send_to_widgets(window, &[Event::Window(window::Event::Unfocused)])?;
        let frame = self.render_frame_at(window, false, options.scale);
        self.send_to_widgets(window, &[Event::Window(window::Event::Focused)])?;
        frame
    }

    /// Records a warning, once per window and set of characters, for text in `tree` that no
    /// loaded font covers, and returns the report's note for it.
    fn warn_uncovered(&mut self, window: window::Id, tree: &SemanticTree) -> Option<String> {
        let characters: String = super::fonts::uncovered(&tree_text(tree))
            .into_iter()
            .collect();
        if characters.is_empty() {
            return None;
        }
        let kind = DiagnosticKind::UncoveredGlyphs {
            window,
            characters: characters.clone(),
        };
        if !self.diagnostics().iter().any(|d| d.kind == kind) {
            self.diagnose(Severity::Warning, kind);
        }
        let codes: Vec<String> = characters
            .chars()
            .map(|c| format!("U+{:04X}", u32::from(c)))
            .collect();
        Some(format!(
            "no loaded font covers {}, which draw as the missing-glyph box",
            codes.join(" ")
        ))
    }

    /// Draws the window for a trace with the caret kept out as [`Caret::Hide`] keeps it out of
    /// a snapshot: unfocused for iced's own fields, masked for any other focused field. Unlike
    /// [`render_with`](Self::render_with) it runs no turn, so tracing never changes a test.
    pub(crate) fn render_caret_hidden(&mut self, window: window::Id) -> Result<Frame> {
        let tree = self.tree_of(window)?;
        let plan = caret_plan(&tree, Caret::Hide)?;
        let frame = self.render_frame(window, plan.unfocus)?;
        if plan.masks.is_empty() {
            return Ok(frame);
        }
        let regions: Vec<Logical<Rect>> = plan.masks.into_iter().map(|(rect, _)| rect).collect();
        Ok(mask(
            &frame,
            &regions,
            Physical::new(Point::new(0, 0)),
            Rgba::MASK,
        )?
        .frame)
    }

    /// Renders until two consecutive frames are byte-identical, advancing one frame of
    /// virtual time between renders. On failure the last two frames are written to `dir`.
    pub(crate) fn stable_frame(
        &mut self,
        window: window::Id,
        options: &RenderOptions,
        dir: &Path,
    ) -> Result<Frame> {
        let mut previous = self.render_with(window, options)?;
        for _ in 0..STABLE_FRAMES {
            self.next_frame()?;
            let next = self.render_with(window, options)?;
            if next == previous {
                return Ok(next);
            }
            previous = next;
        }
        self.next_frame()?;
        let last = self.render_with(window, options)?;
        let previous_path = dir.join("previous.png");
        let last_path = dir.join("last.png");
        write_png(&previous_path, &previous)?;
        write_png(&last_path, &last)?;
        Err(SnapshotError::NeverStable {
            frames: STABLE_FRAMES + 1,
            previous: previous_path,
            last: last_path,
        }
        .into())
    }

    /// The window a screenshot of no element is of: the one the options name, or the focused
    /// one.
    fn screenshot_window(&self, options: &Screenshot) -> Result<window::Id> {
        match options.window {
            Some(window) => Ok(window),
            None => Ok(self.focused().ok_or(HarnessError::NoWindow)?),
        }
    }

    /// Takes a screenshot of a window as a visual snapshot would: stable, with the caret
    /// hidden or masked, clipped and masked as `options` says. Needs a process per test.
    pub fn capture(&mut self, options: &Screenshot) -> Result<Frame> {
        let env = SnapshotEnv::current()?;
        env.runner.require("capture")?;
        let dir = unnamed_failure_dir(&env);
        Ok(shoot::<P, AnyRole>(self, options, None, &dir)?.frame)
    }

    /// Compares a window, the focused one unless `options` names another, with the baseline
    /// `name`, retrying until the timeout. A missing or changed baseline fails and writes the
    /// review files; `ICEDWRIGHT_UPDATE=always` writes the baseline instead. Needs a process
    /// per test.
    pub fn to_match_image(&mut self, name: &str, options: &Screenshot) -> Result {
        match_image::<P, AnyRole>(self, name, options, None)
    }
}

impl<P: TestProgram, R: RoleKind> Handle<'_, P, R> {
    /// The window, rendered as a visual snapshot would be, cropped to the node this handle
    /// resolves to, or outlined in the full window with `Screenshot::full_frame`. Needs a
    /// process per test.
    pub fn screenshot(&mut self, options: &Screenshot) -> Result<Frame> {
        let env = SnapshotEnv::current()?;
        env.runner.require("screenshot")?;
        let dir = unnamed_failure_dir(&env);
        let element = (self.locator.clone(), self.window);
        Ok(shoot(self.harness, options, Some(&element), &dir)?.frame)
    }

    /// Compares the node this handle resolves to with the baseline `name`, as
    /// [`Harness::to_match_image`] compares a window.
    pub fn to_match_image(&mut self, name: &str, options: &Screenshot) -> Result {
        let element = (self.locator.clone(), self.window);
        match_image(self.harness, name, options, Some(&element))
    }
}

type Element<R> = (Locator<R>, Option<window::Id>);

/// The node an element locator resolves to now, and its window.
fn resolve_element<P: TestProgram, R: RoleKind>(
    harness: &mut Harness<P>,
    (locator, window): &Element<R>,
) -> Result<(window::Id, Node)> {
    let tree = match window {
        Some(window) => harness.tree_of(*window)?,
        None => harness.tree()?,
    };
    let id = icedwright_locator::resolve(&tree, locator)?;
    let Some(node) = tree.get(id).cloned() else {
        return Err(SnapshotError::Location(
            "the resolved node is missing from its tree".to_owned(),
        )
        .into());
    };
    let window = harness
        .window_of(node.window)
        .ok_or(HarnessError::NoWindow)?;
    Ok((window, node))
}

fn shoot<P: TestProgram, R: RoleKind>(
    harness: &mut Harness<P>,
    options: &Screenshot,
    element: Option<&Element<R>>,
    dir: &Path,
) -> Result<Shot> {
    harness.settle()?;
    let window = match element {
        Some(element) => resolve_element(harness, element)?.0,
        None => harness.screenshot_window(options)?,
    };
    let before = harness.tree_of(window)?;
    caret_plan(&before, options.caret)?;
    let mut render = RenderOptions::new().caret(options.caret);
    render.scale = options.scale;
    let mut frame = harness.stable_frame(window, &render, dir)?;
    let tree = harness.tree_of(window)?;
    let plan = caret_plan(&tree, options.caret)?;
    let mut notes: Vec<String> = Vec::new();
    notes.extend(font_mode_note(super::fonts::mode()));
    notes.extend(harness.warn_uncovered(window, &tree));
    let mut origin = Physical::new(Point::new(0, 0));

    match element {
        Some(element) => {
            let (_, node) = resolve_element(harness, element)?;
            if options.full_frame {
                let region = visible_part(&node).ok_or_else(|| {
                    SnapshotError::from(icedwright_check::CropError::NotVisible {
                        node: node.path.clone(),
                    })
                })?;
                frame = outline(&frame, Logical(region), options.mask_colour)?;
            } else {
                let crop = crop_to_node(&frame, &node).map_err(SnapshotError::from)?;
                if crop.clamped {
                    notes.push(format!(
                        "{} reaches past the window, so the crop was clamped",
                        node.path
                    ));
                }
                origin = crop.origin;
                frame = crop.frame;
            }
        }
        None => {
            if let Some(clip) = options.clip {
                let (corner, clamped) = clip_origin(&frame, clip);
                if clamped {
                    notes.push("the clip reaches past the window, so it was clamped".to_owned());
                }
                frame = frame.crop(clip)?;
                origin = corner;
            }
        }
    }

    let mut regions: Vec<Logical<Rect>> = Vec::new();
    let mut labels: Vec<String> = Vec::new();
    for locator in &options.mask {
        let matches = icedwright_locator::resolve_all(&tree, locator).matches;
        let parts: Vec<Rect> = matches
            .iter()
            .filter_map(|id| tree.get(*id))
            .filter_map(visible_part)
            .collect();
        if parts.is_empty() {
            notes.push(format!("the mask {locator} matched nothing"));
        }
        for part in parts {
            regions.push(Logical(part));
            labels.push(format!("the mask {locator}"));
        }
    }
    for (region, note) in plan.masks {
        regions.push(region);
        labels.push(note.clone());
        notes.push(note);
    }
    let masked = mask(&frame, &regions, origin, options.mask_colour)?;
    for index in masked.missed {
        if let Some(label) = labels.get(index) {
            notes.push(format!("{label} lies outside the screenshot"));
        }
    }

    let info = harness.window_info(window)?;
    let logical = info.logical_size.get();
    let metadata = PngMetadata::new()
        .with(PngMetadata::VERSION, env!("CARGO_PKG_VERSION"))
        .with(PngMetadata::RENDERER, "tiny-skia")
        .with(PngMetadata::THEME, theme_name(info.theme_mode))
        .with(
            PngMetadata::LOGICAL_SIZE,
            format!("{}x{}", logical.width, logical.height),
        )
        .with(
            PngMetadata::FONTS,
            format!("{:016x}", super::fonts::fingerprint()),
        )
        .with(
            PngMetadata::VARIANT,
            options.naming_variant(harness.variant()).to_string(),
        );
    let metadata = if super::fonts::mode().is_unreliable() {
        metadata.with(PngMetadata::FONT_SOURCE, "system")
    } else {
        metadata
    };
    Ok(Shot {
        frame: masked.frame,
        mask: masked.mask,
        notes,
        metadata,
    })
}

fn match_image<P: TestProgram, R: RoleKind>(
    harness: &mut Harness<P>,
    name: &str,
    options: &Screenshot,
    element: Option<&Element<R>>,
) -> Result {
    let env = SnapshotEnv::current()?;
    env.runner.require(&format!("to_match_image({name:?})"))?;
    if options.only.is_some_and(|keep| !keep(harness.variant())) {
        return Ok(());
    }
    let target = Target::new(&env, name, &options.naming_variant(harness.variant()))?;
    let baseline = read_baseline(&target.baseline)?;
    let timeout = options.timeout.unwrap_or(harness.default_timeout());
    let deadline = harness.now() + timeout;
    let began = harness.real_now();
    loop {
        let shot = shoot(harness, options, element, &target.failed)?;
        let diff_options = options.diff_options(shot.mask.clone());
        let verdict = judge(
            baseline.as_ref().map(|b| &b.frame),
            &shot.frame,
            &diff_options,
        );
        let retry = !matches!(
            verdict,
            super::baseline::Verdict::Pass | super::baseline::Verdict::New
        ) && harness.now() < deadline;
        if retry && harness.wait(deadline, began)?.idle_since.is_none() {
            continue;
        }
        let finish = Finish {
            target: &target,
            verdict: verdict.clone(),
            actual: &shot.frame,
            metadata: &shot.metadata,
            baseline: baseline.as_ref(),
            limits: (options.max_diff_pixels, options.max_diff_ratio.get()),
            notes: shot.notes,
        };
        return finish.apply(writes(&verdict, env.update, env.ci));
    }
}