Skip to main content

btn_recognizer/key/
types.rs

1use std::fmt;
2use std::num::NonZeroU64;
3use std::time::Duration;
4
5/// Monotonic time measured from an application-defined epoch.
6///
7/// The framework never reads a system clock. Callers can therefore use a
8/// hardware timer, an event-loop clock, or deterministic values in tests.
9#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
10pub struct Timestamp(Duration);
11
12impl Timestamp {
13    pub const ZERO: Self = Self(Duration::ZERO);
14
15    pub const fn from_duration(value: Duration) -> Self {
16        Self(value)
17    }
18
19    pub const fn from_millis(value: u64) -> Self {
20        Self(Duration::from_millis(value))
21    }
22
23    pub const fn from_micros(value: u64) -> Self {
24        Self(Duration::from_micros(value))
25    }
26
27    pub const fn as_duration(self) -> Duration {
28        self.0
29    }
30
31    pub fn checked_add(self, duration: Duration) -> Option<Self> {
32        self.0.checked_add(duration).map(Self)
33    }
34
35    pub fn saturating_add(self, duration: Duration) -> Self {
36        Self(self.0.saturating_add(duration))
37    }
38
39    pub fn checked_duration_since(self, earlier: Self) -> Option<Duration> {
40        self.0.checked_sub(earlier.0)
41    }
42}
43
44impl fmt::Display for Timestamp {
45    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
46        write!(f, "{:?}", self.0)
47    }
48}
49
50/// Stable identifier of a physical button.
51#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
52pub struct KeyId(pub u16);
53
54impl fmt::Display for KeyId {
55    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
56        write!(f, "key:{}", self.0)
57    }
58}
59
60/// Stable identifier of a configured virtual chord.
61#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
62pub struct ChordId(pub u16);
63
64impl fmt::Display for ChordId {
65    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
66        write!(f, "chord:{}", self.0)
67    }
68}
69
70#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
71pub enum ButtonPhase {
72    Down,
73    Up,
74}
75
76#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
77pub enum RawLevel {
78    Low,
79    High,
80}
81
82impl From<bool> for RawLevel {
83    fn from(high: bool) -> Self {
84        if high {
85            Self::High
86        } else {
87            Self::Low
88        }
89    }
90}
91
92/// One atomic GPIO snapshot. `levels` uses configured button order.
93#[derive(Debug, Clone, Copy)]
94pub struct ButtonSnapshot<'a> {
95    pub at: Timestamp,
96    pub levels: &'a [RawLevel],
97}
98
99impl ButtonPhase {
100    pub const fn is_down(self) -> bool {
101        matches!(self, Self::Down)
102    }
103}
104
105/// A physical edge after debounce confirmation.
106#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
107pub struct ButtonEdge {
108    pub key: KeyId,
109    pub phase: ButtonPhase,
110    /// Logical time at which the debounced edge occurred.
111    pub occurred_at: Timestamp,
112    /// Time at which this stage recognized the edge.
113    pub recognized_at: Timestamp,
114}
115
116/// A logical control is either one physical key or one virtual chord.
117#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
118pub enum ControlId {
119    Key(KeyId),
120    Chord(ChordId),
121}
122
123/// A logical edge after chord arbitration.
124#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
125pub struct ControlEdge {
126    pub control: ControlId,
127    pub phase: ButtonPhase,
128    /// Original logical edge time, preserved across chord buffering.
129    pub occurred_at: Timestamp,
130    /// Time at which chord arbitration released or recognized the edge.
131    pub recognized_at: Timestamp,
132}
133
134#[derive(Debug, Clone, PartialEq, Eq, Hash)]
135pub enum GestureKind {
136    /// A completed tap sequence. One, two, and higher-order taps share one type.
137    Tap { count: u8 },
138    /// The first configured hold threshold has been reached.
139    HoldStart { threshold: Duration },
140    /// A later configured hold threshold has been reached.
141    HoldMilestone { threshold: Duration },
142    /// One or more repeat intervals elapsed since the previous update.
143    Repeat { count: NonZeroU64 },
144    /// A held control was released.
145    HoldEnd { held_for: Duration },
146}
147
148#[derive(Debug, Clone, PartialEq, Eq, Hash)]
149pub enum ButtonEventKind {
150    State {
151        control: ControlId,
152        phase: ButtonPhase,
153    },
154    Gesture {
155        control: ControlId,
156        kind: GestureKind,
157    },
158}
159
160/// Domain event emitted by the recognition pipeline.
161#[derive(Debug, Clone, PartialEq, Eq, Hash)]
162pub struct ButtonEvent {
163    /// Logical time of the state change, deadline, or final tap release.
164    pub occurred_at: Timestamp,
165    /// Time at which the framework emitted this event.
166    pub recognized_at: Timestamp,
167    pub kind: ButtonEventKind,
168}
169
170impl ButtonEvent {
171    pub const fn state(edge: ControlEdge) -> Self {
172        Self {
173            occurred_at: edge.occurred_at,
174            recognized_at: edge.recognized_at,
175            kind: ButtonEventKind::State {
176                control: edge.control,
177                phase: edge.phase,
178            },
179        }
180    }
181
182    pub fn gesture(
183        control: ControlId,
184        kind: GestureKind,
185        occurred_at: Timestamp,
186        recognized_at: Timestamp,
187    ) -> Self {
188        Self {
189            occurred_at,
190            recognized_at,
191            kind: ButtonEventKind::Gesture { control, kind },
192        }
193    }
194}
195
196/// Owned output of one framework update.
197#[derive(Debug, Clone, Default, PartialEq, Eq)]
198pub struct EventBatch {
199    /// Time through which the engine processed inputs and deadlines.
200    pub processed_at: Timestamp,
201    /// Immediate physical edges, before any chord suppression or delay.
202    pub physical: Vec<ButtonEdge>,
203    /// Logical state and gesture events.
204    pub events: Vec<ButtonEvent>,
205    /// Earliest gesture or chord deadline, if one is pending.
206    pub next_wakeup: Option<Timestamp>,
207}
208
209impl EventBatch {
210    pub fn new(processed_at: Timestamp) -> Self {
211        Self {
212            processed_at,
213            physical: Vec::new(),
214            events: Vec::new(),
215            next_wakeup: None,
216        }
217    }
218
219    pub fn is_empty(&self) -> bool {
220        self.physical.is_empty() && self.events.is_empty()
221    }
222}