Debian Codegraph @

Xtermina/src/event/source/unix.rs

raw symbols SCIP
1 // CREDIT: This is mostly a mirror of crossterm `tty` event source adjusted to use rustix
2 // exclusively, reaching into parts of the `filedescriptor` dependency (NOTE: which is part of the
3 // WezTerm repo) but reimplementing with rustix instead of libc.
4 // Crossterm: <https://github.com/crossterm-rs/crossterm/blob/36d95b26a26e64b0f8c12edfe11f410a6d56a812/src/event/source/unix/tty.rs>
5 // Termwiz: <https://github.com/wezterm/wezterm/blob/a87358516004a652ad840bc1661bdf65ffc89b43/filedescriptor/src/unix.rs#L444-L584>
6 use std::{
7 io::{self, Read, Write as _},
8 os::{
9 fd::{AsFd, BorrowedFd},
10 unix::net::UnixStream,
11 },
12 sync::Arc,
13 time::Duration,
14 };
15
16 use parking_lot::Mutex;
17 use rustix::termios;
18
19 use crate::{parse::Parser, terminal::FileDescriptor, Event};
20
21 use super::{EventSource, PollTimeout};
22
23 #[derive(Debug)]
24 pub struct UnixEventSource {
25 parser: Parser,
26 read: FileDescriptor,
27 write: FileDescriptor,
28 sigwinch_id: signal_hook::SigId,
29 sigwinch_pipe: UnixStream,
30 wake_pipe: UnixStream,
31 wake_pipe_write: Arc<Mutex<UnixStream>>,
32 }
33
34 #[derive(Debug, Clone)]
35 pub struct UnixWaker {
36 inner: Arc<Mutex<UnixStream>>,
37 }
38
39 impl UnixWaker {
40 pub fn wake(&self) -> io::Result<()> {
41 self.inner.lock().write_all(&[0])
42 }
43 }
44
45 impl UnixEventSource {
46 pub(crate) fn new(read: FileDescriptor, write: FileDescriptor) -> io::Result<Self> {
47 let (sigwinch_pipe, sigwinch_pipe_write) = UnixStream::pair()?;
48 let sigwinch_id = signal_hook::low_level::pipe::register(
49 signal_hook::consts::SIGWINCH,
50 sigwinch_pipe_write,
51 )?;
52 sigwinch_pipe.set_nonblocking(true)?;
53 let (wake_pipe, wake_pipe_write) = UnixStream::pair()?;
54 wake_pipe.set_nonblocking(true)?;
55 wake_pipe_write.set_nonblocking(true)?;
56
57 Ok(Self {
58 parser: Default::default(),
59 read,
60 write,
61 sigwinch_id,
62 sigwinch_pipe,
63 wake_pipe,
64 wake_pipe_write: Arc::new(Mutex::new(wake_pipe_write)),
65 })
66 }
67 }
68
69 impl Drop for UnixEventSource {
70 fn drop(&mut self) {
71 signal_hook::low_level::unregister(self.sigwinch_id);
72 }
73 }
74
75 impl EventSource for UnixEventSource {
76 fn waker(&self) -> UnixWaker {
77 UnixWaker {
78 inner: self.wake_pipe_write.clone(),
79 }
80 }
81
82 fn try_read(&mut self, timeout: Option<Duration>) -> io::Result<Option<Event>> {
83 let timeout = PollTimeout::new(timeout);
84
85 loop {
86 if let Some(event) = self.parser.pop() {
87 return Ok(Some(event));
88 }
89
90 let [read_ready, sigwinch_ready, wake_ready] = match poll(
91 [
92 self.read.as_fd(),
93 self.sigwinch_pipe.as_fd(),
94 self.wake_pipe.as_fd(),
95 ],
96 timeout.leftover(),
97 ) {
98 Ok(ready) => ready,
99 Err(err) if err.kind() == io::ErrorKind::Interrupted => continue,
100 Err(err) => return Err(err),
101 };
102
103 // The input/read pipe has data.
104 if read_ready {
105 let mut buffer = [0u8; 64];
106 let read_count = read_complete(&mut self.read, &mut buffer)?;
107 if read_count > 0 {
108 self.parser
109 .parse(&buffer[..read_count], read_count == buffer.len());
110 }
111 if let Some(event) = self.parser.pop() {
112 return Ok(Some(event));
113 }
114 if read_count == 0 {
115 break;
116 }
117 }
118
119 // SIGWINCH received.
120 if sigwinch_ready {
121 // Drain the pipe.
122 while read_complete(&self.sigwinch_pipe, &mut [0; 1024])? != 0 {}
123
124 let winsize = termios::tcgetwinsize(&self.write)?;
125 let event = Event::WindowResized(winsize.into());
126 return Ok(Some(event));
127 }
128
129 // Waker has awoken.
130 if wake_ready {
131 // Drain the pipe.
132 while read_complete(&self.wake_pipe, &mut [0; 1024])? != 0 {}
133
134 return Err(io::Error::new(
135 io::ErrorKind::Interrupted,
136 "Poll operation was woken up",
137 ));
138 }
139
140 if timeout.leftover().is_some_and(|t| t.is_zero()) {
141 break;
142 }
143 }
144
145 Ok(None)
146 }
147 }
148
149 fn read_complete<F: Read>(mut file: F, buf: &mut [u8]) -> io::Result<usize> {
150 loop {
151 match file.read(buf) {
152 Ok(read) => return Ok(read),
153 Err(err) => match err.kind() {
154 io::ErrorKind::WouldBlock => return Ok(0),
155 io::ErrorKind::Interrupted => continue,
156 _ => return Err(err),
157 },
158 }
159 }
160 }
161
162 /// A small abstraction over platform specific polling behavior.
163 ///
164 /// macOS `poll(2)` doesn't work on file descriptors to `/dev/tty` so we need to use `select(2)`
165 /// instead. This provides a function which abstracts over the parts of `poll(2)` and
166 /// `select(2)` we want. Specifically we are looking for `POLLIN` events from `poll(2)` and we
167 /// consider that to be "ready."
168 ///
169 /// This module is not meant to be generic. We consider `POLLIN` to be "ready" and do not look at
170 /// other poll flags. For the sake of simplicity we also only allow polling exactly three FDs at
171 /// a time - the exact amount we need for the event source.
172 fn poll(fds: [BorrowedFd<'_>; 3], timeout: Option<Duration>) -> std::io::Result<[bool; 3]> {
173 use rustix::event::Timespec;
174
175 #[cfg(not(target_os = "macos"))]
176 fn poll2(fds: [BorrowedFd<'_>; 3], timeout: Option<&Timespec>) -> io::Result<[bool; 3]> {
177 use rustix::event::{PollFd, PollFlags};
178 let mut fds = [
179 PollFd::new(&fds[0], PollFlags::IN),
180 PollFd::new(&fds[1], PollFlags::IN),
181 PollFd::new(&fds[2], PollFlags::IN),
182 ];
183
184 rustix::event::poll(&mut fds, timeout)?;
185
186 Ok([
187 fds[0].revents().contains(PollFlags::IN),
188 fds[1].revents().contains(PollFlags::IN),
189 fds[2].revents().contains(PollFlags::IN),
190 ])
191 }
192
193 #[cfg(target_os = "macos")]
194 fn select2(fds: [BorrowedFd<'_>; 3], timeout: Option<&Timespec>) -> io::Result<[bool; 3]> {
195 use rustix::event::{fd_set_insert, fd_set_num_elements, FdSetElement, FdSetIter};
196 use std::os::fd::AsRawFd;
197
198 let fds = [fds[0].as_raw_fd(), fds[1].as_raw_fd(), fds[2].as_raw_fd()];
199 // The array is non-empty so `max()` cannot return `None`.
200 let nfds = fds.iter().copied().max().unwrap() + 1;
201
202 let mut readfds = vec![FdSetElement::default(); fd_set_num_elements(fds.len(), nfds)];
203 for fd in fds {
204 fd_set_insert(&mut readfds, fd);
205 }
206
207 unsafe { rustix::event::select(nfds, Some(&mut readfds), None, None, timeout) }?;
208
209 let mut ready = [false; 3];
210 for (fd, is_ready) in fds.iter().copied().zip(ready.iter_mut()) {
211 if FdSetIter::new(&readfds).any(|set_fd| set_fd == fd) {
212 *is_ready = true;
213 }
214 }
215 Ok(ready)
216 }
217
218 #[cfg(not(target_os = "macos"))]
219 use poll2 as poll_impl;
220 #[cfg(target_os = "macos")]
221 use select2 as poll_impl;
222
223 let timespec = timeout.map(|timeout| timeout.try_into().unwrap());
224 poll_impl(fds, timespec.as_ref())
225 }