1#[path = "input/control.rs"]
4mod control;
5use control::cancelled_controls;
6pub use control::{InputCancellationReason, InputControl};
7
8#[path = "input/pointer.rs"]
9mod pointer;
10
11use pointer::{ALL_MOUSE_BUTTONS, mouse_button_index};
12pub use pointer::{DuplicateMouseBinding, MouseButton, PointerSample, PointerSampleError};
13
14#[path = "input/motion.rs"]
15mod motion;
16pub use motion::{RelativePointerMotion, RelativePointerMotionError};
17#[path = "input/scroll.rs"]
18mod scroll;
19pub use scroll::{FrameInputEvent, PointerScrollEvent, ScrollDelta, ScrollDeltaError, ScrollUnit};
20#[path = "input/capture.rs"]
21mod capture;
22pub use capture::{PointerCapture, PointerCaptureStatus};
23
24#[cfg(test)]
25#[path = "input/cancellation_tests.rs"]
26mod cancellation_tests;
27#[cfg(test)]
28#[path = "input/pointer_tests.rs"]
29mod pointer_tests;
30#[cfg(test)]
31#[path = "input/scroll_tests.rs"]
32mod scroll_tests;
33
34use std::{
35 collections::{HashMap, HashSet},
36 error::Error,
37 fmt,
38 hash::Hash,
39};
40
41use bevy_ecs::{
42 prelude::{Res, Resource},
43 system::SystemParam,
44};
45use sim_engine::Vec2;
46
47use crate::identity::{ApplicationId, TransitionIntentToken, WorldGeneration};
48
49pub const DEFAULT_INPUT_EVENT_LIMIT: usize = 1_024;
54
55pub trait Action: Copy + Eq + Hash + Send + Sync + 'static {}
61
62impl<T> Action for T where T: Copy + Eq + Hash + Send + Sync + 'static {}
63
64#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
70pub struct DigitalAxis2d<A: Action> {
71 negative_x: A,
72 positive_x: A,
73 negative_y: A,
74 positive_y: A,
75}
76
77impl<A: Action> DigitalAxis2d<A> {
78 pub const fn new(negative_x: A, positive_x: A, negative_y: A, positive_y: A) -> Self {
85 Self {
86 negative_x,
87 positive_x,
88 negative_y,
89 positive_y,
90 }
91 }
92
93 pub const fn negative_x(self) -> A {
95 self.negative_x
96 }
97
98 pub const fn positive_x(self) -> A {
100 self.positive_x
101 }
102
103 pub const fn negative_y(self) -> A {
105 self.negative_y
106 }
107
108 pub const fn positive_y(self) -> A {
110 self.positive_y
111 }
112}
113
114#[path = "input/keyboard.rs"]
115mod keyboard;
116pub use keyboard::PhysicalKeyCode;
117pub(crate) use keyboard::{ALL_PHYSICAL_KEYS, SUPPORTED_PHYSICAL_KEY_COUNT, physical_key_index};
118
119#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
121pub enum ButtonState {
122 Pressed,
124 Released,
126}
127
128#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
135pub enum InputEvent {
136 Key {
138 key: PhysicalKeyCode,
140 state: ButtonState,
142 },
143 PointerMoved {
145 sample: PointerSample,
147 },
148 RelativePointerMotion {
152 motion: RelativePointerMotion,
154 },
155 MouseWheel {
159 delta: ScrollDelta,
161 },
162 MouseButton {
164 button: MouseButton,
166 state: ButtonState,
168 },
169 PointerLeft,
173 FocusLost,
181}
182
183impl InputEvent {
184 pub const fn key(key: PhysicalKeyCode, state: ButtonState) -> Self {
186 Self::Key { key, state }
187 }
188
189 pub const fn pointer_moved(sample: PointerSample) -> Self {
191 Self::PointerMoved { sample }
192 }
193
194 pub const fn relative_pointer_motion(motion: RelativePointerMotion) -> Self {
196 Self::RelativePointerMotion { motion }
197 }
198
199 pub const fn mouse_wheel(delta: ScrollDelta) -> Self {
201 Self::MouseWheel { delta }
202 }
203
204 pub const fn mouse_button(button: MouseButton, state: ButtonState) -> Self {
207 Self::MouseButton { button, state }
208 }
209}
210
211#[derive(Debug, Clone, Copy, PartialEq, Eq)]
216pub struct DuplicateKeyBinding {
217 key: PhysicalKeyCode,
218}
219
220impl DuplicateKeyBinding {
221 pub const fn key(self) -> PhysicalKeyCode {
223 self.key
224 }
225}
226
227impl fmt::Display for DuplicateKeyBinding {
228 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
229 write!(formatter, "physical key {:?} is already bound", self.key)
230 }
231}
232
233impl Error for DuplicateKeyBinding {}
234
235#[derive(Debug, Clone)]
236pub(crate) struct ActionBindings<A: Action> {
237 by_key: [Option<A>; SUPPORTED_PHYSICAL_KEY_COUNT],
238 by_mouse: [Option<A>; ALL_MOUSE_BUTTONS.len()],
239}
240
241impl<A: Action> Default for ActionBindings<A> {
242 fn default() -> Self {
243 Self {
244 by_key: [None; SUPPORTED_PHYSICAL_KEY_COUNT],
245 by_mouse: [None; ALL_MOUSE_BUTTONS.len()],
246 }
247 }
248}
249
250impl<A: Action> ActionBindings<A> {
251 pub(crate) fn new() -> Self {
252 Self::default()
253 }
254
255 pub(crate) fn bind_mouse_button(
256 &mut self,
257 button: MouseButton,
258 action: A,
259 ) -> Result<&mut Self, DuplicateMouseBinding> {
260 let slot = &mut self.by_mouse[mouse_button_index(button)];
261 if slot.is_some() {
262 return Err(DuplicateMouseBinding { button });
263 }
264 *slot = Some(action);
265 Ok(self)
266 }
267
268 fn mouse_action_for(&self, button: MouseButton) -> Option<A> {
269 self.by_mouse[mouse_button_index(button)]
270 }
271
272 fn control_action_for(&self, control: InputControl) -> Option<A> {
273 match control {
274 InputControl::Key(key) => self.action_for(key),
275 InputControl::MouseButton(button) => self.mouse_action_for(button),
276 }
277 }
278
279 pub(crate) fn bind(
283 &mut self,
284 key: PhysicalKeyCode,
285 action: A,
286 ) -> Result<&mut Self, DuplicateKeyBinding> {
287 self.bind_all([(key, action)])
288 }
289
290 pub(crate) fn bind_wasd(
292 &mut self,
293 axis: DigitalAxis2d<A>,
294 ) -> Result<&mut Self, DuplicateKeyBinding> {
295 self.bind_all([
296 (PhysicalKeyCode::KeyW, axis.positive_y()),
297 (PhysicalKeyCode::KeyA, axis.negative_x()),
298 (PhysicalKeyCode::KeyS, axis.negative_y()),
299 (PhysicalKeyCode::KeyD, axis.positive_x()),
300 ])
301 }
302
303 pub(crate) fn bind_arrows(
305 &mut self,
306 axis: DigitalAxis2d<A>,
307 ) -> Result<&mut Self, DuplicateKeyBinding> {
308 self.bind_all([
309 (PhysicalKeyCode::ArrowLeft, axis.negative_x()),
310 (PhysicalKeyCode::ArrowRight, axis.positive_x()),
311 (PhysicalKeyCode::ArrowDown, axis.negative_y()),
312 (PhysicalKeyCode::ArrowUp, axis.positive_y()),
313 ])
314 }
315
316 pub(crate) fn bind_wasd_and_arrows(
318 &mut self,
319 axis: DigitalAxis2d<A>,
320 ) -> Result<&mut Self, DuplicateKeyBinding> {
321 self.bind_all([
322 (PhysicalKeyCode::KeyW, axis.positive_y()),
323 (PhysicalKeyCode::KeyA, axis.negative_x()),
324 (PhysicalKeyCode::KeyS, axis.negative_y()),
325 (PhysicalKeyCode::KeyD, axis.positive_x()),
326 (PhysicalKeyCode::ArrowLeft, axis.negative_x()),
327 (PhysicalKeyCode::ArrowRight, axis.positive_x()),
328 (PhysicalKeyCode::ArrowDown, axis.negative_y()),
329 (PhysicalKeyCode::ArrowUp, axis.positive_y()),
330 ])
331 }
332
333 fn bind_all<const N: usize>(
334 &mut self,
335 bindings: [(PhysicalKeyCode, A); N],
336 ) -> Result<&mut Self, DuplicateKeyBinding> {
337 for (key, _) in &bindings {
338 if self.action_for(*key).is_some() {
339 return Err(DuplicateKeyBinding { key: *key });
340 }
341 }
342 for (key, action) in bindings {
343 self.by_key[physical_key_index(key)] = Some(action);
344 }
345 Ok(self)
346 }
347
348 fn action_for(&self, key: PhysicalKeyCode) -> Option<A> {
349 self.by_key[physical_key_index(key)]
350 }
351}
352
353#[derive(Debug, Clone, Copy, PartialEq, Eq)]
355pub enum InputCollectionError {
356 RelativeMotion(RelativePointerMotionError),
358 ZeroEventLimit,
360 StorageAllocationFailed {
363 limit: usize,
365 },
366 EventLimitExceeded {
368 limit: usize,
370 received: usize,
372 },
373 FrameEdgeLimitExceeded {
377 limit: usize,
379 incoming: usize,
381 },
382 RetainedFixedEdgeLimitExceeded {
385 limit: usize,
387 retained: usize,
389 incoming: usize,
391 },
392 OccurrenceIdentityExhausted,
394}
395
396impl fmt::Display for InputCollectionError {
397 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
398 match self {
399 Self::RelativeMotion(error) => {
400 write!(formatter, "relative input collection failed: {error}")
401 }
402 Self::ZeroEventLimit => {
403 formatter.write_str("the input event and retained-edge limit must be positive")
404 }
405 Self::StorageAllocationFailed { limit } => write!(
406 formatter,
407 "failed to reserve bounded input storage for the configured limit of {limit}"
408 ),
409 Self::EventLimitExceeded { limit, received } => write!(
410 formatter,
411 "input frame contains {received} physical events, exceeding the limit of {limit}"
412 ),
413 Self::FrameEdgeLimitExceeded { limit, incoming } => write!(
414 formatter,
415 "input frame generates {incoming} logical edges, exceeding the limit of {limit}"
416 ),
417 Self::RetainedFixedEdgeLimitExceeded {
418 limit,
419 retained,
420 incoming,
421 } => write!(
422 formatter,
423 "fixed input retains {retained} edges and cannot accept {incoming} more without exceeding the limit of {limit}"
424 ),
425 Self::OccurrenceIdentityExhausted => {
426 formatter.write_str("input occurrence identity space is exhausted")
427 }
428 }
429 }
430}
431
432impl Error for InputCollectionError {}
433
434#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
441pub struct ActionEdge<A: Action> {
442 action: A,
443 state: ButtonState,
444 intent: TransitionIntentToken,
445 pointer: Option<PointerSample>,
446 control: InputControl,
447 cancellation: Option<InputCancellationReason>,
448 ordinal: usize,
449}
450
451impl<A: Action> ActionEdge<A> {
452 pub const fn control(self) -> InputControl {
456 self.control
457 }
458
459 pub const fn cancellation_reason(self) -> Option<InputCancellationReason> {
464 self.cancellation
465 }
466
467 pub const fn is_cancelled(self) -> bool {
471 self.cancellation.is_some()
472 }
473
474 pub const fn pointer(self) -> Option<PointerSample> {
478 self.pointer
479 }
480 pub const fn action(self) -> A {
482 self.action
483 }
484
485 pub const fn state(self) -> ButtonState {
487 self.state
488 }
489
490 pub const fn intent(self) -> TransitionIntentToken {
495 self.intent
496 }
497}
498
499#[derive(Debug, Clone, Resource)]
505pub(crate) struct FrameInputState<A: Action> {
506 held: HashSet<A>,
507 edges: Vec<ActionEdge<A>>,
508 scrolls: Vec<PointerScrollEvent>,
509 pointer: Option<PointerSample>,
510 relative_motion: RelativePointerMotion,
511 focus_lost: bool,
512}
513
514impl<A: Action> FrameInputState<A> {
515 pub fn held(&self, action: A) -> bool {
517 self.held.contains(&action)
518 }
519
520 fn digital_axis(&self, axis: DigitalAxis2d<A>) -> Vec2 {
521 sample_digital_axis(axis, |action| self.held(action))
522 }
523
524 pub fn pressed(&self, action: A) -> impl Iterator<Item = ActionEdge<A>> + '_ {
526 self.edges
527 .iter()
528 .copied()
529 .filter(move |edge| edge.action == action && edge.state == ButtonState::Pressed)
530 }
531
532 pub fn released(&self, action: A) -> impl Iterator<Item = ActionEdge<A>> + '_ {
534 self.edges
535 .iter()
536 .copied()
537 .filter(move |edge| edge.action == action && edge.state == ButtonState::Released)
538 }
539
540 pub(crate) fn empty() -> Self {
541 Self {
542 held: HashSet::new(),
543 edges: Vec::new(),
544 scrolls: Vec::new(),
545 pointer: None,
546 relative_motion: RelativePointerMotion::ZERO,
547 focus_lost: false,
548 }
549 }
550
551 pub(crate) fn clear_reusing_storage(&mut self) {
552 self.held.clear();
553 self.edges.clear();
554 self.scrolls.clear();
555 self.pointer = None;
556 self.relative_motion = RelativePointerMotion::ZERO;
557 self.focus_lost = false;
558 }
559
560 fn replace_from(&mut self, held_action_counts: &HashMap<A, usize>, edges: &[ActionEdge<A>]) {
561 replace_snapshot(&mut self.held, &mut self.edges, held_action_counts, edges);
562 }
563}
564
565#[derive(SystemParam)]
570pub struct FrameInput<'w, A: Action> {
571 state: Res<'w, FrameInputState<A>>,
572}
573
574impl<A: Action> FrameInput<'_, A> {
575 pub fn scroll_events(&self) -> impl Iterator<Item = PointerScrollEvent> + '_ {
579 self.state.scrolls.iter().copied()
580 }
581
582 pub fn events(&self) -> impl Iterator<Item = FrameInputEvent<A>> + '_ {
587 scroll::ordered_events(&self.state.edges, &self.state.scrolls)
588 }
589
590 pub fn relative_motion(&self) -> RelativePointerMotion {
593 self.state.relative_motion
594 }
595
596 pub fn focus_lost(&self) -> bool {
599 self.state.focus_lost
600 }
601
602 pub fn pointer(&self) -> Option<PointerSample> {
606 self.state.pointer
607 }
608
609 pub fn held(&self, action: A) -> bool {
611 self.state.held(action)
612 }
613
614 pub fn has_press_occurrence(&self, action: A) -> bool {
622 self.pressed(action).next().is_some()
623 }
624
625 pub fn has_release_occurrence(&self, action: A) -> bool {
632 self.released(action).next().is_some()
633 }
634
635 pub fn digital_axis(&self, axis: DigitalAxis2d<A>) -> Vec2 {
643 self.state.digital_axis(axis)
644 }
645
646 pub fn normalized_digital_axis(&self, axis: DigitalAxis2d<A>) -> Vec2 {
655 self.digital_axis(axis).normalized()
656 }
657
658 pub fn pressed(&self, action: A) -> impl Iterator<Item = ActionEdge<A>> + '_ {
660 self.state.pressed(action)
661 }
662
663 pub fn edges(&self) -> impl Iterator<Item = ActionEdge<A>> + '_ {
669 self.state.edges.iter().copied()
670 }
671
672 pub fn released(&self, action: A) -> impl Iterator<Item = ActionEdge<A>> + '_ {
674 self.state.released(action)
675 }
676}
677
678#[derive(Debug, Clone, Resource)]
684pub(crate) struct FixedInputState<A: Action> {
685 held: HashSet<A>,
686 edges: Vec<ActionEdge<A>>,
687 pointer: Option<PointerSample>,
688 focus_lost: bool,
689}
690
691impl<A: Action> FixedInputState<A> {
692 pub fn held(&self, action: A) -> bool {
694 self.held.contains(&action)
695 }
696
697 fn digital_axis(&self, axis: DigitalAxis2d<A>) -> Vec2 {
698 sample_digital_axis(axis, |action| self.held(action))
699 }
700
701 pub fn pressed(&self, action: A) -> impl Iterator<Item = ActionEdge<A>> + '_ {
703 self.edges
704 .iter()
705 .copied()
706 .filter(move |edge| edge.action == action && edge.state == ButtonState::Pressed)
707 }
708
709 pub fn released(&self, action: A) -> impl Iterator<Item = ActionEdge<A>> + '_ {
711 self.edges
712 .iter()
713 .copied()
714 .filter(move |edge| edge.action == action && edge.state == ButtonState::Released)
715 }
716
717 pub(crate) fn empty() -> Self {
718 Self {
719 held: HashSet::new(),
720 edges: Vec::new(),
721 pointer: None,
722 focus_lost: false,
723 }
724 }
725
726 pub(crate) fn clear_reusing_storage(&mut self) {
727 self.held.clear();
728 self.edges.clear();
729 self.pointer = None;
730 self.focus_lost = false;
731 }
732
733 fn replace_from(&mut self, held_action_counts: &HashMap<A, usize>, edges: &[ActionEdge<A>]) {
734 replace_snapshot(&mut self.held, &mut self.edges, held_action_counts, edges);
735 }
736}
737
738#[derive(SystemParam)]
745pub struct FixedInput<'w, A: Action> {
746 state: Res<'w, FixedInputState<A>>,
747}
748
749impl<A: Action> FixedInput<'_, A> {
750 pub fn focus_lost(&self) -> bool {
755 self.state.focus_lost
756 }
757
758 pub fn pointer(&self) -> Option<PointerSample> {
763 self.state.pointer
764 }
765
766 pub fn held(&self, action: A) -> bool {
768 self.state.held(action)
769 }
770
771 pub fn has_press_occurrence(&self, action: A) -> bool {
779 self.pressed(action).next().is_some()
780 }
781
782 pub fn has_release_occurrence(&self, action: A) -> bool {
791 self.released(action).next().is_some()
792 }
793
794 pub fn digital_axis(&self, axis: DigitalAxis2d<A>) -> Vec2 {
802 self.state.digital_axis(axis)
803 }
804
805 pub fn normalized_digital_axis(&self, axis: DigitalAxis2d<A>) -> Vec2 {
814 self.digital_axis(axis).normalized()
815 }
816
817 pub fn pressed(&self, action: A) -> impl Iterator<Item = ActionEdge<A>> + '_ {
819 self.state.pressed(action)
820 }
821
822 pub fn released(&self, action: A) -> impl Iterator<Item = ActionEdge<A>> + '_ {
824 self.state.released(action)
825 }
826}
827
828#[derive(Debug, Clone, Copy, PartialEq, Eq)]
829pub(crate) struct InputCollectionReport {
830 pub(crate) physical_events: usize,
831 pub(crate) logical_edges: usize,
832 pub(crate) suppressed_repeats: usize,
833 pub(crate) unmapped_events: usize,
834}
835
836#[derive(Clone, Copy)]
837struct EdgeDelivery {
838 paused: bool,
839 application: ApplicationId,
840 origin: WorldGeneration,
841 frame: u64,
842 ordinal: usize,
843}
844
845#[derive(Debug)]
846pub(crate) struct InputState<A: Action> {
847 bindings: ActionBindings<A>,
848 event_limit: usize,
849 held_keys: [bool; SUPPORTED_PHYSICAL_KEY_COUNT],
850 held_mouse: [bool; ALL_MOUSE_BUTTONS.len()],
851 pointer: Option<PointerSample>,
852 relative_motion: RelativePointerMotion,
853 focus_lost: bool,
854 held_action_counts: HashMap<A, usize>,
855 frame_edges: Vec<ActionEdge<A>>,
856 frame_scrolls: Vec<PointerScrollEvent>,
857 fixed_edges: Vec<ActionEdge<A>>,
858 next_occurrence: u64,
859}
860
861impl<A: Action> InputState<A> {
862 pub(crate) fn new(
863 bindings: ActionBindings<A>,
864 event_limit: usize,
865 ) -> Result<Self, InputCollectionError> {
866 if event_limit == 0 {
867 return Err(InputCollectionError::ZeroEventLimit);
868 }
869
870 let mut held_action_counts = HashMap::new();
871 let mut frame_edges = Vec::new();
872 let mut frame_scrolls = Vec::new();
873 let mut fixed_edges = Vec::new();
874 let held_capacity = SUPPORTED_PHYSICAL_KEY_COUNT + ALL_MOUSE_BUTTONS.len();
875 held_action_counts
876 .try_reserve(held_capacity)
877 .map_err(|_| InputCollectionError::StorageAllocationFailed { limit: event_limit })?;
878 frame_edges
879 .try_reserve(event_limit)
880 .map_err(|_| InputCollectionError::StorageAllocationFailed { limit: event_limit })?;
881 frame_scrolls
882 .try_reserve(event_limit)
883 .map_err(|_| InputCollectionError::StorageAllocationFailed { limit: event_limit })?;
884 fixed_edges
885 .try_reserve(event_limit)
886 .map_err(|_| InputCollectionError::StorageAllocationFailed { limit: event_limit })?;
887
888 Ok(Self {
889 bindings,
890 event_limit,
891 held_keys: [false; SUPPORTED_PHYSICAL_KEY_COUNT],
892 held_mouse: [false; ALL_MOUSE_BUTTONS.len()],
893 pointer: None,
894 relative_motion: RelativePointerMotion::ZERO,
895 focus_lost: false,
896 held_action_counts,
897 frame_edges,
898 frame_scrolls,
899 fixed_edges,
900 next_occurrence: 0,
901 })
902 }
903
904 pub(crate) fn collect_frame(
905 &mut self,
906 events: &[InputEvent],
907 paused: bool,
908 application: ApplicationId,
909 origin: WorldGeneration,
910 frame: u64,
911 ) -> Result<InputCollectionReport, InputCollectionError> {
912 if events.len() > self.event_limit {
913 return Err(InputCollectionError::EventLimitExceeded {
914 limit: self.event_limit,
915 received: events.len(),
916 });
917 }
918
919 let (relative_motion, focus_lost) =
920 motion::frame_motion(events).map_err(InputCollectionError::RelativeMotion)?;
921 let report = self.preflight_frame(events, paused)?;
922 let logical_edge_count = u64::try_from(report.logical_edges)
923 .map_err(|_| InputCollectionError::OccurrenceIdentityExhausted)?;
924 if self
925 .next_occurrence
926 .checked_add(logical_edge_count)
927 .is_none()
928 {
929 return Err(InputCollectionError::OccurrenceIdentityExhausted);
930 }
931
932 self.frame_edges.clear();
933 self.frame_scrolls.clear();
934 self.relative_motion = relative_motion;
935 self.focus_lost = focus_lost;
936 let mut delivery = EdgeDelivery {
937 paused,
938 application,
939 origin,
940 frame,
941 ordinal: 0,
942 };
943
944 for (ordinal, event) in events.iter().enumerate() {
945 delivery.ordinal = ordinal;
946 match *event {
947 InputEvent::Key { key, state } => {
948 self.record_edge(InputControl::Key(key), state, None, delivery);
949 }
950 InputEvent::MouseButton { button, state } => {
951 self.record_edge(InputControl::MouseButton(button), state, None, delivery);
952 }
953 InputEvent::PointerMoved { sample } => self.pointer = Some(sample),
954 InputEvent::RelativePointerMotion { .. } => {}
955 InputEvent::MouseWheel { delta } => {
956 if !focus_lost {
957 self.frame_scrolls.push(PointerScrollEvent {
958 delta,
959 pointer: self.pointer,
960 ordinal,
961 });
962 }
963 }
964 InputEvent::PointerLeft | InputEvent::FocusLost => {
965 let reason = cancellation_reason(*event);
966 self.pointer = None;
967 for control in cancelled_controls(reason) {
968 self.record_edge(control, ButtonState::Released, Some(reason), delivery);
969 }
970 }
971 }
972 }
973
974 Ok(report)
975 }
976
977 fn preflight_frame(
978 &self,
979 events: &[InputEvent],
980 paused: bool,
981 ) -> Result<InputCollectionReport, InputCollectionError> {
982 let mut held_keys = self.held_keys;
983 let mut held_mouse = self.held_mouse;
984 let mut report = InputCollectionReport {
985 physical_events: events.len(),
986 logical_edges: 0,
987 suppressed_repeats: 0,
988 unmapped_events: 0,
989 };
990
991 for event in events {
992 match *event {
993 InputEvent::Key { key, state } => {
994 preflight_button(
995 self.bindings.action_for(key),
996 &mut held_keys[physical_key_index(key)],
997 state,
998 &mut report,
999 );
1000 }
1001 InputEvent::MouseButton { button, state } => {
1002 preflight_button(
1003 self.bindings.mouse_action_for(button),
1004 &mut held_mouse[mouse_button_index(button)],
1005 state,
1006 &mut report,
1007 );
1008 }
1009 InputEvent::PointerMoved { .. }
1010 | InputEvent::RelativePointerMotion { .. }
1011 | InputEvent::MouseWheel { .. } => {}
1012 InputEvent::PointerLeft | InputEvent::FocusLost => {
1013 for control in cancelled_controls(cancellation_reason(*event)) {
1014 let held = match control {
1017 InputControl::Key(key) => &mut held_keys[physical_key_index(key)],
1018 InputControl::MouseButton(button) => {
1019 &mut held_mouse[mouse_button_index(button)]
1020 }
1021 };
1022 if self.bindings.control_action_for(control).is_some()
1023 && change_button(held, ButtonState::Released)
1024 {
1025 report.logical_edges += 1;
1026 }
1027 }
1028 }
1029 }
1030 }
1031
1032 if report.logical_edges > self.event_limit {
1033 return Err(InputCollectionError::FrameEdgeLimitExceeded {
1034 limit: self.event_limit,
1035 incoming: report.logical_edges,
1036 });
1037 }
1038
1039 if !paused && report.logical_edges > self.event_limit.saturating_sub(self.fixed_edges.len())
1040 {
1041 return Err(InputCollectionError::RetainedFixedEdgeLimitExceeded {
1042 limit: self.event_limit,
1043 retained: self.fixed_edges.len(),
1044 incoming: report.logical_edges,
1045 });
1046 }
1047
1048 Ok(report)
1049 }
1050
1051 #[cfg(test)]
1052 pub(crate) fn frame_input(&self) -> FrameInputState<A> {
1053 let mut snapshot = FrameInputState::empty();
1054 self.copy_frame_snapshot_into(&mut snapshot);
1055 snapshot
1056 }
1057
1058 #[cfg(test)]
1059 pub(crate) fn fixed_input(&self) -> FixedInputState<A> {
1060 let mut snapshot = FixedInputState::empty();
1061 self.copy_fixed_snapshot_into(&mut snapshot);
1062 snapshot
1063 }
1064
1065 pub(crate) fn copy_frame_snapshot_into(&self, target: &mut FrameInputState<A>) {
1066 target.replace_from(&self.held_action_counts, &self.frame_edges);
1067 target.scrolls.clear();
1068 target.scrolls.extend_from_slice(&self.frame_scrolls);
1069 target.pointer = self.pointer;
1070 target.relative_motion = self.relative_motion;
1071 target.focus_lost = self.focus_lost;
1072 }
1073
1074 pub(crate) fn copy_fixed_snapshot_into(&self, target: &mut FixedInputState<A>) {
1075 target.replace_from(&self.held_action_counts, &self.fixed_edges);
1076 target.pointer = self.pointer;
1077 target.focus_lost = self.focus_lost;
1078 }
1079
1080 pub(crate) fn consume_fixed_delivery(&mut self) {
1081 self.fixed_edges.clear();
1082 }
1083
1084 pub(crate) fn discard_fixed_edges(&mut self) {
1085 self.fixed_edges.clear();
1086 }
1087
1088 pub(crate) fn consume_token_occurrence(&mut self, token: TransitionIntentToken) -> bool {
1089 let was_live = self.token_is_live(token);
1090 self.frame_edges.retain(|edge| edge.intent != token);
1091 self.fixed_edges.retain(|edge| edge.intent != token);
1092 was_live
1093 }
1094
1095 pub(crate) fn token_is_live(&self, token: TransitionIntentToken) -> bool {
1096 self.frame_edges
1097 .iter()
1098 .chain(&self.fixed_edges)
1099 .any(|edge| edge.intent == token)
1100 }
1101
1102 pub(crate) fn token_is_live_in_frame(&self, token: TransitionIntentToken) -> bool {
1103 self.frame_edges.iter().any(|edge| edge.intent == token)
1104 }
1105
1106 pub(crate) fn token_is_live_in_fixed(&self, token: TransitionIntentToken) -> bool {
1107 self.fixed_edges.iter().any(|edge| edge.intent == token)
1108 }
1109
1110 pub(crate) fn clear_world_edges(&mut self) {
1111 self.frame_edges.clear();
1112 self.frame_scrolls.clear();
1113 self.fixed_edges.clear();
1114 self.relative_motion = RelativePointerMotion::ZERO;
1115 self.focus_lost = false;
1116 }
1117
1118 pub(crate) fn end_frame(&mut self) {
1119 self.frame_edges.clear();
1120 self.frame_scrolls.clear();
1121 self.relative_motion = RelativePointerMotion::ZERO;
1122 self.focus_lost = false;
1123 }
1124
1125 fn record_edge(
1126 &mut self,
1127 control: InputControl,
1128 state: ButtonState,
1129 cancellation: Option<InputCancellationReason>,
1130 delivery: EdgeDelivery,
1131 ) {
1132 let Some(action) = self.bindings.control_action_for(control) else {
1133 return;
1134 };
1135 let held = match control {
1136 InputControl::Key(key) => &mut self.held_keys[physical_key_index(key)],
1137 InputControl::MouseButton(button) => &mut self.held_mouse[mouse_button_index(button)],
1138 };
1139 if !change_button(held, state) {
1140 return;
1141 }
1142 let pointer = match (control, cancellation) {
1143 (InputControl::MouseButton(_), None) => self.pointer,
1144 _ => None,
1145 };
1146 self.update_held_action(action, state);
1147 let occurrence = self.next_occurrence;
1148 self.next_occurrence += 1;
1151 let edge = ActionEdge {
1152 action,
1153 state,
1154 pointer,
1155 control,
1156 cancellation,
1157 ordinal: delivery.ordinal,
1158 intent: TransitionIntentToken::input(
1159 delivery.application,
1160 delivery.origin,
1161 delivery.frame,
1162 occurrence,
1163 ),
1164 };
1165 self.frame_edges.push(edge);
1166 if !delivery.paused {
1167 self.fixed_edges.push(edge);
1168 }
1169 }
1170
1171 fn update_held_action(&mut self, action: A, state: ButtonState) {
1172 match state {
1173 ButtonState::Pressed => {
1174 let count = self.held_action_counts.entry(action).or_insert(0);
1175 *count += 1;
1176 }
1177 ButtonState::Released => {
1178 if let Some(count) = self.held_action_counts.get_mut(&action) {
1179 *count -= 1;
1180 if *count == 0 {
1181 self.held_action_counts.remove(&action);
1182 }
1183 }
1184 }
1185 }
1186 }
1187}
1188
1189fn cancellation_reason(event: InputEvent) -> InputCancellationReason {
1190 if matches!(event, InputEvent::FocusLost) {
1193 InputCancellationReason::FocusLost
1194 } else {
1195 InputCancellationReason::PointerLeft
1196 }
1197}
1198
1199fn change_button(held: &mut bool, state: ButtonState) -> bool {
1200 let next = state == ButtonState::Pressed;
1201 let changed = *held != next;
1202 *held = next;
1203 changed
1204}
1205
1206fn preflight_button<A: Action>(
1207 action: Option<A>,
1208 held: &mut bool,
1209 state: ButtonState,
1210 report: &mut InputCollectionReport,
1211) {
1212 if action.is_none() {
1213 report.unmapped_events += 1;
1214 } else if change_button(held, state) {
1215 report.logical_edges += 1;
1216 } else {
1217 report.suppressed_repeats += 1;
1218 }
1219}
1220
1221fn replace_snapshot<A: Action>(
1222 target_held: &mut HashSet<A>,
1223 target_edges: &mut Vec<ActionEdge<A>>,
1224 held_action_counts: &HashMap<A, usize>,
1225 source_edges: &[ActionEdge<A>],
1226) {
1227 target_held.clear();
1228 target_held.extend(held_action_counts.keys().copied());
1229 target_edges.clear();
1230 target_edges.extend_from_slice(source_edges);
1231}
1232
1233fn sample_digital_axis<A: Action>(axis: DigitalAxis2d<A>, mut held: impl FnMut(A) -> bool) -> Vec2 {
1234 let x = f32::from(held(axis.positive_x)) - f32::from(held(axis.negative_x));
1235 let y = f32::from(held(axis.positive_y)) - f32::from(held(axis.negative_y));
1236 Vec2::new(x, y)
1237}
1238
1239#[cfg(test)]
1240mod tests {
1241 use super::*;
1242
1243 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1244 enum TestAction {
1245 Move,
1246 Enter,
1247 Fire,
1248 Left,
1249 Right,
1250 Down,
1251 Up,
1252 }
1253
1254 const TEST_AXIS: DigitalAxis2d<TestAction> = DigitalAxis2d::new(
1255 TestAction::Left,
1256 TestAction::Right,
1257 TestAction::Down,
1258 TestAction::Up,
1259 );
1260
1261 fn identity() -> (ApplicationId, WorldGeneration) {
1262 let application = ApplicationId::from_raw(7);
1263 (application, WorldGeneration::new(application, 3))
1264 }
1265
1266 fn bindings() -> ActionBindings<TestAction> {
1267 let mut bindings = ActionBindings::new();
1268 assert!(
1269 bindings
1270 .bind(PhysicalKeyCode::KeyW, TestAction::Move)
1271 .is_ok()
1272 );
1273 assert!(
1274 bindings
1275 .bind(PhysicalKeyCode::KeyA, TestAction::Move)
1276 .is_ok()
1277 );
1278 assert!(
1279 bindings
1280 .bind(PhysicalKeyCode::Enter, TestAction::Enter)
1281 .is_ok()
1282 );
1283 assert!(
1284 bindings
1285 .bind(PhysicalKeyCode::Space, TestAction::Fire)
1286 .is_ok()
1287 );
1288 bindings
1289 }
1290
1291 fn state(limit: usize) -> InputState<TestAction> {
1292 let result = InputState::new(bindings(), limit);
1293 let Ok(state) = result else {
1294 panic!("test input state should be valid");
1295 };
1296 state
1297 }
1298
1299 #[test]
1300 fn duplicate_physical_key_is_rejected_without_replacement() {
1301 let mut bindings = bindings();
1302 let duplicate = bindings.bind(PhysicalKeyCode::KeyW, TestAction::Enter);
1303
1304 assert_eq!(
1305 duplicate.map(|_| ()),
1306 Err(DuplicateKeyBinding {
1307 key: PhysicalKeyCode::KeyW,
1308 })
1309 );
1310 assert_eq!(
1311 bindings.action_for(PhysicalKeyCode::KeyW),
1312 Some(TestAction::Move)
1313 );
1314 }
1315
1316 #[test]
1317 fn physical_key_catalog_is_unique_and_round_trips_every_index() {
1318 assert_eq!(SUPPORTED_PHYSICAL_KEY_COUNT, 108);
1319 let mut unique = HashSet::new();
1320
1321 for (index, key) in ALL_PHYSICAL_KEYS.into_iter().enumerate() {
1322 assert!(unique.insert(key), "duplicate catalog key {key:?}");
1323 assert_eq!(physical_key_index(key), index);
1324 assert_eq!(ALL_PHYSICAL_KEYS[physical_key_index(key)], key);
1325 }
1326 }
1327
1328 #[test]
1329 fn wasd_binding_maps_axis_slots_and_remains_compatible_with_manual_keys() {
1330 let mut bindings = ActionBindings::new();
1331 assert!(
1332 bindings
1333 .bind(PhysicalKeyCode::Enter, TestAction::Enter)
1334 .is_ok()
1335 );
1336 assert!(bindings.bind_wasd(TEST_AXIS).is_ok());
1337 assert!(
1338 bindings
1339 .bind(PhysicalKeyCode::Space, TestAction::Fire)
1340 .is_ok()
1341 );
1342
1343 assert_eq!(
1344 bindings.action_for(PhysicalKeyCode::KeyW),
1345 Some(TestAction::Up)
1346 );
1347 assert_eq!(
1348 bindings.action_for(PhysicalKeyCode::KeyA),
1349 Some(TestAction::Left)
1350 );
1351 assert_eq!(
1352 bindings.action_for(PhysicalKeyCode::KeyS),
1353 Some(TestAction::Down)
1354 );
1355 assert_eq!(
1356 bindings.action_for(PhysicalKeyCode::KeyD),
1357 Some(TestAction::Right)
1358 );
1359 assert_eq!(
1360 bindings.action_for(PhysicalKeyCode::Enter),
1361 Some(TestAction::Enter)
1362 );
1363 assert_eq!(
1364 bindings.action_for(PhysicalKeyCode::Space),
1365 Some(TestAction::Fire)
1366 );
1367 }
1368
1369 #[test]
1370 fn wasd_binding_conflicts_are_atomic_for_every_key() {
1371 let preset_keys = [
1372 PhysicalKeyCode::KeyW,
1373 PhysicalKeyCode::KeyA,
1374 PhysicalKeyCode::KeyS,
1375 PhysicalKeyCode::KeyD,
1376 ];
1377
1378 for occupied in preset_keys {
1379 let mut bindings = ActionBindings::new();
1380 assert!(bindings.bind(occupied, TestAction::Move).is_ok());
1381
1382 assert_eq!(
1383 bindings.bind_wasd(TEST_AXIS).map(|_| ()),
1384 Err(DuplicateKeyBinding { key: occupied })
1385 );
1386 for key in preset_keys {
1387 let expected = (key == occupied).then_some(TestAction::Move);
1388 assert_eq!(bindings.action_for(key), expected, "occupied={occupied:?}");
1389 }
1390 }
1391 }
1392
1393 #[test]
1394 fn wasd_binding_uses_deterministic_conflict_order_and_allows_repeated_actions() {
1395 let mut conflicted = ActionBindings::new();
1396 assert!(
1397 conflicted
1398 .bind(PhysicalKeyCode::KeyS, TestAction::Fire)
1399 .is_ok()
1400 );
1401 assert!(
1402 conflicted
1403 .bind(PhysicalKeyCode::KeyW, TestAction::Move)
1404 .is_ok()
1405 );
1406 assert_eq!(
1407 conflicted.bind_wasd(TEST_AXIS).map(|_| ()),
1408 Err(DuplicateKeyBinding {
1409 key: PhysicalKeyCode::KeyW,
1410 })
1411 );
1412
1413 let repeated = DigitalAxis2d::new(
1414 TestAction::Move,
1415 TestAction::Move,
1416 TestAction::Move,
1417 TestAction::Move,
1418 );
1419 let mut bindings = ActionBindings::new();
1420 assert!(bindings.bind_wasd(repeated).is_ok());
1421 for key in [
1422 PhysicalKeyCode::KeyW,
1423 PhysicalKeyCode::KeyA,
1424 PhysicalKeyCode::KeyS,
1425 PhysicalKeyCode::KeyD,
1426 ] {
1427 assert_eq!(bindings.action_for(key), Some(TestAction::Move));
1428 }
1429 }
1430
1431 #[test]
1432 fn arrow_binding_maps_axis_slots_and_coexists_with_wasd_and_manual_escape() {
1433 let mut bindings = ActionBindings::new();
1434 assert!(bindings.bind_wasd(TEST_AXIS).is_ok());
1435 assert!(bindings.bind_arrows(TEST_AXIS).is_ok());
1436 assert!(
1437 bindings
1438 .bind(PhysicalKeyCode::Escape, TestAction::Enter)
1439 .is_ok()
1440 );
1441
1442 for (key, expected) in [
1443 (PhysicalKeyCode::ArrowLeft, TestAction::Left),
1444 (PhysicalKeyCode::ArrowRight, TestAction::Right),
1445 (PhysicalKeyCode::ArrowDown, TestAction::Down),
1446 (PhysicalKeyCode::ArrowUp, TestAction::Up),
1447 ] {
1448 assert_eq!(bindings.action_for(key), Some(expected));
1449 }
1450 assert_eq!(
1451 bindings.action_for(PhysicalKeyCode::Escape),
1452 Some(TestAction::Enter)
1453 );
1454 }
1455
1456 #[test]
1457 fn arrow_binding_conflicts_are_atomic_and_use_axis_slot_order() {
1458 let arrow_keys = [
1459 PhysicalKeyCode::ArrowLeft,
1460 PhysicalKeyCode::ArrowRight,
1461 PhysicalKeyCode::ArrowDown,
1462 PhysicalKeyCode::ArrowUp,
1463 ];
1464
1465 for occupied in arrow_keys {
1466 let mut bindings = ActionBindings::new();
1467 assert!(bindings.bind(occupied, TestAction::Move).is_ok());
1468
1469 assert_eq!(
1470 bindings.bind_arrows(TEST_AXIS).map(|_| ()),
1471 Err(DuplicateKeyBinding { key: occupied })
1472 );
1473 for key in arrow_keys {
1474 let expected = (key == occupied).then_some(TestAction::Move);
1475 assert_eq!(bindings.action_for(key), expected, "occupied={occupied:?}");
1476 }
1477 }
1478
1479 let mut two_conflicts = ActionBindings::new();
1480 assert!(
1481 two_conflicts
1482 .bind(PhysicalKeyCode::ArrowUp, TestAction::Fire)
1483 .is_ok()
1484 );
1485 assert!(
1486 two_conflicts
1487 .bind(PhysicalKeyCode::ArrowRight, TestAction::Move)
1488 .is_ok()
1489 );
1490 assert_eq!(
1491 two_conflicts.bind_arrows(TEST_AXIS).map(|_| ()),
1492 Err(DuplicateKeyBinding {
1493 key: PhysicalKeyCode::ArrowRight,
1494 })
1495 );
1496
1497 let repeated = DigitalAxis2d::new(
1498 TestAction::Move,
1499 TestAction::Move,
1500 TestAction::Move,
1501 TestAction::Move,
1502 );
1503 let mut bindings = ActionBindings::new();
1504 assert!(bindings.bind_arrows(repeated).is_ok());
1505 for key in arrow_keys {
1506 assert_eq!(bindings.action_for(key), Some(TestAction::Move));
1507 }
1508 }
1509
1510 #[test]
1511 fn combined_directional_binding_maps_every_slot_and_preserves_manual_keys() {
1512 let mut bindings = ActionBindings::new();
1513 assert!(
1514 bindings
1515 .bind(PhysicalKeyCode::Escape, TestAction::Enter)
1516 .is_ok()
1517 );
1518 assert!(bindings.bind_wasd_and_arrows(TEST_AXIS).is_ok());
1519
1520 for (key, expected) in [
1521 (PhysicalKeyCode::KeyW, TestAction::Up),
1522 (PhysicalKeyCode::KeyA, TestAction::Left),
1523 (PhysicalKeyCode::KeyS, TestAction::Down),
1524 (PhysicalKeyCode::KeyD, TestAction::Right),
1525 (PhysicalKeyCode::ArrowLeft, TestAction::Left),
1526 (PhysicalKeyCode::ArrowRight, TestAction::Right),
1527 (PhysicalKeyCode::ArrowDown, TestAction::Down),
1528 (PhysicalKeyCode::ArrowUp, TestAction::Up),
1529 ] {
1530 assert_eq!(bindings.action_for(key), Some(expected));
1531 }
1532 assert_eq!(
1533 bindings.action_for(PhysicalKeyCode::Escape),
1534 Some(TestAction::Enter)
1535 );
1536 assert_eq!(bindings.action_for(PhysicalKeyCode::Enter), None);
1537 assert_eq!(bindings.action_for(PhysicalKeyCode::Space), None);
1538 let before_repeat = ALL_PHYSICAL_KEYS.map(|key| bindings.action_for(key));
1539 assert_eq!(
1540 bindings.bind_wasd_and_arrows(TEST_AXIS).map(|_| ()),
1541 Err(DuplicateKeyBinding {
1542 key: PhysicalKeyCode::KeyW,
1543 })
1544 );
1545 assert_eq!(
1546 ALL_PHYSICAL_KEYS.map(|key| bindings.action_for(key)),
1547 before_repeat
1548 );
1549 }
1550
1551 #[test]
1552 fn combined_directional_binding_conflicts_are_atomic_for_every_key() {
1553 let preset_keys = [
1554 PhysicalKeyCode::KeyW,
1555 PhysicalKeyCode::KeyA,
1556 PhysicalKeyCode::KeyS,
1557 PhysicalKeyCode::KeyD,
1558 PhysicalKeyCode::ArrowLeft,
1559 PhysicalKeyCode::ArrowRight,
1560 PhysicalKeyCode::ArrowDown,
1561 PhysicalKeyCode::ArrowUp,
1562 ];
1563
1564 for occupied in preset_keys {
1565 let mut bindings = ActionBindings::new();
1566 assert!(bindings.bind(occupied, TestAction::Move).is_ok());
1567 assert!(
1568 bindings
1569 .bind(PhysicalKeyCode::Enter, TestAction::Enter)
1570 .is_ok()
1571 );
1572 let before = ALL_PHYSICAL_KEYS.map(|key| bindings.action_for(key));
1573
1574 assert_eq!(
1575 bindings.bind_wasd_and_arrows(TEST_AXIS).map(|_| ()),
1576 Err(DuplicateKeyBinding { key: occupied })
1577 );
1578 assert_eq!(
1579 ALL_PHYSICAL_KEYS.map(|key| bindings.action_for(key)),
1580 before,
1581 "occupied={occupied:?}"
1582 );
1583 }
1584 }
1585
1586 #[test]
1587 fn combined_directional_binding_uses_one_order_and_allows_repeated_actions() {
1588 let preset_keys = [
1589 PhysicalKeyCode::KeyW,
1590 PhysicalKeyCode::KeyA,
1591 PhysicalKeyCode::KeyS,
1592 PhysicalKeyCode::KeyD,
1593 PhysicalKeyCode::ArrowLeft,
1594 PhysicalKeyCode::ArrowRight,
1595 PhysicalKeyCode::ArrowDown,
1596 PhysicalKeyCode::ArrowUp,
1597 ];
1598 for first_index in 0..preset_keys.len() {
1599 for second_index in (first_index + 1)..preset_keys.len() {
1600 let mut conflicted = ActionBindings::new();
1601 assert!(
1602 conflicted
1603 .bind(preset_keys[second_index], TestAction::Fire)
1604 .is_ok()
1605 );
1606 assert!(
1607 conflicted
1608 .bind(preset_keys[first_index], TestAction::Move)
1609 .is_ok()
1610 );
1611 let before = ALL_PHYSICAL_KEYS.map(|key| conflicted.action_for(key));
1612 assert_eq!(
1613 conflicted.bind_wasd_and_arrows(TEST_AXIS).map(|_| ()),
1614 Err(DuplicateKeyBinding {
1615 key: preset_keys[first_index],
1616 })
1617 );
1618 assert_eq!(
1619 ALL_PHYSICAL_KEYS.map(|key| conflicted.action_for(key)),
1620 before
1621 );
1622 }
1623 }
1624
1625 let repeated = DigitalAxis2d::new(
1626 TestAction::Move,
1627 TestAction::Move,
1628 TestAction::Move,
1629 TestAction::Move,
1630 );
1631 let mut bindings = ActionBindings::new();
1632 assert!(bindings.bind_wasd_and_arrows(repeated).is_ok());
1633 for key in preset_keys {
1634 assert_eq!(bindings.action_for(key), Some(TestAction::Move));
1635 }
1636 }
1637
1638 #[test]
1639 fn digital_axis_descriptor_is_const_copy_and_preserves_slot_order() {
1640 const COPY: DigitalAxis2d<TestAction> = TEST_AXIS;
1641
1642 assert_eq!(COPY.negative_x(), TestAction::Left);
1643 assert_eq!(COPY.positive_x(), TestAction::Right);
1644 assert_eq!(COPY.negative_y(), TestAction::Down);
1645 assert_eq!(COPY.positive_y(), TestAction::Up);
1646 }
1647
1648 #[test]
1649 fn frame_and_fixed_digital_axes_cover_all_held_combinations() {
1650 let actions = [
1651 TestAction::Left,
1652 TestAction::Right,
1653 TestAction::Down,
1654 TestAction::Up,
1655 ];
1656
1657 for mask in 0_u8..16 {
1658 let held: HashSet<_> = actions
1659 .into_iter()
1660 .enumerate()
1661 .filter_map(|(index, action)| (mask & (1 << index) != 0).then_some(action))
1662 .collect();
1663 let frame = FrameInputState {
1664 held: held.clone(),
1665 ..FrameInputState::empty()
1666 };
1667 let fixed = FixedInputState {
1668 held,
1669 ..FixedInputState::empty()
1670 };
1671 let expected = Vec2::new(
1672 f32::from(mask & 0b0010 != 0) - f32::from(mask & 0b0001 != 0),
1673 f32::from(mask & 0b1000 != 0) - f32::from(mask & 0b0100 != 0),
1674 );
1675
1676 assert_eq!(frame.digital_axis(TEST_AXIS), expected, "mask {mask:04b}");
1677 assert_eq!(fixed.digital_axis(TEST_AXIS), expected, "mask {mask:04b}");
1678 }
1679
1680 let diagonal = FrameInputState {
1681 held: HashSet::from([TestAction::Right, TestAction::Up]),
1682 ..FrameInputState::empty()
1683 }
1684 .digital_axis(TEST_AXIS);
1685 assert_eq!(diagonal, Vec2::ONE);
1686 assert!((diagonal.normalized().length() - 1.0).abs() < 0.000_1);
1687 }
1688
1689 #[test]
1690 fn repeated_actions_follow_independent_slot_arithmetic() {
1691 let held = |action| action == TestAction::Move;
1692 let cancelled = DigitalAxis2d::new(
1693 TestAction::Move,
1694 TestAction::Move,
1695 TestAction::Enter,
1696 TestAction::Fire,
1697 );
1698 let diagonal = DigitalAxis2d::new(
1699 TestAction::Enter,
1700 TestAction::Move,
1701 TestAction::Fire,
1702 TestAction::Move,
1703 );
1704
1705 assert_eq!(sample_digital_axis(cancelled, held), Vec2::ZERO);
1706 assert_eq!(sample_digital_axis(diagonal, held), Vec2::ONE);
1707 }
1708
1709 #[test]
1710 fn digital_axis_does_not_consume_press_or_release_edges() {
1711 let (application, generation) = identity();
1712 let mut input = state(4);
1713 let events = [
1714 InputEvent::key(PhysicalKeyCode::KeyW, ButtonState::Pressed),
1715 InputEvent::key(PhysicalKeyCode::KeyW, ButtonState::Released),
1716 ];
1717 assert!(
1718 input
1719 .collect_frame(&events, false, application, generation, 1)
1720 .is_ok()
1721 );
1722 let axis = DigitalAxis2d::new(
1723 TestAction::Enter,
1724 TestAction::Move,
1725 TestAction::Fire,
1726 TestAction::Fire,
1727 );
1728 let frame = input.frame_input();
1729 let fixed = input.fixed_input();
1730
1731 assert_eq!(frame.digital_axis(axis), Vec2::ZERO);
1732 assert_eq!(fixed.digital_axis(axis), Vec2::ZERO);
1733 assert_eq!(frame.pressed(TestAction::Move).count(), 1);
1734 assert_eq!(frame.released(TestAction::Move).count(), 1);
1735 assert_eq!(fixed.pressed(TestAction::Move).count(), 1);
1736 assert_eq!(fixed.released(TestAction::Move).count(), 1);
1737 assert_eq!(frame.digital_axis(axis), Vec2::ZERO);
1738 assert_eq!(fixed.digital_axis(axis), Vec2::ZERO);
1739 }
1740
1741 #[test]
1742 fn space_produces_typed_press_and_release_edges() {
1743 let (application, generation) = identity();
1744 let mut input = state(2);
1745
1746 assert!(
1747 input
1748 .collect_frame(
1749 &[InputEvent::key(
1750 PhysicalKeyCode::Space,
1751 ButtonState::Pressed,
1752 )],
1753 false,
1754 application,
1755 generation,
1756 1,
1757 )
1758 .is_ok()
1759 );
1760 assert!(input.frame_input().held(TestAction::Fire));
1761 assert_eq!(input.frame_input().pressed(TestAction::Fire).count(), 1);
1762
1763 input.end_frame();
1764 assert!(
1765 input
1766 .collect_frame(
1767 &[InputEvent::key(
1768 PhysicalKeyCode::Space,
1769 ButtonState::Released,
1770 )],
1771 false,
1772 application,
1773 generation,
1774 2,
1775 )
1776 .is_ok()
1777 );
1778 assert!(!input.frame_input().held(TestAction::Fire));
1779 assert_eq!(input.frame_input().released(TestAction::Fire).count(), 1);
1780 }
1781
1782 #[test]
1783 fn unreservable_input_limit_returns_a_typed_creation_error() {
1784 let result = InputState::new(bindings(), usize::MAX);
1785
1786 assert!(matches!(
1787 result,
1788 Err(InputCollectionError::StorageAllocationFailed { limit: usize::MAX })
1789 ));
1790 }
1791
1792 #[test]
1793 fn overflow_rejects_the_frame_before_mutating_input() {
1794 let (application, generation) = identity();
1795 let mut input = state(1);
1796 assert!(
1797 input
1798 .collect_frame(
1799 &[InputEvent::key(PhysicalKeyCode::KeyW, ButtonState::Pressed,)],
1800 false,
1801 application,
1802 generation,
1803 1,
1804 )
1805 .is_ok()
1806 );
1807 let before_frame = input.frame_input();
1808 let before_fixed = input.fixed_input();
1809
1810 let result = input.collect_frame(
1811 &[
1812 InputEvent::key(PhysicalKeyCode::KeyW, ButtonState::Released),
1813 InputEvent::key(PhysicalKeyCode::Enter, ButtonState::Pressed),
1814 ],
1815 false,
1816 application,
1817 generation,
1818 2,
1819 );
1820
1821 assert_eq!(
1822 result,
1823 Err(InputCollectionError::EventLimitExceeded {
1824 limit: 1,
1825 received: 2,
1826 })
1827 );
1828 assert_eq!(
1829 before_frame.pressed(TestAction::Move).count(),
1830 input.frame_input().pressed(TestAction::Move).count()
1831 );
1832 assert_eq!(
1833 before_fixed.pressed(TestAction::Move).count(),
1834 input.fixed_input().pressed(TestAction::Move).count()
1835 );
1836 assert!(input.frame_input().held(TestAction::Move));
1837 }
1838
1839 #[test]
1840 fn retained_fixed_edge_overflow_is_atomic_without_fixed_delivery() {
1841 let (application, generation) = identity();
1842 let mut input = state(2);
1843 assert!(
1844 input
1845 .collect_frame(
1846 &[InputEvent::key(PhysicalKeyCode::KeyW, ButtonState::Pressed,)],
1847 false,
1848 application,
1849 generation,
1850 1,
1851 )
1852 .is_ok()
1853 );
1854 input.end_frame();
1855 assert!(
1856 input
1857 .collect_frame(
1858 &[InputEvent::key(
1859 PhysicalKeyCode::KeyW,
1860 ButtonState::Released,
1861 )],
1862 false,
1863 application,
1864 generation,
1865 2,
1866 )
1867 .is_ok()
1868 );
1869 input.end_frame();
1870
1871 let occurrence_before = input.next_occurrence;
1872 let result = input.collect_frame(
1873 &[InputEvent::key(PhysicalKeyCode::KeyW, ButtonState::Pressed)],
1874 false,
1875 application,
1876 generation,
1877 3,
1878 );
1879
1880 assert_eq!(
1881 result,
1882 Err(InputCollectionError::RetainedFixedEdgeLimitExceeded {
1883 limit: 2,
1884 retained: 2,
1885 incoming: 1,
1886 })
1887 );
1888 assert_eq!(input.next_occurrence, occurrence_before);
1889 assert!(!input.frame_input().held(TestAction::Move));
1890 assert_eq!(input.frame_input().pressed(TestAction::Move).count(), 0);
1891 assert_eq!(input.fixed_input().pressed(TestAction::Move).count(), 1);
1892 assert_eq!(input.fixed_input().released(TestAction::Move).count(), 1);
1893 }
1894
1895 #[test]
1896 fn consuming_fixed_delivery_releases_the_retained_edge_budget() {
1897 let (application, generation) = identity();
1898 let mut input = state(1);
1899 assert!(
1900 input
1901 .collect_frame(
1902 &[InputEvent::key(PhysicalKeyCode::KeyW, ButtonState::Pressed,)],
1903 false,
1904 application,
1905 generation,
1906 1,
1907 )
1908 .is_ok()
1909 );
1910 input.end_frame();
1911 input.consume_fixed_delivery();
1912
1913 assert!(
1914 input
1915 .collect_frame(
1916 &[InputEvent::key(
1917 PhysicalKeyCode::KeyW,
1918 ButtonState::Released,
1919 )],
1920 false,
1921 application,
1922 generation,
1923 2,
1924 )
1925 .is_ok()
1926 );
1927 assert_eq!(input.fixed_input().released(TestAction::Move).count(), 1);
1928 }
1929
1930 #[test]
1931 fn repeated_physical_states_do_not_create_edges() {
1932 let (application, generation) = identity();
1933 let mut input = state(8);
1934 let events = [
1935 InputEvent::key(PhysicalKeyCode::KeyW, ButtonState::Pressed),
1936 InputEvent::key(PhysicalKeyCode::KeyW, ButtonState::Pressed),
1937 InputEvent::key(PhysicalKeyCode::KeyW, ButtonState::Released),
1938 InputEvent::key(PhysicalKeyCode::KeyW, ButtonState::Released),
1939 ];
1940
1941 let report = input.collect_frame(&events, false, application, generation, 1);
1942 let Ok(report) = report else {
1943 panic!("bounded input should be accepted");
1944 };
1945
1946 assert_eq!(report.logical_edges, 2);
1947 assert_eq!(report.suppressed_repeats, 2);
1948 assert_eq!(input.frame_input().pressed(TestAction::Move).count(), 1);
1949 assert_eq!(input.frame_input().released(TestAction::Move).count(), 1);
1950 assert!(!input.frame_input().held(TestAction::Move));
1951 }
1952
1953 #[test]
1954 fn every_supported_key_suppresses_repeated_physical_states() {
1955 let (application, generation) = identity();
1956 let new_keys = ALL_PHYSICAL_KEYS;
1957 let mut bindings = ActionBindings::new();
1958 for key in new_keys {
1959 assert!(bindings.bind(key, TestAction::Move).is_ok());
1960 }
1961 let mut input = InputState::new(bindings, new_keys.len() * 4).unwrap();
1962 let mut events = Vec::new();
1963 for key in new_keys {
1964 events.extend([
1965 InputEvent::key(key, ButtonState::Pressed),
1966 InputEvent::key(key, ButtonState::Pressed),
1967 InputEvent::key(key, ButtonState::Released),
1968 InputEvent::key(key, ButtonState::Released),
1969 ]);
1970 }
1971
1972 let report = input
1973 .collect_frame(&events, false, application, generation, 1)
1974 .unwrap();
1975
1976 assert_eq!(report.logical_edges, new_keys.len() * 2);
1977 assert_eq!(report.suppressed_repeats, new_keys.len() * 2);
1978 assert!(!input.frame_input().held(TestAction::Move));
1979 }
1980
1981 #[test]
1982 fn wasd_and_arrow_edges_keep_shared_action_held_until_both_release() {
1983 let (application, generation) = identity();
1984 let mut bindings = ActionBindings::new();
1985 assert!(
1986 bindings
1987 .bind(PhysicalKeyCode::KeyW, TestAction::Move)
1988 .is_ok()
1989 );
1990 assert!(
1991 bindings
1992 .bind(PhysicalKeyCode::ArrowUp, TestAction::Move)
1993 .is_ok()
1994 );
1995 assert!(
1996 bindings
1997 .bind(PhysicalKeyCode::Escape, TestAction::Enter)
1998 .is_ok()
1999 );
2000 let mut input = InputState::new(bindings, 8).unwrap();
2001 let first = [
2002 InputEvent::key(PhysicalKeyCode::KeyW, ButtonState::Pressed),
2003 InputEvent::key(PhysicalKeyCode::ArrowUp, ButtonState::Pressed),
2004 InputEvent::key(PhysicalKeyCode::Escape, ButtonState::Pressed),
2005 ];
2006 input
2007 .collect_frame(&first, false, application, generation, 1)
2008 .unwrap();
2009
2010 let frame = input.frame_input();
2011 let move_edges: Vec<_> = frame.pressed(TestAction::Move).collect();
2012 assert_eq!(move_edges.len(), 2);
2013 assert_ne!(move_edges[0].intent(), move_edges[1].intent());
2014 assert_eq!(
2015 frame.pressed(TestAction::Enter).next(),
2016 input.fixed_input().pressed(TestAction::Enter).next()
2017 );
2018
2019 input
2020 .collect_frame(
2021 &[InputEvent::key(
2022 PhysicalKeyCode::KeyW,
2023 ButtonState::Released,
2024 )],
2025 false,
2026 application,
2027 generation,
2028 2,
2029 )
2030 .unwrap();
2031 assert!(input.frame_input().held(TestAction::Move));
2032
2033 input
2034 .collect_frame(
2035 &[InputEvent::key(
2036 PhysicalKeyCode::ArrowUp,
2037 ButtonState::Released,
2038 )],
2039 false,
2040 application,
2041 generation,
2042 3,
2043 )
2044 .unwrap();
2045 assert!(!input.frame_input().held(TestAction::Move));
2046 }
2047
2048 #[test]
2049 fn two_keys_for_one_action_keep_held_state_until_both_release() {
2050 let (application, generation) = identity();
2051 let mut input = state(8);
2052 assert!(
2053 input
2054 .collect_frame(
2055 &[
2056 InputEvent::key(PhysicalKeyCode::KeyW, ButtonState::Pressed),
2057 InputEvent::key(PhysicalKeyCode::KeyA, ButtonState::Pressed),
2058 InputEvent::key(PhysicalKeyCode::KeyW, ButtonState::Released),
2059 ],
2060 false,
2061 application,
2062 generation,
2063 1,
2064 )
2065 .is_ok()
2066 );
2067
2068 let axis = DigitalAxis2d::new(
2069 TestAction::Enter,
2070 TestAction::Move,
2071 TestAction::Fire,
2072 TestAction::Fire,
2073 );
2074 assert!(input.frame_input().held(TestAction::Move));
2075 assert_eq!(input.frame_input().digital_axis(axis), Vec2::X);
2076
2077 assert!(
2078 input
2079 .collect_frame(
2080 &[InputEvent::key(
2081 PhysicalKeyCode::KeyA,
2082 ButtonState::Released,
2083 )],
2084 false,
2085 application,
2086 generation,
2087 2,
2088 )
2089 .is_ok()
2090 );
2091 assert!(!input.frame_input().held(TestAction::Move));
2092 assert_eq!(input.frame_input().digital_axis(axis), Vec2::ZERO);
2093 }
2094
2095 #[test]
2096 fn fixed_edges_persist_until_one_tick_consumes_them() {
2097 let (application, generation) = identity();
2098 let mut input = state(8);
2099 assert!(
2100 input
2101 .collect_frame(
2102 &[InputEvent::key(
2103 PhysicalKeyCode::Enter,
2104 ButtonState::Pressed,
2105 )],
2106 false,
2107 application,
2108 generation,
2109 1,
2110 )
2111 .is_ok()
2112 );
2113 input.end_frame();
2114
2115 assert!(
2116 input
2117 .collect_frame(&[], false, application, generation, 2)
2118 .is_ok()
2119 );
2120 assert_eq!(input.frame_input().pressed(TestAction::Enter).count(), 0);
2121 assert_eq!(input.fixed_input().pressed(TestAction::Enter).count(), 1);
2122
2123 input.consume_fixed_delivery();
2124 assert_eq!(input.fixed_input().pressed(TestAction::Enter).count(), 0);
2125 }
2126
2127 #[test]
2128 fn paused_events_update_frame_and_held_but_not_fixed_edges() {
2129 let (application, generation) = identity();
2130 let mut input = state(8);
2131 assert!(
2132 input
2133 .collect_frame(
2134 &[InputEvent::key(PhysicalKeyCode::KeyW, ButtonState::Pressed,)],
2135 true,
2136 application,
2137 generation,
2138 1,
2139 )
2140 .is_ok()
2141 );
2142
2143 assert!(input.frame_input().held(TestAction::Move));
2144 assert_eq!(input.frame_input().pressed(TestAction::Move).count(), 1);
2145 assert_eq!(input.fixed_input().pressed(TestAction::Move).count(), 0);
2146 }
2147
2148 #[test]
2149 fn frame_and_fixed_views_share_one_causal_token() {
2150 let (application, generation) = identity();
2151 let mut input = state(8);
2152 assert!(
2153 input
2154 .collect_frame(
2155 &[InputEvent::key(
2156 PhysicalKeyCode::Enter,
2157 ButtonState::Pressed,
2158 )],
2159 false,
2160 application,
2161 generation,
2162 1,
2163 )
2164 .is_ok()
2165 );
2166
2167 let frame_token = input.frame_input().pressed(TestAction::Enter).next();
2168 let fixed_token = input.fixed_input().pressed(TestAction::Enter).next();
2169 assert_eq!(frame_token, fixed_token);
2170 }
2171
2172 #[test]
2173 fn reusable_snapshots_preserve_data_tokens_and_capacity() {
2174 let (application, generation) = identity();
2175 let mut input = state(8);
2176 let events = [
2177 InputEvent::key(PhysicalKeyCode::KeyW, ButtonState::Pressed),
2178 InputEvent::key(PhysicalKeyCode::Enter, ButtonState::Pressed),
2179 ];
2180 assert!(
2181 input
2182 .collect_frame(&events, false, application, generation, 1)
2183 .is_ok()
2184 );
2185
2186 let expected_frame_edges = input.frame_edges.clone();
2187 let expected_fixed_edges = input.fixed_edges.clone();
2188 let mut frame = FrameInputState::empty();
2189 let mut fixed = FixedInputState::empty();
2190 input.copy_frame_snapshot_into(&mut frame);
2191 input.copy_fixed_snapshot_into(&mut fixed);
2192
2193 assert_eq!(frame.edges, expected_frame_edges);
2194 assert_eq!(fixed.edges, expected_fixed_edges);
2195 assert_eq!(input.frame_edges, expected_frame_edges);
2196 assert_eq!(input.fixed_edges, expected_fixed_edges);
2197 assert!(frame.held(TestAction::Move));
2198 assert!(frame.held(TestAction::Enter));
2199 assert!(fixed.held(TestAction::Move));
2200 assert!(fixed.held(TestAction::Enter));
2201
2202 let frame_held_capacity = frame.held.capacity();
2203 let frame_edge_capacity = frame.edges.capacity();
2204 let fixed_held_capacity = fixed.held.capacity();
2205 let fixed_edge_capacity = fixed.edges.capacity();
2206 frame.clear_reusing_storage();
2207 fixed.clear_reusing_storage();
2208 assert!(frame.held.is_empty());
2209 assert!(frame.edges.is_empty());
2210 assert!(fixed.held.is_empty());
2211 assert!(fixed.edges.is_empty());
2212 assert_eq!(frame.held.capacity(), frame_held_capacity);
2213 assert_eq!(frame.edges.capacity(), frame_edge_capacity);
2214 assert_eq!(fixed.held.capacity(), fixed_held_capacity);
2215 assert_eq!(fixed.edges.capacity(), fixed_edge_capacity);
2216
2217 input.end_frame();
2218 input.consume_fixed_delivery();
2219 assert!(
2220 input
2221 .collect_frame(
2222 &[InputEvent::key(
2223 PhysicalKeyCode::KeyW,
2224 ButtonState::Released,
2225 )],
2226 false,
2227 application,
2228 generation,
2229 2,
2230 )
2231 .is_ok()
2232 );
2233 input.copy_frame_snapshot_into(&mut frame);
2234 input.copy_fixed_snapshot_into(&mut fixed);
2235 assert_eq!(frame.edges, input.frame_edges);
2236 assert_eq!(fixed.edges, input.fixed_edges);
2237 assert_eq!(frame.held.capacity(), frame_held_capacity);
2238 assert_eq!(frame.edges.capacity(), frame_edge_capacity);
2239 assert_eq!(fixed.held.capacity(), fixed_held_capacity);
2240 assert_eq!(fixed.edges.capacity(), fixed_edge_capacity);
2241 }
2242
2243 #[test]
2244 fn using_a_token_consumes_its_occurrence_in_both_views() {
2245 let (application, generation) = identity();
2246 let mut input = state(8);
2247 assert!(
2248 input
2249 .collect_frame(
2250 &[InputEvent::key(
2251 PhysicalKeyCode::Enter,
2252 ButtonState::Pressed,
2253 )],
2254 false,
2255 application,
2256 generation,
2257 1,
2258 )
2259 .is_ok()
2260 );
2261 let edge = input.frame_input().pressed(TestAction::Enter).next();
2262 let Some(edge) = edge else {
2263 panic!("press edge should exist");
2264 };
2265
2266 assert!(input.consume_token_occurrence(edge.intent()));
2267 assert!(!input.token_is_live(edge.intent()));
2268 assert_eq!(input.frame_input().pressed(TestAction::Enter).count(), 0);
2269 assert_eq!(input.fixed_input().pressed(TestAction::Enter).count(), 0);
2270 }
2271}