Skip to main content

btn_recognizer/key/
input.rs

1//! Adapters from button-domain events to an application's input subsystem.
2//!
3//! Recognition and delivery are deliberately separated. The recognition core
4//! returns an owned [`EventBatch`], while [`QueuedInputSource`] maps its domain
5//! events into an unbounded `VecDeque`. A fallible downstream sink therefore
6//! cannot make recognition state advance while losing an event.
7
8use std::collections::{HashMap, VecDeque};
9use std::error::Error;
10use std::fmt;
11use std::num::NonZeroU64;
12use std::time::Duration;
13
14use super::types::{
15    ButtonEvent, ButtonEventKind, ButtonPhase, ControlId, EventBatch, GestureKind, Timestamp,
16};
17
18/// Maps one domain event into zero or more owned downstream events.
19///
20/// Implementations append to `output`; they must not clear or reorder values
21/// already present in it. Returning no values is the explicit policy for an
22/// ignored domain event.
23pub trait EventMapper {
24    type Output;
25    type Error;
26
27    fn map_event(
28        &mut self,
29        event: &ButtonEvent,
30        output: &mut Vec<Self::Output>,
31    ) -> Result<(), Self::Error>;
32
33    /// Map a complete ordered domain batch.
34    ///
35    /// The default implementation calls [`Self::map_event`] in slice order.
36    /// It may have mutated mapper state before a later event fails. Stateful
37    /// mappers which require transactional batches should override this method,
38    /// preflight the batch, and mutate only after validation succeeds.
39    fn map_batch(
40        &mut self,
41        events: &[ButtonEvent],
42        output: &mut Vec<Self::Output>,
43    ) -> Result<(), Self::Error> {
44        for event in events {
45            self.map_event(event, output)?;
46        }
47        Ok(())
48    }
49}
50
51/// Pull-based input source backed by an unbounded FIFO.
52///
53/// A successful enqueue appends the entire mapped batch behind older pending
54/// events. Mapping occurs in a temporary vector, so a mapping error never
55/// commits a partial batch to the queue. The generic mapper's own state follows
56/// its [`EventMapper::map_batch`] contract; the queue cannot roll it back.
57#[derive(Debug, Clone)]
58pub struct QueuedInputSource<M>
59where
60    M: EventMapper,
61{
62    mapper: M,
63    pending: VecDeque<M::Output>,
64}
65
66impl<M> QueuedInputSource<M>
67where
68    M: EventMapper,
69{
70    pub fn new(mapper: M) -> Self {
71        Self {
72            mapper,
73            pending: VecDeque::new(),
74        }
75    }
76
77    pub fn mapper(&self) -> &M {
78        &self.mapper
79    }
80
81    pub fn mapper_mut(&mut self) -> &mut M {
82        &mut self.mapper
83    }
84
85    /// Map and atomically append the logical events in one framework batch.
86    ///
87    /// Physical diagnostic edges are intentionally not mapped by this adapter.
88    /// On success, returns the number of downstream events appended.
89    pub fn enqueue_batch(&mut self, batch: &EventBatch) -> Result<usize, M::Error> {
90        self.enqueue_events(&batch.events)
91    }
92
93    /// Map and atomically append an ordered domain-event slice.
94    pub fn enqueue_events(&mut self, events: &[ButtonEvent]) -> Result<usize, M::Error> {
95        let mut mapped = Vec::new();
96        self.mapper.map_batch(events, &mut mapped)?;
97        let appended = mapped.len();
98        self.pending.extend(mapped);
99        Ok(appended)
100    }
101
102    pub fn next_event(&mut self) -> Option<M::Output> {
103        self.pending.pop_front()
104    }
105
106    pub fn pending_len(&self) -> usize {
107        self.pending.len()
108    }
109
110    pub fn is_empty(&self) -> bool {
111        self.pending.is_empty()
112    }
113
114    /// Remove and return every pending event in FIFO order.
115    pub fn drain(&mut self) -> Vec<M::Output> {
116        self.pending.drain(..).collect()
117    }
118
119    /// Try to deliver every pending event to `sink` in FIFO order.
120    ///
121    /// When a send fails, ownership of the rejected event is returned by the
122    /// sink, restored to the front of the queue, and included in the next retry.
123    /// Already accepted events are removed exactly once; the untouched tail
124    /// remains in its original order.
125    pub fn flush_to<S>(&mut self, sink: &mut S) -> Result<usize, FlushError<S::Error>>
126    where
127        S: TryEventSink<M::Output>,
128    {
129        let mut sent = 0;
130        while let Some(event) = self.pending.pop_front() {
131            match sink.try_send(event) {
132                Ok(()) => sent += 1,
133                Err(Rejected { event, error }) => {
134                    self.pending.push_front(event);
135                    return Err(FlushError { sent, error });
136                }
137            }
138        }
139        Ok(sent)
140    }
141
142    pub fn into_parts(self) -> (M, VecDeque<M::Output>) {
143        (self.mapper, self.pending)
144    }
145}
146
147/// A sink rejection which returns ownership of the unaccepted event.
148#[derive(Debug, Clone, PartialEq, Eq)]
149pub struct Rejected<E, Err> {
150    pub event: E,
151    pub error: Err,
152}
153
154impl<E, Err> Rejected<E, Err> {
155    pub const fn new(event: E, error: Err) -> Self {
156        Self { event, error }
157    }
158
159    pub fn into_parts(self) -> (E, Err) {
160        (self.event, self.error)
161    }
162}
163
164/// A fallible, ownership-taking downstream event sink.
165///
166/// On rejection the sink must return the same unaccepted event in [`Rejected`].
167/// This makes retry possible without requiring events to implement `Clone`.
168pub trait TryEventSink<E> {
169    type Error;
170
171    fn try_send(&mut self, event: E) -> Result<(), Rejected<E, Self::Error>>;
172}
173
174/// Failure report from [`QueuedInputSource::flush_to`].
175#[derive(Debug, Clone, PartialEq, Eq)]
176pub struct FlushError<Err> {
177    /// Number of events accepted by the sink during this call.
178    pub sent: usize,
179    pub error: Err,
180}
181
182impl<Err> fmt::Display for FlushError<Err>
183where
184    Err: fmt::Display,
185{
186    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
187        write!(
188            f,
189            "input sink rejected an event after accepting {}: {}",
190            self.sent, self.error
191        )
192    }
193}
194
195impl<Err> Error for FlushError<Err>
196where
197    Err: Error + 'static,
198{
199    fn source(&self) -> Option<&(dyn Error + 'static)> {
200        Some(&self.error)
201    }
202}
203
204/// Stable identifier assigned by the application to one input source.
205#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
206pub struct SourceId(pub u32);
207
208impl SourceId {
209    pub const fn new(value: u32) -> Self {
210        Self(value)
211    }
212
213    pub const fn get(self) -> u32 {
214        self.0
215    }
216}
217
218impl fmt::Display for SourceId {
219    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
220        write!(f, "source:{}", self.0)
221    }
222}
223
224/// Logical and recognition times copied from a domain event.
225#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
226pub struct InputTiming {
227    pub occurred_at: Timestamp,
228    pub recognized_at: Timestamp,
229}
230
231impl From<&ButtonEvent> for InputTiming {
232    fn from(event: &ButtonEvent) -> Self {
233        Self {
234            occurred_at: event.occurred_at,
235            recognized_at: event.recognized_at,
236        }
237    }
238}
239
240/// Common values understood by button-oriented input subsystems.
241///
242/// A binding chooses the value explicitly. `Count` and `Duration` are available
243/// for applications which want semantic payloads; fixed press/release/pulse
244/// mappings can use the dedicated variants.
245#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
246pub enum InputValue {
247    Released,
248    Pressed,
249    Repeat(NonZeroU64),
250    Trigger,
251    Count(NonZeroU64),
252    Duration(Duration),
253    Scalar(i64),
254}
255
256/// Fully owned event ready for an application input subsystem.
257#[derive(Debug, Clone, PartialEq, Eq, Hash)]
258pub struct InputEvent<Code> {
259    pub source: SourceId,
260    pub sequence: u64,
261    pub timing: InputTiming,
262    pub code: Code,
263    pub value: InputValue,
264}
265
266/// Domain-event portion used when looking up configured bindings.
267#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
268pub enum EventSelector {
269    State(ButtonPhase),
270    Tap { count: u8 },
271    HoldStart { threshold: Duration },
272    HoldMilestone { threshold: Duration },
273    Repeat,
274    HoldEnd,
275}
276
277impl EventSelector {
278    /// Return the control and selector represented by a domain event.
279    pub fn classify(event: &ButtonEvent) -> (ControlId, Self) {
280        match &event.kind {
281            ButtonEventKind::State { control, phase } => (*control, Self::State(*phase)),
282            ButtonEventKind::Gesture { control, kind } => {
283                let selector = match kind {
284                    GestureKind::Tap { count } => Self::Tap { count: *count },
285                    GestureKind::HoldStart { threshold } => Self::HoldStart {
286                        threshold: *threshold,
287                    },
288                    GestureKind::HoldMilestone { threshold } => Self::HoldMilestone {
289                        threshold: *threshold,
290                    },
291                    GestureKind::Repeat { .. } => Self::Repeat,
292                    GestureKind::HoldEnd { .. } => Self::HoldEnd,
293                };
294                (*control, selector)
295            }
296        }
297    }
298}
299
300/// One configured downstream output for a domain selector.
301#[derive(Debug, Clone, PartialEq, Eq)]
302pub struct Binding<Code> {
303    pub code: Code,
304    pub value: BindingValue,
305}
306
307impl<Code> Binding<Code> {
308    pub const fn new(code: Code, value: InputValue) -> Self {
309        Self {
310            code,
311            value: BindingValue::Fixed(value),
312        }
313    }
314
315    pub const fn auto(code: Code) -> Self {
316        Self {
317            code,
318            value: BindingValue::Auto,
319        }
320    }
321}
322
323/// Selects either an explicitly configured value or the domain payload.
324#[derive(Debug, Clone, Copy, PartialEq, Eq)]
325pub enum BindingValue {
326    Fixed(InputValue),
327    Auto,
328}
329
330/// Configurable mapping from `(ControlId, EventSelector)` to downstream events.
331///
332/// Multiple bindings may be registered for the same key. They are emitted in
333/// registration order. Unmapped events intentionally produce no output.
334#[derive(Debug, Clone)]
335pub struct BindingMapper<Code> {
336    source: SourceId,
337    next_sequence: Option<u64>,
338    bindings: HashMap<(ControlId, EventSelector), Vec<Binding<Code>>>,
339}
340
341impl<Code> BindingMapper<Code> {
342    pub fn new(source: SourceId) -> Self {
343        Self::with_initial_sequence(source, 0)
344    }
345
346    pub fn with_initial_sequence(source: SourceId, next_sequence: u64) -> Self {
347        Self {
348            source,
349            next_sequence: Some(next_sequence),
350            bindings: HashMap::new(),
351        }
352    }
353
354    pub const fn source(&self) -> SourceId {
355        self.source
356    }
357
358    /// Sequence which will be assigned next, or `None` after `u64::MAX` was used.
359    pub const fn next_sequence(&self) -> Option<u64> {
360        self.next_sequence
361    }
362
363    /// Append a binding for `(control, selector)`.
364    pub fn bind(
365        &mut self,
366        control: ControlId,
367        selector: EventSelector,
368        code: Code,
369        value: InputValue,
370    ) -> &mut Self {
371        self.bindings
372            .entry((control, selector))
373            .or_default()
374            .push(Binding::new(code, value));
375        self
376    }
377
378    /// Fluent, ownership-taking form of [`Self::bind`].
379    pub fn with_binding(
380        mut self,
381        control: ControlId,
382        selector: EventSelector,
383        code: Code,
384        value: InputValue,
385    ) -> Self {
386        self.bind(control, selector, code, value);
387        self
388    }
389
390    /// Append a binding whose value is derived from the matched event.
391    pub fn bind_auto(
392        &mut self,
393        control: ControlId,
394        selector: EventSelector,
395        code: Code,
396    ) -> &mut Self {
397        self.bindings
398            .entry((control, selector))
399            .or_default()
400            .push(Binding::auto(code));
401        self
402    }
403
404    pub fn binding_count(&self) -> usize {
405        self.bindings.values().map(Vec::len).sum()
406    }
407
408    fn mapped_output_count(&self, events: &[ButtonEvent]) -> Result<usize, BindingError> {
409        events.iter().try_fold(0usize, |total, event| {
410            let key = EventSelector::classify(event);
411            let additional = self.bindings.get(&key).map_or(0, Vec::len);
412            total
413                .checked_add(additional)
414                .ok_or(BindingError::SequenceOverflow {
415                    next_sequence: self.next_sequence,
416                    required: usize::MAX,
417                })
418        })
419    }
420
421    fn sequence_after(&self, required: usize) -> Result<Option<u64>, BindingError> {
422        if required == 0 {
423            return Ok(self.next_sequence);
424        }
425
426        let start = self.next_sequence.ok_or(BindingError::SequenceOverflow {
427            next_sequence: None,
428            required,
429        })?;
430        let additional =
431            u64::try_from(required - 1).map_err(|_| BindingError::SequenceOverflow {
432                next_sequence: Some(start),
433                required,
434            })?;
435        let last = start
436            .checked_add(additional)
437            .ok_or(BindingError::SequenceOverflow {
438                next_sequence: Some(start),
439                required,
440            })?;
441        Ok(last.checked_add(1))
442    }
443
444    fn map_events_checked(
445        &mut self,
446        events: &[ButtonEvent],
447        output: &mut Vec<InputEvent<Code>>,
448    ) -> Result<(), BindingError>
449    where
450        Code: Clone,
451    {
452        let required = self.mapped_output_count(events)?;
453        let sequence_after = self.sequence_after(required)?;
454        // Validate every automatic payload before changing output or sequence.
455        for event in events {
456            let key = EventSelector::classify(event);
457            if self.bindings.get(&key).is_some_and(|bindings| {
458                bindings
459                    .iter()
460                    .any(|binding| binding.value == BindingValue::Auto)
461            }) {
462                automatic_value(event)?;
463            }
464        }
465        let mut sequence = self.next_sequence;
466
467        for event in events {
468            let key = EventSelector::classify(event);
469            let Some(bindings) = self.bindings.get(&key) else {
470                continue;
471            };
472            for binding in bindings {
473                let current = sequence.expect("sequence capacity was preflighted");
474                output.push(InputEvent {
475                    source: self.source,
476                    sequence: current,
477                    timing: InputTiming::from(event),
478                    code: binding.code.clone(),
479                    value: match binding.value {
480                        BindingValue::Fixed(value) => value,
481                        BindingValue::Auto => {
482                            automatic_value(event).expect("automatic payloads were preflighted")
483                        }
484                    },
485                });
486                sequence = current.checked_add(1);
487            }
488        }
489
490        debug_assert_eq!(sequence, sequence_after);
491        self.next_sequence = sequence_after;
492        Ok(())
493    }
494}
495
496impl<Code> EventMapper for BindingMapper<Code>
497where
498    Code: Clone,
499{
500    type Output = InputEvent<Code>;
501    type Error = BindingError;
502
503    fn map_event(
504        &mut self,
505        event: &ButtonEvent,
506        output: &mut Vec<Self::Output>,
507    ) -> Result<(), Self::Error> {
508        self.map_events_checked(std::slice::from_ref(event), output)
509    }
510
511    fn map_batch(
512        &mut self,
513        events: &[ButtonEvent],
514        output: &mut Vec<Self::Output>,
515    ) -> Result<(), Self::Error> {
516        self.map_events_checked(events, output)
517    }
518}
519
520/// Binding mapper failure. No output or sequence state is changed on failure.
521#[derive(Debug, Clone, PartialEq, Eq)]
522pub enum BindingError {
523    SequenceOverflow {
524        next_sequence: Option<u64>,
525        required: usize,
526    },
527    InvalidTapCount,
528}
529
530impl fmt::Display for BindingError {
531    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
532        match self {
533            Self::SequenceOverflow {
534                next_sequence,
535                required,
536            } => write!(
537                f,
538                "cannot allocate {required} input sequence numbers starting at {next_sequence:?}"
539            ),
540            Self::InvalidTapCount => write!(f, "a tap event contains count=0"),
541        }
542    }
543}
544
545impl Error for BindingError {}
546
547fn automatic_value(event: &ButtonEvent) -> Result<InputValue, BindingError> {
548    match &event.kind {
549        ButtonEventKind::State { phase, .. } => Ok(match phase {
550            ButtonPhase::Down => InputValue::Pressed,
551            ButtonPhase::Up => InputValue::Released,
552        }),
553        ButtonEventKind::Gesture { kind, .. } => match kind {
554            GestureKind::Tap { count } => NonZeroU64::new(u64::from(*count))
555                .map(InputValue::Count)
556                .ok_or(BindingError::InvalidTapCount),
557            GestureKind::HoldStart { threshold } | GestureKind::HoldMilestone { threshold } => {
558                Ok(InputValue::Duration(*threshold))
559            }
560            GestureKind::Repeat { count } => Ok(InputValue::Repeat(*count)),
561            GestureKind::HoldEnd { held_for } => Ok(InputValue::Duration(*held_for)),
562        },
563    }
564}
565
566#[cfg(test)]
567mod tests {
568    use super::super::types::{ChordId, KeyId};
569    use super::*;
570
571    const KEY_A: ControlId = ControlId::Key(KeyId(1));
572    const KEY_B: ControlId = ControlId::Key(KeyId(2));
573
574    fn state(control: ControlId, phase: ButtonPhase, at: u64) -> ButtonEvent {
575        ButtonEvent {
576            occurred_at: Timestamp::from_millis(at),
577            recognized_at: Timestamp::from_millis(at + 1),
578            kind: ButtonEventKind::State { control, phase },
579        }
580    }
581
582    fn tap(control: ControlId, count: u8, at: u64) -> ButtonEvent {
583        ButtonEvent::gesture(
584            control,
585            GestureKind::Tap { count },
586            Timestamp::from_millis(at),
587            Timestamp::from_millis(at + 2),
588        )
589    }
590
591    fn batch(events: Vec<ButtonEvent>) -> EventBatch {
592        let mut batch = EventBatch::new(Timestamp::from_millis(100));
593        batch.events = events;
594        batch
595    }
596
597    #[derive(Debug, Clone, PartialEq, Eq)]
598    struct FanOutMapper;
599
600    impl EventMapper for FanOutMapper {
601        type Output = String;
602        type Error = &'static str;
603
604        fn map_event(
605            &mut self,
606            event: &ButtonEvent,
607            output: &mut Vec<Self::Output>,
608        ) -> Result<(), Self::Error> {
609            let (control, selector) = EventSelector::classify(event);
610            if control == KEY_B {
611                return Err("unmappable B");
612            }
613            if matches!(selector, EventSelector::State(ButtonPhase::Down)) {
614                output.push("first".to_owned());
615                output.push("second".to_owned());
616            }
617            Ok(())
618        }
619    }
620
621    #[test]
622    fn generic_mapper_can_append_zero_or_many_outputs() {
623        let mut source = QueuedInputSource::new(FanOutMapper);
624        let added = source
625            .enqueue_batch(&batch(vec![
626                state(KEY_A, ButtonPhase::Up, 0),
627                state(KEY_A, ButtonPhase::Down, 2),
628            ]))
629            .unwrap();
630
631        assert_eq!(added, 2);
632        assert_eq!(source.pending_len(), 2);
633        assert_eq!(source.next_event().as_deref(), Some("first"));
634        assert_eq!(source.next_event().as_deref(), Some("second"));
635        assert!(source.is_empty());
636    }
637
638    #[test]
639    fn mapping_error_never_commits_a_partial_domain_batch() {
640        let mut source = QueuedInputSource::new(FanOutMapper);
641        source
642            .enqueue_events(&[state(KEY_A, ButtonPhase::Down, 0)])
643            .unwrap();
644
645        let error = source
646            .enqueue_events(&[
647                state(KEY_A, ButtonPhase::Down, 1),
648                state(KEY_B, ButtonPhase::Down, 2),
649            ])
650            .unwrap_err();
651
652        assert_eq!(error, "unmappable B");
653        assert_eq!(source.drain(), vec!["first", "second"]);
654    }
655
656    #[derive(Debug)]
657    struct ScriptedSink<E> {
658        outcomes: VecDeque<Result<(), &'static str>>,
659        accepted: Vec<E>,
660        calls: usize,
661    }
662
663    impl<E> ScriptedSink<E> {
664        fn new(outcomes: impl IntoIterator<Item = Result<(), &'static str>>) -> Self {
665            Self {
666                outcomes: outcomes.into_iter().collect(),
667                accepted: Vec::new(),
668                calls: 0,
669            }
670        }
671    }
672
673    impl<E> TryEventSink<E> for ScriptedSink<E> {
674        type Error = &'static str;
675
676        fn try_send(&mut self, event: E) -> Result<(), Rejected<E, Self::Error>> {
677            self.calls += 1;
678            match self.outcomes.pop_front().unwrap_or(Ok(())) {
679                Ok(()) => {
680                    self.accepted.push(event);
681                    Ok(())
682                }
683                Err(error) => Err(Rejected::new(event, error)),
684            }
685        }
686    }
687
688    #[test]
689    fn rejected_returns_ownership_without_clone() {
690        let mut sink = ScriptedSink::new([Err("full")]);
691        let event = Box::new(String::from("owned"));
692        let rejected = sink.try_send(event).unwrap_err();
693
694        assert_eq!(*rejected.event, "owned");
695        assert_eq!(rejected.error, "full");
696    }
697
698    #[test]
699    fn fifo_flush_sends_every_event_once() {
700        let mut source = QueuedInputSource::new(FanOutMapper);
701        source
702            .enqueue_events(&[
703                state(KEY_A, ButtonPhase::Down, 0),
704                state(KEY_A, ButtonPhase::Down, 1),
705            ])
706            .unwrap();
707        let mut sink = ScriptedSink::new([]);
708
709        assert_eq!(source.flush_to(&mut sink), Ok(4));
710        assert_eq!(sink.accepted, ["first", "second", "first", "second"]);
711        assert!(source.is_empty());
712    }
713
714    #[test]
715    fn failed_flush_retains_rejected_event_and_tail() {
716        let mut source = QueuedInputSource::new(FanOutMapper);
717        source
718            .enqueue_events(&[
719                state(KEY_A, ButtonPhase::Down, 0),
720                state(KEY_A, ButtonPhase::Down, 1),
721            ])
722            .unwrap();
723        let mut sink = ScriptedSink::new([Ok(()), Err("full")]);
724
725        let error = source.flush_to(&mut sink).unwrap_err();
726        assert_eq!(
727            error,
728            FlushError {
729                sent: 1,
730                error: "full"
731            }
732        );
733        assert_eq!(sink.accepted, ["first"]);
734        assert_eq!(source.drain(), ["second", "first", "second"]);
735    }
736
737    #[test]
738    fn repeated_failure_and_retry_are_exactly_once() {
739        let mut source = QueuedInputSource::new(FanOutMapper);
740        source
741            .enqueue_events(&[state(KEY_A, ButtonPhase::Down, 0)])
742            .unwrap();
743
744        for expected_error in ["full-1", "full-2"] {
745            let mut sink = ScriptedSink::new([Err(expected_error)]);
746            assert_eq!(
747                source.flush_to(&mut sink),
748                Err(FlushError {
749                    sent: 0,
750                    error: expected_error,
751                })
752            );
753            assert!(sink.accepted.is_empty());
754            assert_eq!(source.pending_len(), 2);
755        }
756
757        let mut recovered = ScriptedSink::new([]);
758        assert_eq!(source.flush_to(&mut recovered), Ok(2));
759        assert_eq!(recovered.accepted, ["first", "second"]);
760        assert!(source.is_empty());
761    }
762
763    #[test]
764    fn empty_flush_never_calls_sink() {
765        let mut source = QueuedInputSource::new(FanOutMapper);
766        let mut sink = ScriptedSink::<String>::new([Err("must not be used")]);
767
768        assert_eq!(source.flush_to(&mut sink), Ok(0));
769        assert_eq!(sink.calls, 0);
770    }
771
772    #[test]
773    fn old_pending_events_precede_new_batches() {
774        let mut source = QueuedInputSource::new(FanOutMapper);
775        source
776            .enqueue_events(&[state(KEY_A, ButtonPhase::Down, 0)])
777            .unwrap();
778        let mut blocked = ScriptedSink::new([Ok(()), Err("full")]);
779        source.flush_to(&mut blocked).unwrap_err();
780
781        source
782            .enqueue_events(&[state(KEY_A, ButtonPhase::Down, 1)])
783            .unwrap();
784        assert_eq!(source.drain(), ["second", "first", "second"]);
785    }
786
787    #[test]
788    fn binding_mapper_adds_runtime_context_and_preserves_binding_order() {
789        let mut mapper = BindingMapper::with_initial_sequence(SourceId(7), 41);
790        mapper
791            .bind(
792                KEY_A,
793                EventSelector::State(ButtonPhase::Down),
794                "KEY_A",
795                InputValue::Pressed,
796            )
797            .bind(
798                KEY_A,
799                EventSelector::State(ButtonPhase::Down),
800                "WAKE",
801                InputValue::Trigger,
802            );
803        let mut source = QueuedInputSource::new(mapper);
804        let domain = state(KEY_A, ButtonPhase::Down, 10);
805
806        assert_eq!(source.enqueue_events(std::slice::from_ref(&domain)), Ok(2));
807        assert_eq!(
808            source.drain(),
809            vec![
810                InputEvent {
811                    source: SourceId(7),
812                    sequence: 41,
813                    timing: InputTiming::from(&domain),
814                    code: "KEY_A",
815                    value: InputValue::Pressed,
816                },
817                InputEvent {
818                    source: SourceId(7),
819                    sequence: 42,
820                    timing: InputTiming::from(&domain),
821                    code: "WAKE",
822                    value: InputValue::Trigger,
823                },
824            ]
825        );
826        assert_eq!(source.mapper().next_sequence(), Some(43));
827    }
828
829    #[test]
830    fn unmapped_events_are_explicitly_ignored_without_consuming_sequence() {
831        let mapper = BindingMapper::<u16>::new(SourceId(3));
832        let mut source = QueuedInputSource::new(mapper);
833
834        assert_eq!(source.enqueue_events(&[tap(KEY_A, 1, 10)]), Ok(0));
835        assert!(source.is_empty());
836        assert_eq!(source.mapper().next_sequence(), Some(0));
837    }
838
839    #[test]
840    fn selectors_distinguish_control_gesture_and_threshold() {
841        let chord = ControlId::Chord(ChordId(9));
842        let hold = ButtonEvent::gesture(
843            chord,
844            GestureKind::HoldStart {
845                threshold: Duration::from_secs(1),
846            },
847            Timestamp::from_millis(1_000),
848            Timestamp::from_millis(1_005),
849        );
850        assert_eq!(
851            EventSelector::classify(&hold),
852            (
853                chord,
854                EventSelector::HoldStart {
855                    threshold: Duration::from_secs(1),
856                }
857            )
858        );
859    }
860
861    #[test]
862    fn binding_sequence_preflight_is_transactional_for_the_whole_batch() {
863        let mapper = BindingMapper::with_initial_sequence(SourceId(1), u64::MAX).with_binding(
864            KEY_A,
865            EventSelector::State(ButtonPhase::Down),
866            10u16,
867            InputValue::Pressed,
868        );
869        let mut source = QueuedInputSource::new(mapper);
870
871        let error = source
872            .enqueue_events(&[
873                state(KEY_A, ButtonPhase::Down, 0),
874                state(KEY_A, ButtonPhase::Down, 1),
875            ])
876            .unwrap_err();
877        assert_eq!(
878            error,
879            BindingError::SequenceOverflow {
880                next_sequence: Some(u64::MAX),
881                required: 2,
882            }
883        );
884        assert!(source.is_empty());
885        assert_eq!(source.mapper().next_sequence(), Some(u64::MAX));
886
887        assert_eq!(
888            source.enqueue_events(&[state(KEY_A, ButtonPhase::Down, 2)]),
889            Ok(1)
890        );
891        let last = source.next_event().unwrap();
892        assert_eq!(last.sequence, u64::MAX);
893        assert_eq!(source.mapper().next_sequence(), None);
894
895        let exhausted = source
896            .enqueue_events(&[state(KEY_A, ButtonPhase::Down, 3)])
897            .unwrap_err();
898        assert_eq!(
899            exhausted,
900            BindingError::SequenceOverflow {
901                next_sequence: None,
902                required: 1,
903            }
904        );
905        assert!(source.is_empty());
906    }
907
908    #[test]
909    fn retry_delivers_the_same_numbered_event() {
910        let mapper = BindingMapper::new(SourceId(1)).with_binding(
911            KEY_A,
912            EventSelector::Tap { count: 1 },
913            99u16,
914            InputValue::Trigger,
915        );
916        let mut source = QueuedInputSource::new(mapper);
917        let domain = tap(KEY_A, 1, 20);
918        source
919            .enqueue_events(std::slice::from_ref(&domain))
920            .unwrap();
921        let mut blocked = ScriptedSink::new([Err("full")]);
922
923        source.flush_to(&mut blocked).unwrap_err();
924        assert_eq!(source.mapper().next_sequence(), Some(1));
925
926        let mut recovered = ScriptedSink::new([]);
927        assert_eq!(source.flush_to(&mut recovered), Ok(1));
928        assert_eq!(recovered.accepted[0].sequence, 0);
929        assert_eq!(recovered.accepted[0].timing, InputTiming::from(&domain));
930        assert_eq!(source.mapper().next_sequence(), Some(1));
931    }
932
933    #[test]
934    fn automatic_binding_preserves_dynamic_gesture_payload() {
935        let mapper = BindingMapper::new(SourceId(1));
936        let mut source = QueuedInputSource::new(mapper);
937        source
938            .mapper_mut()
939            .bind_auto(KEY_A, EventSelector::Tap { count: 2 }, "DOUBLE_TAP");
940        let event = tap(KEY_A, 2, 20);
941
942        source.enqueue_events(&[event]).unwrap();
943        assert_eq!(
944            source.next_event().unwrap().value,
945            InputValue::Count(NonZeroU64::new(2).unwrap())
946        );
947    }
948}