icedwright-types 0.1.0

Shared types for icedwright: roles and capabilities, pixel units, virtual time, frames, key chords and the Messages trait
Documentation
//! Node states as trees, YAML, selector strings and the wire name them.
//!
//! [`StateName`] lists every state a semantic node can carry, printed with the names the YAML
//! writer and the selector grammar share. [`StateValue`] is what an annotation or a selector
//! says about one, and [`Checked`] is the tri-state value of a checkable role.

use core::fmt;
use core::str::FromStr;

use crate::suggest;

macro_rules! state_names {
    ($($(#[doc = $doc:literal])+ $variant:ident => $name:literal,)+) => {
        /// A state a semantic node can carry.
        #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
        #[non_exhaustive]
        pub enum StateName {
            $($(#[doc = $doc])+ $variant,)+
        }

        impl StateName {
            /// Every state, in the order the YAML writer and the selector printer use.
            pub const ALL: &'static [StateName] = &[$(StateName::$variant),+];

            /// The name written in YAML and selector strings.
            #[must_use]
            pub const fn name(self) -> &'static str {
                match self {
                    $(StateName::$variant => $name,)+
                }
            }
        }
    };
}

state_names! {
    /// The node takes no input.
    Disabled => "disabled",
    /// The node shows a value that cannot be changed.
    Readonly => "readonly",
    /// Checked, unchecked or mixed.
    Checked => "checked",
    /// A toggle button is pressed.
    Pressed => "pressed",
    /// The node's content or popup is shown.
    Expanded => "expanded",
    /// An item is selected in its container.
    Selected => "selected",
    /// The node has keyboard focus.
    Focused => "focused",
    /// The current item in a set, such as the open page in a sidebar.
    Current => "current",
    /// The node is loading or updating.
    Busy => "busy",
    /// A form control must be filled in.
    Required => "required",
    /// A form control's value is rejected.
    Invalid => "invalid",
    /// A text box takes more than one line.
    Multiline => "multiline",
    /// A container allows more than one selected item.
    Multiselectable => "multiselectable",
    /// Everything outside the node is inert while it is shown.
    Modal => "modal",
    /// The node can take keyboard focus.
    Focusable => "focusable",
    /// The node is not shown.
    Hidden => "hidden",
    /// The node has size but is clipped out of view.
    Offscreen => "offscreen",
    /// The node is outside the topmost modal.
    Inert => "inert",
}

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

/// A string that names no state.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ParseStateError {
    name: String,
    suggestions: Vec<&'static str>,
}

impl ParseStateError {
    /// The name that was not recognised.
    #[must_use]
    pub fn name(&self) -> &str {
        &self.name
    }

    /// The nearest state names, nearest first.
    #[must_use]
    pub fn suggestions(&self) -> &[&'static str] {
        &self.suggestions
    }
}

impl fmt::Display for ParseStateError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "unknown state `{}`{}",
            self.name,
            suggest::did_you_mean(&self.suggestions)
        )
    }
}

impl std::error::Error for ParseStateError {}

impl FromStr for StateName {
    type Err = ParseStateError;

    fn from_str(name: &str) -> Result<Self, ParseStateError> {
        if let Some(state) = StateName::ALL.iter().copied().find(|s| s.name() == name) {
            return Ok(state);
        }
        Err(ParseStateError {
            name: name.to_owned(),
            suggestions: suggest::nearest(name, StateName::ALL.iter().map(|s| s.name())),
        })
    }
}

/// The checked state of a checkable role.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub enum Checked {
    /// Checked.
    True,
    /// Not checked.
    #[default]
    False,
    /// Partly checked, such as a parent whose children disagree.
    Mixed,
}

impl From<bool> for Checked {
    fn from(on: bool) -> Self {
        if on { Checked::True } else { Checked::False }
    }
}

impl fmt::Display for Checked {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        StateValue::from(*self).fmt(f)
    }
}

/// What a source or a selector says about one state.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum StateValue {
    /// On or off.
    Bool(bool),
    /// Partly on, for [`StateName::Checked`] only.
    Mixed,
}

impl StateValue {
    /// The value as a [`Checked`].
    #[must_use]
    pub const fn as_checked(self) -> Checked {
        match self {
            StateValue::Bool(true) => Checked::True,
            StateValue::Bool(false) => Checked::False,
            StateValue::Mixed => Checked::Mixed,
        }
    }

    /// The value as a flag, or `None` for [`StateValue::Mixed`].
    #[must_use]
    pub const fn as_bool(self) -> Option<bool> {
        match self {
            StateValue::Bool(on) => Some(on),
            StateValue::Mixed => None,
        }
    }
}

impl From<bool> for StateValue {
    fn from(on: bool) -> Self {
        StateValue::Bool(on)
    }
}

impl From<Checked> for StateValue {
    fn from(checked: Checked) -> Self {
        match checked {
            Checked::True => StateValue::Bool(true),
            Checked::False => StateValue::Bool(false),
            Checked::Mixed => StateValue::Mixed,
        }
    }
}

impl fmt::Display for StateValue {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(match self {
            StateValue::Bool(true) => "true",
            StateValue::Bool(false) => "false",
            StateValue::Mixed => "mixed",
        })
    }
}

/// A string that is not `true`, `false` or `mixed`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ParseStateValueError(String);

impl fmt::Display for ParseStateValueError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "unknown state value `{}`; expected `true`, `false` or `mixed`",
            self.0
        )
    }
}

impl std::error::Error for ParseStateValueError {}

impl FromStr for StateValue {
    type Err = ParseStateValueError;

    fn from_str(text: &str) -> Result<Self, ParseStateValueError> {
        match text {
            "true" => Ok(StateValue::Bool(true)),
            "false" => Ok(StateValue::Bool(false)),
            "mixed" => Ok(StateValue::Mixed),
            other => Err(ParseStateValueError(other.to_owned())),
        }
    }
}

/// The kind of mouse cursor a widget was handed for its last mouse event this frame.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(rename_all = "snake_case"))]
pub enum CursorSeen {
    /// The cursor was available at a position.
    Available,
    /// The cursor was levitating under a higher `stack` layer.
    Levitating,
    /// The cursor was unavailable, under an overlay.
    Unavailable,
}

#[cfg(feature = "serde")]
mod serde_impls {
    use super::{Checked, StateName, StateValue};

    macro_rules! by_display {
        ($ty:ty, $what:literal) => {
            impl serde::Serialize for $ty {
                fn serialize<S: serde::Serializer>(
                    &self,
                    serializer: S,
                ) -> Result<S::Ok, S::Error> {
                    serializer.collect_str(self)
                }
            }

            impl<'de> serde::Deserialize<'de> for $ty {
                fn deserialize<D: serde::Deserializer<'de>>(
                    deserializer: D,
                ) -> Result<Self, D::Error> {
                    let text = <::std::borrow::Cow<'de, str>>::deserialize(deserializer)?;
                    text.parse::<$ty>().map_err(|_| {
                        serde::de::Error::invalid_value(serde::de::Unexpected::Str(&text), &$what)
                    })
                }
            }
        };
    }

    by_display!(StateName, "a state name");
    by_display!(StateValue, "`true`, `false` or `mixed`");

    impl serde::Serialize for Checked {
        fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
            StateValue::from(*self).serialize(serializer)
        }
    }

    impl<'de> serde::Deserialize<'de> for Checked {
        fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
            StateValue::deserialize(deserializer).map(StateValue::as_checked)
        }
    }
}

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

    #[test]
    fn state_names_round_trip_and_are_unique() {
        for (i, state) in StateName::ALL.iter().enumerate() {
            assert_eq!(state.name().parse::<StateName>(), Ok(*state));
            for other in &StateName::ALL[i + 1..] {
                assert_ne!(state.name(), other.name());
            }
        }
    }

    #[test]
    fn unknown_state_suggests_the_nearest() {
        let error = "expandd".parse::<StateName>().err();
        assert_eq!(
            error.map(|e| e.to_string()),
            Some("unknown state `expandd`; did you mean `expanded`?".to_owned())
        );
    }

    #[test]
    fn values_round_trip_and_convert() {
        for value in [
            StateValue::Bool(true),
            StateValue::Bool(false),
            StateValue::Mixed,
        ] {
            assert_eq!(value.to_string().parse::<StateValue>(), Ok(value));
            assert_eq!(StateValue::from(value.as_checked()), value);
        }
        assert_eq!(Checked::from(true), Checked::True);
        assert_eq!(StateValue::Mixed.as_bool(), None);
        assert!("yes".parse::<StateValue>().is_err());
    }

    #[cfg(feature = "serde")]
    #[test]
    fn serde_uses_the_names() -> Result<(), serde_json::Error> {
        assert_eq!(serde_json::to_string(&StateName::Expanded)?, "\"expanded\"");
        assert_eq!(serde_json::to_string(&Checked::Mixed)?, "\"mixed\"");
        assert_eq!(
            serde_json::from_str::<StateValue>("\"false\"")?,
            StateValue::Bool(false)
        );
        assert_eq!(
            serde_json::to_string(&CursorSeen::Levitating)?,
            "\"levitating\""
        );
        assert!(serde_json::from_str::<StateName>("\"nope\"").is_err());
        Ok(())
    }
}