Skip to main content

blit/
interact.rs

1use crate::*;
2
3/// handle input for your widget
4///
5/// keep settings on this value and pass it to [`crate::Ui::interact`] each build
6///
7/// # execution
8///
9/// interactions run before each build using the last build's settings and layout.
10/// children run before parents, siblings in build order, and interactions on the
11/// same widget in registration order.
12///
13/// # keyboard and text
14///
15/// [`InteractCx::keyboard`] delivers keyboard and text input to the focused widget,
16/// then its ancestors. without focus, all mounted handlers are eligible.
17/// call [`InteractCx::claim_keyboard`] when handled to stop it from reaching another
18/// interaction. ignored events keep bubbling. the route uses focus at the start
19/// of the update, so changing focus does not redirect the current event.
20///
21/// [`InteractCx::input`] bypasses routing and claims.
22///
23/// # sharing contacts
24///
25/// - [`Contact::claim`]: keep the press for this update. call it each update,
26///   or stop to let a parent take over.
27/// - [`Contact::capture`]: keep the press until it ends, even outside your widget.
28///   use this when a drag starts.
29///
30/// both need a [`free`](Contact::free) contact that is not already captured.
31/// they return `true` on success. neither can take another widget's claim.
32/// interactions on the same widget share captures.
33///
34/// # following a contact
35///
36/// save [`Contact::id`] in your state and find it in [`InteractCx::contacts`] on
37/// later updates. the handle itself only lasts one update.
38/// to start tracking a press with an `Option<ContactId>` state:
39///
40/// ```
41/// # use blit::{ContactId, InteractCx, Phase};
42/// # fn begin(state: &mut Option<ContactId>, cx: &mut InteractCx<'_, f32>) {
43/// *state = cx.contacts().find_map(|mut contact| {
44///     (contact.phase == Phase::Started && contact.claim()).then_some(contact.id)
45/// });
46/// # }
47/// ```
48///
49/// on later updates:
50///
51/// - cancel if the contact is missing or [`Contact::free`] is `false`
52/// - cancel on [`Phase::Cancelled`]
53/// - finish on [`Phase::Ended`]
54///
55/// after capture, just follow the contact without claiming or capturing it again
56pub trait Interact<C: Context>: Copy + 'static {
57    /// state kept between updates
58    type State: Copy + Default + 'static;
59    /// the result returned to your widget
60    type Response: Copy + 'static;
61
62    /// update your state for this input and return the result
63    ///
64    /// the first call has no input or contacts
65    fn update(&self, state: &mut Self::State, cx: &mut InteractCx<'_, C::Scalar>) -> Self::Response;
66}
67
68/// identifies one press or touch within a [`Tree`]
69#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
70pub struct ContactId(NonZeroU32);
71
72/// kind of pointer producing a contact
73#[derive(Clone, Copy, Debug, PartialEq, Eq)]
74pub enum ContactSource {
75    Mouse(MouseButton),
76    Touch(u64),
77}
78
79/// keyboard and text input routed through focus
80#[derive(Clone, Copy, Debug, PartialEq, Eq)]
81pub enum KeyboardEvent<'a> {
82    Key(KeyInput),
83    Text(&'a str),
84}
85
86/// wheel or trackpad input for this widget
87#[derive(Clone, Copy, Debug, PartialEq)]
88pub struct ScrollEvent {
89    pub phase: Phase,
90    pub delta: Point<f32>,
91    pub continuous: bool,
92}
93
94#[derive(Clone, Copy, Debug, PartialEq, Eq)]
95#[repr(u8)]
96pub enum Phase {
97    /// no new input for this contact
98    Held = 0,
99    Started = 1,
100    Changed = 2,
101    Ended = 3,
102    /// cancel the gesture without treating it as a release
103    Cancelled = 4,
104}
105
106/// input and timing for your interaction
107///
108/// - [`Self::contacts`] for mouse presses and touches
109/// - [`Self::scroll`] for wheel and trackpad input
110/// - [`Self::keyboard`] for keyboard and text input
111/// - [`Self::wake_at`] for timed gestures
112pub struct InteractCx<'a, T> {
113    id: Id,
114    node: u32,
115    end: u32,
116    contacts: &'a mut [TrackedContact<T>],
117    scroll: &'a mut Option<TrackedScroll>,
118    focused: &'a mut Option<Id>,
119    focus_taken: &'a mut bool,
120    hover: Option<u32>,
121    deadline: &'a mut Option<Duration>,
122    input: &'a Input<T>,
123    keyboard_target: Option<u32>,
124    keyboard_claimed: &'a mut bool,
125    time: Duration,
126}
127
128impl<'a, T: Scalar> InteractCx<'a, T> {
129    /// the current frame time
130    pub fn time(&self) -> Duration {
131        self.time
132    }
133
134    /// request another update at `time`, even without new input
135    ///
136    /// use this for a long press
137    pub fn wake_at(&mut self, time: Duration) {
138        *self.deadline = Some(self.deadline.map_or(time, |deadline| deadline.min(time)));
139    }
140
141    /// read live mouse presses and touches
142    ///
143    /// includes contacts your widget cannot use. see
144    /// [following a contact](Interact#following-a-contact) to choose and track one.
145    pub fn contacts(&mut self) -> Contacts<'_, T> {
146        Contacts {
147            contacts: self.contacts.iter_mut(),
148            id: self.id,
149            node: self.node,
150            end: self.end,
151        }
152    }
153
154    pub fn hovered(&self) -> bool {
155        self.hover.is_some_and(|node| self.contains(node))
156    }
157
158    pub fn focused(&self) -> bool {
159        *self.focused == Some(self.id)
160    }
161
162    /// focuses this widget unless a deeper widget took focus during this update
163    pub fn focus(&mut self) {
164        if !*self.focus_taken {
165            *self.focused = Some(self.id);
166            *self.focus_taken = true;
167        }
168    }
169
170    /// unclaimed keyboard or text input for this widget
171    ///
172    /// input starts at the focused widget and bubbles through its ancestors.
173    /// without focus, all mounted handlers are eligible.
174    pub fn keyboard(&self) -> Option<KeyboardEvent<'a>> {
175        if *self.keyboard_claimed
176            || self.node == UNRESOLVED
177            || self.keyboard_target.is_some_and(|target| !self.contains(target))
178        {
179            return None;
180        }
181        match self.input {
182            Input::Key(key) => Some(KeyboardEvent::Key(*key)),
183            Input::Text(text) => Some(KeyboardEvent::Text(text.as_str())),
184            _ => None,
185        }
186    }
187
188    /// stops this keyboard or text event from reaching another interaction
189    pub fn claim_keyboard(&mut self) {
190        if self.keyboard().is_some() {
191            *self.keyboard_claimed = true;
192        }
193    }
194
195    /// this frame's input regardless of focus or claims
196    pub fn input(&self) -> &'a Input<T> {
197        self.input
198    }
199
200    /// scrolling over this widget, or the cancellation of a sequence it held
201    pub fn scroll(&self) -> Option<ScrollEvent> {
202        let scroll = (*self.scroll)?;
203        let event = scroll.event.filter(|_| match scroll.owner {
204            Some(owner) => owner == self.id,
205            None => scroll.target.is_some_and(|target| self.contains(target.node)),
206        });
207        event.or((scroll.cancelled == Some(self.id)).then_some(ScrollEvent {
208            phase: Phase::Cancelled,
209            delta: Point::ZERO,
210            continuous: true,
211        }))
212    }
213
214    /// keeps a continuous scroll sequence over this widget until it ends
215    pub fn capture_scroll(&mut self) {
216        let id = self.id;
217        let (node, end) = (self.node, self.end);
218        if let Some(scroll) = self.scroll
219            && scroll.owner.is_none()
220            && scroll
221                .target
222                .is_some_and(|target| node <= target.node && target.node <= end)
223        {
224            scroll.owner = Some(id);
225        }
226    }
227
228    fn contains(&self, node: u32) -> bool {
229        self.node <= node && node <= self.end
230    }
231}
232
233/// a mouse button press or touch, from down to release or cancellation
234///
235/// see [sharing contacts](Interact#sharing-contacts) for when to claim or capture
236#[derive(Debug)]
237pub struct Contact<'a, T> {
238    pub id: ContactId,
239    pub source: ContactSource,
240    pub phase: Phase,
241    pub origin: Point<T>,
242    pub position: Point<T>,
243    /// movement since the previous input
244    pub delta: Point<T>,
245    /// when the press started
246    pub started: Duration,
247    /// true if the position hits your widget or one of its children
248    pub over: bool,
249    /// free for this widget to use, including contacts it captured
250    pub free: bool,
251    pending: Option<&'a mut Route>,
252    widget: Id,
253}
254
255impl<T> Contact<'_, T> {
256    /// reserve this contact for the current update
257    pub fn claim(&mut self) -> bool {
258        if let Some(Route::Pending { claim, .. }) = self.pending.as_deref_mut() {
259            *claim = Some(self.widget);
260            return true;
261        }
262        false
263    }
264
265    /// keep this contact until it ends or your widget disappears
266    pub fn capture(&mut self) -> bool {
267        let Some(route) = self.pending.take() else {
268            return false;
269        };
270        *route = Route::Captured { owner: self.widget };
271        true
272    }
273}
274
275/// iterate contact handles from [`InteractCx::contacts`]
276pub struct Contacts<'a, T> {
277    contacts: core::slice::IterMut<'a, TrackedContact<T>>,
278    id: Id,
279    node: u32,
280    end: u32,
281}
282
283impl<'a, T: Scalar> Iterator for Contacts<'a, T> {
284    type Item = Contact<'a, T>;
285
286    fn next(&mut self) -> Option<Self::Item> {
287        let tracked = self.contacts.next()?;
288        let within = |node| self.node <= node && node <= self.end;
289        let free = match tracked.route {
290            Route::Pending {
291                target: Some(target),
292                claim,
293            } => within(target.node) && claim.is_none_or(|claim| claim == self.id),
294            Route::Captured { owner } => owner == self.id,
295            Route::Pending { target: None, .. } | Route::Retired => false,
296        };
297        let pending = free && matches!(tracked.route, Route::Pending { .. });
298        Some(Contact {
299            id: tracked.id,
300            source: tracked.source,
301            phase: tracked.phase,
302            origin: tracked.origin,
303            position: tracked.position,
304            delta: tracked.delta,
305            started: tracked.started,
306            over: tracked.hit.is_some_and(within),
307            free,
308            pending: pending.then_some(&mut tracked.route),
309            widget: self.id,
310        })
311    }
312}
313
314//
315// internals
316//
317
318// slot node for a named widget missing from the layout
319const UNRESOLVED: u32 = u32::MAX;
320
321#[derive(Default)]
322pub struct InteractionState<T> {
323    pub clips: Vec<ResolvedClip<T>>,
324    pub deadline: Option<Duration>,
325    pub focused: Option<Id>,
326    // focus as the latest build saw it
327    pub focus_seen: Option<Id>,
328    pub mouse_position: Option<Point<T>>,
329    contacts: Vec<TrackedContact<T>>,
330    next_contact: u32,
331    scroll: Option<TrackedScroll>,
332    hits: Vec<HitItem<T>>,
333    kinds: Kinds<T>,
334}
335
336impl<T: Scalar> InteractionState<T> {
337    pub fn interact<C: Context<Scalar = T>, K: Interact<C>>(
338        &mut self,
339        id: Id,
340        config: K,
341        time: Duration,
342    ) -> K::Response {
343        fn update<T: Scalar, C: Context<Scalar = T>, K: Interact<C>>(
344            kinds: &mut Kinds<T>,
345            index: usize,
346            cx: &mut InteractCx<'_, T>,
347        ) {
348            let (config, state, response) = kinds.get_mut::<C, K>(index);
349            *response = config.update(state, cx);
350        }
351
352        let kind = self.kinds.register(TypeId::of::<K>(), update::<T, C, K>);
353        match self.kinds.find(id, Some(kind)) {
354            Ok(index) => {
355                self.kinds.mark_requested(index);
356                let cell = self.kinds.get_mut::<C, K>(index);
357                cell.0 = config;
358                cell.2
359            }
360            Err(bucket) => {
361                let mut focused = self.focused;
362                let mut state = K::State::default();
363                let response = config.update(
364                    &mut state,
365                    &mut InteractCx {
366                        id,
367                        node: UNRESOLVED,
368                        end: 0,
369                        contacts: &mut [],
370                        scroll: &mut None,
371                        focused: &mut focused,
372                        focus_taken: &mut true,
373                        hover: None,
374                        deadline: &mut self.deadline,
375                        input: &Input::None,
376                        keyboard_target: None,
377                        keyboard_claimed: &mut true,
378                        time,
379                    },
380                );
381                let value = (config, state, response);
382                // reserve first so a panic cannot lose a reused cell
383                self.kinds.slots.reserve(1);
384                let free = &mut self.kinds.kinds[kind as usize].free;
385                let offset = match *free {
386                    Some(offset) => {
387                        let offset = offset.get() - 1;
388                        // safety: free cells of this kind are dead cells of this layout holding the next link
389                        unsafe {
390                            let cell = self
391                                .kinds
392                                .state
393                                .get_mut::<Cell<(K, K::State, K::Response)>>(Offset::new(offset));
394                            *free = cell.next;
395                            *cell = Cell { value };
396                        }
397                        offset
398                    }
399                    None => self.kinds.state.push(Cell { value }).byte(),
400                };
401                self.kinds.insert_requested(bucket, id, kind, offset);
402                response
403            }
404        }
405    }
406
407    pub fn begin(&mut self, input: &Input<T>, time: Duration, nodes: &[StoredNode]) {
408        self.contacts
409            .retain(|tracked| !matches!(tracked.phase, Phase::Ended | Phase::Cancelled));
410        for tracked in &mut self.contacts {
411            tracked.phase = Phase::Held;
412            tracked.delta = Point::ZERO;
413            // claims last one update, claimants renew them
414            if let Route::Pending { claim, .. } = &mut tracked.route {
415                *claim = None;
416            }
417        }
418        if let Some(scroll) = &mut self.scroll {
419            if scroll.active || scroll.cancelled.is_some() {
420                scroll.event = None;
421            } else {
422                self.scroll = None;
423            }
424        }
425        match input {
426            Input::MouseDown { position, .. } | Input::MouseMove { position, .. } | Input::MouseUp { position, .. } => {
427                let position = *position;
428                self.mouse_position = Some(position);
429                for index in 0..self.contacts.len() {
430                    let ContactSource::Mouse(button) = self.contacts[index].source else {
431                        continue;
432                    };
433                    let released = matches!(input, Input::MouseUp { button: released, .. } if *released == button);
434                    self.update(index, position, if released { Phase::Ended } else { Phase::Changed });
435                }
436                if let Input::MouseDown { button, .. } = input {
437                    let button = *button;
438                    // a press away from any focusable widget clears focus
439                    if button == MouseButton::Primary {
440                        self.focused = None;
441                    }
442                    self.press(ContactSource::Mouse(button), position, time);
443                }
444                if matches!(input, Input::MouseUp { leave: true, .. }) {
445                    self.mouse_position = None;
446                }
447            }
448            &Input::Touch {
449                id,
450                position,
451                phase: TouchPhase::Down,
452            } => {
453                self.press(ContactSource::Touch(id), position, time);
454            }
455            &Input::Touch { id, position, phase } => {
456                if let Some(index) = self
457                    .contacts
458                    .iter()
459                    .position(|tracked| tracked.source == ContactSource::Touch(id))
460                {
461                    self.update(
462                        index,
463                        position,
464                        match phase {
465                            TouchPhase::Move => Phase::Changed,
466                            TouchPhase::Up => Phase::Ended,
467                            TouchPhase::Cancel => Phase::Cancelled,
468                            TouchPhase::Down => unreachable!(),
469                        },
470                    );
471                    // a release nothing captured clears focus unless a focusable widget takes it
472                    if phase == TouchPhase::Up && matches!(self.contacts[index].route, Route::Pending { .. }) {
473                        self.focused = None;
474                    }
475                }
476            }
477            Input::MouseLeave => self.mouse_position = None,
478            &Input::Scroll {
479                position,
480                delta,
481                phase,
482                continuous,
483                ..
484            } => {
485                self.mouse_position = Some(position);
486                let previous = self.scroll.filter(|scroll| scroll.active);
487                let cancelled = self.scroll.and_then(|scroll| scroll.cancelled);
488                let continuing = continuous && phase != ScrollPhase::Started && previous.is_some();
489                // a continuous ending without a sequence has nothing to end
490                let stray = continuous && matches!(phase, ScrollPhase::Ended | ScrollPhase::Cancelled) && !continuing;
491                self.scroll = Some(TrackedScroll {
492                    target: if continuing {
493                        previous.and_then(|scroll| scroll.target)
494                    } else {
495                        hit(&self.hits, &self.clips, position).map(|hit| HitTarget {
496                            id: hit.id,
497                            node: hit.node,
498                        })
499                    },
500                    owner: previous.filter(|_| continuing).and_then(|scroll| scroll.owner),
501                    event: (!stray).then_some(ScrollEvent {
502                        phase: match phase {
503                            ScrollPhase::Started => Phase::Started,
504                            ScrollPhase::Moved => Phase::Changed,
505                            ScrollPhase::Ended => Phase::Ended,
506                            ScrollPhase::Cancelled => Phase::Cancelled,
507                        },
508                        delta: if phase == ScrollPhase::Cancelled {
509                            Point::ZERO
510                        } else {
511                            delta
512                        },
513                        continuous,
514                    }),
515                    active: continuous && matches!(phase, ScrollPhase::Started | ScrollPhase::Moved),
516                    cancelled: previous
517                        .filter(|_| !continuing)
518                        .and_then(|scroll| scroll.owner)
519                        .or(cancelled),
520                });
521            }
522            Input::Cancel => {
523                self.mouse_position = None;
524                for index in 0..self.contacts.len() {
525                    self.update(index, self.contacts[index].position, Phase::Cancelled);
526                }
527                if let Some(scroll) = &mut self.scroll {
528                    scroll.active = false;
529                    scroll.event = Some(ScrollEvent {
530                        phase: Phase::Cancelled,
531                        delta: Point::ZERO,
532                        continuous: true,
533                    });
534                }
535            }
536            Input::None | Input::Text(_) | Input::Key(_) => {}
537        }
538        let hover = self
539            .mouse_position
540            .and_then(|position| hit(&self.hits, &self.clips, position))
541            .map(|hit| hit.node);
542        for tracked in &mut self.contacts {
543            tracked.hit = hit(&self.hits, &self.clips, tracked.position).map(|hit| hit.node);
544        }
545        self.deadline = None;
546        let mut focus_taken = false;
547        let (keyboard_target, mut keyboard_claimed) = match self.focused {
548            Some(id) => match self.kinds.find(id, None) {
549                Ok(index) => (Some(self.kinds.slots[index].node), false),
550                Err(_) => (None, true),
551            },
552            None => (None, false),
553        };
554        let kinds = &mut self.kinds;
555        for index in 0..kinds.slots.len() {
556            let slot = kinds.slots[index];
557            (kinds.kinds[slot.kind as usize].update)(
558                kinds,
559                index,
560                &mut InteractCx {
561                    id: slot.id,
562                    node: slot.node,
563                    end: nodes.get(slot.node as usize).map_or(0, |stored| stored.subtree_end),
564                    contacts: &mut self.contacts,
565                    scroll: &mut self.scroll,
566                    focused: &mut self.focused,
567                    focus_taken: &mut focus_taken,
568                    hover,
569                    deadline: &mut self.deadline,
570                    input,
571                    keyboard_target,
572                    keyboard_claimed: &mut keyboard_claimed,
573                    time,
574                },
575            );
576        }
577        if let Some(scroll) = &mut self.scroll {
578            scroll.cancelled = None;
579        }
580    }
581
582    pub fn contact_position(&self, id: ContactId) -> Option<Point<T>> {
583        self.contacts
584            .iter()
585            .find(|contact| contact.id == id)
586            .map(|contact| contact.position)
587    }
588
589    fn press(&mut self, source: ContactSource, position: Point<T>, time: Duration) {
590        for index in 0..self.contacts.len() {
591            if self.contacts[index].source == source {
592                self.update(index, self.contacts[index].position, Phase::Cancelled);
593            }
594        }
595        // ids wrap past zero, only live contacts need distinct ids
596        let id = NonZeroU32::new(self.next_contact.wrapping_add(1)).unwrap_or(NonZeroU32::MIN);
597        self.next_contact = id.get();
598        let target = hit(&self.hits, &self.clips, position).map(|hit| HitTarget {
599            id: hit.id,
600            node: hit.node,
601        });
602        self.contacts.push(TrackedContact {
603            id: ContactId(id),
604            source,
605            route: Route::Pending { target, claim: None },
606            phase: Phase::Started,
607            origin: position,
608            position,
609            delta: Point::ZERO,
610            started: time,
611            hit: None,
612        });
613    }
614
615    fn update(&mut self, index: usize, position: Point<T>, phase: Phase) {
616        let tracked = &mut self.contacts[index];
617        if matches!(tracked.phase, Phase::Ended | Phase::Cancelled) {
618            return;
619        }
620        tracked.delta = if phase == Phase::Cancelled {
621            Point::ZERO
622        } else {
623            Point::new(position.x - tracked.position.x, position.y - tracked.position.y)
624        };
625        tracked.position = position;
626        tracked.phase = phase;
627    }
628}
629
630pub fn resolve<C: Context>(tree: &mut Tree<C>) {
631    let retained = &mut tree.interaction.kinds;
632    for slot in &mut retained.slots {
633        slot.node = tree.slots.node(slot.id).map_or(UNRESOLVED, |node| node.index() as u32);
634    }
635    let Kinds {
636        slots, kinds, state, ..
637    } = retained;
638    let before = slots.len();
639    slots.retain(|slot| {
640        if slot.order != UNRESOLVED {
641            return true;
642        }
643        let free = &mut kinds[slot.kind as usize].free;
644        let cell = state.as_ptr().wrapping_add(slot.offset as usize);
645        // safety: unrequested cells are dead and every cell starts with room for the link
646        unsafe { cell.cast::<Option<NonZeroU32>>().write(*free) };
647        *free = NonZeroU32::new(slot.offset + 1);
648        false
649    });
650    let removed = slots.len() != before;
651    let nodes = &tree.nodes;
652    let key = |slot: &Slot| {
653        let end = nodes
654            .get(slot.node as usize)
655            .map_or(UNRESOLVED, |stored| stored.subtree_end);
656        (end, core::cmp::Reverse(slot.node), slot.order)
657    };
658    // postorder with missing widgets last
659    let reordered = !slots.is_sorted_by_key(key);
660    if reordered {
661        slots.sort_unstable_by_key(key);
662    }
663    // table indices only shift when slots are removed or reordered
664    if removed || reordered {
665        retained.rebuild();
666    }
667    retained.requested = 0;
668    for slot in &mut retained.slots {
669        slot.order = UNRESOLVED;
670        if let Some(stored) = tree.nodes.get_mut(slot.node as usize) {
671            stored.interactive = true;
672        }
673    }
674    let retained = &*retained;
675    let nodes = &tree.nodes;
676    let node = |id| {
677        let slot = &retained.slots[retained.find(id, None).ok()?];
678        (slot.node != UNRESOLVED).then_some(slot.node as usize)
679    };
680    // a target that disappears retires its contacts rather than passing them on
681    let rebind = |HitTarget { id, .. }| node(id).map(|index| HitTarget { id, node: index as u32 });
682    for tracked in &mut tree.interaction.contacts {
683        tracked.route = match tracked.route {
684            Route::Pending {
685                target: Some(target),
686                claim,
687            } => rebind(target).map_or(Route::Retired, |target| Route::Pending {
688                target: Some(target),
689                claim,
690            }),
691            Route::Captured { owner } if node(owner).is_none() => Route::Retired,
692            route => route,
693        };
694    }
695    tree.interaction.focus_seen = tree.interaction.focused;
696    // focus requested during the build applies once it resolves
697    match core::mem::replace(&mut tree.focus, FocusRequest::Keep) {
698        FocusRequest::Keep => {}
699        FocusRequest::Clear => tree.interaction.focused = None,
700        FocusRequest::Focus(id) => tree.interaction.focused = Some(id),
701    }
702    // focus lasts while its widget requests an interaction
703    if tree.interaction.focused.is_some_and(|id| node(id).is_none()) {
704        tree.interaction.focused = None;
705    }
706    if let Some(scroll) = &mut tree.interaction.scroll {
707        scroll.target = scroll.target.and_then(rebind);
708        if scroll.owner.is_some_and(|id| node(id).is_none()) {
709            // cancel the owner while keeping the rest of its sequence from reaching another widget
710            scroll.cancelled = scroll.owner.take();
711            scroll.event = None;
712            scroll.target = None;
713        }
714    }
715    tree.interaction.hits.clear();
716    if !tree.interaction.kinds.slots.is_empty() {
717        let count = tree.nodes.len();
718        let placements = &tree.placements[..count];
719        let mut collect = {
720            #[inline(always)]
721            |index: usize, stored: &StoredNode, area: Rect<C::Scalar>| {
722                let id = stored.id;
723                if !stored.interactive {
724                    return;
725                }
726                let hit = stored
727                    .aux
728                    .index()
729                    .map_or(Sides::all(C::Scalar::ZERO), |index| tree.aux[index].hit);
730                let area = Rect::new(
731                    area.x - hit.left,
732                    area.y - hit.top,
733                    area.width + hit.left + hit.right,
734                    area.height + hit.top + hit.bottom,
735                );
736                let clip = if tree.resolved_clips.is_empty() {
737                    ResolvedClipId::NONE
738                } else {
739                    tree.resolved_clips[index]
740                };
741                let clip_bounds = clip
742                    .index()
743                    .map_or(tree.screen, |clip| tree.interaction.clips[clip].bounds);
744                tree.interaction.hits.push(HitItem {
745                    id,
746                    area: area.intersection(clip_bounds).unwrap_or_default(),
747                    clip,
748                    node: index as u32,
749                });
750            }
751        };
752        if tree.paint_order.is_empty() {
753            for (index, (stored, &area)) in nodes.iter().zip(placements).enumerate() {
754                collect(index, stored, area);
755            }
756        } else {
757            for id in &tree.paint_order[..count] {
758                collect(id.index(), &nodes[id.index()], placements[id.index()]);
759            }
760        }
761    }
762}
763
764fn hit<T: Scalar>(hits: &[HitItem<T>], clips: &[ResolvedClip<T>], position: Point<T>) -> Option<HitItem<T>> {
765    hits.iter()
766        .rev()
767        .find(|hit| {
768            if !hit.area.contains(position) {
769                return false;
770            }
771            let mut clip = hit.clip;
772            while let Some(index) = clip.index() {
773                let ResolvedClip {
774                    area, radius, parent, ..
775                } = clips[index];
776                if !area.contains(position) {
777                    return false;
778                }
779                if radius == Corners::all(T::ZERO) {
780                    clip = parent;
781                    continue;
782                }
783                let left = (position.x - area.x).to_f32();
784                let right = (area.x.endpoint(area.width) - position.x).to_f32();
785                let top = (position.y - area.y).to_f32();
786                let bottom = (area.y.endpoint(area.height) - position.y).to_f32();
787                // the corner of the quadrant holding the position
788                let radius = match (left < right, top < bottom) {
789                    (true, true) => radius.top_left,
790                    (false, true) => radius.top_right,
791                    (false, false) => radius.bottom_right,
792                    (true, false) => radius.bottom_left,
793                };
794                let radius = radius.to_f32().min(area.width.min(area.height).to_f32() * 0.5).max(0.0);
795                let x = (radius - left.min(right)).max(0.0);
796                let y = (radius - top.min(bottom)).max(0.0);
797                if x * x + y * y > radius * radius {
798                    return false;
799                }
800                clip = parent;
801            }
802            true
803        })
804        .copied()
805}
806
807#[derive(Clone, Copy, Debug, PartialEq)]
808enum Route {
809    Pending {
810        target: Option<HitTarget>,
811        claim: Option<Id>,
812    },
813    Captured {
814        owner: Id,
815    },
816    Retired,
817}
818
819/// a pending contact's deepest widget and its node in the previous layout
820#[derive(Clone, Copy, Debug, PartialEq)]
821struct HitTarget {
822    id: Id,
823    node: u32,
824}
825
826#[derive(Clone, Copy)]
827struct TrackedContact<T> {
828    id: ContactId,
829    source: ContactSource,
830    route: Route,
831    phase: Phase,
832    origin: Point<T>,
833    position: Point<T>,
834    delta: Point<T>,
835    started: Duration,
836    // node under the position in the previous layout
837    hit: Option<u32>,
838}
839
840#[derive(Clone, Copy)]
841struct TrackedScroll {
842    // node under the pointer when the sequence started
843    target: Option<HitTarget>,
844    owner: Option<Id>,
845    event: Option<ScrollEvent>,
846    active: bool,
847    cancelled: Option<Id>,
848}
849
850#[derive(Clone, Copy)]
851struct HitItem<T> {
852    id: Id,
853    area: Rect<T>,
854    clip: ResolvedClipId,
855    node: u32,
856}
857
858/// retained interaction kinds and their state
859#[derive(Default)]
860struct Kinds<T> {
861    // sorted by postorder and request order, then slots added by the current build
862    slots: Vec<Slot>,
863    // slot indices, at most half full
864    table: Vec<u32>,
865    requested: u32,
866    kinds: Vec<Kind<T>>,
867    // cells of every kind, reused through each kind's free list
868    state: Bump,
869}
870
871impl<T> Kinds<T> {
872    #[inline(never)]
873    fn register(&mut self, type_id: TypeId, update: fn(&mut Kinds<T>, usize, &mut InteractCx<'_, T>)) -> u16 {
874        let kind = self
875            .kinds
876            .iter()
877            .position(|kind| kind.type_id == type_id)
878            .unwrap_or_else(|| {
879                assert!(self.kinds.len() <= u16::MAX as usize, "too many interaction kinds");
880                self.kinds.push(Kind {
881                    type_id,
882                    update,
883                    free: None,
884                });
885                self.kinds.len() - 1
886            });
887        kind as u16
888    }
889
890    fn mark_requested(&mut self, index: usize) {
891        let slot = &mut self.slots[index];
892        if slot.order == UNRESOLVED {
893            slot.order = self.requested;
894            self.requested += 1;
895        }
896    }
897
898    #[cold]
899    #[inline(never)]
900    fn insert_requested(&mut self, bucket: usize, id: Id, kind: u16, offset: u32) {
901        let order = self.requested;
902        self.requested += 1;
903        let index = self.slots.len();
904        assert!(index < UNRESOLVED as usize, "too many interaction slots");
905        self.slots.push(Slot {
906            id,
907            node: UNRESOLVED,
908            offset,
909            order,
910            kind,
911        });
912        if self.slots.len() > self.table.len() / 2 {
913            self.rebuild();
914        } else {
915            self.table[bucket] = index as u32;
916        }
917    }
918
919    fn get_mut<C: Context<Scalar = T>, K: Interact<C>>(&mut self, index: usize) -> &mut (K, K::State, K::Response) {
920        let slot = &self.slots[index];
921        assert_eq!(
922            self.kinds[slot.kind as usize].type_id,
923            TypeId::of::<K>(),
924            "interaction kind mismatch"
925        );
926        // safety: the slot is live and its kind was checked above
927        unsafe { self.state.get_mut(Offset::new(slot.offset)) }
928    }
929
930    // slot index on a hit, insertion bucket on a miss
931    fn find(&self, id: Id, kind: Option<u16>) -> Result<usize, usize> {
932        if self.table.is_empty() {
933            return Err(0);
934        }
935        let bucket = self.probe(id, kind);
936        match self.table[bucket] {
937            UNRESOLVED => Err(bucket),
938            index => Ok(index as usize),
939        }
940    }
941
942    fn rebuild(&mut self) {
943        let len = self.slots.len();
944        if len == 0 {
945            self.table.clear();
946            return;
947        }
948        // grow above half full and shrink below one eighth
949        // to avoid resizing on small count changes
950        if len < self.table.len() / 8 {
951            self.table.truncate((len * 2).next_power_of_two());
952        }
953        self.table.fill(UNRESOLVED);
954        if len > self.table.len() / 2 {
955            self.table.resize((len * 2).next_power_of_two(), UNRESOLVED);
956        }
957        for (index, slot) in self.slots.iter().enumerate() {
958            let bucket = self.probe(slot.id, Some(slot.kind));
959            self.table[bucket] = index as u32;
960        }
961    }
962
963    fn probe(&self, id: Id, kind: Option<u16>) -> usize {
964        let mask = self.table.len() - 1;
965        // dense slots with several kinds each would cluster, so the slot is mixed
966        let mixed = u64::from(id.slot).wrapping_mul(0x9e37_79b9_7f4a_7c15);
967        let mut bucket = (mixed >> (64 - self.table.len().trailing_zeros())) as usize;
968        loop {
969            let index = self.table[bucket];
970            if index == UNRESOLVED {
971                return bucket;
972            }
973            let slot = &self.slots[index as usize];
974            if slot.id == id && kind.is_none_or(|kind| slot.kind == kind) {
975                return bucket;
976            }
977            bucket = (bucket + 1) & mask;
978        }
979    }
980}
981
982#[derive(Clone, Copy)]
983struct Slot {
984    id: Id,
985    // in the latest build, or unresolved for a named widget missing from it
986    node: u32,
987    offset: u32,
988    // first request in the current build, or unresolved when unrequested
989    order: u32,
990    kind: u16,
991}
992
993struct Kind<T> {
994    type_id: TypeId,
995    update: fn(&mut Kinds<T>, usize, &mut InteractCx<'_, T>),
996    // dead cells of this kind linked by byte offset plus one
997    free: Option<NonZeroU32>,
998}
999
1000/// a kind with its state and latest response, which holds the free link once it is dead
1001#[derive(Clone, Copy)]
1002#[repr(C)]
1003union Cell<S: Copy> {
1004    value: S,
1005    next: Option<NonZeroU32>,
1006}