btn-recognizer 0.2.2

Timestamp-driven button debouncing with multi-tap, hold, repeat, and multi-key chord gesture recognition
Documentation
use std::fmt;
use std::num::NonZeroU64;
use std::time::Duration;

/// Monotonic time measured from an application-defined epoch.
///
/// The framework never reads a system clock. Callers can therefore use a
/// hardware timer, an event-loop clock, or deterministic values in tests.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Timestamp(Duration);

impl Timestamp {
    pub const ZERO: Self = Self(Duration::ZERO);

    pub const fn from_duration(value: Duration) -> Self {
        Self(value)
    }

    pub const fn from_millis(value: u64) -> Self {
        Self(Duration::from_millis(value))
    }

    pub const fn from_micros(value: u64) -> Self {
        Self(Duration::from_micros(value))
    }

    pub const fn as_duration(self) -> Duration {
        self.0
    }

    pub fn checked_add(self, duration: Duration) -> Option<Self> {
        self.0.checked_add(duration).map(Self)
    }

    pub fn saturating_add(self, duration: Duration) -> Self {
        Self(self.0.saturating_add(duration))
    }

    pub fn checked_duration_since(self, earlier: Self) -> Option<Duration> {
        self.0.checked_sub(earlier.0)
    }
}

impl fmt::Display for Timestamp {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{:?}", self.0)
    }
}

/// Stable identifier of a physical button.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct KeyId(pub u16);

impl fmt::Display for KeyId {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "key:{}", self.0)
    }
}

/// Stable identifier of a configured virtual chord.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct ChordId(pub u16);

impl fmt::Display for ChordId {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "chord:{}", self.0)
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum ButtonPhase {
    Down,
    Up,
}

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

impl From<bool> for RawLevel {
    fn from(high: bool) -> Self {
        if high {
            Self::High
        } else {
            Self::Low
        }
    }
}

/// One atomic GPIO snapshot. `levels` uses configured button order.
#[derive(Debug, Clone, Copy)]
pub struct ButtonSnapshot<'a> {
    pub at: Timestamp,
    pub levels: &'a [RawLevel],
}

impl ButtonPhase {
    pub const fn is_down(self) -> bool {
        matches!(self, Self::Down)
    }
}

/// A physical edge after debounce confirmation.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct ButtonEdge {
    pub key: KeyId,
    pub phase: ButtonPhase,
    /// Logical time at which the debounced edge occurred.
    pub occurred_at: Timestamp,
    /// Time at which this stage recognized the edge.
    pub recognized_at: Timestamp,
}

/// A logical control is either one physical key or one virtual chord.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum ControlId {
    Key(KeyId),
    Chord(ChordId),
}

/// A logical edge after chord arbitration.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct ControlEdge {
    pub control: ControlId,
    pub phase: ButtonPhase,
    /// Original logical edge time, preserved across chord buffering.
    pub occurred_at: Timestamp,
    /// Time at which chord arbitration released or recognized the edge.
    pub recognized_at: Timestamp,
}

#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum GestureKind {
    /// A completed tap sequence. One, two, and higher-order taps share one type.
    Tap { count: u8 },
    /// The first configured hold threshold has been reached.
    HoldStart { threshold: Duration },
    /// A later configured hold threshold has been reached.
    HoldMilestone { threshold: Duration },
    /// One or more repeat intervals elapsed since the previous update.
    Repeat { count: NonZeroU64 },
    /// A held control was released.
    HoldEnd { held_for: Duration },
}

#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum ButtonEventKind {
    State {
        control: ControlId,
        phase: ButtonPhase,
    },
    Gesture {
        control: ControlId,
        kind: GestureKind,
    },
}

/// Domain event emitted by the recognition pipeline.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct ButtonEvent {
    /// Logical time of the state change, deadline, or final tap release.
    pub occurred_at: Timestamp,
    /// Time at which the framework emitted this event.
    pub recognized_at: Timestamp,
    pub kind: ButtonEventKind,
}

impl ButtonEvent {
    pub const fn state(edge: ControlEdge) -> Self {
        Self {
            occurred_at: edge.occurred_at,
            recognized_at: edge.recognized_at,
            kind: ButtonEventKind::State {
                control: edge.control,
                phase: edge.phase,
            },
        }
    }

    pub fn gesture(
        control: ControlId,
        kind: GestureKind,
        occurred_at: Timestamp,
        recognized_at: Timestamp,
    ) -> Self {
        Self {
            occurred_at,
            recognized_at,
            kind: ButtonEventKind::Gesture { control, kind },
        }
    }
}

/// Owned output of one framework update.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct EventBatch {
    /// Time through which the engine processed inputs and deadlines.
    pub processed_at: Timestamp,
    /// Immediate physical edges, before any chord suppression or delay.
    pub physical: Vec<ButtonEdge>,
    /// Logical state and gesture events.
    pub events: Vec<ButtonEvent>,
    /// Earliest gesture or chord deadline, if one is pending.
    pub next_wakeup: Option<Timestamp>,
}

impl EventBatch {
    pub fn new(processed_at: Timestamp) -> Self {
        Self {
            processed_at,
            physical: Vec::new(),
            events: Vec::new(),
            next_wakeup: None,
        }
    }

    pub fn is_empty(&self) -> bool {
        self.physical.is_empty() && self.events.is_empty()
    }
}