1#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
2#[non_exhaustive]
3pub enum Key {
4 Char(char),
5 Ctrl(char),
6 Alt(char),
7 Tab,
8 BackTab,
9 Enter,
10 Esc,
11 Backspace,
12 Left,
13 Right,
14 Up,
15 Down,
16 Other,
17}
18
19#[cfg(feature = "crossterm")]
20impl From<crossterm::event::KeyEvent> for Key {
21 fn from(event: crossterm::event::KeyEvent) -> Self {
22 use crossterm::event::{KeyCode, KeyEventKind, KeyModifiers};
23 if event.kind == KeyEventKind::Release {
24 return Key::Other;
25 }
26 let modifiers = event.modifiers;
27 let control = modifiers.contains(KeyModifiers::CONTROL);
28 let alt = modifiers.contains(KeyModifiers::ALT);
29 let other =
30 modifiers.intersects(KeyModifiers::SUPER | KeyModifiers::HYPER | KeyModifiers::META);
31 match event.code {
32 KeyCode::Char(_) if other => Key::Other,
33 KeyCode::Char(c) if control && alt => Key::Char(c),
34 KeyCode::Char(c) if control => Key::Ctrl(c.to_ascii_lowercase()),
35 KeyCode::Char(c) if alt => Key::Alt(c),
36 KeyCode::Char(c) => Key::Char(c),
37 _ if other || alt => Key::Other,
38 KeyCode::Tab if event.modifiers.contains(KeyModifiers::SHIFT) => Key::BackTab,
39 KeyCode::Tab => Key::Tab,
40 KeyCode::BackTab => Key::BackTab,
41 KeyCode::Enter => Key::Enter,
42 KeyCode::Esc => Key::Esc,
43 KeyCode::Backspace => Key::Backspace,
44 KeyCode::Left => Key::Left,
45 KeyCode::Right => Key::Right,
46 KeyCode::Up => Key::Up,
47 KeyCode::Down => Key::Down,
48 _ => Key::Other,
49 }
50 }
51}