Skip to main content

uncurses/event/
mod.rs

1//! Terminal events and event-stream decoding.
2//!
3//! This module owns the core [`Event`] enum together with the
4//! internal decoder that parses raw terminal bytes into events, the
5//! platform-specific [`EventSource`] that drives the decoder from a
6//! tty, and the key/mouse types that events carry.
7//!
8//! ## The decode pipeline
9//!
10//! Input arrives as a raw byte stream. The source reads bytes (waking on a
11//! self-pipe so another thread can interrupt a blocking read), feeds them to
12//! the decoder, and hands back fully-formed [`Event`] values. Escape
13//! sequences may straddle reads, so the decoder buffers partial input and a
14//! short timeout disambiguates a lone `Esc` key from the start of a CSI/SS3
15//! sequence.
16//!
17//! ```text
18//!   tty input        EventSource              Decoder            caller
19//!   ─────────        ───────────              ───────            ──────
20//!   bytes  ───────▶  read + buffer  ───────▶  scan sequences ─▶  Event
21//!     │                   ▲                        │
22//!     │                   └── Esc-timeout ◀────────┘ (Esc key vs CSI/SS3?)
23//!     └── self-pipe wake ─┘  (interrupt a blocking read from another thread)
24//! ```
25//!
26//! Build an [`EventSource`] over a terminal's input half and read typed
27//! events in a loop. Keys parse from strings and compare by canonical
28//! chord, so matching a shortcut is plain equality.
29//!
30//! ```no_run
31//! use uncurses::event::{Event, EventSource, Key};
32//! use uncurses::terminal::Terminal;
33//!
34//! # fn main() -> std::io::Result<()> {
35//! let mut term = Terminal::stdio();
36//! term.make_raw()?;
37//! let mut events = EventSource::new(term.input())?;
38//! #[cfg(windows)]
39//! events.set_vt_input(true);
40//!
41//! let quit: Key = "ctrl+c".parse().unwrap();
42//! loop {
43//!     match events.read()? {
44//!         Event::KeyPress(ref k) if *k == quit => break,
45//!         Event::KeyPress(k) => { let _ = k.code; }
46//!         Event::Resize(ws) => { let _ = (ws.col, ws.row); }
47//!         _ => {}
48//!     }
49//! }
50//! term.restore()
51//! # }
52//! ```
53//!
54//! ## Queries
55//!
56//! To ask the terminal a question (its background color, cell size,
57//! device attributes, and so on), write the request bytes from the
58//! [`ansi`](crate::ansi) module to the output and read the matching reply
59//! event back through the same source. The
60//! [`Screen`](crate::screen::Screen) facade wraps this in `request_*` methods
61//! whose replies surface as ordinary events, never swallowing the user's
62//! keystrokes in between.
63//!
64//! ## Async
65//!
66//! With the `async` feature, `EventStream` reads the same events through a
67//! [`futures_core::Stream`], so the loop becomes `while let Some(ev) =
68//! stream.next().await`.
69//!
70//! [`futures_core::Stream`]: https://docs.rs/futures-core/latest/futures_core/stream/trait.Stream.html
71
72pub(crate) mod decode;
73#[cfg(test)]
74mod decode_safety_tests;
75mod key;
76mod mouse;
77mod pending;
78pub(crate) mod poll;
79mod sigwinch;
80mod source;
81#[cfg(unix)]
82mod source_unix;
83#[cfg(windows)]
84mod source_windows;
85#[cfg(feature = "async")]
86mod stream;
87
88pub use decode::DecoderFlags;
89pub use key::{Key, KeyCode, KeyModifiers, ParseKeyError};
90pub use mouse::{Mouse, MouseButton, mouse_pixel_to_cell};
91pub use source::{
92    DEFAULT_CLIPBOARD_IDLE_TIMEOUT, DEFAULT_ESC_TIMEOUT, DEFAULT_PASTE_IDLE_TIMEOUT, EventSource,
93    Input, Waker,
94};
95#[cfg(feature = "async")]
96pub use stream::EventStream;
97
98use crate::ansi::mode::{Mode, ModeSetting};
99use crate::color::Color;
100use crate::terminal::Winsize;
101
102/// Which system clipboard selection an OSC 52 event refers to.
103#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
104pub enum ClipboardSelection {
105    /// `c` — system clipboard.
106    System,
107    /// `p` — primary (X11 PRIMARY) selection.
108    Primary,
109    /// Any other / unknown selection character.
110    Other(char),
111}
112
113/// Decoded modifyOtherKeys mode (`CSI > 4 ; n m`).
114#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
115pub enum ModifyOtherKeysMode {
116    /// Disabled.
117    Disabled,
118    /// Mode 1 — only modify keys that don't otherwise have an xterm sequence.
119    Mode1,
120    /// Mode 2 — modify all keys.
121    Mode2,
122}
123
124impl ModifyOtherKeysMode {
125    /// Convert a report value into a modifyOtherKeys mode.
126    pub fn from_value(v: u8) -> Self {
127        match v {
128            1 => Self::Mode1,
129            2 => Self::Mode2,
130            _ => Self::Disabled,
131        }
132    }
133}
134
135/// Reported terminal color scheme (DEC mode 2031).
136#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
137pub enum ColorScheme {
138    /// Dark mode (`CSI ? 997 ; 1 n`).
139    Dark,
140    /// Light mode (`CSI ? 997 ; 2 n`).
141    Light,
142}
143
144impl std::fmt::Display for ColorScheme {
145    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
146        f.write_str(match self {
147            ColorScheme::Dark => "dark",
148            ColorScheme::Light => "light",
149        })
150    }
151}
152
153/// Reported terminal visibility (DEC mode 2033).
154///
155/// This is an advisory, deliberately conservative hint used to skip expensive
156/// rendering that nobody can see. [`Hidden`](Visibility::Hidden) is precise:
157/// the terminal has positive knowledge that the view is not observable.
158/// [`Visible`](Visibility::Visible) only means it *may* be observable.
159///
160/// Only `1` and `2` decode to a report; any other value is left as
161/// [`Event::UnknownCsi`]. Treat a terminal that reports nothing, or reports
162/// something unrecognized, as visible.
163#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
164pub enum Visibility {
165    /// Potentially visible (`CSI ? 999 ; 1 n`). The view may be observable.
166    ///
167    /// This does not promise that any cell is onscreen: the terminal reports
168    /// it whenever visibility is unknown or any view may be observed.
169    Visible,
170    /// Not visible (`CSI ? 999 ; 2 n`). The terminal knows the view is not
171    /// ordinarily observable, so expensive visual updates can be paused.
172    ///
173    /// Never assume this lasts for any minimum duration.
174    Hidden,
175}
176
177impl Visibility {
178    /// Whether the terminal view may be observable, so visual work is worth
179    /// doing. `true` for [`Visible`](Visibility::Visible).
180    pub fn is_visible(self) -> bool {
181        matches!(self, Visibility::Visible)
182    }
183}
184
185impl std::fmt::Display for Visibility {
186    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
187        f.write_str(match self {
188            Visibility::Visible => "visible",
189            Visibility::Hidden => "hidden",
190        })
191    }
192}
193
194/// Accepted program status names from an OSC 7501 query reply.
195///
196/// The decoder supplies fixed defaults for absent fields and preserves
197/// explicit empty lists and names from protocol extensions.
198#[derive(Debug, Clone, PartialEq, Eq)]
199pub struct ProgramStatusCapabilities {
200    /// Accepted state names. An absent field means `idle`, `working`,
201    /// `done`, `blocked`, and `error`. The list excludes `clear`.
202    pub states: Vec<String>,
203    /// Accepted kind names. An absent field means `permission`,
204    /// `question`, and `auth`.
205    pub kinds: Vec<String>,
206}
207
208/// A terminal event.
209#[derive(Debug, Clone, PartialEq, Eq)]
210pub enum Event {
211    // -- Input ---------------------------------------------------------------
212    /// Key was pressed.
213    KeyPress(Key),
214    /// Key auto-repeated (Kitty Keyboard Protocol).
215    KeyRepeat(Key),
216    /// Key was released (Kitty Keyboard Protocol).
217    KeyRelease(Key),
218    /// Mouse button was pressed.
219    MouseClick(Mouse),
220    /// Mouse button was released.
221    MouseRelease(Mouse),
222    /// Mouse wheel scrolled.
223    MouseWheel(Mouse),
224    /// Mouse moved (with or without a button held).
225    MouseMove(Mouse),
226
227    // -- Size / geometry -----------------------------------------------------
228    /// The terminal surface changed size. Emitted only for genuine
229    /// change notifications: kernel SIGWINCH (full `Winsize`),
230    /// `ReadConsoleInput` window-buffer-size events on Windows
231    /// (cells only), and in-band CSI 48 t reports under mode 2048
232    /// (full `Winsize`). Replies to explicit size queries are
233    /// delivered as `WindowCellSize` / `WindowPixelSize` /
234    /// `CellPixelSize` instead.
235    Resize(Winsize),
236    /// Reply to a `CSI 18 t` query — window size in cells.
237    WindowCellSize {
238        /// Width in terminal cells.
239        width: u16,
240        /// Height in terminal cells.
241        height: u16,
242    },
243    /// Reply to a `CSI 14 t` query — window size in pixels.
244    WindowPixelSize {
245        /// Width in pixels.
246        width: u16,
247        /// Height in pixels.
248        height: u16,
249    },
250    /// Reply to a `CSI 16 t` query — single-cell size in pixels.
251    CellPixelSize {
252        /// Cell width in pixels.
253        width: u16,
254        /// Cell height in pixels.
255        height: u16,
256    },
257
258    // -- Focus / paste -------------------------------------------------------
259    /// Focus gained.
260    FocusIn,
261    /// Focus lost.
262    FocusOut,
263    /// Bracketed paste started.
264    PasteStart,
265    /// Bracketed paste ended.
266    ///
267    /// Idle recovery, explicit recovery, and input read failures produce an
268    /// incomplete end after any retained payload bytes.
269    PasteEnd {
270        /// Whether the terminal sent the paste terminator.
271        complete: bool,
272    },
273    /// Streaming chunk of pasted bytes emitted between [`Event::PasteStart`]
274    /// and [`Event::PasteEnd`]. Pastes that exceed the source's read
275    /// buffer are split across multiple chunks; reassembly and any
276    /// text decoding are the caller's responsibility (terminals may
277    /// paste arbitrary binary content, not just valid UTF-8).
278    PasteChunk(Vec<u8>),
279
280    // -- Position / device attrs --------------------------------------------
281    /// Cursor position report (CPR or DECXCPR). Coordinates are zero-based (the
282    /// 1-based wire form is normalized when parsed).
283    ///
284    /// DECXCPR replies use `CSI ? row ; column R` or
285    /// `CSI ? row ; column ; page R`. The decoder retains the page number
286    /// and ignores additional parameters after it. These private replies
287    /// always produce a single cursor event, even at positions that make
288    /// standard CPR ambiguous with modified F3.
289    CursorPosition {
290        /// Zero-based cell coordinates.
291        position: crate::layout::Position,
292        /// One-based page number, or zero when absent.
293        page: u32,
294    },
295    /// Primary device attributes (DA1) — list of decoded numeric attributes.
296    PrimaryDeviceAttributes(Vec<Option<u32>>),
297    /// Secondary device attributes (DA2).
298    SecondaryDeviceAttributes(Vec<Option<u32>>),
299    /// Tertiary device attributes (DA3) — terminal ID string.
300    TertiaryDeviceAttributes(String),
301    /// Terminal name reply (XTVERSION). Carries the raw identifier string,
302    /// which typically combines a name and version (e.g. `"XTerm(380)"`).
303    TerminalName(String),
304
305    // -- Mode / capability reports ------------------------------------------
306    /// DECRPM / RM mode report.
307    ///
308    /// The `setting` distinguishes all five DECRPM states. A terminal can
309    /// report a mode as permanently set or permanently reset, meaning it
310    /// recognizes the mode but will not let the host toggle it. When deciding
311    /// whether a feature is usable, prefer
312    /// [`ModeSetting::is_available`](crate::ansi::mode::ModeSetting::is_available)
313    /// over [`is_recognized`](crate::ansi::mode::ModeSetting::is_recognized): a
314    /// permanently reset mode is recognized yet can never be enabled.
315    ModeReport {
316        /// Reported mode.
317        mode: Mode,
318        /// Current mode setting.
319        setting: ModeSetting,
320    },
321    /// modifyOtherKeys report.
322    ModifyOtherKeys(ModifyOtherKeysMode),
323    /// Kitty keyboard protocol active-enhancements report
324    /// (`CSI ? <flags> u`). The payload is the parsed
325    /// [`crate::ansi::kitty::KittyKeyboardFlags`] bitset.
326    KittyKeyboardEnhancements(crate::ansi::kitty::KittyKeyboardFlags),
327    /// XTWINOPS reply (window operation).
328    WindowOp {
329        /// Window operation number.
330        op: u32,
331        /// Window operation arguments.
332        args: Vec<Option<u32>>,
333    },
334    /// XTGETTCAP / termcap capability reply. `recognized` is `true` for a
335    /// successful reply (`DCS 1 + r`) and `false` for a failure
336    /// (`DCS 0 + r`); the entries are decoded the same way in both cases (a
337    /// failure echoes the requested, now known-unsupported, capability
338    /// names).
339    Termcap {
340        /// Whether the requested capabilities were recognized.
341        recognized: bool,
342        /// Decoded `(name, value)` pairs. The value is `None` when the entry
343        /// carried no `=`: either a boolean capability, reported as a bare
344        /// name, or a failure reply echoing a name it does not support.
345        /// `recognized` is what tells those apart.
346        ///
347        /// Kept as pairs because only the hex wire form is delimiter-safe:
348        /// decoded values commonly contain `;` and `=` (`kf13` is
349        /// `\E[1;2P`), so a joined string could not be split back apart.
350        entries: Vec<(String, Option<String>)>,
351    },
352    /// DECRPSS setting report (`DCS 1 $ r` on success, `DCS 0 $ r` on
353    /// failure), reporting a current setting such as the active SGR
354    /// attributes or cursor style. Sent in answer to
355    /// [`write_decrqss`](crate::ansi::status::write_decrqss).
356    SettingReport(SettingReport),
357
358    // -- Colors --------------------------------------------------------------
359    /// OSC 10 default foreground color reply.
360    ForegroundColor(Color),
361    /// OSC 11 default background color reply.
362    BackgroundColor(Color),
363    /// OSC 12 cursor color reply.
364    CursorColor(Color),
365    /// OSC 4 indexed palette color reply (`OSC 4 ; index ; color`).
366    PaletteColor {
367        /// Palette color index.
368        index: u8,
369        /// Reported palette color.
370        color: Color,
371    },
372    /// Color-scheme report (DEC mode 2031): whether the terminal is in its
373    /// dark or light scheme. Indicates only the dark/light preference, not
374    /// the actual colors.
375    ColorScheme(ColorScheme),
376
377    /// Terminal visibility report (DEC mode 2033): whether the terminal view
378    /// may be observed. Arrives unsolicited while
379    /// [`Program::enable_visibility_reports`] is active, and as the reply to
380    /// [`Program::request_visibility`].
381    ///
382    /// This is independent of focus: focus says which view receives keyboard
383    /// input, visibility says whether output can be seen.
384    ///
385    /// [`Program::enable_visibility_reports`]: crate::program::Program::enable_visibility_reports
386    /// [`Program::request_visibility`]: crate::program::Program::request_visibility
387    Visibility(Visibility),
388
389    /// Supported program status states and kinds (OSC 7501).
390    ///
391    /// Sent in reply to [`Program::request_program_status`]. Absent lists
392    /// use the protocol's fixed defaults. Names from future revisions are
393    /// preserved; unknown pairs are ignored.
394    ///
395    /// [`Program::request_program_status`]: crate::program::Program::request_program_status
396    ProgramStatus(ProgramStatusCapabilities),
397
398    // -- Clipboard / graphics ------------------------------------------------
399    /// Start of an OSC 52 clipboard reply, after its header.
400    ///
401    /// Every recognized reply starts with this event, including empty replies.
402    /// Zero or more chunks follow with the wire payload, normally base64.
403    ClipboardStart {
404        /// Clipboard selection that was reported.
405        selection: ClipboardSelection,
406    },
407    /// Raw OSC 52 payload bytes, excluding the header and terminator.
408    ///
409    /// Chunk boundaries follow input availability, not base64 groups or text
410    /// boundaries. Callers can consume chunks incrementally or assemble them.
411    ClipboardChunk(Vec<u8>),
412    /// End of an OSC 52 clipboard reply.
413    ///
414    /// Caller timeouts and wakes preserve an active reply, subject to the
415    /// source's independent clipboard idle timeout. Idle or explicit recovery
416    /// flushes retained bytes and ends the reply with `complete: false`.
417    /// An interrupting escape sequence ends it before that sequence is decoded.
418    /// An input read failure flushes retained bytes and ends it before the error.
419    /// Readiness errors propagate directly and can leave a reply unfinished.
420    ClipboardEnd {
421        /// Whether BEL or ST terminated the reply normally.
422        complete: bool,
423    },
424    /// Kitty graphics response (APC `G ...` payload).
425    KittyGraphics {
426        /// Response options.
427        options: Vec<(String, String)>,
428        /// Response payload bytes.
429        payload: Vec<u8>,
430    },
431    /// One Kitty OSC 72 drag and drop message.
432    ///
433    /// Metadata and payload are wire values. Callers retain the first chunk's
434    /// metadata, decode base64 when applicable, and manage transfer lifetime.
435    /// An empty final data response ends a transfer; `m=0` alone ends a message.
436    DragDrop {
437        /// Colon-separated metadata pairs, including extension and routing keys.
438        options: Vec<(String, String)>,
439        /// Unchanged payload bytes, including base64 for binary data.
440        payload: Vec<u8>,
441    },
442
443    // -- Group / unknown -----------------------------------------------------
444    /// Multiple events emitted by a single sequence.
445    Multi(Vec<Event>),
446    /// Unknown CSI sequence (parameters + intermediates + final byte).
447    UnknownCsi(Vec<u8>),
448    /// Unknown SS3 sequence.
449    UnknownSs3(Vec<u8>),
450    /// Unknown OSC sequence (payload bytes, no ESC/ST framing).
451    UnknownOsc(Vec<u8>),
452    /// Unknown DCS sequence (payload).
453    UnknownDcs(Vec<u8>),
454    /// Unknown SOS sequence (payload).
455    UnknownSos(Vec<u8>),
456    /// Unknown PM sequence (payload).
457    UnknownPm(Vec<u8>),
458    /// Unknown APC sequence (payload).
459    UnknownApc(Vec<u8>),
460    /// Catch-all for unrecognized byte sequences, including incomplete control
461    /// strings interrupted by another Escape sequence. These incomplete strings
462    /// include their introducer bytes.
463    Unknown(Vec<u8>),
464}
465
466/// The payload of a DECRPSS reply, [`Event::SettingReport`].
467#[derive(Debug, Clone, PartialEq, Eq)]
468#[non_exhaustive]
469pub enum SettingReport {
470    /// The terminal did not recognize the requested setting (`DCS 0 $ r ST`).
471    /// The reply carries no data at all, so only the request that provoked it
472    /// says which setting was turned down.
473    Unrecognized,
474    /// The cursor style the terminal is using, from a DECRPSS reply
475    /// reporting its `DECSCUSR` setting. Ask for it with
476    /// [`Program::request_cursor_style`](crate::program::Program::request_cursor_style).
477    CursorStyle(crate::ansi::cursor::CursorStyle),
478    /// The setting as the terminal spelled it, for a control function this
479    /// library does not decode: the whole CSI sequence without its
480    /// introducer, so `0;1m` for SGR or `>4;2m` for xterm's `XTQMODKEYS`.
481    Raw(String),
482}
483
484impl Event {
485    /// Borrow the [`Key`] payload if this is any key event
486    /// ([`Event::KeyPress`], [`Event::KeyRepeat`], or
487    /// [`Event::KeyRelease`]).
488    pub fn as_key(&self) -> Option<&Key> {
489        match self {
490            Event::KeyPress(k) | Event::KeyRepeat(k) | Event::KeyRelease(k) => Some(k),
491            _ => None,
492        }
493    }
494
495    /// Borrow the [`Mouse`] payload if this is any mouse event
496    /// ([`Event::MouseClick`], [`Event::MouseRelease`],
497    /// [`Event::MouseWheel`], or [`Event::MouseMove`]).
498    pub fn as_mouse(&self) -> Option<&Mouse> {
499        match self {
500            Event::MouseClick(m)
501            | Event::MouseRelease(m)
502            | Event::MouseWheel(m)
503            | Event::MouseMove(m) => Some(m),
504            _ => None,
505        }
506    }
507}
508
509#[cfg(test)]
510mod tests {
511    use super::*;
512
513    #[test]
514    fn color_scheme_display() {
515        assert_eq!(ColorScheme::Dark.to_string(), "dark");
516        assert_eq!(ColorScheme::Light.to_string(), "light");
517    }
518
519    #[test]
520    fn visibility_display_and_predicate() {
521        assert_eq!(Visibility::Visible.to_string(), "visible");
522        assert_eq!(Visibility::Hidden.to_string(), "hidden");
523        assert!(Visibility::Visible.is_visible());
524        assert!(!Visibility::Hidden.is_visible());
525    }
526}