1use std::cmp;
2use std::collections::{HashMap, HashSet};
3use std::error::Error;
4use std::fmt;
5use std::num::NonZeroU64;
6use std::time::Duration;
7
8use crate::fsm_engine::Fsm;
9
10use super::config::{
11 validate_gesture_config, ConfigError, FrameworkConfig, GestureConfig, HoldAfterTapPolicy,
12};
13use super::gesture_fsm::{self, Event, Motion, State};
14use super::types::{
15 ButtonEvent, ButtonPhase, ControlEdge, ControlId, GestureKind, KeyId, Timestamp,
16};
17
18#[derive(Debug, Clone)]
20pub struct GestureRecognizer {
21 control: ControlId,
22 config: GestureConfig,
23 fsm: Fsm<State, Event, Motion>,
24 processed_to: Timestamp,
25 down_at: Option<Timestamp>,
26 press_recognized_at: Option<Timestamp>,
27 tap_count: u8,
28 last_tap_up: Option<Timestamp>,
29 tap_causal_recognized_at: Option<Timestamp>,
30 tap_deadline: Option<Timestamp>,
31 next_hold_index: usize,
32 next_repeat_at: Option<Timestamp>,
33}
34
35impl GestureRecognizer {
36 pub fn new(control: ControlId, config: GestureConfig) -> Result<Self, ConfigError> {
37 validate_gesture_config(&config, Some(control))?;
38 Ok(Self::new_validated(control, config))
39 }
40
41 pub(crate) fn new_validated(control: ControlId, config: GestureConfig) -> Self {
42 Self {
43 control,
44 config,
45 fsm: gesture_fsm::new(),
46 processed_to: Timestamp::ZERO,
47 down_at: None,
48 press_recognized_at: None,
49 tap_count: 0,
50 last_tap_up: None,
51 tap_causal_recognized_at: None,
52 tap_deadline: None,
53 next_hold_index: 0,
54 next_repeat_at: None,
55 }
56 }
57
58 pub fn control(&self) -> ControlId {
59 self.control
60 }
61
62 pub fn next_deadline(&self) -> Option<Timestamp> {
63 match *self.fsm.current_state() {
64 State::Idle => None,
65 State::AwaitNextTap => self.tap_deadline,
66 State::Pressed | State::Holding => {
67 let hold = self.next_hold_deadline();
68 match (hold, self.next_repeat_at) {
69 (Some(left), Some(right)) => Some(cmp::min(left, right)),
70 (Some(value), None) | (None, Some(value)) => Some(value),
71 (None, None) => None,
72 }
73 }
74 }
75 }
76
77 fn prepare_edge(
78 &mut self,
79 edge: ControlEdge,
80 output: &mut Vec<ButtonEvent>,
81 ) -> Result<(), GestureError> {
82 self.validate_edge_timing(edge)?;
83 match edge.phase {
84 ButtonPhase::Down => self.advance_impl(edge.occurred_at, false, output),
87 ButtonPhase::Up => self.advance_impl(edge.occurred_at, true, output),
89 }
90 }
91
92 fn apply_edge(
93 &mut self,
94 edge: ControlEdge,
95 output: &mut Vec<ButtonEvent>,
96 ) -> Result<(), GestureError> {
97 match edge.phase {
98 ButtonPhase::Down => self.on_down(edge),
99 ButtonPhase::Up => self.on_up(edge, output),
100 }
101 }
102
103 fn on_down(&mut self, edge: ControlEdge) -> Result<(), GestureError> {
104 if *self.fsm.current_state() == State::Idle && edge.occurred_at < self.processed_to {
105 self.processed_to = edge.occurred_at;
108 }
109
110 self.ensure_deadline_fits(edge.occurred_at)?;
111 let motion = self.step(Event::Down)?;
112 debug_assert_eq!(motion, Motion::StartPress);
113 self.down_at = Some(edge.occurred_at);
114 self.press_recognized_at = Some(edge.recognized_at);
115 self.next_hold_index = 0;
116 self.next_repeat_at = self
117 .config
118 .repeat
119 .as_ref()
120 .map(|repeat| edge.occurred_at.saturating_add(repeat.starts_after));
121 self.tap_deadline = None;
122 self.processed_to = cmp::max(self.processed_to, edge.occurred_at);
123 Ok(())
124 }
125
126 fn on_up(
127 &mut self,
128 edge: ControlEdge,
129 output: &mut Vec<ButtonEvent>,
130 ) -> Result<(), GestureError> {
131 let state = *self.fsm.current_state();
132 match state {
133 State::Holding => {
134 let motion = self.step(Event::HeldUp)?;
135 debug_assert_eq!(motion, Motion::CompleteHold);
136 let down_at = self
137 .down_at
138 .take()
139 .ok_or(GestureError::MissingPressContext {
140 control: self.control,
141 })?;
142 let held_for = edge.occurred_at.checked_duration_since(down_at).ok_or(
143 GestureError::EventBeforePress {
144 control: self.control,
145 },
146 )?;
147 output.push(ButtonEvent::gesture(
148 self.control,
149 GestureKind::HoldEnd { held_for },
150 edge.occurred_at,
151 edge.recognized_at,
152 ));
153 self.clear_press_context();
154 Ok(())
155 }
156 State::Pressed => {
157 let down_at = self.down_at.ok_or(GestureError::MissingPressContext {
158 control: self.control,
159 })?;
160 let held_for = edge.occurred_at.checked_duration_since(down_at).ok_or(
161 GestureError::EventBeforePress {
162 control: self.control,
163 },
164 )?;
165 let is_tap = held_for <= self.config.tap_max;
166 if !is_tap {
167 let motion = self.step(Event::UpInvalid)?;
168 debug_assert_eq!(motion, Motion::AbortPress);
169 self.commit_pending_taps(edge.recognized_at, output);
170 self.clear_press_context();
171 return Ok(());
172 }
173
174 let new_count = self
175 .tap_count
176 .checked_add(1)
177 .expect("tap count never exceeds configured u8 maximum");
178 if new_count >= self.config.max_taps {
179 let motion = self.step(Event::UpTapComplete)?;
180 debug_assert_eq!(motion, Motion::CompleteTap);
181 self.tap_count = new_count;
182 self.last_tap_up = Some(edge.occurred_at);
183 self.tap_causal_recognized_at = Some(max_timestamp(
184 self.tap_causal_recognized_at,
185 edge.recognized_at,
186 ));
187 self.commit_pending_taps(edge.recognized_at, output);
188 } else {
189 let deadline = edge
190 .occurred_at
191 .checked_add(self.config.multi_tap_window)
192 .ok_or(GestureError::DeadlineOverflow {
193 control: self.control,
194 })?;
195 let motion = self.step(Event::UpTapWait)?;
196 debug_assert_eq!(motion, Motion::RecordTap);
197 self.tap_count = new_count;
198 self.last_tap_up = Some(edge.occurred_at);
199 self.tap_causal_recognized_at = Some(max_timestamp(
200 self.tap_causal_recognized_at,
201 edge.recognized_at,
202 ));
203 self.tap_deadline = Some(deadline);
204 }
205 self.clear_press_context();
206 Ok(())
207 }
208 State::Idle | State::AwaitNextTap => Err(GestureError::UnexpectedEdge {
209 control: self.control,
210 phase: ButtonPhase::Up,
211 state: state_name(state),
212 }),
213 }
214 }
215
216 fn advance_impl(
217 &mut self,
218 now: Timestamp,
219 inclusive: bool,
220 output: &mut Vec<ButtonEvent>,
221 ) -> Result<(), GestureError> {
222 if now < self.processed_to && *self.fsm.current_state() != State::Idle {
223 return Err(GestureError::TimeRegression {
224 control: self.control,
225 previous: self.processed_to,
226 now,
227 });
228 }
229
230 while let Some(deadline) = self.next_deadline() {
231 let due = if inclusive {
232 deadline <= now
233 } else {
234 deadline < now
235 };
236 if !due {
237 break;
238 }
239
240 match *self.fsm.current_state() {
241 State::AwaitNextTap => self.expire_tap_window(deadline, output)?,
242 State::Pressed | State::Holding => {
243 self.process_due_hold_events(now, inclusive, output)?;
244 }
245 State::Idle => break,
246 }
247 }
248
249 if *self.fsm.current_state() != State::Idle {
250 self.processed_to = cmp::max(self.processed_to, now);
251 }
252 Ok(())
253 }
254
255 fn resolve_suspension(
256 &mut self,
257 now: Timestamp,
258 output: &mut Vec<ButtonEvent>,
259 ) -> Result<(), GestureError> {
260 match *self.fsm.current_state() {
261 State::AwaitNextTap => {
262 self.tap_causal_recognized_at =
263 Some(max_timestamp(self.tap_causal_recognized_at, now));
264 }
265 State::Pressed | State::Holding => {
266 self.press_recognized_at = Some(max_timestamp(self.press_recognized_at, now));
267 }
268 State::Idle => {}
269 }
270 self.advance_impl(now, true, output)
271 }
272
273 fn process_due_hold_events(
274 &mut self,
275 now: Timestamp,
276 inclusive: bool,
277 output: &mut Vec<ButtonEvent>,
278 ) -> Result<(), GestureError> {
279 while let Some(deadline) = self.next_hold_deadline() {
280 let due = if inclusive {
281 deadline <= now
282 } else {
283 deadline < now
284 };
285 if !due {
286 break;
287 }
288
289 let threshold = self.config.hold_thresholds[self.next_hold_index];
290 if self.next_hold_index == 0 {
291 let motion = self.step(Event::HoldReached)?;
292 debug_assert_eq!(motion, Motion::StartHold);
293 if self.tap_count > 0 {
294 match self.config.hold_after_tap {
295 HoldAfterTapPolicy::CancelPendingTaps => self.clear_tap_context(),
296 HoldAfterTapPolicy::CommitPendingTaps => {
297 let recognized_at = max_timestamp(
298 self.press_recognized_at,
299 max_timestamp(self.tap_causal_recognized_at, deadline),
300 );
301 self.commit_pending_taps(recognized_at, output);
302 }
303 }
304 }
305 output.push(ButtonEvent::gesture(
306 self.control,
307 GestureKind::HoldStart { threshold },
308 deadline,
309 max_timestamp(self.press_recognized_at, deadline),
310 ));
311 } else {
312 let motion = self.step(Event::HoldMilestoneReached)?;
313 debug_assert_eq!(motion, Motion::EmitHoldMilestone);
314 output.push(ButtonEvent::gesture(
315 self.control,
316 GestureKind::HoldMilestone { threshold },
317 deadline,
318 max_timestamp(self.press_recognized_at, deadline),
319 ));
320 }
321 self.next_hold_index += 1;
322 }
323
324 if *self.fsm.current_state() == State::Holding {
325 self.process_due_repeats(now, inclusive, output)?;
326 }
327 Ok(())
328 }
329
330 fn process_due_repeats(
331 &mut self,
332 now: Timestamp,
333 inclusive: bool,
334 output: &mut Vec<ButtonEvent>,
335 ) -> Result<(), GestureError> {
336 let Some(repeat) = &self.config.repeat else {
337 return Ok(());
338 };
339 let interval = repeat.interval;
340 let Some(next_repeat) = self.next_repeat_at else {
341 return Ok(());
342 };
343 let due = if inclusive {
344 next_repeat <= now
345 } else {
346 next_repeat < now
347 };
348 if !due {
349 return Ok(());
350 }
351
352 let elapsed = now
353 .checked_duration_since(next_repeat)
354 .expect("repeat deadline is not in the future");
355 let interval_ns = interval.as_nanos();
356 let due_count_u128 = elapsed.as_nanos() / interval_ns + 1;
357 let due_count = u64::try_from(due_count_u128).unwrap_or(u64::MAX);
358 let count = NonZeroU64::new(due_count).expect("a due repeat count is non-zero");
359 let offset = duration_mul(interval, due_count.saturating_sub(1));
360 let occurred_at = next_repeat.saturating_add(offset);
361
362 let motion = self.step(Event::RepeatDue)?;
363 debug_assert_eq!(motion, Motion::EmitRepeat);
364 output.push(ButtonEvent::gesture(
365 self.control,
366 GestureKind::Repeat { count },
367 occurred_at,
368 max_timestamp(self.press_recognized_at, occurred_at),
369 ));
370
371 let next_offset = duration_mul(interval, due_count);
372 let candidate = next_repeat.saturating_add(next_offset);
373 self.next_repeat_at = (candidate > next_repeat).then_some(candidate);
374 Ok(())
375 }
376
377 fn expire_tap_window(
378 &mut self,
379 deadline: Timestamp,
380 output: &mut Vec<ButtonEvent>,
381 ) -> Result<(), GestureError> {
382 let motion = self.step(Event::TapWindowExpired)?;
383 debug_assert_eq!(motion, Motion::CompleteTap);
384 let recognized_at = max_timestamp(self.tap_causal_recognized_at, deadline);
385 self.commit_pending_taps(recognized_at, output);
386 Ok(())
387 }
388
389 fn commit_pending_taps(&mut self, recognized_at: Timestamp, output: &mut Vec<ButtonEvent>) {
390 if self.tap_count > 0 {
391 let occurred_at = self
392 .last_tap_up
393 .expect("a non-zero tap count has a release timestamp");
394 output.push(ButtonEvent::gesture(
395 self.control,
396 GestureKind::Tap {
397 count: self.tap_count,
398 },
399 occurred_at,
400 max_timestamp(self.tap_causal_recognized_at, recognized_at),
401 ));
402 }
403 self.clear_tap_context();
404 }
405
406 fn next_hold_deadline(&self) -> Option<Timestamp> {
407 let down_at = self.down_at?;
408 let threshold = *self.config.hold_thresholds.get(self.next_hold_index)?;
409 down_at.checked_add(threshold)
410 }
411
412 fn ensure_deadline_fits(&self, down_at: Timestamp) -> Result<(), GestureError> {
413 if self
414 .config
415 .hold_thresholds
416 .last()
417 .is_some_and(|threshold| down_at.checked_add(*threshold).is_none())
418 || self
419 .config
420 .repeat
421 .as_ref()
422 .is_some_and(|repeat| down_at.checked_add(repeat.starts_after).is_none())
423 {
424 return Err(GestureError::DeadlineOverflow {
425 control: self.control,
426 });
427 }
428 Ok(())
429 }
430
431 fn validate_edge_timing(&self, edge: ControlEdge) -> Result<(), GestureError> {
432 if edge.occurred_at > edge.recognized_at {
433 return Err(GestureError::InvalidCausality {
434 control: self.control,
435 occurred_at: edge.occurred_at,
436 recognized_at: edge.recognized_at,
437 });
438 }
439 Ok(())
440 }
441
442 fn step(&mut self, event: Event) -> Result<Motion, GestureError> {
443 self.fsm
444 .step(&event)
445 .map(|(_, motion)| *motion)
446 .map_err(|source| GestureError::InvalidTransition {
447 control: self.control,
448 detail: source.to_string(),
449 })
450 }
451
452 fn clear_press_context(&mut self) {
453 self.down_at = None;
454 self.press_recognized_at = None;
455 self.next_hold_index = 0;
456 self.next_repeat_at = None;
457 }
458
459 fn clear_tap_context(&mut self) {
460 self.tap_count = 0;
461 self.last_tap_up = None;
462 self.tap_causal_recognized_at = None;
463 self.tap_deadline = None;
464 }
465}
466
467#[derive(Debug, Clone)]
469pub struct GestureBank {
470 recognizers: HashMap<ControlId, GestureRecognizer>,
471}
472
473impl GestureBank {
474 pub fn new(config: &FrameworkConfig) -> Result<Self, ConfigError> {
475 config.validate()?;
476 Ok(Self::new_validated(config))
477 }
478
479 pub(crate) fn new_validated(config: &FrameworkConfig) -> Self {
480 let mut recognizers = HashMap::new();
481 for button in &config.buttons {
482 let control = ControlId::Key(button.id);
483 recognizers.insert(
484 control,
485 GestureRecognizer::new_validated(control, config.gesture_config(control).clone()),
486 );
487 }
488 for chord in &config.chords {
489 let control = ControlId::Chord(chord.id);
490 recognizers.insert(
491 control,
492 GestureRecognizer::new_validated(control, config.gesture_config(control).clone()),
493 );
494 }
495 Self { recognizers }
496 }
497
498 pub fn process_edges(
499 &mut self,
500 edges: impl IntoIterator<Item = ControlEdge>,
501 ) -> Result<Vec<ButtonEvent>, GestureError> {
502 let mut output = Vec::new();
503 for edge in edges {
504 let recognizer = self
505 .recognizers
506 .get_mut(&edge.control)
507 .ok_or(GestureError::UnknownControl(edge.control))?;
508 recognizer.prepare_edge(edge, &mut output)?;
509 output.push(ButtonEvent::state(edge));
510 recognizer.apply_edge(edge, &mut output)?;
511 }
512 Ok(output)
513 }
514
515 pub fn advance_before(
516 &mut self,
517 now: Timestamp,
518 suspended_keys: &HashSet<KeyId>,
519 ) -> Result<Vec<ButtonEvent>, GestureError> {
520 self.advance_impl(now, false, suspended_keys)
521 }
522
523 pub fn advance_through(
524 &mut self,
525 now: Timestamp,
526 suspended_keys: &HashSet<KeyId>,
527 ) -> Result<Vec<ButtonEvent>, GestureError> {
528 self.advance_impl(now, true, suspended_keys)
529 }
530
531 pub fn next_deadline(&self) -> Option<Timestamp> {
532 self.next_deadline_excluding(&HashSet::new())
533 }
534
535 pub fn resolve_suspensions(
539 &mut self,
540 keys: &HashSet<KeyId>,
541 now: Timestamp,
542 ) -> Result<Vec<ButtonEvent>, GestureError> {
543 let mut ordered: Vec<_> = keys.iter().copied().collect();
544 ordered.sort_unstable();
545 let mut output = Vec::new();
546 for key in ordered {
547 let control = ControlId::Key(key);
548 let recognizer = self
549 .recognizers
550 .get_mut(&control)
551 .ok_or(GestureError::UnknownControl(control))?;
552 recognizer.resolve_suspension(now, &mut output)?;
553 }
554 Ok(output)
555 }
556
557 pub fn next_deadline_excluding(&self, suspended_keys: &HashSet<KeyId>) -> Option<Timestamp> {
558 self.recognizers
559 .iter()
560 .filter(|(control, _)| {
561 !matches!(control, ControlId::Key(key) if suspended_keys.contains(key))
562 })
563 .filter_map(|(_, recognizer)| recognizer.next_deadline())
564 .min()
565 }
566
567 fn advance_impl(
568 &mut self,
569 now: Timestamp,
570 inclusive: bool,
571 suspended_keys: &HashSet<KeyId>,
572 ) -> Result<Vec<ButtonEvent>, GestureError> {
573 let mut controls: Vec<_> = self.recognizers.keys().copied().collect();
574 controls.sort_unstable();
575 let mut output = Vec::new();
576 for control in controls {
577 if matches!(control, ControlId::Key(key) if suspended_keys.contains(&key)) {
578 continue;
579 }
580 let recognizer = self
581 .recognizers
582 .get_mut(&control)
583 .expect("control came from recognizer map");
584 recognizer.advance_impl(now, inclusive, &mut output)?;
585 }
586 Ok(output)
587 }
588}
589
590#[derive(Debug, Clone, PartialEq, Eq)]
591pub enum GestureError {
592 UnknownControl(ControlId),
593 TimeRegression {
594 control: ControlId,
595 previous: Timestamp,
596 now: Timestamp,
597 },
598 InvalidCausality {
599 control: ControlId,
600 occurred_at: Timestamp,
601 recognized_at: Timestamp,
602 },
603 UnexpectedEdge {
604 control: ControlId,
605 phase: ButtonPhase,
606 state: &'static str,
607 },
608 EventBeforePress {
609 control: ControlId,
610 },
611 MissingPressContext {
612 control: ControlId,
613 },
614 DeadlineOverflow {
615 control: ControlId,
616 },
617 InvalidTransition {
618 control: ControlId,
619 detail: String,
620 },
621}
622
623impl fmt::Display for GestureError {
624 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
625 match self {
626 Self::UnknownControl(control) => write!(f, "unknown gesture control {control:?}"),
627 Self::TimeRegression {
628 control,
629 previous,
630 now,
631 } => write!(
632 f,
633 "gesture time for {control:?} regressed from {previous} to {now}"
634 ),
635 Self::InvalidCausality {
636 control,
637 occurred_at,
638 recognized_at,
639 } => write!(
640 f,
641 "gesture edge for {control:?} occurs at {occurred_at} after recognition at {recognized_at}"
642 ),
643 Self::UnexpectedEdge {
644 control,
645 phase,
646 state,
647 } => write!(
648 f,
649 "unexpected {phase:?} for {control:?} in gesture state {state:?}"
650 ),
651 Self::EventBeforePress { control } => {
652 write!(f, "release for {control:?} predates its press")
653 }
654 Self::MissingPressContext { control } => {
655 write!(f, "gesture state for {control:?} has no press context")
656 }
657 Self::DeadlineOverflow { control } => {
658 write!(f, "gesture deadline for {control:?} overflows Timestamp")
659 }
660 Self::InvalidTransition { control, detail } => {
661 write!(f, "gesture FSM for {control:?} rejected an event: {detail}")
662 }
663 }
664 }
665}
666
667impl Error for GestureError {
668 fn source(&self) -> Option<&(dyn Error + 'static)> {
669 None
670 }
671}
672
673fn max_timestamp(optional: Option<Timestamp>, value: Timestamp) -> Timestamp {
674 optional.map_or(value, |candidate| cmp::max(candidate, value))
675}
676
677fn state_name(state: State) -> &'static str {
678 match state {
679 State::Idle => "Idle",
680 State::Pressed => "Pressed",
681 State::AwaitNextTap => "AwaitNextTap",
682 State::Holding => "Holding",
683 }
684}
685
686fn duration_mul(duration: Duration, count: u64) -> Duration {
687 let nanos = duration.as_nanos().saturating_mul(u128::from(count));
688 let seconds = nanos / 1_000_000_000;
689 if seconds > u128::from(u64::MAX) {
690 return Duration::MAX;
691 }
692 Duration::new(seconds as u64, (nanos % 1_000_000_000) as u32)
693}
694
695#[cfg(test)]
696mod tests {
697 use super::*;
698 use crate::key::config::{HoldAfterTapPolicy, RepeatConfig};
699 use crate::key::types::{ButtonEventKind, ChordId, GestureKind, KeyId};
700
701 fn time(ms: u64) -> Timestamp {
702 Timestamp::from_millis(ms)
703 }
704
705 fn edge(control: ControlId, phase: ButtonPhase, ms: u64) -> ControlEdge {
706 ControlEdge {
707 control,
708 phase,
709 occurred_at: time(ms),
710 recognized_at: time(ms),
711 }
712 }
713
714 fn gestures(events: &[ButtonEvent]) -> Vec<&GestureKind> {
715 events
716 .iter()
717 .filter_map(|event| match &event.kind {
718 ButtonEventKind::Gesture { kind, .. } => Some(kind),
719 ButtonEventKind::State { .. } => None,
720 })
721 .collect()
722 }
723
724 #[test]
725 fn single_tap_emits_at_window_deadline() {
726 let control = ControlId::Key(KeyId(1));
727 let mut recognizer = GestureRecognizer::new(control, GestureConfig::default()).unwrap();
728 let mut output = Vec::new();
729 recognizer
730 .prepare_edge(edge(control, ButtonPhase::Down, 0), &mut output)
731 .unwrap();
732 recognizer
733 .apply_edge(edge(control, ButtonPhase::Down, 0), &mut output)
734 .unwrap();
735 recognizer
736 .prepare_edge(edge(control, ButtonPhase::Up, 20), &mut output)
737 .unwrap();
738 recognizer
739 .apply_edge(edge(control, ButtonPhase::Up, 20), &mut output)
740 .unwrap();
741 recognizer
742 .advance_impl(time(519), true, &mut output)
743 .unwrap();
744 assert!(gestures(&output).is_empty());
745 recognizer
746 .advance_impl(time(520), true, &mut output)
747 .unwrap();
748 assert_eq!(gestures(&output), vec![&GestureKind::Tap { count: 1 }]);
749 }
750
751 #[test]
752 fn second_down_at_exact_window_deadline_joins_sequence() {
753 let control = ControlId::Key(KeyId(1));
754 let mut recognizer = GestureRecognizer::new(control, GestureConfig::default()).unwrap();
755 let mut output = Vec::new();
756 for value in [
757 edge(control, ButtonPhase::Down, 0),
758 edge(control, ButtonPhase::Up, 20),
759 edge(control, ButtonPhase::Down, 520),
760 edge(control, ButtonPhase::Up, 540),
761 ] {
762 recognizer.prepare_edge(value, &mut output).unwrap();
763 recognizer.apply_edge(value, &mut output).unwrap();
764 }
765 assert_eq!(gestures(&output), vec![&GestureKind::Tap { count: 2 }]);
766 }
767
768 #[test]
769 fn release_at_hold_threshold_emits_start_then_end() {
770 let control = ControlId::Key(KeyId(1));
771 let mut recognizer = GestureRecognizer::new(control, GestureConfig::default()).unwrap();
772 let mut output = Vec::new();
773 let down = edge(control, ButtonPhase::Down, 0);
774 recognizer.prepare_edge(down, &mut output).unwrap();
775 recognizer.apply_edge(down, &mut output).unwrap();
776 let up = edge(control, ButtonPhase::Up, 1_000);
777 recognizer.prepare_edge(up, &mut output).unwrap();
778 recognizer.apply_edge(up, &mut output).unwrap();
779 assert_eq!(
780 gestures(&output),
781 vec![
782 &GestureKind::HoldStart {
783 threshold: Duration::from_secs(1),
784 },
785 &GestureKind::HoldEnd {
786 held_for: Duration::from_secs(1),
787 },
788 ]
789 );
790 }
791
792 #[test]
793 fn repeat_jump_is_coalesced() {
794 let control = ControlId::Chord(ChordId(2));
795 let config = GestureConfig {
796 repeat: Some(RepeatConfig {
797 starts_after: Duration::from_millis(1_200),
798 interval: Duration::from_millis(100),
799 }),
800 ..GestureConfig::default()
801 };
802 let mut recognizer = GestureRecognizer::new(control, config).unwrap();
803 let mut output = Vec::new();
804 let down = edge(control, ButtonPhase::Down, 0);
805 recognizer.prepare_edge(down, &mut output).unwrap();
806 recognizer.apply_edge(down, &mut output).unwrap();
807 recognizer
808 .advance_impl(time(1_600), true, &mut output)
809 .unwrap();
810 assert!(gestures(&output).contains(&&GestureKind::Repeat {
811 count: NonZeroU64::new(5).unwrap(),
812 }));
813 }
814
815 #[test]
816 fn commit_policy_emits_pending_tap_before_hold() {
817 let control = ControlId::Key(KeyId(1));
818 let config = GestureConfig {
819 hold_after_tap: HoldAfterTapPolicy::CommitPendingTaps,
820 ..GestureConfig::default()
821 };
822 let mut recognizer = GestureRecognizer::new(control, config).unwrap();
823 let mut output = Vec::new();
824 for value in [
825 edge(control, ButtonPhase::Down, 0),
826 edge(control, ButtonPhase::Up, 20),
827 edge(control, ButtonPhase::Down, 100),
828 ] {
829 recognizer.prepare_edge(value, &mut output).unwrap();
830 recognizer.apply_edge(value, &mut output).unwrap();
831 }
832 recognizer
833 .advance_impl(time(1_100), true, &mut output)
834 .unwrap();
835 assert_eq!(
836 gestures(&output),
837 vec![
838 &GestureKind::Tap { count: 1 },
839 &GestureKind::HoldStart {
840 threshold: Duration::from_secs(1),
841 },
842 ]
843 );
844 }
845}