Skip to main content

uncurses/event/
source_unix.rs

1//! Unix-specific construction and readiness servicing for [`EventSource`].
2//!
3//! ## Purpose
4//!
5//! This module supplies the Unix [`EventSource::new`] implementation and the
6//! platform hooks used by the shared source pump: drain the wake self-pipe, read
7//! ready bytes, and surface `SIGWINCH` as [`Event::Resize`].
8//!
9//! ```text
10//! [input fd] ─┐
11//! [wake pipe] ├─▶ Poller ──▶ EventSource::fill
12//! [winch pipe]┘        ├─ wake: Interrupted
13//!                      ├─ input: read + decode
14//!                      └─ winch: query Winsize + Resize
15//! ```
16//!
17//! ## Key types
18//!
19//! `UnixWakerInner` owns *both* ends of a non-blocking self-pipe. The shared
20//! [`Waker`] wraps it so other threads can interrupt blocking reads without
21//! touching decoder state. Both ends live behind the same `Arc` because a
22//! `Waker` may outlive its source, and writing to a pipe whose reader has
23//! closed raises a synchronous `SIGPIPE`.
24//!
25//! ## Gotchas
26//!
27//! The input fd is also used for `TIOCGWINSZ`, so it should refer to the same
28//! terminal whose size the caller wants. When in-band resize reports are
29//! enabled, [`EventSource::set_handle_resize`] should disable the SIGWINCH path
30//! to avoid duplicate resize events.
31#![cfg(unix)]
32
33use super::queue::EventQueue;
34use std::io;
35use std::os::fd::{AsRawFd, FromRawFd, OwnedFd};
36#[cfg(feature = "async")]
37use std::sync::Arc;
38
39use super::decode::{Decoder, DecoderFlags};
40use super::pending::Pending;
41use super::poll::PollFd;
42use super::sigwinch as winch;
43use super::source::{
44    DEFAULT_BUFFER_CAPACITY, DEFAULT_CLIPBOARD_IDLE_TIMEOUT, DEFAULT_ESC_TIMEOUT,
45    DEFAULT_PASTE_IDLE_TIMEOUT, DEFAULT_STRING_IDLE_TIMEOUT, EventSource, Input, READY_INPUT,
46    READY_SLOTS, READY_WAKE, READY_WINCH, Waker,
47};
48use crate::event::Event;
49use crate::terminal::get_window_size;
50
51pub(super) struct UnixWakerInner {
52    /// Write end of the self-pipe. Non-blocking; closed on drop.
53    tx: OwnedFd,
54    /// Read end, kept here rather than in [`EventSource`] so that it cannot be
55    /// closed while a `Waker` clone still holds `tx`. A write to a pipe whose
56    /// reader is gone raises a *synchronous* `SIGPIPE` on the calling thread,
57    /// which no error handling can intercept — invisible in a Rust binary
58    /// (std sets `SIG_IGN` at startup) but fatal inside a C or Go host.
59    /// `Waker` is public, `Clone` and `Send`, so it legitimately outlives the
60    /// source it came from; sharing both ends behind the same `Arc` makes that
61    /// safe instead of merely unlikely.
62    rx: OwnedFd,
63}
64
65impl UnixWakerInner {
66    pub(super) fn new() -> io::Result<Self> {
67        let (rx, tx) = make_self_pipe()?;
68        Ok(Self { tx, rx })
69    }
70
71    pub(super) fn clear(&self) -> io::Result<()> {
72        drain_pipe(self.read_fd())
73    }
74
75    pub(super) fn read_fd(&self) -> std::os::fd::RawFd {
76        self.rx.as_raw_fd()
77    }
78
79    pub(super) fn wake(&self) -> io::Result<()> {
80        let buf = b"w";
81        loop {
82            let n = unsafe { libc::write(self.tx.as_raw_fd(), buf.as_ptr() as *const _, 1) };
83            if n < 0 {
84                let err = io::Error::last_os_error();
85                match err.kind() {
86                    io::ErrorKind::Interrupted => continue,
87                    // Pipe full — an earlier wake byte is already pending,
88                    // which is all the consumer needs.
89                    io::ErrorKind::WouldBlock => return Ok(()),
90                    _ => return Err(err),
91                }
92            }
93            return Ok(());
94        }
95    }
96}
97
98// ---------------------------------------------------------------------------
99// Unix implementation
100// ---------------------------------------------------------------------------
101
102impl<I> EventSource<I>
103where
104    I: Input,
105{
106    /// Build a new Unix event source for `input`.
107    ///
108    /// The handle is used both for byte reads and as the `TIOCGWINSZ` target
109    /// when `SIGWINCH` fires, so it should refer to the terminal whose size the
110    /// caller cares about. Construction creates two non-blocking self-pipes,
111    /// subscribes to the shared SIGWINCH fan-out, and registers the input, wake,
112    /// and resize fds with the selected poll backend.
113    ///
114    /// Timeouts start at [`DEFAULT_ESC_TIMEOUT`], [`DEFAULT_PASTE_IDLE_TIMEOUT`],
115    /// [`DEFAULT_CLIPBOARD_IDLE_TIMEOUT`], and [`DEFAULT_STRING_IDLE_TIMEOUT`].
116    /// Override them with
117    /// [`EventSource::with_esc_timeout`], [`EventSource::with_paste_idle_timeout`],
118    /// [`EventSource::with_clipboard_idle_timeout`], and
119    /// [`EventSource::with_string_idle_timeout`].
120    ///
121    /// Resize deduplication starts from the size `input` reports here, so a
122    /// `SIGWINCH` that does not actually change the size produces no
123    /// [`Event::Resize`].
124    ///
125    /// Returns any OS error from pipe creation, fd configuration, SIGWINCH
126    /// subscription, or poller construction. It does not read from `input`.
127    pub fn new(input: I) -> io::Result<Self> {
128        let winch_sub = winch::subscribe()?;
129        let waker = Waker::new()?;
130
131        // Watch input, wake pipe, and winch pipe — in the fixed index
132        // order the pump/ingest path relies on. Detect a tty input fd up
133        // front so Darwin can pick the select backend (its kqueue spins
134        // on tty character devices).
135        let input_fd = input.as_fd().as_raw_fd();
136        let input_is_tty = unsafe { libc::isatty(input_fd) } == 1;
137        // Seed the resize dedupe with the size we start at, so the first wake
138        // reports a resize only if one actually happened. Without this any
139        // first wake emits, including one caused by a late handler write that
140        // landed in this slot's pooled pipe just after it was leased to us.
141        // `None` on a non-tty, where there is no size to compare against.
142        let last_size = get_window_size(input.as_fd()).ok();
143        let mut fds: [PollFd; READY_SLOTS] = [-1; READY_SLOTS];
144        fds[READY_INPUT] = input_fd;
145        fds[READY_WAKE] = waker.poll_fd();
146        fds[READY_WINCH] = winch_sub.read_fd();
147        let poller = super::poll::new_poller(&fds, input_is_tty)?;
148
149        Ok(Self {
150            input,
151            parser: Decoder::new(DecoderFlags::empty()),
152            pending: Pending::with_capacity(DEFAULT_BUFFER_CAPACITY),
153            esc_timeout: DEFAULT_ESC_TIMEOUT,
154            esc_deadline: None,
155            paste_idle_timeout: Some(DEFAULT_PASTE_IDLE_TIMEOUT),
156            paste_deadline: None,
157            clipboard_idle_timeout: Some(DEFAULT_CLIPBOARD_IDLE_TIMEOUT),
158            clipboard_deadline: None,
159            string_idle_timeout: Some(DEFAULT_STRING_IDLE_TIMEOUT),
160            string_deadline: None,
161            #[cfg(feature = "async")]
162            deadline_wakers: Vec::new(),
163            queue: EventQueue::with_capacity(16),
164            pending_error: None,
165            waker,
166            handle_resize: true,
167            poller,
168            winch_sub,
169            last_size,
170        })
171    }
172
173    #[cfg(feature = "async")]
174    pub(super) fn waiter_poller(
175        &self,
176        notification: &Waker,
177    ) -> io::Result<Arc<dyn super::poll::Poller>> {
178        let input_fd = self.input.as_fd().as_raw_fd();
179        let mut fds = [-1; READY_SLOTS + 1];
180        fds[READY_INPUT] = input_fd;
181        fds[READY_WAKE] = self.waker.poll_fd();
182        fds[READY_WINCH] = self.winch_sub.read_fd();
183        fds[READY_SLOTS] = notification.poll_fd();
184        super::poll::new_poller(&fds, unsafe { libc::isatty(input_fd) } == 1)
185    }
186
187    /// Read ready input bytes and run them through the decoder.
188    ///
189    /// Platform hook for [`EventSource::fill`]. `Interrupted` and `WouldBlock`
190    /// reads are treated as a transient absence of bytes. A trailing lone Escape
191    /// gets one ready continuation byte before queued events reach the caller.
192    /// A zero-length read is surfaced as [`io::ErrorKind::UnexpectedEof`]. If the
193    /// pending buffer is already full, it is cleared because its capacity is
194    /// the hard cap on one undecoded sequence.
195    pub(super) fn drain_input(&mut self) -> io::Result<()> {
196        self.read_bytes(self.pending.capacity())?;
197        if self.pending.slice() == b"\x1b" && self.esc_deadline.is_some() {
198            let mut ready = [false; READY_SLOTS];
199            self.poller
200                .poll(&mut ready, Some(std::time::Duration::ZERO))?;
201            if ready[READY_INPUT] {
202                // One byte resolves Escape or makes it a partial sequence, which
203                // gets a readiness check before expiry. Do not drain a new burst.
204                self.read_bytes(1)?;
205            }
206        }
207        Ok(())
208    }
209
210    fn read_bytes(&mut self, limit: usize) -> io::Result<()> {
211        // If the buffer is full and the parser still couldn't extract
212        // an event, the contract says the buffer size is the hard cap
213        // on any single sequence — drop the buffer silently and resume.
214        if self.pending.is_full() {
215            self.pending.clear();
216            self.esc_deadline = None;
217        }
218        let spare = self.pending.spare_mut();
219        let len = spare.len().min(limit);
220        let n = match self.input.read(&mut spare[..len]) {
221            Ok(n) => n,
222            Err(e) => {
223                if matches!(
224                    e.kind(),
225                    io::ErrorKind::Interrupted | io::ErrorKind::WouldBlock
226                ) {
227                    return Ok(());
228                }
229                return Err(e);
230            }
231        };
232        if n == 0 {
233            return Err(io::Error::new(io::ErrorKind::UnexpectedEof, "input closed"));
234        }
235        self.pending.advance_written(n);
236        #[cfg(debug_assertions)]
237        {
238            let s = self.pending.slice();
239            crate::trace::tee_input(&s[s.len() - n..]);
240        }
241        self.drain_parser();
242        Ok(())
243    }
244
245    pub(super) fn handle_winch(&mut self) -> io::Result<()> {
246        drain_pipe(self.winch_sub.read_fd())?;
247        // When in-band resize reporting is enabled the host disables
248        // this path; the terminal delivers resizes through the decoder
249        // instead, so emitting here too would duplicate every event.
250        if !self.handle_resize {
251            return Ok(());
252        }
253        let new_size = match get_window_size(self.input.as_fd()) {
254            Ok(sz) => sz,
255            Err(_) => return Ok(()),
256        };
257        if Some(new_size) == self.last_size {
258            return Ok(());
259        }
260        self.last_size = Some(new_size);
261        self.emit(Event::Resize(new_size));
262        Ok(())
263    }
264}
265
266pub(super) fn make_self_pipe() -> io::Result<(OwnedFd, OwnedFd)> {
267    let mut fds = [0i32; 2];
268    let rc = unsafe { libc::pipe(fds.as_mut_ptr()) };
269    if rc != 0 {
270        return Err(io::Error::last_os_error());
271    }
272    // SAFETY: pipe(2) just produced two fresh, owned fds.
273    let rx = unsafe { OwnedFd::from_raw_fd(fds[0]) };
274    let tx = unsafe { OwnedFd::from_raw_fd(fds[1]) };
275    set_nonblock_cloexec(rx.as_raw_fd())?;
276    set_nonblock_cloexec(tx.as_raw_fd())?;
277    Ok((rx, tx))
278}
279
280fn set_nonblock_cloexec(fd: i32) -> io::Result<()> {
281    unsafe {
282        let flags = libc::fcntl(fd, libc::F_GETFL);
283        if flags < 0 {
284            return Err(io::Error::last_os_error());
285        }
286        if libc::fcntl(fd, libc::F_SETFL, flags | libc::O_NONBLOCK) < 0 {
287            return Err(io::Error::last_os_error());
288        }
289        let fd_flags = libc::fcntl(fd, libc::F_GETFD);
290        if fd_flags < 0 {
291            return Err(io::Error::last_os_error());
292        }
293        if libc::fcntl(fd, libc::F_SETFD, fd_flags | libc::FD_CLOEXEC) < 0 {
294            return Err(io::Error::last_os_error());
295        }
296    }
297    Ok(())
298}
299
300pub(super) fn drain_pipe(fd: i32) -> io::Result<()> {
301    let mut buf = [0u8; 32];
302    loop {
303        let n = unsafe { libc::read(fd, buf.as_mut_ptr() as *mut _, buf.len()) };
304        if n == 0 {
305            return Err(io::Error::new(
306                io::ErrorKind::UnexpectedEof,
307                "wake pipe closed",
308            ));
309        } else if n < 0 {
310            let error = io::Error::last_os_error();
311            match error.kind() {
312                io::ErrorKind::Interrupted => continue,
313                io::ErrorKind::WouldBlock => return Ok(()),
314                _ => return Err(error),
315            }
316        }
317    }
318}
319
320#[cfg(test)]
321mod tests {
322    use super::*;
323    use crate::event::KeyCode;
324    use crate::event::SequenceKind;
325    use std::fs::File;
326    use std::os::fd::FromRawFd;
327    use std::thread;
328    use std::time::Duration;
329    use std::time::Instant;
330
331    fn make_pipe() -> (File, File) {
332        let mut fds = [0i32; 2];
333        let rc = unsafe { libc::pipe(fds.as_mut_ptr()) };
334        assert_eq!(rc, 0, "pipe() failed");
335        // SAFETY: pipe(2) produced two fresh, owned fds.
336        let rx = unsafe { File::from_raw_fd(fds[0]) };
337        let tx = unsafe { File::from_raw_fd(fds[1]) };
338        (rx, tx)
339    }
340
341    fn write_byte(f: &File, byte: u8) {
342        let n = unsafe { libc::write(f.as_raw_fd(), &byte as *const _ as *const _, 1) };
343        assert_eq!(n, 1);
344    }
345
346    fn write_bytes(f: &File, bytes: &[u8]) {
347        let n = unsafe { libc::write(f.as_raw_fd(), bytes.as_ptr() as *const _, bytes.len()) };
348        assert_eq!(n, bytes.len() as isize);
349    }
350
351    fn new_reader(input: File) -> EventSource<File> {
352        EventSource::new(input)
353            .unwrap()
354            .with_esc_timeout(Duration::from_millis(50))
355    }
356
357    #[test]
358    fn vt_input_stays_enabled_and_decodes_vt_bytes() {
359        let (rx, tx) = make_pipe();
360        let mut src = new_reader(rx);
361        src.set_vt_input(false);
362        assert!(src.vt_input());
363        write_bytes(&tx, b"\x1b[A");
364        assert!(src.poll(Some(Duration::from_secs(1))).unwrap());
365        match src.read().unwrap() {
366            Event::KeyPress(k) => assert_eq!(k.code, KeyCode::Up),
367            other => panic!("unexpected event {:?}", other),
368        }
369    }
370
371    #[test]
372    fn reads_event_from_input_fd() {
373        let (rx, tx) = make_pipe();
374        let mut src = new_reader(rx);
375        write_byte(&tx, b'a');
376        assert!(src.poll(Some(Duration::from_secs(1))).unwrap());
377        let ev = src.read().unwrap();
378        match ev {
379            Event::KeyPress(k) => assert_eq!(k.code, KeyCode::Char('a')),
380            other => panic!("unexpected event {:?}", other),
381        }
382    }
383
384    #[test]
385    fn cursor_reports_and_f3_preserve_event_order() {
386        use crate::event::{Key, KeyModifiers};
387        use crate::layout::Position;
388
389        let cpr = |x, y, page| Event::CursorPosition {
390            position: Position::new(x, y),
391            page,
392        };
393        let f3 = |modifiers| Event::KeyPress(Key::new(KeyCode::F(3), modifiers));
394        for prefix in [b"\x1b[".as_slice(), b"\x9b".as_slice()] {
395            for (body, expected) in [
396                ("R", Some(vec![f3(KeyModifiers::empty())])),
397                ("1R", Some(vec![f3(KeyModifiers::empty())])),
398                ("1;5R", Some(vec![f3(KeyModifiers::CTRL), cpr(4, 0, 0)])),
399                ("5;10R", Some(vec![cpr(9, 4, 0)])),
400                ("1;17R", Some(vec![cpr(16, 0, 0)])),
401                ("?1;5R", Some(vec![cpr(4, 0, 0)])),
402                ("?5;10;2R", Some(vec![cpr(9, 4, 2)])),
403                ("?5;10;R", Some(vec![cpr(9, 4, 0)])),
404                ("?1;5;2;3R", Some(vec![cpr(4, 0, 2)])),
405                ("1;2;3R", None),
406                ("?R", None),
407                (">1;5R", None),
408                ("?1;5 R", None),
409            ] {
410                let mut wire = [prefix, body.as_bytes()].concat();
411                let mut expected = expected.unwrap_or_else(|| {
412                    vec![Event::Unknown {
413                        kind: SequenceKind::Csi,
414                        bytes: body.as_bytes().to_vec(),
415                    }]
416                });
417                wire.push(b'x');
418                expected.push(Event::KeyPress(Key::new(
419                    KeyCode::Char('x'),
420                    KeyModifiers::empty(),
421                )));
422                let (rx, tx) = make_pipe();
423                let mut src = new_reader(rx);
424                write_bytes(&tx, &wire);
425                for event in expected {
426                    assert!(src.poll(Some(Duration::from_secs(1))).unwrap(), "{wire:?}");
427                    assert_eq!(src.read().unwrap(), event, "{wire:?}");
428                }
429                assert!(src.try_read().is_none(), "{wire:?}");
430            }
431        }
432    }
433
434    #[test]
435    fn timeout_returns_none() {
436        let (rx, _tx) = make_pipe();
437        let mut src = new_reader(rx);
438        let start = Instant::now();
439        let res = src.poll(Some(Duration::from_millis(10))).unwrap();
440        let elapsed = start.elapsed();
441        assert!(!res);
442        assert!(elapsed >= Duration::from_millis(5));
443    }
444
445    #[test]
446    fn waker_interrupts_blocking_read() {
447        let (rx, _tx) = make_pipe();
448        let mut src = new_reader(rx);
449        let waker = src.waker();
450        let handle = thread::spawn(move || {
451            thread::sleep(Duration::from_millis(20));
452            waker.wake().unwrap();
453        });
454        let err = src.read().expect_err("should be Interrupted");
455        handle.join().unwrap();
456        assert_eq!(err.kind(), io::ErrorKind::Interrupted);
457    }
458
459    #[test]
460    fn ready_input_preserves_a_simultaneous_wake() {
461        let (rx, tx) = make_pipe();
462        let mut src = new_reader(rx);
463        write_bytes(&tx, b"ab");
464        src.waker().wake().unwrap();
465        assert!(src.poll(Some(Duration::ZERO)).unwrap());
466        for code in [KeyCode::Char('a'), KeyCode::Char('b')] {
467            assert!(matches!(src.read().unwrap(), Event::KeyPress(key) if key.code == code));
468        }
469        assert_eq!(
470            src.fill(Some(Duration::ZERO)).unwrap_err().kind(),
471            io::ErrorKind::Interrupted,
472        );
473        src.fill(Some(Duration::ZERO)).unwrap();
474        assert!(src.try_read().is_none());
475    }
476
477    #[test]
478    fn wake_after_poll_snapshot_waits_for_the_next_pass() {
479        use super::super::poll::Poller;
480        use std::sync::Arc;
481
482        struct WakeAfterPoll {
483            poller: Arc<dyn Poller>,
484            waker: Waker,
485        }
486
487        impl Poller for WakeAfterPoll {
488            fn new(_: &[PollFd]) -> io::Result<Self> {
489                unreachable!("wrap an existing poller")
490            }
491
492            fn poll(&self, ready: &mut [bool], timeout: Option<Duration>) -> io::Result<usize> {
493                let count = self.poller.poll(ready, timeout)?;
494                assert!(!ready[READY_WAKE]);
495                self.waker.wake()?;
496                Ok(count)
497            }
498        }
499
500        for bytes in [b"".as_slice(), b"a"] {
501            let (rx, tx) = make_pipe();
502            let mut src = new_reader(rx);
503            write_bytes(&tx, bytes);
504            let poller = Arc::clone(&src.poller);
505            src.poller = Arc::new(WakeAfterPoll {
506                poller: Arc::clone(&poller),
507                waker: src.waker(),
508            });
509            let result = src.fill(Some(Duration::ZERO));
510            result.unwrap();
511            if !bytes.is_empty() {
512                assert!(
513                    matches!(src.try_read(), Some(Event::KeyPress(key)) if key.code == KeyCode::Char('a'))
514                );
515            }
516            src.poller = poller;
517            assert_eq!(
518                src.fill(Some(Duration::ZERO)).unwrap_err().kind(),
519                io::ErrorKind::Interrupted,
520            );
521            src.fill(Some(Duration::ZERO)).unwrap();
522            assert!(src.try_read().is_none());
523        }
524    }
525
526    #[test]
527    fn ready_resize_preserves_a_simultaneous_wake() {
528        let Some((_master, slave)) = crate::testutil::open_pty_pair() else {
529            eprintln!("skipping resize/wake regression: no usable PTY");
530            return;
531        };
532        let mut src = new_reader(slave);
533        src.last_size = None;
534        assert_eq!(unsafe { libc::raise(libc::SIGWINCH) }, 0);
535        src.waker().wake().unwrap();
536        assert!(src.poll(Some(Duration::ZERO)).unwrap());
537        assert!(matches!(src.try_read(), Some(Event::Resize(_))));
538        assert_eq!(
539            src.fill(Some(Duration::ZERO)).unwrap_err().kind(),
540            io::ErrorKind::Interrupted,
541        );
542        src.fill(Some(Duration::ZERO)).unwrap();
543        assert!(src.try_read().is_none());
544    }
545
546    #[test]
547    fn repeated_wakes_do_not_starve_input() {
548        let (rx, tx) = make_pipe();
549        let mut src = new_reader(rx);
550        let waker = src.waker();
551        for _ in 0..100 {
552            write_byte(&tx, b'x');
553            waker.wake().unwrap();
554            assert!(src.poll(Some(Duration::ZERO)).unwrap());
555            assert!(
556                matches!(src.try_read(), Some(Event::KeyPress(key)) if key.code == KeyCode::Char('x'))
557            );
558        }
559        assert_eq!(
560            src.fill(Some(Duration::ZERO)).unwrap_err().kind(),
561            io::ErrorKind::Interrupted,
562        );
563        src.fill(Some(Duration::ZERO)).unwrap();
564        assert!(src.try_read().is_none());
565    }
566
567    #[test]
568    fn queued_events_preserve_wakes_in_poll_and_read() {
569        for use_poll in [false, true] {
570            let (rx, tx) = make_pipe();
571            let mut src = new_reader(rx);
572            write_bytes(&tx, b"ab");
573            assert!(src.poll(Some(Duration::ZERO)).unwrap());
574            src.waker().wake().unwrap();
575            let event = if use_poll {
576                assert!(src.poll(Some(Duration::ZERO)).unwrap());
577                src.try_read().unwrap()
578            } else {
579                src.read().unwrap()
580            };
581            assert!(matches!(event, Event::KeyPress(k) if k.code == KeyCode::Char('a')));
582            assert!(
583                matches!(src.try_read(), Some(Event::KeyPress(k)) if k.code == KeyCode::Char('b'))
584            );
585            assert_eq!(
586                src.fill(Some(Duration::ZERO)).unwrap_err().kind(),
587                io::ErrorKind::Interrupted,
588            );
589            src.fill(Some(Duration::ZERO)).unwrap();
590
591            src.waker().wake().unwrap();
592            assert_eq!(src.read().unwrap_err().kind(), io::ErrorKind::Interrupted);
593            src.fill(Some(Duration::ZERO)).unwrap();
594        }
595    }
596
597    #[test]
598    fn expired_sequences_preserve_wakes() {
599        let (rx, tx) = make_pipe();
600        let mut src = new_reader(rx).with_esc_timeout(Duration::ZERO);
601        write_bytes(&tx, b"\x1b[");
602        assert!(!src.poll(Some(Duration::ZERO)).unwrap());
603        src.waker().wake().unwrap();
604        assert!(src.poll(Some(Duration::ZERO)).unwrap());
605        assert!(src.try_read().is_some());
606        while src.try_read().is_some() {}
607        assert_eq!(
608            src.fill(Some(Duration::ZERO)).unwrap_err().kind(),
609            io::ErrorKind::Interrupted,
610        );
611        src.fill(Some(Duration::ZERO)).unwrap();
612    }
613
614    #[test]
615    fn wakes_coalesce_and_try_read_leaves_them_pending() {
616        let (rx, _tx) = make_pipe();
617        let mut src = new_reader(rx);
618        for _ in 0..10 {
619            src.waker().wake().unwrap();
620        }
621        src.unread(Event::PasteStart);
622        assert_eq!(src.try_read(), Some(Event::PasteStart));
623        assert_eq!(src.read().unwrap_err().kind(), io::ErrorKind::Interrupted);
624        src.fill(Some(Duration::ZERO)).unwrap();
625        src.waker().wake().unwrap();
626        assert_eq!(src.read().unwrap_err().kind(), io::ErrorKind::Interrupted);
627        src.fill(Some(Duration::ZERO)).unwrap();
628    }
629
630    #[test]
631    fn eof_and_expired_input_take_priority_over_wakes() {
632        let (rx, tx) = make_pipe();
633        let mut src = new_reader(rx).with_esc_timeout(Duration::ZERO);
634        write_bytes(&tx, b"\x1b[");
635        assert!(!src.poll(Some(Duration::ZERO)).unwrap());
636        drop(tx);
637        // Concurrent fork tests can briefly retain the pipe's write end.
638        let eof = super::super::poll::new_poller(&[src.input.as_raw_fd()], false).unwrap();
639        assert_eq!(
640            eof.poll(&mut [false], Some(Duration::from_secs(2)))
641                .unwrap(),
642            1
643        );
644        src.waker().wake().unwrap();
645        assert!(src.poll(Some(Duration::ZERO)).unwrap());
646        assert!(src.try_read().is_some());
647        while src.try_read().is_some() {}
648        assert_eq!(src.read().unwrap_err().kind(), io::ErrorKind::UnexpectedEof);
649        assert_eq!(src.read().unwrap_err().kind(), io::ErrorKind::UnexpectedEof);
650        let mut ready = [false; READY_SLOTS];
651        src.poller.poll(&mut ready, Some(Duration::ZERO)).unwrap();
652        assert!(ready[READY_WAKE]);
653    }
654
655    #[test]
656    fn ready_resize_and_input_both_survive_a_wake() {
657        let Some((master, slave)) = crate::testutil::open_pty_pair() else {
658            eprintln!("skipping resize/input/wake regression: no usable PTY");
659            return;
660        };
661        let mut raw = unsafe { std::mem::zeroed() };
662        assert_eq!(unsafe { libc::tcgetattr(slave.as_raw_fd(), &mut raw) }, 0);
663        unsafe { libc::cfmakeraw(&mut raw) };
664        assert_eq!(
665            unsafe { libc::tcsetattr(slave.as_raw_fd(), libc::TCSANOW, &raw) },
666            0
667        );
668        let mut src = new_reader(slave);
669        src.last_size = None;
670        write_byte(&master, b'x');
671        // A PTY write can return before the slave becomes readable.
672        let input = super::super::poll::new_poller(&[src.input.as_raw_fd()], true).unwrap();
673        assert_eq!(
674            input
675                .poll(&mut [false], Some(Duration::from_secs(2)))
676                .unwrap(),
677            1
678        );
679        assert_eq!(unsafe { libc::raise(libc::SIGWINCH) }, 0);
680        src.waker().wake().unwrap();
681        assert!(src.poll(Some(Duration::from_secs(1))).unwrap());
682        assert!(matches!(src.try_read(), Some(Event::Resize(_))));
683        assert!(matches!(src.read().unwrap(), Event::KeyPress(k) if k.code == KeyCode::Char('x')));
684        assert_eq!(
685            src.fill(Some(Duration::ZERO)).unwrap_err().kind(),
686            io::ErrorKind::Interrupted,
687        );
688        src.fill(Some(Duration::ZERO)).unwrap();
689        assert!(src.try_read().is_none());
690    }
691
692    #[test]
693    fn simultaneous_wake_preserves_partial_input() {
694        let (rx, tx) = make_pipe();
695        let mut src = new_reader(rx);
696        write_bytes(&tx, b"\x1b[");
697        src.waker().wake().unwrap();
698        let error = src.fill(Some(Duration::ZERO)).unwrap_err();
699        assert_eq!(error.kind(), io::ErrorKind::Interrupted);
700        assert_eq!(src.pending.slice(), b"\x1b[");
701        write_byte(&tx, b'A');
702        assert!(src.poll(Some(Duration::ZERO)).unwrap());
703        assert!(matches!(src.try_read(), Some(Event::KeyPress(key)) if key.code == KeyCode::Up));
704    }
705
706    #[test]
707    fn queued_escape_continuation_survives_batch_boundary() {
708        struct ShortReads(File);
709
710        impl std::os::fd::AsFd for ShortReads {
711            fn as_fd(&self) -> std::os::fd::BorrowedFd<'_> {
712                self.0.as_fd()
713            }
714        }
715
716        impl std::io::Read for ShortReads {
717            fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
718                let len = buf.len().min(64);
719                self.0.read(&mut buf[..len])
720            }
721        }
722
723        let (rx, tx) = make_pipe();
724        let mut src = EventSource::new(ShortReads(rx))
725            .unwrap()
726            .with_esc_timeout(Duration::ZERO);
727        write_bytes(&tx, &b"\x1b[B".repeat(29));
728        src.waker().wake().unwrap();
729        assert!(src.poll(Some(Duration::ZERO)).unwrap());
730        for _ in 0..29 {
731            assert!(src.poll(Some(Duration::from_secs(1))).unwrap());
732            assert!(
733                matches!(src.read().unwrap(), Event::KeyPress(key) if key.code == KeyCode::Down)
734            );
735        }
736        assert!(src.try_read().is_none());
737        assert_eq!(
738            src.fill(Some(Duration::ZERO)).unwrap_err().kind(),
739            io::ErrorKind::Interrupted,
740        );
741    }
742
743    #[test]
744    fn esc_resolves_before_late_continuation_byte() {
745        // A buffered partial ESC whose deadline elapses must resolve to a
746        // bare Esc before a continuation byte that arrives afterward is
747        // read, so the two never merge into an Alt-modified key.
748        let (rx, tx) = make_pipe();
749        let mut src = new_reader(rx); // 50ms esc timeout
750        write_bytes(&tx, b"\x1b");
751        // Drain the lone ESC so its disambiguation deadline is armed; the
752        // queue stays empty because the sequence is still partial.
753        assert!(!src.poll(Some(Duration::from_millis(0))).unwrap());
754        // Let the deadline elapse without draining, then deliver a byte
755        // that would otherwise complete an ESC-prefixed sequence.
756        thread::sleep(Duration::from_millis(80));
757        write_bytes(&tx, b"a");
758        let first = src.read().unwrap();
759        assert!(
760            matches!(&first, Event::KeyPress(k) if k.code == KeyCode::Escape),
761            "expected bare Esc, got {:?}",
762            first
763        );
764        let second = src.read().unwrap();
765        assert!(
766            matches!(&second, Event::KeyPress(k) if k.code == KeyCode::Char('a')),
767            "expected 'a', got {:?}",
768            second
769        );
770    }
771
772    #[test]
773    fn ambiguous_introducers_expire_as_alt_keys() {
774        use crate::event::{Key, KeyModifiers};
775
776        for flags in [DecoderFlags::empty(), DecoderFlags::CTRL_OPEN_BRACKET] {
777            for byte in b"[O]P_X^" {
778                let (rx, tx) = make_pipe();
779                let mut src = new_reader(rx)
780                    .with_esc_timeout(Duration::ZERO)
781                    .with_decoder_flags(flags);
782                write_bytes(&tx, &[0x1b, *byte]);
783                src.fill(Some(Duration::ZERO)).unwrap();
784                assert!(src.try_read().is_none());
785                src.fill(Some(Duration::ZERO)).unwrap();
786                assert_eq!(
787                    src.try_read(),
788                    Some(Event::KeyPress(
789                        Key::new(KeyCode::Char(*byte as char), KeyModifiers::ALT).normalized()
790                    )),
791                );
792                assert!(src.try_read().is_none());
793            }
794        }
795    }
796
797    #[test]
798    fn expired_input_is_delivered_before_eof() {
799        use crate::event::{Key, KeyModifiers};
800
801        for (input, expected) in [
802            (
803                b"\x1b[".as_slice(),
804                Some(Event::KeyPress(Key::new(
805                    KeyCode::Char('['),
806                    KeyModifiers::ALT,
807                ))),
808            ),
809            (b"\x1b]q", None),
810        ] {
811            for expired in [false, true] {
812                let (rx, tx) = make_pipe();
813                let timeout = if expired {
814                    Duration::ZERO
815                } else {
816                    Duration::from_secs(60)
817                };
818                let mut src = new_reader(rx).with_esc_timeout(timeout);
819                write_bytes(&tx, input);
820                assert!(!src.poll(Some(Duration::ZERO)).unwrap());
821                drop(tx);
822
823                if expired && let Some(expected) = &expected {
824                    assert_eq!(&src.read().unwrap(), expected);
825                }
826                assert_eq!(src.read().unwrap_err().kind(), io::ErrorKind::UnexpectedEof);
827                assert!(src.try_read().is_none());
828            }
829        }
830    }
831
832    #[test]
833    fn expired_input_is_delivered_before_other_read_errors() {
834        use crate::event::{Key, KeyModifiers};
835
836        struct ErrorAfterRead {
837            input: File,
838            fail: bool,
839        }
840
841        impl std::os::fd::AsFd for ErrorAfterRead {
842            fn as_fd(&self) -> std::os::fd::BorrowedFd<'_> {
843                self.input.as_fd()
844            }
845        }
846
847        impl std::io::Read for ErrorAfterRead {
848            fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
849                if self.fail {
850                    return Err(io::Error::from_raw_os_error(libc::EIO));
851                }
852                self.fail = true;
853                self.input.read(buf)
854            }
855        }
856
857        for (input, expected) in [
858            (
859                b"\x1b[".as_slice(),
860                Some(Event::KeyPress(Key::new(
861                    KeyCode::Char('['),
862                    KeyModifiers::ALT,
863                ))),
864            ),
865            (b"\x1b]q", None),
866        ] {
867            let (rx, tx) = make_pipe();
868            let mut src = EventSource::new(ErrorAfterRead {
869                input: rx,
870                fail: false,
871            })
872            .unwrap()
873            .with_esc_timeout(Duration::ZERO);
874            write_bytes(&tx, input);
875            assert!(!src.poll(Some(Duration::ZERO)).unwrap());
876            write_byte(&tx, b'x');
877
878            if let Some(expected) = expected {
879                assert_eq!(src.read().unwrap(), expected);
880            }
881            assert_eq!(src.read().unwrap_err().raw_os_error(), Some(libc::EIO));
882            assert!(src.try_read().is_none());
883        }
884    }
885
886    #[test]
887    fn expired_introducers_preserve_following_keys() {
888        use crate::event::{Key, KeyModifiers};
889
890        for intro in b"[]OP_X^" {
891            for (next, key) in [
892                (
893                    b"\x1b[A".as_slice(),
894                    Key::new(KeyCode::Up, KeyModifiers::empty()),
895                ),
896                (
897                    b"\x1ba".as_slice(),
898                    Key::new(KeyCode::Char('a'), KeyModifiers::ALT),
899                ),
900            ] {
901                let (rx, tx) = make_pipe();
902                let mut src = new_reader(rx);
903                write_bytes(&tx, &[0x1b, *intro]);
904                src.fill(Some(Duration::ZERO)).unwrap();
905                src.esc_deadline = Some(Instant::now() - Duration::from_secs(1));
906                write_bytes(&tx, next);
907                assert_eq!(
908                    src.read().unwrap(),
909                    Event::KeyPress(
910                        Key::new(KeyCode::Char(*intro as char), KeyModifiers::ALT).normalized()
911                    ),
912                    "intro={intro:#x}, next={next:?}",
913                );
914                assert_eq!(src.read().unwrap(), Event::KeyPress(key.normalized()));
915                assert!(src.try_read().is_none());
916            }
917        }
918    }
919
920    #[test]
921    fn ready_continuations_refresh_sequence_deadlines() {
922        use crate::event::{Key, KeyModifiers};
923
924        for prefix in [b"\x1b[".as_slice(), b"\x9b"] {
925            for overdue in [false, true] {
926                let (rx, tx) = make_pipe();
927                let mut src = new_reader(rx);
928                write_bytes(&tx, prefix);
929                src.fill(Some(Duration::ZERO)).unwrap();
930                for fragment in [b"1".as_slice(), b";", b"2"] {
931                    let old = if overdue {
932                        Instant::now() - Duration::from_secs(1)
933                    } else {
934                        Instant::now() + Duration::from_secs(1)
935                    };
936                    src.esc_deadline = Some(old);
937                    write_bytes(&tx, fragment);
938                    src.fill(Some(Duration::ZERO)).unwrap();
939                    assert!(src.try_read().is_none(), "{fragment:?}");
940                    let new = src.esc_deadline.unwrap();
941                    assert!(if overdue { new > old } else { new < old });
942                }
943                write_bytes(&tx, b"A");
944                src.fill(Some(Duration::ZERO)).unwrap();
945                assert_eq!(
946                    src.try_read(),
947                    Some(Event::KeyPress(Key::new(KeyCode::Up, KeyModifiers::SHIFT))),
948                );
949                assert!(src.try_read().is_none());
950            }
951        }
952    }
953
954    #[test]
955    fn control_string_bodies_wait_across_reads_and_timeouts() {
956        for (introducer, c1, expected) in [
957            (b']', 0x9d, SequenceKind::Osc),
958            (b'P', 0x90, SequenceKind::Dcs),
959            (b'_', 0x9f, SequenceKind::Apc),
960            (b'X', 0x98, SequenceKind::Sos),
961            (b'^', 0x9e, SequenceKind::Pm),
962        ] {
963            let expected = Event::Unknown {
964                kind: expected,
965                bytes: b"qqqq".to_vec(),
966            };
967            for prefix in [vec![0x1b, introducer], vec![c1]] {
968                for ending in [b"\x1b\\".as_slice(), b"\x9c"] {
969                    let (rx, tx) = make_pipe();
970                    let mut src = new_reader(rx).with_esc_timeout(Duration::ZERO);
971                    write_bytes(&tx, &[prefix.as_slice(), b"q"].concat());
972                    src.fill(Some(Duration::ZERO)).unwrap();
973                    src.fill(Some(Duration::ZERO)).unwrap();
974                    assert!(src.try_read().is_none(), "{prefix:?}");
975                    assert_eq!(src.effective_timeout(None), None);
976                    for fragment in [b"qqq".as_slice(), &ending[..ending.len() - 1]] {
977                        if !fragment.is_empty() {
978                            write_bytes(&tx, fragment);
979                        }
980                        src.fill(Some(Duration::ZERO)).unwrap();
981                        src.fill(Some(Duration::ZERO)).unwrap();
982                        assert!(src.try_read().is_none(), "{prefix:?}");
983                    }
984                    write_bytes(&tx, &ending[ending.len() - 1..]);
985                    assert_eq!(src.read().unwrap(), expected);
986                    write_bytes(&tx, b"\x1b");
987                    assert_eq!(
988                        src.read().unwrap(),
989                        Event::KeyPress(crate::event::Key::new(
990                            KeyCode::Escape,
991                            crate::event::KeyModifiers::empty()
992                        )),
993                    );
994                    assert!(src.try_read().is_none());
995                }
996            }
997        }
998    }
999
1000    #[test]
1001    fn large_clipboard_reply_keeps_payload_out_of_keyboard_events() {
1002        use std::io::Write;
1003
1004        let (rx, mut tx) = make_pipe();
1005        let mut src = new_reader(rx);
1006        let writer = thread::spawn(move || -> io::Result<()> {
1007            tx.write_all(b"\x1b]52;c;")?;
1008            tx.write_all(&vec![b'A'; 1024 * 1024])?;
1009            tx.write_all(b"\x1b\\x")
1010        });
1011        assert_eq!(
1012            src.read().unwrap(),
1013            Event::ClipboardStart {
1014                selection: crate::event::ClipboardSelection::System,
1015            }
1016        );
1017        let mut bytes = 0;
1018        let mut chunks = 0;
1019        loop {
1020            match src.read().unwrap() {
1021                Event::ClipboardChunk(chunk) => {
1022                    assert!(chunk.iter().all(|&b| b == b'A'));
1023                    bytes += chunk.len();
1024                    chunks += 1;
1025                }
1026                Event::ClipboardEnd { complete: true } => break,
1027                event => panic!("unexpected clipboard event: {event:?}"),
1028            }
1029        }
1030        assert_eq!(bytes, 1024 * 1024);
1031        assert!(chunks > 1);
1032        assert!(
1033            matches!(src.read().unwrap(), Event::KeyPress(key) if key.code == KeyCode::Char('x'))
1034        );
1035        writer.join().unwrap().unwrap();
1036    }
1037
1038    #[test]
1039    fn transfer_eof_delivers_remaining_bytes_and_incomplete_end_before_error() {
1040        for clipboard in [false, true] {
1041            for tail in [b"".as_slice(), b"\x1b", b"\xf0\x9f"] {
1042                let (rx, tx) = make_pipe();
1043                let mut src = new_reader(rx).with_esc_timeout(Duration::ZERO);
1044                let header = if clipboard {
1045                    b"\x1b]52;c;".as_slice()
1046                } else {
1047                    b"\x1b[200~"
1048                };
1049                write_bytes(&tx, &[header, b"QQ==", tail].concat());
1050                drop(tx);
1051                let start = src.read().unwrap();
1052                assert!(if clipboard {
1053                    matches!(start, Event::ClipboardStart { .. })
1054                } else {
1055                    start == Event::PasteStart
1056                });
1057                let mut payload = Vec::new();
1058                loop {
1059                    match src.read().unwrap() {
1060                        Event::ClipboardChunk(bytes) if clipboard => payload.extend(bytes),
1061                        Event::PasteChunk(bytes) if !clipboard => payload.extend(bytes),
1062                        Event::ClipboardEnd { complete: false } if clipboard => break,
1063                        Event::PasteEnd { complete: false } if !clipboard => break,
1064                        event => panic!("unexpected transfer event: {event:?}"),
1065                    }
1066                }
1067                assert_eq!(payload, [b"QQ==".as_slice(), tail].concat());
1068                assert_eq!(src.read().unwrap_err().kind(), io::ErrorKind::UnexpectedEof);
1069            }
1070        }
1071    }
1072
1073    #[test]
1074    fn string_eof_delivers_remaining_bytes_and_incomplete_end_before_error() {
1075        for tail in [b"".as_slice(), b"\x1b", b"\xf0\x9f"] {
1076            let (rx, tx) = make_pipe();
1077            let mut src = new_reader(rx).with_esc_timeout(Duration::ZERO);
1078            let body = [&[b'q'; 4097][..], tail].concat();
1079            let wire = [b"\x1bP".as_slice(), &body].concat();
1080            // The pipe can hold less than the whole string.
1081            let writer = thread::spawn(move || write_bytes(&tx, &wire));
1082            assert_eq!(
1083                src.read().unwrap(),
1084                Event::StringStart {
1085                    kind: SequenceKind::Dcs
1086                }
1087            );
1088            let mut received = Vec::new();
1089            loop {
1090                match src.read().unwrap() {
1091                    Event::StringChunk(bytes) => received.extend(bytes),
1092                    Event::StringEnd { complete: false } => break,
1093                    event => panic!("unexpected string event: {event:?}"),
1094                }
1095            }
1096            writer.join().unwrap();
1097            assert_eq!(received, body);
1098            assert_eq!(src.read().unwrap_err().kind(), io::ErrorKind::UnexpectedEof);
1099        }
1100    }
1101
1102    #[test]
1103    fn string_recovery_flushes_retained_bytes_before_new_keys() {
1104        for manual in [false, true] {
1105            let (rx, tx) = make_pipe();
1106            let mut src = new_reader(rx).with_string_idle_timeout(None);
1107            let body = vec![b'q'; 4097];
1108            src.feed_bytes(&[b"\x1b]".as_slice(), &body, b"\x1b"].concat());
1109            assert_eq!(
1110                src.try_read(),
1111                Some(Event::StringStart {
1112                    kind: SequenceKind::Osc
1113                })
1114            );
1115            assert_eq!(src.try_read(), Some(Event::StringChunk(body)));
1116            assert!(src.try_read().is_none());
1117            if manual {
1118                src.end_string();
1119            } else {
1120                src.set_string_idle_timeout(Some(Duration::ZERO));
1121            }
1122            write_bytes(&tx, b"x");
1123            assert_eq!(src.read().unwrap(), Event::StringChunk(b"\x1b".to_vec()));
1124            assert_eq!(src.read().unwrap(), Event::StringEnd { complete: false });
1125            assert!(matches!(src.read().unwrap(), Event::KeyPress(key)
1126                if key.code == KeyCode::Char('x')));
1127        }
1128    }
1129
1130    #[test]
1131    fn string_idle_deadline_bounds_a_blocking_wait() {
1132        let (rx, _tx) = make_pipe();
1133        let mut src = new_reader(rx).with_string_idle_timeout(Some(Duration::from_millis(40)));
1134        src.feed_bytes(&[b"\x1bP".as_slice(), &[b'q'; 4097]].concat());
1135        assert!(matches!(src.try_read(), Some(Event::StringStart { .. })));
1136        assert!(matches!(src.try_read(), Some(Event::StringChunk(_))));
1137        assert!(src.poll(Some(Duration::from_secs(1))).unwrap());
1138        assert_eq!(src.try_read(), Some(Event::StringEnd { complete: false }));
1139        assert!(src.try_read().is_none());
1140        assert_eq!(src.effective_timeout(None), None);
1141    }
1142
1143    #[test]
1144    fn transfer_recovery_flushes_retained_bytes_before_new_keys() {
1145        for clipboard in [false, true] {
1146            for manual in [false, true] {
1147                let (rx, tx) = make_pipe();
1148                let mut src = new_reader(rx)
1149                    .with_paste_idle_timeout(None)
1150                    .with_clipboard_idle_timeout(None);
1151                let header = if clipboard {
1152                    b"\x1b]52;c;".as_slice()
1153                } else {
1154                    b"\x1b[200~"
1155                };
1156                src.feed_bytes(&[header, b"data\x1b"].concat());
1157                assert!(src.try_read().is_some());
1158                let chunk = if clipboard {
1159                    Event::ClipboardChunk(b"data".to_vec())
1160                } else {
1161                    Event::PasteChunk(b"data".to_vec())
1162                };
1163                assert_eq!(src.try_read(), Some(chunk));
1164                assert!(src.try_read().is_none());
1165                match (clipboard, manual) {
1166                    (true, true) => src.end_clipboard(),
1167                    (false, true) => src.end_paste(),
1168                    (true, false) => src.set_clipboard_idle_timeout(Some(Duration::ZERO)),
1169                    (false, false) => src.set_paste_idle_timeout(Some(Duration::ZERO)),
1170                }
1171                write_bytes(&tx, b"x");
1172                let chunk = if clipboard {
1173                    Event::ClipboardChunk(b"\x1b".to_vec())
1174                } else {
1175                    Event::PasteChunk(b"\x1b".to_vec())
1176                };
1177                let end = if clipboard {
1178                    Event::ClipboardEnd { complete: false }
1179                } else {
1180                    Event::PasteEnd { complete: false }
1181                };
1182                assert_eq!(src.read().unwrap(), chunk);
1183                assert_eq!(src.read().unwrap(), end);
1184                assert!(matches!(src.read().unwrap(), Event::KeyPress(key)
1185                            if key.code == KeyCode::Char('x')));
1186                src.end_clipboard();
1187                src.end_paste();
1188                assert!(src.try_read().is_none());
1189            }
1190        }
1191    }
1192
1193    #[test]
1194    fn transfer_expiry_during_readiness_wait_precedes_new_keys() {
1195        use crate::event::poll::Poller;
1196        use std::sync::Arc;
1197
1198        struct InputAfterTimeout {
1199            poller: Arc<dyn Poller>,
1200            writer: File,
1201        }
1202
1203        impl Poller for InputAfterTimeout {
1204            fn new(_: &[PollFd]) -> io::Result<Self> {
1205                unreachable!("wrap an existing poller")
1206            }
1207
1208            fn poll(&self, ready: &mut [bool], timeout: Option<Duration>) -> io::Result<usize> {
1209                // Simulate input arriving as the timed wait returns to its caller.
1210                thread::sleep(timeout.expect("active transfer deadline"));
1211                write_bytes(&self.writer, b"x");
1212                self.poller.poll(ready, Some(Duration::ZERO))
1213            }
1214        }
1215
1216        for clipboard in [false, true] {
1217            let (rx, tx) = make_pipe();
1218            let timeout = Some(Duration::from_millis(40));
1219            let mut src = new_reader(rx)
1220                .with_paste_idle_timeout(timeout)
1221                .with_clipboard_idle_timeout(timeout);
1222            src.poller = Arc::new(InputAfterTimeout {
1223                poller: Arc::clone(&src.poller),
1224                writer: tx,
1225            });
1226            src.feed_bytes(if clipboard {
1227                b"\x1b]52;c;"
1228            } else {
1229                b"\x1b[200~"
1230            });
1231            assert!(src.try_read().is_some());
1232            src.fill(Some(Duration::from_secs(1))).unwrap();
1233            let end = if clipboard {
1234                Event::ClipboardEnd { complete: false }
1235            } else {
1236                Event::PasteEnd { complete: false }
1237            };
1238            assert_eq!(src.try_read(), Some(end));
1239            assert!(matches!(src.try_read(), Some(Event::KeyPress(key))
1240                if key.code == KeyCode::Char('x')));
1241            assert!(src.try_read().is_none());
1242        }
1243    }
1244
1245    #[test]
1246    fn clipboard_idle_deadline_bounds_a_blocking_wait_after_the_header() {
1247        let (rx, _tx) = make_pipe();
1248        let mut src = new_reader(rx).with_clipboard_idle_timeout(Some(Duration::from_millis(40)));
1249        src.feed_bytes(b"\x1b]52;c;");
1250        assert!(matches!(src.try_read(), Some(Event::ClipboardStart { .. })));
1251        assert!(src.poll(Some(Duration::from_secs(1))).unwrap());
1252        assert_eq!(
1253            src.try_read(),
1254            Some(Event::ClipboardEnd { complete: false })
1255        );
1256        assert!(src.try_read().is_none());
1257        assert_eq!(src.effective_timeout(None), None);
1258    }
1259
1260    #[test]
1261    fn caller_timeout_preserves_an_idle_osc_reply() {
1262        let (rx, tx) = make_pipe();
1263        let mut src = new_reader(rx)
1264            .with_esc_timeout(Duration::ZERO)
1265            .with_clipboard_idle_timeout(None);
1266        write_bytes(&tx, b"\x1b]52;c;Zm9v");
1267        assert!(matches!(src.read().unwrap(), Event::ClipboardStart { .. }));
1268        assert_eq!(src.read().unwrap(), Event::ClipboardChunk(b"Zm9v".to_vec()));
1269        src.waker().wake().unwrap();
1270        assert_eq!(src.read().unwrap_err().kind(), io::ErrorKind::Interrupted);
1271        assert!(!src.poll(Some(Duration::ZERO)).unwrap());
1272        assert!(!src.poll(Some(Duration::from_millis(2100))).unwrap());
1273        assert!(src.try_read().is_none());
1274        write_bytes(&tx, b"\x1b\\");
1275        assert_eq!(src.read().unwrap(), Event::ClipboardEnd { complete: true },);
1276    }
1277
1278    #[test]
1279    fn osc_payloads_wait_for_terminator_after_escape_timeout() {
1280        for prefix in [b"\x1b]".as_slice(), b"\x9d"] {
1281            for ending in [b"\x1b\\".as_slice(), b"\x07", b"\x9c"] {
1282                for (body, expected) in [
1283                    (
1284                        b"72;t=r:x=1;qqqq".as_slice(),
1285                        Event::DragDrop {
1286                            options: vec![("t".into(), "r".into()), ("x".into(), "1".into())],
1287                            payload: b"qqqq".to_vec(),
1288                        },
1289                    ),
1290                    (
1291                        b"999;qqqq",
1292                        Event::Unknown {
1293                            kind: SequenceKind::Osc,
1294                            bytes: b"999;qqqq".to_vec(),
1295                        },
1296                    ),
1297                ] {
1298                    let (rx, tx) = make_pipe();
1299                    let mut src = new_reader(rx).with_esc_timeout(Duration::ZERO);
1300                    write_bytes(&tx, &[prefix, body].concat());
1301                    src.fill(Some(Duration::ZERO)).unwrap();
1302                    src.fill(Some(Duration::ZERO)).unwrap();
1303                    let events: Vec<_> = std::iter::from_fn(|| src.try_read()).collect();
1304                    assert!(
1305                        events.is_empty(),
1306                        "partial OSC payload escaped as input: {events:?}"
1307                    );
1308                    write_bytes(&tx, ending);
1309                    assert_eq!(src.read().unwrap(), expected);
1310                    assert!(src.try_read().is_none());
1311                }
1312            }
1313        }
1314    }
1315
1316    #[test]
1317    fn escape_sequence_interrupts_a_string() {
1318        use crate::event::{Key, KeyModifiers};
1319
1320        let (rx, tx) = make_pipe();
1321        let mut src = new_reader(rx).with_esc_timeout(Duration::ZERO);
1322        write_bytes(&tx, b"\x1b]qqqq\x1b");
1323        src.fill(Some(Duration::ZERO)).unwrap();
1324        src.fill(Some(Duration::ZERO)).unwrap();
1325        assert!(src.try_read().is_none());
1326        write_bytes(&tx, b"[A");
1327        src.fill(Some(Duration::ZERO)).unwrap();
1328        assert_eq!(
1329            src.try_read(),
1330            Some(Event::Unknown {
1331                kind: SequenceKind::Raw,
1332                bytes: b"\x1b]qqqq".to_vec(),
1333            })
1334        );
1335        assert_eq!(
1336            src.try_read(),
1337            Some(Event::KeyPress(Key::new(
1338                KeyCode::Up,
1339                KeyModifiers::empty()
1340            ))),
1341        );
1342        assert!(src.try_read().is_none());
1343        assert_eq!(src.effective_timeout(None), None);
1344    }
1345
1346    #[test]
1347    fn paste_idle_timeout_synthesizes_paste_end() {
1348        let (rx, tx) = make_pipe();
1349        let mut src = EventSource::new(rx)
1350            .unwrap()
1351            .with_paste_idle_timeout(Some(Duration::from_millis(40)));
1352        write_bytes(&tx, b"\x1b[200~hello");
1353        // Drain PasteStart + initial chunk.
1354        let mut got_start = false;
1355        let mut got_chunk = false;
1356        for _ in 0..4 {
1357            if !src.poll(Some(Duration::from_millis(20))).unwrap() {
1358                break;
1359            }
1360            while let Some(ev) = src.try_read() {
1361                match ev {
1362                    Event::PasteStart => got_start = true,
1363                    Event::PasteChunk(b) => {
1364                        assert_eq!(b, b"hello".to_vec());
1365                        got_chunk = true;
1366                    }
1367                    other => panic!("unexpected pre-timeout event {:?}", other),
1368                }
1369            }
1370            if got_start && got_chunk {
1371                break;
1372            }
1373        }
1374        assert!(got_start && got_chunk);
1375
1376        // Now stop sending data and wait past the paste-idle deadline.
1377        let start = Instant::now();
1378        assert!(src.poll(Some(Duration::from_secs(5))).unwrap());
1379        let ev = src.read().unwrap();
1380        let elapsed = start.elapsed();
1381        assert_eq!(ev, Event::PasteEnd { complete: false });
1382        assert!(
1383            elapsed < Duration::from_millis(500),
1384            "elapsed = {:?}",
1385            elapsed
1386        );
1387    }
1388
1389    #[test]
1390    fn paste_completes_when_terminator_arrives_within_idle_window() {
1391        let (rx, tx) = make_pipe();
1392        let mut src = EventSource::new(rx)
1393            .unwrap()
1394            .with_paste_idle_timeout(Some(Duration::from_millis(500)));
1395        write_bytes(&tx, b"\x1b[200~hi");
1396        let _ = src.poll(Some(Duration::from_millis(50))).unwrap();
1397        while src.try_read().is_some() {}
1398        let deadline = src.paste_deadline.expect("open paste has an idle deadline");
1399        // Sub-timeout pause, then deliver the terminator.
1400        thread::sleep(Duration::from_millis(50));
1401        write_bytes(&tx, b"\x1b[201~");
1402        assert!(src.poll(Some(Duration::from_millis(100))).unwrap());
1403        let mut saw_end = false;
1404        while let Some(ev) = src.try_read() {
1405            if matches!(ev, Event::PasteEnd { complete: true }) {
1406                saw_end = true;
1407            }
1408        }
1409        if !saw_end {
1410            // Drain another pump cycle if necessary.
1411            let _ = src.poll(Some(Duration::from_millis(50))).unwrap();
1412            while let Some(ev) = src.try_read() {
1413                if matches!(ev, Event::PasteEnd { complete: true }) {
1414                    saw_end = true;
1415                }
1416            }
1417        }
1418        assert!(saw_end, "expected PasteEnd within the idle window");
1419        assert!(Instant::now() < deadline, "paste idle deadline expired");
1420    }
1421
1422    #[test]
1423    fn explicit_end_paste_recovers_stream() {
1424        let (rx, tx) = make_pipe();
1425        let mut src = EventSource::new(rx).unwrap().with_paste_idle_timeout(None);
1426        write_bytes(&tx, b"\x1b[200~stuck");
1427        let _ = src.poll(Some(Duration::from_millis(50))).unwrap();
1428        while src.try_read().is_some() {}
1429
1430        // No terminator will arrive; force-exit.
1431        src.end_paste();
1432        let ev = src.try_read().expect("PasteEnd should be queued");
1433        assert_eq!(ev, Event::PasteEnd { complete: false });
1434
1435        // Subsequent bytes parse as normal input again.
1436        write_bytes(&tx, b"a");
1437        assert!(src.poll(Some(Duration::from_secs(1))).unwrap());
1438        let ev = src.read().unwrap();
1439        assert!(matches!(
1440            ev,
1441            Event::KeyPress(ref k) if k.code == KeyCode::Char('a')
1442        ));
1443    }
1444
1445    #[test]
1446    fn paste_idle_timeout_disabled_blocks_indefinitely() {
1447        let (rx, tx) = make_pipe();
1448        let mut src = EventSource::new(rx).unwrap().with_paste_idle_timeout(None);
1449        write_bytes(&tx, b"\x1b[200~partial");
1450        let _ = src.poll(Some(Duration::from_millis(50))).unwrap();
1451        while src.try_read().is_some() {}
1452        assert!(src.parser.in_paste());
1453        assert_eq!(src.paste_deadline, None);
1454
1455        // With the safety net disabled, a long-but-finite caller
1456        // timeout should expire without synthesising PasteEnd.
1457        let res = src.poll(Some(Duration::from_millis(80))).unwrap();
1458        assert!(!res, "should time out, not synthesise PasteEnd");
1459        assert!(src.try_read().is_none());
1460    }
1461
1462    /// The flags reach the decoder, and what they change is which key a byte
1463    /// is called. `0x0d` is `enter` by default and `ctrl+m` when a caller
1464    /// asks for that reading.
1465    #[test]
1466    fn the_decoder_flags_a_caller_chose_are_the_ones_used() {
1467        use crate::event::DecoderFlags;
1468
1469        let (rx, tx) = make_pipe();
1470        let mut src = EventSource::new(rx).unwrap();
1471        write_byte(&tx, 0x0d);
1472        assert!(src.poll(Some(Duration::from_secs(1))).unwrap());
1473        let Event::KeyPress(k) = src.read().unwrap() else {
1474            panic!("expected a key")
1475        };
1476        assert_eq!(k.code, KeyCode::Enter, "the reading a terminal means");
1477
1478        let (rx, tx) = make_pipe();
1479        let mut src = EventSource::new(rx)
1480            .unwrap()
1481            .with_decoder_flags(DecoderFlags::CTRL_M);
1482        assert_eq!(src.decoder_flags(), DecoderFlags::CTRL_M);
1483        write_byte(&tx, 0x0d);
1484        assert!(src.poll(Some(Duration::from_secs(1))).unwrap());
1485        let Event::KeyPress(k) = src.read().unwrap() else {
1486            panic!("expected a key")
1487        };
1488        assert_eq!(k.code, KeyCode::Char('m'));
1489        assert_eq!(k.modifiers, crate::event::KeyModifiers::CTRL);
1490    }
1491
1492    /// `0x1b` is the Escape key and `ctrl+[` both, and an application that
1493    /// asked for the Ctrl reading gets it for a real lone `ESC`: the one the
1494    /// source resolves itself once the escape deadline passes, which is the
1495    /// only way that byte ever arrives alone.
1496    #[test]
1497    fn a_lone_escape_from_the_terminal_follows_the_flag() {
1498        use crate::event::DecoderFlags;
1499
1500        let (rx, tx) = make_pipe();
1501        let mut src = EventSource::new(rx)
1502            .unwrap()
1503            .with_esc_timeout(Duration::from_millis(20))
1504            .with_decoder_flags(DecoderFlags::CTRL_OPEN_BRACKET);
1505        write_byte(&tx, 0x1b);
1506        // The first poll buffers it; the deadline is what resolves it, so
1507        // give the source long enough to reach its own.
1508        let _ = src.poll(Some(Duration::from_millis(50))).unwrap();
1509        assert!(src.poll(Some(Duration::from_secs(1))).unwrap());
1510        let Event::KeyPress(k) = src.read().unwrap() else {
1511            panic!("expected a key")
1512        };
1513        assert_eq!(k.code, KeyCode::Char('['));
1514        assert_eq!(k.modifiers, crate::event::KeyModifiers::CTRL);
1515    }
1516
1517    /// The same choice on a source already in use, which is the seam
1518    /// [`Program::init`](crate::program::Program::init) reaches
1519    /// through when it carries `ProgramOptions::legacy_keys`.
1520    #[test]
1521    fn the_flags_can_be_chosen_on_a_source_already_built() {
1522        use crate::event::DecoderFlags;
1523
1524        let (rx, tx) = make_pipe();
1525        let mut src = EventSource::new(rx).unwrap();
1526        assert!(
1527            src.decoder_flags().is_empty(),
1528            "a source reads each as the named key until told otherwise"
1529        );
1530        src.set_decoder_flags(DecoderFlags::CTRL_I);
1531        write_byte(&tx, 0x09);
1532        assert!(src.poll(Some(Duration::from_secs(1))).unwrap());
1533        let Event::KeyPress(k) = src.read().unwrap() else {
1534            panic!("expected a key")
1535        };
1536        assert_eq!(k.code, KeyCode::Char('i'));
1537        assert_eq!(k.modifiers, crate::event::KeyModifiers::CTRL);
1538    }
1539
1540    #[test]
1541    fn esc_deadline_does_not_fire_during_paste() {
1542        // Pre-fix latent bug: while in paste, a partial ESC at the
1543        // head of the pending buffer must not synthesise Key(Esc).
1544        let (rx, tx) = make_pipe();
1545        let mut src = EventSource::new(rx)
1546            .unwrap()
1547            .with_esc_timeout(Duration::from_millis(20))
1548            .with_paste_idle_timeout(Some(Duration::from_secs(5)));
1549        write_bytes(&tx, b"\x1b[200~body");
1550        let _ = src.poll(Some(Duration::from_millis(50))).unwrap();
1551        while src.try_read().is_some() {}
1552
1553        // Send only the beginning of the terminator: a partial ESC
1554        // sequence at the head of pending. The esc_timeout (20 ms)
1555        // must NOT fire — only the paste timeout (5 s) governs here.
1556        write_bytes(&tx, b"\x1b[20");
1557        let _ = src.poll(Some(Duration::from_millis(80))).unwrap();
1558        let mut saw_esc = false;
1559        while let Some(ev) = src.try_read() {
1560            if matches!(ev, Event::KeyPress(ref k) if k.code == KeyCode::Escape) {
1561                saw_esc = true;
1562            }
1563        }
1564        assert!(!saw_esc, "esc deadline must not fire during paste");
1565
1566        // Complete the terminator: paste ends cleanly.
1567        write_bytes(&tx, b"1~");
1568        assert!(src.poll(Some(Duration::from_secs(1))).unwrap());
1569        let mut saw_end = false;
1570        while let Some(ev) = src.try_read() {
1571            if matches!(ev, Event::PasteEnd { complete: true }) {
1572                saw_end = true;
1573            }
1574        }
1575        assert!(saw_end);
1576    }
1577
1578    #[test]
1579    fn esc_deadline_tightens_long_caller_timeout() {
1580        let (rx, tx) = make_pipe();
1581        let mut src = EventSource::new(rx)
1582            .unwrap()
1583            .with_esc_timeout(Duration::from_millis(20));
1584        write_byte(&tx, 0x1b);
1585        let start = Instant::now();
1586        assert!(src.poll(Some(Duration::from_secs(60))).unwrap());
1587        let ev = src.read().unwrap();
1588        let elapsed = start.elapsed();
1589        assert!(matches!(ev, Event::KeyPress(k) if k.code == KeyCode::Escape));
1590        assert!(
1591            elapsed < Duration::from_millis(500),
1592            "elapsed = {:?}",
1593            elapsed
1594        );
1595    }
1596
1597    #[test]
1598    fn paste_end_after_chunk_is_delivered_without_extra_input() {
1599        // Regression: when a paste body and its closing terminator arrive
1600        // in the same read, the decoder returns the chunk first and queues
1601        // PasteEnd on its internal pending list. The source must drain that
1602        // queued event in the same drain pass — otherwise PasteEnd would
1603        // stall until the next byte showed up.
1604        let (rx, tx) = make_pipe();
1605        let mut src = new_reader(rx);
1606        write_bytes(&tx, b"\x1b[200~hello\x1b[201~");
1607        assert!(src.poll(Some(Duration::from_secs(1))).unwrap());
1608        assert!(matches!(src.read().unwrap(), Event::PasteStart));
1609        assert!(matches!(src.read().unwrap(), Event::PasteChunk(ref b) if b == b"hello"));
1610        assert!(matches!(
1611            src.read().unwrap(),
1612            Event::PasteEnd { complete: true }
1613        ));
1614    }
1615
1616    #[test]
1617    fn handle_resize_false_suppresses_sigwinch_resize_event() {
1618        // With resize handling disabled (the host has enabled in-band
1619        // reports), a SIGWINCH must drain its wake pipe but surface no
1620        // Event::Resize — the decoder delivers resizes in-band instead.
1621        let stderr_fd = 2;
1622        let mut ws: libc::winsize = unsafe { std::mem::zeroed() };
1623        let probe = unsafe { libc::ioctl(stderr_fd, libc::TIOCGWINSZ, &mut ws) };
1624        if probe < 0 {
1625            return;
1626        }
1627        let stderr_dup = unsafe { libc::dup(stderr_fd) };
1628        assert!(stderr_dup >= 0);
1629        let stderr_file = unsafe { File::from_raw_fd(stderr_dup) };
1630        let mut src = new_reader(stderr_file);
1631        assert!(src.handle_resize());
1632        src.set_handle_resize(false);
1633        assert!(!src.handle_resize());
1634        src.last_size = None;
1635        unsafe { libc::raise(libc::SIGWINCH) };
1636        // No event is produced; the poll runs to its (short) timeout.
1637        assert!(!src.poll(Some(Duration::from_millis(50))).unwrap());
1638        assert!(src.try_read().is_none());
1639    }
1640
1641    /// The constructor seeds `last_size`, so a `SIGWINCH` that does not change
1642    /// the size must not surface an event. That is what keeps a stray wake on a
1643    /// recycled pool pipe from being mistaken for a resize.
1644    #[cfg(not(target_os = "l4re"))]
1645    #[test]
1646    fn sigwinch_dedups_unchanged_size() {
1647        let Some((master, _slave)) = crate::testutil::open_pty_pair() else {
1648            return;
1649        };
1650        // Probe independently of the code under test: illumos ptys are STREAMS
1651        // devices and a bare master does not answer TIOCGWINSZ. Skipping on the
1652        // probe rather than on `last_size` keeps the assertion below meaningful
1653        // everywhere the ioctl does work.
1654        let mut ws: libc::winsize = unsafe { std::mem::zeroed() };
1655        if unsafe { libc::ioctl(master.as_raw_fd(), libc::TIOCGWINSZ, &mut ws) } < 0 {
1656            return;
1657        }
1658
1659        let mut src = new_reader(master);
1660        assert!(
1661            src.last_size.is_some(),
1662            "constructor did not seed the resize dedupe from the input fd"
1663        );
1664
1665        unsafe { libc::raise(libc::SIGWINCH) };
1666        assert!(
1667            !src.poll(Some(Duration::from_millis(50))).unwrap(),
1668            "an unchanged size surfaced a resize event"
1669        );
1670        assert!(src.try_read().is_none());
1671    }
1672}