bevy_input_sequence/
chord.rs

1use bevy::{
2    input::keyboard::KeyCode,
3    prelude::{Deref, DerefMut, ReflectResource, Resource},
4    reflect::{Enum, Reflect},
5};
6
7use std::{collections::VecDeque, fmt};
8
9use keyseq::Modifiers;
10
11/// Represents a key chord, i.e., a set of modifiers and a key code.
12#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Reflect)]
13pub struct KeyChord(pub Modifiers, pub KeyCode);
14
15impl fmt::Display for KeyChord {
16    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
17        use KeyCode::*;
18        self.0.fmt(f)?;
19        if !self.0.is_empty() {
20            f.write_str("-")?;
21        }
22        let key_repr = match self.1 {
23            Semicolon => ";",
24            Period => ".",
25            Equal => "=",
26            Slash => "/",
27            Minus => "-",
28            BracketLeft => "[",
29            BracketRight => "]",
30            Quote => "'",
31            Backquote => "`",
32            key_code => {
33                let mut key = key_code.variant_name();
34                key = key.strip_prefix("Key").unwrap_or(key);
35                key = key.strip_prefix("Digit").unwrap_or(key);
36                return f.write_str(key);
37            }
38        };
39        f.write_str(key_repr)
40    }
41}
42
43impl From<(Modifiers, KeyCode)> for KeyChord {
44    #[inline(always)]
45    fn from((mods, key): (Modifiers, KeyCode)) -> Self {
46        KeyChord(mods, key)
47    }
48}
49
50impl From<KeyCode> for KeyChord {
51    #[inline(always)]
52    fn from(key: KeyCode) -> Self {
53        KeyChord(Modifiers::empty(), key)
54    }
55}
56
57pub(crate) fn is_modifier(key: KeyCode) -> bool {
58    !Modifiers::from(key).is_empty()
59}
60
61/// Manually add key chords to be processed as through they were pressed by the
62/// user.
63///
64/// Normally this does not need to be manipulated. It is a kind of escape hatch.
65#[derive(Resource, Debug, Deref, DerefMut, Default, Reflect)]
66#[reflect(Resource)]
67pub struct KeyChordQueue(pub VecDeque<KeyChord>);