Debian Codegraph @

Xtermina/src/terminal/unix.rs

raw symbols SCIP
1 use rustix::termios::{self, Termios};
2 use std::{
3 fs,
4 io::{self, BufWriter, IsTerminal as _, Write as _},
5 os::unix::prelude::*,
6 };
7
8 use crate::{event::source::UnixEventSource, Event, EventReader, WindowSize};
9
10 use super::Terminal;
11
12 const BUF_SIZE: usize = 4096;
13
14 // CREDIT: FileDescriptor stuff is mostly based on the WezTerm crate `filedescriptor` but has been
15 // rewritten with `rustix` instead of `libc`.
16 // <https://github.com/wezterm/wezterm/blob/a87358516004a652ad840bc1661bdf65ffc89b43/filedescriptor/src/unix.rs>
17
18 #[derive(Debug)]
19 pub enum FileDescriptor {
20 /// A file descriptor owned by Termina.
21 Owned(OwnedFd),
22
23 /// A borrowed process-global file descriptor such as stdin or stdout.
24 Borrowed(BorrowedFd<'static>),
25 }
26
27 impl AsFd for FileDescriptor {
28 fn as_fd(&self) -> BorrowedFd<'_> {
29 match self {
30 Self::Owned(fd) => fd.as_fd(),
31 Self::Borrowed(fd) => *fd,
32 }
33 }
34 }
35
36 impl FileDescriptor {
37 /// The process stdin file descriptor.
38 pub const STDIN: Self = Self::Borrowed(rustix::stdio::stdin());
39
40 /// The process stdout file descriptor.
41 pub const STDOUT: Self = Self::Borrowed(rustix::stdio::stdout());
42
43 fn try_clone(&self) -> io::Result<Self> {
44 let this = match self {
45 Self::Owned(fd) => Self::Owned(fd.try_clone()?),
46 Self::Borrowed(fd) => Self::Borrowed(*fd),
47 };
48 Ok(this)
49 }
50 }
51
52 impl io::Read for FileDescriptor {
53 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
54 let read = rustix::io::read(&self, buf)?;
55 Ok(read)
56 }
57 }
58
59 impl io::Write for FileDescriptor {
60 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
61 let written = rustix::io::write(self, buf)?;
62 Ok(written)
63 }
64
65 fn flush(&mut self) -> io::Result<()> {
66 Ok(())
67 }
68 }
69
70 fn open_pty() -> io::Result<(FileDescriptor, FileDescriptor)> {
71 let read = if io::stdin().is_terminal() {
72 FileDescriptor::STDIN
73 } else {
74 open_dev_tty()?
75 };
76 let write = if io::stdout().is_terminal() {
77 FileDescriptor::STDOUT
78 } else {
79 open_dev_tty()?
80 };
81
82 // Activate non-blocking mode for the reader.
83 // NOTE: this seems to make macOS consistently fail with io::ErrorKind::WouldBlock errors.
84 // rustix::io::ioctl_fionbio(&read, true)?;
85
86 Ok((read, write))
87 }
88
89 fn open_dev_tty() -> io::Result<FileDescriptor> {
90 let file = fs::OpenOptions::new()
91 .read(true)
92 .write(true)
93 .open("/dev/tty")?;
94 Ok(FileDescriptor::Owned(file.into()))
95 }
96
97 impl From<termios::Winsize> for WindowSize {
98 fn from(size: termios::Winsize) -> Self {
99 Self {
100 cols: size.ws_col,
101 rows: size.ws_row,
102 pixel_width: Some(size.ws_xpixel),
103 pixel_height: Some(size.ws_ypixel),
104 }
105 }
106 }
107
108 /// Unix terminal handle.
109 ///
110 /// `UnixTerminal` writes to stdout or `/dev/tty`, reads events from stdin or `/dev/tty`, and
111 /// restores the captured termios state when dropped.
112 ///
113 /// # Implementation Notes
114 ///
115 /// This type is based on [termwiz's Unix terminal], but Termina splits responsibilities
116 /// differently. TermWiz combines terminal dimensions, event reading, byte output, and terminal
117 /// state in one terminal type. Termina keeps byte output and terminal mode management here, while
118 /// event-source details live in `src/event/source/unix.rs`, closer to crossterm's event-source
119 /// shape. The implementation also uses `rustix` and has different `Drop` behavior, so it no longer
120 /// looks much like the original TermWiz code.
121 ///
122 /// [termwiz's Unix terminal]: https://docs.rs/termwiz/latest/termwiz/terminal/index.html
123 #[derive(Debug)]
124 pub struct UnixTerminal {
125 /// Shared wrapper around the reader (stdin or `/dev/tty`)
126 reader: EventReader,
127 /// Buffered handle to the writer (stdout or `/dev/tty`)
128 write: BufWriter<FileDescriptor>,
129 /// The termios of the PTY's writer detected during `Self::new`.
130 original_termios: Termios,
131 has_panic_hook: bool,
132 }
133
134 impl UnixTerminal {
135 /// Opens the Unix terminal for input and output.
136 ///
137 /// If stdin or stdout is not a terminal, Termina opens `/dev/tty` for that side. The original
138 /// termios state is captured so [`Terminal::enter_cooked_mode`] and `Drop` can restore it.
139 pub fn new() -> io::Result<Self> {
140 let (read, write) = open_pty()?;
141 let source = UnixEventSource::new(read, write.try_clone()?)?;
142 let original_termios = termios::tcgetattr(&write)?;
143 let reader = EventReader::new(source);
144
145 Ok(Self {
146 reader,
147 write: BufWriter::with_capacity(BUF_SIZE, write),
148 original_termios,
149 has_panic_hook: false,
150 })
151 }
152 }
153
154 impl Terminal for UnixTerminal {
155 fn enter_raw_mode(&mut self) -> io::Result<()> {
156 let mut termios = termios::tcgetattr(self.write.get_ref())?;
157 termios.make_raw();
158 termios::tcsetattr(
159 self.write.get_ref(),
160 termios::OptionalActions::Flush,
161 &termios,
162 )?;
163
164 Ok(())
165 }
166
167 fn enter_cooked_mode(&mut self) -> io::Result<()> {
168 termios::tcsetattr(
169 self.write.get_ref(),
170 termios::OptionalActions::Now,
171 &self.original_termios,
172 )?;
173 Ok(())
174 }
175
176 fn get_dimensions(&self) -> io::Result<WindowSize> {
177 let winsize = termios::tcgetwinsize(self.write.get_ref())?;
178 let mut size: WindowSize = winsize.into();
179 // Over a serial connection for example, the ioctl may quietly fail by returning zeroed
180 // rows and columns. Fall back to reading LINES/COLUMNS.
181 // <https://github.com/vim/vim/blob/b88f9e4a04ce9fb70abb7cdae17688aa4f49c8c9/src/os_unix.c#L4349-L4370>
182 if size.cols == 0 || size.rows == 0 {
183 if let Some(rows) = std::env::var("LINES")
184 .ok()
185 .and_then(|l| l.parse::<u16>().ok())
186 {
187 size.rows = rows;
188 }
189 if let Some(cols) = std::env::var("COLUMNS")
190 .ok()
191 .and_then(|c| c.parse::<u16>().ok())
192 {
193 size.cols = cols;
194 }
195 }
196 if size.cols == 0 || size.rows == 0 {
197 Err(io::Error::new(
198 io::ErrorKind::Other,
199 "cannot read non-zero cols/rows from ioctl or COLUMNS/LINES environment variables",
200 ))
201 } else {
202 Ok(size)
203 }
204 }
205
206 fn event_reader(&self) -> EventReader {
207 self.reader.clone()
208 }
209
210 fn poll<F: Fn(&Event) -> bool>(
211 &self,
212 filter: F,
213 timeout: Option<std::time::Duration>,
214 ) -> io::Result<bool> {
215 self.reader.poll(timeout, filter)
216 }
217
218 fn read<F: Fn(&Event) -> bool>(&self, filter: F) -> io::Result<Event> {
219 self.reader.read(filter)
220 }
221
222 fn set_panic_hook(&mut self, f: impl Fn(&mut FileDescriptor) + Send + Sync + 'static) {
223 let original_termios = self.original_termios.clone();
224 let hook = std::panic::take_hook();
225 std::panic::set_hook(Box::new(move |info| {
226 if let Ok((_read, mut write)) = open_pty() {
227 f(&mut write);
228 let _ = termios::tcsetattr(write, termios::OptionalActions::Now, &original_termios);
229 }
230 hook(info);
231 }));
232 self.has_panic_hook = true;
233 }
234 }
235
236 impl Drop for UnixTerminal {
237 fn drop(&mut self) {
238 if !self.has_panic_hook || !std::thread::panicking() {
239 let _ = self.flush();
240 let _ = self.enter_cooked_mode();
241 }
242 }
243 }
244
245 impl io::Write for UnixTerminal {
246 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
247 self.write.write(buf)
248 }
249
250 fn flush(&mut self) -> io::Result<()> {
251 self.write.flush()
252 }
253 }