btn-recognizer 0.2.2

Timestamp-driven button debouncing with multi-tap, hold, repeat, and multi-key chord gesture recognition
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
use std::cmp;
use std::collections::HashSet;
use std::error::Error;
use std::fmt;
use std::time::Duration;

use super::chord::{ChordError, ChordResolver};
use super::config::{ConfigError, FrameworkConfig, GestureConfig};
use super::debounce::{DebounceBank, DebounceBankError};
use super::gesture::{GestureBank, GestureError};
use super::types::{
    ButtonEvent, ButtonPhase, ButtonSnapshot, ControlId, EventBatch, KeyId, Timestamp,
};

/// Complete physical-to-gesture recognition pipeline.
#[derive(Debug, Clone)]
pub struct ButtonEngine {
    config: FrameworkConfig,
    debounce: DebounceBank,
    chords: ChordResolver,
    gestures: GestureBank,
    last_update: Option<Timestamp>,
    max_future_span: Duration,
}

impl ButtonEngine {
    pub fn new(config: FrameworkConfig) -> Result<Self, ConfigError> {
        config.validate()?;
        let max_future_span = max_future_span(&config);
        Ok(Self {
            debounce: DebounceBank::new(&config.buttons),
            chords: ChordResolver::new_validated(&config.chords),
            gestures: GestureBank::new_validated(&config),
            config,
            last_update: None,
            max_future_span,
        })
    }

    /// Process one atomic, complete GPIO snapshot.
    pub fn update(&mut self, snapshot: ButtonSnapshot<'_>) -> Result<EventBatch, UpdateError> {
        self.preflight(snapshot.at)?;
        if snapshot.levels.len() != self.config.buttons.len() {
            return Err(UpdateError::SnapshotLength {
                expected: self.config.buttons.len(),
                actual: snapshot.levels.len(),
            });
        }

        let physical = self
            .debounce
            .update(snapshot.at, snapshot.levels)
            .map_err(UpdateError::Debounce)?;
        self.finish_update(snapshot.at, physical)
    }

    /// Advance chord and gesture deadlines without claiming a new GPIO sample.
    pub fn advance_to(&mut self, now: Timestamp) -> Result<EventBatch, UpdateError> {
        self.preflight(now)?;
        self.finish_update(now, Vec::new())
    }

    pub fn config(&self) -> &FrameworkConfig {
        &self.config
    }

    pub fn next_wakeup(&self) -> Option<Timestamp> {
        let suspended = pending_key_set(&self.chords);
        match (
            self.chords.next_deadline(),
            self.gestures.next_deadline_excluding(&suspended),
        ) {
            (Some(left), Some(right)) => Some(cmp::min(left, right)),
            (Some(value), None) | (None, Some(value)) => Some(value),
            (None, None) => None,
        }
    }

    fn preflight(&self, now: Timestamp) -> Result<(), UpdateError> {
        if let Some(previous) = self.last_update {
            if now < previous {
                return Err(UpdateError::TimeRegression { previous, now });
            }
        }
        if now.checked_add(self.max_future_span).is_none() {
            return Err(UpdateError::TimestampExhausted {
                now,
                required_headroom: self.max_future_span,
            });
        }
        Ok(())
    }

    fn finish_update(
        &mut self,
        now: Timestamp,
        physical: Vec<super::types::ButtonEdge>,
    ) -> Result<EventBatch, UpdateError> {
        let pending_before = pending_key_set(&self.chords);
        let mut events = self
            .gestures
            .advance_before(now, &pending_before)
            .map_err(UpdateError::Gesture)?;

        let control_edges = self
            .chords
            .process_batch(now, &physical)
            .map_err(UpdateError::Chord)?;
        let pending_after = pending_key_set(&self.chords);

        // Keys which disappeared from arbitration without a replayed key Down
        // were claimed by a chord. Their existing gesture clocks can now move
        // forward, but the claimed press itself must never reach the key
        // recognizer.
        let replayed_downs: HashSet<_> = control_edges
            .iter()
            .filter_map(|edge| match (edge.control, edge.phase) {
                (ControlId::Key(key), ButtonPhase::Down) => Some(key),
                _ => None,
            })
            .collect();
        let mut candidates = pending_before;
        candidates.extend(
            physical
                .iter()
                .filter(|edge| edge.phase == ButtonPhase::Down)
                .map(|edge| edge.key),
        );
        let claimed: HashSet<_> = candidates
            .difference(&pending_after)
            .copied()
            .filter(|key| !replayed_downs.contains(key))
            .collect();
        events.extend(
            self.gestures
                .resolve_suspensions(&claimed, now)
                .map_err(UpdateError::Gesture)?,
        );

        events.extend(
            self.gestures
                .process_edges(control_edges)
                .map_err(UpdateError::Gesture)?,
        );
        events.extend(
            self.gestures
                .advance_through(now, &pending_after)
                .map_err(UpdateError::Gesture)?,
        );

        validate_causality(now, &physical, &events)?;
        self.last_update = Some(now);
        let mut batch = EventBatch::new(now);
        batch.physical = physical;
        batch.events = events;
        batch.next_wakeup = self.next_wakeup();
        Ok(batch)
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum UpdateError {
    SnapshotLength {
        expected: usize,
        actual: usize,
    },
    TimeRegression {
        previous: Timestamp,
        now: Timestamp,
    },
    TimestampExhausted {
        now: Timestamp,
        required_headroom: Duration,
    },
    Debounce(DebounceBankError),
    Chord(ChordError),
    Gesture(GestureError),
    InvalidOutputCausality,
}

impl fmt::Display for UpdateError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::SnapshotLength { expected, actual } => {
                write!(f, "expected {expected} GPIO levels, received {actual}")
            }
            Self::TimeRegression { previous, now } => {
                write!(f, "button engine time regressed from {previous} to {now}")
            }
            Self::TimestampExhausted {
                now,
                required_headroom,
            } => write!(
                f,
                "timestamp {now} lacks required deadline headroom {required_headroom:?}"
            ),
            Self::Debounce(source) => write!(f, "debounce stage failed: {source}"),
            Self::Chord(source) => write!(f, "chord stage failed: {source}"),
            Self::Gesture(source) => write!(f, "gesture stage failed: {source}"),
            Self::InvalidOutputCausality => {
                write!(f, "a stage produced an event outside the processed time")
            }
        }
    }
}

impl Error for UpdateError {
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        match self {
            Self::Debounce(source) => Some(source),
            Self::Chord(source) => Some(source),
            Self::Gesture(source) => Some(source),
            _ => None,
        }
    }
}

fn pending_key_set(chords: &ChordResolver) -> HashSet<KeyId> {
    chords.pending_keys().into_iter().collect()
}

fn max_future_span(config: &FrameworkConfig) -> Duration {
    let mut maximum = Duration::ZERO;
    for chord in &config.chords {
        maximum = cmp::max(maximum, chord.window);
    }
    maximum = cmp::max(maximum, gesture_future_span(&config.default_gestures));
    for gestures in config.gesture_overrides.values() {
        maximum = cmp::max(maximum, gesture_future_span(gestures));
    }
    maximum
}

fn gesture_future_span(config: &GestureConfig) -> Duration {
    let mut maximum = config.multi_tap_window;
    if let Some(&threshold) = config.hold_thresholds.last() {
        maximum = cmp::max(maximum, threshold);
    }
    if let Some(repeat) = &config.repeat {
        maximum = cmp::max(maximum, repeat.starts_after);
        maximum = cmp::max(maximum, repeat.interval);
    }
    maximum
}

fn validate_causality(
    processed_at: Timestamp,
    physical: &[super::types::ButtonEdge],
    events: &[ButtonEvent],
) -> Result<(), UpdateError> {
    let valid_physical = physical
        .iter()
        .all(|edge| edge.occurred_at <= edge.recognized_at && edge.recognized_at <= processed_at);
    let valid_events = events.iter().all(|event| {
        event.occurred_at <= event.recognized_at && event.recognized_at <= processed_at
    });
    if valid_physical && valid_events {
        Ok(())
    } else {
        Err(UpdateError::InvalidOutputCausality)
    }
}

#[cfg(test)]
mod tests {
    use std::collections::HashMap;

    use super::*;
    use crate::key::config::{
        ActiveLevel, ButtonConfig, ChordConfig, ChordReleasePolicy, DebounceConfig, GestureConfig,
    };
    use crate::key::types::{
        ButtonEventKind, ButtonPhase, ChordId, ControlId, GestureKind, KeyId, RawLevel,
    };

    fn time(ms: u64) -> Timestamp {
        Timestamp::from_millis(ms)
    }

    fn button(id: u16) -> ButtonConfig {
        ButtonConfig {
            id: KeyId(id),
            active_level: ActiveLevel::Low,
            debounce: DebounceConfig::symmetric(Duration::ZERO),
            initially_pressed: false,
        }
    }

    fn config(chord: bool) -> FrameworkConfig {
        FrameworkConfig {
            buttons: vec![button(1), button(2)],
            chords: if chord {
                vec![ChordConfig {
                    id: ChordId(7),
                    members: vec![KeyId(1), KeyId(2)],
                    window: Duration::from_millis(50),
                    priority: 0,
                    release: ChordReleasePolicy::AnyMember,
                }]
            } else {
                Vec::new()
            },
            default_gestures: GestureConfig::default(),
            gesture_overrides: HashMap::new(),
        }
    }

    fn snapshot<'a>(at: u64, levels: &'a [RawLevel]) -> ButtonSnapshot<'a> {
        ButtonSnapshot {
            at: time(at),
            levels,
        }
    }

    fn state_events(batch: &EventBatch) -> Vec<(ControlId, ButtonPhase)> {
        batch
            .events
            .iter()
            .filter_map(|event| match event.kind {
                ButtonEventKind::State { control, phase } => Some((control, phase)),
                ButtonEventKind::Gesture { .. } => None,
            })
            .collect()
    }

    #[test]
    fn non_chord_key_flows_from_physical_to_logical_state() {
        let mut engine = ButtonEngine::new(config(false)).unwrap();
        let batch = engine
            .update(snapshot(0, &[RawLevel::Low, RawLevel::High]))
            .unwrap();
        assert_eq!(batch.physical.len(), 1);
        assert_eq!(
            state_events(&batch),
            vec![(ControlId::Key(KeyId(1)), ButtonPhase::Down)]
        );
    }

    #[test]
    fn successful_chord_suppresses_member_logical_edges() {
        let mut engine = ButtonEngine::new(config(true)).unwrap();
        let first = engine
            .update(snapshot(0, &[RawLevel::Low, RawLevel::High]))
            .unwrap();
        assert_eq!(first.physical.len(), 1);
        assert!(first.events.is_empty());
        assert_eq!(first.next_wakeup, Some(time(50)));

        let second = engine
            .update(snapshot(50, &[RawLevel::Low, RawLevel::Low]))
            .unwrap();
        assert_eq!(
            state_events(&second),
            vec![(ControlId::Chord(ChordId(7)), ButtonPhase::Down)]
        );
        assert!(second.events.iter().all(|event| !matches!(
            event.kind,
            ButtonEventKind::State {
                control: ControlId::Key(_),
                ..
            }
        )));
    }

    #[test]
    fn failed_chord_replay_uses_original_occurrence_time() {
        let mut engine = ButtonEngine::new(config(true)).unwrap();
        engine
            .update(snapshot(0, &[RawLevel::Low, RawLevel::High]))
            .unwrap();
        let batch = engine.advance_to(time(50)).unwrap();
        let event = batch.events.first().unwrap();
        assert_eq!(event.occurred_at, time(0));
        assert_eq!(event.recognized_at, time(50));
        assert_eq!(
            event.kind,
            ButtonEventKind::State {
                control: ControlId::Key(KeyId(1)),
                phase: ButtonPhase::Down,
            }
        );
    }

    #[test]
    fn chord_is_reused_as_a_tap_control() {
        let mut engine = ButtonEngine::new(config(true)).unwrap();
        engine
            .update(snapshot(0, &[RawLevel::Low, RawLevel::High]))
            .unwrap();
        engine
            .update(snapshot(20, &[RawLevel::Low, RawLevel::Low]))
            .unwrap();
        engine
            .update(snapshot(40, &[RawLevel::High, RawLevel::Low]))
            .unwrap();
        engine
            .update(snapshot(60, &[RawLevel::High, RawLevel::High]))
            .unwrap();
        let batch = engine.advance_to(time(540)).unwrap();
        assert!(batch.events.iter().any(|event| {
            event.kind
                == ButtonEventKind::Gesture {
                    control: ControlId::Chord(ChordId(7)),
                    kind: GestureKind::Tap { count: 1 },
                }
        }));
    }

    #[test]
    fn pending_chord_down_preserves_exact_double_tap_boundary() {
        let mut engine = ButtonEngine::new(config(true)).unwrap();
        engine
            .update(snapshot(0, &[RawLevel::Low, RawLevel::High]))
            .unwrap();
        engine.advance_to(time(50)).unwrap();
        engine
            .update(snapshot(60, &[RawLevel::High, RawLevel::High]))
            .unwrap();

        let pending = engine
            .update(snapshot(560, &[RawLevel::Low, RawLevel::High]))
            .unwrap();
        assert!(!pending.events.iter().any(|event| matches!(
            event.kind,
            ButtonEventKind::Gesture {
                kind: GestureKind::Tap { count: 1 },
                ..
            }
        )));
        engine.advance_to(time(610)).unwrap();
        let finished = engine
            .update(snapshot(620, &[RawLevel::High, RawLevel::High]))
            .unwrap();
        assert!(finished.events.iter().any(|event| {
            event.kind
                == ButtonEventKind::Gesture {
                    control: ControlId::Key(KeyId(1)),
                    kind: GestureKind::Tap { count: 2 },
                }
        }));
    }

    #[test]
    fn front_end_errors_do_not_advance_engine_time() {
        let mut engine = ButtonEngine::new(config(false)).unwrap();
        assert_eq!(
            engine.update(snapshot(10, &[])),
            Err(UpdateError::SnapshotLength {
                expected: 2,
                actual: 0,
            })
        );
        assert!(engine
            .update(snapshot(9, &[RawLevel::High, RawLevel::High]))
            .is_ok());
        assert_eq!(
            engine.advance_to(time(8)),
            Err(UpdateError::TimeRegression {
                previous: time(9),
                now: time(8),
            })
        );
    }
}