Skip to main content

kui_core/
tree.rs

1//! [`Tree`]: the per-frame flat tree the core builds, lays out and emits.
2//!
3//! The tree is a set of parallel `Vec`s, one entry per node, rebuilt from
4//! scratch every frame with their capacities retained. Nodes are stored in
5//! DFS preorder (a parent always precedes its children, and preorder is
6//! paint order) and linked through `parent`, `first_child` and
7//! `next_sibling` indices. Layout writes `size` and `pos` into it; emission
8//! reads them. [`OriginId`] says which frontend (the host app, an
9//! extension, the core's own surfaces) opened each node.
10//!
11//! An app never touches this type: it builds through [`Ui`](crate::ui::Ui)
12//! and reads back through `Core`. It is public for a custom runner or a
13//! test that drives [`layout::compute`](crate::layout::compute) directly.
14
15use crate::geom::{Size, Vec2};
16use crate::key::Key;
17use crate::spec::NodeSpec;
18
19pub const NIL: u32 = u32::MAX;
20
21/// Which frontend produced a node: 0 is the host app, extensions get 1+.
22#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
23pub struct OriginId(pub u16);
24
25impl OriginId {
26    pub const HOST: OriginId = OriginId(0);
27    /// The core's own devtools panel: a node opened
28    /// under it is the panel's, and an event that carries it is acted on
29    /// inside `handle_input` and never handed out. Reserved at the top of
30    /// the range so no extension list ever reaches it.
31    pub const DEVTOOLS: OriginId = OriginId(u16::MAX);
32    /// The core's own context menu and the menu bar it draws: the same
33    /// isolation the
34    /// devtools have — a node opened under one of these is the surface's,
35    /// its events are taken back inside `handle_input` and never handed
36    /// out, and no key list has to remember which nodes those were.
37    pub const MENU: OriginId = OriginId(u16::MAX - 1);
38    pub const MENU_BAR: OriginId = OriginId(u16::MAX - 2);
39
40    /// Whether nodes of this origin are one of the core's own surfaces.
41    pub fn is_core_surface(self) -> bool {
42        matches!(self, Self::DEVTOOLS | Self::MENU | Self::MENU_BAR)
43    }
44}
45
46/// Index into the frame's text list (owned by `TextSystem`).
47#[derive(Clone, Copy, Debug, PartialEq, Eq)]
48pub struct TextId(pub u32);
49
50#[derive(Clone, Copy, Debug, PartialEq)]
51pub enum NodeContent {
52    Container,
53    Text(TextId),
54    /// Editable text; retained state lives in the core's `EditStore`.
55    Edit(Key),
56    /// A host-registered image (see `Resources`), drawn from the atlas or
57    /// from a texture of its own as the entry's backing says, met by its
58    /// box as `opts` say.
59    Image(crate::resources::ImageId, crate::resources::ImageOpts),
60    /// A stroke through a run of points: one segment quad per straight
61    /// piece (see `crate::line`). The node is a float sized to the
62    /// stroke's bounding box, so it takes no room, and its `bg` is the
63    /// stroke colour. In its parent's box space it paints in the parent's
64    /// layer at its place in the tree ([`NodeContent::drawn_in_parent`]).
65    Line(crate::line::LineId),
66    /// A cell grid (see `crate::cells`): a terminal's screen as one node.
67    Cells(crate::cells::CellsId),
68    /// A box a registered WGSL function paints (see `crate::fragment`).
69    /// The handle and the sixteen parameters live in the frame's
70    /// `FragmentList`; the node carries only where.
71    Fragment(crate::fragment::FragmentDrawId),
72    /// A filled polygon: a float sized to its own
73    /// bounding box like a line, painted by the stock polygon fragment
74    /// whose draw sits in the frame's `FragmentList` like any fragment's,
75    /// its `bg` the fill. No hit region, no access row.
76    Polygon(crate::fragment::FragmentDrawId),
77    /// A filled and/or stroked outline of any shape (see `crate::path`):
78    /// a float sized to its own bounding box like a line, its ops in the
79    /// frame's `PathStore`, drawn as glyph-mask quads from the atlas. Its
80    /// `bg` is the fill, its border width and colour the stroke.
81    Path(crate::path::PathId),
82}
83
84impl NodeContent {
85    /// Whether this is a shape the core floats for its own reasons — a
86    /// `line`, `polygon` or `path`, a float only so it takes no room in a
87    /// row or column (ADR 0010 decision 5). Such a node is its parent's
88    /// content as a child is: the parent's clip holds it (F78), and it
89    /// paints in the parent's layer at its place in the tree rather than
90    /// opening a layer of its own (F123) — a glyph drawn into a title bar
91    /// is not over a toast that opened before the bar did.
92    pub fn drawn_in_parent(self) -> bool {
93        matches!(self, Self::Line(_) | Self::Polygon(_) | Self::Path(_))
94    }
95}
96
97impl Tree {
98    /// Whether node `i` opens a float layer of its own (ADR 0023): a float
99    /// a view declared, or a stroke anchored to the viewport. A `line`,
100    /// `polygon` or `path` in its parent's box space does not — the core
101    /// made its float so it takes no room, and it paints where a child
102    /// would ([`NodeContent::drawn_in_parent`]). Reads the float's
103    /// anchor through [`FloatConfig::clipped_by_parent`], which the core
104    /// sets for every such shape, so the one rule serves the clip and the
105    /// layer.
106    ///
107    /// [`FloatConfig::clipped_by_parent`]: crate::spec::FloatConfig::clipped_by_parent
108    pub fn opens_layer(&self, i: usize) -> bool {
109        self.specs[i]
110            .layout
111            .float
112            .is_some_and(|f| !(f.clipped_by_parent() && self.content[i].drawn_in_parent()))
113    }
114
115    /// Whether node `i` is drawn in its parent's layer, as a child is,
116    /// although it floats: [`Tree::opens_layer`]'s complement for a node
117    /// that declares `float` at all.
118    pub fn floats_in_parent(&self, i: usize) -> bool {
119        self.specs[i].layout.float.is_some() && !self.opens_layer(i)
120    }
121
122    /// One past the last node of `i`'s subtree. Preorder storage makes a
123    /// subtree a contiguous index range ending at the next node that is a
124    /// sibling of `i` or of one of its ancestors.
125    pub fn subtree_end(&self, i: usize) -> usize {
126        let mut n = i as u32;
127        loop {
128            if self.next_sibling[n as usize] != NIL {
129                return self.next_sibling[n as usize] as usize;
130            }
131            n = self.parent[n as usize];
132            if n == NIL {
133                return self.len();
134            }
135        }
136    }
137}
138
139/// One frame's nodes as parallel arrays in preorder; see the
140/// [module docs](self).
141#[derive(Default)]
142pub struct Tree {
143    pub keys: Vec<Key>,
144    pub origins: Vec<OriginId>,
145    pub specs: Vec<NodeSpec>,
146    pub content: Vec<NodeContent>,
147
148    pub parent: Vec<u32>,
149    pub first_child: Vec<u32>,
150    pub last_child: Vec<u32>,
151    pub next_sibling: Vec<u32>,
152
153    // Filled by the layout pass.
154    pub size: Vec<Size>,
155    pub pos: Vec<Vec2>,
156    /// Max scroll offset per axis (zero for non-scroll nodes).
157    pub scroll_max: Vec<Vec2>,
158    /// Which wrap line of its parent a node sits on, from the main-axis
159    /// pass. Zero everywhere but under a wrapping container, and the
160    /// in-flow children of one line are always a contiguous sibling run,
161    /// so a line is a range rather than a list.
162    pub line: Vec<u32>,
163    /// Each node's first baseline below its top, logical px, where text
164    /// measured one (`NaN` elsewhere). Filled by the fit-height pass, and
165    /// only on a frame with a baseline row (`any_baseline`); empty
166    /// otherwise.
167    pub baseline: Vec<f32>,
168
169    // Set by `push`, cleared by `clear`: what this frame declared at all,
170    // so a pass whose work exists for one feature can skip it wholesale
171    // when no node asked for that feature. A float check in a layout pass
172    // is a scattered read through the spec of every child of every node;
173    // behind a flag that is false on nearly every frame it is one
174    // predicted branch.
175    /// Whether any node declares `float`.
176    pub any_float: bool,
177    /// Whether any node declares a size expression as a clamp (a
178    /// negative `max_w`, a `Min::calc`): layout resolves
179    /// them only then.
180    pub any_calc_bound: bool,
181    /// Whether any float is anchored to a node by key
182    /// (`FloatAnchor::Node`): the sixth layout pass runs only then.
183    pub any_node_float: bool,
184    /// Whether any node declares `wrap_children`.
185    pub any_wrap: bool,
186    /// Whether any node lines its children up by their baselines
187    /// (`cross_align: Baseline`): the layout measures baselines only then.
188    pub any_baseline: bool,
189    /// Whether any node is a table (`LayoutSpec::table`): the column
190    /// alignment in the layout passes runs only on a frame that has one.
191    pub any_table: bool,
192    /// Whether any node declares a `gradient`: emission looks for one
193    /// only on a frame that has one.
194    pub any_gradient: bool,
195    /// Whether any node declares a `backdrop_blur` (backlog F129):
196    /// emission looks for one only on a frame that has one.
197    pub any_backdrop_blur: bool,
198    /// Whether any node turns or scales (ADR 0043): the per-node clip
199    /// space is tracked only on a frame that has one.
200    pub any_transform: bool,
201    /// Whether any node's keyframe stops name a position (backlog F132):
202    /// the pass that moves them runs only on a frame that has one.
203    pub any_offset_stop: bool,
204    /// Whether any node is text (a `Text` or `Edit` content).
205    pub any_text: bool,
206    /// Whether any node is a `role="line"` row — what a pointer payload
207    /// inside a key sink is resolved against, so a frame
208    /// without a custom editor never walks a sink's subtree for one.
209    pub any_line: bool,
210
211    /// Scratch for the layout pass's freeze loop (`distribute_run`): one
212    /// byte per in-flow child of the run being resolved, in child order.
213    /// Sized per run and never cleared, so the allocation is made once
214    /// and reused by every run of every frame.
215    pub grow_scratch: Vec<u8>,
216    /// Scratch for the shrink CSS's way (`layout::shrink_as_css`): one
217    /// entry per child of the run giving, made once and reused
218    /// by every overflowing run of every frame, as `grow_scratch` is.
219    pub(crate) shrink_scratch: Vec<crate::layout::Give>,
220    /// Whether any node clips (`clip`, or an overflow that scrolls).
221    pub any_clip: bool,
222    /// Whether any node clips *and* has a radius, so the clip its
223    /// descendants inherit is rounded. Separate from `any_clip`: the
224    /// per-corner bookkeeping is skipped for the ordinary square clip.
225    pub any_rounded_clip: bool,
226    /// Whether any node fades (`opacity` below one).
227    pub any_opacity: bool,
228    /// Whether any node declares `modal`.
229    pub any_modal: bool,
230    /// Whether any node declares `focus_region`.
231    pub any_region: bool,
232    /// Whether any node eases its position (`slide`, or an `enter` with
233    /// an offset) under a transition.
234    pub any_slide: bool,
235    /// Whether any node declares `on_layout`, so the rect report can skip
236    /// the walk.
237    pub any_layout: bool,
238    /// Whether any node declares `on_context_menu`, so a hit region's
239    /// walk for the menu it inherits is skipped wholesale on
240    /// a frame that offers none.
241    pub any_context_menu: bool,
242    /// Some node declared `on_scroll`; emission reads the row per node
243    /// only then.
244    pub any_scroll_handler: bool,
245    /// Some node declared `on_drop`: a hit region's walk for
246    /// the zone it inherits is skipped wholesale on a frame with none.
247    pub any_drop: bool,
248    /// Whether any node declares a workable `exit` (one under a
249    /// transition). Gates the tree swap and the key diff.
250    pub any_exit: bool,
251    /// Whether any node asked for the next frame (`animate`): one node
252    /// asking is the whole window asking.
253    pub any_animate: bool,
254    /// The data index of every node opened with one (`open_indexed`), by
255    /// node. A side list rather than a column, because it is a virtual
256    /// list's rows and nothing else: a frame that builds none is one empty
257    /// `Vec`.
258    ///
259    /// What it is for: a selection endpoint in a row that is *not built*
260    /// can still be ordered against the rows that are, because a row's
261    /// index says where it sits in the data even when nothing on screen
262    /// says where it sits in the frame.
263    pub indexed: Vec<(u32, u64)>,
264    /// How many indexed rows a node's virtual list has, built or not
265    /// (`rowCount`), by node. A side list for the reason `indexed` is one.
266    /// What it is for: Select All inside a `selectable` virtual list is
267    /// the *data*, rows `0..count`, not the rows the frame happened to
268    /// build — and the count is the one thing about the data the core
269    /// cannot see.
270    pub row_counts: Vec<(u32, u64)>,
271    /// The node range every slot fill opened, by the slot's key: `(slot,
272    /// first, end)` over node indices, innermost fill first (a fill
273    /// records itself after the fills inside it). A side list for the
274    /// reason `indexed` is one — a frame with no extension is one empty
275    /// `Vec` — and what stamps `UiEvent::slot`, so a host that fills many
276    /// slots from one extension can route an event by the slot it came
277    /// from without stamping every payload.
278    pub fills: Vec<(Key, u32, u32)>,
279    /// Whether any node declares `selectable`. False on every
280    /// frame of an app that never asks for one, which is what keeps the
281    /// scope walk and the off-screen places of tier 2 off those frames
282    /// entirely.
283    pub any_selectable: bool,
284    /// The box a `FloatConfig::viewport()` float of the host's resolves
285    /// against, in window coordinates: the whole window, or what the
286    /// devtools' dock leaves of it. A zero rect means
287    /// the window. The devtools' own nodes always use the window.
288    pub host_area: crate::geom::Rect,
289}
290
291impl Tree {
292    pub fn new() -> Self {
293        Self::default()
294    }
295
296    pub fn len(&self) -> usize {
297        self.keys.len()
298    }
299
300    pub fn is_empty(&self) -> bool {
301        self.keys.is_empty()
302    }
303
304    /// The index of the node `key` names in this frame, if it is here. A
305    /// linear scan: the one place to swap it for a map if a profile asks.
306    #[inline]
307    pub fn index_of(&self, key: Key) -> Option<usize> {
308        self.keys.iter().position(|k| *k == key)
309    }
310
311    /// The parent an ancestor walk that means "where is this shown"
312    /// takes: the node's parent, except for a float anchored to a node by
313    /// key, whose walk continues from the anchor (`FloatAnchor::Node`).
314    /// `NIL` past the root, and for an anchor the frame does not have.
315    #[inline]
316    pub fn region_parent(&self, i: usize) -> u32 {
317        if self.any_node_float
318            && let Some(crate::spec::FloatConfig {
319                anchor: crate::spec::FloatAnchor::Node(key),
320                ..
321            }) = self.specs[i].layout.float
322        {
323            return self.index_of(key).map_or(NIL, |a| a as u32);
324        }
325        self.parent[i]
326    }
327
328    /// Clears contents but keeps allocations for the next frame.
329    pub fn clear(&mut self) {
330        self.keys.clear();
331        self.origins.clear();
332        self.specs.clear();
333        self.content.clear();
334        self.parent.clear();
335        self.first_child.clear();
336        self.last_child.clear();
337        self.next_sibling.clear();
338        self.size.clear();
339        self.pos.clear();
340        self.scroll_max.clear();
341        self.line.clear();
342        self.baseline.clear();
343        self.any_float = false;
344        self.any_calc_bound = false;
345        self.any_baseline = false;
346        self.any_node_float = false;
347        self.any_wrap = false;
348        self.any_table = false;
349        self.any_gradient = false;
350        self.any_backdrop_blur = false;
351        self.any_transform = false;
352        self.any_offset_stop = false;
353        self.any_text = false;
354        self.any_line = false;
355        self.any_selectable = false;
356        self.any_clip = false;
357        self.any_rounded_clip = false;
358        self.any_opacity = false;
359        self.any_modal = false;
360        self.any_region = false;
361        self.any_slide = false;
362        self.any_layout = false;
363        self.any_context_menu = false;
364        self.any_scroll_handler = false;
365        self.any_drop = false;
366        self.any_exit = false;
367        self.any_animate = false;
368        self.indexed.clear();
369        self.row_counts.clear();
370        self.fills.clear();
371    }
372
373    /// The innermost slot fill node `i` was opened inside, if any.
374    pub fn slot_of(&self, i: usize) -> Option<Key> {
375        let i = i as u32;
376        self.fills
377            .iter()
378            .find(|(_, first, end)| (*first..*end).contains(&i))
379            .map(|(slot, _, _)| *slot)
380    }
381
382    /// Notes what a spec asks of the frame, so a pass whose work exists
383    /// for one feature can skip it when no node declared that feature.
384    /// Called by `push` for every node, and by the root paths that
385    /// replace a spec in place — the one door, so a leaf cannot forget a
386    /// flag a box would have set (an `image` once set two of these and
387    /// painted opaque when it was the frame's only fade).
388    ///
389    /// Each boxed group is tested once, not once per flag it can set: a
390    /// node declaring no events and no animation is done after two null
391    /// checks (C15).
392    #[inline]
393    pub fn note(&mut self, spec: &NodeSpec, content: &NodeContent) {
394        if let Some(f) = spec.layout.float {
395            self.any_float = true;
396            self.any_node_float |= matches!(f.anchor, crate::spec::FloatAnchor::Node(_));
397        }
398        self.any_wrap |= spec.layout.wrap;
399        let l = &spec.layout;
400        self.any_calc_bound |= l.max_w < 0.0
401            || l.max_h < 0.0
402            || l.min_w.as_calc().is_some()
403            || l.min_h.as_calc().is_some();
404        self.any_table |= spec.layout.is_table();
405        self.any_gradient |= spec.interact().gradient.is_some();
406        self.any_baseline |= spec.layout.cross_align == crate::spec::Align::Baseline;
407        self.any_text |= matches!(
408            content,
409            NodeContent::Text(_) | NodeContent::Edit(_) | NodeContent::Cells(_)
410        );
411        // Through the box rather than through `interact()`: a node that
412        // declares no interaction group is answered by one null check
413        // instead of a read through the empty static (C15).
414        if let Some(i) = spec.interact.as_deref() {
415            self.any_selectable |= i.selectable;
416            self.any_region |= i.focus_region;
417            self.any_backdrop_blur |= i.backdrop_blur > 0.0;
418            self.any_transform |= i.transform.as_deref().is_some_and(|t| t.active());
419        }
420        if let Some(a) = spec.access.as_deref() {
421            self.any_line |= a.role == Some(crate::access::Role::Line);
422        }
423        if spec.layout.clips() {
424            self.any_clip = true;
425            self.any_rounded_clip |= spec.style.radius != crate::display::SQUARE;
426        }
427        self.any_opacity |= spec.style.opacity < 1.0;
428        self.any_animate |= spec.animate;
429        if let Some(events) = spec.events.as_deref() {
430            self.any_modal |= events.modal.is_some();
431            self.any_layout |= events.on_layout.is_some();
432            self.any_context_menu |= events.on_context_menu.is_some();
433            self.any_scroll_handler |= events.on_scroll.is_some();
434            self.any_drop |= events.on_drop.is_some();
435        }
436        if spec.transition.is_some() {
437            match spec.anim.as_deref() {
438                Some(anim) => {
439                    self.any_slide |= spec.slide || anim.enter.is_some_and(|e| e.offsets());
440                    self.any_offset_stop |=
441                        !anim.keyframes.is_empty() && anim.keyframes.iter().any(|k| k.offsets());
442                    self.any_exit |= anim.exit.is_some();
443                }
444                None => self.any_slide |= spec.slide,
445            }
446        }
447    }
448
449    #[inline]
450    pub fn push(
451        &mut self,
452        parent: u32,
453        key: Key,
454        origin: OriginId,
455        spec: NodeSpec,
456        content: NodeContent,
457    ) -> u32 {
458        let idx = self.keys.len() as u32;
459        // Read before the move, while the spec is in cache anyway.
460        self.note(&spec, &content);
461        self.keys.push(key);
462        self.origins.push(origin);
463        self.specs.push(spec);
464        self.content.push(content);
465        self.parent.push(parent);
466        self.first_child.push(NIL);
467        self.last_child.push(NIL);
468        self.next_sibling.push(NIL);
469        self.size.push(Size::ZERO);
470        self.pos.push(Vec2::ZERO);
471        self.scroll_max.push(Vec2::ZERO);
472        self.line.push(0);
473
474        if parent != NIL {
475            let p = parent as usize;
476            if self.first_child[p] == NIL {
477                self.first_child[p] = idx;
478            } else {
479                let last = self.last_child[p] as usize;
480                self.next_sibling[last] = idx;
481            }
482            self.last_child[p] = idx;
483        }
484        idx
485    }
486
487    pub fn children(&self, i: u32) -> ChildIter<'_> {
488        ChildIter {
489            tree: self,
490            next: self.first_child[i as usize],
491        }
492    }
493}
494
495pub struct ChildIter<'a> {
496    tree: &'a Tree,
497    next: u32,
498}
499
500impl Iterator for ChildIter<'_> {
501    type Item = u32;
502
503    fn next(&mut self) -> Option<u32> {
504        if self.next == NIL {
505            return None;
506        }
507        let cur = self.next;
508        self.next = self.tree.next_sibling[cur as usize];
509        Some(cur)
510    }
511}
512
513#[cfg(test)]
514mod tests {
515    use super::*;
516
517    #[test]
518    fn sibling_links() {
519        let mut t = Tree::new();
520        let root = t.push(
521            NIL,
522            Key::ROOT,
523            OriginId::HOST,
524            NodeSpec::default(),
525            NodeContent::Container,
526        );
527        let a = t.push(
528            root,
529            Key::ROOT.index(0),
530            OriginId::HOST,
531            NodeSpec::default(),
532            NodeContent::Container,
533        );
534        let a1 = t.push(
535            a,
536            Key::ROOT.index(0).index(0),
537            OriginId::HOST,
538            NodeSpec::default(),
539            NodeContent::Container,
540        );
541        let b = t.push(
542            root,
543            Key::ROOT.index(1),
544            OriginId::HOST,
545            NodeSpec::default(),
546            NodeContent::Container,
547        );
548
549        assert_eq!(t.children(root).collect::<Vec<_>>(), vec![a, b]);
550        assert_eq!(t.children(a).collect::<Vec<_>>(), vec![a1]);
551        assert_eq!(t.children(b).collect::<Vec<_>>(), Vec::<u32>::new());
552        // Preorder invariant: parents precede children.
553        assert!(root < a && a < a1 && a1 < b);
554    }
555}