icedwright 0.0.1

The icedwright test harness: run an iced 0.14 program headlessly on virtual time
Documentation
//! The run matrix's axes. Each is an enum or a checked constant, so a value the macro does not
//! know fails the build, and each maps onto the harness configuration it changes.

use std::fmt;

use iced_core::theme;
use icedwright_types::Size as LogicalSize;
use icedwright_types::units::Logical;

/// The system theme a combination runs under.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub enum Theme {
    /// The light system theme.
    #[default]
    Light,
    /// The dark system theme.
    Dark,
}

impl From<Theme> for theme::Mode {
    fn from(theme: Theme) -> Self {
        match theme {
            Theme::Light => theme::Mode::Light,
            Theme::Dark => theme::Mode::Dark,
        }
    }
}

/// The main window's logical size.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Size {
    /// 360 by 780.
    Phone,
    /// 768 by 1024.
    Tablet,
    /// 1280 by 800.
    Desktop,
    /// A width and height of at least one logical pixel each.
    Custom(u16, u16),
}

impl Size {
    /// The width and height in logical pixels.
    #[must_use]
    pub const fn dimensions(self) -> (u16, u16) {
        match self {
            Size::Phone => (360, 780),
            Size::Tablet => (768, 1024),
            Size::Desktop => (1280, 800),
            Size::Custom(width, height) => (width, height),
        }
    }
}

impl From<Size> for Logical<LogicalSize> {
    fn from(size: Size) -> Self {
        let (width, height) = size.dimensions();
        Logical(LogicalSize::new(f32::from(width), f32::from(height)))
    }
}

/// A BCP 47 language tag the app's launch function reads. iced has no locale of its own, so
/// the matrix only decides which one the app is given.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct Locale(&'static str);

/// A string that is not a BCP 47 tag.
#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
#[error("{tag:?} is not a BCP 47 language tag, such as \"en-GB\"")]
pub struct InvalidLocale {
    /// What was given.
    pub tag: &'static str,
}

impl Locale {
    /// British English.
    pub const EN_GB: Self = Self("en-GB");
    /// American English.
    pub const EN_US: Self = Self("en-US");
    /// German.
    pub const DE: Self = Self("de");
    /// French.
    pub const FR: Self = Self("fr");
    /// Spanish.
    pub const ES: Self = Self("es");
    /// Arabic, written right to left.
    pub const AR: Self = Self("ar");
    /// Hebrew, written right to left.
    pub const HE: Self = Self("he");
    /// Japanese.
    pub const JA: Self = Self("ja");

    /// Checks BCP 47 syntax: subtags of one to eight letters or digits joined by `-`, the
    /// first of two, three or five to eight letters. Usable in a `const`.
    pub const fn parse(tag: &'static str) -> Result<Self, InvalidLocale> {
        let bytes = tag.as_bytes();
        let mut index = 0;
        let mut start = 0;
        let mut first = true;
        while index <= bytes.len() {
            if index == bytes.len() || bytes[index] == b'-' {
                let len = index - start;
                let ok = if first {
                    matches!(len, 2 | 3 | 5..=8)
                } else {
                    len >= 1 && len <= 8
                };
                if !ok {
                    return Err(InvalidLocale { tag });
                }
                first = false;
                start = index + 1;
            } else {
                let byte = bytes[index];
                let ok = if first {
                    byte.is_ascii_alphabetic()
                } else {
                    byte.is_ascii_alphanumeric()
                };
                if !ok {
                    return Err(InvalidLocale { tag });
                }
            }
            index += 1;
        }
        Ok(Self(tag))
    }

    /// The tag as written.
    #[must_use]
    pub const fn tag(self) -> &'static str {
        self.0
    }
}

impl Default for Locale {
    fn default() -> Self {
        Self::EN_GB
    }
}

impl fmt::Display for Locale {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.0)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    const PT_BR: Locale = match Locale::parse("pt-BR") {
        Ok(locale) => locale,
        Err(_) => panic!("pt-BR is a tag"),
    };

    #[test]
    fn locales_parse_in_const_context() {
        assert_eq!(PT_BR.tag(), "pt-BR");
        assert_eq!(Locale::EN_GB.to_string(), "en-GB");
    }

    #[test]
    fn a_malformed_locale_is_an_error_value() {
        for bad in [
            "",
            "e",
            "en_GB",
            "en-",
            "en--GB",
            "1en",
            "languages",
            "en-toolongtag",
        ] {
            assert_eq!(Locale::parse(bad), Err(InvalidLocale { tag: bad }), "{bad}");
        }
        for good in ["en", "zh-Hant-TW", "de-1996", "haw", Locale::AR.tag()] {
            assert!(Locale::parse(good).is_ok(), "{good}");
        }
    }

    #[test]
    fn sizes_and_themes_map_to_the_harness_types() {
        assert_eq!(
            Logical::<LogicalSize>::from(Size::Phone),
            Logical(LogicalSize::new(360.0, 780.0))
        );
        assert_eq!(Size::Custom(1024, 700).dimensions(), (1024, 700));
        assert_eq!(theme::Mode::from(Theme::Dark), theme::Mode::Dark);
        assert_eq!(theme::Mode::from(Theme::default()), theme::Mode::Light);
    }
}