leafwing_input_manager/
input_map.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
//! This module contains [`InputMap`] and its supporting methods and impls.

use std::fmt::Debug;
use std::hash::Hash;

#[cfg(feature = "asset")]
use bevy::asset::Asset;
use bevy::prelude::{Component, Deref, DerefMut, Gamepad, Gamepads, Reflect, Resource};
use bevy::utils::HashMap;
use bevy::{log::error, prelude::ReflectComponent};
use bevy::{
    math::{Vec2, Vec3},
    prelude::ReflectResource,
};
use itertools::Itertools;
use serde::{Deserialize, Serialize};

use crate::clashing_inputs::ClashStrategy;
use crate::prelude::updating::CentralInputStore;
use crate::prelude::UserInputWrapper;
use crate::user_input::{Axislike, Buttonlike, DualAxislike, TripleAxislike};
use crate::{Actionlike, InputControlKind};

#[cfg(feature = "gamepad")]
use crate::user_input::gamepad::find_gamepad;

#[cfg(not(feature = "gamepad"))]
fn find_gamepad(_gamepads: &Gamepads) -> Gamepad {
    Gamepad::new(0)
}

/// A Multi-Map that allows you to map actions to multiple [`UserInputs`](crate::user_input::UserInput)s,
/// whether they are [`Buttonlike`], [`Axislike`] or [`DualAxislike`].
///
/// When inserting a binding, the [`InputControlKind`] of the action variant must match that of the input type.
/// Use [`InputMap::insert`] to insert buttonlike inputs,
/// [`InputMap::insert_axis`] to insert axislike inputs,
/// and [`InputMap::insert_dual_axis`] to insert dual-axislike inputs.
///
/// # Many-to-One Mapping
///
/// You can associate multiple [`Buttonlike`]s (e.g., keyboard keys, mouse buttons, gamepad buttons)
/// with a single action, simplifying handling complex input combinations for the same action.
/// Duplicate associations are ignored.
///
/// # One-to-Many Mapping
///
/// A single [`Buttonlike`] can be mapped to multiple actions simultaneously.
/// This allows flexibility in defining alternative ways to trigger an action.
///
/// # Clash Resolution
///
/// By default, the [`InputMap`] prioritizes larger [`Buttonlike`] combinations to trigger actions.
/// This means if two actions share some inputs, and one action requires all the inputs
/// of the other plus additional ones; only the larger combination will be registered.
///
/// This avoids unintended actions from being triggered by more specific input combinations.
/// For example, pressing both `S` and `Ctrl + S` in your text editor app
/// would only save your file (the larger combination), and not enter the letter `s`.
///
/// This behavior can be customized using the [`ClashStrategy`] resource.
///
/// # Examples
///
/// ```rust
/// use bevy::prelude::*;
/// use leafwing_input_manager::prelude::*;
///
/// // Define your actions.
/// #[derive(Actionlike, Debug, Clone, Copy, PartialEq, Eq, Hash, Reflect)]
/// enum Action {
///     #[actionlike(DualAxis)]
///     Move,
///     Run,
///     Jump,
/// }
///
/// // Create an InputMap from an iterable,
/// // allowing for multiple input types per action.
/// let mut input_map = InputMap::new([
///     // Multiple inputs can be bound to the same action.
///     // Note that the type of your iterators must be homogeneous.
///     (Action::Run, KeyCode::ShiftLeft),
///     (Action::Run, KeyCode::ShiftRight),
///     // Note that duplicate associations are ignored.
///     (Action::Run, KeyCode::ShiftRight),
///     (Action::Jump, KeyCode::Space),
/// ])
/// // Associate actions with other input types.
/// .with_dual_axis(Action::Move, KeyboardVirtualDPad::WASD)
/// .with_dual_axis(Action::Move, GamepadStick::LEFT)
/// // Associate an action with multiple inputs at once.
/// .with_one_to_many(Action::Jump, [KeyCode::KeyJ, KeyCode::KeyU]);
///
/// // You can also use methods like a normal MultiMap.
/// input_map.insert(Action::Jump, KeyCode::KeyM);
///
/// // Remove all bindings to a specific action.
/// input_map.clear_action(&Action::Jump);
///
/// // Remove all bindings.
/// input_map.clear();
/// ```
#[derive(Resource, Component, Debug, Clone, PartialEq, Eq, Reflect, Serialize, Deserialize)]
#[cfg_attr(feature = "asset", derive(Asset))]
#[reflect(Resource, Component)]
pub struct InputMap<A: Actionlike> {
    /// The underlying map that stores action-input mappings for [`Buttonlike`] actions.
    buttonlike_map: HashMap<A, Vec<Box<dyn Buttonlike>>>,

    /// The underlying map that stores action-input mappings for [`Axislike`] actions.
    axislike_map: HashMap<A, Vec<Box<dyn Axislike>>>,

    /// The underlying map that stores action-input mappings for [`DualAxislike`] actions.
    dual_axislike_map: HashMap<A, Vec<Box<dyn DualAxislike>>>,

    /// The underlying map that stores action-input mappings for [`TripleAxislike`] actions.
    triple_axislike_map: HashMap<A, Vec<Box<dyn TripleAxislike>>>,

    /// The specified [`Gamepad`] from which this map exclusively accepts input.
    associated_gamepad: Option<Gamepad>,
}

impl<A: Actionlike> Default for InputMap<A> {
    fn default() -> Self {
        InputMap {
            buttonlike_map: HashMap::default(),
            axislike_map: HashMap::default(),
            dual_axislike_map: HashMap::default(),
            triple_axislike_map: HashMap::default(),
            associated_gamepad: None,
        }
    }
}

// Constructors
impl<A: Actionlike> InputMap<A> {
    /// Creates an [`InputMap`] from an iterator over [`Buttonlike`] action-input bindings.
    /// Note that all elements within the iterator must be of the same type (homogeneous).
    ///
    /// This method ensures idempotence, meaning that adding the same input
    /// for the same action multiple times will only result in a single binding being created.
    #[inline(always)]
    pub fn new(bindings: impl IntoIterator<Item = (A, impl Buttonlike)>) -> Self {
        bindings
            .into_iter()
            .fold(Self::default(), |map, (action, input)| {
                map.with(action, input)
            })
    }

    /// Associates an `action` with a specific [`Buttonlike`] `input`.
    /// Multiple inputs can be bound to the same action.
    ///
    /// This method ensures idempotence, meaning that adding the same input
    /// for the same action multiple times will only result in a single binding being created.
    #[inline(always)]
    pub fn with(mut self, action: A, button: impl Buttonlike) -> Self {
        self.insert(action, button);
        self
    }

    /// Associates an `action` with a specific [`Axislike`] `input`.
    /// Multiple inputs can be bound to the same action.
    ///
    /// This method ensures idempotence, meaning that adding the same input
    /// for the same action multiple times will only result in a single binding being created.
    #[inline(always)]
    pub fn with_axis(mut self, action: A, axis: impl Axislike) -> Self {
        self.insert_axis(action, axis);
        self
    }

    /// Associates an `action` with a specific [`DualAxislike`] `input`.
    /// Multiple inputs can be bound to the same action.
    ///
    /// This method ensures idempotence, meaning that adding the same input
    /// for the same action multiple times will only result in a single binding being created.
    #[inline(always)]
    pub fn with_dual_axis(mut self, action: A, dual_axis: impl DualAxislike) -> Self {
        self.insert_dual_axis(action, dual_axis);
        self
    }

    /// Associates an `action` with a specific [`TripleAxislike`] `input`.
    /// Multiple inputs can be bound to the same action.
    ///
    /// This method ensures idempotence, meaning that adding the same input
    /// for the same action multiple times will only result in a single binding being created.
    #[inline(always)]
    pub fn with_triple_axis(mut self, action: A, triple_axis: impl TripleAxislike) -> Self {
        self.insert_triple_axis(action, triple_axis);
        self
    }

    /// Associates an `action` with multiple [`Buttonlike`] `inputs` provided by an iterator.
    /// Note that all elements within the iterator must be of the same type (homogeneous).
    ///
    /// This method ensures idempotence, meaning that adding the same input
    /// for the same action multiple times will only result in a single binding being created.
    #[inline(always)]
    pub fn with_one_to_many(
        mut self,
        action: A,
        inputs: impl IntoIterator<Item = impl Buttonlike>,
    ) -> Self {
        self.insert_one_to_many(action, inputs);
        self
    }

    /// Adds multiple action-input bindings provided by an iterator.
    /// Note that all elements within the iterator must be of the same type (homogeneous).
    ///
    /// This method ensures idempotence, meaning that adding the same input
    /// for the same action multiple times will only result in a single binding being created.
    #[inline(always)]
    pub fn with_multiple(
        mut self,
        bindings: impl IntoIterator<Item = (A, impl Buttonlike)>,
    ) -> Self {
        self.insert_multiple(bindings);
        self
    }
}

#[inline(always)]
fn insert_unique<K, V>(map: &mut HashMap<K, Vec<V>>, key: &K, value: V)
where
    K: Clone + Eq + Hash,
    V: PartialEq,
{
    if let Some(list) = map.get_mut(key) {
        if !list.contains(&value) {
            list.push(value);
        }
    } else {
        map.insert(key.clone(), vec![value]);
    }
}

// Insertion
impl<A: Actionlike> InputMap<A> {
    /// Inserts a binding between an `action` and a specific [`Buttonlike`] `input`.
    /// Multiple inputs can be bound to the same action.
    ///
    /// This method ensures idempotence, meaning that adding the same input
    /// for the same action multiple times will only result in a single binding being created.
    #[inline(always)]
    #[track_caller]
    pub fn insert(&mut self, action: A, button: impl Buttonlike) -> &mut Self {
        debug_assert!(
            action.input_control_kind() == InputControlKind::Button,
            "Cannot map a Buttonlike input for action {:?} of kind {:?}",
            action,
            action.input_control_kind()
        );

        if action.input_control_kind() != InputControlKind::Button {
            error!(
                "Cannot map a Buttonlike input for action {:?} of kind {:?}",
                action,
                action.input_control_kind()
            );

            return self;
        }

        insert_unique(&mut self.buttonlike_map, &action, Box::new(button));
        self
    }

    /// Inserts a binding between an `action` and a specific [`Axislike`] `input`.
    /// Multiple inputs can be bound to the same action.
    ///
    /// This method ensures idempotence, meaning that adding the same input
    /// for the same action multiple times will only result in a single binding being created.
    #[inline(always)]
    #[track_caller]
    pub fn insert_axis(&mut self, action: A, axis: impl Axislike) -> &mut Self {
        debug_assert!(
            action.input_control_kind() == InputControlKind::Axis,
            "Cannot map an Axislike input for action {:?} of kind {:?}",
            action,
            action.input_control_kind()
        );

        if action.input_control_kind() != InputControlKind::Axis {
            error!(
                "Cannot map an Axislike input for action {:?} of kind {:?}",
                action,
                action.input_control_kind()
            );

            return self;
        }

        insert_unique(&mut self.axislike_map, &action, Box::new(axis));
        self
    }

    /// Inserts a binding between an `action` and a specific [`DualAxislike`] `input`.
    /// Multiple inputs can be bound to the same action.
    ///
    /// This method ensures idempotence, meaning that adding the same input
    /// for the same action multiple times will only result in a single binding being created.
    #[inline(always)]
    #[track_caller]
    pub fn insert_dual_axis(&mut self, action: A, dual_axis: impl DualAxislike) -> &mut Self {
        debug_assert!(
            action.input_control_kind() == InputControlKind::DualAxis,
            "Cannot map a DualAxislike input for action {:?} of kind {:?}",
            action,
            action.input_control_kind()
        );

        if action.input_control_kind() != InputControlKind::DualAxis {
            error!(
                "Cannot map a DualAxislike input for action {:?} of kind {:?}",
                action,
                action.input_control_kind()
            );

            return self;
        }

        insert_unique(&mut self.dual_axislike_map, &action, Box::new(dual_axis));
        self
    }

    /// Inserts a binding between an `action` and a specific [`TripleAxislike`] `input`.
    /// Multiple inputs can be bound to the same action.
    ///
    /// This method ensures idempotence, meaning that adding the same input
    /// for the same action multiple times will only result in a single binding being created.
    #[inline(always)]
    #[track_caller]
    pub fn insert_triple_axis(&mut self, action: A, triple_axis: impl TripleAxislike) -> &mut Self {
        debug_assert!(
            action.input_control_kind() == InputControlKind::TripleAxis,
            "Cannot map a TripleAxislike input for action {:?} of kind {:?}",
            action,
            action.input_control_kind()
        );

        if action.input_control_kind() != InputControlKind::TripleAxis {
            error!(
                "Cannot map a TripleAxislike input for action {:?} of kind {:?}",
                action,
                action.input_control_kind()
            );

            return self;
        }

        let boxed = Box::new(triple_axis);
        insert_unique(&mut self.triple_axislike_map, &action, boxed);
        self
    }

    /// Inserts bindings between the same `action` and multiple [`Buttonlike`] `inputs` provided by an iterator.
    /// Note that all elements within the iterator must be of the same type (homogeneous).
    ///
    /// To insert a chord, such as Control + A, use a [`ButtonlikeChord`](crate::user_input::ButtonlikeChord).
    ///
    /// This method ensures idempotence, meaning that adding the same input
    /// for the same action multiple times will only result in a single binding being created.
    #[inline(always)]
    pub fn insert_one_to_many(
        &mut self,
        action: A,
        inputs: impl IntoIterator<Item = impl Buttonlike>,
    ) -> &mut Self {
        let inputs = inputs
            .into_iter()
            .map(|input| Box::new(input) as Box<dyn Buttonlike>);
        if let Some(bindings) = self.buttonlike_map.get_mut(&action) {
            for input in inputs {
                if !bindings.contains(&input) {
                    bindings.push(input);
                }
            }
        } else {
            self.buttonlike_map
                .insert(action, inputs.unique().collect());
        }
        self
    }

    /// Inserts multiple action-input [`Buttonlike`] bindings provided by an iterator.
    /// Note that all elements within the iterator must be of the same type (homogeneous).
    ///
    /// This method ensures idempotence, meaning that adding the same input
    /// for the same action multiple times will only result in a single binding being created.
    #[inline(always)]
    pub fn insert_multiple(
        &mut self,
        bindings: impl IntoIterator<Item = (A, impl Buttonlike)>,
    ) -> &mut Self {
        for (action, input) in bindings.into_iter() {
            self.insert(action, input);
        }
        self
    }

    /// Merges the provided [`InputMap`] into this `map`, combining their bindings,
    /// avoiding duplicates.
    ///
    /// If the associated gamepads do not match, the association will be removed.
    pub fn merge(&mut self, other: &InputMap<A>) -> &mut Self {
        if self.associated_gamepad != other.associated_gamepad {
            self.clear_gamepad();
        }

        for (other_action, other_inputs) in other.iter_buttonlike() {
            for other_input in other_inputs.iter().cloned() {
                insert_unique(&mut self.buttonlike_map, other_action, other_input);
            }
        }

        for (other_action, other_inputs) in other.iter_axislike() {
            for other_input in other_inputs.iter().cloned() {
                insert_unique(&mut self.axislike_map, other_action, other_input);
            }
        }

        for (other_action, other_inputs) in other.iter_dual_axislike() {
            for other_input in other_inputs.iter().cloned() {
                insert_unique(&mut self.dual_axislike_map, other_action, other_input);
            }
        }

        for (other_action, other_inputs) in other.iter_triple_axislike() {
            for other_input in other_inputs.iter().cloned() {
                insert_unique(&mut self.triple_axislike_map, other_action, other_input);
            }
        }

        self
    }
}

// Configuration
impl<A: Actionlike> InputMap<A> {
    /// Fetches the [`Gamepad`] associated with the entity controlled by this input map.
    ///
    /// If this is [`None`], input from any connected gamepad will be used.
    #[must_use]
    #[inline]
    pub const fn gamepad(&self) -> Option<Gamepad> {
        self.associated_gamepad
    }

    /// Assigns a particular [`Gamepad`] to the entity controlled by this input map.
    ///
    /// Use this when an [`InputMap`] should exclusively accept input
    /// from a particular gamepad.
    ///
    /// If this is not called, input from any connected gamepad will be used.
    /// The first matching non-zero input will be accepted,
    /// as determined by gamepad registration order.
    ///
    /// Because of this robust fallback behavior,
    /// this method can typically be ignored when writing single-player games.
    #[inline]
    pub fn with_gamepad(mut self, gamepad: Gamepad) -> Self {
        self.set_gamepad(gamepad);
        self
    }

    /// Assigns a particular [`Gamepad`] to the entity controlled by this input map.
    ///
    /// Use this when an [`InputMap`] should exclusively accept input
    /// from a particular gamepad.
    ///
    /// If this is not called, input from any connected gamepad will be used.
    /// The first matching non-zero input will be accepted,
    /// as determined by gamepad registration order.
    ///
    /// Because of this robust fallback behavior,
    /// this method can typically be ignored when writing single-player games.
    #[inline]
    pub fn set_gamepad(&mut self, gamepad: Gamepad) -> &mut Self {
        self.associated_gamepad = Some(gamepad);
        self
    }

    /// Clears any [`Gamepad`] associated with the entity controlled by this input map.
    #[inline]
    pub fn clear_gamepad(&mut self) -> &mut Self {
        self.associated_gamepad = None;
        self
    }
}

// Check whether actions are pressed
impl<A: Actionlike> InputMap<A> {
    /// Checks if the `action` are currently pressed by any of the associated [`Buttonlike`]s.
    ///
    /// Accounts for clashing inputs according to the [`ClashStrategy`] and remove conflicting actions.
    #[must_use]
    pub fn pressed(
        &self,
        action: &A,
        input_store: &CentralInputStore,
        clash_strategy: ClashStrategy,
    ) -> bool {
        let processed_actions =
            self.process_actions(&Gamepads::default(), input_store, clash_strategy);

        let Some(updated_value) = processed_actions.get(action) else {
            return false;
        };

        match updated_value {
            UpdatedValue::Button(state) => *state,
            _ => false,
        }
    }

    /// Determines the correct state for each action according to provided [`CentralInputStore`].
    ///
    /// This method uses the input bindings for each action to determine how to parse the input data,
    /// and generates corresponding [`ButtonData`](crate::action_state::ButtonData),
    /// [`AxisData`](crate::action_state::AxisData) and [`DualAxisData`](crate::action_state::DualAxisData).
    ///
    /// For [`Buttonlike`] actions, this accounts for clashing inputs according to the [`ClashStrategy`] and removes conflicting actions.
    ///
    /// [`Buttonlike`] inputs will be pressed if any of the associated inputs are pressed.
    /// [`Axislike`] and [`DualAxislike`] inputs will be the sum of all associated inputs.
    #[must_use]
    pub fn process_actions(
        &self,
        gamepads: &Gamepads,
        input_store: &CentralInputStore,
        clash_strategy: ClashStrategy,
    ) -> UpdatedActions<A> {
        let mut updated_actions = UpdatedActions::default();
        let gamepad = self.associated_gamepad.unwrap_or(find_gamepad(gamepads));

        // Generate the base action data for each action
        for (action, _input_bindings) in self.iter_buttonlike() {
            let mut final_state = false;
            for binding in _input_bindings {
                if binding.pressed(input_store, gamepad) {
                    final_state = true;
                    break;
                }
            }

            updated_actions.insert(action.clone(), UpdatedValue::Button(final_state));
        }

        for (action, _input_bindings) in self.iter_axislike() {
            let mut final_value = 0.0;
            for binding in _input_bindings {
                final_value += binding.value(input_store, gamepad);
            }

            updated_actions.insert(action.clone(), UpdatedValue::Axis(final_value));
        }

        for (action, _input_bindings) in self.iter_dual_axislike() {
            let mut final_value = Vec2::ZERO;
            for binding in _input_bindings {
                final_value += binding.axis_pair(input_store, gamepad);
            }

            updated_actions.insert(action.clone(), UpdatedValue::DualAxis(final_value));
        }

        for (action, _input_bindings) in self.iter_triple_axislike() {
            let mut final_value = Vec3::ZERO;
            for binding in _input_bindings {
                final_value += binding.axis_triple(input_store, gamepad);
            }

            updated_actions.insert(action.clone(), UpdatedValue::TripleAxis(final_value));
        }

        // Handle clashing inputs, possibly removing some pressed actions from the list
        self.handle_clashes(&mut updated_actions, input_store, clash_strategy, gamepad);

        updated_actions
    }
}

/// The output returned by [`InputMap::process_actions`],
/// used by [`ActionState::update`](crate::action_state::ActionState) to update the state of each action.
#[derive(Debug, Clone, PartialEq, Deref, DerefMut)]
pub struct UpdatedActions<A: Actionlike>(pub HashMap<A, UpdatedValue>);

impl<A: Actionlike> UpdatedActions<A> {
    /// Returns `true` if the action is both buttonlike and pressed.
    pub fn pressed(&self, action: &A) -> bool {
        match self.0.get(action) {
            Some(UpdatedValue::Button(state)) => *state,
            _ => false,
        }
    }
}

/// An enum representing the updated value of an action.
///
/// Used in [`UpdatedActions`] to store the updated state of each action.
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum UpdatedValue {
    /// A buttonlike action that was pressed or released.
    Button(bool),
    /// An axislike action that was updated.
    Axis(f32),
    /// A dual-axislike action that was updated.
    DualAxis(Vec2),
    /// A triple-axislike action that was updated.
    TripleAxis(Vec3),
}

impl<A: Actionlike> Default for UpdatedActions<A> {
    fn default() -> Self {
        Self(HashMap::default())
    }
}

// Utilities
impl<A: Actionlike> InputMap<A> {
    /// Returns an iterator over all registered [`Buttonlike`] actions with their input bindings.
    pub fn iter_buttonlike(&self) -> impl Iterator<Item = (&A, &Vec<Box<dyn Buttonlike>>)> {
        self.buttonlike_map.iter()
    }

    /// Returns an iterator over all registered [`Axislike`] actions with their input bindings.
    pub fn iter_axislike(&self) -> impl Iterator<Item = (&A, &Vec<Box<dyn Axislike>>)> {
        self.axislike_map.iter()
    }

    /// Returns an iterator over all registered [`DualAxislike`] actions with their input bindings.
    pub fn iter_dual_axislike(&self) -> impl Iterator<Item = (&A, &Vec<Box<dyn DualAxislike>>)> {
        self.dual_axislike_map.iter()
    }

    /// Returns an iterator over all registered [`TripleAxislike`] actions with their input bindings.
    pub fn iter_triple_axislike(
        &self,
    ) -> impl Iterator<Item = (&A, &Vec<Box<dyn TripleAxislike>>)> {
        self.triple_axislike_map.iter()
    }

    /// Returns an iterator over all registered [`Buttonlike`] action-input bindings.
    pub fn buttonlike_bindings(&self) -> impl Iterator<Item = (&A, &dyn Buttonlike)> {
        self.buttonlike_map
            .iter()
            .flat_map(|(action, inputs)| inputs.iter().map(move |input| (action, input.as_ref())))
    }

    /// Returns an iterator over all registered [`Axislike`] action-input bindings.
    pub fn axislike_bindings(&self) -> impl Iterator<Item = (&A, &dyn Axislike)> {
        self.axislike_map
            .iter()
            .flat_map(|(action, inputs)| inputs.iter().map(move |input| (action, input.as_ref())))
    }

    /// Returns an iterator over all registered [`DualAxislike`] action-input bindings.
    pub fn dual_axislike_bindings(&self) -> impl Iterator<Item = (&A, &dyn DualAxislike)> {
        self.dual_axislike_map
            .iter()
            .flat_map(|(action, inputs)| inputs.iter().map(move |input| (action, input.as_ref())))
    }

    /// Returns an iterator over all registered [`TripleAxislike`] action-input bindings.
    pub fn triple_axislike_bindings(&self) -> impl Iterator<Item = (&A, &dyn TripleAxislike)> {
        self.triple_axislike_map
            .iter()
            .flat_map(|(action, inputs)| inputs.iter().map(move |input| (action, input.as_ref())))
    }

    /// Returns an iterator over all registered [`Buttonlike`] actions.
    pub fn buttonlike_actions(&self) -> impl Iterator<Item = &A> {
        self.buttonlike_map.keys()
    }

    /// Returns an iterator over all registered [`Axislike`] actions.
    pub fn axislike_actions(&self) -> impl Iterator<Item = &A> {
        self.axislike_map.keys()
    }

    /// Returns an iterator over all registered [`DualAxislike`] actions.
    pub fn dual_axislike_actions(&self) -> impl Iterator<Item = &A> {
        self.dual_axislike_map.keys()
    }

    /// Returns an iterator over all registered [`TripleAxislike`] actions.
    pub fn triple_axislike_actions(&self) -> impl Iterator<Item = &A> {
        self.triple_axislike_map.keys()
    }

    /// Returns a reference to the [`UserInput`](crate::user_input::UserInput) inputs associated with the given `action`.
    ///
    /// # Warning
    ///
    /// Unlike the other `get` methods, this method is forced to clone the inputs
    /// due to the lack of [trait upcasting coercion](https://github.com/rust-lang/rust/issues/65991).
    ///
    /// As a result, no equivalent `get_mut` method is provided.
    #[must_use]
    pub fn get(&self, action: &A) -> Option<Vec<UserInputWrapper>> {
        match action.input_control_kind() {
            InputControlKind::Button => {
                let buttonlike = self.buttonlike_map.get(action)?;
                Some(
                    buttonlike
                        .iter()
                        .map(|input| UserInputWrapper::Button(input.clone()))
                        .collect(),
                )
            }
            InputControlKind::Axis => {
                let axislike = self.axislike_map.get(action)?;
                Some(
                    axislike
                        .iter()
                        .map(|input| UserInputWrapper::Axis(input.clone()))
                        .collect(),
                )
            }
            InputControlKind::DualAxis => {
                let dual_axislike = self.dual_axislike_map.get(action)?;
                Some(
                    dual_axislike
                        .iter()
                        .map(|input| UserInputWrapper::DualAxis(input.clone()))
                        .collect(),
                )
            }
            InputControlKind::TripleAxis => {
                let triple_axislike = self.triple_axislike_map.get(action)?;
                Some(
                    triple_axislike
                        .iter()
                        .map(|input| UserInputWrapper::TripleAxis(input.clone()))
                        .collect(),
                )
            }
        }
    }

    /// Returns a reference to the [`Buttonlike`] inputs associated with the given `action`.
    #[must_use]
    pub fn get_buttonlike(&self, action: &A) -> Option<&Vec<Box<dyn Buttonlike>>> {
        self.buttonlike_map.get(action)
    }

    /// Returns a mutable reference to the [`Buttonlike`] inputs mapped to `action`
    #[must_use]
    pub fn get_buttonlike_mut(&mut self, action: &A) -> Option<&mut Vec<Box<dyn Buttonlike>>> {
        self.buttonlike_map.get_mut(action)
    }

    /// Returns a reference to the [`Axislike`] inputs associated with the given `action`.
    #[must_use]
    pub fn get_axislike(&self, action: &A) -> Option<&Vec<Box<dyn Axislike>>> {
        self.axislike_map.get(action)
    }

    /// Returns a mutable reference to the [`Axislike`] inputs mapped to `action`
    #[must_use]
    pub fn get_axislike_mut(&mut self, action: &A) -> Option<&mut Vec<Box<dyn Axislike>>> {
        self.axislike_map.get_mut(action)
    }

    /// Returns a reference to the [`DualAxislike`] inputs associated with the given `action`.
    #[must_use]
    pub fn get_dual_axislike(&self, action: &A) -> Option<&Vec<Box<dyn DualAxislike>>> {
        self.dual_axislike_map.get(action)
    }

    /// Returns a mutable reference to the [`DualAxislike`] inputs mapped to `action`
    #[must_use]
    pub fn get_dual_axislike_mut(&mut self, action: &A) -> Option<&mut Vec<Box<dyn DualAxislike>>> {
        self.dual_axislike_map.get_mut(action)
    }

    /// Returns a reference to the [`TripleAxislike`] inputs associated with the given `action`.
    #[must_use]
    pub fn get_triple_axislike(&self, action: &A) -> Option<&Vec<Box<dyn TripleAxislike>>> {
        self.triple_axislike_map.get(action)
    }

    /// Returns a mutable reference to the [`TripleAxislike`] inputs mapped to `action`
    #[must_use]
    pub fn get_triple_axislike_mut(
        &mut self,
        action: &A,
    ) -> Option<&mut Vec<Box<dyn TripleAxislike>>> {
        self.triple_axislike_map.get_mut(action)
    }

    /// Count the total number of registered input bindings.
    #[must_use]
    pub fn len(&self) -> usize {
        self.buttonlike_map.values().map(Vec::len).sum::<usize>()
            + self.axislike_map.values().map(Vec::len).sum::<usize>()
            + self.dual_axislike_map.values().map(Vec::len).sum::<usize>()
            + self
                .triple_axislike_map
                .values()
                .map(Vec::len)
                .sum::<usize>()
    }

    /// Returns `true` if the map contains no action-input bindings.
    #[inline]
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }

    /// Clears the map, removing all action-input bindings.
    pub fn clear(&mut self) {
        self.buttonlike_map.clear();
        self.axislike_map.clear();
        self.dual_axislike_map.clear();
        self.triple_axislike_map.clear();
    }
}

// Removing
impl<A: Actionlike> InputMap<A> {
    /// Clears all input bindings associated with the `action`.
    pub fn clear_action(&mut self, action: &A) {
        match action.input_control_kind() {
            InputControlKind::Button => {
                self.buttonlike_map.remove(action);
            }
            InputControlKind::Axis => {
                self.axislike_map.remove(action);
            }
            InputControlKind::DualAxis => {
                self.dual_axislike_map.remove(action);
            }
            InputControlKind::TripleAxis => {
                self.triple_axislike_map.remove(action);
            }
        }
    }

    /// Removes the input for the `action` at the provided index.
    ///
    /// Returns `Some(())` if the input was found and removed, or `None` if no matching input was found.
    ///
    /// # Note
    ///
    /// The original input cannot be returned, as the trait object may differ based on the [`InputControlKind`].
    pub fn remove_at(&mut self, action: &A, index: usize) -> Option<()> {
        match action.input_control_kind() {
            InputControlKind::Button => {
                let input_bindings = self.buttonlike_map.get_mut(action)?;
                if input_bindings.len() > index {
                    input_bindings.remove(index);
                    Some(())
                } else {
                    None
                }
            }
            InputControlKind::Axis => {
                let input_bindings = self.axislike_map.get_mut(action)?;
                if input_bindings.len() > index {
                    input_bindings.remove(index);
                    Some(())
                } else {
                    None
                }
            }
            InputControlKind::DualAxis => {
                let input_bindings = self.dual_axislike_map.get_mut(action)?;
                if input_bindings.len() > index {
                    input_bindings.remove(index);
                    Some(())
                } else {
                    None
                }
            }
            InputControlKind::TripleAxis => {
                let input_bindings = self.triple_axislike_map.get_mut(action)?;
                if input_bindings.len() > index {
                    input_bindings.remove(index);
                    Some(())
                } else {
                    None
                }
            }
        }
    }

    /// Removes the input for the `action` if it exists
    ///
    /// Returns [`Some`] with index if the input was found, or [`None`] if no matching input was found.
    pub fn remove(&mut self, action: &A, input: impl Buttonlike) -> Option<usize> {
        let bindings = self.buttonlike_map.get_mut(action)?;
        let boxed_input: Box<dyn Buttonlike> = Box::new(input);
        let index = bindings.iter().position(|input| input == &boxed_input)?;
        bindings.remove(index);
        Some(index)
    }
}

impl<A: Actionlike, U: Buttonlike> From<HashMap<A, Vec<U>>> for InputMap<A> {
    /// Converts a [`HashMap`] mapping actions to multiple [`Buttonlike`]s into an [`InputMap`].
    ///
    /// # Examples
    ///
    /// ```rust
    /// use bevy::prelude::*;
    /// use bevy::utils::HashMap;
    /// use leafwing_input_manager::prelude::*;
    ///
    /// #[derive(Actionlike, Debug, Clone, Copy, PartialEq, Eq, Hash, Reflect)]
    /// enum Action {
    ///     Run,
    ///     Jump,
    /// }
    ///
    /// // Create an InputMap from a HashMap mapping actions to their key bindings.
    /// let mut map: HashMap<Action, Vec<KeyCode>> = HashMap::default();
    ///
    /// // Bind the "run" action to either the left or right shift keys to trigger the action.
    /// map.insert(
    ///     Action::Run,
    ///     vec![KeyCode::ShiftLeft, KeyCode::ShiftRight],
    /// );
    ///
    /// let input_map = InputMap::from(map);
    /// ```
    fn from(raw_map: HashMap<A, Vec<U>>) -> Self {
        let mut input_map = Self::default();
        for (action, inputs) in raw_map.into_iter() {
            input_map.insert_one_to_many(action, inputs);
        }
        input_map
    }
}

impl<A: Actionlike, U: Buttonlike> FromIterator<(A, U)> for InputMap<A> {
    fn from_iter<T: IntoIterator<Item = (A, U)>>(iter: T) -> Self {
        let mut input_map = Self::default();
        for (action, input) in iter.into_iter() {
            input_map.insert(action, input);
        }
        input_map
    }
}

#[cfg(feature = "keyboard")]
mod tests {
    use bevy::prelude::Reflect;
    use serde::{Deserialize, Serialize};

    use super::*;
    use crate as leafwing_input_manager;
    use crate::prelude::*;

    #[derive(Actionlike, Serialize, Deserialize, Clone, PartialEq, Eq, Hash, Debug, Reflect)]
    enum Action {
        Run,
        Jump,
        Hide,
        #[actionlike(Axis)]
        Axis,
        #[actionlike(DualAxis)]
        DualAxis,
        #[actionlike(Axis)]
        TripleAxis,
    }

    #[test]
    fn creation() {
        use bevy::input::keyboard::KeyCode;

        let input_map = InputMap::default()
            .with(Action::Run, KeyCode::KeyW)
            .with(Action::Run, KeyCode::ShiftLeft)
            // Duplicate associations should be ignored
            .with(Action::Run, KeyCode::ShiftLeft)
            .with_one_to_many(Action::Run, [KeyCode::KeyR, KeyCode::ShiftRight])
            .with_multiple([
                (Action::Jump, KeyCode::Space),
                (Action::Hide, KeyCode::ControlLeft),
                (Action::Hide, KeyCode::ControlRight),
            ]);

        let expected_bindings: HashMap<Box<dyn Buttonlike>, Action> = HashMap::from([
            (Box::new(KeyCode::KeyW) as Box<dyn Buttonlike>, Action::Run),
            (
                Box::new(KeyCode::ShiftLeft) as Box<dyn Buttonlike>,
                Action::Run,
            ),
            (Box::new(KeyCode::KeyR) as Box<dyn Buttonlike>, Action::Run),
            (
                Box::new(KeyCode::ShiftRight) as Box<dyn Buttonlike>,
                Action::Run,
            ),
            (
                Box::new(KeyCode::Space) as Box<dyn Buttonlike>,
                Action::Jump,
            ),
            (
                Box::new(KeyCode::ControlLeft) as Box<dyn Buttonlike>,
                Action::Hide,
            ),
            (
                Box::new(KeyCode::ControlRight) as Box<dyn Buttonlike>,
                Action::Hide,
            ),
        ]);

        for (action, input) in input_map.buttonlike_bindings() {
            let expected_action = expected_bindings.get(input).unwrap();
            assert_eq!(expected_action, action);
        }
    }

    #[test]
    fn insertion_idempotency() {
        use bevy::input::keyboard::KeyCode;

        let mut input_map = InputMap::default();
        input_map.insert(Action::Run, KeyCode::Space);

        let expected: Vec<Box<dyn Buttonlike>> = vec![Box::new(KeyCode::Space)];
        assert_eq!(input_map.get_buttonlike(&Action::Run), Some(&expected));

        // Duplicate insertions should not change anything
        input_map.insert(Action::Run, KeyCode::Space);
        assert_eq!(input_map.get_buttonlike(&Action::Run), Some(&expected));
    }

    #[test]
    fn multiple_insertion() {
        use bevy::input::keyboard::KeyCode;

        let mut input_map = InputMap::default();
        input_map.insert(Action::Run, KeyCode::Space);
        input_map.insert(Action::Run, KeyCode::Enter);

        let expected: Vec<Box<dyn Buttonlike>> =
            vec![Box::new(KeyCode::Space), Box::new(KeyCode::Enter)];
        assert_eq!(input_map.get_buttonlike(&Action::Run), Some(&expected));
    }

    #[test]
    fn input_clearing() {
        use bevy::input::keyboard::KeyCode;

        let mut input_map = InputMap::default();
        input_map.insert(Action::Run, KeyCode::Space);

        // Clearing action
        input_map.clear_action(&Action::Run);
        assert_eq!(input_map, InputMap::default());

        // Remove input at existing index
        input_map.insert(Action::Run, KeyCode::Space);
        input_map.insert(Action::Run, KeyCode::ShiftLeft);
        assert!(input_map.remove_at(&Action::Run, 1).is_some());
        assert!(
            input_map.remove_at(&Action::Run, 1).is_none(),
            "Should return None on second removal at the same index"
        );
        assert!(input_map.remove_at(&Action::Run, 0).is_some());
        assert!(
            input_map.remove_at(&Action::Run, 0).is_none(),
            "Should return None on second removal at the same index"
        );
    }

    #[test]
    fn merging() {
        use bevy::input::keyboard::KeyCode;

        let mut input_map = InputMap::default();
        let mut default_keyboard_map = InputMap::default();
        default_keyboard_map.insert(Action::Run, KeyCode::ShiftLeft);
        default_keyboard_map.insert(
            Action::Hide,
            ButtonlikeChord::new([KeyCode::ControlLeft, KeyCode::KeyH]),
        );

        let mut default_gamepad_map = InputMap::default();
        default_gamepad_map.insert(Action::Run, KeyCode::Numpad0);
        default_gamepad_map.insert(Action::Hide, KeyCode::Numpad7);

        // Merging works
        input_map.merge(&default_keyboard_map);
        assert_eq!(input_map, default_keyboard_map);

        // Merging is idempotent
        input_map.merge(&default_keyboard_map);
        assert_eq!(input_map, default_keyboard_map);
    }

    #[cfg(feature = "gamepad")]
    #[test]
    fn gamepad_swapping() {
        use bevy::input::gamepad::Gamepad;

        let mut input_map = InputMap::<Action>::default();
        assert_eq!(input_map.gamepad(), None);

        input_map.set_gamepad(Gamepad { id: 0 });
        assert_eq!(input_map.gamepad(), Some(Gamepad { id: 0 }));

        input_map.clear_gamepad();
        assert_eq!(input_map.gamepad(), None);
    }

    #[cfg(feature = "keyboard")]
    #[test]
    fn input_map_serde() {
        use bevy::prelude::{App, KeyCode};
        use serde_test::{assert_tokens, Token};

        let mut app = App::new();

        // Add the plugin to register input deserializers
        app.add_plugins(InputManagerPlugin::<Action>::default());

        let input_map = InputMap::new([(Action::Hide, KeyCode::ControlLeft)]);
        assert_tokens(
            &input_map,
            &[
                Token::Struct {
                    name: "InputMap",
                    len: 5,
                },
                Token::Str("buttonlike_map"),
                Token::Map { len: Some(1) },
                Token::UnitVariant {
                    name: "Action",
                    variant: "Hide",
                },
                Token::Seq { len: Some(1) },
                Token::Map { len: Some(1) },
                Token::BorrowedStr("KeyCode"),
                Token::UnitVariant {
                    name: "KeyCode",
                    variant: "ControlLeft",
                },
                Token::MapEnd,
                Token::SeqEnd,
                Token::MapEnd,
                Token::Str("axislike_map"),
                Token::Map { len: Some(0) },
                Token::MapEnd,
                Token::Str("dual_axislike_map"),
                Token::Map { len: Some(0) },
                Token::MapEnd,
                Token::Str("triple_axislike_map"),
                Token::Map { len: Some(0) },
                Token::MapEnd,
                Token::Str("associated_gamepad"),
                Token::None,
                Token::StructEnd,
            ],
        );
    }
}