Skip to main content

nativeview_engine/tracker/
pointers.rs

1//! Fixed-capacity multi-pointer table with W3C Pointer Events capture semantics.
2//!
3//! One [`PointerSlot`] per *active* pointer (a pressed mouse button, a pen or touch contact),
4//! keyed by `(kind, id)` so ids of different device kinds never collide. The table is a plain
5//! array of [`MAX_ACTIVE_POINTERS`] slots: lookups scan at most 10 keys, nothing allocates, and a
6//! contact beyond capacity is refused instead of spilling to the heap.
7//!
8//! Capture follows W3C: [`PointerTable::set_capture`] / [`PointerTable::release_capture`] write a
9//! *pending* target that [`PointerTable::process_pending_capture`] applies before the pointer's
10//! next event (returning the lost / got targets); ending a pointer releases only its own capture.
11
12use nativeview_abi::{
13    NodeId, NvPointerCaptureRequest, ReprEnum, TimestampUs, NV_POINTER_TYPE_MOUSE, NV_POINTER_TYPE_PEN,
14    NV_POINTER_TYPE_TOUCH,
15};
16
17pub use nativeview_abi::runtime::MAX_ACTIVE_POINTERS;
18
19/// W3C `pointerType` (`NV_POINTER_TYPE_*`; `try_from_u8` rejects unknown codes).
20#[repr(u8)]
21#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, ReprEnum)]
22pub enum PointerType {
23    #[default]
24    Mouse = 0,
25    Pen = 1,
26    Touch = 2,
27}
28
29const _: () = assert!(
30    PointerType::Mouse as u8 == NV_POINTER_TYPE_MOUSE
31        && PointerType::Pen as u8 == NV_POINTER_TYPE_PEN
32        && PointerType::Touch as u8 == NV_POINTER_TYPE_TOUCH
33);
34
35impl PointerType {
36
37    /// Whether the device reports position without contact (drives `:hover`).
38    #[inline]
39    pub const fn hovers(self) -> bool {
40        !matches!(self, Self::Touch)
41    }
42
43    /// Direct-manipulation devices implicitly capture their down target (W3C).
44    #[inline]
45    pub const fn captures_implicitly(self) -> bool {
46        !matches!(self, Self::Mouse)
47    }
48}
49
50/// Identity of one pointer: its device kind plus the host's pointer id.
51#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
52pub struct PointerKey {
53    pub kind: PointerType,
54    pub id: u32,
55}
56
57impl PointerKey {
58    /// The system mouse (pointer id 1, as every host reports it).
59    pub const MOUSE: Self = Self::new(PointerType::Mouse, 1);
60
61    #[inline]
62    pub const fn new(kind: PointerType, id: u32) -> Self {
63        Self { kind, id }
64    }
65}
66
67/// An app's W3C `setPointerCapture` (`capture`) / `releasePointerCapture` call, collected during
68/// dispatch and applied by the runtime as the pointer's pending capture.
69#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
70pub struct PointerCaptureRequest {
71    pub key: PointerKey,
72    pub node: NodeId,
73    pub capture: bool,
74}
75
76impl PointerCaptureRequest {
77    /// The C ABI record (`NvPointerApi`).
78    #[inline]
79    pub const fn to_abi(self) -> NvPointerCaptureRequest {
80        NvPointerCaptureRequest {
81            node: self.node,
82            id: self.key.id,
83            kind: self.key.kind.as_u8(),
84            capture: self.capture as u8,
85            _pad: 0,
86        }
87    }
88
89    /// The request of C ABI record `r` (`None`: unknown pointer type, `capture > 1` or nonzero
90    /// padding).
91    #[inline]
92    pub fn from_abi(r: NvPointerCaptureRequest) -> Option<Self> {
93        let kind = PointerType::try_from_u8(r.kind)?;
94        (r.capture <= 1 && r._pad == 0).then_some(Self {
95            key: PointerKey::new(kind, r.id),
96            node: r.node,
97            capture: r.capture == 1,
98        })
99    }
100}
101
102/// Why a capture request was refused (W3C `setPointerCapture` exceptions).
103#[derive(Debug, Clone, Copy, PartialEq, Eq)]
104pub enum CaptureError {
105    /// The pointer is not active (no pressed button / contact): W3C `NotFoundError`.
106    InvalidPointer,
107    /// The target is disabled or not connected: W3C `InvalidStateError`.
108    InvalidTarget,
109}
110
111/// The table is full: the contact was refused.
112#[derive(Debug, Clone, Copy, PartialEq, Eq)]
113pub struct PointerOverflow;
114
115/// Capture targets that changed when a pending capture was processed (`NULL` = none).
116#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
117pub struct CaptureTransition {
118    pub lost: NodeId,
119    pub got: NodeId,
120}
121
122impl CaptureTransition {
123    #[inline]
124    pub const fn is_empty(&self) -> bool {
125        self.lost.is_null() && self.got.is_null()
126    }
127}
128
129/// One active pointer.
130#[derive(Debug, Clone, Copy, PartialEq, Default)]
131pub struct PointerSlot {
132    pub key: PointerKey,
133    /// W3C `isPrimary`, fixed when the pointer became active.
134    pub primary: bool,
135    /// A modal swallowed the press: the pointer's events are dropped until it ends.
136    pub blocked: bool,
137    /// Pressed buttons at the latest sample.
138    pub buttons: u16,
139    /// Hit target of the down (the press target; `NULL` when nothing was hit).
140    pub down_target: NodeId,
141    /// Hit target of the latest uncaptured sample (per-pointer enter / leave).
142    pub last_target: NodeId,
143    /// Current capture target (`NULL` = none).
144    pub capture: NodeId,
145    /// Pending capture target applied before the pointer's next event.
146    pub pending_capture: NodeId,
147    /// The capture is a claim (declarative or app-requested), not an implicit touch capture.
148    pub claimed: bool,
149    pub down_xy: [f32; 2],
150    pub last_xy: [f32; 2],
151    pub down_ts: TimestampUs,
152}
153
154/// Fixed-capacity active pointer table (see the module docs).
155#[derive(Debug, Clone, Default)]
156pub struct PointerTable {
157    slots: [PointerSlot; MAX_ACTIVE_POINTERS],
158    /// Bit `i` set: `slots[i]` is live.
159    live: u16,
160    /// Settings-imposed capacity (`<= MAX_ACTIVE_POINTERS`; `0` = full capacity).
161    limit: u8,
162}
163
164const _: () = assert!(MAX_ACTIVE_POINTERS <= u16::BITS as usize);
165
166impl PointerTable {
167    #[inline]
168    pub const fn len(&self) -> usize {
169        self.live.count_ones() as usize
170    }
171
172    #[inline]
173    pub const fn is_empty(&self) -> bool {
174        self.live == 0
175    }
176
177    /// Caps simultaneously tracked pointers (`1..=MAX_ACTIVE_POINTERS`); live slots stay.
178    #[inline]
179    pub fn set_limit(&mut self, limit: usize) {
180        self.limit = limit.clamp(1, MAX_ACTIVE_POINTERS) as u8;
181    }
182
183    #[inline]
184    fn capacity(&self) -> usize {
185        if self.limit == 0 { MAX_ACTIVE_POINTERS } else { self.limit as usize }
186    }
187
188    #[inline]
189    fn index_of(&self, key: PointerKey) -> Option<usize> {
190        (0..MAX_ACTIVE_POINTERS).find(|&i| self.live & (1 << i) != 0 && self.slots[i].key == key)
191    }
192
193    #[inline]
194    pub fn get(&self, key: PointerKey) -> Option<&PointerSlot> {
195        self.index_of(key).map(|i| &self.slots[i])
196    }
197
198    #[inline]
199    pub fn get_mut(&mut self, key: PointerKey) -> Option<&mut PointerSlot> {
200        self.index_of(key).map(|i| &mut self.slots[i])
201    }
202
203    /// Live slots in slot order.
204    pub fn iter(&self) -> impl Iterator<Item = &PointerSlot> {
205        (0..MAX_ACTIVE_POINTERS).filter(|&i| self.live & (1 << i) != 0).map(|i| &self.slots[i])
206    }
207
208    /// The first active primary slot.
209    pub fn primary(&self) -> Option<&PointerSlot> {
210        self.iter().find(|s| s.primary)
211    }
212
213    /// W3C primary rule: the mouse is always primary; a pen or touch contact is primary when no
214    /// other pointer of its kind is active.
215    pub fn would_be_primary(&self, key: PointerKey) -> bool {
216        if let Some(slot) = self.get(key) {
217            return slot.primary;
218        }
219        key.kind == PointerType::Mouse || !self.iter().any(|s| s.key.kind == key.kind)
220    }
221
222    /// Activates `key` (no-op returning the slot when already active).
223    pub fn begin(
224        &mut self,
225        key: PointerKey,
226        at: [f32; 2],
227        ts: TimestampUs,
228        target: NodeId,
229    ) -> Result<&mut PointerSlot, PointerOverflow> {
230        if let Some(i) = self.index_of(key) {
231            return Ok(&mut self.slots[i]);
232        }
233        if self.len() >= self.capacity() {
234            return Err(PointerOverflow);
235        }
236        let primary = self.would_be_primary(key);
237        let i = (0..MAX_ACTIVE_POINTERS).find(|&i| self.live & (1 << i) == 0).ok_or(PointerOverflow)?;
238        self.live |= 1 << i;
239        self.slots[i] = PointerSlot {
240            key,
241            primary,
242            down_target: target,
243            last_target: target,
244            down_xy: at,
245            last_xy: at,
246            down_ts: ts,
247            ..PointerSlot::default()
248        };
249        Ok(&mut self.slots[i])
250    }
251
252    /// Ends `key`, returning its final slot.
253    pub fn end(&mut self, key: PointerKey) -> Option<PointerSlot> {
254        let i = self.index_of(key)?;
255        self.live &= !(1 << i);
256        Some(core::mem::take(&mut self.slots[i]))
257    }
258
259    /// Captures `key` to `node` immediately (implicit / declarative capture at down).
260    pub fn capture_now(&mut self, key: PointerKey, node: NodeId, claimed: bool) -> Result<(), CaptureError> {
261        let slot = self.get_mut(key).ok_or(CaptureError::InvalidPointer)?;
262        slot.capture = node;
263        slot.pending_capture = node;
264        slot.claimed = claimed && !node.is_null();
265        Ok(())
266    }
267
268    /// W3C `setPointerCapture`: sets `key`'s pending capture target (`node` must be valid for
269    /// the caller, see [`CaptureError::InvalidTarget`]).
270    pub fn set_capture(&mut self, key: PointerKey, node: NodeId) -> Result<(), CaptureError> {
271        if node.is_null() {
272            return Err(CaptureError::InvalidTarget);
273        }
274        self.get_mut(key).ok_or(CaptureError::InvalidPointer)?.pending_capture = node;
275        Ok(())
276    }
277
278    /// W3C `releasePointerCapture`: clears `key`'s pending capture when `node` holds it (or any
279    /// node when `node` is `NULL`).
280    pub fn release_capture(&mut self, key: PointerKey, node: NodeId) -> Result<(), CaptureError> {
281        let slot = self.get_mut(key).ok_or(CaptureError::InvalidPointer)?;
282        if node.is_null() || slot.pending_capture == node {
283            slot.pending_capture = NodeId::NULL;
284        }
285        Ok(())
286    }
287
288    /// W3C `hasPointerCapture`: `node` is `key`'s pending capture target.
289    #[inline]
290    pub fn has_capture(&self, key: PointerKey, node: NodeId) -> bool {
291        !node.is_null() && self.get(key).is_some_and(|s| s.pending_capture == node)
292    }
293
294    /// Current capture target of `key`.
295    #[inline]
296    pub fn capture_of(&self, key: PointerKey) -> Option<NodeId> {
297        self.get(key).map(|s| s.capture).filter(|n| !n.is_null())
298    }
299
300    /// Applies `key`'s pending capture; an app request (anything but the implicit target)
301    /// becomes a claim.
302    pub fn process_pending_capture(&mut self, key: PointerKey) -> CaptureTransition {
303        let Some(slot) = self.get_mut(key) else {
304            return CaptureTransition::default();
305        };
306        if slot.pending_capture == slot.capture {
307            return CaptureTransition::default();
308        }
309        let t = CaptureTransition { lost: slot.capture, got: slot.pending_capture };
310        slot.capture = slot.pending_capture;
311        slot.claimed = !slot.capture.is_null();
312        t
313    }
314
315    /// Drops capture (current and pending) on every slot where `drop(node)` holds; returns
316    /// whether anything changed.
317    pub fn prune_captures(&mut self, mut drop: impl FnMut(NodeId) -> bool) -> bool {
318        let mut changed = false;
319        for i in 0..MAX_ACTIVE_POINTERS {
320            if self.live & (1 << i) == 0 {
321                continue;
322            }
323            let s = &mut self.slots[i];
324            if !s.capture.is_null() && drop(s.capture) {
325                s.capture = NodeId::NULL;
326                s.claimed = false;
327                changed = true;
328            }
329            if !s.pending_capture.is_null() && drop(s.pending_capture) {
330                s.pending_capture = NodeId::NULL;
331                changed = true;
332            }
333        }
334        changed
335    }
336
337    /// Ends every slot.
338    #[inline]
339    pub fn clear(&mut self) {
340        self.live = 0;
341    }
342
343    /// Keys of every live slot (copied out so callers can mutate while iterating).
344    pub fn keys(&self) -> ([PointerKey; MAX_ACTIVE_POINTERS], usize) {
345        let mut out = [PointerKey::default(); MAX_ACTIVE_POINTERS];
346        let mut n = 0;
347        for s in self.iter() {
348            out[n] = s.key;
349            n += 1;
350        }
351        (out, n)
352    }
353}