Skip to main content

nativeview_engine/ext/input/
pointer.rs

1//! Shared `TARGET_LOCAL_NORM` annotation: pointer coordinates normalized to the box of the
2//! pointer's *owner*, so a slider track maps a drag 1:1 even while the pointer is outside it or
3//! the track is scrolled or transformed. The box comes from a [`PointerGeometry`] (the laid-out
4//! scene for `SurfaceRuntime` hosts, live Skia visual rects in the desktop shell, DOM rects on
5//! the Web); events that already carry a norm are left untouched.
6
7use nativeview_abi::{EventBatchBuf, EventFlags, EventSet, InteractionEvent, LayoutEvent, NodeId};
8use nativeview_store::{NodeStore, NvTable};
9use nativeview_tables::tables::{Interaction, Layout, PointerCaptureMode};
10
11use super::PointerGeometry;
12
13/// The one capture-owner walk every host shares: the nearest `capture_on_primary_down`
14/// ancestor-or-self of `target`, or `None` when there is none or `target` lies in a disabled
15/// subtree (a disabled ancestor anywhere up to the root disables capture, as `:disabled`
16/// inherits). One `O(depth)` walk.
17pub fn capture_owner(store: &NodeStore, target: NodeId) -> Option<NodeId> {
18    let mut owner = None;
19    let mut cur = target;
20    for _ in 0..nativeview_store::MAX_TREE_DEPTH {
21        if let Some(i) = store.try_row::<Interaction>(cur) {
22            if i.disabled() {
23                return None;
24            }
25            if owner.is_none() && i.capture_mode() == PointerCaptureMode::OnPrimaryDown {
26                owner = Some(cur);
27            }
28        }
29        match store.parent(cur) {
30            Some(p) if p != cur => cur = p,
31            _ => break,
32        }
33    }
34    owner
35}
36
37/// The node whose box a pointer event's norm is relative to: the [`capture_owner`] of the target
38/// (the control that captures, or already captured, the drag: captured events target that owner,
39/// a capturing `PointerDown` may target a child such as a thumb), else the target itself.
40#[inline]
41pub fn pointer_norm_owner(store: &NodeStore, target: NodeId) -> NodeId {
42    capture_owner(store, target).unwrap_or(target)
43}
44
45/// `id` itself listens for `ev` on the `Interaction` table.
46#[inline]
47pub fn has_direct_listener(store: &NodeStore, id: NodeId, ev: InteractionEvent) -> bool {
48    store.try_row::<Interaction>(id).is_some_and(|i| i.listeners().contains(ev))
49}
50
51/// `start` or an ancestor listens for `ev` (a bubbling event reaches a listener).
52pub fn has_ancestor_listener(store: &NodeStore, start: NodeId, ev: InteractionEvent) -> bool {
53    let mut cur = start;
54    for _ in 0..nativeview_store::MAX_TREE_DEPTH {
55        if has_direct_listener(store, cur, ev) {
56            return true;
57        }
58        match store.parent(cur) {
59            Some(p) if p != cur => cur = p,
60            _ => return false,
61        }
62    }
63    false
64}
65
66#[inline]
67const fn carries_position(kind: InteractionEvent) -> bool {
68    matches!(
69        kind,
70        InteractionEvent::PointerDown | InteractionEvent::PointerMove | InteractionEvent::PointerUp
71    )
72}
73
74/// `(x, y)` normalized to `owner`'s box in `geometry`; `None` without a usable box.
75#[inline]
76pub fn local_norm<G: PointerGeometry + ?Sized>(
77    geometry: &G,
78    owner: NodeId,
79    x: f32,
80    y: f32,
81) -> Option<(f32, f32)> {
82    let r = geometry.local_rect(owner)?;
83    nativeview_abi::target_local_norm(r.x, r.y, r.width, r.height, x, y)
84}
85
86/// Whether any pointer event of `events` still lacks a norm (callers copy a borrowed batch only
87/// then).
88pub fn needs_pointer_norms(events: nativeview_abi::ValidatedEvents<'_>) -> bool {
89    events.iter().any(|ev| {
90        ev.interaction().is_some_and(carries_position)
91            && !ev.flags().contains(EventFlags::TARGET_LOCAL_NORM)
92    })
93}
94
95/// Attaches norms in place to every positioned pointer event (`PointerDown` / `Move` / `Up`)
96/// that lacks one: one [`PointerGeometry::local_rect`] call per such event, none otherwise.
97/// When a `PointerDown` targets an owner subscribed to [`LayoutEvent::Layout`], inserts the
98/// owner's live visual rect immediately ahead of that `PointerDown` so handlers reading both
99/// layout bounds and pointer norms see exact geometry. Allocation-free when no `Layout` event is
100/// inserted.
101pub fn annotate_pointer_norms<G: PointerGeometry + ?Sized>(
102    store: &NodeStore,
103    events: &mut EventBatchBuf,
104    geometry: &G,
105) {
106    let mut index = 0usize;
107    while index < events.len() {
108        let Some(ev) = events.as_validated().get(index) else {
109            break;
110        };
111        let Some(kind) = ev.interaction().filter(|&k| carries_position(k)) else {
112            index += 1;
113            continue;
114        };
115        let needs_norm = !ev.flags().contains(EventFlags::TARGET_LOCAL_NORM);
116        let owner = pointer_norm_owner(store, ev.node());
117        let needs_layout = kind == InteractionEvent::PointerDown
118            && EventSet::<LayoutEvent>::from_raw(store.node_events_mask(Layout::slot(), owner))
119                .contains(LayoutEvent::Layout);
120        if !needs_norm && !needs_layout {
121            index += 1;
122            continue;
123        }
124        let (surface, ts, x, y) = (ev.surface(), ev.timestamp(), ev.x(), ev.y());
125        if let Some(r) = geometry.local_rect(owner) {
126            if needs_norm
127                && let Some((nx, ny)) = nativeview_abi::target_local_norm(r.x, r.y, r.width, r.height, x, y)
128            {
129                events.set_target_local_norm(index, nx, ny);
130            }
131            if needs_layout && r.width.is_finite() && r.height.is_finite() && r.width > 0.0 && r.height > 0.0 {
132                events.insert_layout_before(index, surface, owner, ts, r.x, r.y, r.width, r.height);
133                index += 1;
134            }
135        }
136        index += 1;
137    }
138}