cranpose-foundation 0.12.0

Modifier-node, input, focus, text and semantics contracts for Cranpose UI
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
use std::{
    cell::{Cell, RefCell},
    rc::Rc,
};

use cranpose_ui_graphics::Point;

use super::rotary::RotaryScrollEvent;

/// Identifies one pointer of a gesture, such as one finger. `0` is the primary pointer.
pub type PointerId = u64;

type PostDispatchAction = Box<dyn FnOnce() -> bool>;

#[derive(Clone)]
struct DeferredPostDispatch {
    action: Rc<RefCell<Option<PostDispatchAction>>>,
}

impl std::fmt::Debug for DeferredPostDispatch {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter
            .debug_struct("DeferredPostDispatch")
            .field("is_pending", &self.action.borrow().is_some())
            .finish()
    }
}

/// The phase of a pointer gesture that an event belongs to.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum PointerPhase {
    /// The pointer went down.
    Start,
    /// The pointer moved, scrolled or hovered.
    Move,
    /// The pointer went up.
    End,
    /// The system canceled the gesture.
    Cancel,
}

/// What a pointer event reports.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum PointerEventKind {
    /// A pointer went down: a mouse button, a finger or a pen touched.
    Down,
    /// A pointer moved.
    Move,
    /// A pointer went up.
    Up,
    /// The system canceled the gesture of the pointer.
    Cancel,
    /// A wheel or trackpad scroll. The delta is in [`PointerEvent::scroll_delta`].
    Scroll,
    /// Discrete zoom step (desktop ctrl+wheel, browser pinch-trackpad).
    /// The multiplicative factor is carried in [`PointerEvent::zoom_delta`].
    Zoom,
    /// Rotary scroll (Wear OS crown / rotating bezel) during the **capture**
    /// pass, which runs root-to-focused so ancestors can intercept the event
    /// before the focused node sees it.
    ///
    /// The scroll amounts are carried in [`PointerEvent::scroll_delta`] (`y` =
    /// vertical pixels, `x` = horizontal pixels) and the rotary uptime in
    /// [`PointerEvent::time_ms`]; use
    /// [`PointerEvent::rotary_scroll_event`] to read them back as a
    /// [`RotaryScrollEvent`]. Mirrors Compose's `onPreRotaryScrollEvent`.
    RotaryScrollPre,
    /// Rotary scroll during the **bubble** pass, which runs focused-to-root.
    /// Mirrors Compose's `onRotaryScrollEvent`.
    RotaryScroll,
    /// A pointer began to hover over the receiving node.
    Enter,
    /// A pointer stopped hovering over the receiving node.
    Exit,
}

impl PointerEventKind {
    /// Returns true for the two rotary passes.
    pub fn is_rotary(self) -> bool {
        matches!(self, Self::RotaryScrollPre | Self::RotaryScroll)
    }
}

/// The kind of physical device that produced a pointer event.
///
/// Threaded from the platform layer (Android `MotionEvent` tool type, winit
/// `PointerSource`/`ButtonSource`, web `PointerEvent.pointerType`) so input
/// consumers can preserve device-specific gesture details while keeping shared
/// direct-manipulation behavior source-independent.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum PointerSource {
    /// A mouse or other indirect precise pointer (desktop, web `"mouse"`).
    Mouse,
    /// A finger on a touchscreen (Android finger, winit touch, web `"touch"`).
    Touch,
    /// A stylus/pen (Android stylus/eraser, winit tablet tool, web `"pen"`).
    Stylus,
    /// The platform did not report a device type.
    #[default]
    Unknown,
}

impl PointerSource {
    /// Whether this source is a direct-touch device (finger or stylus), used
    /// for contact-specific release and velocity semantics.
    pub fn is_touch_like(self) -> bool {
        matches!(self, PointerSource::Touch | PointerSource::Stylus)
    }
}

/// A button of a mouse or of a similar pointing device.
#[repr(u8)]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum PointerButton {
    /// The main button, usually the left mouse button.
    Primary = 0,
    /// The secondary button, usually the right mouse button.
    Secondary = 1,
    /// The middle button, usually a press on the wheel.
    Middle = 2,
    /// The back button of a mouse.
    Back = 3,
    /// The forward button of a mouse.
    Forward = 4,
}

/// A set of pointer buttons that are pressed together.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct PointerButtons(u8);

impl PointerButtons {
    /// The set with no button pressed.
    pub const NONE: Self = Self(0);

    /// Creates a set with no button pressed.
    pub fn new() -> Self {
        Self::NONE
    }

    /// Returns the set with `button` added.
    pub fn with(mut self, button: PointerButton) -> Self {
        self.insert(button);
        self
    }

    /// Adds `button` to the set.
    pub fn insert(&mut self, button: PointerButton) {
        self.0 |= 1 << (button as u8);
    }

    /// Removes `button` from the set.
    pub fn remove(&mut self, button: PointerButton) {
        self.0 &= !(1 << (button as u8));
    }

    /// Whether `button` is in the set.
    pub fn contains(&self, button: PointerButton) -> bool {
        (self.0 & (1 << (button as u8))) != 0
    }
}

impl Default for PointerButtons {
    fn default() -> Self {
        Self::NONE
    }
}

/// Keyboard modifier keys held during an input sample.
///
/// Lives here (rather than up in `cranpose-ui`, where the keyboard `KeyEvent`
/// type lives) because [`PointerEvent`] needs it too and `cranpose-foundation`
/// sits below `cranpose-ui` in the dependency graph — this is the one crate
/// both a key event and a pointer event can share it from. `cranpose-ui`
/// re-exports this type rather than defining its own, so there is exactly one
/// `Modifiers` in the framework.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct Modifiers {
    /// Shift key is pressed.
    pub shift: bool,
    /// Control key is pressed (Cmd on macOS).
    pub ctrl: bool,
    /// Alt key is pressed (Option on macOS).
    pub alt: bool,
    /// Meta/Super key is pressed (Windows key, Cmd on macOS).
    pub meta: bool,
}

impl Modifiers {
    /// No modifiers pressed.
    pub const NONE: Modifiers = Modifiers {
        shift: false,
        ctrl: false,
        alt: false,
        meta: false,
    };

    /// Returns true if any modifier is pressed.
    pub fn any(&self) -> bool {
        self.shift || self.ctrl || self.alt || self.meta
    }

    /// Returns true if Ctrl (or Cmd on macOS) is pressed.
    pub fn command_or_ctrl(&self) -> bool {
        #[cfg(target_os = "macos")]
        {
            self.meta
        }
        #[cfg(not(target_os = "macos"))]
        {
            self.ctrl
        }
    }
}

/// Pointer event with consumption tracking for gesture disambiguation.
///
/// Events can be consumed by handlers (e.g., scroll) to prevent other handlers
/// (e.g., clicks) from receiving them. This enables proper gesture disambiguation
/// matching Jetpack Compose's event consumption pattern.
#[derive(Clone, Debug)]
pub struct PointerEvent {
    /// The pointer this event belongs to. `0` is the primary pointer.
    pub id: PointerId,
    /// What happened to the pointer.
    pub kind: PointerEventKind,
    /// The phase of the gesture that the event belongs to, which follows from `kind`.
    pub phase: PointerPhase,
    /// Where the pointer is, in logical pixels, in the coordinates of the node that receives the
    /// event.
    pub position: Point,
    /// Where the pointer is, in logical pixels, in the coordinates of the composition root.
    pub global_position: Point,
    /// Where the pointer is on the screen, in logical pixels, when the
    /// platform told the shell where the window drawing this event's root
    /// sits. `None` on platforms without window positions and for events a
    /// test dispatches without one. A gesture that crosses windows, such as
    /// a tab torn out of one window and dropped on another, compares this
    /// with the windows' positions instead of translating `global_position`
    /// itself.
    pub screen_position: Option<Point>,
    /// Scroll delta in logical pixels.
    ///
    /// This is non-zero for [`PointerEventKind::Scroll`] events and zero for
    /// button/move events.
    pub scroll_delta: Point,
    /// The buttons that are pressed at the time of this event.
    pub buttons: PointerButtons,
    /// Platform timestamp of the input sample in milliseconds, when available.
    ///
    /// The time base is platform specific (e.g. Android's uptime clock); only
    /// differences between events of the same gesture are meaningful. Gesture
    /// velocity trackers must prefer this over the delivery time because
    /// platforms like Android deliver input batched/frame-aligned: several
    /// samples arrive back-to-back and delivery-time stamping makes computed
    /// velocities wildly wrong.
    pub time_ms: Option<i64>,
    /// Timestamp in the animation frame-clock domain at input dispatch.
    /// Unlike `time_ms`, this has the same origin as frame callbacks and can
    /// anchor input-driven animations without a wall/platform clock conversion.
    pub animation_time_nanos: Option<u64>,
    /// Multiplicative zoom factor for [`PointerEventKind::Zoom`] events
    /// (`> 1.0` zooms in, `< 1.0` zooms out). `1.0` for all other events.
    pub zoom_delta: f32,
    /// The kind of device that produced this event (touch, mouse, stylus), when
    /// the platform reports it. Defaults to [`PointerSource::Unknown`].
    pub source: PointerSource,
    /// Keyboard modifiers held at the time of this sample, when the platform
    /// can report them.
    ///
    /// `None` means the platform never told the shell what the keyboard state
    /// was — touch-only Android/iOS input has no channel for it today — and is
    /// deliberately distinct from `Some(Modifiers::NONE)`, which means the
    /// platform looked and nothing was held. An app that wants shift/ctrl-click
    /// multi-select reads this field directly; it must not treat `None` as
    /// "nothing held" or it silently drops the gesture on the platforms that
    /// cannot yet report it instead of visibly doing nothing.
    pub modifiers: Option<Modifiers>,
    consumed: Rc<Cell<bool>>,
    deferred_post_dispatch: DeferredPostDispatch,
}

impl PointerEvent {
    /// Creates an event of `kind` at `position`, in the coordinates of the receiving node, and at
    /// `global_position`, in the coordinates of the composition root. The pointer id is `0` and the
    /// other fields have neutral values.
    pub fn new(kind: PointerEventKind, position: Point, global_position: Point) -> Self {
        Self {
            id: 0,
            kind,
            phase: match kind {
                PointerEventKind::Down => PointerPhase::Start,
                PointerEventKind::Move | PointerEventKind::Enter | PointerEventKind::Exit => {
                    PointerPhase::Move
                }
                PointerEventKind::Up => PointerPhase::End,
                PointerEventKind::Cancel => PointerPhase::Cancel,
                PointerEventKind::Scroll
                | PointerEventKind::Zoom
                | PointerEventKind::RotaryScrollPre
                | PointerEventKind::RotaryScroll => PointerPhase::Move,
            },
            position,
            global_position,
            screen_position: None,
            scroll_delta: Point { x: 0.0, y: 0.0 },
            buttons: PointerButtons::NONE,
            time_ms: None,
            animation_time_nanos: None,
            zoom_delta: 1.0,
            source: PointerSource::Unknown,
            modifiers: None,
            consumed: Rc::new(Cell::new(false)),
            deferred_post_dispatch: DeferredPostDispatch {
                action: Rc::new(RefCell::new(None)),
            },
        }
    }

    /// Set the pointer id for this event (`0` is the primary pointer).
    pub fn with_id(mut self, id: PointerId) -> Self {
        self.id = id;
        self
    }

    /// Set the multiplicative zoom factor for a [`PointerEventKind::Zoom`] event.
    pub fn with_zoom_delta(mut self, zoom_delta: f32) -> Self {
        self.zoom_delta = zoom_delta;
        self
    }

    /// Set the scroll delta for this event.
    pub fn with_scroll_delta(mut self, scroll_delta: Point) -> Self {
        self.scroll_delta = scroll_delta;
        self
    }

    /// Set the platform timestamp (milliseconds) for this event.
    pub fn with_time_ms(mut self, time_ms: Option<i64>) -> Self {
        self.time_ms = time_ms;
        self
    }

    /// Set the timestamp in the animation frame-clock domain.
    pub fn with_animation_time_nanos(mut self, time_nanos: u64) -> Self {
        self.animation_time_nanos = Some(time_nanos);
        self
    }

    /// Set where the pointer is on the screen, when the platform knows.
    pub fn with_screen_position(mut self, screen_position: Option<Point>) -> Self {
        self.screen_position = screen_position;
        self
    }

    /// Where the pointer is in the steadiest frame the platform offers: on
    /// the screen where it reports window positions, and in the composition
    /// where it does not.
    ///
    /// Two events compared this way say how far the hand travelled even when
    /// the window under it travelled too, which is what a drag threshold has
    /// to measure: a press that drags a borderless window never moves within
    /// that window, because the window follows it.
    pub fn travelled_to(&self) -> Point {
        self.screen_position.unwrap_or(self.global_position)
    }

    /// Set the buttons state for this event
    pub fn with_buttons(mut self, buttons: PointerButtons) -> Self {
        self.buttons = buttons;
        self
    }

    /// Set the device source (touch/mouse/stylus) for this event.
    pub fn with_source(mut self, source: PointerSource) -> Self {
        self.source = source;
        self
    }

    /// Set the keyboard modifiers held during this event, when the platform
    /// can report them. See the [`modifiers`](Self::modifiers) field docs for
    /// why this takes a concrete [`Modifiers`] rather than an `Option`: the
    /// `None` case is the *absence* of a call to this builder, not a value it
    /// produces.
    pub fn with_modifiers(mut self, modifiers: Modifiers) -> Self {
        self.modifiers = Some(modifiers);
        self
    }

    /// Builds a rotary pointer event for one dispatch pass.
    ///
    /// `kind` must be [`PointerEventKind::RotaryScrollPre`] (capture) or
    /// [`PointerEventKind::RotaryScroll`] (bubble). The rotary payload rides on
    /// the existing `scroll_delta`/`time_ms` fields so rotary reuses the
    /// pointer dispatch path without widening [`PointerEvent`].
    pub fn rotary(kind: PointerEventKind, rotary: RotaryScrollEvent, position: Point) -> Self {
        debug_assert!(
            kind.is_rotary(),
            "PointerEvent::rotary requires a rotary event kind"
        );
        Self::new(kind, position, position)
            .with_scroll_delta(Point {
                x: rotary.horizontal_scroll_pixels,
                y: rotary.vertical_scroll_pixels,
            })
            .with_time_ms(Some(rotary.uptime_millis as i64))
    }

    /// Reads this event back as a [`RotaryScrollEvent`], or `None` when it is
    /// not a rotary event.
    ///
    /// Copies three scalars out of the event; it never allocates.
    pub fn rotary_scroll_event(&self) -> Option<RotaryScrollEvent> {
        if !self.kind.is_rotary() {
            return None;
        }
        Some(RotaryScrollEvent {
            vertical_scroll_pixels: self.scroll_delta.y,
            horizontal_scroll_pixels: self.scroll_delta.x,
            uptime_millis: self.time_ms.unwrap_or(0).max(0) as u64,
        })
    }

    /// Mark this event as consumed, preventing other handlers from processing it.
    ///
    /// Example: Scroll gestures consume events once dragging starts to prevent
    /// child buttons from firing clicks.
    pub fn consume(&self) {
        self.consumed.set(true);
    }

    /// Check if this event has been consumed by another handler.
    ///
    /// Handlers should check this before processing events. For example,
    /// clickable should not fire if the event was consumed by a scroll gesture.
    pub fn is_consumed(&self) -> bool {
        self.consumed.get()
    }

    /// Stores `action` to run once after every handler saw the event. It runs only when no handler
    /// consumed the event, and when it returns `true` the event becomes consumed. A later call
    /// replaces the stored action.
    pub fn defer_post_dispatch_action<F>(&self, action: F)
    where
        F: FnOnce() -> bool + 'static,
    {
        *self.deferred_post_dispatch.action.borrow_mut() = Some(Box::new(action));
    }

    /// Runs the action stored by `defer_post_dispatch_action`, unless a handler consumed the event;
    /// then the action is dropped. The shell calls this after it dispatched the event to all
    /// targets.
    pub fn finish_post_dispatch(&self) {
        if self.is_consumed() {
            self.deferred_post_dispatch.action.borrow_mut().take();
            return;
        }

        let Some(action) = self.deferred_post_dispatch.action.borrow_mut().take() else {
            return;
        };
        if action() {
            self.consume();
        }
    }

    /// Creates a copy of this event with a new local position, sharing the consumption state.
    pub fn copy_with_local_position(&self, position: Point) -> Self {
        Self {
            id: self.id,
            kind: self.kind,
            phase: self.phase,
            position,
            global_position: self.global_position,
            screen_position: self.screen_position,
            scroll_delta: self.scroll_delta,
            buttons: self.buttons,
            time_ms: self.time_ms,
            animation_time_nanos: self.animation_time_nanos,
            zoom_delta: self.zoom_delta,
            source: self.source,
            modifiers: self.modifiers,
            consumed: self.consumed.clone(),
            deferred_post_dispatch: self.deferred_post_dispatch.clone(),
        }
    }
}

#[cfg(test)]
#[path = "tests/types_tests.rs"]
mod tests;