nativeview-engine 0.1.0-rc.1

Framework-agnostic scene engine traits, hot-reload cdylib loader, and Frame-0 snapshot codecs.
Documentation
use std::cell::RefCell;
use std::rc::Rc;

use nativeview_abi::{
    EventBatchBuf, EventFlags, InteractionEvent, NV_POINTER_TYPE_MOUSE, NodeId, SurfaceId,
    TimestampUs,
};

use super::*;

type Log = Rc<RefCell<Vec<&'static str>>>;

struct Probe {
    name: &'static str,
    disposition: Disposition,
    log: Log,
}

impl InputInterceptor<u32> for Probe {
    fn intercept(&mut self, ev: &ValidatedEvent<'_>, cx: &mut u32) -> Disposition {
        assert_eq!(ev.key(), "a");
        *cx += 1;
        self.log.borrow_mut().push(self.name);
        self.disposition
    }
}

fn probe(name: &'static str, disposition: Disposition, log: &Log) -> Box<Probe> {
    Box::new(Probe { name, disposition, log: Rc::clone(log) })
}

fn key_down() -> EventBatchBuf {
    let mut buf = EventBatchBuf::new();
    buf.push_key_down(SurfaceId::ROOT, NodeId::ROOT, TimestampUs(1), "a", "KeyA", EventFlags::EMPTY, 65);
    buf
}

const KEYS: InputKinds = KEY_DOWN;

#[test]
fn registration_order_is_priority_and_the_first_consumer_stops_dispatch() {
    let log = Log::default();
    let mut chain = InterceptorChain::<u32>::new();
    chain.push(KEYS, probe("first", Disposition::PassThrough, &log));
    chain.push(KEYS, probe("second", Disposition::Consumed, &log));
    chain.push(KEYS, probe("third", Disposition::ConsumedPreventDefault, &log));
    let buf = key_down();
    let ev = buf.as_validated().get(0).expect("event");
    let mut calls = 0;
    assert_eq!(chain.intercept(&ev, &mut calls), Disposition::Consumed);
    assert_eq!(*log.borrow(), ["first", "second"]);
    assert_eq!(calls, 2, "the context reaches every called hook");
}

#[test]
fn kind_mask_skips_hooks_and_non_interaction_events_reach_none() {
    let log = Log::default();
    let mut chain = InterceptorChain::<u32>::new();
    let pointer = InputKinds::from_raw(1 << InteractionEvent::PointerDown as u32);
    chain.push(pointer, probe("pointer", Disposition::Consumed, &log));
    chain.push(KEYS, probe("key", Disposition::PassThrough, &log));
    let buf = key_down();
    let ev = buf.as_validated().get(0).expect("event");
    assert_eq!(chain.intercept(&ev, &mut 0), Disposition::PassThrough);
    assert_eq!(*log.borrow(), ["key"]);

    let mut text = EventBatchBuf::new();
    text.push_table_event_text(
        nativeview_abi::Key64::of("test.non_interaction"),
        SurfaceId::ROOT,
        NodeId::ROOT,
        TimestampUs(1),
        nativeview_abi::EventId(1),
        EventFlags::EMPTY,
        [0; 6],
        "x",
    );
    let ev = text.as_validated().get(0).expect("event");
    chain.push(InputKinds::ALL, probe("all", Disposition::Consumed, &log));
    assert_eq!(chain.intercept(&ev, &mut 0), Disposition::PassThrough);
    assert_eq!(log.borrow().len(), 1, "text-input events carry no interaction kind");

    let mut moves = EventBatchBuf::new();
    moves.push_pointer_ex(
        SurfaceId::ROOT, NodeId::ROOT, TimestampUs(1), InteractionEvent::PointerMove, 0.0, 0.0, 1,
        0, NV_POINTER_TYPE_MOUSE, EventFlags::EMPTY,
    );
    let ev = moves.as_validated().get(0).expect("event");
    let mut chain = InterceptorChain::<u32>::new();
    chain.push(pointer, probe("down only", Disposition::Consumed, &log));
    assert_eq!(chain.intercept(&ev, &mut 0), Disposition::PassThrough);
}

#[test]
fn remove_unregisters_and_unknown_ids_are_none() {
    let log = Log::default();
    let mut chain = InterceptorChain::<u32>::new();
    let a = chain.push(KEYS, probe("a", Disposition::Consumed, &log));
    let b = chain.push(KEYS, probe("b", Disposition::Consumed, &log));
    assert!(a < b);
    assert!(matches!(chain.remove(a), Some(Some(_))));
    assert!(chain.remove(a).is_none());
    let buf = key_down();
    let ev = buf.as_validated().get(0).expect("event");
    assert!(chain.intercept(&ev, &mut 0).is_consumed());
    assert_eq!(*log.borrow(), ["b"]);
    assert_eq!(chain.len(), 1);
}

/// A hook that removes itself, registers a successor and re-dispatches while it runs.
struct Reentrant {
    chain: Rc<RefCell<DefaultActionChain<u32>>>,
    me: Rc<RefCell<Option<InputHookId>>>,
    log: Log,
}

impl DefaultAction<u32> for Reentrant {
    fn run(&mut self, ev: &ValidatedEvent<'_>, cx: &mut u32) -> Disposition {
        self.log.borrow_mut().push("reentrant");
        let me = self.me.borrow_mut().take().expect("registered");
        assert!(matches!(self.chain.borrow_mut().remove(me), Some(None)), "running: slot empty");
        self.chain.borrow_mut().push(KEYS, Box::new(Tail(Rc::clone(&self.log))));
        let nested = DefaultActionChain::run_default_shared(&self.chain, ev, cx);
        assert_eq!(nested, Disposition::ConsumedPreventDefault, "nested dispatch skips the running hook");
        Disposition::PassThrough
    }
}

struct Tail(Log);

impl DefaultAction<u32> for Tail {
    fn run(&mut self, _: &ValidatedEvent<'_>, _: &mut u32) -> Disposition {
        self.0.borrow_mut().push("tail");
        Disposition::ConsumedPreventDefault
    }
}

#[test]
fn shared_dispatch_is_reentrant() {
    let log = Log::default();
    let chain = Rc::new(RefCell::new(DefaultActionChain::<u32>::new()));
    let me = Rc::new(RefCell::new(None));
    let hook = Reentrant { chain: Rc::clone(&chain), me: Rc::clone(&me), log: Rc::clone(&log) };
    *me.borrow_mut() = Some(chain.borrow_mut().push(KEYS, Box::new(hook)));
    let buf = key_down();
    let ev = buf.as_validated().get(0).expect("event");
    let outcome = DefaultActionChain::run_default_shared(&chain, &ev, &mut 0);
    assert_eq!(outcome, Disposition::ConsumedPreventDefault, "the hook added meanwhile runs after it");
    assert_eq!(*log.borrow(), ["reentrant", "tail", "tail"]);
    assert_eq!(chain.borrow().len(), 1, "the self-removed hook is gone");
}

#[test]
fn disposition_predicates() {
    assert!(!Disposition::PassThrough.is_consumed());
    assert!(Disposition::Consumed.is_consumed() && !Disposition::Consumed.prevents_default());
    assert!(Disposition::ConsumedPreventDefault.prevents_default());
    assert_eq!(Disposition::default(), Disposition::PassThrough);
}

struct Boxes;

impl PointerGeometry for Boxes {
    fn local_rect(&self, node: NodeId) -> Option<crate::LayoutRect> {
        (node == NodeId::ROOT).then_some(crate::LayoutRect { x: 10.0, y: 20.0, width: 100.0, height: 50.0 })
    }
}

#[test]
fn priority_ordering_is_descending_with_stable_fifo_ties_and_mask_updates() {
    let log = Log::default();
    let mut chain = InterceptorChain::<u32>::new();
    assert_eq!(chain.kinds_mask(), InputKinds::EMPTY);

    let pointer = InputKinds::from_raw(1 << InteractionEvent::PointerDown as u32);
    let id_low_1 = chain.push_with_priority(KEYS, InputPriority::LOW, probe("low-1", Disposition::PassThrough, &log));
    let id_norm_1 = chain.push(KEYS, probe("norm-1", Disposition::PassThrough, &log));
    let id_high_1 = chain.push_with_priority(KEYS, InputPriority::HIGH, probe("high-1", Disposition::PassThrough, &log));
    let id_norm_2 = chain.push_with_priority(KEYS, InputPriority::NORMAL, probe("norm-2", Disposition::PassThrough, &log));
    let id_high_2 = chain.push_with_priority(KEYS, InputPriority::HIGH, probe("high-2", Disposition::PassThrough, &log));
    let id_custom = chain.push_with_priority(KEYS, InputPriority(50), probe("mid-50", Disposition::PassThrough, &log));
    let id_ptr = chain.push_with_priority(pointer, InputPriority::HIGH, probe("ptr", Disposition::Consumed, &log));
    assert!(id_low_1 < id_norm_1 && id_norm_1 < id_high_1 && id_high_1 < id_norm_2);
    assert_eq!(chain.kinds_mask(), KEYS.union(pointer));

    let buf = key_down();
    let ev = buf.as_validated().get(0).expect("event");
    let mut calls = 0;
    assert_eq!(chain.intercept(&ev, &mut calls), Disposition::PassThrough);
    assert_eq!(*log.borrow(), ["high-1", "high-2", "mid-50", "norm-1", "norm-2", "low-1"]);
    assert_eq!(calls, 6);

    // Removing the only pointer slot clears the pointer bit from `kinds_mask()`.
    assert!(matches!(chain.remove(id_ptr), Some(Some(_))));
    assert_eq!(chain.kinds_mask(), KEYS);
    assert!(matches!(chain.remove(id_high_1), Some(Some(_))));
    assert!(matches!(chain.remove(id_high_2), Some(Some(_))));
    assert!(matches!(chain.remove(id_custom), Some(Some(_))));
    assert!(matches!(chain.remove(id_norm_1), Some(Some(_))));
    assert!(matches!(chain.remove(id_norm_2), Some(Some(_))));
    assert!(matches!(chain.remove(id_low_1), Some(Some(_))));
    assert!(chain.is_empty());
    assert_eq!(chain.kinds_mask(), InputKinds::EMPTY);
}

#[test]
fn combined_mask_fast_exits_without_touching_slots() {
    struct PanicIfCalled;
    impl InputInterceptor<u32> for PanicIfCalled {
        fn intercept(&mut self, _: &ValidatedEvent<'_>, _: &mut u32) -> Disposition {
            panic!("non-matching kind must fast-exit via combined_kinds");
        }
    }
    let pointer = InputKinds::from_raw(1 << InteractionEvent::PointerDown as u32);
    let mut chain = InterceptorChain::<u32>::new();
    chain.push_with_priority(pointer, InputPriority::HIGH, Box::new(PanicIfCalled));
    let buf = key_down();
    let ev = buf.as_validated().get(0).expect("event");
    assert_eq!(chain.intercept(&ev, &mut 0), Disposition::PassThrough);

    let shared = RefCell::new(chain);
    assert_eq!(InterceptorChain::intercept_shared(&shared, &ev, &mut 0), Disposition::PassThrough);
}

#[test]
fn shared_dispatch_preserves_mixed_priority_positions_across_reentrancy() {
    struct MixedReentrant {
        chain: Rc<RefCell<InterceptorChain<u32>>>,
        log: Log,
        inserted: bool,
    }
    impl InputInterceptor<u32> for MixedReentrant {
        fn intercept(&mut self, ev: &ValidatedEvent<'_>, cx: &mut u32) -> Disposition {
            self.log.borrow_mut().push("norm-reentrant");
            if !self.inserted {
                self.inserted = true;
                // Insert a HIGH hook (before us) and a LOW hook (after us) while running.
                self.chain.borrow_mut().push_with_priority(
                    KEYS,
                    InputPriority::HIGH,
                    probe("added-high", Disposition::PassThrough, &self.log),
                );
                self.chain.borrow_mut().push_with_priority(
                    KEYS,
                    InputPriority::LOW,
                    probe("added-low", Disposition::PassThrough, &self.log),
                );
                // Nested dispatch must see the newly added HIGH hook first, skip us (currently running),
                // and run the LOW hooks.
                let nested = InterceptorChain::intercept_shared(&self.chain, ev, cx);
                assert_eq!(nested, Disposition::PassThrough);
            }
            Disposition::PassThrough
        }
    }

    let log = Log::default();
    let chain = Rc::new(RefCell::new(InterceptorChain::<u32>::new()));
    chain.borrow_mut().push_with_priority(
        KEYS,
        InputPriority::LOW,
        probe("orig-low", Disposition::PassThrough, &log),
    );
    chain.borrow_mut().push_with_priority(
        KEYS,
        InputPriority::NORMAL,
        Box::new(MixedReentrant {
            chain: Rc::clone(&chain),
            log: Rc::clone(&log),
            inserted: false,
        }),
    );
    chain.borrow_mut().push_with_priority(
        KEYS,
        InputPriority::HIGH,
        probe("orig-high", Disposition::PassThrough, &log),
    );

    let buf = key_down();
    let ev = buf.as_validated().get(0).expect("event");
    let mut calls = 0;
    assert_eq!(InterceptorChain::intercept_shared(&chain, &ev, &mut calls), Disposition::PassThrough);
    // Outer runs: orig-high -> norm-reentrant (nested: orig-high, added-high, orig-low, added-low) -> orig-low -> added-low.
    assert_eq!(
        *log.borrow(),
        [
            "orig-high",
            "norm-reentrant",
            "orig-high",
            "added-high",
            "orig-low",
            "added-low",
            "orig-low",
            "added-low",
        ]
    );

    // Second pass verifies `norm-reentrant` was restored into its exact (NORMAL, id) position!
    log.borrow_mut().clear();
    assert_eq!(InterceptorChain::intercept_shared(&chain, &ev, &mut calls), Disposition::PassThrough);
    assert_eq!(
        *log.borrow(),
        ["orig-high", "added-high", "norm-reentrant", "orig-low", "added-low"]
    );
}

#[test]
fn shared_dispatch_self_and_peer_removal_keeps_kinds_mask_consistent() {
    let pointer = InputKinds::from_raw(1 << InteractionEvent::PointerDown as u32);
    let log = Log::default();
    let chain = Rc::new(RefCell::new(InterceptorChain::<u32>::new()));

    let peer_id = chain.borrow_mut().push_with_priority(
        pointer,
        InputPriority::LOW,
        probe("peer-ptr", Disposition::Consumed, &log),
    );
    let low_key_id = chain.borrow_mut().push_with_priority(
        KEYS,
        InputPriority::LOW,
        probe("low-key", Disposition::PassThrough, &log),
    );

    struct SelfAndPeerRemover {
        chain: Rc<RefCell<InterceptorChain<u32>>>,
        self_id: Rc<RefCell<Option<InputHookId>>>,
        peer_id: InputHookId,
        log: Log,
    }
    impl InputInterceptor<u32> for SelfAndPeerRemover {
        fn intercept(&mut self, ev: &ValidatedEvent<'_>, cx: &mut u32) -> Disposition {
            self.log.borrow_mut().push("remover");
            let my_id = self.self_id.borrow().expect("self id initialized");
            assert!(self.chain.borrow_mut().remove(my_id).is_some());
            assert!(self.chain.borrow_mut().remove(self.peer_id).is_some());
            // Nested dispatch sees `low-key` only (remover removed itself, peer_id was removed).
            let _ = InterceptorChain::intercept_shared(&self.chain, ev, cx);
            Disposition::PassThrough
        }
    }

    let self_id_cell = Rc::new(RefCell::new(None));
    let remover_id = chain.borrow_mut().push_with_priority(
        KEYS,
        InputPriority::NORMAL,
        Box::new(SelfAndPeerRemover {
            chain: Rc::clone(&chain),
            self_id: Rc::clone(&self_id_cell),
            peer_id,
            log: Rc::clone(&log),
        }),
    );
    *self_id_cell.borrow_mut() = Some(remover_id);
    assert_eq!(chain.borrow().kinds_mask(), KEYS.union(pointer));

    let buf = key_down();
    let ev = buf.as_validated().get(0).expect("event");
    let mut calls = 0;
    assert_eq!(
        InterceptorChain::intercept_shared(&chain, &ev, &mut calls),
        Disposition::PassThrough
    );
    assert_eq!(*log.borrow(), ["remover", "low-key", "low-key"]);
    // Pointer peer and self were both removed: `kinds_mask()` must now contain only `KEYS`.
    assert_eq!(chain.borrow().kinds_mask(), KEYS);
    assert_eq!(chain.borrow().len(), 1);
    assert!(chain.borrow_mut().remove(low_key_id).is_some());
    assert_eq!(chain.borrow().kinds_mask(), InputKinds::EMPTY);
}

#[test]
fn local_norm_reads_the_geometry_box() {
    assert_eq!(local_norm(&Boxes, NodeId::ROOT, 60.0, 45.0), Some((0.5, 0.5)));
    assert_eq!(local_norm(&Boxes, NodeId::ROOT, 210.0, 20.0), Some((2.0, 0.0)), "outside drags extrapolate");
    assert_eq!(local_norm(&Boxes, NodeId::new(9, 0), 0.0, 0.0), None);
    let dyn_geometry: &dyn PointerGeometry = &Boxes;
    assert_eq!(local_norm(dyn_geometry, NodeId::ROOT, 10.0, 20.0), Some((0.0, 0.0)));
}