use crate::*;
pub trait Interact<C: Context>: Copy + 'static {
type State: Copy + Default + 'static;
type Response: Copy + 'static;
fn update(&self, state: &mut Self::State, cx: &mut InteractCx<'_, C::Scalar>) -> Self::Response;
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct ContactId(NonZeroU32);
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ContactSource {
Mouse(MouseButton),
Touch(u64),
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum KeyboardEvent<'a> {
Key(KeyInput),
Text(&'a str),
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct ScrollEvent {
pub phase: Phase,
pub delta: Point<f32>,
pub continuous: bool,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[repr(u8)]
pub enum Phase {
Held = 0,
Started = 1,
Changed = 2,
Ended = 3,
Cancelled = 4,
}
pub struct InteractCx<'a, T> {
id: Id,
node: u32,
end: u32,
contacts: &'a mut [TrackedContact<T>],
scroll: &'a mut Option<TrackedScroll>,
focused: &'a mut Option<Id>,
focus_taken: &'a mut bool,
hover: Option<u32>,
deadline: &'a mut Option<Duration>,
input: &'a Input<T>,
keyboard_target: Option<u32>,
keyboard_claimed: &'a mut bool,
time: Duration,
}
impl<'a, T: Scalar> InteractCx<'a, T> {
pub fn time(&self) -> Duration {
self.time
}
pub fn wake_at(&mut self, time: Duration) {
*self.deadline = Some(self.deadline.map_or(time, |deadline| deadline.min(time)));
}
pub fn contacts(&mut self) -> Contacts<'_, T> {
Contacts {
contacts: self.contacts.iter_mut(),
id: self.id,
node: self.node,
end: self.end,
}
}
pub fn hovered(&self) -> bool {
self.hover.is_some_and(|node| self.contains(node))
}
pub fn focused(&self) -> bool {
*self.focused == Some(self.id)
}
pub fn focus(&mut self) {
if !*self.focus_taken {
*self.focused = Some(self.id);
*self.focus_taken = true;
}
}
pub fn keyboard(&self) -> Option<KeyboardEvent<'a>> {
if *self.keyboard_claimed
|| self.node == UNRESOLVED
|| self.keyboard_target.is_some_and(|target| !self.contains(target))
{
return None;
}
match self.input {
Input::Key(key) => Some(KeyboardEvent::Key(*key)),
Input::Text(text) => Some(KeyboardEvent::Text(text.as_str())),
_ => None,
}
}
pub fn claim_keyboard(&mut self) {
if self.keyboard().is_some() {
*self.keyboard_claimed = true;
}
}
pub fn input(&self) -> &'a Input<T> {
self.input
}
pub fn scroll(&self) -> Option<ScrollEvent> {
let scroll = (*self.scroll)?;
let event = scroll.event.filter(|_| match scroll.owner {
Some(owner) => owner == self.id,
None => scroll.target.is_some_and(|target| self.contains(target.node)),
});
event.or((scroll.cancelled == Some(self.id)).then_some(ScrollEvent {
phase: Phase::Cancelled,
delta: Point::ZERO,
continuous: true,
}))
}
pub fn capture_scroll(&mut self) {
let id = self.id;
let (node, end) = (self.node, self.end);
if let Some(scroll) = self.scroll
&& scroll.owner.is_none()
&& scroll
.target
.is_some_and(|target| node <= target.node && target.node <= end)
{
scroll.owner = Some(id);
}
}
fn contains(&self, node: u32) -> bool {
self.node <= node && node <= self.end
}
}
#[derive(Debug)]
pub struct Contact<'a, T> {
pub id: ContactId,
pub source: ContactSource,
pub phase: Phase,
pub origin: Point<T>,
pub position: Point<T>,
pub delta: Point<T>,
pub started: Duration,
pub over: bool,
pub free: bool,
pending: Option<&'a mut Route>,
widget: Id,
}
impl<T> Contact<'_, T> {
pub fn claim(&mut self) -> bool {
if let Some(Route::Pending { claim, .. }) = self.pending.as_deref_mut() {
*claim = Some(self.widget);
return true;
}
false
}
pub fn capture(&mut self) -> bool {
let Some(route) = self.pending.take() else {
return false;
};
*route = Route::Captured { owner: self.widget };
true
}
}
pub struct Contacts<'a, T> {
contacts: core::slice::IterMut<'a, TrackedContact<T>>,
id: Id,
node: u32,
end: u32,
}
impl<'a, T: Scalar> Iterator for Contacts<'a, T> {
type Item = Contact<'a, T>;
fn next(&mut self) -> Option<Self::Item> {
let tracked = self.contacts.next()?;
let within = |node| self.node <= node && node <= self.end;
let free = match tracked.route {
Route::Pending {
target: Some(target),
claim,
} => within(target.node) && claim.is_none_or(|claim| claim == self.id),
Route::Captured { owner } => owner == self.id,
Route::Pending { target: None, .. } | Route::Retired => false,
};
let pending = free && matches!(tracked.route, Route::Pending { .. });
Some(Contact {
id: tracked.id,
source: tracked.source,
phase: tracked.phase,
origin: tracked.origin,
position: tracked.position,
delta: tracked.delta,
started: tracked.started,
over: tracked.hit.is_some_and(within),
free,
pending: pending.then_some(&mut tracked.route),
widget: self.id,
})
}
}
const UNRESOLVED: u32 = u32::MAX;
#[derive(Default)]
pub struct InteractionState<T> {
pub clips: Vec<ResolvedClip<T>>,
pub deadline: Option<Duration>,
pub focused: Option<Id>,
pub focus_seen: Option<Id>,
pub mouse_position: Option<Point<T>>,
contacts: Vec<TrackedContact<T>>,
next_contact: u32,
scroll: Option<TrackedScroll>,
hits: Vec<HitItem<T>>,
kinds: Kinds<T>,
}
impl<T: Scalar> InteractionState<T> {
pub fn interact<C: Context<Scalar = T>, K: Interact<C>>(
&mut self,
id: Id,
config: K,
time: Duration,
) -> K::Response {
fn update<T: Scalar, C: Context<Scalar = T>, K: Interact<C>>(
kinds: &mut Kinds<T>,
index: usize,
cx: &mut InteractCx<'_, T>,
) {
let (config, state, response) = kinds.get_mut::<C, K>(index);
*response = config.update(state, cx);
}
let kind = self.kinds.register(TypeId::of::<K>(), update::<T, C, K>);
match self.kinds.find(id, Some(kind)) {
Ok(index) => {
self.kinds.mark_requested(index);
let cell = self.kinds.get_mut::<C, K>(index);
cell.0 = config;
cell.2
}
Err(bucket) => {
let mut focused = self.focused;
let mut state = K::State::default();
let response = config.update(
&mut state,
&mut InteractCx {
id,
node: UNRESOLVED,
end: 0,
contacts: &mut [],
scroll: &mut None,
focused: &mut focused,
focus_taken: &mut true,
hover: None,
deadline: &mut self.deadline,
input: &Input::None,
keyboard_target: None,
keyboard_claimed: &mut true,
time,
},
);
let value = (config, state, response);
self.kinds.slots.reserve(1);
let free = &mut self.kinds.kinds[kind as usize].free;
let offset = match *free {
Some(offset) => {
let offset = offset.get() - 1;
unsafe {
let cell = self
.kinds
.state
.get_mut::<Cell<(K, K::State, K::Response)>>(Offset::new(offset));
*free = cell.next;
*cell = Cell { value };
}
offset
}
None => self.kinds.state.push(Cell { value }).byte(),
};
self.kinds.insert_requested(bucket, id, kind, offset);
response
}
}
}
pub fn begin(&mut self, input: &Input<T>, time: Duration, nodes: &[StoredNode]) {
self.contacts
.retain(|tracked| !matches!(tracked.phase, Phase::Ended | Phase::Cancelled));
for tracked in &mut self.contacts {
tracked.phase = Phase::Held;
tracked.delta = Point::ZERO;
if let Route::Pending { claim, .. } = &mut tracked.route {
*claim = None;
}
}
if let Some(scroll) = &mut self.scroll {
if scroll.active || scroll.cancelled.is_some() {
scroll.event = None;
} else {
self.scroll = None;
}
}
match input {
Input::MouseDown { position, .. } | Input::MouseMove { position, .. } | Input::MouseUp { position, .. } => {
let position = *position;
self.mouse_position = Some(position);
for index in 0..self.contacts.len() {
let ContactSource::Mouse(button) = self.contacts[index].source else {
continue;
};
let released = matches!(input, Input::MouseUp { button: released, .. } if *released == button);
self.update(index, position, if released { Phase::Ended } else { Phase::Changed });
}
if let Input::MouseDown { button, .. } = input {
let button = *button;
if button == MouseButton::Primary {
self.focused = None;
}
self.press(ContactSource::Mouse(button), position, time);
}
if matches!(input, Input::MouseUp { leave: true, .. }) {
self.mouse_position = None;
}
}
&Input::Touch {
id,
position,
phase: TouchPhase::Down,
} => {
self.press(ContactSource::Touch(id), position, time);
}
&Input::Touch { id, position, phase } => {
if let Some(index) = self
.contacts
.iter()
.position(|tracked| tracked.source == ContactSource::Touch(id))
{
self.update(
index,
position,
match phase {
TouchPhase::Move => Phase::Changed,
TouchPhase::Up => Phase::Ended,
TouchPhase::Cancel => Phase::Cancelled,
TouchPhase::Down => unreachable!(),
},
);
if phase == TouchPhase::Up && matches!(self.contacts[index].route, Route::Pending { .. }) {
self.focused = None;
}
}
}
Input::MouseLeave => self.mouse_position = None,
&Input::Scroll {
position,
delta,
phase,
continuous,
..
} => {
self.mouse_position = Some(position);
let previous = self.scroll.filter(|scroll| scroll.active);
let cancelled = self.scroll.and_then(|scroll| scroll.cancelled);
let continuing = continuous && phase != ScrollPhase::Started && previous.is_some();
let stray = continuous && matches!(phase, ScrollPhase::Ended | ScrollPhase::Cancelled) && !continuing;
self.scroll = Some(TrackedScroll {
target: if continuing {
previous.and_then(|scroll| scroll.target)
} else {
hit(&self.hits, &self.clips, position).map(|hit| HitTarget {
id: hit.id,
node: hit.node,
})
},
owner: previous.filter(|_| continuing).and_then(|scroll| scroll.owner),
event: (!stray).then_some(ScrollEvent {
phase: match phase {
ScrollPhase::Started => Phase::Started,
ScrollPhase::Moved => Phase::Changed,
ScrollPhase::Ended => Phase::Ended,
ScrollPhase::Cancelled => Phase::Cancelled,
},
delta: if phase == ScrollPhase::Cancelled {
Point::ZERO
} else {
delta
},
continuous,
}),
active: continuous && matches!(phase, ScrollPhase::Started | ScrollPhase::Moved),
cancelled: previous
.filter(|_| !continuing)
.and_then(|scroll| scroll.owner)
.or(cancelled),
});
}
Input::Cancel => {
self.mouse_position = None;
for index in 0..self.contacts.len() {
self.update(index, self.contacts[index].position, Phase::Cancelled);
}
if let Some(scroll) = &mut self.scroll {
scroll.active = false;
scroll.event = Some(ScrollEvent {
phase: Phase::Cancelled,
delta: Point::ZERO,
continuous: true,
});
}
}
Input::None | Input::Text(_) | Input::Key(_) => {}
}
let hover = self
.mouse_position
.and_then(|position| hit(&self.hits, &self.clips, position))
.map(|hit| hit.node);
for tracked in &mut self.contacts {
tracked.hit = hit(&self.hits, &self.clips, tracked.position).map(|hit| hit.node);
}
self.deadline = None;
let mut focus_taken = false;
let (keyboard_target, mut keyboard_claimed) = match self.focused {
Some(id) => match self.kinds.find(id, None) {
Ok(index) => (Some(self.kinds.slots[index].node), false),
Err(_) => (None, true),
},
None => (None, false),
};
let kinds = &mut self.kinds;
for index in 0..kinds.slots.len() {
let slot = kinds.slots[index];
(kinds.kinds[slot.kind as usize].update)(
kinds,
index,
&mut InteractCx {
id: slot.id,
node: slot.node,
end: nodes.get(slot.node as usize).map_or(0, |stored| stored.subtree_end),
contacts: &mut self.contacts,
scroll: &mut self.scroll,
focused: &mut self.focused,
focus_taken: &mut focus_taken,
hover,
deadline: &mut self.deadline,
input,
keyboard_target,
keyboard_claimed: &mut keyboard_claimed,
time,
},
);
}
if let Some(scroll) = &mut self.scroll {
scroll.cancelled = None;
}
}
pub fn contact_position(&self, id: ContactId) -> Option<Point<T>> {
self.contacts
.iter()
.find(|contact| contact.id == id)
.map(|contact| contact.position)
}
fn press(&mut self, source: ContactSource, position: Point<T>, time: Duration) {
for index in 0..self.contacts.len() {
if self.contacts[index].source == source {
self.update(index, self.contacts[index].position, Phase::Cancelled);
}
}
let id = NonZeroU32::new(self.next_contact.wrapping_add(1)).unwrap_or(NonZeroU32::MIN);
self.next_contact = id.get();
let target = hit(&self.hits, &self.clips, position).map(|hit| HitTarget {
id: hit.id,
node: hit.node,
});
self.contacts.push(TrackedContact {
id: ContactId(id),
source,
route: Route::Pending { target, claim: None },
phase: Phase::Started,
origin: position,
position,
delta: Point::ZERO,
started: time,
hit: None,
});
}
fn update(&mut self, index: usize, position: Point<T>, phase: Phase) {
let tracked = &mut self.contacts[index];
if matches!(tracked.phase, Phase::Ended | Phase::Cancelled) {
return;
}
tracked.delta = if phase == Phase::Cancelled {
Point::ZERO
} else {
Point::new(position.x - tracked.position.x, position.y - tracked.position.y)
};
tracked.position = position;
tracked.phase = phase;
}
}
pub fn resolve<C: Context>(tree: &mut Tree<C>) {
let retained = &mut tree.interaction.kinds;
for slot in &mut retained.slots {
slot.node = tree.slots.node(slot.id).map_or(UNRESOLVED, |node| node.index() as u32);
}
let Kinds {
slots, kinds, state, ..
} = retained;
let before = slots.len();
slots.retain(|slot| {
if slot.order != UNRESOLVED {
return true;
}
let free = &mut kinds[slot.kind as usize].free;
let cell = state.as_ptr().wrapping_add(slot.offset as usize);
unsafe { cell.cast::<Option<NonZeroU32>>().write(*free) };
*free = NonZeroU32::new(slot.offset + 1);
false
});
let removed = slots.len() != before;
let nodes = &tree.nodes;
let key = |slot: &Slot| {
let end = nodes
.get(slot.node as usize)
.map_or(UNRESOLVED, |stored| stored.subtree_end);
(end, core::cmp::Reverse(slot.node), slot.order)
};
let reordered = !slots.is_sorted_by_key(key);
if reordered {
slots.sort_unstable_by_key(key);
}
if removed || reordered {
retained.rebuild();
}
retained.requested = 0;
for slot in &mut retained.slots {
slot.order = UNRESOLVED;
if let Some(stored) = tree.nodes.get_mut(slot.node as usize) {
stored.interactive = true;
}
}
let retained = &*retained;
let nodes = &tree.nodes;
let node = |id| {
let slot = &retained.slots[retained.find(id, None).ok()?];
(slot.node != UNRESOLVED).then_some(slot.node as usize)
};
let rebind = |HitTarget { id, .. }| node(id).map(|index| HitTarget { id, node: index as u32 });
for tracked in &mut tree.interaction.contacts {
tracked.route = match tracked.route {
Route::Pending {
target: Some(target),
claim,
} => rebind(target).map_or(Route::Retired, |target| Route::Pending {
target: Some(target),
claim,
}),
Route::Captured { owner } if node(owner).is_none() => Route::Retired,
route => route,
};
}
tree.interaction.focus_seen = tree.interaction.focused;
match core::mem::replace(&mut tree.focus, FocusRequest::Keep) {
FocusRequest::Keep => {}
FocusRequest::Clear => tree.interaction.focused = None,
FocusRequest::Focus(id) => tree.interaction.focused = Some(id),
}
if tree.interaction.focused.is_some_and(|id| node(id).is_none()) {
tree.interaction.focused = None;
}
if let Some(scroll) = &mut tree.interaction.scroll {
scroll.target = scroll.target.and_then(rebind);
if scroll.owner.is_some_and(|id| node(id).is_none()) {
scroll.cancelled = scroll.owner.take();
scroll.event = None;
scroll.target = None;
}
}
tree.interaction.hits.clear();
if !tree.interaction.kinds.slots.is_empty() {
let count = tree.nodes.len();
let placements = &tree.placements[..count];
let mut collect = {
#[inline(always)]
|index: usize, stored: &StoredNode, area: Rect<C::Scalar>| {
let id = stored.id;
if !stored.interactive {
return;
}
let hit = stored
.aux
.index()
.map_or(Sides::all(C::Scalar::ZERO), |index| tree.aux[index].hit);
let area = Rect::new(
area.x - hit.left,
area.y - hit.top,
area.width + hit.left + hit.right,
area.height + hit.top + hit.bottom,
);
let clip = if tree.resolved_clips.is_empty() {
ResolvedClipId::NONE
} else {
tree.resolved_clips[index]
};
let clip_bounds = clip
.index()
.map_or(tree.screen, |clip| tree.interaction.clips[clip].bounds);
tree.interaction.hits.push(HitItem {
id,
area: area.intersection(clip_bounds).unwrap_or_default(),
clip,
node: index as u32,
});
}
};
if tree.paint_order.is_empty() {
for (index, (stored, &area)) in nodes.iter().zip(placements).enumerate() {
collect(index, stored, area);
}
} else {
for id in &tree.paint_order[..count] {
collect(id.index(), &nodes[id.index()], placements[id.index()]);
}
}
}
}
fn hit<T: Scalar>(hits: &[HitItem<T>], clips: &[ResolvedClip<T>], position: Point<T>) -> Option<HitItem<T>> {
hits.iter()
.rev()
.find(|hit| {
if !hit.area.contains(position) {
return false;
}
let mut clip = hit.clip;
while let Some(index) = clip.index() {
let ResolvedClip {
area, radius, parent, ..
} = clips[index];
if !area.contains(position) {
return false;
}
if radius == Corners::all(T::ZERO) {
clip = parent;
continue;
}
let left = (position.x - area.x).to_f32();
let right = (area.x.endpoint(area.width) - position.x).to_f32();
let top = (position.y - area.y).to_f32();
let bottom = (area.y.endpoint(area.height) - position.y).to_f32();
let radius = match (left < right, top < bottom) {
(true, true) => radius.top_left,
(false, true) => radius.top_right,
(false, false) => radius.bottom_right,
(true, false) => radius.bottom_left,
};
let radius = radius.to_f32().min(area.width.min(area.height).to_f32() * 0.5).max(0.0);
let x = (radius - left.min(right)).max(0.0);
let y = (radius - top.min(bottom)).max(0.0);
if x * x + y * y > radius * radius {
return false;
}
clip = parent;
}
true
})
.copied()
}
#[derive(Clone, Copy, Debug, PartialEq)]
enum Route {
Pending {
target: Option<HitTarget>,
claim: Option<Id>,
},
Captured {
owner: Id,
},
Retired,
}
#[derive(Clone, Copy, Debug, PartialEq)]
struct HitTarget {
id: Id,
node: u32,
}
#[derive(Clone, Copy)]
struct TrackedContact<T> {
id: ContactId,
source: ContactSource,
route: Route,
phase: Phase,
origin: Point<T>,
position: Point<T>,
delta: Point<T>,
started: Duration,
hit: Option<u32>,
}
#[derive(Clone, Copy)]
struct TrackedScroll {
target: Option<HitTarget>,
owner: Option<Id>,
event: Option<ScrollEvent>,
active: bool,
cancelled: Option<Id>,
}
#[derive(Clone, Copy)]
struct HitItem<T> {
id: Id,
area: Rect<T>,
clip: ResolvedClipId,
node: u32,
}
#[derive(Default)]
struct Kinds<T> {
slots: Vec<Slot>,
table: Vec<u32>,
requested: u32,
kinds: Vec<Kind<T>>,
state: Bump,
}
impl<T> Kinds<T> {
#[inline(never)]
fn register(&mut self, type_id: TypeId, update: fn(&mut Kinds<T>, usize, &mut InteractCx<'_, T>)) -> u16 {
let kind = self
.kinds
.iter()
.position(|kind| kind.type_id == type_id)
.unwrap_or_else(|| {
assert!(self.kinds.len() <= u16::MAX as usize, "too many interaction kinds");
self.kinds.push(Kind {
type_id,
update,
free: None,
});
self.kinds.len() - 1
});
kind as u16
}
fn mark_requested(&mut self, index: usize) {
let slot = &mut self.slots[index];
if slot.order == UNRESOLVED {
slot.order = self.requested;
self.requested += 1;
}
}
#[cold]
#[inline(never)]
fn insert_requested(&mut self, bucket: usize, id: Id, kind: u16, offset: u32) {
let order = self.requested;
self.requested += 1;
let index = self.slots.len();
assert!(index < UNRESOLVED as usize, "too many interaction slots");
self.slots.push(Slot {
id,
node: UNRESOLVED,
offset,
order,
kind,
});
if self.slots.len() > self.table.len() / 2 {
self.rebuild();
} else {
self.table[bucket] = index as u32;
}
}
fn get_mut<C: Context<Scalar = T>, K: Interact<C>>(&mut self, index: usize) -> &mut (K, K::State, K::Response) {
let slot = &self.slots[index];
assert_eq!(
self.kinds[slot.kind as usize].type_id,
TypeId::of::<K>(),
"interaction kind mismatch"
);
unsafe { self.state.get_mut(Offset::new(slot.offset)) }
}
fn find(&self, id: Id, kind: Option<u16>) -> Result<usize, usize> {
if self.table.is_empty() {
return Err(0);
}
let bucket = self.probe(id, kind);
match self.table[bucket] {
UNRESOLVED => Err(bucket),
index => Ok(index as usize),
}
}
fn rebuild(&mut self) {
let len = self.slots.len();
if len == 0 {
self.table.clear();
return;
}
if len < self.table.len() / 8 {
self.table.truncate((len * 2).next_power_of_two());
}
self.table.fill(UNRESOLVED);
if len > self.table.len() / 2 {
self.table.resize((len * 2).next_power_of_two(), UNRESOLVED);
}
for (index, slot) in self.slots.iter().enumerate() {
let bucket = self.probe(slot.id, Some(slot.kind));
self.table[bucket] = index as u32;
}
}
fn probe(&self, id: Id, kind: Option<u16>) -> usize {
let mask = self.table.len() - 1;
let mixed = u64::from(id.slot).wrapping_mul(0x9e37_79b9_7f4a_7c15);
let mut bucket = (mixed >> (64 - self.table.len().trailing_zeros())) as usize;
loop {
let index = self.table[bucket];
if index == UNRESOLVED {
return bucket;
}
let slot = &self.slots[index as usize];
if slot.id == id && kind.is_none_or(|kind| slot.kind == kind) {
return bucket;
}
bucket = (bucket + 1) & mask;
}
}
}
#[derive(Clone, Copy)]
struct Slot {
id: Id,
node: u32,
offset: u32,
order: u32,
kind: u16,
}
struct Kind<T> {
type_id: TypeId,
update: fn(&mut Kinds<T>, usize, &mut InteractCx<'_, T>),
free: Option<NonZeroU32>,
}
#[derive(Clone, Copy)]
#[repr(C)]
union Cell<S: Copy> {
value: S,
next: Option<NonZeroU32>,
}