Skip to main content

kui_core/runtime/
emit.rs

1//! The frame's back half: layout, then emission into the display list.
2//!
3//! `finish_frame` runs the passes; the rest are the passes — one node's
4//! quads, the departed subtrees replayed as ghosts, position easing, the
5//! `layout` events, the default focus ring — and the quad helpers they
6//! share. Everything here reads the tree `builder` built and writes
7//! `display`; the input side of the same frame is `dispatch`.
8
9use super::*;
10
11const SCROLLBAR_W: f32 = 4.0;
12/// Thumb width while hovered or dragged.
13const SCROLLBAR_ACTIVE_W: f32 = 6.0;
14/// Grabbable gutter width (wider than the drawn thumb).
15const SCROLLBAR_HIT_W: f32 = 10.0;
16const SCROLLBAR_INSET: f32 = 2.0;
17const SCROLLBAR_MIN: f32 = 24.0;
18/// An `auto` bar (`ScrollbarMode::Auto`): how long it stays after the
19/// scroll state last changed, then how long it takes to fade. Seconds of
20/// the driver's clock.
21const SCROLLBAR_HOLD: f64 = 1.0;
22const SCROLLBAR_FADE: f64 = 0.25;
23/// The default focus ring:
24/// drawn this far outside the focused node, this thick, when focus is
25/// keyboard-visible and the node styles nothing itself.
26///
27/// The *colour* is `theme.focus_ring`: the geometry is
28/// still not a prop and still not negotiable, but a ring that cannot be
29/// seen is not a focus indicator, and the pale blue that reads on a dark
30/// page is invisible on a light one.
31const FOCUS_RING_GAP: f32 = 2.0;
32const FOCUS_RING_W: f32 = 2.0;
33
34/// The disjoint borrows one box's paint needs, split off the core field by
35/// field — a macro rather than a method so the tree, the stroke list and a
36/// ghost's points can stay borrowed beside them.
37macro_rules! painter {
38    ($core:expr) => {
39        Painter {
40            display: &mut $core.display,
41            text: &mut $core.text,
42            edit: &mut $core.edit,
43            cells: &mut $core.cells,
44            atlas: &mut $core.atlas,
45            session: &$core.session,
46            path_tex: &mut $core.path_textures,
47            frame_no: $core.frame_no,
48        }
49    };
50}
51
52impl Core {
53    /// The scrollbar thumb's colour at rest and while hovered or dragged:
54    /// the node's own where it declared one, else the theme's. A wash over
55    /// whatever it sits on rather than a fill, which is why the theme's
56    /// are two translucent colours and not one with an alpha applied.
57    fn thumb_color(&self, bar: &crate::spec::Scrollbar, active: bool) -> Color {
58        let t = self.theme();
59        if active {
60            bar.active_color.unwrap_or(t.scrollbar_active)
61        } else {
62            bar.color.unwrap_or(t.scrollbar)
63        }
64    }
65
66    /// Node `i`'s hit region, for a node that tracks the pointer. Out of
67    /// line: a box that takes no input — most of a frame — does not carry
68    /// the context-menu walk, the slider's track or the shape in
69    /// `emit_node`'s saved registers and stack frame.
70    #[inline(never)]
71    fn push_hit(
72        &mut self,
73        i: usize,
74        rect: Rect,
75        clip: Rect,
76        turn: Option<crate::input::HitTurn>,
77        drop: Option<crate::input::DropOwner>,
78        hits: &mut Vec<HitRegion>,
79    ) {
80        let spec = &self.tree.specs[i];
81        let parent = self.tree.parent[i];
82        let parent_rect = if parent == NIL {
83            Rect::new(0.0, 0.0, self.viewport.w, self.viewport.h)
84        } else {
85            let p = parent as usize;
86            Rect::from_pos_size(self.tree.pos[p], self.tree.size[p])
87        };
88        // A disabled node keeps hover (a tooltip can say why) and loses
89        // every interaction: it emits nothing and takes no focus.
90        let live = !spec.disabled;
91        // The menu this region opens is its own or an ancestor's; the
92        // walk is skipped on a frame where no node offers one (T1).
93        let context_menu = if self.tree.any_context_menu {
94            self.enclosing_menu(i).map(|j| crate::input::MenuOwner {
95                key: self.tree.keys[j],
96                origin: self.tree.origins[j],
97                tag: self.tree.specs[j]
98                    .events()
99                    .on_context_menu
100                    .clone()
101                    .expect("enclosing_menu returns a node that offers one"),
102            })
103        } else {
104            None
105        };
106        // A slider that asked for its changes reads the pointer along
107        // its content box (ADR 0034, decision 4); a disabled one, or a
108        // range that is not one, reads nothing.
109        let slider = match spec.events().on_change.as_ref() {
110            Some(tag) if live && spec.access().role == Some(crate::access::Role::Slider) => {
111                crate::slider::SliderRange::of(spec.access()).map(|range| {
112                    Box::new(crate::slider::SliderTrack::new(
113                        rect,
114                        spec.layout.padding,
115                        spec.layout.dir == crate::spec::Dir::Column,
116                        range,
117                        tag.clone(),
118                    ))
119                })
120            }
121            _ => None,
122        };
123        // The shape past the rect (ADR 0026): a stroke's pieces, a
124        // fill's outline, a rounded box's corners; a plain box none.
125        let shape = match self.tree.content[i] {
126            NodeContent::Line(id) => {
127                let (run, points) = self.lines.run(id);
128                self.hit_shapes.segments(points, run.width)
129            }
130            NodeContent::Polygon(id) => {
131                let draw = self.fragments.get(id);
132                let mut pts = [Vec2::ZERO; crate::fragment::POLYGON_MAX_POINTS];
133                for (k, p) in pts.iter_mut().enumerate() {
134                    *p = Vec2::new(draw.params[k * 2] * rect.w, draw.params[k * 2 + 1] * rect.h);
135                }
136                self.hit_shapes.polygon(&pts)
137            }
138            NodeContent::Path(id) => {
139                let (run, ops) = self.paths.run(id);
140                let mut outline = Vec::new();
141                // Hit by its fill when it may paint one: a `bg`, or one a
142                // hover, a press or the focus brings (the shape is
143                // decided before the pointer is, so by what is declared).
144                // With a stroke too, by the stroke's own pieces as well,
145                // or the outer half of a thick one is painted and not
146                // hit (RG112).
147                let s = &spec.style;
148                let fill = run.stroke_w <= 0.0
149                    || s.bg.is_visible()
150                    || spec.interact.as_deref().is_some_and(|i| {
151                        [i.hover_bg, i.pressed_bg, i.focus_bg]
152                            .iter()
153                            .any(|c| c.is_some_and(|c| c.is_visible()))
154                    });
155                if fill && run.stroke_w <= 0.0 {
156                    crate::path::flatten(ops, &mut outline);
157                } else {
158                    crate::path::flatten_stroke(ops, &mut outline);
159                }
160                // A turned path is hit where it is drawn: the outline
161                // turned about the box's centre, which is its pivot (ADR
162                // 0041). The contour breaks are not points and stay.
163                if let Some(angle) = run.angle.filter(|a| *a != 0.0) {
164                    let c = Vec2::new(rect.w * 0.5, rect.h * 0.5);
165                    for p in outline.iter_mut().filter(|p| !p.x.is_nan()) {
166                        *p = crate::path::turned(*p, c, angle);
167                    }
168                }
169                if fill {
170                    self.hit_shapes.path(&outline, run.rule, run.stroke_w)
171                } else {
172                    // A stroke with no fill is hit as a line is, by the
173                    // pieces it paints: a contour its `Z` closed runs
174                    // back to its start, an open one does not, and the
175                    // breaks are kept so no piece runs from one contour
176                    // to the next.
177                    self.hit_shapes.segments(&outline, run.stroke_w)
178                }
179            }
180            _ if spec.style.radius != crate::display::SQUARE => {
181                crate::input::HitShape::Rounded(spec.style.radius)
182            }
183            _ => crate::input::HitShape::Rect,
184        };
185        hits.push(HitRegion {
186            key: self.tree.keys[i],
187            origin: self.tree.origins[i],
188            rect,
189            clip,
190            turn: turn.map(Box::new),
191            shape,
192            payload: spec.events().on_click.clone().filter(|_| live),
193            drag: spec.events().on_drag.clone().filter(|_| live),
194            parent_rect,
195            key_sink: spec.events().on_key.clone().filter(|_| live),
196            key_up: spec.events().key_up,
197            context_menu,
198            drop,
199            focusable: crate::access::focusable(&self.tree, i),
200            edit_origin: None,
201            select_scope: self.scope_of(i).filter(|_| live),
202            window: spec.window,
203            hover: spec.events().on_hover.clone(),
204            group: spec.interact().hover_group,
205            click_sound: spec.interact().click_sound.filter(|_| live),
206            hover_sound: spec.interact().hover_sound,
207            cursor: spec.cursor,
208            slider,
209        });
210    }
211
212    /// An editor's own hit region, whose origin is where its glyphs sit
213    /// (shifted by what a field is scrolled). Out of line for the reason
214    /// `push_hit` is.
215    #[inline(never)]
216    #[allow(clippy::too_many_arguments)]
217    fn push_edit_hit(
218        &mut self,
219        i: usize,
220        key: Key,
221        rect: Rect,
222        clip: Rect,
223        turn: Option<crate::input::HitTurn>,
224        scale: f32,
225        drop: Option<crate::input::DropOwner>,
226        hits: &mut Vec<HitRegion>,
227    ) {
228        let spec = &self.tree.specs[i];
229        let pad = spec.layout.padding;
230        let content_origin = Vec2::new(rect.x + pad.l, rect.y + pad.t);
231        let inner_w = (rect.w - pad.x()).max(0.0);
232        // A single-line field scrolls its own text (F41). Resolved
233        // here, where the box is known, and read back by the hit
234        // region and the access runs so all three agree on where the
235        // glyphs are; the painter reads the same stored offset.
236        let offset = {
237            let sess = &mut *self.session.state();
238            self.edit.line_offset(key, inner_w * scale, &mut sess.fonts)
239        };
240        hits.push(HitRegion {
241            key,
242            origin: self.tree.origins[i],
243            rect,
244            clip,
245            turn: turn.map(Box::new),
246            // A field's corners round its hit too (ADR 0026).
247            shape: if spec.style.radius != crate::display::SQUARE {
248                crate::input::HitShape::Rounded(spec.style.radius)
249            } else {
250                crate::input::HitShape::Rect
251            },
252            payload: None,
253            drag: None,
254            parent_rect: rect,
255            // Shifted by what the field is scrolled: a click lands on
256            // the character under the pointer.
257            edit_origin: Some(Vec2::new(
258                content_origin.x - offset / scale,
259                content_origin.y,
260            )),
261            // An editor is its own selection scope: a press in it
262            // places a caret and drags a selection through the
263            // editor's own path, not the scope's.
264            select_scope: None,
265            key_sink: None,
266            key_up: false,
267            context_menu: None,
268            // A field inside a zone is the zone's: files dropped on
269            // it land there.
270            drop,
271            focusable: !spec.disabled,
272            window: None,
273            hover: None,
274            group: None,
275            click_sound: None,
276            hover_sound: None,
277            // The editor's own node carries any override.
278            cursor: spec.cursor,
279            slider: None,
280        });
281    }
282
283    /// The index in `regions` of the nearest scroll region around node
284    /// `i` in the tree, [`NIL`] for none. Ancestors are emitted before
285    /// their descendants — a float's layer comes after the one its
286    /// declaring node is in — so the one around is already in the list.
287    /// Off `emit_node`'s straight path: only a scroller pays for it.
288    #[inline(never)]
289    fn enclosing_scroll_region(&self, i: usize, regions: &[ScrollRegion]) -> u32 {
290        let mut a = self.tree.parent[i];
291        while a != NIL {
292            if let Some(r) = regions.iter().rposition(|r| r.node == a) {
293                return r as u32;
294            }
295            a = self.tree.parent[a as usize];
296        }
297        NIL
298    }
299
300    /// Emits one node's quads and registers its hit/scroll regions.
301    fn emit_node(
302        &mut self,
303        i: usize,
304        rect: Rect,
305        paint: Paint,
306        hits: &mut Vec<HitRegion>,
307        scroll_regions: &mut Vec<ScrollRegion>,
308    ) {
309        let Paint {
310            clip_rect, scale, ..
311        } = paint;
312        // The turn the node is drawn through, for its regions (ADR 0043):
313        // looked up by node, and only on a frame that turns something.
314        let turn = if self.tree.any_transform {
315            self.clips.get(i).and_then(crate::input::HitTurn::of)
316        } else {
317            None
318        };
319        // Behind a modal a node still draws, and stops taking input.
320        let interactive = self.interactive(i);
321        let spec = &self.tree.specs[i];
322        let style = spec.style;
323        // The zone this node's regions belong to — its own `on_drop` or
324        // an ancestor's — by the context menu's walk (ADR 0031, decision
325        // 2); skipped wholesale on a frame with no zone.
326        let drop = if self.tree.any_drop && interactive {
327            self.enclosing_drop(i).map(|j| crate::input::DropOwner {
328                key: self.tree.keys[j],
329                origin: self.tree.origins[j],
330                tag: self.tree.specs[j]
331                    .events()
332                    .on_drop
333                    .clone()
334                    .expect("enclosing_drop returns a node that declares one"),
335            })
336        } else {
337            None
338        };
339        // A stroke emits no hit region: it takes no input (ADR 0010,
340        // decision 7).
341        if spec.hover_tracked() && interactive {
342            self.push_hit(i, rect, clip_rect, turn, drop.clone(), hits);
343        }
344        let spec = &self.tree.specs[i];
345        // An `on_scroll` node takes the wheel the way a container does —
346        // one list, one paint-order rule (ADR 0029, decision 4).
347        let handler = self.tree.any_scroll_handler && spec.events().on_scroll.is_some();
348        if spec.layout.scroll_x || spec.layout.scroll_y || handler {
349            // A container behind a modal keeps its scrollbar drawn and
350            // refuses the wheel and the thumb.
351            let (takes_x, takes_y) = if handler {
352                let axes = spec.events().scroll_axes;
353                (axes.takes(true), axes.takes(false))
354            } else {
355                (spec.layout.scroll_x, spec.layout.scroll_y)
356            };
357            scroll_regions.push(ScrollRegion {
358                key: self.tree.keys[i],
359                node: i as u32,
360                rect,
361                clip: clip_rect,
362                turn,
363                inert: !interactive,
364                handler,
365                takes_x,
366                takes_y,
367                scrolls_x: spec.layout.scroll_x,
368                scrolls_y: spec.layout.scroll_y,
369                contain: spec.interact().overscroll == crate::spec::Overscroll::Contain,
370                mods: if handler {
371                    spec.events().scroll_mods.bits()
372                } else {
373                    0
374                },
375                parent: self.enclosing_scroll_region(i, scroll_regions),
376            });
377        }
378        if let NodeContent::Edit(key) = self.tree.content[i]
379            && interactive
380        {
381            self.push_edit_hit(i, key, rect, clip_rect, turn, scale, drop, hits);
382        }
383        // The content, resolved to what the painter needs — a text node's
384        // selection and its place, an editor's focus — then painted by the
385        // one step a ghost also paints through.
386        let leaf = match self.tree.content[i] {
387            NodeContent::Text(tid) => {
388                // The keys above it, nearest first, so a query by the
389                // `line` row (or a wrapper) finds the runs inside it.
390                let ancestry = self.text_ancestors(i);
391                self.text.place(
392                    self.tree.keys[i],
393                    &ancestry,
394                    tid,
395                    self.tree.pos[i],
396                    self.scope_of(i),
397                    true,
398                );
399                Leaf::Text {
400                    tid,
401                    sel: self.sel_range(i, tid),
402                }
403            }
404            NodeContent::Cells(cid) => Leaf::Cells {
405                cid,
406                at: self.cells_origin(i),
407                // The window's selection, when it is in this very grid.
408                sel: self
409                    .cell_selection
410                    .as_ref()
411                    .filter(|s| s.node == self.tree.keys[i] && !s.is_empty()),
412                tint: self.theme.selection,
413            },
414            NodeContent::Edit(key) => Leaf::Edit {
415                key,
416                focused: self.edit.focused() == Some(key),
417                pad: self.tree.specs[i].layout.padding,
418            },
419            NodeContent::Image(id, opts) => Leaf::Image(id, opts),
420            NodeContent::Fragment(id) => Leaf::Fragment(self.fragments.get(id)),
421            NodeContent::Polygon(id) => Leaf::Polygon(self.fragments.get(id)),
422            NodeContent::Line(id) => {
423                let (run, points) = self.lines.run(id);
424                Leaf::Line {
425                    points,
426                    width: run.width,
427                    dash: run.dash,
428                }
429            }
430            NodeContent::Path(id) => {
431                let (run, ops) = self.paths.run(id);
432                Leaf::Path {
433                    ops,
434                    rule: run.rule,
435                    stroke_w: run.stroke_w,
436                    dash: run.dash,
437                    hash: run.hash,
438                    angle: run.angle,
439                    animating: run.animating,
440                }
441            }
442            NodeContent::Container => Leaf::Container,
443        };
444        // A backdrop blur before anything the node paints — its shadow,
445        // its background — so all of it lies over the blurred picture
446        // (backlog F129). Cold, and looked for only on a frame that has one.
447        if self.tree.any_backdrop_blur {
448            let r = self.tree.specs[i].interact().backdrop_blur;
449            if r > 0.0 {
450                backdrop_quad(&mut self.display.quads, rect, &style, &paint, r);
451            }
452        }
453        let first_quad = self.display.quads.len();
454        painter!(self).paint_box(rect, &style, &paint, leaf);
455        // A gradient over the background the box just painted. Out of
456        // `emit_node` as the rules below are, and for the same reason.
457        if self.tree.any_gradient
458            && let Some(g) = &self.tree.specs[i].interact().gradient
459            // A stroke and a fill paint no box for it to lie over.
460            && !matches!(
461                self.tree.content[i],
462                NodeContent::Line(_) | NodeContent::Polygon(_) | NodeContent::Path(_)
463            )
464        {
465            painter!(self).paint_gradient(g, rect, &style, &paint, first_quad);
466        }
467        // A table's grid rules, with its box and under its cells. Out of
468        // `emit_node`: a rare path kept off its codegen (C48).
469        if self.tree.any_table
470            && let Some(c) = self.tree.specs[i].interact().rules
471            && self.tree.specs[i].layout.is_table()
472        {
473            self.emit_rules(i, rect, c, &paint);
474        }
475    }
476
477    /// The `rules` of table `i`, laid out by [`rule_lines`]
478    /// from its in-flow children as layout reads them — a row is what
479    /// `layout::is_table_row` says is one, so the grid is drawn over the
480    /// rows its columns were laid across and not through a heading or a
481    /// section beside them.
482    #[cold]
483    #[inline(never)]
484    fn emit_rules(&mut self, i: usize, rect: Rect, color: Color, paint: &Paint) {
485        let tree = &self.tree;
486        let at = |j: u32| Rect::from_pos_size(tree.pos[j as usize], tree.size[j as usize]);
487        let in_flow = |j: &u32| tree.specs[*j as usize].layout.float.is_none();
488        let children: Vec<RuledChild> = tree
489            .children(i as u32)
490            .filter(in_flow)
491            .map(|c| RuledChild {
492                rect: at(c),
493                cells: crate::layout::is_table_row(tree, c)
494                    .then(|| tree.children(c).filter(in_flow).map(at).collect()),
495            })
496            .collect();
497        let spec = &tree.specs[i];
498        let lines = rule_lines(rect, spec.layout.padding, spec.interact().rule_w, &children);
499        // The clip the table's children get: its own box when it clips or
500        // scrolls, since the rows' places carry its scroll offset and the
501        // rules drawn from them go wherever the rows do.
502        let clip_id = if spec.layout.clips() {
503            let radius = if tree.any_rounded_clip {
504                spec.style.radius
505            } else {
506                crate::display::SQUARE
507            };
508            // The logical clip the table was emitted under, by node: the
509            // painter carries only its rect (see `Paint`).
510            let inherited = self.clips.get(i).copied().unwrap_or(Clip::NONE);
511            let clip = inherited.intersect(rect, radius);
512            self.display.intern_clip(clip.scaled(paint.scale))
513        } else {
514            paint.clip_id
515        };
516        push_rules(&mut self.display, &lines, color, paint, clip_id);
517    }
518
519    /// [`Core::emit_rules`] for a departing table's ghost, node `i` of
520    /// `g` drawn at `rect`, its children `offset` from where they were:
521    /// the same rules from the children the ghost copied, under the same
522    /// clip its children get, faded with it by `paint`.
523    #[cold]
524    #[inline(never)]
525    fn emit_ghost_rules(
526        &mut self,
527        g: &Ghost,
528        i: usize,
529        rect: Rect,
530        offset: Vec2,
531        color: Color,
532        paint: &Paint,
533    ) {
534        let at = |node: &crate::depart::GhostNode| {
535            Rect::new(
536                node.rect.x + offset.x,
537                node.rect.y + offset.y,
538                node.rect.w,
539                node.rect.h,
540            )
541        };
542        // The nodes are in preorder, so a grandchild's parent is the most
543        // recent child. A departing `cells` grid, or a fragment whose draw
544        // was gone, is a `Container` here — a `row` one straight under a
545        // table would read as a row of no cells, where layout read it as
546        // no row.
547        let mut children: Vec<RuledChild> = Vec::new();
548        let mut last = NIL;
549        for (j, node) in g.nodes.iter().enumerate().skip(i + 1) {
550            // Past the table's subtree: a node whose parent precedes it.
551            if node.parent == NIL || (node.parent as usize) < i {
552                break;
553            }
554            if node.spec.layout.float.is_some() {
555                continue;
556            }
557            if node.parent as usize == i {
558                let row = crate::layout::row_shaped(
559                    &node.spec.layout,
560                    matches!(node.content, GhostContent::Container),
561                );
562                children.push(RuledChild {
563                    rect: at(node),
564                    cells: row.then(Vec::new),
565                });
566                last = j as u32;
567            } else if node.parent == last
568                && let Some(cells) = children.last_mut().and_then(|c| c.cells.as_mut())
569            {
570                cells.push(at(node));
571            }
572        }
573        let spec = &g.nodes[i].spec;
574        let lines = rule_lines(rect, spec.layout.padding, spec.interact().rule_w, &children);
575        let clip_id = if spec.layout.clips() {
576            let inherited = self.ghost_clip.get(i).copied().unwrap_or(Clip::NONE);
577            let clip = inherited.intersect(rect, spec.style.radius);
578            self.display.intern_clip(clip.scaled(paint.scale))
579        } else {
580            paint.clip_id
581        };
582        push_rules(&mut self.display, &lines, color, paint, clip_id);
583    }
584
585    /// Runs layout and emission into `output()`, and installs this frame's
586    /// hit and scroll regions for input handling. The last step of
587    /// `Ui::finish`, which runs the extension fills, the devtools panel
588    /// and the open menu first — and crate-private for that reason:
589    /// a host that called this directly got a frame where
590    /// `open_menu` drew nothing and `KUI_DEVTOOLS` did nothing, with no
591    /// warning. A driver with a bare `Core` finishes through
592    /// `Ui::wrap(core).finish()`.
593    pub(crate) fn finish_frame(&mut self) {
594        self.layout_frame();
595        self.emit_frame();
596        self.building = false;
597        self.replay_finish_frame();
598        self.submenu_frame_end();
599        // An exit named for a removal is for this frame's departures,
600        // which `emit_frame` has collected (backlog F136).
601        if !self.exits_named.is_empty() {
602            self.exits_named.clear();
603        }
604        // A focus the view moved, or a focused node the frame declared
605        // `on_focus` on or dropped (backlog DX18).
606        let mut out = std::mem::take(&mut self.pending);
607        self.report_focus("program", &mut out);
608        self.pending = out;
609        self.snapshot_nodes();
610        self.devtools_after_frame();
611        self.trace_finish_frame();
612        // Between frames the host is who talks to the core: a driver that
613        // tagged the last nodes with an extension's origin by hand (rather
614        // than through `fill`, which restores it) must not leave its
615        // `set_tokens` landing in that extension's table (ADR 0027).
616        self.origin = crate::tree::OriginId::HOST;
617    }
618
619    /// The frame's first half: layout, then everything that resolves
620    /// against it before a quad is emitted — the caret and reveal nudges,
621    /// the `layout` events and the diagnostics, the declared window set,
622    /// the modal scope and the Tab step a view asked for.
623    fn layout_frame(&mut self) {
624        // Tolerate unclosed containers (an FFI caller may have bailed early).
625        self.stack.truncate(1);
626        self.counters.truncate(1);
627
628        self.tree.host_area = self.dt_area;
629        if !self.pending_scroll_labels.is_empty() {
630            self.resolve_scroll_labels();
631        }
632        {
633            let sess = &mut *self.session.state();
634            let mut measure = Measure {
635                text: &mut self.text,
636                cells: &mut self.cells,
637                fonts: &mut sess.fonts,
638                edit: &mut self.edit,
639                resources: &sess.resources,
640            };
641            layout::compute(
642                &mut self.tree,
643                &mut measure,
644                &mut self.scroll,
645                self.viewport,
646                self.scale,
647            );
648        }
649        self.scroll_caret_into_view();
650        // An explicit `reveal` after the caret nudge: the app asked for
651        // this one, so it wins the offset if both want to move it.
652        self.apply_pending_reveal();
653        // A container a view sliced its rows by (`scroll_geometry`) that
654        // came out otherwise — taller, scrolled elsewhere — owes a frame
655        // built against this layout, or the slice stays a frame behind
656        // until the next event (`ScrollStore::resliced`).
657        if self.scroll.take_resliced() {
658            self.owe_frame("resliced");
659        }
660        if self.tree.any_slide {
661            self.ease_positions();
662        }
663        // Positions are final: report the rects views asked about, and
664        // look for the misconfigurations that would otherwise fail silently.
665        if self.tree.any_layout {
666            self.emit_layout_events();
667        }
668        self.diag
669            .check(&self.tree, &self.text, &self.edit, self.frame_no);
670        // A stop's position, once the layout events and the checks have
671        // read the layout's (backlog F132).
672        if self.tree.any_offset_stop {
673            self.offset_stops();
674        }
675        // Text set for a key nothing had declared yet was held for this
676        // frame (backlog F25). What it declared has taken its seed; what
677        // is left named an editor no view draws, so drop it and say so.
678        // Drained whatever `diag.enabled` says, so the gate changes what
679        // is reported and never what is retained.
680        for seed in self.edit.take_unclaimed_seeds() {
681            self.diag.raise(match seed {
682                crate::edit::Unclaimed::Key(key) => crate::diag::edit_text_without_editor(key),
683                crate::edit::Unclaimed::Label(label) => {
684                    crate::diag::edit_text_without_editor_label(&label)
685                }
686            });
687        }
688        // The declared window set, diffed against the session's: a frame
689        // that declared a new name queues its `Open` here.
690        self.sync_windows();
691        // The frame's modal scope, and the focus it moves: emission reads
692        // it (everything outside is inert) and so does the Tab ring.
693        self.modal = if self.tree.any_modal {
694            self.modal_scope()
695        } else {
696            None
697        };
698        self.resolve_modal_focus();
699        // Then the regions: a `focus_region` asked for during the build,
700        // the region following a focus the build declared, and a region
701        // that went away handing focus back (`docs/adr/0022`).
702        self.resolve_regions();
703        // The ring exists now: laid out, and scoped to the modal if there
704        // is one, else to the region in effect. A step asked for during
705        // the build lands here, so it wins over both the modal's own focus
706        // move and a same-frame `set_focus`. Like a real Tab press, the
707        // scroll it triggers shows on the next frame.
708        if let Some(forward) = self.pending_focus_step.take() {
709            self.focus_next(forward);
710        }
711    }
712
713    /// Numbers the text nodes of the selection's scope in tree order and
714    /// resolves the two ends against those ordinals. Run once per frame,
715    /// after the scope map and before emission, because a run's range has
716    /// to be known when the run is drawn and its *offset* cannot be —
717    /// the runs after it have not been placed yet, and an end may be one
718    /// of them.
719    fn resolve_selection(&mut self) {
720        self.sel_ords.clear();
721        self.sel_ends = None;
722        let Some(sel) = self.selection else { return };
723        self.sel_ords.resize(self.tree.len(), u32::MAX);
724        let (mut anchor, mut focus) = (None, None);
725        // The built runs, in order, with the virtualised row each is in:
726        // what an end whose own node is *not* built is placed against.
727        let mut built: Vec<(u32, Option<u64>, usize)> = Vec::new();
728        let mut ord = 0u32;
729        for i in 0..self.tree.len() {
730            if self.scopes.get(i).copied().flatten() != Some(sel.scope)
731                || !matches!(self.tree.content[i], NodeContent::Text(_))
732            {
733                continue;
734            }
735            self.sel_ords[i] = ord;
736            let key = self.tree.keys[i];
737            let len = match self.tree.content[i] {
738                NodeContent::Text(tid) => self.text.content_len(tid),
739                _ => 0,
740            };
741            built.push((ord, self.rows.get(i).copied().flatten(), len));
742            if key == sel.anchor.node {
743                anchor = Some((ord, sel.anchor.byte));
744            }
745            if key == sel.focus.node {
746                focus = Some((ord, sel.focus.byte));
747            }
748            ord += 1;
749        }
750        // An end this frame did not build is placed by its row's index in
751        // the data: before everything built, after it, or at the boundary
752        // it falls on. That is what lets the built middle paint while a
753        // virtual list scrolls under a selection (ADR 0017, tier 3).
754        let place = |end: &crate::select::Endpoint| -> Option<(u32, usize)> {
755            let row = end.row?;
756            let (start, last) = (built.first()?, built.last()?);
757            // The row itself is built, on runs no end's key names: a Select
758            // All's placeholder end (`select_all_in` puts it on the scope
759            // with the row's index and `ROW_END`) after the list scrolled
760            // that row into the built window. It lands in that row's own
761            // runs — the end of its last one, or the byte into its first —
762            // rather than at the boundary an unbuilt row would take.
763            let mut in_row = built.iter().filter(|(_, r, _)| *r == Some(row));
764            if let Some(first_run) = in_row.next() {
765                return Some(if end.byte >= crate::select::ROW_END {
766                    let last_run = in_row.next_back().unwrap_or(first_run);
767                    (last_run.0, last_run.2)
768                } else {
769                    (first_run.0, end.byte.min(first_run.2))
770                });
771            }
772            // Against the built runs that *carry* a row, not the first and
773            // last of everything built: a scope can hold plain labels
774            // beside virtual rows — a header, a footer — and a label says
775            // nothing about where a row sits in the data. Comparing
776            // against one puts an end below the list at the top of it.
777            let hi = built.iter().rev().find_map(|(_, r, _)| *r)?;
778            if crate::select::unbuilt_row_is_after(row, Some(hi)) {
779                return Some((last.0, last.2));
780            }
781            // Below the first row, or inside the built range without being
782            // built — a hole, which a contiguous virtual window does not
783            // have. Either way the start is the nearest honest boundary.
784            Some((start.0, 0))
785        };
786        let anchor = anchor.or_else(|| place(&sel.anchor));
787        let focus = focus.or_else(|| place(&sel.focus));
788        if let (Some(a), Some(f)) = (anchor, focus) {
789            self.sel_ends = Some(crate::select::Ends::ordered(a, f));
790        }
791    }
792
793    /// The bytes of node `i`'s text the selection covers, with the colour
794    /// to paint under them. `None` on every node of every frame that has
795    /// no selection.
796    fn sel_range(&self, i: usize, tid: crate::tree::TextId) -> Option<((usize, usize), Color)> {
797        let ends = self.sel_ends?;
798        let ord = self.sel_ords.get(i).copied()?;
799        if ord == u32::MAX {
800            return None;
801        }
802        let range = ends.range_in(ord, self.text.content_len(tid))?;
803        Some((range, self.theme().selection))
804    }
805
806    /// The innermost selection scope node `i` is inside, if any. Empty on
807    /// every frame that declares no `selectable` at all, where the map is
808    /// not even sized.
809    #[inline]
810    fn scope_of(&self, i: usize) -> Option<Key> {
811        self.scopes.get(i).copied().flatten()
812    }
813
814    /// The keys above node `i`, nearest first, as many as a `TextPlace`
815    /// remembers — what lets a query by a `line` row or a wrapper find
816    /// the runs inside it.
817    /// The keys above text node `i`, nearest first, as many as a place
818    /// remembers; how many there are; and the depth of the nearest
819    /// `role="none"` ancestor among them, which a query from above it
820    /// does not reach. A `line` row further up than the
821    /// place can remember raises `text-beyond-line`, once per text.
822    fn text_ancestors(&mut self, i: usize) -> crate::text::Ancestry {
823        use crate::access::Role;
824        let mut ancestors = [Key::ROOT; crate::text::PLACE_ANCESTORS];
825        let mut depth = 0;
826        let mut none_at = None;
827        let mut p = self.tree.parent[i];
828        while p != NIL && depth < ancestors.len() {
829            let j = p as usize;
830            ancestors[depth] = self.tree.keys[j];
831            if none_at.is_none() && self.tree.specs[j].access().role == Some(Role::None) {
832                none_at = Some(depth);
833            }
834            depth += 1;
835            p = self.tree.parent[j];
836        }
837        // Past the reach: a `line` row still above is one the text cannot
838        // be found from, and the app should hear it.
839        if p != NIL && self.tree.any_line {
840            let mut q = p;
841            while q != NIL {
842                let j = q as usize;
843                if self.tree.specs[j].access().role == Some(Role::Line) {
844                    self.diag.raise(crate::diag::text_beyond_line(
845                        self.tree.keys[i],
846                        self.tree.keys[j],
847                        crate::text::PLACE_ANCESTORS,
848                    ));
849                    break;
850                }
851                q = self.tree.parent[j];
852            }
853        }
854        crate::text::Ancestry {
855            keys: ancestors,
856            depth,
857            none_at,
858        }
859    }
860
861    /// The frame's second half: the laid-out tree into the display list,
862    /// in paint order — the in-flow layer, then one layer per floating
863    /// subtree in the order they opened, each with the departed subtrees
864    /// that were painted among it and its own chrome (scrollbars, the
865    /// ring) at its end — and the hit and scroll regions the
866    /// next input is tested against, in the same order.
867    fn emit_frame(&mut self) {
868        let scale = self.scale;
869        let mut hits: Vec<HitRegion> = self.interaction.take_hit_buffer();
870        self.hit_shapes = self.interaction.take_shape_buffer();
871        let mut scroll_regions: Vec<ScrollRegion> = Vec::new();
872        self.display.viewport = Size::new(self.viewport.w * scale, self.viewport.h * scale);
873        self.display.scale = scale;
874        self.display.time = self.anim.time().unwrap_or(0.0) as f32;
875
876        // Read once each: what the frame declared, noted by `Tree::push`
877        // (and by `configure_root`, whose spec replaces the root's). A
878        // turn rides on the clip entry (ADR 0043), so a frame with one
879        // tracks the per-node clip as a frame with a clipper does.
880        let any_transform = self.tree.any_transform;
881        let any_clip = self.tree.any_clip || any_transform;
882        let any_rounded_clip = self.tree.any_rounded_clip;
883        let any_opacity = self.tree.any_opacity;
884        let any_float = self.tree.any_float;
885        // Read once: every per-node selection check below is behind it.
886        let any_selectable = self.tree.any_selectable;
887
888        // inherited clip per node (logical): ancestors only, not the node
889        // itself. Only materialized when something actually clips.
890        // Index 0 is the clip that clips nothing, so an unclipped frame
891        // interns once and every quad on it names entry zero. Seeded
892        // rather than found, so `clip_of` has something to answer with
893        // even on a frame that emitted no quad at all.
894        let no_clip = self.display.intern_clip(Clip::NONE.scaled(scale));
895        // Filled in tree order by the walk below, one push per node: every
896        // node writes its entry and a parent's is written before its
897        // children read it, so a fill of "clips nothing" first would only
898        // be overwritten — eighty bytes a node since ADR 0043, which a
899        // scrolling list's short frame measured.
900        self.clips.clear();
901        self.clip_ids.clear();
902        if any_clip {
903            self.clips.reserve(self.tree.len());
904            self.clip_ids.reserve(self.tree.len());
905        }
906        self.opacity.clear();
907        if any_opacity {
908            self.opacity.resize(self.tree.len(), 1.0);
909        }
910        self.float_root.clear();
911        if any_float {
912            self.float_root.resize(self.tree.len(), NIL);
913        }
914        // The innermost `selectable` above each node (ADR 0017). Parents
915        // precede their children in the tree array, so one forward pass
916        // inherits it; a node declaring `selectable` inside another scope
917        // takes the text under it and is warned about, because two scopes
918        // over one run would each think they own it.
919        self.scopes.clear();
920        self.rows.clear();
921        if any_selectable {
922            self.scopes.resize(self.tree.len(), None);
923            self.rows.resize(self.tree.len(), None);
924            // The rows a virtual list built, by node, so the walk below
925            // can carry each one down to the text inside it.
926            for &(node, index) in &self.tree.indexed {
927                if let Some(slot) = self.rows.get_mut(node as usize) {
928                    *slot = Some(index);
929                }
930            }
931            for i in 0..self.tree.len() {
932                let parent = self.tree.parent[i];
933                // A floating subtree escapes the scope it floats out of,
934                // the way it escapes the clip: a popover over a card is
935                // not part of the card's paragraph, and a float is
936                // emitted in a later pass than its tree position, which
937                // would put its runs out of reading order anyway.
938                let outer = if parent == NIL || self.tree.specs[i].layout.float.is_some() {
939                    None
940                } else {
941                    self.scopes[parent as usize]
942                };
943                // An inner scope takes the text under it; the nesting
944                // itself is reported by `diag`, over the finished tree.
945                //
946                // A `cells` grid is its own scope and never joins the one
947                // around it: it selects in cells, and a selection that ran
948                // from a paragraph into a terminal screen would be two
949                // kinds of selection at once (ADR 0017, decision 4).
950                let grid = matches!(self.tree.content[i], NodeContent::Cells(_));
951                self.scopes[i] = if self.tree.specs[i].interact().selectable {
952                    Some(self.tree.keys[i])
953                } else if grid {
954                    None
955                } else {
956                    outer
957                };
958                // A row's index reaches the text inside it: the node that
959                // declared it keeps its own, everything under it inherits.
960                if self.rows[i].is_none() && parent != NIL {
961                    self.rows[i] = self.rows[parent as usize];
962                }
963            }
964        }
965        self.resolve_selection();
966
967        // Exits: what the previous frame declared and this one does not is
968        // copied out of the tree the previous frame left behind, and every
969        // departing subtree still in flight is taken out for the passes,
970        // which paint each one where its node was (see `depart`).
971        if !self.prev_tree.is_empty() || !self.depart.is_empty() {
972            self.collect_departures();
973        }
974        let mut replay = Replay::default();
975        let mut took_ghosts = false;
976        if !self.depart.is_empty()
977            && let Some(now) = self.anim.time()
978        {
979            replay = self.depart.begin_replay(now);
980            took_ghosts = true;
981        }
982        let any_ghost = !replay.is_empty();
983
984        // Pass 1: clip/float propagation + in-flow emission (preorder =
985        // paint order; parents precede children). `float_root[i]` is the
986        // nearest layer-opening ancestor-or-self, `NIL` in flow: the layer
987        // a node paints in (ADR 0023, decision 1). Every layer root goes
988        // into `roots`, in tree order, for the stack to sort. A `line`,
989        // `polygon` or `path` in its parent's box space floats without
990        // opening a layer (`Tree::opens_layer`, F123): it is the parent's
991        // content, painted at its place in the tree and held by the
992        // parent's clip, as a child is.
993        let mut roots: Vec<u32> = Vec::new();
994        // The last clipper whose children were cut, and the child whose
995        // entry in `self.clips` is the clip it cuts them by: a one-entry
996        // cache, since a clipper's children come one after another between
997        // their own subtrees. Two indices and not the clip, which kept
998        // ninety-six bytes live across every iteration of a walk that
999        // never clips (`deep_nesting_64_levels` +3% when it did).
1000        let mut clipped_by: (u32, u32) = (NIL, NIL);
1001        for i in 0..self.tree.len() {
1002            let parent = self.tree.parent[i];
1003            let floats_here = any_float && self.tree.opens_layer(i);
1004            if any_float {
1005                self.float_root[i] = if floats_here {
1006                    roots.push(i as u32);
1007                    i as u32
1008                } else if parent != NIL {
1009                    self.float_root[parent as usize]
1010                } else {
1011                    NIL
1012                };
1013            }
1014            let rect = Rect::from_pos_size(self.tree.pos[i], self.tree.size[i]);
1015            // Opacity multiplies down the tree, floats included: a tooltip
1016            // inside a fading panel fades with it.
1017            let opacity = if !any_opacity {
1018                1.0
1019            } else {
1020                let inherited = if parent == NIL {
1021                    1.0
1022                } else {
1023                    self.opacity[parent as usize]
1024                };
1025                let o = inherited * self.tree.specs[i].style.opacity;
1026                self.opacity[i] = o;
1027                o
1028            };
1029            // A parent-anchored float that declared `clip` belongs to the
1030            // parent's content as a child does, so the parent's clip holds
1031            // it: a node on a `clip` canvas panned past the canvas's edge
1032            // is cut there (F90). Any other float (a tooltip, a menu, a
1033            // stroke anchored to the viewport) escapes. Only the clip is
1034            // the parent's: a declared float still paints in its own
1035            // layer. A stroke or polygon in its parent's box, which the
1036            // core gives the bit (F78, ADR 0010 decision 5), is not a
1037            // layer root at all (above), so it takes the parent's clip
1038            // here by the in-flow arm, as its graph's rows do.
1039            let drawn_in_parent = floats_here
1040                && parent != NIL
1041                && self.tree.specs[i]
1042                    .layout
1043                    .float
1044                    .is_some_and(|f| f.clipped_by_parent());
1045            // What the walk carries on: the clip's rect in framebuffer space
1046            // (what the node's regions are cut by), the rect it is culled
1047            // against in its own space, and the interned id. The whole clip
1048            // — eighty bytes since ADR 0043 — stays in `self.clips`: a value
1049            // that size built per node cost a frame of 10,000 boxes 2% when
1050            // this walk carried it, on frames that clip and turn nothing.
1051            let (clip_rect, cull_rect, clip_id) = if !any_clip {
1052                (crate::display::NO_CLIP, crate::display::NO_CLIP, no_clip)
1053            } else {
1054                // Floating nodes escape ancestor clips. One anchored to
1055                // its parent keeps the parent's turn, as the parent's
1056                // content does (ADR 0043, decision 3); a viewport float
1057                // and a node-anchored one do not.
1058                let (mut clip, mut id) = if parent == NIL {
1059                    (Clip::NONE, no_clip)
1060                } else if floats_here && !drawn_in_parent {
1061                    let p = parent as usize;
1062                    let turned = any_transform
1063                        && self.clips[p].turned()
1064                        && self.tree.specs[i]
1065                            .layout
1066                            .float
1067                            .is_some_and(|f| f.anchor == crate::spec::FloatAnchor::Parent);
1068                    if turned {
1069                        let c = Clip {
1070                            transform: self.clips[p].transform,
1071                            ..Clip::NONE
1072                        };
1073                        (c, self.display.intern_clip(c.scaled(scale)))
1074                    } else {
1075                        (Clip::NONE, no_clip)
1076                    }
1077                } else {
1078                    let p = parent as usize;
1079                    if self.tree.specs[p].layout.clips() {
1080                        match clipped_by {
1081                            // A sibling already asked: every child of one
1082                            // clipper is cut by the same clip, so the rows
1083                            // of a list intersect and intern it once
1084                            // rather than once each.
1085                            (q, j) if q == p as u32 => {
1086                                (self.clips[j as usize], self.clip_ids[j as usize])
1087                            }
1088                            _ => {
1089                                // A clipper with a radius rounds what it
1090                                // clips, so the children of a rounded card
1091                                // stay inside its corners (see
1092                                // `display::Clip`).
1093                                let box_rect =
1094                                    Rect::from_pos_size(self.tree.pos[p], self.tree.size[p]);
1095                                let box_radius = if any_rounded_clip {
1096                                    self.tree.specs[p].style.radius
1097                                } else {
1098                                    crate::display::SQUARE
1099                                };
1100                                let clip = self.clips[p].intersect(box_rect, box_radius);
1101                                let id = self.display.intern_clip(clip.scaled(scale));
1102                                clipped_by = (p as u32, i as u32);
1103                                (clip, id)
1104                            }
1105                        }
1106                    } else {
1107                        // The overwhelming case: the clip is the parent's,
1108                        // so the entry is too, and nothing is compared.
1109                        (self.clips[p], self.clip_ids[p])
1110                    }
1111                };
1112                // The node's own turn enters a new space for everything
1113                // it draws and holds (ADR 0043, decision 4).
1114                if any_transform
1115                    && let Some(tr) = self.tree.specs[i].transform_spec()
1116                    && tr.active()
1117                {
1118                    clip = clip.turned_by(tr.at(rect));
1119                    id = self.display.intern_clip(clip.scaled(scale));
1120                    // Its entry is its own turned space now, not its
1121                    // clipper's clip: the next sibling asks again.
1122                    if clipped_by.1 == i as u32 {
1123                        clipped_by = (NIL, NIL);
1124                    }
1125                }
1126                debug_assert_eq!(self.clips.len(), i, "one entry per node, in order");
1127                self.clips.push(clip);
1128                self.clip_ids.push(id);
1129                // Under a turn the cull is in the node's own space.
1130                let cull = if any_transform {
1131                    clip.visible()
1132                } else {
1133                    clip.rect
1134                };
1135                (clip.rect, cull, id)
1136            };
1137            if any_float && self.float_root[i] != NIL {
1138                continue; // deferred to its layer, in the float pass
1139            }
1140            // A departing subtree painted just under this node last time
1141            // goes first, so it stays under it.
1142            if any_ghost && replay.may_precede(self.tree.keys[i]) {
1143                let key = self.tree.keys[i];
1144                replay.paint(At::UnderInFlow(key), |g, play| {
1145                    self.emit_ghost(g, play, scale)
1146                });
1147            }
1148            // Entirely clipped away: skip drawing and hit-testing.
1149            // Rect, not rounded: a node that survives only in a corner's
1150            // arc is drawn and clipped rather than culled. Under a turn,
1151            // by the clip pulled back into the node's space (`cull_rect`).
1152            let visible = rect.intersect(&cull_rect);
1153            if visible.w <= 0.0 || visible.h <= 0.0 {
1154                // Culled — but a text run inside a selection scope keeps
1155                // its place in the order and its content reachable, so a
1156                // selection can run past the edge of a scroller (ADR
1157                // 0017, tier 2). Marked undrawn: no hit region, no
1158                // `text_hit`, nothing a pointer can find.
1159                //
1160                // Behind the frame's own flag, hoisted out of the loop:
1161                // a frame that declares no scope does not pay a lookup
1162                // per culled node to find that out (C15).
1163                if any_selectable
1164                    && let Some(scope) = self.scope_of(i)
1165                    && let NodeContent::Text(tid) = self.tree.content[i]
1166                {
1167                    let ancestry = self.text_ancestors(i);
1168                    self.text.place(
1169                        self.tree.keys[i],
1170                        &ancestry,
1171                        tid,
1172                        self.tree.pos[i],
1173                        Some(scope),
1174                        false,
1175                    );
1176                }
1177                continue;
1178            }
1179            let paint = Paint {
1180                clip_rect,
1181                clip_id,
1182                scale,
1183                opacity,
1184            };
1185            self.emit_node(i, rect, paint, &mut hits, &mut scroll_regions);
1186        }
1187
1188        if any_ghost {
1189            // The in-flow ghosts whose place is gone: the end of their
1190            // layer, still under its chrome and under every float.
1191            replay.paint(At::InFlowEnd, |g, play| self.emit_ghost(g, play, scale));
1192        }
1193
1194        // The in-flow layer's chrome — its scrollers' bars and, if the
1195        // focused node is in flow, the ring — above its content and under
1196        // every float (ADR 0023, decision 2).
1197        let mut scrollbars: Vec<ScrollbarRegion> = Vec::new();
1198        let mut chrome_from = 0usize;
1199        self.emit_layer_chrome(
1200            NIL,
1201            &scroll_regions[chrome_from..],
1202            &mut scrollbars,
1203            hits.len(),
1204            scale,
1205        );
1206        chrome_from = scroll_regions.len();
1207
1208        // Pass 2: the float layers, bottom to top in the order they opened
1209        // (ADR 0023, decision 3); each one's chrome at its end. Their hit
1210        // regions land in the same order, so `hit_at` reads the stack.
1211        if any_float {
1212            let order = self.stack_floats(&roots);
1213            for &r in &order {
1214                let root = r as usize;
1215                let root_key = self.tree.keys[root];
1216                if any_ghost && replay.may_precede(root_key) {
1217                    // A departed float that was under this one stays under
1218                    // it: a whole layer, painted before this layer starts.
1219                    replay.paint(At::UnderLayer(root_key), |g, play| {
1220                        self.emit_ghost(g, play, scale)
1221                    });
1222                }
1223                let end = self.tree.subtree_end(root);
1224                for i in root..end {
1225                    if self.float_root[i] != r {
1226                        continue; // a nested float: its own layer, later
1227                    }
1228                    if any_ghost && replay.may_precede(self.tree.keys[i]) {
1229                        let key = self.tree.keys[i];
1230                        replay.paint(At::UnderInLayer(key), |g, play| {
1231                            self.emit_ghost(g, play, scale)
1232                        });
1233                    }
1234                    let rect = Rect::from_pos_size(self.tree.pos[i], self.tree.size[i]);
1235                    let (clip_rect, cull_rect) = match self.clips.get(i) {
1236                        Some(c) if any_clip => {
1237                            (c.rect, if any_transform { c.visible() } else { c.rect })
1238                        }
1239                        _ => (crate::display::NO_CLIP, crate::display::NO_CLIP),
1240                    };
1241                    let clip_id = if any_clip { self.clip_ids[i] } else { no_clip };
1242                    let opacity = if any_opacity { self.opacity[i] } else { 1.0 };
1243                    let visible = rect.intersect(&cull_rect);
1244                    if visible.w <= 0.0 || visible.h <= 0.0 {
1245                        continue;
1246                    }
1247                    let paint = Paint {
1248                        clip_rect,
1249                        clip_id,
1250                        scale,
1251                        opacity,
1252                    };
1253                    self.emit_node(i, rect, paint, &mut hits, &mut scroll_regions);
1254                }
1255                if any_ghost {
1256                    replay.paint(At::LayerEnd(root_key), |g, play| {
1257                        self.emit_ghost(g, play, scale)
1258                    });
1259                }
1260                // A layer with no scroller and no ring to draw has no
1261                // chrome: the common float is a leaf, and ten thousand of
1262                // them (a `line` each) pay a call apiece otherwise (C29).
1263                if scroll_regions.len() > chrome_from || self.focus_visible {
1264                    self.emit_layer_chrome(
1265                        r,
1266                        &scroll_regions[chrome_from..],
1267                        &mut scrollbars,
1268                        hits.len(),
1269                        scale,
1270                    );
1271                    chrome_from = scroll_regions.len();
1272                }
1273            }
1274            self.check_layers_over_modal(&order);
1275        } else if !self.float_stack.is_empty() {
1276            // No floats this frame: every layer closed.
1277            self.float_stack.clear();
1278        }
1279
1280        if any_ghost {
1281            // A ghost whose whole layer is gone: on top, the only place
1282            // left that is under nothing it was under.
1283            replay.paint(At::Top, |g, play| self.emit_ghost(g, play, scale));
1284        }
1285        if took_ghosts {
1286            self.depart.end_replay(replay);
1287        }
1288
1289        // Rounded span backgrounds, joined into one shape with the ones
1290        // they meet now that every text is painted (backlog F101).
1291        let joins = self.text.take_joins();
1292        if !joins.is_empty() {
1293            let sess = &mut *self.session.state();
1294            let id = sess.resources.add_fragment(crate::fragment::JOIN);
1295            if let Some(source) = sess.resources.fragment(id).cloned() {
1296                crate::join::shape(&mut self.display, &joins, id, &source, scale);
1297            }
1298        }
1299
1300        let shapes = std::mem::take(&mut self.hit_shapes);
1301        self.interaction.set_hits_shaped(hits, shapes);
1302        // A button held on a node this frame no longer declares has no one
1303        // to hear its release (backlog F105).
1304        let tree = &self.tree;
1305        self.interaction
1306            .drop_gone_buttons(|key| tree.index_of(key).is_some());
1307        // A new frame can move a hover-sound node under a still cursor.
1308        self.flush_sound_requests();
1309        // Against this window's mounts only (AR7): a popup or a second
1310        // window finishing a frame with no `<audio>` in it says nothing
1311        // about the main window's loop.
1312        let window = self.env.window.id;
1313        self.session.state().audio.reconcile(window);
1314        self.interaction.scroll_regions = scroll_regions;
1315        self.interaction.scrollbars = scrollbars;
1316        self.ime_rect = self.focused_caret_rect();
1317        self.note_sink_caret();
1318        self.atlas.end_frame();
1319        // The atlas refused a glyph for room this frame rather than drop
1320        // a slot the frame had already used (F99): the next frame starts
1321        // on an empty page and draws it, and has to come — an
1322        // input-driven app would keep the short frame until the next
1323        // event. A page that only grew is right as it is presented.
1324        if self.atlas.short() {
1325            self.owe_frame("atlas full");
1326        }
1327        // A long line's rows came out other than layout's once emission
1328        // shaped what shows (backlog RG70): the frame laid out on them is
1329        // owed, or an idle view keeps the estimate's box.
1330        if self.text.take_owed() {
1331            self.owe_frame("long line rows");
1332        }
1333    }
1334
1335    /// The exit diff: every key the previous frame declared an `exit` on
1336    /// and this frame does not becomes a departing subtree, copied out of
1337    /// `prev_tree` — the frame that still had it — and handed to the store
1338    /// with the place it painted in, so its ghost keeps it.
1339    /// A ghost whose key came back is retired here too: the live node wins.
1340    ///
1341    /// Only two kinds of key are interesting (the previous frame's
1342    /// exit-declaring roots, and the roots already departing), and both are
1343    /// few, so the walk over *this* frame's keys — the part that scales
1344    /// with the frame — is one AND against a 64-bit membership mask per
1345    /// node, and a hash lookup only for the handful that collide with it.
1346    fn collect_departures(&mut self) {
1347        let Some(now) = self.anim.time() else {
1348            // No clock: every transition snaps, and an exit that snaps is
1349            // the plain disappearance it has always been.
1350            self.depart.clear();
1351            return;
1352        };
1353        // The steady state: the view declared the same nodes in the same
1354        // order, so nothing left and nothing came back. Two flat arrays of
1355        // u64 compared is cheaper than anything that looks at the keys one
1356        // at a time, and it is the case almost every frame is.
1357        if self.prev_tree.keys == self.tree.keys {
1358            return;
1359        }
1360        let mut watch: FxHashSet<Key> = FxHashSet::default();
1361        let mut mask = 0u64;
1362        for k in self.depart.keys() {
1363            watch.insert(k);
1364            mask |= 1u64 << (k.0 & 63);
1365        }
1366        let mut candidates: Vec<usize> = Vec::new();
1367        for i in 0..self.prev_tree.len() {
1368            if crate::depart::can_depart(&self.prev_tree.specs[i]) {
1369                candidates.push(i);
1370                // The node, and its parent: an exit plays only where the
1371                // parent is still declared (backlog DX19), so the diff has
1372                // to know about that key too.
1373                let p = self.prev_tree.parent[i];
1374                let keys = [
1375                    Some(self.prev_tree.keys[i]),
1376                    (p != NIL).then(|| self.prev_tree.keys[p as usize]),
1377                ];
1378                for k in keys.into_iter().flatten() {
1379                    watch.insert(k);
1380                    mask |= 1u64 << (k.0 & 63);
1381                }
1382            }
1383        }
1384        if watch.is_empty() {
1385            return;
1386        }
1387        let mut live: FxHashSet<Key> = FxHashSet::default();
1388        for &k in &self.tree.keys {
1389            if mask & (1u64 << (k.0 & 63)) != 0 && watch.contains(&k) {
1390                live.insert(k);
1391            }
1392        }
1393        self.depart.retire_returned(&live);
1394        // The frame's removal, whole, before any of it is copied: the roots
1395        // that actually left, in tree order so a departing subtree swallows
1396        // the exits nested inside it rather than drawing them a second time
1397        // on top, and how many nodes they come to together.
1398        let mut roots: Vec<usize> = Vec::new();
1399        let mut wanted = 0usize;
1400        let mut swallowed_until = 0usize;
1401        for i in candidates {
1402            if i < swallowed_until || live.contains(&self.prev_tree.keys[i]) {
1403                continue;
1404            }
1405            // Its parent went too, and the parent declared no exit that
1406            // would have carried it (it would have swallowed it above): the
1407            // node went with its ancestor, not on its own, and plays nothing
1408            // — a tab switched away does not fade out every column that
1409            // fades when it closes (backlog DX19). CSS removes the subtree;
1410            // React's `AnimatePresence` plays the exits of its direct
1411            // children only. This is that rule.
1412            let p = self.prev_tree.parent[i];
1413            if p != NIL && !live.contains(&self.prev_tree.keys[p as usize]) {
1414                continue;
1415            }
1416            swallowed_until = self.prev_tree.subtree_end(i);
1417            wanted += swallowed_until - i;
1418            roots.push(i);
1419        }
1420        if roots.is_empty() {
1421            return;
1422        }
1423        // ADR 0012, decisions 2 and 3: the removal animates whole or not at
1424        // all, and takes the room it needs from the oldest ghosts in flight
1425        // before it is refused. Refused means every node of it vanishes at
1426        // once — what a node with no `exit` does — and one warning for the
1427        // frame, keyed by its first departing root, says how much did.
1428        if !self.depart.admit(wanted) {
1429            self.diag.raise(Warning {
1430                code: crate::diag::EXIT_BUDGET,
1431                key: self.prev_tree.keys[roots[0]],
1432                message: format!(
1433                    "this frame removed {wanted} nodes declaring `exit` and the exit store \
1434                     holds {}, so none of that removal animated: every departing node \
1435                     vanished at once, as a node with no `exit` does; `exit` is per node, \
1436                     and a list that drops many rows at once wants it on the list, not on \
1437                     every row",
1438                    crate::depart::MAX_NODES
1439                ),
1440            });
1441            return;
1442        }
1443        // The previous frame's paint order, built on the first departure:
1444        // a frame with one is a frame that changed shape and paid for a
1445        // layout, and the frames that did not never get here.
1446        let mut order: Option<PaintOrder> = None;
1447        for &i in &roots {
1448            let place = order
1449                .get_or_insert_with(|| PaintOrder::of(&self.prev_tree, &self.tree))
1450                .place(&self.prev_tree, i, &self.float_stack);
1451            // The group opacity the root inherited from ancestors that are
1452            // now gone: a subtree already half-faded departs from there.
1453            let mut base = 1.0;
1454            let mut a = self.prev_tree.parent[i];
1455            while a != NIL {
1456                base *= self.prev_tree.specs[a as usize].style.opacity;
1457                a = self.prev_tree.parent[a as usize];
1458            }
1459            let exit_with = self.exits_named.get(&self.prev_tree.keys[i]).copied();
1460            self.depart.depart(
1461                &self.prev_tree,
1462                i,
1463                now,
1464                base,
1465                place,
1466                &self.text,
1467                &self.lines,
1468                &self.fragments,
1469                &self.paths,
1470                exit_with,
1471            );
1472        }
1473        // Named now, while a tree still has them (backlog F111).
1474        self.trace_departures(&roots);
1475    }
1476
1477    /// One departing subtree's quads: frozen rects moved by however far
1478    /// its `exit` has got, outside every clip (its ancestors may be gone).
1479    /// A smaller `emit_node`: the parts a picture has (shadow, background,
1480    /// border, its content) and none of the parts a node has — no hit
1481    /// region, no scroll region, no access row.
1482    fn emit_ghost(&mut self, g: &Ghost, play: &Playback, scale: f32) {
1483        // Whole physical pixels, for the reason a slide's is: a ghost is
1484        // mostly text, and it moves for its whole life.
1485        let offset = play.offset.snapped(scale);
1486        self.ghost_opacity.clear();
1487        self.ghost_opacity.resize(g.nodes.len(), 1.0);
1488        self.ghost_clip.clear();
1489        self.ghost_clip.resize(g.nodes.len(), Clip::NONE);
1490        self.ghost_clip_ids.clear();
1491        self.ghost_clip_ids.resize(g.nodes.len(), NO_CLIP_ID);
1492        self.ghost_rect.clear();
1493        self.ghost_rect
1494            .resize(g.nodes.len(), Rect::new(0.0, 0.0, 0.0, 0.0));
1495        for (i, node) in g.nodes.iter().enumerate() {
1496            let mut rect = Rect::new(
1497                node.rect.x + offset.x,
1498                node.rect.y + offset.y,
1499                node.rect.w,
1500                node.rect.h,
1501            );
1502            let mut style = node.spec.style;
1503            let inherited = if node.parent == NIL {
1504                // The root carries the eased slots; an `exit` says nothing
1505                // about the subtree under it, which fades and moves with
1506                // its root and no more.
1507                if let Some(bg) = play.bg {
1508                    style.bg = bg;
1509                }
1510                if let Some(radius) = play.radius {
1511                    style.radius = radius;
1512                }
1513                if let Some((w, h)) = play.size {
1514                    // The root's own box only: the subtree inside it is a
1515                    // picture, and re-laying it out is the one thing a
1516                    // frozen ghost must not do.
1517                    rect.w = w.unwrap_or(rect.w);
1518                    rect.h = h.unwrap_or(rect.h);
1519                }
1520                style.opacity = play.opacity;
1521                play.base_opacity
1522            } else {
1523                self.ghost_opacity[node.parent as usize]
1524            };
1525            let opacity = (inherited * style.opacity).clamp(0.0, 1.0);
1526            self.ghost_opacity[i] = opacity;
1527            // The clip is the subtree's own: a scroll box or `clip` node
1528            // inside the picture still bounds what it held (the rows a
1529            // virtual list built past its edge stay past it), while the
1530            // ancestors outside the picture, which may be gone, clip
1531            // nothing. Same rule as the live pass, from the root down —
1532            // a parent-anchored float with `clip`, a stroke or polygon
1533            // included, is held by the parent's clip as a child is (F78,
1534            // F90; the ghost pass kept the old escape, RG26).
1535            let escapes = node
1536                .spec
1537                .layout
1538                .float
1539                .is_some_and(|f| !f.clipped_by_parent());
1540            let (mut clip, mut clip_id) = if node.parent == NIL || escapes {
1541                (Clip::NONE, NO_CLIP_ID)
1542            } else {
1543                let p = node.parent as usize;
1544                let inherited = self.ghost_clip[p];
1545                if g.nodes[p].spec.layout.clips() {
1546                    let clip =
1547                        inherited.intersect(self.ghost_rect[p], g.nodes[p].spec.style.radius);
1548                    (clip, self.display.intern_clip(clip.scaled(scale)))
1549                } else {
1550                    (inherited, self.ghost_clip_ids[p])
1551                }
1552            };
1553            // A ghost keeps its turn (ADR 0043, decision 9): each node's
1554            // own, and the root's eased toward the exit's.
1555            let own = if node.parent == NIL {
1556                play.transform
1557                    .map(|(rotate, scale)| crate::spec::TransformSpec {
1558                        rotate,
1559                        scale,
1560                        pivot: node
1561                            .spec
1562                            .transform_spec()
1563                            .map_or(crate::spec::TransformSpec::NONE.pivot, |t| t.pivot),
1564                    })
1565            } else {
1566                node.spec.transform_spec()
1567            };
1568            if let Some(tr) = own
1569                && tr.active()
1570            {
1571                clip = clip.turned_by(tr.at(rect));
1572                clip_id = self.display.intern_clip(clip.scaled(scale));
1573            }
1574            self.ghost_clip[i] = clip;
1575            self.ghost_clip_ids[i] = clip_id;
1576            self.ghost_rect[i] = rect;
1577            let visible = rect.intersect(&clip.visible());
1578            if visible.w <= 0.0 || visible.h <= 0.0 {
1579                continue;
1580            }
1581            let leaf = match node.content {
1582                GhostContent::Container => Leaf::Container,
1583                // None once the shaped buffer has been evicted: a ghost
1584                // older than the text cache draws no text rather than
1585                // somebody else's. A departing subtree takes no input and
1586                // holds no selection; it records no place either.
1587                GhostContent::Text { cache_key, color } => {
1588                    match self.text.readd(cache_key, color) {
1589                        Some(tid) => Leaf::Text { tid, sel: None },
1590                        None => Leaf::Container,
1591                    }
1592                }
1593                // Never focused: the departing subtree gave the keyboard
1594                // up the frame it stopped being declared.
1595                GhostContent::Edit(key) => Leaf::Edit {
1596                    key,
1597                    focused: false,
1598                    pad: node.spec.layout.padding,
1599                },
1600                GhostContent::Image(id, opts) => Leaf::Image(id, opts),
1601                // The picture is frozen at departure — the parameters are
1602                // the ones the node last declared — while the box eases
1603                // and the group opacity fades it.
1604                GhostContent::Fragment(draw) => Leaf::Fragment(draw),
1605                GhostContent::Polygon(draw) => Leaf::Polygon(draw),
1606                // The points are the ghost's own copy; the colour is the
1607                // `bg` slot, which `play.bg` eases on the root.
1608                GhostContent::Line {
1609                    first,
1610                    len,
1611                    width,
1612                    dash,
1613                } => Leaf::Line {
1614                    points: &g.points[first as usize..(first + len) as usize],
1615                    width,
1616                    dash,
1617                },
1618                // The ops are the ghost's own copy, the hash the live
1619                // node's, so the masks are the slots it already had.
1620                GhostContent::Path {
1621                    first,
1622                    len,
1623                    rule,
1624                    stroke_w,
1625                    dash,
1626                    hash,
1627                    angle,
1628                } => Leaf::Path {
1629                    ops: &g.ops[first as usize..(first + len) as usize],
1630                    rule,
1631                    stroke_w,
1632                    dash,
1633                    hash,
1634                    angle,
1635                    animating: false,
1636                },
1637            };
1638            let paint = Paint {
1639                clip_rect: clip.rect,
1640                clip_id,
1641                scale,
1642                opacity,
1643            };
1644            // A departing box blurs what is under it for as long as it
1645            // fades, as it did while it was declared.
1646            let blur = node.spec.interact().backdrop_blur;
1647            if blur > 0.0 {
1648                backdrop_quad(&mut self.display.quads, rect, &style, &paint, blur);
1649            }
1650            let first_quad = self.display.quads.len();
1651            painter!(self).paint_box(rect, &style, &paint, leaf);
1652            // A departing box keeps its gradient, from the slot it had.
1653            if let Some(grad) = &node.spec.interact().gradient
1654                && !matches!(
1655                    node.content,
1656                    GhostContent::Line { .. }
1657                        | GhostContent::Polygon(_)
1658                        | GhostContent::Path { .. }
1659                )
1660            {
1661                painter!(self).paint_gradient(grad, rect, &style, &paint, first_quad);
1662            }
1663            // A departing table keeps its grid for as long as it fades.
1664            if let Some(c) = node.spec.interact().rules
1665                && node.spec.layout.is_table()
1666            {
1667                self.emit_ghost_rules(g, i, rect, offset, c, &paint);
1668            }
1669        }
1670    }
1671
1672    /// After layout: nodes that `slide` ease from last frame's position
1673    /// toward where layout put them, carrying their subtree along (hit
1674    /// regions come from the same positions, so input follows the motion).
1675    /// Nodes whose `enter` has an offset start that far away on first
1676    /// sight and ease in the same way; without `slide` that entrance is
1677    /// all their position ever eases. Preorder means a parent shifts before
1678    /// its children are visited, so nested sliders ease relative to an
1679    /// already-eased parent.
1680    fn ease_positions(&mut self) {
1681        for i in 0..self.tree.len() {
1682            let spec = &self.tree.specs[i];
1683            let Some(t) = spec.transition else {
1684                continue;
1685            };
1686            let enter = spec.anim().enter.filter(|e| e.offsets());
1687            if !spec.slide && enter.is_none() {
1688                continue;
1689            }
1690            let key = self.tree.keys[i];
1691            let target = self.tree.pos[i];
1692            let from = enter.map(|e| [target.x + e.dx, target.y + e.dy, 0.0, 0.0]);
1693            let v = self.anim.drive(
1694                key,
1695                Slot::Pos,
1696                from,
1697                [target.x, target.y, 0.0, 0.0],
1698                t,
1699                spec.slide,
1700            );
1701            // Whole physical pixels, so the text inside moves with its box
1702            // rather than wobbling in it (`Vec2::snapped`). Rounding here
1703            // and not at the end means the last frame lands exactly on the
1704            // layout position, as it did before.
1705            let d = Vec2::new(v[0] - target.x, v[1] - target.y).snapped(self.scale);
1706            if d.x == 0.0 && d.y == 0.0 {
1707                continue;
1708            }
1709            let end = self.tree.subtree_end(i);
1710            for p in &mut self.tree.pos[i..end] {
1711                p.x += d.x;
1712                p.y += d.y;
1713            }
1714        }
1715    }
1716
1717    /// After the layout events: every node whose keyframe stops name a
1718    /// position (backlog F132) is moved, with its subtree, by the offset
1719    /// the cycle is at — after `ease_positions`, so a slide and a bob
1720    /// compose, and after `emit_layout_events`, so an `onLayout` node
1721    /// reports its layout rect and not a cycle that would post an event
1722    /// every frame for as long as it runs. Drawn, hit and read by
1723    /// assistive technology where it is moved to; the room it takes is
1724    /// its place's.
1725    #[inline(never)]
1726    fn offset_stops(&mut self) {
1727        for i in 0..self.tree.len() {
1728            let spec = &self.tree.specs[i];
1729            let Some(t) = spec.transition else {
1730                continue;
1731            };
1732            let frames = &spec.anim().keyframes;
1733            if frames.is_empty() || !frames.iter().any(|k| k.offsets()) {
1734                continue;
1735            }
1736            // A stop that names no position is the node's own place, 0.
1737            let offsets = crate::keyframes::offsets(frames);
1738            let Some(track) =
1739                crate::keyframes::track(frames, &offsets, [0.0; 4], |k| k.offset_lanes())
1740            else {
1741                continue;
1742            };
1743            let key = self.tree.keys[i];
1744            let iterations = spec.anim().iterations;
1745            let Some(o) = self.anim.sample_cycle(key, &track, t, iterations) else {
1746                continue;
1747            };
1748            // Whole physical pixels, as a slide's are.
1749            let d = Vec2::new(o[0], o[1]).snapped(self.scale);
1750            if d.x == 0.0 && d.y == 0.0 {
1751                continue;
1752            }
1753            let end = self.tree.subtree_end(i);
1754            for p in &mut self.tree.pos[i..end] {
1755                p.x += d.x;
1756                p.y += d.y;
1757            }
1758        }
1759    }
1760
1761    /// After layout: every `on_layout` node whose rect differs from the one
1762    /// last reported for its key — or that was not seen last frame — posts
1763    /// `{kind="layout", x, y, w, h, parent, scale, tag}`, pending like a
1764    /// `resize`.
1765    /// A frame that leaves a node where it was posts nothing, so a view
1766    /// that stores the rect in its model and redraws does not loop.
1767    fn emit_layout_events(&mut self) {
1768        let frame_no = self.frame_no;
1769        for i in 0..self.tree.len() {
1770            let Some(tag) = &self.tree.specs[i].events().on_layout else {
1771                continue;
1772            };
1773            let key = self.tree.keys[i];
1774            let rect = Rect::from_pos_size(self.tree.pos[i], self.tree.size[i]);
1775            let changed = match self.layouts.get(&key) {
1776                Some((last, seen)) if *seen + 1 == frame_no => *last != rect,
1777                _ => true,
1778            };
1779            self.layouts.insert(key, (rect, frame_no));
1780            if !changed {
1781                continue;
1782            }
1783            let parent = self.tree.parent[i];
1784            let parent_rect = if parent == NIL {
1785                Rect::new(0.0, 0.0, self.viewport.w, self.viewport.h)
1786            } else {
1787                let p = parent as usize;
1788                Rect::from_pos_size(self.tree.pos[p], self.tree.size[p])
1789            };
1790            let rect_value = |r: Rect| {
1791                Value::map([
1792                    ("x", Value::Float(r.x as f64)),
1793                    ("y", Value::Float(r.y as f64)),
1794                    ("w", Value::Float(r.w as f64)),
1795                    ("h", Value::Float(r.h as f64)),
1796                ])
1797            };
1798            let payload = Value::map([
1799                ("kind", Value::str("layout")),
1800                ("x", Value::Float(rect.x as f64)),
1801                ("y", Value::Float(rect.y as f64)),
1802                ("w", Value::Float(rect.w as f64)),
1803                ("h", Value::Float(rect.h as f64)),
1804                ("parent", rect_value(parent_rect)),
1805                // Physical px per logical px at this node — the number a
1806                // view multiplies `w`/`h` by to know how many pixels to
1807                // render before `update_image` (ADR 0025, decision 5).
1808                // The frame's today; where a zoom would compose in.
1809                ("scale", Value::Float(self.scale as f64)),
1810            ]);
1811            self.pending
1812                .push(UiEvent::on(self.tree.origins[i], key, payload).tagged(Some(tag)));
1813        }
1814    }
1815
1816    /// The chrome of one layer, after its content: the bars of every
1817    /// scroller the layer emitted (`regions`), then the ring if the focused
1818    /// node is in this layer. `layer` is the float
1819    /// root's index, or `NIL` for the in-flow layer; `above` is the hit
1820    /// list's length now, which is what a bar records so a press can tell
1821    /// a region under it from one in a layer over it.
1822    fn emit_layer_chrome(
1823        &mut self,
1824        layer: u32,
1825        regions: &[ScrollRegion],
1826        scrollbars: &mut Vec<ScrollbarRegion>,
1827        above: usize,
1828        scale: f32,
1829    ) {
1830        let cursor = self.interaction.cursor();
1831        let above = above as u32;
1832        for r in regions {
1833            let i = r.node as usize;
1834            // The node's own bar style, if it declared one: hidden means
1835            // no thumb and no track, and the wheel still works because the
1836            // scroll region is already pushed. A handler has no offset to
1837            // draw a bar for.
1838            let style = self.tree.specs[i].interact().scrollbar;
1839            if r.handler || style.mode == crate::spec::ScrollbarMode::Hidden {
1840                continue;
1841            }
1842            let rest_w = style.width.unwrap_or(SCROLLBAR_W);
1843            let active_w = rest_w + (SCROLLBAR_ACTIVE_W - SCROLLBAR_W);
1844            // The grabbable gutter: the stock one, or enough for a wide
1845            // thumb and its inset.
1846            let hit_w = SCROLLBAR_HIT_W.max(active_w + 2.0 * SCROLLBAR_INSET);
1847            let max = self.tree.scroll_max[i];
1848            let offset = self.scroll.drawn(r.key);
1849            let clip_id = self.clip_ids.get(i).copied().unwrap_or(NO_CLIP_ID);
1850            let mut opacity = self.opacity.get(i).copied().unwrap_or(1.0);
1851            // The tracks, before either bar: an `auto` bar is held while
1852            // the pointer is on either track, and the two tracks share the
1853            // one quiet clock.
1854            let track_y = Rect::new(
1855                r.rect.x + r.rect.w - hit_w,
1856                r.rect.y + SCROLLBAR_INSET,
1857                hit_w,
1858                r.rect.h - 2.0 * SCROLLBAR_INSET,
1859            );
1860            let track_x = Rect::new(
1861                r.rect.x + SCROLLBAR_INSET,
1862                r.rect.y + r.rect.h - hit_w,
1863                r.rect.w - 2.0 * SCROLLBAR_INSET,
1864                hit_w,
1865            );
1866            if style.mode == crate::spec::ScrollbarMode::Auto
1867                && let Some(now) = self.anim.time()
1868            {
1869                let held = self.interaction.is_scrollbar_dragging(r.key, ScrollAxis::Y)
1870                    || self.interaction.is_scrollbar_dragging(r.key, ScrollAxis::X)
1871                    || cursor.is_some_and(|p| {
1872                        (max.y > 0.0 && track_y.contains(p)) || (max.x > 0.0 && track_x.contains(p))
1873                    });
1874                let idle = self.scroll.bar_idle(r.key, now, held);
1875                let shown = if idle < SCROLLBAR_HOLD {
1876                    1.0
1877                } else {
1878                    (1.0 - (idle - SCROLLBAR_HOLD) / SCROLLBAR_FADE).max(0.0)
1879                };
1880                if shown <= 0.0 {
1881                    continue; // faded out: no thumb, and no track to press
1882                }
1883                // Something to settle: the hold running out, or the fade.
1884                // Not while held — that is input's to end, and a frame a
1885                // hover would ask for every 8 ms is the idle CPU C27 fought.
1886                if !held {
1887                    self.owe_frame("scrollbar fade");
1888                }
1889                opacity *= shown as f32;
1890            }
1891            for (axis, track) in [(ScrollAxis::Y, track_y), (ScrollAxis::X, track_x)] {
1892                let (max_a, offset_a) = match axis {
1893                    ScrollAxis::Y => (max.y, offset.y),
1894                    ScrollAxis::X => (max.x, offset.x),
1895                };
1896                if max_a <= 0.0 {
1897                    continue;
1898                }
1899                let active = self.interaction.is_scrollbar_dragging(r.key, axis)
1900                    || cursor.is_some_and(|p| track.contains(p));
1901                let w = if active { active_w } else { rest_w };
1902                let (thumb, bar_len) = thumb_along(axis, r.rect, track, max_a, offset_a, w);
1903                let mut bar =
1904                    scrollbar_quad(thumb, scale, clip_id, self.thumb_color(&style, active));
1905                bar.color.a *= opacity;
1906                self.display.quads.push(bar);
1907                scrollbars.push(ScrollbarRegion {
1908                    key: r.key,
1909                    axis,
1910                    thumb,
1911                    track,
1912                    bar_len,
1913                    max: max_a,
1914                    inert: r.inert,
1915                    above,
1916                });
1917            }
1918        }
1919        self.emit_focus_ring(layer, scale);
1920    }
1921
1922    /// The layer node `i` paints in: its float root's index, `NIL` in flow
1923    /// — and `NIL` for every node of a frame that floats nothing, where the
1924    /// map is not even sized.
1925    #[inline]
1926    fn layer_of(&self, i: usize) -> u32 {
1927        self.float_root.get(i).copied().unwrap_or(NIL)
1928    }
1929
1930    /// This frame's float layers in paint order, from `roots` (the float
1931    /// roots in tree order) and the stack the last frame left: a root the
1932    /// stack knows keeps its place, one it does not is appended, in tree
1933    /// order, and a root the frame no longer declares is dropped. Writes
1934    /// the stack back for the next frame.
1935    ///
1936    /// The steady state — the same roots as last frame — is one pass over
1937    /// the stack and no allocation beyond the order itself: each entry
1938    /// remembers its root's rank in tree order, so the check and the
1939    /// answer are the same read.
1940    fn stack_floats(&mut self, roots: &[u32]) -> Vec<u32> {
1941        let keys = &self.tree.keys;
1942        let parent = &self.tree.parent;
1943        let float_root = &self.float_root;
1944        // The float a root is in, or NIL for one in the flow.
1945        let outer_of = |root: u32| {
1946            let p = parent[root as usize];
1947            if p == NIL {
1948                NIL
1949            } else {
1950                float_root[p as usize]
1951            }
1952        };
1953        // Every nested float above the float it is in.
1954        let nested_above = |order: &[u32]| {
1955            order.iter().enumerate().all(|(pos, &r)| {
1956                let outer = outer_of(r);
1957                outer == NIL || order[..pos].contains(&outer)
1958            })
1959        };
1960        let stack = &mut self.float_stack;
1961        let steady = stack.len() == roots.len()
1962            && stack
1963                .iter()
1964                .all(|&(k, rank)| keys[roots[rank as usize] as usize] == k);
1965        // The steady order holds unless a root moved into a float under a
1966        // key the app keeps (`open_key`), which changes no rank: then the
1967        // rebuild below sorts it, as it does a root the stack is new to
1968        // (backlog RG151).
1969        let order: Vec<u32> = if steady {
1970            stack
1971                .iter()
1972                .map(|&(_, rank)| roots[rank as usize])
1973                .collect()
1974        } else {
1975            Vec::new()
1976        };
1977        let order = if steady && nested_above(&order) {
1978            order
1979        } else {
1980            // A float opened or closed: the ranks are found again, by key.
1981            let rank_of: FxHashMap<Key, u32> = roots
1982                .iter()
1983                .enumerate()
1984                .map(|(rank, &r)| (keys[r as usize], rank as u32))
1985                .collect();
1986            let mut placed = vec![false; roots.len()];
1987            let mut next: Vec<(Key, u32)> = Vec::with_capacity(roots.len());
1988            for &(k, _) in stack.iter() {
1989                if let Some(&rank) = rank_of.get(&k) {
1990                    placed[rank as usize] = true;
1991                    next.push((k, rank));
1992                }
1993            }
1994            for (rank, &r) in roots.iter().enumerate() {
1995                if !placed[rank] {
1996                    next.push((keys[r as usize], rank as u32));
1997                }
1998            }
1999            // A box that kept its key while it became a float is new here,
2000            // and a float it already held is not: the held one waits for
2001            // it and goes just above it, and what it holds in turn after
2002            // that — each in the order it had — so a nested float stays
2003            // over the float it is in and two held side by side keep
2004            // their order (backlog RG151).
2005            let rank_of_outer = |root: u32| {
2006                let outer = outer_of(root);
2007                if outer == NIL {
2008                    None
2009                } else {
2010                    rank_of.get(&keys[outer as usize]).copied()
2011                }
2012            };
2013            let mut out: Vec<(Key, u32)> = Vec::with_capacity(next.len());
2014            let mut out_has = vec![false; roots.len()];
2015            let mut waiting: Vec<(Key, u32)> = Vec::new();
2016            for e in next {
2017                match rank_of_outer(roots[e.1 as usize]) {
2018                    Some(outer) if !out_has[outer as usize] => waiting.push(e),
2019                    _ => {
2020                        out_has[e.1 as usize] = true;
2021                        out.push(e);
2022                        // What waited on it, and on those, in turn.
2023                        while let Some(i) = waiting.iter().position(|w| {
2024                            rank_of_outer(roots[w.1 as usize])
2025                                .is_none_or(|outer| out_has[outer as usize])
2026                        }) {
2027                            let w = waiting.remove(i);
2028                            out_has[w.1 as usize] = true;
2029                            out.push(w);
2030                        }
2031                    }
2032                }
2033            }
2034            debug_assert!(
2035                waiting.is_empty(),
2036                "a float inside a float this frame has no root"
2037            );
2038            *stack = out;
2039            stack
2040                .iter()
2041                .map(|&(_, rank)| roots[rank as usize])
2042                .collect()
2043        };
2044        // Said here so the placement above cannot drift.
2045        debug_assert!(nested_above(&order));
2046        order
2047    }
2048
2049    /// The `modal-behind-content` check, for the stack: a float layer
2050    /// above the modal's whose root is outside the modal's scope is inert
2051    /// and drawn over the one surface that takes input, which is the same
2052    /// defect the in-flow check names. Only a layer
2053    /// with something in it that *would* take input is the defect — a
2054    /// control the user sees and cannot press. A picture over the dialog
2055    /// (a HUD, the devtools' inspector outline) is not, and is not named.
2056    fn check_layers_over_modal(&mut self, order: &[u32]) {
2057        let Some((start, end, modal_key)) = self.modal else {
2058            return;
2059        };
2060        let modal_layer = self.layer_of(start);
2061        if modal_layer == NIL {
2062            return; // `diag::check_modal` has this case
2063        }
2064        let Some(at) = order.iter().position(|&r| r == modal_layer) else {
2065            return;
2066        };
2067        let over = order[at + 1..].iter().any(|&r| {
2068            let root = r as usize;
2069            !(start..end).contains(&root)
2070                && (root..self.tree.subtree_end(root)).any(|i| {
2071                    self.float_root[i] == r
2072                        && (self.tree.specs[i].hover_tracked()
2073                            || crate::access::focusable(&self.tree, i))
2074                })
2075        });
2076        if over {
2077            self.diag.raise(crate::diag::modal_under_layer(modal_key));
2078        }
2079    }
2080
2081    /// The default focus ring around the keyboard-visibly focused node, at
2082    /// the end of the layer the node is in — above every sibling that could
2083    /// touch it, under every layer over it — in the same display list
2084    /// every binding draws. Not for editors (the caret shows focus), key
2085    /// sinks (an app surface styles itself, through `is_focused` /
2086    /// `focus_visible`) or nodes declaring `focus_bg`.
2087    fn emit_focus_ring(&mut self, layer: u32, scale: f32) {
2088        if !self.focus_visible {
2089            return;
2090        }
2091        let Some(i) = self.focus_index() else {
2092            return;
2093        };
2094        if self.layer_of(i) != layer {
2095            return;
2096        }
2097        let spec = &self.tree.specs[i];
2098        let editor = matches!(self.tree.content[i], NodeContent::Edit(_))
2099            || spec
2100                .access()
2101                .role
2102                .is_some_and(crate::access::Role::is_editor);
2103        if editor
2104            || spec.events().on_key.is_some()
2105            || spec.interact().focus_bg.is_some()
2106            || spec.disabled
2107        {
2108            return;
2109        }
2110        let node = Rect::from_pos_size(self.tree.pos[i], self.tree.size[i]);
2111        let rect = Rect::new(
2112            node.x - FOCUS_RING_GAP,
2113            node.y - FOCUS_RING_GAP,
2114            node.w + 2.0 * FOCUS_RING_GAP,
2115            node.h + 2.0 * FOCUS_RING_GAP,
2116        );
2117        let clip = self.clips.get(i).copied().unwrap_or(Clip::NONE);
2118        // No entry means nothing clipped this frame, which is entry zero.
2119        let clip_id = self.clip_ids.get(i).copied().unwrap_or(NO_CLIP_ID);
2120        let visible = rect.intersect(&clip.visible());
2121        if visible.w <= 0.0 || visible.h <= 0.0 {
2122            return;
2123        }
2124        let mut ring = self.theme().focus_ring;
2125        ring.a *= self.opacity.get(i).copied().unwrap_or(1.0);
2126        self.display.quads.push(Quad {
2127            rect: rect.scaled(scale),
2128            color: Color::TRANSPARENT,
2129            border_color: ring,
2130            radius: spec.style.radius.map(|r| (r + FOCUS_RING_GAP) * scale),
2131            border_w: FOCUS_RING_W * scale,
2132            blur: 0.0,
2133            kind: QuadKind::Solid,
2134            clip: clip_id,
2135            uv: [0; 4],
2136        });
2137    }
2138
2139    /// See the `ime_rect` field. None when nothing with a caret is
2140    /// focused: neither a stock editor nor a sink holding a `line` that
2141    /// declares one.
2142    pub fn ime_rect(&self) -> Option<Rect> {
2143        self.ime_rect
2144    }
2145
2146    /// The stock editor `key`'s node and its caret rect in viewport
2147    /// coordinates, from the frame laid out: the editor's own caret
2148    /// (physical px inside its text box) placed at the node's content
2149    /// origin. The one place this arithmetic lives — the
2150    /// IME anchor and the scroll-into-view both read it. None when no
2151    /// node of this frame is that editor, or it has no caret.
2152    pub(crate) fn stock_caret_viewport_rect(&mut self, key: Key) -> Option<(usize, Rect)> {
2153        let i = (0..self.tree.len()).find(|&i| self.tree.content[i] == NodeContent::Edit(key))?;
2154        let caret = self.edit_with_fonts(|edit, fs| edit.caret_rect(key, fs))?;
2155        let pad = self.tree.specs[i].layout.padding;
2156        Some((
2157            i,
2158            Rect::new(
2159                self.tree.pos[i].x + pad.l + caret.x / self.scale,
2160                self.tree.pos[i].y + pad.t + caret.y / self.scale,
2161                caret.w / self.scale,
2162                caret.h / self.scale,
2163            ),
2164        ))
2165    }
2166
2167    /// The IME's anchor: the focused caret where it is drawn, the box it
2168    /// covers through any turn its editor is under (ADR 0043), so the
2169    /// candidate window opens beside a tilted field's caret.
2170    fn focused_caret_rect(&mut self) -> Option<Rect> {
2171        let drawn = |clips: &[crate::display::Clip], i: usize, r: Rect| match clips.get(i) {
2172            Some(c) if c.turned() => c.transform.bounds(r),
2173            _ => r,
2174        };
2175        if let Some(key) = self.edit.focused() {
2176            return self
2177                .stock_caret_viewport_rect(key)
2178                .map(|(i, r)| drawn(&self.clips, i, r));
2179        }
2180        // A custom editor (backlog C17): the focused node's subtree holds
2181        // the `line` rows it draws, and the one carrying `caret` says
2182        // where the caret is — a byte offset into that line's runs, which
2183        // is the question `caret_rect` answers. This runs after the text
2184        // pass, so the places it reads are this frame's.
2185        let (l, caret, _) = self.sink_caret_line()?;
2186        self.text
2187            .caret_at(self.tree.keys[l], caret as usize, false)
2188            .map(|r| drawn(&self.clips, l, r))
2189    }
2190
2191    /// The `line` under the focused node that declares `caret`, the
2192    /// offset it declares, and whether it declares the caret
2193    /// `caret_solid` — a custom editor's caret, in the frame just built.
2194    /// None with a stock editor focused, or nothing declaring one.
2195    fn sink_caret_line(&self) -> Option<(usize, u32, bool)> {
2196        if !self.tree.any_line {
2197            return None;
2198        }
2199        // The editor whose caret this is: the focused sink, or the sink
2200        // enclosing a focused control inside it — the node keys and
2201        // commits already go to (`key_target`, `sink_event`). Read from
2202        // the focused node alone, focus on a pane button inside a custom
2203        // editor un-armed the blink clock and lost the IME its anchor
2204        // while the keys kept arriving (backlog AR29).
2205        let i = self.focus_index()?;
2206        let i = if self.tree.specs[i].events().on_key.is_some() {
2207            i
2208        } else {
2209            self.enclosing_sink(i)?
2210        };
2211        // The candidates are the editor's lines as the access tree reads
2212        // them — `role="none"` subtrees (a gutter) skipped, a line's own
2213        // subtree not descended into — and the *last* one declaring a
2214        // caret is the caret, as `custom_editor` reads it.
2215        let l = crate::access::lines_under(&self.tree, i)
2216            .into_iter()
2217            .rev()
2218            .find(|&l| self.tree.specs[l].access().caret.is_some())?;
2219        let access = self.tree.specs[l].access();
2220        Some((l, access.caret?, access.caret_solid))
2221    }
2222
2223    /// Remembers this frame's custom-editor caret and bumps the stamp when
2224    /// it is not last frame's: the blink clock reads both.
2225    /// Whether it is solid is kept beside it, not in it: a caret going
2226    /// from bar to block has not moved, and the clock re-arms on the
2227    /// way back from `has_caret` alone.
2228    fn note_sink_caret(&mut self) {
2229        let (now, solid) = if self.edit.focused().is_some() {
2230            (None, false)
2231        } else {
2232            match self.sink_caret_line() {
2233                Some((l, offset, solid)) => (Some((self.tree.keys[l], offset)), solid),
2234                None => (None, false),
2235            }
2236        };
2237        if now != self.sink_caret {
2238            self.sink_caret = now;
2239            self.sink_caret_stamp += 1;
2240        }
2241        self.sink_caret_solid = solid;
2242    }
2243
2244    // -- The caret's blink --------------------------------------------
2245    // The clock is the driver's (a frame twice a second is a decision
2246    // about the window, not the tree); what the core keeps is whether
2247    // there is a caret to blink, when it moved, and the phase the driver
2248    // last set — for the stock editor, which paints its own caret on the
2249    // phase, and for a custom one, which reads it (backlog C35).
2250
2251    /// Whether there is a caret to blink: a focused stock editor's, or the
2252    /// `caret` a `line` under the focused custom editor declares — unless
2253    /// that line declares it `caret_solid`, which is a caret to anchor
2254    /// the IME and read to assistive technology but not one to blink. A
2255    /// driver arms its blink clock while this is true and leaves the
2256    /// caret solid otherwise.
2257    pub fn has_caret(&self) -> bool {
2258        self.edit.focused().is_some() || (self.sink_caret.is_some() && !self.sink_caret_solid)
2259    }
2260
2261    /// Changes whenever the caret moved or focus changed — the stock
2262    /// editor's caret through typing or a click, a custom editor's
2263    /// through the `caret` row it declares — so a driver comparing it
2264    /// across frames re-arms the blink with the caret solid, the way a
2265    /// caret that just moved is never mid-blink.
2266    pub fn caret_stamp(&self) -> u64 {
2267        self.edit.caret_stamp().wrapping_add(self.sink_caret_stamp)
2268    }
2269
2270    /// The blink phase, as the driver last set it: `true` draws the
2271    /// caret. The stock editor reads it itself; a custom editor reads it
2272    /// in `view` (`Ui::caret_visible`) and skips its caret node on the
2273    /// off phase, so the two blink in step — and a window without the
2274    /// keyboard, where the driver parks it hidden, shows neither.
2275    /// Headless it stays `true`.
2276    pub fn caret_visible(&self) -> bool {
2277        let v = self.edit.blink_visible();
2278        self.note_read(|| replay::Read::Caret(v));
2279        v
2280    }
2281
2282    /// Sets the blink phase; the driver's, on its clock. A frame is the
2283    /// caller's to ask for.
2284    pub fn set_caret_visible(&mut self, visible: bool) {
2285        self.edit.set_blink_visible(visible);
2286    }
2287}
2288
2289/// Combined measurer handed to the layout pass: static text through the
2290/// shape cache, editors through the edit store (sharing one FontSystem),
2291/// images through the resource registry.
2292struct Measure<'a> {
2293    text: &'a mut TextSystem,
2294    cells: &'a mut crate::cells::CellStore,
2295    fonts: &'a mut cosmic_text::FontSystem,
2296    edit: &'a mut EditStore,
2297    resources: &'a Resources,
2298}
2299
2300impl TextMeasure for Measure<'_> {
2301    fn intrinsic(&mut self, id: crate::tree::TextId) -> Size {
2302        self.text.intrinsic(id)
2303    }
2304
2305    fn wrapped(&mut self, id: crate::tree::TextId, max_w: f32) -> Size {
2306        self.text.wrapped(id, max_w, self.fonts)
2307    }
2308
2309    fn min_content(&mut self, id: crate::tree::TextId) -> f32 {
2310        self.text.min_content(id)
2311    }
2312
2313    fn edit_intrinsic(&mut self, key: Key) -> Size {
2314        self.edit.intrinsic(key, self.fonts)
2315    }
2316
2317    fn edit_wrapped(&mut self, key: Key, max_w: f32) -> Size {
2318        self.edit.wrapped(key, max_w, self.fonts)
2319    }
2320
2321    fn baseline(&mut self, id: crate::tree::TextId) -> f32 {
2322        self.text.baseline(id)
2323    }
2324
2325    fn edit_baseline(&mut self, key: Key) -> f32 {
2326        self.edit.baseline(key)
2327    }
2328
2329    fn cells_size(&mut self, id: crate::cells::CellsId) -> Size {
2330        self.cells.size(id, self.resources, self.fonts)
2331    }
2332
2333    fn image_size(&mut self, id: crate::resources::ImageId) -> Size {
2334        self.resources
2335            .image(id)
2336            .map_or(Size::ZERO, |e| Size::new(e.width as f32, e.height as f32))
2337    }
2338}
2339
2340/// What a node inherits at emission time: the frame's scale, the clip its
2341/// ancestors imposed (logical px), and the group opacity its own `opacity`
2342/// and every ancestor's multiply out to.
2343#[derive(Clone, Copy)]
2344/// What a box holds, resolved to what painting it needs: the live pass
2345/// resolves a text node's selection and an editor's focus from the frame,
2346/// a ghost resolves nothing (no selection, never focused, its text re-added
2347/// from the cache) — and both hand the result here.
2348enum Leaf<'a> {
2349    Container,
2350    Text {
2351        tid: crate::tree::TextId,
2352        sel: Option<((usize, usize), Color)>,
2353    },
2354    Cells {
2355        cid: crate::cells::CellsId,
2356        at: Vec2,
2357        sel: Option<&'a crate::select::CellSelection>,
2358        tint: Color,
2359    },
2360    Edit {
2361        key: Key,
2362        focused: bool,
2363        /// The box's padding: the text starts inside it.
2364        pad: crate::geom::Edges,
2365    },
2366    Image(crate::resources::ImageId, crate::resources::ImageOpts),
2367    Fragment(crate::fragment::Draw),
2368    /// A polygon's draw; the fill is the node's `bg`, put through the
2369    /// fragment quad's colour rather than a box under it.
2370    Polygon(crate::fragment::Draw),
2371    Line {
2372        points: &'a [Vec2],
2373        width: f32,
2374        /// What cuts the stroke into marks (backlog V2); None for solid.
2375        dash: Option<crate::line::Cut>,
2376    },
2377    /// A path's run; the fill is the node's `bg`, the stroke its border
2378    /// colour and width, each a mask quad from the atlas (ADR 0040).
2379    Path {
2380        ops: &'a [crate::path::PathOp],
2381        rule: crate::path::FillRule,
2382        stroke_w: f32,
2383        /// What cuts the stroke into marks, as a line's (backlog V2).
2384        dash: Option<crate::line::Cut>,
2385        hash: u64,
2386        /// The turn in radians of a path that declared one (ADR 0041).
2387        angle: Option<f32>,
2388        animating: bool,
2389    },
2390}
2391
2392/// One box's paint: its shadow, its fill and border, its content, faded by
2393/// the group opacity — written once for the live node and the ghost, which
2394/// differ in what they *record* (hit regions, scroll regions, a text's
2395/// place) and not in what they draw. The two were the same hundred and
2396/// twenty lines until F41 had to be fixed in both.
2397struct Painter<'a> {
2398    display: &'a mut DisplayList,
2399    text: &'a mut TextSystem,
2400    edit: &'a mut EditStore,
2401    cells: &'a mut crate::cells::CellStore,
2402    atlas: &'a mut GlyphAtlas,
2403    session: &'a Session,
2404    /// The masks drawn from textures of their own (ADR 0040).
2405    path_tex: &'a mut crate::path::PathTextures,
2406    frame_no: u64,
2407}
2408
2409impl Painter<'_> {
2410    /// Inlined into its two callers: a call per node with the borrows
2411    /// packed into a struct measured +2.5% on `frame_10k_rects`.
2412    /// What a leaf draws, and a shadow, are calls (`paint_leaf`,
2413    /// `shadow_quad`): inlined as well, they made every box pay for them.
2414    #[inline(always)]
2415    fn paint_box(
2416        &mut self,
2417        rect: Rect,
2418        style: &crate::spec::VisualStyle,
2419        paint: &Paint,
2420        leaf: Leaf<'_>,
2421    ) {
2422        let Paint {
2423            clip_id,
2424            scale,
2425            opacity,
2426            ..
2427        } = *paint;
2428        let first_quad = self.display.quads.len();
2429        if style.shadow.is_visible() {
2430            self.display
2431                .quads
2432                .push(shadow_quad(style, rect, clip_id, scale));
2433        }
2434        // A stroke's `bg` is its colour, not a box to fill (ADR 0010,
2435        // decision 7), and a polygon's is its fill (ADR 0025, decision 6)
2436        // — for the ghost of one as much as for the live one.
2437        let is_line = matches!(
2438            leaf,
2439            Leaf::Line { .. } | Leaf::Polygon(_) | Leaf::Path { .. }
2440        );
2441        if !is_line
2442            && (style.bg.is_visible() || (style.border_w > 0.0 && style.border_color.is_visible()))
2443        {
2444            // Where layout put it, or on whole pixels when it asked
2445            // (`pixelSnap`), from the same numbers a text's backgrounds are.
2446            let px = rect.scaled(scale);
2447            self.display.quads.push(Quad {
2448                rect: if style.pixel_snap { px.on_pixels() } else { px },
2449                color: style.bg,
2450                border_color: style.border_color,
2451                radius: style.radius.map(|r| r * scale),
2452                border_w: style.border_w * scale,
2453                blur: 0.0,
2454                kind: QuadKind::Solid,
2455                clip: clip_id,
2456                uv: [0; 4],
2457            });
2458        }
2459        if !matches!(leaf, Leaf::Container) {
2460            // A picture or a fragment fills its box, so a border painted
2461            // under it with the background is covered: it moves to a ring
2462            // over the content, as it does over a gradient (backlog RG152).
2463            let covers = matches!(leaf, Leaf::Image(..) | Leaf::Fragment(..));
2464            let solid = self.display.quads.len().checked_sub(1);
2465            self.paint_leaf(rect, style, paint, leaf);
2466            if covers && style.border_w > 0.0 && style.border_color.is_visible() {
2467                ring_over_content(&mut self.display.quads, solid);
2468            }
2469        }
2470        if opacity < 1.0 {
2471            fade(&mut self.display.quads[first_quad..], opacity);
2472        }
2473    }
2474
2475    /// A box's `gradient` (ADR 0042): one `Image` quad over the box's
2476    /// rect from the gradient's slot in the atlas, put where it paints
2477    /// over the background and under everything else the box drew — its
2478    /// content, and its border, which moves to a ring of its own on top
2479    /// so the gradient does not cover the inside of it. `first_quad` is
2480    /// where the box's quads start. A gradient no page can hold draws
2481    /// nothing.
2482    #[cold]
2483    #[inline(never)]
2484    fn paint_gradient(
2485        &mut self,
2486        g: &crate::gradient::Gradient,
2487        rect: Rect,
2488        style: &crate::spec::VisualStyle,
2489        paint: &Paint,
2490        first_quad: usize,
2491    ) {
2492        if !g.is_drawable() {
2493            return;
2494        }
2495        let (w, h) = g.slot_size();
2496        let Some(slot) = self
2497            .atlas
2498            .get_or_insert_gradient(g.key(), w, h, || g.rasterize())
2499        else {
2500            return;
2501        };
2502        let quads = &mut self.display.quads;
2503        let px = rect.scaled(paint.scale);
2504        let image = Quad {
2505            rect: if style.pixel_snap { px.on_pixels() } else { px },
2506            // White is untinted; the group opacity rides its alpha.
2507            color: Color {
2508                a: paint.opacity.min(1.0),
2509                ..Color::WHITE
2510            },
2511            border_color: Color::TRANSPARENT,
2512            radius: style.radius.map(|r| r * paint.scale),
2513            border_w: 0.0,
2514            blur: 0.0,
2515            kind: QuadKind::Image,
2516            clip: paint.clip_id,
2517            // The raster inside its gutter (`Gradient::rasterize`).
2518            uv: [slot.x + 1, slot.y + 1, slot.w - 2, slot.h - 2],
2519        };
2520        // Where `paint_box` put the box's own solid, when it painted
2521        // one: after the shadow, before the content.
2522        let at = first_quad + usize::from(style.shadow.is_visible());
2523        let bordered = style.border_w > 0.0 && style.border_color.is_visible();
2524        if !style.bg.is_visible() && !bordered {
2525            // No background and no border: the gradient is the box.
2526            quads.insert(at, image);
2527            return;
2528        }
2529        // The border as a ring of its own, above the gradient; what is
2530        // left under it is the background alone. A picture's or a
2531        // fragment's border is a ring over the content already
2532        // (`ring_over_content`), and its solid has none left to give.
2533        let ring = (bordered && quads[at].border_w > 0.0).then(|| Quad {
2534            color: Color::TRANSPARENT,
2535            ..quads[at]
2536        });
2537        if style.bg.is_visible() {
2538            quads[at].border_w = 0.0;
2539            quads[at].border_color = Color::TRANSPARENT;
2540            quads.insert(at + 1, image);
2541        } else {
2542            quads[at] = image;
2543        }
2544        let over = at + 1 + usize::from(style.bg.is_visible());
2545        if let Some(ring) = ring {
2546            quads.insert(over, ring);
2547        }
2548    }
2549
2550    /// The clip a node's quads name, in physical px: the entry `clip_id`
2551    /// interned, already scaled. Read by the leaves that cull by it — a
2552    /// text, a cell grid, an editor — and by nothing else: eighty bytes
2553    /// copied per leaf cost a frame of 10,000 strokes 2% when every leaf
2554    /// took it (ADR 0043's amendment).
2555    #[inline]
2556    fn clip_px(&self, clip_id: ClipId) -> Clip {
2557        self.display
2558            .clips
2559            .get(clip_id as usize)
2560            .copied()
2561            .unwrap_or(Clip::NONE)
2562    }
2563
2564    /// The level an `image` node draws (ADR 0044): `None` for level 0 —
2565    /// sampled `nearest`, an image ever updated, a draw at no more than
2566    /// two texels a pixel — else the level and its pixels, made now if
2567    /// no draw has asked for it before. The ratio is the texel rect `fit`
2568    /// picks over the drawn rect in physical px, times the scale the clip
2569    /// entry draws the quad through. A level past a page is not drawn
2570    /// from (it would want a texture of its own); level 0 is.
2571    fn image_level(
2572        &self,
2573        rect: Rect,
2574        scale: f32,
2575        clip_id: ClipId,
2576        entry: &crate::resources::ImageEntry,
2577        opts: crate::resources::ImageOpts,
2578    ) -> Option<(u8, std::sync::Arc<crate::resources::Level>)> {
2579        if opts.sampling != crate::resources::Sampling::Linear || !entry.levels_allowed() {
2580            return None;
2581        }
2582        let (drawn, texels) = fit_image(
2583            opts.fit,
2584            rect,
2585            Size::new(entry.width as f32, entry.height as f32),
2586            [0, 0, entry.width, entry.height],
2587        );
2588        let k = scale * self.clip_px(clip_id).transform.scale.abs();
2589        let n = crate::mip::level_for(
2590            (texels[2] as f32, texels[3] as f32),
2591            (drawn.w * k, drawn.h * k),
2592            entry.depth(),
2593        );
2594        let level = entry.level(n)?;
2595        (level.width <= crate::atlas::MAX_ATLAS_SIZE
2596            && level.height <= crate::atlas::MAX_ATLAS_SIZE)
2597            .then_some((n, level))
2598    }
2599
2600    /// What a leaf draws inside its box: text, cells, an editor, an
2601    /// image, a fragment, a polygon's fill or a stroke. Out of line, so the
2602    /// kinds a plain box never takes do not weigh on every node's
2603    /// `emit_node` — its saved registers and its stack frame.
2604    #[inline(never)]
2605    fn paint_leaf(
2606        &mut self,
2607        rect: Rect,
2608        style: &crate::spec::VisualStyle,
2609        paint: &Paint,
2610        leaf: Leaf<'_>,
2611    ) {
2612        let Paint { clip_id, scale, .. } = *paint;
2613        match leaf {
2614            Leaf::Container => {}
2615            Leaf::Text { tid, sel } => {
2616                let clip_px = self.clip_px(clip_id);
2617                let sess = &mut *self.session.state();
2618                self.text.emit(
2619                    tid,
2620                    Vec2::new(rect.x, rect.y),
2621                    Size::new(rect.w, rect.h),
2622                    clip_px,
2623                    clip_id,
2624                    &mut self.display.clips,
2625                    &sess.resources,
2626                    &mut sess.fonts,
2627                    self.atlas,
2628                    &mut self.display.quads,
2629                    sel,
2630                );
2631            }
2632            Leaf::Cells { cid, at, sel, tint } => {
2633                let clip_px = self.clip_px(clip_id);
2634                let sess = &mut *self.session.state();
2635                self.cells.emit(
2636                    cid,
2637                    at,
2638                    clip_px,
2639                    clip_id,
2640                    &sess.resources,
2641                    &mut sess.fonts,
2642                    self.text.raster_mut(),
2643                    self.atlas,
2644                    &mut self.display.quads,
2645                    sel.map(|s| (s, tint)),
2646                );
2647            }
2648            Leaf::Edit { key, focused, pad } => {
2649                let origin = Vec2::new(
2650                    crate::geom::snap_px((rect.x + pad.l) * scale),
2651                    crate::geom::snap_px((rect.y + pad.t) * scale),
2652                );
2653                // A field bounds its own text horizontally — it is what
2654                // makes scrolling one legible rather than a line running
2655                // out over its neighbours (F41). Horizontally only: the
2656                // ancestors own the vertical clip, and a descender or a
2657                // caret is not what a field is trying to cut off.
2658                // Narrowing the clip makes a new one, so it needs an entry
2659                // of its own; an editor that folds to its width — a
2660                // document, or a field with `wrap` (F44) — keeps the node's.
2661                let clip_px = self.clip_px(clip_id);
2662                let (edit_clip, edit_clip_id) = if self.edit.folds(key) {
2663                    (clip_px, clip_id)
2664                } else {
2665                    let narrowed = clip_px.intersect(
2666                        Rect::new(
2667                            origin.x,
2668                            clip_px.rect.y,
2669                            (rect.w - pad.x()).max(0.0) * scale,
2670                            clip_px.rect.h,
2671                        ),
2672                        crate::display::SQUARE,
2673                    );
2674                    (narrowed, self.display.intern_clip(narrowed))
2675                };
2676                let sess = &mut *self.session.state();
2677                self.edit.emit(
2678                    key,
2679                    origin,
2680                    focused,
2681                    edit_clip,
2682                    edit_clip_id,
2683                    &mut sess.fonts,
2684                    self.text,
2685                    self.atlas,
2686                    &mut self.display.quads,
2687                );
2688            }
2689            Leaf::Image(id, opts) => {
2690                let sess = self.session.state();
2691                if let Some(entry) = sess.resources.image(id) {
2692                    // Drawn smaller than it is, from a level of the image
2693                    // halved (ADR 0044) when the page can take it; else
2694                    // level 0, atlas-backed unless the entry says otherwise
2695                    // — or unless the atlas cannot take it after all, which
2696                    // used to draw nothing (ADR 0025, decision 2).
2697                    let level = self.image_level(rect, scale, clip_id, entry, opts);
2698                    let mut size = (entry.width, entry.height);
2699                    let mut slot = level.and_then(|(n, level)| {
2700                        let slot = self.atlas.get_or_insert_image_level(
2701                            id,
2702                            n,
2703                            level.width,
2704                            level.height,
2705                            || &level.rgba,
2706                        )?;
2707                        size = (level.width, level.height);
2708                        Some(slot)
2709                    });
2710                    if slot.is_none() && entry.backing == crate::resources::ImageBacking::Atlas {
2711                        slot = self.atlas.get_or_insert_image(
2712                            id,
2713                            entry.width,
2714                            entry.height,
2715                            &entry.rgba,
2716                        );
2717                    }
2718                    let (kind, uv) = match slot {
2719                        Some(slot) => (QuadKind::Image, [slot.x, slot.y, slot.w, slot.h]),
2720                        None => (
2721                            QuadKind::Texture,
2722                            [self.display.textures.len() as u32, 0, 0, 0],
2723                        ),
2724                    };
2725                    let mut uv = uv;
2726                    let (rect, tex_uv) = fit_image(
2727                        opts.fit,
2728                        rect,
2729                        Size::new(size.0 as f32, size.1 as f32),
2730                        [0, 0, size.0, size.1],
2731                    );
2732                    if kind == QuadKind::Image {
2733                        // The crop, if any, applied inside the atlas slot.
2734                        uv = [uv[0] + tex_uv[0], uv[1] + tex_uv[1], tex_uv[2], tex_uv[3]];
2735                    } else {
2736                        self.display
2737                            .textures
2738                            .push(crate::display::TextureDraw { id, uv: tex_uv });
2739                        self.display
2740                            .texture_pixels
2741                            .push(crate::display::TexturePixels {
2742                                width: entry.width,
2743                                height: entry.height,
2744                                rev: entry.rev,
2745                                rgba: entry.rgba.clone(),
2746                            });
2747                    }
2748                    self.display.quads.push(Quad {
2749                        rect: rect.scaled(scale),
2750                        // White = untinted; radius rounds like a solid.
2751                        color: Color::WHITE,
2752                        border_color: Color::TRANSPARENT,
2753                        radius: style.radius.map(|r| r * scale),
2754                        // The sampling flag rides the slot an image never
2755                        // had a border in (decision 4).
2756                        border_w: match opts.sampling {
2757                            crate::resources::Sampling::Linear => 0.0,
2758                            crate::resources::Sampling::Nearest => 1.0,
2759                        },
2760                        blur: 0.0,
2761                        kind,
2762                        clip: clip_id,
2763                        uv,
2764                    });
2765                }
2766            }
2767            Leaf::Fragment(draw) => {
2768                // On whole pixels when the node asked (`pixelSnap`), as its
2769                // background is, so a stack of fragments meets seamlessly.
2770                let px = rect.scaled(scale);
2771                push_fragment(
2772                    self.display,
2773                    self.atlas,
2774                    &self.session.state().resources,
2775                    draw,
2776                    if style.pixel_snap { px.on_pixels() } else { px },
2777                    style.radius.map(|r| r * scale),
2778                    clip_id,
2779                    Color::WHITE,
2780                );
2781            }
2782            Leaf::Polygon(draw) => {
2783                if style.bg.is_visible() {
2784                    push_fragment(
2785                        self.display,
2786                        self.atlas,
2787                        &self.session.state().resources,
2788                        draw,
2789                        rect.scaled(scale),
2790                        crate::display::SQUARE,
2791                        clip_id,
2792                        style.bg,
2793                    );
2794                }
2795            }
2796            Leaf::Line {
2797                points,
2798                width,
2799                dash,
2800            } => {
2801                let origin = Vec2::new(rect.x, rect.y);
2802                let quads = &mut self.display.quads;
2803                // A pattern too fine to be one draws solid.
2804                let cut = dash.is_some_and(|d| {
2805                    push_marks(quads, origin, points, width, d, style.bg, clip_id, scale)
2806                });
2807                if !cut {
2808                    push_segments(quads, origin, points, width, style.bg, clip_id, scale);
2809                }
2810            }
2811            Leaf::Path {
2812                ops,
2813                rule,
2814                stroke_w,
2815                dash,
2816                hash,
2817                angle,
2818                animating,
2819            } => {
2820                let px = rect.scaled(scale);
2821                let mask = match angle {
2822                    // The mask covers the node's box at physical scale, a
2823                    // pixel over for the ramp, and is drawn on whole
2824                    // pixels with the box's fractional offset baked in at
2825                    // the nearest quarter — the bins a glyph is keyed on
2826                    // — so the quad never resamples it.
2827                    None => {
2828                        let bin_of = |f: f32| -> (f32, u8) {
2829                            let b = (f * 4.0).round() as u8;
2830                            if b >= 4 { (1.0, 0) } else { (0.0, b) }
2831                        };
2832                        let (fx, fy) = (px.x.floor(), px.y.floor());
2833                        let (cx, bx) = bin_of(px.x - fx);
2834                        let (cy, by) = bin_of(px.y - fy);
2835                        MaskAt {
2836                            at: Rect::new(
2837                                fx + cx,
2838                                fy + cy,
2839                                (px.w.ceil() + 1.0).max(1.0),
2840                                (px.h.ceil() + 1.0).max(1.0),
2841                            ),
2842                            bin: (bx, by),
2843                            off: Vec2::new(f32::from(bx) * 0.25, f32::from(by) * 0.25),
2844                            angle: 0.0,
2845                        }
2846                    }
2847                    // A turning path's box is the square about its pivot
2848                    // (ADR 0041): the mask is that square on an even
2849                    // number of pixels with the pivot at its centre, the
2850                    // centre on a whole pixel, so the quad turns about
2851                    // its own middle and, at no angle, is texel for texel.
2852                    Some(angle) => {
2853                        let side = 2.0 * (px.w * 0.5).ceil() + 2.0;
2854                        let (cx, cy) = ((px.x + px.w * 0.5).round(), (px.y + px.h * 0.5).round());
2855                        MaskAt {
2856                            at: Rect::new(cx - side * 0.5, cy - side * 0.5, side, side),
2857                            bin: crate::path::TURNED_BIN,
2858                            off: Vec2::new((side - px.w) * 0.5, (side - px.h) * 0.5),
2859                            angle,
2860                        }
2861                    }
2862                };
2863                if style.bg.is_visible() {
2864                    self.paint_mask(
2865                        ops,
2866                        hash,
2867                        scale,
2868                        mask,
2869                        crate::path::MaskPaint::Fill(rule),
2870                        style.bg,
2871                        clip_id,
2872                        animating,
2873                    );
2874                }
2875                if stroke_w > 0.0 && style.border_color.is_visible() {
2876                    self.paint_mask(
2877                        ops,
2878                        hash,
2879                        scale,
2880                        mask,
2881                        match dash {
2882                            Some(cut) => crate::path::MaskPaint::Dashed(
2883                                stroke_w * scale,
2884                                crate::line::Cut {
2885                                    lens: cut.lens.map(|l| l * scale),
2886                                    offset: cut.offset * scale,
2887                                },
2888                            ),
2889                            None => crate::path::MaskPaint::Stroke(stroke_w * scale),
2890                        },
2891                        style.border_color,
2892                        clip_id,
2893                        animating,
2894                    );
2895                }
2896            }
2897        }
2898    }
2899
2900    /// One mask quad of a path: from the atlas when the mask fits it and
2901    /// the path is still, from a texture of its own otherwise (ADR 0040,
2902    /// decisions 6–8), turned by the quad when the path turns (ADR 0041).
2903    #[allow(clippy::too_many_arguments)]
2904    fn paint_mask(
2905        &mut self,
2906        ops: &[crate::path::PathOp],
2907        hash: u64,
2908        scale: f32,
2909        mask: MaskAt,
2910        paint: crate::path::MaskPaint,
2911        color: Color,
2912        clip_id: ClipId,
2913        animating: bool,
2914    ) {
2915        let MaskAt {
2916            at,
2917            bin,
2918            off,
2919            angle,
2920        } = mask;
2921        let (w, h) = (at.w as u32, at.h as u32);
2922        let key = crate::path::mask_key(hash, scale, bin, paint);
2923        let texels = u64::from(w) * u64::from(h);
2924        let slot = if animating || texels >= crate::path::MAX_ATLAS_MASK_TEXELS {
2925            None
2926        } else {
2927            self.atlas.get_or_insert_path(key, w, h, || {
2928                crate::path::rasterize_at(ops, scale, off, w, h, paint)
2929            })
2930        };
2931        let (kind, uv) = match slot {
2932            Some(slot) => (QuadKind::GlyphMask, [slot.x, slot.y, slot.w, slot.h]),
2933            None => {
2934                let tex =
2935                    self.path_tex
2936                        .get_or_make(key, w, h, self.frame_no, self.session.id(), || {
2937                            crate::path::rasterize_at(ops, scale, off, w, h, paint)
2938                        });
2939                let index = self.display.textures.len() as u32;
2940                self.display.textures.push(crate::display::TextureDraw {
2941                    id: tex.id,
2942                    uv: [0, 0, w, h],
2943                });
2944                self.display
2945                    .texture_pixels
2946                    .push(crate::display::TexturePixels {
2947                        width: w,
2948                        height: h,
2949                        rev: 0,
2950                        rgba: tex.rgba.clone(),
2951                    });
2952                (QuadKind::Texture, [index, 0, 0, 0])
2953            }
2954        };
2955        self.display.quads.push(Quad {
2956            rect: at,
2957            color,
2958            border_color: Color::TRANSPARENT,
2959            radius: crate::display::SQUARE,
2960            border_w: 0.0,
2961            // A mask has no blur; the slot carries its turn, in radians
2962            // about the quad's centre, 0 for none (ADR 0041, decision 4).
2963            blur: angle,
2964            kind,
2965            clip: clip_id,
2966            uv,
2967        });
2968    }
2969}
2970
2971/// Where one path's masks go: the quad in physical px, on whole pixels;
2972/// the bin its masks are keyed under; where the node's box begins inside
2973/// the mask; and the quad's turn in radians.
2974#[derive(Clone, Copy)]
2975struct MaskAt {
2976    at: Rect,
2977    bin: (u8, u8),
2978    off: Vec2,
2979    angle: f32,
2980}
2981
2982#[derive(Clone, Copy)]
2983struct Paint {
2984    /// The rect of the clip the node was emitted under, logical px, in
2985    /// framebuffer space: what its hit and scroll regions are cut by. The
2986    /// whole clip — its radii, its turn, its inner clip (ADR 0043) — is
2987    /// eighty bytes and almost nothing reads it, so it is not carried:
2988    /// the painter reads the scaled entry `clip_id` names out of the
2989    /// display list, and the rare paths that want the logical clip look
2990    /// it up by node. Carrying it cost every node of every frame a copy
2991    /// and a rescale (`frame_10k_rects` +6% when it was).
2992    clip_rect: Rect,
2993    /// The clip, scaled and interned: what the node's quads name.
2994    clip_id: ClipId,
2995    scale: f32,
2996    /// Multiplied into the alpha of every quad the node emits.
2997    opacity: f32,
2998}
2999
3000/// As much of the previous frame's paint order as a departure needs to
3001/// keep its place (see `depart::Place`): the layer each node painted in,
3002/// and for the in-flow layer the next node at or after each index that
3003/// this frame still declares. Built once per frame that has a departure,
3004/// from the previous tree and the stack as that frame left it.
3005struct PaintOrder {
3006    /// The previous tree's float roots, by node: `NIL` in flow.
3007    float_root: Vec<u32>,
3008    /// By previous-tree index: the next live in-flow node at or after it;
3009    /// one past the end reads `NIL`.
3010    next_live: Vec<u32>,
3011    /// This frame's keys.
3012    live: FxHashSet<Key>,
3013    /// This frame's float roots, by key.
3014    roots: FxHashSet<Key>,
3015}
3016
3017impl PaintOrder {
3018    fn of(prev: &Tree, tree: &Tree) -> Self {
3019        let n = prev.len();
3020        let live: FxHashSet<Key> = tree.keys.iter().copied().collect();
3021        let roots: FxHashSet<Key> = (0..tree.len())
3022            .filter(|&i| tree.opens_layer(i))
3023            .map(|i| tree.keys[i])
3024            .collect();
3025        let mut float_root = vec![NIL; n];
3026        for i in 0..n {
3027            let parent = prev.parent[i];
3028            // The live pass's rule (`Tree::opens_layer`): a stroke in its
3029            // parent's box painted in the parent's layer, so a departing
3030            // one keeps its place there.
3031            float_root[i] = if prev.opens_layer(i) {
3032                i as u32
3033            } else if parent != NIL {
3034                float_root[parent as usize]
3035            } else {
3036                NIL
3037            };
3038        }
3039        let mut next_live = vec![NIL; n + 1];
3040        for j in (0..n).rev() {
3041            next_live[j] = next_live[j + 1];
3042            if float_root[j] == NIL && live.contains(&prev.keys[j]) {
3043                next_live[j] = j as u32;
3044            }
3045        }
3046        Self {
3047            float_root,
3048            next_live,
3049            live,
3050            roots,
3051        }
3052    }
3053
3054    /// The place the subtree rooted at `root` of the previous frame painted
3055    /// in: its layer, and what was painted right after it there that is
3056    /// still here. `stack` is the previous frame's float stack, bottom to
3057    /// top — where a departing float finds the layer that was over it.
3058    fn place(&self, prev: &Tree, root: usize, stack: &[(Key, u32)]) -> Place {
3059        let end = prev.subtree_end(root);
3060        let layer = self.float_root[root];
3061        if layer == NIL {
3062            let after = self.next_live[end];
3063            return Place::InFlow {
3064                before: (after != NIL).then(|| prev.keys[after as usize]),
3065            };
3066        }
3067        if layer as usize != root {
3068            // Inside a float: the next live node of the same layer, found
3069            // by a scan bounded by that layer's subtree — a departure is
3070            // rare and a float is small.
3071            let layer_end = prev.subtree_end(layer as usize);
3072            let before = (end..layer_end)
3073                .find(|&j| self.float_root[j] == layer && self.live.contains(&prev.keys[j]))
3074                .map(|j| prev.keys[j]);
3075            return Place::InLayer {
3076                layer: prev.keys[layer as usize],
3077                before,
3078            };
3079        }
3080        // A float root: under the first layer above it in the stack that
3081        // is still a float this frame.
3082        let key = prev.keys[root];
3083        let at = stack.iter().position(|&(k, _)| k == key);
3084        let before = at.and_then(|at| {
3085            stack[at + 1..]
3086                .iter()
3087                .map(|&(k, _)| k)
3088                .find(|k| self.roots.contains(k))
3089        });
3090        Place::Layer { before }
3091    }
3092}
3093
3094/// One [`QuadKind::Segment`] per straight piece of a stroke: `points` are
3095/// relative to `origin` (the node's box, logical px) and `width` is
3096/// logical; everything on the quad is physical. The rect is the piece's
3097/// bounding box padded by half the width plus two logical px, so the
3098/// backend's edge ramp is never cut by the quad's own edge, and the
3099/// endpoints ride in `uv` (see [`Quad::segment_ends`]).
3100///
3101/// Kept out of line on purpose: inlined into `emit_node`,
3102/// whose size moves with every prop a hit region grows, the loop's carried
3103/// point lost its register to the stack once the drop-zone commit tipped
3104/// the allocator — a store and a reload on every segment, +10% on
3105/// `frame_1k_curves`. On its own the loop keeps every value in a register.
3106#[inline(never)]
3107fn push_segments(
3108    quads: &mut Vec<Quad>,
3109    origin: Vec2,
3110    points: &[Vec2],
3111    width: f32,
3112    color: Color,
3113    clip_id: ClipId,
3114    scale: f32,
3115) {
3116    let pad = crate::line::pad(width) * scale;
3117    let w = width.max(0.0) * scale;
3118    for pair in points.windows(2) {
3119        let a = Vec2::new(
3120            (origin.x + pair[0].x) * scale,
3121            (origin.y + pair[0].y) * scale,
3122        );
3123        let b = Vec2::new(
3124            (origin.x + pair[1].x) * scale,
3125            (origin.y + pair[1].y) * scale,
3126        );
3127        let (x0, x1) = (a.x.min(b.x) - pad, a.x.max(b.x) + pad);
3128        let (y0, y1) = (a.y.min(b.y) - pad, a.y.max(b.y) + pad);
3129        quads.push(Quad {
3130            rect: Rect::new(x0, y0, x1 - x0, y1 - y0),
3131            color,
3132            border_color: Color::TRANSPARENT,
3133            radius: crate::display::SQUARE,
3134            border_w: w,
3135            blur: 0.0,
3136            kind: QuadKind::Segment,
3137            clip: clip_id,
3138            uv: Quad::segment_uv([a.x, a.y, b.x, b.y]),
3139        });
3140    }
3141}
3142
3143/// A dashed stroke's quads: one [`QuadKind::Segment`] per mark per
3144/// piece it lies on, as [`push_segments`] makes one per piece — a mark is
3145/// a short stroke, round caps and all, so a backend that draws a line
3146/// draws a dashed one (backlog V2). False, with nothing pushed, for a
3147/// pattern the caller draws solid: a mark and its gap under a physical
3148/// pixel together, or
3149/// more marks than [`crate::line::MAX_MARKS`].
3150///
3151/// Its own function, and never inlined, for the reason `push_segments`
3152/// is: nothing of the rare path belongs in `emit_node`.
3153#[inline(never)]
3154#[allow(clippy::too_many_arguments)]
3155fn push_marks(
3156    quads: &mut Vec<Quad>,
3157    origin: Vec2,
3158    points: &[Vec2],
3159    width: f32,
3160    cut: crate::line::Cut,
3161    color: Color,
3162    clip_id: ClipId,
3163    scale: f32,
3164) -> bool {
3165    let pad = crate::line::pad(width) * scale;
3166    let w = width.max(0.0) * scale;
3167    cut.marks(points, 1.0 / scale, |from, to| {
3168        let a = Vec2::new((origin.x + from.x) * scale, (origin.y + from.y) * scale);
3169        let b = Vec2::new((origin.x + to.x) * scale, (origin.y + to.y) * scale);
3170        let (x0, x1) = (a.x.min(b.x) - pad, a.x.max(b.x) + pad);
3171        let (y0, y1) = (a.y.min(b.y) - pad, a.y.max(b.y) + pad);
3172        quads.push(Quad {
3173            rect: Rect::new(x0, y0, x1 - x0, y1 - y0),
3174            color,
3175            border_color: Color::TRANSPARENT,
3176            radius: crate::display::SQUARE,
3177            border_w: w,
3178            blur: 0.0,
3179            kind: QuadKind::Segment,
3180            clip: clip_id,
3181            uv: Quad::segment_uv([a.x, a.y, b.x, b.y]),
3182        });
3183    })
3184}
3185
3186/// The drop shadow behind one node, in physical pixels. The quad is the
3187/// shadow's own shape — the node's rect moved by `dx`/`dy` and grown by
3188/// `spread` — inflated by `blur` on every side, because that is how far
3189/// the blurred edge reaches; the backend insets by `blur` again to find
3190/// the shape. Radii grow with the spread so a rounded box keeps its
3191/// silhouette instead of sprouting corners. Never inlined: in
3192/// `emit_node` its arithmetic took two more saved float registers for
3193/// every node, shadow or not.
3194#[inline(never)]
3195fn shadow_quad(style: &crate::spec::VisualStyle, rect: Rect, clip_id: ClipId, scale: f32) -> Quad {
3196    let sh = style.shadow;
3197    let blur = sh.blur.max(0.0);
3198    let shape = Rect::new(
3199        rect.x + sh.dx - sh.spread,
3200        rect.y + sh.dy - sh.spread,
3201        (rect.w + 2.0 * sh.spread).max(0.0),
3202        (rect.h + 2.0 * sh.spread).max(0.0),
3203    );
3204    let rect = if style.pixel_snap {
3205        // Snapped with its box, so it stays under it; the blur around it.
3206        let s = shape.scaled(scale).on_pixels();
3207        let b = blur * scale;
3208        Rect::new(s.x - b, s.y - b, s.w + 2.0 * b, s.h + 2.0 * b)
3209    } else {
3210        Rect::new(
3211            (shape.x - blur) * scale,
3212            (shape.y - blur) * scale,
3213            (shape.w + 2.0 * blur) * scale,
3214            (shape.h + 2.0 * blur) * scale,
3215        )
3216    };
3217    Quad {
3218        rect,
3219        color: sh.color,
3220        border_color: Color::TRANSPARENT,
3221        radius: style.radius.map(|r| (r + sh.spread).max(0.0) * scale),
3222        border_w: 0.0,
3223        blur: blur * scale,
3224        kind: QuadKind::Shadow,
3225        clip: clip_id,
3226        uv: [0; 4],
3227    }
3228}
3229
3230/// A node's `backdrop_blur` (backlog F129): one [`QuadKind::Backdrop`]
3231/// over the box, rounded and clipped as its background is, `blur` the
3232/// radius in physical px and the group opacity in `color.a` — how much of
3233/// the blurred picture replaces the sharp one. Pushed before the node's
3234/// own quads, so it is not in the run their fade multiplies; it carries
3235/// the opacity itself.
3236#[cold]
3237#[inline(never)]
3238fn backdrop_quad(
3239    quads: &mut Vec<Quad>,
3240    rect: Rect,
3241    style: &crate::spec::VisualStyle,
3242    paint: &Paint,
3243    radius: f32,
3244) {
3245    let px = rect.scaled(paint.scale);
3246    if px.w <= 0.0 || px.h <= 0.0 || paint.opacity <= 0.0 {
3247        return;
3248    }
3249    quads.push(Quad {
3250        rect: if style.pixel_snap { px.on_pixels() } else { px },
3251        color: Color {
3252            r: 0.0,
3253            g: 0.0,
3254            b: 0.0,
3255            a: paint.opacity.min(1.0),
3256        },
3257        border_color: Color::TRANSPARENT,
3258        radius: style.radius.map(|r| r * paint.scale),
3259        border_w: 0.0,
3260        blur: radius * paint.scale,
3261        kind: QuadKind::Backdrop,
3262        clip: paint.clip_id,
3263        uv: [0; 4],
3264    });
3265}
3266
3267/// Multiplies a group opacity into a run of quads. Alpha only: every quad
3268/// kind reads `color.a` as its coverage, so one multiply fades a
3269/// background, a border, a glyph and an image alike.
3270fn fade(quads: &mut [Quad], opacity: f32) {
3271    for q in quads {
3272        q.color.a *= opacity;
3273        q.border_color.a *= opacity;
3274    }
3275}
3276
3277/// The thumb of a scrollbar along `axis`, inset from the far edge of the
3278/// scroller's `rect`, `w` thick, and its length along the track: the
3279/// track's share of the content that is visible, never shorter than
3280/// `SCROLLBAR_MIN`, placed by how far the content has scrolled. One
3281/// geometry for both bars — the Y bar and the X bar were the same thirty
3282/// lines with the axes swapped.
3283fn thumb_along(
3284    axis: ScrollAxis,
3285    rect: Rect,
3286    track: Rect,
3287    max: f32,
3288    offset: f32,
3289    w: f32,
3290) -> (Rect, f32) {
3291    let t = (offset / max).clamp(0.0, 1.0);
3292    match axis {
3293        ScrollAxis::Y => {
3294            let bar = (track.h * rect.h / (rect.h + max)).max(SCROLLBAR_MIN);
3295            let thumb = Rect::new(
3296                rect.x + rect.w - w - SCROLLBAR_INSET,
3297                track.y + t * (track.h - bar),
3298                w,
3299                bar,
3300            );
3301            (thumb, bar)
3302        }
3303        ScrollAxis::X => {
3304            let bar = (track.w * rect.w / (rect.w + max)).max(SCROLLBAR_MIN);
3305            let thumb = Rect::new(
3306                track.x + t * (track.w - bar),
3307                rect.y + rect.h - w - SCROLLBAR_INSET,
3308                bar,
3309                w,
3310            );
3311            (thumb, bar)
3312        }
3313    }
3314}
3315
3316/// One in-flow child of a table as its rules read it: its box, and for a
3317/// row (`layout::is_table_row`) its in-flow cells' boxes.
3318struct RuledChild {
3319    rect: Rect,
3320    cells: Option<Vec<Rect>>,
3321}
3322
3323/// The rules of a table at `rect` over its in-flow `children`, `rule_w` thick
3324/// (1 when not positive):
3325///
3326/// - across, one down the middle of each gap between two in-flow
3327///   children, the content box wide;
3328/// - down, one down the middle of each gap between the columns of the
3329///   row with the most cells, over each run of consecutive rows — from
3330///   the run's first row's top to its last row's bottom.
3331///
3332/// A child that is no row — a heading text beside the rows, a `column`
3333/// section wrapping a heading over a row — is laid out across the
3334/// table and has no cells, and is ruled as a row spanning every column,
3335/// the way a `colspan` cell of a ruled HTML table is: a rule above and
3336/// below it as between rows, and the column rules stop at its edges
3337/// instead of crossing it. A table with no row has no grid to rule.
3338fn rule_lines(
3339    rect: Rect,
3340    pad: crate::geom::Edges,
3341    rule_w: f32,
3342    children: &[RuledChild],
3343) -> Vec<Rect> {
3344    let w = if rule_w > 0.0 { rule_w } else { 1.0 };
3345    let Some(widest) = children
3346        .iter()
3347        .filter_map(|c| c.cells.as_ref())
3348        .max_by_key(|cells| cells.len())
3349    else {
3350        return Vec::new();
3351    };
3352    let mut lines: Vec<Rect> = Vec::new();
3353    for pair in children.windows(2) {
3354        let (a, b) = (pair[0].rect, pair[1].rect);
3355        let y = (a.y + a.h + b.y) / 2.0;
3356        let x = rect.x + pad.l;
3357        lines.push(Rect::new(x, y - w / 2.0, rect.w - pad.l - pad.r, w));
3358    }
3359    let mut run = 0usize;
3360    while run < children.len() {
3361        if children[run].cells.is_none() {
3362            run += 1;
3363            continue;
3364        }
3365        let mut end = run;
3366        while end + 1 < children.len() && children[end + 1].cells.is_some() {
3367            end += 1;
3368        }
3369        let (top, last) = (children[run].rect.y, children[end].rect);
3370        let bottom = last.y + last.h;
3371        for pair in widest.windows(2) {
3372            let x = (pair[0].x + pair[0].w + pair[1].x) / 2.0;
3373            lines.push(Rect::new(x - w / 2.0, top, w, bottom - top));
3374        }
3375        run = end + 1;
3376    }
3377    lines
3378}
3379
3380/// Pushes a table's `lines` in `color`, faded by `paint`'s opacity, under
3381/// `clip_id`. On whole pixels, so a 1 px rule is one crisp pixel line at
3382/// any scale.
3383fn push_rules(
3384    display: &mut DisplayList,
3385    lines: &[Rect],
3386    color: Color,
3387    paint: &Paint,
3388    clip_id: ClipId,
3389) {
3390    let color = Color {
3391        a: color.a * paint.opacity,
3392        ..color
3393    };
3394    for line in lines {
3395        display.quads.push(Quad {
3396            rect: line.scaled(paint.scale).on_pixels(),
3397            color,
3398            border_color: Color::TRANSPARENT,
3399            radius: [0.0; 4],
3400            border_w: 0.0,
3401            blur: 0.0,
3402            kind: QuadKind::Solid,
3403            clip: clip_id,
3404            uv: [0; 4],
3405        });
3406    }
3407}
3408
3409fn scrollbar_quad(bar: Rect, scale: f32, clip_id: ClipId, color: Color) -> Quad {
3410    Quad {
3411        rect: bar.scaled(scale),
3412        color,
3413        border_color: Color::TRANSPARENT,
3414        radius: [bar.w.min(bar.h) / 2.0 * scale; 4],
3415        border_w: 0.0,
3416        blur: 0.0,
3417        kind: QuadKind::Solid,
3418        clip: clip_id,
3419        uv: [0; 4],
3420    }
3421}
3422
3423/// One `fragment` node's quad, live or ghost.
3424///
3425/// The handle is resolved first: a removed or foreign one draws nothing,
3426/// which is the documented fallback for every resource kind, and the
3427/// lookup is what records the `foreign-resource` warning. The quad carries
3428/// the node's own rect, radii and clip — a fragment rounds and clips like
3429/// a solid — and an opaque white `color`, whose alpha the group-opacity
3430/// pass then multiplies into; the shader reads that alpha and nothing else
3431/// of the colour, because a fragment returns its own.
3432#[allow(clippy::too_many_arguments)]
3433/// Resolves the `fit` row: the rect the pixels paint into (logical px)
3434/// and the texel rect of the image they come from. `fill` stretches the
3435/// whole image to the box; `contain` shrinks the painted rect to the
3436/// image's aspect, centred; `cover` keeps the box and crops the texels,
3437/// centred. A zero-sized image or box falls back to
3438/// `fill`, which paints nothing visible either way.
3439pub(crate) fn fit_image(
3440    fit: crate::resources::ImageFit,
3441    rect: Rect,
3442    image: Size,
3443    texels: [u32; 4],
3444) -> (Rect, [u32; 4]) {
3445    use crate::resources::ImageFit;
3446    if image.w <= 0.0 || image.h <= 0.0 || rect.w <= 0.0 || rect.h <= 0.0 {
3447        return (rect, texels);
3448    }
3449    let box_aspect = rect.w / rect.h;
3450    let image_aspect = image.w / image.h;
3451    match fit {
3452        ImageFit::Fill => (rect, texels),
3453        ImageFit::Contain => {
3454            let (w, h) = if image_aspect > box_aspect {
3455                (rect.w, rect.w / image_aspect)
3456            } else {
3457                (rect.h * image_aspect, rect.h)
3458            };
3459            (
3460                Rect::new(
3461                    rect.x + (rect.w - w) * 0.5,
3462                    rect.y + (rect.h - h) * 0.5,
3463                    w,
3464                    h,
3465                ),
3466                texels,
3467            )
3468        }
3469        ImageFit::Cover => {
3470            // Whole texels: a crop is a rect on the texture, and a
3471            // half-texel edge would sample the neighbour.
3472            let (w, h) = if image_aspect > box_aspect {
3473                ((image.h * box_aspect).round().max(1.0), image.h)
3474            } else {
3475                (image.w, (image.w / box_aspect).round().max(1.0))
3476            };
3477            let x = ((image.w - w) * 0.5).floor();
3478            let y = ((image.h - h) * 0.5).floor();
3479            (
3480                rect,
3481                [
3482                    texels[0] + x as u32,
3483                    texels[1] + y as u32,
3484                    w as u32,
3485                    h as u32,
3486                ],
3487            )
3488        }
3489    }
3490}
3491
3492/// One fragment quad and its side entry: the draw, the source a backend
3493/// compiles, and the colour the function reads as `in.color` — white for
3494/// a `fragment`, the fill for a `polygon`.
3495///
3496/// A draw naming an `image` resolves it here, where the window's atlas
3497/// is: an atlas-backed image goes into the atlas as an `image` node's
3498/// would and the draw carries its slot; a texture-backed one takes an
3499/// entry of the texture side list — the same entry an `image` node of it
3500/// would — and the draw carries the index, so the backend binds that
3501/// texture for this one quad as it does for a texture quad. An image
3502/// handle that is not live draws nothing, the fallback every resource
3503/// kind has, and the lookup is what records a foreign one.
3504#[allow(clippy::too_many_arguments)]
3505fn push_fragment(
3506    display: &mut DisplayList,
3507    atlas: &mut GlyphAtlas,
3508    resources: &crate::resources::Resources,
3509    draw: crate::fragment::Draw,
3510    rect: Rect,
3511    radius: [f32; 4],
3512    clip_id: ClipId,
3513    color: Color,
3514) {
3515    let Some(source) = resources.fragment(draw.id) else {
3516        return;
3517    };
3518    let image = match draw.image {
3519        None => crate::display::FragmentImage::None,
3520        Some(id) => {
3521            let Some(entry) = resources.image(id) else {
3522                return;
3523            };
3524            let slot = match entry.backing {
3525                crate::resources::ImageBacking::Atlas => {
3526                    atlas.get_or_insert_image(id, entry.width, entry.height, &entry.rgba)
3527                }
3528                crate::resources::ImageBacking::Texture => None,
3529            };
3530            match slot {
3531                Some(slot) => {
3532                    crate::display::FragmentImage::Atlas([slot.x, slot.y, slot.w, slot.h])
3533                }
3534                None => {
3535                    let index = display.textures.len() as u32;
3536                    let uv = [0, 0, entry.width, entry.height];
3537                    display
3538                        .textures
3539                        .push(crate::display::TextureDraw { id, uv });
3540                    display.texture_pixels.push(crate::display::TexturePixels {
3541                        width: entry.width,
3542                        height: entry.height,
3543                        rev: entry.rev,
3544                        rgba: entry.rgba.clone(),
3545                    });
3546                    crate::display::FragmentImage::Texture { index, uv }
3547                }
3548            }
3549        }
3550    };
3551    let index = display.fragments.len() as u32;
3552    display.fragments.push(crate::display::FragmentDraw {
3553        id: draw.id,
3554        params: draw.params,
3555        image,
3556    });
3557    display.fragment_sources.push(source.clone());
3558    display.quads.push(Quad {
3559        rect,
3560        // White on a `fragment` — the function returns its own colour and
3561        // reads this as `in.color` if it wants one — and the fill on a
3562        // `polygon`; `a` is the fill's alpha times the group opacity, which
3563        // the fade pass multiplies in after the node's quads are pushed.
3564        color,
3565        border_color: Color::TRANSPARENT,
3566        radius,
3567        border_w: 0.0,
3568        blur: 0.0,
3569        kind: QuadKind::Fragment,
3570        clip: clip_id,
3571        uv: [index, 0, 0, 0],
3572    });
3573}
3574
3575/// The box's own solid, at `solid`, gives its border to a ring pushed
3576/// after what the box drew over it, and keeps the background (backlog
3577/// RG152). Out of `paint_box`: a bordered picture is rare.
3578#[cold]
3579#[inline(never)]
3580fn ring_over_content(quads: &mut Vec<Quad>, solid: Option<usize>) {
3581    let Some(at) =
3582        solid.filter(|&at| quads[at].kind == QuadKind::Solid && quads[at].border_w > 0.0)
3583    else {
3584        return;
3585    };
3586    let ring = Quad {
3587        color: Color::TRANSPARENT,
3588        ..quads[at]
3589    };
3590    quads[at].border_w = 0.0;
3591    quads[at].border_color = Color::TRANSPARENT;
3592    quads.push(ring);
3593}