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
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
//! Adapters from button-domain events to an application's input subsystem.
//!
//! Recognition and delivery are deliberately separated. The recognition core
//! returns an owned [`EventBatch`], while [`QueuedInputSource`] maps its domain
//! events into an unbounded `VecDeque`. A fallible downstream sink therefore
//! cannot make recognition state advance while losing an event.

use std::collections::{HashMap, VecDeque};
use std::error::Error;
use std::fmt;
use std::num::NonZeroU64;
use std::time::Duration;

use super::types::{
    ButtonEvent, ButtonEventKind, ButtonPhase, ControlId, EventBatch, GestureKind, Timestamp,
};

/// Maps one domain event into zero or more owned downstream events.
///
/// Implementations append to `output`; they must not clear or reorder values
/// already present in it. Returning no values is the explicit policy for an
/// ignored domain event.
pub trait EventMapper {
    type Output;
    type Error;

    fn map_event(
        &mut self,
        event: &ButtonEvent,
        output: &mut Vec<Self::Output>,
    ) -> Result<(), Self::Error>;

    /// Map a complete ordered domain batch.
    ///
    /// The default implementation calls [`Self::map_event`] in slice order.
    /// It may have mutated mapper state before a later event fails. Stateful
    /// mappers which require transactional batches should override this method,
    /// preflight the batch, and mutate only after validation succeeds.
    fn map_batch(
        &mut self,
        events: &[ButtonEvent],
        output: &mut Vec<Self::Output>,
    ) -> Result<(), Self::Error> {
        for event in events {
            self.map_event(event, output)?;
        }
        Ok(())
    }
}

/// Pull-based input source backed by an unbounded FIFO.
///
/// A successful enqueue appends the entire mapped batch behind older pending
/// events. Mapping occurs in a temporary vector, so a mapping error never
/// commits a partial batch to the queue. The generic mapper's own state follows
/// its [`EventMapper::map_batch`] contract; the queue cannot roll it back.
#[derive(Debug, Clone)]
pub struct QueuedInputSource<M>
where
    M: EventMapper,
{
    mapper: M,
    pending: VecDeque<M::Output>,
}

impl<M> QueuedInputSource<M>
where
    M: EventMapper,
{
    pub fn new(mapper: M) -> Self {
        Self {
            mapper,
            pending: VecDeque::new(),
        }
    }

    pub fn mapper(&self) -> &M {
        &self.mapper
    }

    pub fn mapper_mut(&mut self) -> &mut M {
        &mut self.mapper
    }

    /// Map and atomically append the logical events in one framework batch.
    ///
    /// Physical diagnostic edges are intentionally not mapped by this adapter.
    /// On success, returns the number of downstream events appended.
    pub fn enqueue_batch(&mut self, batch: &EventBatch) -> Result<usize, M::Error> {
        self.enqueue_events(&batch.events)
    }

    /// Map and atomically append an ordered domain-event slice.
    pub fn enqueue_events(&mut self, events: &[ButtonEvent]) -> Result<usize, M::Error> {
        let mut mapped = Vec::new();
        self.mapper.map_batch(events, &mut mapped)?;
        let appended = mapped.len();
        self.pending.extend(mapped);
        Ok(appended)
    }

    pub fn next_event(&mut self) -> Option<M::Output> {
        self.pending.pop_front()
    }

    pub fn pending_len(&self) -> usize {
        self.pending.len()
    }

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

    /// Remove and return every pending event in FIFO order.
    pub fn drain(&mut self) -> Vec<M::Output> {
        self.pending.drain(..).collect()
    }

    /// Try to deliver every pending event to `sink` in FIFO order.
    ///
    /// When a send fails, ownership of the rejected event is returned by the
    /// sink, restored to the front of the queue, and included in the next retry.
    /// Already accepted events are removed exactly once; the untouched tail
    /// remains in its original order.
    pub fn flush_to<S>(&mut self, sink: &mut S) -> Result<usize, FlushError<S::Error>>
    where
        S: TryEventSink<M::Output>,
    {
        let mut sent = 0;
        while let Some(event) = self.pending.pop_front() {
            match sink.try_send(event) {
                Ok(()) => sent += 1,
                Err(Rejected { event, error }) => {
                    self.pending.push_front(event);
                    return Err(FlushError { sent, error });
                }
            }
        }
        Ok(sent)
    }

    pub fn into_parts(self) -> (M, VecDeque<M::Output>) {
        (self.mapper, self.pending)
    }
}

/// A sink rejection which returns ownership of the unaccepted event.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Rejected<E, Err> {
    pub event: E,
    pub error: Err,
}

impl<E, Err> Rejected<E, Err> {
    pub const fn new(event: E, error: Err) -> Self {
        Self { event, error }
    }

    pub fn into_parts(self) -> (E, Err) {
        (self.event, self.error)
    }
}

/// A fallible, ownership-taking downstream event sink.
///
/// On rejection the sink must return the same unaccepted event in [`Rejected`].
/// This makes retry possible without requiring events to implement `Clone`.
pub trait TryEventSink<E> {
    type Error;

    fn try_send(&mut self, event: E) -> Result<(), Rejected<E, Self::Error>>;
}

/// Failure report from [`QueuedInputSource::flush_to`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FlushError<Err> {
    /// Number of events accepted by the sink during this call.
    pub sent: usize,
    pub error: Err,
}

impl<Err> fmt::Display for FlushError<Err>
where
    Err: fmt::Display,
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "input sink rejected an event after accepting {}: {}",
            self.sent, self.error
        )
    }
}

impl<Err> Error for FlushError<Err>
where
    Err: Error + 'static,
{
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        Some(&self.error)
    }
}

/// Stable identifier assigned by the application to one input source.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct SourceId(pub u32);

impl SourceId {
    pub const fn new(value: u32) -> Self {
        Self(value)
    }

    pub const fn get(self) -> u32 {
        self.0
    }
}

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

/// Logical and recognition times copied from a domain event.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct InputTiming {
    pub occurred_at: Timestamp,
    pub recognized_at: Timestamp,
}

impl From<&ButtonEvent> for InputTiming {
    fn from(event: &ButtonEvent) -> Self {
        Self {
            occurred_at: event.occurred_at,
            recognized_at: event.recognized_at,
        }
    }
}

/// Common values understood by button-oriented input subsystems.
///
/// A binding chooses the value explicitly. `Count` and `Duration` are available
/// for applications which want semantic payloads; fixed press/release/pulse
/// mappings can use the dedicated variants.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum InputValue {
    Released,
    Pressed,
    Repeat(NonZeroU64),
    Trigger,
    Count(NonZeroU64),
    Duration(Duration),
    Scalar(i64),
}

/// Fully owned event ready for an application input subsystem.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct InputEvent<Code> {
    pub source: SourceId,
    pub sequence: u64,
    pub timing: InputTiming,
    pub code: Code,
    pub value: InputValue,
}

/// Domain-event portion used when looking up configured bindings.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum EventSelector {
    State(ButtonPhase),
    Tap { count: u8 },
    HoldStart { threshold: Duration },
    HoldMilestone { threshold: Duration },
    Repeat,
    HoldEnd,
}

impl EventSelector {
    /// Return the control and selector represented by a domain event.
    pub fn classify(event: &ButtonEvent) -> (ControlId, Self) {
        match &event.kind {
            ButtonEventKind::State { control, phase } => (*control, Self::State(*phase)),
            ButtonEventKind::Gesture { control, kind } => {
                let selector = match kind {
                    GestureKind::Tap { count } => Self::Tap { count: *count },
                    GestureKind::HoldStart { threshold } => Self::HoldStart {
                        threshold: *threshold,
                    },
                    GestureKind::HoldMilestone { threshold } => Self::HoldMilestone {
                        threshold: *threshold,
                    },
                    GestureKind::Repeat { .. } => Self::Repeat,
                    GestureKind::HoldEnd { .. } => Self::HoldEnd,
                };
                (*control, selector)
            }
        }
    }
}

/// One configured downstream output for a domain selector.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Binding<Code> {
    pub code: Code,
    pub value: BindingValue,
}

impl<Code> Binding<Code> {
    pub const fn new(code: Code, value: InputValue) -> Self {
        Self {
            code,
            value: BindingValue::Fixed(value),
        }
    }

    pub const fn auto(code: Code) -> Self {
        Self {
            code,
            value: BindingValue::Auto,
        }
    }
}

/// Selects either an explicitly configured value or the domain payload.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BindingValue {
    Fixed(InputValue),
    Auto,
}

/// Configurable mapping from `(ControlId, EventSelector)` to downstream events.
///
/// Multiple bindings may be registered for the same key. They are emitted in
/// registration order. Unmapped events intentionally produce no output.
#[derive(Debug, Clone)]
pub struct BindingMapper<Code> {
    source: SourceId,
    next_sequence: Option<u64>,
    bindings: HashMap<(ControlId, EventSelector), Vec<Binding<Code>>>,
}

impl<Code> BindingMapper<Code> {
    pub fn new(source: SourceId) -> Self {
        Self::with_initial_sequence(source, 0)
    }

    pub fn with_initial_sequence(source: SourceId, next_sequence: u64) -> Self {
        Self {
            source,
            next_sequence: Some(next_sequence),
            bindings: HashMap::new(),
        }
    }

    pub const fn source(&self) -> SourceId {
        self.source
    }

    /// Sequence which will be assigned next, or `None` after `u64::MAX` was used.
    pub const fn next_sequence(&self) -> Option<u64> {
        self.next_sequence
    }

    /// Append a binding for `(control, selector)`.
    pub fn bind(
        &mut self,
        control: ControlId,
        selector: EventSelector,
        code: Code,
        value: InputValue,
    ) -> &mut Self {
        self.bindings
            .entry((control, selector))
            .or_default()
            .push(Binding::new(code, value));
        self
    }

    /// Fluent, ownership-taking form of [`Self::bind`].
    pub fn with_binding(
        mut self,
        control: ControlId,
        selector: EventSelector,
        code: Code,
        value: InputValue,
    ) -> Self {
        self.bind(control, selector, code, value);
        self
    }

    /// Append a binding whose value is derived from the matched event.
    pub fn bind_auto(
        &mut self,
        control: ControlId,
        selector: EventSelector,
        code: Code,
    ) -> &mut Self {
        self.bindings
            .entry((control, selector))
            .or_default()
            .push(Binding::auto(code));
        self
    }

    pub fn binding_count(&self) -> usize {
        self.bindings.values().map(Vec::len).sum()
    }

    fn mapped_output_count(&self, events: &[ButtonEvent]) -> Result<usize, BindingError> {
        events.iter().try_fold(0usize, |total, event| {
            let key = EventSelector::classify(event);
            let additional = self.bindings.get(&key).map_or(0, Vec::len);
            total
                .checked_add(additional)
                .ok_or(BindingError::SequenceOverflow {
                    next_sequence: self.next_sequence,
                    required: usize::MAX,
                })
        })
    }

    fn sequence_after(&self, required: usize) -> Result<Option<u64>, BindingError> {
        if required == 0 {
            return Ok(self.next_sequence);
        }

        let start = self.next_sequence.ok_or(BindingError::SequenceOverflow {
            next_sequence: None,
            required,
        })?;
        let additional =
            u64::try_from(required - 1).map_err(|_| BindingError::SequenceOverflow {
                next_sequence: Some(start),
                required,
            })?;
        let last = start
            .checked_add(additional)
            .ok_or(BindingError::SequenceOverflow {
                next_sequence: Some(start),
                required,
            })?;
        Ok(last.checked_add(1))
    }

    fn map_events_checked(
        &mut self,
        events: &[ButtonEvent],
        output: &mut Vec<InputEvent<Code>>,
    ) -> Result<(), BindingError>
    where
        Code: Clone,
    {
        let required = self.mapped_output_count(events)?;
        let sequence_after = self.sequence_after(required)?;
        // Validate every automatic payload before changing output or sequence.
        for event in events {
            let key = EventSelector::classify(event);
            if self.bindings.get(&key).is_some_and(|bindings| {
                bindings
                    .iter()
                    .any(|binding| binding.value == BindingValue::Auto)
            }) {
                automatic_value(event)?;
            }
        }
        let mut sequence = self.next_sequence;

        for event in events {
            let key = EventSelector::classify(event);
            let Some(bindings) = self.bindings.get(&key) else {
                continue;
            };
            for binding in bindings {
                let current = sequence.expect("sequence capacity was preflighted");
                output.push(InputEvent {
                    source: self.source,
                    sequence: current,
                    timing: InputTiming::from(event),
                    code: binding.code.clone(),
                    value: match binding.value {
                        BindingValue::Fixed(value) => value,
                        BindingValue::Auto => {
                            automatic_value(event).expect("automatic payloads were preflighted")
                        }
                    },
                });
                sequence = current.checked_add(1);
            }
        }

        debug_assert_eq!(sequence, sequence_after);
        self.next_sequence = sequence_after;
        Ok(())
    }
}

impl<Code> EventMapper for BindingMapper<Code>
where
    Code: Clone,
{
    type Output = InputEvent<Code>;
    type Error = BindingError;

    fn map_event(
        &mut self,
        event: &ButtonEvent,
        output: &mut Vec<Self::Output>,
    ) -> Result<(), Self::Error> {
        self.map_events_checked(std::slice::from_ref(event), output)
    }

    fn map_batch(
        &mut self,
        events: &[ButtonEvent],
        output: &mut Vec<Self::Output>,
    ) -> Result<(), Self::Error> {
        self.map_events_checked(events, output)
    }
}

/// Binding mapper failure. No output or sequence state is changed on failure.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum BindingError {
    SequenceOverflow {
        next_sequence: Option<u64>,
        required: usize,
    },
    InvalidTapCount,
}

impl fmt::Display for BindingError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::SequenceOverflow {
                next_sequence,
                required,
            } => write!(
                f,
                "cannot allocate {required} input sequence numbers starting at {next_sequence:?}"
            ),
            Self::InvalidTapCount => write!(f, "a tap event contains count=0"),
        }
    }
}

impl Error for BindingError {}

fn automatic_value(event: &ButtonEvent) -> Result<InputValue, BindingError> {
    match &event.kind {
        ButtonEventKind::State { phase, .. } => Ok(match phase {
            ButtonPhase::Down => InputValue::Pressed,
            ButtonPhase::Up => InputValue::Released,
        }),
        ButtonEventKind::Gesture { kind, .. } => match kind {
            GestureKind::Tap { count } => NonZeroU64::new(u64::from(*count))
                .map(InputValue::Count)
                .ok_or(BindingError::InvalidTapCount),
            GestureKind::HoldStart { threshold } | GestureKind::HoldMilestone { threshold } => {
                Ok(InputValue::Duration(*threshold))
            }
            GestureKind::Repeat { count } => Ok(InputValue::Repeat(*count)),
            GestureKind::HoldEnd { held_for } => Ok(InputValue::Duration(*held_for)),
        },
    }
}

#[cfg(test)]
mod tests {
    use super::super::types::{ChordId, KeyId};
    use super::*;

    const KEY_A: ControlId = ControlId::Key(KeyId(1));
    const KEY_B: ControlId = ControlId::Key(KeyId(2));

    fn state(control: ControlId, phase: ButtonPhase, at: u64) -> ButtonEvent {
        ButtonEvent {
            occurred_at: Timestamp::from_millis(at),
            recognized_at: Timestamp::from_millis(at + 1),
            kind: ButtonEventKind::State { control, phase },
        }
    }

    fn tap(control: ControlId, count: u8, at: u64) -> ButtonEvent {
        ButtonEvent::gesture(
            control,
            GestureKind::Tap { count },
            Timestamp::from_millis(at),
            Timestamp::from_millis(at + 2),
        )
    }

    fn batch(events: Vec<ButtonEvent>) -> EventBatch {
        let mut batch = EventBatch::new(Timestamp::from_millis(100));
        batch.events = events;
        batch
    }

    #[derive(Debug, Clone, PartialEq, Eq)]
    struct FanOutMapper;

    impl EventMapper for FanOutMapper {
        type Output = String;
        type Error = &'static str;

        fn map_event(
            &mut self,
            event: &ButtonEvent,
            output: &mut Vec<Self::Output>,
        ) -> Result<(), Self::Error> {
            let (control, selector) = EventSelector::classify(event);
            if control == KEY_B {
                return Err("unmappable B");
            }
            if matches!(selector, EventSelector::State(ButtonPhase::Down)) {
                output.push("first".to_owned());
                output.push("second".to_owned());
            }
            Ok(())
        }
    }

    #[test]
    fn generic_mapper_can_append_zero_or_many_outputs() {
        let mut source = QueuedInputSource::new(FanOutMapper);
        let added = source
            .enqueue_batch(&batch(vec![
                state(KEY_A, ButtonPhase::Up, 0),
                state(KEY_A, ButtonPhase::Down, 2),
            ]))
            .unwrap();

        assert_eq!(added, 2);
        assert_eq!(source.pending_len(), 2);
        assert_eq!(source.next_event().as_deref(), Some("first"));
        assert_eq!(source.next_event().as_deref(), Some("second"));
        assert!(source.is_empty());
    }

    #[test]
    fn mapping_error_never_commits_a_partial_domain_batch() {
        let mut source = QueuedInputSource::new(FanOutMapper);
        source
            .enqueue_events(&[state(KEY_A, ButtonPhase::Down, 0)])
            .unwrap();

        let error = source
            .enqueue_events(&[
                state(KEY_A, ButtonPhase::Down, 1),
                state(KEY_B, ButtonPhase::Down, 2),
            ])
            .unwrap_err();

        assert_eq!(error, "unmappable B");
        assert_eq!(source.drain(), vec!["first", "second"]);
    }

    #[derive(Debug)]
    struct ScriptedSink<E> {
        outcomes: VecDeque<Result<(), &'static str>>,
        accepted: Vec<E>,
        calls: usize,
    }

    impl<E> ScriptedSink<E> {
        fn new(outcomes: impl IntoIterator<Item = Result<(), &'static str>>) -> Self {
            Self {
                outcomes: outcomes.into_iter().collect(),
                accepted: Vec::new(),
                calls: 0,
            }
        }
    }

    impl<E> TryEventSink<E> for ScriptedSink<E> {
        type Error = &'static str;

        fn try_send(&mut self, event: E) -> Result<(), Rejected<E, Self::Error>> {
            self.calls += 1;
            match self.outcomes.pop_front().unwrap_or(Ok(())) {
                Ok(()) => {
                    self.accepted.push(event);
                    Ok(())
                }
                Err(error) => Err(Rejected::new(event, error)),
            }
        }
    }

    #[test]
    fn rejected_returns_ownership_without_clone() {
        let mut sink = ScriptedSink::new([Err("full")]);
        let event = Box::new(String::from("owned"));
        let rejected = sink.try_send(event).unwrap_err();

        assert_eq!(*rejected.event, "owned");
        assert_eq!(rejected.error, "full");
    }

    #[test]
    fn fifo_flush_sends_every_event_once() {
        let mut source = QueuedInputSource::new(FanOutMapper);
        source
            .enqueue_events(&[
                state(KEY_A, ButtonPhase::Down, 0),
                state(KEY_A, ButtonPhase::Down, 1),
            ])
            .unwrap();
        let mut sink = ScriptedSink::new([]);

        assert_eq!(source.flush_to(&mut sink), Ok(4));
        assert_eq!(sink.accepted, ["first", "second", "first", "second"]);
        assert!(source.is_empty());
    }

    #[test]
    fn failed_flush_retains_rejected_event_and_tail() {
        let mut source = QueuedInputSource::new(FanOutMapper);
        source
            .enqueue_events(&[
                state(KEY_A, ButtonPhase::Down, 0),
                state(KEY_A, ButtonPhase::Down, 1),
            ])
            .unwrap();
        let mut sink = ScriptedSink::new([Ok(()), Err("full")]);

        let error = source.flush_to(&mut sink).unwrap_err();
        assert_eq!(
            error,
            FlushError {
                sent: 1,
                error: "full"
            }
        );
        assert_eq!(sink.accepted, ["first"]);
        assert_eq!(source.drain(), ["second", "first", "second"]);
    }

    #[test]
    fn repeated_failure_and_retry_are_exactly_once() {
        let mut source = QueuedInputSource::new(FanOutMapper);
        source
            .enqueue_events(&[state(KEY_A, ButtonPhase::Down, 0)])
            .unwrap();

        for expected_error in ["full-1", "full-2"] {
            let mut sink = ScriptedSink::new([Err(expected_error)]);
            assert_eq!(
                source.flush_to(&mut sink),
                Err(FlushError {
                    sent: 0,
                    error: expected_error,
                })
            );
            assert!(sink.accepted.is_empty());
            assert_eq!(source.pending_len(), 2);
        }

        let mut recovered = ScriptedSink::new([]);
        assert_eq!(source.flush_to(&mut recovered), Ok(2));
        assert_eq!(recovered.accepted, ["first", "second"]);
        assert!(source.is_empty());
    }

    #[test]
    fn empty_flush_never_calls_sink() {
        let mut source = QueuedInputSource::new(FanOutMapper);
        let mut sink = ScriptedSink::<String>::new([Err("must not be used")]);

        assert_eq!(source.flush_to(&mut sink), Ok(0));
        assert_eq!(sink.calls, 0);
    }

    #[test]
    fn old_pending_events_precede_new_batches() {
        let mut source = QueuedInputSource::new(FanOutMapper);
        source
            .enqueue_events(&[state(KEY_A, ButtonPhase::Down, 0)])
            .unwrap();
        let mut blocked = ScriptedSink::new([Ok(()), Err("full")]);
        source.flush_to(&mut blocked).unwrap_err();

        source
            .enqueue_events(&[state(KEY_A, ButtonPhase::Down, 1)])
            .unwrap();
        assert_eq!(source.drain(), ["second", "first", "second"]);
    }

    #[test]
    fn binding_mapper_adds_runtime_context_and_preserves_binding_order() {
        let mut mapper = BindingMapper::with_initial_sequence(SourceId(7), 41);
        mapper
            .bind(
                KEY_A,
                EventSelector::State(ButtonPhase::Down),
                "KEY_A",
                InputValue::Pressed,
            )
            .bind(
                KEY_A,
                EventSelector::State(ButtonPhase::Down),
                "WAKE",
                InputValue::Trigger,
            );
        let mut source = QueuedInputSource::new(mapper);
        let domain = state(KEY_A, ButtonPhase::Down, 10);

        assert_eq!(source.enqueue_events(std::slice::from_ref(&domain)), Ok(2));
        assert_eq!(
            source.drain(),
            vec![
                InputEvent {
                    source: SourceId(7),
                    sequence: 41,
                    timing: InputTiming::from(&domain),
                    code: "KEY_A",
                    value: InputValue::Pressed,
                },
                InputEvent {
                    source: SourceId(7),
                    sequence: 42,
                    timing: InputTiming::from(&domain),
                    code: "WAKE",
                    value: InputValue::Trigger,
                },
            ]
        );
        assert_eq!(source.mapper().next_sequence(), Some(43));
    }

    #[test]
    fn unmapped_events_are_explicitly_ignored_without_consuming_sequence() {
        let mapper = BindingMapper::<u16>::new(SourceId(3));
        let mut source = QueuedInputSource::new(mapper);

        assert_eq!(source.enqueue_events(&[tap(KEY_A, 1, 10)]), Ok(0));
        assert!(source.is_empty());
        assert_eq!(source.mapper().next_sequence(), Some(0));
    }

    #[test]
    fn selectors_distinguish_control_gesture_and_threshold() {
        let chord = ControlId::Chord(ChordId(9));
        let hold = ButtonEvent::gesture(
            chord,
            GestureKind::HoldStart {
                threshold: Duration::from_secs(1),
            },
            Timestamp::from_millis(1_000),
            Timestamp::from_millis(1_005),
        );
        assert_eq!(
            EventSelector::classify(&hold),
            (
                chord,
                EventSelector::HoldStart {
                    threshold: Duration::from_secs(1),
                }
            )
        );
    }

    #[test]
    fn binding_sequence_preflight_is_transactional_for_the_whole_batch() {
        let mapper = BindingMapper::with_initial_sequence(SourceId(1), u64::MAX).with_binding(
            KEY_A,
            EventSelector::State(ButtonPhase::Down),
            10u16,
            InputValue::Pressed,
        );
        let mut source = QueuedInputSource::new(mapper);

        let error = source
            .enqueue_events(&[
                state(KEY_A, ButtonPhase::Down, 0),
                state(KEY_A, ButtonPhase::Down, 1),
            ])
            .unwrap_err();
        assert_eq!(
            error,
            BindingError::SequenceOverflow {
                next_sequence: Some(u64::MAX),
                required: 2,
            }
        );
        assert!(source.is_empty());
        assert_eq!(source.mapper().next_sequence(), Some(u64::MAX));

        assert_eq!(
            source.enqueue_events(&[state(KEY_A, ButtonPhase::Down, 2)]),
            Ok(1)
        );
        let last = source.next_event().unwrap();
        assert_eq!(last.sequence, u64::MAX);
        assert_eq!(source.mapper().next_sequence(), None);

        let exhausted = source
            .enqueue_events(&[state(KEY_A, ButtonPhase::Down, 3)])
            .unwrap_err();
        assert_eq!(
            exhausted,
            BindingError::SequenceOverflow {
                next_sequence: None,
                required: 1,
            }
        );
        assert!(source.is_empty());
    }

    #[test]
    fn retry_delivers_the_same_numbered_event() {
        let mapper = BindingMapper::new(SourceId(1)).with_binding(
            KEY_A,
            EventSelector::Tap { count: 1 },
            99u16,
            InputValue::Trigger,
        );
        let mut source = QueuedInputSource::new(mapper);
        let domain = tap(KEY_A, 1, 20);
        source
            .enqueue_events(std::slice::from_ref(&domain))
            .unwrap();
        let mut blocked = ScriptedSink::new([Err("full")]);

        source.flush_to(&mut blocked).unwrap_err();
        assert_eq!(source.mapper().next_sequence(), Some(1));

        let mut recovered = ScriptedSink::new([]);
        assert_eq!(source.flush_to(&mut recovered), Ok(1));
        assert_eq!(recovered.accepted[0].sequence, 0);
        assert_eq!(recovered.accepted[0].timing, InputTiming::from(&domain));
        assert_eq!(source.mapper().next_sequence(), Some(1));
    }

    #[test]
    fn automatic_binding_preserves_dynamic_gesture_payload() {
        let mapper = BindingMapper::new(SourceId(1));
        let mut source = QueuedInputSource::new(mapper);
        source
            .mapper_mut()
            .bind_auto(KEY_A, EventSelector::Tap { count: 2 }, "DOUBLE_TAP");
        let event = tap(KEY_A, 2, 20);

        source.enqueue_events(&[event]).unwrap();
        assert_eq!(
            source.next_event().unwrap().value,
            InputValue::Count(NonZeroU64::new(2).unwrap())
        );
    }
}