Skip to main content

strata_platform/
events.rs

1//! Platform Event Model: Mouse, Keyboard, Touch, Window State, and File Drag-and-Drop.
2
3use crate::window::ThemeMode;
4use std::path::PathBuf;
5
6/// Mouse button identifiers.
7#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
8pub enum MouseButton {
9    Left,
10    Right,
11    Middle,
12    Other(u16),
13}
14
15impl MouseButton {
16    /// Returns the standard W3C DOM button index: 0 for Left, 1 for Middle, 2 for Right, or custom.
17    pub fn to_button_index(&self) -> i16 {
18        match self {
19            MouseButton::Left => 0,
20            MouseButton::Middle => 1,
21            MouseButton::Right => 2,
22            MouseButton::Other(b) => *b as i16,
23        }
24    }
25}
26
27/// Keyboard key codes.
28#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
29pub enum KeyCode {
30    KeyA,
31    KeyB,
32    KeyC,
33    KeyD,
34    KeyE,
35    KeyF,
36    KeyG,
37    KeyH,
38    KeyI,
39    KeyJ,
40    KeyK,
41    KeyL,
42    KeyM,
43    KeyN,
44    KeyO,
45    KeyP,
46    KeyQ,
47    KeyR,
48    KeyS,
49    KeyT,
50    KeyU,
51    KeyV,
52    KeyW,
53    KeyX,
54    KeyY,
55    KeyZ,
56    Digit0,
57    Digit1,
58    Digit2,
59    Digit3,
60    Digit4,
61    Digit5,
62    Digit6,
63    Digit7,
64    Digit8,
65    Digit9,
66    Escape,
67    Enter,
68    Tab,
69    Space,
70    Backspace,
71    Delete,
72    ArrowUp,
73    ArrowDown,
74    ArrowLeft,
75    ArrowRight,
76    Home,
77    End,
78    PageUp,
79    PageDown,
80    F1,
81    F2,
82    F3,
83    F4,
84    F5,
85    F6,
86    F7,
87    F8,
88    F9,
89    F10,
90    F11,
91    F12,
92    Slash,
93    Comma,
94    Period,
95    Minus,
96    Equals,
97    BracketLeft,
98    BracketRight,
99    Semicolon,
100    Quote,
101    Backslash,
102    Backquote,
103    Unknown,
104}
105
106/// Keyboard modifier keys active during an event.
107#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
108pub struct Modifiers {
109    pub shift: bool,
110    pub ctrl: bool,
111    pub alt: bool,
112    pub meta: bool, // Command on macOS, Windows key on Windows
113}
114
115/// Touch phase for mobile and touchscreens.
116#[derive(Debug, Clone, Copy, PartialEq, Eq)]
117pub enum TouchPhase {
118    Started,
119    Moved,
120    Ended,
121    Cancelled,
122}
123
124/// Native platform event emitted to the Strata event loop.
125#[derive(Debug, Clone, PartialEq)]
126pub enum PlatformEvent {
127    // Window lifecycle & geometry
128    WindowResized {
129        width: u32,
130        height: u32,
131    },
132    WindowMoved {
133        x: i32,
134        y: i32,
135    },
136    WindowCloseRequested,
137    WindowFocused(bool),
138    /// Emitted when the window enters or leaves the maximized state.
139    WindowMaximized(bool),
140    ScaleFactorChanged {
141        scale_factor: f32,
142    },
143    ThemeChanged(ThemeMode),
144    RedrawRequested,
145    /// Periodic VSync display frame animation tick for physics and inertial kinetic scrolling.
146    AnimationTick,
147
148    // Cursor / Mouse
149    MouseMove {
150        x: f32,
151        y: f32,
152    },
153    MouseDown {
154        button: MouseButton,
155        x: f32,
156        y: f32,
157    },
158    MouseUp {
159        button: MouseButton,
160        x: f32,
161        y: f32,
162    },
163    DoubleClick {
164        button: MouseButton,
165        x: f32,
166        y: f32,
167    },
168    Scroll {
169        delta_x: f32,
170        delta_y: f32,
171        is_momentum: bool,
172    },
173    CursorEntered,
174    CursorLeft,
175
176    // Keyboard
177    KeyDown {
178        key: KeyCode,
179        modifiers: Modifiers,
180    },
181    KeyUp {
182        key: KeyCode,
183        modifiers: Modifiers,
184    },
185    ReceivedCharacter(char),
186
187    // Input Method Editor (IME) for internationalized / CJK text composition
188    ImePreedit {
189        text: String,
190        cursor: Option<(usize, usize)>,
191    },
192    ImeCommit(String),
193    ImeDeleteSurrounding {
194        offset: i32,
195        n_chars: u32,
196    },
197
198    // Multi-touch
199    Touch {
200        touch_id: u64,
201        phase: TouchPhase,
202        x: f32,
203        y: f32,
204    },
205
206    // Stylus / Pen Tablet (W3C Pointer Events Level 3 / Wayland tablet-v2 / GTK / NSEvent / WM_POINTER)
207    Stylus {
208        phase: StylusPhase,
209        pointer_id: u64,
210        tool: PointerKind,
211        x: f32,
212        y: f32,
213        /// Normalized tip pressure in `[0.0, 1.0]`.
214        pressure: f32,
215        /// Pen tilt along the X axis in degrees (`-90.0..=90.0`).
216        tilt_x: f32,
217        /// Pen tilt along the Y axis in degrees (`-90.0..=90.0`).
218        tilt_y: f32,
219        /// Clockwise barrel rotation in degrees (`0.0..=359.0`).
220        twist: f32,
221        /// Barrel tangential pressure / airbrush wheel in `[-1.0, 1.0]`.
222        tangential_pressure: f32,
223        /// `true` when the stylus is hovering in proximity without touching the surface.
224        hovering: bool,
225        /// Bitmask of pressed barrel / tip buttons.
226        buttons: u16,
227    },
228
229    // File Drag-and-Drop
230    FileDrop(Vec<PathBuf>),
231
232    // Desktop System Tray
233    TrayIconClicked,
234    TrayMenuItemClicked(u64),
235
236    // Single-Instance IPC
237    SingleInstanceTriggered(Vec<String>),
238}
239
240/// Type of pointing device / stylus tool emitting pointer events.
241#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
242pub enum PointerKind {
243    Mouse,
244    Touch,
245    Pen,
246    Eraser,
247    Brush,
248    Airbrush,
249}
250
251impl PointerKind {
252    /// Returns the W3C PointerEvent `pointerType` string (`"mouse"`, `"touch"`, or `"pen"`).
253    pub const fn as_w3c_str(self) -> &'static str {
254        match self {
255            Self::Mouse => "mouse",
256            Self::Touch => "touch",
257            Self::Pen | Self::Eraser | Self::Brush | Self::Airbrush => "pen",
258        }
259    }
260}
261
262/// Lifecycle phase of a stylus / pen tablet interaction.
263#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
264pub enum StylusPhase {
265    Down,
266    Move,
267    Up,
268    Hover,
269    Cancel,
270}
271
272/// Decodes a `file://` URI (or raw local filesystem path) with RFC 3986 percent-encoding into a `PathBuf`.
273pub fn decode_file_uri_to_path(uri: &str) -> Option<PathBuf> {
274    let trimmed = uri.trim();
275    if trimmed.is_empty() || trimmed.starts_with('#') {
276        return None;
277    }
278    let raw_path = if let Some(rest) = trimmed.strip_prefix("file://localhost") {
279        rest
280    } else if let Some(rest) = trimmed.strip_prefix("file://") {
281        rest
282    } else {
283        trimmed
284    };
285    if raw_path.is_empty() {
286        return None;
287    }
288    let bytes = raw_path.as_bytes();
289    let mut decoded = Vec::with_capacity(bytes.len());
290    let mut i = 0;
291    while i < bytes.len() {
292        if bytes[i] == b'%' && i + 2 < bytes.len() {
293            let h1 = (bytes[i + 1] as char).to_digit(16);
294            let h2 = (bytes[i + 2] as char).to_digit(16);
295            if let (Some(d1), Some(d2)) = (h1, h2) {
296                decoded.push(((d1 << 4) | d2) as u8);
297                i += 3;
298                continue;
299            }
300        }
301        decoded.push(bytes[i]);
302        i += 1;
303    }
304    let s = String::from_utf8_lossy(&decoded).into_owned();
305    Some(PathBuf::from(s))
306}
307
308/// Parses an RFC 2483 `text/uri-list` payload into a list of local `PathBuf`s.
309pub fn parse_dropped_uri_list_to_paths(payload: &str) -> Vec<PathBuf> {
310    payload
311        .lines()
312        .filter_map(decode_file_uri_to_path)
313        .collect()
314}