use std::io;
#[cfg(unix)]
use std::os::fd::{AsFd, AsRawFd};
#[cfg(windows)]
use std::os::windows::io::{AsHandle, AsRawHandle};
#[cfg(windows)]
use windows_sys::Win32::Foundation::HANDLE;
#[derive(Clone, Debug)]
#[non_exhaustive]
pub struct State {
#[cfg(unix)]
pub input: Option<libc::termios>,
#[cfg(unix)]
pub output: Option<libc::termios>,
#[cfg(windows)]
pub input: u32,
#[cfg(windows)]
pub output: u32,
}
#[cfg(windows)]
unsafe impl Send for State {}
#[cfg(windows)]
unsafe impl Sync for State {}
#[cfg(unix)]
pub fn get_state<I: AsFd, O: AsFd>(input: I, output: O) -> io::Result<State> {
use std::mem::MaybeUninit;
fn try_read(fd: i32) -> io::Result<libc::termios> {
let mut t = MaybeUninit::<libc::termios>::uninit();
if unsafe { libc::tcgetattr(fd, t.as_mut_ptr()) } != 0 {
return Err(io::Error::last_os_error());
}
Ok(unsafe { t.assume_init() })
}
let input = try_read(input.as_fd().as_raw_fd()).ok();
let output = try_read(output.as_fd().as_raw_fd());
match (input, output) {
(None, Err(e)) => Err(e),
(input, output) => Ok(State {
input,
output: output.ok(),
}),
}
}
#[cfg(unix)]
pub fn set_state<I: AsFd, O: AsFd>(input: I, output: O, state: &State) -> io::Result<()> {
fn try_write(fd: i32, termios: Option<&libc::termios>) -> io::Result<()> {
let Some(termios) = termios else {
return Ok(());
};
if unsafe { libc::tcsetattr(fd, libc::TCSANOW, termios) } != 0 {
return Err(io::Error::last_os_error());
}
Ok(())
}
let applied_input = try_write(input.as_fd().as_raw_fd(), state.input.as_ref());
let applied_output = try_write(output.as_fd().as_raw_fd(), state.output.as_ref());
applied_input.and(applied_output)
}
#[cfg(windows)]
pub fn get_state<I: AsHandle, O: AsHandle>(input: I, output: O) -> io::Result<State> {
use windows_sys::Win32::System::Console::GetConsoleMode;
let ih = input.as_handle().as_raw_handle() as HANDLE;
let oh = output.as_handle().as_raw_handle() as HANDLE;
let mut input_mode: u32 = 0;
if unsafe { GetConsoleMode(ih, &mut input_mode) } == 0 {
return Err(io::Error::last_os_error());
}
let mut output_mode: u32 = 0;
if unsafe { GetConsoleMode(oh, &mut output_mode) } == 0 {
return Err(io::Error::last_os_error());
}
Ok(State {
input: input_mode,
output: output_mode,
})
}
#[cfg(windows)]
pub fn set_state<I: AsHandle, O: AsHandle>(input: I, output: O, state: &State) -> io::Result<()> {
set_state_with_input(input, output, state, |_| {})
}
#[cfg(windows)]
pub(super) fn set_state_with_input<I: AsHandle, O: AsHandle>(
input: I,
output: O,
state: &State,
on_input: impl FnOnce(u32),
) -> io::Result<()> {
use windows_sys::Win32::System::Console::SetConsoleMode;
fn try_write(handle: HANDLE, mode: u32) -> io::Result<()> {
if unsafe { SetConsoleMode(handle, mode) } == 0 {
return Err(io::Error::last_os_error());
}
Ok(())
}
let ih = input.as_handle().as_raw_handle() as HANDLE;
let oh = output.as_handle().as_raw_handle() as HANDLE;
let applied_input = try_write(ih, state.input);
if applied_input.is_ok() {
on_input(state.input);
}
let applied_output = try_write(oh, state.output);
applied_input.and(applied_output)
}
#[cfg(unix)]
pub fn make_raw_mode<I: AsFd, O: AsFd>(input: I, output: O) -> io::Result<State> {
fn rawify(mut t: libc::termios) -> libc::termios {
t.c_iflag &= !(libc::IGNBRK
| libc::BRKINT
| libc::PARMRK
| libc::ISTRIP
| libc::INLCR
| libc::IGNCR
| libc::ICRNL
| libc::IXON);
t.c_oflag &= !libc::OPOST;
t.c_lflag &= !(libc::ECHO | libc::ECHONL | libc::ICANON | libc::ISIG | libc::IEXTEN);
t.c_cflag &= !(libc::CSIZE | libc::PARENB);
t.c_cflag |= libc::CS8;
t.c_cc[libc::VMIN] = 1;
t.c_cc[libc::VTIME] = 0;
t
}
let original = get_state(&input, &output)?;
let raw = State {
input: original.input.map(rawify),
output: original.output.map(rawify),
};
if let Err(e) = set_state(&input, &output, &raw) {
let _ = set_state(&input, &output, &original);
return Err(e);
}
Ok(original)
}
#[cfg(windows)]
pub fn make_raw_mode<I: AsHandle, O: AsHandle>(input: I, output: O) -> io::Result<State> {
use windows_sys::Win32::System::Console::{
DISABLE_NEWLINE_AUTO_RETURN, ENABLE_ECHO_INPUT, ENABLE_EXTENDED_FLAGS, ENABLE_LINE_INPUT,
ENABLE_PROCESSED_INPUT, ENABLE_PROCESSED_OUTPUT, ENABLE_QUICK_EDIT_MODE,
ENABLE_VIRTUAL_TERMINAL_INPUT, ENABLE_VIRTUAL_TERMINAL_PROCESSING, ENABLE_WINDOW_INPUT,
};
let original = get_state(&input, &output)?;
let raw_input = (original.input
& !(ENABLE_ECHO_INPUT
| ENABLE_PROCESSED_INPUT
| ENABLE_LINE_INPUT
| ENABLE_QUICK_EDIT_MODE))
| ENABLE_VIRTUAL_TERMINAL_INPUT
| ENABLE_EXTENDED_FLAGS
| ENABLE_WINDOW_INPUT;
let raw_output = original.output
| ENABLE_PROCESSED_OUTPUT
| ENABLE_VIRTUAL_TERMINAL_PROCESSING
| DISABLE_NEWLINE_AUTO_RETURN;
let raw = State {
input: raw_input,
output: raw_output,
};
if let Err(e) = set_state(&input, &output, &raw) {
let _ = set_state(&input, &output, &original);
return Err(e);
}
Ok(original)
}
#[cfg(unix)]
pub fn is_terminal<F: AsFd>(fd: F) -> bool {
unsafe { libc::isatty(fd.as_fd().as_raw_fd()) != 0 }
}
#[cfg(windows)]
pub fn is_terminal<H: AsHandle>(h: H) -> bool {
use windows_sys::Win32::System::Console::GetConsoleMode;
let handle = h.as_handle().as_raw_handle() as HANDLE;
let mut mode: u32 = 0;
unsafe { GetConsoleMode(handle, &mut mode) != 0 }
}
#[cfg(not(any(unix, windows)))]
pub fn is_terminal<T>(_: T) -> bool {
false
}
#[cfg(all(test, unix, not(target_os = "l4re")))]
mod tests {
use super::*;
use crate::testutil::{ScriptedFd, attrs, open_pty_pair, opost, prime};
use std::fs::File;
const RAW_IFLAGS: libc::tcflag_t = libc::IGNBRK
| libc::BRKINT
| libc::PARMRK
| libc::ISTRIP
| libc::INLCR
| libc::IGNCR
| libc::ICRNL
| libc::IXON;
const RAW_LFLAGS: libc::tcflag_t =
libc::ECHO | libc::ECHONL | libc::ICANON | libc::ISIG | libc::IEXTEN;
const RAW_CFLAGS: libc::tcflag_t = libc::CSIZE | libc::PARENB;
fn assert_raw(f: &File, half: &str) {
let t = attrs(f);
assert_eq!(t.c_oflag & libc::OPOST, 0, "{half}: OPOST still set");
assert_eq!(
t.c_iflag & RAW_IFLAGS,
0,
"{half}: cooked input flags still set"
);
assert_eq!(
t.c_lflag & RAW_LFLAGS,
0,
"{half}: line-editing flags still set"
);
assert_eq!(
t.c_cflag & RAW_CFLAGS,
libc::CS8,
"{half}: not 8-bit, no parity"
);
assert_eq!(t.c_cc[libc::VMIN], 1, "{half}: VMIN");
assert_eq!(t.c_cc[libc::VTIME], 0, "{half}: VTIME");
}
fn assert_restored(before: &libc::termios, f: &File, half: &str) {
let now = attrs(f);
assert_eq!(
now.c_iflag & RAW_IFLAGS,
before.c_iflag & RAW_IFLAGS,
"{half}: input flags not restored"
);
assert_eq!(
now.c_oflag & libc::OPOST,
before.c_oflag & libc::OPOST,
"{half}: OPOST not restored"
);
assert_eq!(
now.c_lflag & RAW_LFLAGS,
before.c_lflag & RAW_LFLAGS,
"{half}: line-editing flags not restored"
);
assert_eq!(
now.c_cflag & RAW_CFLAGS,
before.c_cflag & RAW_CFLAGS,
"{half}: control flags not restored"
);
assert_eq!(
now.c_cc[libc::VMIN],
before.c_cc[libc::VMIN],
"{half}: VMIN not restored"
);
assert_eq!(
now.c_cc[libc::VTIME],
before.c_cc[libc::VTIME],
"{half}: VTIME not restored"
);
}
fn not_a_terminal() -> std::io::PipeReader {
std::io::pipe().expect("pipe").0
}
#[test]
fn get_state_reads_each_half_independently() {
let (Some((_ma, a)), Some((_mb, b))) = (open_pty_pair(), open_pty_pair()) else {
return;
};
prime(&a, true);
prime(&b, false);
let state = get_state(&a, &b).expect("both halves are terminals");
assert!(
state.input.expect("input half read").c_oflag & libc::OPOST != 0,
"input half must report the input device's flags"
);
assert!(
state.output.expect("output half read").c_oflag & libc::OPOST == 0,
"output half must report the output device's flags, not the input's"
);
}
#[test]
fn make_raw_and_restore_cover_both_terminals() {
let (Some((_ma, a)), Some((_mb, b))) = (open_pty_pair(), open_pty_pair()) else {
return;
};
prime(&a, true);
prime(&b, true);
let (before_a, before_b) = (attrs(&a), attrs(&b));
let original = make_raw_mode(&a, &b).expect("raw mode");
assert_raw(&a, "input half");
assert_raw(&b, "output half");
set_state(&a, &b, &original).expect("restore");
assert_restored(&before_a, &a, "input half");
assert_restored(&before_b, &b, "output half");
}
#[test]
fn non_terminal_half_is_skipped() {
let Some((_master, tty)) = open_pty_pair() else {
return;
};
prime(&tty, true);
let before = attrs(&tty);
let state = make_raw_mode(not_a_terminal(), &tty).expect("output half is a terminal");
assert!(state.input.is_none(), "a pipe is not a terminal");
assert!(state.output.is_some(), "the pty half must be recorded");
assert_raw(&tty, "output half");
set_state(not_a_terminal(), &tty, &state).expect("restore");
assert_restored(&before, &tty, "output half");
let state = make_raw_mode(&tty, not_a_terminal()).expect("input half is a terminal");
assert!(state.input.is_some(), "the pty half must be recorded");
assert!(state.output.is_none(), "a pipe is not a terminal");
assert_raw(&tty, "input half");
set_state(&tty, not_a_terminal(), &state).expect("restore");
assert_restored(&before, &tty, "input half");
}
#[test]
fn a_half_that_fails_is_reported_and_the_other_is_still_applied() {
let Some((_master, tty)) = open_pty_pair() else {
return;
};
prime(&tty, true);
let mut target = get_state(&tty, &tty).expect("pty is a terminal");
let clear_opost = |mut t: libc::termios| {
t.c_oflag &= !libc::OPOST;
t
};
target.input = target.input.map(clear_opost);
target.output = target.output.map(clear_opost);
assert!(
set_state(not_a_terminal(), &tty, &target).is_err(),
"a failing input half must be reported"
);
assert!(
!opost(&tty),
"the output half must be attempted even after the input half failed"
);
prime(&tty, true);
assert!(
set_state(&tty, not_a_terminal(), &target).is_err(),
"a failing output half must be reported"
);
assert!(!opost(&tty), "the input half must still be applied");
}
#[test]
fn get_state_errors_when_neither_half_is_a_terminal() {
assert!(get_state(not_a_terminal(), not_a_terminal()).is_err());
}
#[test]
fn a_failed_half_does_not_strand_the_half_that_succeeded() {
let (Some((_ma, a)), Some((_mb, b))) = (open_pty_pair(), open_pty_pair()) else {
return;
};
prime(&a, true);
prime(&b, true);
let (before_a, before_b) = (attrs(&a), attrs(&b));
let pipe = not_a_terminal();
let output = ScriptedFd::new(&[&b as &dyn AsFd, &pipe, &b]);
let Err(err) = make_raw_mode(&a, &output) else {
panic!("a pipe cannot be rawified, so make_raw_mode must fail");
};
assert!(
matches!(err.raw_os_error(), Some(libc::ENOTTY | libc::EINVAL)),
"expected a not-a-terminal error, got {err}"
);
assert_restored(&before_a, &a, "input half");
assert_restored(&before_b, &b, "output half");
}
}