xref: /Held/src/utils/input.rs (revision 984a200e159c143eb730a2df362731fe1a62fe01)
1 use std::io::{self, Read};
2 
3 pub struct Input;
4 
5 impl Input {
6     pub fn wait_keydown() -> io::Result<KeyEventType> {
7         let buf: &mut [u8] = &mut [0; 8];
8         let count = io::stdin().read(buf)?;
9         Ok(KeyCodeParser::parse(&buf[0..count]))
10     }
11 }
12 
13 struct KeyCodeParser;
14 
15 impl KeyCodeParser {
16     pub fn parse(bytes: &[u8]) -> KeyEventType {
17         if bytes[0] == 224 {
18             // 控制字符
19             return Self::parse_ctrl(&bytes[1..]);
20         }
21         match bytes {
22             // Enter key
23             b"\n" => KeyEventType::Enter,
24             // Tab key
25             b"\t" => KeyEventType::Tab,
26             // Esc
27             [0] => KeyEventType::Esc,
28 
29             [8] => KeyEventType::Backspace,
30 
31             // ASCII 字符
32             [byte] if *byte >= 32 && *byte <= 126 => KeyEventType::Common(bytes[0]),
33             // Unknown bytes
34             bytes => {
35                 error!("unknown bytes {bytes:?}");
36                 KeyEventType::Unknown(bytes.to_vec())
37             }
38         }
39     }
40 
41     fn parse_ctrl(bytes: &[u8]) -> KeyEventType {
42         match bytes {
43             [72] => KeyEventType::Up,
44             [80] => KeyEventType::Down,
45             [75] => KeyEventType::Left,
46             [77] => KeyEventType::Right,
47             bytes => {
48                 error!("unknown ctrl bytes {bytes:?}");
49                 KeyEventType::Unknown(bytes.to_vec())
50             }
51         }
52     }
53 }
54 
55 #[derive(Debug, Clone)]
56 pub enum KeyEventType {
57     Common(u8),
58 
59     Up,
60     Down,
61     Right,
62     Left,
63 
64     Enter,
65     Tab,
66     Backspace,
67 
68     Esc,
69 
70     Unknown(Vec<u8>),
71 }
72