icedwright-types 0.1.0

Shared types for icedwright: roles and capabilities, pixel units, virtual time, frames, key chords and the Messages trait
Documentation
//! Key chords: modifiers held around one key, written `Control+Shift+K`.
//!
//! [`Chord`] and [`Keystroke`] print their canonical form with `Display` and parse it back with
//! `FromStr`. The grammar is in [`grammar`], which the `chord!` macro also runs at compile time.

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

pub mod grammar;
mod keys;

pub use grammar::{ChordError, ChordErrorKind};
#[cfg(feature = "iced")]
pub use keys::UnsupportedKeyCode;
pub use keys::{KeyCode, NamedKey};

/// One modifier.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[non_exhaustive]
pub enum Modifier {
    /// Control on Linux and Windows, Command on macOS. Stays symbolic until a chord is turned
    /// into iced events, so a chord prints the same on every platform.
    ControlOrMeta,
    /// Control.
    Control,
    /// Alt, or Option on macOS.
    Alt,
    /// Shift.
    Shift,
    /// The logo key: Super, Windows or Command.
    Meta,
}

impl Modifier {
    /// Every modifier, in the order a chord prints them.
    pub const ALL: &'static [Modifier] = &[
        Modifier::ControlOrMeta,
        Modifier::Control,
        Modifier::Alt,
        Modifier::Shift,
        Modifier::Meta,
    ];

    /// The canonical name, as `Display` prints it.
    #[must_use]
    pub const fn name(self) -> &'static str {
        match self {
            Modifier::ControlOrMeta => "ControlOrMeta",
            Modifier::Control => "Control",
            Modifier::Alt => "Alt",
            Modifier::Shift => "Shift",
            Modifier::Meta => "Meta",
        }
    }

    /// The modifier's own key, for pressing it on its own with `Key(..)`.
    #[must_use]
    pub const fn key(self) -> Option<NamedKey> {
        match self {
            Modifier::ControlOrMeta => None,
            Modifier::Control => Some(NamedKey::Control),
            Modifier::Alt => Some(NamedKey::Alt),
            Modifier::Shift => Some(NamedKey::Shift),
            Modifier::Meta => Some(NamedKey::Meta),
        }
    }

    const fn bit(self) -> u8 {
        match self {
            Modifier::ControlOrMeta => 1,
            Modifier::Control => 1 << 1,
            Modifier::Alt => 1 << 2,
            Modifier::Shift => 1 << 3,
            Modifier::Meta => 1 << 4,
        }
    }
}

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

/// A set of held modifiers.
#[derive(Clone, Copy, PartialEq, Eq, Hash, Default)]
pub struct ModifierSet(u8);

impl ModifierSet {
    /// No modifiers.
    pub const NONE: Self = Self(0);
    /// [`Modifier::ControlOrMeta`].
    pub const CONTROL_OR_META: Self = Self(Modifier::ControlOrMeta.bit());
    /// [`Modifier::Control`].
    pub const CONTROL: Self = Self(Modifier::Control.bit());
    /// [`Modifier::Alt`].
    pub const ALT: Self = Self(Modifier::Alt.bit());
    /// [`Modifier::Shift`].
    pub const SHIFT: Self = Self(Modifier::Shift.bit());
    /// [`Modifier::Meta`].
    pub const META: Self = Self(Modifier::Meta.bit());

    /// The set holding just `modifier`.
    #[must_use]
    pub const fn only(modifier: Modifier) -> Self {
        Self(modifier.bit())
    }

    /// The modifiers in either set.
    #[must_use]
    pub const fn union(self, other: Self) -> Self {
        Self(self.0 | other.0)
    }

    /// This set with `modifier` added.
    #[must_use]
    pub const fn with(self, modifier: Modifier) -> Self {
        Self(self.0 | modifier.bit())
    }

    /// Whether `modifier` is held.
    #[must_use]
    pub const fn has(self, modifier: Modifier) -> bool {
        self.0 & modifier.bit() != 0
    }

    /// Whether every modifier in `other` is held.
    #[must_use]
    pub const fn contains(self, other: Self) -> bool {
        self.0 & other.0 == other.0
    }

    /// Whether no modifier is held.
    #[must_use]
    pub const fn is_empty(self) -> bool {
        self.0 == 0
    }

    /// The held modifiers, in the order a chord prints them.
    pub fn iter(self) -> impl Iterator<Item = Modifier> {
        Modifier::ALL
            .iter()
            .copied()
            .filter(move |modifier| self.has(*modifier))
    }
}

impl From<Modifier> for ModifierSet {
    fn from(modifier: Modifier) -> Self {
        Self::only(modifier)
    }
}

impl FromIterator<Modifier> for ModifierSet {
    fn from_iter<I: IntoIterator<Item = Modifier>>(modifiers: I) -> Self {
        modifiers.into_iter().fold(Self::NONE, Self::with)
    }
}

impl core::ops::BitOr for ModifierSet {
    type Output = Self;

    fn bitor(self, other: Self) -> Self {
        self.union(other)
    }
}

impl core::ops::BitOr<Modifier> for ModifierSet {
    type Output = Self;

    fn bitor(self, modifier: Modifier) -> Self {
        self.with(modifier)
    }
}

impl fmt::Debug for ModifierSet {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_set().entries(self.iter()).finish()
    }
}

/// The key of a chord.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Keystroke {
    /// A named key, such as `Enter`.
    Named(NamedKey),
    /// A physical key, mapped to a character through the keyboard layout.
    Code(KeyCode),
    /// The key that types this character in the keyboard layout. Letters written bare in a
    /// chord, such as `K`, are stored lower case; `"K"` in quotes is the capital itself.
    Character(char),
}

impl From<NamedKey> for Keystroke {
    fn from(key: NamedKey) -> Self {
        Keystroke::Named(key)
    }
}

impl From<KeyCode> for Keystroke {
    fn from(code: KeyCode) -> Self {
        Keystroke::Code(code)
    }
}

impl From<char> for Keystroke {
    fn from(character: char) -> Self {
        Keystroke::Character(character)
    }
}

impl fmt::Display for Keystroke {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        grammar::write_keystroke(f, *self)
    }
}

impl FromStr for Keystroke {
    type Err = ChordError;

    fn from_str(input: &str) -> Result<Self, ChordError> {
        grammar::parse_keystroke(input)
    }
}

/// Modifiers held around one key, such as `Control+Shift+K`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct Chord {
    modifiers: ModifierSet,
    key: Keystroke,
}

impl Chord {
    /// `key` with `modifiers` held.
    #[must_use]
    pub const fn new(modifiers: ModifierSet, key: Keystroke) -> Self {
        Self { modifiers, key }
    }

    /// The held modifiers.
    #[must_use]
    pub const fn modifiers(self) -> ModifierSet {
        self.modifiers
    }

    /// The key.
    #[must_use]
    pub const fn key(self) -> Keystroke {
        self.key
    }
}

impl From<Keystroke> for Chord {
    fn from(key: Keystroke) -> Self {
        Self::new(ModifierSet::NONE, key)
    }
}

/// The canonical form, which `FromStr` parses back to an equal chord.
impl fmt::Display for Chord {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        for modifier in self.modifiers.iter() {
            write!(f, "{modifier}+")?;
        }
        grammar::write_keystroke(f, self.key)
    }
}

impl FromStr for Chord {
    type Err = ChordError;

    fn from_str(input: &str) -> Result<Self, ChordError> {
        grammar::parse_chord(input)
    }
}

#[cfg(feature = "serde")]
mod serde_impls {
    use super::{Chord, Keystroke};
    use serde::de::Error as _;

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

    impl<'de> serde::Deserialize<'de> for Chord {
        fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
            String::deserialize(deserializer)?
                .parse()
                .map_err(D::Error::custom)
        }
    }

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

    impl<'de> serde::Deserialize<'de> for Keystroke {
        fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
            String::deserialize(deserializer)?
                .parse()
                .map_err(D::Error::custom)
        }
    }
}

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

    #[test]
    fn modifier_sets() {
        let set = ModifierSet::CONTROL | ModifierSet::SHIFT;
        assert!(set.has(Modifier::Control));
        assert!(!set.has(Modifier::Alt));
        assert!(set.contains(ModifierSet::SHIFT));
        assert!(!set.contains(ModifierSet::SHIFT | ModifierSet::META));
        assert!(ModifierSet::default().is_empty());
        assert_eq!(
            set.iter().collect::<Vec<_>>(),
            [Modifier::Control, Modifier::Shift]
        );
        assert_eq!(format!("{set:?}"), "{Control, Shift}");
        assert_eq!(
            [Modifier::Shift, Modifier::Control]
                .into_iter()
                .collect::<ModifierSet>(),
            set
        );
        assert_eq!(ModifierSet::NONE | Modifier::Alt, ModifierSet::ALT);
        assert_eq!(ModifierSet::from(Modifier::Meta), ModifierSet::META);
        assert_eq!(
            ModifierSet::only(Modifier::ControlOrMeta),
            ModifierSet::CONTROL_OR_META
        );
    }

    #[test]
    fn modifiers_print_in_canonical_order() {
        let all: ModifierSet = Modifier::ALL.iter().copied().collect();
        let chord = Chord::new(all, Keystroke::Character('k'));
        assert_eq!(chord.to_string(), "ControlOrMeta+Control+Alt+Shift+Meta+K");
    }

    #[test]
    fn modifier_keys() {
        assert_eq!(Modifier::ControlOrMeta.key(), None);
        assert_eq!(Modifier::Control.key(), Some(NamedKey::Control));
        assert_eq!(Modifier::Meta.to_string(), "Meta");
    }

    #[test]
    fn chord_parts_and_conversions() {
        let chord = Chord::new(ModifierSet::SHIFT, NamedKey::Enter.into());
        assert_eq!(chord.modifiers(), ModifierSet::SHIFT);
        assert_eq!(chord.key(), Keystroke::Named(NamedKey::Enter));
        assert_eq!(
            Chord::from(Keystroke::from('a')).modifiers(),
            ModifierSet::NONE
        );
        assert_eq!(
            Keystroke::from(KeyCode::KeyK),
            Keystroke::Code(KeyCode::KeyK)
        );
    }

    #[cfg(feature = "serde")]
    #[test]
    fn chords_serialise_as_strings() -> Result<(), serde_json::Error> {
        let chord: Chord = Chord::new(
            ModifierSet::CONTROL | ModifierSet::SHIFT,
            Keystroke::Character('k'),
        );
        assert_eq!(serde_json::to_string(&chord)?, "\"Control+Shift+K\"");
        assert_eq!(
            serde_json::from_str::<Chord>("\"Ctrl + Shift + K\"")?,
            chord
        );
        assert!(serde_json::from_str::<Chord>("\"Ctrl+\"").is_err());
        assert_eq!(
            serde_json::to_string(&Keystroke::Code(KeyCode::KeyA))?,
            "\"Code(KeyA)\""
        );
        assert_eq!(
            serde_json::from_str::<Keystroke>("\"F5\"")?,
            Keystroke::Named(NamedKey::F5)
        );
        Ok(())
    }
}