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, and its `bg` is the stroke colour.
63 Line(crate::line::LineId),
64 /// A cell grid (see `crate::cells`): a terminal's screen as one node.
65 Cells(crate::cells::CellsId),
66 /// A box a registered WGSL function paints (see `crate::fragment`).
67 /// The handle and the sixteen parameters live in the frame's
68 /// `FragmentList`; the node carries only where.
69 Fragment(crate::fragment::FragmentDrawId),
70 /// A filled polygon: a float sized to its own
71 /// bounding box like a line, painted by the stock polygon fragment
72 /// whose draw sits in the frame's `FragmentList` like any fragment's,
73 /// its `bg` the fill. No hit region, no access row.
74 Polygon(crate::fragment::FragmentDrawId),
75 /// A filled and/or stroked outline of any shape (see `crate::path`):
76 /// a float sized to its own bounding box like a line, its ops in the
77 /// frame's `PathStore`, drawn as glyph-mask quads from the atlas. Its
78 /// `bg` is the fill, its border width and colour the stroke.
79 Path(crate::path::PathId),
80}
81
82impl Tree {
83 /// One past the last node of `i`'s subtree. Preorder storage makes a
84 /// subtree a contiguous index range ending at the next node that is a
85 /// sibling of `i` or of one of its ancestors.
86 pub fn subtree_end(&self, i: usize) -> usize {
87 let mut n = i as u32;
88 loop {
89 if self.next_sibling[n as usize] != NIL {
90 return self.next_sibling[n as usize] as usize;
91 }
92 n = self.parent[n as usize];
93 if n == NIL {
94 return self.len();
95 }
96 }
97 }
98}
99
100/// One frame's nodes as parallel arrays in preorder; see the
101/// [module docs](self).
102#[derive(Default)]
103pub struct Tree {
104 pub keys: Vec<Key>,
105 pub origins: Vec<OriginId>,
106 pub specs: Vec<NodeSpec>,
107 pub content: Vec<NodeContent>,
108
109 pub parent: Vec<u32>,
110 pub first_child: Vec<u32>,
111 pub last_child: Vec<u32>,
112 pub next_sibling: Vec<u32>,
113
114 // Filled by the layout pass.
115 pub size: Vec<Size>,
116 pub pos: Vec<Vec2>,
117 /// Max scroll offset per axis (zero for non-scroll nodes).
118 pub scroll_max: Vec<Vec2>,
119 /// Which wrap line of its parent a node sits on, from the main-axis
120 /// pass. Zero everywhere but under a wrapping container, and the
121 /// in-flow children of one line are always a contiguous sibling run,
122 /// so a line is a range rather than a list.
123 pub line: Vec<u32>,
124 /// Each node's first baseline below its top, logical px, where text
125 /// measured one (`NaN` elsewhere). Filled by the fit-height pass, and
126 /// only on a frame with a baseline row (`any_baseline`); empty
127 /// otherwise.
128 pub baseline: Vec<f32>,
129
130 // Set by `push`, cleared by `clear`: what this frame declared at all,
131 // so a pass whose work exists for one feature can skip it wholesale
132 // when no node asked for that feature. A float check in a layout pass
133 // is a scattered read through the spec of every child of every node;
134 // behind a flag that is false on nearly every frame it is one
135 // predicted branch.
136 /// Whether any node declares `float`.
137 pub any_float: bool,
138 /// Whether any node declares a size expression as a clamp (a
139 /// negative `max_w`, a `Min::calc`): layout resolves
140 /// them only then.
141 pub any_calc_bound: bool,
142 /// Whether any float is anchored to a node by key
143 /// (`FloatAnchor::Node`): the sixth layout pass runs only then.
144 pub any_node_float: bool,
145 /// Whether any node declares `wrap_children`.
146 pub any_wrap: bool,
147 /// Whether any node lines its children up by their baselines
148 /// (`cross_align: Baseline`): the layout measures baselines only then.
149 pub any_baseline: bool,
150 /// Whether any node is a table (`LayoutSpec::table`): the column
151 /// alignment in the layout passes runs only on a frame that has one.
152 pub any_table: bool,
153 /// Whether any node is text (a `Text` or `Edit` content).
154 pub any_text: bool,
155 /// Whether any node is a `role="line"` row — what a pointer payload
156 /// inside a key sink is resolved against, so a frame
157 /// without a custom editor never walks a sink's subtree for one.
158 pub any_line: bool,
159
160 /// Scratch for the layout pass's freeze loop (`distribute_run`): one
161 /// byte per in-flow child of the run being resolved, in child order.
162 /// Sized per run and never cleared, so the allocation is made once
163 /// and reused by every run of every frame.
164 pub grow_scratch: Vec<u8>,
165 /// Scratch for the shrink CSS's way (`layout::shrink_as_css`): one
166 /// entry per child of the run giving, made once and reused
167 /// by every overflowing run of every frame, as `grow_scratch` is.
168 pub(crate) shrink_scratch: Vec<crate::layout::Give>,
169 /// Whether any node clips (`clip`, or an overflow that scrolls).
170 pub any_clip: bool,
171 /// Whether any node clips *and* has a radius, so the clip its
172 /// descendants inherit is rounded. Separate from `any_clip`: the
173 /// per-corner bookkeeping is skipped for the ordinary square clip.
174 pub any_rounded_clip: bool,
175 /// Whether any node fades (`opacity` below one).
176 pub any_opacity: bool,
177 /// Whether any node declares `modal`.
178 pub any_modal: bool,
179 /// Whether any node declares `focus_region`.
180 pub any_region: bool,
181 /// Whether any node eases its position (`slide`, or an `enter` with
182 /// an offset) under a transition.
183 pub any_slide: bool,
184 /// Whether any node declares `on_layout`, so the rect report can skip
185 /// the walk.
186 pub any_layout: bool,
187 /// Whether any node declares `on_context_menu`, so a hit region's
188 /// walk for the menu it inherits is skipped wholesale on
189 /// a frame that offers none.
190 pub any_context_menu: bool,
191 /// Some node declared `on_scroll`; emission reads the row per node
192 /// only then.
193 pub any_scroll_handler: bool,
194 /// Some node declared `on_drop`: a hit region's walk for
195 /// the zone it inherits is skipped wholesale on a frame with none.
196 pub any_drop: bool,
197 /// Whether any node declares a workable `exit` (one under a
198 /// transition). Gates the tree swap and the key diff.
199 pub any_exit: bool,
200 /// Whether any node asked for the next frame (`animate`): one node
201 /// asking is the whole window asking.
202 pub any_animate: bool,
203 /// The data index of every node opened with one (`open_indexed`), by
204 /// node. A side list rather than a column, because it is a virtual
205 /// list's rows and nothing else: a frame that builds none is one empty
206 /// `Vec`.
207 ///
208 /// What it is for: a selection endpoint in a row that is *not built*
209 /// can still be ordered against the rows that are, because a row's
210 /// index says where it sits in the data even when nothing on screen
211 /// says where it sits in the frame.
212 pub indexed: Vec<(u32, u64)>,
213 /// How many indexed rows a node's virtual list has, built or not
214 /// (`rowCount`), by node. A side list for the reason `indexed` is one.
215 /// What it is for: Select All inside a `selectable` virtual list is
216 /// the *data*, rows `0..count`, not the rows the frame happened to
217 /// build — and the count is the one thing about the data the core
218 /// cannot see.
219 pub row_counts: Vec<(u32, u64)>,
220 /// The node range every slot fill opened, by the slot's key: `(slot,
221 /// first, end)` over node indices, innermost fill first (a fill
222 /// records itself after the fills inside it). A side list for the
223 /// reason `indexed` is one — a frame with no extension is one empty
224 /// `Vec` — and what stamps `UiEvent::slot`, so a host that fills many
225 /// slots from one extension can route an event by the slot it came
226 /// from without stamping every payload.
227 pub fills: Vec<(Key, u32, u32)>,
228 /// Whether any node declares `selectable`. False on every
229 /// frame of an app that never asks for one, which is what keeps the
230 /// scope walk and the off-screen places of tier 2 off those frames
231 /// entirely.
232 pub any_selectable: bool,
233 /// The box a `FloatConfig::viewport()` float of the host's resolves
234 /// against, in window coordinates: the whole window, or what the
235 /// devtools' dock leaves of it. A zero rect means
236 /// the window. The devtools' own nodes always use the window.
237 pub host_area: crate::geom::Rect,
238}
239
240impl Tree {
241 pub fn new() -> Self {
242 Self::default()
243 }
244
245 pub fn len(&self) -> usize {
246 self.keys.len()
247 }
248
249 pub fn is_empty(&self) -> bool {
250 self.keys.is_empty()
251 }
252
253 /// The index of the node `key` names in this frame, if it is here. A
254 /// linear scan: the one place to swap it for a map if a profile asks.
255 #[inline]
256 pub fn index_of(&self, key: Key) -> Option<usize> {
257 self.keys.iter().position(|k| *k == key)
258 }
259
260 /// The parent an ancestor walk that means "where is this shown"
261 /// takes: the node's parent, except for a float anchored to a node by
262 /// key, whose walk continues from the anchor (`FloatAnchor::Node`).
263 /// `NIL` past the root, and for an anchor the frame does not have.
264 #[inline]
265 pub fn region_parent(&self, i: usize) -> u32 {
266 if self.any_node_float
267 && let Some(crate::spec::FloatConfig {
268 anchor: crate::spec::FloatAnchor::Node(key),
269 ..
270 }) = self.specs[i].layout.float
271 {
272 return self.index_of(key).map_or(NIL, |a| a as u32);
273 }
274 self.parent[i]
275 }
276
277 /// Clears contents but keeps allocations for the next frame.
278 pub fn clear(&mut self) {
279 self.keys.clear();
280 self.origins.clear();
281 self.specs.clear();
282 self.content.clear();
283 self.parent.clear();
284 self.first_child.clear();
285 self.last_child.clear();
286 self.next_sibling.clear();
287 self.size.clear();
288 self.pos.clear();
289 self.scroll_max.clear();
290 self.line.clear();
291 self.baseline.clear();
292 self.any_float = false;
293 self.any_calc_bound = false;
294 self.any_baseline = false;
295 self.any_node_float = false;
296 self.any_wrap = false;
297 self.any_table = false;
298 self.any_text = false;
299 self.any_line = false;
300 self.any_selectable = false;
301 self.any_clip = false;
302 self.any_rounded_clip = false;
303 self.any_opacity = false;
304 self.any_modal = false;
305 self.any_region = false;
306 self.any_slide = false;
307 self.any_layout = false;
308 self.any_context_menu = false;
309 self.any_scroll_handler = false;
310 self.any_drop = false;
311 self.any_exit = false;
312 self.any_animate = false;
313 self.indexed.clear();
314 self.row_counts.clear();
315 self.fills.clear();
316 }
317
318 /// The innermost slot fill node `i` was opened inside, if any.
319 pub fn slot_of(&self, i: usize) -> Option<Key> {
320 let i = i as u32;
321 self.fills
322 .iter()
323 .find(|(_, first, end)| (*first..*end).contains(&i))
324 .map(|(slot, _, _)| *slot)
325 }
326
327 /// Notes what a spec asks of the frame, so a pass whose work exists
328 /// for one feature can skip it when no node declared that feature.
329 /// Called by `push` for every node, and by the root paths that
330 /// replace a spec in place — the one door, so a leaf cannot forget a
331 /// flag a box would have set (an `image` once set two of these and
332 /// painted opaque when it was the frame's only fade).
333 ///
334 /// Each boxed group is tested once, not once per flag it can set: a
335 /// node declaring no events and no animation is done after two null
336 /// checks (C15).
337 #[inline]
338 pub fn note(&mut self, spec: &NodeSpec, content: &NodeContent) {
339 if let Some(f) = spec.layout.float {
340 self.any_float = true;
341 self.any_node_float |= matches!(f.anchor, crate::spec::FloatAnchor::Node(_));
342 }
343 self.any_wrap |= spec.layout.wrap;
344 let l = &spec.layout;
345 self.any_calc_bound |= l.max_w < 0.0
346 || l.max_h < 0.0
347 || l.min_w.as_calc().is_some()
348 || l.min_h.as_calc().is_some();
349 self.any_table |= spec.layout.is_table();
350 self.any_baseline |= spec.layout.cross_align == crate::spec::Align::Baseline;
351 self.any_text |= matches!(
352 content,
353 NodeContent::Text(_) | NodeContent::Edit(_) | NodeContent::Cells(_)
354 );
355 // Through the box rather than through `interact()`: a node that
356 // declares no interaction group is answered by one null check
357 // instead of a read through the empty static (C15).
358 if let Some(i) = spec.interact.as_deref() {
359 self.any_selectable |= i.selectable;
360 self.any_region |= i.focus_region;
361 }
362 if let Some(a) = spec.access.as_deref() {
363 self.any_line |= a.role == Some(crate::access::Role::Line);
364 }
365 if spec.layout.clips() {
366 self.any_clip = true;
367 self.any_rounded_clip |= spec.style.radius != crate::display::SQUARE;
368 }
369 self.any_opacity |= spec.style.opacity < 1.0;
370 self.any_animate |= spec.animate;
371 if let Some(events) = spec.events.as_deref() {
372 self.any_modal |= events.modal.is_some();
373 self.any_layout |= events.on_layout.is_some();
374 self.any_context_menu |= events.on_context_menu.is_some();
375 self.any_scroll_handler |= events.on_scroll.is_some();
376 self.any_drop |= events.on_drop.is_some();
377 }
378 if spec.transition.is_some() {
379 match spec.anim.as_deref() {
380 Some(anim) => {
381 self.any_slide |= spec.slide || anim.enter.is_some_and(|e| e.offsets());
382 self.any_exit |= anim.exit.is_some();
383 }
384 None => self.any_slide |= spec.slide,
385 }
386 }
387 }
388
389 #[inline]
390 pub fn push(
391 &mut self,
392 parent: u32,
393 key: Key,
394 origin: OriginId,
395 spec: NodeSpec,
396 content: NodeContent,
397 ) -> u32 {
398 let idx = self.keys.len() as u32;
399 // Read before the move, while the spec is in cache anyway.
400 self.note(&spec, &content);
401 self.keys.push(key);
402 self.origins.push(origin);
403 self.specs.push(spec);
404 self.content.push(content);
405 self.parent.push(parent);
406 self.first_child.push(NIL);
407 self.last_child.push(NIL);
408 self.next_sibling.push(NIL);
409 self.size.push(Size::ZERO);
410 self.pos.push(Vec2::ZERO);
411 self.scroll_max.push(Vec2::ZERO);
412 self.line.push(0);
413
414 if parent != NIL {
415 let p = parent as usize;
416 if self.first_child[p] == NIL {
417 self.first_child[p] = idx;
418 } else {
419 let last = self.last_child[p] as usize;
420 self.next_sibling[last] = idx;
421 }
422 self.last_child[p] = idx;
423 }
424 idx
425 }
426
427 pub fn children(&self, i: u32) -> ChildIter<'_> {
428 ChildIter {
429 tree: self,
430 next: self.first_child[i as usize],
431 }
432 }
433}
434
435pub struct ChildIter<'a> {
436 tree: &'a Tree,
437 next: u32,
438}
439
440impl Iterator for ChildIter<'_> {
441 type Item = u32;
442
443 fn next(&mut self) -> Option<u32> {
444 if self.next == NIL {
445 return None;
446 }
447 let cur = self.next;
448 self.next = self.tree.next_sibling[cur as usize];
449 Some(cur)
450 }
451}
452
453#[cfg(test)]
454mod tests {
455 use super::*;
456
457 #[test]
458 fn sibling_links() {
459 let mut t = Tree::new();
460 let root = t.push(
461 NIL,
462 Key::ROOT,
463 OriginId::HOST,
464 NodeSpec::default(),
465 NodeContent::Container,
466 );
467 let a = t.push(
468 root,
469 Key::ROOT.index(0),
470 OriginId::HOST,
471 NodeSpec::default(),
472 NodeContent::Container,
473 );
474 let a1 = t.push(
475 a,
476 Key::ROOT.index(0).index(0),
477 OriginId::HOST,
478 NodeSpec::default(),
479 NodeContent::Container,
480 );
481 let b = t.push(
482 root,
483 Key::ROOT.index(1),
484 OriginId::HOST,
485 NodeSpec::default(),
486 NodeContent::Container,
487 );
488
489 assert_eq!(t.children(root).collect::<Vec<_>>(), vec![a, b]);
490 assert_eq!(t.children(a).collect::<Vec<_>>(), vec![a1]);
491 assert_eq!(t.children(b).collect::<Vec<_>>(), Vec::<u32>::new());
492 // Preorder invariant: parents precede children.
493 assert!(root < a && a < a1 && a1 < b);
494 }
495}