Debian Codegraph @

Xtermina/src/event.rs

raw symbols SCIP
1 //! Terminal input events.
2 //!
3 //! [`Event`] is the typed output of [`Parser`], [`EventReader`], and the optional `EventStream`.
4 //! Termina reports ordinary input events such as keys, mouse input, focus changes, resize events,
5 //! and bracketed paste. It also keeps terminal responses such as CSI, OSC, and DCS in the same
6 //! public enum so callers can issue a query and read the response without a second internal event
7 //! model.
8 //!
9 //! Use [`EventReader::read`] or [`Terminal::read`] when reading from a process terminal. Use
10 //! [`Parser::pop`] when parsing bytes from a PTY, terminal multiplexer, or other caller-owned
11 //! input source. [`EventReader`] is the main place to look for event-reading examples and filter
12 //! behavior.
13 //!
14 //! # Implementation Notes
15 //!
16 //! Most event code is adapted from [crossterm events]. The main difference is intentional: Termina
17 //! includes escape sequences like [`Csi`] and [`Dcs`] in [`Event`] and does not split the model
18 //! into separate internal and public events. The key event types otherwise stay close to
19 //! crossterm's shape.
20 //!
21 //! [crossterm events]: https://docs.rs/crossterm/latest/crossterm/event/index.html
22 //! [`Csi`]: crate::escape::csi::Csi
23 //! [`Dcs`]: crate::escape::dcs::Dcs
24 //! [`EventReader`]: crate::EventReader
25 //! [`EventReader::read`]: crate::EventReader::read
26 //! [`Parser`]: crate::Parser
27 //! [`Parser::pop`]: crate::Parser::pop
28 //! [`Terminal::read`]: crate::Terminal::read
29
30 use crate::{
31 escape::{csi::Csi, dcs::Dcs, osc::Osc},
32 WindowSize,
33 };
34
35 #[cfg(doc)]
36 use crate::escape::csi::{DecPrivateModeCode, KittyKeyboardFlags};
37 #[cfg(doc)]
38 use crate::{EventReader, Parser, Terminal};
39
40 pub(crate) mod reader;
41 pub(crate) mod source;
42 #[cfg(feature = "event-stream")]
43 pub(crate) mod stream;
44
45 /// A parsed terminal input event or terminal protocol response.
46 ///
47 /// Values of this type are returned by [`EventReader::read`], [`Terminal::read`], and
48 /// [`Parser::pop`]. See [`EventReader`] for the normal terminal-reading flow, including how
49 /// filters skip events without losing them.
50 #[derive(Debug, Clone, PartialEq, Eq)]
51 pub enum Event {
52 /// A keyboard event described by [`KeyEvent`].
53 ///
54 /// Check [`KeyEvent::kind`] when a binding should run once per physical key press. Some input
55 /// sources report both press and release for the same key, so handling every `Event::Key`
56 /// without checking for [`KeyEventKind::Press`] can run the binding twice.
57 Key(KeyEvent),
58
59 /// A mouse event described by [`MouseEvent`].
60 ///
61 /// Terminals produce these after an application enables mouse tracking with modes such as
62 /// [`DecPrivateModeCode::MouseTracking`], [`DecPrivateModeCode::ButtonEventMouse`], or
63 /// [`DecPrivateModeCode::AnyEventMouse`].
64 Mouse(MouseEvent),
65
66 /// The terminal window was resized to the given [`WindowSize`].
67 WindowResized(WindowSize),
68
69 /// Terminal focus entered the application window.
70 ///
71 /// Terminals send this only after [`DecPrivateModeCode::FocusTracking`] has enabled focus
72 /// tracking.
73 FocusIn,
74
75 /// Terminal focus left the application window.
76 ///
77 /// Terminals send this only after [`DecPrivateModeCode::FocusTracking`] has enabled focus
78 /// tracking.
79 FocusOut,
80
81 /// A "bracketed" paste.
82 ///
83 /// Normally pasting into a terminal with Ctrl+v (or Super+v) enters the pasted text as if
84 /// you had typed the keys individually. [`DecPrivateModeCode::BracketedPaste`] asks compatible
85 /// terminals to wrap pasted text in explicit start/end markers so Termina can deliver the
86 /// entire pasted content as one event. xterm documents this as [bracketed paste mode].
87 ///
88 /// [bracketed paste mode]: https://invisible-island.net/xterm/ctlseqs/ctlseqs.html#h2-Bracketed-Paste-Mode
89 Paste(String),
90
91 /// A parsed CSI response or report described by [`Csi`].
92 ///
93 /// Applications see this when the terminal sends a Control Sequence Introducer response, such
94 /// as a cursor position report, device attributes, mode report, or [`Csi::Keyboard`] protocol
95 /// report.
96 Csi(Csi),
97
98 /// A parsed OSC response described by [`Osc`].
99 ///
100 /// Applications see this when the terminal answers an Operating System Command query, such as a
101 /// dynamic color query.
102 Osc(Osc<'static>),
103
104 /// A parsed DCS response described by [`Dcs`].
105 ///
106 /// Applications see this when the terminal answers a Device Control String query, such as
107 /// DECRQSS.
108 Dcs(Dcs),
109 }
110
111 impl Event {
112 /// Returns `true` for CSI, OSC, and DCS protocol responses.
113 #[inline]
114 pub fn is_escape(&self) -> bool {
115 matches!(self, Self::Csi(_) | Self::Dcs(_) | Self::Osc(_))
116 }
117 }
118
119 /// A key event plus modifiers and protocol state.
120 ///
121 /// `KeyEvent` appears inside [`Event::Key`], which is normally returned by [`EventReader::read`]
122 /// or [`Terminal::read`]. See [`EventReader`] for examples of filtering key events while leaving
123 /// other terminal events buffered.
124 ///
125 /// `code` identifies the key, `kind` distinguishes press/release/repeat when the terminal reports
126 /// that detail, `modifiers` carries held modifier keys, and `state` carries protocol state such as
127 /// keypad-originated input.
128 ///
129 /// Code that handles shortcuts should usually check `kind == KeyEventKind::Press` before acting.
130 /// Unix-style terminal input commonly reports only presses unless a keyboard enhancement protocol
131 /// requests event types, but the Windows legacy console API reports press and release records for
132 /// many keys. Ignoring `kind` can make a shortcut run twice on backends that expose releases.
133 ///
134 /// Some key combinations also cannot be represented by some terminals at all. Crossterm's
135 /// [missing key combinations] issue is a useful catalogue of those terminal-level limitations;
136 /// report Termina bugs in Termina, not on that upstream issue.
137 ///
138 /// # Implementation Notes
139 ///
140 /// This mirrors the layout used by [crossterm key events].
141 ///
142 /// [crossterm key events]: https://docs.rs/crossterm/latest/crossterm/event/struct.KeyEvent.html
143 /// [missing key combinations]: https://github.com/crossterm-rs/crossterm/issues/685
144 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
145 pub struct KeyEvent {
146 /// The key identity.
147 pub code: KeyCode,
148
149 /// Whether this event is a press, release, or repeat.
150 ///
151 /// Check this before triggering a shortcut or command. If the command should run once per
152 /// physical key press, require [`KeyEventKind::Press`] and ignore release events.
153 pub kind: KeyEventKind,
154
155 /// Modifier keys active for this key event.
156 ///
157 /// This is the modifier state Termina could infer from the terminal protocol or platform
158 /// backend. Plain terminal input does not report every modifier independently; for example,
159 /// Shift may be inferred from an uppercase decoded character, while lock-key and keypad state
160 /// require an enhanced keyboard protocol or platform backend that reports them.
161 pub modifiers: Modifiers,
162
163 /// Extra key state reported by the terminal protocol.
164 ///
165 /// This is empty unless the input source reports state outside the ordinary modifier mask,
166 /// such as keypad-originated input, Caps Lock, or Num Lock.
167 pub state: KeyEventState,
168 }
169
170 impl KeyEvent {
171 /// Creates a key-press event with the given key code and modifiers.
172 pub const fn new(code: KeyCode, modifiers: Modifiers) -> Self {
173 Self {
174 code,
175 modifiers,
176 kind: KeyEventKind::Press,
177 state: KeyEventState::NONE,
178 }
179 }
180 }
181
182 impl From<KeyCode> for KeyEvent {
183 fn from(code: KeyCode) -> Self {
184 Self {
185 code,
186 kind: KeyEventKind::Press,
187 modifiers: Modifiers::NONE,
188 state: KeyEventState::NONE,
189 }
190 }
191 }
192
193 /// Whether a key was pressed, released, or repeated.
194 ///
195 /// This controls whether a key event should trigger an action. Unix-style terminal input commonly
196 /// produces [`Self::Press`] only, while Windows legacy console input and enhanced keyboard
197 /// protocols can also produce [`Self::Release`] and [`Self::Repeat`]. Code that treats every
198 /// [`Event::Key`] as an action can therefore run twice for one physical key press. Shortcuts and
199 /// commands should usually act only on [`Self::Press`]. Some key combinations are also limited by
200 /// what the terminal can encode; Crossterm's [missing key combinations] issue is useful background
201 /// for those limitations, but Termina bugs should be reported to Termina.
202 ///
203 /// [missing key combinations]: https://github.com/crossterm-rs/crossterm/issues/685
204 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
205 pub enum KeyEventKind {
206 /// A key was pressed.
207 Press,
208
209 /// A key was released.
210 ///
211 /// Terminals report releases when a keyboard protocol flag such as
212 /// [`KittyKeyboardFlags::REPORT_EVENT_TYPES`] requests event types, or when the platform
213 /// backend exposes releases directly.
214 Release,
215
216 /// A key press was repeated while held.
217 Repeat,
218 }
219
220 bitflags::bitflags! {
221 /// Modifier keys active during a key or mouse event.
222 ///
223 /// Terminals vary in which modifiers they report. Treat these flags as the state Termina
224 /// observed, not as proof that every unlisted physical modifier was inactive.
225 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
226 pub struct Modifiers: u8 {
227 /// No modifier keys were active.
228 const NONE = 0;
229
230 /// Shift was active.
231 const SHIFT = 1;
232
233 /// Alt or Option was active.
234 const ALT = 1 << 1;
235
236 /// Control was active.
237 const CONTROL = 1 << 2;
238
239 /// Super key.
240 ///
241 /// This is Command on macOS, the Windows key on Windows, and commonly the Super key on
242 /// Linux and other Unix-like systems.
243 const SUPER = 1 << 3;
244 /// Hyper key.
245 ///
246 /// Hyper is an additional modifier from older keyboard layouts and terminal protocols. It
247 /// is uncommon on modern Mac and Windows keyboards, but some terminals can still report it.
248 const HYPER = 1 << 4;
249
250 /// Meta was active.
251 const META = 1 << 5;
252
253 /// Caps Lock was active.
254 const CAPS_LOCK = 1 << 6;
255
256 /// Num Lock was active.
257 const NUM_LOCK = 1 << 7;
258 }
259 }
260
261 bitflags::bitflags! {
262 /// Extra key state reported by the terminal or platform backend.
263 ///
264 /// These flags are present only when the input source reports them. Ordinary terminal input
265 /// often cannot distinguish keypad-originated keys or lock-key state.
266 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
267 pub struct KeyEventState: u8 {
268 /// No extra key state was reported.
269 const NONE = 0;
270
271 /// The key came from the keypad.
272 const KEYPAD = 1 << 1;
273
274 /// Caps Lock was active for this key event.
275 const CAPS_LOCK = 1 << 2;
276
277 /// Num Lock was active for this key event.
278 const NUM_LOCK = 1 << 3;
279 }
280 }
281
282 /// The key identity reported by the terminal.
283 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
284 pub enum KeyCode {
285 /// A Unicode character key after terminal decoding.
286 ///
287 /// Termina stores the character it can identify from the input source rather than normalizing
288 /// every alphabetic key to lowercase plus [`Modifiers::SHIFT`]. For ordinary UTF-8 terminal
289 /// input, `A` is reported as `Char('A')` and Shift is also recorded in `modifiers` when Termina
290 /// can infer it from the decoded character. Control bytes such as Ctrl+A are reported as
291 /// `Char('a')` with [`Modifiers::CONTROL`]. Enhanced keyboard protocols and the Windows
292 /// backend may use layout-aware or protocol-supplied characters, so callers should compare
293 /// against the character they want to handle instead of assuming another terminal library's
294 /// capitalization model.
295 Char(char),
296
297 /// The Enter or Return key.
298 Enter,
299
300 /// The Backspace key.
301 Backspace,
302
303 /// The Tab key.
304 Tab,
305
306 /// The Escape key.
307 Escape,
308
309 /// The left arrow key.
310 Left,
311
312 /// The right arrow key.
313 Right,
314
315 /// The up arrow key.
316 Up,
317
318 /// The down arrow key.
319 Down,
320
321 /// The Home key.
322 Home,
323
324 /// The End key.
325 End,
326
327 /// Shift+Tab or another backwards-tab key sequence.
328 BackTab,
329
330 /// The Page Up key.
331 PageUp,
332
333 /// The Page Down key.
334 PageDown,
335
336 /// The Insert key.
337 Insert,
338
339 /// The Delete key.
340 Delete,
341
342 /// The keypad begin key.
343 KeypadBegin,
344
345 /// The Caps Lock key.
346 CapsLock,
347
348 /// The Scroll Lock key.
349 ScrollLock,
350
351 /// The Num Lock key.
352 NumLock,
353
354 /// The Print Screen key.
355 PrintScreen,
356
357 /// The Pause or Break key.
358 Pause,
359
360 /// The Menu or Application key.
361 Menu,
362
363 /// A null key code.
364 ///
365 /// This can appear when a platform backend reports a key event without a printable or named
366 /// key identity.
367 Null,
368
369 /// F1-F35 function keys.
370 Function(u8),
371
372 /// A modifier key such as Shift, Control, Alt, Super, Hyper, or Meta.
373 Modifier(ModifierKeyCode),
374
375 /// A media control key.
376 Media(MediaKeyCode),
377 }
378
379 /// Physical modifier keys reported as key events.
380 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
381 pub enum ModifierKeyCode {
382 /// Left Shift key.
383 LeftShift,
384 /// Left Control key. (Control on macOS, Ctrl on other platforms)
385 LeftControl,
386 /// Left Alt key. (Option on macOS, Alt on other platforms)
387 LeftAlt,
388 /// Left Super key. (Command on macOS, Windows key on Windows, Super on Linux)
389 LeftSuper,
390 /// Left Hyper key. (An extended modifier used by some keyboards and terminal protocols)
391 LeftHyper,
392 /// Left Meta key.
393 LeftMeta,
394 /// Right Shift key.
395 RightShift,
396 /// Right Control key. (Control on macOS, Ctrl on other platforms)
397 RightControl,
398 /// Right Alt key. (Option on macOS, Alt on other platforms)
399 RightAlt,
400 /// Right Super key. (Command on macOS, Windows key on Windows, Super on Linux)
401 RightSuper,
402 /// Right Hyper key. (An extended modifier used by some keyboards and terminal protocols)
403 RightHyper,
404 /// Right Meta key.
405 RightMeta,
406 /// Iso Level3 Shift key.
407 IsoLevel3Shift,
408 /// Iso Level5 Shift key.
409 IsoLevel5Shift,
410 }
411
412 /// Media keys reported as key events.
413 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
414 pub enum MediaKeyCode {
415 /// Play media key.
416 Play,
417 /// Pause media key.
418 Pause,
419 /// Play/Pause media key.
420 PlayPause,
421 /// Reverse media key.
422 Reverse,
423 /// Stop media key.
424 Stop,
425 /// Fast-forward media key.
426 FastForward,
427 /// Rewind media key.
428 Rewind,
429 /// Next-track media key.
430 TrackNext,
431 /// Previous-track media key.
432 TrackPrevious,
433 /// Record media key.
434 Record,
435 /// Lower-volume media key.
436 LowerVolume,
437 /// Raise-volume media key.
438 RaiseVolume,
439 /// Mute media key.
440 MuteVolume,
441 }
442
443 /// Mouse input event with zero-based terminal cell coordinates.
444 ///
445 /// Terminal mouse protocols encode cell positions as one-based coordinates, but Termina converts
446 /// them to zero-based `column` and `row` values for consistency with Rust indexing and the parser's
447 /// existing event model. SGR pixel mouse reports are represented separately as
448 /// [`crate::escape::csi::MouseReport::Sgr1016`].
449 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
450 pub struct MouseEvent {
451 /// The mouse action.
452 pub kind: MouseEventKind,
453
454 /// The zero-based terminal column where the event occurred.
455 pub column: u16,
456
457 /// The zero-based terminal row where the event occurred.
458 pub row: u16,
459
460 /// The key modifiers active when the event occurred.
461 pub modifiers: Modifiers,
462 }
463
464 /// The mouse action reported by the terminal.
465 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
466 pub enum MouseEventKind {
467 /// A mouse button was pressed.
468 Down(MouseButton),
469
470 /// A mouse button was released.
471 Up(MouseButton),
472
473 /// The pointer moved while a mouse button was pressed.
474 Drag(MouseButton),
475
476 /// The pointer moved without a pressed mouse button.
477 Moved,
478
479 /// The wheel scrolled down, usually toward the user.
480 ScrollDown,
481
482 /// The wheel scrolled up, usually away from the user.
483 ScrollUp,
484
485 /// The wheel or touchpad scrolled left.
486 ScrollLeft,
487
488 /// The wheel or touchpad scrolled right.
489 ScrollRight,
490 }
491
492 /// Mouse buttons reported by terminal mouse tracking.
493 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
494 pub enum MouseButton {
495 /// Left mouse button.
496 Left,
497 /// Right mouse button.
498 Right,
499 /// Middle mouse button.
500 Middle,
501 }