Skip to main content

sui_core/
event.rs

1use std::{ops::Range, path::PathBuf};
2
3use crate::{
4    AsyncWakeToken, DragEvent, Point, SafeAreaInsets, SemanticsActionRequest, Size, TimerToken,
5    Vector, WidgetId,
6};
7
8#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
9pub struct Modifiers {
10    pub shift: bool,
11    pub control: bool,
12    pub alt: bool,
13    pub meta: bool,
14}
15
16/// Requested host behavior for the system cursor.
17///
18/// Cursor grabbing is best effort. A platform may fall back from [`Self::Locked`]
19/// to [`Self::Confined`], or leave the cursor ungrabbed when neither mode is
20/// supported.
21#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
22pub enum CursorGrabMode {
23    /// The cursor can leave the host viewport and absolute pointer motion is
24    /// available normally.
25    #[default]
26    None,
27    /// Keep the cursor inside the host viewport while retaining an absolute
28    /// cursor position.
29    Confined,
30    /// Decouple motion from the host's absolute cursor position and report
31    /// relative movement. Visibility remains a separate host request.
32    Locked,
33}
34
35/// Device-relative mouse motion in the host's raw, device-specific units.
36///
37/// This event is independent of [`PointerEvent::position`] and is not DPI
38/// normalized. Desktop hosts deliver it to the widget that owns the active
39/// cursor grab.
40#[derive(Debug, Clone, Copy, PartialEq)]
41pub struct RawMouseMotionEvent {
42    pub delta: Vector,
43    pub modifiers: Modifiers,
44}
45
46impl Modifiers {
47    pub const NONE: Self = Self {
48        shift: false,
49        control: false,
50        alt: false,
51        meta: false,
52    };
53
54    pub const fn any(self) -> bool {
55        self.shift || self.control || self.alt || self.meta
56    }
57}
58
59#[derive(Debug, Clone, Copy, PartialEq, Eq)]
60pub enum PointerButton {
61    Primary,
62    Secondary,
63    Middle,
64    Back,
65    Forward,
66    Other(u16),
67}
68
69#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
70pub struct PointerButtons(u8);
71
72impl PointerButtons {
73    const PRIMARY: u8 = 1 << 0;
74    const SECONDARY: u8 = 1 << 1;
75    const MIDDLE: u8 = 1 << 2;
76    const BACK: u8 = 1 << 3;
77    const FORWARD: u8 = 1 << 4;
78
79    pub const NONE: Self = Self(0);
80
81    pub const fn new(bits: u8) -> Self {
82        Self(bits)
83    }
84
85    pub const fn bits(self) -> u8 {
86        self.0
87    }
88
89    pub const fn is_empty(self) -> bool {
90        self.0 == 0
91    }
92
93    pub const fn contains(self, button: PointerButton) -> bool {
94        match Self::mask(button) {
95            Some(mask) => self.0 & mask != 0,
96            None => false,
97        }
98    }
99
100    pub fn insert(&mut self, button: PointerButton) {
101        if let Some(mask) = Self::mask(button) {
102            self.0 |= mask;
103        }
104    }
105
106    const fn mask(button: PointerButton) -> Option<u8> {
107        match button {
108            PointerButton::Primary => Some(Self::PRIMARY),
109            PointerButton::Secondary => Some(Self::SECONDARY),
110            PointerButton::Middle => Some(Self::MIDDLE),
111            PointerButton::Back => Some(Self::BACK),
112            PointerButton::Forward => Some(Self::FORWARD),
113            PointerButton::Other(_) => None,
114        }
115    }
116}
117
118#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
119pub enum PointerKind {
120    #[default]
121    Mouse,
122    Touch,
123    Pen,
124    Unknown,
125}
126
127#[derive(Debug, Clone, Copy, PartialEq, Eq)]
128pub enum PointerEventKind {
129    Down,
130    Up,
131    Move,
132    Scroll,
133    Enter,
134    Leave,
135    Cancel,
136}
137
138#[derive(Debug, Clone, Copy, PartialEq)]
139pub enum ScrollDelta {
140    Lines(Vector),
141    Pixels(Vector),
142}
143
144#[derive(Debug, Clone, PartialEq)]
145pub struct PointerEvent {
146    pub pointer_id: u64,
147    pub kind: PointerEventKind,
148    pub position: Point,
149    pub delta: Vector,
150    pub scroll_delta: Option<ScrollDelta>,
151    pub button: Option<PointerButton>,
152    pub buttons: PointerButtons,
153    pub modifiers: Modifiers,
154    pub pointer_kind: PointerKind,
155    pub is_primary: bool,
156}
157
158impl PointerEvent {
159    pub fn new(kind: PointerEventKind, position: Point) -> Self {
160        Self {
161            pointer_id: 0,
162            kind,
163            position,
164            delta: Vector::ZERO,
165            scroll_delta: None,
166            button: None,
167            buttons: PointerButtons::NONE,
168            modifiers: Modifiers::NONE,
169            pointer_kind: PointerKind::Mouse,
170            is_primary: true,
171        }
172    }
173}
174
175#[derive(Debug, Clone, Copy, PartialEq)]
176pub enum WakeEvent {
177    Timer {
178        token: TimerToken,
179        time: f64,
180        deadline: f64,
181    },
182    Async {
183        token: AsyncWakeToken,
184        time: f64,
185    },
186    AnimationFrame {
187        time: f64,
188        delta: f64,
189        frame_index: u64,
190    },
191}
192
193#[derive(Debug, Clone, Copy, PartialEq, Eq)]
194pub enum KeyState {
195    Pressed,
196    Released,
197}
198
199#[derive(Debug, Clone, PartialEq)]
200pub struct KeyboardEvent {
201    pub key: String,
202    pub code: String,
203    pub text: Option<String>,
204    pub state: KeyState,
205    pub modifiers: Modifiers,
206    pub repeat: bool,
207    pub is_composing: bool,
208}
209
210impl KeyboardEvent {
211    pub fn new(key: impl Into<String>, state: KeyState) -> Self {
212        let key = key.into();
213
214        Self {
215            code: key.clone(),
216            text: keyboard_text_for_key(&key, state),
217            key,
218            state,
219            modifiers: Modifiers::NONE,
220            repeat: false,
221            is_composing: false,
222        }
223    }
224}
225
226fn keyboard_text_for_key(key: &str, state: KeyState) -> Option<String> {
227    if state != KeyState::Pressed {
228        return None;
229    }
230
231    if key.is_empty() || key.chars().any(char::is_control) {
232        return None;
233    }
234
235    if key.chars().count() == 1 {
236        Some(key.to_string())
237    } else {
238        None
239    }
240}
241
242#[derive(Debug, Clone, PartialEq)]
243pub enum ImeEvent {
244    CompositionStart,
245    CompositionUpdate {
246        text: String,
247        cursor_range: Option<Range<usize>>,
248    },
249    CompositionCommit {
250        text: String,
251    },
252    CompositionEnd,
253}
254
255#[derive(Debug, Clone, PartialEq)]
256pub enum WindowEvent {
257    /// The host target should close. The target is identified by the
258    /// `WindowId` attached to the delivery path rather than by this event.
259    CloseRequested,
260    /// The host target's viewport changed size. The target may be a native
261    /// window or an embedded viewport/region.
262    Resized(Size),
263    /// The native desktop window moved to a new physical desktop position.
264    /// Embedded and web hosts may never emit this event.
265    Moved(Point),
266    ScaleFactorChanged {
267        scale_factor: f64,
268        raw_dpi: Option<f32>,
269        suggested_size: Option<Size>,
270    },
271    /// The unobscured inset from each viewport edge changed, usually after a
272    /// mobile rotation, browser viewport update, or host embedding change.
273    SafeAreaChanged(SafeAreaInsets),
274    Focused(bool),
275    Occluded(bool),
276    /// A file from outside the application is being hovered over the host
277    /// window. Platforms emit one event per file when several files are
278    /// dragged together.
279    ExternalFileHovered(PathBuf),
280    /// Files from outside the application left the host window without being
281    /// dropped.
282    ExternalFileHoverCancelled,
283    /// A file from outside the application was dropped on the host window.
284    /// Platforms emit one event per file when several files are dropped
285    /// together.
286    ExternalFileDropped(PathBuf),
287    RedrawRequested,
288}
289
290#[derive(Debug, Clone, PartialEq)]
291pub struct CustomEvent {
292    pub kind: String,
293    pub payload: Option<String>,
294}
295
296/// An assistive-technology action directed at a semantic node.
297///
298/// The runtime routes this event to the retained widget that owns `target` (or
299/// the nearest graph-backed semantic ancestor for a virtual node). The semantic
300/// target remains in the event so widgets with virtual or generated children
301/// can update their own local state.
302#[derive(Debug, Clone, PartialEq)]
303pub struct SemanticsEvent {
304    pub target: WidgetId,
305    pub action: SemanticsActionRequest,
306}
307
308impl SemanticsEvent {
309    pub fn new(target: WidgetId, action: SemanticsActionRequest) -> Self {
310        Self { target, action }
311    }
312}
313
314impl CustomEvent {
315    pub fn new(kind: impl Into<String>) -> Self {
316        Self {
317            kind: kind.into(),
318            payload: None,
319        }
320    }
321}
322
323#[derive(Debug, Clone, PartialEq)]
324pub enum Event {
325    Pointer(PointerEvent),
326    RawMouseMotion(RawMouseMotionEvent),
327    Drag(DragEvent),
328    Keyboard(KeyboardEvent),
329    Ime(ImeEvent),
330    Semantics(SemanticsEvent),
331    Wake(WakeEvent),
332    /// Window or embedded-viewport lifecycle event. The receiving `WindowId`
333    /// is carried by the platform/runtime call that delivers the event.
334    Window(WindowEvent),
335    Custom(CustomEvent),
336}
337
338#[cfg(test)]
339mod tests {
340    use std::path::PathBuf;
341
342    use super::{WakeEvent, WindowEvent};
343
344    #[test]
345    fn wake_event_animation_frame_carries_time_and_delta() {
346        let event = WakeEvent::AnimationFrame {
347            time: 42.5,
348            delta: 1.0 / 120.0,
349            frame_index: 7,
350        };
351
352        assert!(matches!(
353            event,
354            WakeEvent::AnimationFrame {
355                time,
356                delta,
357                frame_index
358            } if time == 42.5 && delta == 1.0 / 120.0 && frame_index == 7
359        ));
360    }
361
362    #[test]
363    fn external_file_window_events_preserve_paths_and_cancellation() {
364        let path = PathBuf::from(r"C:\workspace\candidate.json");
365
366        let hovered = WindowEvent::ExternalFileHovered(path.clone());
367        let dropped = WindowEvent::ExternalFileDropped(path.clone());
368
369        assert!(matches!(
370            hovered,
371            WindowEvent::ExternalFileHovered(event_path) if event_path == path
372        ));
373        assert!(matches!(
374            dropped,
375            WindowEvent::ExternalFileDropped(event_path) if event_path == path
376        ));
377        assert!(matches!(
378            WindowEvent::ExternalFileHoverCancelled,
379            WindowEvent::ExternalFileHoverCancelled
380        ));
381    }
382}