icedwright 0.0.1

The icedwright test harness: run an iced 0.14 program headlessly on virtual time
Documentation
//! PNG files for baselines and failure images, with what they were drawn with in `tEXt`
//! chunks.

use std::collections::BTreeMap;
use std::io::Cursor;

use icedwright_types::units::{Physical, ScaleFactor};
use icedwright_types::{Frame, Size};

use super::SnapshotError;

/// The `tEXt` chunks of a snapshot PNG: what drew it, so a review or a failure can tell a
/// font or renderer change from a change in the app.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
#[must_use]
pub struct PngMetadata {
    entries: BTreeMap<String, String>,
}

impl PngMetadata {
    /// The icedwright version that wrote the file.
    pub const VERSION: &'static str = "icedwright-version";
    /// The renderer, `tiny-skia`.
    pub const RENDERER: &'static str = "renderer";
    /// The window's theme, `light` or `dark`.
    pub const THEME: &'static str = "theme";
    /// The logical size, `1024x768`.
    pub const LOGICAL_SIZE: &'static str = "logical-size";
    /// The scale factor the frame was drawn at.
    pub const SCALE: &'static str = "scale-factor";
    /// The font database's fingerprint, in hex.
    pub const FONTS: &'static str = "fonts";
    /// `system` when the frame was drawn with the machine's fonts; absent with the bundled set.
    pub const FONT_SOURCE: &'static str = "font-source";
    /// The run variant, `light-desktop-2x`.
    pub const VARIANT: &'static str = "variant";

    /// No entries.
    pub fn new() -> Self {
        Self::default()
    }

    /// Adds or replaces an entry. Keys are 1 to 79 Latin-1 bytes and values Latin-1, as PNG
    /// requires; anything else fails when the file is encoded.
    pub fn with(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
        self.entries.insert(key.into(), value.into());
        self
    }

    /// An entry.
    #[must_use]
    pub fn get(&self, key: &str) -> Option<&str> {
        self.entries.get(key).map(String::as_str)
    }

    /// Every entry, sorted by key.
    pub fn iter(&self) -> impl Iterator<Item = (&str, &str)> {
        self.entries.iter().map(|(k, v)| (k.as_str(), v.as_str()))
    }
}

fn encode_error(error: impl std::fmt::Display) -> SnapshotError {
    SnapshotError::Png {
        action: "encoded",
        message: error.to_string(),
    }
}

fn decode_error(error: impl std::fmt::Display) -> SnapshotError {
    SnapshotError::Png {
        action: "decoded",
        message: error.to_string(),
    }
}

/// Encodes an RGBA frame as a PNG with the metadata as `tEXt` chunks. The scale factor is
/// always recorded, so [`decode_png`] gives back an equal frame.
pub fn encode_png(frame: &Frame, metadata: &PngMetadata) -> Result<Vec<u8>, SnapshotError> {
    let size = frame.size().get();
    let mut out = Vec::new();
    let mut encoder = png::Encoder::new(&mut out, size.width, size.height);
    encoder.set_color(png::ColorType::Rgba);
    encoder.set_depth(png::BitDepth::Eight);
    let metadata = metadata
        .clone()
        .with(PngMetadata::SCALE, frame.scale().get().to_string());
    for (key, value) in metadata.iter() {
        encoder
            .add_text_chunk(key.to_owned(), value.to_owned())
            .map_err(encode_error)?;
    }
    let mut writer = encoder.write_header().map_err(encode_error)?;
    writer
        .write_image_data(frame.rgba())
        .map_err(encode_error)?;
    writer.finish().map_err(encode_error)?;
    Ok(out)
}

/// Decodes a PNG into an RGBA frame and its `tEXt` chunks. The frame's scale factor comes
/// from the `scale-factor` chunk, and is 1 when there is none.
pub fn decode_png(bytes: &[u8]) -> Result<(Frame, PngMetadata), SnapshotError> {
    let mut decoder = png::Decoder::new(Cursor::new(bytes));
    decoder.set_transformations(png::Transformations::normalize_to_color8());
    let mut reader = decoder.read_info().map_err(decode_error)?;
    let metadata = reader
        .info()
        .uncompressed_latin1_text
        .iter()
        .fold(PngMetadata::new(), |metadata, chunk| {
            metadata.with(chunk.keyword.clone(), chunk.text.clone())
        });
    let length = reader
        .output_buffer_size()
        .ok_or_else(|| decode_error("the image is too large"))?;
    let mut buffer = vec![0; length];
    let info = reader.next_frame(&mut buffer).map_err(decode_error)?;
    buffer.truncate(info.buffer_size());
    let rgba = match info.color_type {
        png::ColorType::Rgba => buffer,
        png::ColorType::Rgb => buffer
            .as_chunks::<3>()
            .0
            .iter()
            .flat_map(|[r, g, b]| [*r, *g, *b, 255])
            .collect(),
        png::ColorType::GrayscaleAlpha => buffer
            .as_chunks::<2>()
            .0
            .iter()
            .flat_map(|[g, a]| [*g, *g, *g, *a])
            .collect(),
        png::ColorType::Grayscale => buffer.iter().flat_map(|g| [*g, *g, *g, 255]).collect(),
        png::ColorType::Indexed => {
            return Err(decode_error("an indexed image was not expanded"));
        }
    };
    let scale = metadata
        .get(PngMetadata::SCALE)
        .and_then(|value| value.parse::<f32>().ok())
        .map_or(Ok(ScaleFactor::ONE), ScaleFactor::new)
        .map_err(decode_error)?;
    let frame = Frame::new(
        rgba,
        Physical::new(Size::new(info.width, info.height)),
        scale,
    )
    .map_err(decode_error)?;
    Ok((frame, metadata))
}