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 is text (a `Text` or `Edit` content).
199 pub any_text: bool,
200 /// Whether any node is a `role="line"` row — what a pointer payload
201 /// inside a key sink is resolved against, so a frame
202 /// without a custom editor never walks a sink's subtree for one.
203 pub any_line: bool,
204
205 /// Scratch for the layout pass's freeze loop (`distribute_run`): one
206 /// byte per in-flow child of the run being resolved, in child order.
207 /// Sized per run and never cleared, so the allocation is made once
208 /// and reused by every run of every frame.
209 pub grow_scratch: Vec<u8>,
210 /// Scratch for the shrink CSS's way (`layout::shrink_as_css`): one
211 /// entry per child of the run giving, made once and reused
212 /// by every overflowing run of every frame, as `grow_scratch` is.
213 pub(crate) shrink_scratch: Vec<crate::layout::Give>,
214 /// Whether any node clips (`clip`, or an overflow that scrolls).
215 pub any_clip: bool,
216 /// Whether any node clips *and* has a radius, so the clip its
217 /// descendants inherit is rounded. Separate from `any_clip`: the
218 /// per-corner bookkeeping is skipped for the ordinary square clip.
219 pub any_rounded_clip: bool,
220 /// Whether any node fades (`opacity` below one).
221 pub any_opacity: bool,
222 /// Whether any node declares `modal`.
223 pub any_modal: bool,
224 /// Whether any node declares `focus_region`.
225 pub any_region: bool,
226 /// Whether any node eases its position (`slide`, or an `enter` with
227 /// an offset) under a transition.
228 pub any_slide: bool,
229 /// Whether any node declares `on_layout`, so the rect report can skip
230 /// the walk.
231 pub any_layout: bool,
232 /// Whether any node declares `on_context_menu`, so a hit region's
233 /// walk for the menu it inherits is skipped wholesale on
234 /// a frame that offers none.
235 pub any_context_menu: bool,
236 /// Some node declared `on_scroll`; emission reads the row per node
237 /// only then.
238 pub any_scroll_handler: bool,
239 /// Some node declared `on_drop`: a hit region's walk for
240 /// the zone it inherits is skipped wholesale on a frame with none.
241 pub any_drop: bool,
242 /// Whether any node declares a workable `exit` (one under a
243 /// transition). Gates the tree swap and the key diff.
244 pub any_exit: bool,
245 /// Whether any node asked for the next frame (`animate`): one node
246 /// asking is the whole window asking.
247 pub any_animate: bool,
248 /// The data index of every node opened with one (`open_indexed`), by
249 /// node. A side list rather than a column, because it is a virtual
250 /// list's rows and nothing else: a frame that builds none is one empty
251 /// `Vec`.
252 ///
253 /// What it is for: a selection endpoint in a row that is *not built*
254 /// can still be ordered against the rows that are, because a row's
255 /// index says where it sits in the data even when nothing on screen
256 /// says where it sits in the frame.
257 pub indexed: Vec<(u32, u64)>,
258 /// How many indexed rows a node's virtual list has, built or not
259 /// (`rowCount`), by node. A side list for the reason `indexed` is one.
260 /// What it is for: Select All inside a `selectable` virtual list is
261 /// the *data*, rows `0..count`, not the rows the frame happened to
262 /// build — and the count is the one thing about the data the core
263 /// cannot see.
264 pub row_counts: Vec<(u32, u64)>,
265 /// The node range every slot fill opened, by the slot's key: `(slot,
266 /// first, end)` over node indices, innermost fill first (a fill
267 /// records itself after the fills inside it). A side list for the
268 /// reason `indexed` is one — a frame with no extension is one empty
269 /// `Vec` — and what stamps `UiEvent::slot`, so a host that fills many
270 /// slots from one extension can route an event by the slot it came
271 /// from without stamping every payload.
272 pub fills: Vec<(Key, u32, u32)>,
273 /// Whether any node declares `selectable`. False on every
274 /// frame of an app that never asks for one, which is what keeps the
275 /// scope walk and the off-screen places of tier 2 off those frames
276 /// entirely.
277 pub any_selectable: bool,
278 /// The box a `FloatConfig::viewport()` float of the host's resolves
279 /// against, in window coordinates: the whole window, or what the
280 /// devtools' dock leaves of it. A zero rect means
281 /// the window. The devtools' own nodes always use the window.
282 pub host_area: crate::geom::Rect,
283}
284
285impl Tree {
286 pub fn new() -> Self {
287 Self::default()
288 }
289
290 pub fn len(&self) -> usize {
291 self.keys.len()
292 }
293
294 pub fn is_empty(&self) -> bool {
295 self.keys.is_empty()
296 }
297
298 /// The index of the node `key` names in this frame, if it is here. A
299 /// linear scan: the one place to swap it for a map if a profile asks.
300 #[inline]
301 pub fn index_of(&self, key: Key) -> Option<usize> {
302 self.keys.iter().position(|k| *k == key)
303 }
304
305 /// The parent an ancestor walk that means "where is this shown"
306 /// takes: the node's parent, except for a float anchored to a node by
307 /// key, whose walk continues from the anchor (`FloatAnchor::Node`).
308 /// `NIL` past the root, and for an anchor the frame does not have.
309 #[inline]
310 pub fn region_parent(&self, i: usize) -> u32 {
311 if self.any_node_float
312 && let Some(crate::spec::FloatConfig {
313 anchor: crate::spec::FloatAnchor::Node(key),
314 ..
315 }) = self.specs[i].layout.float
316 {
317 return self.index_of(key).map_or(NIL, |a| a as u32);
318 }
319 self.parent[i]
320 }
321
322 /// Clears contents but keeps allocations for the next frame.
323 pub fn clear(&mut self) {
324 self.keys.clear();
325 self.origins.clear();
326 self.specs.clear();
327 self.content.clear();
328 self.parent.clear();
329 self.first_child.clear();
330 self.last_child.clear();
331 self.next_sibling.clear();
332 self.size.clear();
333 self.pos.clear();
334 self.scroll_max.clear();
335 self.line.clear();
336 self.baseline.clear();
337 self.any_float = false;
338 self.any_calc_bound = false;
339 self.any_baseline = false;
340 self.any_node_float = false;
341 self.any_wrap = false;
342 self.any_table = false;
343 self.any_gradient = false;
344 self.any_backdrop_blur = false;
345 self.any_text = false;
346 self.any_line = false;
347 self.any_selectable = false;
348 self.any_clip = false;
349 self.any_rounded_clip = false;
350 self.any_opacity = false;
351 self.any_modal = false;
352 self.any_region = false;
353 self.any_slide = false;
354 self.any_layout = false;
355 self.any_context_menu = false;
356 self.any_scroll_handler = false;
357 self.any_drop = false;
358 self.any_exit = false;
359 self.any_animate = false;
360 self.indexed.clear();
361 self.row_counts.clear();
362 self.fills.clear();
363 }
364
365 /// The innermost slot fill node `i` was opened inside, if any.
366 pub fn slot_of(&self, i: usize) -> Option<Key> {
367 let i = i as u32;
368 self.fills
369 .iter()
370 .find(|(_, first, end)| (*first..*end).contains(&i))
371 .map(|(slot, _, _)| *slot)
372 }
373
374 /// Notes what a spec asks of the frame, so a pass whose work exists
375 /// for one feature can skip it when no node declared that feature.
376 /// Called by `push` for every node, and by the root paths that
377 /// replace a spec in place — the one door, so a leaf cannot forget a
378 /// flag a box would have set (an `image` once set two of these and
379 /// painted opaque when it was the frame's only fade).
380 ///
381 /// Each boxed group is tested once, not once per flag it can set: a
382 /// node declaring no events and no animation is done after two null
383 /// checks (C15).
384 #[inline]
385 pub fn note(&mut self, spec: &NodeSpec, content: &NodeContent) {
386 if let Some(f) = spec.layout.float {
387 self.any_float = true;
388 self.any_node_float |= matches!(f.anchor, crate::spec::FloatAnchor::Node(_));
389 }
390 self.any_wrap |= spec.layout.wrap;
391 let l = &spec.layout;
392 self.any_calc_bound |= l.max_w < 0.0
393 || l.max_h < 0.0
394 || l.min_w.as_calc().is_some()
395 || l.min_h.as_calc().is_some();
396 self.any_table |= spec.layout.is_table();
397 self.any_gradient |= spec.interact().gradient.is_some();
398 self.any_baseline |= spec.layout.cross_align == crate::spec::Align::Baseline;
399 self.any_text |= matches!(
400 content,
401 NodeContent::Text(_) | NodeContent::Edit(_) | NodeContent::Cells(_)
402 );
403 // Through the box rather than through `interact()`: a node that
404 // declares no interaction group is answered by one null check
405 // instead of a read through the empty static (C15).
406 if let Some(i) = spec.interact.as_deref() {
407 self.any_selectable |= i.selectable;
408 self.any_region |= i.focus_region;
409 self.any_backdrop_blur |= i.backdrop_blur > 0.0;
410 }
411 if let Some(a) = spec.access.as_deref() {
412 self.any_line |= a.role == Some(crate::access::Role::Line);
413 }
414 if spec.layout.clips() {
415 self.any_clip = true;
416 self.any_rounded_clip |= spec.style.radius != crate::display::SQUARE;
417 }
418 self.any_opacity |= spec.style.opacity < 1.0;
419 self.any_animate |= spec.animate;
420 if let Some(events) = spec.events.as_deref() {
421 self.any_modal |= events.modal.is_some();
422 self.any_layout |= events.on_layout.is_some();
423 self.any_context_menu |= events.on_context_menu.is_some();
424 self.any_scroll_handler |= events.on_scroll.is_some();
425 self.any_drop |= events.on_drop.is_some();
426 }
427 if spec.transition.is_some() {
428 match spec.anim.as_deref() {
429 Some(anim) => {
430 self.any_slide |= spec.slide || anim.enter.is_some_and(|e| e.offsets());
431 self.any_exit |= anim.exit.is_some();
432 }
433 None => self.any_slide |= spec.slide,
434 }
435 }
436 }
437
438 #[inline]
439 pub fn push(
440 &mut self,
441 parent: u32,
442 key: Key,
443 origin: OriginId,
444 spec: NodeSpec,
445 content: NodeContent,
446 ) -> u32 {
447 let idx = self.keys.len() as u32;
448 // Read before the move, while the spec is in cache anyway.
449 self.note(&spec, &content);
450 self.keys.push(key);
451 self.origins.push(origin);
452 self.specs.push(spec);
453 self.content.push(content);
454 self.parent.push(parent);
455 self.first_child.push(NIL);
456 self.last_child.push(NIL);
457 self.next_sibling.push(NIL);
458 self.size.push(Size::ZERO);
459 self.pos.push(Vec2::ZERO);
460 self.scroll_max.push(Vec2::ZERO);
461 self.line.push(0);
462
463 if parent != NIL {
464 let p = parent as usize;
465 if self.first_child[p] == NIL {
466 self.first_child[p] = idx;
467 } else {
468 let last = self.last_child[p] as usize;
469 self.next_sibling[last] = idx;
470 }
471 self.last_child[p] = idx;
472 }
473 idx
474 }
475
476 pub fn children(&self, i: u32) -> ChildIter<'_> {
477 ChildIter {
478 tree: self,
479 next: self.first_child[i as usize],
480 }
481 }
482}
483
484pub struct ChildIter<'a> {
485 tree: &'a Tree,
486 next: u32,
487}
488
489impl Iterator for ChildIter<'_> {
490 type Item = u32;
491
492 fn next(&mut self) -> Option<u32> {
493 if self.next == NIL {
494 return None;
495 }
496 let cur = self.next;
497 self.next = self.tree.next_sibling[cur as usize];
498 Some(cur)
499 }
500}
501
502#[cfg(test)]
503mod tests {
504 use super::*;
505
506 #[test]
507 fn sibling_links() {
508 let mut t = Tree::new();
509 let root = t.push(
510 NIL,
511 Key::ROOT,
512 OriginId::HOST,
513 NodeSpec::default(),
514 NodeContent::Container,
515 );
516 let a = t.push(
517 root,
518 Key::ROOT.index(0),
519 OriginId::HOST,
520 NodeSpec::default(),
521 NodeContent::Container,
522 );
523 let a1 = t.push(
524 a,
525 Key::ROOT.index(0).index(0),
526 OriginId::HOST,
527 NodeSpec::default(),
528 NodeContent::Container,
529 );
530 let b = t.push(
531 root,
532 Key::ROOT.index(1),
533 OriginId::HOST,
534 NodeSpec::default(),
535 NodeContent::Container,
536 );
537
538 assert_eq!(t.children(root).collect::<Vec<_>>(), vec![a, b]);
539 assert_eq!(t.children(a).collect::<Vec<_>>(), vec![a1]);
540 assert_eq!(t.children(b).collect::<Vec<_>>(), Vec::<u32>::new());
541 // Preorder invariant: parents precede children.
542 assert!(root < a && a < a1 && a1 < b);
543 }
544}