uncurses/event/source.rs
1//! Wakeable event source shared by synchronous and asynchronous readers.
2//!
3//! ## Purpose
4//!
5//! [`EventSource`] owns the input handle, waits for platform readiness, feeds a
6//! [`Decoder`], and queues typed [`Event`] values. It is the entry
7//! point for applications that want blocking, timeout-based, or wakeable event
8//! reads.
9//!
10//! ```text
11//! input fd / HANDLE ─┬─▶ Poller ── ready ──▶ read bytes ──▶ Decoder
12//! wake handle ───────┤ │ │
13//! SIGWINCH pipe ─────┘ └──────────────┴─▶ queue
14//! (Unix only) deadlines: ESC, paste idle, clipboard idle
15//! ```
16//!
17//! ## Key types
18//!
19//! * [`Input`] describes the platform capabilities required from an input
20//! handle.
21//! * [`EventSource`] stores the decoder, bounded pending-byte buffer, readiness
22//! poller, event queue, timeout deadlines, and resize state.
23//! * [`Waker`] is a cloneable handle that interrupts an in-progress wait from
24//! another thread.
25//!
26//! ## Lifecycle
27//!
28//! Construct with [`EventSource::new`]. Call
29//! [`EventSource::poll`] to wait up to a timeout, drain queued events with
30//! [`EventSource::try_read`], or call [`EventSource::read`] to block until one
31//! event arrives. [`EventSource::unread`] can put an unrelated event back while
32//! code waits for a specific terminal reply.
33//!
34//! ## Gotchas
35//!
36//! [`EventSource::try_read`] is purely non-blocking: it only pops the queue.
37//! [`EventSource::poll`] performs I/O and timeout handling. The effective poll
38//! wait is shortened when a partial sequence, string, or paste has an internal
39//! deadline, so a long caller timeout does not delay disambiguation.
40//! Win32 repeats stay compact in the queue. Each read expands one occurrence,
41//! with repeat metadata on additional key-down occurrences in the same record.
42use std::io;
43use std::io::Read;
44use std::sync::Arc;
45use std::time::{Duration, Instant};
46
47#[cfg(unix)]
48use std::os::fd::AsFd;
49#[cfg(windows)]
50use std::os::windows::io::AsHandle;
51
52use super::decode::{Decoder, DecoderFlags, is_c1_introducer};
53use super::pending::Pending;
54#[cfg(any(unix, windows))]
55use super::poll::Poller;
56use super::queue::EventQueue;
57#[cfg(unix)]
58use super::sigwinch as winch;
59#[cfg(unix)]
60use super::source_unix::UnixWakerInner;
61#[cfg(windows)]
62use super::source_windows::WindowsWakerInner;
63use crate::event::{Event, SequenceKind};
64#[cfg(unix)]
65use crate::terminal::Winsize;
66
67/// Platform-specific capabilities required from a Unix event input handle.
68///
69/// The handle must implement [`Read`], expose an fd through [`AsFd`], and be
70/// safe to move to the helper thread used by async streams. Any type satisfying
71/// those bounds implements this trait automatically.
72///
73/// Users normally do not implement this trait manually; pass the input half
74/// returned by the terminal API to [`EventSource::new`].
75#[cfg(unix)]
76pub trait Input: Read + AsFd + Send {}
77#[cfg(unix)]
78impl<T: Read + AsFd + Send> Input for T {}
79
80/// Platform-specific capabilities required from a Windows event input handle.
81///
82/// The handle must implement [`Read`], expose a console `HANDLE` through
83/// [`AsHandle`], and be safe to move to the helper thread used by async streams.
84/// Any type satisfying those bounds implements this trait automatically.
85///
86/// Users normally do not implement this trait manually; pass the input half
87/// returned by the terminal API to [`EventSource::new`].
88#[cfg(windows)]
89pub trait Input: Read + AsHandle + Send {}
90#[cfg(windows)]
91impl<T: Read + AsHandle + Send> Input for T {}
92
93/// Default read buffer capacity. Paste, clipboard, and long string bodies
94/// stream through it; other sequences must fit. The buffer is allocated once
95/// at construction.
96pub(super) const DEFAULT_BUFFER_CAPACITY: usize = 8192;
97
98// The decoder streams a control string before it fills this much space.
99const _: () = assert!(DEFAULT_BUFFER_CAPACITY >= super::decode::STRING_BUFFER_LEN);
100
101/// Readiness slots the platform poller reports, in fixed index order.
102/// Unix watches `[input, wake, winch]`; Windows watches `[input, wake]`
103/// (resize arrives in-band as a console record, so there is no winch fd).
104#[cfg(unix)]
105pub(super) const READY_SLOTS: usize = 3;
106#[cfg(windows)]
107pub(super) const READY_SLOTS: usize = 2;
108/// Index of the input handle in the readiness slice.
109#[cfg(any(unix, windows))]
110pub(super) const READY_INPUT: usize = 0;
111/// Index of the wake handle in the readiness slice.
112#[cfg(any(unix, windows))]
113pub(super) const READY_WAKE: usize = 1;
114/// Index of the SIGWINCH pipe in the readiness slice (Unix only).
115#[cfg(unix)]
116pub(super) const READY_WINCH: usize = 2;
117
118/// Default escape-sequence timeout.
119///
120/// When the pending buffer holds a partial `ESC`-prefixed sequence or 8-bit C1
121/// introducer and no continuation arrives within this window, the source asks
122/// the decoder to resolve the buffered bytes as best-effort events. This is how
123/// a physical Escape key is distinguished from an Alt-prefixed key or CSI-style
124/// control sequence.
125/// Fresh input resets the deadline while a sequence remains incomplete.
126/// Once bytes follow an OSC, DCS, APC, SOS, or PM introducer, the string waits
127/// for its terminator or an interrupting Escape sequence.
128/// Recognized clipboard headers switch to the separate clipboard idle timeout.
129/// An introducer alone still uses the Escape timeout.
130/// A timed-out two-byte introducer such as `ESC ]` resolves to `Alt+]`.
131///
132/// Applications that prefer more responsive Escape handling can lower this
133/// value with [`EventSource::with_esc_timeout`]; applications that need to
134/// tolerate slow byte delivery can raise it.
135pub const DEFAULT_ESC_TIMEOUT: Duration = Duration::from_millis(50);
136
137/// Default bracketed-paste idle timeout.
138///
139/// When a paste has been opened (a `PasteStart` was emitted) and no
140/// further input arrives within this window, the source flushes retained bytes
141/// as a final `PasteChunk`, then emits `PasteEnd { complete: false }`
142/// and clears the decoder's paste state. Guards against terminators
143/// that never arrive (truncated stream, malformed input).
144pub const DEFAULT_PASTE_IDLE_TIMEOUT: Duration = Duration::from_secs(2);
145
146/// Default OSC 52 clipboard idle timeout.
147///
148/// After a recognized header, two seconds without input ends the reply with
149/// `ClipboardEnd { complete: false }`. Retained bytes precede that event.
150pub const DEFAULT_CLIPBOARD_IDLE_TIMEOUT: Duration = Duration::from_secs(2);
151
152/// Default idle timeout for a streamed control string.
153///
154/// After [`Event::StringStart`], two seconds without input ends the string
155/// with `StringEnd { complete: false }`. Retained bytes precede that event.
156pub const DEFAULT_STRING_IDLE_TIMEOUT: Duration = Duration::from_secs(2);
157
158/// Cloneable handle that interrupts an in-progress [`EventSource::poll`] or
159/// [`EventSource::read`].
160///
161/// A waker is bound to one source. A pending wake ends its next wait.
162/// Ready events, including resizes, take priority and leave the wake pending.
163/// Without an event, [`EventSource::read`] returns `Interrupted` and
164/// [`EventSource::poll`] returns `false`. Concurrent wake calls may coalesce.
165///
166/// For cancellation, set a shared flag before waking the source and check
167/// that flag after every read result, including successful events.
168/// The handle is cheap to clone and can be sent to other threads.
169#[derive(Clone)]
170pub struct Waker {
171 #[cfg(unix)]
172 inner: Arc<UnixWakerInner>,
173 #[cfg(windows)]
174 inner: Arc<WindowsWakerInner>,
175 #[cfg(not(any(unix, windows)))]
176 _phantom: std::marker::PhantomData<()>,
177}
178
179impl Waker {
180 pub(super) fn new() -> io::Result<Self> {
181 #[cfg(unix)]
182 return Ok(Self::from_unix_inner(Arc::new(UnixWakerInner::new()?)));
183 #[cfg(windows)]
184 return Ok(Self::from_windows_inner(
185 Arc::new(WindowsWakerInner::new()?),
186 ));
187 }
188
189 pub(super) fn poll_fd(&self) -> super::poll::PollFd {
190 #[cfg(unix)]
191 return self.inner.read_fd();
192 #[cfg(windows)]
193 return self.inner.raw_handle();
194 }
195
196 /// Clear a wake after the poller reports its handle ready.
197 pub(super) fn clear(&self) -> io::Result<()> {
198 self.inner.clear()
199 }
200
201 #[cfg(unix)]
202 pub(super) fn from_unix_inner(inner: Arc<UnixWakerInner>) -> Self {
203 Self { inner }
204 }
205
206 #[cfg(windows)]
207 pub(super) fn from_windows_inner(inner: Arc<WindowsWakerInner>) -> Self {
208 Self { inner }
209 }
210
211 /// Interrupt the [`EventSource`] this waker is bound to.
212 ///
213 /// Ready events take priority and leave the wake pending. Without an
214 /// event, [`EventSource::poll`] returns `Ok(false)` and [`EventSource::read`]
215 /// returns [`io::ErrorKind::Interrupted`]. Input errors still surface.
216 /// A wake before a wait remains pending until the source services it.
217 ///
218 /// The wake does not enqueue an [`Event`] or discard partial input.
219 /// `EventStream` retries after a wake; its next item is an event
220 /// or an error. Use a separate async signal for application cancellation.
221 ///
222 /// Returns any platform error produced while signalling the wake handle.
223 pub fn wake(&self) -> io::Result<()> {
224 #[cfg(any(unix, windows))]
225 {
226 self.inner.wake()
227 }
228 #[cfg(not(any(unix, windows)))]
229 {
230 Err(io::Error::new(
231 io::ErrorKind::Unsupported,
232 "waker not supported on this platform",
233 ))
234 }
235 }
236}
237
238/// Wakeable event source backed by a platform readiness primitive.
239///
240/// `EventSource` is the synchronous owner of terminal input. It stores pending
241/// bytes, a `Decoder`, an event queue, deadline state for ambiguous `ESC`
242/// prefixes, bracketed pastes, and clipboard replies, and the platform handles for
243/// wakeups and resize notifications.
244///
245/// Construct it with [`EventSource::new`]. Use [`EventSource::poll`] to perform
246/// I/O and wait for queued events, [`EventSource::try_read`] to pop an already
247/// queued event, or [`EventSource::read`] to block until one event is available.
248/// The type is generic over the platform [`Input`] handle.
249pub struct EventSource<I>
250where
251 I: Input,
252{
253 /// Owned input handle. Used both as the byte source (`Read`) and, on
254 /// Unix, as the readiness target (its fd is registered with the
255 /// [`super::poll::Poller`]).
256 #[cfg_attr(windows, allow(dead_code))]
257 pub(super) input: I,
258
259 pub(super) parser: Decoder,
260 /// Bounded read buffer. The unread slice is `pending.slice()`; new
261 /// input is written into `pending.spare_mut()`. `pending.capacity()`
262 /// bounds retained input and is never resized.
263 pub(super) pending: Pending,
264 pub(super) esc_timeout: Duration,
265 /// Wall-clock instant at which a buffered partial escape sequence
266 /// should be force-resolved (typically as a bare `Esc` keypress).
267 pub(super) esc_deadline: Option<Instant>,
268 /// Idle timeout applied while the decoder is in a bracketed paste.
269 /// `None` disables the safety net.
270 pub(super) paste_idle_timeout: Option<Duration>,
271 /// Wall-clock instant at which an open paste should be
272 /// force-closed (synthesised `PasteEnd`).
273 pub(super) paste_deadline: Option<Instant>,
274 pub(super) clipboard_idle_timeout: Option<Duration>,
275 pub(super) clipboard_deadline: Option<Instant>,
276 pub(super) string_idle_timeout: Option<Duration>,
277 pub(super) string_deadline: Option<Instant>,
278 #[cfg(feature = "async")]
279 pub(super) deadline_wakers: Vec<std::sync::Weak<super::stream::DeadlineWake>>,
280 pub(super) queue: EventQueue,
281 pub(super) pending_error: Option<io::Error>,
282 pub(super) waker: Waker,
283 /// Whether the source delivers [`Event::Resize`] from the
284 /// out-of-band kernel resize notification (`SIGWINCH` on Unix).
285 /// Defaults to `true`. Set to `false` when in-band resize reports
286 /// (DEC mode 2048) are enabled so resizes arrive solely through the
287 /// decoder and are not duplicated. No effect on Windows, where resize
288 /// is always delivered in-band through the decoder.
289 pub(super) handle_resize: bool,
290
291 // --- Unix-only state ---
292 /// Shared readiness poller watching `[input, wake_rx, winch_rx]` (in
293 /// that index order). Held behind `Arc` so an [`super::EventStream`]
294 /// reader thread can wait on it lock-free while the source's decode
295 /// state is mutated under a separate lock.
296 #[cfg(unix)]
297 pub(super) poller: Arc<dyn Poller>,
298 /// Active SIGWINCH subscription, and owner of the pipe the handler wakes.
299 /// The pipe is leased from a process-lifetime pool rather than owned here,
300 /// so no descriptor the handler may be about to write to can be closed —
301 /// see the `PIPES` pool in the sigwinch module.
302 #[cfg(unix)]
303 pub(super) winch_sub: winch::Subscription,
304 #[cfg(unix)]
305 pub(super) last_size: Option<Winsize>,
306
307 // --- Windows-only state ---
308 #[cfg(windows)]
309 pub(super) vt_input: bool,
310 /// Shared readiness poller watching `[input_handle, wake_event]` (in
311 /// that index order). Held behind `Arc` so an [`super::EventStream`]
312 /// reader thread can wait on it lock-free while the source's decode
313 /// state is mutated under a separate lock.
314 #[cfg(windows)]
315 pub(super) poller: Arc<dyn Poller>,
316 /// Pending high surrogate per key direction (0 = up, 1 = down).
317 /// VT input delivers astral code points as two consecutive
318 /// `KEY_EVENT` records, one per UTF-16 unit.
319 #[cfg(windows)]
320 pub(super) pending_high_surrogate: [Option<u16>; 2],
321 #[cfg(windows)]
322 pub(super) last_size: Option<(i16, i16)>,
323 #[cfg(windows)]
324 pub(super) last_mouse_buttons: u32,
325}
326
327// Drop ordering note for Unix: the winch pipe is leased from a
328// process-lifetime pool and is never closed, so dropping the subscription
329// only frees the slot. Field drop order is therefore not load-bearing here.
330
331// ---------------------------------------------------------------------------
332// Shared methods (platform-agnostic)
333// ---------------------------------------------------------------------------
334
335impl<I> EventSource<I>
336where
337 I: Input,
338{
339 /// Return whether VT input serialization is enabled.
340 ///
341 /// Unix input is always VT bytes, so this returns `true` on Unix.
342 pub fn vt_input(&self) -> bool {
343 #[cfg(windows)]
344 return self.vt_input;
345 #[cfg(not(windows))]
346 true
347 }
348
349 /// Select how console key records are serialized.
350 ///
351 /// On Windows, set `enabled` to match the console's
352 /// `ENABLE_VIRTUAL_TERMINAL_INPUT` bit. With `false`, native console keys
353 /// go through the win32-input decoder. With `true`, character records
354 /// supply VT input. [`EventSource::new`] reads the initial value from the
355 /// console mode, and [`has_vt_input`](crate::terminal::has_vt_input)
356 /// reads it from a saved [`State`](crate::terminal::State).
357 ///
358 /// Update this setting after a successful console mode change and before
359 /// the next read. This method changes only serialization, not console modes
360 /// or decoder flags. A change discards incomplete UTF-16 pairs.
361 ///
362 /// Unix input is always VT bytes, so this method has no effect on Unix.
363 /// Portable code can call it on every platform.
364 pub fn set_vt_input(&mut self, enabled: bool) {
365 #[cfg(windows)]
366 {
367 if self.vt_input != enabled {
368 self.pending_high_surrogate = [None, None];
369 }
370 self.vt_input = enabled;
371 }
372 #[cfg(not(windows))]
373 let _ = enabled;
374 }
375
376 /// Return the configured escape-sequence timeout.
377 ///
378 /// This is the duration used to disambiguate a physical Escape key from an
379 /// Alt-prefixed key or a partial control sequence. Reading it has no side
380 /// effects and never performs I/O.
381 pub fn esc_timeout(&self) -> Duration {
382 self.esc_timeout
383 }
384
385 /// Set the escape-sequence timeout.
386 ///
387 /// `timeout` is how long the source waits for a continuation byte before a
388 /// buffered partial escape sequence is force-resolved. The default is
389 /// [`DEFAULT_ESC_TIMEOUT`]. Fresh input resets the deadline for incomplete
390 /// sequences. Ready continuation bytes take priority over their expiry.
391 /// A lone Escape expires before the next read once its deadline passes.
392 ///
393 /// A zero duration resolves a lone Escape on the next poll cycle and other
394 /// ambiguous prefixes when a poll finds no continuation input.
395 /// String bodies wait for their terminators regardless of this timeout.
396 ///
397 /// This is a consuming builder intended to be chained after
398 /// [`EventSource::new`]. It does not inspect or clear any already-buffered
399 /// input and never panics.
400 pub fn with_esc_timeout(mut self, timeout: Duration) -> Self {
401 self.esc_timeout = timeout;
402 self
403 }
404
405 /// Choose how the ambiguous legacy keys are read.
406 ///
407 /// LF reads as Ctrl+J by default. Set [`DecoderFlags::LF_IS_ENTER`] to
408 /// read it as Enter instead. See [`DecoderFlags`] for all mappings.
409 ///
410 /// This is a consuming builder intended to be chained after
411 /// [`EventSource::new`]. It never panics.
412 pub fn with_decoder_flags(mut self, flags: DecoderFlags) -> Self {
413 self.set_decoder_flags(flags);
414 self
415 }
416
417 /// Choose how the ambiguous legacy keys are read, on a source already in
418 /// use.
419 ///
420 /// The same choice [`with_decoder_flags`](Self::with_decoder_flags)
421 /// makes, for a caller holding the source rather than building it.
422 /// Buffered input is left alone: the flags decide how a byte is named,
423 /// not how it is framed.
424 pub fn set_decoder_flags(&mut self, flags: DecoderFlags) {
425 self.parser.set_flags(flags);
426 }
427
428 /// How the ambiguous legacy keys are being read.
429 pub fn decoder_flags(&self) -> DecoderFlags {
430 self.parser.flags()
431 }
432
433 /// Return the decoder's current Backarrow mode (DECBKM).
434 ///
435 /// Defaults to reset (`false`).
436 pub fn backspace_mode(&self) -> bool {
437 self.parser.backspace_mode()
438 }
439
440 /// Select Backarrow mode for future legacy input without terminal I/O.
441 ///
442 /// Set (`true`) selects BS (`0x08`) for Backspace; reset (`false`) selects
443 /// DEL (`0x7f`). [`DecoderFlags`] choose the ambiguous interpretations.
444 /// Mode reports are returned to the caller for handling. Already queued
445 /// events keep their decoded values.
446 ///
447 /// Use [`Program::set_backspace_mode`](crate::program::Program::set_backspace_mode)
448 /// to change both the terminal and decoder.
449 pub fn set_backspace_mode(&mut self, enabled: bool) {
450 self.parser.set_backspace_mode(enabled);
451 }
452
453 /// Set the idle timeout for an open bracketed paste.
454 ///
455 /// If no further input arrives before `timeout`, the source flushes any
456 /// held bytes as a final [`Event::PasteChunk`], synthesizes
457 /// [`Event::PasteEnd`] with `complete: false`, and leaves paste mode.
458 /// Passing `None` disables this safety net and waits for a real terminator.
459 /// The default is
460 /// `Some(`[`DEFAULT_PASTE_IDLE_TIMEOUT`]`)`.
461 ///
462 /// Changing this setting during a paste restarts its idle wait.
463 pub fn with_paste_idle_timeout(mut self, timeout: Option<Duration>) -> Self {
464 self.set_paste_idle_timeout(timeout);
465 self
466 }
467
468 /// Set the paste idle timeout on an existing source.
469 ///
470 /// This applies the same policy as
471 /// [`with_paste_idle_timeout`](Self::with_paste_idle_timeout).
472 /// Changing it during a paste restarts the idle wait; `None` disables it.
473 /// Live async streams refresh their readiness waits when the deadline changes.
474 pub fn set_paste_idle_timeout(&mut self, timeout: Option<Duration>) {
475 #[cfg(feature = "async")]
476 let previous = self.paste_deadline;
477 self.paste_idle_timeout = timeout;
478 self.paste_deadline = if self.parser.in_paste() {
479 timeout.map(|t| Instant::now() + t)
480 } else {
481 None
482 };
483 #[cfg(feature = "async")]
484 if self.paste_deadline != previous {
485 self.wake_deadline_waiters();
486 }
487 }
488
489 /// Set the idle timeout for an OSC 52 clipboard reply.
490 ///
491 /// After its header, new input restarts the idle wait. Expiry flushes
492 /// retained bytes as a final [`Event::ClipboardChunk`], then emits
493 /// [`Event::ClipboardEnd`] with `complete: false` and leaves clipboard mode.
494 /// The default is `Some(`[`DEFAULT_CLIPBOARD_IDLE_TIMEOUT`]`)`.
495 /// `None` disables idle recovery.
496 ///
497 /// This is a recovery heuristic: keys before expiry can become payload,
498 /// and delayed payload after expiry can become keys.
499 pub fn with_clipboard_idle_timeout(mut self, timeout: Option<Duration>) -> Self {
500 self.set_clipboard_idle_timeout(timeout);
501 self
502 }
503
504 /// Change the clipboard idle timeout, restarting the wait in an active reply.
505 ///
506 /// `None` disables idle recovery. Live async streams refresh their waits
507 /// when the deadline changes. See [`Self::with_clipboard_idle_timeout`].
508 pub fn set_clipboard_idle_timeout(&mut self, timeout: Option<Duration>) {
509 #[cfg(feature = "async")]
510 let previous = self.clipboard_deadline;
511 self.clipboard_idle_timeout = timeout;
512 self.clipboard_deadline = if self.parser.in_clipboard() {
513 timeout.map(|t| Instant::now() + t)
514 } else {
515 None
516 };
517 #[cfg(feature = "async")]
518 if self.clipboard_deadline != previous {
519 self.wake_deadline_waiters();
520 }
521 }
522
523 /// Set the idle timeout for a streamed control string.
524 ///
525 /// After [`Event::StringStart`], new input restarts the idle wait. Expiry
526 /// flushes retained bytes as a final [`Event::StringChunk`], then emits
527 /// [`Event::StringEnd`] with `complete: false` and decodes later input
528 /// normally. The default is `Some(`[`DEFAULT_STRING_IDLE_TIMEOUT`]`)`.
529 /// `None` disables idle recovery.
530 ///
531 /// This is a recovery heuristic: keys before expiry can become string
532 /// bytes, and delayed string bytes after expiry can become keys.
533 pub fn with_string_idle_timeout(mut self, timeout: Option<Duration>) -> Self {
534 self.set_string_idle_timeout(timeout);
535 self
536 }
537
538 /// Change the string idle timeout, restarting the wait in an active string.
539 ///
540 /// `None` disables idle recovery. Live async streams refresh their waits
541 /// when the deadline changes. See [`Self::with_string_idle_timeout`].
542 pub fn set_string_idle_timeout(&mut self, timeout: Option<Duration>) {
543 #[cfg(feature = "async")]
544 let previous = self.string_deadline;
545 self.string_idle_timeout = timeout;
546 self.string_deadline = if self.parser.in_string() {
547 timeout.map(|t| Instant::now() + t)
548 } else {
549 None
550 };
551 #[cfg(feature = "async")]
552 if self.string_deadline != previous {
553 self.wake_deadline_waiters();
554 }
555 }
556
557 #[cfg(feature = "async")]
558 fn wake_deadline_waiters(&mut self) {
559 self.deadline_wakers.retain(|weak| {
560 if let Some(waker) = weak.upgrade() {
561 waker.notify();
562 true
563 } else {
564 false
565 }
566 });
567 }
568
569 /// Return a cloneable [`Waker`] bound to this source.
570 ///
571 /// Use the returned handle from another thread to interrupt a blocking
572 /// [`EventSource::poll`] or [`EventSource::read`]. Cloning the waker does
573 /// not clone the source or its input handle.
574 pub fn waker(&self) -> Waker {
575 self.waker.clone()
576 }
577
578 /// Return whether out-of-band resize handling is enabled.
579 ///
580 /// On Unix, `true` means a readable SIGWINCH pipe can produce
581 /// [`Event::Resize`]. On Windows, resize records are delivered in-band and
582 /// this flag has no practical effect.
583 pub fn handle_resize(&self) -> bool {
584 self.handle_resize
585 }
586
587 /// Control whether the source delivers [`Event::Resize`] from the
588 /// kernel's out-of-band window-resize notification (`SIGWINCH` on
589 /// Unix). Defaults to `true`.
590 ///
591 /// Set this to `false` after enabling in-band resize reports (DEC
592 /// mode 2048): the terminal then reports size changes in-band as
593 /// `CSI 48 t`, which the decoder surfaces as [`Event::Resize`], so
594 /// leaving the `SIGWINCH` path on would deliver each resize twice.
595 /// Restore it to `true` when in-band reporting is disabled again.
596 ///
597 /// No effect on Windows, where resize is always delivered in-band
598 /// through the decoder.
599 pub fn set_handle_resize(&mut self, enable: bool) {
600 self.handle_resize = enable;
601 }
602
603 /// Wait up to `timeout` for at least one event to become available.
604 ///
605 /// This method performs I/O, drains decoder output into the internal queue,
606 /// handles resize notifications, and resolves any expired ESC or paste
607 /// deadlines. `None` means block until an event or wake; `Some(Duration::ZERO)`
608 /// means perform a non-blocking readiness pass.
609 /// A caller timeout preserves an incomplete control string for the next poll.
610 ///
611 /// A platform whose wait takes a whole number of milliseconds rounds a
612 /// fractional millisecond up, so such a wait can return up to a
613 /// millisecond after the deadline.
614 ///
615 /// Returns:
616 ///
617 /// * `Ok(true)` when the queue has at least one event;
618 /// * `Ok(false)` when the timeout elapsed or a paired [`Waker`] interrupted
619 /// the wait without producing an event;
620 /// * `Err(_)` for fatal input or platform readiness errors.
621 ///
622 /// Ready and already queued events take priority and leave the wake pending.
623 /// A later poll with no event clears the wake and returns `Ok(false)`.
624 pub fn poll(&mut self, timeout: Option<Duration>) -> io::Result<bool> {
625 if !self.queue.is_empty() {
626 return Ok(true);
627 }
628 let deadline = timeout.map(|t| Instant::now() + t);
629 loop {
630 let remaining = deadline.map(|d| d.saturating_duration_since(Instant::now()));
631 match self.fill(remaining) {
632 Ok(()) => {
633 if !self.queue.is_empty() {
634 return Ok(true);
635 }
636 if let Some(left) = remaining
637 && left.is_zero()
638 {
639 return Ok(false);
640 }
641 }
642 Err(e) if e.kind() == io::ErrorKind::Interrupted => return Ok(false),
643 Err(e) => return Err(e),
644 }
645 }
646 }
647
648 /// Return the next queued event without performing I/O.
649 ///
650 /// This takes one event from the internal queue, expanding one occurrence
651 /// of a repeat run. Call [`EventSource::poll`] first when
652 /// the queue may be empty but input could be ready. Returns `None` when no
653 /// event is currently queued.
654 pub fn try_read(&mut self) -> Option<Event> {
655 self.queue.pop_front()
656 }
657
658 /// One read-decode cycle: resolve overdue lone Escape or transfer deadlines,
659 /// wait up to `timeout` for readiness, then service it. Winch surfaces a
660 /// [`Event::Resize`]; a [`Waker`] surfaces `Err(Interrupted)` if no event
661 /// or input error is available; ready input is drained and decoded; a wait
662 /// that returns with no input ready resolves the decode deadline it was
663 /// tightened to. Fills [`Self::queue`].
664 pub(super) fn fill(&mut self, timeout: Option<Duration>) -> io::Result<()> {
665 // A late key must not join an expired lone Escape. Partial sequences
666 // get a readiness check first, since continuation bytes may be queued.
667 // Idle transfers end before new input can join their payload.
668 if self.pending.slice() == b"\x1b"
669 || self.parser.in_paste()
670 || self.parser.in_clipboard()
671 || self.parser.in_string()
672 {
673 self.expire_elapsed();
674 }
675 if !self.queue.is_empty() {
676 return Ok(());
677 }
678 if let Some(error) = self.pending_error.take() {
679 return Err(error);
680 }
681
682 let effective = self.effective_timeout(timeout);
683 let mut ready = [false; READY_SLOTS];
684 self.poller.poll(&mut ready, effective)?;
685
686 #[cfg(unix)]
687 if ready[READY_WINCH] {
688 self.handle_winch()?;
689 }
690
691 if ready[READY_INPUT]
692 && (self.parser.in_paste() || self.parser.in_clipboard() || self.parser.in_string())
693 {
694 self.expire_elapsed();
695 }
696 if ready[READY_INPUT]
697 && let Err(error) = self.drain_input()
698 {
699 // A failed read supplies no continuation bytes.
700 self.expire_elapsed();
701 self.expire_paste();
702 self.expire_clipboard();
703 self.expire_string();
704 self.pending_error = Some(error);
705 }
706 if !ready[READY_INPUT] {
707 // The wait was tightened to a decode deadline that has elapsed.
708 self.expire_elapsed();
709 }
710 if !self.queue.is_empty() {
711 return Ok(());
712 }
713 if let Some(error) = self.pending_error.take() {
714 return Err(error);
715 }
716 if ready[READY_WAKE] {
717 self.waker.clear()?;
718 // A shared reader can leave a new deadline behind after draining readiness.
719 #[cfg(feature = "async")]
720 self.wake_deadline_waiters();
721 return Err(io::Error::new(io::ErrorKind::Interrupted, "wake"));
722 }
723 Ok(())
724 }
725
726 /// Block until the next event is available, then return it.
727 ///
728 /// This calls [`EventSource::poll`] with no caller timeout, then returns
729 /// the next event. Ready events leave a pending wake for a later read.
730 ///
731 /// Returns [`io::ErrorKind::Interrupted`] if a paired [`Waker`] fired while
732 /// waiting, and propagates fatal input/readiness errors.
733 pub fn read(&mut self) -> io::Result<Event> {
734 if !self.poll(None)? {
735 return Err(io::Error::new(io::ErrorKind::Interrupted, "wake"));
736 }
737 Ok(self
738 .queue
739 .pop_front()
740 .expect("poll reported a queued event"))
741 }
742
743 /// Return an event to the front of the queue, so the next
744 /// [`read`](Self::read) / [`try_read`](Self::try_read) yields it before
745 /// anything already queued. Use to put back an event read while waiting
746 /// for a specific reply (e.g. a cursor-position report), preserving it
747 /// for normal delivery. Restore a batch in original order by unreading
748 /// in reverse.
749 pub fn unread(&mut self, event: Event) {
750 self.queue.push_front(event);
751 #[cfg(feature = "async")]
752 self.wake_deadline_waiters();
753 }
754
755 /// Push a freshly produced event onto the queue.
756 pub(super) fn emit(&mut self, ev: Event) {
757 self.queue.push_back(ev);
758 }
759
760 /// Feed serialized console bytes in bounded batches.
761 #[cfg(any(windows, test))]
762 pub(super) fn feed_bytes(&mut self, mut bytes: &[u8]) {
763 #[cfg(debug_assertions)]
764 crate::trace::tee_input(bytes);
765 while !bytes.is_empty() {
766 if self.pending.is_full() {
767 self.pending.clear();
768 self.esc_deadline = None;
769 }
770 let count = self.pending.append(bytes);
771 bytes = &bytes[count..];
772 self.drain_parser();
773 }
774 }
775
776 /// Drive the parser as far as it will go against the bytes
777 /// currently in `pending`, pushing extracted events onto the
778 /// queue and arming the appropriate timeout deadline.
779 ///
780 /// Fresh input refreshes the active transfer or Escape deadline.
781 /// Other control strings wait for a terminator or an interrupting Escape.
782 pub(super) fn drain_parser(&mut self) {
783 loop {
784 let (n, run) = self.parser.parse_one_run(self.pending.slice());
785 if n == 0 && run.is_none() {
786 break;
787 }
788 if n > 0 {
789 self.pending.consume(n);
790 }
791 if let Some(run) = run {
792 self.queue.push_run(run);
793 }
794 }
795
796 self.clipboard_deadline = if self.parser.in_clipboard() {
797 self.clipboard_idle_timeout.map(|t| Instant::now() + t)
798 } else {
799 None
800 };
801 self.string_deadline = if self.parser.in_string() {
802 self.string_idle_timeout.map(|t| Instant::now() + t)
803 } else {
804 None
805 };
806 if self.parser.in_paste() {
807 // In paste: only the paste-idle timer applies. Reset on
808 // every drain (input has just arrived).
809 self.esc_deadline = None;
810 self.paste_deadline = self.paste_idle_timeout.map(|t| Instant::now() + t);
811 return;
812 }
813
814 // Not in paste: clear paste deadline; arm esc deadline if a
815 // partial sequence sits at the head.
816 self.paste_deadline = None;
817 if self.parser.waiting_for_terminator() {
818 self.esc_deadline = None;
819 return;
820 }
821 let Some(b0) = self.pending.first() else {
822 self.esc_deadline = None;
823 return;
824 };
825 let armable = b0 == 0x1b || is_c1_introducer(b0);
826 if armable {
827 self.esc_deadline = Some(Instant::now() + self.esc_timeout);
828 } else {
829 self.esc_deadline = None;
830 }
831 }
832
833 /// Force-resolve a buffered partial sequence whose ESC deadline
834 /// elapsed.
835 pub(super) fn expire_partial(&mut self) {
836 self.esc_deadline = None;
837 if self.pending.first().is_none() {
838 return;
839 }
840 // Flip the decoder into expired mode so its recursive ESC
841 // handler can commit buffered partial sequences (e.g. resolving
842 // `\x1b\x1b` to `Alt+Esc`). Anything the decoder still can't
843 // consume falls back to the single-byte fallback below.
844 self.parser.set_expired(true);
845 self.drain_parser();
846 while !self.parser.waiting_for_terminator() {
847 let Some(b0) = self.pending.first() else {
848 break;
849 };
850 let ev = self
851 .parser
852 .expire_leading(b0)
853 .unwrap_or_else(|| Event::Unknown {
854 kind: SequenceKind::Raw,
855 bytes: vec![b0],
856 });
857 self.pending.consume(1);
858 self.emit(ev);
859 self.drain_parser();
860 }
861 self.parser.set_expired(false);
862 }
863
864 /// Force-close a stuck bracketed paste. Flushes any leftover
865 /// pending bytes as a final `PasteChunk`, then enqueues
866 /// `PasteEnd { complete: false }` and clears the decoder's paste state.
867 ///
868 /// Called from `pump` when the paste-idle deadline elapses, and
869 /// from the public [`EventSource::end_paste`] escape hatch.
870 pub(super) fn expire_paste(&mut self) {
871 self.paste_deadline = None;
872 if !self.parser.in_paste() {
873 return;
874 }
875 if !self.pending.is_empty() {
876 let bytes = self.pending.slice().to_vec();
877 self.pending.clear();
878 self.emit(Event::PasteChunk(bytes));
879 }
880 if let Some(ev) = self.parser.end_paste() {
881 self.emit(ev);
882 }
883 }
884
885 /// Force-exit bracketed paste mode.
886 ///
887 /// If the decoder is currently inside a paste, this flushes any pending
888 /// bytes as a [`Event::PasteChunk`], queues [`Event::PasteEnd`] with
889 /// `complete: false`, and clears paste state so later bytes parse as input.
890 /// Use it when an
891 /// embedding application enforces a paste size cap, user cancellation, or a
892 /// custom watchdog. It has no effect outside paste mode and never panics.
893 /// An active async stream wakes to deliver the queued events.
894 pub fn end_paste(&mut self) {
895 if self.parser.in_paste() {
896 self.expire_paste();
897 #[cfg(feature = "async")]
898 self.wake_deadline_waiters();
899 }
900 }
901
902 fn expire_clipboard(&mut self) {
903 self.clipboard_deadline = None;
904 if let Some(end) = self.parser.end_clipboard() {
905 if !self.pending.is_empty() {
906 let bytes = self.pending.slice().to_vec();
907 self.pending.clear();
908 self.emit(Event::ClipboardChunk(bytes));
909 }
910 self.emit(end);
911 }
912 }
913
914 fn expire_string(&mut self) {
915 self.string_deadline = None;
916 if let Some(end) = self.parser.end_string() {
917 if !self.pending.is_empty() {
918 let bytes = self.pending.slice().to_vec();
919 self.pending.clear();
920 self.emit(Event::StringChunk(bytes));
921 }
922 self.emit(end);
923 }
924 }
925
926 /// Force-exit an OSC 52 reply.
927 ///
928 /// Flushes retained bytes as a final [`Event::ClipboardChunk`], then queues
929 /// [`Event::ClipboardEnd`] with `complete: false`. Later input is decoded
930 /// normally. Use this for a size cap, cancellation, or custom recovery.
931 /// This has no effect outside a reply. An active async stream wakes to
932 /// deliver the queued events.
933 pub fn end_clipboard(&mut self) {
934 if self.parser.in_clipboard() {
935 self.expire_clipboard();
936 #[cfg(feature = "async")]
937 self.wake_deadline_waiters();
938 }
939 }
940
941 /// Force-exit a streamed control string.
942 ///
943 /// Flushes retained bytes as a final [`Event::StringChunk`], then queues
944 /// [`Event::StringEnd`] with `complete: false`. Later input is decoded
945 /// normally. Use this for a size cap, cancellation, or custom recovery.
946 /// This has no effect outside a streamed string. An active async stream
947 /// wakes to deliver the queued events.
948 pub fn end_string(&mut self) {
949 if self.parser.in_string() {
950 self.expire_string();
951 #[cfg(feature = "async")]
952 self.wake_deadline_waiters();
953 }
954 }
955
956 /// Resolve any decode deadline that has already elapsed.
957 /// A buffered partial `ESC` past its window becomes a
958 /// bare `Esc`; idle transfers past their windows are force-closed.
959 /// Run before input for a lone Escape or transfer, and after a wait that
960 /// returned no input for other partial sequences.
961 /// A no-op when no deadline is overdue;
962 /// transfer and Escape deadlines govern separate decoder states.
963 pub(super) fn expire_elapsed(&mut self) {
964 let now = Instant::now();
965 if self.parser.in_paste() {
966 if self.paste_deadline.is_some_and(|d| d <= now) {
967 self.expire_paste();
968 }
969 } else if self.parser.in_clipboard() {
970 if self.clipboard_deadline.is_some_and(|d| d <= now) {
971 self.expire_clipboard();
972 }
973 } else if self.parser.in_string() {
974 if self.string_deadline.is_some_and(|d| d <= now) {
975 self.expire_string();
976 }
977 } else if self.esc_deadline.is_some_and(|d| d <= now) {
978 self.expire_partial();
979 }
980 }
981
982 /// Effective wait for the next readiness poll: the caller's `timeout`
983 /// tightened to the nearest decode deadline (Escape, paste, clipboard, or string)
984 /// so a buffered partial sequence resolves promptly even when the caller
985 /// asked to block longer.
986 pub(super) fn effective_timeout(&self, timeout: Option<Duration>) -> Option<Duration> {
987 let now = Instant::now();
988 let deadline = [
989 self.esc_deadline,
990 self.paste_deadline,
991 self.clipboard_deadline,
992 self.string_deadline,
993 ]
994 .into_iter()
995 .flatten()
996 .min();
997 let internal = deadline.map(|d| d.saturating_duration_since(now));
998 match (timeout, internal) {
999 (Some(t), Some(i)) => Some(t.min(i)),
1000 (None, i) => i,
1001 (t, None) => t,
1002 }
1003 }
1004}
1005
1006#[cfg(all(test, unix))]
1007mod win32_repeat_tests {
1008 use super::*;
1009 use crate::event::{KeyCode, KeyModifiers};
1010 use std::io::Write;
1011 use std::net::Shutdown;
1012 use std::os::unix::net::UnixStream;
1013
1014 #[test]
1015 fn maximum_win32_runs_stay_compact_and_preserve_delivery() {
1016 let (reader, mut writer) = UnixStream::pair().unwrap();
1017 writer
1018 .write_all(b"\x1b[65;30;97;1;0;65535_\x1b[66;48;98;1;0;65535_z")
1019 .unwrap();
1020 writer.shutdown(Shutdown::Write).unwrap();
1021 let mut source = EventSource::new(reader).unwrap();
1022 assert!(source.poll(Some(Duration::ZERO)).unwrap());
1023 assert_eq!(source.queue.len(), 3);
1024
1025 for code in [KeyCode::Char('a'), KeyCode::Char('b')] {
1026 for index in 0..65535 {
1027 let Event::KeyPress(key) = source.read().unwrap() else {
1028 panic!("expected a Win32 key press");
1029 };
1030 assert_eq!(key.code, code);
1031 assert_eq!(key.modifiers, KeyModifiers::empty());
1032 assert_eq!(key.repeat, index != 0);
1033 if index == 1 {
1034 source.unread(Event::KeyPress(key));
1035 assert!(matches!(source.try_read(),
1036 Some(Event::KeyPress(key)) if key.code == code && key.repeat));
1037 }
1038 }
1039 }
1040 assert!(matches!(source.read().unwrap(),
1041 Event::KeyPress(key) if key.code == KeyCode::Char('z') && !key.repeat));
1042 assert_eq!(
1043 source.read().unwrap_err().kind(),
1044 io::ErrorKind::UnexpectedEof
1045 );
1046 }
1047}
1048
1049#[cfg(all(test, unix))]
1050mod drag_drop_tests {
1051 use super::*;
1052 use std::io::Write;
1053
1054 #[test]
1055 fn drag_drop_maximum_payload_fits_the_source_buffer() {
1056 let (reader, mut writer) = io::pipe().unwrap();
1057 let mut source = EventSource::new(reader).unwrap();
1058 let payload = vec![b'A'; 4096];
1059 let body = [b"72;t=r:x=1;".as_slice(), &payload].concat();
1060 let writer = std::thread::spawn(move || -> io::Result<()> {
1061 writer.write_all(b"\x1b]")?;
1062 writer.write_all(&body)?;
1063 writer.write_all(b"\x1b\\")
1064 });
1065 let event = source.read();
1066 writer.join().unwrap().unwrap();
1067 assert_eq!(
1068 event.unwrap(),
1069 Event::DragDrop {
1070 options: vec![("t".into(), "r".into()), ("x".into(), "1".into())],
1071 payload,
1072 }
1073 );
1074 }
1075
1076 #[test]
1077 fn long_unknown_strings_stream_without_becoming_keys() {
1078 let (reader, mut writer) = io::pipe().unwrap();
1079 let mut source = EventSource::new(reader).unwrap();
1080 let body = [b"1337;File=".as_slice(), &[b'a'; 10 * 1024]].concat();
1081 let wire = [b"\x1b]".as_slice(), &body, b"\x1b\\x"].concat();
1082 let writer = std::thread::spawn(move || writer.write_all(&wire));
1083 assert_eq!(
1084 source.read().unwrap(),
1085 Event::StringStart {
1086 kind: SequenceKind::Osc
1087 }
1088 );
1089 let mut received = Vec::new();
1090 loop {
1091 match source.read().unwrap() {
1092 Event::StringChunk(bytes) => received.extend(bytes),
1093 Event::StringEnd { complete: true } => break,
1094 event => panic!("unexpected string event: {event:?}"),
1095 }
1096 }
1097 writer.join().unwrap().unwrap();
1098 assert_eq!(received, body);
1099 assert!(matches!(source.read().unwrap(), Event::KeyPress(key)
1100 if key.code == crate::event::KeyCode::Char('x')));
1101 }
1102
1103 #[test]
1104 fn drag_drop_batches_and_split_terminators_preserve_events() {
1105 let (reader, _writer) = io::pipe().unwrap();
1106 let mut source = EventSource::new(reader).unwrap();
1107 let payload = vec![b'A'; 4096];
1108 let frame = [b"\x1b]72;t=r:x=1;".as_slice(), &payload, b"\x1b\\"].concat();
1109 source.feed_bytes(&frame[..frame.len() - 1]);
1110 assert!(source.queue.is_empty());
1111 source.feed_bytes(&[b"\\".as_slice(), &frame, &frame, b"\x1b]72;t=q\x1b\\z"].concat());
1112 for _ in 0..3 {
1113 assert_eq!(
1114 source.queue.pop_front(),
1115 Some(Event::DragDrop {
1116 options: vec![("t".into(), "r".into()), ("x".into(), "1".into())],
1117 payload: payload.clone(),
1118 })
1119 );
1120 }
1121 assert!(matches!(
1122 source.queue.pop_front(),
1123 Some(Event::DragDrop { .. })
1124 ));
1125 assert!(matches!(source.queue.pop_front(), Some(Event::KeyPress(_))));
1126 assert!(source.queue.is_empty());
1127 }
1128}