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::time::Duration;

use fsm_engine::key::{
    ActiveLevel, ButtonConfig, ButtonEngine, ButtonEventKind, ButtonPhase, ButtonSnapshot,
    ChordConfig, ChordId, ChordReleasePolicy, ControlId, DebounceConfig, EventBatch,
    FrameworkConfig, GestureConfig, GestureKind, HoldAfterTapPolicy, KeyId, RawLevel, RepeatConfig,
    Timestamp,
};

const KEYS: [KeyId; 3] = [KeyId(1), KeyId(2), KeyId(3)];

fn framework() -> FrameworkConfig {
    let button = |id| ButtonConfig {
        id,
        active_level: ActiveLevel::Low,
        debounce: DebounceConfig::symmetric(Duration::ZERO),
        initially_pressed: false,
    };
    FrameworkConfig {
        buttons: KEYS.into_iter().map(button).collect(),
        chords: vec![
            ChordConfig {
                id: ChordId(1),
                members: vec![KeyId(1), KeyId(2)],
                window: Duration::from_millis(17),
                priority: 2,
                release: ChordReleasePolicy::AnyMember,
            },
            ChordConfig {
                id: ChordId(2),
                members: vec![KeyId(2), KeyId(3)],
                window: Duration::from_millis(23),
                priority: 1,
                release: ChordReleasePolicy::AllMembers,
            },
        ],
        default_gestures: GestureConfig {
            tap_max: Duration::from_millis(30),
            multi_tap_window: Duration::from_millis(41),
            max_taps: 3,
            hold_thresholds: vec![Duration::from_millis(20), Duration::from_millis(60)],
            repeat: Some(RepeatConfig {
                starts_after: Duration::from_millis(30),
                interval: Duration::from_millis(10),
            }),
            hold_after_tap: HoldAfterTapPolicy::CommitPendingTaps,
        },
        gesture_overrides: HashMap::new(),
    }
}

fn next_random(state: &mut u64) -> u64 {
    *state = state
        .wrapping_mul(6_364_136_223_846_793_005)
        .wrapping_add(1_442_695_040_888_963_407);
    *state
}

#[derive(Default)]
struct Invariants {
    physical_down: HashMap<KeyId, bool>,
    control_down: HashMap<ControlId, bool>,
    holding: HashSet<ControlId>,
}

impl Invariants {
    fn observe(&mut self, batch: &EventBatch) {
        for edge in &batch.physical {
            assert!(edge.occurred_at <= edge.recognized_at);
            assert!(edge.recognized_at <= batch.processed_at);
            let down = self.physical_down.entry(edge.key).or_default();
            assert_eq!(
                edge.phase,
                if *down {
                    ButtonPhase::Up
                } else {
                    ButtonPhase::Down
                }
            );
            *down = !*down;
        }

        for event in &batch.events {
            assert!(event.occurred_at <= event.recognized_at);
            assert!(event.recognized_at <= batch.processed_at);
            match &event.kind {
                ButtonEventKind::State { control, phase } => {
                    let down = self.control_down.entry(*control).or_default();
                    assert_eq!(
                        *phase,
                        if *down {
                            ButtonPhase::Up
                        } else {
                            ButtonPhase::Down
                        },
                        "non-alternating logical state for {control:?}"
                    );
                    *down = !*down;
                }
                ButtonEventKind::Gesture { control, kind } => match kind {
                    GestureKind::Tap { count } => assert!((1..=3).contains(count)),
                    GestureKind::HoldStart { .. } => {
                        assert!(self.holding.insert(*control), "duplicate HoldStart");
                    }
                    GestureKind::HoldMilestone { .. } => {
                        assert!(self.holding.contains(control), "milestone outside hold");
                    }
                    GestureKind::Repeat { count } => {
                        assert!(self.holding.contains(control), "repeat outside hold");
                        assert!(count.get() > 0);
                    }
                    GestureKind::HoldEnd { .. } => {
                        assert!(self.holding.remove(control), "HoldEnd without HoldStart");
                    }
                },
            }
        }
    }

    fn assert_quiescent(&self) {
        assert!(self.physical_down.values().all(|pressed| !pressed));
        assert!(self.control_down.values().all(|pressed| !pressed));
        assert!(self.holding.is_empty());
    }
}

#[test]
fn deterministic_random_pipeline_preserves_invariants_and_quiesces() {
    for seed in 0..256_u64 {
        let config = framework();
        let mut left = ButtonEngine::new(config.clone()).unwrap();
        let mut right = ButtonEngine::new(config).unwrap();
        let mut invariants = Invariants::default();
        let mut random = seed ^ 0xd1b5_4a32_d192_ed03;
        let mut millis = 0_u64;
        let mut pressed = [false; 3];

        for _ in 0..4096 {
            let value = next_random(&mut random);
            millis += if value % 97 == 0 {
                100 + value % 200
            } else {
                value % 8
            };
            for (index, state) in pressed.iter_mut().enumerate() {
                if value.rotate_left((index * 13) as u32) % 11 < 2 {
                    *state = !*state;
                }
            }
            let levels = pressed.map(|state| if state { RawLevel::Low } else { RawLevel::High });
            let snapshot = ButtonSnapshot {
                at: Timestamp::from_millis(millis),
                levels: &levels,
            };
            let left_batch = left.update(snapshot).unwrap();
            let right_batch = right.update(snapshot).unwrap();
            assert_eq!(left_batch, right_batch, "non-deterministic seed={seed}");
            assert!(
                left_batch.events.len() <= 32,
                "unbounded per-update output seed={seed}: {left_batch:?}"
            );
            invariants.observe(&left_batch);
        }

        millis += 1;
        let released = [RawLevel::High; 3];
        let snapshot = ButtonSnapshot {
            at: Timestamp::from_millis(millis),
            levels: &released,
        };
        let left_batch = left.update(snapshot).unwrap();
        let right_batch = right.update(snapshot).unwrap();
        assert_eq!(left_batch, right_batch);
        invariants.observe(&left_batch);

        millis += 1_000;
        let left_batch = left.advance_to(Timestamp::from_millis(millis)).unwrap();
        let right_batch = right.advance_to(Timestamp::from_millis(millis)).unwrap();
        assert_eq!(left_batch, right_batch);
        invariants.observe(&left_batch);
        invariants.assert_quiescent();
        assert_eq!(left_batch.next_wakeup, None);

        let quiet = left.advance_to(Timestamp::from_millis(millis + 1)).unwrap();
        assert!(quiet.is_empty(), "non-quiescent seed={seed}: {quiet:?}");
        assert_eq!(quiet.next_wakeup, None);
    }
}