btn-recognizer 0.2.2

Timestamp-driven button debouncing with multi-tap, hold, repeat, and multi-key chord gesture recognition
Documentation
use std::collections::{HashMap, HashSet};
use std::error::Error;
use std::fmt;
use std::time::Duration;

use super::types::{ChordId, ControlId, KeyId, RawLevel};

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ActiveLevel {
    Low,
    High,
}

impl ActiveLevel {
    pub const fn is_pressed(self, raw_level: RawLevel) -> bool {
        match self {
            Self::Low => matches!(raw_level, RawLevel::Low),
            Self::High => matches!(raw_level, RawLevel::High),
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ButtonConfig {
    pub id: KeyId,
    pub active_level: ActiveLevel,
    pub debounce: DebounceConfig,
    /// Logical state assumed before the first sample is processed.
    pub initially_pressed: bool,
}

impl ButtonConfig {
    pub fn active_low(id: KeyId, debounce: Duration) -> Self {
        Self {
            id,
            active_level: ActiveLevel::Low,
            debounce: DebounceConfig::symmetric(debounce),
            initially_pressed: false,
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct DebounceConfig {
    pub press: Duration,
    pub release: Duration,
}

impl DebounceConfig {
    pub const fn symmetric(duration: Duration) -> Self {
        Self {
            press: duration,
            release: duration,
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ChordReleasePolicy {
    /// Release the virtual control as soon as any member is released.
    AnyMember,
    /// Keep the virtual control down until every member is released.
    AllMembers,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ChordConfig {
    pub id: ChordId,
    pub members: Vec<KeyId>,
    pub window: Duration,
    pub priority: i16,
    pub release: ChordReleasePolicy,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RepeatConfig {
    /// Time from the original down edge to the first repeat.
    pub starts_after: Duration,
    pub interval: Duration,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum HoldAfterTapPolicy {
    /// A later hold replaces taps still waiting in the multi-tap window.
    CancelPendingTaps,
    /// Emit already completed taps before starting the hold.
    CommitPendingTaps,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct GestureConfig {
    /// Maximum down-to-up duration that can be counted as a tap.
    pub tap_max: Duration,
    /// Maximum delay from one tap release to the next down edge.
    pub multi_tap_window: Duration,
    /// Emit immediately after this many taps. Must be at least one.
    pub max_taps: u8,
    /// Strictly increasing hold thresholds. The first starts a hold; later
    /// values are milestones.
    pub hold_thresholds: Vec<Duration>,
    pub repeat: Option<RepeatConfig>,
    pub hold_after_tap: HoldAfterTapPolicy,
}

impl Default for GestureConfig {
    fn default() -> Self {
        Self {
            tap_max: Duration::from_millis(500),
            multi_tap_window: Duration::from_millis(500),
            max_taps: 2,
            hold_thresholds: vec![Duration::from_secs(1), Duration::from_secs(3)],
            repeat: None,
            hold_after_tap: HoldAfterTapPolicy::CancelPendingTaps,
        }
    }
}

impl GestureConfig {
    pub fn validate(&self) -> Result<(), ConfigError> {
        validate_gesture_config(self, None)
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FrameworkConfig {
    pub buttons: Vec<ButtonConfig>,
    pub chords: Vec<ChordConfig>,
    pub default_gestures: GestureConfig,
    pub gesture_overrides: HashMap<ControlId, GestureConfig>,
}

impl FrameworkConfig {
    pub fn new(buttons: Vec<ButtonConfig>) -> Self {
        Self {
            buttons,
            chords: Vec::new(),
            default_gestures: GestureConfig::default(),
            gesture_overrides: HashMap::new(),
        }
    }

    pub fn validate(&self) -> Result<(), ConfigError> {
        let mut key_ids = HashSet::with_capacity(self.buttons.len());
        for button in &self.buttons {
            if !key_ids.insert(button.id) {
                return Err(ConfigError::DuplicateKey(button.id));
            }
        }

        validate_gesture_config(&self.default_gestures, None)?;
        for (&control, config) in &self.gesture_overrides {
            match control {
                ControlId::Key(key) if !key_ids.contains(&key) => {
                    return Err(ConfigError::UnknownKey(key));
                }
                ControlId::Chord(chord)
                    if !self.chords.iter().any(|candidate| candidate.id == chord) =>
                {
                    return Err(ConfigError::UnknownChord(chord));
                }
                _ => {}
            }
            validate_gesture_config(config, Some(control))?;
        }

        let mut chord_ids = HashSet::with_capacity(self.chords.len());
        let mut normalized_members = Vec::with_capacity(self.chords.len());
        for chord in &self.chords {
            if !chord_ids.insert(chord.id) {
                return Err(ConfigError::DuplicateChord(chord.id));
            }
            if chord.members.len() < 2 {
                return Err(ConfigError::ChordTooSmall(chord.id));
            }

            let members: HashSet<_> = chord.members.iter().copied().collect();
            if members.len() != chord.members.len() {
                return Err(ConfigError::DuplicateChordMember(chord.id));
            }
            if let Some(&unknown) = members.iter().find(|key| !key_ids.contains(key)) {
                return Err(ConfigError::UnknownChordMember {
                    chord: chord.id,
                    key: unknown,
                });
            }
            normalized_members.push((chord.id, members));
        }

        for (index, (left_id, left)) in normalized_members.iter().enumerate() {
            for (right_id, right) in normalized_members.iter().skip(index + 1) {
                if left == right {
                    return Err(ConfigError::DuplicateChordMembers {
                        first: *left_id,
                        second: *right_id,
                    });
                }
                if left.is_subset(right) || right.is_subset(left) {
                    return Err(ConfigError::SubsetChords {
                        first: *left_id,
                        second: *right_id,
                    });
                }
            }
        }

        Ok(())
    }

    pub fn gesture_config(&self, control: ControlId) -> &GestureConfig {
        self.gesture_overrides
            .get(&control)
            .unwrap_or(&self.default_gestures)
    }
}

pub(crate) fn validate_gesture_config(
    config: &GestureConfig,
    control: Option<ControlId>,
) -> Result<(), ConfigError> {
    if config.max_taps == 0 {
        return Err(ConfigError::ZeroMaxTaps(control));
    }

    if config
        .hold_thresholds
        .windows(2)
        .any(|pair| pair[0] >= pair[1])
    {
        return Err(ConfigError::UnorderedHoldThresholds(control));
    }

    if let Some(repeat) = &config.repeat {
        if repeat.interval.is_zero() {
            return Err(ConfigError::ZeroRepeatInterval(control));
        }
        let Some(&first_hold) = config.hold_thresholds.first() else {
            return Err(ConfigError::RepeatWithoutHold(control));
        };
        if repeat.starts_after < first_hold {
            return Err(ConfigError::RepeatBeforeHold(control));
        }
    }

    Ok(())
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ConfigError {
    DuplicateKey(KeyId),
    DuplicateChord(ChordId),
    UnknownKey(KeyId),
    UnknownChord(ChordId),
    ChordTooSmall(ChordId),
    DuplicateChordMember(ChordId),
    UnknownChordMember { chord: ChordId, key: KeyId },
    DuplicateChordMembers { first: ChordId, second: ChordId },
    SubsetChords { first: ChordId, second: ChordId },
    ZeroMaxTaps(Option<ControlId>),
    UnorderedHoldThresholds(Option<ControlId>),
    ZeroRepeatInterval(Option<ControlId>),
    RepeatWithoutHold(Option<ControlId>),
    RepeatBeforeHold(Option<ControlId>),
}

impl fmt::Display for ConfigError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::DuplicateKey(key) => write!(f, "duplicate button id {key}"),
            Self::DuplicateChord(chord) => write!(f, "duplicate chord id {chord}"),
            Self::UnknownKey(key) => write!(f, "unknown button id {key}"),
            Self::UnknownChord(chord) => write!(f, "unknown chord id {chord}"),
            Self::ChordTooSmall(chord) => {
                write!(f, "{chord} must contain at least two buttons")
            }
            Self::DuplicateChordMember(chord) => {
                write!(f, "{chord} contains a duplicate button")
            }
            Self::UnknownChordMember { chord, key } => {
                write!(f, "{chord} references unknown {key}")
            }
            Self::DuplicateChordMembers { first, second } => {
                write!(f, "{first} and {second} contain the same buttons")
            }
            Self::SubsetChords { first, second } => {
                write!(f, "{first} and {second} have an ambiguous subset relation")
            }
            Self::ZeroMaxTaps(control) => {
                write!(f, "gesture config {control:?} has max_taps=0")
            }
            Self::UnorderedHoldThresholds(control) => write!(
                f,
                "gesture config {control:?} hold thresholds are not strictly increasing"
            ),
            Self::ZeroRepeatInterval(control) => {
                write!(f, "gesture config {control:?} has a zero repeat interval")
            }
            Self::RepeatWithoutHold(control) => {
                write!(f, "gesture config {control:?} enables repeat without hold")
            }
            Self::RepeatBeforeHold(control) => write!(
                f,
                "gesture config {control:?} starts repeat before the first hold threshold"
            ),
        }
    }
}

impl Error for ConfigError {}

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

    fn button(id: u16) -> ButtonConfig {
        ButtonConfig::active_low(KeyId(id), Duration::from_millis(20))
    }

    fn framework() -> FrameworkConfig {
        FrameworkConfig {
            buttons: vec![button(1), button(2), button(3)],
            chords: Vec::new(),
            default_gestures: GestureConfig::default(),
            gesture_overrides: HashMap::new(),
        }
    }

    #[test]
    fn valid_default_configuration() {
        assert_eq!(framework().validate(), Ok(()));
    }

    #[test]
    fn rejects_duplicate_buttons() {
        let mut config = framework();
        config.buttons.push(button(1));
        assert_eq!(config.validate(), Err(ConfigError::DuplicateKey(KeyId(1))));
    }

    #[test]
    fn rejects_subset_chords() {
        let mut config = framework();
        config.chords = vec![
            ChordConfig {
                id: ChordId(1),
                members: vec![KeyId(1), KeyId(2)],
                window: Duration::from_millis(50),
                priority: 0,
                release: ChordReleasePolicy::AnyMember,
            },
            ChordConfig {
                id: ChordId(2),
                members: vec![KeyId(1), KeyId(2), KeyId(3)],
                window: Duration::from_millis(50),
                priority: 1,
                release: ChordReleasePolicy::AnyMember,
            },
        ];
        assert_eq!(
            config.validate(),
            Err(ConfigError::SubsetChords {
                first: ChordId(1),
                second: ChordId(2),
            })
        );
    }

    #[test]
    fn rejects_invalid_repeat() {
        let mut config = framework();
        config.default_gestures.repeat = Some(RepeatConfig {
            starts_after: Duration::from_millis(500),
            interval: Duration::from_millis(100),
        });
        assert_eq!(config.validate(), Err(ConfigError::RepeatBeforeHold(None)));
    }
}