Skip to main content

uncurses/event/
stream.rs

1//! Thread-backed asynchronous stream over a shared [`EventSource`].
2//!
3//! ## Purpose
4//!
5//! [`EventStream`] adapts a blocking [`EventSource`] into a
6//! [`futures_core::Stream`] of `io::Result<Event>`. It preserves the same
7//! decoder and queue semantics as synchronous reading while avoiding blocking
8//! the async task that polls the stream.
9//!
10//! ```text
11//! async task poll_next ─┬─ try lock + drain ready events ──▶ Poll::Ready
12//!                       └─ arm helper thread ─┬─ brief lock: read decode deadline
13//!                                             └─ block lock-free on private poller ──▶ wake task
14//! deadline change / drop stream ──▶ private Waker ──▶ helper wakes
15//! ```
16//!
17//! ## Key types
18//!
19//! * [`EventStream`] owns or shares an `Arc<Mutex<EventSource<_>>>` and gives
20//!   its helper a private poller, notification [`Waker`], and request channel.
21//! * A private `Wait` value tells the helper whether a wait is in flight and
22//!   whether stream drop requested shutdown.
23//!
24//! ## Lifecycle
25//!
26//! Use [`EventSource::into_stream`] when the stream should be the sole owner of
27//! the source. Use [`EventStream::from_shared`] when synchronous code keeps an
28//! `Arc<Mutex<_>>` clone. Dropping the stream wakes the helper so it can stop;
29//! the underlying shared source is not closed or drained.
30//!
31//! ## Coexistence caveats
32//!
33//! Sharing one source between a live stream and synchronous readers is
34//! supported but best-effort. The helper waits **lock-free** on its own poller
35//! (it locks the source only briefly to read the decode deadline, then releases
36//! it), so a synchronous reader, [`Screen::render`], or teardown can take the
37//! source lock while the stream is parked. Events go to whichever consumer
38//! drains first and are not broadcast. Read errors surface once as
39//! `Some(Err(_))`; after that the stream fuses to `None`.
40//!
41//! [`Screen::render`]: crate::screen::Screen::render
42//!
43//! [`futures_core::Stream`]: https://docs.rs/futures-core/latest/futures_core/stream/trait.Stream.html
44use 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
56/// A private wake handle watched only by this stream's helper.
57pub(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
82/// A readiness wait requested by the polling task: block until the source
83/// signals input (or a decode deadline elapses), then wake the task's
84/// latest registered waker.
85struct Wait {
86    /// Cleared by the helper just before waking, so the task can request a
87    /// fresh wait on its next poll. Guards against queueing more than one
88    /// wait at a time.
89    dispatched: Arc<AtomicBool>,
90    /// Set on drop to break the helper out of its blocking wait and end the
91    /// thread instead of re-arming.
92    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
99/// A thread-backed [`futures_core::Stream`] of `io::Result<Event>` over a
100/// shared [`EventSource`].
101///
102/// Build one with [`EventSource::into_stream`] (sole owner) or
103/// [`EventStream::from_shared`] (sharing a source kept elsewhere). A helper
104/// thread waits for readiness or a decode deadline, then wakes the polling
105/// task. The task drains queued events and decodes through a non-blocking poll.
106/// A private notification handle refreshes waits after deadline changes.
107/// The stream yields `Some(Ok(event))` for each event. It reports an input or
108/// readiness error once as `Some(Err(_))`, then fuses to `None`. Dropping it ends the
109/// helper thread; the shared source is left intact for any other holder.
110///
111/// Source wakes request another readiness pass. Ready events leave wakes pending;
112/// a wake alone keeps the stream pending. Use a separate async signal
113/// for cancellation.
114pub struct EventStream<I: Input> {
115    source: Arc<Mutex<EventSource<I>>>,
116    notification: Arc<DeadlineWake>,
117    /// Set while a readiness wait is queued, so only one is in flight.
118    dispatched: Arc<AtomicBool>,
119    /// Set on drop to tell the in-flight wait (if any) to end the helper.
120    shutdown: Arc<AtomicBool>,
121    /// Hands a readiness wait to the helper thread.
122    waits: SyncSender<Wait>,
123    /// Latched once a read error or end-of-input has been surfaced, after
124    /// which the stream yields `None`.
125    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    /// Convert this source into a thread-backed [`EventStream`].
137    ///
138    /// The source is wrapped in `Arc<Mutex<_>>` owned solely by the stream.
139    /// To keep reading the source synchronously alongside the stream, build
140    /// the `Arc<Mutex<_>>` yourself and use [`EventStream::from_shared`].
141    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    /// Build a stream over a source shared via `Arc<Mutex<_>>`.
151    ///
152    /// The caller may keep its own clone of the `Arc` to read the source
153    /// synchronously while the stream is live (see the coexistence caveats
154    /// on this module).
155    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(&notification.waker)
165                .expect("create event waiter poller");
166            src.deadline_wakers.retain(|weak| weak.strong_count() > 0);
167            src.deadline_wakers.push(Arc::downgrade(&notification));
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(&notification);
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    /// Record the current task waker and, if none is in flight, queue a
197    /// single readiness wait so the helper wakes the task when input
198    /// arrives or a decode deadline elapses.
199    fn arm(&self, cx: &Context<'_>) {
200        // Always refresh the waker, even when a wait is already in flight:
201        // the helper wakes whatever is latest, so a changed waker is never
202        // lost.
203        *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        // Tell the in-flight wait to end the helper, then break it out of
225        // its blocking readiness wait. The `waits` channel closes as this
226        // value drops, so the helper's `recv` then returns and the thread
227        // exits. The shared source itself is untouched.
228        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        // Try to decode on this task without blocking. If the helper holds
246        // the lock (parked in its brief deadline peek), fall through to arm a
247        // wait and stay pending rather than block here.
248        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                // Only drive I/O when no waiter is in flight. A dispatched
254                // waiter owns the next readiness wait and already captured the
255                // decode deadline; draining here could consume input (and set
256                // a fresh ESC/paste deadline) that the parked waiter's timeout
257                // won't honor, hanging a lone Esc until unrelated input. When
258                // a waiter is in flight the input stays level-ready, so the
259                // waiter wakes on it and the next poll (with `dispatched`
260                // cleared) drains and re-arms with the new deadline.
261                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                        // A stray wake is not an error; just stay pending.
269                        Err(e) if e.kind() == io::ErrorKind::Interrupted => {}
270                        // A read error (including end-of-input) surfaces once,
271                        // then the stream fuses.
272                        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        // Wait for readiness WITHOUT holding the source mutex, so the owner
298        // (render, teardown, capability application) can lock the source
299        // freely while this thread is parked. The poller is level-triggered
300        // and `poll` takes `&self`, so a concurrent readiness check here and a
301        // later drain by the task both observe the same readiness. One wait
302        // per dispatched request; the task re-arms for the next.
303        if !wait.shutdown.load(Ordering::SeqCst) {
304            // Briefly lock only to read the nearest ESC/paste decode deadline.
305            // The guard is dropped at the end of this `map`, before the
306            // blocking wait below, so the source stays lockable while parked.
307            // Without honoring the deadline, a buffered partial escape with no
308            // further input would never wake the task and a lone Esc would
309            // hang. On a poisoned lock, skip the wait and let the task surface
310            // the poison on its next poll.
311            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                // Any return (readiness, elapsed deadline, wake, or error)
322                // hands back to the task, which drains and decodes under its
323                // own `try_lock`; stray wakes are harmless.
324                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        // SAFETY: pipe(2) just produced two fresh, owned fds.
361        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    /// Minimal waker that flips a flag when woken, so a parked test thread
380    /// can re-poll the stream without an async runtime.
381    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    /// Drive `poll_next` to its next `Ready`, parking briefly between
393    /// pending polls.
394    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        // Other tests raise process-wide SIGWINCH, which also wakes pipe sources.
547        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        // Input arrives after the first poll parks, so the wake path runs.
609        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        // Closing the write end makes the read end report EOF, which the
622        // stream surfaces once as an error item and then fuses to `None`.
623        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        // A second handle to the same shared source can read synchronously
675        // while a stream is live; neither path deadlocks.
676        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        // The synchronous side can take the lock and read.
681        let ev = shared.lock().unwrap().read().unwrap();
682        assert!(matches!(ev, Event::KeyPress(k) if k.code == KeyCode::Char('a')));
683        // The stream still functions for subsequent input.
684        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        // Path 2: the waiter must not hold the source lock while parked, so
692        // the owner (render, teardown, capability application) can lock the
693        // source even with no input pending. Under the old lock-while-parked
694        // design this would block until input arrived.
695        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        // Poll once with no input: the stream parks and the waiter thread
700        // enters its blocking, lock-free readiness wait.
701        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        // Give the waiter time to pass its brief deadline peek and reach the
709        // blocking poll.
710        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        // The stream still delivers input afterwards.
718        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        // A bare Esc has no follow-up bytes, so it only resolves once its
879        // decode deadline elapses. The stream must honor that deadline: the
880        // waiter wakes on the elapsed timeout and the next poll drains the
881        // resolved key. Guards the `dispatched`-gated drain path.
882        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}