| 1 |
#[cfg(target_os = "macos")] |
| 2 |
use core::ptr; |
| 3 |
use core::{fmt::Display, mem, str}; |
| 4 |
use std::env; |
| 5 |
use std::fs; |
| 6 |
use std::io::{self, BufRead, BufReader}; |
| 7 |
use std::os::fd::{AsRawFd, RawFd}; |
| 8 |
|
| 9 |
#[cfg(not(target_os = "macos"))] |
| 10 |
use std::sync::OnceLock; |
| 11 |
|
| 12 |
use crate::is_dumb; |
| 13 |
use crate::kb::Key; |
| 14 |
use crate::term::Term; |
| 15 |
|
| 16 |
pub(crate) use crate::common_term::*; |
| 17 |
|
| 18 |
pub(crate) const DEFAULT_WIDTH: u16 = 80; |
| 19 |
|
| 20 |
#[inline] |
| 21 |
pub(crate) fn is_a_terminal(out: &impl AsRawFd) -> bool { |
| 22 |
unsafe { libc::isatty(out.as_raw_fd()) != 0 } |
| 23 |
} |
| 24 |
|
| 25 |
pub(crate) fn is_a_color_terminal(out: &Term) -> bool { |
| 26 |
if !is_a_terminal(out) { |
| 27 |
return false; |
| 28 |
} |
| 29 |
|
| 30 |
if env::var("NO_COLOR").is_ok() { |
| 31 |
return false; |
| 32 |
} |
| 33 |
|
| 34 |
!is_dumb() |
| 35 |
} |
| 36 |
|
| 37 |
pub(crate) fn is_a_true_color_terminal(out: &Term) -> bool { |
| 38 |
if !is_a_color_terminal(out) { |
| 39 |
return false; |
| 40 |
} |
| 41 |
env::var("COLORTERM").is_ok_and(|term| term == "truecolor" || term == "24bit") |
| 42 |
} |
| 43 |
|
| 44 |
fn c_result<F: FnOnce() -> libc::c_int>(f: F) -> io::Result<()> { |
| 45 |
let res = f(); |
| 46 |
if res != 0 { |
| 47 |
Err(io::Error::last_os_error()) |
| 48 |
} else { |
| 49 |
Ok(()) |
| 50 |
} |
| 51 |
} |
| 52 |
|
| 53 |
pub(crate) fn terminal_size(out: &Term) -> Option<(u16, u16)> { |
| 54 |
if !is_a_terminal(out) { |
| 55 |
return None; |
| 56 |
} |
| 57 |
let winsize = unsafe { |
| 58 |
let mut winsize: libc::winsize = mem::zeroed(); |
| 59 |
|
| 60 |
// FIXME: ".into()" used as a temporary fix for a libc bug |
| 61 |
// https://github.com/rust-lang/libc/pull/704 |
| 62 |
#[allow(clippy::useless_conversion)] |
| 63 |
libc::ioctl(out.as_raw_fd(), libc::TIOCGWINSZ.into(), &mut winsize); |
| 64 |
winsize |
| 65 |
}; |
| 66 |
if winsize.ws_row > 0 && winsize.ws_col > 0 { |
| 67 |
Some((winsize.ws_row, winsize.ws_col)) |
| 68 |
} else { |
| 69 |
None |
| 70 |
} |
| 71 |
} |
| 72 |
|
| 73 |
enum Input<T> { |
| 74 |
Stdin(io::Stdin), |
| 75 |
File(T), |
| 76 |
} |
| 77 |
|
| 78 |
impl Input<BufReader<fs::File>> { |
| 79 |
fn buffered() -> io::Result<Self> { |
| 80 |
Ok(match Input::unbuffered()? { |
| 81 |
Input::Stdin(s) => Input::Stdin(s), |
| 82 |
Input::File(f) => Input::File(BufReader::new(f)), |
| 83 |
}) |
| 84 |
} |
| 85 |
} |
| 86 |
|
| 87 |
impl Input<fs::File> { |
| 88 |
fn unbuffered() -> io::Result<Self> { |
| 89 |
let stdin = io::stdin(); |
| 90 |
if is_a_terminal(&stdin) { |
| 91 |
Ok(Input::Stdin(stdin)) |
| 92 |
} else { |
| 93 |
let f = fs::OpenOptions::new() |
| 94 |
.read(true) |
| 95 |
.write(true) |
| 96 |
.open("/dev/tty")?; |
| 97 |
Ok(Input::File(f)) |
| 98 |
} |
| 99 |
} |
| 100 |
} |
| 101 |
|
| 102 |
// NB: this is not a full BufRead implementation because io::Stdin does not implement BufRead. |
| 103 |
impl<T: BufRead> Input<T> { |
| 104 |
fn read_line(&mut self, buf: &mut String) -> io::Result<usize> { |
| 105 |
match self { |
| 106 |
Self::Stdin(s) => s.read_line(buf), |
| 107 |
Self::File(f) => f.read_line(buf), |
| 108 |
} |
| 109 |
} |
| 110 |
} |
| 111 |
|
| 112 |
impl AsRawFd for Input<fs::File> { |
| 113 |
fn as_raw_fd(&self) -> RawFd { |
| 114 |
match self { |
| 115 |
Self::Stdin(s) => s.as_raw_fd(), |
| 116 |
Self::File(f) => f.as_raw_fd(), |
| 117 |
} |
| 118 |
} |
| 119 |
} |
| 120 |
|
| 121 |
impl AsRawFd for Input<BufReader<fs::File>> { |
| 122 |
fn as_raw_fd(&self) -> RawFd { |
| 123 |
match self { |
| 124 |
Self::Stdin(s) => s.as_raw_fd(), |
| 125 |
Self::File(f) => f.get_ref().as_raw_fd(), |
| 126 |
} |
| 127 |
} |
| 128 |
} |
| 129 |
|
| 130 |
pub(crate) fn read_secure() -> io::Result<String> { |
| 131 |
let mut input = Input::buffered()?; |
| 132 |
|
| 133 |
let mut termios = mem::MaybeUninit::uninit(); |
| 134 |
c_result(|| unsafe { libc::tcgetattr(input.as_raw_fd(), termios.as_mut_ptr()) })?; |
| 135 |
let mut termios = unsafe { termios.assume_init() }; |
| 136 |
let original = termios; |
| 137 |
termios.c_lflag &= !libc::ECHO; |
| 138 |
c_result(|| unsafe { libc::tcsetattr(input.as_raw_fd(), libc::TCSAFLUSH, &termios) })?; |
| 139 |
let mut rv = String::new(); |
| 140 |
|
| 141 |
let read_rv = input.read_line(&mut rv); |
| 142 |
|
| 143 |
c_result(|| unsafe { libc::tcsetattr(input.as_raw_fd(), libc::TCSAFLUSH, &original) })?; |
| 144 |
|
| 145 |
read_rv.map(|_| { |
| 146 |
let len = rv.trim_end_matches(&['\r', '\n'][..]).len(); |
| 147 |
rv.truncate(len); |
| 148 |
rv |
| 149 |
}) |
| 150 |
} |
| 151 |
|
| 152 |
fn poll_fd(fd: RawFd, timeout: i32) -> io::Result<bool> { |
| 153 |
let mut pollfd = libc::pollfd { |
| 154 |
fd, |
| 155 |
events: libc::POLLIN, |
| 156 |
revents: 0, |
| 157 |
}; |
| 158 |
let ret = unsafe { libc::poll(&mut pollfd as *mut _, 1, timeout) }; |
| 159 |
if ret < 0 { |
| 160 |
Err(io::Error::last_os_error()) |
| 161 |
} else { |
| 162 |
Ok(pollfd.revents & libc::POLLIN != 0) |
| 163 |
} |
| 164 |
} |
| 165 |
|
| 166 |
#[cfg(target_os = "macos")] |
| 167 |
fn select_fd(fd: RawFd, timeout: i32) -> io::Result<bool> { |
| 168 |
unsafe { |
| 169 |
let mut read_fd_set: libc::fd_set = mem::zeroed(); |
| 170 |
|
| 171 |
let mut timeout_val; |
| 172 |
let timeout = if timeout < 0 { |
| 173 |
ptr::null_mut() |
| 174 |
} else { |
| 175 |
timeout_val = libc::timeval { |
| 176 |
tv_sec: (timeout / 1000) as _, |
| 177 |
tv_usec: (timeout * 1000) as _, |
| 178 |
}; |
| 179 |
&mut timeout_val |
| 180 |
}; |
| 181 |
|
| 182 |
libc::FD_ZERO(&mut read_fd_set); |
| 183 |
libc::FD_SET(fd, &mut read_fd_set); |
| 184 |
let ret = libc::select( |
| 185 |
fd + 1, |
| 186 |
&mut read_fd_set, |
| 187 |
ptr::null_mut(), |
| 188 |
ptr::null_mut(), |
| 189 |
timeout, |
| 190 |
); |
| 191 |
if ret < 0 { |
| 192 |
Err(io::Error::last_os_error()) |
| 193 |
} else { |
| 194 |
Ok(libc::FD_ISSET(fd, &read_fd_set)) |
| 195 |
} |
| 196 |
} |
| 197 |
} |
| 198 |
|
| 199 |
fn select_or_poll_term_fd(fd: RawFd, timeout: i32) -> io::Result<bool> { |
| 200 |
// There is a bug on macos that ttys cannot be polled, only select() |
| 201 |
// works. However given how problematic select is in general, we |
| 202 |
// normally want to use poll there too. |
| 203 |
#[cfg(target_os = "macos")] |
| 204 |
{ |
| 205 |
if unsafe { libc::isatty(fd) == 1 } { |
| 206 |
return select_fd(fd, timeout); |
| 207 |
} |
| 208 |
} |
| 209 |
poll_fd(fd, timeout) |
| 210 |
} |
| 211 |
|
| 212 |
fn read_single_char(fd: RawFd) -> io::Result<Option<char>> { |
| 213 |
// timeout of zero means that it will not block |
| 214 |
let is_ready = select_or_poll_term_fd(fd, 0)?; |
| 215 |
|
| 216 |
if is_ready { |
| 217 |
// if there is something to be read, take 1 byte from it |
| 218 |
let mut buf: [u8; 1] = [0]; |
| 219 |
|
| 220 |
read_bytes(fd, &mut buf, 1)?; |
| 221 |
Ok(Some(buf[0] as char)) |
| 222 |
} else { |
| 223 |
//there is nothing to be read |
| 224 |
Ok(None) |
| 225 |
} |
| 226 |
} |
| 227 |
|
| 228 |
// Similar to libc::read. Read count bytes into slice buf from descriptor fd. |
| 229 |
// If successful, return the number of bytes read. |
| 230 |
// Will return an error if nothing was read, i.e when called at end of file. |
| 231 |
fn read_bytes(fd: RawFd, buf: &mut [u8], count: u8) -> io::Result<u8> { |
| 232 |
let read = unsafe { libc::read(fd, buf.as_mut_ptr() as *mut _, count as usize) }; |
| 233 |
if read < 0 { |
| 234 |
Err(io::Error::last_os_error()) |
| 235 |
} else if read == 0 { |
| 236 |
Err(io::Error::new( |
| 237 |
io::ErrorKind::UnexpectedEof, |
| 238 |
"Reached end of file", |
| 239 |
)) |
| 240 |
} else if buf[0] == b'\x03' { |
| 241 |
Err(io::Error::new( |
| 242 |
io::ErrorKind::Interrupted, |
| 243 |
"read interrupted", |
| 244 |
)) |
| 245 |
} else { |
| 246 |
Ok(read as u8) |
| 247 |
} |
| 248 |
} |
| 249 |
|
| 250 |
fn read_single_key_impl(fd: RawFd) -> Result<Key, io::Error> { |
| 251 |
loop { |
| 252 |
match read_single_char(fd)? { |
| 253 |
Some('\x1b') => { |
| 254 |
// Escape was read, keep reading in case we find a familiar key |
| 255 |
break if let Some(c1) = read_single_char(fd)? { |
| 256 |
if c1 == '[' { |
| 257 |
if let Some(c2) = read_single_char(fd)? { |
| 258 |
match c2 { |
| 259 |
'A' => Ok(Key::ArrowUp), |
| 260 |
'B' => Ok(Key::ArrowDown), |
| 261 |
'C' => Ok(Key::ArrowRight), |
| 262 |
'D' => Ok(Key::ArrowLeft), |
| 263 |
'H' => Ok(Key::Home), |
| 264 |
'F' => Ok(Key::End), |
| 265 |
'Z' => Ok(Key::BackTab), |
| 266 |
_ => { |
| 267 |
let c3 = read_single_char(fd)?; |
| 268 |
if let Some(c3) = c3 { |
| 269 |
if c3 == '~' { |
| 270 |
match c2 { |
| 271 |
'1' => Ok(Key::Home), // tmux |
| 272 |
'2' => Ok(Key::Insert), |
| 273 |
'3' => Ok(Key::Del), |
| 274 |
'4' => Ok(Key::End), // tmux |
| 275 |
'5' => Ok(Key::PageUp), |
| 276 |
'6' => Ok(Key::PageDown), |
| 277 |
'7' => Ok(Key::Home), // xrvt |
| 278 |
'8' => Ok(Key::End), // xrvt |
| 279 |
_ => Ok(Key::UnknownEscSeq(vec![c1, c2, c3])), |
| 280 |
} |
| 281 |
} else { |
| 282 |
Ok(Key::UnknownEscSeq(vec![c1, c2, c3])) |
| 283 |
} |
| 284 |
} else { |
| 285 |
// \x1b[ and 1 more char |
| 286 |
Ok(Key::UnknownEscSeq(vec![c1, c2])) |
| 287 |
} |
| 288 |
} |
| 289 |
} |
| 290 |
} else { |
| 291 |
// \x1b[ and no more input |
| 292 |
Ok(Key::UnknownEscSeq(vec![c1])) |
| 293 |
} |
| 294 |
} else { |
| 295 |
// char after escape is not [ |
| 296 |
Ok(Key::UnknownEscSeq(vec![c1])) |
| 297 |
} |
| 298 |
} else { |
| 299 |
//nothing after escape |
| 300 |
Ok(Key::Escape) |
| 301 |
}; |
| 302 |
} |
| 303 |
Some(c) => { |
| 304 |
let byte = c as u8; |
| 305 |
let mut buf: [u8; 4] = [byte, 0, 0, 0]; |
| 306 |
|
| 307 |
break if byte & 224u8 == 192u8 { |
| 308 |
// a two byte unicode character |
| 309 |
read_bytes(fd, &mut buf[1..], 1)?; |
| 310 |
Ok(key_from_utf8(&buf[..2])) |
| 311 |
} else if byte & 240u8 == 224u8 { |
| 312 |
// a three byte unicode character |
| 313 |
read_bytes(fd, &mut buf[1..], 2)?; |
| 314 |
Ok(key_from_utf8(&buf[..3])) |
| 315 |
} else if byte & 248u8 == 240u8 { |
| 316 |
// a four byte unicode character |
| 317 |
read_bytes(fd, &mut buf[1..], 3)?; |
| 318 |
Ok(key_from_utf8(&buf[..4])) |
| 319 |
} else { |
| 320 |
Ok(match c { |
| 321 |
'\n' | '\r' => Key::Enter, |
| 322 |
'\x7f' => Key::Backspace, |
| 323 |
'\t' => Key::Tab, |
| 324 |
'\x01' => Key::Home, // Control-A (home) |
| 325 |
'\x05' => Key::End, // Control-E (end) |
| 326 |
'\x08' => Key::Backspace, // Control-H (8) (Identical to '\b') |
| 327 |
_ => Key::Char(c), |
| 328 |
}) |
| 329 |
}; |
| 330 |
} |
| 331 |
None => { |
| 332 |
// there is no subsequent byte ready to be read, block and wait for input |
| 333 |
// negative timeout means that it will block indefinitely |
| 334 |
match select_or_poll_term_fd(fd, -1) { |
| 335 |
Ok(_) => continue, |
| 336 |
Err(_) => break Err(io::Error::last_os_error()), |
| 337 |
} |
| 338 |
} |
| 339 |
} |
| 340 |
} |
| 341 |
} |
| 342 |
|
| 343 |
pub(crate) fn read_single_key(ctrlc_key: bool) -> io::Result<Key> { |
| 344 |
let input = Input::unbuffered()?; |
| 345 |
|
| 346 |
let mut termios = core::mem::MaybeUninit::uninit(); |
| 347 |
c_result(|| unsafe { libc::tcgetattr(input.as_raw_fd(), termios.as_mut_ptr()) })?; |
| 348 |
let mut termios = unsafe { termios.assume_init() }; |
| 349 |
let original = termios; |
| 350 |
make_raw(&mut termios); |
| 351 |
termios.c_oflag = original.c_oflag; |
| 352 |
c_result(|| unsafe { libc::tcsetattr(input.as_raw_fd(), libc::TCSADRAIN, &termios) })?; |
| 353 |
let rv = read_single_key_impl(input.as_raw_fd()); |
| 354 |
c_result(|| unsafe { libc::tcsetattr(input.as_raw_fd(), libc::TCSADRAIN, &original) })?; |
| 355 |
|
| 356 |
// if the user hit ^C we want to signal SIGINT to ourselves. |
| 357 |
if let Err(ref err) = rv { |
| 358 |
if err.kind() == io::ErrorKind::Interrupted { |
| 359 |
if !ctrlc_key { |
| 360 |
unsafe { |
| 361 |
libc::raise(libc::SIGINT); |
| 362 |
} |
| 363 |
} else { |
| 364 |
return Ok(Key::CtrlC); |
| 365 |
} |
| 366 |
} |
| 367 |
} |
| 368 |
|
| 369 |
rv |
| 370 |
} |
| 371 |
|
| 372 |
fn key_from_utf8(buf: &[u8]) -> Key { |
| 373 |
if let Ok(s) = str::from_utf8(buf) { |
| 374 |
if let Some(c) = s.chars().next() { |
| 375 |
return Key::Char(c); |
| 376 |
} |
| 377 |
} |
| 378 |
Key::Unknown |
| 379 |
} |
| 380 |
|
| 381 |
#[cfg(target_os = "macos")] |
| 382 |
pub(crate) fn wants_emoji() -> bool { |
| 383 |
true |
| 384 |
} |
| 385 |
|
| 386 |
#[cfg(not(target_os = "macos"))] |
| 387 |
pub(crate) fn wants_emoji() -> bool { |
| 388 |
static IS_LANG_UTF8: OnceLock<bool> = OnceLock::new(); |
| 389 |
|
| 390 |
*IS_LANG_UTF8.get_or_init(|| match std::env::var("LANG") { |
| 391 |
Ok(lang) => lang.to_uppercase().ends_with("UTF-8"), |
| 392 |
_ => false, |
| 393 |
}) |
| 394 |
} |
| 395 |
|
| 396 |
pub(crate) fn set_title<T: Display>(title: T) { |
| 397 |
print!("\x1b]0;{title}\x07"); |
| 398 |
} |
| 399 |
|
| 400 |
#[cfg(target_os = "nto")] |
| 401 |
fn make_raw(termios: &mut libc::termios) { |
| 402 |
// This is the manual implementation for QNX, which does not have cfmakeraw. |
| 403 |
termios.c_iflag &= !(libc::IGNBRK |
| 404 |
| libc::BRKINT |
| 405 |
| libc::PARMRK |
| 406 |
| libc::ISTRIP |
| 407 |
| libc::INLCR |
| 408 |
| libc::IGNCR |
| 409 |
| libc::ICRNL |
| 410 |
| libc::IXON); |
| 411 |
termios.c_oflag &= !libc::OPOST; |
| 412 |
termios.c_lflag &= !(libc::ECHO | libc::ECHONL | libc::ICANON | libc::ISIG | libc::IEXTEN); |
| 413 |
termios.c_cflag &= !(libc::CSIZE | libc::PARENB); |
| 414 |
termios.c_cflag |= libc::CS8; |
| 415 |
} |
| 416 |
|
| 417 |
// This version will be compiled for all targets that are NOT QNX. |
| 418 |
#[cfg(not(target_os = "nto"))] |
| 419 |
fn make_raw(termios: &mut libc::termios) { |
| 420 |
// For other systems (Linux, macOS, BSD, etc.), use the standard libc call. |
| 421 |
unsafe { libc::cfmakeraw(termios) }; |
| 422 |
} |