1use std::sync::atomic::{AtomicUsize, Ordering};
4
5mod config;
6#[cfg(test)]
7mod tests;
8pub use config::{
9 AppliedConfig, BindingConflict, ConfigBinding, ConfigError, ConfigValidation, ControlSettings,
10 DecodedConfig, MAX_CONFIG_BYTES, MAX_CONFIG_CONFLICTS, SavedAction, decode_config,
11};
12pub mod touch;
13pub const MAX_ACTIONS: usize = 256;
14pub const MAX_BINDINGS: usize = 64;
15pub const MAX_ACTIVE_CODES: usize = 1024;
16pub const MAX_CONTEXTS: usize = 16;
17pub const MAX_CONTEXT_DEPTH: usize = 8;
18#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
19pub enum InputCode {
20 Key(u16),
21 Mouse(u8),
22 PadButton(u8),
23 PadAxis(u8),
24 Touch(u8),
25 MouseDelta(u8),
27 TouchDelta(u8),
28 Wheel(u8),
29}
30impl InputCode {
31 pub fn is_delta(self) -> bool {
32 matches!(
33 self,
34 Self::MouseDelta(_) | Self::TouchDelta(_) | Self::Wheel(_)
35 )
36 }
37 pub fn valid(self) -> bool {
38 match self {
39 Self::Key(k) => k != 0,
40 Self::Mouse(b) => (1..=5).contains(&b),
41 Self::PadButton(b) => b < 32,
42 Self::PadAxis(a) => a < 16,
43 Self::Touch(t) => t < 64,
44 Self::MouseDelta(a) | Self::Wheel(a) => a < 2,
45 Self::TouchDelta(a) => a < 16,
46 }
47 }
48}
49#[derive(Clone, Copy, Debug, PartialEq)]
50pub struct Binding {
51 pub code: InputCode,
52 pub scale: f32,
53 pub deadzone: f32,
54}
55impl Binding {
56 pub fn digital(code: InputCode) -> Self {
57 Self {
58 code,
59 scale: 1.,
60 deadzone: 0.,
61 }
62 }
63 fn valid(self) -> bool {
64 self.code.valid()
65 && self.scale.is_finite()
66 && self.deadzone.is_finite()
67 && (0. ..=0.99).contains(&self.deadzone)
68 && (!self.code.is_delta() || self.deadzone == 0.)
69 }
70}
71#[derive(Clone, Copy, Default, Debug, PartialEq)]
72pub struct Action {
73 pub value: f32,
74 pub pressed: bool,
75 pub released: bool,
76}
77#[derive(Clone, Copy, Debug, PartialEq, Eq)]
78pub enum ActionKind {
79 Axis,
80 Button,
81 Delta,
82}
83#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
115pub struct ActionHandle {
116 map_id: usize,
117 index: usize,
118}
119
120#[derive(Clone, Copy, Debug, PartialEq, Eq)]
141pub enum ActionSnapshotError {
142 TooManyHandles { count: usize },
144 OutputTooSmall { required: usize, available: usize },
146 InvalidHandle { index: usize },
148}
149impl std::fmt::Display for ActionSnapshotError {
150 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
151 write!(f, "action snapshot: {self:?}")
152 }
153}
154impl std::error::Error for ActionSnapshotError {}
155
156#[derive(Clone, Copy, Debug, PartialEq)]
185pub struct ActionDescriptor<'a> {
186 pub handle: ActionHandle,
188 pub name: Option<&'a str>,
190 pub kind: ActionKind,
192 pub context: ContextId,
194 pub context_name: &'a str,
196 pub context_active: bool,
200 pub bindings: &'a [Binding],
205}
206
207static NEXT_MAP_ID: AtomicUsize = AtomicUsize::new(1);
210
211#[derive(Clone, Copy, Debug, PartialEq, Eq)]
212pub struct ContextId(u8);
213impl ContextId {
214 pub const GLOBAL: Self = Self(0);
216}
217#[derive(Clone, Copy, Debug, PartialEq, Eq)]
218pub enum ContextMode {
219 Exclusive,
220 Passthrough,
221}
222#[derive(Clone, Copy, Debug, PartialEq, Eq)]
223pub enum InputError {
224 InvalidName,
225 DuplicateName,
226 InvalidBinding,
227 InvalidHandle,
228 ActionCapacity,
229 BindingCapacity,
230 ContextCapacity,
231 ContextDepth,
232 InvalidContext,
233 InvalidTouch,
234 TouchCapacity,
235 InvalidConfig,
236 ConfigVersion,
237 ConfigChecksum,
238}
239impl std::fmt::Display for InputError {
240 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
241 write!(f, "input: {self:?}")
242 }
243}
244impl std::error::Error for InputError {}
245fn valid_name(name: &str) -> bool {
246 !name.is_empty()
247 && name.len() <= 64
248 && name
249 .bytes()
250 .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b"_-.".contains(&b))
251}
252struct Entry {
253 name: Option<String>,
254 kind: ActionKind,
255 context: ContextId,
256 bindings: Box<[Binding]>,
257 state: Action,
258 suppressed: bool,
259}
260pub struct ActionMap {
264 map_id: usize,
265 entries: Vec<Entry>,
266 values: Vec<(InputCode, f32)>,
267 contexts: Vec<String>,
268 stack: Vec<(ContextId, ContextMode)>,
269}
270impl Default for ActionMap {
271 fn default() -> Self {
272 #[allow(deprecated)]
274 let map_id = NEXT_MAP_ID
275 .fetch_update(Ordering::Relaxed, Ordering::Relaxed, |id| id.checked_add(1))
276 .expect("action map identity space exhausted");
277 Self {
278 map_id,
279 entries: Vec::new(),
280 values: Vec::with_capacity(MAX_ACTIVE_CODES),
281 contexts: vec!["global".into()],
282 stack: Vec::with_capacity(MAX_CONTEXT_DEPTH),
283 }
284 }
285}
286impl ActionMap {
287 pub fn action(&mut self, bindings: Vec<Binding>) -> usize {
288 self.try_action(bindings)
289 .expect("valid actions within capacities")
290 }
291 pub fn try_action(&mut self, bindings: Vec<Binding>) -> Option<usize> {
292 self.insert(None, ActionKind::Axis, ContextId::GLOBAL, bindings)
293 .ok()
294 }
295 pub fn named_action(
296 &mut self,
297 name: &str,
298 kind: ActionKind,
299 context: ContextId,
300 bindings: Vec<Binding>,
301 ) -> Result<usize, InputError> {
302 if !valid_name(name) {
303 return Err(InputError::InvalidName);
304 }
305 if self.action_id(name).is_some() {
306 return Err(InputError::DuplicateName);
307 }
308 self.insert(Some(name.to_string()), kind, context, bindings)
309 }
310 pub fn named_action_handle(
323 &mut self,
324 name: &str,
325 kind: ActionKind,
326 context: ContextId,
327 bindings: Vec<Binding>,
328 ) -> Result<ActionHandle, InputError> {
329 let index = self.named_action(name, kind, context, bindings)?;
330 Ok(ActionHandle {
331 map_id: self.map_id,
332 index,
333 })
334 }
335 fn insert(
336 &mut self,
337 name: Option<String>,
338 kind: ActionKind,
339 context: ContextId,
340 bindings: Vec<Binding>,
341 ) -> Result<usize, InputError> {
342 if self.entries.len() >= MAX_ACTIONS {
343 return Err(InputError::ActionCapacity);
344 }
345 if context.0 as usize >= self.contexts.len() {
346 return Err(InputError::InvalidContext);
347 }
348 validate_bindings(kind, &bindings)?;
349 let id = self.entries.len();
350 self.entries.push(Entry {
351 name,
352 kind,
353 context,
354 bindings: bindings.into_boxed_slice(),
355 state: Action::default(),
356 suppressed: false,
357 });
358 self.recompute();
359 Ok(id)
360 }
361 pub fn action_id(&self, name: &str) -> Option<usize> {
362 self.entries
363 .iter()
364 .position(|e| e.name.as_deref() == Some(name))
365 }
366 pub fn action_handle(&self, name: &str) -> Option<ActionHandle> {
373 self.action_id(name).and_then(|id| self.handle_from_id(id))
374 }
375 pub fn handle_from_id(&self, id: usize) -> Option<ActionHandle> {
391 self.entries.get(id).map(|_| ActionHandle {
392 map_id: self.map_id,
393 index: id,
394 })
395 }
396 fn validate_handle(&self, handle: ActionHandle) -> Result<usize, InputError> {
397 if handle.map_id != self.map_id || handle.index >= self.entries.len() {
398 Err(InputError::InvalidHandle)
399 } else {
400 Ok(handle.index)
401 }
402 }
403 pub fn named_actions(&self) -> impl Iterator<Item = (usize, &str, ActionKind, ContextId)> {
404 self.entries
405 .iter()
406 .enumerate()
407 .filter_map(|(id, e)| e.name.as_deref().map(|name| (id, name, e.kind, e.context)))
408 }
409 pub fn bindings(&self, id: usize) -> Option<&[Binding]> {
410 self.entries.get(id).map(|e| e.bindings.as_ref())
411 }
412 pub fn bindings_handle(&self, handle: ActionHandle) -> Result<&[Binding], InputError> {
417 let id = self.validate_handle(handle)?;
418 Ok(self.entries[id].bindings.as_ref())
419 }
420 pub fn action_descriptor(
437 &self,
438 handle: ActionHandle,
439 ) -> Result<ActionDescriptor<'_>, InputError> {
440 let id = self.validate_handle(handle)?;
441 Ok(self.descriptor_at(id, self.active_mask()))
442 }
443 pub fn action_descriptors(
468 &self,
469 ) -> impl ExactSizeIterator<Item = ActionDescriptor<'_>> + DoubleEndedIterator + '_ {
470 let active = self.active_mask();
471 (0..self.entries.len()).map(move |id| self.descriptor_at(id, active))
472 }
473 fn descriptor_at(&self, id: usize, active: u16) -> ActionDescriptor<'_> {
474 let entry = &self.entries[id];
475 ActionDescriptor {
476 handle: ActionHandle {
477 map_id: self.map_id,
478 index: id,
479 },
480 name: entry.name.as_deref(),
481 kind: entry.kind,
482 context: entry.context,
483 context_name: &self.contexts[entry.context.0 as usize],
484 context_active: active & (1 << entry.context.0) != 0,
485 bindings: &entry.bindings,
486 }
487 }
488 pub fn create_context(&mut self, name: &str) -> Result<ContextId, InputError> {
489 if !valid_name(name) {
490 return Err(InputError::InvalidName);
491 }
492 if self.contexts.iter().any(|n| n == name) {
493 return Err(InputError::DuplicateName);
494 }
495 if self.contexts.len() >= MAX_CONTEXTS {
496 return Err(InputError::ContextCapacity);
497 }
498 let id = ContextId(self.contexts.len() as u8);
499 self.contexts.push(name.to_string());
500 Ok(id)
501 }
502 pub fn context(&self, name: &str) -> Option<ContextId> {
503 self.contexts
504 .iter()
505 .position(|n| n == name)
506 .map(|n| ContextId(n as u8))
507 }
508 pub fn push_context(&mut self, id: ContextId, mode: ContextMode) -> Result<(), InputError> {
509 if id == ContextId::GLOBAL
510 || id.0 as usize >= self.contexts.len()
511 || self.stack.iter().any(|v| v.0 == id)
512 {
513 return Err(InputError::InvalidContext);
514 }
515 if self.stack.len() >= MAX_CONTEXT_DEPTH {
516 return Err(InputError::ContextDepth);
517 }
518 let old = self.active_mask();
519 self.stack.push((id, mode));
520 self.transition(old);
521 Ok(())
522 }
523 pub fn pop_context(&mut self) -> Option<ContextId> {
524 let old = self.active_mask();
525 let id = self.stack.pop()?.0;
526 self.transition(old);
527 Some(id)
528 }
529 pub fn clear_contexts(&mut self) {
530 let old = self.active_mask();
531 self.stack.clear();
532 self.transition(old);
533 }
534 pub fn set_context(&mut self, id: Option<ContextId>) -> Result<(), InputError> {
537 if id.is_some_and(|id| id == ContextId::GLOBAL || id.0 as usize >= self.contexts.len()) {
538 return Err(InputError::InvalidContext);
539 }
540 if id.is_none() && self.stack.is_empty()
541 || self.stack.len() == 1
542 && id == Some(self.stack[0].0)
543 && self.stack[0].1 == ContextMode::Exclusive
544 {
545 return Ok(());
546 }
547 let old = self.active_mask();
548 self.stack.clear();
549 if let Some(id) = id {
550 self.stack.push((id, ContextMode::Exclusive));
551 }
552 self.transition(old);
553 Ok(())
554 }
555 fn active_mask(&self) -> u16 {
556 let mut mask = 1;
557 for &(id, mode) in self.stack.iter().rev() {
558 mask |= 1 << id.0;
559 if mode == ContextMode::Exclusive {
560 break;
561 }
562 }
563 mask
564 }
565 fn transition(&mut self, old: u16) {
566 let new = self.active_mask();
567 for entry in &mut self.entries {
568 let was = old & (1 << entry.context.0) != 0;
569 let active = new & (1 << entry.context.0) != 0;
570 if was != active {
571 entry.state.pressed = false;
574 entry.state.released = false;
575 if entry.kind == ActionKind::Delta {
576 entry.state.value = 0.;
577 }
578 if active && entry.kind == ActionKind::Button {
579 entry.suppressed = raw_value(entry, &self.values).abs() >= 0.5;
580 }
581 }
582 }
583 self.recompute();
584 }
585 pub fn rebind(&mut self, id: usize, bindings: Vec<Binding>) -> bool {
586 self.try_rebind(id, bindings).is_ok()
587 }
588 pub fn try_rebind(&mut self, id: usize, bindings: Vec<Binding>) -> Result<(), InputError> {
589 let entry = self.entries.get_mut(id).ok_or(InputError::InvalidHandle)?;
590 validate_bindings(entry.kind, &bindings)?;
591 entry.bindings = bindings.into_boxed_slice();
592 entry.state = Action::default();
593 entry.suppressed =
594 entry.kind == ActionKind::Button && raw_value(entry, &self.values).abs() >= 0.5;
595 self.recompute();
596 Ok(())
597 }
598 pub fn try_rebind_handle(
613 &mut self,
614 handle: ActionHandle,
615 bindings: Vec<Binding>,
616 ) -> Result<(), InputError> {
617 let id = self.validate_handle(handle)?;
618 self.try_rebind(id, bindings)
619 }
620 pub fn feed(&mut self, code: InputCode, value: f32) {
623 if !code.valid() {
624 return;
625 }
626 if code.is_delta() {
627 self.feed_delta(code, value);
628 return;
629 }
630 let value = if value.is_finite() {
631 value.clamp(-1., 1.)
632 } else {
633 0.
634 };
635 match self.values.binary_search_by_key(&code, |v| v.0) {
636 Ok(i) => {
637 if self.values[i].1 == value {
638 return;
639 }
640 if value == 0. {
641 self.values.remove(i);
642 } else {
643 self.values[i].1 = value;
644 }
645 }
646 Err(i) => {
647 if value == 0. || self.values.len() >= MAX_ACTIVE_CODES {
648 return;
649 }
650 self.values.insert(i, (code, value));
651 }
652 }
653 self.recompute();
654 }
655 pub fn feed_delta(&mut self, code: InputCode, value: f32) {
658 if !code.valid() || !code.is_delta() || !value.is_finite() || value == 0. {
659 return;
660 }
661 let active = self.active_mask();
662 for entry in &mut self.entries {
663 if entry.kind != ActionKind::Delta || active & (1 << entry.context.0) == 0 {
664 continue;
665 }
666 let delta = entry
667 .bindings
668 .iter()
669 .filter(|b| b.code == code)
670 .map(|b| f64::from(b.scale) * f64::from(value))
671 .sum::<f64>();
672 let was = entry.state.value.abs() > 0.000001;
673 entry.state.value = (f64::from(entry.state.value) + delta).clamp(-1e6, 1e6) as f32;
674 let down = entry.state.value.abs() > 0.000001;
675 entry.state.pressed |= down && !was;
676 entry.state.released |= !down && was;
677 }
678 }
679 fn recompute(&mut self) {
680 let active = self.active_mask();
681 for entry in &mut self.entries {
682 if entry.kind == ActionKind::Delta {
683 continue;
684 }
685 let raw = raw_value(entry, &self.values);
686 if entry.suppressed && raw.abs() < 0.5 {
687 entry.suppressed = false;
688 }
689 let mut value = if active & (1 << entry.context.0) != 0 && !entry.suppressed {
690 raw
691 } else {
692 0.
693 };
694 if entry.kind == ActionKind::Button {
695 value = if value.abs() >= 0.5 {
696 value.signum()
697 } else {
698 0.
699 };
700 }
701 let down = value.abs() > 0.001;
702 let was = entry.state.value.abs() > 0.001;
703 entry.state.pressed |= down && !was;
704 entry.state.released |= !down && was;
705 entry.state.value = value;
706 }
707 }
708 pub fn peek(&self, id: usize) -> Action {
709 self.entries.get(id).map_or(Action::default(), |e| e.state)
710 }
711 pub fn peek_handle(&self, handle: ActionHandle) -> Result<Action, InputError> {
718 let id = self.validate_handle(handle)?;
719 Ok(self.entries[id].state)
720 }
721 pub fn consume_tick(&mut self, id: usize) -> Action {
722 let Some(entry) = self.entries.get_mut(id) else {
723 return Action::default();
724 };
725 let state = entry.state;
726 entry.state.pressed = false;
727 entry.state.released = false;
728 if entry.kind == ActionKind::Delta {
729 entry.state.value = 0.;
730 }
731 state
732 }
733 pub fn consume_tick_handle(&mut self, handle: ActionHandle) -> Result<Action, InputError> {
742 let id = self.validate_handle(handle)?;
743 Ok(self.consume_tick(id))
744 }
745 pub fn peek_handles<const N: usize>(
764 &self,
765 handles: [ActionHandle; N],
766 ) -> Result<[Action; N], ActionSnapshotError> {
767 let mut output = [Action::default(); N];
768 self.peek_handles_into(&handles, &mut output)?;
769 Ok(output)
770 }
771 pub fn peek_handles_into(
791 &self,
792 handles: &[ActionHandle],
793 output: &mut [Action],
794 ) -> Result<(), ActionSnapshotError> {
795 self.validate_snapshot(handles, output.len())?;
796 for (handle, slot) in handles.iter().zip(output) {
797 *slot = self.entries[handle.index].state;
798 }
799 Ok(())
800 }
801 pub fn consume_tick_handles<const N: usize>(
849 &mut self,
850 handles: [ActionHandle; N],
851 ) -> Result<[Action; N], ActionSnapshotError> {
852 let mut output = [Action::default(); N];
853 self.consume_tick_handles_into(&handles, &mut output)?;
854 Ok(output)
855 }
856 pub fn consume_tick_handles_into(
878 &mut self,
879 handles: &[ActionHandle],
880 output: &mut [Action],
881 ) -> Result<(), ActionSnapshotError> {
882 self.peek_handles_into(handles, output)?;
883 for handle in handles {
886 self.consume_tick(handle.index);
887 }
888 Ok(())
889 }
890 fn validate_snapshot(
891 &self,
892 handles: &[ActionHandle],
893 output_len: usize,
894 ) -> Result<(), ActionSnapshotError> {
895 if handles.len() > MAX_ACTIONS {
896 return Err(ActionSnapshotError::TooManyHandles {
897 count: handles.len(),
898 });
899 }
900 if output_len < handles.len() {
901 return Err(ActionSnapshotError::OutputTooSmall {
902 required: handles.len(),
903 available: output_len,
904 });
905 }
906 for (index, &handle) in handles.iter().enumerate() {
907 self.validate_handle(handle)
908 .map_err(|_| ActionSnapshotError::InvalidHandle { index })?;
909 }
910 Ok(())
911 }
912 pub fn physical_value(&self, code: InputCode) -> f32 {
913 self.values
914 .binary_search_by_key(&code, |v| v.0)
915 .ok()
916 .map_or(0., |i| self.values[i].1)
917 }
918 pub fn active_codes(&self) -> usize {
919 self.values.len()
920 }
921 pub fn suppress_held(&mut self) {
924 for entry in &mut self.entries {
925 entry.state.pressed = false;
926 entry.state.released = false;
927 if entry.kind == ActionKind::Delta {
928 entry.state.value = 0.;
929 }
930 if entry.kind == ActionKind::Button {
931 entry.suppressed = raw_value(entry, &self.values).abs() >= 0.5;
932 }
933 }
934 self.recompute();
935 for entry in &mut self.entries {
936 entry.state.pressed = false;
937 entry.state.released = false;
938 }
939 }
940 pub fn lose_focus(&mut self) {
942 self.values.clear();
943 for e in &mut self.entries {
944 let released = e.kind != ActionKind::Delta && e.state.value.abs() > 0.001;
945 e.state = Action {
946 value: 0.,
947 pressed: false,
948 released,
949 };
950 e.suppressed = false;
951 }
952 }
953}
954#[cfg(test)]
955#[test]
956fn journey400_291_corrupt_late_index_rejects_without_input_or_output_mutation() {
957 let mut map = ActionMap::default();
958 let id = map.action(vec![Binding::digital(InputCode::Key(1))]);
959 let handle = map.handle_from_id(id).unwrap();
960 let corrupt = ActionHandle {
962 map_id: map.map_id,
963 index: usize::MAX,
964 };
965 map.feed(InputCode::Key(1), 1.);
966 let before = map.peek(id);
967 let mut output = [Action::default(); 3];
968 let expected = Err(ActionSnapshotError::InvalidHandle { index: 2 });
969 assert_eq!(
970 map.peek_handles_into(&[handle, handle, corrupt], &mut output),
971 expected
972 );
973 assert_eq!(output, [Action::default(); 3]);
974 assert_eq!(
975 map.consume_tick_handles_into(&[handle, handle, corrupt], &mut output),
976 expected
977 );
978 assert_eq!(output, [Action::default(); 3]);
979 assert_eq!(map.peek(id), before);
980}
981
982fn validate_bindings(kind: ActionKind, bindings: &[Binding]) -> Result<(), InputError> {
983 if bindings.len() > MAX_BINDINGS {
984 return Err(InputError::BindingCapacity);
985 }
986 if bindings
987 .iter()
988 .any(|b| !b.valid() || b.code.is_delta() != (kind == ActionKind::Delta))
989 {
990 return Err(InputError::InvalidBinding);
991 }
992 Ok(())
993}
994fn raw_value(entry: &Entry, values: &[(InputCode, f32)]) -> f32 {
995 entry
996 .bindings
997 .iter()
998 .map(|b| {
999 let raw = values
1000 .binary_search_by_key(&b.code, |v| v.0)
1001 .ok()
1002 .map_or(0., |i| f64::from(values[i].1));
1003 let dead = f64::from(b.deadzone);
1004 if raw.abs() <= dead {
1005 0.
1006 } else {
1007 raw.signum() * (raw.abs() - dead) / (1. - dead) * f64::from(b.scale)
1008 }
1009 })
1010 .sum::<f64>()
1011 .clamp(-1., 1.) as f32
1012}
1013
1014#[cfg(test)]
1015mod journey200_051 {
1016 use super::*;
1017
1018 #[test]
1019 fn descriptors_borrow_all_metadata_and_preserve_binding_order() {
1020 let mut map = ActionMap::default();
1021 assert_eq!(map.action_descriptors().len(), 0);
1022 assert_eq!(map.action_descriptors().next_back(), None);
1023 let game = map.create_context("game").unwrap();
1024 let axis_bindings = vec![
1025 Binding {
1026 code: InputCode::PadAxis(0),
1027 scale: -2.,
1028 deadzone: 0.25,
1029 },
1030 Binding::digital(InputCode::Key(65)),
1031 Binding::digital(InputCode::Key(65)),
1032 Binding {
1033 code: InputCode::Touch(63),
1034 scale: 0.,
1035 deadzone: 0.,
1036 },
1037 ];
1038 let legacy = map.action(axis_bindings.clone());
1039 let jump = map
1040 .named_action_handle(
1041 "jump",
1042 ActionKind::Button,
1043 game,
1044 vec![
1045 Binding::digital(InputCode::Mouse(1)),
1046 Binding::digital(InputCode::PadButton(0)),
1047 ],
1048 )
1049 .unwrap();
1050 let look = map
1051 .named_action_handle(
1052 "look",
1053 ActionKind::Delta,
1054 ContextId::GLOBAL,
1055 vec![
1056 Binding::digital(InputCode::MouseDelta(0)),
1057 Binding::digital(InputCode::TouchDelta(1)),
1058 Binding::digital(InputCode::Wheel(1)),
1059 ],
1060 )
1061 .unwrap();
1062 let unbound = map
1063 .named_action_handle("unbound", ActionKind::Button, ContextId::GLOBAL, vec![])
1064 .unwrap();
1065
1066 let mut descriptors = map.action_descriptors();
1067 assert_eq!(descriptors.len(), 4);
1068 let axis = descriptors.next().unwrap();
1069 assert_eq!(axis.handle, map.handle_from_id(legacy).unwrap());
1070 assert_eq!(axis.name, None);
1071 assert_eq!(axis.kind, ActionKind::Axis);
1072 assert_eq!(axis.context, ContextId::GLOBAL);
1073 assert_eq!(axis.context_name, "global");
1074 assert!(axis.context_active);
1075 assert_eq!(axis.bindings, axis_bindings);
1076 assert!(std::ptr::eq(axis.bindings, map.bindings(legacy).unwrap()));
1077
1078 let last = descriptors.next_back().unwrap();
1079 assert_eq!(last.handle, unbound);
1080 assert!(last.bindings.is_empty());
1081 assert!(last.context_active);
1082 assert_eq!(descriptors.len(), 2);
1083 let button = descriptors.next().unwrap();
1084 assert_eq!(button, map.action_descriptor(jump).unwrap());
1085 assert_eq!(button.name, Some("jump"));
1086 assert_eq!(button.kind, ActionKind::Button);
1087 assert_eq!(button.context, game);
1088 assert_eq!(button.context_name, "game");
1089 assert!(!button.context_active);
1090 assert!(std::ptr::eq(
1091 button.bindings,
1092 map.bindings_handle(jump).unwrap()
1093 ));
1094 let delta = descriptors.next().unwrap();
1095 assert_eq!(delta.handle, look);
1096 assert_eq!(delta.kind, ActionKind::Delta);
1097 assert_eq!(delta.bindings, map.bindings_handle(look).unwrap());
1098 assert_eq!(descriptors.len(), 0);
1099 assert_eq!(descriptors.next(), None);
1100 }
1101
1102 #[test]
1103 fn descriptor_lookup_rejects_foreign_stale_and_out_of_bounds_handles() {
1104 let mut original = ActionMap::default();
1105 let original_id = original.action(vec![Binding::digital(InputCode::Key(32))]);
1106 let old = original.action_descriptors().next().unwrap().handle;
1107 let mut replacement = ActionMap::default();
1108 let replacement_id = replacement.action(vec![Binding::digital(InputCode::Key(32))]);
1109 assert_eq!(original_id, replacement_id);
1110 let current = replacement.action_descriptors().next().unwrap().handle;
1111 replacement.feed(InputCode::Key(32), 1.);
1112 assert_eq!(
1113 replacement.action_descriptor(old),
1114 Err(InputError::InvalidHandle)
1115 );
1116 assert_eq!(
1117 original.action_descriptor(current),
1118 Err(InputError::InvalidHandle)
1119 );
1120 original = replacement;
1121 assert_eq!(
1122 original.action_descriptor(old),
1123 Err(InputError::InvalidHandle)
1124 );
1125 let mut moved = Box::new(original);
1126 moved.action(vec![]);
1127 assert_eq!(moved.action_descriptor(current).unwrap().handle, current);
1128 for index in [2, usize::MAX] {
1129 let invalid = ActionHandle {
1130 map_id: moved.map_id,
1131 index,
1132 };
1133 assert_eq!(
1134 moved.action_descriptor(invalid),
1135 Err(InputError::InvalidHandle)
1136 );
1137 }
1138 assert!(moved.consume_tick_handle(current).unwrap().pressed);
1139 }
1140
1141 #[test]
1142 fn descriptors_follow_context_stack_without_changing_held_suppression() {
1143 let mut map = ActionMap::default();
1144 let game = map.create_context("game").unwrap();
1145 let hud = map.create_context("hud").unwrap();
1146 let menu = map.create_context("menu").unwrap();
1147 let tooltip = map.create_context("tooltip").unwrap();
1148 for (name, context) in [
1149 ("pause", ContextId::GLOBAL),
1150 ("jump", game),
1151 ("hint", hud),
1152 ("accept", menu),
1153 ("dismiss", tooltip),
1154 ] {
1155 map.named_action_handle(
1156 name,
1157 ActionKind::Button,
1158 context,
1159 vec![Binding::digital(InputCode::Key(32))],
1160 )
1161 .unwrap();
1162 }
1163 let active_names = |map: &ActionMap| {
1164 map.action_descriptors()
1165 .filter(|d| d.context_active)
1166 .map(|d| d.name.unwrap().to_owned())
1167 .collect::<Vec<_>>()
1168 };
1169 let jump = map.action_handle("jump").unwrap();
1170 assert_eq!(active_names(&map), ["pause"]);
1171 map.feed(InputCode::Key(32), 1.);
1172 map.push_context(game, ContextMode::Exclusive).unwrap();
1173 assert_eq!(active_names(&map), ["pause", "jump"]);
1174 assert!(map.action_descriptor(jump).unwrap().context_active);
1175 assert_eq!(map.consume_tick_handle(jump).unwrap(), Action::default());
1176 map.push_context(hud, ContextMode::Passthrough).unwrap();
1177 assert_eq!(active_names(&map), ["pause", "jump", "hint"]);
1178 map.push_context(menu, ContextMode::Exclusive).unwrap();
1179 assert_eq!(active_names(&map), ["pause", "accept"]);
1180 map.push_context(tooltip, ContextMode::Passthrough).unwrap();
1181 assert_eq!(active_names(&map), ["pause", "accept", "dismiss"]);
1182 map.pop_context();
1183 map.pop_context();
1184 assert_eq!(active_names(&map), ["pause", "jump", "hint"]);
1185 assert_eq!(map.consume_tick_handle(jump).unwrap(), Action::default());
1186 map.feed(InputCode::Key(32), 0.);
1187 map.feed(InputCode::Key(32), 1.);
1188 let pending = map.peek_handle(jump).unwrap();
1189 assert!(pending.pressed);
1190 assert_eq!(active_names(&map), ["pause", "jump", "hint"]);
1191 assert_eq!(map.consume_tick_handle(jump).unwrap(), pending);
1192 map.suppress_held();
1193 assert_eq!(active_names(&map), ["pause", "jump", "hint"]);
1194 assert_eq!(map.consume_tick_handle(jump).unwrap(), Action::default());
1195 map.lose_focus();
1196 assert_eq!(active_names(&map), ["pause", "jump", "hint"]);
1197 map.clear_contexts();
1198 assert_eq!(active_names(&map), ["pause"]);
1199 map.set_context(Some(menu)).unwrap();
1200 assert_eq!(active_names(&map), ["pause", "accept"]);
1201 }
1202
1203 #[test]
1204 fn hint_reads_leave_zero_tick_taps_and_accumulated_motion_for_one_tick() {
1205 let mut map = ActionMap::default();
1206 let jump = map
1207 .named_action_handle(
1208 "jump",
1209 ActionKind::Button,
1210 ContextId::GLOBAL,
1211 vec![Binding::digital(InputCode::Key(32))],
1212 )
1213 .unwrap();
1214 let look = map
1215 .named_action_handle(
1216 "look",
1217 ActionKind::Delta,
1218 ContextId::GLOBAL,
1219 vec![Binding::digital(InputCode::MouseDelta(0))],
1220 )
1221 .unwrap();
1222 map.feed(InputCode::Key(32), 1.);
1223 map.feed(InputCode::Key(32), 0.);
1224 for motion in [3., 5.] {
1225 map.feed_delta(InputCode::MouseDelta(0), motion);
1226 for hint in map.action_descriptors() {
1227 assert_eq!(map.action_descriptor(hint.handle).unwrap(), hint);
1228 }
1229 }
1230 let tap = Action {
1231 value: 0.,
1232 pressed: true,
1233 released: true,
1234 };
1235 assert_eq!(map.consume_tick_handle(jump).unwrap(), tap);
1236 let delta = map.consume_tick_handle(look).unwrap();
1237 assert_eq!(delta.value, 8.);
1238 assert!(delta.pressed);
1239 assert_eq!(map.consume_tick_handle(jump).unwrap(), Action::default());
1240 assert_eq!(map.consume_tick_handle(look).unwrap(), Action::default());
1241 }
1242
1243 #[test]
1244 fn descriptors_track_rebinding_and_config_without_changing_identity() {
1245 let mut map = ActionMap::default();
1246 let original = Binding::digital(InputCode::Key(32));
1247 let jump = map
1248 .named_action_handle(
1249 "jump",
1250 ActionKind::Button,
1251 ContextId::GLOBAL,
1252 vec![original],
1253 )
1254 .unwrap();
1255 let saved = map.encode_config(ControlSettings::default()).unwrap();
1256 let remapped = [
1257 Binding::digital(InputCode::PadButton(0)),
1258 Binding::digital(InputCode::Key(74)),
1259 ];
1260 map.try_rebind_handle(jump, remapped.to_vec()).unwrap();
1261 assert_eq!(map.action_descriptor(jump).unwrap().bindings, remapped);
1262 map.feed(InputCode::Key(74), 1.);
1263 let pending = map.peek_handle(jump).unwrap();
1264 for (bindings, error) in [
1265 (
1266 vec![Binding::digital(InputCode::Key(0))],
1267 InputError::InvalidBinding,
1268 ),
1269 (
1270 vec![Binding {
1271 scale: f32::NAN,
1272 ..original
1273 }],
1274 InputError::InvalidBinding,
1275 ),
1276 (
1277 vec![Binding::digital(InputCode::MouseDelta(0))],
1278 InputError::InvalidBinding,
1279 ),
1280 (
1281 vec![original; MAX_BINDINGS + 1],
1282 InputError::BindingCapacity,
1283 ),
1284 ] {
1285 assert_eq!(map.try_rebind_handle(jump, bindings), Err(error));
1286 let hint = map.action_descriptor(jump).unwrap();
1287 assert_eq!(hint.handle, jump);
1288 assert_eq!(hint.bindings, remapped);
1289 assert_eq!(map.peek_handle(jump).unwrap(), pending);
1290 }
1291 assert!(map.apply_config(b"invalid").is_err());
1292 assert_eq!(map.action_descriptor(jump).unwrap().bindings, remapped);
1293 assert_eq!(map.peek_handle(jump).unwrap(), pending);
1294 map.feed(InputCode::Key(32), 1.);
1295 map.apply_config(&saved).unwrap();
1296 assert_eq!(map.action_handle("jump"), Some(jump));
1297 assert_eq!(map.action_descriptor(jump).unwrap().bindings, &[original]);
1298 assert_eq!(map.consume_tick_handle(jump).unwrap(), Action::default());
1299 map.feed(InputCode::Key(32), 0.);
1300 map.feed(InputCode::Key(32), 1.);
1301 assert!(map.action_descriptor(jump).unwrap().context_active);
1302 assert!(map.consume_tick_handle(jump).unwrap().pressed);
1303 map.try_rebind_handle(jump, vec![]).unwrap();
1304 assert!(map.action_descriptor(jump).unwrap().bindings.is_empty());
1305 }
1306
1307 #[test]
1308 fn enumeration_observes_existing_action_binding_and_context_bounds() {
1309 let mut map = ActionMap::default();
1310 let mut context = ContextId::GLOBAL;
1311 for i in 1..MAX_CONTEXTS {
1312 context = map.create_context(&format!("context_{i}")).unwrap();
1313 }
1314 let bindings = vec![Binding::digital(InputCode::Key(32)); MAX_BINDINGS];
1315 for i in 0..MAX_ACTIONS {
1316 map.named_action_handle(
1317 &format!("action_{i}"),
1318 ActionKind::Button,
1319 context,
1320 bindings.clone(),
1321 )
1322 .unwrap();
1323 }
1324 assert_eq!(
1325 map.named_action_handle("overflow", ActionKind::Button, context, vec![]),
1326 Err(InputError::ActionCapacity)
1327 );
1328 assert_eq!(map.action_descriptors().len(), MAX_ACTIONS);
1329 assert!(map.action_descriptors().all(|d| !d.context_active));
1330 map.set_context(Some(context)).unwrap();
1331 for (i, descriptor) in map.action_descriptors().enumerate() {
1332 assert_eq!(descriptor.name, Some(format!("action_{i}").as_str()));
1333 assert_eq!(descriptor.handle, map.handle_from_id(i).unwrap());
1334 assert!(descriptor.context_active);
1335 assert_eq!(descriptor.bindings.len(), MAX_BINDINGS);
1336 assert_eq!(descriptor.bindings, bindings);
1337 }
1338 }
1339}