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
use std::os::unix::prelude::AsRawFd;
use async_recursion::async_recursion;
use eyre::{eyre, Result};
use nix::poll::{poll, PollFd, PollFlags};
use nix::sys::termios;
use nix::sys::termios::InputFlags;
use nix::unistd::isatty;
use tokio::fs::File;
pub async fn next_keypress() -> Result<Keypress> {
let fd = if isatty(libc::STDIN_FILENO)? {
libc::STDIN_FILENO
} else {
File::open("/dev/tty").await?.as_raw_fd()
};
let original_termios = termios::tcgetattr(fd)?;
let mut termios = original_termios.clone();
termios.input_flags &= !(InputFlags::IGNBRK
| InputFlags::BRKINT
| InputFlags::PARMRK
| InputFlags::ISTRIP
| InputFlags::INLCR
| InputFlags::IGNCR
| InputFlags::ICRNL
| InputFlags::IXON);
termios.local_flags &= !(termios::LocalFlags::ECHO
| termios::LocalFlags::ECHONL
| termios::LocalFlags::ICANON
| termios::LocalFlags::ISIG
| termios::LocalFlags::IEXTEN);
termios::tcsetattr(fd, termios::SetArg::TCSADRAIN, &termios)?;
let out = read_next_key(fd).await;
termios::tcsetattr(fd, termios::SetArg::TCSADRAIN, &original_termios)?;
out
}
#[async_recursion]
async fn read_next_key(fd: std::os::unix::io::RawFd) -> Result<Keypress> {
match read_char(fd)? {
Some('\x1b') => match read_char(fd)? {
Some('[') => match read_char(fd)? {
Some('A') => Ok(Keypress::Up),
Some('B') => Ok(Keypress::Down),
Some('C') => Ok(Keypress::Right),
Some('D') => Ok(Keypress::Left),
Some('H') => Ok(Keypress::Home),
Some('F') => Ok(Keypress::End),
Some('Z') => Ok(Keypress::ShiftTab),
Some(byte3) => match read_char(fd)? {
Some('~') => match read_char(fd)? {
Some('1') => Ok(Keypress::Home),
Some('2') => Ok(Keypress::Insert),
Some('3') => Ok(Keypress::Delete),
Some('4') => Ok(Keypress::End),
Some('5') => Ok(Keypress::PageUp),
Some('6') => Ok(Keypress::PageDown),
Some('7') => Ok(Keypress::Home),
Some('8') => Ok(Keypress::End),
Some(byte5) => Ok(Keypress::UnknownSequence(vec![
'\x1b', '[', byte3, '~', byte5,
])),
None => Ok(Keypress::UnknownSequence(vec!['\x1b', '[', byte3, '~'])),
},
Some(byte4) => Ok(Keypress::UnknownSequence(vec!['\x1b', '[', byte3, byte4])),
None => Ok(Keypress::UnknownSequence(vec!['\x1b', '[', byte3])),
},
None => Ok(Keypress::Escape),
},
Some(byte) => Ok(Keypress::UnknownSequence(vec!['\x1b', byte])),
None => Ok(Keypress::Escape),
},
Some('\r') | Some('\n') => Ok(Keypress::Return),
Some('\t') => Ok(Keypress::Tab),
Some('\x7f') => Ok(Keypress::Backspace),
Some('\x01') => Ok(Keypress::Home),
Some('\x03') => Err(ConsoleError::Interrupted.into()),
Some('\x05') => Ok(Keypress::End),
Some('\x08') => Ok(Keypress::Backspace),
Some(byte) => {
if (byte as u8) & 224u8 == 192u8 {
let bytes = vec![byte as u8, read_byte(fd)?.unwrap()];
Ok(Keypress::Char(char_from_utf8(&bytes)?))
} else if (byte as u8) & 240u8 == 224u8 {
let bytes: Vec<u8> =
vec![byte as u8, read_byte(fd)?.unwrap(), read_byte(fd)?.unwrap()];
Ok(Keypress::Char(char_from_utf8(&bytes)?))
} else if (byte as u8) & 248u8 == 240u8 {
let bytes: Vec<u8> = vec![
byte as u8,
read_byte(fd)?.unwrap(),
read_byte(fd)?.unwrap(),
read_byte(fd)?.unwrap(),
];
Ok(Keypress::Char(char_from_utf8(&bytes)?))
} else {
Ok(Keypress::Char(byte))
}
}
None => {
let pollfd = PollFd::new(fd, PollFlags::POLLIN);
let ret = poll(&mut [pollfd], 0)?;
if ret < 0 {
let last_error = std::io::Error::last_os_error();
if last_error.kind() == std::io::ErrorKind::Interrupted {
return Err(ConsoleError::Interrupted.into());
} else {
return Err(ConsoleError::Io(last_error).into());
}
}
read_next_key(fd).await
}
}
}
fn read_byte(fd: std::os::unix::io::RawFd) -> Result<Option<u8>> {
let mut buf = [0u8; 1];
match nix::unistd::read(fd, &mut buf) {
Ok(0) => Ok(None),
Ok(_) => Ok(Some(buf[0])),
Err(err) => Err(err.into()),
}
}
fn read_char(fd: std::os::unix::io::RawFd) -> Result<Option<char>> {
read_byte(fd).map(|byte| byte.map(|byte| byte as char))
}
fn char_from_utf8(buf: &[u8]) -> Result<char> {
let str = std::str::from_utf8(buf)?;
let ch = str.chars().next();
match ch {
Some(c) => Ok(c),
None => Err(eyre!("invalid utf8 sequence: {:?}", buf)),
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Keypress {
Up,
Down,
Right,
Left,
Home,
End,
ShiftTab,
Insert,
Delete,
PageUp,
PageDown,
Return,
Tab,
Backspace,
Escape,
Char(char),
UnknownSequence(Vec<char>),
}
#[derive(thiserror::Error, Debug)]
pub enum ConsoleError {
#[error("Interrupted!")]
Interrupted,
#[error("IO error: {0}")]
Io(#[from] std::io::Error),
}