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
//! Handles clashing inputs into a [`InputMap`](crate::input_map::InputMap) in a configurable fashion.

use crate::action_state::ActionData;
use crate::input_map::InputMap;
use crate::user_input::{InputButton, InputStreams, UserInput};
use crate::Actionlike;

use itertools::Itertools;
use petitset::PetitSet;
use serde::{Deserialize, Serialize};
use std::cmp::Ordering;
use std::marker::PhantomData;

/// How should clashing inputs by handled by an [`InputMap`]?
///
/// Inputs "clash" if and only if one [`UserInput`] is a strict subset of the other.
/// By example:
///
/// - `S` and `W`: does not clash
/// - `LControl + S` and `S`: clashes
/// - `S` and `S`: does not clash
/// - `LControl + S` and ` LAlt + S`: clashes
/// - `LControl + S`, `LAlt + S` and `LControl + LAlt + S`: clashes
///
/// This strategy is only used when assessing the actions and input holistically,
/// in [`InputMap::which_pressed`], using [`InputMap::handle_clashes`].
#[non_exhaustive]
#[derive(Clone, Copy, PartialEq, Eq, Debug, Serialize, Deserialize)]
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.
    PrioritizeLongest,
    /// Use the order in which actions are defined in the enum to resolve clashing inputs
    ///
    /// Uses the iteration order returned by [`Actionlike::variants()`],
    /// which is generated in order of the enum items by the `#[derive(Actionlike)]` macro.
    UseActionOrder,
}

impl Default for ClashStrategy {
    fn default() -> Self {
        ClashStrategy::PrioritizeLongest
    }
}

impl UserInput {
    /// Does `self` clash with `other`?
    #[must_use]
    fn clashes(&self, other: &UserInput) -> bool {
        use UserInput::*;

        match self {
            Single(self_button) => match other {
                Single(_) => false,
                Chord(other_set) => button_chord_clash(self_button, other_set),
            },
            Chord(self_set) => match other {
                Single(other_button) => button_chord_clash(other_button, self_set),
                Chord(other_set) => chord_chord_clash(self_set, other_set),
            },
        }
    }
}

impl<A: Actionlike> InputMap<A> {
    /// Resolve clashing inputs, removing action presses that have been overruled
    ///
    /// The `usize` stored in `pressed_actions` corresponds to `Actionlike::index`
    pub fn handle_clashes(
        &self,
        action_data: &mut [ActionData],
        input_streams: &InputStreams,
        clash_strategy: ClashStrategy,
    ) {
        for clash in self.get_clashes(action_data, input_streams) {
            // Remove the action in the pair that was overruled, if any
            if let Some(culled_action) = resolve_clash(&clash, clash_strategy, input_streams) {
                action_data[culled_action.index()] = ActionData::default();
            }
        }
    }

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

        for action_pair in A::variants().combinations(2) {
            let action_a = action_pair.get(0).unwrap().clone();
            let action_b = action_pair.get(1).unwrap().clone();

            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`]s for each clashing set
    #[must_use]
    fn get_clashes(
        &self,
        action_data: &[ActionData],
        input_streams: &InputStreams,
    ) -> 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() {
            // Clashes can only occur if both actions were triggered
            // This is not strictly necessary, but saves work
            if action_data[clash.index_a].state.pressed()
                && action_data[clash.index_b].state.pressed()
            {
                // Check if the potential clash occured based on the pressed inputs
                if let Some(clash) = check_clash(&clash, input_streams) {
                    clashes.push(clash)
                }
            }
        }

        clashes
    }

    /// If the pair of actions could clash, how?
    #[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(action_a).iter() {
            for input_b in self.get(action_b.clone()).iter() {
                if input_a.clashes(input_b) {
                    clash.inputs_a.push(input_a.clone());
                    clash.inputs_b.push(input_b.clone());
                }
            }
        }

        if !clash.inputs_a.is_empty() {
            Some(clash)
        } else {
            None
        }
    }
}

/// 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> {
    /// The `Actionlike::index` value corresponding to `action_a`
    index_a: usize,
    /// The `Actionlike::index` value corresponding to `action_b`
    index_b: usize,
    inputs_a: Vec<UserInput>,
    inputs_b: Vec<UserInput>,
    _phantom: PhantomData<A>,
}

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 {
            index_a: action_a.index(),
            index_b: action_b.index(),
            inputs_a: Vec::default(),
            inputs_b: Vec::default(),
            _phantom: PhantomData::default(),
        }
    }

    /// Creates a new clash between the two actions based on their `Actionlike::index` indexes
    #[must_use]
    fn from_indexes(index_a: usize, index_b: usize) -> Self {
        Self {
            index_a,
            index_b,
            inputs_a: Vec::default(),
            inputs_b: Vec::default(),
            _phantom: PhantomData::default(),
        }
    }
}

/// Does the `button` clash with the `chord`?
#[must_use]
fn button_chord_clash(button: &InputButton, chord: &PetitSet<InputButton, 8>) -> bool {
    if chord.len() <= 1 {
        return false;
    }

    chord.contains(button)
}

/// Does the `chord_a` clash with `chord_b`?
#[must_use]
fn chord_chord_clash(
    chord_a: &PetitSet<InputButton, 8>,
    chord_b: &PetitSet<InputButton, 8>,
) -> bool {
    if chord_a.len() <= 1 || chord_b.len() <= 1 {
        return false;
    }

    if chord_a == chord_b {
        return false;
    }

    chord_a.is_subset(chord_b) || chord_b.is_subset(chord_a)
}

/// Given the `input_streams`, 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_streams: &InputStreams) -> Option<Clash<A>> {
    let mut actual_clash: Clash<A> = Clash::from_indexes(clash.index_a, clash.index_b);

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

    if !clash.inputs_a.is_empty() {
        Some(actual_clash)
    } else {
        None
    }
}

/// 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_streams: &InputStreams,
) -> Option<A> {
    // Figure out why the actions are pressed
    let reasons_a_is_pressed: Vec<&UserInput> = clash
        .inputs_a
        .iter()
        .filter(|&input| input_streams.input_pressed(input))
        .collect();

    let reasons_b_is_pressed: Vec<&UserInput> = clash
        .inputs_b
        .iter()
        .filter(|&input| input_streams.input_pressed(input))
        .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.clashes(reason_b) {
                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.len())
                .reduce(|a, b| a.max(b))
                .unwrap_or_default();

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

            match longest_a.cmp(&longest_b) {
                Ordering::Greater => Some(A::get_at(clash.index_b).unwrap()),
                Ordering::Less => Some(A::get_at(clash.index_a).unwrap()),
                Ordering::Equal => None,
            }
        } // Remove the clashing action that comes later in the action enum
        ClashStrategy::UseActionOrder => match clash.index_a.cmp(&clash.index_b) {
            Ordering::Greater => Some(A::get_at(clash.index_a).unwrap()),
            Ordering::Less => Some(A::get_at(clash.index_b).unwrap()),
            Ordering::Equal => None,
        },
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate as leafwing_input_manager;
    use crate::Actionlike;
    use bevy_input::keyboard::KeyCode::*;

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

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

        let mut input_map = InputMap::default();

        input_map.insert(One, Key1);
        input_map.insert(Two, Key2);
        input_map.insert_chord(OneAndTwo, [Key1, Key2]);
        input_map.insert_chord(TwoAndThree, [Key2, Key3]);
        input_map.insert_chord(OneAndTwoAndThree, [Key1, Key2, Key3]);
        input_map.insert_chord(CtrlOne, [LControl, Key1]);
        input_map.insert_chord(AltOne, [LAlt, Key1]);
        input_map.insert_chord(CtrlAltOne, [LControl, LAlt, Key1]);

        input_map
    }

    mod basic_functionality {
        use super::*;

        #[test]
        fn clash_detection() {
            let a: UserInput = A.into();
            let b: UserInput = B.into();
            let c: UserInput = C.into();
            let ab = UserInput::chord([A, B]);
            let bc = UserInput::chord([B, C]);
            let abc = UserInput::chord([A, B, C]);

            assert!(!a.clashes(&b));
            assert!(a.clashes(&ab));
            assert!(!c.clashes(&ab));
            assert!(!ab.clashes(&bc));
            assert!(ab.clashes(&abc))
        }

        #[test]
        fn button_chord_clash_construction() {
            use Action::*;

            let input_map = test_input_map();

            let observed_clash = input_map.possible_clash(One, OneAndTwo).unwrap();
            let correct_clash = Clash {
                index_a: One.index(),
                index_b: OneAndTwo.index(),
                inputs_a: vec![Key1.into()],
                inputs_b: vec![UserInput::chord([Key1, Key2])],
                _phantom: PhantomData::default(),
            };

            assert_eq!(observed_clash, correct_clash);
        }

        #[test]
        fn chord_chord_clash_construction() {
            use Action::*;

            let input_map = test_input_map();

            let observed_clash = input_map
                .possible_clash(OneAndTwoAndThree, OneAndTwo)
                .unwrap();
            let correct_clash = Clash {
                index_a: OneAndTwoAndThree.index(),
                index_b: OneAndTwo.index(),
                inputs_a: vec![UserInput::chord([Key1, Key2, Key3])],
                inputs_b: vec![UserInput::chord([Key1, Key2])],
                _phantom: PhantomData::default(),
            };

            assert_eq!(observed_clash, correct_clash);
        }

        #[test]
        fn can_clash() {
            use Action::*;

            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 clash_caching() {
            let mut input_map = test_input_map();
            // Possible clashes are cached upon initialization
            assert_eq!(input_map.possible_clashes().len(), 12);

            // Possible clashes are cached upon binding insertion
            input_map.insert(Action::Two, UserInput::chord([LControl, LAlt, Key1]));
            assert_eq!(input_map.possible_clashes().len(), 15);

            // Possible clashes are cached upon binding removal
            input_map.clear_action(Action::One);
            assert_eq!(input_map.possible_clashes().len(), 9);
        }

        #[test]
        fn resolve_prioritize_longest() {
            use bevy::prelude::*;
            use Action::*;

            let input_map = test_input_map();
            let simple_clash = input_map.possible_clash(One, OneAndTwo).unwrap();
            let mut keyboard: Input<KeyCode> = Default::default();
            keyboard.press(Key1);
            keyboard.press(Key2);

            let input_streams = InputStreams::from_keyboard(&keyboard);

            assert_eq!(
                resolve_clash(
                    &simple_clash,
                    ClashStrategy::PrioritizeLongest,
                    &input_streams,
                ),
                Some(One)
            );

            let reversed_clash = input_map.possible_clash(OneAndTwo, One).unwrap();
            assert_eq!(
                resolve_clash(
                    &reversed_clash,
                    ClashStrategy::PrioritizeLongest,
                    &input_streams,
                ),
                Some(One)
            );

            let chord_clash = input_map
                .possible_clash(OneAndTwo, OneAndTwoAndThree)
                .unwrap();
            keyboard.press(Key3);

            let input_streams = InputStreams::from_keyboard(&keyboard);

            assert_eq!(
                resolve_clash(
                    &chord_clash,
                    ClashStrategy::PrioritizeLongest,
                    &input_streams,
                ),
                Some(OneAndTwo)
            );
        }

        #[test]
        fn resolve_use_action_order() {
            use bevy::prelude::*;
            use Action::*;

            let input_map = test_input_map();
            let simple_clash = input_map.possible_clash(One, CtrlOne).unwrap();
            let reversed_clash = input_map.possible_clash(CtrlOne, One).unwrap();
            let mut keyboard: Input<KeyCode> = Default::default();
            keyboard.press(Key1);
            keyboard.press(LControl);

            let input_streams = InputStreams::from_keyboard(&keyboard);

            assert_eq!(
                resolve_clash(&simple_clash, ClashStrategy::UseActionOrder, &input_streams,),
                Some(CtrlOne)
            );

            assert_eq!(
                resolve_clash(
                    &reversed_clash,
                    ClashStrategy::UseActionOrder,
                    &input_streams,
                ),
                Some(CtrlOne)
            );
        }

        #[test]
        fn handle_clashes() {
            use crate::buttonlike::ButtonState;
            use bevy::prelude::*;
            use Action::*;

            let input_map = test_input_map();

            let mut keyboard: Input<KeyCode> = Default::default();
            keyboard.press(Key1);
            keyboard.press(Key2);

            let mut action_data = vec![ActionData::default(); Action::N_VARIANTS];
            action_data[One.index()].state = ButtonState::JustPressed;
            action_data[Two.index()].state = ButtonState::JustPressed;
            action_data[OneAndTwo.index()].state = ButtonState::JustPressed;

            input_map.handle_clashes(
                &mut action_data,
                &InputStreams::from_keyboard(&keyboard),
                ClashStrategy::PrioritizeLongest,
            );

            let mut expected = vec![ActionData::default(); Action::N_VARIANTS];
            expected[OneAndTwo.index()].state = ButtonState::JustPressed;

            assert_eq!(action_data, expected);
        }

        #[test]
        fn which_pressed() {
            use bevy::prelude::*;
            use Action::*;

            let input_map = test_input_map();

            let mut keyboard: Input<KeyCode> = Default::default();
            keyboard.press(Key1);
            keyboard.press(Key2);
            keyboard.press(LControl);

            let action_data = input_map.which_pressed(
                &InputStreams::from_keyboard(&keyboard),
                ClashStrategy::PrioritizeLongest,
            );

            for (i, action_data) in action_data.iter().enumerate() {
                if i == CtrlOne.index() || i == OneAndTwo.index() {
                    assert!(action_data.state.pressed());
                } else {
                    assert!(action_data.state.released());
                }
            }
        }
    }
}