Skip to main content

blit/
ui.rs

1use crate::*;
2
3/// typestate modes for [`Ui`]
4///
5/// every mode can query its target and access shared frame services
6pub mod state {
7    use super::PhantomData;
8
9    /// a node without a layout that may establish one
10    pub struct Build;
11
12    /// a child without a layout, with layout item `I`
13    pub struct Child<I>(PhantomData<I>);
14
15    /// a laid-out node that may create children
16    pub struct Open<L>(PhantomData<L>);
17
18    /// adds content and interactions to an existing node through [`crate::Ui::insert`]
19    pub struct Insert;
20
21    /// another node referenced by id through [`crate::Ui::node`], which may be built later
22    pub struct Ref;
23
24    /// modes that own their node and may set its properties
25    pub trait Owned {}
26
27    impl Owned for Build {}
28    impl<I> Owned for Child<I> {}
29    impl<L> Owned for Open<L> {}
30
31    /// modes that act on their own node rather than a target
32    pub trait Local {}
33
34    impl Local for Build {}
35    impl<I> Local for Child<I> {}
36    impl<L> Local for Open<L> {}
37    impl Local for Insert {}
38
39    /// modes whose node has no layout yet
40    pub trait NoLayout: Owned + Local {}
41
42    impl NoLayout for Build {}
43    impl<I> NoLayout for Child<I> {}
44}
45
46/// scoped handle for building a tree node
47///
48/// its [`state`] mode determines which operations are available
49pub struct Ui<'ui, C: Context, S = state::Build> {
50    inner: UiInner<'ui, C>,
51    marker: PhantomData<S>,
52}
53
54impl<'ui, C: Context, S> Ui<'ui, C, S> {
55    /// the target's stable id
56    pub fn id(&self) -> Id {
57        self.inner.target
58    }
59
60    /// the target's area from the previous layout
61    #[inline(always)]
62    pub fn area(&self) -> Option<Rect<C::Scalar>> {
63        self.inner.area()
64    }
65
66    /// adds `interaction` to the target and returns its latest response
67    ///
68    /// one interaction of each kind per target, repeated requests share it
69    #[inline(always)]
70    pub fn interact<K: Interact<C>>(&mut self, interaction: K) -> K::Response {
71        let tree = &mut *self.inner.tree;
72        tree.interaction
73            .interact::<C, K>(self.inner.target, interaction, tree.time)
74    }
75
76    /// animates toward `target`, keyed by the target and call site, then by call order within a frame
77    #[inline(always)]
78    #[track_caller]
79    pub fn animate(&mut self, target: f32, animation: impl Into<Animation>, options: AnimationOptions) -> f32 {
80        self.inner
81            .animate(target, animation.into(), options, Location::caller())
82    }
83
84    #[inline(always)]
85    #[track_caller]
86    pub fn animate_loop(&mut self, tween: Tween) -> f32 {
87        self.inner.animate_loop(tween, Location::caller())
88    }
89
90    /// fires once, `duration` after the target first calls it from this site or after a reset
91    #[inline(always)]
92    #[track_caller]
93    pub fn timer(&mut self, duration: Duration) -> Timer<'_> {
94        self.inner.timer(duration, false, Location::caller())
95    }
96
97    /// fires every `period`, counting from when the target first calls it from this site or from a reset
98    #[inline(always)]
99    #[track_caller]
100    pub fn interval(&mut self, period: Duration) -> Timer<'_> {
101        self.inner.timer(period, true, Location::caller())
102    }
103
104    /// focuses the target from the next build while it requests an interaction
105    pub fn focus(&mut self) {
106        self.inner.tree.focus = FocusRequest::Focus(self.inner.target);
107    }
108
109    /// whether the target holds focus as this build began
110    pub fn focused(&self) -> bool {
111        self.inner.tree.interaction.focused == Some(self.inner.target)
112    }
113
114    /// whether focus changed from the previous build
115    pub fn focus_moved(&self) -> bool {
116        let interaction = &self.inner.tree.interaction;
117        interaction.focused != interaction.focus_seen
118    }
119
120    /// clears focus from the next build
121    pub fn clear_focus(&mut self) {
122        self.inner.tree.focus = FocusRequest::Clear;
123    }
124
125    /// access context during frame construction
126    pub fn context(&self) -> &C {
127        self.inner.context
128    }
129
130    /// access mutable context during frame construction
131    pub fn context_mut(&mut self) -> &mut C {
132        self.inner.context
133    }
134
135    /// the mouse cursor position, independent of touches
136    pub fn mouse_position(&self) -> Option<Point<C::Scalar>> {
137        self.inner.tree.interaction.mouse_position
138    }
139
140    /// the position of a contact in this frame
141    ///
142    /// ended and cancelled contacts remain available until the next build
143    pub fn contact_position(&self, id: ContactId) -> Option<Point<C::Scalar>> {
144        self.inner.tree.interaction.contact_position(id)
145    }
146
147    /// this frame's input regardless of focus or claims
148    ///
149    /// handle keyboard shortcuts through an interaction to respect input routing.
150    pub fn input(&self) -> &Input<C::Scalar> {
151        &self.inner.tree.input
152    }
153
154    pub fn screen(&self) -> Rect<C::Scalar> {
155        self.inner.tree.screen
156    }
157
158    pub fn time(&self) -> Duration {
159        self.inner.tree.time
160    }
161
162    pub fn request_frame(&mut self) {
163        self.inner.tree.request_frame();
164    }
165}
166
167impl<'ui, C: Context, S: state::Local> Ui<'ui, C, S> {
168    /// refers to the node with `id`, which may be built later, and keeps its id through this build
169    #[inline]
170    pub fn node(&mut self, id: Id) -> Ui<'_, C, state::Ref> {
171        self.inner.tree.slots.keep(id);
172        Ui {
173            inner: self.inner.borrow(id),
174            marker: PhantomData,
175        }
176    }
177
178    /// resolves `key` in `scope` to its id, taking a slot if nothing holds it yet
179    #[inline]
180    pub fn resolve(&mut self, scope: Scope, key: impl Key) -> Id {
181        let id = self.inner.tree.slots.name(scope.0, key.value());
182        self.inner.tree.slots.keep(id);
183        id
184    }
185
186    /// a scope for keys of this node and call site, so keys of unrelated code never meet
187    ///
188    /// scopes made at one call site repeat within a build, told apart by their order
189    #[inline(always)]
190    #[track_caller]
191    pub fn scope(&mut self) -> Scope {
192        self.inner.scope(Location::caller())
193    }
194
195    /// inserts content into the current node
196    #[inline]
197    pub fn insert<W: Widget<C, state::Insert>>(&mut self, widget: W) -> W::Response {
198        widget.build(Ui {
199            inner: self.inner.borrow(self.inner.target),
200            marker: PhantomData,
201        })
202    }
203
204    /// schedules a deferred paint closure on the current node
205    #[inline]
206    pub fn paint<F>(&mut self, paint: F)
207    where
208        F: Fn(&mut PaintCx<'_, C>, Rect<C::Scalar>) + 'static,
209    {
210        paint::insert_paint(self.inner.tree, self.inner.node, paint);
211    }
212
213    /// registers a deferred measurement closure on the current node
214    ///
215    /// measurement may be skipped under tight constraints or when widened past natural width.
216    /// painting must not depend on prior measurement.
217    #[inline]
218    pub fn measure<R, F>(&mut self, measure: F)
219    where
220        R: Into<Fit<Size<C::Scalar>>>,
221        F: Fn(&mut C, Constraints<C::Scalar>) -> R + 'static,
222    {
223        paint::insert_measure(self.inner.tree, self.inner.node, measure);
224    }
225
226    /// the focused node, if it was beneath this one in the previous layout
227    #[inline(always)]
228    pub fn focus_within(&self) -> Option<Id> {
229        self.inner.focus_within()
230    }
231
232    /// the id of this node's structural parent, or its own for the root
233    pub fn parent_id(&self) -> Id {
234        let nodes = &self.inner.tree.nodes;
235        nodes[nodes[self.inner.node.index()].parent.index()].id
236    }
237
238    /// temporary storage that stays usable while building this node
239    pub fn scratch(&self) -> &'ui ScratchBuffer {
240        self.inner.scratch
241    }
242}
243
244impl<'ui, C: Context, S: state::Owned> Ui<'ui, C, S> {
245    /// sets this node's size limits
246    #[inline(always)]
247    pub fn constrain(mut self, limits: Constraints<C::Scalar>) -> Self {
248        self.inner.constrain(limits);
249        self
250    }
251
252    /// creates a child placed against `target` outside its parent's flow
253    ///
254    /// a target not built before this node places it against its parent
255    #[inline]
256    #[track_caller]
257    pub fn place<P: Place<C>>(&mut self, target: Id, place: P) -> Ui<'_, C, state::Build> {
258        let (node, old) = self.inner.child(Location::caller());
259        attach_place(self.inner.tree, node, target, place);
260        Ui::new(self.inner.tree, self.inner.context, self.inner.scratch, node, old)
261    }
262
263    /// creates the child keyed `key` in `scope`, placed against `target` outside its parent's flow
264    ///
265    /// a target not built before this node places it against its parent
266    #[inline]
267    #[track_caller]
268    pub fn place_in<P: Place<C>>(
269        &mut self,
270        scope: Scope,
271        key: impl Key,
272        target: Id,
273        place: P,
274    ) -> Ui<'_, C, state::Build> {
275        let (node, old) = self.inner.child_in(scope.0, key.value(), Location::caller());
276        attach_place(self.inner.tree, node, target, place);
277        Ui::new(self.inner.tree, self.inner.context, self.inner.scratch, node, old)
278    }
279
280    #[inline(always)]
281    pub fn motion(mut self, motion: Motion) -> Self {
282        self.inner.motion(motion);
283        self
284    }
285
286    /// selects the parent for stacking, clipping and containing size
287    ///
288    /// positioning stays with its anchor. a target not built before this node leaves its own parent
289    #[inline(always)]
290    pub fn parent(mut self, target: Id) -> Self {
291        self.inner.parent(target);
292        self
293    }
294
295    /// clips drawing and hit testing of this node and its visual descendants to its rounded area
296    #[inline(always)]
297    pub fn clip(mut self, radius: impl Into<Corners<C::Scalar>>) -> Self {
298        self.inner.clip(radius.into());
299        self
300    }
301
302    /// sets this node's paint order among its visual siblings
303    #[inline(always)]
304    pub fn z_index(mut self, z_index: i16) -> Self {
305        self.inner.z_index(z_index);
306        self
307    }
308
309    #[inline(always)]
310    pub fn hit(mut self, hit: Sides<C::Scalar>) -> Self {
311        self.inner.hit(hit);
312        self
313    }
314}
315
316impl<'ui, C: Context, S: state::NoLayout> Ui<'ui, C, S> {
317    /// builds a widget in this node
318    pub fn build<W: Widget<C>>(self, widget: W) -> W::Response {
319        widget.build(Ui {
320            inner: self.inner,
321            marker: PhantomData,
322        })
323    }
324
325    /// establishes the current node's layout
326    #[inline]
327    pub fn layout<L: Layout<C>>(self, layout: L) -> Ui<'ui, C, state::Open<L>> {
328        let Ui { mut inner, .. } = self;
329        let kind = inner.register_layout_kind(TypeId::of::<L>(), layout::fit::<C, L>, layout::distribute::<C, L>);
330        if inner.tree.layout_kinds[kind as usize].default_item.offset().is_none() {
331            inner.tree.layout_kinds[kind as usize].default_item = inner.tree.bump.store(L::Item::default());
332        }
333        let bump_id = inner.tree.bump.store(layout);
334        let node = &mut inner.tree.nodes[inner.node.index()];
335        node.layout = bump_id;
336        node.layout_kind = kind;
337        Ui {
338            inner,
339            marker: PhantomData,
340        }
341    }
342}
343
344impl<'ui, C: Context, I: 'static> Ui<'ui, C, state::Child<I>> {
345    /// sets this child's layout item
346    #[inline]
347    pub fn item(self, item: I) -> Ui<'ui, C, state::Build> {
348        let Ui { inner, .. } = self;
349        inner.tree.nodes[inner.node.index()].item = inner.tree.bump.store(item);
350        Ui {
351            inner,
352            marker: PhantomData,
353        }
354    }
355}
356
357impl<'ui, C: Context, L: Layout<C>> Ui<'ui, C, state::Open<L>> {
358    /// creates a child identified by where it is built
359    ///
360    /// children built from one place are told apart by the order they are built in
361    #[inline]
362    #[track_caller]
363    pub fn child(&mut self) -> Ui<'_, C, state::Child<L::Item>> {
364        let (node, old) = self.inner.child(Location::caller());
365        Ui::new(self.inner.tree, self.inner.context, self.inner.scratch, node, old)
366    }
367
368    /// creates the child keyed `key` in `scope` rather than one identified by where it is built
369    ///
370    /// it keeps its state as its siblings change or it moves to another parent, as its key stays.
371    /// [`Ui::resolve`] with the same scope and key returns its id before it is built
372    #[inline]
373    #[track_caller]
374    pub fn child_in(&mut self, scope: Scope, key: impl Key) -> Ui<'_, C, state::Child<L::Item>> {
375        let (node, old) = self.inner.child_in(scope.0, key.value(), Location::caller());
376        Ui::new(self.inner.tree, self.inner.context, self.inner.scratch, node, old)
377    }
378
379    /// lays out a built child now and returns its current animated size under `bounds`
380    ///
381    /// the layout pass lays it out again with whatever bounds this node's layout gives it
382    #[inline(always)]
383    pub fn layout_child(&mut self, child: Id, bounds: Constraints<C::Scalar>) -> Size<C::Scalar> {
384        self.inner.layout_child(child, bounds)
385    }
386
387    /// insets this node's children while painted content keeps the full box
388    #[inline(always)]
389    pub fn pad(mut self, padding: impl Into<Sides<C::Scalar>>) -> Self {
390        self.inner.pad(padding.into());
391        self
392    }
393}
394
395//
396// internals
397//
398
399/// the node with `target`, if it was built before `node`
400// keeps target and visual parent chains acyclic and ordered for single pass layout and paint
401pub fn resolve_target<C: Context>(tree: &Tree<C>, node: NodeId, target: Id) -> Option<NodeId> {
402    let target = tree.slots.node(target)?;
403    (target.index() < node.index()).then_some(target)
404}
405
406fn attach_place<C: Context, P: Place<C>>(tree: &mut Tree<C>, node: NodeId, target: Id, place: P) {
407    let reference = resolve_target(tree, node, target);
408    let id = PlaceId::new(tree.places.len());
409    tree.places.push(StoredPlace {
410        bump_id: tree.bump.store(place),
411        run: layout::place::<C, P>,
412    });
413    let stored = &mut tree.nodes[node.index()];
414    stored.target = reference.unwrap_or(stored.target);
415    stored.place = id;
416    stored.place_scope = node;
417}
418
419struct UiInner<'ui, C: Context> {
420    tree: &'ui mut Tree<C>,
421    context: &'ui mut C,
422    scratch: &'ui ScratchBuffer,
423    node: NodeId,
424    // the node this ui acts on, its own unless made by `node`
425    target: Id,
426    // where this node's call sites start in the frame's site stack or Slots::NONE when not owning a node
427    sites: u32,
428    // this node in the previous build, and its child to try next
429    cursor: Cursor,
430}
431
432// methods are here to avoid monomorphizing to type states
433impl<'ui, C: Context> UiInner<'ui, C> {
434    fn new(tree: &'ui mut Tree<C>, context: &'ui mut C, scratch: &'ui ScratchBuffer, node: NodeId, old: u32) -> Self {
435        Self {
436            target: tree.nodes[node.index()].id,
437            sites: tree.sites.len() as u32,
438            // wraps to zero for a node new to this build, which has no children to try
439            cursor: Cursor {
440                old,
441                next: old.wrapping_add(1),
442            },
443            tree,
444            context,
445            scratch,
446            node,
447        }
448    }
449
450    #[inline]
451    fn borrow(&mut self, target: Id) -> UiInner<'_, C> {
452        UiInner {
453            tree: self.tree,
454            context: self.context,
455            scratch: self.scratch,
456            node: self.node,
457            target,
458            sites: Slots::NONE,
459            cursor: Cursor {
460                old: Slots::NONE,
461                next: 0,
462            },
463        }
464    }
465
466    fn area(&self) -> Option<Rect<C::Scalar>> {
467        let tree = &*self.tree;
468        let old = tree.slots.old(self.target)?;
469        tree.old_placements.get(old).copied()
470    }
471
472    #[inline(never)]
473    fn animate(
474        &mut self,
475        target: f32,
476        animation: Animation,
477        mut options: AnimationOptions,
478        location: &'static Location<'static>,
479    ) -> f32 {
480        let call = Call::new(self.target, location);
481        let tree = &mut *self.tree;
482        // cleared so stored options stay equal across frames and do not retarget
483        let initial = options.initial.take().unwrap_or(target);
484        let state = AnimationState::update(&mut tree.animations, call, initial);
485        match &mut state.playback {
486            Playback::Target(animator) => {
487                animator
488                    .advance([target], [true], animation, options, tree.time, true)
489                    .0[0]
490            }
491            Playback::Loop { value, .. } => {
492                let mut animator = Animator::new([*value], Animation::default());
493                let value = animator
494                    .advance([target], [true], animation, options, tree.time, true)
495                    .0[0];
496                state.playback = Playback::Target(animator);
497                value
498            }
499        }
500    }
501
502    #[inline(never)]
503    fn animate_loop(&mut self, mut tween: Tween, location: &'static Location<'static>) -> f32 {
504        tween.duration = tween.duration.max(0.0);
505        if tween.duration == 0.0 {
506            return self.animate(0.0, Animation::default(), AnimationOptions::default(), location);
507        }
508        let call = Call::new(self.target, location);
509        let tree = &mut *self.tree;
510        let state = AnimationState::update(&mut tree.animations, call, 0.0);
511        let now = tree.time.as_secs_f64();
512        let time = match state.playback {
513            Playback::Loop {
514                tween: previous, time, ..
515            } if previous == tween => time,
516            _ => now,
517        };
518        let progress = (now - time).max(0.0) as f32 / tween.duration;
519        let value = tween.easing.sample(progress % 1.0).0;
520        state.playback = Playback::Loop { tween, time, value };
521        value
522    }
523
524    #[inline(never)]
525    fn timer(&mut self, period: Duration, repeat: bool, location: &'static Location<'static>) -> Timer<'_> {
526        if repeat {
527            assert!(!period.is_zero(), "an interval must be nonzero");
528        }
529        let call = Call::new(self.target, location);
530        let tree = &mut *self.tree;
531        TimerState::update(&mut tree.timers, call, period, repeat, tree.time)
532    }
533
534    #[inline(never)]
535    fn scope(&mut self, location: &'static Location<'static>) -> Scope {
536        let tree = &mut *self.tree;
537        let mut call = Call::new(self.target, location);
538        let index = loop {
539            match tree.scopes.binary_search_by_key(&call, |scope| scope.call) {
540                Ok(index) if tree.slots.is_kept(tree.scopes[index].id) => call.repeat += 1,
541                Ok(index) => break index,
542                Err(index) => {
543                    let id = tree.slots.alloc();
544                    tree.scopes.insert(index, CallScope { call, id });
545                    break index;
546                }
547            }
548        };
549        let id = tree.scopes[index].id;
550        tree.slots.keep(id);
551        Scope(id)
552    }
553
554    fn focus_within(&self) -> Option<Id> {
555        let tree = &*self.tree;
556        let focused = tree.interaction.focused?;
557        let node = tree.slots.old(self.target)?;
558        let inside = tree.slots.old(focused)?;
559        (node < inside && inside <= tree.old_nodes[node].subtree_end as usize).then_some(focused)
560    }
561
562    #[inline(never)]
563    fn constrain(&mut self, limits: Constraints<C::Scalar>) {
564        assert!(
565            limits.min.width >= C::Scalar::ZERO
566                && limits.min.height >= C::Scalar::ZERO
567                && limits.min.width.is_finite()
568                && limits.min.height.is_finite()
569                && limits.max.width >= limits.min.width
570                && limits.max.height >= limits.min.height,
571            "invalid local bounds"
572        );
573        self.tree.aux_mut(self.node).limits = limits;
574    }
575
576    fn motion(&mut self, motion: Motion) {
577        let tree = &mut *self.tree;
578        match tree.aux_mut(self.node).motion.index() {
579            Some(index) => tree.node_motions[index].motion = motion,
580            None => {
581                tree.aux_mut(self.node).motion = NodeMotionId::new(tree.node_motions.len());
582                tree.node_motions.push(NodeMotion {
583                    node: self.node,
584                    motion,
585                });
586            }
587        }
588    }
589
590    fn parent(&mut self, target: Id) {
591        if let Some(parent) = resolve_target(self.tree, self.node, target) {
592            self.tree.aux_mut(self.node).visual_parent = parent;
593            if parent != self.tree.nodes[self.node.index()].parent {
594                self.tree.has_custom_order = true;
595            }
596        }
597    }
598
599    fn clip(&mut self, radius: Corners<C::Scalar>) {
600        self.tree.aux_mut(self.node).clip = Some(radius);
601        self.tree.has_clips = true;
602    }
603
604    fn z_index(&mut self, z_index: i16) {
605        self.tree.set_z_index(self.node, z_index);
606    }
607
608    fn hit(&mut self, hit: Sides<C::Scalar>) {
609        self.tree.aux_mut(self.node).hit = hit;
610    }
611
612    #[inline(never)]
613    fn pad(&mut self, padding: Sides<C::Scalar>) {
614        assert!(
615            [padding.top, padding.right, padding.bottom, padding.left]
616                .iter()
617                .all(|side| *side >= C::Scalar::ZERO && side.is_finite()),
618            "invalid padding"
619        );
620        self.tree.aux_mut(self.node).padding = padding;
621    }
622
623    fn layout_child(&mut self, child: Id, bounds: Constraints<C::Scalar>) -> Size<C::Scalar> {
624        let tree = &mut *self.tree;
625        let child = tree.slots.node(child).expect("a laid out child must be built first");
626        assert!(
627            tree.nodes[child.index()].place.index().is_none(),
628            "measured widgets must stay in flow"
629        );
630        let mut bump = core::mem::take(&mut tree.bump);
631        bump.storage.prepare();
632        let size = layout::resolve(tree, &bump, self.context, child, bounds, false);
633        tree.bump = bump;
634        size
635    }
636
637    #[inline(never)]
638    fn register_layout_kind(
639        &mut self,
640        type_id: TypeId,
641        fit: fn(&mut LayoutCx<'_, C>, BumpId, Axis) -> Fit<C::Scalar>,
642        distribute: fn(&mut LayoutCx<'_, C>, BumpId, Axis, C::Scalar),
643    ) -> u16 {
644        let tree = &mut *self.tree;
645        let kind = tree
646            .layout_kinds
647            .iter()
648            .position(|kind| kind.type_id == type_id)
649            .unwrap_or_else(|| {
650                tree.layout_kinds.push(LayoutKind {
651                    type_id,
652                    fit,
653                    distribute,
654                    default_item: BumpId::NONE,
655                });
656                tree.layout_kinds.len() - 1
657            });
658        u16::try_from(kind).expect("too many layout kinds")
659    }
660
661    // children return their node and its match in the previous build, which fit in one register
662    fn child(&mut self, location: &'static Location<'static>) -> (NodeId, u32) {
663        // out of line so the usual match stays small
664        #[cold]
665        fn search(
666            old_nodes: &[StoredNode],
667            old_marks: &[Mark],
668            cursor: Cursor,
669            end: u32,
670            location: &Location<'_>,
671            ordinal: u32,
672        ) -> Option<u32> {
673            // scan past the cursor first so skipped siblings stay linear, then wrap around
674            let mut index = if cursor.next <= end {
675                old_nodes[cursor.next as usize].subtree_end + 1
676            } else {
677                end + 1
678            };
679            while index <= end {
680                if old_marks[index as usize].is_site(location, ordinal) {
681                    return Some(index);
682                }
683                index = old_nodes[index as usize].subtree_end + 1;
684            }
685            let mut index = cursor.old + 1;
686            while index < cursor.next {
687                if old_marks[index as usize].is_site(location, ordinal) {
688                    return Some(index);
689                }
690                index = old_nodes[index as usize].subtree_end + 1;
691            }
692            None
693        }
694
695        let tree = &mut *self.tree;
696        let start = self.sites as usize;
697        let (site, ordinal, scan) = match tree.sites[start..]
698            .iter()
699            .rposition(|site| same_place(site.location, location))
700        {
701            Some(index) => {
702                let site = &mut tree.sites[start + index];
703                site.ordinal = site.ordinal.checked_add(1).expect("too many children from one place");
704                (start + index, site.ordinal, site.scan)
705            }
706            None => {
707                tree.sites.push(Site {
708                    location,
709                    ordinal: 0,
710                    scan: true,
711                });
712                (tree.sites.len() - 1, 0, true)
713            }
714        };
715        let mut found = None;
716        if scan && self.cursor.old != Slots::NONE {
717            let end = tree.old_nodes[self.cursor.old as usize].subtree_end;
718            if self.cursor.next <= end && tree.old_marks[self.cursor.next as usize].is_site(location, ordinal) {
719                found = Some(self.cursor.next);
720            } else {
721                found = search(&tree.old_nodes, &tree.old_marks, self.cursor, end, location, ordinal);
722                tree.sites[site].scan = found.is_some();
723            }
724        }
725        let (id, old) = match found {
726            Some(index) => {
727                let stored = &tree.old_nodes[index as usize];
728                self.cursor.next = stored.subtree_end + 1;
729                (stored.id, index)
730            }
731            None => (tree.slots.alloc(), Slots::NONE),
732        };
733        (tree.push_node(Some(self.node), id, Mark::Site(location, ordinal)), old)
734    }
735
736    fn child_in(&mut self, scope: Id, key: u64, location: &'static Location<'static>) -> (NodeId, u32) {
737        let tree = &mut *self.tree;
738        // a scope is kept by the build that made it, while one held from an older build names alone
739        let keyed = tree.slots.is_kept(scope);
740        let mut mark = if keyed { Mark::Key(scope.slot, key) } else { Mark::Named };
741        let (mut id, mut old) = if keyed
742            && self.cursor.old != Slots::NONE
743            && self.cursor.next <= tree.old_nodes[self.cursor.old as usize].subtree_end
744            && matches!(tree.old_marks[self.cursor.next as usize], Mark::Key(slot, other) if slot == scope.slot && other == key)
745        {
746            let index = self.cursor.next;
747            let stored = &tree.old_nodes[index as usize];
748            self.cursor.next = stored.subtree_end + 1;
749            (stored.id, index)
750        } else {
751            let id = tree.slots.name(scope, key);
752            let old = tree.slots.old(id).map_or(Slots::NONE, |node| node as u32);
753            // a moved key among these siblings keeps the ones after it on the cursor
754            if old != Slots::NONE && tree.old_nodes[old as usize].parent.index() as u32 == self.cursor.old {
755                self.cursor.next = tree.old_nodes[old as usize].subtree_end + 1;
756            }
757            (id, old)
758        };
759        if tree.slots.claimed(id) {
760            // the repeat is named alone so the next build finds the first holder
761            self.context.duplicate_key(Scope(scope), key, location);
762            id = tree.slots.alloc();
763            old = Slots::NONE;
764            mark = Mark::Named;
765        }
766        (tree.push_node(Some(self.node), id, mark), old)
767    }
768}
769
770impl<'ui, C: Context, S> Ui<'ui, C, S> {
771    pub(crate) fn new(
772        tree: &'ui mut Tree<C>,
773        context: &'ui mut C,
774        scratch: &'ui ScratchBuffer,
775        node: NodeId,
776        old: u32,
777    ) -> Self {
778        Self {
779            inner: UiInner::new(tree, context, scratch, node, old),
780            marker: PhantomData,
781        }
782    }
783}
784
785impl<C: Context> Drop for UiInner<'_, C> {
786    fn drop(&mut self) {
787        if self.sites == Slots::NONE {
788            return;
789        }
790        self.tree.nodes[self.node.index()].subtree_end = (self.tree.nodes.len() - 1) as u32;
791        // sites nest like open nodes so this node's are always last
792        self.tree.sites.truncate(self.sites as usize);
793    }
794}