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
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
use crate::console::{ClearType, Console, Key, Position};
use async_trait::async_trait;
use crossterm::{cursor, event, execute, style, terminal, tty::IsTty, QueueableCommand};
use std::cmp::Ordering;
use std::collections::VecDeque;
use std::env;
use std::io::{self, Write};
fn crossterm_error_to_io_error(e: crossterm::ErrorKind) -> io::Error {
match e {
crossterm::ErrorKind::IoError(e) => e,
crossterm::ErrorKind::Utf8Error(e) => {
io::Error::new(io::ErrorKind::InvalidData, format!("{}", e))
}
_ => io::Error::new(io::ErrorKind::Other, format!("{}", e)),
}
}
fn get_env_var_as_usize(name: &str) -> Option<usize> {
match env::var_os(name) {
Some(value) => {
value.as_os_str().to_string_lossy().parse::<usize>().map(Some).unwrap_or(None)
}
None => None,
}
}
pub struct TerminalConsole {
is_tty: bool,
buffer: VecDeque<Key>,
need_line_flush: bool,
}
impl Drop for TerminalConsole {
fn drop(&mut self) {
if self.is_tty {
terminal::disable_raw_mode().unwrap();
}
}
}
impl TerminalConsole {
pub fn from_stdio() -> io::Result<Self> {
let is_tty = io::stdin().is_tty() && io::stdout().is_tty();
if is_tty {
terminal::enable_raw_mode().map_err(crossterm_error_to_io_error)?;
}
Ok(Self { is_tty, buffer: VecDeque::default(), need_line_flush: false })
}
fn line_to_keys(s: String) -> VecDeque<Key> {
let mut keys = VecDeque::default();
for ch in s.chars() {
if ch == '\x1b' {
keys.push_back(Key::Escape);
} else if ch == '\n' {
keys.push_back(Key::NewLine);
} else if ch == '\r' {
} else if !ch.is_control() {
keys.push_back(Key::Char(ch));
} else {
keys.push_back(Key::Unknown(format!("{}", ch)));
}
}
keys
}
fn read_key_from_stdin(&mut self) -> io::Result<Key> {
if self.buffer.is_empty() {
let mut line = String::new();
if io::stdin().read_line(&mut line)? == 0 {
return Ok(Key::Eof);
}
self.buffer = TerminalConsole::line_to_keys(line);
}
match self.buffer.pop_front() {
Some(key) => Ok(key),
None => Ok(Key::Eof),
}
}
fn read_key_from_tty(&mut self) -> io::Result<Key> {
loop {
if let event::Event::Key(ev) = event::read().map_err(crossterm_error_to_io_error)? {
match ev.code {
event::KeyCode::Backspace => return Ok(Key::Backspace),
event::KeyCode::Esc => return Ok(Key::Escape),
event::KeyCode::Up => return Ok(Key::ArrowUp),
event::KeyCode::Down => return Ok(Key::ArrowDown),
event::KeyCode::Left => return Ok(Key::ArrowLeft),
event::KeyCode::Right => return Ok(Key::ArrowRight),
event::KeyCode::Char('c') if ev.modifiers == event::KeyModifiers::CONTROL => {
return Ok(Key::Interrupt)
}
event::KeyCode::Char('d') if ev.modifiers == event::KeyModifiers::CONTROL => {
return Ok(Key::Eof)
}
event::KeyCode::Char('j') if ev.modifiers == event::KeyModifiers::CONTROL => {
return Ok(Key::NewLine)
}
event::KeyCode::Char('m') if ev.modifiers == event::KeyModifiers::CONTROL => {
return Ok(Key::NewLine)
}
event::KeyCode::Char(ch) => return Ok(Key::Char(ch)),
event::KeyCode::Enter => return Ok(Key::NewLine),
_ => return Ok(Key::Unknown(format!("{:?}", ev))),
}
}
}
}
}
#[async_trait(?Send)]
impl Console for TerminalConsole {
fn clear(&mut self, how: ClearType) -> io::Result<()> {
let how = match how {
ClearType::All => terminal::ClearType::All,
ClearType::CurrentLine => terminal::ClearType::CurrentLine,
ClearType::UntilNewLine => terminal::ClearType::UntilNewLine,
};
let mut output = io::stdout();
output.queue(terminal::Clear(how)).map_err(crossterm_error_to_io_error)?;
if how == terminal::ClearType::All {
output.queue(cursor::MoveTo(0, 0)).map_err(crossterm_error_to_io_error)?;
}
output.flush()
}
fn color(&mut self, fg: Option<u8>, bg: Option<u8>) -> io::Result<()> {
let mut output = io::stdout();
let fg = match fg {
None => style::Color::Reset,
Some(color) => style::Color::AnsiValue(color),
};
let bg = match bg {
None => style::Color::Reset,
Some(color) => style::Color::AnsiValue(color),
};
output.queue(style::SetForegroundColor(fg)).map_err(crossterm_error_to_io_error)?;
output.queue(style::SetBackgroundColor(bg)).map_err(crossterm_error_to_io_error)?;
output.flush()?;
self.need_line_flush = bg != style::Color::Reset;
Ok(())
}
fn enter_alt(&mut self) -> io::Result<()> {
execute!(io::stdout(), terminal::EnterAlternateScreen).map_err(crossterm_error_to_io_error)
}
fn hide_cursor(&mut self) -> io::Result<()> {
execute!(io::stdout(), cursor::Hide).map_err(crossterm_error_to_io_error)
}
fn is_interactive(&self) -> bool {
self.is_tty
}
fn leave_alt(&mut self) -> io::Result<()> {
execute!(io::stdout(), terminal::LeaveAlternateScreen).map_err(crossterm_error_to_io_error)
}
fn locate(&mut self, pos: Position) -> io::Result<()> {
if pos.row > std::u16::MAX as usize {
return Err(io::Error::new(io::ErrorKind::Other, "Row out of range"));
}
let row = pos.row as u16;
if pos.column > std::u16::MAX as usize {
return Err(io::Error::new(io::ErrorKind::Other, "Column out of range"));
}
let column = pos.column as u16;
execute!(io::stdout(), cursor::MoveTo(column, row)).map_err(crossterm_error_to_io_error)
}
fn move_within_line(&mut self, off: i16) -> io::Result<()> {
match off.cmp(&0) {
Ordering::Less => execute!(io::stdout(), cursor::MoveLeft(-off as u16)),
Ordering::Equal => Ok(()),
Ordering::Greater => execute!(io::stdout(), cursor::MoveRight(off as u16)),
}
.map_err(crossterm_error_to_io_error)
}
fn print(&mut self, text: &str) -> io::Result<()> {
let stdout = io::stdout();
let mut stdout = stdout.lock();
stdout.write_all(text.as_bytes())?;
if self.need_line_flush {
execute!(stdout, terminal::Clear(terminal::ClearType::UntilNewLine))
.map_err(crossterm_error_to_io_error)?;
}
if self.is_tty {
stdout.write_all(b"\r\n")?;
} else {
stdout.write_all(b"\n")?;
}
Ok(())
}
async fn read_key(&mut self) -> io::Result<Key> {
if self.is_tty {
self.read_key_from_tty()
} else {
self.read_key_from_stdin()
}
}
fn show_cursor(&mut self) -> io::Result<()> {
execute!(io::stdout(), cursor::Show).map_err(crossterm_error_to_io_error)
}
fn size(&self) -> io::Result<Position> {
let lines = get_env_var_as_usize("LINES");
let columns = get_env_var_as_usize("COLUMNS");
let size = match (lines, columns) {
(Some(l), Some(c)) => Position { row: l, column: c },
(l, c) => {
let (actual_columns, actual_lines) =
terminal::size().map_err(crossterm_error_to_io_error)?;
Position {
row: l.unwrap_or(actual_lines as usize),
column: c.unwrap_or(actual_columns as usize),
}
}
};
Ok(size)
}
fn write(&mut self, bytes: &[u8]) -> io::Result<()> {
let stdout = io::stdout();
let mut stdout = stdout.lock();
stdout.write_all(bytes)?;
stdout.flush()
}
}