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//!
39//! let quit: Key = "ctrl+c".parse().unwrap();
40//! loop {
41//! match events.read()? {
42//! Event::KeyPress(ref k) if *k == quit => break,
43//! Event::KeyPress(k) => { let _ = k.code; }
44//! Event::Resize(ws) => { let _ = (ws.col, ws.row); }
45//! _ => {}
46//! }
47//! }
48//! term.restore()
49//! # }
50//! ```
51//!
52//! ## Queries
53//!
54//! To ask the terminal a question (its background color, cell size,
55//! device attributes, and so on), write the request bytes from the
56//! [`ansi`](crate::ansi) module to the output and read the matching reply
57//! event back through the same source. The
58//! [`Screen`](crate::screen::Screen) facade wraps this in `request_*` methods
59//! whose replies surface as ordinary events, never swallowing the user's
60//! keystrokes in between.
61//!
62//! ## Async
63//!
64//! With the `async` feature, `EventStream` reads the same events through a
65//! [`futures_core::Stream`], so the loop becomes `while let Some(ev) =
66//! stream.next().await`.
67//!
68//! [`futures_core::Stream`]: https://docs.rs/futures-core/latest/futures_core/stream/trait.Stream.html
69
70pub(crate) mod decode;
71#[cfg(test)]
72mod decode_safety_tests;
73mod key;
74mod mouse;
75mod pending;
76pub(crate) mod poll;
77mod queue;
78mod sigwinch;
79mod source;
80#[cfg(unix)]
81mod source_unix;
82#[cfg(windows)]
83mod source_windows;
84#[cfg(feature = "async")]
85mod stream;
86
87pub use decode::DecoderFlags;
88pub use key::{Key, KeyCode, KeyLocation, KeyModifiers, ParseKeyError};
89pub use mouse::{Mouse, MouseButton, mouse_pixel_to_cell};
90pub use source::{
91 DEFAULT_CLIPBOARD_IDLE_TIMEOUT, DEFAULT_ESC_TIMEOUT, DEFAULT_PASTE_IDLE_TIMEOUT,
92 DEFAULT_STRING_IDLE_TIMEOUT, EventSource, Input, Waker,
93};
94#[cfg(feature = "async")]
95pub use stream::EventStream;
96
97use crate::ansi::mode::{Mode, ModeSetting};
98use crate::color::Color;
99use crate::layout::Size;
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 an
161/// [`Event::Unknown`] CSI sequence. 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/// Payload formats and capabilities from a Glyph Protocol support reply.
209///
210/// Names from future protocol revisions are preserved. Compare against the
211/// names you use and ignore the others.
212#[derive(Debug, Clone, Default, PartialEq, Eq)]
213pub struct GlyphSupport {
214 /// Accepted payload formats, such as `vg`, `glyf`, `colrv0`, and
215 /// `colrv1`. An empty list means every registration is rejected.
216 pub formats: Vec<String>,
217 /// Optional capabilities, such as `grapheme` for cluster queries.
218 pub capabilities: Vec<String>,
219}
220
221/// The subject of a Glyph Protocol coverage query.
222///
223/// Use [`to_string()`](std::string::ToString::to_string) to get the query text.
224#[derive(Debug, Clone, PartialEq, Eq)]
225pub enum GlyphQueryTarget {
226 /// One codepoint (`cp=`).
227 Codepoint(char),
228 /// One grapheme cluster, as its scalar values in order (`grapheme=`).
229 Grapheme(Vec<char>),
230}
231
232impl std::fmt::Display for GlyphQueryTarget {
233 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
234 match self {
235 Self::Codepoint(codepoint) => write!(f, "{codepoint}"),
236 Self::Grapheme(cluster) => {
237 for codepoint in cluster {
238 write!(f, "{codepoint}")?;
239 }
240 Ok(())
241 }
242 }
243 }
244}
245
246/// A Glyph Protocol reply (APC `25a1;` payload).
247///
248/// A `status` of `0` reports success. A nonzero `status` comes with a
249/// `reason`, such as `out_of_namespace` or `unsupported_format`.
250#[derive(Debug, Clone, PartialEq, Eq)]
251pub enum GlyphReply {
252 /// Reply to [`REQUEST_GLYPH_SUPPORT`](crate::ansi::glyph::REQUEST_GLYPH_SUPPORT).
253 Support(GlyphSupport),
254 /// Reply to a coverage query.
255 Query {
256 /// The echoed subject, when the terminal parsed one.
257 target: Option<GlyphQueryTarget>,
258 /// The sources that draw the subject, such as `system` and
259 /// `glossary`. An empty list means the subject renders as a missing
260 /// glyph. `None` means the terminal could not answer; see `reason`.
261 coverage: Option<Vec<String>>,
262 /// Why the terminal could not answer, such as `unknown`.
263 reason: Option<String>,
264 },
265 /// Reply to a registration.
266 Register {
267 /// The echoed codepoint.
268 codepoint: char,
269 /// `0` on success.
270 status: u8,
271 /// The failure reason.
272 reason: Option<String>,
273 },
274 /// Reply to a clear request.
275 Clear {
276 /// The echoed codepoint. `None` answers a request to clear every slot.
277 codepoint: Option<char>,
278 /// `0` on success.
279 status: u8,
280 /// The failure reason.
281 reason: Option<String>,
282 },
283}
284
285/// A terminal event.
286///
287/// Key events compare their [`Key`] identities. Inspect [`Key::repeat`]
288/// separately when repeat status matters.
289#[derive(Debug, Clone, PartialEq, Eq)]
290pub enum Event {
291 // -- Input ---------------------------------------------------------------
292 /// Key was pressed or repeated. Inspect [`Key::repeat`] for repeat status.
293 KeyPress(Key),
294 /// Key was released. Decoder-generated releases have [`Key::repeat`] set to `false`.
295 KeyRelease(Key),
296 /// Mouse button was pressed.
297 MouseClick(Mouse),
298 /// Mouse button was released.
299 MouseRelease(Mouse),
300 /// Mouse wheel scrolled.
301 MouseWheel(Mouse),
302 /// Mouse moved (with or without a button held).
303 MouseMove(Mouse),
304
305 // -- Size / geometry -----------------------------------------------------
306 /// The terminal surface changed size. Emitted only for genuine
307 /// change notifications: kernel SIGWINCH (full `Winsize`),
308 /// `ReadConsoleInput` window-buffer-size events on Windows
309 /// (cells only), and in-band CSI 48 t reports under mode 2048
310 /// (full `Winsize`). Replies to explicit size queries are
311 /// delivered as `WindowCellSize` / `WindowPixelSize` /
312 /// `CellPixelSize` instead.
313 Resize(Winsize),
314 /// Reply to a `CSI 18 t` query: window size in columns by rows.
315 WindowCellSize(Size),
316 /// Reply to a `CSI 14 t` query: text-area pixel dimensions (width by height).
317 WindowPixelSize(Size),
318 /// Reply to a `CSI 16 t` query: one cell's pixel width by pixel height.
319 CellPixelSize(Size),
320
321 // -- Focus / paste -------------------------------------------------------
322 /// Focus gained.
323 FocusIn,
324 /// Focus lost.
325 FocusOut,
326 /// Bracketed paste started.
327 PasteStart,
328 /// Bracketed paste ended.
329 ///
330 /// Idle recovery, explicit recovery, and input read failures produce an
331 /// incomplete end after any retained payload bytes.
332 PasteEnd {
333 /// Whether the terminal sent the paste terminator.
334 complete: bool,
335 },
336 /// Streaming chunk of pasted bytes emitted between [`Event::PasteStart`]
337 /// and [`Event::PasteEnd`]. Pastes that exceed the source's read
338 /// buffer are split across multiple chunks; reassembly and any
339 /// text decoding are the caller's responsibility (terminals may
340 /// paste arbitrary binary content, not just valid UTF-8).
341 PasteChunk(Vec<u8>),
342
343 // -- Position / device attrs --------------------------------------------
344 /// Cursor position report (CPR or DECXCPR). Coordinates are zero-based (the
345 /// 1-based wire form is normalized when parsed).
346 ///
347 /// A standard report on row 1, column 1 to 16, has the same bytes as
348 /// legacy modified F3 (`CSI 1 ; m R`). For that report, the decoder emits
349 /// a [`KeyPress`](Event::KeyPress) for F3 first and this event second.
350 /// The code that owns the cursor request drops that key.
351 ///
352 /// DECXCPR replies use `CSI ? row ; column R` or
353 /// `CSI ? row ; column ; page R`. The decoder retains the page number
354 /// and ignores additional parameters after it. These private replies
355 /// always produce a single cursor event.
356 CursorPosition {
357 /// Zero-based cell coordinates.
358 position: crate::layout::Position,
359 /// One-based page number, or zero when absent.
360 page: u32,
361 },
362 /// Primary device attributes (DA1) — list of decoded numeric attributes.
363 PrimaryDeviceAttributes(Vec<Option<u32>>),
364 /// Secondary device attributes (DA2).
365 SecondaryDeviceAttributes(Vec<Option<u32>>),
366 /// Tertiary device attributes (DA3) — terminal ID string.
367 TertiaryDeviceAttributes(String),
368 /// Terminal name reply (XTVERSION). Carries the raw identifier string,
369 /// which typically combines a name and version (e.g. `"XTerm(380)"`).
370 TerminalName(String),
371
372 // -- Mode / capability reports ------------------------------------------
373 /// DECRPM / RM mode report.
374 ///
375 /// The `setting` distinguishes all five DECRPM states. A terminal can
376 /// report a mode as permanently set or permanently reset, meaning it
377 /// recognizes the mode but will not let the host toggle it. When deciding
378 /// whether a feature is usable, prefer
379 /// [`ModeSetting::is_available`](crate::ansi::mode::ModeSetting::is_available)
380 /// over [`is_recognized`](crate::ansi::mode::ModeSetting::is_recognized): a
381 /// permanently reset mode is recognized yet can never be enabled.
382 ModeReport {
383 /// Reported mode.
384 mode: Mode,
385 /// Current mode setting.
386 setting: ModeSetting,
387 },
388 /// modifyOtherKeys report.
389 ModifyOtherKeys(ModifyOtherKeysMode),
390 /// Kitty keyboard protocol active-enhancements report
391 /// (`CSI ? <flags> u`). The payload is the parsed
392 /// [`crate::ansi::kitty::KittyKeyboardFlags`] bitset.
393 KittyKeyboardEnhancements(crate::ansi::kitty::KittyKeyboardFlags),
394 /// XTWINOPS reply (window operation).
395 WindowOp {
396 /// Window operation number.
397 op: u32,
398 /// Window operation arguments.
399 args: Vec<Option<u32>>,
400 },
401 /// XTGETTCAP / termcap capability reply. `recognized` is `true` for a
402 /// successful reply (`DCS 1 + r`) and `false` for a failure
403 /// (`DCS 0 + r`); the entries are decoded the same way in both cases (a
404 /// failure echoes the requested, now known-unsupported, capability
405 /// names).
406 Termcap {
407 /// Whether the requested capabilities were recognized.
408 recognized: bool,
409 /// Decoded `(name, value)` pairs. The value is `None` when the entry
410 /// carried no `=`: either a boolean capability, reported as a bare
411 /// name, or a failure reply echoing a name it does not support.
412 /// `recognized` is what tells those apart.
413 ///
414 /// Kept as pairs because only the hex wire form is delimiter-safe:
415 /// decoded values commonly contain `;` and `=` (`kf13` is
416 /// `\E[1;2P`), so a joined string could not be split back apart.
417 entries: Vec<(String, Option<String>)>,
418 },
419 /// DECRPSS setting report (`DCS 1 $ r` on success, `DCS 0 $ r` on
420 /// failure), reporting a current setting such as the active SGR
421 /// attributes or cursor style. Sent in answer to
422 /// [`write_decrqss`](crate::ansi::status::write_decrqss).
423 SettingReport(SettingReport),
424
425 // -- Colors --------------------------------------------------------------
426 /// OSC 10 default foreground color reply.
427 ForegroundColor(Color),
428 /// OSC 11 default background color reply.
429 BackgroundColor(Color),
430 /// OSC 12 cursor color reply.
431 CursorColor(Color),
432 /// OSC 4 indexed palette color reply (`OSC 4 ; index ; color`).
433 PaletteColor {
434 /// Palette color index.
435 index: u8,
436 /// Reported palette color.
437 color: Color,
438 },
439 /// Color-scheme report (DEC mode 2031): whether the terminal is in its
440 /// dark or light scheme. Indicates only the dark/light preference, not
441 /// the actual colors.
442 ColorScheme(ColorScheme),
443
444 /// Terminal visibility report (DEC mode 2033): whether the terminal view
445 /// may be observed. Arrives unsolicited while
446 /// [`Program::enable_visibility_reports`] is active, and as the reply to
447 /// [`Program::request_visibility`].
448 ///
449 /// This is independent of focus: focus says which view receives keyboard
450 /// input, visibility says whether output can be seen.
451 ///
452 /// [`Program::enable_visibility_reports`]: crate::program::Program::enable_visibility_reports
453 /// [`Program::request_visibility`]: crate::program::Program::request_visibility
454 Visibility(Visibility),
455
456 /// Supported program status states and kinds (OSC 7501).
457 ///
458 /// Sent in reply to [`Program::request_program_status`]. Absent lists
459 /// use the protocol's fixed defaults. Names from future revisions are
460 /// preserved; unknown pairs are ignored.
461 ///
462 /// [`Program::request_program_status`]: crate::program::Program::request_program_status
463 ProgramStatus(ProgramStatusCapabilities),
464
465 // -- Clipboard / graphics ------------------------------------------------
466 /// Start of an OSC 52 clipboard reply, after its header.
467 ///
468 /// Every recognized reply starts with this event, including empty replies.
469 /// Zero or more chunks follow with the wire payload, normally base64.
470 ClipboardStart {
471 /// Clipboard selection that was reported.
472 selection: ClipboardSelection,
473 },
474 /// Raw OSC 52 payload bytes, excluding the header and terminator.
475 ///
476 /// Chunk boundaries follow input availability, not base64 groups or text
477 /// boundaries. Callers can consume chunks incrementally or assemble them.
478 ClipboardChunk(Vec<u8>),
479 /// End of an OSC 52 clipboard reply.
480 ///
481 /// Caller timeouts and wakes preserve an active reply, subject to the
482 /// source's independent clipboard idle timeout. Idle or explicit recovery
483 /// flushes retained bytes and ends the reply with `complete: false`.
484 /// An interrupting escape sequence ends it before that sequence is decoded.
485 /// An input read failure flushes retained bytes and ends it before the error.
486 /// Readiness errors propagate directly and can leave a reply unfinished.
487 ClipboardEnd {
488 /// Whether BEL or ST terminated the reply normally.
489 complete: bool,
490 },
491 /// Kitty graphics response (APC `G ...` payload).
492 KittyGraphics {
493 /// Response options.
494 options: Vec<(String, String)>,
495 /// Response payload bytes.
496 payload: Vec<u8>,
497 },
498 /// Glyph Protocol reply (APC `25a1;` payload).
499 ///
500 /// See [`crate::ansi::glyph`] for the requests.
501 Glyph(GlyphReply),
502 /// One Kitty OSC 72 drag and drop message.
503 ///
504 /// Metadata and payload are wire values. Callers retain the first chunk's
505 /// metadata, decode base64 when applicable, and manage transfer lifetime.
506 /// An empty final data response ends a transfer; `m=0` alone ends a message.
507 DragDrop {
508 /// Colon-separated metadata pairs, including extension and routing keys.
509 options: Vec<(String, String)>,
510 /// Unchanged payload bytes, including base64 for binary data.
511 payload: Vec<u8>,
512 },
513
514 // -- Unknown input -------------------------------------------------------
515 /// A sequence that the decoder frames but does not recognize.
516 ///
517 /// For [`SequenceKind::Csi`] and [`SequenceKind::Ss3`], `bytes` holds the
518 /// parameters, intermediates, and final byte. For the string kinds,
519 /// `bytes` holds the string body. The introducer and the terminator are
520 /// not included, in either the 7-bit or the 8-bit form.
521 ///
522 /// A string body of more than 4096 bytes arrives as
523 /// [`StringStart`](Event::StringStart), [`StringChunk`](Event::StringChunk),
524 /// and [`StringEnd`](Event::StringEnd) events instead.
525 ///
526 /// [`SequenceKind::Raw`] holds the exact input bytes, including any
527 /// introducer. The decoder uses it for a stray byte, and for a CSI
528 /// sequence or a short control string that another Escape sequence
529 /// interrupts.
530 Unknown {
531 /// The sequence family.
532 kind: SequenceKind,
533 /// The sequence bytes, as described above.
534 bytes: Vec<u8>,
535 },
536 /// Start of a control string body of more than 4096 bytes that has no
537 /// typed event.
538 ///
539 /// [`StringChunk`](Event::StringChunk) events follow with the body, then
540 /// one [`StringEnd`](Event::StringEnd). A recognized reply of up to
541 /// 4096 bytes keeps its own event. Drag and drop, XTGETTCAP, Kitty
542 /// graphics, and Glyph Protocol replies keep their events up to the source
543 /// buffer size.
544 StringStart {
545 /// The string family. This is never [`SequenceKind::Csi`],
546 /// [`SequenceKind::Ss3`], or [`SequenceKind::Raw`].
547 kind: SequenceKind,
548 },
549 /// Raw body bytes of a streamed control string, without the introducer
550 /// or the terminator.
551 ///
552 /// Chunk boundaries follow input availability, not text boundaries.
553 StringChunk(Vec<u8>),
554 /// End of a streamed control string.
555 ///
556 /// An interrupting Escape sequence ends the string before that sequence
557 /// is decoded. An input read failure flushes retained bytes and ends the
558 /// string before the error.
559 StringEnd {
560 /// Whether ST, or BEL for OSC, terminated the string normally.
561 complete: bool,
562 },
563}
564
565/// The family of an [`Event::Unknown`] sequence or a streamed string.
566#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
567#[non_exhaustive]
568pub enum SequenceKind {
569 /// Exact input bytes with no recognized framing.
570 Raw,
571 /// Control Sequence Introducer: `ESC [` or `0x9B`.
572 Csi,
573 /// Single Shift 3: `ESC O` or `0x8F`.
574 Ss3,
575 /// Operating System Command: `ESC ]` or `0x9D`.
576 Osc,
577 /// Device Control String: `ESC P` or `0x90`.
578 Dcs,
579 /// Application Program Command: `ESC _` or `0x9F`.
580 Apc,
581 /// Start of String: `ESC X` or `0x98`.
582 Sos,
583 /// Privacy Message: `ESC ^` or `0x9E`.
584 Pm,
585}
586
587/// The payload of a DECRPSS reply, [`Event::SettingReport`].
588#[derive(Debug, Clone, PartialEq, Eq)]
589#[non_exhaustive]
590pub enum SettingReport {
591 /// The terminal did not recognize the requested setting (`DCS 0 $ r ST`).
592 /// The reply carries no data at all, so only the request that provoked it
593 /// says which setting was turned down.
594 Unrecognized,
595 /// The cursor style the terminal is using, from a DECRPSS reply
596 /// reporting its `DECSCUSR` setting. Ask for it with
597 /// [`Program::request_cursor_style`](crate::program::Program::request_cursor_style).
598 CursorStyle(crate::ansi::cursor::CursorStyle),
599 /// SGR parameters for the terminal's current text attributes.
600 ///
601 /// Request them with [`write_decrqss`](crate::ansi::status::write_decrqss)
602 /// and selector `"m"`. Use [`Sgr::style`](crate::ansi::sgr::Sgr::style)
603 /// to obtain a [`Style`](crate::style::Style).
604 Sgr(crate::ansi::sgr::Sgr),
605 /// The setting as the terminal spelled it, for a control function this
606 /// library does not decode: the whole CSI sequence without its
607 /// introducer, such as `>4;2m` for xterm's `XTQMODKEYS`.
608 /// SGR replies with values above `u16::MAX` also use this variant.
609 Raw(String),
610}
611
612impl Event {
613 /// Borrow the [`Key`] payload if this is any key event
614 /// ([`Event::KeyPress`] or [`Event::KeyRelease`]).
615 pub fn as_key(&self) -> Option<&Key> {
616 match self {
617 Event::KeyPress(k) | Event::KeyRelease(k) => Some(k),
618 _ => None,
619 }
620 }
621
622 /// Borrow the [`Mouse`] payload if this is any mouse event
623 /// ([`Event::MouseClick`], [`Event::MouseRelease`],
624 /// [`Event::MouseWheel`], or [`Event::MouseMove`]).
625 pub fn as_mouse(&self) -> Option<&Mouse> {
626 match self {
627 Event::MouseClick(m)
628 | Event::MouseRelease(m)
629 | Event::MouseWheel(m)
630 | Event::MouseMove(m) => Some(m),
631 _ => None,
632 }
633 }
634}
635
636#[cfg(test)]
637mod tests {
638 use super::*;
639
640 #[test]
641 fn color_scheme_display() {
642 assert_eq!(ColorScheme::Dark.to_string(), "dark");
643 assert_eq!(ColorScheme::Light.to_string(), "light");
644 }
645
646 #[test]
647 fn glyph_query_target_display() {
648 assert_eq!(
649 GlyphQueryTarget::Codepoint('\u{100000}').to_string(),
650 "\u{100000}"
651 );
652 assert_eq!(
653 GlyphQueryTarget::Grapheme(vec!['\u{1f3f3}', '\u{fe0f}', '\u{200d}', '\u{1f308}'])
654 .to_string(),
655 "\u{1f3f3}\u{fe0f}\u{200d}\u{1f308}"
656 );
657 }
658
659 #[test]
660 fn visibility_display_and_predicate() {
661 assert_eq!(Visibility::Visible.to_string(), "visible");
662 assert_eq!(Visibility::Hidden.to_string(), "hidden");
663 assert!(Visibility::Visible.is_visible());
664 assert!(!Visibility::Hidden.is_visible());
665 }
666}