diff --git a/Cargo.toml b/Cargo.toml index ac2d829db..6b918a3fc 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -15,6 +15,8 @@ num = "0.2.0" num-traits = "0.2.5" derive_builder = "0.5.1" semver = "0.9.0" +termios = "0.3.0" +libc = "0.2.42" [dependencies.num-derive] version = "~0.2" diff --git a/examples/hello.rs b/examples/hello.rs index d0c2dc277..904515349 100644 --- a/examples/hello.rs +++ b/examples/hello.rs @@ -10,9 +10,14 @@ use termwiz::color::AnsiColor; use termwiz::render::terminfo::TerminfoRenderer; use termwiz::render::Renderer; use termwiz::screen::{Change, Screen}; +use termwiz::terminal::{Terminal, UnixTerminal}; fn main() -> Result<(), Error> { let caps = Capabilities::new_from_env()?; + + let mut terminal = UnixTerminal::new()?; + terminal.set_raw_mode()?; + let renderer = TerminfoRenderer::new(caps); // TODO: obtain the size via termios @@ -24,7 +29,7 @@ fn main() -> Result<(), Error> { screen.add_change("Hello world\r\n"); let (seq, changes) = screen.get_changes(0); - let end_attr = renderer.render_to(&CellAttributes::default(), &changes, &mut stdout()); + let end_attr = renderer.render_to(&CellAttributes::default(), &changes, &mut terminal); //println!("changes: {:?}", changes); Ok(()) } diff --git a/src/istty.rs b/src/istty.rs new file mode 100644 index 000000000..f893092ad --- /dev/null +++ b/src/istty.rs @@ -0,0 +1,25 @@ +//! Making it a little more convenient and safe to query whether +//! something is a terminal teletype or not. +//! This module defines the IsTty trait and the is_tty method to +//! return true if the item represents a terminal. +//! The implementation at the time of writing is unix centric, but +//! the trait could also be ported to Windows and have meaning. +use libc; +use std::os::unix::io::AsRawFd; + +/// Adds the is_tty method to types that might represent a terminal +pub trait IsTty { + /// Returns true if the instance is a terminal teletype, false + /// otherwise. + fn is_tty(&self) -> bool; +} + +/// On unix, the `isatty()` library function returns true if a file +/// descriptor is a terminal. Let's implement `IsTty` for anything +/// that has an associated raw file descriptor. +impl IsTty for S { + fn is_tty(&self) -> bool { + let fd = self.as_raw_fd(); + unsafe { libc::isatty(fd) == 1 } + } +} diff --git a/src/lib.rs b/src/lib.rs index 832f23f83..b8f35d176 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,9 +1,11 @@ #[macro_use] extern crate failure; +extern crate libc; extern crate palette; extern crate semver; extern crate serde; extern crate terminfo; +extern crate termios; #[macro_use] extern crate serde_derive; extern crate num; @@ -17,5 +19,7 @@ pub mod caps; pub mod cell; pub mod color; pub mod escape; +pub mod istty; pub mod render; pub mod screen; +pub mod terminal; diff --git a/src/terminal.rs b/src/terminal.rs new file mode 100644 index 000000000..579af960d --- /dev/null +++ b/src/terminal.rs @@ -0,0 +1,138 @@ +//! An abstraction over a terminal device +//! `Terminal` implements `Read` and `Write` and offers methods +//! for changing the input mode. The interface considers the differences +//! between POSIX and Windows systems, but is implemented only for POSIX +//! at this time. + +use failure::Error; +use istty::IsTty; +use std::fs::{File, OpenOptions}; +use std::io::{stdin, stdout, Stdin, Stdout}; +use std::io::{Read, Result as IOResult, Write}; +use std::os::unix::io::{AsRawFd, RawFd}; +use termios::{cfmakeraw, tcsetattr, Termios, TCSANOW}; + +/// `Terminal` abstracts over some basic terminal capabilities. +/// If the `set_raw_mode` or `set_cooked_mode` functions are used in +/// any combination, the implementation is required to restore the +/// terminal mode that was in effect when it was created. +pub trait Terminal: Read + Write { + /// Raw mode disables input line buffering, allowing data to be + /// read as the user presses keys, disables local echo, so keys + /// pressed by the user do not implicitly render to the terminal + /// output, and disables canonicalization of unix newlines to CRLF. + fn set_raw_mode(&mut self) -> Result<(), Error>; + + /* + /// Sets the terminal to cooked mode, which is essentially the opposite + /// to raw mode: input and output processing are enabled. + fn set_cooked_mode(&mut self) -> Result<(), Error>; + + /// Queries the current screen size, returning width, height. + fn get_screen_size(&mut self) -> Result<(u32, u32), Error>; + + /// Sets the current screen size + fn set_screen_size(&mut self, width: u32, height: u32) -> Result<(), Error>; + */ +} + +enum Handle { + File(File), + Stdio { stdin: Stdin, stdout: Stdout }, +} + +impl Handle { + fn read T>(&mut self, func: F) -> T { + match self { + Handle::File(f) => func(f), + Handle::Stdio { stdin, .. } => func(stdin), + } + } + + fn write T>(&mut self, func: F) -> T { + match self { + Handle::File(f) => func(f), + Handle::Stdio { stdout, .. } => func(stdout), + } + } + + fn writable_fd(&self) -> RawFd { + match self { + Handle::File(f) => f.as_raw_fd(), + Handle::Stdio { stdout, .. } => stdout.as_raw_fd(), + } + } +} + +pub struct UnixTerminal { + handle: Handle, + saved_termios: Termios, +} + +impl UnixTerminal { + /// Attempt to create an instance from the stdin and stdout of the + /// process. This will fail unless both are associated with a tty. + pub fn new_from_stdio() -> Result { + let read = stdin(); + let write = stdout(); + + if !read.is_tty() || !write.is_tty() { + bail!("stdin and stdout must both be tty handles"); + } + let saved_termios = Termios::from_fd(write.as_raw_fd())?; + + Ok(UnixTerminal { + handle: Handle::Stdio { + stdin: read, + stdout: write, + }, + saved_termios, + }) + } + + /// Attempt to explicitly open a handle to the terminal device + /// (/dev/tty) and build a `UnixTerminal` from there. This will + /// yield a terminal even if the stdio streams have been redirected, + /// provided that the process has an associated controlling terminal. + pub fn new() -> Result { + let file = OpenOptions::new().read(true).write(true).open("/dev/tty")?; + let saved_termios = Termios::from_fd(file.as_raw_fd())?; + Ok(UnixTerminal { + handle: Handle::File(file), + saved_termios, + }) + } +} + +impl Read for UnixTerminal { + fn read(&mut self, buf: &mut [u8]) -> IOResult { + self.handle.read(|r| r.read(buf)) + } +} + +impl Write for UnixTerminal { + fn write(&mut self, buf: &[u8]) -> IOResult { + self.handle.write(|w| w.write(buf)) + } + + fn flush(&mut self) -> IOResult<()> { + self.handle.write(|w| w.flush()) + } +} + +impl Terminal for UnixTerminal { + fn set_raw_mode(&mut self) -> Result<(), Error> { + let fd = self.handle.writable_fd(); + let mut raw = Termios::from_fd(fd)?; + cfmakeraw(&mut raw); + tcsetattr(fd, TCSANOW, &raw).map_err(|e| format_err!("failed to set raw mode: {}", e)) + } +} + +impl Drop for UnixTerminal { + fn drop(&mut self) { + let fd = self.handle.writable_fd(); + tcsetattr(fd, TCSANOW, &self.saved_termios) + .expect("failed to restore original termios state"); + } +}