| 1 | use std::{collections::VecDeque, io, time::Duration}; |
| 2 | |
| 3 | use mio::{unix::SourceFd, Events, Interest, Poll, Token}; |
| 4 | use signal_hook_mio::v1_0::Signals; |
| 5 | |
| 6 | #[cfg(feature = "event-stream")] |
| 7 | use crate::event::sys::Waker; |
| 8 | use crate::event::{ |
| 9 | source::EventSource, sys::unix::parse::parse_event, timeout::PollTimeout, Event, InternalEvent, |
| 10 | }; |
| 11 | use crate::terminal::sys::file_descriptor::{tty_fd, FileDesc}; |
| 12 | |
| 13 | // Tokens to identify file descriptor |
| 14 | const TTY_TOKEN: Token = Token(0); |
| 15 | const SIGNAL_TOKEN: Token = Token(1); |
| 16 | #[cfg(feature = "event-stream")] |
| 17 | const WAKE_TOKEN: Token = Token(2); |
| 18 | |
| 19 | // I (@zrzka) wasn't able to read more than 1_022 bytes when testing |
| 20 | // reading on macOS/Linux -> we don't need bigger buffer and 1k of bytes |
| 21 | // is enough. |
| 22 | const TTY_BUFFER_SIZE: usize = 1_024; |
| 23 | |
| 24 | pub(crate) struct UnixInternalEventSource { |
| 25 | poll: Poll, |
| 26 | events: Events, |
| 27 | parser: Parser, |
| 28 | tty_buffer: [u8; TTY_BUFFER_SIZE], |
| 29 | tty_fd: FileDesc<'static>, |
| 30 | signals: Signals, |
| 31 | #[cfg(feature = "event-stream")] |
| 32 | waker: Waker, |
| 33 | } |
| 34 | |
| 35 | impl UnixInternalEventSource { |
| 36 | pub fn new() -> io::Result<Self> { |
| 37 | UnixInternalEventSource::from_file_descriptor(tty_fd()?) |
| 38 | } |
| 39 | |
| 40 | pub(crate) fn from_file_descriptor(input_fd: FileDesc<'static>) -> io::Result<Self> { |
| 41 | let poll = Poll::new()?; |
| 42 | let registry = poll.registry(); |
| 43 | |
| 44 | let tty_raw_fd = input_fd.raw_fd(); |
| 45 | let mut tty_ev = SourceFd(&tty_raw_fd); |
| 46 | registry.register(&mut tty_ev, TTY_TOKEN, Interest::READABLE)?; |
| 47 | |
| 48 | let mut signals = Signals::new([signal_hook::consts::SIGWINCH])?; |
| 49 | registry.register(&mut signals, SIGNAL_TOKEN, Interest::READABLE)?; |
| 50 | |
| 51 | #[cfg(feature = "event-stream")] |
| 52 | let waker = Waker::new(registry, WAKE_TOKEN)?; |
| 53 | |
| 54 | Ok(UnixInternalEventSource { |
| 55 | poll, |
| 56 | events: Events::with_capacity(3), |
| 57 | parser: Parser::default(), |
| 58 | tty_buffer: [0u8; TTY_BUFFER_SIZE], |
| 59 | tty_fd: input_fd, |
| 60 | signals, |
| 61 | #[cfg(feature = "event-stream")] |
| 62 | waker, |
| 63 | }) |
| 64 | } |
| 65 | } |
| 66 | |
| 67 | impl EventSource for UnixInternalEventSource { |
| 68 | fn try_read(&mut self, timeout: Option<Duration>) -> io::Result<Option<InternalEvent>> { |
| 69 | if let Some(event) = self.parser.next() { |
| 70 | return Ok(Some(event)); |
| 71 | } |
| 72 | |
| 73 | let timeout = PollTimeout::new(timeout); |
| 74 | |
| 75 | loop { |
| 76 | let tty_ready = self.tty_fd.read_ready()?; |
| 77 | let wait = if tty_ready { |
| 78 | Some(Duration::ZERO) |
| 79 | } else { |
| 80 | timeout.leftover() |
| 81 | }; |
| 82 | if let Err(e) = self.poll.poll(&mut self.events, wait) { |
| 83 | // Mio will throw an interrupted error in case of cursor position retrieval. We need to retry until it succeeds. |
| 84 | // Previous versions of Mio (< 0.7) would automatically retry the poll call if it was interrupted (if EINTR was returned). |
| 85 | // https://docs.rs/mio/0.7.0/mio/struct.Poll.html#notes |
| 86 | if e.kind() == io::ErrorKind::Interrupted { |
| 87 | if timeout.elapsed() { |
| 88 | return Ok(None); |
| 89 | } |
| 90 | continue; |
| 91 | } else { |
| 92 | return Err(e); |
| 93 | } |
| 94 | }; |
| 95 | |
| 96 | if self.events.is_empty() && !tty_ready { |
| 97 | // No readiness events = timeout |
| 98 | return Ok(None); |
| 99 | } |
| 100 | |
| 101 | let include_tty = |
| 102 | tty_ready && !self.events.iter().any(|event| event.token() == TTY_TOKEN); |
| 103 | for token in self |
| 104 | .events |
| 105 | .iter() |
| 106 | .map(|event| event.token()) |
| 107 | .chain(include_tty.then_some(TTY_TOKEN)) |
| 108 | { |
| 109 | match token { |
| 110 | TTY_TOKEN => { |
| 111 | loop { |
| 112 | if !self.tty_fd.read_ready()? { |
| 113 | break; |
| 114 | } |
| 115 | match self.tty_fd.read(&mut self.tty_buffer) { |
| 116 | Ok(0) => { |
| 117 | return Err(io::Error::new( |
| 118 | io::ErrorKind::UnexpectedEof, |
| 119 | "terminal input source closed", |
| 120 | )); |
| 121 | } |
| 122 | Ok(read_count) => { |
| 123 | self.parser.advance( |
| 124 | &self.tty_buffer[..read_count], |
| 125 | read_count == TTY_BUFFER_SIZE, |
| 126 | ); |
| 127 | } |
| 128 | Err(e) => { |
| 129 | // No more data to read at the moment. We will receive another event |
| 130 | if e.kind() == io::ErrorKind::WouldBlock { |
| 131 | break; |
| 132 | } |
| 133 | // once more data is available to read. |
| 134 | else if e.kind() == io::ErrorKind::Interrupted { |
| 135 | if timeout.elapsed() { |
| 136 | return Ok(None); |
| 137 | } |
| 138 | continue; |
| 139 | } else { |
| 140 | return Err(e); |
| 141 | } |
| 142 | } |
| 143 | }; |
| 144 | |
| 145 | if let Some(event) = self.parser.next() { |
| 146 | return Ok(Some(event)); |
| 147 | } |
| 148 | if timeout.elapsed() { |
| 149 | return Ok(None); |
| 150 | } |
| 151 | } |
| 152 | } |
| 153 | SIGNAL_TOKEN => { |
| 154 | if self.signals.pending().next() == Some(signal_hook::consts::SIGWINCH) { |
| 155 | // TODO Should we remove tput? |
| 156 | // |
| 157 | // This can take a really long time, because terminal::size can |
| 158 | // launch new process (tput) and then it parses its output. It's |
| 159 | // not a really long time from the absolute time point of view, but |
| 160 | // it's a really long time from the mio, async-std/tokio executor, ... |
| 161 | // point of view. |
| 162 | let new_size = crate::terminal::size()?; |
| 163 | return Ok(Some(InternalEvent::Event(Event::Resize( |
| 164 | new_size.0, new_size.1, |
| 165 | )))); |
| 166 | } |
| 167 | } |
| 168 | #[cfg(feature = "event-stream")] |
| 169 | WAKE_TOKEN => { |
| 170 | return Err(std::io::Error::new( |
| 171 | std::io::ErrorKind::Interrupted, |
| 172 | "Poll operation was woken up by `Waker::wake`", |
| 173 | )); |
| 174 | } |
| 175 | _ => unreachable!("Synchronize Evented handle registration & token handling"), |
| 176 | } |
| 177 | } |
| 178 | |
| 179 | // Processing above can take some time, check if timeout expired |
| 180 | if timeout.elapsed() { |
| 181 | return Ok(None); |
| 182 | } |
| 183 | } |
| 184 | } |
| 185 | |
| 186 | #[cfg(feature = "event-stream")] |
| 187 | fn waker(&self) -> Waker { |
| 188 | self.waker.clone() |
| 189 | } |
| 190 | } |
| 191 | |
| 192 | // |
| 193 | // Following `Parser` structure exists for two reasons: |
| 194 | // |
| 195 | // * mimic anes Parser interface |
| 196 | // * move the advancing, parsing, ... stuff out of the `try_read` method |
| 197 | // |
| 198 | #[derive(Debug)] |
| 199 | struct Parser { |
| 200 | buffer: Vec<u8>, |
| 201 | internal_events: VecDeque<InternalEvent>, |
| 202 | } |
| 203 | |
| 204 | impl Default for Parser { |
| 205 | fn default() -> Self { |
| 206 | Parser { |
| 207 | // This buffer is used for -> 1 <- ANSI escape sequence. Are we |
| 208 | // aware of any ANSI escape sequence that is bigger? Can we make |
| 209 | // it smaller? |
| 210 | // |
| 211 | // Probably not worth spending more time on this as "there's a plan" |
| 212 | // to use the anes crate parser. |
| 213 | buffer: Vec::with_capacity(256), |
| 214 | // TTY_BUFFER_SIZE is 1_024 bytes. How many ANSI escape sequences can |
| 215 | // fit? What is an average sequence length? Let's guess here |
| 216 | // and say that the average ANSI escape sequence length is 8 bytes. Thus |
| 217 | // the buffer size should be 1024/8=128 to avoid additional allocations |
| 218 | // when processing large amounts of data. |
| 219 | // |
| 220 | // There's no need to make it bigger, because when you look at the `try_read` |
| 221 | // method implementation, all events are consumed before the next TTY_BUFFER |
| 222 | // is processed -> events pushed. |
| 223 | internal_events: VecDeque::with_capacity(128), |
| 224 | } |
| 225 | } |
| 226 | } |
| 227 | |
| 228 | impl Parser { |
| 229 | fn advance(&mut self, buffer: &[u8], more: bool) { |
| 230 | for (idx, byte) in buffer.iter().enumerate() { |
| 231 | let more = idx + 1 < buffer.len() || more; |
| 232 | |
| 233 | self.buffer.push(*byte); |
| 234 | |
| 235 | match parse_event(&self.buffer, more) { |
| 236 | Ok(Some(ie)) => { |
| 237 | self.internal_events.push_back(ie); |
| 238 | self.buffer.clear(); |
| 239 | } |
| 240 | Ok(None) => { |
| 241 | // Event can't be parsed, because we don't have enough bytes for |
| 242 | // the current sequence. Keep the buffer and process next bytes. |
| 243 | } |
| 244 | Err(_) => { |
| 245 | // Event can't be parsed (not enough parameters, parameter is not a number, ...). |
| 246 | // Clear the buffer and continue with another sequence. |
| 247 | self.buffer.clear(); |
| 248 | } |
| 249 | } |
| 250 | } |
| 251 | } |
| 252 | } |
| 253 | |
| 254 | impl Iterator for Parser { |
| 255 | type Item = InternalEvent; |
| 256 | |
| 257 | fn next(&mut self) -> Option<Self::Item> { |
| 258 | self.internal_events.pop_front() |
| 259 | } |
| 260 | } |
| 261 |