Skip to main content

nativeview_engine/tracker/
mod.rs

1//! Reusable zero-allocation stateful interaction tracker (`InteractionTracker`) shared by every
2//! scene consumer (`LaidOutScene`, `SkiaBackend`, the runtime pointer-resolution stage).
3//!
4//! Tracks leaf-to-root ancestor chains for `:hover`, `:active` and `:drag-over`, the active
5//! pointers and their W3C capture ([`PointerTable`]), `:focus` + [`FocusModality`]
6//! (`:focus-visible`), and `:disabled`. `:hover` follows the primary hover-capable pointer
7//! (mouse, hovering pen); `:active` and `Press` follow the primary pointer only, so a second
8//! finger never steals them. All steady-state transitions reuse internal scratch buffers with
9//! zero heap allocations.
10//!
11//! - [`chains`]: hover / active / drag-over chain transitions and their dirty sets.
12//! - [`focus`]: focus and modality.
13//! - [`pointers`]: the fixed-capacity [`PointerTable`].
14
15mod chains;
16mod focus;
17pub mod pointers;
18
19use nativeview_abi::hash::HashSet;
20use nativeview_abi::NodeId;
21use nativeview_tables::interaction::{resolve_focus_visible, FocusModality, InteractionState};
22
23use crate::focus::FocusAnchor;
24
25pub use chains::PointerEnd;
26pub use pointers::{
27    CaptureError, CaptureTransition, PointerCaptureRequest, PointerKey, PointerType,
28    PointerOverflow, PointerSlot, PointerTable, MAX_ACTIVE_POINTERS,
29};
30
31const MAX_CHAIN_DEPTH: usize = 256;
32
33/// Reusable stateful interaction tracker (see the module docs).
34#[derive(Debug, Clone, Default)]
35pub struct InteractionTracker {
36    /// Leaf-to-root hovered ancestor chain (`[leaf, parent, ..., root]`).
37    hovered_chain: Vec<NodeId>,
38    /// Leaf-to-root active (non-disabled) ancestor chain of [`Self::active_key`]'s press.
39    active_chain: Vec<NodeId>,
40    /// The primary pointer whose press owns `active_chain`.
41    active_key: Option<PointerKey>,
42    /// Leaf-to-root `:drag-over` ancestor chain (zero recomposition on drag hover).
43    drag_over_chain: Vec<NodeId>,
44    /// Active pointers and their capture.
45    pointers: PointerTable,
46    focused: Option<NodeId>,
47    focus_modality: FocusModality,
48    last_input_modality: FocusModality,
49    focused_is_text_entry: bool,
50    focus_anchor: FocusAnchor,
51    disabled: HashSet<NodeId>,
52    /// Top-down (`root -> leaf`) nodes that entered hover on the latest move/down/up transition.
53    entered_scratch: Vec<NodeId>,
54    /// Bottom-up (`leaf -> root`) nodes that exited hover on the latest move/down/up/leave/cancel.
55    exited_scratch: Vec<NodeId>,
56    /// Top-down (`root -> leaf`) nodes that entered `:drag-over` on the latest drag-over update.
57    drag_entered_scratch: Vec<NodeId>,
58    /// Bottom-up (`leaf -> root`) nodes that exited `:drag-over` on the latest drag-over update.
59    drag_exited_scratch: Vec<NodeId>,
60    /// Sorted deduplicated dirty `NodeId`s produced by the latest transition.
61    prev_dirty_scratch: Vec<NodeId>,
62    /// Reusable buffer for assembling the next leaf-to-root ancestor chain.
63    next_chain_scratch: Vec<NodeId>,
64    /// Reusable buffer snapshotting prior [`InteractionState`] of candidate nodes.
65    candidate_scratch: Vec<(NodeId, InteractionState)>,
66}
67
68impl InteractionTracker {
69    pub fn new() -> Self {
70        Self::default()
71    }
72
73    #[inline]
74    pub fn hovered(&self) -> Option<NodeId> {
75        self.hovered_chain.first().copied()
76    }
77
78    #[inline]
79    pub fn active(&self) -> Option<NodeId> {
80        self.active_chain.first().copied()
81    }
82
83    #[inline]
84    pub fn hovered_chain(&self) -> &[NodeId] {
85        &self.hovered_chain
86    }
87
88    #[inline]
89    pub fn active_chain(&self) -> &[NodeId] {
90        &self.active_chain
91    }
92
93    /// The primary pointer whose press owns `:active`.
94    #[inline]
95    pub fn active_key(&self) -> Option<PointerKey> {
96        self.active_key
97    }
98
99    #[inline]
100    pub fn drag_over(&self) -> Option<NodeId> {
101        self.drag_over_chain.first().copied()
102    }
103
104    #[inline]
105    pub fn drag_over_chain(&self) -> &[NodeId] {
106        &self.drag_over_chain
107    }
108
109    /// Top-down (`root -> leaf`) nodes that entered `:drag-over` on the latest drag-over update.
110    #[inline]
111    pub fn drag_entered(&self) -> &[NodeId] {
112        &self.drag_entered_scratch
113    }
114
115    /// Bottom-up (`leaf -> root`) nodes that exited `:drag-over` on the latest drag-over update.
116    #[inline]
117    pub fn drag_exited(&self) -> &[NodeId] {
118        &self.drag_exited_scratch
119    }
120
121    /// The active pointers.
122    #[inline]
123    pub fn pointers(&self) -> &PointerTable {
124        &self.pointers
125    }
126
127    /// Mutable active pointers (capture requests, settings-imposed capacity).
128    #[inline]
129    pub fn pointers_mut(&mut self) -> &mut PointerTable {
130        &mut self.pointers
131    }
132
133    /// `(pointer, capture target)` of the primary pointer, when it is captured.
134    #[inline]
135    pub fn captured(&self) -> Option<(PointerKey, NodeId)> {
136        let slot = self.pointers.primary()?;
137        (!slot.capture.is_null()).then_some((slot.key, slot.capture))
138    }
139
140    /// The primary pointer's capture target.
141    #[inline]
142    pub fn captured_node(&self) -> Option<NodeId> {
143        self.captured().map(|(_, n)| n)
144    }
145
146    /// Whether the press owning `:active` is captured (drag-off then keeps `:active`).
147    #[inline]
148    fn active_press_captured(&self) -> bool {
149        self.active_key.is_some_and(|k| self.pointers.capture_of(k).is_some())
150    }
151
152    #[inline]
153    pub fn focused(&self) -> Option<NodeId> {
154        self.focused
155    }
156
157    #[inline]
158    pub fn focus_modality(&self) -> FocusModality {
159        self.focus_modality
160    }
161
162    #[inline]
163    pub fn last_input_modality(&self) -> FocusModality {
164        self.last_input_modality
165    }
166
167    #[inline]
168    pub fn is_disabled(&self, id: NodeId) -> bool {
169        self.disabled.contains(&id)
170    }
171
172    /// Top-down (`root -> leaf`) nodes that entered hover during the latest pointer transition.
173    #[inline]
174    pub fn entered(&self) -> &[NodeId] {
175        &self.entered_scratch
176    }
177
178    /// Bottom-up (`leaf -> root`) nodes that exited hover during the latest pointer transition.
179    #[inline]
180    pub fn exited(&self) -> &[NodeId] {
181        &self.exited_scratch
182    }
183
184    /// Sorted, deduplicated dirty `NodeId`s from the latest transition.
185    #[inline]
186    pub fn last_dirty(&self) -> &[NodeId] {
187        &self.prev_dirty_scratch
188    }
189
190    /// Returns the node that currently governs the window pointer cursor:
191    /// prefers the primary capture, then `active`, falling back to `hovered`.
192    #[inline]
193    pub fn active_cursor_node(&self) -> Option<NodeId> {
194        self.captured_node()
195            .or_else(|| self.active())
196            .or_else(|| self.hovered())
197    }
198
199    /// Computes the exact active [`InteractionState`] flags for `id` (O(chains); pointer slots
200    /// never feed the cascade).
201    #[inline]
202    pub fn state(&self, id: NodeId) -> InteractionState {
203        let mut s = InteractionState::NONE;
204        if self.hovered_chain.contains(&id) {
205            s |= InteractionState::HOVER;
206        }
207        if self.focused == Some(id) {
208            s |= InteractionState::FOCUS;
209            if resolve_focus_visible(
210                self.focus_modality,
211                self.last_input_modality,
212                self.focused_is_text_entry,
213            ) {
214                s |= InteractionState::FOCUS_VISIBLE;
215            }
216        }
217        if self.active_chain.contains(&id) {
218            s |= InteractionState::ACTIVE;
219        }
220        if self.drag_over_chain.contains(&id) {
221            s |= InteractionState::DRAG_OVER;
222        }
223        if self.disabled.contains(&id) {
224            s |= InteractionState::DISABLED;
225        }
226        s
227    }
228
229    /// Marks `id` disabled or enabled (zero-alloc when `disabled` set already has capacity).
230    /// Disabling clears `active`, `focused`, and every pointer capture on `id`.
231    pub fn set_disabled_slice(&mut self, id: NodeId, disabled: bool) -> &[NodeId] {
232        self.candidate_scratch.clear();
233        self.push_candidate_id(id);
234        if disabled {
235            self.disabled.insert(id);
236            self.active_chain.retain(|&n| n != id);
237            self.drag_over_chain.retain(|&n| n != id);
238            if self.focused == Some(id) {
239                self.focused = None;
240            }
241            let _ = self.pointers.prune_captures(|n| n == id);
242        } else {
243            self.disabled.remove(&id);
244        }
245        self.finalize_dirty()
246    }
247
248    /// Prunes nodes where `keep(id)` is `false` from hover, active, drag-over, and every pointer
249    /// capture (0-alloc).
250    pub fn prune_disconnected(&mut self, mut keep: impl FnMut(NodeId) -> bool) -> bool {
251        let mut changed = false;
252        for c in [&mut self.hovered_chain, &mut self.active_chain, &mut self.drag_over_chain] {
253            let n = c.len();
254            c.retain(|&id| keep(id));
255            changed |= c.len() != n;
256        }
257        changed | self.pointers.prune_captures(|id| !keep(id))
258    }
259
260    /// Removes `id` from all tracked chains, captures, focus, and disabled state (zero-alloc).
261    pub fn remove_node_slice(&mut self, id: NodeId) -> &[NodeId] {
262        let prev = self.state(id);
263        self.hovered_chain.retain(|&n| n != id);
264        self.active_chain.retain(|&n| n != id);
265        self.drag_over_chain.retain(|&n| n != id);
266        if self.focused == Some(id) {
267            self.focused = None;
268        }
269        let _ = self.pointers.prune_captures(|n| n == id);
270        self.disabled.remove(&id);
271        self.prev_dirty_scratch.clear();
272        if prev != InteractionState::NONE {
273            self.prev_dirty_scratch.push(id);
274        }
275        &self.prev_dirty_scratch
276    }
277
278    /// Resets all tracked interaction state (retaining scratch capacity).
279    pub fn clear(&mut self) {
280        self.hovered_chain.clear();
281        self.active_chain.clear();
282        self.active_key = None;
283        self.drag_over_chain.clear();
284        self.pointers.clear();
285        self.focused = None;
286        self.focus_modality = FocusModality::Pointer;
287        self.last_input_modality = FocusModality::Pointer;
288        self.focused_is_text_entry = false;
289        self.focus_anchor.clear();
290        self.disabled.clear();
291        self.entered_scratch.clear();
292        self.exited_scratch.clear();
293        self.drag_entered_scratch.clear();
294        self.drag_exited_scratch.clear();
295        self.prev_dirty_scratch.clear();
296        self.next_chain_scratch.clear();
297        self.candidate_scratch.clear();
298    }
299}