Skip to main content

indigo_key/
key.rs

1use bitflags::bitflags;
2use std::{
3    fmt::{self, Display, Formatter},
4    hash::Hash,
5    str::FromStr,
6};
7use winnow::{
8    ascii::{multispace1, till_line_ending},
9    combinator::{alt, cut_err, delimited, fail, opt, preceded, repeat, terminated},
10    error::StrContext,
11    prelude::*,
12    token::one_of,
13};
14
15#[derive(Clone, Debug)]
16pub struct Keys<K = Vec<Key>>(pub K);
17
18impl FromStr for Keys {
19    type Err = anyhow::Error;
20    fn from_str(s: &str) -> Result<Self, Self::Err> {
21        keys.parse(s).map_err(|e| anyhow::format_err!("{e}"))
22    }
23}
24
25impl<K: AsRef<[Key]>> Display for Keys<K> {
26    fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), fmt::Error> {
27        for key in self.0.as_ref() {
28            write!(f, "{key}")?;
29        }
30        Ok(())
31    }
32}
33
34fn comment(input: &mut &str) -> ModalResult<()> {
35    ('#', till_line_ending).void().parse_next(input)
36}
37
38fn not_key(input: &mut &str) -> ModalResult<()> {
39    repeat(0.., alt((multispace1.void(), comment))).parse_next(input)
40}
41
42fn keys(input: &mut &str) -> ModalResult<Keys> {
43    not_key.parse_next(input)?;
44    repeat(0.., terminated(key, not_key))
45        .map(Keys)
46        .parse_next(input)
47}
48
49#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
50pub struct Key {
51    pub modifiers: KeyModifiers,
52    pub code: KeyCode,
53}
54
55impl Key {
56    pub const ANY: Self = Self {
57        modifiers: KeyModifiers::empty(),
58        code: KeyCode::Any,
59    };
60
61    pub fn normalize(&mut self) {
62        if !self.modifiers.contains(KeyModifiers::SHIFT) {
63            return;
64        }
65        if let KeyCode::Char(c @ (b'a'..=b'z' | b'A'..=b'Z')) = self.code {
66            self.modifiers.remove(KeyModifiers::SHIFT);
67            self.code = KeyCode::Char(c.to_ascii_uppercase());
68        }
69    }
70
71    #[must_use]
72    pub fn typed_char(&self) -> Option<u8> {
73        if let KeyCode::Char(c) = self.code
74            && self.modifiers.difference(KeyModifiers::SHIFT).is_empty()
75        {
76            Some(c)
77        } else {
78            None
79        }
80    }
81}
82
83impl FromStr for Key {
84    type Err = anyhow::Error;
85    fn from_str(s: &str) -> Result<Self, Self::Err> {
86        key.parse(s).map_err(|e| anyhow::format_err!("{e}"))
87    }
88}
89
90impl Display for Key {
91    fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), fmt::Error> {
92        if self.modifiers.is_empty()
93            && let KeyCode::Char(_) = self.code
94        {
95            write!(f, "{}", self.code)?;
96        } else {
97            write!(f, "<{}{}>", self.modifiers, self.code)?;
98        }
99        Ok(())
100    }
101}
102
103fn key(input: &mut &str) -> ModalResult<Key> {
104    alt((key_wrapped, key_bare_unmodified)).parse_next(input)
105}
106
107fn key_wrapped(input: &mut &str) -> ModalResult<Key> {
108    let k = |input: &mut &str| {
109        let modifiers = key_modifiers
110            .context(StrContext::Label("key modifiers"))
111            .parse_next(input)?;
112        let allow_bare = !modifiers.is_empty();
113        let code = alt((key_code_wrapped, key_code_bare.verify(|_| allow_bare)))
114            .verify(|code| modifiers.is_empty() || *code != KeyCode::Any)
115            // Shift is expressed by the character itself (`A`, not `<s-a>`), except for space,
116            // which shift doesn't change.
117            .verify(|code| {
118                !(modifiers.contains(KeyModifiers::SHIFT)
119                    && matches!(code, KeyCode::Char(c) if *c != b' '))
120            })
121            .context(StrContext::Label("key code"))
122            .parse_next(input)?;
123        Ok(Key { modifiers, code })
124    };
125    delimited("<", cut_err(k), ">").parse_next(input)
126}
127
128fn key_bare_unmodified(input: &mut &str) -> ModalResult<Key> {
129    let modifiers = KeyModifiers::empty();
130    let code = key_code_bare.parse_next(input)?;
131    Ok(Key { modifiers, code })
132}
133
134bitflags! {
135    #[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
136    pub struct KeyModifiers: u8 {
137        const CONTROL = 1 << 0;
138        const ALT = 1 << 1;
139        const SHIFT = 1 << 2;
140    }
141}
142
143impl FromStr for KeyModifiers {
144    type Err = anyhow::Error;
145    fn from_str(s: &str) -> Result<Self, Self::Err> {
146        key_modifiers
147            .parse(s)
148            .map_err(|e| anyhow::format_err!("{e}"))
149    }
150}
151
152impl Display for KeyModifiers {
153    fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), fmt::Error> {
154        if self.contains(Self::CONTROL) {
155            write!(f, "c-")?;
156        }
157        if self.contains(Self::ALT) {
158            write!(f, "a-")?;
159        }
160        if self.contains(Self::SHIFT) {
161            write!(f, "s-")?;
162        }
163        Ok(())
164    }
165}
166
167fn key_modifiers(input: &mut &str) -> ModalResult<KeyModifiers> {
168    let mut modifiers = KeyModifiers::empty();
169    while !modifiers.is_all() {
170        let Some(modifier) = opt(alt((
171            "c-".value(KeyModifiers::CONTROL),
172            "a-".value(KeyModifiers::ALT),
173            "s-".value(KeyModifiers::SHIFT),
174        )))
175        .parse_next(input)?
176        else {
177            break;
178        };
179        if modifiers.contains(modifier) {
180            return fail.parse_next(input);
181        }
182        modifiers.insert(modifier);
183    }
184    Ok(modifiers)
185}
186
187#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
188pub enum KeyCode {
189    Backspace,
190    Delete,
191    Return,
192    Left,
193    Right,
194    Up,
195    Down,
196    Tab,
197    Escape,
198    // NOTE: Replace `u8` with `AsciiChar` once it stabilizes.
199    // https://github.com/rust-lang/rust/issues/110998
200    Char(u8),
201    /// <https://en.wikipedia.org/wiki/Any_key>
202    Any,
203}
204
205impl FromStr for KeyCode {
206    type Err = anyhow::Error;
207    fn from_str(s: &str) -> Result<Self, Self::Err> {
208        key_code.parse(s).map_err(|e| anyhow::format_err!("{e}"))
209    }
210}
211
212impl Display for KeyCode {
213    fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), fmt::Error> {
214        match self {
215            Self::Backspace => write!(f, "bs")?,
216            Self::Delete => write!(f, "del")?,
217            Self::Return => write!(f, "ret")?,
218            Self::Left => write!(f, "left")?,
219            Self::Right => write!(f, "right")?,
220            Self::Up => write!(f, "up")?,
221            Self::Down => write!(f, "down")?,
222            Self::Tab => write!(f, "tab")?,
223            Self::Escape => write!(f, "esc")?,
224            Self::Char(b' ') => write!(f, "\\ ")?,
225            Self::Char(b'#') => write!(f, "\\#")?,
226            Self::Char(b'<') => write!(f, "\\<")?,
227            Self::Char(b'>') => write!(f, "\\>")?,
228            Self::Char(b'\\') => write!(f, "\\\\")?,
229            Self::Char(c) => write!(f, "{}", char::from(*c))?,
230            Self::Any => write!(f, "any")?,
231        }
232        Ok(())
233    }
234}
235
236fn key_code(input: &mut &str) -> ModalResult<KeyCode> {
237    alt((key_code_wrapped, key_code_bare)).parse_next(input)
238}
239
240fn key_code_wrapped(input: &mut &str) -> ModalResult<KeyCode> {
241    alt([
242        "bs".value(KeyCode::Backspace),
243        "del".value(KeyCode::Delete),
244        "ret".value(KeyCode::Return),
245        "left".value(KeyCode::Left),
246        "right".value(KeyCode::Right),
247        "up".value(KeyCode::Up),
248        "down".value(KeyCode::Down),
249        "tab".value(KeyCode::Tab),
250        "esc".value(KeyCode::Escape),
251        "any".value(KeyCode::Any),
252    ])
253    .parse_next(input)
254}
255
256fn key_code_bare(input: &mut &str) -> ModalResult<KeyCode> {
257    alt((
258        one_of(b' '..=b'~')
259            .verify(|c| !" #<>\\".contains(*c))
260            .map(|c| KeyCode::Char(u8::try_from(c).expect("Only parsing ASCII"))),
261        key_code_escaped,
262    ))
263    .parse_next(input)
264}
265
266fn key_code_escaped(input: &mut &str) -> ModalResult<KeyCode> {
267    preceded(
268        '\\',
269        cut_err(alt((
270            ' '.value(KeyCode::Char(b' ')),
271            '#'.value(KeyCode::Char(b'#')),
272            '<'.value(KeyCode::Char(b'<')),
273            '>'.value(KeyCode::Char(b'>')),
274            '\\'.value(KeyCode::Char(b'\\')),
275        ))),
276    )
277    .parse_next(input)
278}
279
280#[must_use]
281pub fn is(mut x: Key, y: &str) -> bool {
282    x.normalize();
283    let y = y.parse::<Key>().unwrap();
284    x == y
285}
286
287#[cfg(test)]
288mod tests {
289    use super::*;
290
291    #[test]
292    fn random() {
293        let input = "
294            # comment
295            # comment
296            abc a b c # comment
297
298            \\# \\\\ <s-\\ > <c-->
299
300            # comment
301            <c-a-del> <a-a> <tab> <s-tab> <a-esc>
302        ";
303        let expected = "abcabc\\#\\\\<s-\\ ><c--><c-a-del><a-a><tab><s-tab><a-esc>";
304        let actual = input.parse::<Keys>().unwrap().to_string();
305        assert_eq!(expected, actual);
306    }
307
308    #[test]
309    fn weird() {
310        assert_eq!("<c-->".parse::<Key>().unwrap().to_string(), "<c-->");
311        assert_eq!("<c-\\>>".parse::<Key>().unwrap().to_string(), "<c-\\>>");
312    }
313
314    #[test]
315    fn escaped() {
316        for key in ["\\ ", "\\#", "\\<", "\\>", "\\\\"] {
317            assert_eq!(key.parse::<Key>().unwrap().to_string(), key);
318        }
319        assert!("\\t".parse::<Key>().is_err());
320        assert!("\\n".parse::<Key>().is_err());
321        assert!("\\r".parse::<Key>().is_err());
322    }
323
324    #[test]
325    fn no_wrapped_bare() {
326        assert_eq!("a".parse::<Key>().unwrap().to_string(), "a");
327        assert!("<a>".parse::<Key>().is_err());
328    }
329
330    #[test]
331    fn modifier_ordering() {
332        assert_eq!(
333            "<c-a-s-tab>".parse::<Key>().unwrap().to_string(),
334            "<c-a-s-tab>"
335        );
336        assert_eq!("<s-c-tab>".parse::<Key>().unwrap().to_string(), "<c-s-tab>");
337        assert_eq!(
338            "<s-c-a-tab>".parse::<Key>().unwrap().to_string(),
339            "<c-a-s-tab>"
340        );
341        assert_eq!(
342            "<a-s-c-tab>".parse::<Key>().unwrap().to_string(),
343            "<c-a-s-tab>"
344        );
345    }
346
347    #[test]
348    fn no_shifted_chars() {
349        assert!("<s-a>".parse::<Key>().is_err());
350        assert!("<s-A>".parse::<Key>().is_err());
351        assert!("<c-s-a>".parse::<Key>().is_err());
352        assert!("<s-1>".parse::<Key>().is_err());
353        assert!("<s-\\#>".parse::<Key>().is_err());
354        assert!("<s-\\ >".parse::<Key>().is_ok());
355        assert!("<c-s-\\ >".parse::<Key>().is_ok());
356        assert!("<s-tab>".parse::<Key>().is_ok());
357    }
358
359    #[test]
360    fn no_duplicate_modifiers() {
361        assert!("<c-c-a>".parse::<Key>().is_err());
362        assert!("<s-c-a-c-a>".parse::<Key>().is_err());
363    }
364
365    #[test]
366    fn key_roundtrip() {
367        let mut codes: Vec<KeyCode> = (b' '..=b'~').map(KeyCode::Char).collect();
368        codes.extend([
369            KeyCode::Backspace,
370            KeyCode::Delete,
371            KeyCode::Return,
372            KeyCode::Left,
373            KeyCode::Right,
374            KeyCode::Up,
375            KeyCode::Down,
376            KeyCode::Tab,
377            KeyCode::Escape,
378        ]);
379        for bits in 0..=KeyModifiers::all().bits() {
380            let modifiers = KeyModifiers::from_bits_truncate(bits);
381            for &code in &codes {
382                let key = Key { modifiers, code };
383                if modifiers.contains(KeyModifiers::SHIFT)
384                    && matches!(code, KeyCode::Char(c) if c != b' ')
385                {
386                    assert!(key.to_string().parse::<Key>().is_err());
387                    continue;
388                }
389                match key.to_string().parse::<Key>() {
390                    Ok(parsed_key) => assert_eq!(key, parsed_key),
391                    Err(e) => panic!("Failed to parse `{key:?}` printed as `{key}`:\n{e}"),
392                }
393            }
394        }
395    }
396
397    #[test]
398    fn no_modified_any() {
399        assert_eq!("<any>".parse::<Key>().unwrap(), Key::ANY);
400        assert!("<a-any>".parse::<Key>().is_err());
401        assert!("<s-any>".parse::<Key>().is_err());
402    }
403
404    #[test]
405    fn normalize() {
406        let cases = [
407            (KeyModifiers::SHIFT, b'a', KeyModifiers::empty(), b'A'),
408            (KeyModifiers::SHIFT, b'Z', KeyModifiers::empty(), b'Z'),
409            (KeyModifiers::empty(), b'a', KeyModifiers::empty(), b'a'),
410            (KeyModifiers::SHIFT, b'1', KeyModifiers::SHIFT, b'1'),
411        ];
412
413        for (input_modifiers, input_code, expected_modifiers, expected_code) in cases {
414            let mut key = Key {
415                modifiers: input_modifiers,
416                code: KeyCode::Char(input_code),
417            };
418            key.normalize();
419            assert_eq!(key.modifiers, expected_modifiers);
420            assert_eq!(key.code, KeyCode::Char(expected_code));
421        }
422    }
423}