Skip to main content

nativeview_engine/ext/input/
chain.rs

1//! [`InputChain`]: the ordered, kind-masked hook registry behind every input extension point.
2
3use std::cell::RefCell;
4use std::cmp::Reverse;
5
6use nativeview_abi::ValidatedEvent;
7
8use super::{Disposition, InputKinds};
9
10/// Explicit execution priority band for [`InputChain`] hooks. Higher values run earlier; hooks
11/// with equal priority preserve stable FIFO registration order (ascending [`InputHookId`]).
12#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
13pub struct InputPriority(pub i16);
14
15impl InputPriority {
16    pub const HIGH: Self = Self(100);
17    pub const NORMAL: Self = Self(0);
18    pub const LOW: Self = Self(-100);
19}
20
21impl Default for InputPriority {
22    #[inline]
23    fn default() -> Self {
24        Self::NORMAL
25    }
26}
27
28/// Handle of a registered hook (for [`InputChain::remove`]); ids grow with registration order.
29#[repr(transparent)]
30#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
31pub struct InputHookId(u64);
32
33struct Slot<T: ?Sized> {
34    id: InputHookId,
35    priority: InputPriority,
36    kinds: InputKinds,
37    /// `None` while the hook runs through [`InputChain::run_shared`].
38    hook: Option<Box<T>>,
39}
40
41/// Hooks ordered stably by `(priority DESC, id ASC)`. Steady-state dispatch never allocates: an
42/// empty chain or non-matching event kind exits in O(1) via the cached [`Self::kinds_mask`].
43pub struct InputChain<T: ?Sized> {
44    /// The id the next [`InputChain::push`] / [`InputChain::push_with_priority`] hands out.
45    next_id: InputHookId,
46    /// Cached union of every registered slot's `kinds` mask (recomputed on push/remove).
47    combined_kinds: InputKinds,
48    slots: Vec<Slot<T>>,
49}
50
51impl<T: ?Sized> Default for InputChain<T> {
52    fn default() -> Self {
53        Self::new()
54    }
55}
56
57impl<T: ?Sized> InputChain<T> {
58    pub const fn new() -> Self {
59        Self {
60            next_id: InputHookId(0),
61            combined_kinds: InputKinds::EMPTY,
62            slots: Vec::new(),
63        }
64    }
65
66    #[inline]
67    const fn order_key(priority: InputPriority, id: InputHookId) -> (Reverse<InputPriority>, InputHookId) {
68        (Reverse(priority), id)
69    }
70
71    #[inline]
72    pub fn is_empty(&self) -> bool {
73        self.slots.is_empty()
74    }
75
76    #[inline]
77    pub fn len(&self) -> usize {
78        self.slots.len()
79    }
80
81    /// Cached union of all registered slots' [`InputKinds`] masks for O(1) batch pre-filtering.
82    #[inline]
83    pub const fn kinds_mask(&self) -> InputKinds {
84        self.combined_kinds
85    }
86
87    /// Returns `true` when any registered slot satisfies `pred` (a hook currently executing
88    /// through [`Self::run_shared`] counts as active).
89    #[inline]
90    pub fn any_hook(&self, mut pred: impl FnMut(&T) -> bool) -> bool {
91        self.slots
92            .iter()
93            .any(|s| s.hook.as_deref().is_none_or(&mut pred))
94    }
95
96    /// Registers `hook` for the event kinds in `kinds` at [`InputPriority::NORMAL`].
97    pub fn push(&mut self, kinds: InputKinds, hook: Box<T>) -> InputHookId {
98        self.push_with_priority(kinds, InputPriority::NORMAL, hook)
99    }
100
101    /// Registers `hook` for the event kinds in `kinds` at `priority`, maintaining stable
102    /// `(priority DESC, id ASC)` order.
103    pub fn push_with_priority(
104        &mut self,
105        kinds: InputKinds,
106        priority: InputPriority,
107        hook: Box<T>,
108    ) -> InputHookId {
109        let id = self.next_id;
110        self.next_id = InputHookId(id.0 + 1);
111        let key = Self::order_key(priority, id);
112        let pos = self
113            .slots
114            .partition_point(|s| Self::order_key(s.priority, s.id) < key);
115        self.slots.insert(
116            pos,
117            Slot {
118                id,
119                priority,
120                kinds,
121                hook: Some(hook),
122            },
123        );
124        self.combined_kinds = self.combined_kinds.union(kinds);
125        id
126    }
127
128    /// Unregisters `id`. `None` when unknown; `Some(None)` while it runs through
129    /// [`Self::run_shared`] (it drops once it returns). Callers holding a `RefCell` borrow drop
130    /// the returned hook after releasing it.
131    pub fn remove(&mut self, id: InputHookId) -> Option<Option<Box<T>>> {
132        let pos = self.slots.iter().position(|s| s.id == id)?;
133        let hook = self.slots.remove(pos).hook;
134        let mut mask = InputKinds::EMPTY;
135        for slot in &self.slots {
136            mask = mask.union(slot.kinds);
137        }
138        self.combined_kinds = mask;
139        Some(hook)
140    }
141
142    /// Runs `call` on each hook whose kinds contain `ev`'s interaction kind, in `(priority DESC,
143    /// id ASC)` order, until one consumes it; returns that disposition (or
144    /// [`Disposition::PassThrough`]).
145    #[inline]
146    pub fn run(
147        &mut self,
148        ev: &ValidatedEvent<'_>,
149        mut call: impl FnMut(&mut T) -> Disposition,
150    ) -> Disposition {
151        if self.slots.is_empty() {
152            return Disposition::PassThrough;
153        }
154        let Some(kind) = ev.interaction() else {
155            return Disposition::PassThrough;
156        };
157        if !self.combined_kinds.contains(kind) {
158            return Disposition::PassThrough;
159        }
160        for slot in &mut self.slots {
161            if let Some(hook) = slot.hook.as_mut().filter(|_| slot.kinds.contains(kind)) {
162                let disposition = call(hook);
163                if disposition.is_consumed() {
164                    return disposition;
165                }
166            }
167        }
168        Disposition::PassThrough
169    }
170
171    /// [`Self::run`] without holding a borrow of `cell` while a hook runs, so hooks may register
172    /// or remove hooks or dispatch again: a nested dispatch skips the hooks already running,
173    /// hooks added after the current `(priority DESC, id ASC)` position run later in this pass,
174    /// and a hook removed while it runs drops once it returns (outside any borrow).
175    pub fn run_shared(
176        cell: &RefCell<Self>,
177        ev: &ValidatedEvent<'_>,
178        mut call: impl FnMut(&mut T) -> Disposition,
179    ) -> Disposition {
180        let Some(kind) = ev.interaction() else {
181            return Disposition::PassThrough;
182        };
183        if cell
184            .try_borrow()
185            .is_ok_and(|chain| chain.slots.is_empty() || !chain.combined_kinds.contains(kind))
186        {
187            return Disposition::PassThrough;
188        }
189        let mut after = None;
190        loop {
191            let next = cell
192                .try_borrow_mut()
193                .ok()
194                .and_then(|mut chain| chain.take_next(after, kind));
195            let Some((priority, id, mut hook)) = next else {
196                return Disposition::PassThrough;
197            };
198            let disposition = call(&mut hook);
199            let removed = match cell.try_borrow_mut() {
200                Ok(mut chain) => chain.restore(priority, id, hook),
201                Err(_) => Some(hook),
202            };
203            drop(removed);
204            if disposition.is_consumed() {
205                return disposition;
206            }
207            after = Some((priority, id));
208        }
209    }
210
211    fn take_next(
212        &mut self,
213        after: Option<(InputPriority, InputHookId)>,
214        kind: nativeview_abi::InteractionEvent,
215    ) -> Option<(InputPriority, InputHookId, Box<T>)> {
216        if !self.combined_kinds.contains(kind) {
217            return None;
218        }
219        let start = after.map_or(0, |(ap, aid)| {
220            let key = Self::order_key(ap, aid);
221            self.slots
222                .partition_point(|s| Self::order_key(s.priority, s.id) <= key)
223        });
224        self.slots[start..].iter_mut().find_map(|s| {
225            if !s.kinds.contains(kind) {
226                return None;
227            }
228            Some((s.priority, s.id, s.hook.take()?))
229        })
230    }
231
232    /// Puts a ran hook back into its `(priority DESC, id ASC)` slot; hands it back when it was
233    /// removed meanwhile.
234    fn restore(&mut self, priority: InputPriority, id: InputHookId, hook: Box<T>) -> Option<Box<T>> {
235        let key = Self::order_key(priority, id);
236        match self
237            .slots
238            .binary_search_by_key(&key, |s| Self::order_key(s.priority, s.id))
239        {
240            Ok(pos) if self.slots[pos].hook.is_none() => {
241                self.slots[pos].hook = Some(hook);
242                None
243            }
244            _ => Some(hook),
245        }
246    }
247}