use super::*;
#[cfg(unix)]
unsafe extern "C" {
fn isatty(fd: i32) -> i32;
fn tcgetattr(fd: i32, termios: *mut UnixTermios) -> i32;
fn tcsetattr(fd: i32, optional_actions: i32, termios: *const UnixTermios) -> i32;
fn ioctl(fd: i32, request: usize, ...) -> i32;
fn signal(sig: i32, handler: extern "C" fn(i32)) -> usize;
fn poll(fds: *mut c_void, nfds: usize, timeout: i32) -> i32;
fn read(fd: i32, buf: *mut c_void, count: usize) -> isize;
}
#[cfg(target_os = "windows")]
#[link(name = "kernel32")]
unsafe extern "system" {
fn GetStdHandle(n_std_handle: u32) -> isize;
fn GetFileType(h_file: isize) -> u32;
fn GetConsoleMode(h_console_handle: isize, lp_mode: *mut u32) -> i32;
fn SetConsoleMode(h_console_handle: isize, dw_mode: u32) -> i32;
fn GetConsoleScreenBufferInfo(
h_console_output: isize,
lp_console_screen_buffer_info: *mut Win32ConsoleScreenBufferInfo,
) -> i32;
}
#[cfg(unix)]
extern "C" fn terminal_sigwinch_handler(_sig: i32) {
TERMINAL_SIGWINCH_FLAG.store(true, Ordering::Release);
}
pub fn terminal_install_sigwinch_handler() {
#[cfg(unix)]
{
if !TERMINAL_SIGWINCH_INSTALLED.swap(true, Ordering::AcqRel) {
unsafe {
let _: usize = signal(UNIX_SIGWINCH, terminal_sigwinch_handler);
}
}
}
}
#[must_use]
pub fn terminal_take_sigwinch_resized() -> bool {
TERMINAL_SIGWINCH_FLAG.swap(false, Ordering::AcqRel)
}
#[must_use]
pub fn terminal_fd_is_tty(fd: i32) -> bool {
#[cfg(unix)]
{
unsafe { isatty(fd) == 1 }
}
#[cfg(target_os = "windows")]
{
let std_id: u32 = match fd {
0 => WIN32_STD_INPUT_HANDLE,
2 => WIN32_STD_ERROR_HANDLE,
_ => WIN32_STD_OUTPUT_HANDLE,
};
unsafe {
let handle: isize = GetStdHandle(std_id);
if handle == 0 || handle == -1 {
return false;
}
if GetFileType(handle) != WIN32_FILE_TYPE_CHAR {
return false;
}
let mut mode: u32 = 0;
GetConsoleMode(handle, &mut mode) != 0
}
}
#[cfg(not(any(unix, target_os = "windows")))]
{
let _: i32 = fd;
false
}
}
#[must_use]
pub fn terminal_query_pty_size() -> (u16, u16) {
#[cfg(unix)]
{
unsafe {
let mut ws: UnixWinsize = zeroed();
if ioctl(UNIX_STDOUT_FD, UNIX_TIOCGWINSZ, &mut ws) == 0
&& ws.ws_col > 0
&& ws.ws_row > 0
{
return (ws.ws_col, ws.ws_row);
}
if ioctl(UNIX_STDIN_FD, UNIX_TIOCGWINSZ, &mut ws) == 0 && ws.ws_col > 0 && ws.ws_row > 0
{
return (ws.ws_col, ws.ws_row);
}
}
}
#[cfg(target_os = "windows")]
{
unsafe {
let handle: isize = GetStdHandle(WIN32_STD_OUTPUT_HANDLE);
if handle != 0 && handle != -1 {
let mut info: Win32ConsoleScreenBufferInfo =
Win32ConsoleScreenBufferInfo::default();
if GetConsoleScreenBufferInfo(handle, &mut info) != 0 {
let cols: i32 =
i32::from(info.sr_window.right) - i32::from(info.sr_window.left) + 1;
let rows: i32 =
i32::from(info.sr_window.bottom) - i32::from(info.sr_window.top) + 1;
if cols > 0 && rows > 0 {
return (cols as u16, rows as u16);
}
}
}
}
}
#[cfg(not(target_arch = "wasm32"))]
{
let env_cols: u16 = env::var(ENV_COLUMNS)
.ok()
.and_then(|v: String| v.trim().parse::<u16>().ok())
.filter(|v: &u16| *v > 0)
.unwrap_or(TERMINAL_DEFAULT_COLS);
let env_rows: u16 = env::var(ENV_LINES)
.ok()
.and_then(|v: String| v.trim().parse::<u16>().ok())
.filter(|v: &u16| *v > 0)
.unwrap_or(TERMINAL_DEFAULT_ROWS);
(env_cols, env_rows)
}
#[cfg(target_arch = "wasm32")]
{
(TERMINAL_DEFAULT_COLS, TERMINAL_DEFAULT_ROWS)
}
}
#[must_use]
pub fn terminal_probe_tty() -> TerminalTtyProbe {
let stdin_tty: bool = terminal_fd_is_tty(UNIX_STDIN_FD);
let stdout_tty: bool = terminal_fd_is_tty(UNIX_STDOUT_FD);
let stderr_tty: bool = terminal_fd_is_tty(UNIX_STDERR_FD);
let (cols, rows): (u16, u16) = terminal_query_pty_size();
#[cfg(not(target_arch = "wasm32"))]
let (no_color, color): (bool, TerminalColorCapability) = {
let no_col: bool = env::var(ENV_NO_COLOR).is_ok();
let term_val: String = env::var(ENV_TERM).unwrap_or_default().to_ascii_lowercase();
let colorterm_val: String = env::var(ENV_COLORTERM)
.unwrap_or_default()
.to_ascii_lowercase();
let cap: TerminalColorCapability = if !stdout_tty || term_val == TERM_VAL_DUMB || no_col {
TerminalColorCapability::None
} else if colorterm_val.contains(TERM_VAL_TRUECOLOR)
|| colorterm_val.contains(TERM_VAL_24BIT)
{
TerminalColorCapability::TrueColor
} else if term_val.contains(TERM_VAL_256COLOR) {
TerminalColorCapability::Ansi256
} else {
TerminalColorCapability::Ansi16
};
(no_col, cap)
};
#[cfg(target_arch = "wasm32")]
let (no_color, color): (bool, TerminalColorCapability) = (true, TerminalColorCapability::None);
TerminalTtyProbe::new(
stdin_tty, stdout_tty, stderr_tty, color, no_color, cols, rows,
)
}
#[cfg(unix)]
pub(crate) fn terminal_unix_enter_raw_mode() -> Option<UnixTermios> {
if !terminal_fd_is_tty(UNIX_STDIN_FD) {
return None;
}
unsafe {
let mut orig: UnixTermios = zeroed();
if tcgetattr(UNIX_STDIN_FD, &mut orig) != 0 {
return None;
}
let mut raw: UnixTermios = orig;
raw.c_iflag &= !UNIX_TERMIOS_IFLAG_RAW_MASK;
raw.c_oflag &= !UNIX_TERMIOS_OFLAG_OPOST;
raw.c_cflag |= UNIX_TERMIOS_CFLAG_CS8;
raw.c_lflag &= !UNIX_TERMIOS_LFLAG_RAW_MASK;
raw.c_cc[UNIX_TERMIOS_VMIN_IDX] = 0;
raw.c_cc[UNIX_TERMIOS_VTIME_IDX] = 0;
if tcsetattr(UNIX_STDIN_FD, UNIX_TCSANOW, &raw) != 0 {
return None;
}
Some(orig)
}
}
#[cfg(unix)]
pub(crate) fn terminal_unix_restore_raw_mode(orig: &UnixTermios) {
unsafe {
let _: i32 = tcsetattr(UNIX_STDIN_FD, UNIX_TCSANOW, orig);
}
}
#[cfg(target_os = "windows")]
pub(crate) fn terminal_win32_enter_vt_mode() -> Option<(u32, u32)> {
unsafe {
let h_in: isize = GetStdHandle(WIN32_STD_INPUT_HANDLE);
let h_out: isize = GetStdHandle(WIN32_STD_OUTPUT_HANDLE);
if h_in == 0 || h_in == -1 || h_out == 0 || h_out == -1 {
return None;
}
let mut orig_in: u32 = 0;
let mut orig_out: u32 = 0;
if GetConsoleMode(h_in, &mut orig_in) == 0 || GetConsoleMode(h_out, &mut orig_out) == 0 {
return None;
}
let clear_mask: u32 =
WIN32_ENABLE_LINE_INPUT + WIN32_ENABLE_ECHO_INPUT + WIN32_ENABLE_PROCESSED_INPUT;
let enable_mask: u32 = WIN32_ENABLE_VIRTUAL_TERMINAL_INPUT
+ WIN32_ENABLE_WINDOW_INPUT
+ WIN32_ENABLE_MOUSE_INPUT;
let raw_in: u32 = (orig_in & !clear_mask) | enable_mask;
let raw_out: u32 = orig_out | WIN32_ENABLE_VIRTUAL_TERMINAL_PROCESSING;
let _: i32 = SetConsoleMode(h_in, raw_in);
let _: i32 = SetConsoleMode(h_out, raw_out);
Some((orig_in, orig_out))
}
}
#[cfg(target_os = "windows")]
pub(crate) fn terminal_win32_restore_vt_mode(modes: (u32, u32)) {
unsafe {
let h_in: isize = GetStdHandle(WIN32_STD_INPUT_HANDLE);
let h_out: isize = GetStdHandle(WIN32_STD_OUTPUT_HANDLE);
if h_in != 0 && h_in != -1 {
let _: i32 = SetConsoleMode(h_in, modes.0);
}
if h_out != 0 && h_out != -1 {
let _: i32 = SetConsoleMode(h_out, modes.1);
}
}
}
#[must_use]
pub fn terminal_read_pty_bytes(timeout_ms: i32) -> Vec<u8> {
#[cfg(unix)]
{
if !terminal_fd_is_tty(UNIX_STDIN_FD) {
return Vec::new();
}
let mut pfd: UnixPollFd = UnixPollFd {
fd: UNIX_STDIN_FD,
events: UNIX_POLLIN,
revents: 0,
};
unsafe {
let ready: i32 = poll(
(&mut pfd as *mut UnixPollFd).cast::<c_void>(),
1,
timeout_ms.max(0),
);
if ready <= 0 || (pfd.revents & UNIX_POLLIN) == 0 {
return Vec::new();
}
let mut buf: [u8; 256] = [0; 256];
let n: isize = read(UNIX_STDIN_FD, buf.as_mut_ptr().cast::<c_void>(), buf.len());
if n > 0 {
buf[..(n as usize)].to_vec()
} else {
Vec::new()
}
}
}
#[cfg(not(unix))]
{
let _: i32 = timeout_ms;
Vec::new()
}
}
pub(crate) fn terminal_write_os_stream(
stream: TerminalStreamKind,
bytes: &[u8],
) -> Result<bool, PlatformError> {
#[cfg(not(target_arch = "wasm32"))]
{
let write_res: io::Result<()> = match stream {
TerminalStreamKind::Stdout => {
let mut handle: io::StdoutLock<'_> = stdout().lock();
handle.write_all(bytes).and_then(|_: ()| handle.flush())
}
TerminalStreamKind::Stderr => {
let mut handle: io::StderrLock<'_> = stderr().lock();
handle.write_all(bytes).and_then(|_: ()| handle.flush())
}
};
match write_res {
Ok(()) => Ok(true),
Err(err) if err.kind() == ErrorKind::BrokenPipe => Ok(false),
Err(_) => Err(PlatformError::SurfaceError(
ERR_TERMINAL_IO_WRITE.to_string(),
)),
}
}
#[cfg(target_arch = "wasm32")]
{
let _: (TerminalStreamKind, &[u8]) = (stream, bytes);
Ok(true)
}
}
#[must_use]
pub(crate) fn terminal_decode_csi_modifiers(param: u32) -> Modifiers {
let bits: u32 = param.saturating_sub(1);
Modifiers::new(
(bits & 1) != 0,
(bits & 4) != 0,
(bits & 2) != 0,
(bits & 8) != 0,
)
}
#[must_use]
pub(crate) fn terminal_parse_sgr_mouse(
wid: WindowId,
params: &str,
pressed: bool,
cell_w: f32,
cell_h: f32,
) -> Option<WindowEvent> {
let mut parts: Vec<u32> = Vec::with_capacity(3);
for token in params.split(';') {
if let Ok(val) = token.parse::<u32>() {
parts.push(val);
}
}
if parts.len() < 3 {
return None;
}
let code: u32 = parts[0];
let col: u32 = parts[1].saturating_sub(1);
let row: u32 = parts[2].saturating_sub(1);
let pos: Point = Point::new(
((col as f32) + 0.5) * cell_w.max(1.0),
((row as f32) + 0.5) * cell_h.max(1.0),
);
let mods: Modifiers = Modifiers::new((code & 4) != 0, (code & 16) != 0, (code & 8) != 0, false);
if (code & 64) != 0 {
let dir: f32 = if (code & 1) == 0 {
-TERMINAL_WHEEL_SCROLL_STEP_PX
} else {
TERMINAL_WHEEL_SCROLL_STEP_PX
};
let delta: Point = if mods.get_shift() {
Point::new(dir, 0.0)
} else {
Point::new(0.0, dir)
};
return Some(WindowEvent::Scroll(wid, delta));
}
let button: PointerButton = match code & 3 {
1 => PointerButton::Auxiliary,
2 => PointerButton::Secondary,
_ => PointerButton::Primary,
};
let is_motion: bool = (code & 32) != 0;
let ev: PointerEvent = PointerEvent::new(
1,
PointerDevice::Mouse,
pos,
button,
if pressed { 1.0 } else { 0.0 },
mods,
);
if is_motion {
Some(WindowEvent::PointerMove(wid, ev))
} else if pressed {
Some(WindowEvent::PointerDown(wid, ev))
} else {
Some(WindowEvent::PointerUp(wid, ev))
}
}
#[must_use]
pub(crate) fn terminal_find_bytes(haystack: &[u8], needle: &[u8]) -> Option<usize> {
if needle.is_empty() || haystack.len() < needle.len() {
return None;
}
haystack
.windows(needle.len())
.position(|window: &[u8]| window == needle)
}