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
//! This module contains [`InputMap`] and its supporting methods and impls.

use crate::user_input::{InputButton, InputMode, UserInput};
use crate::{Actionlike, IntoEnumIterator};
use bevy::prelude::*;
use bevy::utils::HashMap;
use core::fmt::Debug;
use petitset::PetitSet;

/// Maps from raw inputs to an input-method agnostic representation
///
/// Multiple inputs can be mapped to the same action,
/// and each input can be mapped to multiple actions.
///
/// The provided input types must be one of [`GamepadButtonType`], [`KeyCode`] or [`MouseButton`].
///
/// The maximum number of bindings (total) that can be stored for each action is 16.
/// Insertions will silently fail if you have reached this cap.
///
/// In addition, you can configure the per-mode cap for each [`InputMode`] using [`InputMap::new`] or [`InputMap::set_per_mode_cap`].
/// This can be useful if your UI can only display one or two possible keybindings for each input mode.
///
/// # Example
/// ```rust
/// use bevy::prelude::*;
/// use leafwing_input_manager::prelude::*;
/// use leafwing_input_manager::user_input::InputButton;
///
/// // You can Run!
/// #[derive(Actionlike, Clone, Copy, PartialEq, Eq, Hash, EnumIter)]
/// enum Action {
///     Run,
///     Hide,
/// }
///
/// let mut input_map: InputMap<Action> = InputMap::default();
///
/// // Basic insertion
/// input_map.insert(Action::Run, GamepadButtonType::South);
/// input_map.insert(Action::Run, MouseButton::Left);
/// input_map.insert(Action::Run, KeyCode::LShift);
/// input_map.insert_multiple(Action::Hide, [GamepadButtonType::LeftTrigger, GamepadButtonType::RightTrigger]);
///
/// // Combinations!
/// input_map.insert_chord(Action::Run, [KeyCode::LControl, KeyCode::R]);
/// input_map.insert_chord(Action::Hide, [InputButton::Keyboard(KeyCode::H),
///                                       InputButton::Gamepad(GamepadButtonType::South),
///                                       InputButton::Mouse(MouseButton::Middle)]);
///
/// // But you can't Hide :(
/// input_map.clear_action(Action::Hide, None);
///```
#[derive(Component, Debug, Clone, PartialEq)]
pub struct InputMap<A: Actionlike> {
    /// The raw [HashMap] of [PetitSet]s used to store the input mapping
    pub map: HashMap<A, PetitSet<UserInput, 16>>,
    per_mode_cap: Option<usize>,
    associated_gamepad: Option<Gamepad>,
}

impl<A: Actionlike> Default for InputMap<A> {
    fn default() -> Self {
        Self {
            map: HashMap::default(),
            associated_gamepad: None,
            per_mode_cap: None,
        }
    }
}

// Constructors
impl<A: Actionlike> InputMap<A> {
    /// Creates a new empty [`InputMap`]
    ///
    /// The `per_mode_cap` controls the maximum number of inputs of each [`InputMode`] that can be stored.
    /// If a value of 0 is supplied, no cap will be provided (although the global `CAP` must still be obeyed).
    ///
    /// PANICS: `3 * per_mode_cap` cannot exceed the global `CAP`, as we need space to store all mappings.
    pub fn new(per_mode_cap: usize) -> Self {
        if per_mode_cap == 0 {
            Self::default()
        } else {
            let mut input_map = Self::default();
            input_map.set_per_mode_cap(per_mode_cap);
            input_map
        }
    }
}

// Check whether buttons are pressed
impl<A: Actionlike> InputMap<A> {
    /// Is at least one of the corresponding inputs for `action` found in the provided `input` stream?
    #[must_use]
    pub fn pressed(
        &self,
        action: A,
        gamepad_input_stream: &Input<GamepadButton>,
        keyboard_input_stream: &Input<KeyCode>,
        mouse_input_stream: &Input<MouseButton>,
    ) -> bool {
        if let Some(matching_inputs) = self.map.get(&action) {
            self.any_pressed(
                matching_inputs,
                gamepad_input_stream,
                keyboard_input_stream,
                mouse_input_stream,
            )
        } else {
            // No matches can be found if no inputs are registred for that action
            false
        }
    }

    /// Is at least one of the `inputs` pressed?
    #[must_use]
    pub fn any_pressed(
        &self,
        inputs: &PetitSet<UserInput, 16>,
        gamepad_input_stream: &Input<GamepadButton>,
        keyboard_input_stream: &Input<KeyCode>,
        mouse_input_stream: &Input<MouseButton>,
    ) -> bool {
        for input in inputs.iter() {
            if match input {
                UserInput::Single(button) => self.button_pressed(
                    *button,
                    gamepad_input_stream,
                    keyboard_input_stream,
                    mouse_input_stream,
                ),
                UserInput::Chord(buttons) => self.all_buttons_pressed(
                    buttons,
                    gamepad_input_stream,
                    keyboard_input_stream,
                    mouse_input_stream,
                ),
                UserInput::Null => false,
            } {
                // If any of the appropriate inputs match, the action is considered pressed
                return true;
            }
        }
        // If none of the inputs matched, return false
        false
    }

    /// Is the `button` pressed?
    #[must_use]
    pub fn button_pressed(
        &self,
        button: InputButton,
        gamepad_input_stream: &Input<GamepadButton>,
        keyboard_input_stream: &Input<KeyCode>,
        mouse_input_stream: &Input<MouseButton>,
    ) -> bool {
        match button {
            InputButton::Gamepad(gamepad_button) => {
                // If no gamepad is registered, we know for sure that no match was found
                if let Some(gamepad) = self.associated_gamepad {
                    gamepad_input_stream.pressed(GamepadButton(gamepad, gamepad_button))
                } else {
                    false
                }
            }
            InputButton::Keyboard(keycode) => keyboard_input_stream.pressed(keycode),
            InputButton::Mouse(mouse_button) => mouse_input_stream.pressed(mouse_button),
        }
    }

    /// Are all of the `buttons` pressed?
    #[must_use]
    pub fn all_buttons_pressed(
        &self,
        buttons: &PetitSet<InputButton, 8>,
        gamepad_input_stream: &Input<GamepadButton>,
        keyboard_input_stream: &Input<KeyCode>,
        mouse_input_stream: &Input<MouseButton>,
    ) -> bool {
        for &button in buttons.iter() {
            // If any of the appropriate inputs failed to match, the action is considered pressed
            if !self.button_pressed(
                button,
                gamepad_input_stream,
                keyboard_input_stream,
                mouse_input_stream,
            ) {
                return false;
            }
        }
        // If none of the inputs failed to match, return true
        true
    }
}

// Utilities
impl<A: Actionlike> InputMap<A> {
    /// Returns the mapping between the `action` that uses the supplied `input_mode`
    ///
    /// If `input_mode` is `None`, all inputs will be returned regardless of input mode.
    ///
    /// For chords, an input will be returned if any of the contained buttons use that input mode.
    ///
    /// If no matching bindings are found, an empty [`PetitSet`] will be returned.
    ///
    /// A copy of the values are returned, rather than a reference to them.
    /// The order of these values is stable, in a first-in, first-out fashion.
    /// Use `self.map.get` or `self.map.get_mut` if you require a reference.
    #[must_use]
    pub fn get(&self, action: A, input_mode: Option<InputMode>) -> PetitSet<UserInput, 16> {
        if let Some(full_set) = self.map.get(&action) {
            if let Some(input_mode) = input_mode {
                let mut matching_set = PetitSet::default();
                for input in full_set.iter() {
                    if input.matches_input_mode(input_mode) {
                        matching_set.insert(input.clone());
                    }
                }

                if matching_set.is_empty() {
                    PetitSet::default()
                } else {
                    matching_set
                }
            } else {
                full_set.clone()
            }
        } else {
            PetitSet::default()
        }
    }

    /// Returns how many bindings are currently registered for the provided action with the provided [`InputMode`]
    ///
    /// If `None` is provided, a total across all input modes will be provided.
    ///
    /// A maximum of `CAP` bindings across all input modes can be stored for each action,
    /// and insert operations will silently fail if used when `CAP` bindings already exist.
    #[must_use]
    pub fn n_registered(&self, action: A, input_mode: Option<InputMode>) -> usize {
        self.get(action, input_mode).len()
    }
}

// Insertion
impl<A: Actionlike> InputMap<A> {
    /// Insert a mapping between `action` and `input`
    ///
    /// Existing mappings for that action will not be overwritten.
    /// If the set for this action is already full, this insertion will silently fail.
    pub fn insert(&mut self, action: A, input: impl Into<UserInput>) {
        let input = input.into();

        // Don't insert Null inputs into the map
        if input == UserInput::Null {
            return;
        }

        // Don't overflow the set!
        if self.n_registered(action, None) >= 16 {
            return;
        }

        // Respect any per-input-mode caps that have been set
        if let Some(per_mode_cap) = self.per_mode_cap {
            for input_mode in input.input_modes() {
                if self.n_registered(action, Some(input_mode)) >= per_mode_cap {
                    return;
                }
            }
        }

        if let Some(existing_set) = self.map.get_mut(&action) {
            existing_set.insert(input);
        } else {
            let mut new_set = PetitSet::default();
            new_set.insert(input);
            self.map.insert(action, new_set);
        }
    }

    /// Insert a mapping between `action` and the provided `inputs`
    ///
    /// This method creates multiple distinct bindings.
    /// If you want to require multiple buttons to be pressed at once, use [`insert_chord`](Self::insert_chord).
    /// Any iterator that can be converted into a [`UserInput`] can be supplied.
    ///
    /// Existing mappings for that action will not be overwritten.
    pub fn insert_multiple(
        &mut self,
        action: A,
        inputs: impl IntoIterator<Item = impl Into<UserInput>>,
    ) {
        for input in inputs {
            self.insert(action, input);
        }
    }

    /// Insert a mapping between `action` and the simultaneous combination of `buttons` provided
    ///
    /// Any iterator that can be converted into a [`Button`] can be supplied, but will be converted into a [`PetitSet`] for storage and use.
    /// Chords can also be added with the [insert](Self::insert) method, if the [`UserInput::Chord`] variant is constructed explicitly.
    ///
    /// Existing mappings for that action will not be overwritten.
    pub fn insert_chord(
        &mut self,
        action: A,
        buttons: impl IntoIterator<Item = impl Into<InputButton>>,
    ) {
        self.insert(action, UserInput::chord(buttons));
    }

    /// Replaces any existing inputs for the `action` of the same [`InputMode`] with the provided `input`
    ///
    /// Returns all previously registered inputs, if any
    pub fn replace(
        &mut self,
        action: A,
        input: impl Into<UserInput>,
    ) -> Option<PetitSet<UserInput, 16>> {
        let input = input.into();

        let mut old_inputs: PetitSet<UserInput, 16> = PetitSet::default();
        for input_mode in input.input_modes() {
            if let Some(removed_inputs) = self.clear_action(action, Some(input_mode)) {
                for removed_input in removed_inputs {
                    old_inputs.insert(removed_input);
                }
            }
        }

        self.insert(action, input);

        Some(old_inputs)
    }

    /// Replaces the input for the `action`of the same [`InputMode`] at the same index with the provided `input`
    ///
    /// If the input is a [`UserInput::Chord`] that combines multiple input modes or [`UserInput::Null`], this method will silently fail.
    /// Returns the replaced input, if any.
    pub fn replace_at(
        &mut self,
        action: A,
        input: impl Into<UserInput>,
        index: usize,
    ) -> Option<UserInput> {
        let input = input.into();
        let input_modes = input.input_modes();

        if input_modes.len() != 1 {
            return None;
        }

        // We know that the input belongs to exactly one mode
        let input_mode = input_modes.into_iter().next().unwrap();
        let removed = self.clear_at(action, input_mode, index);
        self.insert(action, input);

        removed
    }

    /// Merges the provided [`InputMap`] into the [`InputMap`] this method was called on
    ///
    /// This adds both of their bindings to the resulting [`InputMap`].
    /// Like usual, any duplicate bindings are ignored.
    ///
    /// If the associated gamepads do not match, the resulting associated gamepad will be set to `None`.
    pub fn merge(&mut self, other: &InputMap<A>) {
        let associated_gamepad = if self.associated_gamepad == other.associated_gamepad {
            self.associated_gamepad
        } else {
            None
        };

        let mut new_map = InputMap {
            associated_gamepad,
            ..Default::default()
        };

        for action in A::iter() {
            new_map.insert_multiple(action, self.get(action, None));
            new_map.insert_multiple(action, other.get(action, None));
        }

        *self = new_map;
    }
}

// Clearing
impl<A: Actionlike> InputMap<A> {
    /// Clears all inputs registered for the `action` that use the supplied `input_mode`
    ///
    /// If `input_mode` is `None`, all inputs will be cleared regardless of input mode.
    ///
    /// For chords, an input will be removed if any of the contained buttons use that input mode.
    ///
    /// Returns all previously registered inputs, if any
    pub fn clear_action(
        &mut self,
        action: A,
        input_mode: Option<InputMode>,
    ) -> Option<PetitSet<UserInput, 16>> {
        if let Some(input_mode) = input_mode {
            // Pull out all the matching inputs
            if let Some(bindings) = self.map.remove(&action) {
                let mut retained_set: PetitSet<UserInput, 16> = PetitSet::default();
                let mut removed_set: PetitSet<UserInput, 16> = PetitSet::default();

                for input in bindings {
                    if input.matches_input_mode(input_mode) {
                        removed_set.insert(input);
                    } else {
                        retained_set.insert(input);
                    }
                }

                // Put back the ones that didn't match
                self.insert_multiple(action, retained_set);

                // Return the items that matched
                if removed_set.is_empty() {
                    None
                } else {
                    Some(removed_set)
                }
            } else {
                None
            }
        } else {
            self.map.remove(&action)
        }
    }

    /// Clears the input for the `action` with the specified [`InputMode`] at the provided index
    ///
    /// Returns the removed input, if any
    pub fn clear_at(
        &mut self,
        action: A,
        input_mode: InputMode,
        index: usize,
    ) -> Option<UserInput> {
        let mut bindings = self.get(action, Some(input_mode));
        if bindings.len() < index {
            // Not enough matching bindings were found
            return None;
        }

        // Clear out existing mappings for that input mode
        self.clear_action(action, Some(input_mode));

        // Remove the binding at the provided index
        let removed = bindings.take_at(index);

        // Reinsert the other bindings
        self.insert_multiple(action, bindings);

        removed
    }

    /// Clears all inputs that use the supplied `input_mode`
    ///
    /// If `input_mode` is `None`, all inputs will be cleared regardless of input mode.
    ///
    /// For chords, an input will be removed if any of the contained buttons use that input mode.
    ///
    /// Returns the subset of the action map that was removed
    #[allow(clippy::return_self_not_must_use)]
    pub fn clear_input_mode(&mut self, input_mode: Option<InputMode>) -> InputMap<A> {
        let mut cleared_input_map = InputMap {
            associated_gamepad: self.associated_gamepad,
            ..Default::default()
        };

        for action in A::iter() {
            if let Some(removed_inputs) = self.clear_action(action, input_mode) {
                cleared_input_map.insert_multiple(action, removed_inputs);
            }
        }

        cleared_input_map
    }
}

// Per-mode cap
impl<A: Actionlike> InputMap<A> {
    /// Returns the per-[`InputMode`] cap on input bindings for every action
    ///
    /// Each individual action can have at most this many bindings, making them easier to display and configure.
    pub fn per_mode_cap(&self) -> usize {
        if let Some(cap) = self.per_mode_cap {
            cap
        } else {
            0
        }
    }

    /// Sets the per-[`InputMode`] cap on input bindings for every action
    ///
    /// Each individual action can have at most this many bindings, making them easier to display and configure.
    /// Any excess actions will be removed, and returned from this method.
    ///
    /// Supplying a value of 0 removes any per-mode cap.
    ///
    /// PANICS: `3 * per_mode_cap` cannot exceed the global `CAP`, as we need space to store all mappings.
    #[allow(clippy::return_self_not_must_use)]
    pub fn set_per_mode_cap(&mut self, per_mode_cap: usize) -> InputMap<A> {
        assert!(3 * per_mode_cap <= 16);

        if per_mode_cap == 0 {
            self.per_mode_cap = None;
            return InputMap::default();
        } else {
            self.per_mode_cap = Some(per_mode_cap);
        }

        // Store the actions that get culled and then return them
        let mut removed_actions = InputMap::default();

        // Cull excess mappings
        for action in A::iter() {
            for input_mode in InputMode::iter() {
                let n_registered = self.n_registered(action, Some(input_mode));
                if n_registered > per_mode_cap {
                    for i in per_mode_cap..n_registered {
                        let removed_input = self.clear_at(action, input_mode, i);
                        if let Some(input) = removed_input {
                            removed_actions.insert(action, input);
                        }
                    }
                }
            }
        }

        removed_actions
    }
}

// Gamepads
impl<A: Actionlike> InputMap<A> {
    /// Assigns a particular [`Gamepad`] to the entity controlled by this input map
    pub fn assign_gamepad(&mut self, gamepad: Gamepad) {
        self.associated_gamepad = Some(gamepad);
    }

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

    /// Fetches the [Gamepad] associated with the entity controlled by this entity map
    #[must_use]
    pub fn gamepad(&self) -> Option<Gamepad> {
        self.associated_gamepad
    }
}

mod tests {
    use crate::prelude::*;
    use strum::EnumIter;

    #[derive(Actionlike, Clone, Copy, PartialEq, Eq, Hash, EnumIter, Debug)]
    enum Action {
        Run,
        Jump,
        Hide,
    }

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

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

        assert_eq!(
            input_map.get(Action::Run, None),
            PetitSet::<UserInput, 16>::from_iter([KeyCode::Space.into()])
        );

        // Duplicate insertions should not change anything
        input_map.insert(Action::Run, KeyCode::Space);
        assert_eq!(
            input_map.get(Action::Run, None),
            PetitSet::<UserInput, 16>::from_iter([KeyCode::Space.into()])
        );
    }

    #[test]
    fn multiple_insertion() {
        use crate::user_input::{InputButton, UserInput};
        use bevy::input::keyboard::KeyCode;
        use petitset::PetitSet;

        let mut input_map_1 = InputMap::<Action>::default();
        input_map_1.insert(Action::Run, KeyCode::Space);
        input_map_1.insert(Action::Run, KeyCode::Return);

        assert_eq!(
            input_map_1.get(Action::Run, None),
            PetitSet::<UserInput, 16>::from_iter([KeyCode::Space.into(), KeyCode::Return.into()])
        );

        let mut input_map_2 = InputMap::<Action>::default();
        input_map_2.insert_multiple(Action::Run, [KeyCode::Space, KeyCode::Return]);

        assert_eq!(input_map_1, input_map_2);

        let mut input_map_3 = InputMap::<Action>::default();
        input_map_3.insert_multiple(Action::Run, [KeyCode::Return, KeyCode::Space]);

        assert_eq!(input_map_1, input_map_3);

        let mut input_map_4 = InputMap::<Action>::default();
        input_map_4.insert_multiple(
            Action::Run,
            [
                InputButton::Keyboard(KeyCode::Space),
                InputButton::Keyboard(KeyCode::Return),
            ],
        );

        assert_eq!(input_map_1, input_map_4);

        let mut input_map_5 = InputMap::<Action>::default();
        input_map_5.insert_multiple(
            Action::Run,
            [
                UserInput::Single(InputButton::Keyboard(KeyCode::Space)),
                UserInput::Single(InputButton::Keyboard(KeyCode::Return)),
            ],
        );

        assert_eq!(input_map_1, input_map_5);
    }

    #[test]
    pub fn chord_coercion() {
        use crate::input_map::{InputButton, UserInput};
        use bevy::input::keyboard::KeyCode;

        // Single items in a chord should be coerced to a singleton
        let mut input_map_1 = InputMap::<Action>::default();
        input_map_1.insert(Action::Run, KeyCode::Space);

        let mut input_map_2 = InputMap::<Action>::default();
        input_map_2.insert(Action::Run, UserInput::chord([KeyCode::Space]));

        assert_eq!(input_map_1, input_map_2);

        // Empty chords are converted to UserInput::Null, and then ignored
        let mut input_map_3 = InputMap::<Action>::default();
        let empty_vec: Vec<InputButton> = Vec::default();
        input_map_3.insert_chord(Action::Run, empty_vec);

        assert_eq!(input_map_3, InputMap::<Action>::default());
    }

    #[test]
    fn input_clearing() {
        use crate::user_input::{InputButton, InputMode};
        use bevy::input::{gamepad::GamepadButtonType, keyboard::KeyCode, mouse::MouseButton};

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

        let one_item_input_map = input_map.clone();

        // Clearing without a specified input mode
        input_map.clear_action(Action::Run, None);
        assert_eq!(input_map, InputMap::default());

        // Clearing with the non-matching input mode
        input_map.insert(Action::Run, KeyCode::Space);
        input_map.clear_action(Action::Run, Some(InputMode::Gamepad));
        input_map.clear_action(Action::Run, Some(InputMode::Mouse));
        assert_eq!(input_map, one_item_input_map);

        // Clearing with the matching input mode
        input_map.clear_action(Action::Run, Some(InputMode::Keyboard));
        assert_eq!(input_map, InputMap::default());

        // Clearing an entire input mode
        input_map.insert_multiple(Action::Run, [KeyCode::Space, KeyCode::A]);
        input_map.insert(Action::Hide, KeyCode::RBracket);
        input_map.clear_input_mode(Some(InputMode::Keyboard));
        assert_eq!(input_map, InputMap::default());

        // Other stored inputs should be unaffected
        input_map.insert(Action::Run, KeyCode::Space);
        input_map.insert(Action::Hide, GamepadButtonType::South);
        input_map.insert(Action::Run, MouseButton::Left);
        input_map.clear_input_mode(Some(InputMode::Gamepad));
        input_map.clear_action(Action::Run, Some(InputMode::Mouse));
        assert_eq!(input_map, one_item_input_map);

        // Clearing all inputs works
        input_map.insert(Action::Hide, GamepadButtonType::South);
        input_map.insert(Action::Run, MouseButton::Left);
        let big_input_map = input_map.clone();
        let removed_items = input_map.clear_input_mode(None);
        assert_eq!(input_map, InputMap::default());

        // Items are returned on clearing
        assert_eq!(removed_items, big_input_map);

        // Chords are removed if at least one button matches
        input_map.insert_chord(Action::Run, [KeyCode::A, KeyCode::B]);
        input_map.insert_chord(
            Action::Run,
            [GamepadButtonType::South, GamepadButtonType::West],
        );
        input_map.insert_chord(
            Action::Run,
            [
                InputButton::Gamepad(GamepadButtonType::South),
                InputButton::Keyboard(KeyCode::A),
            ],
        );

        let removed_items = input_map.clear_input_mode(Some(InputMode::Gamepad));
        let mut expected_removed_items = InputMap::default();
        expected_removed_items.insert_chord(
            Action::Run,
            [GamepadButtonType::South, GamepadButtonType::West],
        );
        expected_removed_items.insert_chord(
            Action::Run,
            [
                InputButton::Gamepad(GamepadButtonType::South),
                InputButton::Keyboard(KeyCode::A),
            ],
        );

        assert_eq!(removed_items, expected_removed_items);
    }

    #[test]
    fn reset_to_default() {
        use crate::input_map::InputMode;
        use bevy::input::{gamepad::GamepadButtonType, keyboard::KeyCode};

        let mut input_map = InputMap::default();
        let mut default_keyboard_map = InputMap::default();
        default_keyboard_map.insert(Action::Run, KeyCode::LShift);
        default_keyboard_map.insert_chord(Action::Hide, [KeyCode::LControl, KeyCode::H]);
        let mut default_gamepad_map = InputMap::default();
        default_gamepad_map.insert(Action::Run, GamepadButtonType::South);
        default_gamepad_map.insert(Action::Hide, GamepadButtonType::East);

        // 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);

        // Fully default settings
        input_map.merge(&default_gamepad_map);
        let default_input_map = input_map.clone();

        // Changing from the default
        input_map.replace(Action::Jump, KeyCode::J);

        // Clearing all keyboard bindings works as expected
        input_map.clear_input_mode(Some(InputMode::Keyboard));
        assert_eq!(input_map, default_gamepad_map);

        // Resetting to default works
        input_map.merge(&default_keyboard_map);
        assert_eq!(input_map, default_input_map);
    }

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

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

        input_map.assign_gamepad(Gamepad(0));
        assert_eq!(input_map.gamepad(), Some(Gamepad(0)));

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

    #[test]
    fn mock_inputs() {
        use crate::input_map::InputButton;
        use bevy::prelude::*;

        // Setting up the input map
        let mut input_map = InputMap::<Action>::default();
        input_map.assign_gamepad(Gamepad(42));

        // Gamepad
        input_map.insert(Action::Run, GamepadButtonType::South);
        input_map.insert_chord(
            Action::Jump,
            [GamepadButtonType::South, GamepadButtonType::North],
        );

        // Keyboard
        input_map.insert(Action::Run, KeyCode::LShift);
        input_map.insert(Action::Hide, KeyCode::LShift);

        // Mouse
        input_map.insert(Action::Run, MouseButton::Left);
        input_map.insert(Action::Jump, MouseButton::Other(42));

        // Cross-device chords
        input_map.insert_chord(
            Action::Hide,
            [
                InputButton::Keyboard(KeyCode::LControl),
                InputButton::Mouse(MouseButton::Left),
            ],
        );

        // Input streams
        let mut gamepad_input_stream = Input::<GamepadButton>::default();
        let mut keyboard_input_stream = Input::<KeyCode>::default();
        let mut mouse_input_stream = Input::<MouseButton>::default();

        // With no inputs, nothing should be detected
        for action in Action::iter() {
            assert!(!input_map.pressed(
                action,
                &gamepad_input_stream,
                &keyboard_input_stream,
                &mouse_input_stream,
            ));
        }

        // Pressing the wrong gamepad
        gamepad_input_stream.press(GamepadButton(Gamepad(0), GamepadButtonType::South));
        for action in Action::iter() {
            assert!(!input_map.pressed(
                action,
                &gamepad_input_stream,
                &keyboard_input_stream,
                &mouse_input_stream,
            ));
        }

        // Pressing the correct gamepad
        gamepad_input_stream.press(GamepadButton(Gamepad(42), GamepadButtonType::South));
        assert!(input_map.pressed(
            Action::Run,
            &gamepad_input_stream,
            &keyboard_input_stream,
            &mouse_input_stream,
        ));
        assert!(!input_map.pressed(
            Action::Jump,
            &gamepad_input_stream,
            &keyboard_input_stream,
            &mouse_input_stream,
        ));

        // Chord
        gamepad_input_stream.press(GamepadButton(Gamepad(42), GamepadButtonType::North));
        assert!(input_map.pressed(
            Action::Run,
            &gamepad_input_stream,
            &keyboard_input_stream,
            &mouse_input_stream,
        ));
        assert!(input_map.pressed(
            Action::Jump,
            &gamepad_input_stream,
            &keyboard_input_stream,
            &mouse_input_stream,
        ));

        // Clearing inputs
        gamepad_input_stream = Input::<GamepadButton>::default();
        for action in Action::iter() {
            assert!(!input_map.pressed(
                action,
                &gamepad_input_stream,
                &keyboard_input_stream,
                &mouse_input_stream,
            ));
        }

        // Keyboard
        keyboard_input_stream.press(KeyCode::LShift);
        assert!(input_map.pressed(
            Action::Run,
            &gamepad_input_stream,
            &keyboard_input_stream,
            &mouse_input_stream,
        ));
        assert!(input_map.pressed(
            Action::Hide,
            &gamepad_input_stream,
            &keyboard_input_stream,
            &mouse_input_stream,
        ));

        keyboard_input_stream = Input::<KeyCode>::default();

        // Mouse
        mouse_input_stream.press(MouseButton::Left);
        mouse_input_stream.press(MouseButton::Other(42));

        assert!(input_map.pressed(
            Action::Run,
            &gamepad_input_stream,
            &keyboard_input_stream,
            &mouse_input_stream,
        ));
        assert!(input_map.pressed(
            Action::Jump,
            &gamepad_input_stream,
            &keyboard_input_stream,
            &mouse_input_stream,
        ));

        mouse_input_stream = Input::<MouseButton>::default();

        // Cross-device chording
        keyboard_input_stream.press(KeyCode::LControl);
        mouse_input_stream.press(MouseButton::Left);
        assert!(input_map.pressed(
            Action::Hide,
            &gamepad_input_stream,
            &keyboard_input_stream,
            &mouse_input_stream,
        ));
    }
}