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