| 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, POLLERR, POLLHUP, 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 | POLLHUP | POLLERR) != 0 { |
| 148 | loop { |
| 149 | if !self.tty.read_ready()? { |
| 150 | break; |
| 151 | } |
| 152 | let read_count = match self.tty.read(&mut self.tty_buffer) { |
| 153 | Ok(0) => { |
| 154 | return Err(io::Error::new( |
| 155 | io::ErrorKind::UnexpectedEof, |
| 156 | "terminal input source closed", |
| 157 | )); |
| 158 | } |
| 159 | Ok(read_count) => read_count, |
| 160 | Err(error) if error.kind() == io::ErrorKind::WouldBlock => { |
| 161 | if fds[0].revents & (POLLHUP | POLLERR) != 0 { |
| 162 | return Err(io::Error::new( |
| 163 | io::ErrorKind::BrokenPipe, |
| 164 | "terminal input source closed", |
| 165 | )); |
| 166 | } |
| 167 | break; |
| 168 | } |
| 169 | Err(error) if error.kind() == io::ErrorKind::Interrupted => { |
| 170 | if timeout.elapsed() { |
| 171 | return Ok(None); |
| 172 | } |
| 173 | continue; |
| 174 | } |
| 175 | Err(error) => return Err(error), |
| 176 | }; |
| 177 | self.parser.advance( |
| 178 | &self.tty_buffer[..read_count], |
| 179 | read_count == TTY_BUFFER_SIZE, |
| 180 | ); |
| 181 | |
| 182 | if let Some(event) = self.parser.next() { |
| 183 | return Ok(Some(event)); |
| 184 | } |
| 185 | if timeout.elapsed() { |
| 186 | return Ok(None); |
| 187 | } |
| 188 | } |
| 189 | } |
| 190 | if fds[1].revents & POLLIN != 0 { |
| 191 | #[cfg(feature = "libc")] |
| 192 | let fd = FileDesc::new(self.winch_signal_receiver.as_raw_fd(), false); |
| 193 | #[cfg(not(feature = "libc"))] |
| 194 | let fd = FileDesc::Borrowed(self.winch_signal_receiver.as_fd()); |
| 195 | // drain the pipe |
| 196 | while read_complete(&fd, &mut [0; 1024])? != 0 {} |
| 197 | // TODO Should we remove tput? |
| 198 | // |
| 199 | // This can take a really long time, because terminal::size can |
| 200 | // launch new process (tput) and then it parses its output. It's |
| 201 | // not a really long time from the absolute time point of view, but |
| 202 | // it's a really long time from the mio, async-std/tokio executor, ... |
| 203 | // point of view. |
| 204 | let new_size = crate::terminal::size()?; |
| 205 | return Ok(Some(InternalEvent::Event(Event::Resize( |
| 206 | new_size.0, new_size.1, |
| 207 | )))); |
| 208 | } |
| 209 | |
| 210 | #[cfg(feature = "event-stream")] |
| 211 | if fds[2].revents & POLLIN != 0 { |
| 212 | #[cfg(feature = "libc")] |
| 213 | let fd = FileDesc::new(self.wake_pipe.receiver.as_raw_fd(), false); |
| 214 | #[cfg(not(feature = "libc"))] |
| 215 | let fd = FileDesc::Borrowed(self.wake_pipe.receiver.as_fd()); |
| 216 | // drain the pipe |
| 217 | while read_complete(&fd, &mut [0; 1024])? != 0 {} |
| 218 | |
| 219 | return Err(std::io::Error::new( |
| 220 | std::io::ErrorKind::Interrupted, |
| 221 | "Poll operation was woken up by `Waker::wake`", |
| 222 | )); |
| 223 | } |
| 224 | } |
| 225 | Ok(None) |
| 226 | } |
| 227 | |
| 228 | #[cfg(feature = "event-stream")] |
| 229 | fn waker(&self) -> Waker { |
| 230 | self.wake_pipe.waker.clone() |
| 231 | } |
| 232 | } |
| 233 | |
| 234 | // |
| 235 | // Following `Parser` structure exists for two reasons: |
| 236 | // |
| 237 | // * mimic anes Parser interface |
| 238 | // * move the advancing, parsing, ... stuff out of the `try_read` method |
| 239 | // |
| 240 | #[derive(Debug)] |
| 241 | struct Parser { |
| 242 | buffer: Vec<u8>, |
| 243 | internal_events: VecDeque<InternalEvent>, |
| 244 | } |
| 245 | |
| 246 | impl Default for Parser { |
| 247 | fn default() -> Self { |
| 248 | Parser { |
| 249 | // This buffer is used for -> 1 <- ANSI escape sequence. Are we |
| 250 | // aware of any ANSI escape sequence that is bigger? Can we make |
| 251 | // it smaller? |
| 252 | // |
| 253 | // Probably not worth spending more time on this as "there's a plan" |
| 254 | // to use the anes crate parser. |
| 255 | buffer: Vec::with_capacity(256), |
| 256 | // TTY_BUFFER_SIZE is 1_024 bytes. How many ANSI escape sequences can |
| 257 | // fit? What is an average sequence length? Let's guess here |
| 258 | // and say that the average ANSI escape sequence length is 8 bytes. Thus |
| 259 | // the buffer size should be 1024/8=128 to avoid additional allocations |
| 260 | // when processing large amounts of data. |
| 261 | // |
| 262 | // There's no need to make it bigger, because when you look at the `try_read` |
| 263 | // method implementation, all events are consumed before the next TTY_BUFFER |
| 264 | // is processed -> events pushed. |
| 265 | internal_events: VecDeque::with_capacity(128), |
| 266 | } |
| 267 | } |
| 268 | } |
| 269 | |
| 270 | impl Parser { |
| 271 | fn advance(&mut self, buffer: &[u8], more: bool) { |
| 272 | for (idx, byte) in buffer.iter().enumerate() { |
| 273 | let more = idx + 1 < buffer.len() || more; |
| 274 | |
| 275 | self.buffer.push(*byte); |
| 276 | |
| 277 | match parse_event(&self.buffer, more) { |
| 278 | Ok(Some(ie)) => { |
| 279 | self.internal_events.push_back(ie); |
| 280 | self.buffer.clear(); |
| 281 | } |
| 282 | Ok(None) => { |
| 283 | // Event can't be parsed, because we don't have enough bytes for |
| 284 | // the current sequence. Keep the buffer and process next bytes. |
| 285 | } |
| 286 | Err(_) => { |
| 287 | // Event can't be parsed (not enough parameters, parameter is not a number, ...). |
| 288 | // Clear the buffer and continue with another sequence. |
| 289 | self.buffer.clear(); |
| 290 | } |
| 291 | } |
| 292 | } |
| 293 | } |
| 294 | } |
| 295 | |
| 296 | impl Iterator for Parser { |
| 297 | type Item = InternalEvent; |
| 298 | |
| 299 | fn next(&mut self) -> Option<Self::Item> { |
| 300 | self.internal_events.pop_front() |
| 301 | } |
| 302 | } |
| 303 |