Skip to content

Commit

Permalink
Prefer /dev/tty over stdin in terminal functions
Browse files Browse the repository at this point in the history
This is part of crossterm-rs#500.
  • Loading branch information
acidghost committed Oct 24, 2020
1 parent 4b1c857 commit 89ef2ad
Showing 1 changed file with 13 additions and 10 deletions.
23 changes: 13 additions & 10 deletions src/terminal/sys/unix.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
//! UNIX related logic for terminal manipulation.
use std::{io, mem, process, sync::Mutex};

use crate::event::sys::unix::file_descriptor::FileDesc;
use crate::event::sys::unix::file_descriptor::{tty_fd, FileDesc};
use lazy_static::lazy_static;
use libc::{
cfmakeraw, ioctl, tcgetattr, tcsetattr, termios as Termios, winsize, STDIN_FILENO,
STDOUT_FILENO, TCSANOW, TIOCGWINSZ,
cfmakeraw, ioctl, tcgetattr, tcsetattr, termios as Termios, winsize, STDOUT_FILENO, TCSANOW,
TIOCGWINSZ,
};

use crate::error::{ErrorKind, Result};
Expand Down Expand Up @@ -54,11 +54,13 @@ pub(crate) fn enable_raw_mode() -> Result<()> {
return Ok(());
}

let mut ios = get_terminal_attr()?;
let tty = tty_fd()?;
let fd = tty.raw_fd();
let mut ios = get_terminal_attr(fd)?;
let original_mode_ios = ios;

raw_terminal_attr(&mut ios);
set_terminal_attr(&ios)?;
set_terminal_attr(fd, &ios)?;

// Keep it last - set the original mode only if we were able to switch to the raw mode
*original_mode = Some(original_mode_ios);
Expand All @@ -70,7 +72,8 @@ pub(crate) fn disable_raw_mode() -> Result<()> {
let mut original_mode = TERMINAL_MODE_PRIOR_RAW_MODE.lock().unwrap();

if let Some(original_mode_ios) = original_mode.as_ref() {
set_terminal_attr(original_mode_ios)?;
let tty = tty_fd()?;
set_terminal_attr(tty.raw_fd(), original_mode_ios)?;
// Keep it last - remove the original mode only if we were able to switch back
*original_mode = None;
}
Expand Down Expand Up @@ -116,16 +119,16 @@ fn raw_terminal_attr(termios: &mut Termios) {
unsafe { cfmakeraw(termios) }
}

fn get_terminal_attr() -> Result<Termios> {
fn get_terminal_attr(fd: i32) -> Result<Termios> {
unsafe {
let mut termios = mem::zeroed();
wrap_with_result(tcgetattr(STDIN_FILENO, &mut termios))?;
wrap_with_result(tcgetattr(fd, &mut termios))?;
Ok(termios)
}
}

fn set_terminal_attr(termios: &Termios) -> Result<bool> {
wrap_with_result(unsafe { tcsetattr(STDIN_FILENO, TCSANOW, termios) })
fn set_terminal_attr(fd: i32, termios: &Termios) -> Result<bool> {
wrap_with_result(unsafe { tcsetattr(fd, TCSANOW, termios) })
}

pub fn wrap_with_result(result: i32) -> Result<bool> {
Expand Down

0 comments on commit 89ef2ad

Please sign in to comment.