icedwright 0.0.1

The icedwright test harness: run an iced 0.14 program headlessly on virtual time
Documentation
//! How a visual snapshot is taken and compared.

use iced_core::window;
use icedwright_check::snapshot::{DiffOptions, PixelMask, Rgba};
use icedwright_locator::{AnyRole, IntoLocator, Locator, RoleKind};
use icedwright_types::units::{Logical, Ratio, ScaleFactor};
use icedwright_types::{Rect, VirtualDuration};

use super::Variant;

/// Whether the focused field's caret is drawn.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum Caret {
    /// Hidden: iced's text inputs and editors are drawn as if the window were unfocused, and
    /// any other focused field is masked. Deterministic for every widget.
    #[default]
    Hide,
    /// Drawn. Only for fields whose caret follows the virtual clock; any other focused field
    /// fails with [`SnapshotError::CaretOnRealClock`](super::SnapshotError::CaretOnRealClock).
    Show,
}

/// How [`Harness::render_with`](crate::Harness::render_with) draws a window.
#[derive(Debug, Clone, Copy, PartialEq, Default)]
#[must_use]
pub struct RenderOptions {
    /// The caret of a focused iced text input or editor.
    pub caret: Caret,
    /// A system scale factor to rasterise at instead of the window's. Layout and the app are
    /// unchanged, so the app never sees `Rescaled`.
    pub scale: Option<ScaleFactor>,
}

impl RenderOptions {
    /// The defaults: the caret hidden, at the window's own scale.
    pub fn new() -> Self {
        Self::default()
    }

    /// Hides or shows the caret.
    pub fn caret(mut self, caret: Caret) -> Self {
        self.caret = caret;
        self
    }

    /// Rasterises at `factor` instead of the window's system scale factor.
    pub fn scale(mut self, factor: ScaleFactor) -> Self {
        self.scale = Some(factor);
        self
    }
}

const DEFAULT_THRESHOLD: Ratio = match Ratio::new(0.1) {
    Ok(ratio) => ratio,
    Err(_) => Ratio::ZERO,
};

/// How a visual snapshot is taken and when it matches.
#[derive(Debug, Clone)]
#[must_use]
pub struct Screenshot {
    pub(crate) threshold: Ratio,
    pub(crate) max_diff_pixels: u32,
    pub(crate) max_diff_ratio: Ratio,
    pub(crate) include_anti_aliased: bool,
    pub(crate) mask: Vec<Locator<AnyRole>>,
    pub(crate) mask_colour: Rgba,
    pub(crate) caret: Caret,
    pub(crate) full_frame: bool,
    pub(crate) clip: Option<Logical<Rect>>,
    pub(crate) window: Option<window::Id>,
    pub(crate) timeout: Option<VirtualDuration>,
    pub(crate) only: Option<fn(&Variant) -> bool>,
    pub(crate) scale: Option<ScaleFactor>,
}

/// A threshold of 0.1, no changed pixels allowed, anti-aliasing ignored, no masks, masks in
/// `#ff00ff`, the caret hidden, element screenshots cropped, and the harness's default timeout.
impl Default for Screenshot {
    fn default() -> Self {
        Self {
            threshold: DEFAULT_THRESHOLD,
            max_diff_pixels: 0,
            max_diff_ratio: Ratio::ZERO,
            include_anti_aliased: false,
            mask: Vec::new(),
            mask_colour: Rgba::MASK,
            caret: Caret::Hide,
            full_frame: false,
            clip: None,
            window: None,
            timeout: None,
            only: None,
            scale: None,
        }
    }
}

impl Screenshot {
    /// The defaults.
    pub fn new() -> Self {
        Self::default()
    }

    /// The per-pixel colour distance that counts as a change, as in pixelmatch.
    pub fn threshold(mut self, threshold: Ratio) -> Self {
        self.threshold = threshold;
        self
    }

    /// The most changed pixels that still match.
    pub fn max_diff_pixels(mut self, pixels: u32) -> Self {
        self.max_diff_pixels = pixels;
        self
    }

    /// The largest share of changed pixels that still matches.
    pub fn max_diff_ratio(mut self, ratio: Ratio) -> Self {
        self.max_diff_ratio = ratio;
        self
    }

    /// Counts changed pixels on anti-aliased edges as changed.
    pub fn include_anti_aliased(mut self, on: bool) -> Self {
        self.include_anti_aliased = on;
        self
    }

    /// Paints every node `locator` matches over before comparing. A mask that matches nothing
    /// is not an error, and is listed in the report.
    pub fn mask<R: RoleKind>(mut self, locator: impl IntoLocator<R>) -> Self {
        self.mask.push(locator.into_locator().any_role());
        self
    }

    /// The colour masks are painted in.
    pub fn mask_colour(mut self, colour: Rgba) -> Self {
        self.mask_colour = colour;
        self
    }

    /// Hides or shows the caret.
    pub fn caret(mut self, caret: Caret) -> Self {
        self.caret = caret;
        self
    }

    /// For an element screenshot, keeps the whole window with the element outlined in the
    /// mask colour instead of cropping to it.
    pub fn full_frame(mut self, on: bool) -> Self {
        self.full_frame = on;
        self
    }

    /// For a window screenshot, crops to a region in logical pixels, rounded outwards to whole
    /// physical pixels and clamped to the window.
    pub fn clip(mut self, region: Logical<Rect>) -> Self {
        self.clip = Some(region);
        self
    }

    /// For a window screenshot, which window; the focused one by default.
    pub fn window(mut self, window: window::Id) -> Self {
        self.window = Some(window);
        self
    }

    /// How long a comparison retries in virtual time before it fails.
    pub fn timeout(mut self, timeout: impl Into<VirtualDuration>) -> Self {
        self.timeout = Some(timeout.into());
        self
    }

    /// Takes the snapshot only in the variants `keep` accepts, and passes in the rest.
    pub fn only(mut self, keep: fn(&Variant) -> bool) -> Self {
        self.only = Some(keep);
        self
    }

    /// Rasterises the snapshot at `factor` instead of the run's system scale factor, with the
    /// layout unchanged and nothing sent to the app. The scale goes in the snapshot's name in
    /// place of the variant's, so `reader@2x.png` sits beside the variant's own baseline.
    pub fn scale(mut self, factor: ScaleFactor) -> Self {
        self.scale = Some(factor);
        self
    }

    /// The variant the snapshot is named after: the run's, with this screenshot's scale.
    pub(crate) fn naming_variant(&self, variant: &Variant) -> Variant {
        match self.scale {
            Some(scale) => variant.scale(scale),
            None => *variant,
        }
    }

    pub(crate) fn diff_options(&self, mask: PixelMask) -> DiffOptions {
        DiffOptions {
            threshold: self.threshold,
            include_anti_aliased: self.include_anti_aliased,
            max_diff_pixels: self.max_diff_pixels,
            max_diff_ratio: self.max_diff_ratio,
            mask,
            mask_colour: self.mask_colour,
        }
    }
}