nativeview-engine 0.1.0-rc.1

Framework-agnostic scene engine traits, hot-reload cdylib loader, and Frame-0 snapshot codecs.
Documentation
//! Fixed-capacity multi-pointer table with W3C Pointer Events capture semantics.
//!
//! One [`PointerSlot`] per *active* pointer (a pressed mouse button, a pen or touch contact),
//! keyed by `(kind, id)` so ids of different device kinds never collide. The table is a plain
//! array of [`MAX_ACTIVE_POINTERS`] slots: lookups scan at most 10 keys, nothing allocates, and a
//! contact beyond capacity is refused instead of spilling to the heap.
//!
//! Capture follows W3C: [`PointerTable::set_capture`] / [`PointerTable::release_capture`] write a
//! *pending* target that [`PointerTable::process_pending_capture`] applies before the pointer's
//! next event (returning the lost / got targets); ending a pointer releases only its own capture.

use nativeview_abi::{
    NodeId, NvPointerCaptureRequest, ReprEnum, TimestampUs, NV_POINTER_TYPE_MOUSE, NV_POINTER_TYPE_PEN,
    NV_POINTER_TYPE_TOUCH,
};

pub use nativeview_abi::runtime::MAX_ACTIVE_POINTERS;

/// W3C `pointerType` (`NV_POINTER_TYPE_*`; `try_from_u8` rejects unknown codes).
#[repr(u8)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, ReprEnum)]
pub enum PointerType {
    #[default]
    Mouse = 0,
    Pen = 1,
    Touch = 2,
}

const _: () = assert!(
    PointerType::Mouse as u8 == NV_POINTER_TYPE_MOUSE
        && PointerType::Pen as u8 == NV_POINTER_TYPE_PEN
        && PointerType::Touch as u8 == NV_POINTER_TYPE_TOUCH
);

impl PointerType {

    /// Whether the device reports position without contact (drives `:hover`).
    #[inline]
    pub const fn hovers(self) -> bool {
        !matches!(self, Self::Touch)
    }

    /// Direct-manipulation devices implicitly capture their down target (W3C).
    #[inline]
    pub const fn captures_implicitly(self) -> bool {
        !matches!(self, Self::Mouse)
    }
}

/// Identity of one pointer: its device kind plus the host's pointer id.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub struct PointerKey {
    pub kind: PointerType,
    pub id: u32,
}

impl PointerKey {
    /// The system mouse (pointer id 1, as every host reports it).
    pub const MOUSE: Self = Self::new(PointerType::Mouse, 1);

    #[inline]
    pub const fn new(kind: PointerType, id: u32) -> Self {
        Self { kind, id }
    }
}

/// An app's W3C `setPointerCapture` (`capture`) / `releasePointerCapture` call, collected during
/// dispatch and applied by the runtime as the pointer's pending capture.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct PointerCaptureRequest {
    pub key: PointerKey,
    pub node: NodeId,
    pub capture: bool,
}

impl PointerCaptureRequest {
    /// The C ABI record (`NvPointerApi`).
    #[inline]
    pub const fn to_abi(self) -> NvPointerCaptureRequest {
        NvPointerCaptureRequest {
            node: self.node,
            id: self.key.id,
            kind: self.key.kind.as_u8(),
            capture: self.capture as u8,
            _pad: 0,
        }
    }

    /// The request of C ABI record `r` (`None`: unknown pointer type, `capture > 1` or nonzero
    /// padding).
    #[inline]
    pub fn from_abi(r: NvPointerCaptureRequest) -> Option<Self> {
        let kind = PointerType::try_from_u8(r.kind)?;
        (r.capture <= 1 && r._pad == 0).then_some(Self {
            key: PointerKey::new(kind, r.id),
            node: r.node,
            capture: r.capture == 1,
        })
    }
}

/// Why a capture request was refused (W3C `setPointerCapture` exceptions).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CaptureError {
    /// The pointer is not active (no pressed button / contact): W3C `NotFoundError`.
    InvalidPointer,
    /// The target is disabled or not connected: W3C `InvalidStateError`.
    InvalidTarget,
}

/// The table is full: the contact was refused.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct PointerOverflow;

/// Capture targets that changed when a pending capture was processed (`NULL` = none).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct CaptureTransition {
    pub lost: NodeId,
    pub got: NodeId,
}

impl CaptureTransition {
    #[inline]
    pub const fn is_empty(&self) -> bool {
        self.lost.is_null() && self.got.is_null()
    }
}

/// One active pointer.
#[derive(Debug, Clone, Copy, PartialEq, Default)]
pub struct PointerSlot {
    pub key: PointerKey,
    /// W3C `isPrimary`, fixed when the pointer became active.
    pub primary: bool,
    /// A modal swallowed the press: the pointer's events are dropped until it ends.
    pub blocked: bool,
    /// Pressed buttons at the latest sample.
    pub buttons: u16,
    /// Hit target of the down (the press target; `NULL` when nothing was hit).
    pub down_target: NodeId,
    /// Hit target of the latest uncaptured sample (per-pointer enter / leave).
    pub last_target: NodeId,
    /// Current capture target (`NULL` = none).
    pub capture: NodeId,
    /// Pending capture target applied before the pointer's next event.
    pub pending_capture: NodeId,
    /// The capture is a claim (declarative or app-requested), not an implicit touch capture.
    pub claimed: bool,
    pub down_xy: [f32; 2],
    pub last_xy: [f32; 2],
    pub down_ts: TimestampUs,
}

/// Fixed-capacity active pointer table (see the module docs).
#[derive(Debug, Clone, Default)]
pub struct PointerTable {
    slots: [PointerSlot; MAX_ACTIVE_POINTERS],
    /// Bit `i` set: `slots[i]` is live.
    live: u16,
    /// Settings-imposed capacity (`<= MAX_ACTIVE_POINTERS`; `0` = full capacity).
    limit: u8,
}

const _: () = assert!(MAX_ACTIVE_POINTERS <= u16::BITS as usize);

impl PointerTable {
    #[inline]
    pub const fn len(&self) -> usize {
        self.live.count_ones() as usize
    }

    #[inline]
    pub const fn is_empty(&self) -> bool {
        self.live == 0
    }

    /// Caps simultaneously tracked pointers (`1..=MAX_ACTIVE_POINTERS`); live slots stay.
    #[inline]
    pub fn set_limit(&mut self, limit: usize) {
        self.limit = limit.clamp(1, MAX_ACTIVE_POINTERS) as u8;
    }

    #[inline]
    fn capacity(&self) -> usize {
        if self.limit == 0 { MAX_ACTIVE_POINTERS } else { self.limit as usize }
    }

    #[inline]
    fn index_of(&self, key: PointerKey) -> Option<usize> {
        (0..MAX_ACTIVE_POINTERS).find(|&i| self.live & (1 << i) != 0 && self.slots[i].key == key)
    }

    #[inline]
    pub fn get(&self, key: PointerKey) -> Option<&PointerSlot> {
        self.index_of(key).map(|i| &self.slots[i])
    }

    #[inline]
    pub fn get_mut(&mut self, key: PointerKey) -> Option<&mut PointerSlot> {
        self.index_of(key).map(|i| &mut self.slots[i])
    }

    /// Live slots in slot order.
    pub fn iter(&self) -> impl Iterator<Item = &PointerSlot> {
        (0..MAX_ACTIVE_POINTERS).filter(|&i| self.live & (1 << i) != 0).map(|i| &self.slots[i])
    }

    /// The first active primary slot.
    pub fn primary(&self) -> Option<&PointerSlot> {
        self.iter().find(|s| s.primary)
    }

    /// W3C primary rule: the mouse is always primary; a pen or touch contact is primary when no
    /// other pointer of its kind is active.
    pub fn would_be_primary(&self, key: PointerKey) -> bool {
        if let Some(slot) = self.get(key) {
            return slot.primary;
        }
        key.kind == PointerType::Mouse || !self.iter().any(|s| s.key.kind == key.kind)
    }

    /// Activates `key` (no-op returning the slot when already active).
    pub fn begin(
        &mut self,
        key: PointerKey,
        at: [f32; 2],
        ts: TimestampUs,
        target: NodeId,
    ) -> Result<&mut PointerSlot, PointerOverflow> {
        if let Some(i) = self.index_of(key) {
            return Ok(&mut self.slots[i]);
        }
        if self.len() >= self.capacity() {
            return Err(PointerOverflow);
        }
        let primary = self.would_be_primary(key);
        let i = (0..MAX_ACTIVE_POINTERS).find(|&i| self.live & (1 << i) == 0).ok_or(PointerOverflow)?;
        self.live |= 1 << i;
        self.slots[i] = PointerSlot {
            key,
            primary,
            down_target: target,
            last_target: target,
            down_xy: at,
            last_xy: at,
            down_ts: ts,
            ..PointerSlot::default()
        };
        Ok(&mut self.slots[i])
    }

    /// Ends `key`, returning its final slot.
    pub fn end(&mut self, key: PointerKey) -> Option<PointerSlot> {
        let i = self.index_of(key)?;
        self.live &= !(1 << i);
        Some(core::mem::take(&mut self.slots[i]))
    }

    /// Captures `key` to `node` immediately (implicit / declarative capture at down).
    pub fn capture_now(&mut self, key: PointerKey, node: NodeId, claimed: bool) -> Result<(), CaptureError> {
        let slot = self.get_mut(key).ok_or(CaptureError::InvalidPointer)?;
        slot.capture = node;
        slot.pending_capture = node;
        slot.claimed = claimed && !node.is_null();
        Ok(())
    }

    /// W3C `setPointerCapture`: sets `key`'s pending capture target (`node` must be valid for
    /// the caller, see [`CaptureError::InvalidTarget`]).
    pub fn set_capture(&mut self, key: PointerKey, node: NodeId) -> Result<(), CaptureError> {
        if node.is_null() {
            return Err(CaptureError::InvalidTarget);
        }
        self.get_mut(key).ok_or(CaptureError::InvalidPointer)?.pending_capture = node;
        Ok(())
    }

    /// W3C `releasePointerCapture`: clears `key`'s pending capture when `node` holds it (or any
    /// node when `node` is `NULL`).
    pub fn release_capture(&mut self, key: PointerKey, node: NodeId) -> Result<(), CaptureError> {
        let slot = self.get_mut(key).ok_or(CaptureError::InvalidPointer)?;
        if node.is_null() || slot.pending_capture == node {
            slot.pending_capture = NodeId::NULL;
        }
        Ok(())
    }

    /// W3C `hasPointerCapture`: `node` is `key`'s pending capture target.
    #[inline]
    pub fn has_capture(&self, key: PointerKey, node: NodeId) -> bool {
        !node.is_null() && self.get(key).is_some_and(|s| s.pending_capture == node)
    }

    /// Current capture target of `key`.
    #[inline]
    pub fn capture_of(&self, key: PointerKey) -> Option<NodeId> {
        self.get(key).map(|s| s.capture).filter(|n| !n.is_null())
    }

    /// Applies `key`'s pending capture; an app request (anything but the implicit target)
    /// becomes a claim.
    pub fn process_pending_capture(&mut self, key: PointerKey) -> CaptureTransition {
        let Some(slot) = self.get_mut(key) else {
            return CaptureTransition::default();
        };
        if slot.pending_capture == slot.capture {
            return CaptureTransition::default();
        }
        let t = CaptureTransition { lost: slot.capture, got: slot.pending_capture };
        slot.capture = slot.pending_capture;
        slot.claimed = !slot.capture.is_null();
        t
    }

    /// Drops capture (current and pending) on every slot where `drop(node)` holds; returns
    /// whether anything changed.
    pub fn prune_captures(&mut self, mut drop: impl FnMut(NodeId) -> bool) -> bool {
        let mut changed = false;
        for i in 0..MAX_ACTIVE_POINTERS {
            if self.live & (1 << i) == 0 {
                continue;
            }
            let s = &mut self.slots[i];
            if !s.capture.is_null() && drop(s.capture) {
                s.capture = NodeId::NULL;
                s.claimed = false;
                changed = true;
            }
            if !s.pending_capture.is_null() && drop(s.pending_capture) {
                s.pending_capture = NodeId::NULL;
                changed = true;
            }
        }
        changed
    }

    /// Ends every slot.
    #[inline]
    pub fn clear(&mut self) {
        self.live = 0;
    }

    /// Keys of every live slot (copied out so callers can mutate while iterating).
    pub fn keys(&self) -> ([PointerKey; MAX_ACTIVE_POINTERS], usize) {
        let mut out = [PointerKey::default(); MAX_ACTIVE_POINTERS];
        let mut n = 0;
        for s in self.iter() {
            out[n] = s.key;
            n += 1;
        }
        (out, n)
    }
}