| 1 | use std::{collections::vec_deque::VecDeque, io, time::Duration}; |
| 2 | |
| 3 | #[cfg(unix)] |
| 4 | use crate::event::source::unix::UnixInternalEventSource; |
| 5 | #[cfg(windows)] |
| 6 | use crate::event::source::windows::WindowsEventSource; |
| 7 | #[cfg(feature = "event-stream")] |
| 8 | use crate::event::sys::Waker; |
| 9 | use crate::event::{filter::Filter, source::EventSource, timeout::PollTimeout, InternalEvent}; |
| 10 | |
| 11 | /// Can be used to read `InternalEvent`s. |
| 12 | pub(crate) struct InternalEventReader { |
| 13 | events: VecDeque<InternalEvent>, |
| 14 | source: Option<Box<dyn EventSource>>, |
| 15 | skipped_events: Vec<InternalEvent>, |
| 16 | } |
| 17 | |
| 18 | impl Default for InternalEventReader { |
| 19 | fn default() -> Self { |
| 20 | #[cfg(windows)] |
| 21 | let source = WindowsEventSource::new(); |
| 22 | #[cfg(unix)] |
| 23 | let source = UnixInternalEventSource::new(); |
| 24 | |
| 25 | let source = source.ok().map(|x| Box::new(x) as Box<dyn EventSource>); |
| 26 | |
| 27 | InternalEventReader { |
| 28 | source, |
| 29 | events: VecDeque::with_capacity(32), |
| 30 | skipped_events: Vec::with_capacity(32), |
| 31 | } |
| 32 | } |
| 33 | } |
| 34 | |
| 35 | impl InternalEventReader { |
| 36 | /// Returns a `Waker` allowing to wake/force the `poll` method to return `Ok(false)`. |
| 37 | #[cfg(feature = "event-stream")] |
| 38 | pub(crate) fn waker(&self) -> Waker { |
| 39 | self.source.as_ref().expect("reader source not set").waker() |
| 40 | } |
| 41 | |
| 42 | pub(crate) fn poll<F>(&mut self, timeout: Option<Duration>, filter: &F) -> io::Result<bool> |
| 43 | where |
| 44 | F: Filter, |
| 45 | { |
| 46 | for event in &self.events { |
| 47 | if filter.eval(event) { |
| 48 | return Ok(true); |
| 49 | } |
| 50 | } |
| 51 | |
| 52 | let event_source = match self.source.as_mut() { |
| 53 | Some(source) => source, |
| 54 | None => { |
| 55 | return Err(std::io::Error::new( |
| 56 | std::io::ErrorKind::Other, |
| 57 | "Failed to initialize input reader", |
| 58 | )) |
| 59 | } |
| 60 | }; |
| 61 | |
| 62 | let poll_timeout = PollTimeout::new(timeout); |
| 63 | |
| 64 | loop { |
| 65 | let maybe_event = match event_source.try_read(poll_timeout.leftover()) { |
| 66 | Ok(None) => None, |
| 67 | Ok(Some(event)) => { |
| 68 | if filter.eval(&event) { |
| 69 | Some(event) |
| 70 | } else { |
| 71 | self.skipped_events.push(event); |
| 72 | None |
| 73 | } |
| 74 | } |
| 75 | Err(e) => { |
| 76 | self.events.extend(self.skipped_events.drain(..)); |
| 77 | if e.kind() == io::ErrorKind::Interrupted { |
| 78 | return Ok(false); |
| 79 | } |
| 80 | |
| 81 | return Err(e); |
| 82 | } |
| 83 | }; |
| 84 | |
| 85 | if poll_timeout.elapsed() || maybe_event.is_some() { |
| 86 | self.events.extend(self.skipped_events.drain(..)); |
| 87 | |
| 88 | if let Some(event) = maybe_event { |
| 89 | self.events.push_front(event); |
| 90 | return Ok(true); |
| 91 | } |
| 92 | |
| 93 | return Ok(false); |
| 94 | } |
| 95 | } |
| 96 | } |
| 97 | |
| 98 | pub(crate) fn read<F>(&mut self, filter: &F) -> io::Result<InternalEvent> |
| 99 | where |
| 100 | F: Filter, |
| 101 | { |
| 102 | let mut skipped_events = VecDeque::new(); |
| 103 | |
| 104 | loop { |
| 105 | while let Some(event) = self.events.pop_front() { |
| 106 | if filter.eval(&event) { |
| 107 | while let Some(event) = skipped_events.pop_front() { |
| 108 | self.events.push_back(event); |
| 109 | } |
| 110 | |
| 111 | return Ok(event); |
| 112 | } else { |
| 113 | // We can not directly write events back to `self.events`. |
| 114 | // If we did, we would put our self's into an endless loop |
| 115 | // that would enqueue -> dequeue -> enqueue etc. |
| 116 | // This happens because `poll` in this function will always return true if there are events in it's. |
| 117 | // And because we just put the non-fulfilling event there this is going to be the case. |
| 118 | // Instead we can store them into the temporary buffer, |
| 119 | // and then when the filter is fulfilled write all events back in order. |
| 120 | skipped_events.push_back(event); |
| 121 | } |
| 122 | } |
| 123 | |
| 124 | if let Err(error) = self.poll(None, filter) { |
| 125 | while let Some(event) = skipped_events.pop_back() { |
| 126 | self.events.push_front(event); |
| 127 | } |
| 128 | return Err(error); |
| 129 | } |
| 130 | } |
| 131 | } |
| 132 | } |
| 133 | |
| 134 | #[cfg(test)] |
| 135 | mod tests { |
| 136 | use std::io; |
| 137 | use std::{collections::VecDeque, time::Duration}; |
| 138 | |
| 139 | #[cfg(unix)] |
| 140 | use super::super::filter::CursorPositionFilter; |
| 141 | use super::{super::Event, EventSource, Filter, InternalEvent, InternalEventReader}; |
| 142 | |
| 143 | #[derive(Debug, Clone)] |
| 144 | pub(crate) struct InternalEventFilter; |
| 145 | |
| 146 | impl Filter for InternalEventFilter { |
| 147 | fn eval(&self, _: &InternalEvent) -> bool { |
| 148 | true |
| 149 | } |
| 150 | } |
| 151 | |
| 152 | #[test] |
| 153 | fn test_poll_fails_without_event_source() { |
| 154 | let mut reader = InternalEventReader { |
| 155 | events: VecDeque::new(), |
| 156 | source: None, |
| 157 | skipped_events: Vec::with_capacity(32), |
| 158 | }; |
| 159 | |
| 160 | assert!(reader.poll(None, &InternalEventFilter).is_err()); |
| 161 | assert!(reader |
| 162 | .poll(Some(Duration::from_secs(0)), &InternalEventFilter) |
| 163 | .is_err()); |
| 164 | assert!(reader |
| 165 | .poll(Some(Duration::from_secs(10)), &InternalEventFilter) |
| 166 | .is_err()); |
| 167 | } |
| 168 | |
| 169 | #[test] |
| 170 | fn test_poll_returns_true_for_matching_event_in_queue_at_front() { |
| 171 | let mut reader = InternalEventReader { |
| 172 | events: vec![InternalEvent::Event(Event::Resize(10, 10))].into(), |
| 173 | source: None, |
| 174 | skipped_events: Vec::with_capacity(32), |
| 175 | }; |
| 176 | |
| 177 | assert!(reader.poll(None, &InternalEventFilter).unwrap()); |
| 178 | } |
| 179 | |
| 180 | #[test] |
| 181 | #[cfg(unix)] |
| 182 | fn test_poll_returns_true_for_matching_event_in_queue_at_back() { |
| 183 | let mut reader = InternalEventReader { |
| 184 | events: vec![ |
| 185 | InternalEvent::Event(Event::Resize(10, 10)), |
| 186 | InternalEvent::CursorPosition(10, 20), |
| 187 | ] |
| 188 | .into(), |
| 189 | source: None, |
| 190 | skipped_events: Vec::with_capacity(32), |
| 191 | }; |
| 192 | |
| 193 | assert!(reader.poll(None, &CursorPositionFilter).unwrap()); |
| 194 | } |
| 195 | |
| 196 | #[test] |
| 197 | fn test_read_returns_matching_event_in_queue_at_front() { |
| 198 | const EVENT: InternalEvent = InternalEvent::Event(Event::Resize(10, 10)); |
| 199 | |
| 200 | let mut reader = InternalEventReader { |
| 201 | events: vec![EVENT].into(), |
| 202 | source: None, |
| 203 | skipped_events: Vec::with_capacity(32), |
| 204 | }; |
| 205 | |
| 206 | assert_eq!(reader.read(&InternalEventFilter).unwrap(), EVENT); |
| 207 | } |
| 208 | |
| 209 | #[test] |
| 210 | #[cfg(unix)] |
| 211 | fn test_read_returns_matching_event_in_queue_at_back() { |
| 212 | const CURSOR_EVENT: InternalEvent = InternalEvent::CursorPosition(10, 20); |
| 213 | |
| 214 | let mut reader = InternalEventReader { |
| 215 | events: vec![InternalEvent::Event(Event::Resize(10, 10)), CURSOR_EVENT].into(), |
| 216 | source: None, |
| 217 | skipped_events: Vec::with_capacity(32), |
| 218 | }; |
| 219 | |
| 220 | assert_eq!(reader.read(&CursorPositionFilter).unwrap(), CURSOR_EVENT); |
| 221 | } |
| 222 | |
| 223 | #[test] |
| 224 | #[cfg(unix)] |
| 225 | fn test_read_does_not_consume_skipped_event() { |
| 226 | const SKIPPED_EVENT: InternalEvent = InternalEvent::Event(Event::Resize(10, 10)); |
| 227 | const CURSOR_EVENT: InternalEvent = InternalEvent::CursorPosition(10, 20); |
| 228 | |
| 229 | let mut reader = InternalEventReader { |
| 230 | events: vec![SKIPPED_EVENT, CURSOR_EVENT].into(), |
| 231 | source: None, |
| 232 | skipped_events: Vec::with_capacity(32), |
| 233 | }; |
| 234 | |
| 235 | assert_eq!(reader.read(&CursorPositionFilter).unwrap(), CURSOR_EVENT); |
| 236 | assert_eq!(reader.read(&InternalEventFilter).unwrap(), SKIPPED_EVENT); |
| 237 | |
| 238 | const LATER_EVENT: InternalEvent = InternalEvent::Event(Event::Resize(20, 30)); |
| 239 | reader.events.push_back(SKIPPED_EVENT); |
| 240 | reader.source = Some(Box::new(FakeSource::new(&[LATER_EVENT, CURSOR_EVENT]))); |
| 241 | assert!(reader.read(&CursorPositionFilter).is_err()); |
| 242 | assert_eq!(reader.read(&InternalEventFilter).unwrap(), SKIPPED_EVENT); |
| 243 | assert_eq!(reader.read(&InternalEventFilter).unwrap(), LATER_EVENT); |
| 244 | assert_eq!(reader.read(&CursorPositionFilter).unwrap(), CURSOR_EVENT); |
| 245 | } |
| 246 | |
| 247 | #[test] |
| 248 | fn test_poll_timeouts_if_source_has_no_events() { |
| 249 | let source = FakeSource::default(); |
| 250 | |
| 251 | let mut reader = InternalEventReader { |
| 252 | events: VecDeque::new(), |
| 253 | source: Some(Box::new(source)), |
| 254 | skipped_events: Vec::with_capacity(32), |
| 255 | }; |
| 256 | |
| 257 | assert!(!reader |
| 258 | .poll(Some(Duration::from_secs(0)), &InternalEventFilter) |
| 259 | .unwrap()); |
| 260 | } |
| 261 | |
| 262 | #[test] |
| 263 | fn test_poll_returns_true_if_source_has_at_least_one_event() { |
| 264 | let source = FakeSource::with_events(&[InternalEvent::Event(Event::Resize(10, 10))]); |
| 265 | |
| 266 | let mut reader = InternalEventReader { |
| 267 | events: VecDeque::new(), |
| 268 | source: Some(Box::new(source)), |
| 269 | skipped_events: Vec::with_capacity(32), |
| 270 | }; |
| 271 | |
| 272 | assert!(reader.poll(None, &InternalEventFilter).unwrap()); |
| 273 | assert!(reader |
| 274 | .poll(Some(Duration::from_secs(0)), &InternalEventFilter) |
| 275 | .unwrap()); |
| 276 | } |
| 277 | |
| 278 | #[test] |
| 279 | fn test_reads_returns_event_if_source_has_at_least_one_event() { |
| 280 | const EVENT: InternalEvent = InternalEvent::Event(Event::Resize(10, 10)); |
| 281 | |
| 282 | let source = FakeSource::with_events(&[EVENT]); |
| 283 | |
| 284 | let mut reader = InternalEventReader { |
| 285 | events: VecDeque::new(), |
| 286 | source: Some(Box::new(source)), |
| 287 | skipped_events: Vec::with_capacity(32), |
| 288 | }; |
| 289 | |
| 290 | assert_eq!(reader.read(&InternalEventFilter).unwrap(), EVENT); |
| 291 | } |
| 292 | |
| 293 | #[test] |
| 294 | fn test_read_returns_events_if_source_has_events() { |
| 295 | const EVENT: InternalEvent = InternalEvent::Event(Event::Resize(10, 10)); |
| 296 | |
| 297 | let source = FakeSource::with_events(&[EVENT, EVENT, EVENT]); |
| 298 | |
| 299 | let mut reader = InternalEventReader { |
| 300 | events: VecDeque::new(), |
| 301 | source: Some(Box::new(source)), |
| 302 | skipped_events: Vec::with_capacity(32), |
| 303 | }; |
| 304 | |
| 305 | assert_eq!(reader.read(&InternalEventFilter).unwrap(), EVENT); |
| 306 | assert_eq!(reader.read(&InternalEventFilter).unwrap(), EVENT); |
| 307 | assert_eq!(reader.read(&InternalEventFilter).unwrap(), EVENT); |
| 308 | } |
| 309 | |
| 310 | #[test] |
| 311 | fn test_poll_returns_false_after_all_source_events_are_consumed() { |
| 312 | const EVENT: InternalEvent = InternalEvent::Event(Event::Resize(10, 10)); |
| 313 | |
| 314 | let source = FakeSource::with_events(&[EVENT, EVENT, EVENT]); |
| 315 | |
| 316 | let mut reader = InternalEventReader { |
| 317 | events: VecDeque::new(), |
| 318 | source: Some(Box::new(source)), |
| 319 | skipped_events: Vec::with_capacity(32), |
| 320 | }; |
| 321 | |
| 322 | assert_eq!(reader.read(&InternalEventFilter).unwrap(), EVENT); |
| 323 | assert_eq!(reader.read(&InternalEventFilter).unwrap(), EVENT); |
| 324 | assert_eq!(reader.read(&InternalEventFilter).unwrap(), EVENT); |
| 325 | assert!(!reader |
| 326 | .poll(Some(Duration::from_secs(0)), &InternalEventFilter) |
| 327 | .unwrap()); |
| 328 | } |
| 329 | |
| 330 | #[test] |
| 331 | fn test_poll_propagates_error() { |
| 332 | let mut reader = InternalEventReader { |
| 333 | events: VecDeque::new(), |
| 334 | source: Some(Box::new(FakeSource::new(&[]))), |
| 335 | skipped_events: Vec::with_capacity(32), |
| 336 | }; |
| 337 | |
| 338 | assert_eq!( |
| 339 | reader |
| 340 | .poll(Some(Duration::from_secs(0)), &InternalEventFilter) |
| 341 | .err() |
| 342 | .map(|e| format!("{:?}", &e.kind())), |
| 343 | Some(format!("{:?}", io::ErrorKind::Other)) |
| 344 | ); |
| 345 | } |
| 346 | |
| 347 | #[test] |
| 348 | fn test_read_propagates_error() { |
| 349 | let mut reader = InternalEventReader { |
| 350 | events: VecDeque::new(), |
| 351 | source: Some(Box::new(FakeSource::new(&[]))), |
| 352 | skipped_events: Vec::with_capacity(32), |
| 353 | }; |
| 354 | |
| 355 | assert_eq!( |
| 356 | reader |
| 357 | .read(&InternalEventFilter) |
| 358 | .err() |
| 359 | .map(|e| format!("{:?}", &e.kind())), |
| 360 | Some(format!("{:?}", io::ErrorKind::Other)) |
| 361 | ); |
| 362 | } |
| 363 | |
| 364 | #[test] |
| 365 | fn test_poll_continues_after_error() { |
| 366 | const EVENT: InternalEvent = InternalEvent::Event(Event::Resize(10, 10)); |
| 367 | |
| 368 | let source = FakeSource::new(&[EVENT, EVENT]); |
| 369 | |
| 370 | let mut reader = InternalEventReader { |
| 371 | events: VecDeque::new(), |
| 372 | source: Some(Box::new(source)), |
| 373 | skipped_events: Vec::with_capacity(32), |
| 374 | }; |
| 375 | |
| 376 | assert_eq!(reader.read(&InternalEventFilter).unwrap(), EVENT); |
| 377 | reader.skipped_events.push(EVENT); |
| 378 | assert!(reader.poll(None, &InternalEventFilter).is_err()); |
| 379 | assert_eq!(reader.read(&InternalEventFilter).unwrap(), EVENT); |
| 380 | assert!(reader |
| 381 | .poll(Some(Duration::from_secs(0)), &InternalEventFilter) |
| 382 | .unwrap()); |
| 383 | } |
| 384 | |
| 385 | #[test] |
| 386 | fn test_read_continues_after_error() { |
| 387 | const EVENT: InternalEvent = InternalEvent::Event(Event::Resize(10, 10)); |
| 388 | |
| 389 | let source = FakeSource::new(&[EVENT, EVENT]); |
| 390 | |
| 391 | let mut reader = InternalEventReader { |
| 392 | events: VecDeque::new(), |
| 393 | source: Some(Box::new(source)), |
| 394 | skipped_events: Vec::with_capacity(32), |
| 395 | }; |
| 396 | |
| 397 | assert_eq!(reader.read(&InternalEventFilter).unwrap(), EVENT); |
| 398 | assert!(reader.read(&InternalEventFilter).is_err()); |
| 399 | assert_eq!(reader.read(&InternalEventFilter).unwrap(), EVENT); |
| 400 | } |
| 401 | |
| 402 | #[derive(Default)] |
| 403 | struct FakeSource { |
| 404 | events: VecDeque<InternalEvent>, |
| 405 | error: Option<io::Error>, |
| 406 | } |
| 407 | |
| 408 | impl FakeSource { |
| 409 | fn new(events: &[InternalEvent]) -> FakeSource { |
| 410 | FakeSource { |
| 411 | events: events.to_vec().into(), |
| 412 | error: Some(io::Error::new(io::ErrorKind::Other, "")), |
| 413 | } |
| 414 | } |
| 415 | |
| 416 | fn with_events(events: &[InternalEvent]) -> FakeSource { |
| 417 | FakeSource { |
| 418 | events: events.to_vec().into(), |
| 419 | error: None, |
| 420 | } |
| 421 | } |
| 422 | } |
| 423 | |
| 424 | impl EventSource for FakeSource { |
| 425 | fn try_read(&mut self, _timeout: Option<Duration>) -> io::Result<Option<InternalEvent>> { |
| 426 | // Return error if set in case there's just one remaining event |
| 427 | if self.events.len() == 1 { |
| 428 | if let Some(error) = self.error.take() { |
| 429 | return Err(error); |
| 430 | } |
| 431 | } |
| 432 | |
| 433 | // Return all events from the queue |
| 434 | if let Some(event) = self.events.pop_front() { |
| 435 | return Ok(Some(event)); |
| 436 | } |
| 437 | |
| 438 | // Return error if there're no more events |
| 439 | if let Some(error) = self.error.take() { |
| 440 | return Err(error); |
| 441 | } |
| 442 | |
| 443 | // Timeout |
| 444 | Ok(None) |
| 445 | } |
| 446 | |
| 447 | #[cfg(feature = "event-stream")] |
| 448 | fn waker(&self) -> super::super::sys::Waker { |
| 449 | unimplemented!(); |
| 450 | } |
| 451 | } |
| 452 | } |
| 453 |