use std::cell::RefCell;
use std::cmp::Reverse;
use nativeview_abi::ValidatedEvent;
use super::{Disposition, InputKinds};
#[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
}
}
#[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,
hook: Option<Box<T>>,
}
pub struct InputChain<T: ?Sized> {
next_id: InputHookId,
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()
}
#[inline]
pub const fn kinds_mask(&self) -> InputKinds {
self.combined_kinds
}
#[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))
}
pub fn push(&mut self, kinds: InputKinds, hook: Box<T>) -> InputHookId {
self.push_with_priority(kinds, InputPriority::NORMAL, hook)
}
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
}
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)
}
#[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
}
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()?))
})
}
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),
}
}
}