-
Notifications
You must be signed in to change notification settings - Fork 119
/
Copy pathunix_term.rs
649 lines (587 loc) · 21.2 KB
/
unix_term.rs
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
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
use std::env;
use std::fmt::Display;
use std::fs;
use std::io;
use std::io::{BufRead, BufReader};
use std::mem;
use std::os::unix::io::AsRawFd;
use std::os::unix::io::FromRawFd;
use std::os::unix::io::IntoRawFd;
use std::str;
use crate::kb::Key;
use crate::term::Term;
pub use crate::common_term::*;
pub const DEFAULT_WIDTH: u16 = 80;
#[inline]
pub fn is_a_terminal(out: &Term) -> bool {
unsafe { libc::isatty(out.as_raw_fd()) != 0 }
}
pub fn is_a_color_terminal(out: &Term) -> bool {
if !is_a_terminal(out) {
return false;
}
if env::var("NO_COLOR").is_ok() {
return false;
}
match env::var("TERM") {
Ok(term) => term != "dumb",
Err(_) => false,
}
}
pub fn c_result<F: FnOnce() -> libc::c_int>(f: F) -> io::Result<()> {
let res = f();
if res != 0 {
Err(io::Error::last_os_error())
} else {
Ok(())
}
}
pub fn terminal_size(out: &Term) -> Option<(u16, u16)> {
unsafe {
if libc::isatty(libc::STDOUT_FILENO) != 1 {
return None;
}
let mut winsize: libc::winsize = std::mem::zeroed();
// FIXME: ".into()" used as a temporary fix for a libc bug
// https://github.com/rust-lang/libc/pull/704
#[allow(clippy::useless_conversion)]
libc::ioctl(out.as_raw_fd(), libc::TIOCGWINSZ.into(), &mut winsize);
if winsize.ws_row > 0 && winsize.ws_col > 0 {
Some((winsize.ws_row as u16, winsize.ws_col as u16))
} else {
None
}
}
}
pub fn read_secure() -> io::Result<String> {
let f_tty;
let fd = unsafe {
if libc::isatty(libc::STDIN_FILENO) == 1 {
f_tty = None;
libc::STDIN_FILENO
} else {
let f = fs::OpenOptions::new()
.read(true)
.write(true)
.open("/dev/tty")?;
let fd = f.as_raw_fd();
f_tty = Some(BufReader::new(f));
fd
}
};
let mut termios = core::mem::MaybeUninit::uninit();
c_result(|| unsafe { libc::tcgetattr(fd, termios.as_mut_ptr()) })?;
let mut termios = unsafe { termios.assume_init() };
let original = termios;
termios.c_lflag &= !libc::ECHO;
c_result(|| unsafe { libc::tcsetattr(fd, libc::TCSAFLUSH, &termios) })?;
let mut rv = String::new();
let read_rv = if let Some(mut f) = f_tty {
f.read_line(&mut rv)
} else {
io::stdin().read_line(&mut rv)
};
c_result(|| unsafe { libc::tcsetattr(fd, libc::TCSAFLUSH, &original) })?;
read_rv.map(|_| {
let len = rv.trim_end_matches(&['\r', '\n'][..]).len();
rv.truncate(len);
rv
})
}
fn poll_fd(fd: i32, timeout: i32) -> io::Result<bool> {
let mut pollfd = libc::pollfd {
fd,
events: libc::POLLIN,
revents: 0,
};
let ret = unsafe { libc::poll(&mut pollfd as *mut _, 1, timeout) };
if ret < 0 {
Err(io::Error::last_os_error())
} else {
Ok(pollfd.revents & libc::POLLIN != 0)
}
}
#[cfg(target_os = "macos")]
fn select_fd(fd: i32, timeout: i32) -> io::Result<bool> {
unsafe {
let mut read_fd_set: libc::fd_set = mem::zeroed();
let mut timeout_val;
let timeout = if timeout < 0 {
ptr::null_mut()
} else {
timeout_val = libc::timeval {
tv_sec: (timeout / 1000) as _,
tv_usec: (timeout * 1000) as _,
};
&mut timeout_val
};
libc::FD_ZERO(&mut read_fd_set);
libc::FD_SET(fd, &mut read_fd_set);
let ret = libc::select(
fd + 1,
&mut read_fd_set,
ptr::null_mut(),
ptr::null_mut(),
timeout,
);
if ret < 0 {
Err(io::Error::last_os_error())
} else {
Ok(libc::FD_ISSET(fd, &read_fd_set))
}
}
}
fn select_or_poll_term_fd(fd: i32, timeout: i32) -> io::Result<bool> {
// There is a bug on macos that ttys cannot be polled, only select()
// works. However given how problematic select is in general, we
// normally want to use poll there too.
#[cfg(target_os = "macos")]
{
if unsafe { libc::isatty(fd) == 1 } {
return select_fd(fd, timeout);
}
}
poll_fd(fd, timeout)
}
fn read_single_char(fd: i32) -> io::Result<Option<char>> {
// timeout of zero means that it will not block
let is_ready = select_or_poll_term_fd(fd, 0)?;
if is_ready {
// if there is something to be read, take 1 byte from it
let mut buf: [u8; 1] = [0];
read_bytes(fd, &mut buf, 1)?;
Ok(Some(buf[0] as char))
} else {
//there is nothing to be read
Ok(None)
}
}
// Similar to libc::read. Read count bytes into slice buf from descriptor fd.
// If successful, return the number of bytes read.
// Will return an error if nothing was read, i.e when called at end of file.
fn read_bytes(fd: i32, buf: &mut [u8], count: u8) -> io::Result<u8> {
let read = unsafe { libc::read(fd, buf.as_mut_ptr() as *mut _, count as usize) };
if read < 0 {
Err(io::Error::last_os_error())
} else if read == 0 {
Err(io::Error::new(
io::ErrorKind::UnexpectedEof,
"Reached end of file",
))
} else if buf[0] == b'\x03' {
Err(io::Error::new(
io::ErrorKind::Interrupted,
"read interrupted",
))
} else {
Ok(read as u8)
}
}
fn read_single_key_impl(fd: i32) -> Result<Key, io::Error> {
loop {
match read_single_char(fd)? {
Some('\x1b') => {
// Escape was read, keep reading in case we find a familiar key
break if let Some(c1) = read_single_char(fd)? {
if c1 == '[' {
if let Some(c2) = read_single_char(fd)? {
match c2 {
'A' => Ok(Key::ArrowUp),
'B' => Ok(Key::ArrowDown),
'C' => Ok(Key::ArrowRight),
'D' => Ok(Key::ArrowLeft),
'H' => Ok(Key::Home),
'F' => Ok(Key::End),
'Z' => Ok(Key::BackTab),
_ => {
let c3 = read_single_char(fd)?;
if let Some(c3) = c3 {
if c3 == '~' {
match c2 {
'1' => Ok(Key::Home), // tmux
'2' => Ok(Key::Insert),
'3' => Ok(Key::Del),
'4' => Ok(Key::End), // tmux
'5' => Ok(Key::PageUp),
'6' => Ok(Key::PageDown),
'7' => Ok(Key::Home), // xrvt
'8' => Ok(Key::End), // xrvt
_ => Ok(Key::UnknownEscSeq(vec![c1, c2, c3])),
}
} else {
Ok(Key::UnknownEscSeq(vec![c1, c2, c3]))
}
} else {
// \x1b[ and 1 more char
Ok(Key::UnknownEscSeq(vec![c1, c2]))
}
}
}
} else {
// \x1b[ and no more input
Ok(Key::UnknownEscSeq(vec![c1]))
}
} else {
// char after escape is not [
Ok(Key::UnknownEscSeq(vec![c1]))
}
} else {
//nothing after escape
Ok(Key::Escape)
};
}
Some(c) => {
let byte = c as u8;
let mut buf: [u8; 4] = [byte, 0, 0, 0];
break if byte & 224u8 == 192u8 {
// a two byte unicode character
read_bytes(fd, &mut buf[1..], 1)?;
Ok(key_from_utf8(&buf[..2]))
} else if byte & 240u8 == 224u8 {
// a three byte unicode character
read_bytes(fd, &mut buf[1..], 2)?;
Ok(key_from_utf8(&buf[..3]))
} else if byte & 248u8 == 240u8 {
// a four byte unicode character
read_bytes(fd, &mut buf[1..], 3)?;
Ok(key_from_utf8(&buf[..4]))
} else {
Ok(match c {
'\n' | '\r' => Key::Enter,
'\x7f' => Key::Backspace,
'\t' => Key::Tab,
'\x01' => Key::Home, // Control-A (home)
'\x05' => Key::End, // Control-E (end)
'\x08' => Key::Backspace, // Control-H (8) (Identical to '\b')
_ => Key::Char(c),
})
};
}
None => {
// there is no subsequent byte ready to be read, block and wait for input
// negative timeout means that it will block indefinitely
match select_or_poll_term_fd(fd, -1) {
Ok(_) => continue,
Err(_) => break Err(io::Error::last_os_error()),
}
}
}
}
}
pub fn read_single_key() -> io::Result<Key> {
let tty_f;
let fd = unsafe {
if libc::isatty(libc::STDIN_FILENO) == 1 {
libc::STDIN_FILENO
} else {
tty_f = fs::OpenOptions::new()
.read(true)
.write(true)
.open("/dev/tty")?;
tty_f.as_raw_fd()
}
};
let mut termios = core::mem::MaybeUninit::uninit();
c_result(|| unsafe { libc::tcgetattr(fd, termios.as_mut_ptr()) })?;
let mut termios = unsafe { termios.assume_init() };
let original = termios;
unsafe { libc::cfmakeraw(&mut termios) };
termios.c_oflag = original.c_oflag;
c_result(|| unsafe { libc::tcsetattr(fd, libc::TCSADRAIN, &termios) })?;
let rv: io::Result<Key> = read_single_key_impl(fd);
c_result(|| unsafe { libc::tcsetattr(fd, libc::TCSADRAIN, &original) })?;
// if the user hit ^C we want to signal SIGINT to outselves.
if let Err(ref err) = rv {
if err.kind() == io::ErrorKind::Interrupted {
unsafe {
libc::raise(libc::SIGINT);
}
}
}
rv
}
pub fn key_from_utf8(buf: &[u8]) -> Key {
if let Ok(s) = str::from_utf8(buf) {
if let Some(c) = s.chars().next() {
return Key::Char(c);
}
}
Key::Unknown
}
#[cfg(not(target_os = "macos"))]
lazy_static::lazy_static! {
static ref IS_LANG_UTF8: bool = match std::env::var("LANG") {
Ok(lang) => lang.to_uppercase().ends_with("UTF-8"),
_ => false,
};
}
#[cfg(target_os = "macos")]
pub fn wants_emoji() -> bool {
true
}
#[cfg(not(target_os = "macos"))]
pub fn wants_emoji() -> bool {
*IS_LANG_UTF8
}
pub fn set_title<T: Display>(title: T) {
print!("\x1b]0;{}\x07", title);
}
fn with_raw_terminal<R>(f: impl FnOnce(&mut fs::File) -> R) -> io::Result<R> {
// We need a custom drop implementation for File,
// so that the fd for stdin does not get closed
enum CustomDropFile {
CloseFd(Option<fs::File>),
NotCloseFd(Option<fs::File>),
}
impl Drop for CustomDropFile {
fn drop(&mut self) {
match self {
CustomDropFile::CloseFd(_) => {}
CustomDropFile::NotCloseFd(inner) => {
if let Some(file) = inner.take() {
file.into_raw_fd();
}
}
}
}
}
let (mut tty_handle, tty_fd) = if unsafe { libc::isatty(libc::STDIN_FILENO) } == 1 {
(
CustomDropFile::NotCloseFd(Some(unsafe { fs::File::from_raw_fd(libc::STDIN_FILENO) })),
libc::STDIN_FILENO,
)
} else {
let handle = fs::OpenOptions::new()
.read(true)
.write(true)
.open("/dev/tty")?;
let fd = handle.as_raw_fd();
(CustomDropFile::CloseFd(Some(handle)), fd)
};
// Get current mode
let mut termios = mem::MaybeUninit::uninit();
c_result(|| unsafe { libc::tcgetattr(tty_fd, termios.as_mut_ptr()) })?;
let mut termios = unsafe { termios.assume_init() };
let old_iflag = termios.c_iflag;
let old_oflag = termios.c_oflag;
let old_cflag = termios.c_cflag;
let old_lflag = termios.c_lflag;
// Go into raw mode
unsafe { libc::cfmakeraw(&mut termios) };
if old_lflag & libc::ISIG != 0 {
// Re-enable INTR, QUIT, SUSP, DSUSP, if it was activated before
termios.c_lflag |= libc::ISIG;
}
c_result(|| unsafe { libc::tcsetattr(tty_fd, libc::TCSADRAIN, &termios) })?;
let result = match &mut tty_handle {
CustomDropFile::CloseFd(Some(handle)) => f(handle),
CustomDropFile::NotCloseFd(Some(handle)) => f(handle),
_ => unreachable!(),
};
// Reset to previous mode
termios.c_iflag = old_iflag;
termios.c_oflag = old_oflag;
termios.c_cflag = old_cflag;
termios.c_lflag = old_lflag;
c_result(|| unsafe { libc::tcsetattr(tty_fd, libc::TCSADRAIN, &termios) })?;
Ok(result)
}
pub fn supports_synchronized_output() -> bool {
*sync_output::SUPPORTS_SYNCHRONIZED_OUTPUT
}
/// Specification: https://gist.github.com/christianparpart/d8a62cc1ab659194337d73e399004036
mod sync_output {
use std::convert::TryInto as _;
use std::io::Read as _;
use std::io::Write as _;
use std::os::unix::io::AsRawFd as _;
use std::time;
use lazy_static::lazy_static;
use super::select_or_poll_term_fd;
use super::with_raw_terminal;
const RESPONSE_TIMEOUT: time::Duration = time::Duration::from_millis(10);
lazy_static! {
pub(crate) static ref SUPPORTS_SYNCHRONIZED_OUTPUT: bool =
supports_synchronized_output_uncached();
}
struct ResponseParser {
state: ResponseParserState,
response: u8,
}
#[derive(PartialEq)]
enum ResponseParserState {
None,
CsiOne,
CsiTwo,
QuestionMark,
ModeDigit1,
ModeDigit2,
ModeDigit3,
ModeDigit4,
Semicolon,
Response,
DollarSign,
Ypsilon,
}
impl ResponseParser {
const fn new() -> Self {
Self {
state: ResponseParserState::None,
response: u8::MAX,
}
}
fn process_byte(&mut self, byte: u8) {
match byte {
b'\x1b' => {
self.state = ResponseParserState::CsiOne;
}
b'[' => {
self.state = if self.state == ResponseParserState::CsiOne {
ResponseParserState::CsiTwo
} else {
ResponseParserState::None
};
}
b'?' => {
self.state = if self.state == ResponseParserState::CsiTwo {
ResponseParserState::QuestionMark
} else {
ResponseParserState::None
};
}
byte @ b'0' => {
self.state = if self.state == ResponseParserState::Semicolon {
self.response = byte;
ResponseParserState::Response
} else if self.state == ResponseParserState::ModeDigit1 {
ResponseParserState::ModeDigit2
} else {
ResponseParserState::None
};
}
byte @ b'2' => {
self.state = if self.state == ResponseParserState::Semicolon {
self.response = byte;
ResponseParserState::Response
} else if self.state == ResponseParserState::QuestionMark {
ResponseParserState::ModeDigit1
} else if self.state == ResponseParserState::ModeDigit2 {
ResponseParserState::ModeDigit3
} else {
ResponseParserState::None
};
}
byte @ b'1' | byte @ b'3' | byte @ b'4' => {
self.state = if self.state == ResponseParserState::Semicolon {
self.response = byte;
ResponseParserState::Response
} else {
ResponseParserState::None
};
}
b'6' => {
self.state = if self.state == ResponseParserState::ModeDigit3 {
ResponseParserState::ModeDigit4
} else {
ResponseParserState::None
};
}
b';' => {
self.state = if self.state == ResponseParserState::ModeDigit4 {
ResponseParserState::Semicolon
} else {
ResponseParserState::None
};
}
b'$' => {
self.state = if self.state == ResponseParserState::Response {
ResponseParserState::DollarSign
} else {
ResponseParserState::None
};
}
b'y' => {
self.state = if self.state == ResponseParserState::DollarSign {
ResponseParserState::Ypsilon
} else {
ResponseParserState::None
};
}
_ => {
self.state = ResponseParserState::None;
}
}
}
fn get_response(&self) -> Option<u8> {
if self.state == ResponseParserState::Ypsilon {
Some(self.response - b'0')
} else {
None
}
}
}
fn supports_synchronized_output_uncached() -> bool {
with_raw_terminal(|term_handle| {
// Query the state of the (DEC) mode 2026 (Synchronized Output)
write!(term_handle, "\x1b[?2026$p").ok()?;
term_handle.flush().ok()?;
// Wait for response or timeout
let term_fd = term_handle.as_raw_fd();
let mut parser = ResponseParser::new();
let mut buf = [0u8; 256];
let deadline = time::Instant::now() + RESPONSE_TIMEOUT;
loop {
let remaining_time = deadline
.saturating_duration_since(time::Instant::now())
.as_millis()
.try_into()
.ok()?;
if remaining_time == 0 {
// Timeout
return Some(false);
}
match select_or_poll_term_fd(term_fd, remaining_time) {
Ok(false) => {
// Timeout
return Some(false);
}
Ok(true) => {
'read: loop {
match term_handle.read(&mut buf) {
Ok(0) => {
// Reached EOF
return Some(false);
}
Ok(size) => {
for byte in &buf[..size] {
parser.process_byte(*byte);
match parser.get_response() {
Some(1) | Some(2) => return Some(true),
Some(_) => return Some(false),
None => {}
}
}
break 'read;
}
Err(err) if err.kind() == std::io::ErrorKind::Interrupted => {
// Got interrupted, retry read
continue 'read;
}
Err(_) => {
return Some(false);
}
}
}
}
Err(_) => {
// Error
return Some(false);
}
}
}
})
.ok()
.flatten()
.unwrap_or(false)
}
}