use std::io::{self, Write};
use std::ops;
use sys::Termios;
use sys::attr::{get_terminal_attr, raw_terminal_attr, set_terminal_attr};
pub const CONTROL_SEQUENCE_TIMEOUT: u64 = 100;
pub struct RawTerminal<W: Write> {
prev_ios: Termios,
output: W,
}
impl<W: Write> Drop for RawTerminal<W> {
fn drop(&mut self) {
set_terminal_attr(&self.prev_ios).unwrap();
}
}
impl<W: Write> ops::Deref for RawTerminal<W> {
type Target = W;
fn deref(&self) -> &W {
&self.output
}
}
impl<W: Write> ops::DerefMut for RawTerminal<W> {
fn deref_mut(&mut self) -> &mut W {
&mut self.output
}
}
impl<W: Write> Write for RawTerminal<W> {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
self.output.write(buf)
}
fn flush(&mut self) -> io::Result<()> {
self.output.flush()
}
}
pub trait IntoRawMode: Write + Sized {
fn into_raw_mode(self) -> io::Result<RawTerminal<Self>>;
}
impl<W: Write> IntoRawMode for W {
fn into_raw_mode(self) -> io::Result<RawTerminal<W>> {
let mut ios = get_terminal_attr()?;
let prev_ios = ios;
raw_terminal_attr(&mut ios);
set_terminal_attr(&ios)?;
Ok(RawTerminal {
prev_ios: prev_ios,
output: self,
})
}
}
#[cfg(test)]
mod test {
use super::*;
use std::io::{Write, stdout};
#[test]
fn test_into_raw_mode() {
let mut out = stdout().into_raw_mode().unwrap();
out.write_all(b"this is a test, muahhahahah\r\n").unwrap();
drop(out);
}
}