-
-
Notifications
You must be signed in to change notification settings - Fork 332
Expand file tree
/
Copy pathtty.rs
More file actions
178 lines (142 loc) · 4.25 KB
/
tty.rs
File metadata and controls
178 lines (142 loc) · 4.25 KB
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
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
use std::fs::File;
use std::io;
use std::io::Write;
use std::mem::MaybeUninit;
use std::os::fd::RawFd;
use std::os::unix::prelude::AsRawFd;
use crate::utils::log;
pub struct Terminal {
settings: Option<TerminalSettings>,
alt_screen: bool,
}
impl Drop for Terminal {
fn drop(&mut self) {
self.teardown()
}
}
impl Terminal {
/// Setup the input stream to operate in raw mode.
/// Returns an object that'll revert terminal settings.
pub fn setup() -> Self {
Self {
settings: match TerminalSettings::open_raw() {
Ok(settings) => Some(settings),
Err(error) => {
log::error!("Failed to setup terminal: {error}");
None
}
},
alt_screen: if let Err(error) = TTY::enter_alt_screen() {
log::error!("Failed to enter alternative screen: {error}");
false
} else {
true
},
}
}
pub fn teardown(&mut self) {
if let Some(ref settings) = self.settings {
if let Err(error) = settings.apply() {
log::error!("Failed to revert terminal settings: {error}");
}
self.settings = None;
}
if self.alt_screen {
if let Err(error) = TTY::quit_alt_screen() {
log::error!("Failed to quit alternative screen: {error}");
}
self.alt_screen = false;
}
}
}
enum TTY {
Raw(RawFd),
File(File),
}
const SEQUENCES: [(u32, bool); 5] = [(1049, true), (1002, true), (1003, true), (1006, true), (25, false)];
impl TTY {
fn stdin() -> TTY {
let isatty = unsafe { libc::isatty(libc::STDIN_FILENO) };
if isatty != 1 {
if let Ok(file) = File::open("/dev/tty") {
return TTY::File(file);
}
}
TTY::Raw(libc::STDIN_FILENO)
}
fn enter_alt_screen() -> io::Result<()> {
let mut out = io::stdout();
for (sequence, enable) in SEQUENCES {
write!(out, "\x1b[?{}{}", sequence, if enable { "h" } else { "l" })?;
}
// Set the current foreground color to black
write!(out, "\x1b[48;2;0;0;0m")?;
// Query current foreground color to for true-color support detection
write!(out, "\x1bP$qm\x1b\\")?;
// Query current terminal name
write!(out, "\x1bP+q544e\x1b\\")?;
out.flush()
}
fn quit_alt_screen() -> io::Result<()> {
let mut out = io::stdout();
for (sequence, enable) in SEQUENCES {
write!(out, "\x1b[?{}{}", sequence, if enable { "l" } else { "h" })?;
}
out.flush()
}
fn as_raw_fd(self) -> RawFd {
match self {
TTY::Raw(fd) => fd,
TTY::File(file) => file.as_raw_fd(),
}
}
}
trait ToErr {
fn to_err(self) -> io::Result<()>;
}
impl ToErr for libc::c_int {
fn to_err(self) -> io::Result<()> {
if self == 0 {
Ok(())
} else {
Err(io::Error::last_os_error())
}
}
}
/// Safe wrapper around libc::termios
#[derive(Clone)]
struct TerminalSettings {
data: libc::termios,
}
impl TerminalSettings {
/// Fetch settings from the current TTY
fn open() -> io::Result<Self> {
let tty = TTY::stdin();
let mut term = MaybeUninit::uninit();
let data = unsafe {
libc::tcgetattr(tty.as_raw_fd(), term.as_mut_ptr()).to_err()?;
term.assume_init()
};
Ok(Self { data })
}
fn open_raw() -> io::Result<TerminalSettings> {
let mut raw = Self::open()?;
let settings = raw.clone();
raw.make_raw();
raw.apply()?;
Ok(settings)
}
/// Enable raw input
fn make_raw(&mut self) {
let c_oflag = self.data.c_oflag;
// Set the terminal to raw mode
unsafe { libc::cfmakeraw(&mut self.data) }
// Restore output flags, ensures carriage returns are consistent
self.data.c_oflag = c_oflag;
}
/// Apply the settings to the current TTY
fn apply(&self) -> io::Result<()> {
let tty = TTY::stdin();
unsafe { libc::tcsetattr(tty.as_raw_fd(), libc::TCSANOW, &self.data).to_err() }
}
}