ratatui_widgets/
events.rs

1//! Events module.
2//!
3//! This module provides a cross-backend interface for handling the events that are generated by
4//! the terminal.
5//!
6//! This is not yet stable and will likely change in the future - each backend has some quirks that
7//! are difficult to handle in a generic way.
8
9use bitflags::bitflags;
10use strum::EnumIs;
11
12#[cfg(feature = "crossterm")]
13mod crossterm;
14
15#[cfg(feature = "termion")]
16mod termion;
17
18#[cfg(feature = "termwiz")]
19mod termwiz;
20
21pub trait EventHandler {
22    fn handle_event(&mut self, event: Event) {
23        match event {
24            Event::KeyPressed(key_pressed_event) => self.handle_key(key_pressed_event),
25            Event::Mouse(mouse_event) => self.handle_mouse(mouse_event),
26        }
27    }
28
29    #[allow(unused_variables)]
30    fn handle_key(&mut self, event: KeyPressedEvent) {}
31
32    #[allow(unused_variables)]
33    fn handle_mouse(&mut self, event: MouseEvent) {}
34}
35
36pub enum Event {
37    KeyPressed(KeyPressedEvent),
38    Mouse(MouseEvent),
39}
40
41#[derive(Debug, Clone, PartialEq, Eq, Hash)]
42pub struct KeyPressedEvent {
43    pub key: Key,
44    pub modifiers: KeyModifiers,
45}
46
47#[derive(Debug, Clone, PartialEq, Eq, Hash, EnumIs)]
48pub enum Key {
49    Char(char),
50    Backspace,
51    Delete,
52    Insert,
53    Enter,
54    Left,
55    Right,
56    Up,
57    Esc,
58    Down,
59    Home,
60    End,
61    PageUp,
62    PageDown,
63    Tab,
64    BackTab,
65    F(u8),
66    Null,
67}
68
69bitflags! {
70    #[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash)]
71    pub struct KeyModifiers: u8 {
72        /// Shift key
73        const SHIFT = 1;
74        /// Control key
75        const CTRL = 1 << 1;
76        /// Alias for `CTRL`
77        const CONTROL = KeyModifiers::CTRL.bits();
78        /// Alt key (Option on macOS)
79        const ALT = 1 << 2;
80        /// Alias for `ALT`
81        const OPTION = KeyModifiers::ALT.bits();
82        /// Super key (Windows key on Windows, Command key on macOS)
83        const SUPER = 1 << 3;
84        /// Alias for `SUPER`
85        const WIN = KeyModifiers::SUPER.bits();
86        /// Alias for `SUPER`
87        const COMMAND = KeyModifiers::SUPER.bits();
88        /// Hyper key
89        const HYPER = 1 << 4;
90        /// Meta key
91        const META = 1 << 5;
92    }
93}
94
95#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
96pub struct MouseEvent {
97    pub column: u16,
98    pub row: u16,
99    pub kind: MouseEventKind,
100    pub modifiers: KeyModifiers,
101}
102
103#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
104pub enum MouseEventKind {
105    Down(MouseButton),
106    Up(MouseButton),
107    Drag(MouseButton),
108    Moved,
109    ScrollUp,
110    ScrollDown,
111    ScrollLeft,
112    ScrollRight,
113}
114
115#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
116pub enum MouseButton {
117    Left,
118    Right,
119    Middle,
120}