nativeview-engine 0.1.0-rc.1

Framework-agnostic scene engine traits, hot-reload cdylib loader, and Frame-0 snapshot codecs.
Documentation
//! Shared `TARGET_LOCAL_NORM` annotation: pointer coordinates normalized to the box of the
//! pointer's *owner*, so a slider track maps a drag 1:1 even while the pointer is outside it or
//! the track is scrolled or transformed. The box comes from a [`PointerGeometry`] (the laid-out
//! scene for `SurfaceRuntime` hosts, live Skia visual rects in the desktop shell, DOM rects on
//! the Web); events that already carry a norm are left untouched.

use nativeview_abi::{EventBatchBuf, EventFlags, EventSet, InteractionEvent, LayoutEvent, NodeId};
use nativeview_store::{NodeStore, NvTable};
use nativeview_tables::tables::{Interaction, Layout, PointerCaptureMode};

use super::PointerGeometry;

/// The one capture-owner walk every host shares: the nearest `capture_on_primary_down`
/// ancestor-or-self of `target`, or `None` when there is none or `target` lies in a disabled
/// subtree (a disabled ancestor anywhere up to the root disables capture, as `:disabled`
/// inherits). One `O(depth)` walk.
pub fn capture_owner(store: &NodeStore, target: NodeId) -> Option<NodeId> {
    let mut owner = None;
    let mut cur = target;
    for _ in 0..nativeview_store::MAX_TREE_DEPTH {
        if let Some(i) = store.try_row::<Interaction>(cur) {
            if i.disabled() {
                return None;
            }
            if owner.is_none() && i.capture_mode() == PointerCaptureMode::OnPrimaryDown {
                owner = Some(cur);
            }
        }
        match store.parent(cur) {
            Some(p) if p != cur => cur = p,
            _ => break,
        }
    }
    owner
}

/// The node whose box a pointer event's norm is relative to: the [`capture_owner`] of the target
/// (the control that captures, or already captured, the drag: captured events target that owner,
/// a capturing `PointerDown` may target a child such as a thumb), else the target itself.
#[inline]
pub fn pointer_norm_owner(store: &NodeStore, target: NodeId) -> NodeId {
    capture_owner(store, target).unwrap_or(target)
}

/// `id` itself listens for `ev` on the `Interaction` table.
#[inline]
pub fn has_direct_listener(store: &NodeStore, id: NodeId, ev: InteractionEvent) -> bool {
    store.try_row::<Interaction>(id).is_some_and(|i| i.listeners().contains(ev))
}

/// `start` or an ancestor listens for `ev` (a bubbling event reaches a listener).
pub fn has_ancestor_listener(store: &NodeStore, start: NodeId, ev: InteractionEvent) -> bool {
    let mut cur = start;
    for _ in 0..nativeview_store::MAX_TREE_DEPTH {
        if has_direct_listener(store, cur, ev) {
            return true;
        }
        match store.parent(cur) {
            Some(p) if p != cur => cur = p,
            _ => return false,
        }
    }
    false
}

#[inline]
const fn carries_position(kind: InteractionEvent) -> bool {
    matches!(
        kind,
        InteractionEvent::PointerDown | InteractionEvent::PointerMove | InteractionEvent::PointerUp
    )
}

/// `(x, y)` normalized to `owner`'s box in `geometry`; `None` without a usable box.
#[inline]
pub fn local_norm<G: PointerGeometry + ?Sized>(
    geometry: &G,
    owner: NodeId,
    x: f32,
    y: f32,
) -> Option<(f32, f32)> {
    let r = geometry.local_rect(owner)?;
    nativeview_abi::target_local_norm(r.x, r.y, r.width, r.height, x, y)
}

/// Whether any pointer event of `events` still lacks a norm (callers copy a borrowed batch only
/// then).
pub fn needs_pointer_norms(events: nativeview_abi::ValidatedEvents<'_>) -> bool {
    events.iter().any(|ev| {
        ev.interaction().is_some_and(carries_position)
            && !ev.flags().contains(EventFlags::TARGET_LOCAL_NORM)
    })
}

/// Attaches norms in place to every positioned pointer event (`PointerDown` / `Move` / `Up`)
/// that lacks one: one [`PointerGeometry::local_rect`] call per such event, none otherwise.
/// When a `PointerDown` targets an owner subscribed to [`LayoutEvent::Layout`], inserts the
/// owner's live visual rect immediately ahead of that `PointerDown` so handlers reading both
/// layout bounds and pointer norms see exact geometry. Allocation-free when no `Layout` event is
/// inserted.
pub fn annotate_pointer_norms<G: PointerGeometry + ?Sized>(
    store: &NodeStore,
    events: &mut EventBatchBuf,
    geometry: &G,
) {
    let mut index = 0usize;
    while index < events.len() {
        let Some(ev) = events.as_validated().get(index) else {
            break;
        };
        let Some(kind) = ev.interaction().filter(|&k| carries_position(k)) else {
            index += 1;
            continue;
        };
        let needs_norm = !ev.flags().contains(EventFlags::TARGET_LOCAL_NORM);
        let owner = pointer_norm_owner(store, ev.node());
        let needs_layout = kind == InteractionEvent::PointerDown
            && EventSet::<LayoutEvent>::from_raw(store.node_events_mask(Layout::slot(), owner))
                .contains(LayoutEvent::Layout);
        if !needs_norm && !needs_layout {
            index += 1;
            continue;
        }
        let (surface, ts, x, y) = (ev.surface(), ev.timestamp(), ev.x(), ev.y());
        if let Some(r) = geometry.local_rect(owner) {
            if needs_norm
                && let Some((nx, ny)) = nativeview_abi::target_local_norm(r.x, r.y, r.width, r.height, x, y)
            {
                events.set_target_local_norm(index, nx, ny);
            }
            if needs_layout && r.width.is_finite() && r.height.is_finite() && r.width > 0.0 && r.height > 0.0 {
                events.insert_layout_before(index, surface, owner, ts, r.x, r.y, r.width, r.height);
                index += 1;
            }
        }
        index += 1;
    }
}