1use std::io;
45use std::pin::Pin;
46use std::sync::atomic::{AtomicBool, Ordering};
47use std::sync::mpsc::{self, Receiver, SyncSender};
48use std::sync::{Arc, Mutex, TryLockError};
49use std::task::{Context, Poll, Waker as TaskWaker};
50use std::time::Duration;
51
52use super::Event;
53use super::poll::Poller;
54use super::source::{EventSource, Input, READY_SLOTS, Waker};
55
56pub(super) struct DeadlineWake {
58 waker: Waker,
59 task_waker: Mutex<Option<TaskWaker>>,
60 error: Mutex<Option<io::Error>>,
61}
62
63impl DeadlineWake {
64 pub(super) fn notify(&self) {
65 if let Err(error) = self.waker.wake() {
66 self.fail(error);
67 }
68 }
69
70 fn fail(&self, error: io::Error) {
71 self.error.lock().unwrap().get_or_insert(error);
72 self.wake_task();
73 }
74
75 fn wake_task(&self) {
76 if let Some(waker) = self.task_waker.lock().unwrap().as_ref() {
77 waker.wake_by_ref();
78 }
79 }
80}
81
82struct Wait {
86 dispatched: Arc<AtomicBool>,
90 shutdown: Arc<AtomicBool>,
93 #[cfg(test)]
94 started: Option<SyncSender<Option<Duration>>>,
95 #[cfg(test)]
96 before_wait: Option<Arc<std::sync::Barrier>>,
97}
98
99pub struct EventStream<I: Input> {
115 source: Arc<Mutex<EventSource<I>>>,
116 notification: Arc<DeadlineWake>,
117 dispatched: Arc<AtomicBool>,
119 shutdown: Arc<AtomicBool>,
121 waits: SyncSender<Wait>,
123 done: bool,
126 #[cfg(test)]
127 wait_started: Option<SyncSender<Option<Duration>>>,
128 #[cfg(test)]
129 before_wait: Option<Arc<std::sync::Barrier>>,
130}
131
132impl<I> EventSource<I>
133where
134 I: Input + 'static,
135{
136 pub fn into_stream(self) -> EventStream<I> {
142 EventStream::from_shared(Arc::new(Mutex::new(self)))
143 }
144}
145
146impl<I> EventStream<I>
147where
148 I: Input + 'static,
149{
150 pub fn from_shared(source: Arc<Mutex<EventSource<I>>>) -> Self {
156 let notification = Arc::new(DeadlineWake {
157 waker: Waker::new().expect("create event waiter notification"),
158 task_waker: Mutex::new(None),
159 error: Mutex::new(None),
160 });
161 let poller = {
162 let mut src = source.lock().unwrap();
163 let poller = src
164 .waiter_poller(¬ification.waker)
165 .expect("create event waiter poller");
166 src.deadline_wakers.retain(|weak| weak.strong_count() > 0);
167 src.deadline_wakers.push(Arc::downgrade(¬ification));
168 poller
169 };
170 let (waits, rx) = mpsc::sync_channel::<Wait>(1);
171 let wait_source = Arc::clone(&source);
172 let wait_notification = Arc::clone(¬ification);
173 std::thread::Builder::new()
174 .name("uncurses-event-waiter".to_string())
175 .spawn(move || waiter_loop(wait_source, poller, wait_notification, rx))
176 .expect("spawn event waiter thread");
177 Self {
178 source,
179 notification,
180 dispatched: Arc::new(AtomicBool::new(false)),
181 shutdown: Arc::new(AtomicBool::new(false)),
182 waits,
183 done: false,
184 #[cfg(test)]
185 wait_started: None,
186 #[cfg(test)]
187 before_wait: None,
188 }
189 }
190}
191
192impl<I> EventStream<I>
193where
194 I: Input,
195{
196 fn arm(&self, cx: &Context<'_>) {
200 *self.notification.task_waker.lock().unwrap() = Some(cx.waker().clone());
204 if !self
205 .dispatched
206 .compare_exchange(false, true, Ordering::SeqCst, Ordering::SeqCst)
207 .unwrap_or_else(|prev| prev)
208 {
209 self.shutdown.store(false, Ordering::SeqCst);
210 let _ = self.waits.send(Wait {
211 dispatched: Arc::clone(&self.dispatched),
212 shutdown: Arc::clone(&self.shutdown),
213 #[cfg(test)]
214 started: self.wait_started.clone(),
215 #[cfg(test)]
216 before_wait: self.before_wait.clone(),
217 });
218 }
219 }
220}
221
222impl<I: Input> Drop for EventStream<I> {
223 fn drop(&mut self) {
224 self.shutdown.store(true, Ordering::SeqCst);
229 self.notification.notify();
230 }
231}
232
233impl<I: Input> futures_core::Stream for EventStream<I> {
234 type Item = io::Result<Event>;
235
236 fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
237 let this = self.get_mut();
238 if this.done {
239 return Poll::Ready(None);
240 }
241 if let Some(error) = this.notification.error.lock().unwrap().take() {
242 this.done = true;
243 return Poll::Ready(Some(Err(error)));
244 }
245 match this.source.try_lock() {
249 Ok(mut src) => {
250 if let Some(event) = src.try_read() {
251 return Poll::Ready(Some(Ok(event)));
252 }
253 if !this.dispatched.load(Ordering::SeqCst) {
262 match src.poll(Some(Duration::ZERO)) {
263 Ok(_) => {
264 if let Some(ev) = src.try_read() {
265 return Poll::Ready(Some(Ok(ev)));
266 }
267 }
268 Err(e) if e.kind() == io::ErrorKind::Interrupted => {}
270 Err(e) => {
273 this.done = true;
274 return Poll::Ready(Some(Err(e)));
275 }
276 }
277 }
278 }
279 Err(TryLockError::WouldBlock) => {}
280 Err(TryLockError::Poisoned(_)) => {
281 this.done = true;
282 return Poll::Ready(Some(Err(io::Error::other("event source mutex poisoned"))));
283 }
284 }
285 this.arm(cx);
286 Poll::Pending
287 }
288}
289
290fn waiter_loop<I: Input>(
291 source: Arc<Mutex<EventSource<I>>>,
292 poller: Arc<dyn Poller>,
293 notification: Arc<DeadlineWake>,
294 waits: Receiver<Wait>,
295) {
296 while let Ok(wait) = waits.recv() {
297 if !wait.shutdown.load(Ordering::SeqCst) {
304 if let Ok(timeout) = source.lock().map(|src| src.effective_timeout(None)) {
312 #[cfg(test)]
313 if let Some(started) = &wait.started {
314 let _ = started.try_send(timeout);
315 }
316 #[cfg(test)]
317 if let Some(barrier) = &wait.before_wait {
318 barrier.wait();
319 }
320 let mut ready = [false; READY_SLOTS + 1];
321 match poller.poll(&mut ready, timeout) {
325 Ok(_) if ready[READY_SLOTS] => {
326 if let Err(error) = notification.waker.clear() {
327 notification.fail(error);
328 }
329 }
330 Err(error) => notification.fail(error),
331 Ok(_) => {}
332 }
333 }
334 }
335 wait.dispatched.store(false, Ordering::SeqCst);
336 notification.wake_task();
337 }
338}
339
340#[cfg(all(test, unix))]
341mod tests {
342 use std::fs::File;
343 use std::os::fd::FromRawFd;
344 use std::os::unix::io::AsRawFd;
345 use std::pin::Pin;
346 use std::sync::Arc;
347 use std::sync::atomic::{AtomicBool, Ordering};
348 use std::task::{Context, Poll, Wake, Waker};
349 use std::time::Duration;
350
351 use futures_core::Stream;
352
353 use super::*;
354 use crate::event::KeyCode;
355
356 fn make_pipe() -> (File, File) {
357 let mut fds = [0i32; 2];
358 let rc = unsafe { libc::pipe(fds.as_mut_ptr()) };
359 assert_eq!(rc, 0, "pipe(2) failed");
360 let rx = unsafe { File::from_raw_fd(fds[0]) };
362 let tx = unsafe { File::from_raw_fd(fds[1]) };
363 (rx, tx)
364 }
365
366 fn write_bytes(f: &File, bytes: &[u8]) {
367 let n = unsafe { libc::write(f.as_raw_fd(), bytes.as_ptr() as *const _, bytes.len()) };
368 assert_eq!(n, bytes.len() as isize);
369 }
370
371 struct Notify(SyncSender<()>);
372
373 impl Wake for Notify {
374 fn wake(self: Arc<Self>) {
375 let _ = self.0.try_send(());
376 }
377 }
378
379 struct FlagWaker(AtomicBool);
382
383 impl Wake for FlagWaker {
384 fn wake(self: Arc<Self>) {
385 self.0.store(true, Ordering::SeqCst);
386 }
387 fn wake_by_ref(self: &Arc<Self>) {
388 self.0.store(true, Ordering::SeqCst);
389 }
390 }
391
392 fn next_blocking<I: Input>(stream: &mut EventStream<I>) -> Option<io::Result<Event>> {
395 let flag = Arc::new(FlagWaker(AtomicBool::new(false)));
396 let waker = Waker::from(Arc::clone(&flag));
397 loop {
398 let mut cx = Context::from_waker(&waker);
399 match Pin::new(&mut *stream).poll_next(&mut cx) {
400 Poll::Ready(item) => return item,
401 Poll::Pending => {
402 while !flag.0.swap(false, Ordering::SeqCst) {
403 std::thread::sleep(Duration::from_millis(1));
404 }
405 }
406 }
407 }
408 }
409
410 #[test]
411 fn reads_events_in_order() {
412 let (rx, tx) = make_pipe();
413 let mut stream = EventSource::new(rx).unwrap().into_stream();
414 write_bytes(&tx, b"ab");
415 let a = next_blocking(&mut stream).unwrap().unwrap();
416 let b = next_blocking(&mut stream).unwrap().unwrap();
417 assert!(matches!(a, Event::KeyPress(k) if k.code == KeyCode::Char('a')));
418 assert!(matches!(b, Event::KeyPress(k) if k.code == KeyCode::Char('b')));
419 }
420
421 #[test]
422 fn win32_runs_deliver_repeats_before_later_events_and_eof() {
423 let (rx, tx) = make_pipe();
424 let mut stream = EventSource::new(rx).unwrap().into_stream();
425 write_bytes(&tx, b"\x1b[65;30;97;1;0;3_z");
426 drop(tx);
427 for repeat in [false, true, true] {
428 assert!(matches!(next_blocking(&mut stream).unwrap().unwrap(),
429 Event::KeyPress(key) if key.code == KeyCode::Char('a') && key.repeat == repeat));
430 }
431 assert!(matches!(next_blocking(&mut stream).unwrap().unwrap(),
432 Event::KeyPress(key) if key.code == KeyCode::Char('z') && !key.repeat));
433 assert_eq!(
434 next_blocking(&mut stream).unwrap().unwrap_err().kind(),
435 io::ErrorKind::UnexpectedEof
436 );
437 }
438
439 #[test]
440 fn clipboard_stream_delivers_chunks_before_termination_and_reports_eof() {
441 let (rx, tx) = make_pipe();
442 let mut stream = EventSource::new(rx).unwrap().into_stream();
443 write_bytes(&tx, b"\x1b]52;c;QQ==");
444 assert!(matches!(
445 next_blocking(&mut stream).unwrap().unwrap(),
446 Event::ClipboardStart { .. }
447 ));
448 assert_eq!(
449 next_blocking(&mut stream).unwrap().unwrap(),
450 Event::ClipboardChunk(b"QQ==".to_vec())
451 );
452 drop(tx);
453 assert_eq!(
454 next_blocking(&mut stream).unwrap().unwrap(),
455 Event::ClipboardEnd { complete: false }
456 );
457 assert_eq!(
458 next_blocking(&mut stream).unwrap().unwrap_err().kind(),
459 io::ErrorKind::UnexpectedEof
460 );
461 assert!(next_blocking(&mut stream).is_none());
462 }
463
464 #[test]
465 fn queued_event_preserves_wake_even_with_a_wait_in_flight() {
466 let (rx, _tx) = make_pipe();
467 let shared = Arc::new(Mutex::new(EventSource::new(rx).unwrap()));
468 let mut stream = EventStream::from_shared(Arc::clone(&shared));
469 let (started_tx, started_rx) = mpsc::sync_channel(1);
470 stream.wait_started = Some(started_tx);
471 let waker = Waker::from(Arc::new(FlagWaker(AtomicBool::new(false))));
472 let mut cx = Context::from_waker(&waker);
473 assert!(Pin::new(&mut stream).poll_next(&mut cx).is_pending());
474 assert_eq!(
475 started_rx.recv_timeout(Duration::from_secs(1)).unwrap(),
476 None
477 );
478 {
479 let mut source = shared.lock().unwrap();
480 source.unread(Event::PasteStart);
481 source.unread(Event::PasteEnd { complete: true });
482 source.waker().wake().unwrap();
483 }
484 assert!(matches!(
485 Pin::new(&mut stream).poll_next(&mut cx),
486 Poll::Ready(Some(Ok(Event::PasteEnd { complete: true })))
487 ));
488 let mut source = shared.lock().unwrap();
489 assert_eq!(source.try_read(), Some(Event::PasteStart));
490 assert_eq!(
491 source.fill(Some(Duration::ZERO)).unwrap_err().kind(),
492 io::ErrorKind::Interrupted,
493 );
494 source.fill(Some(Duration::ZERO)).unwrap();
495 }
496
497 #[test]
498 fn interrupted_shared_read_refreshes_a_snapshotted_deadline() {
499 for (bytes, expected) in [
500 (b"\x1b[".as_slice(), KeyCode::Char('[')),
501 (b"\x1b".as_slice(), KeyCode::Escape),
502 ] {
503 let (rx, tx) = make_pipe();
504 let source = EventSource::new(rx)
505 .unwrap()
506 .with_esc_timeout(Duration::ZERO);
507 let shared = Arc::new(Mutex::new(source));
508 let mut stream = EventStream::from_shared(Arc::clone(&shared));
509 let (started_tx, started_rx) = mpsc::sync_channel(1);
510 stream.wait_started = Some(started_tx);
511 let barrier = Arc::new(std::sync::Barrier::new(2));
512 stream.before_wait = Some(Arc::clone(&barrier));
513 let (wake_tx, wake_rx) = mpsc::sync_channel(1);
514 let waker = Waker::from(Arc::new(Notify(wake_tx)));
515 let mut cx = Context::from_waker(&waker);
516 assert!(Pin::new(&mut stream).poll_next(&mut cx).is_pending());
517 assert_eq!(
518 started_rx.recv_timeout(Duration::from_secs(1)).unwrap(),
519 None
520 );
521 stream.before_wait = None;
522 {
523 let mut source = shared.lock().unwrap();
524 write_bytes(&tx, bytes);
525 source.waker().wake().unwrap();
526 assert_eq!(
527 source.read().unwrap_err().kind(),
528 io::ErrorKind::Interrupted,
529 );
530 }
531 barrier.wait();
532 wake_rx
533 .recv_timeout(Duration::from_secs(1))
534 .expect("the interrupted read must refresh the helper's stale timeout");
535 assert!(matches!(
536 Pin::new(&mut stream).poll_next(&mut cx),
537 Poll::Ready(Some(Ok(Event::KeyPress(key)))) if key.code == expected
538 ));
539 }
540 }
541
542 #[test]
543 fn wake_only_retries_and_string_still_arrives() {
544 const CHILD: &str = "UNCURSES_WAKE_QUIET_CHILD";
545 const NAME: &str = "event::stream::tests::wake_only_retries_and_string_still_arrives";
546 if std::env::var_os(CHILD).is_none() {
548 let output = std::process::Command::new(std::env::current_exe().unwrap())
549 .args([NAME, "--exact", "--nocapture", "--test-threads=1"])
550 .env(CHILD, "1")
551 .output()
552 .expect("re-exec wake test");
553 let stdout = String::from_utf8_lossy(&output.stdout);
554 assert!(
555 output.status.success() && stdout.contains("1 passed"),
556 "isolated wake test failed or did not run:\n{stdout}\n{}",
557 String::from_utf8_lossy(&output.stderr)
558 );
559 return;
560 }
561 let (rx, tx) = make_pipe();
562 let source = EventSource::new(rx).unwrap();
563 let shared = Arc::new(Mutex::new(source));
564 let mut stream = EventStream::from_shared(Arc::clone(&shared));
565 let (started_tx, started_rx) = mpsc::sync_channel(1);
566 stream.wait_started = Some(started_tx);
567 let (wake_tx, wake_rx) = mpsc::sync_channel(1);
568 let waker = Waker::from(Arc::new(Notify(wake_tx)));
569 let mut cx = Context::from_waker(&waker);
570 shared.lock().unwrap().waker().wake().unwrap();
571 assert!(Pin::new(&mut stream).poll_next(&mut cx).is_pending());
572 assert_eq!(
573 started_rx.recv_timeout(Duration::from_secs(1)).unwrap(),
574 None
575 );
576 wake_rx.recv_timeout(Duration::from_secs(1)).unwrap();
577 assert!(Pin::new(&mut stream).poll_next(&mut cx).is_pending());
578 assert_eq!(
579 started_rx.recv_timeout(Duration::from_secs(1)).unwrap(),
580 None
581 );
582 assert!(matches!(
583 wake_rx.recv_timeout(Duration::from_millis(20)),
584 Err(mpsc::RecvTimeoutError::Timeout)
585 ));
586 {
587 let mut source = shared.lock().unwrap();
588 write_bytes(&tx, b"\x1b]unfinished");
589 assert!(!source.poll(Some(Duration::ZERO)).unwrap());
590 source.waker().wake().unwrap();
591 }
592 wake_rx.recv_timeout(Duration::from_secs(1)).unwrap();
593 assert!(Pin::new(&mut stream).poll_next(&mut cx).is_pending());
594 write_bytes(&tx, b"\x1b\\");
595 assert_eq!(
596 next_blocking(&mut stream).unwrap().unwrap(),
597 Event::Unknown {
598 kind: crate::event::SequenceKind::Osc,
599 bytes: b"unfinished".to_vec(),
600 },
601 );
602 }
603
604 #[test]
605 fn waits_then_reads_late_input() {
606 let (rx, tx) = make_pipe();
607 let mut stream = EventSource::new(rx).unwrap().into_stream();
608 std::thread::spawn(move || {
610 std::thread::sleep(Duration::from_millis(20));
611 write_bytes(&tx, b"z");
612 });
613 let z = next_blocking(&mut stream).unwrap().unwrap();
614 assert!(matches!(z, Event::KeyPress(k) if k.code == KeyCode::Char('z')));
615 }
616
617 #[test]
618 fn surfaces_error_then_fuses_on_input_eof() {
619 let (rx, tx) = make_pipe();
620 let mut stream = EventSource::new(rx).unwrap().into_stream();
621 std::thread::spawn(move || {
624 std::thread::sleep(Duration::from_millis(20));
625 drop(tx);
626 });
627 let item = next_blocking(&mut stream).unwrap();
628 assert!(
629 matches!(&item, Err(e) if e.kind() == io::ErrorKind::UnexpectedEof),
630 "expected UnexpectedEof, got {:?}",
631 item
632 );
633 assert!(
634 next_blocking(&mut stream).is_none(),
635 "stream should fuse to None after the error"
636 );
637 }
638
639 #[test]
640 fn expired_input_is_delivered_before_eof() {
641 use crate::event::{Key, KeyModifiers};
642
643 for (input, expected) in [
644 (
645 b"\x1b[".as_slice(),
646 Some(Event::KeyPress(Key::new(
647 KeyCode::Char('['),
648 KeyModifiers::ALT,
649 ))),
650 ),
651 (b"\x1b]q", None),
652 ] {
653 let (rx, tx) = make_pipe();
654 let mut source = EventSource::new(rx)
655 .unwrap()
656 .with_esc_timeout(Duration::ZERO);
657 source.feed_bytes(input);
658 let mut stream = source.into_stream();
659 drop(tx);
660
661 if let Some(expected) = expected {
662 assert_eq!(next_blocking(&mut stream).unwrap().unwrap(), expected);
663 }
664 assert_eq!(
665 next_blocking(&mut stream).unwrap().unwrap_err().kind(),
666 io::ErrorKind::UnexpectedEof
667 );
668 assert!(next_blocking(&mut stream).is_none());
669 }
670 }
671
672 #[test]
673 fn sync_reads_coexist_with_a_live_stream() {
674 let (rx, tx) = make_pipe();
677 let shared = Arc::new(Mutex::new(EventSource::new(rx).unwrap()));
678 let mut stream = EventStream::from_shared(Arc::clone(&shared));
679 write_bytes(&tx, b"a");
680 let ev = shared.lock().unwrap().read().unwrap();
682 assert!(matches!(ev, Event::KeyPress(k) if k.code == KeyCode::Char('a')));
683 write_bytes(&tx, b"b");
685 let b = next_blocking(&mut stream).unwrap().unwrap();
686 assert!(matches!(b, Event::KeyPress(k) if k.code == KeyCode::Char('b')));
687 }
688
689 #[test]
690 fn source_lockable_while_stream_parked() {
691 let (rx, tx) = make_pipe();
696 let shared = Arc::new(Mutex::new(EventSource::new(rx).unwrap()));
697 let mut stream = EventStream::from_shared(Arc::clone(&shared));
698
699 let flag = Arc::new(FlagWaker(AtomicBool::new(false)));
702 let waker = Waker::from(Arc::clone(&flag));
703 let mut cx = Context::from_waker(&waker);
704 assert!(matches!(
705 Pin::new(&mut stream).poll_next(&mut cx),
706 Poll::Pending
707 ));
708 std::thread::sleep(Duration::from_millis(20));
711
712 assert!(
713 shared.try_lock().is_ok(),
714 "source lock is held by the parked waiter (deadlock risk)"
715 );
716
717 write_bytes(&tx, b"q");
719 let q = next_blocking(&mut stream).unwrap().unwrap();
720 assert!(matches!(q, Event::KeyPress(k) if k.code == KeyCode::Char('q')));
721 }
722
723 #[test]
724 fn explicit_end_wakes_a_parked_transfer_stream() {
725 for clipboard in [false, true] {
726 let (rx, _tx) = make_pipe();
727 let mut source = EventSource::new(rx)
728 .unwrap()
729 .with_paste_idle_timeout(None)
730 .with_clipboard_idle_timeout(None);
731 source.feed_bytes(if clipboard {
732 b"\x1b]52;c;"
733 } else {
734 b"\x1b[200~"
735 });
736 assert!(source.try_read().is_some());
737 let shared = Arc::new(Mutex::new(source));
738 let mut stream = EventStream::from_shared(Arc::clone(&shared));
739 let (started_tx, started_rx) = mpsc::sync_channel(1);
740 stream.wait_started = Some(started_tx);
741 let (wake_tx, wake_rx) = mpsc::sync_channel(1);
742 let waker = Waker::from(Arc::new(Notify(wake_tx)));
743 let mut cx = Context::from_waker(&waker);
744 assert!(Pin::new(&mut stream).poll_next(&mut cx).is_pending());
745 assert_eq!(
746 started_rx.recv_timeout(Duration::from_secs(1)).unwrap(),
747 None
748 );
749 if clipboard {
750 shared.lock().unwrap().end_clipboard();
751 } else {
752 shared.lock().unwrap().end_paste();
753 }
754 wake_rx
755 .recv_timeout(Duration::from_secs(1))
756 .expect("explicit recovery must wake the stream without more input");
757 let end = if clipboard {
758 Event::ClipboardEnd { complete: false }
759 } else {
760 Event::PasteEnd { complete: false }
761 };
762 assert!(matches!(Pin::new(&mut stream).poll_next(&mut cx),
763 Poll::Ready(Some(Ok(event))) if event == end));
764 }
765 }
766
767 #[test]
768 fn changing_a_parked_transfer_deadline_wakes_the_stream() {
769 for clipboard in [false, true] {
770 for (timeout, disable_first) in [
771 (None, false),
772 (Some(Duration::from_secs(60)), false),
773 (Some(Duration::from_secs(60)), true),
774 ] {
775 let (rx, _tx) = make_pipe();
776 let mut source = EventSource::new(rx)
777 .unwrap()
778 .with_paste_idle_timeout(timeout)
779 .with_clipboard_idle_timeout(timeout);
780 source.feed_bytes(if clipboard {
781 b"\x1b]52;c;"
782 } else {
783 b"\x1b[200~"
784 });
785 assert!(source.try_read().is_some());
786 let shared = Arc::new(Mutex::new(source));
787 let mut stream = EventStream::from_shared(Arc::clone(&shared));
788 let (started_tx, started_rx) = mpsc::sync_channel(1);
789 stream.wait_started = Some(started_tx);
790 let (wake_tx, wake_rx) = mpsc::sync_channel(1);
791 let waker = Waker::from(Arc::new(Notify(wake_tx)));
792 let mut cx = Context::from_waker(&waker);
793 assert!(Pin::new(&mut stream).poll_next(&mut cx).is_pending());
794 let captured = started_rx.recv_timeout(Duration::from_secs(1)).unwrap();
795 match timeout {
796 None => assert_eq!(captured, None),
797 Some(_) => assert!(captured.unwrap() > Duration::from_secs(30)),
798 }
799
800 if disable_first {
801 if clipboard {
802 shared.lock().unwrap().set_clipboard_idle_timeout(None);
803 } else {
804 shared.lock().unwrap().set_paste_idle_timeout(None);
805 }
806 wake_rx.recv_timeout(Duration::from_secs(1)).unwrap();
807 assert!(Pin::new(&mut stream).poll_next(&mut cx).is_pending());
808 assert_eq!(
809 started_rx.recv_timeout(Duration::from_secs(1)).unwrap(),
810 None
811 );
812 }
813
814 if clipboard {
815 shared
816 .lock()
817 .unwrap()
818 .set_clipboard_idle_timeout(Some(Duration::ZERO));
819 } else {
820 shared
821 .lock()
822 .unwrap()
823 .set_paste_idle_timeout(Some(Duration::ZERO));
824 }
825 wake_rx
826 .recv_timeout(Duration::from_secs(1))
827 .expect("deadline change must wake the parked stream without more input");
828 let end = if clipboard {
829 Event::ClipboardEnd { complete: false }
830 } else {
831 Event::PasteEnd { complete: false }
832 };
833 assert!(matches!(
834 Pin::new(&mut stream).poll_next(&mut cx),
835 Poll::Ready(Some(Ok(event))) if event == end
836 ));
837 }
838 }
839 }
840
841 #[test]
842 fn deadline_notifications_leave_sync_wake_behavior_intact() {
843 let (rx, tx) = make_pipe();
844 let mut source = EventSource::new(rx).unwrap().with_paste_idle_timeout(None);
845 source.feed_bytes(b"\x1b[200~");
846 assert_eq!(source.try_read(), Some(Event::PasteStart));
847 let shared = Arc::new(Mutex::new(source));
848 let mut stream = EventStream::from_shared(Arc::clone(&shared));
849 let (started_tx, started_rx) = mpsc::sync_channel(1);
850 stream.wait_started = Some(started_tx);
851 let waker = Waker::from(Arc::new(FlagWaker(AtomicBool::new(false))));
852 let mut cx = Context::from_waker(&waker);
853 assert!(Pin::new(&mut stream).poll_next(&mut cx).is_pending());
854 assert_eq!(
855 started_rx.recv_timeout(Duration::from_secs(1)).unwrap(),
856 None
857 );
858
859 {
860 let mut source = shared.lock().unwrap();
861 source.set_paste_idle_timeout(Some(Duration::ZERO));
862 assert_eq!(source.read().unwrap(), Event::PasteEnd { complete: false });
863 source.waker().wake().unwrap();
864 assert_eq!(
865 source.read().unwrap_err().kind(),
866 io::ErrorKind::Interrupted
867 );
868 }
869
870 drop(stream);
871 write_bytes(&tx, b"x");
872 assert!(matches!(shared.lock().unwrap().read().unwrap(),
873 Event::KeyPress(k) if k.code == KeyCode::Char('x')));
874 }
875
876 #[test]
877 fn lone_esc_resolves_through_the_stream() {
878 let (rx, tx) = make_pipe();
883 let mut stream = EventSource::new(rx).unwrap().into_stream();
884 write_bytes(&tx, b"\x1b");
885 let esc = next_blocking(&mut stream).unwrap().unwrap();
886 assert!(matches!(esc, Event::KeyPress(k) if k.code == KeyCode::Escape));
887 }
888
889 fn _assert_send_sync<T: Send + Sync>() {}
890 #[test]
891 fn stream_is_send_sync() {
892 _assert_send_sync::<EventStream<File>>();
893 }
894}