Debian Codegraph @

src/event/source/unix/tty.rs

raw
1 #[cfg(feature = "libc")]
2 use std::os::unix::prelude::AsRawFd;
3 use std::{collections::VecDeque, io, os::unix::net::UnixStream, time::Duration};
4
5 #[cfg(not(feature = "libc"))]
6 use rustix::fd::{AsFd, AsRawFd};
7
8 use signal_hook::low_level::pipe;
9
10 use crate::event::timeout::PollTimeout;
11 use crate::event::Event;
12 use filedescriptor::{poll, pollfd, POLLIN};
13
14 #[cfg(feature = "event-stream")]
15 use crate::event::sys::Waker;
16 use crate::event::{source::EventSource, sys::unix::parse::parse_event, InternalEvent};
17 use crate::terminal::sys::file_descriptor::{tty_fd, FileDesc};
18
19 /// Holds a prototypical Waker and a receiver we can wait on when doing select().
20 #[cfg(feature = "event-stream")]
21 struct WakePipe {
22 receiver: UnixStream,
23 waker: Waker,
24 }
25
26 #[cfg(feature = "event-stream")]
27 impl WakePipe {
28 fn new() -> io::Result<Self> {
29 let (receiver, sender) = nonblocking_unix_pair()?;
30 Ok(WakePipe {
31 receiver,
32 waker: Waker::new(sender),
33 })
34 }
35 }
36
37 // I (@zrzka) wasn't able to read more than 1_022 bytes when testing
38 // reading on macOS/Linux -> we don't need bigger buffer and 1k of bytes
39 // is enough.
40 const TTY_BUFFER_SIZE: usize = 1_024;
41
42 pub(crate) struct UnixInternalEventSource {
43 parser: Parser,
44 tty_buffer: [u8; TTY_BUFFER_SIZE],
45 tty: FileDesc<'static>,
46 winch_signal_receiver: UnixStream,
47 #[cfg(feature = "event-stream")]
48 wake_pipe: WakePipe,
49 }
50
51 fn nonblocking_unix_pair() -> io::Result<(UnixStream, UnixStream)> {
52 let (receiver, sender) = UnixStream::pair()?;
53 receiver.set_nonblocking(true)?;
54 sender.set_nonblocking(true)?;
55 Ok((receiver, sender))
56 }
57
58 impl UnixInternalEventSource {
59 pub fn new() -> io::Result<Self> {
60 UnixInternalEventSource::from_file_descriptor(tty_fd()?)
61 }
62
63 pub(crate) fn from_file_descriptor(input_fd: FileDesc<'static>) -> io::Result<Self> {
64 Ok(UnixInternalEventSource {
65 parser: Parser::default(),
66 tty_buffer: [0u8; TTY_BUFFER_SIZE],
67 tty: input_fd,
68 winch_signal_receiver: {
69 let (receiver, sender) = nonblocking_unix_pair()?;
70 // Unregistering is unnecessary because EventSource is a singleton
71 #[cfg(feature = "libc")]
72 pipe::register(libc::SIGWINCH, sender)?;
73 #[cfg(not(feature = "libc"))]
74 pipe::register(rustix::process::Signal::WINCH.as_raw(), sender)?;
75 receiver
76 },
77 #[cfg(feature = "event-stream")]
78 wake_pipe: WakePipe::new()?,
79 })
80 }
81 }
82
83 /// read_complete reads from a non-blocking file descriptor
84 /// until the buffer is full or it would block.
85 ///
86 /// Similar to `std::io::Read::read_to_end`, except this function
87 /// only fills the given buffer and does not read beyond that.
88 fn read_complete(fd: &FileDesc, buf: &mut [u8]) -> io::Result<usize> {
89 loop {
90 match fd.read(buf) {
91 Ok(x) => return Ok(x),
92 Err(e) => match e.kind() {
93 io::ErrorKind::WouldBlock => return Ok(0),
94 io::ErrorKind::Interrupted => continue,
95 _ => return Err(e),
96 },
97 }
98 }
99 }
100
101 impl EventSource for UnixInternalEventSource {
102 fn try_read(&mut self, timeout: Option<Duration>) -> io::Result<Option<InternalEvent>> {
103 let timeout = PollTimeout::new(timeout);
104
105 fn make_pollfd<F: AsRawFd>(fd: &F) -> pollfd {
106 pollfd {
107 fd: fd.as_raw_fd(),
108 events: POLLIN,
109 revents: 0,
110 }
111 }
112
113 #[cfg(not(feature = "event-stream"))]
114 let mut fds = [
115 make_pollfd(&self.tty),
116 make_pollfd(&self.winch_signal_receiver),
117 ];
118
119 #[cfg(feature = "event-stream")]
120 let mut fds = [
121 make_pollfd(&self.tty),
122 make_pollfd(&self.winch_signal_receiver),
123 make_pollfd(&self.wake_pipe.receiver),
124 ];
125
126 while timeout.leftover().map_or(true, |t| !t.is_zero()) {
127 // check if there are buffered events from the last read
128 if let Some(event) = self.parser.next() {
129 return Ok(Some(event));
130 }
131 match poll(&mut fds, timeout.leftover()) {
132 Err(filedescriptor::Error::Poll(e)) | Err(filedescriptor::Error::Io(e)) => {
133 match e.kind() {
134 // retry on EINTR
135 io::ErrorKind::Interrupted => continue,
136 _ => return Err(e),
137 }
138 }
139 Err(e) => {
140 return Err(std::io::Error::new(
141 std::io::ErrorKind::Other,
142 format!("got unexpected error while polling: {:?}", e),
143 ))
144 }
145 Ok(_) => (),
146 };
147 if fds[0].revents & POLLIN != 0 {
148 loop {
149 let read_count = read_complete(&self.tty, &mut self.tty_buffer)?;
150 if read_count > 0 {
151 self.parser.advance(
152 &self.tty_buffer[..read_count],
153 read_count == TTY_BUFFER_SIZE,
154 );
155 }
156
157 if let Some(event) = self.parser.next() {
158 return Ok(Some(event));
159 }
160
161 if read_count == 0 {
162 break;
163 }
164 }
165 }
166 if fds[1].revents & POLLIN != 0 {
167 #[cfg(feature = "libc")]
168 let fd = FileDesc::new(self.winch_signal_receiver.as_raw_fd(), false);
169 #[cfg(not(feature = "libc"))]
170 let fd = FileDesc::Borrowed(self.winch_signal_receiver.as_fd());
171 // drain the pipe
172 while read_complete(&fd, &mut [0; 1024])? != 0 {}
173 // TODO Should we remove tput?
174 //
175 // This can take a really long time, because terminal::size can
176 // launch new process (tput) and then it parses its output. It's
177 // not a really long time from the absolute time point of view, but
178 // it's a really long time from the mio, async-std/tokio executor, ...
179 // point of view.
180 let new_size = crate::terminal::size()?;
181 return Ok(Some(InternalEvent::Event(Event::Resize(
182 new_size.0, new_size.1,
183 ))));
184 }
185
186 #[cfg(feature = "event-stream")]
187 if fds[2].revents & POLLIN != 0 {
188 #[cfg(feature = "libc")]
189 let fd = FileDesc::new(self.wake_pipe.receiver.as_raw_fd(), false);
190 #[cfg(not(feature = "libc"))]
191 let fd = FileDesc::Borrowed(self.wake_pipe.receiver.as_fd());
192 // drain the pipe
193 while read_complete(&fd, &mut [0; 1024])? != 0 {}
194
195 return Err(std::io::Error::new(
196 std::io::ErrorKind::Interrupted,
197 "Poll operation was woken up by `Waker::wake`",
198 ));
199 }
200 }
201 Ok(None)
202 }
203
204 #[cfg(feature = "event-stream")]
205 fn waker(&self) -> Waker {
206 self.wake_pipe.waker.clone()
207 }
208 }
209
210 //
211 // Following `Parser` structure exists for two reasons:
212 //
213 // * mimic anes Parser interface
214 // * move the advancing, parsing, ... stuff out of the `try_read` method
215 //
216 #[derive(Debug)]
217 struct Parser {
218 buffer: Vec<u8>,
219 internal_events: VecDeque<InternalEvent>,
220 }
221
222 impl Default for Parser {
223 fn default() -> Self {
224 Parser {
225 // This buffer is used for -> 1 <- ANSI escape sequence. Are we
226 // aware of any ANSI escape sequence that is bigger? Can we make
227 // it smaller?
228 //
229 // Probably not worth spending more time on this as "there's a plan"
230 // to use the anes crate parser.
231 buffer: Vec::with_capacity(256),
232 // TTY_BUFFER_SIZE is 1_024 bytes. How many ANSI escape sequences can
233 // fit? What is an average sequence length? Let's guess here
234 // and say that the average ANSI escape sequence length is 8 bytes. Thus
235 // the buffer size should be 1024/8=128 to avoid additional allocations
236 // when processing large amounts of data.
237 //
238 // There's no need to make it bigger, because when you look at the `try_read`
239 // method implementation, all events are consumed before the next TTY_BUFFER
240 // is processed -> events pushed.
241 internal_events: VecDeque::with_capacity(128),
242 }
243 }
244 }
245
246 impl Parser {
247 fn advance(&mut self, buffer: &[u8], more: bool) {
248 for (idx, byte) in buffer.iter().enumerate() {
249 let more = idx + 1 < buffer.len() || more;
250
251 self.buffer.push(*byte);
252
253 match parse_event(&self.buffer, more) {
254 Ok(Some(ie)) => {
255 self.internal_events.push_back(ie);
256 self.buffer.clear();
257 }
258 Ok(None) => {
259 // Event can't be parsed, because we don't have enough bytes for
260 // the current sequence. Keep the buffer and process next bytes.
261 }
262 Err(_) => {
263 // Event can't be parsed (not enough parameters, parameter is not a number, ...).
264 // Clear the buffer and continue with another sequence.
265 self.buffer.clear();
266 }
267 }
268 }
269 }
270 }
271
272 impl Iterator for Parser {
273 type Item = InternalEvent;
274
275 fn next(&mut self) -> Option<Self::Item> {
276 self.internal_events.pop_front()
277 }
278 }