nativeview-engine 0.1.0-rc.1

Framework-agnostic scene engine traits, hot-reload cdylib loader, and Frame-0 snapshot codecs.
Documentation
//! [`InputChain`]: the ordered, kind-masked hook registry behind every input extension point.

use std::cell::RefCell;
use std::cmp::Reverse;

use nativeview_abi::ValidatedEvent;

use super::{Disposition, InputKinds};

/// Explicit execution priority band for [`InputChain`] hooks. Higher values run earlier; hooks
/// with equal priority preserve stable FIFO registration order (ascending [`InputHookId`]).
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct InputPriority(pub i16);

impl InputPriority {
    pub const HIGH: Self = Self(100);
    pub const NORMAL: Self = Self(0);
    pub const LOW: Self = Self(-100);
}

impl Default for InputPriority {
    #[inline]
    fn default() -> Self {
        Self::NORMAL
    }
}

/// Handle of a registered hook (for [`InputChain::remove`]); ids grow with registration order.
#[repr(transparent)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct InputHookId(u64);

struct Slot<T: ?Sized> {
    id: InputHookId,
    priority: InputPriority,
    kinds: InputKinds,
    /// `None` while the hook runs through [`InputChain::run_shared`].
    hook: Option<Box<T>>,
}

/// Hooks ordered stably by `(priority DESC, id ASC)`. Steady-state dispatch never allocates: an
/// empty chain or non-matching event kind exits in O(1) via the cached [`Self::kinds_mask`].
pub struct InputChain<T: ?Sized> {
    /// The id the next [`InputChain::push`] / [`InputChain::push_with_priority`] hands out.
    next_id: InputHookId,
    /// Cached union of every registered slot's `kinds` mask (recomputed on push/remove).
    combined_kinds: InputKinds,
    slots: Vec<Slot<T>>,
}

impl<T: ?Sized> Default for InputChain<T> {
    fn default() -> Self {
        Self::new()
    }
}

impl<T: ?Sized> InputChain<T> {
    pub const fn new() -> Self {
        Self {
            next_id: InputHookId(0),
            combined_kinds: InputKinds::EMPTY,
            slots: Vec::new(),
        }
    }

    #[inline]
    const fn order_key(priority: InputPriority, id: InputHookId) -> (Reverse<InputPriority>, InputHookId) {
        (Reverse(priority), id)
    }

    #[inline]
    pub fn is_empty(&self) -> bool {
        self.slots.is_empty()
    }

    #[inline]
    pub fn len(&self) -> usize {
        self.slots.len()
    }

    /// Cached union of all registered slots' [`InputKinds`] masks for O(1) batch pre-filtering.
    #[inline]
    pub const fn kinds_mask(&self) -> InputKinds {
        self.combined_kinds
    }

    /// Returns `true` when any registered slot satisfies `pred` (a hook currently executing
    /// through [`Self::run_shared`] counts as active).
    #[inline]
    pub fn any_hook(&self, mut pred: impl FnMut(&T) -> bool) -> bool {
        self.slots
            .iter()
            .any(|s| s.hook.as_deref().is_none_or(&mut pred))
    }

    /// Registers `hook` for the event kinds in `kinds` at [`InputPriority::NORMAL`].
    pub fn push(&mut self, kinds: InputKinds, hook: Box<T>) -> InputHookId {
        self.push_with_priority(kinds, InputPriority::NORMAL, hook)
    }

    /// Registers `hook` for the event kinds in `kinds` at `priority`, maintaining stable
    /// `(priority DESC, id ASC)` order.
    pub fn push_with_priority(
        &mut self,
        kinds: InputKinds,
        priority: InputPriority,
        hook: Box<T>,
    ) -> InputHookId {
        let id = self.next_id;
        self.next_id = InputHookId(id.0 + 1);
        let key = Self::order_key(priority, id);
        let pos = self
            .slots
            .partition_point(|s| Self::order_key(s.priority, s.id) < key);
        self.slots.insert(
            pos,
            Slot {
                id,
                priority,
                kinds,
                hook: Some(hook),
            },
        );
        self.combined_kinds = self.combined_kinds.union(kinds);
        id
    }

    /// Unregisters `id`. `None` when unknown; `Some(None)` while it runs through
    /// [`Self::run_shared`] (it drops once it returns). Callers holding a `RefCell` borrow drop
    /// the returned hook after releasing it.
    pub fn remove(&mut self, id: InputHookId) -> Option<Option<Box<T>>> {
        let pos = self.slots.iter().position(|s| s.id == id)?;
        let hook = self.slots.remove(pos).hook;
        let mut mask = InputKinds::EMPTY;
        for slot in &self.slots {
            mask = mask.union(slot.kinds);
        }
        self.combined_kinds = mask;
        Some(hook)
    }

    /// Runs `call` on each hook whose kinds contain `ev`'s interaction kind, in `(priority DESC,
    /// id ASC)` order, until one consumes it; returns that disposition (or
    /// [`Disposition::PassThrough`]).
    #[inline]
    pub fn run(
        &mut self,
        ev: &ValidatedEvent<'_>,
        mut call: impl FnMut(&mut T) -> Disposition,
    ) -> Disposition {
        if self.slots.is_empty() {
            return Disposition::PassThrough;
        }
        let Some(kind) = ev.interaction() else {
            return Disposition::PassThrough;
        };
        if !self.combined_kinds.contains(kind) {
            return Disposition::PassThrough;
        }
        for slot in &mut self.slots {
            if let Some(hook) = slot.hook.as_mut().filter(|_| slot.kinds.contains(kind)) {
                let disposition = call(hook);
                if disposition.is_consumed() {
                    return disposition;
                }
            }
        }
        Disposition::PassThrough
    }

    /// [`Self::run`] without holding a borrow of `cell` while a hook runs, so hooks may register
    /// or remove hooks or dispatch again: a nested dispatch skips the hooks already running,
    /// hooks added after the current `(priority DESC, id ASC)` position run later in this pass,
    /// and a hook removed while it runs drops once it returns (outside any borrow).
    pub fn run_shared(
        cell: &RefCell<Self>,
        ev: &ValidatedEvent<'_>,
        mut call: impl FnMut(&mut T) -> Disposition,
    ) -> Disposition {
        let Some(kind) = ev.interaction() else {
            return Disposition::PassThrough;
        };
        if cell
            .try_borrow()
            .is_ok_and(|chain| chain.slots.is_empty() || !chain.combined_kinds.contains(kind))
        {
            return Disposition::PassThrough;
        }
        let mut after = None;
        loop {
            let next = cell
                .try_borrow_mut()
                .ok()
                .and_then(|mut chain| chain.take_next(after, kind));
            let Some((priority, id, mut hook)) = next else {
                return Disposition::PassThrough;
            };
            let disposition = call(&mut hook);
            let removed = match cell.try_borrow_mut() {
                Ok(mut chain) => chain.restore(priority, id, hook),
                Err(_) => Some(hook),
            };
            drop(removed);
            if disposition.is_consumed() {
                return disposition;
            }
            after = Some((priority, id));
        }
    }

    fn take_next(
        &mut self,
        after: Option<(InputPriority, InputHookId)>,
        kind: nativeview_abi::InteractionEvent,
    ) -> Option<(InputPriority, InputHookId, Box<T>)> {
        if !self.combined_kinds.contains(kind) {
            return None;
        }
        let start = after.map_or(0, |(ap, aid)| {
            let key = Self::order_key(ap, aid);
            self.slots
                .partition_point(|s| Self::order_key(s.priority, s.id) <= key)
        });
        self.slots[start..].iter_mut().find_map(|s| {
            if !s.kinds.contains(kind) {
                return None;
            }
            Some((s.priority, s.id, s.hook.take()?))
        })
    }

    /// Puts a ran hook back into its `(priority DESC, id ASC)` slot; hands it back when it was
    /// removed meanwhile.
    fn restore(&mut self, priority: InputPriority, id: InputHookId, hook: Box<T>) -> Option<Box<T>> {
        let key = Self::order_key(priority, id);
        match self
            .slots
            .binary_search_by_key(&key, |s| Self::order_key(s.priority, s.id))
        {
            Ok(pos) if self.slots[pos].hook.is_none() => {
                self.slots[pos].hook = Some(hook);
                None
            }
            _ => Some(hook),
        }
    }
}