1 //! Making it a little more convenient and safe to query whether 2 //! something is a terminal teletype or not. 3 //! This module defines the IsTty trait and the is_tty method to 4 //! return true if the item represents a terminal. 5 6 #[cfg(unix)] 7 use std::os::unix::io::AsRawFd; 8 #[cfg(windows)] 9 use std::os::windows::io::AsRawHandle; 10 #[cfg(windows)] 11 use winapi::um::consoleapi::GetConsoleMode; 12 13 /// Adds the `is_tty` method to types that might represent a terminal 14 /// 15 /// ```rust 16 /// use std::io::stdout; 17 /// use crossterm::tty::IsTty; 18 /// 19 /// let is_tty: bool = stdout().is_tty(); 20 /// ``` 21 pub trait IsTty { 22 /// Returns true when an instance is a terminal teletype, otherwise false. is_tty(&self) -> bool23 fn is_tty(&self) -> bool; 24 } 25 26 /// On unix, the `isatty()` function returns true if a file 27 /// descriptor is a terminal. 28 #[cfg(unix)] 29 impl<S: AsRawFd> IsTty for S { is_tty(&self) -> bool30 fn is_tty(&self) -> bool { 31 let fd = self.as_raw_fd(); 32 unsafe { libc::isatty(fd) == 1 } 33 } 34 } 35 36 /// On windows, `GetConsoleMode` will return true if we are in a terminal. 37 /// Otherwise false. 38 #[cfg(windows)] 39 impl<S: AsRawHandle> IsTty for S { is_tty(&self) -> bool40 fn is_tty(&self) -> bool { 41 let mut mode = 0; 42 let ok = unsafe { GetConsoleMode(self.as_raw_handle() as *mut _, &mut mode) }; 43 ok == 1 44 } 45 } 46