nativeview-engine 0.1.0-rc.1

Framework-agnostic scene engine traits, hot-reload cdylib loader, and Frame-0 snapshot codecs.
Documentation
//! Reusable zero-allocation stateful interaction tracker (`InteractionTracker`) shared by every
//! scene consumer (`LaidOutScene`, `SkiaBackend`, the runtime pointer-resolution stage).
//!
//! Tracks leaf-to-root ancestor chains for `:hover`, `:active` and `:drag-over`, the active
//! pointers and their W3C capture ([`PointerTable`]), `:focus` + [`FocusModality`]
//! (`:focus-visible`), and `:disabled`. `:hover` follows the primary hover-capable pointer
//! (mouse, hovering pen); `:active` and `Press` follow the primary pointer only, so a second
//! finger never steals them. All steady-state transitions reuse internal scratch buffers with
//! zero heap allocations.
//!
//! - [`chains`]: hover / active / drag-over chain transitions and their dirty sets.
//! - [`focus`]: focus and modality.
//! - [`pointers`]: the fixed-capacity [`PointerTable`].

mod chains;
mod focus;
pub mod pointers;

use nativeview_abi::hash::HashSet;
use nativeview_abi::NodeId;
use nativeview_tables::interaction::{resolve_focus_visible, FocusModality, InteractionState};

use crate::focus::FocusAnchor;

pub use chains::PointerEnd;
pub use pointers::{
    CaptureError, CaptureTransition, PointerCaptureRequest, PointerKey, PointerType,
    PointerOverflow, PointerSlot, PointerTable, MAX_ACTIVE_POINTERS,
};

const MAX_CHAIN_DEPTH: usize = 256;

/// Reusable stateful interaction tracker (see the module docs).
#[derive(Debug, Clone, Default)]
pub struct InteractionTracker {
    /// Leaf-to-root hovered ancestor chain (`[leaf, parent, ..., root]`).
    hovered_chain: Vec<NodeId>,
    /// Leaf-to-root active (non-disabled) ancestor chain of [`Self::active_key`]'s press.
    active_chain: Vec<NodeId>,
    /// The primary pointer whose press owns `active_chain`.
    active_key: Option<PointerKey>,
    /// Leaf-to-root `:drag-over` ancestor chain (zero recomposition on drag hover).
    drag_over_chain: Vec<NodeId>,
    /// Active pointers and their capture.
    pointers: PointerTable,
    focused: Option<NodeId>,
    focus_modality: FocusModality,
    last_input_modality: FocusModality,
    focused_is_text_entry: bool,
    focus_anchor: FocusAnchor,
    disabled: HashSet<NodeId>,
    /// Top-down (`root -> leaf`) nodes that entered hover on the latest move/down/up transition.
    entered_scratch: Vec<NodeId>,
    /// Bottom-up (`leaf -> root`) nodes that exited hover on the latest move/down/up/leave/cancel.
    exited_scratch: Vec<NodeId>,
    /// Top-down (`root -> leaf`) nodes that entered `:drag-over` on the latest drag-over update.
    drag_entered_scratch: Vec<NodeId>,
    /// Bottom-up (`leaf -> root`) nodes that exited `:drag-over` on the latest drag-over update.
    drag_exited_scratch: Vec<NodeId>,
    /// Sorted deduplicated dirty `NodeId`s produced by the latest transition.
    prev_dirty_scratch: Vec<NodeId>,
    /// Reusable buffer for assembling the next leaf-to-root ancestor chain.
    next_chain_scratch: Vec<NodeId>,
    /// Reusable buffer snapshotting prior [`InteractionState`] of candidate nodes.
    candidate_scratch: Vec<(NodeId, InteractionState)>,
}

impl InteractionTracker {
    pub fn new() -> Self {
        Self::default()
    }

    #[inline]
    pub fn hovered(&self) -> Option<NodeId> {
        self.hovered_chain.first().copied()
    }

    #[inline]
    pub fn active(&self) -> Option<NodeId> {
        self.active_chain.first().copied()
    }

    #[inline]
    pub fn hovered_chain(&self) -> &[NodeId] {
        &self.hovered_chain
    }

    #[inline]
    pub fn active_chain(&self) -> &[NodeId] {
        &self.active_chain
    }

    /// The primary pointer whose press owns `:active`.
    #[inline]
    pub fn active_key(&self) -> Option<PointerKey> {
        self.active_key
    }

    #[inline]
    pub fn drag_over(&self) -> Option<NodeId> {
        self.drag_over_chain.first().copied()
    }

    #[inline]
    pub fn drag_over_chain(&self) -> &[NodeId] {
        &self.drag_over_chain
    }

    /// Top-down (`root -> leaf`) nodes that entered `:drag-over` on the latest drag-over update.
    #[inline]
    pub fn drag_entered(&self) -> &[NodeId] {
        &self.drag_entered_scratch
    }

    /// Bottom-up (`leaf -> root`) nodes that exited `:drag-over` on the latest drag-over update.
    #[inline]
    pub fn drag_exited(&self) -> &[NodeId] {
        &self.drag_exited_scratch
    }

    /// The active pointers.
    #[inline]
    pub fn pointers(&self) -> &PointerTable {
        &self.pointers
    }

    /// Mutable active pointers (capture requests, settings-imposed capacity).
    #[inline]
    pub fn pointers_mut(&mut self) -> &mut PointerTable {
        &mut self.pointers
    }

    /// `(pointer, capture target)` of the primary pointer, when it is captured.
    #[inline]
    pub fn captured(&self) -> Option<(PointerKey, NodeId)> {
        let slot = self.pointers.primary()?;
        (!slot.capture.is_null()).then_some((slot.key, slot.capture))
    }

    /// The primary pointer's capture target.
    #[inline]
    pub fn captured_node(&self) -> Option<NodeId> {
        self.captured().map(|(_, n)| n)
    }

    /// Whether the press owning `:active` is captured (drag-off then keeps `:active`).
    #[inline]
    fn active_press_captured(&self) -> bool {
        self.active_key.is_some_and(|k| self.pointers.capture_of(k).is_some())
    }

    #[inline]
    pub fn focused(&self) -> Option<NodeId> {
        self.focused
    }

    #[inline]
    pub fn focus_modality(&self) -> FocusModality {
        self.focus_modality
    }

    #[inline]
    pub fn last_input_modality(&self) -> FocusModality {
        self.last_input_modality
    }

    #[inline]
    pub fn is_disabled(&self, id: NodeId) -> bool {
        self.disabled.contains(&id)
    }

    /// Top-down (`root -> leaf`) nodes that entered hover during the latest pointer transition.
    #[inline]
    pub fn entered(&self) -> &[NodeId] {
        &self.entered_scratch
    }

    /// Bottom-up (`leaf -> root`) nodes that exited hover during the latest pointer transition.
    #[inline]
    pub fn exited(&self) -> &[NodeId] {
        &self.exited_scratch
    }

    /// Sorted, deduplicated dirty `NodeId`s from the latest transition.
    #[inline]
    pub fn last_dirty(&self) -> &[NodeId] {
        &self.prev_dirty_scratch
    }

    /// Returns the node that currently governs the window pointer cursor:
    /// prefers the primary capture, then `active`, falling back to `hovered`.
    #[inline]
    pub fn active_cursor_node(&self) -> Option<NodeId> {
        self.captured_node()
            .or_else(|| self.active())
            .or_else(|| self.hovered())
    }

    /// Computes the exact active [`InteractionState`] flags for `id` (O(chains); pointer slots
    /// never feed the cascade).
    #[inline]
    pub fn state(&self, id: NodeId) -> InteractionState {
        let mut s = InteractionState::NONE;
        if self.hovered_chain.contains(&id) {
            s |= InteractionState::HOVER;
        }
        if self.focused == Some(id) {
            s |= InteractionState::FOCUS;
            if resolve_focus_visible(
                self.focus_modality,
                self.last_input_modality,
                self.focused_is_text_entry,
            ) {
                s |= InteractionState::FOCUS_VISIBLE;
            }
        }
        if self.active_chain.contains(&id) {
            s |= InteractionState::ACTIVE;
        }
        if self.drag_over_chain.contains(&id) {
            s |= InteractionState::DRAG_OVER;
        }
        if self.disabled.contains(&id) {
            s |= InteractionState::DISABLED;
        }
        s
    }

    /// Marks `id` disabled or enabled (zero-alloc when `disabled` set already has capacity).
    /// Disabling clears `active`, `focused`, and every pointer capture on `id`.
    pub fn set_disabled_slice(&mut self, id: NodeId, disabled: bool) -> &[NodeId] {
        self.candidate_scratch.clear();
        self.push_candidate_id(id);
        if disabled {
            self.disabled.insert(id);
            self.active_chain.retain(|&n| n != id);
            self.drag_over_chain.retain(|&n| n != id);
            if self.focused == Some(id) {
                self.focused = None;
            }
            let _ = self.pointers.prune_captures(|n| n == id);
        } else {
            self.disabled.remove(&id);
        }
        self.finalize_dirty()
    }

    /// Prunes nodes where `keep(id)` is `false` from hover, active, drag-over, and every pointer
    /// capture (0-alloc).
    pub fn prune_disconnected(&mut self, mut keep: impl FnMut(NodeId) -> bool) -> bool {
        let mut changed = false;
        for c in [&mut self.hovered_chain, &mut self.active_chain, &mut self.drag_over_chain] {
            let n = c.len();
            c.retain(|&id| keep(id));
            changed |= c.len() != n;
        }
        changed | self.pointers.prune_captures(|id| !keep(id))
    }

    /// Removes `id` from all tracked chains, captures, focus, and disabled state (zero-alloc).
    pub fn remove_node_slice(&mut self, id: NodeId) -> &[NodeId] {
        let prev = self.state(id);
        self.hovered_chain.retain(|&n| n != id);
        self.active_chain.retain(|&n| n != id);
        self.drag_over_chain.retain(|&n| n != id);
        if self.focused == Some(id) {
            self.focused = None;
        }
        let _ = self.pointers.prune_captures(|n| n == id);
        self.disabled.remove(&id);
        self.prev_dirty_scratch.clear();
        if prev != InteractionState::NONE {
            self.prev_dirty_scratch.push(id);
        }
        &self.prev_dirty_scratch
    }

    /// Resets all tracked interaction state (retaining scratch capacity).
    pub fn clear(&mut self) {
        self.hovered_chain.clear();
        self.active_chain.clear();
        self.active_key = None;
        self.drag_over_chain.clear();
        self.pointers.clear();
        self.focused = None;
        self.focus_modality = FocusModality::Pointer;
        self.last_input_modality = FocusModality::Pointer;
        self.focused_is_text_entry = false;
        self.focus_anchor.clear();
        self.disabled.clear();
        self.entered_scratch.clear();
        self.exited_scratch.clear();
        self.drag_entered_scratch.clear();
        self.drag_exited_scratch.clear();
        self.prev_dirty_scratch.clear();
        self.next_chain_scratch.clear();
        self.candidate_scratch.clear();
    }
}