Skip to main content

kui_core/runtime/
builder.rs

1//! The frame builder: what a view calls between `begin_frame` and
2//! `finish_frame` to declare the tree — open, close, text, editors,
3//! images — with each spec eased against its transitions and keyframes
4//! as it is opened, and the hover / press queries a view styles by.
5
6use super::*;
7
8use crate::schema::{Identity, PropsOut};
9use crate::slots::one;
10
11/// What a node opened through [`Core::open_from`] holds: a box (left open
12/// for its children), a fragment (likewise), a `cells` grid or a stroke
13/// (leaves, closed by the door).
14pub enum Content<'a> {
15    Box,
16    /// A fragment: the function (and its image, if any) and the params.
17    Fragment(crate::fragment::FragmentRef, &'a [f32]),
18    Cells(&'a crate::cells::CellGrid<'a>),
19    Line(&'a [Vec2], Stroke),
20    /// A filled polygon; the fill is the spec's `bg`.
21    Polygon(&'a [Vec2]),
22    /// A path: its ops, the fill rule, and a stroke if it has one. The
23    /// fill is the spec's `bg`.
24    Path(
25        &'a [crate::path::PathOp],
26        crate::path::FillRule,
27        Option<Stroke>,
28        Option<crate::path::Turn>,
29    ),
30    /// The same from a `d` string, parsed here by the one parser; one
31    /// that does not parse raises `path-malformed` under the node's key.
32    PathD(
33        &'a str,
34        crate::path::FillRule,
35        Option<Stroke>,
36        Option<crate::path::Turn>,
37    ),
38    /// The same from the flat op form (`Path::to_floats`), read here; one
39    /// that is not the form raises `path-malformed` under the node's key
40    /// as a `d` that does not parse does.
41    PathFlat(
42        &'a [f32],
43        crate::path::FillRule,
44        Option<Stroke>,
45        Option<crate::path::Turn>,
46    ),
47}
48
49/// Whether a transitioning node has a transform slot to ease: it declares
50/// a turn or a scale, or its entrance or a stop names one (ADR 0043). Two
51/// box checks for the node that does none of it.
52#[inline]
53fn turns(spec: &NodeSpec) -> bool {
54    spec.interact
55        .as_deref()
56        .is_some_and(|i| i.transform.is_some())
57        || spec.anim.as_deref().is_some_and(anim_turns)
58}
59
60/// [`turns`]'s half for the animation group, out of line: inlined, its
61/// scan of the stops made `prepare_spec` too big to inline into
62/// `open_content`, and every node paid the call (ADR 0043's amendment).
63#[inline(never)]
64fn anim_turns(a: &crate::spec::AnimSpec) -> bool {
65    a.enter
66        .is_some_and(|e| e.rotate.is_some() || e.scale.is_some())
67        || a.keyframes
68            .iter()
69            .any(|k| k.rotate.is_some() || k.scale.is_some())
70}
71
72/// The transform slot's lanes a node declares: `[rotate, scale, 0, 0]`,
73/// the identity for a node that declares none (ADR 0043).
74#[inline]
75fn transform_lanes(spec: &NodeSpec) -> [f32; 4] {
76    let t = spec.transform_spec().unwrap_or_default();
77    crate::geom::Transform::lanes(t.rotate, t.scale)
78}
79
80/// A node's keyframes flattened per slot for `ease_spec`, built once per
81/// node per frame (only for nodes that declare keyframes).
82struct Tracks {
83    width: Option<Vec<(f32, [f32; 4])>>,
84    height: Option<Vec<(f32, [f32; 4])>>,
85    bg: Option<Vec<(f32, [f32; 4])>>,
86    radius: Option<Vec<(f32, [f32; 4])>>,
87    opacity: Option<Vec<(f32, [f32; 4])>>,
88}
89
90impl Tracks {
91    fn of(spec: &NodeSpec) -> Self {
92        let frames = &spec.anim().keyframes;
93        let offsets = keyframes::offsets(frames);
94        // Each slot's stops in lanes, the node's own value at the ends the
95        // stops do not reach; a sizing with no amount (`fit`) has no track.
96        let track = |slot: Slot, base: Option<[f32; 4]>| {
97            keyframes::track(frames, &offsets, base?, |k| k.lanes(slot))
98        };
99        Tracks {
100            width: track(Slot::Width, spec.layout.width.amount().map(one)),
101            height: track(Slot::Height, spec.layout.height.amount().map(one)),
102            bg: track(Slot::Bg, Some(spec.style.bg.lanes())),
103            radius: track(Slot::Radius, Some(spec.style.radius)),
104            opacity: track(Slot::Opacity, Some(one(spec.style.opacity))),
105        }
106    }
107
108    fn get(&self, slot: Slot) -> Option<&Track> {
109        match slot {
110            Slot::Width => self.width.as_deref(),
111            Slot::Height => self.height.as_deref(),
112            Slot::Bg => self.bg.as_deref(),
113            Slot::Radius => self.radius.as_deref(),
114            Slot::Opacity => self.opacity.as_deref(),
115            // Eased apart, in `ease_transform`.
116            Slot::Transform => None,
117            // Keyframing a shadow would need stops for four more numbers
118            // and a color; a shadow tweens with `transition` and no more.
119            Slot::Border | Slot::Pos | Slot::Shadow | Slot::ShadowColor => None,
120        }
121    }
122}
123
124impl Core {
125    // -- Frame builder ------------------------------------------------------
126    // Flat, non-panicking, callable through FFI. Misuse (close past the root,
127    // building outside a frame) is ignored rather than UB or panic.
128
129    /// Tags subsequently created nodes with an origin (set by the runner
130    /// before handing the frame to an extension).
131    pub fn set_origin(&mut self, origin: OriginId) {
132        self.origin = origin;
133    }
134
135    /// Replaces the implicit root's spec (e.g. to make the top level a row).
136    /// Root sizing is resolved against the viewport regardless.
137    pub fn configure_root(&mut self, mut spec: NodeSpec) {
138        if let Some(app) = self.dt_app {
139            // The host's tree is wrapped for the devtools (ADR 0024,
140            // decision 2): the spec is split between the two nodes.
141            self.devtools_configure_root(app, spec);
142            return;
143        }
144        if !self.tree.is_empty() {
145            self.ease_spec(Key::ROOT, &mut spec);
146            self.tree.note(&spec, &NodeContent::Container);
147            self.tree.specs[0] = spec;
148        }
149    }
150
151    /// Replaces a transitioning node's animatable values with this frame's
152    /// eased ones. Nodes without a transition cost one branch — inlined at
153    /// the call site, so it is a branch and not a call that returns.
154    /// A slot the node's keyframes name is sampled from its cycle instead
155    /// of tweened.
156    #[inline]
157    pub(super) fn ease_spec(&mut self, key: Key, spec: &mut NodeSpec) {
158        if let Some(t) = spec.transition {
159            // A turn the node starts declaring eases in from upright when
160            // the node was already drawn: read before `ease_transitioning`
161            // marks its other slots used this frame.
162            let declares = turns(spec);
163            let upright = declares && self.anim.turn_starts_upright(key);
164            self.ease_transitioning(key, spec, t);
165            // The turn and the scale (ADR 0043) are eased apart, after the
166            // other slots and out of line, so `ease_transitioning` is the
167            // code it was before ADR 0043 (a test for the turn inside it
168            // measured about 2% on a frame of 10,000 transitioning boxes).
169            // A turn the node stops declaring eases back to upright on the
170            // tween it had.
171            if declares || self.anim.turn_live(key) {
172                self.ease_transform(key, spec, t, upright);
173            }
174        }
175    }
176
177    #[inline(never)]
178    fn ease_transitioning(&mut self, key: Key, spec: &mut NodeSpec, t: crate::anim::Transition) {
179        // One lookup for the whole node. Every slot below used to reach
180        // `AnimStore` by key on its own, which was seven to nine hashes and
181        // probes of the same entry per transitioning node, per frame.
182        let mut anim = self.anim.node(key);
183        let tracks = (!spec.anim().keyframes.is_empty()).then(|| Tracks::of(spec));
184        let track = |slot: Slot| tracks.as_ref().and_then(|k| k.get(slot));
185        let enter = spec.anim().enter.unwrap_or_default();
186        let iterations = spec.anim().iterations;
187        // Each slot: sampled from its track when keyframed, else tweened
188        // toward its declared value from where the entrance says it starts.
189        let mut ease = |slot: Slot, target: [f32; 4]| match track(slot) {
190            Some(track) => anim.sample(track, t, iterations).unwrap_or(target),
191            None => anim.drive(slot, enter.lanes(slot), target, t, true),
192        };
193        let mut sizing = |slot: Slot, s: Sizing| match s.amount() {
194            Some(v) => s.with_amount(ease(slot, one(v))[0]),
195            None => s,
196        };
197        spec.layout.width = sizing(Slot::Width, spec.layout.width);
198        spec.layout.height = sizing(Slot::Height, spec.layout.height);
199        let mut color = |slot: Slot, c: Color| Color::from_lanes(ease(slot, c.lanes()));
200        spec.style.bg = color(Slot::Bg, spec.style.bg);
201        spec.style.border_color = color(Slot::Border, spec.style.border_color);
202        spec.style.shadow.color = color(Slot::ShadowColor, spec.style.shadow.color);
203        let sh = spec.style.shadow;
204        let geom = ease(Slot::Shadow, [sh.dx, sh.dy, sh.blur, sh.spread]);
205        spec.style.shadow.dx = geom[0];
206        spec.style.shadow.dy = geom[1];
207        spec.style.shadow.blur = geom[2].max(0.0);
208        spec.style.shadow.spread = geom[3];
209        spec.style.opacity = ease(Slot::Opacity, one(spec.style.opacity))[0].clamp(0.0, 1.0);
210        spec.style.radius = ease(Slot::Radius, spec.style.radius);
211    }
212
213    /// The transform slot of a transitioning node that turns
214    /// ([`turns`]): sampled from its stops when they name `rotate` or
215    /// `scale`, else tweened from where its entrance says. The eased
216    /// lanes land on the spec's transform, allocated for an entrance or a
217    /// cycle that turns a node declaring none.
218    #[cold]
219    #[inline(never)]
220    fn ease_transform(
221        &mut self,
222        key: Key,
223        spec: &mut NodeSpec,
224        t: crate::anim::Transition,
225        upright: bool,
226    ) {
227        let declared = spec.interact().transform.is_some();
228        let base = transform_lanes(spec);
229        let frames = &spec.anim().keyframes;
230        // A stop's lanes are filled from the node's own transform, so a
231        // stop naming only `rotate` keeps the scale.
232        let track = if frames.is_empty() {
233            None
234        } else {
235            keyframes::track(frames, &keyframes::offsets(frames), base, |k| {
236                k.transform_lanes(base)
237            })
238        };
239        let v = match track {
240            Some(track) => self
241                .anim
242                .sample_cycle(key, &track, t, spec.anim().iterations)
243                .unwrap_or(base),
244            None => {
245                // Already drawn upright, the turn eases in from there; a
246                // node new this frame enters as its `enter` says.
247                const UPRIGHT: [f32; 4] = [0.0, 1.0, 0.0, 0.0];
248                let from = if upright {
249                    Some(UPRIGHT)
250                } else {
251                    spec.anim().enter.and_then(|e| e.transform_lanes(base))
252                };
253                let v = self.anim.drive_turn(key, from, base, t);
254                if !declared && v == UPRIGHT {
255                    self.anim.forget_settled_turn(key, UPRIGHT);
256                }
257                v
258            }
259        };
260        if declared || v != base {
261            let tr = spec.transform_mut();
262            tr.rotate = v[0];
263            tr.scale = v[1];
264        }
265    }
266
267    /// The root node's key — for hover/press queries or `set_key_focus` when
268    /// the root itself declares the interaction (e.g. a root-level key sink).
269    pub fn root_key(&self) -> Key {
270        self.tree.keys.first().copied().unwrap_or(Key(0))
271    }
272
273    fn current(&self) -> u32 {
274        self.stack.last().copied().unwrap_or(0)
275    }
276
277    /// The key a child of the current node is derived from: the node's own
278    /// key, except inside a slot fill at the depth the fill began, where it
279    /// is the fill's namespace (`Core::fill`). One
280    /// compare on the auto-key path; `ns_depth` is `usize::MAX` outside a
281    /// fill.
282    #[inline]
283    pub(crate) fn parent_key(&self) -> Key {
284        if self.stack.len() == self.ns_depth {
285            self.ns_key
286        } else {
287            // Outside a frame — or in the devtools' own window, where the
288            // root is deferred (ADR 0024, decision 6) — there is no node
289            // to derive from, and the open that follows is a no-op.
290            self.tree
291                .keys
292                .get(self.current() as usize)
293                .copied()
294                .unwrap_or(Key::ROOT)
295        }
296    }
297
298    #[inline]
299    pub(crate) fn auto_key(&mut self) -> Key {
300        let parent = self.parent_key();
301        let i = self.counters.last().copied().unwrap_or(0);
302        if let Some(c) = self.counters.last_mut() {
303            *c += 1;
304        }
305        parent.index(i)
306    }
307
308    /// The key a child labeled `label` would get — usable before creating it,
309    /// e.g. to check hover state for styling.
310    pub fn child_key(&self, label: &str) -> Key {
311        self.parent_key().str(label)
312    }
313
314    /// The key the `i`th child gets from auto-keying — what `open_indexed`
315    /// opens with, usable before the node exists.
316    pub fn child_key_indexed(&self, i: u64) -> Key {
317        self.parent_key().index(i)
318    }
319
320    pub fn is_hovered(&self, key: Key) -> bool {
321        self.interaction.is_hovered(key)
322    }
323
324    /// Whether files dragged in from the OS are over `key`.
325    pub fn is_drop_target(&self, key: Key) -> bool {
326        self.interaction.is_drop_target(key)
327    }
328
329    /// The zone the dragged files are over, if any — what a driver
330    /// answers the OS with.
331    pub fn drop_target(&self) -> Option<Key> {
332        self.interaction.drop_target()
333    }
334
335    pub fn is_pressed(&self, key: Key) -> bool {
336        self.interaction.is_pressed(key)
337    }
338
339    /// Whether any member of hover group `group` (see
340    /// `NodeSpec::hover_group`) is hovered.
341    pub fn is_group_hovered(&self, group: u64) -> bool {
342        self.interaction.is_group_hovered(group)
343    }
344
345    /// Whether hover group `group` is pressed (press started on a member,
346    /// pointer still over one).
347    pub fn is_group_pressed(&self, group: u64) -> bool {
348        self.interaction.is_group_pressed(group)
349    }
350
351    /// Events raised outside `handle_input`: the `resize` a changed
352    /// viewport produced at `begin_frame`, and `on_hover` enter/leave
353    /// caused by a finished frame changing what sits under a still cursor.
354    /// Frame drivers route these after `finish_frame`; they also ride along
355    /// with the next `handle_input` result, so a driver that never calls
356    /// this merely sees them a little later.
357    pub fn take_pending_events(&mut self) -> Vec<UiEvent> {
358        let mut out = std::mem::take(&mut self.pending);
359        out.append(&mut self.interaction.take_pending());
360        self.devtools_consume(&mut out);
361        self.devtools_translate(&mut out);
362        self.stamp(&mut out);
363        self.devtools_log(&out);
364        out
365    }
366
367    /// Swaps in the hover / pressed / focus background the spec declares
368    /// for the node's (or its group's) current state: pressed wins over
369    /// keyboard-visible focus wins over hover. A disabled node keeps its
370    /// plain `bg`. Runs before easing so a `transition` tweens between
371    /// the states.
372    #[inline]
373    fn resolve_hover_style(&self, key: Key, spec: &mut NodeSpec) {
374        // Runs for every node of every frame, and almost every node declares
375        // none of this — so the early-out is one null check on the boxed
376        // group rather than three `Option`s read out of the spec, and it is
377        // inlined so the check is a branch rather than a call (C15).
378        if spec.interact.is_some() {
379            self.resolve_declared_hover_style(key, spec);
380        }
381    }
382
383    #[inline(never)]
384    fn resolve_declared_hover_style(&self, key: Key, spec: &mut NodeSpec) {
385        let Some(interact) = spec.interact.as_deref() else {
386            return;
387        };
388        let (hover_bg, pressed_bg, focus_bg, drop_bg, group) = (
389            interact.hover_bg,
390            interact.pressed_bg,
391            interact.focus_bg,
392            interact.drop_bg,
393            interact.hover_group,
394        );
395        if spec.disabled
396            || (hover_bg.is_none()
397                && pressed_bg.is_none()
398                && focus_bg.is_none()
399                && drop_bg.is_none())
400        {
401            return;
402        }
403        // Dragged files over the zone win over every pointer state: a
404        // press cannot be held while the OS holds a drag (ADR 0031,
405        // decision 3).
406        if let Some(c) = drop_bg
407            && self.interaction.is_drop_target(key)
408        {
409            spec.style.bg = c;
410            return;
411        }
412        let pressed = self.interaction.is_pressed(key)
413            || group.is_some_and(|g| self.interaction.is_group_pressed(g));
414        let hovered = pressed
415            || self.interaction.is_hovered(key)
416            || group.is_some_and(|g| self.interaction.is_group_hovered(g));
417        let focused = self.focus_visible && self.focus == Some(key);
418        if pressed && let Some(c) = pressed_bg {
419            spec.style.bg = c;
420        } else if focused && let Some(c) = focus_bg {
421            spec.style.bg = c;
422        } else if hovered && let Some(c) = hover_bg {
423            spec.style.bg = c;
424        }
425    }
426
427    /// Physical modifier state as of the last `InputEvent::Modifiers`.
428    pub fn modifiers(&self) -> crate::input::KeyMods {
429        self.interaction.modifiers()
430    }
431
432    /// Where the pointer is, in this window's logical viewport
433    /// coordinates, as of the last `CursorMoved` — `None` once it has
434    /// left the window. What a view that follows the pointer reads (the
435    /// devtools' picker outlines the node under it); a control that wants
436    /// to *react* to the pointer declares `hoverable` or `on_hover` and
437    /// lets the core do the hit test.
438    pub fn cursor(&self) -> Option<Vec2> {
439        self.interaction.cursor().map(|p| p.minus(self.dt_shift()))
440    }
441
442    // The open chain is inlined end to end (`Ui::open` → here →
443    // `open_with_key` → `Tree::push`): a `NodeSpec` is 224 bytes and moved
444    // by value at every step, and each step that is a real call is a copy
445    // of all of them. Inlined, the spec the view built travels by pointer
446    // and is copied once, into the tree (C15).
447    #[inline]
448    pub fn open(&mut self, spec: NodeSpec) -> Key {
449        let key = self.auto_key();
450        self.open_with_key(key, spec);
451        key
452    }
453
454    #[inline]
455    pub fn open_keyed(&mut self, label: &str, spec: NodeSpec) -> Key {
456        let key = self.child_key(label);
457        if self.tree.is_empty() {
458            // No frame to open into (the same no-op as `open_with_key`),
459            // and so no node for the label to name.
460            return key;
461        }
462        self.open_with_key(key, spec);
463        self.key_labels.push(key, label, self.origin);
464        key
465    }
466
467    /// The inverse of [`Self::key_of`]: the label `key` was opened under
468    /// — in the frame being built so far, else in the last one — or
469    /// `None` for an auto-keyed node or a key no frame has declared. What
470    /// a reader holding a key from an event or from `focus()` turns back
471    /// into the name the view gave it.
472    pub fn label_of(&self, key: Key) -> Option<&str> {
473        self.key_labels
474            .label_of(key)
475            .or_else(|| self.key_labels_last.label_of(key))
476    }
477
478    /// The key of the node opened under the key label `label`
479    /// (`open_keyed`; a `key` prop in JSX or a Lua table — not the `label`
480    /// row, the accessible name, which [`Self::key_named`] reads) in the
481    /// last finished frame — or, while
482    /// a frame is being built, in it so far and then in the last one. The
483    /// door for a caller that holds only strings: keys are hashes of the
484    /// path from the root, and that path runs through auto-keyed
485    /// ancestors nothing outside the build can spell, so "focus the node
486    /// I just declared" is this and not `child_key`. None when no node
487    /// declared the label. Labels are unique among siblings, not across a
488    /// tree, so two nodes may share one under different parents. A guest
489    /// asking from inside its fill is answered from the nodes
490    /// it opened and no one else's — it cannot know what the host or
491    /// another guest called theirs, and its env is a reading of its own
492    /// view; the host, whose frame it is, from its own first and from
493    /// everyone's when it opened none. Within that, the first in tree
494    /// order wins and an `ambiguous-key` warning says so.
495    pub fn key_of(&mut self, label: &str) -> Option<Key> {
496        self.find_label(label, true)
497    }
498
499    /// The one label lookup: the first node in tree order
500    /// opened under `label` in the frame being built, and — with
501    /// `fall_back` and a build under way — in the last frame when this
502    /// one has not declared it yet; an `ambiguous-key` warning when more
503    /// than one did. `key_of` falls back; `resolve_regions` runs at the
504    /// frame's end, when this frame's labels are the whole story.
505    pub(crate) fn find_label(&mut self, label: &str, fall_back: bool) -> Option<Key> {
506        let (first, count) = {
507            let mut hits = self.key_labels.find_for(label, self.origin);
508            if hits.0.is_none() && fall_back && self.building {
509                hits = self.key_labels_last.find_for(label, self.origin);
510            }
511            (hits.0?, hits.1)
512        };
513        if count > 1 {
514            self.diag
515                .raise(crate::diag::ambiguous_key(label, first, count));
516        }
517        Some(first)
518    }
519
520    /// `open_keyed` in the sibling-index namespace: the key auto-keying
521    /// would have given the `i`th child. A list that builds only rows
522    /// 900..930 opens each with its *data* index, so row 900 keeps the key
523    /// it has when the whole list is built — hover, focus, edit buffers and
524    /// tweens follow the row instead of the slot it happens to occupy.
525    #[inline]
526    pub fn open_indexed(&mut self, i: u64, spec: NodeSpec) -> Key {
527        let key = self.child_key_indexed(i);
528        let at = self.tree.len() as u32;
529        self.open_with_key(key, spec);
530        // Remembered for the node that was actually pushed, so a selection
531        // inside a virtual row can be ordered by the row's place in the
532        // *data* when the row itself is not built (ADR 0017, tier 3).
533        if self.tree.len() as u32 > at {
534            self.tree.indexed.push((at, i));
535        }
536        key
537    }
538
539    /// Declares how many indexed rows the *open* node's virtual list has,
540    /// built or not (`rowCount`): what Select All inside a `selectable`
541    /// virtual list spans, since the built rows are all the core can see.
542    /// `widgets::uniform_list` and `widgets::list`
543    /// call it on their container; a list composed by hand calls it
544    /// inside the container's `with`. Nothing, outside any node.
545    pub fn row_count(&mut self, n: u64) {
546        if self.tree.is_empty() || self.stack.is_empty() {
547            return;
548        }
549        let at = self.current();
550        self.tree.row_counts.push((at, n));
551    }
552
553    /// Opens a node under a key the caller built; see `Ui::open_key`.
554    #[inline]
555    pub fn open_key(&mut self, key: Key, spec: NodeSpec) -> Key {
556        self.open_with_key(key, spec);
557        key
558    }
559
560    #[inline]
561    pub(crate) fn open_with_key(&mut self, key: Key, spec: NodeSpec) {
562        self.open_content(key, spec, NodeContent::Container);
563    }
564
565    /// `open_with_key` with the node named `label` for `key_of`, the way
566    /// `open_keyed` names its node — for a key the caller fixed rather
567    /// than derived (a devtools tab's body).
568    pub(crate) fn open_with_key_named(&mut self, key: Key, label: &str, spec: NodeSpec) {
569        if self.tree.is_empty() {
570            return;
571        }
572        self.open_with_key(key, spec);
573        self.key_labels.push(key, label, self.origin);
574    }
575
576    /// `open_with_key` for a node that is a box in every way but what it
577    /// paints: the caller supplies the content and closes the node. What
578    /// the node asks of the frame is noted by `Tree::push`, the same for a
579    /// box, a `fragment` and every leaf.
580    fn open_content(&mut self, key: Key, mut spec: NodeSpec, content: NodeContent) {
581        if self.tree.is_empty() {
582            return;
583        }
584        self.prepare_spec(key, &mut spec);
585        // `NodeSpec::tooltip`: the hint floats on this node's `close`, the
586        // way a parsed `tooltip` prop's does. One pointer check for a node
587        // that declares no access group.
588        let tip = match spec.access.as_deref() {
589            Some(a) if a.tooltip => a.description.clone(),
590            _ => None,
591        };
592        let parent = self.current();
593        let idx = self.tree.push(parent, key, self.origin, spec, content);
594        self.stack.push(idx);
595        self.counters.push(0);
596        if let Some(tip) = tip {
597            self.spec_hint(key, &tip);
598        }
599    }
600
601    /// The hint of a node that declared [`NodeSpec::tooltip`], recorded
602    /// only while it is hovered — `close` would drop it otherwise.
603    #[cold]
604    #[inline(never)]
605    fn spec_hint(&mut self, key: Key, tip: &str) {
606        if self.is_hovered(key) {
607            self.hint(key, tip);
608        }
609    }
610
611    /// Pushes a leaf — a node that is never left open for children: a
612    /// `cells` grid, an editor, an image, a stroke, a fill, a path — under
613    /// the current node. The one door every leaf goes through, so a leaf
614    /// whose spec asks for its tooltip drawn (`AccessSpec::tooltip`) has it
615    /// floated here once rather than by six doors. One pointer check for a
616    /// leaf that declares no access group.
617    #[inline]
618    fn push_leaf(&mut self, key: Key, spec: NodeSpec, content: NodeContent) {
619        let parent = self.current();
620        let idx = self.tree.push(parent, key, self.origin, spec, content);
621        // Read off the pushed spec rather than before the push, so nothing
622        // is held across `Tree::push` on the path every leaf takes.
623        if self.tree.specs[idx as usize]
624            .access
625            .as_deref()
626            .is_some_and(|a| a.tooltip)
627        {
628            self.leaf_hint(key, idx);
629        }
630    }
631
632    /// The hint of the leaf just pushed, floated while it is hovered: a
633    /// leaf holds no children, so the hint cannot be its last child the
634    /// way `close` floats a box's, and it floats beside the leaf anchored
635    /// to it instead (`widgets::leaf_hint`, backlog RG113). The string is
636    /// the leaf's description, which is what `apply_tooltip` set it to.
637    #[cold]
638    #[inline(never)]
639    fn leaf_hint(&mut self, key: Key, idx: u32) {
640        if !self.is_hovered(key) {
641            return;
642        }
643        let Some(tip) = self
644            .tree
645            .specs
646            .get(idx as usize)
647            .and_then(|s| s.access.as_deref())
648            .and_then(|a| a.description.clone())
649        else {
650            return;
651        };
652        crate::widgets::leaf_hint(&mut Ui::wrap(self), key, &tip);
653    }
654
655    /// What every node's spec goes through between the door and the tree,
656    /// in this order — one pipeline for a box, a leaf, a stroke and a
657    /// fill alike (AR16: five doors ran five subsets of it, and a wedge's
658    /// `hover_bg` never painted). The one paint the environment decides
659    /// (`accent`): the theme's accent, which is the OS's where the host
660    /// reported one, the app's where it pinned one, and kui's otherwise;
661    /// before the hover resolution, so a node that
662    /// declares both still hovers to what it declared. Then the hover /
663    /// pressed / focus background for the node's state, then the eased
664    /// values a transition, entrance or keyframes put over the declared
665    /// ones.
666    #[inline]
667    fn prepare_spec(&mut self, key: Key, spec: &mut NodeSpec) {
668        if spec.accent && self.has_accent() {
669            spec.style.bg = self.theme.accent;
670        }
671        self.resolve_hover_style(key, spec);
672        self.ease_spec(key, spec);
673    }
674
675    /// The layout of a node placed by its own geometry — a stroke, a fill:
676    /// never in layout, a float at `rect` in the
677    /// parent's box space sized exactly to it, the declared float's
678    /// *anchor* kept and every sizing, clamp and scroll row overridden,
679    /// since the box is the shape's own and not a size the view chose or
680    /// a tween may lag.
681    fn float_box_for(spec: &mut NodeSpec, rect: Rect) {
682        let anchor = spec
683            .layout
684            .float
685            .map_or(crate::spec::FloatAnchor::Parent, |f| f.anchor);
686        spec.layout.float = Some(crate::spec::FloatConfig {
687            anchor,
688            offset: crate::spec::Vec2Offset {
689                x: rect.x,
690                y: rect.y,
691            },
692            // A stroke drawn in its parent's box is the parent's content,
693            // so the parent's clip holds it as it holds a child (F78; ADR
694            // 0010 decision 5, as amended by F90): the bit a declared float
695            // opts into, set here for every stroke. A viewport-anchored
696            // one escapes regardless (`FloatConfig::clipped_by_parent`).
697            clip: true,
698            ..crate::spec::FloatConfig::default()
699        });
700        spec.layout.width = Sizing::Fixed(rect.w);
701        spec.layout.height = Sizing::Fixed(rect.h);
702        spec.layout.min_w = crate::spec::Min::AUTO;
703        spec.layout.max_w = f32::INFINITY;
704        spec.layout.min_h = crate::spec::Min::AUTO;
705        spec.layout.max_h = f32::INFINITY;
706        spec.layout.clip = false;
707        spec.layout.scroll_x = false;
708        spec.layout.scroll_y = false;
709    }
710
711    #[inline]
712    pub fn close(&mut self) {
713        // The tooltip prop's third effect, for the node being closed: its
714        // hint floats below it as its last child while it is hovered. One
715        // length check per close for a frame that declared no hints.
716        if let Some((depth, _, _)) = self.hints.last()
717            && *depth == self.stack.len()
718        {
719            let (_, key, hint) = self.hints.pop().unwrap();
720            if self.is_hovered(key) {
721                crate::widgets::hover_hint(&mut Ui::wrap(self), &hint);
722            }
723        }
724        if self.stack.len() > 1 {
725            self.stack.pop();
726            self.counters.pop();
727        }
728    }
729
730    /// Records the hover hint of the node just opened (the top of the
731    /// stack): `close` floats `widgets::hover_hint` below it while it is
732    /// hovered. The one place that decides *when* a tooltip shows, so a
733    /// binding that parsed the string cannot show it some other way.
734    pub fn hint(&mut self, key: Key, text: impl Into<String>) {
735        self.hints.push((self.stack.len(), key, text.into()));
736    }
737
738    /// Opens a node the way a parsed prop list says — under the data
739    /// index, the label or the next auto key; taking keyboard focus when
740    /// `keyFocus` asked; floating its `tooltip` on `close` while hovered —
741    /// with whatever the node holds. The one door for every binding that
742    /// lowers props, so the identity match, the focus edge and the hint
743    /// are not re-derived per binding per element (they were, eight, five
744    /// and four times). A box or a fragment is left open for its children,
745    /// and its hint floats as its last child on `close`; a `cells` grid, a
746    /// `line`, a `polygon` and a `path` are leaves, and theirs floats
747    /// beside the leaf, anchored to it (`PropsOut::for_leaf`, backlog
748    /// RG113). Returns the key.
749    pub fn open_from(&mut self, props: PropsOut, content: Content<'_>) -> Key {
750        let leaf = !matches!(content, Content::Box | Content::Fragment(..));
751        let props = if leaf { props.for_leaf() } else { props };
752        let PropsOut {
753            spec,
754            key: label,
755            index,
756            row_count,
757            key_focus,
758            tooltip,
759            ..
760        } = props;
761        let identity = match (index, &label) {
762            (Some(i), _) => Identity::Index(i),
763            (None, Some(label)) => Identity::Label(label),
764            (None, None) => Identity::Auto,
765        };
766        let key = match identity {
767            Identity::Auto => self.auto_key(),
768            Identity::Label(l) => self.child_key(l),
769            Identity::Index(i) => self.child_key_indexed(i),
770        };
771        let at = self.tree.len() as u32;
772        match content {
773            Content::Box => self.open_with_key(key, spec),
774            Content::Fragment(frag, params) => self.fragment_with_key(key, frag, params, spec),
775            Content::Cells(grid) => self.cells_at(key, grid, spec),
776            Content::Line(points, stroke) => self.line_with_key(key, points, &stroke, spec),
777            Content::Polygon(points) => self.polygon_with_key(key, points, spec),
778            Content::Path(ops, rule, stroke, turn) => {
779                self.path_with_key(key, ops, rule, stroke, turn, spec)
780            }
781            Content::PathD(d, rule, stroke, turn) => {
782                self.path_node_d(key, d, rule, stroke, turn, spec)
783            }
784            Content::PathFlat(floats, rule, stroke, turn) => {
785                self.path_node_flat(key, floats, rule, stroke, turn, spec)
786            }
787        }
788        // Bookkeeping for the node that was actually pushed: the label
789        // `key_of` resolves through, or the data index a selection inside
790        // a virtual row is ordered by when the row is not built (ADR 0017).
791        if self.tree.len() as u32 > at {
792            match identity {
793                Identity::Label(l) => self.key_labels.push(key, l, self.origin),
794                Identity::Index(i) => self.tree.indexed.push((at, i)),
795                Identity::Auto => {}
796            }
797            if let Some(n) = row_count {
798                self.tree.row_counts.push((at, n));
799            }
800        }
801        if key_focus {
802            self.set_key_focus(Some(key));
803        }
804        // A leaf's hint was asked of its door by `for_leaf`, above.
805        if let Some(hint) = tooltip
806            && !leaf
807        {
808            self.hint(key, hint);
809        }
810        key
811    }
812
813    /// The root the way a parsed prop list says: its title, whether it
814    /// wants the window on top, its keyboard secure, its Option keys as
815    /// Alt or its input method off, the windows it declares, its spec, and
816    /// keyboard focus on it when asked — what a binding's root op does,
817    /// once.
818    pub fn configure_root_from(&mut self, props: PropsOut) {
819        if let Some(title) = &props.title {
820            self.set_window_title(title);
821        }
822        if props.always_on_top {
823            self.set_always_on_top(true);
824        }
825        if props.secure_input {
826            self.set_secure_input(true);
827        }
828        if props.option_as_alt != crate::OptionAsAlt::None {
829            self.set_option_as_alt(props.option_as_alt);
830        }
831        if props.ime_off {
832            self.set_ime_off(true);
833        }
834        for (name, cfg) in &props.windows {
835            self.declare_window(name, *cfg);
836        }
837        self.configure_root(props.spec);
838        if props.key_focus {
839            let root = self.root_key();
840            self.set_key_focus(Some(root));
841        }
842    }
843
844    pub fn text_node(&mut self, content: &str, style: TextStyle) {
845        if self.tree.is_empty() {
846            return;
847        }
848        // A style that named no colour takes the theme's foreground here,
849        // at the one door text comes through, so the shaping cache, the
850        // display list and every binding downstream see a real colour
851        // (ADR 0019).
852        let style = style.or_fg(self.theme.fg);
853        let tid = {
854            let sess = &mut *self.session.state();
855            self.text
856                .add(content, &style, &sess.resources, &mut sess.fonts)
857        };
858        let key = self.auto_key();
859        let parent = self.current();
860        self.tree.push(
861            parent,
862            key,
863            self.origin,
864            NodeSpec::default(),
865            NodeContent::Text(tid),
866        );
867    }
868
869    /// A cell grid as one leaf node, sized `cols × cell_w` by `rows ×
870    /// cell_h`. `spec` is the node's:
871    /// an `on_key` makes it the terminal's sink, an `on_click` / `on_drag`
872    /// carry `cell: {row, col}` on their events.
873    pub fn cells(&mut self, grid: &crate::cells::CellGrid<'_>, spec: NodeSpec) {
874        let key = self.auto_key();
875        self.cells_at(key, grid, spec);
876    }
877
878    /// [`Self::cells`] under a declared key.
879    pub fn cells_keyed(&mut self, label: &str, grid: &crate::cells::CellGrid<'_>, spec: NodeSpec) {
880        if self.tree.is_empty() {
881            return;
882        }
883        let key = self.child_key(label);
884        self.cells_at(key, grid, spec);
885        // Like every other keyed door: the label after the node, so a
886        // frame with no root records no name (AR16).
887        self.key_labels.push(key, label, self.origin);
888    }
889
890    /// [`Self::cells`] under a data index; see [`Self::open_indexed`].
891    pub fn cells_indexed(&mut self, i: u64, grid: &crate::cells::CellGrid<'_>, spec: NodeSpec) {
892        let key = self.child_key_indexed(i);
893        self.cells_at(key, grid, spec);
894    }
895
896    fn cells_at(&mut self, key: Key, grid: &crate::cells::CellGrid<'_>, mut spec: NodeSpec) {
897        if self.tree.is_empty() {
898            return;
899        }
900        // The node's box is a box like any leaf's: its `hoverBg` lights
901        // and its `transition` tweens the bg, the opacity, the size. The
902        // cells inside it are a picture the app redraws, and nothing here
903        // touches them (AR5).
904        self.prepare_spec(key, &mut spec);
905        let cid = self.cells.add(key, grid);
906        self.push_leaf(key, spec, NodeContent::Cells(cid));
907    }
908
909    /// An editable text node. State (buffer, cursor, selection) is retained
910    /// by key across frames; edits arrive via `handle_input` and come back to
911    /// the host as "changed"/"submit" events. Read with `edit_text`.
912    pub fn text_edit(
913        &mut self,
914        label: &str,
915        initial: &str,
916        opts: &EditOptions,
917        mut spec: NodeSpec,
918    ) -> Key {
919        if self.tree.is_empty() {
920            return Key::ROOT;
921        }
922        let key = self.child_key(label);
923        self.prepare_spec(key, &mut spec);
924        // The same stamp the two text funnels make: an editor that named
925        // no text colour and no selection tint takes the theme's, so a
926        // field and a label beside it agree on both (ADR 0019).
927        let opts = &EditOptions {
928            style: opts.style.or_fg(self.theme.fg),
929            accent: Some(opts.accent.unwrap_or(self.theme.selection)),
930            ..opts.clone()
931        };
932        let edge = {
933            let origin = self.origin;
934            let scale = self.scale;
935            let sess = &mut *self.session.state();
936            // A `set_edit_text` by label, held for the frame that would
937            // declare the name (backlog F32): claimed here, where the
938            // label and its key are both in hand, and before `declare`,
939            // which is what turns it into this key's seed.
940            self.edit
941                .claim_label(key, label, &mut sess.fonts, &sess.resources);
942            self.edit.declare(
943                key,
944                initial,
945                opts,
946                origin,
947                scale,
948                &mut sess.fonts,
949                &sess.resources,
950            )
951        };
952        // Autofocus takes the keyboard only while nothing holds it — never
953        // from a control Tab landed on — and only on the frame the editor
954        // starts being declared (`docs/adr/0022`, decision 9): asked every
955        // frame, it would take focus straight back from every blur, and an
956        // app with an autofocus field could never have nothing focused.
957        if opts.autofocus && edge && self.focus.is_none() && !spec.disabled {
958            self.move_focus(Some(key));
959        }
960        self.push_leaf(key, spec, NodeContent::Edit(key));
961        // A leaf keyed by its label, like `open_keyed`: `key_of` must find
962        // the editor an app wants to focus by name.
963        self.key_labels.push(key, label, self.origin);
964        key
965    }
966
967    /// A registered image (see `Resources::add_image`). Fit sizing takes
968    /// the image's pixel dimensions as logical px; a Fit height against a
969    /// resolved width preserves the aspect ratio. `style.radius` rounds the
970    /// corners. Linear sampling, stretched to the box: [`Self::image_node_with`]
971    /// takes the two rows that say otherwise.
972    pub fn image_node(&mut self, id: crate::resources::ImageId, spec: NodeSpec) {
973        self.image_node_with(id, crate::resources::ImageOpts::default(), spec);
974    }
975
976    /// [`Self::image_node`] with its `sampling` and `fit` rows: how texels are
977    /// read between pixels, and how the pixels
978    /// meet a box of another aspect. The box — its layout, hit region and
979    /// access rect — is the same in every mode.
980    pub fn image_node_with(
981        &mut self,
982        id: crate::resources::ImageId,
983        opts: crate::resources::ImageOpts,
984        mut spec: NodeSpec,
985    ) {
986        if self.tree.is_empty() {
987            return;
988        }
989        let key = self.auto_key();
990        self.prepare_spec(key, &mut spec);
991        self.push_leaf(key, spec, NodeContent::Image(id, opts));
992    }
993
994    /// A box a registered WGSL function paints.
995    ///
996    /// An ordinary node in every other respect: it lays out where it is
997    /// declared, sizes from `spec`, rounds by `radius`, clips, fades with
998    /// its subtree's opacity, takes input like any box, and may hold
999    /// children — which paint over it, so a gradient card is a `fragment`
1000    /// with a title and buttons inside it.
1001    ///
1002    /// It has **no intrinsic size**: unlike an image there is nothing to
1003    /// measure, so a fragment with no `width` / `height` / `fill` is zero
1004    /// by zero and draws nothing. Size it.
1005    ///
1006    /// `params` is up to sixteen numbers, positional, zero-padded, read by
1007    /// the shader as four `vec4<f32>`; more than sixteen are dropped with
1008    /// a `fragment-params-truncated` warning. A handle that is not live in
1009    /// this session draws nothing, as every resource kind does — and so
1010    /// does one whose `image` (`FragmentId::with_image`) is not, which is
1011    /// the removal order: the image goes, the fragment reading it draws
1012    /// the fallback, and the handle it kept is a `foreign-resource` miss
1013    /// like any other.
1014    pub fn fragment_node(
1015        &mut self,
1016        frag: impl Into<crate::fragment::FragmentRef>,
1017        params: &[f32],
1018        spec: NodeSpec,
1019    ) -> Key {
1020        let key = self.open_fragment(frag, params, spec);
1021        self.close();
1022        key
1023    }
1024
1025    /// Opens a fragment as a parent: its children paint over it, which is
1026    /// what a gradient card with a title and buttons in it is. Balance it
1027    /// with [`Self::close`], or use `Ui::fragment_with`.
1028    pub fn open_fragment(
1029        &mut self,
1030        frag: impl Into<crate::fragment::FragmentRef>,
1031        params: &[f32],
1032        spec: NodeSpec,
1033    ) -> Key {
1034        if self.tree.is_empty() {
1035            return Key::ROOT;
1036        }
1037        let key = self.auto_key();
1038        self.fragment_with_key(key, frag.into(), params, spec);
1039        key
1040    }
1041
1042    /// [`Self::fragment_node`] under a label key, for a fragment that
1043    /// transitions or exits and needs a stable identity across frames.
1044    pub fn fragment_node_keyed(
1045        &mut self,
1046        label: &str,
1047        frag: impl Into<crate::fragment::FragmentRef>,
1048        params: &[f32],
1049        spec: NodeSpec,
1050    ) -> Key {
1051        let key = self.open_fragment_keyed(label, frag, params, spec);
1052        self.close();
1053        key
1054    }
1055
1056    /// [`Self::open_fragment`] under a label key.
1057    pub fn open_fragment_keyed(
1058        &mut self,
1059        label: &str,
1060        frag: impl Into<crate::fragment::FragmentRef>,
1061        params: &[f32],
1062        spec: NodeSpec,
1063    ) -> Key {
1064        if self.tree.is_empty() {
1065            return Key::ROOT;
1066        }
1067        let key = self.child_key(label);
1068        self.fragment_with_key(key, frag.into(), params, spec);
1069        self.key_labels.push(key, label, self.origin);
1070        key
1071    }
1072
1073    /// [`Self::open_fragment`] under a data index; see [`Self::open_indexed`].
1074    pub fn open_fragment_indexed(
1075        &mut self,
1076        i: u64,
1077        frag: impl Into<crate::fragment::FragmentRef>,
1078        params: &[f32],
1079        spec: NodeSpec,
1080    ) -> Key {
1081        if self.tree.is_empty() {
1082            return Key::ROOT;
1083        }
1084        let key = self.child_key_indexed(i);
1085        self.fragment_with_key(key, frag.into(), params, spec);
1086        key
1087    }
1088
1089    fn fragment_with_key(
1090        &mut self,
1091        key: Key,
1092        frag: crate::fragment::FragmentRef,
1093        params: &[f32],
1094        spec: NodeSpec,
1095    ) {
1096        let (params, dropped) = crate::fragment::params_of(params);
1097        if dropped > 0 {
1098            self.diag.raise(Warning {
1099                code: crate::diag::FRAGMENT_PARAMS_TRUNCATED,
1100                key,
1101                message: format!(
1102                    "a fragment takes sixteen params and {} were declared, so the last {dropped}                      were dropped; pack what the shader needs into the sixteen it has",
1103                    params.len() + dropped
1104                ),
1105            });
1106        }
1107        let draw = self.fragments.push(crate::fragment::Draw {
1108            id: frag.id,
1109            image: frag.image,
1110            params,
1111        });
1112        self.open_content(key, spec, NodeContent::Fragment(draw));
1113    }
1114
1115    /// A stroke through `points` in the parent's box space: one round-capped
1116    /// segment for two points, a polyline for more, a smooth curve through
1117    /// them with [`Stroke::curve`].
1118    ///
1119    /// Never in layout. The node is a float sized to the stroke's padded
1120    /// bounding box, so it takes no room in a row or column, and `spec`'s
1121    /// sizing, clamps, padding, gap and alignment are ignored. What `spec`
1122    /// carries that matters: `transition` (the colour eases — it rides in
1123    /// the `bg` slot — and `slide`, `enter` and `exit` offsets move the
1124    /// float), `opacity`, `on_layout` (reports the bounding box), a
1125    /// declared `float` whose *anchor* is kept (`FloatAnchor::Viewport`
1126    /// reads the points in viewport space), and `role` / `label`, which are
1127    /// honoured like any node's; without them a line has no access row —
1128    /// unless it takes input, when it derives one as a box would. Input
1129    /// is hit by *shape*: a press within half the stroke's
1130    /// width of any piece (at least `MIN_STROKE_GRAB` wide) hits it, and
1131    /// a press elsewhere in its box falls through to what is under it.
1132    /// Fewer than two points draw nothing.
1133    ///
1134    /// Consecutive segments overlap at their round caps, which is the
1135    /// join: exact for an opaque stroke, and a translucent one
1136    /// double-blends there, the way a faded subtree shows its seams.
1137    pub fn line_node(&mut self, points: &[Vec2], stroke: Stroke, spec: NodeSpec) {
1138        if self.tree.is_empty() {
1139            return;
1140        }
1141        let key = self.auto_key();
1142        self.line_with_key(key, points, &stroke, spec);
1143    }
1144
1145    /// [`Self::line_node`] under a label key, for a stroke that transitions
1146    /// or exits and needs a stable identity across frames.
1147    pub fn line_node_keyed(
1148        &mut self,
1149        label: &str,
1150        points: &[Vec2],
1151        stroke: Stroke,
1152        spec: NodeSpec,
1153    ) {
1154        if self.tree.is_empty() {
1155            return;
1156        }
1157        let key = self.child_key(label);
1158        self.line_with_key(key, points, &stroke, spec);
1159        // Like every other keyed door: the label `key_of` resolves through.
1160        self.key_labels.push(key, label, self.origin);
1161    }
1162
1163    /// [`Self::line_node`] under a data index; see [`Self::open_indexed`].
1164    pub fn line_node_indexed(&mut self, i: u64, points: &[Vec2], stroke: Stroke, spec: NodeSpec) {
1165        if self.tree.is_empty() {
1166            return;
1167        }
1168        let key = self.child_key_indexed(i);
1169        self.line_with_key(key, points, &stroke, spec);
1170    }
1171
1172    /// The stroke is lent from here down: at 44 bytes with its dash it
1173    /// is passed in memory, and a copy at each call of the chain was
1174    /// most of what a solid line cost over alpha.36's (backlog C52).
1175    fn line_with_key(&mut self, key: Key, points: &[Vec2], stroke: &Stroke, mut spec: NodeSpec) {
1176        let Some((id, rect)) = self.lines.push(points, stroke) else {
1177            return;
1178        };
1179        // The stroke colour rides in the slot backgrounds tween through, so
1180        // `transition`, `enter` and `exit` reach it with no slot of its own;
1181        // nothing else of the box vocabulary applies to a stroke.
1182        spec.style.bg = stroke.color;
1183        spec.style.border_w = 0.0;
1184        spec.style.border_color = Color::TRANSPARENT;
1185        spec.style.shadow = crate::spec::Shadow::default();
1186        // The same pipeline as a box's, so a stroke's `hover_bg` is the
1187        // colour it takes under the pointer and `accent` is honoured.
1188        self.prepare_spec(key, &mut spec);
1189        // The box is the stroke's own, and the points are stored relative
1190        // to it.
1191        Self::float_box_for(&mut spec, rect);
1192        self.push_leaf(key, spec, NodeContent::Line(id));
1193    }
1194
1195    /// A filled polygon through `points` in the parent's box space:
1196    /// up to
1197    /// eight vertices, the fill in `spec`'s `bg`, painted by the stock
1198    /// polygon fragment the core registers itself.
1199    ///
1200    /// Placed exactly as a line is: never in
1201    /// layout, a float sized to the points' bounding box inflated by a
1202    /// logical pixel for the edge ramp, so it takes no room in a row or
1203    /// column and `spec`'s sizing, clamps, padding, gap and alignment are
1204    /// ignored. `transition` eases the fill through the `bg` slot, and
1205    /// `slide`, `enter` and `exit` move the float; a declared `float`
1206    /// keeps its *anchor*; `role` and `label` are honoured, and without
1207    /// them a polygon has no access row unless it takes input, when it
1208    /// derives one as a box would (a clickable wedge is a button). Input
1209    /// is hit by *shape*: a press inside the outline hits it,
1210    /// one in its box but outside the outline falls through to what is
1211    /// under. Fewer than three points draw nothing; a ninth and later are
1212    /// dropped with `polygon-points-truncated`. The outline may be
1213    /// concave; a self-intersecting one fills even-odd, its overlaps
1214    /// unfilled.
1215    pub fn polygon_node(&mut self, points: &[Vec2], spec: NodeSpec) {
1216        if self.tree.is_empty() {
1217            return;
1218        }
1219        let key = self.auto_key();
1220        self.polygon_with_key(key, points, spec);
1221    }
1222
1223    /// [`Self::polygon_node`] under a label key.
1224    pub fn polygon_node_keyed(&mut self, label: &str, points: &[Vec2], spec: NodeSpec) {
1225        if self.tree.is_empty() {
1226            return;
1227        }
1228        let key = self.child_key(label);
1229        self.polygon_with_key(key, points, spec);
1230        self.key_labels.push(key, label, self.origin);
1231    }
1232
1233    /// [`Self::polygon_node`] under a data index; see [`Self::open_indexed`].
1234    pub fn polygon_node_indexed(&mut self, i: u64, points: &[Vec2], spec: NodeSpec) {
1235        if self.tree.is_empty() {
1236            return;
1237        }
1238        let key = self.child_key_indexed(i);
1239        self.polygon_with_key(key, points, spec);
1240    }
1241
1242    /// The stock polygon fragment's handle, registered on first use and
1243    /// again after `remove_fragment` forgot it.
1244    fn stock_polygon(&mut self) -> Option<crate::resources::FragmentId> {
1245        if let Some(id) = self.stock_polygon {
1246            return Some(id);
1247        }
1248        let id = self.add_fragment(crate::fragment::POLYGON);
1249        self.stock_polygon = id;
1250        id
1251    }
1252
1253    fn polygon_with_key(&mut self, key: Key, points: &[Vec2], mut spec: NodeSpec) {
1254        if points.len() < 3 {
1255            return;
1256        }
1257        if points.len() > crate::fragment::POLYGON_MAX_POINTS {
1258            self.diag.raise(Warning {
1259                code: crate::diag::POLYGON_POINTS_TRUNCATED,
1260                key,
1261                message: format!(
1262                    "a polygon takes {} points and {} were declared, so the last {} were \
1263                     dropped; split it in two",
1264                    crate::fragment::POLYGON_MAX_POINTS,
1265                    points.len(),
1266                    points.len() - crate::fragment::POLYGON_MAX_POINTS
1267                ),
1268            });
1269        }
1270        let points = &points[..points.len().min(crate::fragment::POLYGON_MAX_POINTS)];
1271        let Some(id) = self.stock_polygon() else {
1272            return;
1273        };
1274        // The box: the points' bounds, a logical pixel out on every side
1275        // so the one-pixel edge ramp is never cut by the quad's own edge.
1276        let (mut x0, mut y0, mut x1, mut y1) = (f32::MAX, f32::MAX, f32::MIN, f32::MIN);
1277        for p in points {
1278            x0 = x0.min(p.x);
1279            y0 = y0.min(p.y);
1280            x1 = x1.max(p.x);
1281            y1 = y1.max(p.y);
1282        }
1283        let rect = Rect::new(x0 - 1.0, y0 - 1.0, x1 - x0 + 2.0, y1 - y0 + 2.0);
1284        // The vertices, normalised to that box; the last repeated to pad,
1285        // which the stock source reads as a zero-length edge and skips.
1286        let mut params = [0.0f32; 16];
1287        let last = points[points.len() - 1];
1288        for i in 0..crate::fragment::POLYGON_MAX_POINTS {
1289            let p = points.get(i).copied().unwrap_or(last);
1290            params[i * 2] = (p.x - rect.x) / rect.w;
1291            params[i * 2 + 1] = (p.y - rect.y) / rect.h;
1292        }
1293        let draw = self.fragments.push(crate::fragment::Draw {
1294            id,
1295            image: None,
1296            params,
1297        });
1298        // The fill rides in `bg`, which `transition`, `enter` and `exit`
1299        // already ease — and which `hover_bg` and `accent` swap, through
1300        // the same pipeline as a box's; nothing else of the box vocabulary
1301        // applies.
1302        spec.style.border_w = 0.0;
1303        spec.style.border_color = Color::TRANSPARENT;
1304        spec.style.shadow = crate::spec::Shadow::default();
1305        self.prepare_spec(key, &mut spec);
1306        Self::float_box_for(&mut spec, rect);
1307        self.push_leaf(key, spec, NodeContent::Polygon(draw));
1308    }
1309
1310    /// A path — any outline, SVG's `d` — filled with `spec`'s `bg` by the
1311    /// path's rule and stroked by its stroke if it has one
1312    /// (`docs/adr/0040-a-path-is-a-mask-in-the-atlas.md`).
1313    ///
1314    /// Placed exactly as a line is: never in layout, a float sized to the
1315    /// outline's bounding box two logical pixels out (and half the stroke's
1316    /// width further), so it takes no room in a row or column and
1317    /// `spec`'s sizing, clamps, padding, gap and alignment are ignored.
1318    /// `transition` eases the fill through the `bg` slot, and `slide`,
1319    /// `enter` and `exit` move the float; a declared `float` keeps its
1320    /// *anchor*; `role` and `label` are honoured, and without them a path
1321    /// has no access row unless it takes input, when it derives one as a
1322    /// box would. Input is hit by *shape*: a press inside the outline by
1323    /// the fill rule hits it, one in its box past the outline falls
1324    /// through to what is under. A path with no outline draws nothing.
1325    ///
1326    /// The outline is rasterized once per shape, scale and quarter-pixel
1327    /// position into the glyph atlas and drawn as a glyph-mask quad; the
1328    /// fill bleeds half a pixel so two paths sharing an edge meet without
1329    /// the background showing through. A path whose ops change twice within
1330    /// a few frames, or whose mask is a quarter of the biggest atlas page or
1331    /// more, draws from a texture of its own instead.
1332    pub fn path_node(&mut self, path: &crate::path::Path, spec: NodeSpec) {
1333        if self.tree.is_empty() {
1334            return;
1335        }
1336        let key = self.auto_key();
1337        self.path_with_key(
1338            key,
1339            path.ops(),
1340            path.rule(),
1341            path.stroke(),
1342            path.turn(),
1343            spec,
1344        );
1345    }
1346
1347    /// [`Self::path_node`] under a label key.
1348    pub fn path_node_keyed(&mut self, label: &str, path: &crate::path::Path, spec: NodeSpec) {
1349        if self.tree.is_empty() {
1350            return;
1351        }
1352        let key = self.child_key(label);
1353        self.path_with_key(
1354            key,
1355            path.ops(),
1356            path.rule(),
1357            path.stroke(),
1358            path.turn(),
1359            spec,
1360        );
1361        self.key_labels.push(key, label, self.origin);
1362    }
1363
1364    /// [`Self::path_node`] under a data index; see [`Self::open_indexed`].
1365    pub fn path_node_indexed(&mut self, i: u64, path: &crate::path::Path, spec: NodeSpec) {
1366        if self.tree.is_empty() {
1367            return;
1368        }
1369        let key = self.child_key_indexed(i);
1370        self.path_with_key(
1371            key,
1372            path.ops(),
1373            path.rule(),
1374            path.stroke(),
1375            path.turn(),
1376            spec,
1377        );
1378    }
1379
1380    /// SVG path data to a [`crate::path::Path`], through the one parser
1381    /// every binding's `d` goes through (`Path::parse`, reached here as
1382    /// the door the C API's `kui_path_parse` is). `Err` names the byte.
1383    pub fn parse_path(&self, d: &str) -> Result<crate::path::Path, crate::path::PathError> {
1384        crate::path::Path::parse(d)
1385    }
1386
1387    /// [`Self::path_node`] from SVG path data, parsed by the one parser
1388    /// every binding goes through; data that does not parse raises
1389    /// `path-malformed` under the node's key and draws nothing.
1390    pub fn path_d_node(
1391        &mut self,
1392        d: &str,
1393        rule: crate::path::FillRule,
1394        stroke: Option<Stroke>,
1395        turn: Option<crate::path::Turn>,
1396        spec: NodeSpec,
1397    ) {
1398        if self.tree.is_empty() {
1399            return;
1400        }
1401        let key = self.auto_key();
1402        self.path_node_d(key, d, rule, stroke, turn, spec);
1403    }
1404
1405    /// [`Self::path_d_node`] under a label key.
1406    pub fn path_d_node_keyed(
1407        &mut self,
1408        label: &str,
1409        d: &str,
1410        rule: crate::path::FillRule,
1411        stroke: Option<Stroke>,
1412        turn: Option<crate::path::Turn>,
1413        spec: NodeSpec,
1414    ) {
1415        if self.tree.is_empty() {
1416            return;
1417        }
1418        let key = self.child_key(label);
1419        self.path_node_d(key, d, rule, stroke, turn, spec);
1420        self.key_labels.push(key, label, self.origin);
1421    }
1422
1423    /// [`Self::path_d_node`] under a key the caller derived.
1424    pub fn path_node_d(
1425        &mut self,
1426        key: Key,
1427        d: &str,
1428        rule: crate::path::FillRule,
1429        stroke: Option<Stroke>,
1430        turn: Option<crate::path::Turn>,
1431        spec: NodeSpec,
1432    ) {
1433        // The string a key declared last frame is the string it declares
1434        // this frame, nearly always: its ops are kept, and the parse is
1435        // paid when the string changes.
1436        let hash = crate::key::hash_bulk(d.as_bytes());
1437        let kept = self
1438            .path_parsed
1439            .remove(&key)
1440            .filter(|p| p.hash == hash && p.len == d.len());
1441        let ops = match kept {
1442            Some(p) => p.ops,
1443            None => match crate::path::Path::parse(d) {
1444                Ok(path) => path.into_ops(),
1445                Err(e) => {
1446                    self.diag.raise(Warning {
1447                        code: crate::diag::PATH_MALFORMED,
1448                        key,
1449                        message: format!("the path's `d` did not parse: expected {e}"),
1450                    });
1451                    return;
1452                }
1453            },
1454        };
1455        self.path_with_key(key, &ops, rule, stroke, turn, spec);
1456        self.path_parsed.insert(
1457            key,
1458            crate::path::Parsed {
1459                hash,
1460                len: d.len(),
1461                seen: self.frame_no,
1462                ops,
1463            },
1464        );
1465    }
1466
1467    /// [`Self::path_node`] from the flat op form — a code, then its
1468    /// operands, per op, as `Path::to_floats` writes it and a binding's
1469    /// wire carries it. Floats that are not the form (a code that is not
1470    /// one, an op cut short) raise `path-malformed` under the node's key
1471    /// and draw nothing: one answer in every binding, where it was an
1472    /// error in one and silence in two (RG112).
1473    pub fn path_flat_node(
1474        &mut self,
1475        floats: &[f32],
1476        rule: crate::path::FillRule,
1477        stroke: Option<Stroke>,
1478        turn: Option<crate::path::Turn>,
1479        spec: NodeSpec,
1480    ) {
1481        if self.tree.is_empty() {
1482            return;
1483        }
1484        let key = self.auto_key();
1485        self.path_node_flat(key, floats, rule, stroke, turn, spec);
1486    }
1487
1488    /// [`Self::path_flat_node`] under a label key.
1489    pub fn path_flat_node_keyed(
1490        &mut self,
1491        label: &str,
1492        floats: &[f32],
1493        rule: crate::path::FillRule,
1494        stroke: Option<Stroke>,
1495        turn: Option<crate::path::Turn>,
1496        spec: NodeSpec,
1497    ) {
1498        if self.tree.is_empty() {
1499            return;
1500        }
1501        let key = self.child_key(label);
1502        self.path_node_flat(key, floats, rule, stroke, turn, spec);
1503        self.key_labels.push(key, label, self.origin);
1504    }
1505
1506    /// [`Self::path_flat_node`] under a key the caller derived.
1507    pub fn path_node_flat(
1508        &mut self,
1509        key: Key,
1510        floats: &[f32],
1511        rule: crate::path::FillRule,
1512        stroke: Option<Stroke>,
1513        turn: Option<crate::path::Turn>,
1514        spec: NodeSpec,
1515    ) {
1516        match crate::path::Path::from_floats(floats) {
1517            Ok(path) => self.path_with_key(key, path.ops(), rule, stroke, turn, spec),
1518            Err(e) => self.diag.raise(Warning {
1519                code: crate::diag::PATH_MALFORMED,
1520                key,
1521                message: format!(
1522                    "the path's ops are not the flat form: expected {} at float {}",
1523                    e.what, e.at
1524                ),
1525            }),
1526        }
1527    }
1528
1529    fn path_with_key(
1530        &mut self,
1531        key: Key,
1532        ops: &[crate::path::PathOp],
1533        rule: crate::path::FillRule,
1534        stroke: Option<Stroke>,
1535        turn: Option<crate::path::Turn>,
1536        mut spec: NodeSpec,
1537    ) {
1538        // A number that is not one - `1e99` in `d` is an infinity, a
1539        // chart's 0/0 a NaN - has no outline to draw: the bounds would
1540        // drop it and the rasterizer would not.
1541        // The same for its turn, which the box does not depend on and so
1542        // could not catch.
1543        let turn_ok = turn.is_none_or(|t| {
1544            t.turns.is_finite() && t.pivot.is_none_or(|p| p.x.is_finite() && p.y.is_finite())
1545        });
1546        if !turn_ok || !ops.iter().all(crate::path::PathOp::is_finite) {
1547            self.diag.raise(Warning {
1548                code: crate::diag::PATH_MALFORMED,
1549                key,
1550                message: "the path holds a number that is not finite (a NaN or an \
1551                          infinity), among its coordinates or in its turn"
1552                    .into(),
1553            });
1554            return;
1555        }
1556        let stroke_w = stroke.map_or(0.0, |s| s.width.max(0.0));
1557        let dash = stroke.and_then(|s| s.dash.cut(stroke_w));
1558        let Some((id, rect)) = self.paths.push(ops, rule, stroke_w, dash, turn) else {
1559            return;
1560        };
1561        // The mask is the box at the frame's scale; past what a texture
1562        // can hold it draws nothing, and says so once per key. A box
1563        // that is not finite - a coordinate past what an f32 holds, a NaN
1564        // among the ops or in the turn - is past it too: `max` drops a
1565        // NaN, so the side alone would let one through.
1566        let side = (rect.w.max(rect.h) * self.scale).ceil();
1567        let finite = [rect.x, rect.y, rect.w, rect.h]
1568            .iter()
1569            .all(|v| v.is_finite());
1570        if !finite || side + 2.0 > crate::path::MAX_MASK_SIDE as f32 {
1571            self.diag.raise(Warning {
1572                code: crate::diag::PATH_TOO_LARGE,
1573                key,
1574                message: format!(
1575                    "the path's mask would be {side} px on a side at this scale, and a \
1576                     texture holds {} at most; draw it smaller, or as several paths",
1577                    crate::path::MAX_MASK_SIDE
1578                ),
1579            });
1580            return;
1581        }
1582        // A key whose ops changed twice within a few frames is animating:
1583        // its masks go to a texture of their own rather than churning the
1584        // atlas (ADR 0040, decision 8). One change is a new shape and a
1585        // new slot.
1586        // A pattern that moves - a marquee's marching ants - is a shape
1587        // that moves: each offset is a mask of its own.
1588        let hash = self.paths.run(id).0.hash ^ dash.map_or(0, |d| d.hash());
1589        let now = self.frame_no;
1590        let motion = match self.path_motion.get(&key) {
1591            Some(&m) if m.hash != hash => crate::path::Motion {
1592                hash,
1593                seen: now,
1594                changed: now,
1595                animating: m.animating
1596                    || (m.changed != 0 && now - m.changed <= crate::path::ANIMATING_WINDOW),
1597            },
1598            // Still for long enough, it is a shape again and goes back
1599            // to the atlas: the latch is for what moves, and a key from
1600            // the tree position whose siblings came and went would
1601            // otherwise hold a texture of its own for good (RG112).
1602            Some(&m) => crate::path::Motion {
1603                seen: now,
1604                animating: m.animating && now - m.changed <= crate::path::SETTLED_AFTER,
1605                ..m
1606            },
1607            None => crate::path::Motion {
1608                hash,
1609                seen: now,
1610                changed: 0,
1611                animating: false,
1612            },
1613        };
1614        if motion.animating {
1615            self.paths.set_animating(id);
1616        }
1617        self.path_motion.insert(key, motion);
1618        // The fill rides in `bg`, which `transition`, `enter` and `exit`
1619        // ease and `hover_bg` and `accent` swap; the stroke rides in the
1620        // border slots, which is what a border is to a box.
1621        spec.style.border_w = stroke_w;
1622        spec.style.border_color = stroke.map_or(Color::TRANSPARENT, |s| s.color);
1623        spec.style.shadow = crate::spec::Shadow::default();
1624        self.prepare_spec(key, &mut spec);
1625        Self::float_box_for(&mut spec, rect);
1626        self.push_leaf(key, spec, NodeContent::Path(id));
1627    }
1628
1629    /// A paragraph of styled spans, shaped and wrapped as one flow.
1630    pub fn rich_text_node(&mut self, spans: &[Span<'_>], base: TextStyle) {
1631        if self.tree.is_empty() {
1632            return;
1633        }
1634        // The paragraph's own colour, which each span falls back to.
1635        let base = base.or_fg(self.theme.fg);
1636        let tid = {
1637            let sess = &mut *self.session.state();
1638            self.text
1639                .add_rich(spans, &base, &sess.resources, &mut sess.fonts)
1640        };
1641        let key = self.auto_key();
1642        let parent = self.current();
1643        self.tree.push(
1644            parent,
1645            key,
1646            self.origin,
1647            NodeSpec::default(),
1648            NodeContent::Text(tid),
1649        );
1650    }
1651}