Skip to main content

cranpose_foundation/nodes/input/
types.rs

1use std::{
2    cell::{Cell, RefCell},
3    rc::Rc,
4};
5
6use cranpose_ui_graphics::{Point, space::Ray};
7
8use super::rotary::RotaryScrollEvent;
9
10/// Identifies one pointer of a gesture, such as one finger, as Compose's `PointerId`. The
11/// primary pointer is [`PointerId::PRIMARY`].
12#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
13pub struct PointerId(pub u64);
14
15impl PointerId {
16    /// The mouse, or the first finger of a touch.
17    pub const PRIMARY: Self = Self(0);
18
19    /// Whether this is [`PointerId::PRIMARY`].
20    pub const fn is_primary(self) -> bool {
21        self.0 == Self::PRIMARY.0
22    }
23}
24
25impl std::fmt::Display for PointerId {
26    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
27        self.0.fmt(f)
28    }
29}
30
31/// When a pointer sample happened, in the clock that timed it, as Compose's
32/// `PointerInputChange.uptimeMillis`. [`PointerEvent::uptime`] gives it.
33///
34/// Times of one clock compare with each other and with no other clock, so a
35/// gesture that measures the time between two events never mixes clocks.
36#[derive(Clone, Copy, Debug, PartialEq, Eq)]
37pub enum PointerUptime {
38    /// The platform's sample time: Android's `MotionEvent` time or the
39    /// browser's event time stamp.
40    Platform {
41        /// Milliseconds in the platform's clock.
42        millis: i64,
43    },
44    /// The frame-clock time at which the shell took the event, on a platform
45    /// that gives no sample time: desktop, iOS and watchOS.
46    FrameClock {
47        /// Nanoseconds in the frame clock.
48        nanos: u64,
49    },
50    /// The time at which a handler read an event that carries neither time,
51    /// such as one built by a test and passed straight to a handler.
52    Delivery {
53        /// Nanoseconds since the first event that a handler timed this way.
54        nanos: u64,
55    },
56}
57
58impl PointerUptime {
59    /// The milliseconds from `earlier` to this time, negative when `earlier`
60    /// is the later one. `None` when the two times come from different clocks.
61    pub fn millis_since(self, earlier: Self) -> Option<i64> {
62        match (self, earlier) {
63            (Self::Platform { millis }, Self::Platform { millis: from }) => Some(millis - from),
64            (Self::FrameClock { nanos }, Self::FrameClock { nanos: from })
65            | (Self::Delivery { nanos }, Self::Delivery { nanos: from }) => {
66                Some(nanos.wrapping_sub(from) as i64 / 1_000_000)
67            }
68            _ => None,
69        }
70    }
71}
72
73fn delivery_nanos() -> u64 {
74    static EPOCH: std::sync::OnceLock<web_time::Instant> = std::sync::OnceLock::new();
75    let elapsed = EPOCH.get_or_init(web_time::Instant::now).elapsed();
76    u64::try_from(elapsed.as_nanos()).unwrap_or(u64::MAX)
77}
78
79type PostDispatchAction = Box<dyn FnOnce() -> bool>;
80
81#[derive(Clone)]
82struct DeferredPostDispatch {
83    action: Rc<RefCell<Option<PostDispatchAction>>>,
84}
85
86impl std::fmt::Debug for DeferredPostDispatch {
87    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
88        formatter
89            .debug_struct("DeferredPostDispatch")
90            .field("is_pending", &self.action.borrow().is_some())
91            .finish()
92    }
93}
94
95/// The phase of a pointer gesture that an event belongs to.
96#[derive(Clone, Copy, Debug, PartialEq, Eq)]
97pub enum PointerPhase {
98    /// The pointer went down.
99    Start,
100    /// The pointer moved, scrolled or hovered.
101    Move,
102    /// The pointer went up.
103    End,
104    /// The system canceled the gesture.
105    Cancel,
106}
107
108/// What a pointer event reports.
109#[derive(Clone, Copy, Debug, PartialEq, Eq)]
110pub enum PointerEventKind {
111    /// A pointer went down: the primary mouse button, a finger or a pen
112    /// touched. Other mouse buttons arrive as
113    /// [`ButtonDown`](Self::ButtonDown).
114    Down,
115    /// A pointer moved.
116    Move,
117    /// A pointer went up: the primary mouse button, a finger or a pen
118    /// lifted.
119    Up,
120    /// A mouse button other than the primary one went down: the right, the
121    /// middle or a side button. A click, a drag or a scroll starts only from
122    /// [`Down`](Self::Down); a handler that takes another button, such as one
123    /// that opens a menu or turns a camera, matches this. The nodes under the
124    /// pointer receive it, or, while another button is down, the nodes that
125    /// took that button's press. Those nodes receive the moves until the
126    /// last button goes up, with the buttons held in
127    /// [`PointerEvent::buttons`].
128    ButtonDown(PointerButton),
129    /// A mouse button other than the primary one went up; see
130    /// [`ButtonDown`](Self::ButtonDown).
131    ButtonUp(PointerButton),
132    /// The system canceled the gesture of the pointer.
133    Cancel,
134    /// A wheel or trackpad scroll. The delta is in [`PointerEvent::scroll_delta`].
135    Scroll,
136    /// Discrete zoom step (desktop ctrl+wheel, browser pinch-trackpad).
137    /// The multiplicative factor is carried in [`PointerEvent::zoom_delta`].
138    Zoom,
139    /// Rotary scroll (Wear OS crown / rotating bezel) during the **capture**
140    /// pass, which runs root-to-focused so ancestors can intercept the event
141    /// before the focused node sees it.
142    ///
143    /// The scroll amounts are carried in [`PointerEvent::scroll_delta`] (`y` =
144    /// vertical pixels, `x` = horizontal pixels) and the rotary uptime in
145    /// [`PointerEvent::time_ms`]; use
146    /// [`PointerEvent::rotary_scroll_event`] to read them back as a
147    /// [`RotaryScrollEvent`]. Mirrors Compose's `onPreRotaryScrollEvent`.
148    RotaryScrollPre,
149    /// Rotary scroll during the **bubble** pass, which runs focused-to-root.
150    /// Mirrors Compose's `onRotaryScrollEvent`.
151    RotaryScroll,
152    /// A pointer began to hover over the receiving node.
153    Enter,
154    /// A pointer stopped hovering over the receiving node.
155    Exit,
156}
157
158impl PointerEventKind {
159    /// Returns true for the two rotary passes.
160    pub fn is_rotary(self) -> bool {
161        matches!(self, Self::RotaryScrollPre | Self::RotaryScroll)
162    }
163}
164
165/// The kind of physical device that produced a pointer event.
166///
167/// Threaded from the platform layer (Android `MotionEvent` tool type, winit
168/// `PointerSource`/`ButtonSource`, web `PointerEvent.pointerType`) so input
169/// consumers can preserve device-specific gesture details while keeping shared
170/// direct-manipulation behavior source-independent.
171#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
172pub enum PointerSource {
173    /// A mouse or other indirect precise pointer (desktop, web `"mouse"`).
174    Mouse,
175    /// A finger on a touchscreen (Android finger, winit touch, web `"touch"`).
176    Touch,
177    /// A stylus/pen (Android stylus/eraser, winit tablet tool, web `"pen"`).
178    Stylus,
179    /// The platform did not report a device type.
180    #[default]
181    Unknown,
182}
183
184impl PointerSource {
185    /// Whether this source is a direct-touch device (finger or stylus), used
186    /// for contact-specific release and velocity semantics.
187    pub fn is_touch_like(self) -> bool {
188        matches!(self, Self::Touch | Self::Stylus)
189    }
190}
191
192/// A button of a mouse or of a similar pointing device.
193#[repr(u8)]
194#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
195pub enum PointerButton {
196    /// The main button, usually the left mouse button.
197    Primary = 0,
198    /// The secondary button, usually the right mouse button.
199    Secondary = 1,
200    /// The middle button, usually a press on the wheel.
201    Middle = 2,
202    /// The back button of a mouse.
203    Back = 3,
204    /// The forward button of a mouse.
205    Forward = 4,
206}
207
208/// A set of pointer buttons that are pressed together.
209#[derive(Clone, Copy, Debug, PartialEq, Eq)]
210pub struct PointerButtons(u8);
211
212impl PointerButtons {
213    /// The set with no button pressed.
214    pub const NONE: Self = Self(0);
215
216    /// Creates a set with no button pressed.
217    pub fn new() -> Self {
218        Self::NONE
219    }
220
221    /// Returns the set with `button` added.
222    pub fn with(mut self, button: PointerButton) -> Self {
223        self.insert(button);
224        self
225    }
226
227    /// Adds `button` to the set.
228    pub fn insert(&mut self, button: PointerButton) {
229        self.0 |= 1 << (button as u8);
230    }
231
232    /// Removes `button` from the set.
233    pub fn remove(&mut self, button: PointerButton) {
234        self.0 &= !(1 << (button as u8));
235    }
236
237    /// Whether `button` is in the set.
238    pub fn contains(&self, button: PointerButton) -> bool {
239        (self.0 & (1 << (button as u8))) != 0
240    }
241}
242
243impl Default for PointerButtons {
244    fn default() -> Self {
245        Self::NONE
246    }
247}
248
249/// Keyboard modifier keys held during an input sample.
250///
251/// Lives here (rather than up in `cranpose-ui`, where the keyboard `KeyEvent`
252/// type lives) because [`PointerEvent`] needs it too and `cranpose-foundation`
253/// sits below `cranpose-ui` in the dependency graph — this is the one crate
254/// both a key event and a pointer event can share it from. `cranpose-ui`
255/// re-exports this type rather than defining its own, so there is exactly one
256/// `Modifiers` in the framework.
257#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
258pub struct Modifiers {
259    /// Shift key is pressed.
260    pub shift: bool,
261    /// Control key is pressed (Cmd on macOS).
262    pub ctrl: bool,
263    /// Alt key is pressed (Option on macOS).
264    pub alt: bool,
265    /// Meta/Super key is pressed (Windows key, Cmd on macOS).
266    pub meta: bool,
267}
268
269impl Modifiers {
270    /// No modifiers pressed.
271    pub const NONE: Self = Self {
272        shift: false,
273        ctrl: false,
274        alt: false,
275        meta: false,
276    };
277
278    /// Shift alone.
279    pub const SHIFT: Self = Self {
280        shift: true,
281        ..Self::NONE
282    };
283
284    /// Control alone.
285    pub const CTRL: Self = Self {
286        ctrl: true,
287        ..Self::NONE
288    };
289
290    /// The platform's command key alone: Cmd on macOS, Control elsewhere,
291    /// the key [`Modifiers::command_or_ctrl`] reads.
292    pub const COMMAND: Self = Self {
293        ctrl: cfg!(not(target_os = "macos")),
294        meta: cfg!(target_os = "macos"),
295        ..Self::NONE
296    };
297
298    /// The keys held in `self` or in `other`.
299    pub const fn union(self, other: Self) -> Self {
300        Self {
301            shift: self.shift || other.shift,
302            ctrl: self.ctrl || other.ctrl,
303            alt: self.alt || other.alt,
304            meta: self.meta || other.meta,
305        }
306    }
307
308    /// Returns true if any modifier is pressed.
309    pub fn any(&self) -> bool {
310        self.shift || self.ctrl || self.alt || self.meta
311    }
312
313    /// Returns true if Ctrl (or Cmd on macOS) is pressed.
314    pub fn command_or_ctrl(&self) -> bool {
315        #[cfg(target_os = "macos")]
316        {
317            self.meta
318        }
319        #[cfg(not(target_os = "macos"))]
320        {
321            self.ctrl
322        }
323    }
324}
325
326/// Pointer event with consumption tracking for gesture disambiguation.
327///
328/// Events can be consumed by handlers (e.g., scroll) to prevent other handlers
329/// (e.g., clicks) from receiving them. This enables proper gesture disambiguation
330/// matching Jetpack Compose's event consumption pattern.
331#[derive(Clone, Debug)]
332pub struct PointerEvent {
333    /// The pointer this event belongs to. `0` is the primary pointer.
334    pub id: PointerId,
335    /// What happened to the pointer.
336    pub kind: PointerEventKind,
337    /// The phase of the gesture that the event belongs to, which follows from `kind`.
338    pub phase: PointerPhase,
339    /// Where the pointer is, in logical pixels, in the coordinates of the node that receives the
340    /// event.
341    pub position: Point,
342    /// Where the pointer is, in logical pixels, in the coordinates of the composition root.
343    pub global_position: Point,
344    /// Where the pointer is on the screen, in logical pixels, when the
345    /// platform told the shell where the window drawing this event's root
346    /// sits. `None` on platforms without window positions and for events a
347    /// test dispatches without one. A gesture that crosses windows, such as
348    /// a tab torn out of one window and dropped on another, compares this
349    /// with the windows' positions instead of translating `global_position`
350    /// itself.
351    pub screen_position: Option<Point>,
352    /// Scroll delta in logical pixels.
353    ///
354    /// This is non-zero for [`PointerEventKind::Scroll`] events and zero for
355    /// button/move events.
356    pub scroll_delta: Point,
357    /// The buttons that are pressed at the time of this event.
358    pub buttons: PointerButtons,
359    /// Platform timestamp of the input sample in milliseconds, when available.
360    ///
361    /// The time base is platform specific (e.g. Android's uptime clock); only
362    /// differences between events of the same gesture are meaningful. Gesture
363    /// velocity trackers must prefer this over the delivery time because
364    /// platforms like Android deliver input batched/frame-aligned: several
365    /// samples arrive back-to-back and delivery-time stamping makes computed
366    /// velocities wildly wrong.
367    pub time_ms: Option<i64>,
368    /// Timestamp in the animation frame-clock domain at input dispatch.
369    /// Unlike `time_ms`, this has the same origin as frame callbacks and can
370    /// anchor input-driven animations without a wall/platform clock conversion.
371    pub animation_time_nanos: Option<u64>,
372    /// Multiplicative zoom factor for [`PointerEventKind::Zoom`] events
373    /// (`> 1.0` zooms in, `< 1.0` zooms out). `1.0` for all other events.
374    pub zoom_delta: f32,
375    /// The kind of device that produced this event (touch, mouse, stylus), when
376    /// the platform reports it. Defaults to [`PointerSource::Unknown`].
377    pub source: PointerSource,
378    /// Keyboard modifiers held at the time of this sample, when the platform
379    /// can report them.
380    ///
381    /// `None` means the platform never told the shell what the keyboard state
382    /// was — touch-only Android/iOS input has no channel for it today — and is
383    /// deliberately distinct from `Some(Modifiers::NONE)`, which means the
384    /// platform looked and nothing was held. An app that wants shift/ctrl-click
385    /// multi-select reads this field directly; it must not treat `None` as
386    /// "nothing held" or it silently drops the gesture on the platforms that
387    /// cannot yet report it instead of visibly doing nothing.
388    pub modifiers: Option<Modifiers>,
389    /// For a pointer that points along a ray in a 3D scene from somewhere
390    /// other than the window's eye (a controller, a hand, a gaze), the ray,
391    /// in the space the scene's eye stands in. A target on a mesh surface
392    /// finds the event's position where the ray meets the surface, in place
393    /// of where `global_position` shows. `None` for a pointer on the window.
394    pub ray: Option<Ray>,
395    consumed: Rc<Cell<bool>>,
396    deferred_post_dispatch: DeferredPostDispatch,
397}
398
399impl PointerEvent {
400    /// Creates an event of `kind` at `position`, in the coordinates of the receiving node, and at
401    /// `global_position`, in the coordinates of the composition root. The pointer is
402    /// [`PointerId::PRIMARY`] and the other fields have neutral values.
403    pub fn new(kind: PointerEventKind, position: Point, global_position: Point) -> Self {
404        Self {
405            id: PointerId::PRIMARY,
406            kind,
407            phase: match kind {
408                PointerEventKind::Down => PointerPhase::Start,
409                PointerEventKind::Move
410                | PointerEventKind::Enter
411                | PointerEventKind::Exit
412                | PointerEventKind::ButtonDown(_)
413                | PointerEventKind::ButtonUp(_) => PointerPhase::Move,
414                PointerEventKind::Up => PointerPhase::End,
415                PointerEventKind::Cancel => PointerPhase::Cancel,
416                PointerEventKind::Scroll
417                | PointerEventKind::Zoom
418                | PointerEventKind::RotaryScrollPre
419                | PointerEventKind::RotaryScroll => PointerPhase::Move,
420            },
421            position,
422            global_position,
423            screen_position: None,
424            scroll_delta: Point { x: 0.0, y: 0.0 },
425            buttons: PointerButtons::NONE,
426            time_ms: None,
427            animation_time_nanos: None,
428            zoom_delta: 1.0,
429            source: PointerSource::Unknown,
430            modifiers: None,
431            ray: None,
432            consumed: Rc::new(Cell::new(false)),
433            deferred_post_dispatch: DeferredPostDispatch {
434                action: Rc::new(RefCell::new(None)),
435            },
436        }
437    }
438
439    /// Set the pointer id for this event (`0` is the primary pointer).
440    pub fn with_id(mut self, id: PointerId) -> Self {
441        self.id = id;
442        self
443    }
444
445    /// Set the ray a pointer in a 3D scene points along (see
446    /// [`PointerEvent::ray`]).
447    pub fn with_ray(mut self, ray: Ray) -> Self {
448        self.ray = Some(ray);
449        self
450    }
451
452    /// Set the multiplicative zoom factor for a [`PointerEventKind::Zoom`] event.
453    pub fn with_zoom_delta(mut self, zoom_delta: f32) -> Self {
454        self.zoom_delta = zoom_delta;
455        self
456    }
457
458    /// Set the scroll delta for this event.
459    pub fn with_scroll_delta(mut self, scroll_delta: Point) -> Self {
460        self.scroll_delta = scroll_delta;
461        self
462    }
463
464    /// Set the platform timestamp (milliseconds) for this event.
465    pub fn with_time_ms(mut self, time_ms: Option<i64>) -> Self {
466        self.time_ms = time_ms;
467        self
468    }
469
470    /// Set the timestamp in the animation frame-clock domain.
471    pub fn with_animation_time_nanos(mut self, time_nanos: u64) -> Self {
472        self.animation_time_nanos = Some(time_nanos);
473        self
474    }
475
476    /// When this sample happened: the platform's sample time where the
477    /// platform gives one, else the frame-clock time at which the shell took
478    /// the event, else the time of this call. A gesture that counts taps or
479    /// measures a hold compares these, so a busy main thread that delivers
480    /// events late or in a batch does not change what the gesture was.
481    pub fn uptime(&self) -> PointerUptime {
482        match (self.time_ms, self.animation_time_nanos) {
483            (Some(millis), _) => PointerUptime::Platform { millis },
484            (None, Some(nanos)) => PointerUptime::FrameClock { nanos },
485            (None, None) => PointerUptime::Delivery {
486                nanos: delivery_nanos(),
487            },
488        }
489    }
490
491    /// Set where the pointer is on the screen, when the platform knows.
492    pub fn with_screen_position(mut self, screen_position: Option<Point>) -> Self {
493        self.screen_position = screen_position;
494        self
495    }
496
497    /// Where the pointer is in the steadiest frame the platform offers: on
498    /// the screen where it reports window positions, and in the composition
499    /// where it does not.
500    ///
501    /// Two events compared this way say how far the hand travelled even when
502    /// the window under it travelled too, which is what a drag threshold has
503    /// to measure: a press that drags a borderless window never moves within
504    /// that window, because the window follows it.
505    pub fn travelled_to(&self) -> Point {
506        self.screen_position.unwrap_or(self.global_position)
507    }
508
509    /// Set the buttons state for this event
510    pub fn with_buttons(mut self, buttons: PointerButtons) -> Self {
511        self.buttons = buttons;
512        self
513    }
514
515    /// Set the device source (touch/mouse/stylus) for this event.
516    pub fn with_source(mut self, source: PointerSource) -> Self {
517        self.source = source;
518        self
519    }
520
521    /// Set the keyboard modifiers held during this event, when the platform
522    /// can report them. See the [`modifiers`](Self::modifiers) field docs for
523    /// why this takes a concrete [`Modifiers`] rather than an `Option`: the
524    /// `None` case is the *absence* of a call to this builder, not a value it
525    /// produces.
526    pub fn with_modifiers(mut self, modifiers: Modifiers) -> Self {
527        self.modifiers = Some(modifiers);
528        self
529    }
530
531    /// Builds a rotary pointer event for one dispatch pass.
532    ///
533    /// `kind` must be [`PointerEventKind::RotaryScrollPre`] (capture) or
534    /// [`PointerEventKind::RotaryScroll`] (bubble). The rotary payload rides on
535    /// the existing `scroll_delta`/`time_ms` fields so rotary reuses the
536    /// pointer dispatch path without widening [`PointerEvent`].
537    pub fn rotary(kind: PointerEventKind, rotary: RotaryScrollEvent, position: Point) -> Self {
538        debug_assert!(
539            kind.is_rotary(),
540            "PointerEvent::rotary requires a rotary event kind"
541        );
542        Self::new(kind, position, position)
543            .with_scroll_delta(Point {
544                x: rotary.horizontal_scroll_pixels,
545                y: rotary.vertical_scroll_pixels,
546            })
547            .with_time_ms(Some(rotary.uptime_millis as i64))
548    }
549
550    /// Reads this event back as a [`RotaryScrollEvent`], or `None` when it is
551    /// not a rotary event.
552    ///
553    /// Copies three scalars out of the event; it never allocates.
554    pub fn rotary_scroll_event(&self) -> Option<RotaryScrollEvent> {
555        if !self.kind.is_rotary() {
556            return None;
557        }
558        Some(RotaryScrollEvent {
559            vertical_scroll_pixels: self.scroll_delta.y,
560            horizontal_scroll_pixels: self.scroll_delta.x,
561            uptime_millis: self.time_ms.unwrap_or(0).max(0) as u64,
562        })
563    }
564
565    /// Mark this event as consumed, preventing other handlers from processing it.
566    ///
567    /// Example: Scroll gestures consume events once dragging starts to prevent
568    /// child buttons from firing clicks.
569    pub fn consume(&self) {
570        self.consumed.set(true);
571    }
572
573    /// Check if this event has been consumed by another handler.
574    ///
575    /// Handlers should check this before processing events. For example,
576    /// clickable should not fire if the event was consumed by a scroll gesture.
577    pub fn is_consumed(&self) -> bool {
578        self.consumed.get()
579    }
580
581    /// Stores `action` to run once after every handler saw the event. It runs only when no handler
582    /// consumed the event, and when it returns `true` the event becomes consumed. A later call
583    /// replaces the stored action.
584    pub fn defer_post_dispatch_action<F>(&self, action: F)
585    where
586        F: FnOnce() -> bool + 'static,
587    {
588        *self.deferred_post_dispatch.action.borrow_mut() = Some(Box::new(action));
589    }
590
591    /// Runs the action stored by `defer_post_dispatch_action`, unless a handler consumed the event;
592    /// then the action is dropped. The shell calls this after it dispatched the event to all
593    /// targets.
594    pub fn finish_post_dispatch(&self) {
595        if self.is_consumed() {
596            self.deferred_post_dispatch.action.borrow_mut().take();
597            return;
598        }
599
600        let Some(action) = self.deferred_post_dispatch.action.borrow_mut().take() else {
601            return;
602        };
603        if action() {
604            self.consume();
605        }
606    }
607
608    /// Creates a copy of this event with a new local position, sharing the consumption state.
609    pub fn copy_with_local_position(&self, position: Point) -> Self {
610        Self {
611            id: self.id,
612            kind: self.kind,
613            phase: self.phase,
614            position,
615            global_position: self.global_position,
616            screen_position: self.screen_position,
617            scroll_delta: self.scroll_delta,
618            buttons: self.buttons,
619            time_ms: self.time_ms,
620            animation_time_nanos: self.animation_time_nanos,
621            zoom_delta: self.zoom_delta,
622            source: self.source,
623            modifiers: self.modifiers,
624            ray: self.ray,
625            consumed: Rc::clone(&self.consumed),
626            deferred_post_dispatch: self.deferred_post_dispatch.clone(),
627        }
628    }
629}
630
631#[cfg(test)]
632#[path = "tests/types_tests.rs"]
633mod tests;