Skip to main content

nativeview_layout/scene/pointer/
resolve.rs

1//! [`LaidOutScene::apply_pointer`]: the mutating half of core pointer resolution (see the
2//! parent module docs).
3
4use nativeview_abi::{
5    EventBatchBuf, EventFlags, InteractionEvent, NodeId, ValidatedEvent, NV_POINTER_ID_ALL,
6};
7use nativeview_engine::ext::input::{has_ancestor_listener, has_direct_listener};
8use nativeview_engine::tracker::{CaptureError, PointerCaptureRequest, PointerKey, PointerSlot};
9use nativeview_store::NodeStore;
10
11use super::{PointerOutcomeFlags, PointerProbe, PointerResolution};
12use crate::StoreLayoutEngine;
13use crate::scene::LaidOutScene;
14
15const CAPTURED_FLAGS: EventFlags = EventFlags::CAPTURE.union(EventFlags::NO_BUBBLE);
16
17/// One resolved-event emitter for the sample being resolved.
18struct Emit<'s, 'e> {
19    store: &'s NodeStore,
20    ev: &'s ValidatedEvent<'e>,
21    key: PointerKey,
22    primary: bool,
23}
24
25impl Emit<'_, '_> {
26    /// Pushes `kind` to `target` when `target` (`NO_BUBBLE`: itself) or an ancestor listens.
27    fn push(&self, out: &mut EventBatchBuf, kind: InteractionEvent, target: NodeId, extra: EventFlags) {
28        let listens = if extra.contains(EventFlags::NO_BUBBLE) {
29            has_direct_listener(self.store, target, kind)
30        } else {
31            has_ancestor_listener(self.store, target, kind)
32        };
33        if listens {
34            out.push_resolved_pointer(self.ev, kind, target, self.key.id, self.key.kind.as_u8(), self.primary, extra);
35        }
36    }
37}
38
39impl<L: StoreLayoutEngine> LaidOutScene<L> {
40    /// Applies probed raw sample `ev` to the tracker, appending the targeted events to `out`.
41    pub fn apply_pointer(
42        &mut self,
43        store: &NodeStore,
44        ev: &ValidatedEvent<'_>,
45        p: &PointerProbe,
46        out: &mut EventBatchBuf,
47    ) -> PointerResolution {
48        let mut r = PointerResolution { painted: p.painted, ..PointerResolution::default() };
49        let slot = self.interaction.pointers().get(p.key).copied();
50        let primary = slot.map_or_else(|| self.interaction.pointers().would_be_primary(p.key), |s| s.primary);
51        let em = Emit { store, ev, key: p.key, primary };
52        if slot.is_some_and(|s| s.blocked) && p.phase != InteractionEvent::PointerLeave {
53            if matches!(p.phase, InteractionEvent::PointerUp | InteractionEvent::PointerCancel) {
54                let _ = self.interaction.pointers_mut().end(p.key);
55            }
56            r.outcome = PointerOutcomeFlags::MODAL_BARRIER;
57            return r;
58        }
59        let transitioned = match p.phase {
60            kind @ (InteractionEvent::PointerDown | InteractionEvent::PointerUp) if p.button != 0 => {
61                self.route_secondary_button(&em, out, p, kind, &mut r);
62                false
63            }
64            InteractionEvent::PointerDown => self.apply_down(store, &em, out, p, &mut r),
65            InteractionEvent::PointerMove => self.apply_move(store, &em, out, p, &mut r),
66            InteractionEvent::PointerUp => self.apply_up(store, &em, out, p, &mut r),
67            InteractionEvent::PointerCancel => self.apply_cancel(store, &em, out),
68            _ => {
69                let hovering = p.key.kind.hovers() && primary;
70                if hovering {
71                    let _ = self.interaction.pointer_leave_slice();
72                    self.emit_transitions(&em, out);
73                }
74                hovering
75            }
76        };
77        if transitioned && !self.interaction.last_dirty().is_empty() {
78            self.bump_interaction_epoch();
79            r.changed = true;
80            r.relayout = self.sync_interaction_dirty(store);
81        }
82        r
83    }
84
85    /// W3C `setPointerCapture` / `releasePointerCapture` from the app: sets the pointer's pending
86    /// capture (applied before its next sample). Capture needs a connected, enabled target.
87    pub fn request_pointer_capture(
88        &mut self,
89        store: &NodeStore,
90        req: PointerCaptureRequest,
91    ) -> Result<(), CaptureError> {
92        if !req.capture {
93            return self.interaction.pointers_mut().release_capture(req.key, req.node);
94        }
95        if !self.is_capture_target(store, req.node) {
96            return Err(CaptureError::InvalidTarget);
97        }
98        self.interaction.pointers_mut().set_capture(req.key, req.node)
99    }
100
101    /// Non-zero mouse / pen buttons neither begin a pointer nor touch `:active`: the event goes
102    /// to the capture target, else the hit.
103    fn route_secondary_button(
104        &self,
105        em: &Emit<'_, '_>,
106        out: &mut EventBatchBuf,
107        p: &PointerProbe,
108        kind: InteractionEvent,
109        r: &mut PointerResolution,
110    ) {
111        if let Some(cap) = p.capture {
112            r.outcome = PointerOutcomeFlags::TARGETED | PointerOutcomeFlags::CAPTURED;
113            r.capture = Some(cap);
114            em.push(out, kind, cap, CAPTURED_FLAGS);
115        } else if let Some(hit) = p.hit {
116            r.outcome = PointerOutcomeFlags::TARGETED;
117            em.push(out, kind, hit, EventFlags::EMPTY);
118        }
119    }
120
121    fn apply_down(
122        &mut self,
123        store: &NodeStore,
124        em: &Emit<'_, '_>,
125        out: &mut EventBatchBuf,
126        p: &PointerProbe,
127        r: &mut PointerResolution,
128    ) -> bool {
129        let at = [p.x, p.y];
130        if p.press.is_some_and(|t| t.modal_barrier) {
131            if let Ok(slot) = self.interaction.pointers_mut().begin(p.key, at, p.timestamp, NodeId::NULL) {
132                slot.blocked = true;
133            }
134            r.outcome = PointerOutcomeFlags::MODAL_BARRIER;
135            return false;
136        }
137        let primary = match self.interaction.pointer_down_with(p.key, at, p.timestamp, p.hit, |id| store.parent(id)) {
138            Ok(primary) => primary,
139            Err(_) => {
140                r.outcome = PointerOutcomeFlags::REFUSED;
141                if let Some(hit) = p.hit {
142                    Emit { primary: false, ..*em }.push(out, InteractionEvent::PointerCancel, hit, EventFlags::EMPTY);
143                }
144                return false;
145            }
146        };
147        let em = Emit { primary, ..*em };
148        self.emit_transitions(&em, out);
149        let capture = match (p.owner, p.hit) {
150            (Some(owner), _) => Some((owner, true)),
151            (None, Some(hit)) if p.key.kind.captures_implicitly() => Some((hit, false)),
152            _ => None,
153        };
154        if let Some((node, claimed)) = capture {
155            let _ = self.interaction.pointers_mut().capture_now(p.key, node, claimed);
156        }
157        if let Some(hit) = p.hit {
158            r.outcome.insert(PointerOutcomeFlags::TARGETED);
159            let extra = if capture.is_some() { EventFlags::CAPTURE } else { EventFlags::EMPTY };
160            em.push(out, InteractionEvent::PointerDown, hit, extra);
161        }
162        if let Some((node, claimed)) = capture {
163            r.outcome.insert(PointerOutcomeFlags::CAPTURED);
164            r.outcome.set(PointerOutcomeFlags::CLAIMED, claimed);
165            r.capture = Some(node);
166            em.push(out, InteractionEvent::GotPointerCapture, node, EventFlags::EMPTY);
167        }
168        true
169    }
170
171    fn apply_move(
172        &mut self,
173        store: &NodeStore,
174        em: &Emit<'_, '_>,
175        out: &mut EventBatchBuf,
176        p: &PointerProbe,
177        r: &mut PointerResolution,
178    ) -> bool {
179        if let Some(cap) = self.settle_capture(store, em, out) {
180            self.mark_captured(p.key, cap, r);
181            em.push(out, InteractionEvent::PointerMove, cap, CAPTURED_FLAGS);
182            return false;
183        }
184        let _ = self.interaction.pointer_move_with(p.key, p.hit, |id| store.parent(id));
185        self.emit_transitions(em, out);
186        if let Some(slot) = self.interaction.pointers_mut().get_mut(p.key) {
187            slot.last_xy = [p.x, p.y];
188            slot.last_target = p.hit.unwrap_or(NodeId::NULL);
189        }
190        if let Some(hit) = p.hit {
191            r.outcome.insert(PointerOutcomeFlags::TARGETED);
192            em.push(out, InteractionEvent::PointerMove, hit, EventFlags::EMPTY);
193        }
194        true
195    }
196
197    fn apply_up(
198        &mut self,
199        store: &NodeStore,
200        em: &Emit<'_, '_>,
201        out: &mut EventBatchBuf,
202        p: &PointerProbe,
203        r: &mut PointerResolution,
204    ) -> bool {
205        let cap = self.settle_capture(store, em, out);
206        if let Some(cap) = cap {
207            self.mark_captured(p.key, cap, r);
208        }
209        if let Some(cap) = cap {
210            em.push(out, InteractionEvent::PointerUp, cap, CAPTURED_FLAGS);
211            em.push(out, InteractionEvent::LostPointerCapture, cap, EventFlags::EMPTY);
212        } else if let Some(hit) = p.hit {
213            r.outcome.insert(PointerOutcomeFlags::TARGETED);
214            em.push(out, InteractionEvent::PointerUp, hit, EventFlags::EMPTY);
215        }
216        // Boundary events of the release (a released capture re-targets hover) follow
217        // `lostpointercapture` and precede the click (W3C).
218        let end = self.interaction.pointer_up_with(p.key, p.hit, |id| store.parent(id));
219        self.emit_transitions(em, out);
220        if let Some(clicked) = end.clicked {
221            out.push_press(em.ev.surface(), clicked, p.timestamp, p.x, p.y);
222            r.clicked = Some(clicked);
223        }
224        true
225    }
226
227    fn apply_cancel(&mut self, store: &NodeStore, em: &Emit<'_, '_>, out: &mut EventBatchBuf) -> bool {
228        if em.key.id != NV_POINTER_ID_ALL {
229            let end = self.interaction.pointer_cancel(em.key);
230            self.emit_transitions(em, out);
231            if let Some(slot) = end.slot {
232                self.emit_cancel(store, em, out, &slot);
233            }
234            return true;
235        }
236        let (keys, n) = self.interaction.pointers().keys();
237        for key in &keys[..n] {
238            if let Some(slot) = self.interaction.pointers().get(*key).copied() {
239                self.emit_cancel(store, &Emit { key: *key, primary: slot.primary, ..*em }, out, &slot);
240            }
241        }
242        let _ = self.interaction.pointer_cancel_all();
243        self.emit_transitions(em, out);
244        true
245    }
246
247    /// W3C `pointercancel` to the ended pointer's capture target (else its down target), then
248    /// `lostpointercapture`.
249    fn emit_cancel(&self, store: &NodeStore, em: &Emit<'_, '_>, out: &mut EventBatchBuf, slot: &PointerSlot) {
250        if slot.blocked {
251            return;
252        }
253        if self.is_capture_target(store, slot.capture) {
254            em.push(out, InteractionEvent::PointerCancel, slot.capture, CAPTURED_FLAGS);
255            em.push(out, InteractionEvent::LostPointerCapture, slot.capture, EventFlags::EMPTY);
256        } else if !slot.down_target.is_null() && store.is_connected(slot.down_target) {
257            em.push(out, InteractionEvent::PointerCancel, slot.down_target, EventFlags::EMPTY);
258        }
259    }
260
261    /// Drops `em.key`'s capture targets that became invalid (disconnected, disabled), applies its
262    /// pending capture (emitting `LostPointerCapture` / `GotPointerCapture`), and returns its
263    /// capture target.
264    fn settle_capture(&mut self, store: &NodeStore, em: &Emit<'_, '_>, out: &mut EventBatchBuf) -> Option<NodeId> {
265        self.interaction.pointers().get(em.key)?;
266        let _ = self.prune_capture_of(store, em.key);
267        let t = self.interaction.pointers_mut().process_pending_capture(em.key);
268        if !t.lost.is_null() {
269            em.push(out, InteractionEvent::LostPointerCapture, t.lost, EventFlags::EMPTY);
270        }
271        if !t.got.is_null() {
272            em.push(out, InteractionEvent::GotPointerCapture, t.got, EventFlags::EMPTY);
273        }
274        self.interaction.pointers().capture_of(em.key)
275    }
276
277    /// Drops every capture (current or pending) whose target became invalid (disconnected,
278    /// disabled subtree); returns whether any was dropped.
279    pub(crate) fn prune_invalid_captures(&mut self, store: &NodeStore) -> bool {
280        let (keys, n) = self.interaction.pointers().keys();
281        let mut changed = false;
282        for &key in &keys[..n] {
283            changed |= self.prune_capture_of(store, key);
284        }
285        changed
286    }
287
288    fn prune_capture_of(&mut self, store: &NodeStore, key: PointerKey) -> bool {
289        let Some(slot) = self.interaction.pointers().get(key).copied() else {
290            return false;
291        };
292        let cap_ok = slot.capture.is_null() || self.is_capture_target(store, slot.capture);
293        let pending_ok = slot.pending_capture.is_null() || self.is_capture_target(store, slot.pending_capture);
294        if cap_ok && pending_ok {
295            return false;
296        }
297        if let Some(s) = self.interaction.pointers_mut().get_mut(key) {
298            if !cap_ok {
299                s.capture = NodeId::NULL;
300                s.claimed = false;
301            }
302            if !pending_ok {
303                s.pending_capture = NodeId::NULL;
304            }
305        }
306        true
307    }
308
309    fn mark_captured(&self, key: PointerKey, cap: NodeId, r: &mut PointerResolution) {
310        r.outcome.insert(PointerOutcomeFlags::TARGETED | PointerOutcomeFlags::CAPTURED);
311        let claimed = self.interaction.pointers().get(key).is_some_and(|s| s.claimed);
312        r.outcome.set(PointerOutcomeFlags::CLAIMED, claimed);
313        r.capture = Some(cap);
314    }
315
316    /// Non-bubbling `PointerLeave` (bottom-up) then `PointerEnter` (top-down) for the tracker's
317    /// latest hover transition.
318    fn emit_transitions(&self, em: &Emit<'_, '_>, out: &mut EventBatchBuf) {
319        let tracker = &self.interaction;
320        for &node in tracker.exited() {
321            em.push(out, InteractionEvent::PointerLeave, node, EventFlags::NO_BUBBLE);
322        }
323        for &node in tracker.entered() {
324            em.push(out, InteractionEvent::PointerEnter, node, EventFlags::NO_BUBBLE);
325        }
326    }
327}