leafwing_input_manager/
clashing_inputs.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
//! Handles clashing inputs into a [`InputMap`] in a configurable fashion.
//!
//! [`Buttonlike`] actions can clash, if one is a strict subset of the other.
//! For example, the user might have bound `Ctrl + S` to save, and `S` to move down.
//! If the user presses `Ctrl + S`, the input manager should not also trigger the `S` action.

use std::cmp::Ordering;

use bevy::prelude::{Gamepad, Resource};
use serde::{Deserialize, Serialize};

use crate::input_map::{InputMap, UpdatedActions};
use crate::prelude::updating::CentralInputStore;
use crate::user_input::Buttonlike;
use crate::{Actionlike, InputControlKind};

/// How should clashing inputs by handled by an [`InputMap`]?
///
/// Inputs "clash" if and only if the [`Buttonlike`] components of one user input is a strict subset of the other.
/// For example:
///
/// - `S` and `W`: does not clash
/// - `ControlLeft + S` and `S`: clashes
/// - `S` and `S`: does not clash
/// - `ControlLeft + S` and ` AltLeft + S`: does not clash
/// - `ControlLeft + S`, `AltLeft + S` and `ControlLeft + AltLeft + S`: clashes
///
/// This strategy is only used when assessing the actions and input holistically,
/// in [`InputMap::process_actions`], using [`InputMap::handle_clashes`].
#[non_exhaustive]
#[derive(Resource, Clone, Copy, PartialEq, Eq, Debug, Serialize, Deserialize, Default)]
pub enum ClashStrategy {
    /// All matching inputs will always be pressed
    PressAll,
    /// Only press the action that corresponds to the longest chord
    ///
    /// This is the default strategy.
    #[default]
    PrioritizeLongest,
}

impl ClashStrategy {
    /// Returns the list of all possible clash strategies.
    pub fn variants() -> &'static [ClashStrategy] {
        use ClashStrategy::*;

        &[PressAll, PrioritizeLongest]
    }
}

/// A flat list of the [`Buttonlike`] inputs that make up a [`UserInput`](crate::user_input::UserInput).
///
/// This is used to check for potential clashes between actions,
/// where one action is a strict subset of another.
#[derive(Debug, Clone)]
#[must_use]
pub enum BasicInputs {
    /// No buttonlike inputs are involved.
    ///
    /// This might be used for things like a joystick axis.
    None,

    /// The input consists of a single, fundamental [`Buttonlike`] [`UserInput`](crate::user_input::UserInput).
    ///
    /// For example, a single key press.
    Simple(Box<dyn Buttonlike>),

    /// The input can be triggered by multiple independent [`Buttonlike`] [`UserInput`](crate::user_input::UserInput)s,
    /// but is still fundamentally considered a single input.
    ///
    /// For example, a virtual D-Pad is only one input, but can be triggered by multiple keys.
    Composite(Vec<Box<dyn Buttonlike>>),

    /// The input represents one or more independent [`Buttonlike`] [`UserInput`](crate::user_input::UserInput) types.
    ///
    /// For example, a chorded input is a group of multiple keys that must be pressed together.
    Chord(Vec<Box<dyn Buttonlike>>),
}

impl BasicInputs {
    /// Returns a list of the underlying [`Buttonlike`] [`UserInput`](crate::user_input::UserInput)s.
    ///
    /// # Warning
    ///
    /// When checking for clashes, do not use this method to compute the length of the input.
    /// Instead, use [`BasicInputs::len`], as these do not always agree.
    #[inline]
    pub fn inputs(&self) -> Vec<Box<dyn Buttonlike>> {
        match self.clone() {
            Self::None => Vec::default(),
            Self::Simple(input) => vec![input],
            Self::Composite(inputs) => inputs,
            Self::Chord(inputs) => inputs,
        }
    }

    ///  Create a [`BasicInputs::Composite`] from two existing [`BasicInputs`].
    pub fn compose(self, other: BasicInputs) -> Self {
        let combined_inputs = self.inputs().into_iter().chain(other.inputs()).collect();

        BasicInputs::Composite(combined_inputs)
    }

    /// Returns the number of the logical [`Buttonlike`] [`UserInput`](crate::user_input::UserInput)s that make up the input.
    ///
    /// A single key press is one input, while a chorded input is multiple inputs.
    /// A composite input is still considered one input, even if it can be triggered by multiple keys,
    /// as only one input need actually be pressed.
    #[allow(clippy::len_without_is_empty)]
    #[inline]
    pub fn len(&self) -> usize {
        match self {
            Self::None => 0,
            Self::Simple(_) => 1,
            Self::Composite(_) => 1,
            Self::Chord(inputs) => inputs.len(),
        }
    }

    /// Checks if the given two [`BasicInputs`] clash with each other.
    #[inline]
    pub fn clashes_with(&self, other: &BasicInputs) -> bool {
        match (self, other) {
            (Self::None, _) | (_, Self::None) => false,
            (Self::Simple(_), Self::Simple(_)) => false,
            (Self::Simple(self_single), Self::Chord(other_group)) => {
                other_group.len() > 1 && other_group.contains(self_single)
            }
            (Self::Chord(self_group), Self::Simple(other_single)) => {
                self_group.len() > 1 && self_group.contains(other_single)
            }
            (Self::Simple(self_single), Self::Composite(other_composite)) => {
                other_composite.contains(self_single)
            }
            (Self::Composite(self_composite), Self::Simple(other_single)) => {
                self_composite.contains(other_single)
            }
            (Self::Composite(self_composite), Self::Chord(other_group)) => {
                other_group.len() > 1
                    && other_group
                        .iter()
                        .any(|input| self_composite.contains(input))
            }
            (Self::Chord(self_group), Self::Composite(other_composite)) => {
                self_group.len() > 1
                    && self_group
                        .iter()
                        .any(|input| other_composite.contains(input))
            }
            (Self::Chord(self_group), Self::Chord(other_group)) => {
                self_group.len() > 1
                    && other_group.len() > 1
                    && self_group != other_group
                    && (self_group.iter().all(|input| other_group.contains(input))
                        || other_group.iter().all(|input| self_group.contains(input)))
            }
            (Self::Composite(self_composite), Self::Composite(other_composite)) => {
                other_composite
                    .iter()
                    .any(|input| self_composite.contains(input))
                    || self_composite
                        .iter()
                        .any(|input| other_composite.contains(input))
            }
        }
    }
}

impl<A: Actionlike> InputMap<A> {
    /// Resolve clashing button-like inputs, removing action presses that have been overruled
    ///
    /// The `usize` stored in `pressed_actions` corresponds to `Actionlike::index`
    pub fn handle_clashes(
        &self,
        updated_actions: &mut UpdatedActions<A>,
        input_store: &CentralInputStore,
        clash_strategy: ClashStrategy,
        gamepad: Gamepad,
    ) {
        for clash in self.get_clashes(updated_actions, input_store, gamepad) {
            // Remove the action in the pair that was overruled, if any
            if let Some(culled_action) = resolve_clash(&clash, clash_strategy, input_store, gamepad)
            {
                updated_actions.remove(&culled_action);
            }
        }
    }

    /// Updates the cache of possible input clashes
    pub(crate) fn possible_clashes(&self) -> Vec<Clash<A>> {
        let mut clashes = Vec::default();

        for action_a in self.buttonlike_actions() {
            for action_b in self.buttonlike_actions() {
                if let Some(clash) = self.possible_clash(action_a, action_b) {
                    clashes.push(clash);
                }
            }
        }

        clashes
    }

    /// Gets the set of clashing action-input pairs
    ///
    /// Returns both the action and [`UserInput`](crate::user_input::UserInput)s for each clashing set
    #[must_use]
    fn get_clashes(
        &self,
        updated_actions: &UpdatedActions<A>,
        input_store: &CentralInputStore,
        gamepad: Gamepad,
    ) -> Vec<Clash<A>> {
        let mut clashes = Vec::default();

        // We can limit our search to the cached set of possibly clashing actions
        for clash in self.possible_clashes() {
            let pressed_a = updated_actions.pressed(&clash.action_a);
            let pressed_b = updated_actions.pressed(&clash.action_b);

            // Clashes can only occur if both actions were triggered
            // This is not strictly necessary, but saves work
            if pressed_a && pressed_b {
                // Check if the potential clash occurred based on the pressed inputs
                if let Some(clash) = check_clash(&clash, input_store, gamepad) {
                    clashes.push(clash)
                }
            }
        }

        clashes
    }

    /// Gets the decomposed [`BasicInputs`] for each binding mapped to the given action.
    pub fn decomposed(&self, action: &A) -> Vec<BasicInputs> {
        match action.input_control_kind() {
            InputControlKind::Button => {
                let Some(buttonlike) = self.get_buttonlike(action) else {
                    return Vec::new();
                };

                buttonlike.iter().map(|input| input.decompose()).collect()
            }
            InputControlKind::Axis => {
                let Some(axislike) = self.get_axislike(action) else {
                    return Vec::new();
                };

                axislike.iter().map(|input| input.decompose()).collect()
            }
            InputControlKind::DualAxis => {
                let Some(dual_axislike) = self.get_dual_axislike(action) else {
                    return Vec::new();
                };

                dual_axislike
                    .iter()
                    .map(|input| input.decompose())
                    .collect()
            }
            InputControlKind::TripleAxis => {
                let Some(triple_axislike) = self.get_triple_axislike(action) else {
                    return Vec::new();
                };

                triple_axislike
                    .iter()
                    .map(|input| input.decompose())
                    .collect()
            }
        }
    }

    /// If the pair of actions could clash, how?
    // FIXME: does not handle axis inputs. Should use the `decomposed` method instead of `get_buttonlike`
    #[must_use]
    fn possible_clash(&self, action_a: &A, action_b: &A) -> Option<Clash<A>> {
        let mut clash = Clash::new(action_a.clone(), action_b.clone());

        for input_a in self.get_buttonlike(action_a)? {
            for input_b in self.get_buttonlike(action_b)? {
                if input_a.decompose().clashes_with(&input_b.decompose()) {
                    clash.inputs_a.push(input_a.clone());
                    clash.inputs_b.push(input_b.clone());
                }
            }
        }

        let clashed = !clash.inputs_a.is_empty();
        clashed.then_some(clash)
    }
}

/// A user-input clash, which stores the actions that are being clashed on,
/// as well as the corresponding user inputs
#[derive(Debug, PartialEq, Clone, Serialize, Deserialize)]
pub(crate) struct Clash<A: Actionlike> {
    action_a: A,
    action_b: A,
    inputs_a: Vec<Box<dyn Buttonlike>>,
    inputs_b: Vec<Box<dyn Buttonlike>>,
}

impl<A: Actionlike> Clash<A> {
    /// Creates a new clash between the two actions
    #[must_use]
    fn new(action_a: A, action_b: A) -> Self {
        Self {
            action_a,
            action_b,
            inputs_a: Vec::default(),
            inputs_b: Vec::default(),
        }
    }
}

/// Given the `input_store`, does the provided clash actually occur?
///
/// Returns `Some(clash)` if they are clashing, and `None` if they are not.
#[must_use]
fn check_clash<A: Actionlike>(
    clash: &Clash<A>,
    input_store: &CentralInputStore,
    gamepad: Gamepad,
) -> Option<Clash<A>> {
    let mut actual_clash: Clash<A> = clash.clone();

    // For all inputs actually pressed that match action A
    for input_a in clash
        .inputs_a
        .iter()
        .filter(|&input| input.pressed(input_store, gamepad))
    {
        // For all inputs actually pressed that match action B
        for input_b in clash
            .inputs_b
            .iter()
            .filter(|&input| input.pressed(input_store, gamepad))
        {
            // If a clash was detected
            if input_a.decompose().clashes_with(&input_b.decompose()) {
                actual_clash.inputs_a.push(input_a.clone());
                actual_clash.inputs_b.push(input_b.clone());
            }
        }
    }

    let clashed = !clash.inputs_a.is_empty();
    clashed.then_some(actual_clash)
}

/// Which (if any) of the actions in the [`Clash`] should be discarded?
#[must_use]
fn resolve_clash<A: Actionlike>(
    clash: &Clash<A>,
    clash_strategy: ClashStrategy,
    input_store: &CentralInputStore,
    gamepad: Gamepad,
) -> Option<A> {
    // Figure out why the actions are pressed
    let reasons_a_is_pressed: Vec<&dyn Buttonlike> = clash
        .inputs_a
        .iter()
        .filter(|input| input.pressed(input_store, gamepad))
        .map(|input| input.as_ref())
        .collect();

    let reasons_b_is_pressed: Vec<&dyn Buttonlike> = clash
        .inputs_b
        .iter()
        .filter(|input| input.pressed(input_store, gamepad))
        .map(|input| input.as_ref())
        .collect();

    // Clashes are spurious if the actions are pressed for any non-clashing reason
    for reason_a in reasons_a_is_pressed.iter() {
        for reason_b in reasons_b_is_pressed.iter() {
            // If there is at least one non-clashing reason why these buttons should both be pressed,
            // we can avoid resolving the clash completely
            if !reason_a.decompose().clashes_with(&reason_b.decompose()) {
                return None;
            }
        }
    }

    // There's a real clash; resolve it according to the `clash_strategy`
    match clash_strategy {
        // Do nothing
        ClashStrategy::PressAll => None,
        // Remove the clashing action with the shorter chord
        ClashStrategy::PrioritizeLongest => {
            let longest_a: usize = reasons_a_is_pressed
                .iter()
                .map(|input| input.decompose().len())
                .reduce(|a, b| a.max(b))
                .unwrap_or_default();

            let longest_b: usize = reasons_b_is_pressed
                .iter()
                .map(|input| input.decompose().len())
                .reduce(|a, b| a.max(b))
                .unwrap_or_default();

            match longest_a.cmp(&longest_b) {
                Ordering::Greater => Some(clash.action_b.clone()),
                Ordering::Less => Some(clash.action_a.clone()),
                Ordering::Equal => None,
            }
        }
    }
}

#[cfg(feature = "keyboard")]
#[cfg(test)]
mod tests {
    use bevy::input::keyboard::KeyCode::*;
    use bevy::prelude::Reflect;

    use super::*;
    use crate::prelude::{KeyboardVirtualDPad, UserInput};
    use crate::user_input::ButtonlikeChord;

    use crate as leafwing_input_manager;

    #[derive(Actionlike, Clone, Copy, PartialEq, Eq, Hash, Debug, Reflect)]
    enum Action {
        One,
        Two,
        OneAndTwo,
        TwoAndThree,
        OneAndTwoAndThree,
        CtrlOne,
        AltOne,
        CtrlAltOne,
        CtrlUp,
        #[actionlike(DualAxis)]
        MoveDPad,
    }

    fn test_input_map() -> InputMap<Action> {
        use Action::*;

        let mut input_map = InputMap::default();

        input_map.insert(One, Digit1);
        input_map.insert(Two, Digit2);
        input_map.insert(OneAndTwo, ButtonlikeChord::new([Digit1, Digit2]));
        input_map.insert(TwoAndThree, ButtonlikeChord::new([Digit2, Digit3]));
        input_map.insert(
            OneAndTwoAndThree,
            ButtonlikeChord::new([Digit1, Digit2, Digit3]),
        );
        input_map.insert(CtrlOne, ButtonlikeChord::new([ControlLeft, Digit1]));
        input_map.insert(AltOne, ButtonlikeChord::new([AltLeft, Digit1]));
        input_map.insert(
            CtrlAltOne,
            ButtonlikeChord::new([ControlLeft, AltLeft, Digit1]),
        );
        input_map.insert_dual_axis(MoveDPad, KeyboardVirtualDPad::ARROW_KEYS);
        input_map.insert(CtrlUp, ButtonlikeChord::new([ControlLeft, ArrowUp]));

        input_map
    }

    fn inputs_clash(input_a: impl UserInput, input_b: impl UserInput) -> bool {
        let decomposed_a = input_a.decompose();
        println!("{decomposed_a:?}");
        let decomposed_b = input_b.decompose();
        println!("{decomposed_b:?}");
        let do_inputs_clash = decomposed_a.clashes_with(&decomposed_b);
        println!("Clash: {do_inputs_clash}");
        do_inputs_clash
    }

    mod basic_functionality {
        use crate::{
            input_map::UpdatedValue,
            plugin::{AccumulatorPlugin, CentralInputStorePlugin},
            prelude::{AccumulatedMouseMovement, AccumulatedMouseScroll, ModifierKey},
        };
        use bevy::{input::InputPlugin, prelude::*};
        use Action::*;

        use super::*;

        #[test]
        #[ignore = "Figuring out how to handle the length of chords with group inputs is out of scope."]
        fn input_types_have_right_length() {
            let simple = KeyA.decompose();
            assert_eq!(simple.len(), 1);

            let empty_chord = ButtonlikeChord::default().decompose();
            assert_eq!(empty_chord.len(), 0);

            let chord = ButtonlikeChord::new([KeyA, KeyB, KeyC]).decompose();
            assert_eq!(chord.len(), 3);

            let modifier = ModifierKey::Control.decompose();
            assert_eq!(modifier.len(), 1);

            let modified_chord = ButtonlikeChord::modified(ModifierKey::Control, KeyA).decompose();
            assert_eq!(modified_chord.len(), 2);

            let group = KeyboardVirtualDPad::WASD.decompose();
            assert_eq!(group.len(), 1);
        }

        #[test]
        fn clash_detection() {
            let a = KeyA;
            let b = KeyB;
            let c = KeyC;
            let ab = ButtonlikeChord::new([KeyA, KeyB]);
            let bc = ButtonlikeChord::new([KeyB, KeyC]);
            let abc = ButtonlikeChord::new([KeyA, KeyB, KeyC]);
            let axyz_dpad = KeyboardVirtualDPad::new(KeyA, KeyX, KeyY, KeyZ);
            let abcd_dpad = KeyboardVirtualDPad::WASD;

            let ctrl_up = ButtonlikeChord::new([ArrowUp, ControlLeft]);
            let directions_dpad = KeyboardVirtualDPad::ARROW_KEYS;

            assert!(!inputs_clash(a, b));
            assert!(inputs_clash(a, ab.clone()));
            assert!(!inputs_clash(c, ab.clone()));
            assert!(!inputs_clash(ab.clone(), bc.clone()));
            assert!(inputs_clash(ab.clone(), abc.clone()));
            assert!(inputs_clash(axyz_dpad.clone(), a));
            assert!(inputs_clash(axyz_dpad.clone(), ab.clone()));
            assert!(!inputs_clash(axyz_dpad.clone(), bc.clone()));
            assert!(inputs_clash(axyz_dpad.clone(), abcd_dpad.clone()));
            assert!(inputs_clash(ctrl_up.clone(), directions_dpad.clone()));
        }

        #[test]
        fn button_chord_clash_construction() {
            let input_map = test_input_map();

            let observed_clash = input_map.possible_clash(&One, &OneAndTwo).unwrap();

            let correct_clash = Clash {
                action_a: One,
                action_b: OneAndTwo,
                inputs_a: vec![Box::new(Digit1)],
                inputs_b: vec![Box::new(ButtonlikeChord::new([Digit1, Digit2]))],
            };

            assert_eq!(observed_clash, correct_clash);
        }

        #[test]
        fn chord_chord_clash_construction() {
            let input_map = test_input_map();

            let observed_clash = input_map
                .possible_clash(&OneAndTwoAndThree, &OneAndTwo)
                .unwrap();
            let correct_clash = Clash {
                action_a: OneAndTwoAndThree,
                action_b: OneAndTwo,
                inputs_a: vec![Box::new(ButtonlikeChord::new([Digit1, Digit2, Digit3]))],
                inputs_b: vec![Box::new(ButtonlikeChord::new([Digit1, Digit2]))],
            };

            assert_eq!(observed_clash, correct_clash);
        }

        #[test]
        fn can_clash() {
            let input_map = test_input_map();

            assert!(input_map.possible_clash(&One, &Two).is_none());
            assert!(input_map.possible_clash(&One, &OneAndTwo).is_some());
            assert!(input_map.possible_clash(&One, &OneAndTwoAndThree).is_some());
            assert!(input_map.possible_clash(&One, &TwoAndThree).is_none());
            assert!(input_map
                .possible_clash(&OneAndTwo, &OneAndTwoAndThree)
                .is_some());
        }

        #[test]
        fn resolve_prioritize_longest() {
            let mut app = App::new();
            app.add_plugins((InputPlugin, AccumulatorPlugin, CentralInputStorePlugin));
            app.init_resource::<AccumulatedMouseMovement>();
            app.init_resource::<AccumulatedMouseScroll>();

            let input_map = test_input_map();
            let simple_clash = input_map.possible_clash(&One, &OneAndTwo).unwrap();
            Digit1.press(app.world_mut());
            Digit2.press(app.world_mut());
            app.update();

            let input_store = app.world().resource::<CentralInputStore>();

            assert_eq!(
                resolve_clash(
                    &simple_clash,
                    ClashStrategy::PrioritizeLongest,
                    input_store,
                    Gamepad::new(0),
                ),
                Some(One)
            );

            let reversed_clash = input_map.possible_clash(&OneAndTwo, &One).unwrap();
            let input_store = app.world().resource::<CentralInputStore>();

            assert_eq!(
                resolve_clash(
                    &reversed_clash,
                    ClashStrategy::PrioritizeLongest,
                    input_store,
                    Gamepad::new(0),
                ),
                Some(One)
            );

            let chord_clash = input_map
                .possible_clash(&OneAndTwo, &OneAndTwoAndThree)
                .unwrap();
            Digit3.press(app.world_mut());
            app.update();

            let input_store = app.world().resource::<CentralInputStore>();

            assert_eq!(
                resolve_clash(
                    &chord_clash,
                    ClashStrategy::PrioritizeLongest,
                    input_store,
                    Gamepad::new(0),
                ),
                Some(OneAndTwo)
            );
        }

        #[test]
        fn handle_simple_clash() {
            let mut app = App::new();
            app.add_plugins((InputPlugin, AccumulatorPlugin, CentralInputStorePlugin));
            let input_map = test_input_map();

            Digit1.press(app.world_mut());
            Digit2.press(app.world_mut());
            app.update();

            let mut updated_actions = UpdatedActions::default();

            updated_actions.insert(One, UpdatedValue::Button(true));
            updated_actions.insert(Two, UpdatedValue::Button(true));
            updated_actions.insert(OneAndTwo, UpdatedValue::Button(true));

            let input_store = app.world().resource::<CentralInputStore>();

            input_map.handle_clashes(
                &mut updated_actions,
                input_store,
                ClashStrategy::PrioritizeLongest,
                Gamepad::new(0),
            );

            let mut expected = UpdatedActions::default();
            expected.insert(OneAndTwo, UpdatedValue::Button(true));

            assert_eq!(updated_actions, expected);
        }

        // Checks that a clash between a VirtualDPad and a chord chooses the chord
        #[test]
        #[ignore = "Clashing inputs for non-buttonlike inputs is broken."]
        fn handle_clashes_dpad_chord() {
            let mut app = App::new();
            app.add_plugins(InputPlugin);
            app.init_resource::<AccumulatedMouseMovement>();
            app.init_resource::<AccumulatedMouseScroll>();
            let input_map = test_input_map();

            ControlLeft.press(app.world_mut());
            ArrowUp.press(app.world_mut());
            app.update();

            // Both the DPad and the chord are pressed,
            // because we've sent the inputs for both
            let mut updated_actions = UpdatedActions::default();
            updated_actions.insert(CtrlUp, UpdatedValue::Button(true));
            updated_actions.insert(MoveDPad, UpdatedValue::Button(true));

            // Double-check that the two input bindings clash
            let chord_input = input_map.get_buttonlike(&CtrlUp).unwrap().first().unwrap();
            let dpad_input = input_map
                .get_dual_axislike(&MoveDPad)
                .unwrap()
                .first()
                .unwrap();

            assert!(chord_input
                .decompose()
                .clashes_with(&dpad_input.decompose()));

            // Triple check that the inputs are clashing
            input_map
                .possible_clash(&CtrlUp, &MoveDPad)
                .expect("Clash not detected");

            // Double check that the chord is longer than the DPad
            assert!(chord_input.decompose().len() > dpad_input.decompose().len());

            let input_store = app.world().resource::<CentralInputStore>();

            input_map.handle_clashes(
                &mut updated_actions,
                input_store,
                ClashStrategy::PrioritizeLongest,
                Gamepad::new(0),
            );

            // Only the chord should be pressed,
            // because it is longer than the DPad
            let mut expected = UpdatedActions::default();
            expected.insert(CtrlUp, UpdatedValue::Button(true));

            assert_eq!(updated_actions, expected);
        }

        #[test]
        fn check_which_pressed() {
            let mut app = App::new();
            app.add_plugins((InputPlugin, AccumulatorPlugin, CentralInputStorePlugin));
            app.init_resource::<AccumulatedMouseMovement>();
            app.init_resource::<AccumulatedMouseScroll>();
            let input_map = test_input_map();

            Digit1.press(app.world_mut());
            Digit2.press(app.world_mut());
            ControlLeft.press(app.world_mut());
            app.update();

            let input_store = app.world().resource::<CentralInputStore>();

            let action_data = input_map.process_actions(
                &Gamepads::default(),
                input_store,
                ClashStrategy::PrioritizeLongest,
            );

            for (action, &updated_value) in action_data.iter() {
                if *action == CtrlOne || *action == OneAndTwo {
                    assert_eq!(updated_value, UpdatedValue::Button(true));
                } else {
                    match updated_value {
                        UpdatedValue::Button(pressed) => assert!(!pressed),
                        UpdatedValue::Axis(value) => assert_eq!(value, 0.0),
                        UpdatedValue::DualAxis(pair) => assert_eq!(pair, Vec2::ZERO),
                        UpdatedValue::TripleAxis(triple) => assert_eq!(triple, Vec3::ZERO),
                    }
                }
            }
        }
    }
}