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