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};
pub(crate) const STABLE_FRAMES: u32 = 120;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum CaretKind {
VirtualClock,
Unfocus,
Unknown,
}
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
}
}
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)
})
}
#[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)
}
#[derive(Debug, Clone)]
pub(crate) struct Shot {
pub frame: Frame,
pub mask: PixelMask,
pub notes: Vec<String>,
pub metadata: PngMetadata,
}
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)
}
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",
}
}
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
}
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
}
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> {
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
}
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(" ")
))
}
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,
®ions,
Physical::new(Point::new(0, 0)),
Rgba::MASK,
)?
.frame)
}
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())
}
fn screenshot_window(&self, options: &Screenshot) -> Result<window::Id> {
match options.window {
Some(window) => Ok(window),
None => Ok(self.focused().ok_or(HarnessError::NoWindow)?),
}
}
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)
}
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> {
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)
}
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>);
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, ®ions, 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));
}
}