1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
use std::io::{self, Write};
use std::ops;
#[cfg(target_os = "redox")]
pub struct RawTerminal<W: Write> {
output: W,
}
#[cfg(target_os = "redox")]
impl<W: Write> Drop for RawTerminal<W> {
fn drop(&mut self) {
write!(self, csi!("?82l")).unwrap();
}
}
#[cfg(not(target_os = "redox"))]
use termios::Termios;
#[cfg(not(target_os = "redox"))]
pub struct RawTerminal<W: Write> {
prev_ios: Termios,
output: W,
}
#[cfg(not(target_os = "redox"))]
impl<W: Write> Drop for RawTerminal<W> {
fn drop(&mut self) {
use termios::set_terminal_attr;
set_terminal_attr(&mut self.prev_ios as *mut _);
}
}
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 {
#[cfg(not(target_os = "redox"))]
fn into_raw_mode(self) -> io::Result<RawTerminal<W>> {
use termios::{cfmakeraw, get_terminal_attr, set_terminal_attr};
let (mut ios, exit) = get_terminal_attr();
let prev_ios = ios.clone();
if exit != 0 {
return Err(io::Error::new(io::ErrorKind::Other, "Unable to get Termios attribute."));
}
unsafe {
cfmakeraw(&mut ios);
}
if set_terminal_attr(&mut ios as *mut _) != 0 {
Err(io::Error::new(io::ErrorKind::Other, "Unable to set Termios attribute."))
} else {
let res = RawTerminal {
prev_ios: prev_ios,
output: self,
};
Ok(res)
}
}
#[cfg(target_os = "redox")]
fn into_raw_mode(mut self) -> io::Result<RawTerminal<W>> {
write!(self, csi!("?82h")).map(|_| {
RawTerminal { 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(b"this is a test, muahhahahah").unwrap();
}
}