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