Skip to main content

ftui_core/
event.rs

1#![forbid(unsafe_code)]
2
3//! Canonical input/event types.
4//!
5//! This module defines the standard event types used throughout ftui for
6//! input handling. All events derive `Clone`, `PartialEq`, and `Eq` for
7//! use in tests and pattern matching.
8//!
9//! # Design Notes
10//!
11//! - Mouse coordinates are 0-indexed (terminal is 1-indexed internally)
12//! - `KeyEventKind` defaults to `Press` when not available from the terminal
13//! - `Modifiers` use bitflags for easy combination
14//! - Clipboard events are optional and feature-gated in the future
15
16use bitflags::bitflags;
17#[cfg(all(not(target_arch = "wasm32"), feature = "crossterm"))]
18use crossterm::event as cte;
19
20/// Canonical input event.
21///
22/// This enum represents all possible input events that ftui can receive
23/// from the terminal.
24#[derive(Debug, Clone, PartialEq, Eq)]
25pub enum Event {
26    /// A keyboard event.
27    Key(KeyEvent),
28
29    /// A mouse event.
30    Mouse(MouseEvent),
31
32    /// Terminal was resized.
33    Resize {
34        /// New terminal width in columns.
35        width: u16,
36        /// New terminal height in rows.
37        height: u16,
38    },
39
40    /// Paste event (from bracketed paste mode).
41    Paste(PasteEvent),
42
43    /// IME composition event (preedit lifecycle).
44    Ime(ImeEvent),
45
46    /// Focus gained or lost.
47    ///
48    /// `true` = focus gained, `false` = focus lost.
49    Focus(bool),
50
51    /// Clipboard content received (optional, from OSC 52 response).
52    Clipboard(ClipboardEvent),
53
54    /// Terminal query or control-string response (DCS, APC, XTWINOPS cell size).
55    TerminalResponse(TerminalResponse),
56
57    /// A tick event from the runtime.
58    ///
59    /// Fired when a scheduled tick interval elapses. Applications use this
60    /// for periodic updates (animations, polling, timers). The model's `update`
61    /// method receives the tick and can respond with state changes.
62    Tick,
63}
64
65impl Event {
66    /// Convert a Crossterm event into an ftui [`Event`].
67    #[must_use]
68    #[cfg(all(not(target_arch = "wasm32"), feature = "crossterm"))]
69    pub fn from_crossterm(event: cte::Event) -> Option<Self> {
70        map_crossterm_event_internal(event)
71    }
72
73    /// Return a static label for the event type (for metrics/tracing).
74    #[must_use]
75    pub const fn event_type_label(&self) -> &'static str {
76        match self {
77            Event::Key(_) => "key",
78            Event::Mouse(_) => "mouse",
79            Event::Resize { .. } => "resize",
80            Event::Paste(_) => "paste",
81            Event::Ime(_) => "ime",
82            Event::Focus(_) => "focus",
83            Event::Clipboard(_) => "clipboard",
84            Event::TerminalResponse(_) => "terminal_response",
85            Event::Tick => "tick",
86        }
87    }
88
89    /// Return the canonical event type name (alias for [`Self::event_type_label`]).
90    #[must_use]
91    pub const fn name(&self) -> &'static str {
92        self.event_type_label()
93    }
94}
95
96/// A keyboard event.
97#[derive(Debug, Clone, Copy, PartialEq, Eq)]
98pub struct KeyEvent {
99    /// The key code that was pressed.
100    pub code: KeyCode,
101
102    /// Modifier keys held during the event.
103    pub modifiers: Modifiers,
104
105    /// The type of key event (press, repeat, or release).
106    pub kind: KeyEventKind,
107}
108
109impl KeyEvent {
110    /// Create a new key event with default modifiers and Press kind.
111    #[must_use]
112    pub const fn new(code: KeyCode) -> Self {
113        Self {
114            code,
115            modifiers: Modifiers::NONE,
116            kind: KeyEventKind::Press,
117        }
118    }
119
120    /// Create a key event with modifiers.
121    #[must_use]
122    pub const fn with_modifiers(mut self, modifiers: Modifiers) -> Self {
123        self.modifiers = modifiers;
124        self
125    }
126
127    /// Create a key event with a specific kind.
128    #[must_use]
129    pub const fn with_kind(mut self, kind: KeyEventKind) -> Self {
130        self.kind = kind;
131        self
132    }
133
134    /// Check if this is a specific character key.
135    #[must_use]
136    pub fn is_char(&self, c: char) -> bool {
137        matches!(self.code, KeyCode::Char(ch) if ch == c)
138    }
139
140    /// Check if Ctrl modifier is held.
141    #[must_use]
142    pub const fn ctrl(&self) -> bool {
143        self.modifiers.contains(Modifiers::CTRL)
144    }
145
146    /// Check if Alt modifier is held.
147    #[must_use]
148    pub const fn alt(&self) -> bool {
149        self.modifiers.contains(Modifiers::ALT)
150    }
151
152    /// Check if Shift modifier is held.
153    #[must_use]
154    pub const fn shift(&self) -> bool {
155        self.modifiers.contains(Modifiers::SHIFT)
156    }
157
158    /// Check if Super/Meta/Cmd modifier is held.
159    #[must_use]
160    pub const fn super_key(&self) -> bool {
161        self.modifiers.contains(Modifiers::SUPER)
162    }
163}
164
165/// Key codes for keyboard events.
166#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
167pub enum KeyCode {
168    /// A regular character key.
169    Char(char),
170
171    /// Enter/Return key.
172    Enter,
173
174    /// Escape key.
175    Escape,
176
177    /// Backspace key.
178    Backspace,
179
180    /// Tab key.
181    Tab,
182
183    /// Shift+Tab (back-tab).
184    BackTab,
185
186    /// Delete key.
187    Delete,
188
189    /// Insert key.
190    Insert,
191
192    /// Home key.
193    Home,
194
195    /// End key.
196    End,
197
198    /// Page Up key.
199    PageUp,
200
201    /// Page Down key.
202    PageDown,
203
204    /// Up arrow key.
205    Up,
206
207    /// Down arrow key.
208    Down,
209
210    /// Left arrow key.
211    Left,
212
213    /// Right arrow key.
214    Right,
215
216    /// Function key (F1-F24).
217    F(u8),
218
219    /// Null character (Ctrl+Space or Ctrl+@).
220    Null,
221
222    /// Media key: Play/Pause.
223    MediaPlayPause,
224
225    /// Media key: Stop.
226    MediaStop,
227
228    /// Media key: Next track.
229    MediaNextTrack,
230
231    /// Media key: Previous track.
232    MediaPrevTrack,
233}
234
235/// The type of key event.
236#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
237pub enum KeyEventKind {
238    /// Key was pressed (default when not distinguishable).
239    #[default]
240    Press,
241
242    /// Key is being held (repeat event).
243    Repeat,
244
245    /// Key was released.
246    Release,
247}
248
249bitflags! {
250    /// Modifier keys that can be held during a key event.
251    #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
252    pub struct Modifiers: u8 {
253        /// No modifiers.
254        const NONE  = 0b0000;
255        /// Shift key.
256        const SHIFT = 0b0001;
257        /// Alt/Option key.
258        const ALT   = 0b0010;
259        /// Control key.
260        const CTRL  = 0b0100;
261        /// Super/Meta/Command key.
262        const SUPER = 0b1000;
263    }
264}
265
266impl Default for Modifiers {
267    fn default() -> Self {
268        Self::NONE
269    }
270}
271
272/// A mouse event.
273#[derive(Debug, Clone, Copy, PartialEq, Eq)]
274pub struct MouseEvent {
275    /// The type of mouse event.
276    pub kind: MouseEventKind,
277
278    /// X coordinate (0-indexed, leftmost column is 0).
279    pub x: u16,
280
281    /// Y coordinate (0-indexed, topmost row is 0).
282    pub y: u16,
283
284    /// Modifier keys held during the event.
285    pub modifiers: Modifiers,
286
287    /// Optional sub-cell pixel coordinates (`(px, py)`) when reported via
288    /// SGR-Pixels (`?1016h`) mode.
289    pub pixel: Option<(u32, u32)>,
290}
291
292impl MouseEvent {
293    /// Create a new mouse event.
294    #[must_use]
295    pub const fn new(kind: MouseEventKind, x: u16, y: u16) -> Self {
296        Self {
297            kind,
298            x,
299            y,
300            modifiers: Modifiers::NONE,
301            pixel: None,
302        }
303    }
304
305    /// Create a mouse event with modifiers.
306    #[must_use]
307    pub const fn with_modifiers(mut self, modifiers: Modifiers) -> Self {
308        self.modifiers = modifiers;
309        self
310    }
311
312    /// Attach pixel coordinates `(px, py)` reported via SGR-Pixels (`?1016h`) mode.
313    #[must_use]
314    pub const fn with_pixel(mut self, px: u32, py: u32) -> Self {
315        self.pixel = Some((px, py));
316        self
317    }
318
319    /// Get the position as a tuple.
320    #[must_use]
321    pub const fn position(&self) -> (u16, u16) {
322        (self.x, self.y)
323    }
324}
325
326/// The type of mouse event.
327#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
328pub enum MouseEventKind {
329    /// Mouse button pressed down.
330    Down(MouseButton),
331
332    /// Mouse button released.
333    Up(MouseButton),
334
335    /// Mouse dragged while button held.
336    Drag(MouseButton),
337
338    /// Mouse moved (no button pressed).
339    Moved,
340
341    /// Mouse wheel scrolled up.
342    ScrollUp,
343
344    /// Mouse wheel scrolled down.
345    ScrollDown,
346
347    /// Mouse wheel scrolled left (horizontal scroll).
348    ScrollLeft,
349
350    /// Mouse wheel scrolled right (horizontal scroll).
351    ScrollRight,
352}
353
354/// Mouse button identifiers.
355#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
356pub enum MouseButton {
357    /// Left mouse button.
358    Left,
359
360    /// Right mouse button.
361    Right,
362
363    /// Middle mouse button (scroll wheel click).
364    Middle,
365}
366
367/// A paste event from bracketed paste mode.
368#[derive(Debug, Clone, PartialEq, Eq)]
369pub struct PasteEvent {
370    /// The pasted text content.
371    pub text: String,
372
373    /// True if this came from bracketed paste mode.
374    ///
375    /// When true, the text was received atomically and should be
376    /// treated as a single paste operation rather than individual
377    /// key presses.
378    pub bracketed: bool,
379}
380
381impl PasteEvent {
382    /// Create a new paste event.
383    #[must_use]
384    pub fn new(text: impl Into<String>, bracketed: bool) -> Self {
385        Self {
386            text: text.into(),
387            bracketed,
388        }
389    }
390
391    /// Create a bracketed paste event (the common case).
392    #[must_use]
393    pub fn bracketed(text: impl Into<String>) -> Self {
394        Self::new(text, true)
395    }
396}
397
398/// IME composition lifecycle phase.
399#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
400pub enum ImePhase {
401    /// Composition started; preedit is active.
402    Start,
403    /// Preedit text changed.
404    Update,
405    /// Composition committed text to the input stream.
406    Commit,
407    /// Composition was canceled.
408    Cancel,
409}
410
411/// IME composition event.
412#[derive(Debug, Clone, PartialEq, Eq)]
413pub struct ImeEvent {
414    /// IME lifecycle phase.
415    pub phase: ImePhase,
416    /// Associated text payload (preedit or committed text).
417    pub text: String,
418}
419
420impl ImeEvent {
421    /// Create a new IME event.
422    #[must_use]
423    pub fn new(phase: ImePhase, text: impl Into<String>) -> Self {
424        Self {
425            phase,
426            text: text.into(),
427        }
428    }
429
430    /// Create a composition-start event.
431    #[must_use]
432    pub fn start() -> Self {
433        Self::new(ImePhase::Start, "")
434    }
435
436    /// Create a composition-update event.
437    #[must_use]
438    pub fn update(preedit: impl Into<String>) -> Self {
439        Self::new(ImePhase::Update, preedit)
440    }
441
442    /// Create a composition-commit event.
443    #[must_use]
444    pub fn commit(text: impl Into<String>) -> Self {
445        Self::new(ImePhase::Commit, text)
446    }
447
448    /// Create a composition-cancel event.
449    #[must_use]
450    pub fn cancel() -> Self {
451        Self::new(ImePhase::Cancel, "")
452    }
453}
454
455/// A clipboard event from OSC 52 response.
456///
457/// This is optional and may not be supported by all terminals.
458#[derive(Debug, Clone, PartialEq, Eq)]
459pub struct ClipboardEvent {
460    /// The clipboard content (decoded from base64).
461    pub content: String,
462
463    /// The source of the clipboard content.
464    pub source: ClipboardSource,
465}
466
467impl ClipboardEvent {
468    /// Create a new clipboard event.
469    #[must_use]
470    pub fn new(content: impl Into<String>, source: ClipboardSource) -> Self {
471        Self {
472            content: content.into(),
473            source,
474        }
475    }
476}
477
478/// The source of clipboard content.
479#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
480pub enum ClipboardSource {
481    /// Clipboard content from OSC 52 protocol.
482    Osc52,
483
484    /// Unknown or unspecified source.
485    #[default]
486    Unknown,
487}
488
489/// Terminal query or control-string response decoded from the input stream.
490#[derive(Debug, Clone, PartialEq, Eq)]
491pub enum TerminalResponse {
492    /// Device Control String (`ESC P ... ST`) payload (e.g. XTGETTCAP or DECRQSS reply).
493    Dcs {
494        /// Raw payload bytes between `ESC P` and `ESC \`.
495        payload: Vec<u8>,
496        /// `true` when the payload exceeded the parser's `MAX_DCS_LEN` cap (8 KiB).
497        truncated: bool,
498    },
499    /// Application Program Command (`ESC _ ... ST`) payload when APC capture is enabled.
500    Apc {
501        /// Raw payload bytes between `ESC _` and `ESC \`.
502        payload: Vec<u8>,
503        /// `true` when the payload exceeded the parser's `MAX_DCS_LEN` cap (8 KiB).
504        truncated: bool,
505    },
506    /// XTWINOPS cell size in pixels (`CSI 6 ; height ; width t`).
507    CellSize {
508        /// Cell width in pixels.
509        width: u16,
510        /// Cell height in pixels.
511        height: u16,
512    },
513}
514
515#[cfg(all(not(target_arch = "wasm32"), feature = "crossterm"))]
516fn map_crossterm_event_internal(event: cte::Event) -> Option<Event> {
517    match event {
518        cte::Event::Key(key) => map_key_event(key).map(Event::Key),
519        cte::Event::Mouse(mouse) => Some(Event::Mouse(map_mouse_event(mouse))),
520        cte::Event::Resize(width, height) => Some(Event::Resize { width, height }),
521        cte::Event::Paste(text) => Some(Event::Paste(PasteEvent::bracketed(text))),
522        cte::Event::FocusGained => Some(Event::Focus(true)),
523        cte::Event::FocusLost => Some(Event::Focus(false)),
524    }
525}
526
527#[cfg(all(not(target_arch = "wasm32"), feature = "crossterm"))]
528fn map_key_event(event: cte::KeyEvent) -> Option<KeyEvent> {
529    let code = map_key_code(event.code)?;
530    let modifiers = map_modifiers(event.modifiers);
531    let kind = map_key_kind(event.kind);
532    Some(KeyEvent {
533        code,
534        modifiers,
535        kind,
536    })
537}
538
539#[cfg(all(not(target_arch = "wasm32"), feature = "crossterm"))]
540fn map_key_kind(kind: cte::KeyEventKind) -> KeyEventKind {
541    match kind {
542        cte::KeyEventKind::Press => KeyEventKind::Press,
543        cte::KeyEventKind::Repeat => KeyEventKind::Repeat,
544        cte::KeyEventKind::Release => KeyEventKind::Release,
545    }
546}
547
548#[cfg(all(not(target_arch = "wasm32"), feature = "crossterm"))]
549pub(crate) fn map_key_code(code: cte::KeyCode) -> Option<KeyCode> {
550    match code {
551        cte::KeyCode::Backspace => Some(KeyCode::Backspace),
552        cte::KeyCode::Enter => Some(KeyCode::Enter),
553        cte::KeyCode::Left => Some(KeyCode::Left),
554        cte::KeyCode::Right => Some(KeyCode::Right),
555        cte::KeyCode::Up => Some(KeyCode::Up),
556        cte::KeyCode::Down => Some(KeyCode::Down),
557        cte::KeyCode::Home => Some(KeyCode::Home),
558        cte::KeyCode::End => Some(KeyCode::End),
559        cte::KeyCode::PageUp => Some(KeyCode::PageUp),
560        cte::KeyCode::PageDown => Some(KeyCode::PageDown),
561        cte::KeyCode::Tab => Some(KeyCode::Tab),
562        cte::KeyCode::BackTab => Some(KeyCode::BackTab),
563        cte::KeyCode::Delete => Some(KeyCode::Delete),
564        cte::KeyCode::Insert => Some(KeyCode::Insert),
565        cte::KeyCode::F(n) => Some(KeyCode::F(n)),
566        cte::KeyCode::Char(c) => Some(KeyCode::Char(c)),
567        cte::KeyCode::Null => Some(KeyCode::Null),
568        cte::KeyCode::Esc => Some(KeyCode::Escape),
569        cte::KeyCode::Media(media) => map_media_key(media),
570        _ => None,
571    }
572}
573
574#[cfg(all(not(target_arch = "wasm32"), feature = "crossterm"))]
575fn map_media_key(code: cte::MediaKeyCode) -> Option<KeyCode> {
576    match code {
577        cte::MediaKeyCode::Play | cte::MediaKeyCode::Pause | cte::MediaKeyCode::PlayPause => {
578            Some(KeyCode::MediaPlayPause)
579        }
580        cte::MediaKeyCode::Stop => Some(KeyCode::MediaStop),
581        cte::MediaKeyCode::TrackNext => Some(KeyCode::MediaNextTrack),
582        cte::MediaKeyCode::TrackPrevious => Some(KeyCode::MediaPrevTrack),
583        _ => None,
584    }
585}
586
587#[cfg(all(not(target_arch = "wasm32"), feature = "crossterm"))]
588fn map_modifiers(modifiers: cte::KeyModifiers) -> Modifiers {
589    let mut mapped = Modifiers::NONE;
590    if modifiers.contains(cte::KeyModifiers::SHIFT) {
591        mapped |= Modifiers::SHIFT;
592    }
593    if modifiers.contains(cte::KeyModifiers::ALT) {
594        mapped |= Modifiers::ALT;
595    }
596    if modifiers.contains(cte::KeyModifiers::CONTROL) {
597        mapped |= Modifiers::CTRL;
598    }
599    if modifiers.contains(cte::KeyModifiers::SUPER)
600        || modifiers.contains(cte::KeyModifiers::HYPER)
601        || modifiers.contains(cte::KeyModifiers::META)
602    {
603        mapped |= Modifiers::SUPER;
604    }
605    mapped
606}
607
608#[cfg(all(not(target_arch = "wasm32"), feature = "crossterm"))]
609fn map_mouse_event(event: cte::MouseEvent) -> MouseEvent {
610    let kind = match event.kind {
611        cte::MouseEventKind::Down(button) => MouseEventKind::Down(map_mouse_button(button)),
612        cte::MouseEventKind::Up(button) => MouseEventKind::Up(map_mouse_button(button)),
613        cte::MouseEventKind::Drag(button) => MouseEventKind::Drag(map_mouse_button(button)),
614        cte::MouseEventKind::Moved => MouseEventKind::Moved,
615        cte::MouseEventKind::ScrollUp => MouseEventKind::ScrollUp,
616        cte::MouseEventKind::ScrollDown => MouseEventKind::ScrollDown,
617        cte::MouseEventKind::ScrollLeft => MouseEventKind::ScrollLeft,
618        cte::MouseEventKind::ScrollRight => MouseEventKind::ScrollRight,
619    };
620
621    let (x, y) = sanitize_crossterm_mouse_coords(event.column, event.row);
622    MouseEvent::new(kind, x, y).with_modifiers(map_modifiers(event.modifiers))
623}
624
625#[cfg(all(not(target_arch = "wasm32"), feature = "crossterm"))]
626fn map_mouse_button(button: cte::MouseButton) -> MouseButton {
627    match button {
628        cte::MouseButton::Left => MouseButton::Left,
629        cte::MouseButton::Right => MouseButton::Right,
630        cte::MouseButton::Middle => MouseButton::Middle,
631    }
632}
633
634#[cfg(all(not(target_arch = "wasm32"), feature = "crossterm"))]
635fn sanitize_crossterm_mouse_coords(x: u16, y: u16) -> (u16, u16) {
636    // We strictly disable 1016 mode (pixel reporting) in TerminalSession.
637    // The previous heuristic (x >= 512 => divide by 8) was dangerous for
638    // large terminals (e.g. 4K/8K screens where columns > 512 are valid).
639    // We trust the terminal to send cell coordinates as requested by SGR 1006.
640    (x, y)
641}
642
643#[cfg(all(test, not(target_arch = "wasm32"), feature = "crossterm"))]
644mod tests {
645    use super::*;
646    use crossterm::event as ct_event;
647
648    #[test]
649    fn key_event_is_char() {
650        let event = KeyEvent::new(KeyCode::Char('q'));
651        assert!(event.is_char('q'));
652        assert!(!event.is_char('x'));
653    }
654
655    #[test]
656    fn key_event_modifiers() {
657        let event = KeyEvent::new(KeyCode::Char('c')).with_modifiers(Modifiers::CTRL);
658        assert!(event.ctrl());
659        assert!(!event.alt());
660        assert!(!event.shift());
661        assert!(!event.super_key());
662    }
663
664    #[test]
665    fn key_event_combined_modifiers() {
666        let event =
667            KeyEvent::new(KeyCode::Char('s')).with_modifiers(Modifiers::CTRL | Modifiers::SHIFT);
668        assert!(event.ctrl());
669        assert!(event.shift());
670        assert!(!event.alt());
671    }
672
673    #[test]
674    fn key_event_kind() {
675        let press = KeyEvent::new(KeyCode::Enter);
676        assert_eq!(press.kind, KeyEventKind::Press);
677
678        let release = press.with_kind(KeyEventKind::Release);
679        assert_eq!(release.kind, KeyEventKind::Release);
680    }
681
682    #[test]
683    fn mouse_event_position() {
684        let event = MouseEvent::new(MouseEventKind::Down(MouseButton::Left), 10, 20);
685        assert_eq!(event.position(), (10, 20));
686        assert_eq!(event.x, 10);
687        assert_eq!(event.y, 20);
688    }
689
690    #[test]
691    fn mouse_event_with_modifiers() {
692        let event = MouseEvent::new(MouseEventKind::Moved, 0, 0).with_modifiers(Modifiers::ALT);
693        assert_eq!(event.modifiers, Modifiers::ALT);
694    }
695
696    #[test]
697    fn paste_event_creation() {
698        let paste = PasteEvent::bracketed("hello world");
699        assert_eq!(paste.text, "hello world");
700        assert!(paste.bracketed);
701    }
702
703    #[test]
704    fn clipboard_event_creation() {
705        let clip = ClipboardEvent::new("copied text", ClipboardSource::Osc52);
706        assert_eq!(clip.content, "copied text");
707        assert_eq!(clip.source, ClipboardSource::Osc52);
708    }
709
710    #[test]
711    fn event_variants() {
712        // Test that all event variants can be created
713        let _key = Event::Key(KeyEvent::new(KeyCode::Char('a')));
714        let _mouse = Event::Mouse(MouseEvent::new(
715            MouseEventKind::Down(MouseButton::Left),
716            0,
717            0,
718        ));
719        let _resize = Event::Resize {
720            width: 80,
721            height: 24,
722        };
723        let _paste = Event::Paste(PasteEvent::bracketed("test"));
724        let _ime = Event::Ime(ImeEvent::update("漢"));
725        let _focus = Event::Focus(true);
726        let _clipboard = Event::Clipboard(ClipboardEvent::new("test", ClipboardSource::Unknown));
727        let _tick = Event::Tick;
728    }
729
730    #[test]
731    fn ime_event_constructors() {
732        assert_eq!(ImeEvent::start().phase, ImePhase::Start);
733        assert_eq!(ImeEvent::update("x"), ImeEvent::new(ImePhase::Update, "x"));
734        assert_eq!(ImeEvent::commit("漢").phase, ImePhase::Commit);
735        assert_eq!(ImeEvent::cancel().phase, ImePhase::Cancel);
736    }
737
738    #[test]
739    fn modifiers_default() {
740        assert_eq!(Modifiers::default(), Modifiers::NONE);
741    }
742
743    #[test]
744    fn key_event_kind_default() {
745        assert_eq!(KeyEventKind::default(), KeyEventKind::Press);
746    }
747
748    #[test]
749    fn clipboard_source_default() {
750        assert_eq!(ClipboardSource::default(), ClipboardSource::Unknown);
751    }
752
753    #[test]
754    fn function_keys() {
755        let f1 = KeyEvent::new(KeyCode::F(1));
756        let f12 = KeyEvent::new(KeyCode::F(12));
757        assert_eq!(f1.code, KeyCode::F(1));
758        assert_eq!(f12.code, KeyCode::F(12));
759    }
760
761    #[test]
762    fn event_is_clone_and_eq() {
763        let event = Event::Key(KeyEvent::new(KeyCode::Char('x')));
764        let cloned = event.clone();
765        assert_eq!(event, cloned);
766    }
767
768    // -- Crossterm mapping tests --
769
770    #[test]
771    fn map_modifiers_ctrl() {
772        let mapped = map_modifiers(ct_event::KeyModifiers::CONTROL);
773        assert!(mapped.contains(Modifiers::CTRL));
774        assert!(!mapped.contains(Modifiers::SHIFT));
775    }
776
777    #[test]
778    fn map_modifiers_alt() {
779        let mapped = map_modifiers(ct_event::KeyModifiers::ALT);
780        assert!(mapped.contains(Modifiers::ALT));
781    }
782
783    #[test]
784    fn map_modifiers_super_variants() {
785        let super_mapped = map_modifiers(ct_event::KeyModifiers::SUPER);
786        assert!(super_mapped.contains(Modifiers::SUPER));
787
788        let hyper_mapped = map_modifiers(ct_event::KeyModifiers::HYPER);
789        assert!(hyper_mapped.contains(Modifiers::SUPER));
790
791        let meta_mapped = map_modifiers(ct_event::KeyModifiers::META);
792        assert!(meta_mapped.contains(Modifiers::SUPER));
793    }
794
795    #[test]
796    fn map_modifiers_combined() {
797        let combined = ct_event::KeyModifiers::SHIFT | ct_event::KeyModifiers::CONTROL;
798        let mapped = map_modifiers(combined);
799        assert!(mapped.contains(Modifiers::SHIFT));
800        assert!(mapped.contains(Modifiers::CTRL));
801        assert!(!mapped.contains(Modifiers::ALT));
802    }
803
804    #[test]
805    fn map_mouse_button_all() {
806        assert_eq!(
807            map_mouse_button(ct_event::MouseButton::Left),
808            MouseButton::Left
809        );
810        assert_eq!(
811            map_mouse_button(ct_event::MouseButton::Right),
812            MouseButton::Right
813        );
814        assert_eq!(
815            map_mouse_button(ct_event::MouseButton::Middle),
816            MouseButton::Middle
817        );
818    }
819
820    #[test]
821    fn map_mouse_event_down() {
822        let ct_event = ct_event::MouseEvent {
823            kind: ct_event::MouseEventKind::Down(ct_event::MouseButton::Left),
824            column: 10,
825            row: 5,
826            modifiers: ct_event::KeyModifiers::NONE,
827        };
828        let mapped = map_mouse_event(ct_event);
829        assert!(matches!(
830            mapped.kind,
831            MouseEventKind::Down(MouseButton::Left)
832        ));
833        assert_eq!(mapped.x, 10);
834        assert_eq!(mapped.y, 5);
835    }
836
837    #[test]
838    fn map_mouse_event_up() {
839        let ct_event = ct_event::MouseEvent {
840            kind: ct_event::MouseEventKind::Up(ct_event::MouseButton::Right),
841            column: 20,
842            row: 15,
843            modifiers: ct_event::KeyModifiers::NONE,
844        };
845        let mapped = map_mouse_event(ct_event);
846        assert!(matches!(
847            mapped.kind,
848            MouseEventKind::Up(MouseButton::Right)
849        ));
850        assert_eq!(mapped.x, 20);
851        assert_eq!(mapped.y, 15);
852    }
853
854    #[test]
855    fn map_mouse_event_drag() {
856        let ct_event = ct_event::MouseEvent {
857            kind: ct_event::MouseEventKind::Drag(ct_event::MouseButton::Middle),
858            column: 5,
859            row: 10,
860            modifiers: ct_event::KeyModifiers::NONE,
861        };
862        let mapped = map_mouse_event(ct_event);
863        assert!(matches!(
864            mapped.kind,
865            MouseEventKind::Drag(MouseButton::Middle)
866        ));
867    }
868
869    #[test]
870    fn map_mouse_event_moved() {
871        let ct_event = ct_event::MouseEvent {
872            kind: ct_event::MouseEventKind::Moved,
873            column: 0,
874            row: 0,
875            modifiers: ct_event::KeyModifiers::NONE,
876        };
877        let mapped = map_mouse_event(ct_event);
878        assert!(matches!(mapped.kind, MouseEventKind::Moved));
879    }
880
881    #[test]
882    fn map_mouse_event_scroll() {
883        let scroll_up = ct_event::MouseEvent {
884            kind: ct_event::MouseEventKind::ScrollUp,
885            column: 0,
886            row: 0,
887            modifiers: ct_event::KeyModifiers::NONE,
888        };
889        let scroll_down = ct_event::MouseEvent {
890            kind: ct_event::MouseEventKind::ScrollDown,
891            column: 0,
892            row: 0,
893            modifiers: ct_event::KeyModifiers::NONE,
894        };
895        let scroll_left = ct_event::MouseEvent {
896            kind: ct_event::MouseEventKind::ScrollLeft,
897            column: 0,
898            row: 0,
899            modifiers: ct_event::KeyModifiers::NONE,
900        };
901        let scroll_right = ct_event::MouseEvent {
902            kind: ct_event::MouseEventKind::ScrollRight,
903            column: 0,
904            row: 0,
905            modifiers: ct_event::KeyModifiers::NONE,
906        };
907
908        assert!(matches!(
909            map_mouse_event(scroll_up).kind,
910            MouseEventKind::ScrollUp
911        ));
912        assert!(matches!(
913            map_mouse_event(scroll_down).kind,
914            MouseEventKind::ScrollDown
915        ));
916        assert!(matches!(
917            map_mouse_event(scroll_left).kind,
918            MouseEventKind::ScrollLeft
919        ));
920        assert!(matches!(
921            map_mouse_event(scroll_right).kind,
922            MouseEventKind::ScrollRight
923        ));
924    }
925
926    #[test]
927    fn map_mouse_event_modifiers() {
928        let ct_event = ct_event::MouseEvent {
929            kind: ct_event::MouseEventKind::Down(ct_event::MouseButton::Left),
930            column: 0,
931            row: 0,
932            modifiers: ct_event::KeyModifiers::SHIFT | ct_event::KeyModifiers::ALT,
933        };
934        let mapped = map_mouse_event(ct_event);
935        assert!(mapped.modifiers.contains(Modifiers::SHIFT));
936        assert!(mapped.modifiers.contains(Modifiers::ALT));
937    }
938
939    #[test]
940    fn map_mouse_event_respects_large_coordinates() {
941        let ct_event = ct_event::MouseEvent {
942            kind: ct_event::MouseEventKind::Moved,
943            column: 1600,
944            row: 640,
945            modifiers: ct_event::KeyModifiers::NONE,
946        };
947        let mapped = map_mouse_event(ct_event);
948        assert_eq!(mapped.x, 1600);
949        assert_eq!(mapped.y, 640);
950    }
951
952    #[test]
953    fn map_mouse_event_keeps_cell_coordinates() {
954        let ct_event = ct_event::MouseEvent {
955            kind: ct_event::MouseEventKind::Moved,
956            column: 120,
957            row: 40,
958            modifiers: ct_event::KeyModifiers::NONE,
959        };
960        let mapped = map_mouse_event(ct_event);
961        assert_eq!(mapped.x, 120);
962        assert_eq!(mapped.y, 40);
963    }
964
965    #[test]
966    fn map_key_event_char() {
967        let ct_event = ct_event::KeyEvent {
968            code: ct_event::KeyCode::Char('x'),
969            modifiers: ct_event::KeyModifiers::CONTROL,
970            kind: ct_event::KeyEventKind::Press,
971            state: ct_event::KeyEventState::NONE,
972        };
973        let mapped = map_key_event(ct_event).expect("should map");
974        assert_eq!(mapped.code, KeyCode::Char('x'));
975        assert!(mapped.modifiers.contains(Modifiers::CTRL));
976        assert_eq!(mapped.kind, KeyEventKind::Press);
977    }
978
979    #[test]
980    fn map_key_event_function_key() {
981        let ct_event = ct_event::KeyEvent {
982            code: ct_event::KeyCode::F(5),
983            modifiers: ct_event::KeyModifiers::NONE,
984            kind: ct_event::KeyEventKind::Press,
985            state: ct_event::KeyEventState::NONE,
986        };
987        let mapped = map_key_event(ct_event).expect("should map");
988        assert_eq!(mapped.code, KeyCode::F(5));
989    }
990
991    #[test]
992    fn map_crossterm_event_key() {
993        let ct_event = ct_event::Event::Key(ct_event::KeyEvent {
994            code: ct_event::KeyCode::Enter,
995            modifiers: ct_event::KeyModifiers::NONE,
996            kind: ct_event::KeyEventKind::Press,
997            state: ct_event::KeyEventState::NONE,
998        });
999        let mapped = map_crossterm_event_internal(ct_event).expect("should map");
1000        assert!(matches!(mapped, Event::Key(_)));
1001    }
1002
1003    #[test]
1004    fn map_crossterm_event_mouse() {
1005        let ct_event = ct_event::Event::Mouse(ct_event::MouseEvent {
1006            kind: ct_event::MouseEventKind::Down(ct_event::MouseButton::Left),
1007            column: 10,
1008            row: 5,
1009            modifiers: ct_event::KeyModifiers::NONE,
1010        });
1011        let mapped = map_crossterm_event_internal(ct_event).expect("should map");
1012        assert!(matches!(mapped, Event::Mouse(_)));
1013    }
1014
1015    #[test]
1016    fn map_crossterm_event_resize() {
1017        let ct_event = ct_event::Event::Resize(80, 24);
1018        let mapped = map_crossterm_event_internal(ct_event).expect("should map");
1019        assert!(matches!(
1020            mapped,
1021            Event::Resize {
1022                width: 80,
1023                height: 24
1024            }
1025        ));
1026    }
1027
1028    #[test]
1029    fn map_crossterm_event_paste() {
1030        let ct_event = ct_event::Event::Paste("hello world".to_string());
1031        let mapped = map_crossterm_event_internal(ct_event).expect("should map");
1032        match mapped {
1033            Event::Paste(paste) => assert_eq!(paste.text, "hello world"),
1034            _ => panic!("expected Paste event"),
1035        }
1036    }
1037
1038    #[test]
1039    fn map_crossterm_event_focus() {
1040        let gained = ct_event::Event::FocusGained;
1041        let lost = ct_event::Event::FocusLost;
1042
1043        assert!(matches!(
1044            map_crossterm_event_internal(gained),
1045            Some(Event::Focus(true))
1046        ));
1047        assert!(matches!(
1048            map_crossterm_event_internal(lost),
1049            Some(Event::Focus(false))
1050        ));
1051    }
1052
1053    #[test]
1054    fn map_key_kind_repeat_and_release() {
1055        assert_eq!(
1056            map_key_kind(ct_event::KeyEventKind::Repeat),
1057            KeyEventKind::Repeat
1058        );
1059        assert_eq!(
1060            map_key_kind(ct_event::KeyEventKind::Release),
1061            KeyEventKind::Release
1062        );
1063    }
1064
1065    #[test]
1066    fn map_key_code_escape() {
1067        assert_eq!(map_key_code(ct_event::KeyCode::Esc), Some(KeyCode::Escape));
1068    }
1069
1070    #[test]
1071    fn map_key_code_unmapped_returns_none() {
1072        // These variants exist in crossterm but are intentionally not mapped into ftui.
1073        assert_eq!(map_key_code(ct_event::KeyCode::CapsLock), None);
1074        assert_eq!(map_key_code(ct_event::KeyCode::ScrollLock), None);
1075        assert_eq!(map_key_code(ct_event::KeyCode::NumLock), None);
1076        assert_eq!(map_key_code(ct_event::KeyCode::PrintScreen), None);
1077        assert_eq!(map_key_code(ct_event::KeyCode::Pause), None);
1078        assert_eq!(map_key_code(ct_event::KeyCode::Menu), None);
1079        assert_eq!(map_key_code(ct_event::KeyCode::KeypadBegin), None);
1080        assert_eq!(
1081            map_key_code(ct_event::KeyCode::Modifier(
1082                ct_event::ModifierKeyCode::LeftShift
1083            )),
1084            None
1085        );
1086    }
1087
1088    #[test]
1089    fn map_media_key_known_and_unknown_variants() {
1090        // Known mapped variants.
1091        assert_eq!(
1092            map_media_key(ct_event::MediaKeyCode::Play),
1093            Some(KeyCode::MediaPlayPause)
1094        );
1095        assert_eq!(
1096            map_media_key(ct_event::MediaKeyCode::Pause),
1097            Some(KeyCode::MediaPlayPause)
1098        );
1099        assert_eq!(
1100            map_media_key(ct_event::MediaKeyCode::PlayPause),
1101            Some(KeyCode::MediaPlayPause)
1102        );
1103        assert_eq!(
1104            map_media_key(ct_event::MediaKeyCode::TrackNext),
1105            Some(KeyCode::MediaNextTrack)
1106        );
1107        assert_eq!(
1108            map_media_key(ct_event::MediaKeyCode::TrackPrevious),
1109            Some(KeyCode::MediaPrevTrack)
1110        );
1111        assert_eq!(
1112            map_media_key(ct_event::MediaKeyCode::Stop),
1113            Some(KeyCode::MediaStop)
1114        );
1115
1116        // A representative unmapped variant.
1117        assert_eq!(map_media_key(ct_event::MediaKeyCode::Reverse), None);
1118    }
1119
1120    #[test]
1121    fn from_crossterm_returns_none_for_unmapped_keys() {
1122        let ct_event = ct_event::Event::Key(ct_event::KeyEvent {
1123            code: ct_event::KeyCode::CapsLock,
1124            modifiers: ct_event::KeyModifiers::NONE,
1125            kind: ct_event::KeyEventKind::Press,
1126            state: ct_event::KeyEventState::NONE,
1127        });
1128
1129        assert_eq!(Event::from_crossterm(ct_event), None);
1130    }
1131
1132    #[test]
1133    fn crossterm_key_event_maps_to_ftui_key() {
1134        let cases = [
1135            (
1136                ct_event::KeyCode::Up,
1137                ct_event::KeyModifiers::NONE,
1138                KeyCode::Up,
1139                Modifiers::NONE,
1140            ),
1141            (
1142                ct_event::KeyCode::Down,
1143                ct_event::KeyModifiers::NONE,
1144                KeyCode::Down,
1145                Modifiers::NONE,
1146            ),
1147            (
1148                ct_event::KeyCode::Left,
1149                ct_event::KeyModifiers::SHIFT,
1150                KeyCode::Left,
1151                Modifiers::SHIFT,
1152            ),
1153            (
1154                ct_event::KeyCode::Right,
1155                ct_event::KeyModifiers::ALT,
1156                KeyCode::Right,
1157                Modifiers::ALT,
1158            ),
1159            (
1160                ct_event::KeyCode::F(1),
1161                ct_event::KeyModifiers::NONE,
1162                KeyCode::F(1),
1163                Modifiers::NONE,
1164            ),
1165            (
1166                ct_event::KeyCode::F(12),
1167                ct_event::KeyModifiers::CONTROL,
1168                KeyCode::F(12),
1169                Modifiers::CTRL,
1170            ),
1171            (
1172                ct_event::KeyCode::Char('c'),
1173                ct_event::KeyModifiers::CONTROL,
1174                KeyCode::Char('c'),
1175                Modifiers::CTRL,
1176            ),
1177            (
1178                ct_event::KeyCode::Enter,
1179                ct_event::KeyModifiers::NONE,
1180                KeyCode::Enter,
1181                Modifiers::NONE,
1182            ),
1183            (
1184                ct_event::KeyCode::Backspace,
1185                ct_event::KeyModifiers::NONE,
1186                KeyCode::Backspace,
1187                Modifiers::NONE,
1188            ),
1189        ];
1190
1191        for (ct_code, ct_mods, expected_code, expected_mods) in cases {
1192            let ct = ct_event::Event::Key(ct_event::KeyEvent {
1193                code: ct_code,
1194                modifiers: ct_mods,
1195                kind: ct_event::KeyEventKind::Press,
1196                state: ct_event::KeyEventState::NONE,
1197            });
1198            let mapped = Event::from_crossterm(ct).expect("table key must map");
1199            assert_eq!(
1200                mapped,
1201                Event::Key(KeyEvent {
1202                    code: expected_code,
1203                    modifiers: expected_mods,
1204                    kind: KeyEventKind::Press,
1205                })
1206            );
1207        }
1208    }
1209}