Skip to main content

btn_recognizer/key/
engine.rs

1use std::cmp;
2use std::collections::HashSet;
3use std::error::Error;
4use std::fmt;
5use std::time::Duration;
6
7use super::chord::{ChordError, ChordResolver};
8use super::config::{ConfigError, FrameworkConfig, GestureConfig};
9use super::debounce::{DebounceBank, DebounceBankError};
10use super::gesture::{GestureBank, GestureError};
11use super::types::{
12    ButtonEvent, ButtonPhase, ButtonSnapshot, ControlId, EventBatch, KeyId, Timestamp,
13};
14
15/// Complete physical-to-gesture recognition pipeline.
16#[derive(Debug, Clone)]
17pub struct ButtonEngine {
18    config: FrameworkConfig,
19    debounce: DebounceBank,
20    chords: ChordResolver,
21    gestures: GestureBank,
22    last_update: Option<Timestamp>,
23    max_future_span: Duration,
24}
25
26impl ButtonEngine {
27    pub fn new(config: FrameworkConfig) -> Result<Self, ConfigError> {
28        config.validate()?;
29        let max_future_span = max_future_span(&config);
30        Ok(Self {
31            debounce: DebounceBank::new(&config.buttons),
32            chords: ChordResolver::new_validated(&config.chords),
33            gestures: GestureBank::new_validated(&config),
34            config,
35            last_update: None,
36            max_future_span,
37        })
38    }
39
40    /// Process one atomic, complete GPIO snapshot.
41    pub fn update(&mut self, snapshot: ButtonSnapshot<'_>) -> Result<EventBatch, UpdateError> {
42        self.preflight(snapshot.at)?;
43        if snapshot.levels.len() != self.config.buttons.len() {
44            return Err(UpdateError::SnapshotLength {
45                expected: self.config.buttons.len(),
46                actual: snapshot.levels.len(),
47            });
48        }
49
50        let physical = self
51            .debounce
52            .update(snapshot.at, snapshot.levels)
53            .map_err(UpdateError::Debounce)?;
54        self.finish_update(snapshot.at, physical)
55    }
56
57    /// Advance chord and gesture deadlines without claiming a new GPIO sample.
58    pub fn advance_to(&mut self, now: Timestamp) -> Result<EventBatch, UpdateError> {
59        self.preflight(now)?;
60        self.finish_update(now, Vec::new())
61    }
62
63    pub fn config(&self) -> &FrameworkConfig {
64        &self.config
65    }
66
67    pub fn next_wakeup(&self) -> Option<Timestamp> {
68        let suspended = pending_key_set(&self.chords);
69        match (
70            self.chords.next_deadline(),
71            self.gestures.next_deadline_excluding(&suspended),
72        ) {
73            (Some(left), Some(right)) => Some(cmp::min(left, right)),
74            (Some(value), None) | (None, Some(value)) => Some(value),
75            (None, None) => None,
76        }
77    }
78
79    fn preflight(&self, now: Timestamp) -> Result<(), UpdateError> {
80        if let Some(previous) = self.last_update {
81            if now < previous {
82                return Err(UpdateError::TimeRegression { previous, now });
83            }
84        }
85        if now.checked_add(self.max_future_span).is_none() {
86            return Err(UpdateError::TimestampExhausted {
87                now,
88                required_headroom: self.max_future_span,
89            });
90        }
91        Ok(())
92    }
93
94    fn finish_update(
95        &mut self,
96        now: Timestamp,
97        physical: Vec<super::types::ButtonEdge>,
98    ) -> Result<EventBatch, UpdateError> {
99        let pending_before = pending_key_set(&self.chords);
100        let mut events = self
101            .gestures
102            .advance_before(now, &pending_before)
103            .map_err(UpdateError::Gesture)?;
104
105        let control_edges = self
106            .chords
107            .process_batch(now, &physical)
108            .map_err(UpdateError::Chord)?;
109        let pending_after = pending_key_set(&self.chords);
110
111        // Keys which disappeared from arbitration without a replayed key Down
112        // were claimed by a chord. Their existing gesture clocks can now move
113        // forward, but the claimed press itself must never reach the key
114        // recognizer.
115        let replayed_downs: HashSet<_> = control_edges
116            .iter()
117            .filter_map(|edge| match (edge.control, edge.phase) {
118                (ControlId::Key(key), ButtonPhase::Down) => Some(key),
119                _ => None,
120            })
121            .collect();
122        let mut candidates = pending_before;
123        candidates.extend(
124            physical
125                .iter()
126                .filter(|edge| edge.phase == ButtonPhase::Down)
127                .map(|edge| edge.key),
128        );
129        let claimed: HashSet<_> = candidates
130            .difference(&pending_after)
131            .copied()
132            .filter(|key| !replayed_downs.contains(key))
133            .collect();
134        events.extend(
135            self.gestures
136                .resolve_suspensions(&claimed, now)
137                .map_err(UpdateError::Gesture)?,
138        );
139
140        events.extend(
141            self.gestures
142                .process_edges(control_edges)
143                .map_err(UpdateError::Gesture)?,
144        );
145        events.extend(
146            self.gestures
147                .advance_through(now, &pending_after)
148                .map_err(UpdateError::Gesture)?,
149        );
150
151        validate_causality(now, &physical, &events)?;
152        self.last_update = Some(now);
153        let mut batch = EventBatch::new(now);
154        batch.physical = physical;
155        batch.events = events;
156        batch.next_wakeup = self.next_wakeup();
157        Ok(batch)
158    }
159}
160
161#[derive(Debug, Clone, PartialEq, Eq)]
162pub enum UpdateError {
163    SnapshotLength {
164        expected: usize,
165        actual: usize,
166    },
167    TimeRegression {
168        previous: Timestamp,
169        now: Timestamp,
170    },
171    TimestampExhausted {
172        now: Timestamp,
173        required_headroom: Duration,
174    },
175    Debounce(DebounceBankError),
176    Chord(ChordError),
177    Gesture(GestureError),
178    InvalidOutputCausality,
179}
180
181impl fmt::Display for UpdateError {
182    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
183        match self {
184            Self::SnapshotLength { expected, actual } => {
185                write!(f, "expected {expected} GPIO levels, received {actual}")
186            }
187            Self::TimeRegression { previous, now } => {
188                write!(f, "button engine time regressed from {previous} to {now}")
189            }
190            Self::TimestampExhausted {
191                now,
192                required_headroom,
193            } => write!(
194                f,
195                "timestamp {now} lacks required deadline headroom {required_headroom:?}"
196            ),
197            Self::Debounce(source) => write!(f, "debounce stage failed: {source}"),
198            Self::Chord(source) => write!(f, "chord stage failed: {source}"),
199            Self::Gesture(source) => write!(f, "gesture stage failed: {source}"),
200            Self::InvalidOutputCausality => {
201                write!(f, "a stage produced an event outside the processed time")
202            }
203        }
204    }
205}
206
207impl Error for UpdateError {
208    fn source(&self) -> Option<&(dyn Error + 'static)> {
209        match self {
210            Self::Debounce(source) => Some(source),
211            Self::Chord(source) => Some(source),
212            Self::Gesture(source) => Some(source),
213            _ => None,
214        }
215    }
216}
217
218fn pending_key_set(chords: &ChordResolver) -> HashSet<KeyId> {
219    chords.pending_keys().into_iter().collect()
220}
221
222fn max_future_span(config: &FrameworkConfig) -> Duration {
223    let mut maximum = Duration::ZERO;
224    for chord in &config.chords {
225        maximum = cmp::max(maximum, chord.window);
226    }
227    maximum = cmp::max(maximum, gesture_future_span(&config.default_gestures));
228    for gestures in config.gesture_overrides.values() {
229        maximum = cmp::max(maximum, gesture_future_span(gestures));
230    }
231    maximum
232}
233
234fn gesture_future_span(config: &GestureConfig) -> Duration {
235    let mut maximum = config.multi_tap_window;
236    if let Some(&threshold) = config.hold_thresholds.last() {
237        maximum = cmp::max(maximum, threshold);
238    }
239    if let Some(repeat) = &config.repeat {
240        maximum = cmp::max(maximum, repeat.starts_after);
241        maximum = cmp::max(maximum, repeat.interval);
242    }
243    maximum
244}
245
246fn validate_causality(
247    processed_at: Timestamp,
248    physical: &[super::types::ButtonEdge],
249    events: &[ButtonEvent],
250) -> Result<(), UpdateError> {
251    let valid_physical = physical
252        .iter()
253        .all(|edge| edge.occurred_at <= edge.recognized_at && edge.recognized_at <= processed_at);
254    let valid_events = events.iter().all(|event| {
255        event.occurred_at <= event.recognized_at && event.recognized_at <= processed_at
256    });
257    if valid_physical && valid_events {
258        Ok(())
259    } else {
260        Err(UpdateError::InvalidOutputCausality)
261    }
262}
263
264#[cfg(test)]
265mod tests {
266    use std::collections::HashMap;
267
268    use super::*;
269    use crate::key::config::{
270        ActiveLevel, ButtonConfig, ChordConfig, ChordReleasePolicy, DebounceConfig, GestureConfig,
271    };
272    use crate::key::types::{
273        ButtonEventKind, ButtonPhase, ChordId, ControlId, GestureKind, KeyId, RawLevel,
274    };
275
276    fn time(ms: u64) -> Timestamp {
277        Timestamp::from_millis(ms)
278    }
279
280    fn button(id: u16) -> ButtonConfig {
281        ButtonConfig {
282            id: KeyId(id),
283            active_level: ActiveLevel::Low,
284            debounce: DebounceConfig::symmetric(Duration::ZERO),
285            initially_pressed: false,
286        }
287    }
288
289    fn config(chord: bool) -> FrameworkConfig {
290        FrameworkConfig {
291            buttons: vec![button(1), button(2)],
292            chords: if chord {
293                vec![ChordConfig {
294                    id: ChordId(7),
295                    members: vec![KeyId(1), KeyId(2)],
296                    window: Duration::from_millis(50),
297                    priority: 0,
298                    release: ChordReleasePolicy::AnyMember,
299                }]
300            } else {
301                Vec::new()
302            },
303            default_gestures: GestureConfig::default(),
304            gesture_overrides: HashMap::new(),
305        }
306    }
307
308    fn snapshot<'a>(at: u64, levels: &'a [RawLevel]) -> ButtonSnapshot<'a> {
309        ButtonSnapshot {
310            at: time(at),
311            levels,
312        }
313    }
314
315    fn state_events(batch: &EventBatch) -> Vec<(ControlId, ButtonPhase)> {
316        batch
317            .events
318            .iter()
319            .filter_map(|event| match event.kind {
320                ButtonEventKind::State { control, phase } => Some((control, phase)),
321                ButtonEventKind::Gesture { .. } => None,
322            })
323            .collect()
324    }
325
326    #[test]
327    fn non_chord_key_flows_from_physical_to_logical_state() {
328        let mut engine = ButtonEngine::new(config(false)).unwrap();
329        let batch = engine
330            .update(snapshot(0, &[RawLevel::Low, RawLevel::High]))
331            .unwrap();
332        assert_eq!(batch.physical.len(), 1);
333        assert_eq!(
334            state_events(&batch),
335            vec![(ControlId::Key(KeyId(1)), ButtonPhase::Down)]
336        );
337    }
338
339    #[test]
340    fn successful_chord_suppresses_member_logical_edges() {
341        let mut engine = ButtonEngine::new(config(true)).unwrap();
342        let first = engine
343            .update(snapshot(0, &[RawLevel::Low, RawLevel::High]))
344            .unwrap();
345        assert_eq!(first.physical.len(), 1);
346        assert!(first.events.is_empty());
347        assert_eq!(first.next_wakeup, Some(time(50)));
348
349        let second = engine
350            .update(snapshot(50, &[RawLevel::Low, RawLevel::Low]))
351            .unwrap();
352        assert_eq!(
353            state_events(&second),
354            vec![(ControlId::Chord(ChordId(7)), ButtonPhase::Down)]
355        );
356        assert!(second.events.iter().all(|event| !matches!(
357            event.kind,
358            ButtonEventKind::State {
359                control: ControlId::Key(_),
360                ..
361            }
362        )));
363    }
364
365    #[test]
366    fn failed_chord_replay_uses_original_occurrence_time() {
367        let mut engine = ButtonEngine::new(config(true)).unwrap();
368        engine
369            .update(snapshot(0, &[RawLevel::Low, RawLevel::High]))
370            .unwrap();
371        let batch = engine.advance_to(time(50)).unwrap();
372        let event = batch.events.first().unwrap();
373        assert_eq!(event.occurred_at, time(0));
374        assert_eq!(event.recognized_at, time(50));
375        assert_eq!(
376            event.kind,
377            ButtonEventKind::State {
378                control: ControlId::Key(KeyId(1)),
379                phase: ButtonPhase::Down,
380            }
381        );
382    }
383
384    #[test]
385    fn chord_is_reused_as_a_tap_control() {
386        let mut engine = ButtonEngine::new(config(true)).unwrap();
387        engine
388            .update(snapshot(0, &[RawLevel::Low, RawLevel::High]))
389            .unwrap();
390        engine
391            .update(snapshot(20, &[RawLevel::Low, RawLevel::Low]))
392            .unwrap();
393        engine
394            .update(snapshot(40, &[RawLevel::High, RawLevel::Low]))
395            .unwrap();
396        engine
397            .update(snapshot(60, &[RawLevel::High, RawLevel::High]))
398            .unwrap();
399        let batch = engine.advance_to(time(540)).unwrap();
400        assert!(batch.events.iter().any(|event| {
401            event.kind
402                == ButtonEventKind::Gesture {
403                    control: ControlId::Chord(ChordId(7)),
404                    kind: GestureKind::Tap { count: 1 },
405                }
406        }));
407    }
408
409    #[test]
410    fn pending_chord_down_preserves_exact_double_tap_boundary() {
411        let mut engine = ButtonEngine::new(config(true)).unwrap();
412        engine
413            .update(snapshot(0, &[RawLevel::Low, RawLevel::High]))
414            .unwrap();
415        engine.advance_to(time(50)).unwrap();
416        engine
417            .update(snapshot(60, &[RawLevel::High, RawLevel::High]))
418            .unwrap();
419
420        let pending = engine
421            .update(snapshot(560, &[RawLevel::Low, RawLevel::High]))
422            .unwrap();
423        assert!(!pending.events.iter().any(|event| matches!(
424            event.kind,
425            ButtonEventKind::Gesture {
426                kind: GestureKind::Tap { count: 1 },
427                ..
428            }
429        )));
430        engine.advance_to(time(610)).unwrap();
431        let finished = engine
432            .update(snapshot(620, &[RawLevel::High, RawLevel::High]))
433            .unwrap();
434        assert!(finished.events.iter().any(|event| {
435            event.kind
436                == ButtonEventKind::Gesture {
437                    control: ControlId::Key(KeyId(1)),
438                    kind: GestureKind::Tap { count: 2 },
439                }
440        }));
441    }
442
443    #[test]
444    fn front_end_errors_do_not_advance_engine_time() {
445        let mut engine = ButtonEngine::new(config(false)).unwrap();
446        assert_eq!(
447            engine.update(snapshot(10, &[])),
448            Err(UpdateError::SnapshotLength {
449                expected: 2,
450                actual: 0,
451            })
452        );
453        assert!(engine
454            .update(snapshot(9, &[RawLevel::High, RawLevel::High]))
455            .is_ok());
456        assert_eq!(
457            engine.advance_to(time(8)),
458            Err(UpdateError::TimeRegression {
459                previous: time(9),
460                now: time(8),
461            })
462        );
463    }
464}