diff --git a/src/lib.rs b/src/lib.rs index d9fff93..8e1b2b0 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -21,6 +21,44 @@ extern "C" { static mut foregroundColor: c_int; } + +static mut SAVED_TERMIOS: Option = None; + +/// Turn off terminal echo and line buffering when passed an integer value +/// that evaluates to true. Restore the original terminal values when passed +/// an integer value that evaluates to false. +#[no_mangle] +pub extern "C" fn nmstermio_set_terminal(s: c_int) { + use std::os::fd::AsRawFd; + use std::fs::File; + use termios::*; + + let fd = if atty::is(atty::Stream::Stdin) { + println!("stdin"); + std::io::stdin().as_raw_fd() + } else { + println!("tty"); + File::open("/dev/tty").unwrap().as_raw_fd() + }; + println!("{fd}"); + + let mut termios = Termios::from_fd(fd).unwrap(); + + if s == 0 { + unsafe { + SAVED_TERMIOS = Some(termios.clone()); + } + termios.c_lflag &= !ICANON & !ECHO; + tcsetattr(fd, TCSANOW, &mut termios).unwrap(); + } else { + unsafe { + if let Some(saved_termios) = SAVED_TERMIOS { + tcsetattr(fd, TCSANOW, &saved_termios).unwrap(); + } + } + } +} + ///Sleep for the number of milliseconds indicated by argument #[no_mangle] pub extern "C" fn nmseffect_sleep(t: c_int) { diff --git a/src/nmstermio.c b/src/nmstermio.c index bcce7ee..ffc7be0 100644 --- a/src/nmstermio.c +++ b/src/nmstermio.c @@ -53,7 +53,7 @@ static int clearScr = 0; // clearScr flag int foregroundColor = COLOR_BLUE; // Foreground color setting // Function prototypes -static void nmstermio_set_terminal(int); +extern void nmstermio_set_terminal(int); /* * Initialize and configure the terminal for output. This usually means @@ -257,37 +257,3 @@ int nmstermio_get_cursor_row(void) { return row; } - -/* - * Turn off terminal echo and line buffering when passed an integer value - * that evaluates to true. Restore the original terminal values when passed - * an integer value that evaluates to false. - */ -static void nmstermio_set_terminal(int s) { - struct termios tp; - static struct termios save; - static int state = 1; - - if (!isatty(STDIN_FILENO)) { - stdin = freopen("/dev/tty", "r", stdin); - } - - if (s == 0) { - if (tcgetattr(STDIN_FILENO, &tp) == -1) { - return; - } - - save = tp; - - tp.c_lflag &=(~ICANON & ~ECHO); - - if (tcsetattr(STDIN_FILENO, TCSAFLUSH, &tp) == -1) { - return; - } - } else { - if (state == 0 && tcsetattr(STDIN_FILENO, TCSANOW, &save) == -1) - return; - } - - state = s; -}