nativeview-layout 0.1.0-rc.1

Shared NodeStore layout layer: StoreLayoutEngine / TextMeasurer traits and the default direct Taffy engine
Documentation
//! Core pointer resolution: one host-agnostic stage that turns untargeted raw pointer samples
//! (`EventFlags::RAW_POINTER`, see `nativeview_abi::EventBatchBuf::push_pointer_raw`) into the
//! targeted W3C Pointer Events stream every app sees, on every host.
//!
//! Per sample the stage runs, in order:
//! 1. **Top-layer press** (primary `PointerDown`): the HTML "hide popovers until" walk
//!    ([`super::top_layer_press`]) emits the light-dismiss `close` events; a press outside the
//!    topmost modal is swallowed ([`PointerOutcomeFlags::MODAL_BARRIER`]) until it ends.
//! 2. **Hit-test / capture**: a captured pointer targets its capture node; otherwise the deepest
//!    interaction target ([`PointerHitTest`]). Captures are W3C: pending targets
//!    ([`InteractionTracker::pointers_mut`]) switch before the pointer's next sample, emitting
//!    `LostPointerCapture` / `GotPointerCapture`; touch and pen capture their down target
//!    implicitly; a `capture_on_primary_down` owner ([`nativeview_engine::ext::input::capture_owner`])
//!    claims the pointer ([`PointerOutcomeFlags::CLAIMED`]).
//! 3. **`PointerTable` + tracker**: `:hover` follows the primary hover-capable pointer, `:active`
//!    and `Press` the primary pointer only; a contact beyond the table's capacity is refused
//!    ([`PointerOutcomeFlags::REFUSED`]) with a `PointerCancel`.
//! 4. **Synthesis**: non-bubbling `PointerLeave` / `PointerEnter` transitions, the targeted
//!    pointer event, capture changes, and `Press` on a primary release over the press chain.
//!
//! Resolution is split in two so a hit tester may borrow the scene (or the backend owning it):
//! [`PointerProbe::new`] reads (hits, top-layer decision, capture owner) and
//! [`LaidOutScene::apply_pointer`] mutates the tracker. [`LaidOutScene::resolve_pointer`] runs
//! both against the scene's own hit test (`SurfaceRuntime`); the Skia backend probes with its
//! paint-accurate hit test. Zero heap allocations in steady state.

mod geometry;
mod resolve;

use nativeview_abi::{
    is_raw_pointer_kind, EventBatchBuf, EventFlags, InteractionEvent, NodeId, TimestampUs, ValidatedEvent,
};
use nativeview_engine::tracker::{PointerKey, PointerType};
use nativeview_store::NodeStore;

pub use geometry::SceneGeometry;
pub use nativeview_abi::runtime::PointerOutcomeFlags;

use super::{LaidOutScene, ResolvedOverlay, TopLayerPress};
use crate::StoreLayoutEngine;

/// The geometry queries the stage needs. Backends with paint-accurate state (live animated
/// transforms, the painted stacking plan) implement it over their own hit test.
pub trait PointerHitTest {
    /// The deepest interaction target at `(x, y)` (falling back to any event target).
    fn hit_interaction(&self, store: &NodeStore, x: f32, y: f32) -> Option<NodeId>;
    /// The deepest painted node at `(x, y)`, unfiltered (the top-layer press hit).
    fn hit_painted(&self, store: &NodeStore, x: f32, y: f32) -> Option<NodeId>;
    /// Whether `(x, y)` lies inside the (transform-aware) box of open overlay `ro`.
    fn overlay_contains(&self, store: &NodeStore, ro: ResolvedOverlay, x: f32, y: f32) -> bool;
}

impl<L: StoreLayoutEngine> PointerHitTest for LaidOutScene<L> {
    #[inline]
    fn hit_interaction(&self, store: &NodeStore, x: f32, y: f32) -> Option<NodeId> {
        self.hit_test_interaction(store, x, y).or_else(|| self.hit_test(store, x, y))
    }

    #[inline]
    fn hit_painted(&self, store: &NodeStore, x: f32, y: f32) -> Option<NodeId> {
        self.hit_test_painted(store, x, y)
    }

    #[inline]
    fn overlay_contains(&self, store: &NodeStore, ro: ResolvedOverlay, x: f32, y: f32) -> bool {
        self.overlay_contains_point(store, ro, x, y)
    }
}

/// What one raw sample resolved to.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct PointerResolution {
    /// `NV_POINTER_OUTCOME_*` bits for the host.
    pub outcome: PointerOutcomeFlags,
    /// A pseudo-state (`:hover`, `:active`) changed: republish / repaint.
    pub changed: bool,
    /// The change re-ran layout (state rules patching the box).
    pub relayout: bool,
    /// Primary release over the press chain: the `Press` target.
    pub clicked: Option<NodeId>,
    /// The sample's pointer is captured after it (the capture target).
    pub capture: Option<NodeId>,
    /// Primary button-0 `Down`: the deepest painted node (hosts reuse it for press focus).
    pub painted: Option<NodeId>,
}

/// The read-only half of resolution (see the module docs).
#[derive(Debug, Clone, Copy)]
pub struct PointerProbe {
    pub key: PointerKey,
    /// The sample's kind: one of [`is_raw_pointer_kind`].
    pub phase: InteractionEvent,
    /// The pointer button of a `Down` / `Up` (`0` = primary).
    pub button: u8,
    pub x: f32,
    pub y: f32,
    pub timestamp: TimestampUs,
    /// The deepest interaction target (`None` while captured, for `Cancel` / `Leave`).
    pub hit: Option<NodeId>,
    /// Primary `Down`: the deepest painted node (hosts reuse it for press focus).
    pub painted: Option<NodeId>,
    /// The valid capture the sample routes to (pending capture applied, invalid targets dropped).
    pub capture: Option<NodeId>,
    /// `Down`: the declarative `capture_on_primary_down` owner of the hit.
    pub owner: Option<NodeId>,
    /// Primary `Down`: the top-layer decision (its closes are already in the output batch).
    pub press: Option<TopLayerPress>,
}

impl PointerProbe {
    /// Probes raw sample `ev` (`None` when it is not a raw pointer sample) against `scene`'s
    /// tracker and `hit`, appending the top-layer light-dismiss `close` events to `out`.
    pub fn new<L: StoreLayoutEngine>(
        scene: &LaidOutScene<L>,
        store: &NodeStore,
        ev: &ValidatedEvent<'_>,
        hit: &impl PointerHitTest,
        out: &mut EventBatchBuf,
    ) -> Option<Self> {
        if !ev.is_raw_pointer() {
            return None;
        }
        let phase = ev.interaction().filter(|&k| is_raw_pointer_kind(k))?;
        let key = PointerKey::new(PointerType::try_from_u8(ev.pointer_type())?, ev.pointer_id());
        let (x, y) = (ev.x(), ev.y());
        let mut probe = Self {
            key,
            phase,
            button: ev.pointer_button(),
            x,
            y,
            timestamp: ev.timestamp(),
            hit: None,
            painted: None,
            capture: None,
            owner: None,
            press: None,
        };
        let tracker = &scene.interaction;
        probe.capture = tracker
            .pointers()
            .get(key)
            .map(|s| s.pending_capture)
            .filter(|&n| scene.is_capture_target(store, n));
        let begins = phase == InteractionEvent::PointerDown && probe.button == 0;
        let hits = match phase {
            InteractionEvent::PointerDown => begins || probe.capture.is_none(),
            InteractionEvent::PointerMove => probe.capture.is_none(),
            InteractionEvent::PointerUp => true,
            _ => false,
        };
        if hits {
            probe.hit = hit.hit_interaction(store, x, y);
        }
        if begins {
            probe.owner = probe
                .hit
                .and_then(|h| nativeview_engine::ext::input::capture_owner(store, h))
                .filter(|&o| !scene.is_subtree_disabled(store, o));
            if tracker.pointers().would_be_primary(key) {
                probe.painted = hit.hit_painted(store, x, y);
                let press = scene.top_layer_press_at(store, probe.painted, |ro| hit.overlay_contains(store, ro, x, y));
                for node in press.light_dismissed(scene.open_overlays()) {
                    out.push_custom_with_flags(ev.surface(), node, ev.timestamp(), "close", &[], EventFlags::NO_BUBBLE);
                }
                probe.press = Some(press);
            }
        }
        Some(probe)
    }
}

impl<L: StoreLayoutEngine> LaidOutScene<L> {
    /// Whether `node` may hold pointer capture: connected and not in a disabled subtree.
    #[inline]
    pub fn is_capture_target(&self, store: &NodeStore, node: NodeId) -> bool {
        !node.is_null() && store.is_connected(node) && !self.is_subtree_disabled(store, node)
    }

    /// Caps simultaneously tracked pointers (`NvGestureSettings::max_pointers`).
    #[inline]
    pub fn set_max_pointers(&mut self, max: usize) {
        self.interaction.pointers_mut().set_limit(max);
    }

    /// The top-layer press decision over the open overlays for press hit `painted`.
    pub fn top_layer_press_at(
        &self,
        store: &NodeStore,
        painted: Option<NodeId>,
        contains: impl Fn(ResolvedOverlay) -> bool,
    ) -> TopLayerPress {
        super::top_layer_press(
            self.open_overlays(),
            self.topmost_modal(),
            painted,
            |node, ancestor| nativeview_engine::is_within_subtree(store, node, ancestor),
            |&ro| contains(ro),
        )
    }

    /// Resolves raw sample `ev` against the scene's own hit test, appending the targeted events
    /// to `out` (`None` when `ev` is not a raw pointer sample).
    pub fn resolve_pointer(
        &mut self,
        store: &NodeStore,
        ev: &ValidatedEvent<'_>,
        out: &mut EventBatchBuf,
    ) -> Option<PointerResolution> {
        let probe = PointerProbe::new(self, store, ev, self, out)?;
        Some(self.apply_pointer(store, ev, &probe, out))
    }
}