use std::fs::{File, OpenOptions};
use std::io;
use std::os::fd::AsFd;
use rustix::fs::{OFlags, fcntl_getfl, fcntl_setfl};
use rustix::process::getpgrp;
use rustix::termios::{OptionalActions, Termios, tcgetattr, tcgetpgrp, tcsetattr};
use signal_hook::consts::SIGTTOU;
use signal_hook::low_level;
pub fn open() -> io::Result<File> {
OpenOptions::new().read(true).write(true).open("/dev/tty")
}
pub fn open_nonblocking() -> io::Result<File> {
let tty = open()?;
fcntl_setfl(&tty, fcntl_getfl(&tty)? | OFlags::NONBLOCK)?;
Ok(tty)
}
pub fn is_foreground(tty: impl AsFd) -> bool {
tcgetpgrp(tty).is_ok_and(|group| group == getpgrp())
}
pub fn wait_until_foreground(tty: impl AsFd) -> bool {
is_foreground(&tty) || (low_level::raise(SIGTTOU).is_ok() && is_foreground(&tty))
}
pub struct RawMode<T: AsFd> {
tty: T,
saved: Termios,
}
impl<T: AsFd> RawMode<T> {
pub fn enable(tty: T) -> io::Result<Self> {
let saved = tcgetattr(&tty)?;
let mut raw = saved.clone();
raw.make_raw();
tcsetattr(&tty, OptionalActions::Now, &raw)?;
Ok(Self { tty, saved })
}
pub fn saved(&self) -> &Termios {
&self.saved
}
}
impl<T: AsFd> Drop for RawMode<T> {
fn drop(&mut self) {
let _ = tcsetattr(&self.tty, OptionalActions::Flush, &self.saved);
}
}