1
//! Generates a renderer-agnostic display list from a laid-out tree.
2
//!
3
//! This module is the bridge between the layout solver and the compositor/renderer.
4
//! Key types:
5
//! - [`DisplayList`] — flat, paint-order-sorted list of drawing commands
6
//! - [`DisplayListItem`] — a single drawing primitive or state-management command
7
//! - [`DisplayListBuilder`] — internal builder that accumulates items during generation
8
//!
9
//! Entry points:
10
//! - [`generate_display_list`] — converts a laid-out [`LayoutTree`] into a [`DisplayList`]
11
//! - [`paginate_display_list_with_slicer_and_breaks`] — slices a display list into pages
12
//!
13
//! Coordinates are in **absolute window-logical pixels** ([`WindowLogicalRect`]).
14
//! `HiDPI` scaling and scroll-offset conversion happen in the compositor.
15

            
16
use std::{
17
    collections::{BTreeMap, HashMap},
18
    sync::Arc,
19
};
20

            
21
use azul_core::{
22
    dom::{DomId, FormattingContext, NodeId, NodeType, ScrollbarOrientation},
23
    geom::{LogicalPosition, LogicalRect, LogicalSize},
24
    gpu::GpuValueCache,
25
    hit_test::{CursorType, ScrollPosition, TAG_TYPE_CURSOR, TAG_TYPE_DOM_NODE},
26
    resources::{IdNamespace, ImageRef, OpacityKey, RendererResources, TransformKey},
27
    selection::{Selection, SelectionRange, TextSelection},
28
    styled_dom::StyledDom,
29
    transform::ComputedTransform3D,
30
    ui_solver::GlyphInstance,
31
};
32
use azul_css::{
33
    codegen::format::GetHash,
34
    css::CssPropertyValue,
35
    props::{
36
        basic::{ColorU, FontRef, PixelValue},
37
        layout::{LayoutDisplay, LayoutOverflow, LayoutPosition},
38
        property::{CssProperty, CssPropertyType},
39
        style::{
40
            background::{ConicGradient, ExtendMode, LinearGradient, RadialGradient},
41
            border_radius::StyleBorderRadius,
42
            box_shadow::{BoxShadowClipMode, StyleBoxShadow},
43
            filter::{StyleFilter, StyleFilterVec},
44
            BorderStyle, LayoutBorderBottomWidth, LayoutBorderLeftWidth, LayoutBorderRightWidth,
45
            LayoutBorderTopWidth, StyleBorderBottomColor, StyleBorderBottomStyle,
46
            StyleBorderLeftColor, StyleBorderLeftStyle, StyleBorderRightColor,
47
            StyleBorderRightStyle, StyleBorderTopColor, StyleBorderTopStyle,
48
        },
49
    },
50
    LayoutDebugMessage,
51
};
52

            
53
#[cfg(feature = "text_layout")]
54
use crate::text3;
55
#[cfg(feature = "text_layout")]
56
use crate::text3::cache::{InlineShape, PositionedItem};
57
use crate::{
58
    debug_info,
59
    font_traits::{
60
        FontHash, FontLoaderTrait, ImageSource, InlineContent, ParsedFontTrait, ShapedItem,
61
        UnifiedLayout,
62
    },
63
    solver3::{
64
        getters::{
65
            get_background_color, get_background_contents, get_border_info, get_border_radius,
66
            get_break_after, get_break_before, get_caret_style, get_overflow_clip_margin_property,
67
            get_overflow_x, get_overflow_y, get_scrollbar_gutter_property,
68
            get_scrollbar_info_from_layout, get_scrollbar_style, get_selection_style,
69
            get_style_border_radius, get_visibility, get_z_index, is_forced_page_break, BorderInfo,
70
            CaretStyle, ComputedScrollbarStyle, SelectionStyle,
71
        },
72
        layout_tree::{LayoutNode, LayoutNodeHot, LayoutNodeId, LayoutNodeWarm, LayoutTree},
73
        positioning::get_position_type,
74
        scrollbar::{compute_scrollbar_geometry_with_button_size, ScrollbarRequirements},
75
        LayoutContext, LayoutError, Result,
76
    },
77
};
78

            
79
const APPROX_ASCENT_RATIO: f32 = 0.8;
80
const APPROX_UNDERLINE_THICKNESS_RATIO: f32 = 0.08;
81
const APPROX_UNDERLINE_OFFSET_RATIO: f32 = 0.12;
82
const APPROX_STRIKETHROUGH_OFFSET_RATIO: f32 = 0.3;
83
const APPROX_OVERLINE_OFFSET_RATIO: f32 = 0.85;
84
const APPROX_ELLIPSIS_WIDTH_RATIO: f32 = 0.6;
85
const DEFAULT_A4_WIDTH_PT: f32 = 595.0;
86
const DEFAULT_SHADOW_FONT_SIZE_PX: f32 = 16.0;
87

            
88
/// Border widths for all four sides.
89
///
90
/// Each field is optional to allow partial border specifications.
91
/// Used in [`DisplayListItem::Border`] to specify per-side border widths.
92
#[derive(Debug, Clone, Copy)]
93
pub struct StyleBorderWidths {
94
    /// Top border width (CSS `border-top-width`)
95
    pub top: Option<CssPropertyValue<LayoutBorderTopWidth>>,
96
    /// Right border width (CSS `border-right-width`)
97
    pub right: Option<CssPropertyValue<LayoutBorderRightWidth>>,
98
    /// Bottom border width (CSS `border-bottom-width`)
99
    pub bottom: Option<CssPropertyValue<LayoutBorderBottomWidth>>,
100
    /// Left border width (CSS `border-left-width`)
101
    pub left: Option<CssPropertyValue<LayoutBorderLeftWidth>>,
102
}
103

            
104
/// Border colors for all four sides.
105
///
106
/// Each field is optional to allow partial border specifications.
107
/// Used in [`DisplayListItem::Border`] to specify per-side border colors.
108
#[derive(Debug, Clone, Copy)]
109
pub struct StyleBorderColors {
110
    /// Top border color (CSS `border-top-color`)
111
    pub top: Option<CssPropertyValue<StyleBorderTopColor>>,
112
    /// Right border color (CSS `border-right-color`)
113
    pub right: Option<CssPropertyValue<StyleBorderRightColor>>,
114
    /// Bottom border color (CSS `border-bottom-color`)
115
    pub bottom: Option<CssPropertyValue<StyleBorderBottomColor>>,
116
    /// Left border color (CSS `border-left-color`)
117
    pub left: Option<CssPropertyValue<StyleBorderLeftColor>>,
118
}
119

            
120
/// Border styles for all four sides.
121
///
122
/// Each field is optional to allow partial border specifications.
123
/// Used in [`DisplayListItem::Border`] to specify per-side border styles
124
/// (solid, dashed, dotted, none, etc.).
125
#[derive(Debug, Clone, Copy)]
126
pub struct StyleBorderStyles {
127
    /// Top border style (CSS `border-top-style`)
128
    pub top: Option<CssPropertyValue<StyleBorderTopStyle>>,
129
    /// Right border style (CSS `border-right-style`)
130
    pub right: Option<CssPropertyValue<StyleBorderRightStyle>>,
131
    /// Bottom border style (CSS `border-bottom-style`)
132
    pub bottom: Option<CssPropertyValue<StyleBorderBottomStyle>>,
133
    /// Left border style (CSS `border-left-style`)
134
    pub left: Option<CssPropertyValue<StyleBorderLeftStyle>>,
135
}
136

            
137
/// A rectangle in border-box coordinates (includes padding and border).
138
/// This is what layout calculates and stores in `used_size` and absolute positions.
139
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
140
pub struct BorderBoxRect(pub LogicalRect);
141

            
142
/// A `LogicalRect` known to be in **absolute window coordinates** (as output
143
/// by the layout engine).
144
///
145
/// All spatial bounds stored in [`DisplayListItem`] use
146
/// this type so that the compositor is *forced* to convert them to
147
/// frame-relative coordinates before passing them to `WebRender`.
148
///
149
/// ## Coordinate-space contract
150
///
151
/// * **Layout engine** produces `WindowLogicalRect` values.
152
/// * **Compositor** converts via `resolve_rect()` → `WebRender` `LayoutRect`.
153
/// * Passing a `WindowLogicalRect` directly to a `WebRender` push function is a **type error** (it
154
///   wraps `LogicalRect`, not `LayoutRect`).
155
#[derive(Debug, Copy, Clone, Default, PartialEq, PartialOrd, Eq, Ord, Hash)]
156
pub struct WindowLogicalRect(pub LogicalRect);
157

            
158
/// Anything at or below this is the unassigned-position sentinel, not geometry.
159
///
160
/// The sentinel is exactly `f32::MIN`; the threshold is deliberately a little
161
/// looser so a sentinel that has been through one offset addition (which barely
162
/// moves a value of that magnitude) is still recognised.
163
const UNASSIGNED_POSITION_LIMIT: f32 = f32::MIN / 2.0;
164

            
165
impl WindowLogicalRect {
166
    #[inline]
167
    #[must_use]
168
56
    pub const fn new(origin: LogicalPosition, size: LogicalSize) -> Self {
169
56
        Self(LogicalRect::new(origin, size))
170
56
    }
171

            
172
    #[inline]
173
    #[must_use]
174
8
    pub const fn zero() -> Self {
175
8
        Self(LogicalRect::zero())
176
8
    }
177

            
178
    /// Access the inner `LogicalRect` (still in window space – the caller is
179
    /// responsible for applying any offset conversion).
180
    #[inline]
181
    #[must_use]
182
2790842
    pub const fn inner(&self) -> &LogicalRect {
183
2790842
        &self.0
184
2790842
    }
185

            
186
    #[inline]
187
    #[must_use]
188
23603
    pub const fn into_inner(self) -> LogicalRect {
189
23603
        self.0
190
23603
    }
191

            
192
    // Convenience accessors
193
    #[inline]
194
    #[must_use]
195
118
    pub const fn origin(&self) -> LogicalPosition {
196
118
        self.0.origin
197
118
    }
198
    #[inline]
199
    #[must_use]
200
125
    pub const fn size(&self) -> LogicalSize {
201
125
        self.0.size
202
125
    }
203
}
204

            
205
impl From<LogicalRect> for WindowLogicalRect {
206
    #[inline]
207
2151404
    fn from(r: LogicalRect) -> Self {
208
2151404
        Self(r)
209
2151404
    }
210
}
211

            
212
impl From<WindowLogicalRect> for LogicalRect {
213
    #[inline]
214
1
    fn from(w: WindowLogicalRect) -> Self {
215
1
        w.0
216
1
    }
217
}
218

            
219
/// Simple struct for passing element dimensions to border-radius calculation
220
#[derive(Debug, Clone, Copy)]
221
pub struct PhysicalSizeImport {
222
    pub width: f32,
223
    pub height: f32,
224
}
225

            
226
/// Complete drawing information for a scrollbar with all visual components.
227
///
228
/// This contains the resolved geometry and colors for all scrollbar parts:
229
/// - Track: The background area where the thumb slides
230
/// - Thumb: The draggable indicator showing current scroll position
231
/// - Buttons: Optional up/down or left/right arrow buttons
232
/// - Corner: The area where horizontal and vertical scrollbars meet
233
#[derive(Debug, Clone, PartialEq)]
234
pub struct ScrollbarDrawInfo {
235
    /// Overall bounds of the entire scrollbar (including track and buttons)
236
    pub bounds: WindowLogicalRect,
237
    /// Scrollbar orientation (horizontal or vertical)
238
    pub orientation: ScrollbarOrientation,
239

            
240
    // Track area (the background rail)
241
    /// Bounds of the track area
242
    pub track_bounds: WindowLogicalRect,
243
    /// Color of the track background
244
    pub track_color: ColorU,
245

            
246
    // Thumb (the draggable part)
247
    /// Bounds of the thumb
248
    pub thumb_bounds: WindowLogicalRect,
249
    /// Color of the thumb
250
    pub thumb_color: ColorU,
251
    /// Border radius for rounded thumb corners
252
    pub thumb_border_radius: BorderRadius,
253

            
254
    // Optional buttons (arrows at ends)
255
    /// Optional decrement button bounds (up/left arrow)
256
    pub button_decrement_bounds: Option<WindowLogicalRect>,
257
    /// Optional increment button bounds (down/right arrow)
258
    pub button_increment_bounds: Option<WindowLogicalRect>,
259
    /// Color for buttons
260
    pub button_color: ColorU,
261

            
262
    /// Optional opacity key for GPU-side fading animation.
263
    pub opacity_key: Option<OpacityKey>,
264
    /// Optional transform key for GPU-side scrollbar thumb positioning.
265
    /// When present, the compositor will wrap the thumb in a `PushReferenceFrame`
266
    /// with `PropertyBinding::Binding` so `WebRender` can animate the thumb position
267
    /// without rebuilding the display list.
268
    pub thumb_transform_key: Option<TransformKey>,
269
    /// Initial transform for the scrollbar thumb (current scroll position).
270
    /// This is the transform applied when the display list is first built.
271
    /// During GPU-only scroll, `synchronize_gpu_values` updates this dynamically.
272
    pub thumb_initial_transform: ComputedTransform3D,
273
    /// Optional hit-test ID for `WebRender` hit-testing.
274
    pub hit_id: Option<azul_core::hit_test::ScrollbarHitId>,
275
    /// Whether to clip scrollbar to container's border-radius
276
    pub clip_to_container_border: bool,
277
    /// Container's border-radius (for clipping)
278
    pub container_border_radius: BorderRadius,
279
    /// Scrollbar visibility mode — used by back-registration to choose initial opacity.
280
    /// `Always` → initial opacity 1.0; `WhenScrolling` → initial opacity 0.0.
281
    pub visibility: azul_css::props::style::scrollbar::ScrollbarVisibilityMode,
282
}
283

            
284
impl BorderBoxRect {
285
    /// Convert border-box to content-box by subtracting padding and border.
286
    /// Content-box is where inline layout and text actually render.
287
    #[must_use]
288
327348
    pub fn to_content_box(
289
327348
        self,
290
327348
        padding: &crate::solver3::geometry::EdgeSizes,
291
327348
        border: &crate::solver3::geometry::EdgeSizes,
292
327348
    ) -> ContentBoxRect {
293
327348
        ContentBoxRect(LogicalRect {
294
327348
            origin: LogicalPosition {
295
327348
                x: self.0.origin.x + padding.left + border.left,
296
327348
                y: self.0.origin.y + padding.top + border.top,
297
327348
            },
298
327348
            size: LogicalSize {
299
327348
                width: self.0.size.width
300
327348
                    - padding.left
301
327348
                    - padding.right
302
327348
                    - border.left
303
327348
                    - border.right,
304
327348
                height: self.0.size.height
305
327348
                    - padding.top
306
327348
                    - padding.bottom
307
327348
                    - border.top
308
327348
                    - border.bottom,
309
327348
            },
310
327348
        })
311
327348
    }
312

            
313
    /// Convert border-box to padding-box by subtracting only the border.
314
    ///
315
    /// THE SCROLLPORT. CSS Overflow 3 §2: "scrolling occurs within the padding
316
    /// box", and azul measures overflow content against the padding box too
317
    /// (`compute_scrollbar_geometry`, `register_scroll_nodes`), so the clamp
318
    /// range `max_scroll = content − scrollport` is only self-consistent if
319
    /// every consumer takes ORIGIN AND SIZE off this box.
320
    #[must_use]
321
254820
    pub fn to_padding_box(self, border: &crate::solver3::geometry::EdgeSizes) -> PaddingBoxRect {
322
254820
        PaddingBoxRect(LogicalRect {
323
254820
            origin: LogicalPosition {
324
254820
                x: self.0.origin.x + border.left,
325
254820
                y: self.0.origin.y + border.top,
326
254820
            },
327
254820
            size: LogicalSize {
328
254820
                width: self.0.size.width - border.left - border.right,
329
254820
                height: self.0.size.height - border.top - border.bottom,
330
254820
            },
331
254820
        })
332
254820
    }
333

            
334
    /// Get the inner `LogicalRect`
335
    #[must_use]
336
4
    pub const fn rect(&self) -> LogicalRect {
337
4
        self.0
338
4
    }
339
}
340

            
341
/// A rectangle in padding-box coordinates (excludes border, includes padding).
342
///
343
/// This is the CSS **scrollport**: the box a scroll container's content is
344
/// clipped to and scrolls within.
345
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
346
pub struct PaddingBoxRect(pub LogicalRect);
347

            
348
impl PaddingBoxRect {
349
    /// Get the inner `LogicalRect`
350
    #[must_use]
351
254820
    pub const fn rect(&self) -> LogicalRect {
352
254820
        self.0
353
254820
    }
354
}
355

            
356
/// A rectangle in content-box coordinates (excludes padding and border).
357
/// This is where text and inline content is positioned by the inline formatter.
358
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
359
pub struct ContentBoxRect(pub LogicalRect);
360

            
361
impl ContentBoxRect {
362
    /// Get the inner `LogicalRect`
363
    #[must_use]
364
327351
    pub const fn rect(&self) -> LogicalRect {
365
327351
        self.0
366
327351
    }
367
}
368

            
369
/// The final, renderer-agnostic output of the layout engine.
370
///
371
/// This is a flat list of drawing and state-management commands, already sorted
372
/// according to the CSS paint order. A renderer can consume this list directly.
373
/// A CSS-forced page break recorded while building the display list.
374
#[derive(Debug, Clone, Copy, PartialEq)]
375
pub struct ForcedBreak {
376
    /// Absolute document-space Y of the break.
377
    pub y: f32,
378
    /// The node whose `break-before`/`break-after` property forced it.
379
    /// `None` only for synthetic inputs (tests, hand-built lists).
380
    pub causing_node: Option<NodeId>,
381
}
382

            
383
#[derive(Debug, Default, Clone)]
384
pub struct DisplayList {
385
    pub items: Vec<DisplayListItem>,
386
    /// Optional mapping from item index to the DOM `NodeId` that generated it.
387
    /// Used for pagination to look up CSS break properties.
388
    /// Not all items have a source node (e.g., synthesized decorations).
389
    pub node_mapping: Vec<Option<NodeId>>,
390
    /// Forced page breaks (from break-before/break-after: always), with the
391
    /// node whose break property caused each one. Y coordinates are absolute
392
    /// in the infinite canvas coordinate system; the slicer aligns page
393
    /// boundaries with these positions.
394
    pub forced_page_breaks: Vec<ForcedBreak>,
395
    /// Index ranges (start, end) of display list items that belong to fixed-position elements.
396
    /// In paged media, these items are replicated on every page (CSS Positioned Layout §2.1).
397
    pub fixed_position_item_ranges: Vec<(usize, usize)>,
398
    /// Per-item PROVEN uniform background (Text items only, None elsewhere).
399
    /// Parallel to `items` like `node_mapping`. Lives on the LIST rather
400
    /// than in the `Text` variant because printpdf (crates.io, immutable)
401
    /// pattern-matches the variant exhaustively — a new variant field is a
402
    /// downstream semver break; a new list field is not. See
403
    /// `compute_uniform_text_bg` for what "proven" means and the raster's
404
    /// pre-blended tile path for what it buys (~6 ms/repaint of per-pixel
405
    /// linear LCD compositing).
406
    pub uniform_text_bgs: Vec<Option<(ColorU, WindowLogicalRect)>>,
407
    /// Per-item `(unselected, selected)` text colours of a `Text` item emitted
408
    /// under a `::selection` recolour, `None` elsewhere. Parallel to `items`.
409
    ///
410
    /// The list carries each run in ONE colour — its final selection state.
411
    /// While the selection highlight glides (`LayoutWindow::apply_text_tweens`)
412
    /// the glyphs its edge crosses must be painted in BOTH colours, split at
413
    /// the animated edge, or white text shows on the background (or black text
414
    /// inside the highlight) until the glide ends. This table is where the
415
    /// post-pass finds the colour the run is NOT painted in. It lives on the
416
    /// list, like `uniform_text_bgs`, so the `Text` variant stays unchanged.
417
    pub text_selection_colors: Vec<Option<(ColorU, ColorU)>>,
418
    /// Per-item (layout-tree index, emission phase) — the DL-PATCHING key.
419
    /// `node_mapping` attributes items to DOM ids, but patching substitutes
420
    /// per LAYOUT-NODE PAINT CALL: on a resize-skip pass the tree object and
421
    /// its indices are unchanged, so a node's cached items can replace a
422
    /// paint call — IF the run for the bg/border call can be told apart from
423
    /// the run for the content call and from items the SC walk itself pushes
424
    /// (scroll-frame hit areas, clips, scrollbars — those always re-emit
425
    /// fresh). Parallel to `items`, like `node_mapping`.
426
    pub layout_node_mapping: Vec<Option<(usize, EmitPhase)>>,
427
}
428

            
429
impl DisplayList {
430
    /// Insert one item at `at`, keeping EVERY parallel array and index range
431
    /// consistent.
432
    ///
433
    /// `items` has four vectors parallel to it (`node_mapping`,
434
    /// `uniform_text_bgs`, `layout_node_mapping`) plus
435
    /// `fixed_position_item_ranges`, which stores INDEX RANGES into `items`.
436
    /// A bare `items.insert(at, x)` therefore misaligns the per-item side
437
    /// tables from `at` onwards — the raster then reads another item's proven
438
    /// background, and the patch key attributes an item to the wrong layout
439
    /// node — and silently moves every fixed-position range off its items.
440
    /// Appending at the END is the only insertion that gets away with it, which
441
    /// is why this was not needed until the focus ring had to go INSIDE a
442
    /// scroll frame.
443
    ///
444
    /// `at` is clamped to the end, so an index computed from a stale view of
445
    /// the list cannot panic here.
446
74
    pub fn insert_item(&mut self, at: usize, item: DisplayListItem, node: Option<NodeId>) {
447
74
        let at = at.min(self.items.len());
448
74
        self.items.insert(at, item);
449
        // The side tables are allowed to be SHORTER than `items` (older code
450
        // appended without extending them), so grow before indexing.
451
74
        Self::insert_parallel(&mut self.node_mapping, at, node);
452
74
        Self::insert_parallel(&mut self.uniform_text_bgs, at, None);
453
74
        Self::insert_parallel(&mut self.text_selection_colors, at, None);
454
74
        Self::insert_parallel(&mut self.layout_node_mapping, at, None);
455
75
        for (start, end) in &mut self.fixed_position_item_ranges {
456
            // A range that CONTAINS the insertion point grows; one entirely
457
            // after it slides. `end` is exclusive, so `at == *end` is "after".
458
1
            if *start >= at {
459
1
                *start += 1;
460
1
            }
461
1
            if *end > at {
462
1
                *end += 1;
463
1
            }
464
        }
465
74
    }
466

            
467
    /// Insert into a side table that may be shorter than `items`, padding with
468
    /// the default first so the entry lands at the right index.
469
296
    fn insert_parallel<T: Clone + Default>(v: &mut Vec<T>, at: usize, value: T) {
470
296
        if v.len() < at {
471
5
            v.resize(at, T::default());
472
291
        }
473
296
        v.insert(at, value);
474
296
    }
475

            
476
    /// Replace item `at` with `replacement` (each with its own proven text
477
    /// background), keeping every parallel table and every fixed-position
478
    /// range aligned. The new items inherit the replaced item's DOM and
479
    /// layout attribution and its selection colours: they are pieces of the
480
    /// same paint call. An empty `replacement` removes the item.
481
    ///
482
    /// For post-passes that split one item (the tween's glyph reveal and
483
    /// selection split). Splicing from the BACK of the list keeps the
484
    /// indices of earlier items valid.
485
1930
    pub fn splice_item(
486
1930
        &mut self,
487
1930
        at: usize,
488
1930
        replacement: Vec<(DisplayListItem, Option<(ColorU, WindowLogicalRect)>)>,
489
1930
    ) {
490
1930
        if at >= self.items.len() {
491
            return;
492
1930
        }
493
1930
        let n = replacement.len();
494
1930
        let node = self.node_mapping.get(at).copied().flatten();
495
1930
        let layout = self.layout_node_mapping.get(at).copied().flatten();
496
1930
        let colors = self.text_selection_colors.get(at).copied().flatten();
497
        // Side tables may be shorter than `items`; pad before splicing.
498
1930
        let len = self.items.len();
499
1930
        if self.node_mapping.len() < len {
500
            self.node_mapping.resize(len, None);
501
1930
        }
502
1930
        if self.uniform_text_bgs.len() < len {
503
            self.uniform_text_bgs.resize(len, None);
504
1930
        }
505
1930
        if self.text_selection_colors.len() < len {
506
            self.text_selection_colors.resize(len, None);
507
1930
        }
508
1930
        if self.layout_node_mapping.len() < len {
509
            self.layout_node_mapping.resize(len, None);
510
1930
        }
511
1930
        let (items, bgs): (Vec<DisplayListItem>, Vec<Option<(ColorU, WindowLogicalRect)>>) =
512
1930
            replacement.into_iter().unzip();
513
1930
        self.items.splice(at..=at, items);
514
1930
        self.node_mapping.splice(at..=at, core::iter::repeat_n(node, n));
515
1930
        self.uniform_text_bgs.splice(at..=at, bgs);
516
1930
        self.text_selection_colors
517
1930
            .splice(at..=at, core::iter::repeat_n(colors, n));
518
1930
        self.layout_node_mapping
519
1930
            .splice(at..=at, core::iter::repeat_n(layout, n));
520
        // One item became `n`: ranges after it slide by n - 1, a range
521
        // containing it grows (or shrinks) by the same amount.
522
1930
        let grow = n as isize - 1;
523
1930
        if grow != 0 {
524
1880
            for (start, end) in &mut self.fixed_position_item_ranges {
525
                if *start > at {
526
                    *start = start.saturating_add_signed(grow);
527
                }
528
                if *end > at {
529
                    *end = end.saturating_add_signed(grow);
530
                }
531
            }
532
50
        }
533
1930
    }
534

            
535
    /// Approximate heap bytes retained by this display list — the
536
    /// item vec + parallel vecs + every item's owned heap. The memory
537
    /// report used to charge a FLAT 2 KiB for a cached display list;
538
    /// on a paginated document the `Text` items alone hold an offset
539
    /// COPY of every painted glyph (20 B each), which made the single
540
    /// biggest DL cost invisible ("a zero is not a measurement" — and
541
    /// so is a constant).
542
    ///
543
    /// Returns `(bytes, text_instances, item_count)` — the counters that
544
    /// explain the byte figure (glyph copies vs item slots), same pattern
545
    /// as the cluster counters on the tree report.
546
    #[must_use]
547
2
    pub fn retained_bytes(&self) -> (usize, usize, usize) {
548
        use core::mem::size_of;
549
2
        let mut bytes = self.items.capacity() * size_of::<DisplayListItem>()
550
2
            + self.node_mapping.capacity() * size_of::<Option<NodeId>>()
551
2
            + self.forced_page_breaks.capacity() * size_of::<ForcedBreak>()
552
2
            + self.fixed_position_item_ranges.capacity() * size_of::<(usize, usize)>()
553
2
            + self.uniform_text_bgs.capacity() * size_of::<Option<(ColorU, WindowLogicalRect)>>()
554
2
            + self.text_selection_colors.capacity() * size_of::<Option<(ColorU, ColorU)>>()
555
2
            + self.layout_node_mapping.capacity() * size_of::<Option<(usize, EmitPhase)>>();
556
2
        let mut text_instances = 0usize;
557
4
        for item in &self.items {
558
2
            bytes += Self::item_heap_bytes(item, &mut text_instances);
559
2
        }
560
2
        (bytes, text_instances, self.items.len())
561
2
    }
562

            
563
    /// Owned heap hanging off one item. EXHAUSTIVE on purpose — a new
564
    /// variant must fail this match so its heap gets classified rather
565
    /// than silently uncounted. `Arc`/`ImageRef` fields are CLONES of
566
    /// allocations owned (and counted) elsewhere → 0 here.
567
2
    const fn item_heap_bytes(item: &DisplayListItem, text_instances: &mut usize) -> usize {
568
        use core::mem::size_of;
569

            
570
        use DisplayListItem as I;
571
2
        match item {
572
2
            I::Text { glyphs, .. } => {
573
2
                *text_instances += glyphs.len();
574
2
                glyphs.capacity() * size_of::<GlyphInstance>()
575
            }
576
            I::ScrollBarStyled { .. } => size_of::<ScrollbarDrawInfo>(),
577
            // The rings the stroke walks. Bounded by the path, not the
578
            // document, and cloned from the DOM's own geometry.
579
            I::StrokedPath { .. } => 0,
580
            I::LinearGradient { gradient, .. } => {
581
                gradient.stops.len()
582
                    * size_of::<azul_css::props::style::NormalizedLinearColorStop>()
583
            }
584
            I::RadialGradient { gradient, .. } => {
585
                gradient.stops.len()
586
                    * size_of::<azul_css::props::style::NormalizedLinearColorStop>()
587
            }
588
            I::ConicGradient { gradient, .. } => {
589
                gradient.stops.len()
590
                    * size_of::<azul_css::props::style::NormalizedRadialColorStop>()
591
            }
592
            I::PushFilter { filters, .. } | I::PushBackdropFilter { filters, .. } => {
593
                filters.capacity() * size_of::<StyleFilter>()
594
            }
595
            // Arc / ImageRef clones — owned and counted elsewhere.
596
            I::TextLayout { .. } | I::Image { .. } | I::PushImageMaskClip { .. } => 0,
597
            // Flat payloads: everything lives inline in the enum variant,
598
            // already covered by `items.capacity() * size_of::<DisplayListItem>()`.
599
            I::Rect { .. }
600
            | I::SelectionRect { .. }
601
            | I::CursorRect { .. }
602
            | I::Border { .. }
603
            | I::Underline { .. }
604
            | I::Strikethrough { .. }
605
            | I::Overline { .. }
606
            | I::ScrollBar { .. }
607
            | I::VirtualView { .. }
608
            | I::VirtualViewPlaceholder { .. }
609
            | I::PushClip { .. }
610
            | I::PopClip
611
            | I::PopImageMaskClip
612
            | I::PushScrollFrame { .. }
613
            | I::PopScrollFrame
614
            | I::PushStackingContext { .. }
615
            | I::PopStackingContext
616
            | I::PushReferenceFrame { .. }
617
            | I::PopReferenceFrame
618
            | I::HitTestArea { .. }
619
            | I::BoxShadow { .. }
620
            | I::PopFilter
621
            | I::PopBackdropFilter
622
            | I::PushOpacity { .. }
623
            | I::PopOpacity
624
            | I::PushTextShadow { .. }
625
            | I::PopTextShadow => 0,
626
        }
627
2
    }
628
}
629

            
630
/// Translate a display-list item's geometry by `delta` (DL patching:
631
/// same item content, moved node). Every variant the two paint fns can
632
/// emit is handled; variants outside `patchable_item` never reach this
633
/// (`PatchState::build` forces their node into the re-emit set).
634
#[must_use]
635
538
pub(crate) fn translate_item(mut item: DisplayListItem, delta: LogicalPosition) -> DisplayListItem {
636
    use DisplayListItem as I;
637
538
    if delta.x == 0.0 && delta.y == 0.0 {
638
535
        return item;
639
3
    }
640
3
    let shift = |b: &mut WindowLogicalRect| {
641
3
        b.0.origin.x += delta.x;
642
3
        b.0.origin.y += delta.y;
643
3
    };
644
3
    match &mut item {
645
        I::Rect { bounds, .. }
646
        | I::SelectionRect { bounds, .. }
647
        | I::CursorRect { bounds, .. }
648
        | I::Border { bounds, .. }
649
        | I::TextLayout { bounds, .. }
650
        | I::Underline { bounds, .. }
651
        | I::Strikethrough { bounds, .. }
652
        | I::Overline { bounds, .. }
653
        | I::Image { bounds, .. }
654
        | I::LinearGradient { bounds, .. }
655
        | I::RadialGradient { bounds, .. }
656
        | I::ConicGradient { bounds, .. }
657
        | I::BoxShadow { bounds, .. }
658
2
        | I::HitTestArea { bounds, .. } => shift(bounds),
659
        I::Text {
660
1
            glyphs, clip_rect, ..
661
        } => {
662
40
            for g in glyphs.iter_mut() {
663
40
                g.point.x += delta.x;
664
40
                g.point.y += delta.y;
665
40
            }
666
1
            shift(clip_rect);
667
        }
668
        // No geometry of their own.
669
        I::PushTextShadow { .. } | I::PopTextShadow => {}
670
        // Anything else is untranslatable by contract (see patchable_item).
671
        _ => {}
672
    }
673
3
    item
674
538
}
675

            
676
/// Paint the glyphs a gliding caret or selection edge is crossing in BOTH of
677
/// their configurations, split exactly at the animated edge.
678
///
679
/// The display list holds text in its FINAL state, while
680
/// `LayoutWindow::apply_text_tweens` animates only the caret and highlight
681
/// rects. Without this, a typed glyph appeared whole while the caret was
682
/// still sliding towards it, and a glyph changed colour the moment a
683
/// selection started to grow, long before the highlight reached it (white on
684
/// the page, or black inside the blue).
685
///
686
/// * `caret` = `(from, to, rendered)` of a glide caused by TYPING
687
///   ([`crate::managers::text_edit::CaretTweenTrack::reveal`]). On the caret's
688
///   line, glyphs whose origin lies in `[from.x - font_size, to.x)` are the
689
///   ones being revealed: they are clipped at the rendered caret's CENTRE and
690
///   appear as it passes over them. The `font_size` margin keeps a glyph that
691
///   straddled an earlier glide's edge continuous across a retarget.
692
/// * `selection` = `(current, rendered)` highlight bands, one pair per line.
693
///   Glyphs near an edge that moves get three pieces clipped at the rendered
694
///   band: unselected colour left of it, `::selection` colour inside it,
695
///   unselected colour right of it. The colours come from
696
///   [`DisplayList::text_selection_colors`]; a run without them is left
697
///   alone.
698
///
699
/// Only the x extent of a piece is clipped. Its glyphs are filtered to one
700
/// line, so ink above or below the line box is untouched.
701
#[allow(clippy::too_many_lines)]
702
2031
pub fn split_text_for_glides(
703
2031
    dl: &mut DisplayList,
704
2031
    caret: Option<(LogicalRect, LogicalRect, LogicalRect)>,
705
2031
    selection: Option<(&[LogicalRect], &[LogicalRect])>,
706
2031
) {
707
    type Piece = (Vec<GlyphInstance>, ColorU, LogicalRect, Option<(ColorU, WindowLogicalRect)>);
708

            
709
    /// `clip` narrowed to `[x0, x1)`, or `None` when nothing is left.
710
1970
    fn clip_x(clip: LogicalRect, x0: f32, x1: f32) -> Option<LogicalRect> {
711
1970
        let left = clip.origin.x.max(x0);
712
1970
        let right = (clip.origin.x + clip.size.width).min(x1);
713
1970
        (right > left).then_some(LogicalRect {
714
1970
            origin: LogicalPosition {
715
1970
                x: left,
716
1970
                y: clip.origin.y,
717
1970
            },
718
1970
            size: LogicalSize {
719
1970
                width: right - left,
720
1970
                height: clip.size.height,
721
1970
            },
722
1970
        })
723
1970
    }
724
14051280
    fn on_line(g: &GlyphInstance, top: f32, bottom: f32) -> bool {
725
14051280
        g.point.y >= top && g.point.y <= bottom
726
14051280
    }
727

            
728
    // A caret glide reveals only on its own line and only while moving
729
    // forward: text typed at a caret pushes it right, and the glyphs behind a
730
    // backward move were deleted, not hidden.
731
2031
    let caret = caret.filter(|(from, to, _)| {
732
1920
        (from.origin.y - to.origin.y).abs() < to.size.height * 0.5
733
1910
            && to.origin.x > from.origin.x + 0.5
734
1920
    });
735
2031
    let selection = selection.filter(|(current, rendered)| {
736
242
        current.len() == rendered.len() && current.iter().zip(rendered.iter()).any(|(c, r)| c != r)
737
111
    });
738
2031
    if caret.is_none() && selection.is_none() {
739
41
        return;
740
1990
    }
741

            
742
1214180
    for i in (0..dl.items.len()).rev() {
743
        let DisplayListItem::Text {
744
480480
            glyphs,
745
480480
            font_hash,
746
480480
            font_size_px,
747
480480
            color,
748
480480
            clip_rect,
749
480480
            source_node_index,
750
1214180
        } = &dl.items[i]
751
        else {
752
733700
            continue;
753
        };
754
480480
        let (font_hash, font_size, source_node_index) = (*font_hash, *font_size_px, *source_node_index);
755
480480
        let margin = font_size.max(1.0);
756
480480
        let bg = dl.uniform_text_bgs.get(i).copied().flatten();
757
480480
        let mut pieces: Vec<Piece> = vec![(glyphs.clone(), *color, clip_rect.0, bg)];
758
480480
        let mut changed = false;
759

            
760
110
        if let (Some((current, rendered)), Some((unselected, selected))) =
761
480480
            (selection, dl.text_selection_colors.get(i).copied().flatten())
762
        {
763
110
            let mut next: Vec<Piece> = Vec::new();
764
220
            for (piece_glyphs, piece_color, clip, piece_bg) in pieces {
765
110
                let mut rest = Vec::new();
766
110
                let mut per_band: Vec<Vec<GlyphInstance>> = vec![Vec::new(); current.len()];
767
1040
                for g in piece_glyphs {
768
2540
                    let band = current.iter().zip(rendered.iter()).position(|(c, r)| {
769
2540
                        if c == r {
770
1610
                            return false;
771
930
                        }
772
                        // The glyph's OWN line: the final band's line box. A
773
                        // band sliding in from another line overlaps this one
774
                        // mid-glide, and matching glyphs to it split them at
775
                        // that band's edges, painting a selected line's glyphs
776
                        // unselected over their own highlight.
777
930
                        if !on_line(&g, c.origin.y, c.origin.y + c.size.height) {
778
610
                            return false;
779
320
                        }
780
                        // The x ranges where the rendered band disagrees
781
                        // with the final one: between the two left edges
782
                        // and between the two right edges.
783
320
                        let (cl, rl) = (c.origin.x, r.origin.x);
784
320
                        let (cr, rr) = (c.origin.x + c.size.width, r.origin.x + r.size.width);
785
640
                        let in_zone = |a: f32, b: f32| {
786
640
                            let (lo, hi) = (a.min(b), a.max(b));
787
640
                            hi - lo > 0.01 && g.point.x >= lo - margin && g.point.x < hi
788
640
                        };
789
320
                        in_zone(cl, rl) || in_zone(cr, rr)
790
2540
                    });
791
930
                    match band {
792
220
                        Some(b) => per_band[b].push(g),
793
710
                        None => rest.push(g),
794
                    }
795
                }
796
110
                if !rest.is_empty() {
797
110
                    next.push((rest, piece_color, clip, piece_bg));
798
110
                }
799
320
                for (b, band_glyphs) in per_band.into_iter().enumerate() {
800
320
                    if band_glyphs.is_empty() {
801
300
                        continue;
802
20
                    }
803
20
                    changed = true;
804
20
                    let r = rendered[b];
805
20
                    let (left, right) = (r.origin.x, r.origin.x + r.size.width);
806
                    // The proven background under an unselected glyph is the
807
                    // run's own, under a selected one the highlight.
808
20
                    let unselected_bg = if piece_color == unselected { piece_bg } else { None };
809
20
                    if let Some(c) = clip_x(clip, f32::NEG_INFINITY, left) {
810
                        next.push((band_glyphs.clone(), unselected, c, unselected_bg));
811
20
                    }
812
20
                    if let Some(c) = clip_x(clip, left, right) {
813
20
                        next.push((band_glyphs.clone(), selected, c, None));
814
20
                    }
815
20
                    if let Some(c) = clip_x(clip, right, f32::INFINITY) {
816
20
                        next.push((band_glyphs, unselected, c, unselected_bg));
817
20
                    }
818
                }
819
            }
820
110
            pieces = next;
821
480370
        }
822

            
823
480480
        if let Some((from, to, rendered)) = caret {
824
479870
            let edge = rendered.origin.x + rendered.size.width * 0.5;
825
479870
            let (top, bottom) = (to.origin.y, to.origin.y + to.size.height);
826
479870
            let mut next: Vec<Piece> = Vec::new();
827
959740
            for (piece_glyphs, piece_color, clip, piece_bg) in pieces {
828
479870
                let (revealing, rest): (Vec<GlyphInstance>, Vec<GlyphInstance>) =
829
14050350
                    piece_glyphs.into_iter().partition(|g| {
830
14050350
                        on_line(g, top, bottom)
831
107260
                            && g.point.x >= from.origin.x - margin
832
105970
                            && g.point.x < to.origin.x
833
14050350
                    });
834
479870
                if !rest.is_empty() {
835
479820
                    next.push((rest, piece_color, clip, piece_bg));
836
479820
                }
837
479870
                if !revealing.is_empty() {
838
1910
                    changed = true;
839
1910
                    if let Some(c) = clip_x(clip, f32::NEG_INFINITY, edge) {
840
1910
                        next.push((revealing, piece_color, c, piece_bg));
841
1910
                    }
842
477960
                }
843
            }
844
479870
            pieces = next;
845
610
        }
846

            
847
480480
        if changed {
848
1930
            let replacement = pieces
849
1930
                .into_iter()
850
3830
                .map(|(glyphs, color, clip, bg)| {
851
3830
                    (
852
3830
                        DisplayListItem::Text {
853
3830
                            glyphs,
854
3830
                            font_hash,
855
3830
                            font_size_px: font_size,
856
3830
                            color,
857
3830
                            clip_rect: clip.into(),
858
3830
                            source_node_index,
859
3830
                        },
860
3830
                        bg,
861
3830
                    )
862
3830
                })
863
1930
                .collect();
864
1930
            dl.splice_item(i, replacement);
865
478550
        }
866
    }
867
2031
}
868

            
869
/// Whether an item may appear in a PATCHED (copied+translated) run. The
870
/// build step forces nodes emitting anything else into the re-emit set —
871
/// scroll frames, clips, stacking contexts, virtual views, filters and
872
/// scrollbars all carry state beyond a rect and must re-emit fresh.
873
#[must_use]
874
1750
pub(crate) const fn patchable_item(item: &DisplayListItem) -> bool {
875
    use DisplayListItem as I;
876
    matches!(
877
1750
        item,
878
        I::Rect { .. }
879
            | I::SelectionRect { .. }
880
            | I::CursorRect { .. }
881
            | I::Border { .. }
882
            | I::TextLayout { .. }
883
            | I::Text { .. }
884
            | I::Underline { .. }
885
            | I::Strikethrough { .. }
886
            | I::Overline { .. }
887
            | I::Image { .. }
888
            | I::LinearGradient { .. }
889
            | I::RadialGradient { .. }
890
            | I::ConicGradient { .. }
891
            | I::BoxShadow { .. }
892
            | I::HitTestArea { .. }
893
            | I::PushTextShadow { .. }
894
            | I::PopTextShadow
895
    )
896
1750
}
897

            
898
/// Runtime toggle for DL patching. 0 = uninitialized (resolve from
899
/// `AZ_NO_DL_PATCH` on first read), 1 = enabled, 2 = disabled. A runtime
900
/// atomic rather than a latched `OnceLock` so tests can A/B the patched and
901
/// full paths in one process (the golden-equality gate), and so a live
902
/// session can be flipped for diagnosis.
903
static DL_PATCHING: core::sync::atomic::AtomicU8 = core::sync::atomic::AtomicU8::new(0);
904

            
905
#[must_use]
906
8607
pub fn dl_patching_enabled() -> bool {
907
    use core::sync::atomic::Ordering;
908
8607
    match DL_PATCHING.load(Ordering::Relaxed) {
909
8455
        1 => true,
910
110
        2 => false,
911
        _ => {
912
42
            let on = std::env::var_os("AZ_NO_DL_PATCH").is_none();
913
42
            DL_PATCHING.store(if on { 1 } else { 2 }, Ordering::Relaxed);
914
42
            on
915
        }
916
    }
917
8607
}
918

            
919
/// Force DL patching on/off (tests + live diagnosis; overrides the env).
920
80
pub fn set_dl_patching_enabled(on: bool) {
921
    use core::sync::atomic::Ordering;
922
80
    DL_PATCHING.store(if on { 1 } else { 2 }, Ordering::Relaxed);
923
80
}
924

            
925
/// Which emission site produced a display-list item. See
926
/// [`DisplayList::layout_node_mapping`].
927
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
928
pub enum EmitPhase {
929
    /// Pushed by the stacking-context walk itself (clips, scroll frames,
930
    /// scrollable hit areas, scrollbars) — never substituted from cache.
931
    ScWalk,
932
    /// Pushed by `paint_node_background_and_border`.
933
    BgBorder,
934
    /// Pushed by `paint_node_content`.
935
    Content,
936
}
937

            
938
impl DisplayList {
939
    /// THE display-list ↔ DOM identity invariant, checkable after every
940
    /// build or patch.
941
    ///
942
    /// `node_mapping` is how thirty-plus consumers (damage attribution,
943
    /// pagination break lookup, hit-testing, the coming display-list PATCHING)
944
    /// resolve an item back to the DOM. A stale or out-of-range id does not
945
    /// fail — it succeeds at describing the WRONG node, which is the silent
946
    /// corruption class `assert_dom_ids_are_in_range` documents on the tree
947
    /// side (a ribbon tab click once repainted rects of unrelated nodes; it
948
    /// was only caught because an index happened to trip a bounds check).
949
    /// This is the missing display-list-side counterpart, and the hard gate
950
    /// the DL-patching work patches AGAINST: every patch must leave this
951
    /// invariant intact.
952
    ///
953
    /// Checks: (1) `node_mapping` covers `items` 1:1; (2) every mapped id
954
    /// indexes into `styled_dom`; (3) every item's bounds, where it has any,
955
    /// is finite (a NaN origin poisons every damage union it touches).
956
    /// Deliberately NOT checked: bounds-within-node-rect — decorations
957
    /// (shadows, outlines, selection) legitimately paint outside their node.
958
    ///
959
    /// # Errors
960
    /// Returns a message naming the first offending item index.
961
60
    pub fn validate_node_mapping(
962
60
        &self,
963
60
        styled_dom: &StyledDom,
964
60
    ) -> core::result::Result<(), String> {
965
60
        if self.node_mapping.len() != self.items.len() {
966
10
            return Err(format!(
967
10
                "node_mapping covers {} items but the list has {}",
968
10
                self.node_mapping.len(),
969
10
                self.items.len()
970
10
            ));
971
50
        }
972
50
        let dom_len = styled_dom.node_data.as_ref().len();
973
900
        for (i, (item, mapping)) in self.items.iter().zip(self.node_mapping.iter()).enumerate() {
974
900
            if let Some(node_id) = mapping {
975
810
                if node_id.index() >= dom_len {
976
10
                    return Err(format!(
977
10
                        "item {i} maps to NodeId {} but the DOM has {dom_len} nodes",
978
10
                        node_id.index()
979
10
                    ));
980
800
                }
981
90
            }
982
890
            if let Some(b) = item.bounds() {
983
850
                if !b.origin.x.is_finite()
984
850
                    || !b.origin.y.is_finite()
985
850
                    || !b.size.width.is_finite()
986
850
                    || !b.size.height.is_finite()
987
                {
988
                    return Err(format!("item {i} has non-finite bounds {b:?}"));
989
850
                }
990
40
            }
991
        }
992
40
        Ok(())
993
60
    }
994

            
995
    /// Patch text glyph data for a specific layout node without rebuilding
996
    /// the entire display list. Returns the damage rect covering all
997
    /// affected text items, or None if no matching items found.
998
    ///
999
    /// Used for `GlyphSwap` incremental relayout: glyphs changed but
    /// positions are identical, so only the glyph IDs need updating.
7
    pub(crate) fn patch_text_glyphs(
7
        &mut self,
7
        node_index: usize,
7
        new_glyphs_by_run: &[Vec<GlyphInstance>],
7
    ) -> Option<LogicalRect> {
7
        let mut run_idx = 0;
7
        let mut damage: Option<LogicalRect> = None;
23
        for item in &mut self.items {
            if let DisplayListItem::Text {
10
                ref mut glyphs,
10
                ref clip_rect,
10
                source_node_index: Some(src_idx),
                ..
13
            } = item
            {
10
                if *src_idx == node_index && run_idx < new_glyphs_by_run.len() {
5
                    glyphs.clone_from(&new_glyphs_by_run[run_idx]);
5
                    let bounds = *clip_rect.inner();
5
                    damage = Some(damage.map_or(bounds, |d| {
                        // rect union (was crate::cpurender::union_rect, which
                        // is gated behind the `cpurender` feature; inlined here
                        // so display-list damage tracking works without it / on WASM)
1
                        let x = d.origin.x.min(bounds.origin.x);
1
                        let y = d.origin.y.min(bounds.origin.y);
1
                        let right =
1
                            (d.origin.x + d.size.width).max(bounds.origin.x + bounds.size.width);
1
                        let bottom =
1
                            (d.origin.y + d.size.height).max(bounds.origin.y + bounds.size.height);
1
                        LogicalRect {
1
                            origin: LogicalPosition { x, y },
1
                            size: LogicalSize {
1
                                width: right - x,
1
                                height: bottom - y,
1
                            },
1
                        }
1
                    }));
5
                    run_idx += 1;
5
                }
6
            }
        }
7
        damage
7
    }
    /// Rewrite the `ImageRef` of every `Image` item generated by `node`
    /// without rebuilding the display list, returning the union of the
    /// patched bounds (None if the node produced no image items).
    ///
    /// The single caller is the content chokepoint
    /// (`LayoutWindow::apply_content_change`, paint tier): geometry is
    /// unchanged, only the content identity moves — the backend display-list
    /// diff sees the `ImageRef` id change and damages exactly these bounds.
    /// Patch PAINT COLOURS in place for a node's SUBTREE — the per-tick fast
    /// path of a paint-only `animation` transition. Items attributed (via
    /// `node_mapping`) to a node id in `range` whose colour equals `from`
    /// take `to`; the from-match is what implements inheritance without a
    /// cascade pass (a descendant with its OWN explicit colour differs from
    /// `from` and is untouched). Returns the damage union, `None` when
    /// nothing matched (the caller falls back to a full rebuild).
58
    pub fn patch_paint_colors(
58
        &mut self,
58
        range: core::ops::Range<usize>,
58
        from: ColorU,
58
        to: ColorU,
58
        patch_text: bool,
58
        patch_background: bool,
58
    ) -> Option<LogicalRect> {
58
        let mut damage: Option<LogicalRect> = None;
58
        let mut grow = |bounds: LogicalRect| {
58
            damage = Some(damage.map_or(bounds, |d| {
                let x = d.origin.x.min(bounds.origin.x);
                let y = d.origin.y.min(bounds.origin.y);
                let right = (d.origin.x + d.size.width).max(bounds.origin.x + bounds.size.width);
                let bottom = (d.origin.y + d.size.height).max(bounds.origin.y + bounds.size.height);
                LogicalRect {
                    origin: LogicalPosition { x, y },
                    size: LogicalSize {
                        width: right - x,
                        height: bottom - y,
                    },
                }
            }));
58
        };
870
        for (idx, item) in self.items.iter_mut().enumerate() {
870
            let Some(node) = self.node_mapping.get(idx).copied().flatten() else {
116
                continue;
            };
754
            if !range.contains(&node.index()) {
580
                continue;
174
            }
            match item {
                DisplayListItem::Text {
58
                    color, clip_rect, ..
58
                } if patch_text && *color == from => {
58
                    *color = to;
58
                    grow(*clip_rect.inner());
58
                }
                DisplayListItem::Underline { color, bounds, .. }
                | DisplayListItem::Strikethrough { color, bounds, .. }
                    if patch_text && *color == from =>
                {
                    *color = to;
                    grow(*bounds.inner());
                }
                DisplayListItem::Rect { color, bounds, .. }
                    if patch_background && *color == from =>
                {
                    *color = to;
                    grow(*bounds.inner());
                }
116
                _ => {}
            }
        }
58
        damage
58
    }
1
    pub fn patch_node_image(&mut self, node: NodeId, image: &ImageRef) -> Option<LogicalRect> {
1
        let mut damage: Option<LogicalRect> = None;
8
        for (idx, item) in self.items.iter_mut().enumerate() {
8
            if self.node_mapping.get(idx).copied().flatten() != Some(node) {
7
                continue;
1
            }
            if let DisplayListItem::Image {
1
                bounds,
1
                image: item_image,
                ..
1
            } = item
            {
1
                *item_image = image.clone();
1
                let bounds = *bounds.inner();
1
                damage = Some(damage.map_or(bounds, |d| {
                    let x = d.origin.x.min(bounds.origin.x);
                    let y = d.origin.y.min(bounds.origin.y);
                    let right =
                        (d.origin.x + d.size.width).max(bounds.origin.x + bounds.size.width);
                    let bottom =
                        (d.origin.y + d.size.height).max(bounds.origin.y + bounds.size.height);
                    LogicalRect {
                        origin: LogicalPosition { x, y },
                        size: LogicalSize {
                            width: right - x,
                            height: bottom - y,
                        },
                    }
                }));
            }
        }
1
        damage
1
    }
    /// Compute a damage rect from the difference between old and new text
    /// layout results, starting from a given line index.
    #[allow(clippy::similar_names)] // domain-standard coordinate/geometry/short-lived names
7
    pub(crate) fn compute_text_damage_rect(
7
        old_items: &[PositionedItem],
7
        new_items: &[PositionedItem],
7
        container_origin: LogicalPosition,
7
        affected_line: usize,
7
    ) -> LogicalRect {
14
        let expand = |items: &[PositionedItem]| -> (f32, f32, f32, f32) {
14
            let mut lx = f32::MAX;
14
            let mut ly = f32::MAX;
14
            let mut rx = f32::MIN;
14
            let mut ry = f32::MIN;
28
            for item in items {
14
                if item.line_index >= affected_line {
8
                    let bounds = item.item.bounds();
8
                    let x = container_origin.x + item.position.x;
8
                    let y = container_origin.y + item.position.y;
8
                    lx = lx.min(x);
8
                    ly = ly.min(y);
8
                    rx = rx.max(x + bounds.width);
8
                    ry = ry.max(y + bounds.height);
8
                }
            }
14
            (lx, ly, rx, ry)
14
        };
7
        let (olx, oly, orx, ory) = expand(old_items);
7
        let (nlx, nly, nrx, nry) = expand(new_items);
7
        let min_x = olx.min(nlx);
7
        let min_y = oly.min(nly);
7
        let max_x = orx.max(nrx);
7
        let max_y = ory.max(nry);
7
        if min_x > max_x || min_y > max_y {
3
            return LogicalRect::default();
4
        }
4
        LogicalRect {
4
            origin: LogicalPosition { x: min_x, y: min_y },
4
            size: LogicalSize {
4
                width: max_x - min_x,
4
                height: max_y - min_y,
4
            },
4
        }
7
    }
    /// Generates a JSON representation of the display list for debugging.
    /// This includes clip chain analysis showing how clips are stacked.
    #[allow(clippy::too_many_lines)] // large but cohesive: single-purpose layout/render/parse routine (one branch per case)
    #[must_use]
4
    pub fn to_debug_json(&self) -> String {
        use std::fmt::Write;
4
        let mut json = String::new();
4
        writeln!(json, "{{").unwrap();
4
        writeln!(json, "  \"total_items\": {},", self.items.len()).unwrap();
4
        writeln!(json, "  \"items\": [").unwrap();
4
        let mut clip_depth = 0i32;
4
        let mut scroll_depth = 0i32;
4
        let mut stacking_depth = 0i32;
9
        for (i, item) in self.items.iter().enumerate() {
9
            let comma = if i < self.items.len() - 1 { "," } else { "" };
9
            let node_id = self.node_mapping.get(i).and_then(|n| *n);
9
            match item {
                DisplayListItem::PushClip {
2
                    bounds,
2
                    border_radius,
2
                } => {
2
                    clip_depth += 1;
2
                    writeln!(json, "    {{").unwrap();
2
                    writeln!(json, "      \"index\": {i},").unwrap();
2
                    writeln!(json, "      \"type\": \"PushClip\",").unwrap();
2
                    writeln!(json, "      \"clip_depth\": {clip_depth},").unwrap();
2
                    writeln!(json, "      \"scroll_depth\": {scroll_depth},").unwrap();
2
                    writeln!(
2
                        json,
2
                        "      \"bounds\": {{ \"x\": {:.1}, \"y\": {:.1}, \"w\": {:.1}, \"h\": \
2
                         {:.1} }},",
2
                        bounds.0.origin.x,
2
                        bounds.0.origin.y,
2
                        bounds.0.size.width,
2
                        bounds.0.size.height
2
                    )
2
                    .unwrap();
2
                    writeln!(
2
                        json,
2
                        "      \"border_radius\": {{ \"tl\": {:.1}, \"tr\": {:.1}, \"bl\": {:.1}, \
2
                         \"br\": {:.1} }},",
2
                        border_radius.top_left,
2
                        border_radius.top_right,
2
                        border_radius.bottom_left,
2
                        border_radius.bottom_right
2
                    )
2
                    .unwrap();
2
                    writeln!(json, "      \"node_id\": {node_id:?}").unwrap();
2
                    writeln!(json, "    }}{comma}").unwrap();
2
                }
2
                DisplayListItem::PopClip => {
2
                    writeln!(json, "    {{").unwrap();
2
                    writeln!(json, "      \"index\": {i},").unwrap();
2
                    writeln!(json, "      \"type\": \"PopClip\",").unwrap();
2
                    writeln!(json, "      \"clip_depth_before\": {clip_depth},").unwrap();
2
                    writeln!(json, "      \"clip_depth_after\": {}", clip_depth - 1).unwrap();
2
                    writeln!(json, "    }}{comma}").unwrap();
2
                    clip_depth -= 1;
2
                }
                DisplayListItem::PushScrollFrame {
1
                    clip_bounds,
1
                    content_size,
1
                    scroll_id,
1
                } => {
1
                    scroll_depth += 1;
1
                    writeln!(json, "    {{").unwrap();
1
                    writeln!(json, "      \"index\": {i},").unwrap();
1
                    writeln!(json, "      \"type\": \"PushScrollFrame\",").unwrap();
1
                    writeln!(json, "      \"clip_depth\": {clip_depth},").unwrap();
1
                    writeln!(json, "      \"scroll_depth\": {scroll_depth},").unwrap();
1
                    writeln!(
1
                        json,
1
                        "      \"clip_bounds\": {{ \"x\": {:.1}, \"y\": {:.1}, \"w\": {:.1}, \
1
                         \"h\": {:.1} }},",
1
                        clip_bounds.0.origin.x,
1
                        clip_bounds.0.origin.y,
1
                        clip_bounds.0.size.width,
1
                        clip_bounds.0.size.height
1
                    )
1
                    .unwrap();
1
                    writeln!(
1
                        json,
1
                        "      \"content_size\": {{ \"w\": {:.1}, \"h\": {:.1} }},",
1
                        content_size.width, content_size.height
1
                    )
1
                    .unwrap();
1
                    writeln!(json, "      \"scroll_id\": {scroll_id},").unwrap();
1
                    writeln!(json, "      \"node_id\": {node_id:?}").unwrap();
1
                    writeln!(json, "    }}{comma}").unwrap();
1
                }
1
                DisplayListItem::PopScrollFrame => {
1
                    writeln!(json, "    {{").unwrap();
1
                    writeln!(json, "      \"index\": {i},").unwrap();
1
                    writeln!(json, "      \"type\": \"PopScrollFrame\",").unwrap();
1
                    writeln!(json, "      \"scroll_depth_before\": {scroll_depth},").unwrap();
1
                    writeln!(json, "      \"scroll_depth_after\": {}", scroll_depth - 1).unwrap();
1
                    writeln!(json, "    }}{comma}").unwrap();
1
                    scroll_depth -= 1;
1
                }
1
                DisplayListItem::PushStackingContext { z_index, bounds } => {
1
                    stacking_depth += 1;
1
                    writeln!(json, "    {{").unwrap();
1
                    writeln!(json, "      \"index\": {i},").unwrap();
1
                    writeln!(json, "      \"type\": \"PushStackingContext\",").unwrap();
1
                    writeln!(json, "      \"stacking_depth\": {stacking_depth},").unwrap();
1
                    writeln!(json, "      \"z_index\": {z_index},").unwrap();
1
                    writeln!(
1
                        json,
1
                        "      \"bounds\": {{ \"x\": {:.1}, \"y\": {:.1}, \"w\": {:.1}, \"h\": \
1
                         {:.1} }}",
1
                        bounds.0.origin.x,
1
                        bounds.0.origin.y,
1
                        bounds.0.size.width,
1
                        bounds.0.size.height
1
                    )
1
                    .unwrap();
1
                    writeln!(json, "    }}{comma}").unwrap();
1
                }
1
                DisplayListItem::PopStackingContext => {
1
                    writeln!(json, "    {{").unwrap();
1
                    writeln!(json, "      \"index\": {i},").unwrap();
1
                    writeln!(json, "      \"type\": \"PopStackingContext\",").unwrap();
1
                    writeln!(json, "      \"stacking_depth_before\": {stacking_depth},").unwrap();
1
                    writeln!(
1
                        json,
1
                        "      \"stacking_depth_after\": {}",
1
                        stacking_depth - 1
1
                    )
1
                    .unwrap();
1
                    writeln!(json, "    }}{comma}").unwrap();
1
                    stacking_depth -= 1;
1
                }
                DisplayListItem::Rect {
                    bounds,
                    color,
                    border_radius,
                } => {
                    writeln!(json, "    {{").unwrap();
                    writeln!(json, "      \"index\": {i},").unwrap();
                    writeln!(json, "      \"type\": \"Rect\",").unwrap();
                    writeln!(json, "      \"clip_depth\": {clip_depth},").unwrap();
                    writeln!(json, "      \"scroll_depth\": {scroll_depth},").unwrap();
                    writeln!(
                        json,
                        "      \"bounds\": {{ \"x\": {:.1}, \"y\": {:.1}, \"w\": {:.1}, \"h\": \
                         {:.1} }},",
                        bounds.0.origin.x,
                        bounds.0.origin.y,
                        bounds.0.size.width,
                        bounds.0.size.height
                    )
                    .unwrap();
                    writeln!(
                        json,
                        "      \"color\": \"rgba({},{},{},{})\",",
                        color.r, color.g, color.b, color.a
                    )
                    .unwrap();
                    writeln!(json, "      \"node_id\": {node_id:?}").unwrap();
                    writeln!(json, "    }}{comma}").unwrap();
                }
                DisplayListItem::Border { bounds, .. } => {
                    writeln!(json, "    {{").unwrap();
                    writeln!(json, "      \"index\": {i},").unwrap();
                    writeln!(json, "      \"type\": \"Border\",").unwrap();
                    writeln!(json, "      \"clip_depth\": {clip_depth},").unwrap();
                    writeln!(json, "      \"scroll_depth\": {scroll_depth},").unwrap();
                    writeln!(
                        json,
                        "      \"bounds\": {{ \"x\": {:.1}, \"y\": {:.1}, \"w\": {:.1}, \"h\": \
                         {:.1} }},",
                        bounds.0.origin.x,
                        bounds.0.origin.y,
                        bounds.0.size.width,
                        bounds.0.size.height
                    )
                    .unwrap();
                    writeln!(json, "      \"node_id\": {node_id:?}").unwrap();
                    writeln!(json, "    }}{comma}").unwrap();
                }
                DisplayListItem::ScrollBarStyled { info } => {
                    writeln!(json, "    {{").unwrap();
                    writeln!(json, "      \"index\": {i},").unwrap();
                    writeln!(json, "      \"type\": \"ScrollBarStyled\",").unwrap();
                    writeln!(json, "      \"clip_depth\": {clip_depth},").unwrap();
                    writeln!(json, "      \"scroll_depth\": {scroll_depth},").unwrap();
                    writeln!(json, "      \"orientation\": \"{:?}\",", info.orientation).unwrap();
                    writeln!(
                        json,
                        "      \"bounds\": {{ \"x\": {:.1}, \"y\": {:.1}, \"w\": {:.1}, \"h\": \
                         {:.1} }}",
                        info.bounds.0.origin.x,
                        info.bounds.0.origin.y,
                        info.bounds.0.size.width,
                        info.bounds.0.size.height
                    )
                    .unwrap();
                    writeln!(json, "    }}{comma}").unwrap();
                }
                DisplayListItem::Text {
                    glyphs,
                    font_size_px,
                    clip_rect,
                    source_node_index,
                    ..
                } => {
                    writeln!(json, "    {{").unwrap();
                    writeln!(json, "      \"index\": {i},").unwrap();
                    writeln!(json, "      \"type\": \"Text\",").unwrap();
                    writeln!(json, "      \"clip_depth\": {clip_depth},").unwrap();
                    writeln!(json, "      \"scroll_depth\": {scroll_depth},").unwrap();
                    writeln!(json, "      \"glyphs\": {},", glyphs.len()).unwrap();
                    writeln!(json, "      \"font_size_px\": {font_size_px},").unwrap();
                    writeln!(
                        json,
                        "      \"clip_rect\": {{ \"x\": {:.1}, \"y\": {:.1}, \"w\": {:.1}, \"h\": \
                         {:.1} }},",
                        clip_rect.0.origin.x,
                        clip_rect.0.origin.y,
                        clip_rect.0.size.width,
                        clip_rect.0.size.height
                    )
                    .unwrap();
                    writeln!(json, "      \"source_node_index\": {source_node_index:?},").unwrap();
                    writeln!(json, "      \"node_id\": {node_id:?}").unwrap();
                    writeln!(json, "    }}{comma}").unwrap();
                }
1
                _ => {
1
                    writeln!(json, "    {{").unwrap();
1
                    writeln!(json, "      \"index\": {i},").unwrap();
1
                    writeln!(
1
                        json,
1
                        "      \"type\": \"{:?}\",",
1
                        std::mem::discriminant(item)
1
                    )
1
                    .unwrap();
1
                    writeln!(json, "      \"clip_depth\": {clip_depth},").unwrap();
1
                    writeln!(json, "      \"scroll_depth\": {scroll_depth},").unwrap();
1
                    writeln!(json, "      \"node_id\": {node_id:?}").unwrap();
1
                    writeln!(json, "    }}{comma}").unwrap();
1
                }
            }
        }
4
        writeln!(json, "  ],").unwrap();
4
        writeln!(json, "  \"final_clip_depth\": {clip_depth},").unwrap();
4
        writeln!(json, "  \"final_scroll_depth\": {scroll_depth},").unwrap();
4
        writeln!(json, "  \"final_stacking_depth\": {stacking_depth},").unwrap();
4
        writeln!(
4
            json,
4
            "  \"balanced\": {}",
4
            clip_depth == 0 && scroll_depth == 0 && stacking_depth == 0
        )
4
        .unwrap();
4
        writeln!(json, "}}").unwrap();
4
        json
4
    }
}
/// A command in the display list. Can be either a drawing primitive or a
/// state-management instruction for the renderer's graphics context.
#[derive(Debug, Clone)]
pub enum DisplayListItem {
    // Drawing Primitives
    /// A filled rectangle with optional rounded corners.
    /// Used for backgrounds, colored boxes, and other solid fills.
    Rect {
        /// The rectangle bounds in absolute window coordinates
        bounds: WindowLogicalRect,
        /// The fill color (RGBA)
        color: ColorU,
        /// Corner radii for rounded rectangles
        border_radius: BorderRadius,
    },
    /// A selection highlight rectangle (e.g., for text selection).
    /// Rendered behind text to show selected regions.
    SelectionRect {
        /// The rectangle bounds in absolute window coordinates
        bounds: WindowLogicalRect,
        /// Corner radii for rounded selection
        border_radius: BorderRadius,
        /// The selection highlight color (typically semi-transparent)
        color: ColorU,
    },
    /// A text cursor (caret) rectangle.
    /// Typically a thin vertical line indicating text insertion point.
    CursorRect {
        /// The cursor bounds (usually narrow width)
        bounds: WindowLogicalRect,
        /// The cursor color
        color: ColorU,
    },
    /// A CSS border with per-side widths, colors, and styles.
    /// Supports different styles per side (solid, dashed, dotted, etc.).
    Border {
        /// The border-box bounds
        bounds: WindowLogicalRect,
        /// Border widths for each side
        widths: StyleBorderWidths,
        /// Border colors for each side
        colors: StyleBorderColors,
        /// Border styles for each side (solid, dashed, etc.)
        styles: StyleBorderStyles,
        /// Corner radii for rounded borders
        border_radius: StyleBorderRadius,
    },
    /// Text layout with full metadata (for PDF, accessibility, etc.)
    /// This is pushed BEFORE the individual Text items and contains
    /// the original text, glyph-to-unicode mapping, and positioning info
    TextLayout {
        layout: Arc<dyn std::any::Any + Send + Sync>, // Type-erased UnifiedLayout
        bounds: WindowLogicalRect,
        font_hash: FontHash,
        font_size_px: f32,
        color: ColorU,
    },
    /// Text rendered with individual glyph positioning (for simple renderers)
    Text {
        glyphs: Vec<GlyphInstance>,
        font_hash: FontHash,
        font_size_px: f32,
        color: ColorU,
        clip_rect: WindowLogicalRect,
        /// Layout node index that produced this text run.
        /// Enables patching glyphs without full display list regeneration.
        source_node_index: Option<usize>,
    },
    /// Underline decoration for text (CSS text-decoration: underline)
    Underline {
        bounds: WindowLogicalRect,
        color: ColorU,
        thickness: f32,
    },
    /// Strikethrough decoration for text (CSS text-decoration: line-through)
    Strikethrough {
        bounds: WindowLogicalRect,
        color: ColorU,
        thickness: f32,
    },
    /// Overline decoration for text (CSS text-decoration: overline)
    Overline {
        bounds: WindowLogicalRect,
        color: ColorU,
        thickness: f32,
    },
    Image {
        bounds: WindowLogicalRect,
        image: ImageRef,
        border_radius: BorderRadius,
    },
    /// A dedicated primitive for a scrollbar with optional GPU-animated opacity.
    /// This is a simple single-color scrollbar used for basic rendering.
    ScrollBar {
        bounds: WindowLogicalRect,
        color: ColorU,
        orientation: ScrollbarOrientation,
        /// Optional opacity key for GPU-side fading animation.
        /// If present, the renderer will use this key to look up dynamic opacity.
        /// If None, the alpha channel of `color` is used directly.
        opacity_key: Option<OpacityKey>,
        /// Optional hit-test ID for `WebRender` hit-testing.
        /// If present, allows event handlers to identify which scrollbar component was clicked.
        hit_id: Option<azul_core::hit_test::ScrollbarHitId>,
    },
    /// A fully styled scrollbar with separate track, thumb, and optional buttons.
    /// Used when CSS scrollbar properties are specified.
    ScrollBarStyled {
        /// Complete drawing information for all scrollbar components
        info: Box<ScrollbarDrawInfo>,
    },
    /// An embedded `VirtualView` that references a child DOM with its own display list.
    /// The renderer will look up the child display list by `child_dom_id` and
    /// render it within the bounds. The `VirtualView` viewport is rendered in parent
    /// coordinate space (NOT inside a scroll frame) so it stays stationary.
    /// Scroll offset is communicated to the `VirtualView` callback, not via `WebRender`.
    VirtualView {
        /// The `DomId` of the child DOM (similar to webrender's `pipeline_id`)
        child_dom_id: DomId,
        /// The bounds where the `VirtualView` should be rendered
        bounds: WindowLogicalRect,
        /// The clip rect for the `VirtualView` content
        clip_rect: WindowLogicalRect,
        /// How far to shift the child content inside `bounds`, in logical px:
        /// `materialized_window_origin - current_scroll_offset`.
        ///
        /// This is what makes a `VirtualView` SCROLL rather than merely
        /// re-materialize. It is deliberately derived from the materialized
        /// window's origin and the live scroll offset ONLY — never from the
        /// virtual document size — so refining the document estimate (as
        /// background pagination lands) resizes the scrollbar and moves
        /// nothing on screen.
        content_offset: LogicalPosition,
    },
    /// Placeholder emitted during display list generation for `VirtualView` nodes.
    /// `window.rs` replaces this with a real `VirtualView` item after invoking
    /// the `VirtualView` callback. This avoids the need for post-hoc scroll frame
    /// scanning — `window.rs` simply finds the placeholder by `node_id`.
    ///
    /// Unlike regular scrollable nodes, `VirtualView` nodes do NOT get a
    /// PushScrollFrame/PopScrollFrame pair. Scroll state is managed by
    /// `ScrollManager` and passed to the `VirtualView` callback as `scroll_offset`.
    VirtualViewPlaceholder {
        /// The DOM `NodeId` of the `VirtualView` element in the parent DOM
        node_id: NodeId,
        /// The layout bounds of the `VirtualView` container
        bounds: WindowLogicalRect,
        /// The clip rect (same as bounds initially, may be adjusted)
        clip_rect: WindowLogicalRect,
    },
    // --- State-Management Commands ---
    /// Pushes a new clipping rectangle onto the renderer's clip stack.
    /// All subsequent primitives will be clipped by this rect until a `PopClip`.
    PushClip {
        bounds: WindowLogicalRect,
        border_radius: BorderRadius,
    },
    /// Pops the current clip from the renderer's clip stack.
    PopClip,
    /// Pushes an image-based clip mask onto the renderer's clip stack.
    /// The mask image should be R8 format: white (255) = visible, black (0) = clipped.
    /// All subsequent primitives will be masked until `PopImageMaskClip`.
    PushImageMaskClip {
        /// The bounds of the element being clipped
        bounds: WindowLogicalRect,
        /// The mask image (R8 format)
        mask_image: ImageRef,
        /// The rect within which the mask is applied
        mask_rect: WindowLogicalRect,
    },
    /// Pops the current image mask clip from the renderer's clip stack.
    PopImageMaskClip,
    /// A STROKED vector path - SVG's `stroke`, and the PDF model's second
    /// paint operator.
    ///
    /// Not a `Border`: a border follows the box, a stroke follows the
    /// GEOMETRY. Drawing a stroked outline as a rectangle inside the shape's
    /// own clip leaves a hairline at the corners and nothing anywhere else,
    /// which is what a line drawn with `fill="none"` looked like.
    ///
    /// The geometry is carried in USER SPACE with the `<svg>`'s `view_box`, so
    /// the renderer maps it into `bounds` itself - a stroke scaled by
    /// pre-transforming the points would scale the WIDTH with them, and a 2px
    /// rule in a 16-unit icon would come out 8px wide in a 64px slot.
    ///
    /// A CPU renderer strokes this directly; a GPU one rasterises it into a
    /// mask and paints `color` through it.
    StrokedPath {
        /// The box the geometry maps into, in absolute window coordinates.
        bounds: WindowLogicalRect,
        /// The path, in the user space `view_box` describes.
        path: azul_core::svg::SvgMultiPolygon,
        /// `(min_x, min_y, width, height)` of the enclosing `<svg>`, or `None`
        /// when the geometry is already in window-logical px.
        view_box: Option<(f32, f32, f32, f32)>,
        /// The stroke colour.
        color: ColorU,
        /// The stroke width, in the same user space as the geometry.
        width: f32,
        /// The stroke, pre-rasterised as an R8 coverage mask over `bounds`.
        ///
        /// For the GPU backend, which has no vector rasteriser: it paints
        /// `color` through this mask. The CPU backend IGNORES it and strokes
        /// the real outline, which has no resolution ceiling. `None` when the
        /// build has no rasteriser at all - the CPU path still draws, the GPU
        /// path draws nothing rather than something wrong.
        mask: Option<ImageRef>,
    },
    /// Defines a scrollable area. This is a specialized clip that also
    /// establishes a new coordinate system for its children, which can be offset.
    PushScrollFrame {
        /// The clip rect in the parent's coordinate space.
        clip_bounds: WindowLogicalRect,
        /// The total size of the scrollable content.
        content_size: LogicalSize,
        /// An ID for the renderer to track this scrollable area between frames.
        scroll_id: LocalScrollId,
    },
    /// Pops the current scroll frame.
    PopScrollFrame,
    /// Pushes a new stacking context for proper z-index layering.
    /// All subsequent primitives until `PopStackingContext` will be in this stacking context.
    PushStackingContext {
        /// The z-index for this stacking context (for debugging/validation)
        z_index: i32,
        /// The bounds of the stacking context root element
        bounds: WindowLogicalRect,
    },
    /// Pops the current stacking context.
    PopStackingContext,
    /// Pushes a reference frame with a GPU-accelerated transform.
    /// Used for CSS transforms and drag visual offsets.
    /// Creates a new spatial coordinate system for all children.
    PushReferenceFrame {
        /// The transform key for GPU-animated property binding
        transform_key: TransformKey,
        /// The initial transform value (identity for drag, computed for CSS transform)
        initial_transform: ComputedTransform3D,
        /// The bounds of the reference frame (origin = transform origin)
        bounds: WindowLogicalRect,
    },
    /// Pops the current reference frame.
    PopReferenceFrame,
    /// Defines a region for hit-testing.
    HitTestArea {
        bounds: WindowLogicalRect,
        tag: DisplayListTagId, // This would be a renderer-agnostic ID type
    },
    // --- Gradient Primitives ---
    /// A linear gradient fill.
    LinearGradient {
        bounds: WindowLogicalRect,
        gradient: LinearGradient,
        border_radius: BorderRadius,
    },
    /// A radial gradient fill.
    RadialGradient {
        bounds: WindowLogicalRect,
        gradient: RadialGradient,
        border_radius: BorderRadius,
    },
    /// A conic (angular) gradient fill.
    ConicGradient {
        bounds: WindowLogicalRect,
        gradient: ConicGradient,
        border_radius: BorderRadius,
    },
    // --- Shadow Effects ---
    /// A box shadow (either outset or inset).
    BoxShadow {
        bounds: WindowLogicalRect,
        shadow: StyleBoxShadow,
        border_radius: BorderRadius,
    },
    // --- Filter Effects ---
    /// Push a filter effect that applies to subsequent content.
    PushFilter {
        bounds: WindowLogicalRect,
        filters: Vec<StyleFilter>,
    },
    /// Pop a previously pushed filter.
    PopFilter,
    /// Push a backdrop filter (applies to content behind the element).
    PushBackdropFilter {
        bounds: WindowLogicalRect,
        filters: Vec<StyleFilter>,
    },
    /// Pop a previously pushed backdrop filter.
    PopBackdropFilter,
    /// Push an opacity layer.
    PushOpacity {
        bounds: WindowLogicalRect,
        /// The BAKED (CSS) opacity — the value at display-list build time.
        opacity: f32,
        /// GPU binding for ANIMATED opacity (enter/exit fades, diff-driven
        /// animation). Same contract as `PushReferenceFrame.transform_key`:
        /// the display list carries the KEY, the per-tick value lives in the
        /// `GpuValueCache` animation channel, so the cached list serves every
        /// tick while the fade advances. `None` for plain CSS opacity.
        opacity_key: Option<OpacityKey>,
    },
    /// Pop an opacity layer.
    PopOpacity,
    /// Push a text shadow that applies to subsequent text content.
    PushTextShadow { shadow: StyleBoxShadow },
    /// Pop all text shadows.
    PopTextShadow,
}
/// Intersect `a` with `b`; if they do not overlap, fall back to `b`.
///
/// Used to clamp a computed ink extent to its clip rect. The fallback is
/// deliberately the CLIP and not an empty rect: a non-overlapping result
/// means the extent was computed wrongly, and in that case damaging too
/// much is recoverable while damaging nothing leaves stale pixels.
/// The caret of an editable that has no text yet, in the node's CONTENT-BOX
/// space: at the origin, one line-height tall (`font-size × line-height`,
/// the `normal` 1.2 when unset), one pixel wide — the line box the first
/// character will create. Height is floored at 1 px so a zero font never
/// produces an invisible caret.
#[must_use]
736
pub fn empty_editable_caret_rect(font_size_px: f32, line_height: f32) -> LogicalRect {
736
    let height = (font_size_px * line_height).max(1.0);
736
    let height = if height.is_finite() { height } else { 1.0 };
736
    LogicalRect {
736
        origin: LogicalPosition::zero(),
736
        size: LogicalSize { width: 1.0, height },
736
    }
736
}
261839
fn intersect_or(a: LogicalRect, b: LogicalRect) -> LogicalRect {
261839
    let x0 = a.origin.x.max(b.origin.x);
261839
    let y0 = a.origin.y.max(b.origin.y);
261839
    let x1 = (a.origin.x + a.size.width).min(b.origin.x + b.size.width);
261839
    let y1 = (a.origin.y + a.size.height).min(b.origin.y + b.size.height);
261839
    if x1 > x0 && y1 > y0 {
261839
        LogicalRect {
261839
            origin: LogicalPosition { x: x0, y: y0 },
261839
            size: LogicalSize {
261839
                width: x1 - x0,
261839
                height: y1 - y0,
261839
            },
261839
        }
    } else {
        b
    }
261839
}
impl DisplayListItem {
    /// Compare two display list items for visual equality (same appearance when rendered).
    /// Used by damage computation to detect content changes within the same bounds.
    /// Conservative: returns `false` (assumes different) for complex types like Arc<dyn Any>.
    // Exact float equality is intentional: this is frame-to-frame damage detection,
    // so any bit-level change in a coordinate/color/thickness SHOULD force a redraw.
    // An epsilon comparison would wrongly skip sub-epsilon visual updates.
    #[allow(clippy::float_cmp)]
    #[allow(clippy::similar_names)] // domain-standard coordinate/geometry/short-lived names
    #[allow(clippy::match_same_arms)]
    // enum/value mapping/dispatch table: one arm per input variant (or cross-type bindings that
    // can't merge)
    #[allow(clippy::too_many_lines)] // large but cohesive: single-purpose layout/render/parse routine (one branch per case)
    /// Is this a structure-opening marker (clip / scroll frame / stacking
    /// context / text shadow / image mask)? Paired with [`Self::is_pop_marker`]
    /// and [`Self::matching_pop`] by the page slicer's E17 re-derivation.
    #[must_use]
28703
    pub const fn is_push_marker(&self) -> bool {
26882
        matches!(
28703
            self,
            Self::PushClip { .. }
                | Self::PushScrollFrame { .. }
                | Self::PushStackingContext { .. }
                | Self::PushTextShadow { .. }
                | Self::PushImageMaskClip { .. }
        )
28703
    }
    /// Is this a structure-closing marker?
    #[must_use]
26882
    pub const fn is_pop_marker(&self) -> bool {
25061
        matches!(
26882
            self,
            Self::PopClip
                | Self::PopScrollFrame
                | Self::PopStackingContext
                | Self::PopTextShadow
                | Self::PopImageMaskClip
        )
26882
    }
    /// The Pop item that closes this Push marker (None for non-markers).
    #[must_use]
    pub const fn matching_pop(&self) -> Option<Self> {
        match self {
            Self::PushClip { .. } => Some(Self::PopClip),
            Self::PushScrollFrame { .. } => Some(Self::PopScrollFrame),
            Self::PushStackingContext { .. } => Some(Self::PopStackingContext),
            Self::PushTextShadow { .. } => Some(Self::PopTextShadow),
            Self::PushImageMaskClip { .. } => Some(Self::PopImageMaskClip),
            _ => None,
        }
    }
    #[must_use]
613962
    pub fn is_visually_equal(&self, other: &Self) -> bool {
613962
        if std::mem::discriminant(self) != std::mem::discriminant(other) {
140
            return false;
613822
        }
613822
        match (self, other) {
            (
                Self::Rect {
2961
                    bounds: b1,
2961
                    color: c1,
2961
                    border_radius: br1,
                },
                Self::Rect {
2961
                    bounds: b2,
2961
                    color: c2,
2961
                    border_radius: br2,
                },
            ) => {
2961
                b1 == b2
2928
                    && c1 == c2
2912
                    && br1.top_left == br2.top_left
2911
                    && br1.top_right == br2.top_right
2911
                    && br1.bottom_left == br2.bottom_left
2911
                    && br1.bottom_right == br2.bottom_right
            }
            (
                Self::SelectionRect {
                    bounds: b1,
                    border_radius: br1,
                    color: c1,
                },
                Self::SelectionRect {
                    bounds: b2,
                    border_radius: br2,
                    color: c2,
                },
            ) => {
                b1 == b2
                    && c1 == c2
                    && br1.top_left == br2.top_left
                    && br1.top_right == br2.top_right
                    && br1.bottom_left == br2.bottom_left
                    && br1.bottom_right == br2.bottom_right
            }
            (
                Self::CursorRect {
913
                    bounds: b1,
913
                    color: c1,
                },
                Self::CursorRect {
913
                    bounds: b2,
913
                    color: c2,
                },
913
            ) => b1 == b2 && c1 == c2,
            (
                Self::Text {
243157
                    glyphs: g1,
243157
                    font_hash: fh1,
243157
                    font_size_px: fs1,
243157
                    color: c1,
243157
                    clip_rect: cr1,
                    ..
                },
                Self::Text {
243157
                    glyphs: g2,
243157
                    font_hash: fh2,
243157
                    font_size_px: fs2,
243157
                    color: c2,
243157
                    clip_rect: cr2,
                    ..
                },
            ) => {
243157
                cr1 == cr2
241210
                    && c1 == c2
241208
                    && fh1 == fh2
241208
                    && fs1 == fs2
241208
                    && g1.len() == g2.len()
7017714
                    && g1.iter().zip(g2.iter()).all(|(a, b)| {
7017714
                        a.index == b.index && a.point.x == b.point.x && a.point.y == b.point.y
7017714
                    })
            }
            (
                Self::Underline {
1
                    bounds: b1,
1
                    color: c1,
1
                    thickness: t1,
                },
                Self::Underline {
1
                    bounds: b2,
1
                    color: c2,
1
                    thickness: t2,
                },
1
            ) => b1 == b2 && c1 == c2 && t1 == t2,
            (
                Self::Strikethrough {
                    bounds: b1,
                    color: c1,
                    thickness: t1,
                },
                Self::Strikethrough {
                    bounds: b2,
                    color: c2,
                    thickness: t2,
                },
            ) => b1 == b2 && c1 == c2 && t1 == t2,
            (
                Self::Overline {
                    bounds: b1,
                    color: c1,
                    thickness: t1,
                },
                Self::Overline {
                    bounds: b2,
                    color: c2,
                    thickness: t2,
                },
            ) => b1 == b2 && c1 == c2 && t1 == t2,
            (
                Self::Border {
950
                    bounds: b1,
950
                    widths: w1,
950
                    colors: c1,
950
                    styles: s1,
                    ..
                },
                Self::Border {
950
                    bounds: b2,
950
                    widths: w2,
950
                    colors: c2,
950
                    styles: s2,
                    ..
                },
            ) => {
950
                b1 == b2
950
                    && w1.top == w2.top
950
                    && w1.right == w2.right
950
                    && w1.bottom == w2.bottom
950
                    && w1.left == w2.left
950
                    && c1.top == c2.top
950
                    && c1.right == c2.right
950
                    && c1.bottom == c2.bottom
950
                    && c1.left == c2.left
950
                    && s1.top == s2.top
950
                    && s1.right == s2.right
950
                    && s1.bottom == s2.bottom
950
                    && s1.left == s2.left
            }
            (
                Self::Image {
4
                    bounds: b1,
4
                    image: i1,
4
                    border_radius: br1,
                },
                Self::Image {
4
                    bounds: b2,
4
                    image: i2,
4
                    border_radius: br2,
                },
            ) => {
4
                b1 == b2
                    // Compare the never-reused ImageRef identity, NOT the data
                    // pointer: `id` exists precisely because heap addresses
                    // get reused (core/resources.rs), and pointer identity
                    // also can't see "same image object, new pixels" swaps
                    // (per-frame producers replacing an ImageRef with an
                    // equal-address reallocation reported no damage).
4
                    && i1.get_hash() == i2.get_hash()
1
                    && br1.top_left == br2.top_left && br1.top_right == br2.top_right
1
                    && br1.bottom_left == br2.bottom_left && br1.bottom_right == br2.bottom_right
            }
            (
                Self::BoxShadow {
                    bounds: b1,
                    shadow: s1,
                    border_radius: br1,
                },
                Self::BoxShadow {
                    bounds: b2,
                    shadow: s2,
                    border_radius: br2,
                },
            ) => {
                b1 == b2
                    && s1 == s2
                    && br1.top_left == br2.top_left
                    && br1.top_right == br2.top_right
                    && br1.bottom_left == br2.bottom_left
                    && br1.bottom_right == br2.bottom_right
            }
            (
                Self::LinearGradient {
                    bounds: b1,
                    gradient: g1,
                    border_radius: br1,
                },
                Self::LinearGradient {
                    bounds: b2,
                    gradient: g2,
                    border_radius: br2,
                },
            ) => {
                b1 == b2
                    && g1 == g2
                    && br1.top_left == br2.top_left
                    && br1.top_right == br2.top_right
                    && br1.bottom_left == br2.bottom_left
                    && br1.bottom_right == br2.bottom_right
            }
            (
                Self::RadialGradient {
                    bounds: b1,
                    gradient: g1,
                    border_radius: br1,
                },
                Self::RadialGradient {
                    bounds: b2,
                    gradient: g2,
                    border_radius: br2,
                },
            ) => {
                b1 == b2
                    && g1 == g2
                    && br1.top_left == br2.top_left
                    && br1.top_right == br2.top_right
                    && br1.bottom_left == br2.bottom_left
                    && br1.bottom_right == br2.bottom_right
            }
            (
                Self::ConicGradient {
                    bounds: b1,
                    gradient: g1,
                    border_radius: br1,
                },
                Self::ConicGradient {
                    bounds: b2,
                    gradient: g2,
                    border_radius: br2,
                },
            ) => {
                b1 == b2
                    && g1 == g2
                    && br1.top_left == br2.top_left
                    && br1.top_right == br2.top_right
                    && br1.bottom_left == br2.bottom_left
                    && br1.bottom_right == br2.bottom_right
            }
            (
                Self::ScrollBar {
                    bounds: b1,
                    color: c1,
                    ..
                },
                Self::ScrollBar {
                    bounds: b2,
                    color: c2,
                    ..
                },
            ) => b1 == b2 && c1 == c2,
143
            (Self::PushClip { bounds: b1, .. }, Self::PushClip { bounds: b2, .. }) => b1 == b2,
            (
                Self::PushScrollFrame {
135
                    clip_bounds: b1,
135
                    scroll_id: s1,
                    ..
                },
                Self::PushScrollFrame {
135
                    clip_bounds: b2,
135
                    scroll_id: s2,
                    ..
                },
135
            ) => b1 == b2 && s1 == s2,
            (
                Self::PushStackingContext {
1085
                    z_index: z1,
1085
                    bounds: b1,
                },
                Self::PushStackingContext {
1085
                    z_index: z2,
1085
                    bounds: b2,
                },
1085
            ) => z1 == z2 && b1 == b2,
            (
                Self::PushOpacity {
2
                    bounds: b1,
2
                    opacity: o1,
2
                    opacity_key: k1,
                },
                Self::PushOpacity {
2
                    bounds: b2,
2
                    opacity: o2,
2
                    opacity_key: k2,
                },
            ) => {
                // The key participates: two lists binding different keys draw
                // from different animation channels and are NOT interchangeable
                // (same rule the GPU-damage diff relies on).
2
                b1 == b2 && o1 == o2 && k1 == k2
            }
            // Pop items with no fields are always equal (discriminant already matched)
            (Self::PopClip, Self::PopClip)
            | (Self::PopImageMaskClip, Self::PopImageMaskClip)
            | (Self::PopScrollFrame, Self::PopScrollFrame)
            | (Self::PopStackingContext, Self::PopStackingContext)
            | (Self::PopReferenceFrame, Self::PopReferenceFrame)
            | (Self::PopFilter, Self::PopFilter)
            | (Self::PopBackdropFilter, Self::PopBackdropFilter)
            | (Self::PopOpacity, Self::PopOpacity)
1415
            | (Self::PopTextShadow, Self::PopTextShadow) => true,
            // HitTestArea paints NO pixels (hit-testing only), so two of them are
            // always visually equal — a moved/changed hit region never needs a
            // repaint on its own. Without this it hit `_ => false` and forced
            // false-positive damage on every relayout (#12).
362952
            (Self::HitTestArea { .. }, Self::HitTestArea { .. }) => true,
            // TextLayout: visually equal iff same box / font / colour AND the same
            // underlying (type-erased) layout allocation. A no-op relayout reuses
            // the cached layout Arc (pointer identity holds); a real text change
            // reshapes into a new Arc. Without this it hit `_ => false` and
            // reported damage every frame (#12).
            (
                Self::TextLayout {
2
                    layout: l1,
2
                    bounds: b1,
2
                    font_hash: fh1,
2
                    font_size_px: fs1,
2
                    color: c1,
                },
                Self::TextLayout {
2
                    layout: l2,
2
                    bounds: b2,
2
                    font_hash: fh2,
2
                    font_size_px: fs2,
2
                    color: c2,
                },
2
            ) => b1 == b2 && fh1 == fh2 && fs1 == fs2 && c1 == c2 && Arc::ptr_eq(l1, l2),
            // ScrollBarStyled: equal iff the STATIC drawing info matches. The
            // LIVE thumb position/opacity are read from the GPU value cache at
            // raster time (thumb_transform_key/opacity_key) — value changes are
            // damaged by the render_frame GPU-value diff, NOT by this item
            // comparison. Without this arm every scrollbar'd window re-damaged
            // its bar every frame (`_ => false`), so `FrameDamage::None` was
            // unreachable and idle windows re-rendered + re-presented forever.
58
            (Self::ScrollBarStyled { info: i1 }, Self::ScrollBarStyled { info: i2 }) => i1 == i2,
            // VirtualView: the item only carries WHERE the child renders; the
            // child DOM's content changes are detected by
            // compute_virtual_view_damage (child display-list diff).
            (
                Self::VirtualView {
                    child_dom_id: d1,
                    bounds: b1,
                    clip_rect: c1,
                    ..
                },
                Self::VirtualView {
                    child_dom_id: d2,
                    bounds: b2,
                    clip_rect: c2,
                    ..
                },
            ) => d1 == d2 && b1 == b2 && c1 == c2,
            (
                Self::VirtualViewPlaceholder { bounds: b1, .. },
                Self::VirtualViewPlaceholder { bounds: b2, .. },
            ) => b1 == b2,
            // PushReferenceFrame: the LIVE transform (drag, animation) is a GPU
            // cache value keyed by transform_key — covered by the GPU-value
            // diff, same as the scrollbar thumb.
            (
                Self::PushReferenceFrame {
44
                    transform_key: k1,
44
                    initial_transform: t1,
44
                    bounds: b1,
                },
                Self::PushReferenceFrame {
44
                    transform_key: k2,
44
                    initial_transform: t2,
44
                    bounds: b2,
                },
44
            ) => k1 == k2 && t1 == t2 && b1 == b2,
            (
                Self::PushFilter {
                    bounds: b1,
                    filters: f1,
                },
                Self::PushFilter {
                    bounds: b2,
                    filters: f2,
                },
            ) => b1 == b2 && f1 == f2,
            (
                Self::PushBackdropFilter {
                    bounds: b1,
                    filters: f1,
                },
                Self::PushBackdropFilter {
                    bounds: b2,
                    filters: f2,
                },
            ) => b1 == b2 && f1 == f2,
            // PushImageMaskClip: ImageRef comparison is by underlying data hash
            // (cheap identity), so a swapped mask image reports unequal.
            (
                Self::PushImageMaskClip {
                    bounds: b1,
                    mask_image: m1,
                    mask_rect: r1,
                },
                Self::PushImageMaskClip {
                    bounds: b2,
                    mask_image: m2,
                    mask_rect: r2,
                },
            ) => b1 == b2 && r1 == r2 && m1.get_hash() == m2.get_hash(),
            (Self::PushTextShadow { shadow: s1 }, Self::PushTextShadow { shadow: s2 }) => s1 == s2,
            // For other complex types (Image, gradients, etc.),
            // conservatively assume different
            _ => false,
        }
613962
    }
    /// Returns true if this item is a state-management command (Push/Pop)
    /// that must always be processed to maintain correct stacks.
    #[must_use]
631424
    pub const fn is_state_management(&self) -> bool {
628287
        matches!(
631424
            self,
            Self::PushClip { .. }
                | Self::PopClip
                | Self::PushImageMaskClip { .. }
                | Self::PopImageMaskClip
                | Self::PushScrollFrame { .. }
                | Self::PopScrollFrame
                | Self::PushStackingContext { .. }
                | Self::PopStackingContext
                | Self::PushReferenceFrame { .. }
                | Self::PopReferenceFrame
                | Self::PushFilter { .. }
                | Self::PopFilter
                | Self::PushBackdropFilter { .. }
                | Self::PopBackdropFilter
                | Self::PushOpacity { .. }
                | Self::PopOpacity
                | Self::PushTextShadow { .. }
                | Self::PopTextShadow
        )
631424
    }
    /// Return the visual bounding rect including effects that extend beyond
    /// content bounds (e.g. box-shadow spread/blur/offset). Used for damage
    /// rect computation where we need the full repaint area.
    #[allow(clippy::suboptimal_flops)] // mul_add not guaranteed faster/available without target +fma; keep explicit a*b+c
    #[must_use]
659815
    pub fn visual_bounds(&self) -> Option<LogicalRect> {
659815
        match self {
            // TextLayout paints NOTHING — `render_single_item` skips it
            // outright ("metadata for PDF/accessibility"). So it must not
            // contribute damage either.
            //
            // It did. Its bounds is the enclosing node's whole content box
            // and its payload (the unified layout) changes on every edit, so
            // `is_visually_equal` said "changed" and the damage diff unioned
            // that box in — repainting the entire editor for a one-character
            // keystroke. It dominated the union completely: measured on a
            // 400x300 contenteditable, the two items that differ per
            // keystroke are this one at 356x65 (identical before and after)
            // and the caret at 2x22. Tightening TEXT damage could never show
            // up while a non-painting item was damaging everything.
            //
            // `None` here is what push/pop items already return: no pixels,
            // no damage. `bounds()` is left alone — it is the item filter in
            // the damaged renderer, and the render arm for TextLayout is a
            // no-op either way.
4660
            Self::TextLayout { .. } => None,
            // Text damages only where its GLYPHS are, not its whole clip box.
            //
            // `bounds()` reports a text run's `clip_rect`, and the emission
            // site sets that to the node's entire viewport-sized content box.
            // Since `compute_display_list_damage` unions `visual_bounds()`,
            // that made damage for a text change as coarse as the enclosing
            // text node however little of it changed — measured at 384x48 for
            // a one-character edit, i.e. every line of the paragraph.
            //
            // `bounds()` deliberately keeps returning the clip rect: it is the
            // item filter in `render_display_list_damaged`, where being too
            // WIDE only costs a redundant intersection test, while being too
            // narrow would skip an item that should have painted. Only the
            // damage side is tightened here.
            //
            // The extent is padded generously and then clamped to the clip.
            // Ink routinely exceeds the advance box — diacritics, italic
            // overhang, `f`/`j` descenders, emoji — and under-damaging leaves
            // stale pixels on screen, which is worse than the coarseness this
            // replaces. The padding is in em, so it scales with the font.
            Self::Text {
261839
                glyphs,
261839
                clip_rect,
261839
                font_size_px,
                ..
            } => {
261839
                let clip = *clip_rect.inner();
261839
                if glyphs.is_empty() {
                    return Some(clip);
261839
                }
261839
                let em = *font_size_px;
261839
                let mut min_x = f32::MAX;
261839
                let mut max_x = f32::MIN;
261839
                let mut min_y = f32::MAX;
261839
                let mut max_y = f32::MIN;
8083045
                for g in glyphs {
7821206
                    min_x = min_x.min(g.point.x);
7821206
                    max_x = max_x.max(g.point.x);
7821206
                    min_y = min_y.min(g.point.y);
7821206
                    max_y = max_y.max(g.point.y);
7821206
                }
                // `point` is the pen position ON the baseline, so the box has
                // to grow upward by the ascent and downward by the descent;
                // 1.5em/0.75em covers every Latin face plus stacked marks.
                // Horizontally the last glyph's own advance is still to come,
                // hence the extra em on the right.
261839
                let ink = LogicalRect {
261839
                    origin: LogicalPosition {
261839
                        x: min_x - em,
261839
                        y: min_y - em * 1.5,
261839
                    },
261839
                    size: LogicalSize {
261839
                        width: (max_x - min_x) + em * 2.0,
261839
                        height: (max_y - min_y) + em * 2.25,
261839
                    },
261839
                };
261839
                Some(intersect_or(ink, clip))
            }
83
            Self::BoxShadow { bounds, shadow, .. } => {
83
                let b = *bounds.inner();
                // Shadow can extend beyond element bounds by offset + spread + blur
83
                let ox = shadow
83
                    .offset_x
83
                    .to_pixels_internal(DEFAULT_SHADOW_FONT_SIZE_PX, DEFAULT_SHADOW_FONT_SIZE_PX)
83
                    .abs();
83
                let oy = shadow
83
                    .offset_y
83
                    .to_pixels_internal(DEFAULT_SHADOW_FONT_SIZE_PX, DEFAULT_SHADOW_FONT_SIZE_PX)
83
                    .abs();
83
                let blur = shadow
83
                    .blur_radius
83
                    .to_pixels_internal(DEFAULT_SHADOW_FONT_SIZE_PX, DEFAULT_SHADOW_FONT_SIZE_PX)
83
                    .abs();
83
                let spread = shadow
83
                    .spread_radius
83
                    .to_pixels_internal(DEFAULT_SHADOW_FONT_SIZE_PX, DEFAULT_SHADOW_FONT_SIZE_PX)
83
                    .abs();
83
                let expand = ox + oy + blur + spread;
83
                Some(LogicalRect {
83
                    origin: LogicalPosition {
83
                        x: b.origin.x - expand,
83
                        y: b.origin.y - expand,
83
                    },
83
                    size: LogicalSize {
83
                        width: b.size.width + expand * 2.0,
83
                        height: b.size.height + expand * 2.0,
83
                    },
83
                })
            }
393233
            _ => self.bounds(),
        }
659815
    }
    /// Return the bounding rect of this item, or None for push/pop commands
    /// that don't have their own visual bounds.
    #[allow(clippy::match_same_arms)]
    // enum/value mapping/dispatch table: one arm per input variant (or cross-type bindings that
    // can't merge)
    #[must_use]
2254180
    pub fn bounds(&self) -> Option<LogicalRect> {
2254180
        match self {
44951
            Self::Rect { bounds, .. }
1286
            | Self::SelectionRect { bounds, .. }
5921
            | Self::CursorRect { bounds, .. }
46870
            | Self::Border { bounds, .. }
            | Self::Text {
634388
                clip_rect: bounds, ..
            }
33150
            | Self::TextLayout { bounds, .. }
701
            | Self::Underline { bounds, .. }
            | Self::Strikethrough { bounds, .. }
            | Self::Overline { bounds, .. }
174
            | Self::Image { bounds, .. }
1
            | Self::ScrollBar { bounds, .. }
30
            | Self::StrokedPath { bounds, .. }
211
            | Self::LinearGradient { bounds, .. }
51
            | Self::RadialGradient { bounds, .. }
1
            | Self::ConicGradient { bounds, .. }
761
            | Self::BoxShadow { bounds, .. }
10
            | Self::VirtualView { bounds, .. }
1265
            | Self::VirtualViewPlaceholder { bounds, .. }
1418089
            | Self::HitTestArea { bounds, .. }
8547
            | Self::PushClip { bounds, .. }
181
            | Self::PushImageMaskClip { bounds, .. }
            | Self::PushScrollFrame {
2092
                clip_bounds: bounds,
                ..
            }
21273
            | Self::PushStackingContext { bounds, .. }
290
            | Self::PushReferenceFrame { bounds, .. }
            | Self::PushFilter { bounds, .. }
            | Self::PushBackdropFilter { bounds, .. }
2220349
            | Self::PushOpacity { bounds, .. } => Some(*bounds.inner()),
1472
            Self::ScrollBarStyled { info, .. } => Some(*info.bounds.inner()),
1
            Self::PushTextShadow { .. } => None, /* text shadow has no bounds, affects following
                                                   * text */
            Self::PopClip
            | Self::PopImageMaskClip
            | Self::PopScrollFrame
            | Self::PopStackingContext
            | Self::PopReferenceFrame
            | Self::PopFilter
            | Self::PopBackdropFilter
            | Self::PopOpacity
32358
            | Self::PopTextShadow => None,
        }
2254180
    }
}
// Helper structs for the DisplayList
#[derive(Debug, Copy, Clone, Default, PartialEq)]
pub struct BorderRadius {
    pub top_left: f32,
    pub top_right: f32,
    pub bottom_left: f32,
    pub bottom_right: f32,
}
impl BorderRadius {
    #[must_use]
13752
    pub fn is_zero(&self) -> bool {
13752
        self.top_left == 0.0
13144
            && self.top_right == 0.0
13143
            && self.bottom_left == 0.0
13142
            && self.bottom_right == 0.0
13752
    }
}
// Dummy types for compilation
pub type LocalScrollId = u64;
/// Display list tag ID as (payload, `type_marker`) tuple.
/// The u16 field is used as a namespace marker:
/// - 0x0100 = DOM Node (regular interactive elements)
/// - 0x0200 = Scrollbar component
pub(crate) type DisplayListTagId = (u64, u16);
/// Internal builder to accumulate display list items during generation.
#[derive(Debug, Default)]
struct DisplayListBuilder {
    items: Vec<DisplayListItem>,
    node_mapping: Vec<Option<NodeId>>,
    /// Current node being processed (set by generator)
    current_node: Option<NodeId>,
    /// Collected debug messages (transferred to ctx on finalize)
    debug_messages: Vec<LayoutDebugMessage>,
    /// Whether debug logging is enabled
    debug_enabled: bool,
    /// Y-positions where forced page breaks should occur
    forced_page_breaks: Vec<ForcedBreak>,
    /// Index ranges of items from fixed-position elements (for paged media replication)
    fixed_position_item_ranges: Vec<(usize, usize)>,
    /// Start index of the current fixed-position element being built, if any
    fixed_position_start: Option<usize>,
    /// Current (layout index, phase) for `layout_node_mapping` — see
    /// [`DisplayList::layout_node_mapping`].
    current_layout: Option<(usize, EmitPhase)>,
    layout_node_mapping: Vec<Option<(usize, EmitPhase)>>,
    /// One-shot: the uniform background for the NEXT pushed item (set by
    /// `push_text_run` / the patch copy just before pushing a Text item).
    next_text_bg: Option<(ColorU, WindowLogicalRect)>,
    uniform_text_bgs: Vec<Option<(ColorU, WindowLogicalRect)>>,
    /// One-shot: the `(unselected, selected)` colours for the NEXT pushed
    /// item — see [`DisplayList::text_selection_colors`].
    pub(crate) next_text_selection_colors: Option<(ColorU, ColorU)>,
    text_selection_colors: Vec<Option<(ColorU, ColorU)>>,
}
impl DisplayListBuilder {
26
    pub(crate) fn new() -> Self {
26
        Self::default()
26
    }
16492
    pub(crate) const fn with_debug(debug_enabled: bool) -> Self {
16492
        Self {
16492
            items: Vec::new(),
16492
            node_mapping: Vec::new(),
16492
            current_node: None,
16492
            debug_messages: Vec::new(),
16492
            debug_enabled,
16492
            forced_page_breaks: Vec::new(),
16492
            fixed_position_item_ranges: Vec::new(),
16492
            fixed_position_start: None,
16492
            current_layout: None,
16492
            layout_node_mapping: Vec::new(),
16492
            next_text_bg: None,
16492
            uniform_text_bgs: Vec::new(),
16492
            next_text_selection_colors: None,
16492
            text_selection_colors: Vec::new(),
16492
        }
16492
    }
    /// Log a debug message if debug is enabled
597636
    fn debug_log(&mut self, message: String) {
597636
        if self.debug_enabled {
64574
            self.debug_messages.push(LayoutDebugMessage::info(message));
533062
        }
597636
    }
    /// Build the display list and transfer debug messages to the provided option
16490
    pub(crate) fn build_with_debug(
16490
        mut self,
16490
        debug_messages: &mut Option<Vec<LayoutDebugMessage>>,
16490
    ) -> DisplayList {
        // Transfer collected debug messages to the context
16490
        if let Some(msgs) = debug_messages.as_mut() {
8498
            msgs.append(&mut self.debug_messages);
8593
        }
16490
        DisplayList {
16490
            items: self.items,
16490
            node_mapping: self.node_mapping,
16490
            forced_page_breaks: self.forced_page_breaks,
16490
            fixed_position_item_ranges: self.fixed_position_item_ranges,
16490
            layout_node_mapping: self.layout_node_mapping,
16490
            uniform_text_bgs: self.uniform_text_bgs,
16490
            text_selection_colors: self.text_selection_colors,
16490
        }
16490
    }
    /// Set the current node context for subsequent push operations
1592311
    pub(crate) const fn set_current_node(&mut self, node_id: Option<NodeId>) {
1592311
        self.current_node = node_id;
1592311
    }
    /// Tag subsequent pushes with (layout index, phase). `None` = untagged
    /// (equivalent to `ScWalk` for patching purposes — never substituted).
3150212
    pub(crate) const fn set_current_layout(&mut self, tag: Option<(usize, EmitPhase)>) {
3150212
        self.current_layout = tag;
3150212
    }
    /// The current node context (to save/restore around pushes that must be
    /// attributed to a DIFFERENT node, e.g. inline images inside an IFC).
    pub(crate) const fn current_node(&self) -> Option<NodeId> {
        self.current_node
    }
    /// Mark the start of a fixed-position element's display items.
2
    pub(crate) const fn begin_fixed_position_element(&mut self) {
2
        self.fixed_position_start = Some(self.items.len());
2
    }
    /// Mark the end of a fixed-position element's display items.
    /// Records the (start, end) index range for paged media replication.
4
    pub(crate) fn end_fixed_position_element(&mut self) {
4
        if let Some(start) = self.fixed_position_start.take() {
2
            let end = self.items.len();
2
            if end > start {
1
                self.fixed_position_item_ranges.push((start, end));
1
            }
2
        }
4
    }
    /// Register a forced page break at the given Y position, remembering the
    /// node whose break property caused it (diagnostics: surfaces in
    /// `PageBreakPosition::causing_node`).
    /// This is used for CSS break-before: always and break-after: always.
71
    pub(crate) fn add_forced_page_break(&mut self, y_position: f32, causing_node: Option<NodeId>) {
        // Avoid duplicates and keep sorted by Y
86
        if !self.forced_page_breaks.iter().any(|b| b.y == y_position) {
70
            self.forced_page_breaks.push(ForcedBreak {
70
                y: y_position,
70
                causing_node,
70
            });
70
            self.forced_page_breaks
95
                .sort_by(|a, b| a.y.partial_cmp(&b.y).unwrap_or(core::cmp::Ordering::Equal));
1
        }
71
    }
    /// Push an item and record its node mapping.
    ///
    /// Drops items whose geometry is still the UNASSIGNED-POSITION SENTINEL.
    ///
    /// `calculated_positions` seeds entries with `f32::MIN`, and an inline text
    /// node's own box position is never assigned — see the comment on
    /// `paint_text_selection`, which anchors to the IFC root precisely because
    /// "the node's OWN box position is never assigned (stays the `f32::MIN`
    /// sentinel)". That workaround is local to one caller; the other thirteen
    /// readers of `calculated_positions` get the raw sentinel.
    ///
    /// The published 0.2.0 azul-self-test-linux display list carried 24 of
    /// them, e.g.
    ///
    /// ```text
    /// Border      { bounds: WindowLogicalRect(624x0 @ (-3.4028235e38, -3.4028235e38)) }
    /// HitTestArea { bounds: WindowLogicalRect(624x0 @ (-3.4028235e38, -3.4028235e38)) }
    /// ```
    ///
    /// A `Border` at -3.4e38 is merely invisible. A `HitTestArea` there is
    /// ACTIVELY WRONG: it is a live hit-test rectangle at a coordinate no
    /// pointer can reach, and any arithmetic on it (offsetting into a parent
    /// space, unioning a bounding box) produces infinities that then propagate
    /// into rects that ARE on screen.
    ///
    /// Dropping is right rather than clamping to the origin: the item has no
    /// position, and inventing (0,0) would put a phantom border and a live
    /// hit target in the top-left corner of the window. An item nobody can
    /// see and nobody can click is exactly what an unpositioned node should
    /// contribute.
1722719
    fn push_item(&mut self, item: DisplayListItem) {
        // A TextLayout carrying `FontHash::invalid()` (0) describes text in a
        // font that does not exist. Verified before dropping it, because
        // "harmless metadata" is a claim that has to be checked:
        //   * compositor2.rs   — explicit no-op, "handled elsewhere (via PushCachedTextRuns)"; the
        //     GPU path never draws it
        //   * cpurender/raster — "TextLayout is metadata for PDF/accessibility - skip in CPU
        //     rendering"
        //   * hit-testing      — uses separate HitTestArea items
        //   * selection        — uses get_selection_rects on the inline layout, not display-list
        //     items
        //   * scan_used_fonts  — reads font_hash (fixed separately: 0 was being turned into a
        //     phantom FontKey and marked live)
        //   * PDF export       — cannot render text in a font it cannot resolve
        // So nothing draws, hits, or selects it, and the one consumer that read
        // it was harmed by doing so.
1722719
        if let DisplayListItem::TextLayout { font_hash, .. } = &item {
9800
            if font_hash.font_hash == 0 {
                #[cfg(debug_assertions)]
                eprintln!(
                    "[azul][displaylist] dropping a TextLayout with FontHash::invalid() — its \
                     font never resolved, so no renderer would have drawn it"
                );
250
                return;
9550
            }
1712919
        }
1722469
        if let Some(b) = item.bounds() {
3388235
            let unassigned = |v: f32| !v.is_finite() || v <= UNASSIGNED_POSITION_LIMIT;
1695099
            if unassigned(b.origin.x) || unassigned(b.origin.y) {
                #[cfg(debug_assertions)]
                eprintln!(
                    "[azul][displaylist] dropping {item:?} at an unassigned position ({}, {}) — \
                     its layout node never received a computed position",
                    b.origin.x, b.origin.y,
                );
1963
                return;
1693136
            }
27370
        }
        // Structural push/pop items get NO node attribution. Before this,
        // they inherited whatever `current_node` the LAST paint call leaked —
        // a PopStackingContext attributed to some text node that happened to
        // paint last. No consumer legitimately reads a break property or a
        // damage source off a Push/Pop, and the leak made attribution
        // pass-history-dependent (the DL-patch golden test caught patched
        // and full passes disagreeing about it).
1720506
        let attr = if matches!(
1720506
            item,
            DisplayListItem::PushClip { .. }
                | DisplayListItem::PopClip
                | DisplayListItem::PushImageMaskClip { .. }
                | DisplayListItem::PopImageMaskClip
                | DisplayListItem::PushScrollFrame { .. }
                | DisplayListItem::PopScrollFrame
                | DisplayListItem::PushStackingContext { .. }
                | DisplayListItem::PopStackingContext
                | DisplayListItem::PushReferenceFrame { .. }
                | DisplayListItem::PopReferenceFrame
                | DisplayListItem::PushFilter { .. }
                | DisplayListItem::PopFilter
                | DisplayListItem::PushBackdropFilter { .. }
                | DisplayListItem::PopBackdropFilter
                | DisplayListItem::PushOpacity { .. }
                | DisplayListItem::PopOpacity
        ) {
54736
            None
        } else {
1665770
            self.current_node
        };
1720506
        self.items.push(item);
1720506
        self.node_mapping.push(attr);
1720506
        self.layout_node_mapping.push(self.current_layout);
1720506
        self.uniform_text_bgs.push(self.next_text_bg.take());
1720506
        self.text_selection_colors
1720506
            .push(self.next_text_selection_colors.take());
1722719
    }
3
    pub(crate) fn build(self) -> DisplayList {
3
        DisplayList {
3
            items: self.items,
3
            node_mapping: self.node_mapping,
3
            forced_page_breaks: self.forced_page_breaks,
3
            fixed_position_item_ranges: self.fixed_position_item_ranges,
3
            layout_node_mapping: self.layout_node_mapping,
3
            uniform_text_bgs: self.uniform_text_bgs,
3
            text_selection_colors: self.text_selection_colors,
3
        }
3
    }
969089
    pub(crate) fn push_hit_test_area(&mut self, bounds: LogicalRect, tag: DisplayListTagId) {
969089
        self.push_item(DisplayListItem::HitTestArea {
969089
            bounds: bounds.into(),
969089
            tag,
969089
        });
969089
    }
    /// Push a simple single-color scrollbar (legacy method).
2
    pub(crate) fn push_scrollbar(
2
        &mut self,
2
        bounds: LogicalRect,
2
        color: ColorU,
2
        orientation: ScrollbarOrientation,
2
        opacity_key: Option<OpacityKey>,
2
        hit_id: Option<azul_core::hit_test::ScrollbarHitId>,
2
    ) {
2
        if color.a > 0 || opacity_key.is_some() {
1
            // Optimization: Don't draw fully transparent items without opacity keys.
1
            self.push_item(DisplayListItem::ScrollBar {
1
                bounds: bounds.into(),
1
                color,
1
                orientation,
1
                opacity_key,
1
                hit_id,
1
            });
1
        }
2
    }
    /// Push a fully styled scrollbar with track, thumb, and optional buttons.
1254
    pub(crate) fn push_scrollbar_styled(&mut self, info: ScrollbarDrawInfo) {
        // Only push if at least the thumb or track is visible
1254
        if info.thumb_color.a > 0 || info.track_color.a > 0 || info.opacity_key.is_some() {
1254
            self.push_item(DisplayListItem::ScrollBarStyled {
1254
                info: Box::new(info),
1254
            });
1254
        }
1254
    }
52776
    pub(crate) fn push_rect(
52776
        &mut self,
52776
        bounds: LogicalRect,
52776
        color: ColorU,
52776
        border_radius: BorderRadius,
52776
    ) {
52776
        if color.a > 0 {
35625
            // Optimization: Don't draw fully transparent items.
35625
            self.push_item(DisplayListItem::Rect {
35625
                bounds: bounds.into(),
35625
                color,
35625
                border_radius,
35625
            });
35625
        }
52776
    }
    /// Unified method to paint all background layers and border for an element.
    ///
    /// This consolidates the background/border painting logic that was previously
    /// duplicated across:
    /// - `paint_node_background_and_border()` for block elements
    /// - `paint_inline_shape()` for inline-block elements
    ///
    /// The backgrounds are painted in order (back to front per CSS spec), followed
    /// by the border.
446068
    pub(crate) fn push_backgrounds_and_border(
446068
        &mut self,
446068
        bounds: LogicalRect,
446068
        background_contents: &[azul_css::props::style::StyleBackgroundContent],
446068
        border_info: &BorderInfo,
446068
        simple_border_radius: BorderRadius,
446068
        style_border_radius: StyleBorderRadius,
446068
        image_cache: &azul_core::resources::ImageCache,
446068
    ) {
        use azul_css::props::style::StyleBackgroundContent;
        // Paint all background layers in order (CSS paints backgrounds back to front)
495365
        for bg in background_contents {
49297
            match bg {
49204
                StyleBackgroundContent::Color(color) => {
49204
                    self.push_rect(bounds, *color, simple_border_radius);
49204
                }
40
                StyleBackgroundContent::LinearGradient(gradient) => {
40
                    self.push_linear_gradient(bounds, gradient.clone(), simple_border_radius);
40
                }
10
                StyleBackgroundContent::RadialGradient(gradient) => {
10
                    self.push_radial_gradient(bounds, gradient.clone(), simple_border_radius);
10
                }
                StyleBackgroundContent::ConicGradient(gradient) => {
                    self.push_conic_gradient(bounds, gradient.clone(), simple_border_radius);
                }
3
                StyleBackgroundContent::Image(image_id) => {
3
                    if let Some(image_ref) = image_cache.get_css_image_id(image_id) {
1
                        self.push_image(bounds, image_ref.clone(), simple_border_radius);
2
                    }
                }
40
                StyleBackgroundContent::SystemColor(_s) => {
40
                    // TODO(superplan g8): resolve via SystemColorRef::resolve(&SystemColors,
40
                    // fallback) and push_rect. SystemColors is not threaded into the
40
                    // display-list builder yet, so `background: system:<name>` currently
40
                    // parses but paints nothing (graceful no-op rather than a wrong color).
40
                }
            }
        }
        // Paint border
446068
        self.push_border(
446068
            bounds,
446068
            border_info.widths,
446068
            border_info.colors,
446068
            border_info.styles,
446068
            style_border_radius,
        );
446068
    }
    /// Paint backgrounds and border for inline text elements.
    ///
    /// Similar to `push_backgrounds_and_border` but uses `InlineBorderInfo` which stores
    /// pre-resolved pixel values instead of CSS property values. This is used for
    /// inline (display: inline) elements where the border info is computed during
    /// text layout and stored in the glyph runs.
593730
    pub(crate) fn push_inline_backgrounds_and_border(
593730
        &mut self,
593730
        bounds: LogicalRect,
593730
        background_color: Option<ColorU>,
593730
        background_contents: &[azul_css::props::style::StyleBackgroundContent],
593730
        border: Option<&crate::text3::cache::InlineBorderInfo>,
593730
        image_cache: &azul_core::resources::ImageCache,
593730
    ) {
        use azul_css::props::style::StyleBackgroundContent;
        // Paint solid background color if present
593730
        if let Some(bg_color) = background_color {
30
            self.push_rect(bounds, bg_color, BorderRadius::default());
593700
        }
        // Paint all background layers in order (CSS paints backgrounds back to front)
593770
        for bg in background_contents {
40
            match bg {
30
                StyleBackgroundContent::Color(color) => {
30
                    self.push_rect(bounds, *color, BorderRadius::default());
30
                }
10
                StyleBackgroundContent::LinearGradient(gradient) => {
10
                    self.push_linear_gradient(bounds, gradient.clone(), BorderRadius::default());
10
                }
                StyleBackgroundContent::RadialGradient(gradient) => {
                    self.push_radial_gradient(bounds, gradient.clone(), BorderRadius::default());
                }
                StyleBackgroundContent::ConicGradient(gradient) => {
                    self.push_conic_gradient(bounds, gradient.clone(), BorderRadius::default());
                }
                StyleBackgroundContent::Image(image_id) => {
                    if let Some(image_ref) = image_cache.get_css_image_id(image_id) {
                        self.push_image(bounds, image_ref.clone(), BorderRadius::default());
                    }
                }
                StyleBackgroundContent::SystemColor(_s) => {
                    // TODO(superplan g8): resolve via SystemColorRef::resolve(&SystemColors,
                    // fallback) and push_rect. SystemColors is not threaded into the
                    // display-list builder yet, so `background: system:<name>` currently
                    // parses but paints nothing (graceful no-op rather than a wrong color).
                }
            }
        }
        // Paint border if present
        // CSS 2.2 §8.6: suppress left/right borders at split points, respecting direction
593730
        if let Some(border) = border {
30
            let effective_left = if border.left_inset() > 0.0 {
30
                border.left
            } else {
                0.0
            };
30
            let effective_right = if border.right_inset() > 0.0 {
30
                border.right
            } else {
                0.0
            };
30
            if border.top > 0.0
20
                || effective_right > 0.0
20
                || border.bottom > 0.0
20
                || effective_left > 0.0
10
            {
10
                let border_widths = StyleBorderWidths {
10
                    top: Some(CssPropertyValue::Exact(LayoutBorderTopWidth {
10
                        inner: PixelValue::px(border.top),
10
                    })),
10
                    right: Some(CssPropertyValue::Exact(LayoutBorderRightWidth {
10
                        inner: PixelValue::px(effective_right),
10
                    })),
10
                    bottom: Some(CssPropertyValue::Exact(LayoutBorderBottomWidth {
10
                        inner: PixelValue::px(border.bottom),
10
                    })),
10
                    left: Some(CssPropertyValue::Exact(LayoutBorderLeftWidth {
10
                        inner: PixelValue::px(effective_left),
10
                    })),
10
                };
10
                let border_colors = StyleBorderColors {
10
                    top: Some(CssPropertyValue::Exact(StyleBorderTopColor {
10
                        inner: border.top_color,
10
                    })),
10
                    right: Some(CssPropertyValue::Exact(StyleBorderRightColor {
10
                        inner: border.right_color,
10
                    })),
10
                    bottom: Some(CssPropertyValue::Exact(StyleBorderBottomColor {
10
                        inner: border.bottom_color,
10
                    })),
10
                    left: Some(CssPropertyValue::Exact(StyleBorderLeftColor {
10
                        inner: border.left_color,
10
                    })),
10
                };
10
                let border_styles = StyleBorderStyles {
10
                    top: Some(CssPropertyValue::Exact(StyleBorderTopStyle {
10
                        inner: BorderStyle::Solid,
10
                    })),
10
                    right: Some(CssPropertyValue::Exact(StyleBorderRightStyle {
10
                        inner: BorderStyle::Solid,
10
                    })),
10
                    bottom: Some(CssPropertyValue::Exact(StyleBorderBottomStyle {
10
                        inner: BorderStyle::Solid,
10
                    })),
10
                    left: Some(CssPropertyValue::Exact(StyleBorderLeftStyle {
10
                        inner: BorderStyle::Solid,
10
                    })),
10
                };
10
                let radius_px = PixelValue::px(border.radius.unwrap_or(0.0));
10
                let border_radius = StyleBorderRadius {
10
                    top_left: radius_px,
10
                    top_right: radius_px,
10
                    bottom_left: radius_px,
10
                    bottom_right: radius_px,
10
                };
10

            
10
                self.push_border(
10
                    bounds,
10
                    border_widths,
10
                    border_colors,
10
                    border_styles,
10
                    border_radius,
10
                );
20
            }
593700
        }
593730
    }
    /// Push a linear gradient background
51
    pub(crate) fn push_linear_gradient(
51
        &mut self,
51
        bounds: LogicalRect,
51
        gradient: LinearGradient,
51
        border_radius: BorderRadius,
51
    ) {
51
        self.push_item(DisplayListItem::LinearGradient {
51
            bounds: bounds.into(),
51
            gradient,
51
            border_radius,
51
        });
51
    }
    /// Push a radial gradient background
11
    pub(crate) fn push_radial_gradient(
11
        &mut self,
11
        bounds: LogicalRect,
11
        gradient: RadialGradient,
11
        border_radius: BorderRadius,
11
    ) {
11
        self.push_item(DisplayListItem::RadialGradient {
11
            bounds: bounds.into(),
11
            gradient,
11
            border_radius,
11
        });
11
    }
    /// Push a conic gradient background
1
    pub(crate) fn push_conic_gradient(
1
        &mut self,
1
        bounds: LogicalRect,
1
        gradient: ConicGradient,
1
        border_radius: BorderRadius,
1
    ) {
1
        self.push_item(DisplayListItem::ConicGradient {
1
            bounds: bounds.into(),
1
            gradient,
1
            border_radius,
1
        });
1
    }
1285
    pub(crate) fn push_selection_rect(
1285
        &mut self,
1285
        bounds: LogicalRect,
1285
        color: ColorU,
1285
        border_radius: BorderRadius,
1285
    ) {
1285
        if color.a > 0 {
1284
            self.push_item(DisplayListItem::SelectionRect {
1284
                bounds: bounds.into(),
1284
                color,
1284
                border_radius,
1284
            });
1284
        }
1285
    }
4819
    pub(crate) fn push_cursor_rect(&mut self, bounds: LogicalRect, color: ColorU) {
        // Always emit the caret item — even with alpha == 0 in the blink-off phase — so
        // the display-list item COUNT stays stable across blink phases. That lets
        // compute_display_list_damage diff it down to a caret-sized rect instead of
        // falling back to a full-window repaint every ~530ms.
4819
        self.push_item(DisplayListItem::CursorRect {
4819
            bounds: bounds.into(),
4819
            color,
4819
        });
4819
    }
8305
    pub(crate) fn push_clip(&mut self, bounds: LogicalRect, border_radius: BorderRadius) {
8305
        self.push_item(DisplayListItem::PushClip {
8305
            bounds: bounds.into(),
8305
            border_radius,
8305
        });
8305
    }
8307
    pub(crate) fn pop_clip(&mut self) {
8307
        self.push_item(DisplayListItem::PopClip);
8307
    }
181
    pub(crate) fn push_image_mask_clip(
181
        &mut self,
181
        bounds: LogicalRect,
181
        mask_image: ImageRef,
181
        mask_rect: LogicalRect,
181
    ) {
181
        self.push_item(DisplayListItem::PushImageMaskClip {
181
            bounds: bounds.into(),
181
            mask_image,
181
            mask_rect: mask_rect.into(),
181
        });
181
    }
181
    pub(crate) fn pop_image_mask_clip(&mut self) {
181
        self.push_item(DisplayListItem::PopImageMaskClip);
181
    }
2091
    pub(crate) fn push_scroll_frame(
2091
        &mut self,
2091
        clip_bounds: LogicalRect,
2091
        content_size: LogicalSize,
2091
        scroll_id: LocalScrollId,
2091
    ) {
2091
        self.push_item(DisplayListItem::PushScrollFrame {
2091
            clip_bounds: clip_bounds.into(),
2091
            content_size,
2091
            scroll_id,
2091
        });
2091
    }
2091
    pub(crate) fn pop_scroll_frame(&mut self) {
2091
        self.push_item(DisplayListItem::PopScrollFrame);
2091
    }
1205
    pub(crate) fn push_virtual_view_placeholder(
1205
        &mut self,
1205
        node_id: NodeId,
1205
        bounds: LogicalRect,
1205
        clip_rect: LogicalRect,
1205
    ) {
1205
        self.push_item(DisplayListItem::VirtualViewPlaceholder {
1205
            node_id,
1205
            bounds: bounds.into(),
1205
            clip_rect: clip_rect.into(),
1205
        });
1205
    }
446086
    pub(crate) fn push_border(
446086
        &mut self,
446086
        bounds: LogicalRect,
446086
        widths: StyleBorderWidths,
446086
        colors: StyleBorderColors,
446086
        styles: StyleBorderStyles,
446086
        border_radius: StyleBorderRadius,
446086
    ) {
        // A `Border` item exists only when some side actually PAINTS: a
        // positive width AND a style other than `none` / `hidden` on that
        // side (CSS Backgrounds 3 §4.2: `border-style: none` computes the
        // width to 0). "Any width is Some and any style is Some" was not
        // that test — the compact property cache answers `Some(0px)` and
        // `Some(none)` for every UNSET border, so every node in its normal
        // state carried an invisible zero-width Border item, while the same
        // node in a `:hover` / `:focus` / `:active` state (resolved through
        // the slow path, which answers `None`) carried none. A pseudo-state
        // flip therefore changed the item list without any restyle, and the
        // patched display list drifted from the wholesale build by exactly
        // those phantoms (`bug-scroll-offsets-hit-test` under
        // AZ_PATCH_VERIFY).
446086
        let has_visible_border = Self::border_side_paints(
446086
            widths
446086
                .top
446086
                .as_ref()
446086
                .and_then(|w| w.get_property())
446086
                .map(|w| w.inner),
446086
            styles
446086
                .top
446086
                .as_ref()
446086
                .and_then(|s| s.get_property())
446086
                .map(|s| s.inner),
419047
        ) || Self::border_side_paints(
419047
            widths
419047
                .right
419047
                .as_ref()
419047
                .and_then(|w| w.get_property())
419047
                .map(|w| w.inner),
419047
            styles
419047
                .right
419047
                .as_ref()
419047
                .and_then(|s| s.get_property())
419047
                .map(|s| s.inner),
413627
        ) || Self::border_side_paints(
413627
            widths
413627
                .bottom
413627
                .as_ref()
413627
                .and_then(|w| w.get_property())
413627
                .map(|w| w.inner),
413627
            styles
413627
                .bottom
413627
                .as_ref()
413627
                .and_then(|s| s.get_property())
413627
                .map(|s| s.inner),
402407
        ) || Self::border_side_paints(
402407
            widths
402407
                .left
402407
                .as_ref()
402407
                .and_then(|w| w.get_property())
402407
                .map(|w| w.inner),
402407
            styles
402407
                .left
402407
                .as_ref()
402407
                .and_then(|s| s.get_property())
402407
                .map(|s| s.inner),
        );
446086
        if has_visible_border {
45110
            self.push_item(DisplayListItem::Border {
45110
                bounds: bounds.into(),
45110
                widths,
45110
                colors,
45110
                styles,
45110
                border_radius,
45110
            });
400976
        }
446086
    }
    /// One border side paints when its width resolves above zero and its
    /// style draws something (`none` and `hidden` never do). Widths are
    /// resolved the way the rasterizer resolves them (no percentage basis,
    /// the default font size for em).
1681167
    fn border_side_paints(width: Option<PixelValue>, style: Option<BorderStyle>) -> bool {
1681167
        let width = width.map_or(0.0, |w| {
1680635
            w.to_pixels_internal(
                0.0,
                azul_css::props::basic::pixel::DEFAULT_FONT_SIZE,
                azul_css::props::basic::pixel::DEFAULT_FONT_SIZE,
            )
1680635
        });
1681167
        width > 0.0 && style.is_some_and(|s| !matches!(s, BorderStyle::None | BorderStyle::Hidden))
1681167
    }
16594
    pub(crate) fn push_stacking_context(&mut self, z_index: i32, bounds: LogicalRect) {
16594
        self.push_item(DisplayListItem::PushStackingContext {
16594
            z_index,
16594
            bounds: bounds.into(),
16594
        });
16594
    }
16593
    pub(crate) fn pop_stacking_context(&mut self) {
16593
        self.push_item(DisplayListItem::PopStackingContext);
16593
    }
95
    pub(crate) fn push_reference_frame(
95
        &mut self,
95
        transform_key: TransformKey,
95
        initial_transform: ComputedTransform3D,
95
        bounds: LogicalRect,
95
    ) {
95
        self.push_item(DisplayListItem::PushReferenceFrame {
95
            transform_key,
95
            initial_transform,
95
            bounds: bounds.into(),
95
        });
95
    }
95
    pub(crate) fn pop_reference_frame(&mut self) {
95
        self.push_item(DisplayListItem::PopReferenceFrame);
95
    }
597628
    pub(crate) fn push_text_run(
597628
        &mut self,
597628
        glyphs: Vec<GlyphInstance>,
597628
        font_hash: FontHash, // Just the hash, not the full FontRef
597628
        font_size_px: f32,
597628
        color: ColorU,
597628
        clip_rect: LogicalRect,
597628
        source_node_index: Option<usize>,
597628
        uniform_bg: Option<(ColorU, WindowLogicalRect)>,
597628
    ) {
597628
        self.debug_log(format!(
597628
            "[push_text_run] {} glyphs, font_size={}px, color=({},{},{},{}), clip={:?}",
597628
            glyphs.len(),
            font_size_px,
            color.r,
            color.g,
            color.b,
            color.a,
            clip_rect
        ));
597628
        if !glyphs.is_empty() && color.a > 0 {
597626
            self.next_text_bg = uniform_bg;
597626
            self.push_item(DisplayListItem::Text {
597626
                glyphs,
597626
                font_hash,
597626
                font_size_px,
597626
                color,
597626
                clip_rect: clip_rect.into(),
597626
                source_node_index,
597626
            });
597626
        } else {
2
            // Nothing pushed: the one-shot must not land on the next item.
2
            self.next_text_selection_colors = None;
2
            self.debug_log(format!(
2
                "[push_text_run] SKIPPED: glyphs.is_empty()={}, color.a={}",
2
                glyphs.is_empty(),
2
                color.a
2
            ));
2
        }
597628
    }
9800
    pub(crate) fn push_text_layout(
9800
        &mut self,
9800
        layout: Arc<dyn std::any::Any + Send + Sync>,
9800
        bounds: LogicalRect,
9800
        font_hash: FontHash,
9800
        font_size_px: f32,
9800
        color: ColorU,
9800
    ) {
9800
        if color.a > 0 {
9800
            self.push_item(DisplayListItem::TextLayout {
9800
                layout,
9800
                bounds: bounds.into(),
9800
                font_hash,
9800
                font_size_px,
9800
                color,
9800
            });
9800
        }
9800
    }
705
    pub(crate) fn push_underline(&mut self, bounds: LogicalRect, color: ColorU, thickness: f32) {
705
        if color.a > 0 && thickness > 0.0 {
701
            self.push_item(DisplayListItem::Underline {
701
                bounds: bounds.into(),
701
                color,
701
                thickness,
701
            });
704
        }
705
    }
4
    pub(crate) fn push_strikethrough(
4
        &mut self,
4
        bounds: LogicalRect,
4
        color: ColorU,
4
        thickness: f32,
4
    ) {
4
        if color.a > 0 && thickness > 0.0 {
            self.push_item(DisplayListItem::Strikethrough {
                bounds: bounds.into(),
                color,
                thickness,
            });
4
        }
4
    }
5
    pub(crate) fn push_overline(&mut self, bounds: LogicalRect, color: ColorU, thickness: f32) {
5
        if color.a > 0 && thickness > 0.0 {
            self.push_item(DisplayListItem::Overline {
                bounds: bounds.into(),
                color,
                thickness,
            });
5
        }
5
    }
155
    pub(crate) fn push_image(
155
        &mut self,
155
        bounds: LogicalRect,
155
        image: ImageRef,
155
        border_radius: BorderRadius,
155
    ) {
155
        self.push_item(DisplayListItem::Image {
155
            bounds: bounds.into(),
155
            image,
155
            border_radius,
155
        });
155
    }
}
/// Main entry point for generating the display list.
#[allow(clippy::implicit_hasher)] // internal helper; only ever called with the default-hasher HashMap/HashSet
/// # Errors
///
/// Returns a `LayoutError` if display-list generation fails.
6189
pub fn generate_display_list<T: ParsedFontTrait + Sync + 'static>(
6189
    ctx: &mut LayoutContext<'_, T>,
6189
    tree: &LayoutTree,
6189
    calculated_positions: &super::PositionVec,
6189
    scroll_offsets: &BTreeMap<NodeId, ScrollPosition>,
6189
    scroll_ids: &HashMap<LayoutNodeId, u64>,
6189
    gpu_value_cache: Option<&GpuValueCache>,
6189
    renderer_resources: &RendererResources,
6189
    id_namespace: IdNamespace,
6189
    dom_id: DomId,
6189
) -> Result<DisplayList> {
6189
    generate_display_list_impl(
6189
        ctx,
6189
        tree,
6189
        calculated_positions,
6189
        scroll_offsets,
6189
        scroll_ids,
6189
        gpu_value_cache,
6189
        renderer_resources,
6189
        id_namespace,
6189
        dom_id,
6189
        None,
    )
6189
}
/// [`generate_display_list`] + the DL-PATCHING source. With `patch` armed
/// (resize-skip passes), unchanged nodes' paint calls are substituted by
/// their previous items translated by the node's position delta — only
/// re-flowed IFCs and size-changed nodes actually re-emit.
#[allow(clippy::too_many_arguments)]
14796
pub fn generate_display_list_impl<T: ParsedFontTrait + Sync + 'static>(
14796
    ctx: &mut LayoutContext<'_, T>,
14796
    tree: &LayoutTree,
14796
    calculated_positions: &super::PositionVec,
14796
    scroll_offsets: &BTreeMap<NodeId, ScrollPosition>,
14796
    scroll_ids: &HashMap<LayoutNodeId, u64>,
14796
    gpu_value_cache: Option<&GpuValueCache>,
14796
    renderer_resources: &RendererResources,
14796
    id_namespace: IdNamespace,
14796
    dom_id: DomId,
14796
    patch: Option<PatchState<'_>>,
14796
) -> Result<DisplayList> {
14796
    debug_info!(
7138
        ctx,
7138
        "[DisplayList] generate_display_list: tree has {} nodes, {} positions calculated",
7138
        tree.nodes.len(),
7138
        calculated_positions.len()
    );
    // AZ_PROFILE=cpu breakdown of the DL build. Inert (one relaxed load)
    // unless recording is on — see probe::set_recording.
14796
    let _dl_span = crate::probe::Probe::span("dl_generate");
14796
    debug_info!(ctx, "Starting display list generation");
14796
    debug_info!(
7138
        ctx,
7138
        "Collecting stacking contexts from root node {}",
        tree.root
    );
14796
    let positioned_tree = PositionedTree {
14796
        tree,
14796
        calculated_positions,
14796
    };
14796
    let mut generator = DisplayListGenerator::new(
14796
        ctx,
14796
        scroll_offsets,
14796
        &positioned_tree,
14796
        scroll_ids,
14796
        gpu_value_cache,
14796
        renderer_resources,
14796
        id_namespace,
14796
        dom_id,
    );
14796
    generator.patch = patch;
    // Create builder with debug enabled if ctx has debug messages
14796
    let debug_enabled = generator.ctx.debug_messages.is_some();
14796
    let mut builder = DisplayListBuilder::with_debug(debug_enabled);
    // 0. Canvas background propagation (CSS 2.1 § 14.2): "The background of the root element
    //    becomes the background of the canvas." If the root (html) has a transparent background,
    //    propagate from <body>. The canvas background fills the ENTIRE viewport, not just the
    //    root's content box. This is critical when <html> doesn't have height:100% — without this,
    //    the body's background only covers the body's content area, not the viewport.
    {
14796
        let root_node = tree.get(LayoutNodeId::new(tree.root));
14796
        if let Some(root) = root_node {
14796
            if let Some(root_dom_id) = root.dom_node_id {
14796
                let root_state = generator.get_styled_node_state(root_dom_id);
14796
                let canvas_bg =
14796
                    get_background_color(generator.ctx.styled_dom, root_dom_id, &root_state);
14796
                if canvas_bg.a > 0 {
2795
                    let viewport_rect = LogicalRect {
2795
                        origin: LogicalPosition::zero(),
2795
                        size: generator.ctx.viewport_size,
2795
                    };
2795
                    builder.push_rect(viewport_rect, canvas_bg, BorderRadius::default());
2795
                    debug_info!(
290
                        generator.ctx,
290
                        "[DisplayList] Canvas background: color=({},{},{},{}), size={:?}",
                        canvas_bg.r,
                        canvas_bg.g,
                        canvas_bg.b,
                        canvas_bg.a,
                        generator.ctx.viewport_size
                    );
12001
                }
            }
        }
    }
    // +spec:stacking-contexts:33d435 - CSS 2.2 painting order: build stacking context tree then
    // traverse in z-order +spec:stacking-contexts:887766 - CSS2 §9.9 stacking contexts, z-index
    // layering, and painting order
    // 1. Build a tree of stacking contexts, which defines the global paint order.
    // +spec:display-property:9a419c - root element always forms a stacking context (it's the tree
    // root)
14796
    let stacking_context_tree = {
14796
        let _p = crate::probe::Probe::span("dl_collect_stacking");
14796
        generator.collect_stacking_contexts(tree.root)?
    };
    // 2. Traverse the stacking context tree to generate display items in the correct order.
14796
    debug_info!(
7138
        generator.ctx,
7138
        "Generating display items from stacking context tree"
    );
14796
    generator.generate_for_stacking_context(&mut builder, &stacking_context_tree)?;
    // Build display list and transfer debug messages to context
14796
    let display_list = builder.build_with_debug(generator.ctx.debug_messages);
14796
    debug_info!(
7138
        generator.ctx,
7138
        "[DisplayList] Generated {} display items",
7138
        display_list.items.len()
    );
14796
    Ok(display_list)
14796
}
/// A helper struct that holds all necessary state and context for the generation process.
struct DisplayListGenerator<'a, 'b, T: ParsedFontTrait> {
    ctx: &'a mut LayoutContext<'b, T>,
    scroll_offsets: &'a BTreeMap<NodeId, ScrollPosition>,
    positioned_tree: &'a PositionedTree<'a>,
    scroll_ids: &'a HashMap<LayoutNodeId, u64>,
    gpu_value_cache: Option<&'a GpuValueCache>,
    renderer_resources: &'a RendererResources,
    id_namespace: IdNamespace,
    dom_id: DomId,
    /// DL-PATCHING source (resize-skip passes only): the previous pass's
    /// display list plus per-node deltas. `None` = full generation.
    patch: Option<PatchState<'a>>,
}
/// State for patched display-list generation. Built by `layout_document`
/// on a resize-skip pass — the tree object and its indices are unchanged,
/// so per-(layout node, phase) item runs from the PREVIOUS list can replace
/// the paint calls of every node that neither re-flowed its inline content
/// nor changed size; their geometry moves by the node's position delta.
pub(crate) struct PatchState<'a> {
    prev: &'a DisplayList,
    /// Per (layout idx, phase): queue of item ranges in `prev`, walk order.
    runs: HashMap<(usize, u8), std::collections::VecDeque<(usize, usize)>>,
    /// Per layout idx: (`new_pos` - `old_pos`).
    deltas: Vec<LogicalPosition>,
    /// Nodes that MUST re-emit (re-flowed IFC, size changed).
    reemit: std::collections::BTreeSet<usize>,
}
/// Presentation summary of a patched pass: which single translation moved
/// most of the frame, and which rects must be repainted anyway. Feeds the
/// CPU compositor's translate-aware presentation (blit the retained pixmap
/// by `dominant_delta`, repaint `exceptions` + exposed strips) — the round-3
/// path that makes a drag frame memory-bandwidth instead of rendering.
#[derive(Debug, Clone)]
pub struct PatchMoveSummary {
    /// The translation shared by the largest moved item AREA (logical px).
    pub dominant_delta: LogicalPosition,
    /// OLD rects of the dominant movers, one blit each. Per-rect (not a
    /// union): the union would include the gaps BETWEEN movers — static
    /// backdrop that must not be dragged. Only movers that paint an OPAQUE
    /// background over their own rect qualify (a translucent mover's pixels
    /// are a blend with the static backdrop, which does not translate).
    pub mover_rects_old: Vec<LogicalRect>,
    /// Union of `mover_rects_old` — the region the translated DIFF may
    /// classify as moves.
    pub moved_region_old: LogicalRect,
    /// Rects that must repaint regardless: re-emitted nodes, off-delta
    /// movers, non-opaque movers, and NON-ANCESTOR static nodes overlapping
    /// a mover (ancestors paint BELOW their descendants — the root
    /// background under a page is covered by the opaque page and never
    /// dragged visibly; a static sibling painted ABOVE would be) — each as
    /// old∪new bounds.
    pub exceptions: Vec<LogicalRect>,
}
/// Compute a [`PatchMoveSummary`] from the same inputs `PatchState::build`
/// consumes. Returns `None` when the frame has no dominant translation
/// (nothing moved, or the exception list would exceed its cap — at which
/// point a plain full repaint is the better deal).
#[allow(clippy::too_many_lines)]
#[must_use]
224
pub fn compute_patch_move_summary(
224
    prev_positions: &[LogicalPosition],
224
    new_positions: &[LogicalPosition],
224
    prev_sizes: &[Option<LogicalSize>],
224
    new_sizes: &[Option<LogicalSize>],
224
    reemit: &std::collections::BTreeSet<usize>,
224
    // parents[i] = layout parent of node i (ancestor exclusion);
224
    // opaque_bg[i] = node i paints a fully opaque background over its own
224
    // rect (blit eligibility for movers).
224
    parents: &[Option<usize>],
224
    opaque_bg: &[bool],
224
) -> Option<PatchMoveSummary> {
    const EPS: f32 = 0.01;
    const MAX_EXCEPTIONS: usize = 64;
224
    let n = prev_positions
224
        .len()
224
        .min(new_positions.len())
224
        .min(prev_sizes.len())
224
        .min(new_sizes.len());
    // Group movers by exact delta bits, weighted by new area.
224
    let mut groups: HashMap<(u32, u32), f32> = HashMap::new();
1328
    for i in 0..n {
1328
        if reemit.contains(&i) {
677
            continue;
651
        }
651
        let dx = new_positions[i].x - prev_positions[i].x;
651
        let dy = new_positions[i].y - prev_positions[i].y;
651
        if dx.abs() < EPS && dy.abs() < EPS {
649
            continue;
2
        }
2
        let area = new_sizes[i].map_or(1.0, |s| (s.width * s.height).max(1.0));
2
        *groups.entry((dx.to_bits(), dy.to_bits())).or_insert(0.0) += area;
    }
224
    let ((dxb, dyb), _) = groups
224
        .into_iter()
224
        .max_by(|a, b| a.1.partial_cmp(&b.1).unwrap_or(core::cmp::Ordering::Equal))?;
1
    let dominant = LogicalPosition {
1
        x: f32::from_bits(dxb),
1
        y: f32::from_bits(dyb),
1
    };
1
    let rect_of = |pos: LogicalPosition, size: Option<LogicalSize>| -> Option<LogicalRect> {
        let s = size?;
        if s.width <= 0.0 || s.height <= 0.0 || !pos.x.is_finite() || !pos.y.is_finite() {
            return None;
        }
        Some(LogicalRect {
            origin: pos,
            size: s,
        })
    };
1
    let union = |a: Option<LogicalRect>, b: LogicalRect| -> LogicalRect {
        match a {
            None => b,
            Some(a) => {
                let x0 = a.origin.x.min(b.origin.x);
                let y0 = a.origin.y.min(b.origin.y);
                let x1 = (a.origin.x + a.size.width).max(b.origin.x + b.size.width);
                let y1 = (a.origin.y + a.size.height).max(b.origin.y + b.size.height);
                LogicalRect {
                    origin: LogicalPosition { x: x0, y: y0 },
                    size: LogicalSize {
                        width: x1 - x0,
                        height: y1 - y0,
                    },
                }
            }
        }
    };
1
    let intersects = |a: &LogicalRect, b: &LogicalRect| -> bool {
        a.origin.x < b.origin.x + b.size.width
            && b.origin.x < a.origin.x + a.size.width
            && a.origin.y < b.origin.y + b.size.height
            && b.origin.y < a.origin.y + a.size.height
    };
    // Pass 1: dominant movers. Only OPAQUE-background movers may blit;
    // the rest become exceptions in pass 2. Keep only TOP-LEVEL mover
    // rects (drop movers whose ancestor is already a collected mover —
    // the ancestor's blit carries them).
    const MAX_MOVERS: usize = 32;
1
    let mut is_dominant_mover = vec![false; n];
7
    for i in 0..n {
7
        if reemit.contains(&i) {
1
            continue;
6
        }
6
        let dx = new_positions[i].x - prev_positions[i].x;
6
        let dy = new_positions[i].y - prev_positions[i].y;
6
        if (dx - dominant.x).abs() < EPS
6
            && (dy - dominant.y).abs() < EPS
2
            && (dx.abs() >= EPS || dy.abs() >= EPS)
2
        {
2
            is_dominant_mover[i] = true;
4
        }
    }
1
    let covered_by_mover_ancestor = |i: usize| -> bool {
        let mut cur = parents.get(i).copied().flatten();
        while let Some(p) = cur {
            if is_dominant_mover.get(p).copied().unwrap_or(false)
                && opaque_bg.get(p).copied().unwrap_or(false)
            {
                return true;
            }
            cur = parents.get(p).copied().flatten();
        }
        false
    };
1
    let mut mover_rects_old: Vec<LogicalRect> = Vec::new();
1
    let mut moved_region: Option<LogicalRect> = None;
7
    for i in 0..n {
7
        if !is_dominant_mover[i]
2
            || !opaque_bg.get(i).copied().unwrap_or(false)
            || covered_by_mover_ancestor(i)
        {
7
            continue;
        }
        if let Some(r) = rect_of(prev_positions[i], prev_sizes[i]) {
            mover_rects_old.push(r);
            if mover_rects_old.len() > MAX_MOVERS {
                return None; // too many independent blits — full repaint
            }
            moved_region = Some(union(moved_region, r));
        }
    }
1
    let moved_region_old = moved_region?;
    // Descendant-of-blitted-mover test for pass 2: a static (or any) node
    // whose OPAQUE mover ancestor blits is carried by that blit and needs
    // no exception; equally, dominant movers inside a blitted ancestor are
    // fine. Everything else that touches a mover rect must repaint.
    let inside_blit = |i: usize| -> bool {
        is_dominant_mover[i] && opaque_bg.get(i).copied().unwrap_or(false)
            || covered_by_mover_ancestor(i)
    };
    // Pass 2: exceptions — re-emitted nodes, off-delta movers, non-opaque
    // dominant movers outside any blitted ancestor, and NON-ANCESTOR
    // static nodes overlapping a blitted mover. Ancestors of a mover paint
    // BELOW it (covered by the mover's opaque background) — no exception.
    let is_ancestor_of_any_mover = |i: usize| -> bool {
        // ancestor test via the parent chains of the collected movers is
        // O(movers × depth); movers are ≤32 and depth is small.
        for (j, dom) in is_dominant_mover.iter().enumerate() {
            if !dom || !opaque_bg.get(j).copied().unwrap_or(false) {
                continue;
            }
            let mut cur = parents.get(j).copied().flatten();
            while let Some(p) = cur {
                if p == i {
                    return true;
                }
                cur = parents.get(p).copied().flatten();
            }
        }
        false
    };
    let mut exceptions: Vec<LogicalRect> = Vec::new();
    for i in 0..n {
        let dx = new_positions[i].x - prev_positions[i].x;
        let dy = new_positions[i].y - prev_positions[i].y;
        let is_static = dx.abs() < EPS && dy.abs() < EPS;
        let old_r = rect_of(prev_positions[i], prev_sizes[i]);
        let new_r = rect_of(new_positions[i], new_sizes[i]);
        let needs_exception = if reemit.contains(&i) {
            // NOT an exception: a re-emitted node's items genuinely differ
            // (fresh content / new size), so the translated DIFF damages
            // them itself — old∪new bounds — which also repaints over any
            // pixels a blit dragged through them. Listing them here
            // double-covered the damage and, for the size-changed ROOT
            // (width:100% on every resize), turned the whole viewport into
            // an exception — the blit was decorative and the NC could not
            // go red.
            false
        } else if inside_blit(i) {
            false
        } else if is_static {
            // Static content BELOW the movers (their ancestors) is covered
            // by the opaque blits; anything else touching a mover rect
            // would be visibly dragged or stamped over — repaint it.
            !is_ancestor_of_any_mover(i)
                && old_r.is_some_and(|r| mover_rects_old.iter().any(|m| intersects(&r, m)))
        } else {
            true // off-delta mover (or non-opaque dominant outside a blit)
        };
        if needs_exception {
            let mut acc: Option<LogicalRect> = None;
            if let Some(r) = old_r {
                acc = Some(union(acc, r));
            }
            if let Some(r) = new_r {
                acc = Some(union(acc, r));
            }
            if let Some(r) = acc {
                exceptions.push(r);
                if exceptions.len() > MAX_EXCEPTIONS {
                    return None; // too fragmented — full repaint is cheaper
                }
            }
        }
    }
    Some(PatchMoveSummary {
        dominant_delta: dominant,
        mover_rects_old,
        moved_region_old,
        exceptions,
    })
224
}
impl<'a> PatchState<'a> {
224
    pub(crate) fn build(
224
        prev: &'a DisplayList,
224
        prev_positions: &[LogicalPosition],
224
        new_positions: &[LogicalPosition],
224
        prev_sizes: &[Option<LogicalSize>],
224
        new_sizes: &[Option<LogicalSize>],
224
        reflowed_ifcs: &std::collections::BTreeSet<usize>,
224
    ) -> Option<Self> {
        // The tagging is as old as the patcher — a cached list from before
        // the tagging (or a page slice) cannot be patched.
224
        if prev.layout_node_mapping.len() != prev.items.len() {
            return None;
224
        }
224
        let n = new_positions.len().min(prev_positions.len());
224
        let mut reemit: std::collections::BTreeSet<usize> = reflowed_ifcs.clone();
1328
        for i in 0..n.min(prev_sizes.len()).min(new_sizes.len()) {
1328
            if prev_sizes[i] != new_sizes[i] {
501
                reemit.insert(i);
827
            }
        }
224
        let mut deltas = vec![LogicalPosition::zero(); new_positions.len()];
1328
        for i in 0..n {
1328
            deltas[i] = LogicalPosition {
1328
                x: new_positions[i].x - prev_positions[i].x,
1328
                y: new_positions[i].y - prev_positions[i].y,
1328
            };
1328
        }
        // Contiguous same-(node,phase) runs, in list order.
224
        let mut runs: HashMap<(usize, u8), std::collections::VecDeque<(usize, usize)>> =
224
            HashMap::new();
224
        let mut i = 0usize;
1862
        while i < prev.items.len() {
1638
            let tag = prev.layout_node_mapping[i];
1638
            let start = i;
5016
            while i < prev.items.len() && prev.layout_node_mapping[i] == tag {
3378
                i += 1;
3378
            }
1638
            if let Some((node, phase)) = tag {
910
                if !matches!(phase, EmitPhase::ScWalk) {
910
                    if prev.items[start..i].iter().all(patchable_item) {
910
                        runs.entry((node, phase as u8))
910
                            .or_default()
910
                            .push_back((start, i));
910
                    } else {
                        // The run carries state beyond translatable geometry
                        // (virtual view, filter, …) — this node re-emits.
                        reemit.insert(node);
                    }
                }
728
            }
        }
224
        Some(Self {
224
            prev,
224
            runs,
224
            deltas,
224
            reemit,
224
        })
224
    }
}
// +spec:stacking-contexts:9e85a3 - Stacking context tree: hierarchical, nested, atomic painting
// order
/// Represents a node in the CSS stacking context tree, not the DOM tree.
#[derive(Debug)]
struct StackingContext {
    node_index: usize,
    z_index: i32,
    child_contexts: Vec<StackingContext>,
    /// Children that do not create their own stacking contexts and are painted in DOM order.
    in_flow_children: Vec<usize>,
}
impl<'a, 'b, T> DisplayListGenerator<'a, 'b, T>
where
    T: ParsedFontTrait + Sync + 'static,
{
14796
    pub(crate) const fn new(
14796
        ctx: &'a mut LayoutContext<'b, T>,
14796
        scroll_offsets: &'a BTreeMap<NodeId, ScrollPosition>,
14796
        positioned_tree: &'a PositionedTree<'a>,
14796
        scroll_ids: &'a HashMap<LayoutNodeId, u64>,
14796
        gpu_value_cache: Option<&'a GpuValueCache>,
14796
        renderer_resources: &'a RendererResources,
14796
        id_namespace: IdNamespace,
14796
        dom_id: DomId,
14796
    ) -> Self {
14796
        Self {
14796
            ctx,
14796
            scroll_offsets,
14796
            positioned_tree,
14796
            scroll_ids,
14796
            gpu_value_cache,
14796
            renderer_resources,
14796
            id_namespace,
14796
            dom_id,
14796
            patch: None,
14796
        }
14796
    }
    /// Prove the SOLID OPAQUE color a text run inside this IFC sits on, or
    /// `None`. Correct-by-construction: only claims a background when the
    /// nearest layout ancestor that paints ANY background paints exactly one
    /// solid opaque color (no gradients/images, no translucency) and no
    /// selection touches the node (selection rects paint between background
    /// and glyphs). No claim for canvas-direct text — the clear color is a
    /// renderer detail (`AZ_DEBUG_FILL` can change it).
317291
    fn compute_uniform_text_bg(
317291
        &self,
317291
        source_node_index: usize,
317291
    ) -> Option<(ColorU, WindowLogicalRect)> {
317291
        let tree = self.positioned_tree.tree;
317291
        let dom_id_opt = tree
317291
            .get(LayoutNodeId::new(source_node_index))
317291
            .and_then(|n| n.dom_node_id);
2105
        if let (Some(sel), Some(dom_id)) = (
317291
            self.ctx.text_selections.get(&self.ctx.styled_dom.dom_id),
317291
            dom_id_opt,
        ) {
2105
            if sel.affected_nodes.contains_key(&dom_id) {
974
                return None;
1131
            }
315186
        }
316317
        let mut cur = Some(source_node_index);
756122
        while let Some(idx) = cur {
730009
            if let Some(dom_id) = tree.get(LayoutNodeId::new(idx)).and_then(|n| n.dom_node_id) {
729842
                let state = self.get_styled_node_state(dom_id);
729842
                let contents = get_background_contents(self.ctx.styled_dom, dom_id, &state);
729842
                let mut saw_any = false;
742312
                for c in &contents {
                    use azul_css::props::style::StyleBackgroundContent as B;
12470
                    match c {
302487
                        B::Color(col) if col.a == 255 => {
                            // The PROOF's extent: this node's painted rect.
                            // The LCD fringe of a glyph at the very edge of
                            // it spills onto UNPROVEN pixels — the raster
                            // must sweep those glyphs (a pre-blended tile
                            // stamped across the boundary bakes the wrong
                            // neighbour into the fringe; caught by the
                            // round-3 blit gate as an 8-pixel divergence at
                            // the page edge).
290017
                            let rect = self.get_paint_rect(idx)?;
290017
                            return Some((*col, rect.into()));
                        }
12470
                        B::Color(col) if col.a == 0 => {}
                        // translucent color, gradient or image — unprovable
187
                        _ => return None,
                    }
12470
                    saw_any = true;
                }
439638
                let _ = saw_any;
167
            }
439805
            cur = tree.get(LayoutNodeId::new(idx)).and_then(|n| n.parent);
        }
26113
        None
317291
    }
    /// DL-PATCHING substitution: if a patch source is armed and this node's
    /// (phase) run can be reused, copy it translated by the node's position
    /// delta and report `true` (the caller skips painting). `false` = paint
    /// normally (no patch, node in the re-emit set, or no cached run left —
    /// the last one falls back to a fresh paint, which is always correct).
1524888
    fn try_copy_cached_run(
1524888
        &mut self,
1524888
        builder: &mut DisplayListBuilder,
1524888
        node_index: usize,
1524888
        phase: EmitPhase,
1524888
    ) -> bool {
1524888
        let Some(patch) = self.patch.as_mut() else {
1522192
            return false;
        };
2696
        if patch.reemit.contains(&node_index) {
1354
            return false;
1342
        }
1342
        let Some(run) = patch
1342
            .runs
1342
            .get_mut(&(node_index, phase as u8))
1342
            .and_then(std::collections::VecDeque::pop_front)
        else {
            // No cached run for this call. For a node that emitted nothing
            // last pass this is the COMMON case — and emitting nothing again
            // is exactly right, so treat it as a successful (empty) copy.
            // A node that DID emit but whose run count changed cannot occur
            // without a reflow/size change (both force re-emit).
1046
            drop(crate::probe::Probe::span("dl_patch_empty"));
1046
            return true;
        };
296
        let delta = patch
296
            .deltas
296
            .get(node_index)
296
            .copied()
296
            .unwrap_or_else(LogicalPosition::zero);
296
        drop(crate::probe::Probe::span("dl_patch_copy"));
        // DOM attribution is PER ITEM, not per run: a content run can switch
        // attribution mid-run (e.g. an IFC root's items ending with a text
        // child's id) — the golden test caught a first-item flattening here.
296
        let saved_node = builder.current_node;
296
        builder.set_current_layout(Some((node_index, phase)));
538
        for i in run.0..run.1 {
538
            builder.set_current_node(patch.prev.node_mapping.get(i).copied().flatten());
538
            builder.next_text_bg = patch.prev.uniform_text_bgs.get(i).copied().flatten();
538
            builder.next_text_selection_colors =
538
                patch.prev.text_selection_colors.get(i).copied().flatten();
538
            let item = translate_item(patch.prev.items[i].clone(), delta);
538
            builder.push_item(item);
538
        }
296
        builder.set_current_layout(None);
296
        builder.set_current_node(saved_node);
296
        true
1524888
    }
    /// Helper to get styled node state for a node
7783887
    fn get_styled_node_state(&self, dom_id: NodeId) -> azul_core::styled_dom::StyledNodeState {
7783887
        self.ctx
7783887
            .styled_dom
7783887
            .styled_nodes
7783887
            .as_container()
7783887
            .get(dom_id)
7783887
            .map(|n| n.styled_node_state)
7783887
            .unwrap_or_default()
7783887
    }
    // +spec:overflow:visibility - CSS 2.2 §11.2: visibility:hidden makes the box invisible
    // but still affects layout. Checked per-node because visibility is inherited and a child
    // with visibility:visible inside a hidden parent must still be painted.
2300890
    fn is_node_hidden(&self, node_index: usize) -> bool {
        use azul_css::props::style::effects::StyleVisibility;
2300890
        let Some(node) = self.positioned_tree.tree.get(LayoutNodeId::new(node_index)) else {
            return false;
        };
2300890
        let Some(dom_id) = node.dom_node_id else {
483
            return false;
        };
2300407
        let node_state = self.get_styled_node_state(dom_id);
2300407
        matches!(
2300407
            get_visibility(self.ctx.styled_dom, dom_id, &node_state),
            crate::solver3::getters::MultiValue::Exact(
                StyleVisibility::Hidden | StyleVisibility::Collapse
            )
        )
2300890
    }
    /// Gets the cursor type for a text node from its CSS properties.
    /// Defaults to Text (I-beam) cursor if no explicit cursor is set.
    #[allow(clippy::match_same_arms)] // enum/value mapping/dispatch table: one arm per input
                                      // variant (or cross-type bindings that can't merge)
578526
    fn get_cursor_type_for_text_node(&self, node_id: NodeId) -> CursorType {
        use azul_css::props::style::effects::StyleCursor;
578526
        let styled_node_state = self.get_styled_node_state(node_id);
578526
        let node_data_container = self.ctx.styled_dom.node_data.as_container();
578526
        let node_data = node_data_container.get(node_id);
        // Query the cursor CSS property for this text node
578526
        if let Some(node_data) = node_data {
578526
            if let Some(CssPropertyValue::Exact(cursor)) = self
578526
                .ctx
578526
                .styled_dom
578526
                .get_css_property_cache()
578526
                .get_cursor(node_data, &node_id, &styled_node_state)
            {
578486
                return match cursor {
23830
                    StyleCursor::Default => CursorType::Default,
10533
                    StyleCursor::Pointer => CursorType::Pointer,
544123
                    StyleCursor::Text => CursorType::Text,
                    StyleCursor::Crosshair => CursorType::Crosshair,
                    StyleCursor::Move => CursorType::Move,
                    StyleCursor::Help => CursorType::Help,
                    StyleCursor::Wait => CursorType::Wait,
                    StyleCursor::Progress => CursorType::Progress,
                    StyleCursor::NsResize => CursorType::NsResize,
                    StyleCursor::EwResize => CursorType::EwResize,
                    StyleCursor::NeswResize => CursorType::NeswResize,
                    StyleCursor::NwseResize => CursorType::NwseResize,
                    StyleCursor::NResize => CursorType::NResize,
                    StyleCursor::SResize => CursorType::SResize,
                    StyleCursor::EResize => CursorType::EResize,
                    StyleCursor::WResize => CursorType::WResize,
                    StyleCursor::Grab => CursorType::Grab,
                    StyleCursor::Grabbing => CursorType::Grabbing,
                    StyleCursor::RowResize => CursorType::RowResize,
                    StyleCursor::ColResize => CursorType::ColResize,
                    // Map less common cursors to closest available
                    StyleCursor::SeResize | StyleCursor::NeswResize => CursorType::NeswResize,
                    StyleCursor::ZoomIn | StyleCursor::ZoomOut => CursorType::Default,
                    StyleCursor::Copy | StyleCursor::Alias => CursorType::Default,
                    StyleCursor::Cell => CursorType::Crosshair,
                    StyleCursor::AllScroll => CursorType::Move,
                    StyleCursor::ContextMenu => CursorType::Default,
                    StyleCursor::VerticalText => CursorType::Text,
                    StyleCursor::Unset => CursorType::Text, // Default to text for text nodes
                };
40
            }
        }
        // Default: Text cursor (I-beam) for text nodes
40
        CursorType::Text
578526
    }
    /// Emits drawing commands for text selections only (not cursor).
    /// The cursor is drawn separately via `paint_cursor()`.
762444
    fn paint_selections(&self, builder: &mut DisplayListBuilder, node_index: usize) -> Result<()> {
762444
        let node = self
762444
            .positioned_tree
762444
            .tree
762444
            .get(LayoutNodeId::new(node_index))
762444
            .ok_or(LayoutError::InvalidTree)?;
762444
        let Some(dom_id) = node.dom_node_id else {
161
            return Ok(());
        };
        // Get inline layout using the unified helper that handles IFC membership
        // This is critical: text nodes don't have their own inline_layout_result,
        // but they have ifc_membership pointing to their IFC root
        // (d6h) Materialized: sentinel-safe caret/selection geometry.
762283
        let Some(layout) = self
762283
            .positioned_tree
762283
            .tree
762283
            .materialized_inline_layout_for_node(node_index)
        else {
445121
            return Ok(());
        };
        // Get the absolute position of this node (border-box position)
317162
        let node_pos = self
317162
            .positioned_tree
317162
            .calculated_positions
317162
            .get(node_index)
317162
            .copied()
317162
            .unwrap_or_default();
        // Selection rects from `get_selection_rects` are in the IFC root's content-box
        // coordinate space. For an inline text node, the node's OWN box position is never
        // assigned (stays the `f32::MIN` sentinel), so we must anchor to the IFC root's
        // position + padding/border — exactly the box that owns the inline layout. (The
        // caret avoids this because paint_cursor runs on the IFC-root node directly.)
317162
        let anchor = self.ifc_content_box_origin(node_index, node_pos);
317162
        let content_box_offset_x = anchor.x;
317162
        let content_box_offset_y = anchor.y;
        // Check if text is selectable (respects CSS user-select property)
317162
        let node_state = &self.ctx.styled_dom.styled_nodes.as_container()[dom_id].styled_node_state;
317162
        let is_selectable =
317162
            super::getters::is_text_selectable(self.ctx.styled_dom, dom_id, node_state);
317162
        if !is_selectable {
40489
            return Ok(());
276673
        }
        // === NEW: Check text_selections first (multi-node selection support) ===
276673
        if let Some(text_selection) = self.ctx.text_selections.get(&self.ctx.styled_dom.dom_id) {
2105
            let local_ranges = text_selection.affected_nodes.get(&dom_id);
            // Remote / seat ranges are keyed by the node the caret sits in,
            // which may be a text CHILD of this IFC root rather than the root
            // itself (a seat's caret lives in the text node, 9b-ii-a-i-d-ii-a)
            // - the same ownership rule the caret path applies below.
2105
            let remote_ranges: Vec<&(
2105
                azul_core::selection::SelectionOwner,
2105
                azul_core::selection::SelectionRange,
2105
            )> = text_selection
2105
                .remote_ranges
2105
                .iter()
2105
                .filter(|(node, _)| {
80
                    **node == dom_id || self.ifc_root_owns_dom_node(node_index, **node)
80
                })
2105
                .flat_map(|(_, ranges)| ranges.iter())
2105
                .collect();
2105
            if local_ranges.is_some() || !remote_ranges.is_empty() {
1014
                let style = get_selection_style(
1014
                    self.ctx.styled_dom,
1014
                    Some(dom_id),
1014
                    self.ctx.system_style.as_ref(),
                );
1014
                let border_radius = BorderRadius {
1014
                    top_left: style.radius,
1014
                    top_right: style.radius,
1014
                    bottom_left: style.radius,
1014
                    bottom_right: style.radius,
1014
                };
                // REMOTE FIRST, so a local selection over the same span stays
                // legible on top of it.
                //
                // Deliberately NOT gated on `is_collapsed`: that flag
                // describes the LOCAL session's anchor and focus, and says
                // nothing about whether another participant has a range. A
                // local caret sitting in a field must not erase everybody
                // else's highlight.
1054
                for (owner, range) in remote_ranges {
40
                    let color = match self.ctx.owner_colors.get(owner) {
40
                        Some(c) => remote_selection_tint(*c),
                        // An owner the app never registered a colour for. It
                        // still gets painted - a range nobody can see is
                        // indistinguishable from a bug - just in the node's
                        // own `::selection` colour.
                        None => style.bg_color,
                    };
40
                    for mut rect in layout.get_selection_rects(range) {
40
                        rect.origin.x += content_box_offset_x;
40
                        rect.origin.y += content_box_offset_y;
40
                        builder.push_selection_rect(rect, color, border_radius);
40
                    }
                }
1014
                if let Some(ranges) = local_ranges {
                    // Only draw selection highlight if NOT collapsed
974
                    if !text_selection.is_collapsed() {
                        // A multi-cursor session (Ctrl+D) puts EVERY occurrence
                        // on this one node, so every range gets its own rects.
974
                        let rects: Vec<LogicalRect> = ranges
974
                            .iter()
984
                            .flat_map(|range| layout.get_selection_rects(range))
974
                            .collect();
1958
                        for mut rect in rects {
984
                            rect.origin.x += content_box_offset_x;
984
                            rect.origin.y += content_box_offset_y;
984
                            builder.push_selection_rect(rect, style.bg_color, border_radius);
984
                        }
                        // THE HANDLES (U2-a): one teardrop under each end of
                        // the PRIMARY range - the one `anchor`/`focus` name,
                        // which is the one the platform seams and the handle
                        // drag address. Painted after the highlight so they
                        // sit on top of it. Only where the platform lends a
                        // custom view no handles of its own.
974
                        if self.ctx.paint_selection_handles {
130
                            paint_selection_handles(
130
                                builder,
130
                                &layout,
130
                                text_selection,
130
                                content_box_offset_x,
130
                                content_box_offset_y,
130
                                style.bg_color,
130
                            );
844
                        }
                    }
40
                }
1014
                return Ok(());
1091
            }
274568
        }
275659
        Ok(())
762444
    }
    /// Selection rects covering this IFC, already translated into the same
    /// space as the offset glyph positions, plus the `::selection` text colour
    /// — or `None` when there is nothing to recolour.
    ///
    /// Resolves the selection through `ifc_root_owns_dom_node` rather than off
    /// the IFC root's own `dom_node_id`: an editing session keys `affected_nodes`
    /// on the TEXT node (`initialize_editing` puts the caret there), while this
    /// pass runs on the root that owns the inline layout. A cross-block
    /// selection keys on the block, which is its own IFC root — both resolve.
    /// The `user-select` gate matches `paint_selections` on purpose: the
    /// recolour must cover exactly the glyphs the highlight covers.
    /// The origin of the content box that owns an IFC's inline layout.
    ///
    /// Selection rects come out of `get_selection_rects` in this space. An
    /// inline text node's own box position is never assigned (it keeps the
    /// `f32::MIN` sentinel), so the anchor has to be the IFC ROOT's box — which
    /// is why both the highlight and the recolour resolve it here rather than
    /// each computing its own.
317372
    fn ifc_content_box_origin(
317372
        &self,
317372
        node_index: usize,
317372
        fallback: LogicalPosition,
317372
    ) -> LogicalPosition {
317372
        let ifc_root_index = self
317372
            .positioned_tree
317372
            .tree
317372
            .get_ifc_root_layout_index(node_index);
317372
        let pos = self
317372
            .positioned_tree
317372
            .calculated_positions
317372
            .get(ifc_root_index)
317372
            .copied()
317372
            .unwrap_or(fallback);
317372
        let bp = self
317372
            .positioned_tree
317372
            .tree
317372
            .get(LayoutNodeId::new(ifc_root_index))
317372
            .map(|n| n.box_props.unpack());
317372
        let (pad_left, pad_top, bor_left, bor_top) = bp.map_or((0.0, 0.0, 0.0, 0.0), |b| {
317372
            (b.padding.left, b.padding.top, b.border.left, b.border.top)
317372
        });
317372
        LogicalPosition::new(pos.x + pad_left + bor_left, pos.y + pad_top + bor_top)
317372
    }
317291
    fn selection_recolour_for_ifc(
317291
        &self,
317291
        source_node_index: usize,
317291
    ) -> Option<(Vec<LogicalRect>, ColorU)> {
317291
        let sel = self.ctx.text_selections.get(&self.ctx.styled_dom.dom_id)?;
2105
        if sel.is_collapsed() {
80
            return None;
2025
        }
2025
        let (dom_id, ranges) = sel
2025
            .affected_nodes
2025
            .iter()
11317
            .find(|&(node, _)| self.ifc_root_owns_dom_node(source_node_index, *node))?;
974
        let node_state = self.get_styled_node_state(*dom_id);
974
        if !super::getters::is_text_selectable(self.ctx.styled_dom, *dom_id, &node_state) {
            return None;
974
        }
974
        let style = get_selection_style(
974
            self.ctx.styled_dom,
974
            Some(*dom_id),
974
            self.ctx.system_style.as_ref(),
        );
974
        let text_color = style.text_color?;
        // The SAME geometry the highlight is painted from: the sentinel-safe
        // materialized layout, anchored on the IFC root's content box. Reading
        // the raw cached layout here yielded no rects at all, so the recolour
        // silently never applied.
210
        let layout = self
210
            .positioned_tree
210
            .tree
210
            .materialized_inline_layout_for_node(source_node_index)?;
210
        let node_pos = self
210
            .positioned_tree
210
            .calculated_positions
210
            .get(source_node_index)
210
            .copied()
210
            .unwrap_or_default();
210
        let anchor = self.ifc_content_box_origin(source_node_index, node_pos);
210
        let rects: Vec<LogicalRect> = ranges
210
            .iter()
210
            .flat_map(|r| layout.get_selection_rects(r))
210
            .map(|mut r| {
210
                r.origin.x += anchor.x;
210
                r.origin.y += anchor.y;
210
                r
210
            })
210
            .collect();
210
        if rects.is_empty() {
            return None;
210
        }
210
        Some((rects, text_color))
317291
    }
    /// Does the IFC rooted at `node_index` own the inline content of `dom_id`?
    ///
    /// The editing session's text node need not be a DIRECT child of the IFC
    /// root — `p > span > text` puts it one level deeper — so resolve it through
    /// `ifc_membership`, which every inline descendant of the root carries,
    /// instead of scanning the root's children.
22861
    fn ifc_root_owns_dom_node(&self, node_index: usize, dom_id: NodeId) -> bool {
22861
        let tree = self.positioned_tree.tree;
22861
        if let Some(indices) = tree.dom_to_layout.get(&dom_id) {
22841
            return indices
22841
                .iter()
22841
                .any(|&idx| tree.get_ifc_root_layout_index(idx.index()) == node_index);
20
        }
        // The node generated NO box of its own — an EMPTY text node is
        // filtered out of the layout tree — so it belongs to the IFC of the
        // nearest DOM ancestor that did generate one. This is the focused
        // empty editable: the caret session sits on the value's empty text
        // node, and the strut line box lives on its `<p>`.
20
        let hierarchy = self.ctx.styled_dom.node_hierarchy.as_container();
20
        let mut current = hierarchy
20
            .get(dom_id)
20
            .and_then(azul_core::styled_dom::NodeHierarchyItem::parent_id);
20
        while let Some(parent) = current {
            if let Some(indices) = tree.dom_to_layout.get(&parent) {
                return indices.iter().any(|&idx| {
                    idx.index() == node_index
                        || tree.get_ifc_root_layout_index(idx.index()) == node_index
                });
            }
            current = hierarchy
                .get(parent)
                .and_then(azul_core::styled_dom::NodeHierarchyItem::parent_id);
        }
20
        false
22861
    }
    /// Emits drawing commands for all text cursors (carets).
    ///
    /// Iterates over `ctx.cursor_locations` to support multi-cursor rendering.
    /// An editable with NO text gets the strut caret of
    /// [`empty_editable_caret_rect`].
    /// Preedit underline is only rendered for the primary (last) cursor.
    #[allow(clippy::cast_precision_loss)] // bounded graphics/coord/font/fixed-point/debug-marker
                                          // cast
762444
    fn paint_cursor(&self, builder: &mut DisplayListBuilder, node_index: usize) -> Result<()> {
        // NOTE: we deliberately do NOT early-return in the blink-off phase. Emitting the
        // caret item every frame — with alpha forced to 0 when invisible (see caret_color
        // below) — keeps the display-list item COUNT stable across blink phases, so
        // compute_display_list_damage yields a tiny caret-sized damage rect instead of
        // bailing to a full-window repaint on every ~530ms blink toggle.
        // Early exit if no cursor locations
762444
        if self.ctx.cursor_locations.is_empty() {
253981
            return Ok(());
508463
        }
508463
        let node = self
508463
            .positioned_tree
508463
            .tree
508463
            .get(LayoutNodeId::new(node_index))
508463
            .ok_or(LayoutError::InvalidTree)?;
508463
        let Some(dom_id) = node.dom_node_id else {
10
            return Ok(());
        };
        // Check if this node is contenteditable
508453
        let is_contenteditable =
508453
            super::getters::is_node_contenteditable_inherited(self.ctx.styled_dom, dom_id);
508453
        if !is_contenteditable {
491983
            return Ok(());
16470
        }
        // Check if text is selectable
16470
        let node_state = &self.ctx.styled_dom.styled_nodes.as_container()[dom_id].styled_node_state;
16470
        let is_selectable =
16470
            super::getters::is_text_selectable(self.ctx.styled_dom, dom_id, node_state);
16470
        if !is_selectable {
            return Ok(());
16470
        }
        // Get inline layout
        // (d6h) Materialized: sentinel-safe caret/selection geometry.
16470
        let Some(layout) = self
16470
            .positioned_tree
16470
            .tree
16470
            .materialized_inline_layout_for_node(node_index)
        else {
9188
            return Ok(());
        };
        // Compute content-box offset once
7282
        let node_pos = self
7282
            .positioned_tree
7282
            .calculated_positions
7282
            .get(node_index)
7282
            .copied()
7282
            .unwrap_or_default();
7282
        let bp = node.box_props.unpack();
7282
        let padding = &bp.padding;
7282
        let border = &bp.border;
7282
        let content_box_offset_x = node_pos.x + padding.left + border.left;
7282
        let content_box_offset_y = node_pos.y + padding.top + border.top;
7282
        let style = get_caret_style(self.ctx.styled_dom, Some(dom_id));
        // Find the index of the last (primary) cursor that belongs to this DOM/node,
        // so preedit underline is only drawn on the actual primary cursor.
7282
        let primary_idx_for_this_node = self
7282
            .ctx
7282
            .cursor_locations
7282
            .iter()
7282
            .enumerate()
7282
            .rev()
7432
            .find(|(_, loc)| {
7432
                loc.dom == self.ctx.styled_dom.dom_id
7432
                    && (loc.node == dom_id || self.ifc_root_owns_dom_node(node_index, loc.node))
7432
            })
7282
            .map(|(i, _)| i);
7582
        for (i, location) in self.ctx.cursor_locations.iter().enumerate() {
7582
            let cursor = &location.cursor;
            // Check DOM ID matches
7582
            if self.ctx.styled_dom.dom_id != location.dom {
                continue;
7582
            }
            // Check this node contains the cursor
7582
            if dom_id != location.node && !self.ifc_root_owns_dom_node(node_index, location.node) {
2764
                continue;
4818
            }
            // Get cursor rect from text layout — or, for an EMPTY editable,
            // the strut caret. `get_cursor_rect` anchors the caret to a
            // cluster, and an editable with no text has none, so nothing was
            // painted: a focused, empty TextInput showed no caret at all
            // (and, with the placeholder hidden on focus, nothing else
            // either — the field looked dead). The first character will
            // create a line box at the content-box origin one line-height
            // tall; the caret stands where that line will be.
4818
            let rect = match layout.get_cursor_rect(cursor) {
4788
                Some(rect) => rect,
30
                None if layout.items.is_empty() => {
30
                    let font_size = super::getters::get_element_font_size(
30
                        self.ctx.styled_dom,
30
                        dom_id,
30
                        node_state,
                    );
30
                    let line_height = super::getters::get_line_height_value(
30
                        self.ctx.styled_dom,
30
                        dom_id,
30
                        node_state,
                    )
30
                    .map_or(1.2, |lh| lh.inner.normalized());
30
                    empty_editable_caret_rect(font_size, line_height)
                }
                None => continue,
            };
4818
            let mut rect = rect;
4818
            rect.origin.x += content_box_offset_x;
4818
            rect.origin.y += content_box_offset_y;
4818
            rect.size.width = style.width;
            // Blink: keep the caret item present every frame (stable item count for
            // incremental damage) but make it invisible in the off phase by zeroing alpha.
            // PER-PARTICIPANT COLOUR (U1). A shared editing session paints
            // each person's caret in their own colour; `caret-color` answers
            // "what colour is the caret in this field", which is a different
            // question and cannot name a person. An owner the app has not
            // registered - the local caret included - falls back to the CSS
            // value, so a single-user app is unaffected.
4818
            let owner_color = self
4818
                .ctx
4818
                .owner_colors
4818
                .get(&location.owner)
4818
                .copied()
4818
                .unwrap_or(style.color);
4818
            let caret_color = if self.ctx.cursor_is_visible {
4547
                owner_color
            } else {
271
                ColorU {
271
                    a: 0,
271
                    ..owner_color
271
                }
            };
4818
            builder.push_cursor_rect(rect, caret_color);
            // Preedit underline only on the primary cursor for this node
4818
            let is_primary = primary_idx_for_this_node == Some(i);
            // The primary's composition comes from the context; a seat's
            // travels with its location (9b-ii-a-i-d-ii-c).
            // (`is_primary` is "the last location on this node", which a
            // seat's can be when the primary edits elsewhere - only a LOCAL
            // location carries the primary's composition.)
4818
            let composing: Option<(u32, f32)> = if is_primary && location.owner.is_local() {
4598
                self.ctx
4598
                    .preedit_text
4598
                    .as_ref()
4598
                    .filter(|p| !p.is_empty())
4598
                    .map(|p| (p.len() as u32, p.chars().count() as f32))
220
            } else if location.preedit_bytes > 0 {
40
                Some((location.preedit_bytes, location.preedit_chars as f32))
            } else {
180
                None
            };
            {
4818
                if let Some((preedit_bytes, preedit_chars)) = composing {
                    {
                        // The composition IS in this layout: apply_preedit_to_
                        // text_cache splices it into the run at the cursor's
                        // byte offset and re-shapes, so the underline can span
                        // the MEASURED advance of the composed clusters. The
                        // old `char_count × max(caret_width, 8px)` guess was
                        // wrong for every script whose advances aren't ~8px —
                        // a CJK cluster is roughly double that.
280
                        let run = cursor.cluster_id.source_run;
280
                        let start_byte = cursor.cluster_id.start_byte_in_run;
280
                        let end_byte = start_byte.saturating_add(preedit_bytes);
                        // (line_index, min_x, max_x) of the composed clusters.
                        // Clusters on a later line belong to a composition that
                        // wrapped; they would need their own rect, so the span
                        // stays on the line the caret sits on.
280
                        let mut span: Option<(usize, f32, f32)> = None;
1140
                        for item in &layout.items {
1140
                            let Some(cluster) = item.item.as_cluster() else {
                                continue;
                            };
1140
                            let id = cluster.source_cluster_id;
1140
                            if id.source_run != run
1140
                                || id.start_byte_in_run < start_byte
920
                                || id.start_byte_in_run >= end_byte
                            {
660
                                continue;
480
                            }
480
                            let edge = item.position.x + cluster.advance;
480
                            let (lo, hi) = (item.position.x.min(edge), item.position.x.max(edge));
240
                            span = Some(match span {
240
                                Some((line, min_x, max_x)) if line == item.line_index => {
240
                                    (line, min_x.min(lo), max_x.max(hi))
                                }
                                Some(other_line) => other_line,
240
                                None => (item.line_index, lo, hi),
                            });
                        }
280
                        let (underline_x, preedit_width) = if let Some((_, lo, hi)) = span {
240
                            (lo + content_box_offset_x, hi - lo)
                        } else {
                            // Composition not (yet) in the cache — keep the
                            // old estimate rather than drawing nothing.
40
                            let char_count = preedit_chars;
40
                            (
40
                                rect.origin.x + rect.size.width,
40
                                char_count * style.width.max(8.0),
40
                            )
                        };
280
                        let underline_bounds = LogicalRect {
280
                            origin: LogicalPosition {
280
                                x: underline_x,
280
                                y: rect.origin.y + rect.size.height - 2.0,
280
                            },
280
                            size: LogicalSize {
280
                                width: preedit_width,
280
                                height: 2.0,
280
                            },
280
                        };
280
                        builder.push_underline(underline_bounds, style.color, 2.0);
                    }
4538
                }
            }
        }
7282
        Ok(())
762444
    }
    /// Emits drawing commands for selection and cursor.
    /// Delegates to `paint_selections()` and `paint_cursor()`.
    /// Recursively builds the tree of stacking contexts starting from a given layout node.
    // +spec:writing-modes:a86a28 - preorder depth-first traversal of the rendering tree in logical
    // order
14900
    fn collect_stacking_contexts(&mut self, node_index: usize) -> Result<StackingContext> {
14900
        let node = self
14900
            .positioned_tree
14900
            .tree
14900
            .get(LayoutNodeId::new(node_index))
14900
            .ok_or(LayoutError::InvalidTree)?;
14900
        let z_index = get_z_index(self.ctx.styled_dom, node.dom_node_id);
14900
        if let Some(dom_id) = node.dom_node_id {
14900
            let node_type = &self.ctx.styled_dom.node_data.as_container()[dom_id];
14900
            debug_info!(
7161
                self.ctx,
7161
                "Collecting stacking context for node {} ({:?}), z-index={}",
                node_index,
7161
                node_type.get_node_type(),
                z_index
            );
        }
14900
        let mut child_contexts = Vec::new();
14900
        let mut in_flow_children = Vec::new();
262927
        for &child_index in self.positioned_tree.tree.children(node_index) {
262927
            if self.establishes_stacking_context(child_index) {
20
                child_contexts.push(self.collect_stacking_contexts(child_index)?);
            } else {
262907
                in_flow_children.push(child_index);
                // Recurse into non-stacking-context children to find nested
                // stacking contexts. Per CSS 2.2 Appendix E, these are promoted
                // to be child stacking contexts of the nearest ancestor SC.
262907
                self.find_nested_stacking_contexts(child_index, &mut child_contexts)?;
            }
        }
14900
        Ok(StackingContext {
14900
            node_index,
14900
            z_index,
14900
            child_contexts,
14900
            in_flow_children,
14900
        })
14900
    }
    /// Recursively searches non-stacking-context subtrees for nested stacking
    /// contexts, promoting them to the parent stacking context's child list.
747544
    fn find_nested_stacking_contexts(
747544
        &mut self,
747544
        parent_index: usize,
747544
        child_contexts: &mut Vec<StackingContext>,
747544
    ) -> Result<()> {
747544
        for &child_index in self.positioned_tree.tree.children(parent_index) {
484721
            if self.establishes_stacking_context(child_index) {
84
                child_contexts.push(self.collect_stacking_contexts(child_index)?);
            } else {
484637
                self.find_nested_stacking_contexts(child_index, child_contexts)?;
            }
        }
747544
        Ok(())
747544
    }
    // +spec:box-model:de94ab - stacking context painting order (negative z, in-flow, z=0, positive
    // z) +spec:display-property:337069 - CSS 2.2 E.2 painting order: stacking contexts sorted
    // by z-index, in-flow children in tree order +spec:display-property:7b0a87 - CSS 2.2 E.2
    // painting order: negative z-index, in-flow, z-index 0/auto, positive z-index
    // +spec:stacking-contexts:5cbdfb - full CSS painting order (bg, neg-z, in-flow, z0, pos-z)
    // +spec:stacking-contexts:3ded3a - CSS 2.2 Appendix E painting order: definitions and tree
    // order traversal +spec:stacking-contexts:973368 - CSS 2.2 Appendix E.2 painting order:
    // bg/border, negative z, in-flow, zero z, positive z +spec:stacking-contexts:464bb7 - CSS
    // 2.2 §9.9.1 painting order: negative z-index, in-flow, z-index 0, positive z-index (recursive)
    /// Recursively traverses the stacking context tree, emitting drawing commands to the builder
    /// according to the CSS Painting Algorithm specification.
    // +spec:display-property:39e879 - CSS 2.2 E.2 painting order for block-level and inline-level
    // elements +spec:display-property:de4c66 - CSS 2.2 E.2 stacking context paint order (canvas
    // bg, negative z, in-flow, floats, inline, positive z) +spec:overflow:6e48b4 - CSS 2.2
    // Appendix E painting order: bg/border, negative z-index, in-flow, floats, z-index 0/auto,
    // positive z-index +spec:stacking-contexts:55ca96 - CSS 2.2 E.2 painting order:
    // backgrounds, negative z-index, in-flow, z-index 0/auto, positive z-index
    #[allow(clippy::too_many_lines, clippy::cognitive_complexity)] // large but cohesive:
                                                                   // single-purpose
                                                                   // layout/render/parse routine
                                                                   // (one branch per case)
14900
    fn generate_for_stacking_context(
14900
        &mut self,
14900
        builder: &mut DisplayListBuilder,
14900
        context: &StackingContext,
14900
    ) -> Result<()> {
        // Before painting the node, check if it establishes a new clip or scroll frame.
14900
        let node = self
14900
            .positioned_tree
14900
            .tree
14900
            .get(LayoutNodeId::new(context.node_index))
14900
            .ok_or(LayoutError::InvalidTree)?;
14900
        if let Some(dom_id) = node.dom_node_id {
14900
            let node_type = &self.ctx.styled_dom.node_data.as_container()[dom_id];
14900
            debug_info!(
7161
                self.ctx,
7161
                "Painting stacking context for node {} ({:?}), z-index={}, {} child contexts, {} \
7161
                 in-flow children",
                context.node_index,
7161
                node_type.get_node_type(),
                context.z_index,
7161
                context.child_contexts.len(),
7161
                context.in_flow_children.len()
            );
        }
        // Set current node BEFORE pushing stacking context so that
        // the PushStackingContext item gets the correct node_mapping entry.
        // This is critical for drag visual offset matching.
14900
        builder.set_current_node(node.dom_node_id);
        // Track fixed-position elements for paged media replication (CSS Positioned Layout §2.1)
14900
        let is_fixed_position = node.dom_node_id.is_some_and(|dom_id| {
14900
            get_position_type(self.ctx.styled_dom, Some(dom_id)) == LayoutPosition::Fixed
14900
        });
14900
        if is_fixed_position {
            builder.begin_fixed_position_element();
14900
        }
        // Check if this node has a GPU-accelerated transform (CSS transform or drag).
        // If so, wrap in a reference frame so WebRender can animate it on the GPU.
14900
        let has_reference_frame = node.dom_node_id.and_then(|dom_id| {
14900
            self.gpu_value_cache.and_then(|cache| {
                // CSS transform first, then the ANIMATION channel. An
                // engine-driven transition animates nodes that have no CSS
                // `transform` of their own, so without this second lookup they
                // get no reference frame and the element jumps to its
                // destination instead of travelling there.
14024
                let (key, transform) = cache
14024
                    .css_transform_keys
14024
                    .get(&dom_id)
14024
                    .zip(cache.css_current_transform_values.get(&dom_id))
14024
                    .or_else(|| {
14003
                        cache
14003
                            .anim_transform_keys
14003
                            .get(&dom_id)
14003
                            .zip(cache.anim_current_transform_values.get(&dom_id))
14003
                    })?;
21
                Some((*key, *transform))
14024
            })
14900
        });
        // Push a stacking context for WebRender
        // Get the node's bounds for the stacking context
14900
        let node_pos = self
14900
            .positioned_tree
14900
            .calculated_positions
14900
            .get(context.node_index)
14900
            .copied()
14900
            .unwrap_or_default();
14900
        let node_size = node.used_size.unwrap_or(LogicalSize {
14900
            width: 0.0,
14900
            height: 0.0,
14900
        });
14900
        let node_bounds = LogicalRect {
14900
            origin: node_pos,
14900
            size: node_size,
14900
        };
        // Push reference frame BEFORE stacking context if node has a transform
14900
        if let Some((transform_key, initial_transform)) = has_reference_frame {
21
            builder.push_reference_frame(transform_key, initial_transform, node_bounds);
14879
        }
14900
        builder.push_stacking_context(context.z_index, node_bounds);
        // Push opacity/filter effects if the node has them
14900
        let mut pushed_opacity = false;
14900
        let mut pushed_filter = false;
14900
        let mut pushed_backdrop_filter = false;
14900
        if let Some(dom_id) = node.dom_node_id {
14900
            let node_data = &self.ctx.styled_dom.node_data.as_container()[dom_id];
14900
            let node_state =
14900
                &self.ctx.styled_dom.styled_nodes.as_container()[dom_id].styled_node_state;
            // Opacity (GPU: fast path via compact cache)
14900
            let opacity =
14900
                crate::solver3::getters::get_opacity(self.ctx.styled_dom, dom_id, node_state);
            // ANIMATED opacity binds a key from the animation channel — the
            // exact twin of `has_reference_frame` for transforms: the list
            // carries the key, the value flows per tick through the GPU cache,
            // and an enter/exit fade needs a layer even while the BAKED CSS
            // opacity is 1.0.
14900
            let anim_opacity_key = self.gpu_value_cache.and_then(|cache| {
14024
                cache
14024
                    .anim_opacity_keys
14024
                    .get(&dom_id)
14024
                    .zip(cache.anim_current_opacity_values.get(&dom_id))
14024
                    .map(|(k, _)| *k)
14024
            });
14900
            if opacity < 1.0 || anim_opacity_key.is_some() {
103
                builder.push_item(DisplayListItem::PushOpacity {
103
                    bounds: node_bounds.into(),
103
                    opacity,
103
                    opacity_key: anim_opacity_key,
103
                });
103
                pushed_opacity = true;
14797
            }
            // Filter
14900
            if let Some(filter_vec_value) = self
14900
                .ctx
14900
                .styled_dom
14900
                .css_property_cache
14900
                .ptr
14900
                .get_filter(node_data, &dom_id, node_state)
            {
                if let Some(filter_vec) = filter_vec_value.get_property() {
                    let filters: Vec<_> = filter_vec.as_ref().to_vec();
                    if !filters.is_empty() {
                        builder.push_item(DisplayListItem::PushFilter {
                            bounds: node_bounds.into(),
                            filters,
                        });
                        pushed_filter = true;
                    }
                }
14900
            }
            // Backdrop filter
14900
            if let Some(backdrop_filter_value) = self
14900
                .ctx
14900
                .styled_dom
14900
                .css_property_cache
14900
                .ptr
14900
                .get_backdrop_filter(node_data, &dom_id, node_state)
            {
                if let Some(filter_vec) = backdrop_filter_value.get_property() {
                    let filters: Vec<_> = filter_vec.as_ref().to_vec();
                    if !filters.is_empty() {
                        builder.push_item(DisplayListItem::PushBackdropFilter {
                            bounds: node_bounds.into(),
                            filters,
                        });
                        pushed_backdrop_filter = true;
                    }
                }
14900
            }
        }
        // 0b. Push image mask clip if this node has one.
        // This wraps background, border, and all children so the SVG mask clips everything.
14900
        let did_push_image_mask = self.push_image_mask_clip(builder, context.node_index);
        // +spec:box-model:84b238 - CSS 2.2 E.2 painting order: bg/border, negative z, in-flow, z=0,
        // positive z
        // 1. Paint background and borders for the context's root element.
        // This must be BEFORE push_node_clips so the container background
        // is rendered in parent space (stationary), not scroll space.
        // +spec:overflow:40052b - backgrounds paint at border-box, scrollbars overlay on top
        // (scrollbar-extended background positioning area)
14900
        self.paint_node_background_and_border(builder, context.node_index)?;
        // 1b. For scrollable containers, push the hit-test area BEFORE the scroll frame
        // so the hit-test covers the entire container box (including visible area),
        // not just the scrolled content. This ensures scroll wheel events hit the
        // container regardless of scroll position.
        // +spec:overflow:visibility - visibility:hidden scroll containers must not allow
        // interactive scrolling per CSS 2.2 §11.2
14900
        if !self.is_node_hidden(context.node_index) {
14900
            if let Some(dom_id) = node.dom_node_id {
14900
                let styled_node_state = self.get_styled_node_state(dom_id);
14900
                let overflow_x = get_overflow_x(self.ctx.styled_dom, dom_id, &styled_node_state);
14900
                let overflow_y = get_overflow_y(self.ctx.styled_dom, dom_id, &styled_node_state);
14900
                if overflow_x.is_scroll() || overflow_y.is_scroll() {
170
                    if let Some(tag_id) = get_tag_id(self.ctx.styled_dom, node.dom_node_id) {
170
                        builder.push_hit_test_area(node_bounds, tag_id);
170
                    }
14730
                }
            }
        }
        // 2. Push clips and scroll frames AFTER painting background
        // +spec:positioning:ddc554 - overflow clips apply to absolutely positioned descendants
        // when this node is their containing block (stacking contexts painted within clip scope)
        // TODO: CSS Overflow 3 says overflow clips should NOT apply to abs-pos descendants
        // whose containing block is above this clipper. Currently all descendants are clipped.
        // The containing_block_index field on LayoutNode is set for this purpose.
14900
        let did_push_clip_or_scroll = self.push_node_clips(builder, context.node_index, node);
        // +spec:display-contents:434de8 - E.2 painting order: negative z-index, in-flow, z-index
        // 0/auto, positive z-index
        // 3. Paint child stacking contexts with negative z-indices.
14900
        let mut negative_z_children: Vec<_> = context
14900
            .child_contexts
14900
            .iter()
14900
            .filter(|c| c.z_index < 0)
14900
            .collect();
14900
        negative_z_children.sort_by_key(|c| c.z_index);
14900
        for child in negative_z_children {
            self.generate_for_stacking_context(builder, child)?;
        }
        // 4. Paint the in-flow descendants of the context root.
14900
        self.paint_in_flow_descendants(builder, context.node_index, &context.in_flow_children)?;
        // +spec:stacking-contexts:9a4eb3 - z-index:auto/0 positioned descendants painted in tree
        // order
        // 5. Paint child stacking contexts with z-index: 0 / auto.
14900
        for child in context.child_contexts.iter().filter(|c| c.z_index == 0) {
104
            self.generate_for_stacking_context(builder, child)?;
        }
        // +spec:stacking-contexts:198fa4 - positive z-index stacking contexts painted in z-index
        // order then tree order
        // 6. Paint child stacking contexts with positive z-indices.
14900
        let mut positive_z_children: Vec<_> = context
14900
            .child_contexts
14900
            .iter()
14900
            .filter(|c| c.z_index > 0)
14900
            .collect();
14900
        positive_z_children.sort_by_key(|c| c.z_index);
14900
        for child in positive_z_children {
            self.generate_for_stacking_context(builder, child)?;
        }
        // Pop image mask clip (before filter/opacity since it was pushed after them)
14900
        if did_push_image_mask {
50
            builder.pop_image_mask_clip();
14850
        }
        // The stroke follows the geometry, not the fill region - it must be
        // outside the mask the fill was painted through.
14900
        self.paint_svg_stroke(builder, context.node_index);
        // Pop filter/opacity effects (in reverse order of push)
14900
        if pushed_backdrop_filter {
            builder.push_item(DisplayListItem::PopBackdropFilter);
14900
        }
14900
        if pushed_filter {
            builder.push_item(DisplayListItem::PopFilter);
14900
        }
14900
        if pushed_opacity {
103
            builder.push_item(DisplayListItem::PopOpacity);
14797
        }
        // Pop the stacking context for WebRender
14900
        builder.pop_stacking_context();
        // Pop reference frame if we pushed one
14900
        if has_reference_frame.is_some() {
21
            builder.pop_reference_frame();
14879
        }
        // End fixed-position tracking (records the item range for paged media replication)
14900
        if is_fixed_position {
            builder.end_fixed_position_element();
14900
        }
        // After painting the node and all its descendants, pop any contexts it pushed.
        // For VirtualView nodes, emit the placeholder INSIDE the clip (before PopClip)
        // so the virtualized view viewport is clipped to the container.
14900
        if did_push_clip_or_scroll {
            // Emit VirtualViewPlaceholder before popping the clip so it's inside PushClip/PopClip
250
            if let Some(dom_id) = node.dom_node_id {
250
                if self.is_virtual_view_node(dom_id) {
                    builder.push_virtual_view_placeholder(dom_id, node_bounds, node_bounds);
250
                }
            }
250
            self.pop_node_clips(builder, node);
        } else {
            // Even without clips, emit VirtualViewPlaceholder for VirtualView nodes
14650
            if let Some(dom_id) = node.dom_node_id {
14650
                if self.is_virtual_view_node(dom_id) {
                    builder.push_virtual_view_placeholder(dom_id, node_bounds, node_bounds);
14650
                }
            }
        }
        // Paint scrollbars AFTER popping the clip, so they appear on top of content
        // and are not clipped by the scroll frame
14900
        self.paint_scrollbars(builder, context.node_index)?;
14900
        Ok(())
14900
    }
    /// Paints the content and non-stacking-context children.
    #[allow(clippy::too_many_lines, clippy::cognitive_complexity)] // large but cohesive:
                                                                   // single-purpose
                                                                   // layout/render/parse routine
                                                                   // (one branch per case)
762444
    fn paint_in_flow_descendants(
762444
        &mut self,
762444
        builder: &mut DisplayListBuilder,
762444
        node_index: usize,
762444
        children_indices: &[usize],
762444
    ) -> Result<()> {
        // NOTE: We do NOT paint the node's background here - that was already done by
        // generate_for_stacking_context! Only paint selection, cursor, and content for the
        // current node
        // 2. Selection highlights go UNDER the content...
762444
        self.paint_selections(builder, node_index)?;
        // 3. Paint the node's own content (text, images, hit-test areas).
762444
        self.paint_node_content(builder, node_index)?;
        // 4. ...and the caret goes OVER it. Emitted before the text, the
        // caret was erased wherever an LCD glyph tile (an opaque pre-blended
        // copy, glyph box + FIR pad) landed on it - the caret segment inside
        // the last typed glyph's box vanished (2026-08-31).
762444
        self.paint_cursor(builder, node_index)?;
        // +spec:display-property:86a3de - inline-level boxes painted in document order; z-index
        // does not apply +spec:floats:b8c494 - E.2 painting order: non-positioned floats
        // painted after block-level descendants, in tree order
        // 4. Recursively paint the in-flow children in correct CSS painting order:
        //    - First: Non-float, non-dragging block-level children
        //    - Then: Float, non-dragging children (so they appear on top)
        //    - Finally: Dragging children (so they appear on top of everything per W3C spec)
        // Separate children into floats, non-floats, and dragging.
        // Skip children that establish stacking contexts - those are painted
        // separately via generate_for_stacking_context with proper z-ordering.
762444
        let mut non_float_children = Vec::new();
762444
        let mut float_children = Vec::new();
762444
        let mut dragging_children = Vec::new();
1510072
        for &child_index in children_indices {
            // Skip stacking context children - they're painted by the stacking
            // context tree traversal, not by the in-flow descendant path.
747628
            if self.establishes_stacking_context(child_index) {
84
                continue;
747544
            }
747544
            let child_node = self
747544
                .positioned_tree
747544
                .tree
747544
                .get(LayoutNodeId::new(child_index))
747544
                .ok_or(LayoutError::InvalidTree)?;
            // Check if this child is being dragged (paint last for z-order)
747544
            let is_dragging = child_node.dom_node_id.is_some_and(|dom_id| {
747383
                let styled_node_state = self.get_styled_node_state(dom_id);
747383
                styled_node_state.dragging
747383
            });
747544
            if is_dragging {
                dragging_children.push(child_index);
                continue;
747544
            }
            // Check if this child is a float
747544
            let is_float = if let Some(dom_id) = child_node.dom_node_id {
                use crate::solver3::getters::get_float;
747383
                let styled_node_state = self.get_styled_node_state(dom_id);
747383
                let float_value = get_float(self.ctx.styled_dom, dom_id, &styled_node_state);
52
                !matches!(
747383
                    float_value.unwrap_or_default(),
                    azul_css::props::layout::LayoutFloat::None
                )
            } else {
161
                false
            };
747544
            if is_float {
52
                float_children.push(child_index);
747492
            } else {
747492
                non_float_children.push(child_index);
747492
            }
        }
        // Paint non-float children first
1509936
        for child_index in non_float_children {
747492
            let child_node = self
747492
                .positioned_tree
747492
                .tree
747492
                .get(LayoutNodeId::new(child_index))
747492
                .ok_or(LayoutError::InvalidTree)?;
            // Check if this child has a GPU transform (CSS transform or drag)
747492
            let child_ref_frame = child_node.dom_node_id.and_then(|dom_id| {
747331
                self.gpu_value_cache.and_then(|cache| {
                    // CSS transform first, then the ANIMATION channel — an
                    // engine-driven transition animates nodes that have no CSS
                    // `transform` of their own, and without this they get no
                    // reference frame and jump to their destination.
742128
                    let (key, transform) = cache
742128
                        .css_transform_keys
742128
                        .get(&dom_id)
742128
                        .zip(cache.css_current_transform_values.get(&dom_id))
742128
                        .or_else(|| {
742128
                            cache
742128
                                .anim_transform_keys
742128
                                .get(&dom_id)
742128
                                .zip(cache.anim_current_transform_values.get(&dom_id))
742128
                        })?;
73
                    Some((*key, *transform))
742128
                })
747331
            });
            // Push reference frame if child has a transform
747492
            if let Some((transform_key, initial_transform)) = child_ref_frame {
73
                let child_pos = self
73
                    .positioned_tree
73
                    .calculated_positions
73
                    .get(child_index)
73
                    .copied()
73
                    .unwrap_or_default();
73
                let child_size = child_node.used_size.unwrap_or(LogicalSize {
73
                    width: 0.0,
73
                    height: 0.0,
73
                });
73
                let child_bounds = LogicalRect {
73
                    origin: child_pos,
73
                    size: child_size,
73
                };
73
                builder.set_current_node(child_node.dom_node_id);
73
                builder.push_reference_frame(transform_key, initial_transform, child_bounds);
747419
            }
            // Push image mask clip if this child has one (wraps background + children)
747492
            let did_push_child_image_mask = self.push_image_mask_clip(builder, child_index);
            // IMPORTANT: Paint background and border BEFORE pushing clips!
            // This ensures the container's background is in parent space (stationary),
            // not in scroll space. Same logic as generate_for_stacking_context.
747492
            self.paint_node_background_and_border(builder, child_index)?;
            // Push clips and scroll frames AFTER painting background
747492
            let did_push_clip = self.push_node_clips(builder, child_index, child_node);
            // Paint descendants inside the clip/scroll frame
747492
            self.paint_in_flow_descendants(
747492
                builder,
747492
                child_index,
747492
                self.positioned_tree.tree.children(child_index),
            )?;
            // For VirtualView children: emit placeholder INSIDE the clip
747492
            if let Some(dom_id) = child_node.dom_node_id {
747331
                if self.is_virtual_view_node(dom_id) {
1186
                    let child_bounds = self.get_paint_rect(child_index).unwrap_or_default();
1186
                    builder.push_virtual_view_placeholder(dom_id, child_bounds, child_bounds);
746145
                }
161
            }
            // Pop the child's clips.
747492
            if did_push_clip {
7982
                self.pop_node_clips(builder, child_node);
739510
            }
            // Pop image mask clip
747492
            if did_push_child_image_mask {
130
                builder.pop_image_mask_clip();
747362
            }
            // The stroke follows the geometry, not the fill region - it must
            // be outside the mask the fill was painted through.
747492
            self.paint_svg_stroke(builder, child_index);
            // Paint scrollbars AFTER popping clips so they appear on top of content
747492
            self.paint_scrollbars(builder, child_index)?;
            // Pop reference frame if we pushed one
747492
            if child_ref_frame.is_some() {
73
                builder.pop_reference_frame();
747419
            }
        }
        // +spec:positioning:1bcbb5 - floats rendered in front of non-positioned in-flow blocks, but
        // behind in-flow inlines Paint float children AFTER non-floats (so they appear on
        // top)
762496
        for child_index in float_children {
52
            let child_node = self
52
                .positioned_tree
52
                .tree
52
                .get(LayoutNodeId::new(child_index))
52
                .ok_or(LayoutError::InvalidTree)?;
            // Check if this child has a GPU transform (CSS transform or drag)
52
            let child_ref_frame = child_node.dom_node_id.and_then(|dom_id| {
52
                self.gpu_value_cache.and_then(|cache| {
                    // CSS transform first, then the ANIMATION channel — an
                    // engine-driven transition animates nodes that have no CSS
                    // `transform` of their own, and without this they get no
                    // reference frame and jump to their destination.
                    let (key, transform) = cache
                        .css_transform_keys
                        .get(&dom_id)
                        .zip(cache.css_current_transform_values.get(&dom_id))
                        .or_else(|| {
                            cache
                                .anim_transform_keys
                                .get(&dom_id)
                                .zip(cache.anim_current_transform_values.get(&dom_id))
                        })?;
                    Some((*key, *transform))
                })
52
            });
            // Push reference frame if child has a transform
52
            if let Some((transform_key, initial_transform)) = child_ref_frame {
                let child_pos = self
                    .positioned_tree
                    .calculated_positions
                    .get(child_index)
                    .copied()
                    .unwrap_or_default();
                let child_size = child_node.used_size.unwrap_or(LogicalSize {
                    width: 0.0,
                    height: 0.0,
                });
                let child_bounds = LogicalRect {
                    origin: child_pos,
                    size: child_size,
                };
                builder.set_current_node(child_node.dom_node_id);
                builder.push_reference_frame(transform_key, initial_transform, child_bounds);
52
            }
            // Same as above: push image mask, paint background, then clips
52
            let did_push_child_image_mask = self.push_image_mask_clip(builder, child_index);
52
            self.paint_node_background_and_border(builder, child_index)?;
52
            let did_push_clip = self.push_node_clips(builder, child_index, child_node);
52
            self.paint_in_flow_descendants(
52
                builder,
52
                child_index,
52
                self.positioned_tree.tree.children(child_index),
            )?;
            // For VirtualView children: emit placeholder INSIDE the clip
52
            if let Some(dom_id) = child_node.dom_node_id {
52
                if self.is_virtual_view_node(dom_id) {
                    let child_bounds = self.get_paint_rect(child_index).unwrap_or_default();
                    builder.push_virtual_view_placeholder(dom_id, child_bounds, child_bounds);
52
                }
            }
52
            if did_push_clip {
                self.pop_node_clips(builder, child_node);
52
            }
52
            if did_push_child_image_mask {
                builder.pop_image_mask_clip();
52
            }
            // The stroke follows the geometry, not the fill region - it must
            // be outside the mask the fill was painted through.
52
            self.paint_svg_stroke(builder, child_index);
            // Paint scrollbars AFTER popping clips so they appear on top of content
52
            self.paint_scrollbars(builder, child_index)?;
            // Pop reference frame if we pushed one
52
            if child_ref_frame.is_some() {
                builder.pop_reference_frame();
52
            }
        }
        // Paint dragging children LAST so they appear on top of everything (W3C spec)
762444
        for child_index in dragging_children {
            let child_node = self
                .positioned_tree
                .tree
                .get(LayoutNodeId::new(child_index))
                .ok_or(LayoutError::InvalidTree)?;
            // Check if this child has a GPU transform (CSS transform or drag)
            let child_ref_frame = child_node.dom_node_id.and_then(|dom_id| {
                self.gpu_value_cache.and_then(|cache| {
                    // CSS transform first, then the ANIMATION channel — an
                    // engine-driven transition animates nodes that have no CSS
                    // `transform` of their own, and without this they get no
                    // reference frame and jump to their destination.
                    let (key, transform) = cache
                        .css_transform_keys
                        .get(&dom_id)
                        .zip(cache.css_current_transform_values.get(&dom_id))
                        .or_else(|| {
                            cache
                                .anim_transform_keys
                                .get(&dom_id)
                                .zip(cache.anim_current_transform_values.get(&dom_id))
                        })?;
                    Some((*key, *transform))
                })
            });
            // Push reference frame if child has a transform
            if let Some((transform_key, initial_transform)) = child_ref_frame {
                let child_pos = self
                    .positioned_tree
                    .calculated_positions
                    .get(child_index)
                    .copied()
                    .unwrap_or_default();
                let child_size = child_node.used_size.unwrap_or(LogicalSize {
                    width: 0.0,
                    height: 0.0,
                });
                let child_bounds = LogicalRect {
                    origin: child_pos,
                    size: child_size,
                };
                builder.set_current_node(child_node.dom_node_id);
                builder.push_reference_frame(transform_key, initial_transform, child_bounds);
            }
            // Same as above: push image mask, paint background, then clips
            let did_push_child_image_mask = self.push_image_mask_clip(builder, child_index);
            self.paint_node_background_and_border(builder, child_index)?;
            let did_push_clip = self.push_node_clips(builder, child_index, child_node);
            self.paint_in_flow_descendants(
                builder,
                child_index,
                self.positioned_tree.tree.children(child_index),
            )?;
            // For VirtualView children: emit placeholder INSIDE the clip
            if let Some(dom_id) = child_node.dom_node_id {
                if self.is_virtual_view_node(dom_id) {
                    let child_bounds = self.get_paint_rect(child_index).unwrap_or_default();
                    builder.push_virtual_view_placeholder(dom_id, child_bounds, child_bounds);
                }
            }
            if did_push_clip {
                self.pop_node_clips(builder, child_node);
            }
            if did_push_child_image_mask {
                builder.pop_image_mask_clip();
            }
            // The stroke follows the geometry, not the fill region - it must
            // be outside the mask the fill was painted through.
            self.paint_svg_stroke(builder, child_index);
            // Paint scrollbars AFTER popping clips so they appear on top of content
            self.paint_scrollbars(builder, child_index)?;
            // Pop reference frame if we pushed one
            if child_ref_frame.is_some() {
                builder.pop_reference_frame();
            }
        }
762444
        Ok(())
762444
    }
    /// Returns true if the given DOM node is a `VirtualView` node.
778747
    fn is_virtual_view_node(&self, dom_id: NodeId) -> bool {
778747
        let node_data_container = self.ctx.styled_dom.node_data.as_container();
778747
        node_data_container
778747
            .get(dom_id)
778747
            .is_some_and(|nd| matches!(nd.get_node_type(), NodeType::VirtualView))
778747
    }
    /// Checks if a node has an image mask clip and pushes `PushImageMaskClip` if so.
    /// Returns true if a clip was pushed (caller must pop it).
    /// Paint this node's SVG stroke, if it has one.
    ///
    /// Called AFTER the node's own image-mask clip is popped, and that is the
    /// whole point: the mask is the shape's FILL region, and in SVG (and in
    /// PDF) a stroke is not clipped by the fill. An open path - a line, an
    /// arc, a chevron - encloses no area at all, so its fill mask is empty and
    /// a stroke drawn inside it disappears completely. That is exactly how a
    /// 4px rule rendered as nothing.
762444
    fn paint_svg_stroke(&self, builder: &mut DisplayListBuilder, node_index: usize) {
762444
        let Some(node) = self.positioned_tree.tree.get(LayoutNodeId::new(node_index)) else {
            return;
        };
762444
        let Some(dom_id) = node.dom_node_id else {
161
            return;
        };
762283
        let styled_node_state = self.get_styled_node_state(dom_id);
762283
        let border_info = get_border_info(self.ctx.styled_dom, dom_id, &styled_node_state);
762283
        let Some((path, color, width)) = self.svg_stroke_for(dom_id, &border_info) else {
762253
            return;
        };
30
        let Some(paint_rect) = self.get_paint_rect(node_index) else {
            return;
        };
30
        let view_box = self.enclosing_view_box(dom_id);
        #[cfg(feature = "cpurender")]
30
        let mask = rasterize_svg_stroke_to_r8(&path, &paint_rect, view_box, width);
        #[cfg(not(feature = "cpurender"))]
        let mask = None;
30
        builder.push_item(DisplayListItem::StrokedPath {
30
            bounds: paint_rect.into(),
30
            path,
30
            view_box,
30
            color,
30
            width,
30
            mask,
30
        });
762444
    }
    /// This node's STROKE, if it has geometry and a border to stroke it with.
    ///
    /// `stroke`/`stroke-width` are accepted spellings of
    /// `border-color`/`border-width`, so they arrive through the ordinary
    /// cascade and land in `border_info` - one width and one colour are read
    /// back out here (SVG has a single stroke, not four sides; the top slot is
    /// the one the shorthand fills).
1192804
    fn svg_stroke_for(
1192804
        &self,
1192804
        dom_id: NodeId,
1192804
        border_info: &BorderInfo,
1192804
    ) -> Option<(azul_core::svg::SvgMultiPolygon, ColorU, f32)> {
1192804
        let node_data = self.ctx.styled_dom.node_data.as_container();
1192804
        let azul_core::dom::SvgNodeData::Path(path) = node_data.get(dom_id)?.get_svg_data()? else {
130
            return None;
        };
360
        let width = border_info
360
            .widths
360
            .top
360
            .and_then(CssPropertyValue::get_property_owned)
360
            .map(|w| w.inner.to_pixels_internal(0.0, 16.0, 16.0))?;
360
        if !width.is_finite() || width <= 0.0 {
300
            return None;
60
        }
60
        let color = border_info
60
            .colors
60
            .top
60
            .and_then(CssPropertyValue::get_property_owned)
60
            .map(|c| c.inner)?;
60
        if color.a == 0 {
            return None;
60
        }
60
        Some((path.clone(), color, width))
1192804
    }
    /// The `viewBox` of the nearest `<svg>` ancestor of `node` (itself
    /// included), as `(min_x, min_y, width, height)`.
    ///
    /// An SVG shape's geometry is in its `<svg>`'s USER SPACE, and the element
    /// it paints into is sized in CSS px; this is the only place that knows
    /// both. Bounded by the tree depth, and `None` for a clip-path on an
    /// ordinary element - which has no user space and whose geometry is
    /// already window-logical.
210
    fn enclosing_view_box(&self, node: NodeId) -> Option<(f32, f32, f32, f32)> {
210
        let node_data = self.ctx.styled_dom.node_data.as_container();
210
        let hierarchy = self.ctx.styled_dom.node_hierarchy.as_container();
210
        let mut cursor = Some(node);
420
        while let Some(id) = cursor {
            if let Some(azul_core::dom::SvgNodeData::ViewBox {
160
                min_x,
160
                min_y,
160
                width,
160
                height,
370
            }) = node_data
370
                .get(id)
370
                .and_then(azul_core::dom::NodeData::get_svg_data)
            {
160
                return Some((*min_x, *min_y, *width, *height));
210
            }
210
            cursor = hierarchy
210
                .get(id)
210
                .and_then(azul_core::styled_dom::NodeHierarchyItem::parent_id);
        }
50
        None
210
    }
762444
    fn push_image_mask_clip(&self, builder: &mut DisplayListBuilder, node_index: usize) -> bool {
762444
        let Some(node) = self.positioned_tree.tree.get(LayoutNodeId::new(node_index)) else {
            return false;
        };
762444
        let Some(dom_id) = node.dom_node_id else {
161
            return false;
        };
762283
        let node_data_container = self.ctx.styled_dom.node_data.as_container();
762283
        let Some(node_data) = node_data_container.get(dom_id) else {
            return false;
        };
762283
        match node_data.get_svg_data() {
            Some(azul_core::dom::SvgNodeData::ImageClipMask(clip_mask)) => {
                let paint_rect = self.get_paint_rect(node_index).unwrap_or_default();
                // Convert mask rect from element-local to window-logical coordinates
                let mask_rect = LogicalRect {
                    origin: LogicalPosition {
                        x: paint_rect.origin.x + clip_mask.rect.origin.x,
                        y: paint_rect.origin.y + clip_mask.rect.origin.y,
                    },
                    size: clip_mask.rect.size,
                };
                builder.push_image_mask_clip(paint_rect, clip_mask.image.clone(), mask_rect);
                true
            }
            #[cfg(feature = "cpurender")]
180
            Some(azul_core::dom::SvgNodeData::Path(svg_clip)) => {
180
                let paint_rect = self.get_paint_rect(node_index).unwrap_or_default();
                // The coordinate system the geometry was authored in: the
                // nearest `<svg>` ancestor's viewBox. Without it a shape drawn
                // at 16 units paints a sixteenth of a 256px slot.
180
                let view_box = self.enclosing_view_box(dom_id);
180
                rasterize_svg_clip_to_r8(svg_clip, &paint_rect, view_box).is_some_and(
180
                    |mask_image| {
180
                        builder.push_image_mask_clip(paint_rect, mask_image, paint_rect);
180
                        true
180
                    },
                )
            }
            #[cfg(not(feature = "cpurender"))]
            Some(azul_core::dom::SvgNodeData::Path(_)) => {
                // The DOM asked for an SVG clip mask; without `cpurender` the
                // clip silently does not clip. Say so once.
                static ANNOUNCE: std::sync::Once = std::sync::Once::new();
                ANNOUNCE.call_once(|| {
                    eprintln!(
                        "[azul][svg] an SVG clip-path is present, but this build has no \
                         `cpurender` feature — SVG clips will NOT clip"
                    );
                });
                false
            }
            // Other SvgNodeData variants (shapes, gradients, etc.) don't produce clip masks
130
            Some(_) => false,
761973
            None => false,
        }
762444
    }
    // +spec:overflow:531bd2 - ancestor clips accumulate via push_clip/pop_clip stack (cumulative
    // intersection) +spec:overflow:8098ec - overflow clipping/scrolling; abs-pos elements with
    // containing block outside scroller are not scrolled
    /// Checks if a node requires clipping or scrolling and pushes the appropriate commands.
    /// Returns true if any command was pushed.
    ///
    /// // +spec:containing-block:62aa5c - overflow clipping applies to all content except
    /// // descendants whose containing block is the viewport or an ancestor of this element
    /// // (i.e. absolutely positioned elements that escape the overflow container).
    /// // TODO: exempt abs-pos descendants whose containing block is an ancestor of this node.
    ///
    /// For `VirtualView` nodes with `overflow: scroll/auto`, we intentionally skip
    /// `PushScrollFrame` / `PopScrollFrame`. `VirtualView` scroll state is managed by
    /// `ScrollManager`, not `WebRender`'s APZ. Instead we emit only a `PushClip`
    /// and later an `VirtualViewPlaceholder` (see `generate_for_stacking_context`).
    #[allow(clippy::similar_names)] // domain-standard coordinate/geometry/short-lived names
762444
    fn push_node_clips(
762444
        &self,
762444
        builder: &mut DisplayListBuilder,
762444
        node_index: usize,
762444
        node: &LayoutNodeHot,
762444
    ) -> bool {
762444
        let Some(dom_id) = node.dom_node_id else {
161
            return false;
        };
762283
        let styled_node_state = self.get_styled_node_state(dom_id);
762283
        let raw_overflow_x = get_overflow_x(self.ctx.styled_dom, dom_id, &styled_node_state);
762283
        let raw_overflow_y = get_overflow_y(self.ctx.styled_dom, dom_id, &styled_node_state);
        // +spec:overflow:833078 - resolve visible/clip to auto/hidden per CSS Overflow 3 §3.1
762283
        let overflow_x = raw_overflow_x.resolve_computed(&raw_overflow_y);
762283
        let overflow_y = raw_overflow_y.resolve_computed(&raw_overflow_x);
762283
        let paint_rect = self.get_paint_rect(node_index).unwrap_or_default();
762283
        let element_size = PhysicalSizeImport {
762283
            width: paint_rect.size.width,
762283
            height: paint_rect.size.height,
762283
        };
762283
        let border_radius = get_border_radius(
762283
            self.ctx.styled_dom,
762283
            dom_id,
762283
            &styled_node_state,
762283
            element_size,
762283
            self.ctx.viewport_size,
        );
        // +spec:positioning:9c261b - clip-path (modern replacement for legacy 'clip' property)
        // The legacy CSS 2.2 'clip' property applied only to absolutely positioned elements;
        // clip-path supersedes it and applies to all elements per CSS Masking Level 1.
        // If present, push a clip region derived from the clip-path shape.
        // This is evaluated before overflow clips; both can be active simultaneously.
762283
        let has_clip_path =
762283
            super::getters::get_clip_path(self.ctx.styled_dom, dom_id, &styled_node_state)
762283
                .is_some_and(|clip_path| {
                    if let Some((clip_rect, radius)) = resolve_clip_path(&clip_path, paint_rect) {
                        let br = if radius > 0.0 {
                            BorderRadius {
                                top_left: radius,
                                top_right: radius,
                                bottom_left: radius,
                                bottom_right: radius,
                            }
                        } else {
                            BorderRadius::default()
                        };
                        builder.push_clip(clip_rect, br);
                        true
                    } else {
                        false
                    }
                });
        // +spec:overflow:6890f2 - text-overflow: clip inline content at end line box edge when
        // overflow != visible +spec:overflow:77d7ce - clipping region defines visible
        // portion of border box; default is not clipped
762283
        let needs_clip = overflow_x.is_clipped() || overflow_y.is_clipped();
762283
        if !needs_clip {
754051
            return has_clip_path;
8232
        }
        // +spec:overflow:c52f2a - clipping region is rounded to element's border-radius
        // +spec:overflow:913b23 - when both axes are clip, region is rounded per
        // overflow-clip-margin +spec:overflow:449d69 - when one axis is clip and the other
        // is visible, clipping region is not rounded +spec:overflow:449d69 - when one axis
        // is clip and the other is visible, clipping region is not rounded
8232
        let ox_clip =
8232
            overflow_x.is_clipped() && !overflow_x.is_scroll() && !overflow_x.is_auto_overflow();
8232
        let oy_clip =
8232
            overflow_y.is_clipped() && !overflow_y.is_scroll() && !overflow_y.is_auto_overflow();
8232
        let ox_visible = !overflow_x.is_clipped();
8232
        let oy_visible = !overflow_y.is_clipped();
8232
        let border_radius = if (ox_clip && oy_visible) || (oy_clip && ox_visible) {
            BorderRadius::default()
        } else {
8232
            border_radius
        };
8232
        let paint_rect = self.get_paint_rect(node_index).unwrap_or_default();
8232
        let bp = node.box_props.unpack();
8232
        let border = &bp.border;
        // Get scrollbar info to adjust clip rect for content area
8232
        let scrollbar_info = self
8232
            .positioned_tree
8232
            .tree
8232
            .warm(LayoutNodeId::new(node_index))
8232
            .and_then(|w| w.scrollbar_info)
8232
            .unwrap_or_default();
        // +spec:overflow:13cacb - clip rect clamped to 0 so zero-size clips hide all pixels
        // +spec:overflow:9207bc - clip rect computed from border-box edges (analogous to CSS 2.2
        // clip: rect() offsets) +spec:overflow:3d5b53 - overflow clips to padding edge,
        // scroll mechanism for scroll/auto The clip rect for content should exclude the
        // scrollbar area Scrollbars are drawn inside the border-box, on the right/bottom
        // edges +spec:overflow:a825a6 - TODO: abs-pos elements with containing block
        // outside this element should not be clipped (currently all DOM children are
        // clipped)
8232
        let mut clip_rect = LogicalRect {
8232
            origin: LogicalPosition {
8232
                x: paint_rect.origin.x + border.left,
8232
                y: paint_rect.origin.y + border.top,
8232
            },
8232
            size: LogicalSize {
8232
                // Reduce width/height by scrollbar dimensions so content doesn't overlap scrollbar
8232
                width: (paint_rect.size.width
8232
                    - border.left
8232
                    - border.right
8232
                    - scrollbar_info.scrollbar_width)
8232
                    .max(0.0),
8232
                height: (paint_rect.size.height
8232
                    - border.top
8232
                    - border.bottom
8232
                    - scrollbar_info.scrollbar_height)
8232
                    .max(0.0),
8232
            },
8232
        };
        // +spec:overflow:342f47 - overflow-clip-margin expands clip edge for overflow:clip only
        // Per CSS Overflow 3 §3.2: overflow-clip-margin has no effect on overflow:hidden
        // or overflow:scroll. It only expands the overflow clip edge when overflow:clip is used.
8232
        apply_overflow_clip_margin(
8232
            &mut clip_rect,
8232
            &overflow_x,
8232
            &overflow_y,
8232
            self.ctx.styled_dom,
8232
            dom_id,
8232
            &styled_node_state,
        );
8232
        let is_virtual_view = self.is_virtual_view_node(dom_id);
        // +spec:overflow:484889 - clip content in unreachable scrollable overflow region
        // +spec:overflow:917dae - scrollable overflow rect is a rectangle in box's own coordinate
        // system Every clipped node pushes a clip (scrollable, hidden, or clip alike).
8232
        builder.push_clip(clip_rect, border_radius);
        // Regular scrollable nodes ALSO push a scroll frame: WebRender's APZ
        // manages the offset via define_scroll_frame, CPU renderers translate
        // children by scroll_offset. VirtualView scroll state is instead managed
        // by ScrollManager and passed to the callback as scroll_offset, with the
        // VirtualViewPlaceholder emitted after pop_node_clips in
        // generate_for_stacking_context — so VirtualView nodes get only the clip.
8232
        if (overflow_x.is_scroll() || overflow_y.is_scroll()) && !is_virtual_view {
2090
            let scroll_id = self
2090
                .scroll_ids
2090
                .get(&LayoutNodeId::new(node_index))
2090
                .copied()
2090
                .unwrap_or(0);
2090
            let content_size = get_scroll_content_size(
2090
                node,
2090
                self.positioned_tree
2090
                    .tree
2090
                    .warm(LayoutNodeId::new(node_index)),
2090
            );
2090
            builder.push_scroll_frame(clip_rect, content_size, scroll_id);
6191
        }
8232
        true
762444
    }
    /// Pops any clip/scroll commands associated with a node.
8232
    fn pop_node_clips(&self, builder: &mut DisplayListBuilder, node: &LayoutNodeHot) {
8232
        let Some(dom_id) = node.dom_node_id else {
            return;
        };
8232
        let styled_node_state = self.get_styled_node_state(dom_id);
        // Mirror push_node_clips EXACTLY: resolve visible/clip → auto/hidden per
        // CSS Overflow 3 §3.1 (an axis computes to auto/hidden when the *other*
        // axis is a scroll container). push_node_clips decides whether to emit a
        // scroll frame from the RESOLVED values; popping from the RAW values can
        // disagree. Concretely: the auto-injected titlebar title has
        // overflow-x:hidden, overflow-y:visible → push resolves y→auto (a scroll
        // container, since is_scroll() counts Auto) and emits PushClip +
        // PushScrollFrame, but pop saw raw y=visible (is_scroll=false) and emitted
        // only PopClip → an unbalanced PushScrollFrame. The layer allocator then
        // extends the titlebar's scroll layer to the end of the list, swallowing
        // the document body into the titlebar's clip rect (blank window) and
        // underflowing the clip stack. Resolving here keeps push/pop symmetric.
8232
        let raw_overflow_x = get_overflow_x(self.ctx.styled_dom, dom_id, &styled_node_state);
8232
        let raw_overflow_y = get_overflow_y(self.ctx.styled_dom, dom_id, &styled_node_state);
8232
        let overflow_x = raw_overflow_x.resolve_computed(&raw_overflow_y);
8232
        let overflow_y = raw_overflow_y.resolve_computed(&raw_overflow_x);
8232
        let paint_rect = self
8232
            .get_paint_rect(
8232
                self.positioned_tree
8232
                    .tree
8232
                    .nodes
8232
                    .iter()
283680
                    .position(|n| n.dom_node_id == Some(dom_id))
8232
                    .unwrap_or(0),
            )
8232
            .unwrap_or_default();
8232
        let element_size = PhysicalSizeImport {
8232
            width: paint_rect.size.width,
8232
            height: paint_rect.size.height,
8232
        };
8232
        let border_radius = get_border_radius(
8232
            self.ctx.styled_dom,
8232
            dom_id,
8232
            &styled_node_state,
8232
            element_size,
8232
            self.ctx.viewport_size,
        );
8232
        let needs_clip = overflow_x.is_clipped() || overflow_y.is_clipped();
8232
        let is_virtual_view = self.is_virtual_view_node(dom_id);
8232
        if needs_clip {
            // Regular (non-VirtualView) scroll/auto also pushed a scroll frame;
            // pop it first (LIFO) before the shared clip. Hidden/clip and
            // VirtualView scroll only pushed a clip.
8232
            if (overflow_x.is_scroll() || overflow_y.is_scroll()) && !is_virtual_view {
2090
                builder.pop_scroll_frame();
6191
            }
8232
            builder.pop_clip();
        }
        // Pop the clip-path clip if one was pushed.
        // This mirrors the push_node_clips logic: if clip-path is set,
        // a PushClip was emitted before any overflow clips.
        // We pop it last (stack order: clip-path pushed first, popped last).
        if let Some(clip_path) =
8232
            super::getters::get_clip_path(self.ctx.styled_dom, dom_id, &styled_node_state)
        {
            if resolve_clip_path(&clip_path, paint_rect).is_some() {
                builder.pop_clip();
            }
8232
        }
8232
    }
    /// Calculates the final paint-time rectangle for a node.
    ///
    /// ## Coordinate Space
    ///
    /// Returns the node's position in **absolute window coordinates** (logical pixels).
    /// This is the coordinate space used throughout the display list:
    ///
    /// - Origin: Top-left corner of the window
    /// - Units: Logical pixels (`HiDPI` scaling happens in compositor2.rs)
    /// - Scroll: NOT applied here - `WebRender` scroll frames handle scroll offset transformation
    ///   internally via `define_scroll_frame()`
    ///
    /// ## Important
    ///
    /// Do NOT manually subtract scroll offset here! `WebRender`'s scroll spatial
    /// transforms handle this. Subtracting here would cause double-offset and
    /// parallax effects (backgrounds and text moving at different speeds).
4120034
    fn get_paint_rect(&self, node_index: usize) -> Option<LogicalRect> {
4120034
        let node = self
4120034
            .positioned_tree
4120034
            .tree
4120034
            .get(LayoutNodeId::new(node_index))?;
4120034
        let pos = self
4120034
            .positioned_tree
4120034
            .calculated_positions
4120034
            .get(node_index)
4120034
            .copied()
4120034
            .unwrap_or_default();
4120034
        let size = node.used_size.unwrap_or_default();
        // NOTE: Scroll offset is NOT applied here!
        // WebRender scroll frames handle scroll transformation.
        // See compositor2.rs PushScrollFrame for details.
4120034
        Some(LogicalRect::new(pos, size))
4120034
    }
    /// Emits drawing commands for the background and border of a single node.
    #[allow(clippy::too_many_lines)] // large but cohesive: single-purpose layout/render/parse routine (one branch per case)
    /// Does this node's PARENT paint it, as an `InlineShape` of the parent's own
    /// inline formatting context?
    ///
    /// This is the ownership question behind every inline-level box: exactly one
    /// path must emit it. When the parent runs an IFC, the text engine measured
    /// this box, gave it a position on a line, and paints it from that shape —
    /// so `paint_node_background_and_border` must NOT paint it again, or the box
    /// appears twice (once on its line, once at the parent's content origin).
    /// When the parent runs anything else there is no shape and no other painter,
    /// so the box must paint itself or it vanishes entirely.
    ///
    /// Two kinds of parent do NOT build inline shapes:
    ///
    ///  * a **flex or grid container**, which treats an inline-level child as a flex/grid item and
    ///    lays it out directly;
    ///  * a **replaced element** (`<img>`, `<video>`, `<canvas>`, …), whose own content is the
    ///    replaced object. azul lets a replaced element carry children as an overlay (the frontpage
    ///    `opengl` example composits a `Button` over its canvas); they are laid out by an interior
    ///    run and painted by the ordinary node walk, never as inline shapes.
    ///
    /// Both were previously handled by asking only "is the parent flex or grid?",
    /// which silently answered "yes, the parent paints it" for a replaced element
    /// — so a `Button` over an `<img>` had its background painted by nobody.
761773
    fn parent_paints_as_inline_shape(&self, node_index: usize) -> bool {
761773
        let tree = &self.positioned_tree.tree;
761773
        let parent_fc = tree
761773
            .warm(LayoutNodeId::new(node_index))
761773
            .and_then(|w| w.parent_formatting_context);
633688
        if matches!(
747021
            parent_fc,
            Some(FormattingContext::Flex | FormattingContext::Grid)
        ) {
128085
            return false;
633688
        }
633688
        let parent_is_replaced = tree
633688
            .get(LayoutNodeId::new(node_index))
633688
            .and_then(|n| n.parent)
633688
            .and_then(|p| tree.get(LayoutNodeId::new(p)))
633688
            .and_then(|p| p.dom_node_id)
633688
            .is_some_and(|parent_dom_id| {
618737
                let node_data = &self.ctx.styled_dom.node_data.as_container()[parent_dom_id];
618737
                crate::solver3::layout_tree::is_replaced_element(node_data)
618737
            });
633688
        !parent_is_replaced
761773
    }
762444
    fn paint_node_background_and_border(
762444
        &mut self,
762444
        builder: &mut DisplayListBuilder,
762444
        node_index: usize,
762444
    ) -> Result<()> {
762444
        let _p = crate::probe::Probe::span("dl_bg_border");
762444
        if self.try_copy_cached_run(builder, node_index, EmitPhase::BgBorder) {
671
            return Ok(());
761773
        }
761773
        builder.set_current_layout(Some((node_index, EmitPhase::BgBorder)));
761773
        let result = self.paint_node_background_and_border_inner(builder, node_index);
761773
        builder.set_current_layout(None);
761773
        result
762444
    }
761773
    fn paint_node_background_and_border_inner(
761773
        &mut self,
761773
        builder: &mut DisplayListBuilder,
761773
        node_index: usize,
761773
    ) -> Result<()> {
761773
        let Some(paint_rect) = self.get_paint_rect(node_index) else {
            return Ok(());
        };
761773
        let node = self
761773
            .positioned_tree
761773
            .tree
761773
            .get(LayoutNodeId::new(node_index))
761773
            .ok_or(LayoutError::InvalidTree)?;
        // Set current node for node mapping (for pagination break properties)
761773
        builder.set_current_node(node.dom_node_id);
        // Check for CSS break-before/break-after properties and register forced page breaks
        // This is used by the pagination slicer to insert page breaks at correct positions
761773
        if let Some(dom_id) = node.dom_node_id {
761612
            let break_before = get_break_before(self.ctx.styled_dom, Some(dom_id));
761612
            let break_after = get_break_after(self.ctx.styled_dom, Some(dom_id));
            // For break-before: always, insert a page break at the top of this element
761612
            if is_forced_page_break(break_before) {
15
                let y_position = paint_rect.origin.y;
15
                builder.add_forced_page_break(y_position, Some(dom_id));
15
                debug_info!(
15
                    self.ctx,
15
                    "Registered forced page break BEFORE node {} at y={}",
                    node_index,
                    y_position
                );
761597
            }
            // For break-after: always, insert a page break at the bottom of this element
761612
            if is_forced_page_break(break_after) {
                let y_position = paint_rect.origin.y + paint_rect.size.height;
                builder.add_forced_page_break(y_position, Some(dom_id));
                debug_info!(
                    self.ctx,
                    "Registered forced page break AFTER node {} at y={}",
                    node_index,
                    y_position
                );
761612
            }
161
        }
        // CSS 2.2 §11.2: visibility:hidden — box is invisible but still affects layout.
        // Skip painting background/border for hidden nodes, but traversal continues
        // so visible descendants are still painted.
761773
        if self.is_node_hidden(node_index) {
            return Ok(());
761773
        }
        // An inline-level box is painted by whoever OWNS it: if its parent runs an
        // inline formatting context, the text engine positioned it as an
        // `InlineShape` and paints it from there, and painting it again here
        // would double it at the wrong origin. If the parent runs anything else,
        // nobody else will paint it and it must paint itself. See
        // `parent_paints_as_inline_shape` for what the two cases actually are.
761773
        let warm = self
761773
            .positioned_tree
761773
            .tree
761773
            .warm(LayoutNodeId::new(node_index));
761773
        let parent_paints_me_as_an_inline_shape = self.parent_paints_as_inline_shape(node_index);
761773
        if let Some(dom_id) = node.dom_node_id {
761612
            let display = {
                use crate::solver3::getters::get_display_property;
761612
                get_display_property(self.ctx.styled_dom, Some(dom_id))
761612
                    .unwrap_or(LayoutDisplay::Inline)
            };
            // EVERY atomic inline is represented in its parent's inline layout
            // as an `InlineShape` (fc.rs builds one for each), and
            // `paint_inline_shape` paints it from there. Naming only
            // `InlineBlock` here let an `inline-flex` / `inline-grid` /
            // `inline-table` box paint its own background AS WELL, so it
            // appeared twice — once where the shape put it and once at the
            // parent's content origin. A `Button` (inline-flex) composited
            // over an `<img>` showed both copies on the frontpage screenshot.
761612
            let is_atomic_inline = display.is_atomic_inline();
761612
            if is_atomic_inline || display == LayoutDisplay::Inline {
353347
                debug_info!(
88063
                    self.ctx,
88063
                    "[paint_node] node {} has display={:?}, parent_formatting_context={:?}, \
88063
                     parent_paints_me_as_an_inline_shape={}",
                    node_index,
                    display,
88063
                    warm.and_then(|w| w.parent_formatting_context.as_ref()),
                    parent_paints_me_as_an_inline_shape
                );
353347
                if parent_paints_me_as_an_inline_shape {
                    // Normally, text3 handles inline/inline-block backgrounds via
                    // InlineShape (inline-block) or glyph runs (inline). However,
                    // if this inline-block establishes a stacking context (e.g.
                    // position:relative + z-index, opacity < 1, transform), we MUST
                    // paint its background here. generate_for_stacking_context paints
                    // background (step 1) → children (steps 3-6). If we skip the
                    // background, paint_inline_shape in the parent's paint_node_content
                    // would paint it AFTER the children, obscuring them.
330201
                    if is_atomic_inline && self.establishes_stacking_context(node_index) {
                        // Fall through to paint background/border now
                    } else {
330201
                        return Ok(());
                    }
23146
                }
                // Fall through to paint this element - it's a flex/grid item
408265
            }
161
        }
        // CSS 2.2 Section 17.5.1: Tables in the visual formatting model
        // Table-internal elements (row groups, rows, columns, column groups) have their
        // backgrounds painted by paint_table_items() in the correct 6-layer order.
        // Skip background painting here to avoid double-painting at wrong positions
        // (calculated_positions for TR elements may not reflect row offsets correctly;
        // paint_table_items computes row rects from cell bounding boxes instead).
        // Table CELLS still need content painting via paint_in_flow_descendants, so
        // we only skip the background/border here — content painting continues normally.
431152
        if matches!(
431572
            node.formatting_context,
            FormattingContext::TableRowGroup
                | FormattingContext::TableRow
                | FormattingContext::TableColumnGroup
        ) {
420
            return Ok(());
431152
        }
        // Tables have a special 6-layer background painting order
431152
        if matches!(node.formatting_context, FormattingContext::Table) {
380
            debug_info!(
380
                self.ctx,
380
                "Painting table backgrounds/borders for node {} at {:?}",
                node_index,
                paint_rect
            );
            // Delegate to specialized table painting function
380
            return self.paint_table_items(builder, node_index);
430772
        }
        // CSS 2.2 section 17.5.1: a cell's BACKGROUND belongs to layer 6 of
        // the table paint order and is painted by paint_table_items — never
        // here, or it re-paints ON TOP of whatever the table painted after
        // layer 6 (the resolved collapsed borders). The cell's own BORDER is
        // painted here in the separate-borders model only; in the collapsing
        // model the table paints one resolved border per grid edge
        // (paint_collapsed_table_borders), so the cell contributes nothing.
430772
        let is_table_cell = matches!(node.formatting_context, FormattingContext::TableCell);
430772
        if is_table_cell && self.is_inside_collapsed_table(node_index) {
90
            return Ok(());
430682
        }
430682
        if let Some(dom_id) = node.dom_node_id {
430521
            let styled_node_state = self.get_styled_node_state(dom_id);
430521
            let background_contents = if is_table_cell {
850
                Vec::new()
            } else {
429671
                get_background_contents(self.ctx.styled_dom, dom_id, &styled_node_state)
            };
430521
            let border_info = get_border_info(self.ctx.styled_dom, dom_id, &styled_node_state);
430521
            let node_type = &self.ctx.styled_dom.node_data.as_container()[dom_id];
430521
            debug_info!(
150446
                self.ctx,
150446
                "Painting background/border for node {} ({:?}) at {:?}, backgrounds={:?}",
                node_index,
150446
                node_type.get_node_type(),
                paint_rect,
150446
                background_contents.len()
            );
            // Get both versions: simple BorderRadius for rect clipping and StyleBorderRadius for
            // border rendering
430521
            let element_size = PhysicalSizeImport {
430521
                width: paint_rect.size.width,
430521
                height: paint_rect.size.height,
430521
            };
430521
            let simple_border_radius = get_border_radius(
430521
                self.ctx.styled_dom,
430521
                dom_id,
430521
                &styled_node_state,
430521
                element_size,
430521
                self.ctx.viewport_size,
            );
430521
            let style_border_radius =
430521
                get_style_border_radius(self.ctx.styled_dom, dom_id, &styled_node_state);
            // Paint box shadows before backgrounds (CSS spec: shadows render behind the element)
430521
            let node_state =
430521
                &self.ctx.styled_dom.styled_nodes.as_container()[dom_id].styled_node_state;
            // +spec:overflow:bb4308 - box shadows are ink overflow: painted outside border box, not
            // affecting layout Check all four sides for box-shadow (azul stores them
            // per-side). Routed through `super::getters::*` so the compact-cache
            // has_box_shadow fast path fires — most nodes have no shadow and skip 4
            // cascade walks.
430521
            for shadow in [
430521
                super::getters::get_box_shadow_left(self.ctx.styled_dom, dom_id, node_state),
430521
                super::getters::get_box_shadow_right(self.ctx.styled_dom, dom_id, node_state),
430521
                super::getters::get_box_shadow_top(self.ctx.styled_dom, dom_id, node_state),
430521
                super::getters::get_box_shadow_bottom(self.ctx.styled_dom, dom_id, node_state),
430521
            ]
430521
            .into_iter()
430521
            .flatten()
680
            {
680
                builder.push_item(DisplayListItem::BoxShadow {
680
                    bounds: paint_rect.into(),
680
                    shadow,
680
                    border_radius: simple_border_radius,
680
                });
680
            }
            // An SVG SHAPE takes its border as a STROKE. A stroke follows the
            // geometry; a border follows the box - and the box is clipped to
            // the geometry, so a rectangular border on a shape leaves a
            // hairline at the corners and nothing anywhere else. The border
            // slots are how `stroke`/`stroke-width` reach the cascade (see
            // `COMBINED_CSS_PROPERTIES_KEY_MAP`), so they are consumed here
            // and NOT handed to the rectangle painter.
430521
            let stroke = self.svg_stroke_for(dom_id, &border_info);
430521
            let border_info = if stroke.is_some() {
30
                let mut without_border = border_info;
30
                without_border.widths = StyleBorderWidths {
30
                    top: None,
30
                    right: None,
30
                    bottom: None,
30
                    left: None,
30
                };
30
                without_border
            } else {
430491
                border_info
            };
            // Use unified background/border painting
430521
            builder.push_backgrounds_and_border(
430521
                paint_rect,
430521
                &background_contents,
430521
                &border_info,
430521
                simple_border_radius,
430521
                style_border_radius,
430521
                self.ctx.image_cache,
            );
            // The stroke is NOT painted here: it must land OUTSIDE this
            // node's own clip mask. See `paint_svg_stroke`.
430521
            drop(stroke);
161
        }
        // Seat focus ring (9b-ii-a-i-d-iii, the overlay half). `:focus` and
        // its restyle are the primary's alone (one pseudo-class, one a11y
        // focus), so a NON-primary seat's focused node gets a 2px ring in
        // that seat's colour around its border box - the seat-coloured
        // convention the seat carets already use. Four strips, not a Border
        // item, so every backend paints it the same and no style resolution
        // is involved. The primary is never in `seat_focus_rings`.
430682
        if let Some(dom_node) = node.dom_node_id {
430521
            if !self.ctx.seat_focus_rings.is_empty() {
535
                let dom_id = self.ctx.styled_dom.dom_id;
535
                let colors: Vec<ColorU> = self
535
                    .ctx
535
                    .seat_focus_rings
535
                    .iter()
535
                    .filter(|(n, _)| {
535
                        n.dom == dom_id && n.node.into_crate_internal() == Some(dom_node)
535
                    })
535
                    .map(|(_, c)| *c)
535
                    .collect();
535
                for (i, color) in colors.into_iter().enumerate() {
                    // Several seats on one node: concentric rings, 3px apart.
16
                    let inset = 1.0 + 3.0 * i as f32;
16
                    let thickness = 2.0;
16
                    let x = paint_rect.origin.x - inset;
16
                    let y = paint_rect.origin.y - inset;
16
                    let w = paint_rect.size.width + 2.0 * inset;
16
                    let h = paint_rect.size.height + 2.0 * inset;
                    use azul_core::geom::{LogicalPosition, LogicalSize};
64
                    let strip = |sx: f32, sy: f32, sw: f32, sh: f32| {
64
                        LogicalRect::new(LogicalPosition::new(sx, sy), LogicalSize::new(sw, sh))
64
                    };
16
                    let vertical = h - 2.0 * thickness;
16
                    builder.push_rect(strip(x, y, w, thickness), color, BorderRadius::default());
16
                    builder.push_rect(
16
                        strip(x, y + h - thickness, w, thickness),
16
                        color,
16
                        BorderRadius::default(),
                    );
16
                    builder.push_rect(
16
                        strip(x, y + thickness, thickness, vertical),
16
                        color,
16
                        BorderRadius::default(),
                    );
16
                    builder.push_rect(
16
                        strip(x + w - thickness, y + thickness, thickness, vertical),
16
                        color,
16
                        BorderRadius::default(),
                    );
                }
429986
            }
161
        }
430682
        Ok(())
761773
    }
    //   backgrounds are invisible, allowing table background to show through
    // +spec:box-model:124815 - Table layer background painting order (6 layers: table, col-group,
    // col, row-group, row, cell) +spec:positioning:702985 - Table background painting in 6
    // layers (17.5.1) +spec:table-layout:7370dc - Table layers and transparency: 6-layer
    // background painting order +spec:table-layout:7a5909 - table layers: 6-layer background
    // paint order (table/colgroup/col/rowgroup/row/cell)
    /// CSS 2.2 Section 17.5.1: Table background painting in 6 layers
    ///
    /// Implements the CSS 2.2 specification for table background painting order.
    /// Unlike regular block elements, tables paint backgrounds in layers from back to front:
    ///
    /// 1. Table background (lowest layer)
    /// 2. Column group backgrounds
    /// 3. Column backgrounds
    /// 4. Row group backgrounds
    /// 5. Row backgrounds
    /// 6. Cell backgrounds (topmost layer)
    ///
    /// Then borders are painted (respecting border-collapse mode).
    /// Finally, cell content is painted on top of everything.
    ///
    /// This function generates simple display list items (Rect, Border) in the correct
    /// CSS paint order, making `WebRender` integration trivial.
380
    fn paint_table_items(
380
        &self,
380
        builder: &mut DisplayListBuilder,
380
        table_index: usize,
380
    ) -> Result<()> {
380
        let table_node = self
380
            .positioned_tree
380
            .tree
380
            .get(LayoutNodeId::new(table_index))
380
            .ok_or(LayoutError::InvalidTree)?;
380
        let Some(table_paint_rect) = self.get_paint_rect(table_index) else {
            return Ok(());
        };
        // Layer 1: Table background
380
        if let Some(dom_id) = table_node.dom_node_id {
380
            let styled_node_state = self.get_styled_node_state(dom_id);
380
            let bg_color = get_background_color(self.ctx.styled_dom, dom_id, &styled_node_state);
380
            let element_size = PhysicalSizeImport {
380
                width: table_paint_rect.size.width,
380
                height: table_paint_rect.size.height,
380
            };
380
            let border_radius = get_border_radius(
380
                self.ctx.styled_dom,
380
                dom_id,
380
                &styled_node_state,
380
                element_size,
380
                self.ctx.viewport_size,
380
            );
380

            
380
            builder.push_rect(table_paint_rect, bg_color, border_radius);
380
        }
        // Traverse table children to paint layers 2-6
        // Layer 2: Column group backgrounds
        // Layer 3: Column backgrounds (columns are children of column groups)
400
        for &child_idx in self.positioned_tree.tree.children(table_index) {
400
            let child_node = self.positioned_tree.tree.get(LayoutNodeId::new(child_idx));
400
            if let Some(node) = child_node {
400
                if matches!(node.formatting_context, FormattingContext::TableColumnGroup) {
                    // Paint column group background
                    self.paint_element_background(builder, child_idx);
                    // Paint backgrounds of individual columns within this group
                    for &col_idx in self.positioned_tree.tree.children(child_idx) {
                        self.paint_element_background(builder, col_idx);
                    }
400
                }
            }
        }
        // Layer 4: Row group backgrounds (tbody, thead, tfoot)
        // Layer 5: Row backgrounds
        // Layer 6: Cell backgrounds
400
        for &child_idx in self.positioned_tree.tree.children(table_index) {
400
            let child_node = self.positioned_tree.tree.get(LayoutNodeId::new(child_idx));
400
            if let Some(node) = child_node {
400
                match node.formatting_context {
                    FormattingContext::TableRowGroup => {
                        // Paint row group background
30
                        self.paint_element_background(builder, child_idx);
                        // Paint rows within this group
30
                        for &row_idx in self.positioned_tree.tree.children(child_idx) {
30
                            self.paint_table_row_and_cells(builder, row_idx);
30
                        }
                    }
360
                    FormattingContext::TableRow => {
360
                        // Direct row child (no row group wrapper)
360
                        self.paint_table_row_and_cells(builder, child_idx);
360
                    }
10
                    _ => {}
                }
            }
        }
        // Borders: separate model cells paint their own borders in the normal
        // flow; the collapsing model paints ONE resolved border per grid edge
        // here, on top of all table backgrounds (cell borders are suppressed
        // in paint_node_background_and_border for collapsed tables).
380
        if self.table_is_border_collapsed(table_index) {
40
            self.paint_collapsed_table_borders(builder, table_index);
340
        }
380
        Ok(())
380
    }
    /// Whether `table_index` (a `FormattingContext::Table` node) uses the
    /// collapsing border model. Anonymous wrapper tables have no DOM node and
    /// keep the initial value (separate).
1320
    fn table_is_border_collapsed(&self, table_index: usize) -> bool {
        use azul_css::props::layout::table::StyleBorderCollapse;
1320
        let Some(node) = self
1320
            .positioned_tree
1320
            .tree
1320
            .get(LayoutNodeId::new(table_index))
        else {
            return false;
        };
1320
        let Some(dom_id) = node.dom_node_id else {
            return false;
        };
1320
        if let Some(ref cc) = self.ctx.styled_dom.css_property_cache.ptr.compact_cache {
1320
            return cc.get_border_collapse(dom_id.index()) == StyleBorderCollapse::Collapse;
        }
        let node_data = &self.ctx.styled_dom.node_data.as_container()[dom_id];
        let node_state = self.get_styled_node_state(dom_id);
        self.ctx
            .styled_dom
            .css_property_cache
            .ptr
            .get_border_collapse(node_data, &dom_id, &node_state)
            .and_then(|prop| prop.get_property().copied())
            .unwrap_or(StyleBorderCollapse::Separate)
            == StyleBorderCollapse::Collapse
1320
    }
    /// Whether a node lives inside a `border-collapse: collapse` table
    /// (walks the layout-tree parent chain to the nearest Table node).
940
    fn is_inside_collapsed_table(&self, node_index: usize) -> bool {
940
        let mut cur = self
940
            .positioned_tree
940
            .tree
940
            .get(LayoutNodeId::new(node_index))
940
            .and_then(|n| n.parent);
1940
        while let Some(idx) = cur {
1940
            let Some(node) = self.positioned_tree.tree.get(LayoutNodeId::new(idx)) else {
                return false;
            };
1940
            if matches!(node.formatting_context, FormattingContext::Table) {
940
                return self.table_is_border_collapsed(idx);
1000
            }
1000
            cur = node.parent;
        }
        false
940
    }
    /// CSS 2.2 section 17.6.2: paint the collapsing-border grid.
    ///
    /// For every grid edge the participating borders (the two adjacent cells
    /// on interior edges; cell + table on perimeter edges; the row's own
    /// border on horizontal edges) compete via
    /// `BorderInfo::resolve_conflict` (hidden wins, then wider, then style
    /// priority, then source priority) and the single winner is painted as a
    /// strip CENTERED on the grid line — perimeter borders deliberately
    /// straddle the table edge, exactly like browsers render them.
    ///
    /// v1 limitations, acceptable for the current corpus and safe (worst
    /// case: a border strip at a slightly wrong offset, never a double
    /// border): cells are paired positionally per row (colspan/rowspan
    /// pairing is approximate), column/column-group borders do not
    /// participate, and non-solid winners (dashed/dotted/double) paint as a
    /// solid strip of the winning color.
40
    fn paint_collapsed_table_borders(&self, builder: &mut DisplayListBuilder, table_index: usize) {
        use azul_css::props::style::border::BorderStyle;
        use crate::solver3::fc::{
            get_border_info as collapsed_border_info, BorderInfo as CollapsedBorder, BorderSource,
        };
        // (cell layout-tree index, paint rect, owning row index) per row
40
        let mut rows: Vec<(usize, Vec<(usize, LogicalRect)>)> = Vec::new();
50
        for &child_idx in self.positioned_tree.tree.children(table_index) {
50
            let Some(child) = self.positioned_tree.tree.get(LayoutNodeId::new(child_idx)) else {
                continue;
            };
50
            match child.formatting_context {
                FormattingContext::TableRowGroup => {
30
                    for &row_idx in self.positioned_tree.tree.children(child_idx) {
30
                        rows.push((row_idx, self.collect_row_cells(row_idx)));
30
                    }
                }
20
                FormattingContext::TableRow => {
20
                    rows.push((child_idx, self.collect_row_cells(child_idx)));
20
                }
                _ => {}
            }
        }
50
        rows.retain(|(_, cells)| !cells.is_empty());
40
        if rows.is_empty() {
            return;
40
        }
360
        let cell_border = |idx: usize| -> Option<[CollapsedBorder; 4]> {
360
            let node = self.positioned_tree.tree.get(LayoutNodeId::new(idx))?;
360
            Some(collapsed_border_info(self.ctx, node, BorderSource::Cell).into())
360
        };
180
        let row_border = |idx: usize| -> Option<[CollapsedBorder; 4]> {
180
            let node = self.positioned_tree.tree.get(LayoutNodeId::new(idx))?;
180
            Some(collapsed_border_info(self.ctx, node, BorderSource::Row).into())
180
        };
40
        let table_border: Option<[CollapsedBorder; 4]> = self
40
            .positioned_tree
40
            .tree
40
            .get(LayoutNodeId::new(table_index))
40
            .map(|node| collapsed_border_info(self.ctx, node, BorderSource::Table).into());
        const TOP: usize = 0;
        const RIGHT: usize = 1;
        const BOTTOM: usize = 2;
        const LEFT: usize = 3;
        // Fold the participants down to one winner. `resolve_conflict`
        // returning None means `hidden` participated: paint nothing.
300
        let resolve = |participants: &[Option<CollapsedBorder>]| -> Option<CollapsedBorder> {
300
            let mut winner: Option<CollapsedBorder> = None;
720
            for b in participants.iter().flatten() {
720
                winner = match winner {
300
                    None => Some(*b),
420
                    Some(w) => Some(CollapsedBorder::resolve_conflict(&w, b)?),
                };
            }
190
            let w = winner?;
190
            (w.width > 0.0 && !matches!(w.style, BorderStyle::None | BorderStyle::Hidden))
190
                .then_some(w)
300
        };
        // Vertical edges, one strip per (row, boundary).
90
        for (row_idx, cells) in &rows {
50
            let _ = row_idx;
50
            let n = cells.len();
140
            for boundary in 0..=n {
140
                let left_cell = boundary.checked_sub(1).and_then(|i| cells.get(i));
140
                let right_cell = cells.get(boundary);
140
                let winner = resolve(&[
140
                    left_cell
140
                        .and_then(|(i, _)| cell_border(*i))
140
                        .map(|b| b[RIGHT]),
140
                    right_cell
140
                        .and_then(|(i, _)| cell_border(*i))
140
                        .map(|b| b[LEFT]),
                    // table border participates on the perimeter only
140
                    if boundary == 0 {
50
                        table_border.map(|b| b[LEFT])
90
                    } else if boundary == n {
50
                        table_border.map(|b| b[RIGHT])
                    } else {
40
                        None
                    },
                ]);
140
                let Some(w) = winner else { continue };
90
                let (x, y0, y1) = match (left_cell, right_cell) {
60
                    (Some((_, lr)), _) => (
60
                        lr.origin.x + lr.size.width,
60
                        lr.origin.y,
60
                        lr.origin.y + lr.size.height,
60
                    ),
30
                    (None, Some((_, rr))) => {
30
                        (rr.origin.x, rr.origin.y, rr.origin.y + rr.size.height)
                    }
                    (None, None) => continue,
                };
90
                builder.push_rect(
90
                    LogicalRect::new(
90
                        LogicalPosition::new(w.width.mul_add(-0.5, x), y0),
90
                        LogicalSize::new(w.width, y1 - y0),
                    ),
90
                    w.color,
90
                    BorderRadius::default(),
                );
            }
        }
        // Horizontal edges: for each row boundary, one strip per column
        // segment (positional pairing of the cells above/below).
40
        let n_rows = rows.len();
90
        for boundary in 0..=n_rows {
90
            let above = boundary.checked_sub(1).and_then(|i| rows.get(i));
90
            let below = rows.get(boundary);
90
            let segments: &[(usize, LogicalRect)] = match below.or(above) {
90
                Some((_, cells)) => cells,
                None => continue,
            };
160
            for (col, (_, seg_rect)) in segments.iter().enumerate() {
160
                let above_cell = above.and_then(|(_, cells)| cells.get(col));
160
                let below_cell = below.and_then(|(_, cells)| cells.get(col));
160
                let winner = resolve(&[
160
                    above_cell
160
                        .and_then(|(i, _)| cell_border(*i))
160
                        .map(|b| b[BOTTOM]),
160
                    above.and_then(|(r, _)| row_border(*r)).map(|b| b[BOTTOM]),
160
                    below_cell
160
                        .and_then(|(i, _)| cell_border(*i))
160
                        .map(|b| b[TOP]),
160
                    below.and_then(|(r, _)| row_border(*r)).map(|b| b[TOP]),
160
                    if boundary == 0 {
70
                        table_border.map(|b| b[TOP])
90
                    } else if boundary == n_rows {
70
                        table_border.map(|b| b[BOTTOM])
                    } else {
20
                        None
                    },
                ]);
160
                let Some(w) = winner else { continue };
100
                let y = match above_cell.or(below_cell) {
100
                    Some((_, r)) if above_cell.is_some() => r.origin.y + r.size.height,
40
                    Some((_, r)) => r.origin.y,
                    None => continue,
                };
                // Extend the strip by its own half-width at both ends so the
                // corners where a wider horizontal border meets a narrower
                // vertical one are filled.
100
                let x0 = w.width.mul_add(-0.5, seg_rect.origin.x);
100
                let x1 = w
100
                    .width
100
                    .mul_add(0.5, seg_rect.origin.x + seg_rect.size.width);
100
                builder.push_rect(
100
                    LogicalRect::new(
100
                        LogicalPosition::new(x0, w.width.mul_add(-0.5, y)),
100
                        LogicalSize::new(x1 - x0, w.width),
                    ),
100
                    w.color,
100
                    BorderRadius::default(),
                );
            }
        }
40
    }
    /// Paint rects of a row's cell children, in tree order.
50
    fn collect_row_cells(&self, row_idx: usize) -> Vec<(usize, LogicalRect)> {
50
        self.positioned_tree
50
            .tree
50
            .children(row_idx)
50
            .iter()
90
            .filter_map(|&cell_idx| {
90
                let rect = self.get_paint_rect(cell_idx)?;
90
                Some((cell_idx, rect))
90
            })
50
            .collect()
50
    }
    /// Helper function to paint a table row's background and then its cells' backgrounds
    /// Layer 5: Row background
    /// Layer 6: Cell backgrounds (painted after row, so they appear on top)
390
    fn paint_table_row_and_cells(&self, builder: &mut DisplayListBuilder, row_idx: usize) {
        // Layer 5: Paint row background.
        // Rows don't have entries in calculated_positions (adding them would
        // double-offset cells during position recursion). Compute the row rect
        // from the bounding box of its cell children.
390
        if let Some(row_node) = self.positioned_tree.tree.get(LayoutNodeId::new(row_idx)) {
390
            if let Some(dom_id) = row_node.dom_node_id {
390
                let styled_node_state = self.get_styled_node_state(dom_id);
390
                let bg_color =
390
                    get_background_color(self.ctx.styled_dom, dom_id, &styled_node_state);
390
                if bg_color.a > 0 {
                    // Compute row rect from cell children
                    let mut min_x = f32::MAX;
                    let mut min_y = f32::MAX;
                    let mut max_x = f32::MIN;
                    let mut max_y = f32::MIN;
                    for &cell_idx in self.positioned_tree.tree.children(row_idx) {
                        if let Some(cell_rect) = self.get_paint_rect(cell_idx) {
                            min_x = min_x.min(cell_rect.origin.x);
                            min_y = min_y.min(cell_rect.origin.y);
                            max_x = max_x.max(cell_rect.origin.x + cell_rect.size.width);
                            max_y = max_y.max(cell_rect.origin.y + cell_rect.size.height);
                        }
                    }
                    if min_x < max_x && min_y < max_y {
                        let row_rect = LogicalRect::new(
                            LogicalPosition::new(min_x, min_y),
                            LogicalSize::new(max_x - min_x, max_y - min_y),
                        );
                        builder.push_rect(row_rect, bg_color, BorderRadius::default());
                    }
390
                }
            }
        }
        // Layer 6: Paint cell backgrounds (topmost layer)
390
        if let Some(_node) = self.positioned_tree.tree.get(LayoutNodeId::new(row_idx)) {
940
            for &cell_idx in self.positioned_tree.tree.children(row_idx) {
940
                self.paint_element_background(builder, cell_idx);
940
            }
        }
390
    }
    /// Helper function to paint an element's background (used for all table elements)
    /// Reads background-color and border-radius from CSS properties and emits `push_rect()`
970
    fn paint_element_background(&self, builder: &mut DisplayListBuilder, node_index: usize) {
970
        let Some(paint_rect) = self.get_paint_rect(node_index) else {
            return;
        };
970
        let Some(node) = self.positioned_tree.tree.get(LayoutNodeId::new(node_index)) else {
            return;
        };
970
        let Some(dom_id) = node.dom_node_id else {
            return;
        };
970
        let styled_node_state = self.get_styled_node_state(dom_id);
970
        let bg_color = get_background_color(self.ctx.styled_dom, dom_id, &styled_node_state);
        // Only paint if background color has alpha > 0 (optimization)
970
        if bg_color.a == 0 {
910
            return;
60
        }
60
        let element_size = PhysicalSizeImport {
60
            width: paint_rect.size.width,
60
            height: paint_rect.size.height,
60
        };
60
        let border_radius = get_border_radius(
60
            self.ctx.styled_dom,
60
            dom_id,
60
            &styled_node_state,
60
            element_size,
60
            self.ctx.viewport_size,
        );
60
        builder.push_rect(paint_rect, bg_color, border_radius);
970
    }
    /// Emits drawing commands for the foreground content, including hit-test areas and scrollbars.
    #[allow(clippy::too_many_lines)] // large but cohesive: single-purpose layout/render/parse
                                     // routine (one branch per case)
762444
    fn paint_node_content(
762444
        &mut self,
762444
        builder: &mut DisplayListBuilder,
762444
        node_index: usize,
762444
    ) -> Result<()> {
762444
        let _p = crate::probe::Probe::span("dl_content");
        // ENGINE-LEVEL PLACEHOLDER (`placeholder` attribute): painted here,
        // never modelled as a DOM node, so it cannot intercept clicks, own
        // clusters an editing consumer could seat a caret in, or latch a
        // stale visibility override - (empty && unfocused) is recomputed
        // from scratch on every build.
        //
        // Emitted OUTSIDE the cached content run, and BEFORE the copy: the
        // run recorded while the host was empty carries the prompt item, and
        // `try_copy_cached_run` replays a run wholesale - so a cached copy
        // re-emitted the prompt over text the user had just typed (device
        // report, 2026-08-31). Kept out of the cache, the prompt is decided
        // fresh on every emission, cached run or not.
762444
        if let Some(rect) = self.get_paint_rect(node_index) {
762444
            self.maybe_paint_placeholder_prompt(builder, node_index, &rect);
762444
        }
762444
        if self.try_copy_cached_run(builder, node_index, EmitPhase::Content) {
671
            return Ok(());
761773
        }
761773
        builder.set_current_layout(Some((node_index, EmitPhase::Content)));
761773
        let result = self.paint_node_content_inner(builder, node_index);
761773
        builder.set_current_layout(None);
761773
        result
762444
    }
761773
    fn paint_node_content_inner(
761773
        &mut self,
761773
        builder: &mut DisplayListBuilder,
761773
        node_index: usize,
761773
    ) -> Result<()> {
        // CSS 2.2 §11.2: visibility:hidden — skip painting content for hidden nodes.
761773
        if self.is_node_hidden(node_index) {
            return Ok(());
761773
        }
761773
        let node = self
761773
            .positioned_tree
761773
            .tree
761773
            .get(LayoutNodeId::new(node_index))
761773
            .ok_or(LayoutError::InvalidTree)?;
761773
        let node_warm = self
761773
            .positioned_tree
761773
            .tree
761773
            .warm(LayoutNodeId::new(node_index));
        // Set current node for node mapping (for pagination break properties)
761773
        builder.set_current_node(node.dom_node_id);
761773
        let Some(mut paint_rect) = self.get_paint_rect(node_index) else {
            return Ok(());
        };
        // For text nodes (with inline layout), the used_size might be 0x0.
        // In this case, compute the bounds from the inline layout result.
761773
        if paint_rect.size.width == 0.0 || paint_rect.size.height == 0.0 {
347081
            if let Some(cached_layout) = node_warm.and_then(|w| w.inline_layout_result.as_ref()) {
13
                let content_bounds = cached_layout.layout.bounds();
13
                paint_rect.size.width = content_bounds.width;
13
                paint_rect.size.height = content_bounds.height;
347068
            }
414692
        }
        // Add a hit-test area for this node if it's interactive.
        // NOTE: For scrollable containers (overflow: scroll/auto), the hit-test area
        // was already pushed in generate_for_stacking_context BEFORE the scroll frame,
        // so we skip it here to avoid duplicate hit-test areas that would scroll with content.
761773
        if let Some(tag_id) = get_tag_id(self.ctx.styled_dom, node.dom_node_id) {
367247
            let is_scrollable = if let Some(dom_id) = node.dom_node_id {
367247
                let styled_node_state = self.get_styled_node_state(dom_id);
367247
                let overflow_x = get_overflow_x(self.ctx.styled_dom, dom_id, &styled_node_state);
367247
                let overflow_y = get_overflow_y(self.ctx.styled_dom, dom_id, &styled_node_state);
367247
                overflow_x.is_scroll() || overflow_y.is_scroll()
            } else {
                false
            };
            // Push hit-test area for this node ONLY if it's not a scrollable container.
            // Scrollable containers already have their hit-test area pushed BEFORE the scroll frame
            // in generate_for_stacking_context, ensuring the hit-test stays stationary in parent
            // space while content scrolls. Pushing it again here would create a
            // duplicate that scrolls with content, causing hit-test failures when
            // scrolled to the bottom.
367247
            if !is_scrollable {
364673
                builder.push_hit_test_area(paint_rect, tag_id);
364673
            }
394526
        }
        // Paint the node's visible content.
761773
        if let Some(cached_layout) = node_warm.and_then(|w| w.inline_layout_result.as_ref()) {
317291
            let inline_layout = &cached_layout.layout;
            // (d6h) Dense-aware count: the stored sparse may be the
            // retirement sentinel; logs should report the real content.
317291
            let logged_item_count = cached_layout
317291
                .dense
317291
                .as_deref()
317291
                .filter(|d| !d.clusters.is_empty())
317291
                .map_or(inline_layout.items.len(), |d| d.clusters.len());
317291
            debug_info!(
53369
                self.ctx,
53369
                "[paint_node] node {} has inline_layout with {} items",
                node_index,
                logged_item_count
            );
317291
            if let Some(dom_id) = node.dom_node_id {
317131
                let node_type = &self.ctx.styled_dom.node_data.as_container()[dom_id];
317131
                debug_info!(
53239
                    self.ctx,
53239
                    "Painting inline content for node {} ({:?}) at {:?}, {} layout items",
                    node_index,
53239
                    node_type.get_node_type(),
                    paint_rect,
                    logged_item_count
                );
160
            }
            // paint_rect is the border-box, but inline layout positions are relative to
            // content-box. Use type-safe conversion to make this clear and avoid manual
            // calculations.
317291
            let border_box = BorderBoxRect(paint_rect);
317291
            let nbp = node.box_props.unpack();
317291
            let mut content_box_rect = border_box.to_content_box(&nbp.padding, &nbp.border).rect();
            // Save the viewport-sized content box for clipping BEFORE expanding
            // to full scroll content size. Text must be clipped to the viewport
            // when overflow is hidden/scroll/auto, not to the full content size.
317291
            let mut viewport_clip_rect = content_box_rect;
            // For scrollable containers, extend the content rect to the full content size.
            // The scroll frame handles clipping - we need to paint ALL content, not just
            // what fits in the viewport. Otherwise glyphs beyond the viewport are not rendered.
317291
            let content_size = get_scroll_content_size(node, node_warm);
317291
            if content_size.height > content_box_rect.size.height {
4273
                content_box_rect.size.height = content_size.height;
313018
            }
317291
            if content_size.width > content_box_rect.size.width {
4840
                content_box_rect.size.width = content_size.width;
312451
            }
            // An overflow-VISIBLE axis does not clip its own inline content:
            // the ink paints past the box and only the nearest clipping
            // ANCESTOR (scroll frame / overflow clip) bounds it. The tight
            // box here was wrong twice over for such a node — the renderer
            // paints those glyphs anyway, and `Text::visual_bounds()` clamps
            // its DAMAGE into this rect. After a text edit grew an IFC past
            // its stale box (`used_size` only catches up on the next
            // relayout), every moved line's pixels lay outside the clamp and
            // the incremental present never repainted them — the TextArea's
            // garbled-lines-below-the-Enter bug. Per axis: only an axis that
            // actually clips (hidden/scroll/auto) keeps the viewport bound;
            // a visible axis takes the full content extent computed above,
            // which `reshape_text_node` keeps fresh between relayouts.
317291
            if let Some(dom_id) = node.dom_node_id {
317131
                let st = self.get_styled_node_state(dom_id);
634262
                let clips = |ov: crate::solver3::getters::MultiValue<LayoutOverflow>| {
632796
                    matches!(
634198
                        ov,
                        crate::solver3::getters::MultiValue::Exact(
                            LayoutOverflow::Hidden | LayoutOverflow::Scroll | LayoutOverflow::Auto
                        )
                    )
634262
                };
317131
                if !clips(get_overflow_x(self.ctx.styled_dom, dom_id, &st)) {
316423
                    viewport_clip_rect.size.width = content_box_rect.size.width;
316423
                }
317131
                if !clips(get_overflow_y(self.ctx.styled_dom, dom_id, &st)) {
316373
                    viewport_clip_rect.size.height = content_box_rect.size.height;
316373
                }
160
            }
            // Check for text-shadow and wrap inline content with push/pop shadow
317291
            let mut pushed_text_shadow = false;
317291
            if let Some(dom_id) = node.dom_node_id {
317131
                let node_data = &self.ctx.styled_dom.node_data.as_container()[dom_id];
317131
                let node_state =
317131
                    &self.ctx.styled_dom.styled_nodes.as_container()[dom_id].styled_node_state;
317131
                if let Some(shadow_val) = self
317131
                    .ctx
317131
                    .styled_dom
317131
                    .css_property_cache
317131
                    .ptr
317131
                    .get_text_shadow(node_data, &dom_id, node_state)
                {
                    if let Some(shadow) = shadow_val.get_property() {
                        builder.push_item(DisplayListItem::PushTextShadow { shadow: (**shadow) });
                        pushed_text_shadow = true;
                    }
317131
                }
160
            }
317291
            self.paint_inline_content(
317291
                builder,
317291
                content_box_rect,
317291
                viewport_clip_rect,
317291
                inline_layout,
317291
                cached_layout.dense.as_deref(),
317291
                &cached_layout.payload,
317291
                &cached_layout.glyph_runs,
317291
                node_index,
            );
317291
            if pushed_text_shadow {
                builder.push_item(DisplayListItem::PopTextShadow);
317291
            }
444482
        } else if let Some(dom_id) = node.dom_node_id {
            // +spec:replaced-elements:edd21b - block-level replaced element painted atomically per
            // E.2 +spec:replaced-elements:516b2a - replaced content painted atomically
            // in painting order This node might be a simple replaced element, like an
            // <img> tag. Content resolves overlay→DOM: a runtime-swapped image or
            // produced callback frame (overlay) wins over the immutable DOM's ImageRef.
444481
            let node_data = &self.ctx.styled_dom.node_data.as_container()[dom_id];
444481
            if matches!(node_data.get_node_type(), NodeType::Image(_)) {
153
                if let Some(image_ref) = self.ctx.resolved_content().image_for_paint(dom_id) {
153
                    debug_info!(
122
                        self.ctx,
122
                        "Painting image for node {} at {:?}",
                        node_index,
                        paint_rect
                    );
                    // Get border-radius so the compositor can clip the image to rounded corners
153
                    let styled_node_state = self.get_styled_node_state(dom_id);
153
                    let element_size = PhysicalSizeImport {
153
                        width: paint_rect.size.width,
153
                        height: paint_rect.size.height,
153
                    };
153
                    let border_radius = get_border_radius(
153
                        self.ctx.styled_dom,
153
                        dom_id,
153
                        &styled_node_state,
153
                        element_size,
153
                        self.ctx.viewport_size,
                    );
                    // Store the ImageRef directly in the display list
153
                    builder.push_image(paint_rect, image_ref, border_radius);
                }
444328
            }
1
        }
761773
        Ok(())
761773
    }
    /// Paints the `placeholder` attribute's prompt for an EMPTY, unfocused
    /// contenteditable host: the host's own resolved style at half alpha,
    /// one line at the content-box origin, clipped to the content box.
    ///
    /// Deliberately NOT a DOM node: no hit area, no clusters, no focus
    /// participation, no show/hide state - the overlay-`<p>` design this
    /// replaces intercepted clicks meant for the editable and its
    /// imperative visibility toggles latched (`TextArea`'s prompt never
    /// returned after blur, 2026-08-31).
    #[cfg(feature = "text_layout")]
    #[allow(clippy::cast_precision_loss)]
762444
    fn maybe_paint_placeholder_prompt(
762444
        &self,
762444
        builder: &mut DisplayListBuilder,
762444
        node_index: usize,
762444
        paint_rect: &LogicalRect,
762444
    ) {
762444
        let Some(node) = self.positioned_tree.tree.get(LayoutNodeId::new(node_index)) else {
            return;
        };
762444
        let Some(dom_id) = node.dom_node_id else {
161
            return;
        };
762283
        let node_data = &self.ctx.styled_dom.node_data.as_container()[dom_id];
762283
        let Some(text) = node_data.get_placeholder() else {
761110
            return;
        };
1173
        if text.trim().is_empty() {
1110
            return;
63
        }
63
        if !super::getters::is_node_contenteditable_inherited(self.ctx.styled_dom, dom_id) {
            return;
63
        }
        // Only an EMPTY host shows its prompt, and "empty" is asked of the
        // CONTENT, not of the layout: an earlier version read
        // `inline_layout_result` and treated its ABSENCE as emptiness, so a
        // filled but defocused field painted the prompt UNDER its own text.
        //
        // The question is asked of the EDITING HOST, not of the node holding
        // the attribute. A live edit is recorded against the host (the
        // focused contenteditable container), while the attribute rides on
        // the value line inside it - so a check that only looked at the
        // attribute's node and its descendants never saw the text the user
        // had just typed, and the prompt painted over it (device report,
        // 2026-08-31). Walk UP to the host, then check the host and its
        // whole subtree, resolving overlay-then-DOM the way the a11y tree
        // and the exporters do, so an uncommitted edit counts immediately.
63
        let resolved = self.ctx.resolved_content();
63
        let hierarchy = self.ctx.styled_dom.node_hierarchy.as_container();
63
        let node_data = self.ctx.styled_dom.node_data.as_container();
63
        let host = {
63
            let mut h = dom_id;
            loop {
126
                if node_data
126
                    .get(h)
126
                    .is_some_and(azul_core::dom::NodeData::is_contenteditable)
                {
63
                    break h;
63
                }
63
                match hierarchy
63
                    .get(h)
63
                    .and_then(azul_core::styled_dom::NodeHierarchyItem::parent_id)
                {
63
                    Some(p) => h = p,
                    None => break dom_id,
                }
            }
        };
149
        let has_text = |n: NodeId| {
149
            resolved
149
                .text_for_node(n)
149
                .is_some_and(|t| !t.trim().is_empty())
149
        };
63
        let mut content_empty = !has_text(host);
63
        if content_empty {
43
            let mut stack = hierarchy
43
                .get(host)
43
                .and_then(|h| h.first_child_id(host))
43
                .into_iter()
43
                .collect::<Vec<_>>();
129
            while let Some(n) = stack.pop() {
86
                if has_text(n) {
                    content_empty = false;
                    break;
86
                }
86
                if let Some(h) = hierarchy.get(n) {
86
                    if let Some(c) = h.first_child_id(n) {
43
                        stack.push(c);
43
                    }
86
                    if let Some(sib) = h.next_sibling_id() {
                        stack.push(sib);
86
                    }
                }
            }
20
        }
63
        if !content_empty {
20
            return;
43
        }
        // Focus can sit ABOVE the prompt line (on the editable container) or
        // INSIDE the host (on the very line the pointer hit); either means the
        // field is being edited and the prompt stays hidden.
43
        if super::getters::is_focus_within_or_above(self.ctx.styled_dom, dom_id)
43
            || super::getters::is_focus_within_subtree(self.ctx.styled_dom, host)
        {
            return;
43
        }
43
        let bp = node.box_props.unpack();
43
        let content_box = BorderBoxRect(*paint_rect)
43
            .to_content_box(&bp.padding, &bp.border)
43
            .rect();
43
        if content_box.size.width <= 0.0 || content_box.size.height <= 0.0 {
            return;
43
        }
        // THE PROMPT'S OWN STYLE, through the real cascade: resolve the node
        // with `::placeholder` turned on, so author rules
        // (`.field::placeholder { color: ... }`) and the widgets' inline
        // `on_placeholder(...)` declarations both land here. Everything the
        // rule does not set falls back to the host's own value, which is why
        // an unstyled prompt still inherits the field's font.
43
        let style = Arc::new(super::getters::get_style_properties_for_state(
43
            self.ctx.styled_dom,
43
            dom_id,
43
            self.ctx.system_style.as_ref(),
43
            azul_css::props::basic::PhysicalSize {
43
                width: self.ctx.viewport_size.width,
43
                height: self.ctx.viewport_size.height,
43
            },
43
            &{
43
                let mut st = self.get_styled_node_state(dom_id);
43
                st.placeholder = true;
43
                st
43
            },
        ));
        // Whether the cascade actually said anything about the prompt's
        // colour. If it did not, the engine keeps its own default (the
        // host's colour at half alpha) rather than painting the value's
        // full-strength colour on top of nothing.
43
        let prompt_color_declared = self
43
            .ctx
43
            .styled_dom
43
            .css_property_cache
43
            .ptr
43
            .get_text_color(
43
                &self.ctx.styled_dom.node_data.as_container()[dom_id],
43
                &dom_id,
43
                &{
43
                    let mut st = self.get_styled_node_state(dom_id);
43
                    st.placeholder = true;
43
                    st
43
                },
43
            )
43
            .is_some();
43
        let loaded_fonts = self.ctx.font_manager.get_loaded_fonts();
43
        let glyphs = crate::text3::cache::shape_placeholder_text(
43
            text,
43
            &style,
43
            &self.ctx.font_manager.font_chain_cache,
43
            &self.ctx.font_manager.fc_cache,
43
            &loaded_fonts,
        );
43
        if glyphs.is_empty() {
            return;
43
        }
        // A declared `::placeholder` colour is used verbatim. With none, the
        // default is the host's own colour at half alpha - readable on any
        // theme, with no second colour channel to keep in sync.
43
        let color = if prompt_color_declared {
43
            style.color
        } else {
            ColorU {
                a: style.color.a / 2,
                ..style.color
            }
        };
        // One line at the content-box origin: baseline = origin + scaled
        // ascent of the first glyph's face.
43
        let first = &glyphs[0];
43
        let upem = f32::from(first.font_metrics.units_per_em.max(1));
43
        let baseline_y =
43
            content_box.origin.y + first.font_metrics.ascent / upem * style.font_size_px;
        // Split into per-font runs (fallback can mix faces).
43
        let mut pen_x = content_box.origin.x;
43
        let mut run: Vec<GlyphInstance> = Vec::with_capacity(glyphs.len());
43
        let mut run_hash = first.font_hash;
660
        for g in &glyphs {
617
            if g.font_hash != run_hash && !run.is_empty() {
                builder.push_text_run(
                    core::mem::take(&mut run),
                    FontHash {
                        font_hash: run_hash,
                    },
                    style.font_size_px,
                    color,
                    content_box,
                    None,
                    None,
                );
                run_hash = g.font_hash;
617
            }
617
            run.push(GlyphInstance {
617
                index: u32::from(g.glyph_id),
617
                point: LogicalPosition {
617
                    x: pen_x + g.offset.x,
617
                    y: baseline_y - g.offset.y,
617
                },
617
                size: LogicalSize::zero(),
617
            });
617
            pen_x += g.advance + g.kerning;
        }
43
        if !run.is_empty() {
43
            builder.push_text_run(
43
                run,
43
                FontHash {
43
                    font_hash: run_hash,
43
                },
43
                style.font_size_px,
43
                color,
43
                content_box,
43
                None,
43
                None,
43
            );
43
        }
762444
    }
    #[cfg(not(feature = "text_layout"))]
    fn maybe_paint_placeholder_prompt(
        &self,
        _builder: &mut DisplayListBuilder,
        _node_index: usize,
        _paint_rect: &LogicalRect,
    ) {
    }
    /// Emits drawing commands for scrollbars. This is called AFTER popping the scroll frame
    /// clip so scrollbars appear on top of content and are not clipped.
    #[allow(clippy::too_many_lines)] // large but cohesive: single-purpose layout/render/parse
                                     // routine (one branch per case)
762444
    fn paint_scrollbars(&self, builder: &mut DisplayListBuilder, node_index: usize) -> Result<()> {
        // CSS 2.2 §11.2: visibility:hidden scroll containers must not paint scrollbars,
        // but their layout space is preserved (already handled by layout).
762444
        if self.is_node_hidden(node_index) {
            return Ok(());
762444
        }
762444
        let node = self
762444
            .positioned_tree
762444
            .tree
762444
            .get(LayoutNodeId::new(node_index))
762444
            .ok_or(LayoutError::InvalidTree)?;
762444
        let Some(paint_rect) = self.get_paint_rect(node_index) else {
            return Ok(());
        };
        // Check if we need to draw scrollbars for this node.
762444
        let mut scrollbar_info = self
762444
            .positioned_tree
762444
            .tree
762444
            .warm(LayoutNodeId::new(node_index))
762444
            .and_then(|w| w.scrollbar_info)
762444
            .unwrap_or_default();
        // Get node_id for GPU cache lookup and CSS style lookup
762444
        let node_id = node.dom_node_id;
        // A VirtualView is a replaced element with NO flow content, so the
        // layout-side necessity test (`check_scrollbar_necessity`: laid-out
        // content > container) can never fire for it and `overflow: auto` would
        // stay bar-less no matter how large the virtualized document is. The
        // virtual size does reach the display list — the ScrollManager puts the
        // callback's `virtual_scroll_size` into `ScrollPosition::children_rect`,
        // which the thumb geometry below already prefers — so decide from that,
        // through the one function that owns the rule.
        //
        // The answer cannot simply be read off `warm.scrollbar_info` here:
        // `register_scroll_nodes` writes the same amendment back into the tree
        // for the GPU/hit-test consumers, but it runs AFTER this display list is
        // built, and the layout pass that precedes this one has already
        // recomputed `warm.scrollbar_info` from the laid-out sizes.
762444
        if let Some(nid) = node_id {
762283
            if std::env::var("AZ_VV_BAR_TRACE").is_ok()
                && self
                    .ctx
                    .styled_dom
                    .node_data
                    .as_container()
                    .get(nid)
                    .is_some_and(azul_core::dom::NodeData::is_virtual_view_node)
            {
                eprintln!(
                    "[vv-bar] nid={nid:?} offsets_hit={} n_offsets={} \
                     reqs_before={scrollbar_info:?}",
                    self.scroll_offsets.contains_key(&nid),
                    self.scroll_offsets.len(),
                );
762283
            }
762283
            if let Some(pos) = self.scroll_offsets.get(&nid) {
1583
                let bp = node.box_props.unpack();
1583
                let border = &bp.border;
1583
                let padding_box_size = LogicalSize::new(
1583
                    (paint_rect.size.width - border.left - border.right).max(0.0),
1583
                    (paint_rect.size.height - border.top - border.bottom).max(0.0),
                );
1583
                let raised = crate::solver3::cache::apply_virtual_scroll_necessity(
1583
                    self.ctx.styled_dom,
1583
                    nid,
1583
                    pos.children_rect.size,
1583
                    padding_box_size,
1583
                    &mut scrollbar_info,
                );
1583
                if std::env::var("AZ_VV_BAR_TRACE").is_ok() {
                    eprintln!(
                        "[vv-bar] nid={nid:?} raised={raised} virt={:?} \
                         padbox={padding_box_size:?} reqs_after={scrollbar_info:?}",
                        pos.children_rect.size,
                    );
1583
                }
760700
            }
161
        }
        // Get CSS scrollbar style for this node (cached per LayoutContext).
762444
        let scrollbar_style = node_id
762444
            .map(|nid| {
762283
                let node_state =
762283
                    &self.ctx.styled_dom.styled_nodes.as_container()[nid].styled_node_state;
762283
                crate::solver3::getters::get_scrollbar_style_cached(self.ctx, nid, node_state)
762283
            })
762444
            .unwrap_or_default();
        // Skip if scrollbar-width: none
762024
        if matches!(
762444
            scrollbar_style.width_mode,
            azul_css::props::style::scrollbar::LayoutScrollbarWidth::None
        ) {
420
            return Ok(());
762024
        }
        // +spec:overflow:3dfb2c - when scrollbar gutter is present but scrollbar is not,
        // paint the gutter background as an extension of the padding
762024
        let scrollbar_gutter = node_id
762024
            .and_then(|nid| {
761863
                let node_state =
761863
                    &self.ctx.styled_dom.styled_nodes.as_container()[nid].styled_node_state;
761863
                get_scrollbar_gutter_property(self.ctx.styled_dom, nid, node_state).exact()
761863
            })
762024
            .unwrap_or_default();
762024
        let gutter_is_stable = matches!(
762024
            scrollbar_gutter,
            azul_css::props::layout::overflow::StyleScrollbarGutter::Stable
                | azul_css::props::layout::overflow::StyleScrollbarGutter::StableBothEdges
        );
762024
        let gutter_both_edges = matches!(
762024
            scrollbar_gutter,
            azul_css::props::layout::overflow::StyleScrollbarGutter::StableBothEdges
        );
762024
        if gutter_is_stable {
            let gbp = node.box_props.unpack();
            let border = &gbp.border;
            let gutter_width = scrollbar_style.visual_width_px;
            // Paint gutter as padding extension when scrollbar is absent
            let bg_color = node_id.map_or(ColorU::TRANSPARENT, |nid| {
                let node_state =
                    &self.ctx.styled_dom.styled_nodes.as_container()[nid].styled_node_state;
                get_background_color(self.ctx.styled_dom, nid, node_state)
            });
            if !scrollbar_info.needs_vertical && gutter_width > 0.0 {
                // Right-side gutter (inline-end)
                let gutter_rect = LogicalRect {
                    origin: LogicalPosition::new(
                        paint_rect.origin.x + paint_rect.size.width - border.right - gutter_width,
                        paint_rect.origin.y + border.top,
                    ),
                    size: LogicalSize::new(
                        gutter_width,
                        (paint_rect.size.height - border.top - border.bottom).max(0.0),
                    ),
                };
                builder.push_rect(gutter_rect, bg_color, BorderRadius::default());
                // Both-edges: also paint left-side gutter (inline-start)
                if gutter_both_edges {
                    let left_gutter_rect = LogicalRect {
                        origin: LogicalPosition::new(
                            paint_rect.origin.x + border.left,
                            paint_rect.origin.y + border.top,
                        ),
                        size: LogicalSize::new(
                            gutter_width,
                            (paint_rect.size.height - border.top - border.bottom).max(0.0),
                        ),
                    };
                    builder.push_rect(left_gutter_rect, bg_color, BorderRadius::default());
                }
            }
762024
        }
        // Get border dimensions to position scrollbar inside the border-box
762024
        let sbp = node.box_props.unpack();
762024
        let border = &sbp.border;
        // Get border-radius for potential clipping
762024
        let container_border_radius = node_id
762024
            .map(|nid| {
761863
                let node_state =
761863
                    &self.ctx.styled_dom.styled_nodes.as_container()[nid].styled_node_state;
761863
                let element_size = PhysicalSizeImport {
761863
                    width: paint_rect.size.width,
761863
                    height: paint_rect.size.height,
761863
                };
761863
                let viewport_size =
761863
                    LogicalSize::new(self.ctx.viewport_size.width, self.ctx.viewport_size.height);
761863
                get_border_radius(
761863
                    self.ctx.styled_dom,
761863
                    nid,
761863
                    node_state,
761863
                    element_size,
761863
                    viewport_size,
                )
761863
            })
762024
            .unwrap_or_default();
        // Calculate the inner rect (content-box) where scrollbars should be placed
        // Scrollbars are positioned inside the border, at the right/bottom edges
762024
        let inner_rect = LogicalRect {
762024
            origin: LogicalPosition::new(
762024
                paint_rect.origin.x + border.left,
762024
                paint_rect.origin.y + border.top,
762024
            ),
762024
            size: LogicalSize::new(
762024
                (paint_rect.size.width - border.left - border.right).max(0.0),
762024
                (paint_rect.size.height - border.top - border.bottom).max(0.0),
762024
            ),
762024
        };
        // Get scroll position for thumb calculation.
        // `children_rect.origin` IS the scroll offset (see
        // `ScrollManager::get_scroll_states_for_dom`); `parent_rect.origin` is
        // an ABSOLUTE window coordinate, so subtracting it here mixed two
        // spaces and started the thumb `container.y` px down its own track for
        // any scroller not at the window origin. The GPU-only scroll path
        // (`GpuStateManager::update_scrollbar_transforms`) feeds the raw
        // `current_offset` into the same geometry fn — these two MUST agree,
        // because the transform written here is the initial value of the key
        // that path later overwrites.
762024
        let (scroll_offset_x, scroll_offset_y) = node_id
762024
            .and_then(|nid| {
761863
                self.scroll_offsets
761863
                    .get(&nid)
761863
                    .map(|pos| (pos.children_rect.origin.x, pos.children_rect.origin.y))
761863
            })
762024
            .unwrap_or((0.0, 0.0));
        // Get content size for thumb proportional sizing
        // Use the node's get_content_size() method which returns the actual content size
        // from overflow_content_size (set during layout) or computes it from text/children.
        // For VirtualView nodes, the virtual_scroll_size (propagated through
        // ScrollPosition.children_rect) is more accurate than the layout-computed content
        // size.
762024
        let content_size = node_id
762024
            .and_then(|nid| self.scroll_offsets.get(&nid))
762024
            .map_or_else(
760611
                || {
760611
                    self.positioned_tree
760611
                        .tree
760611
                        .get_content_size(LayoutNodeId::new(node_index))
760611
                },
                |pos| pos.children_rect.size,
            );
        // The HANDLE's own width, which is not the groove's: Breeze centres a
        // 6px handle in a 21px groove, and Adwaita/macOS inset theirs too.
        // Filling the groove made every azul scrollbar read as a fat pill next
        // to a native one. `None` keeps the old fill-the-groove behaviour.
762024
        let handle_width = scrollbar_style
762024
            .handle_width_px
762024
            .unwrap_or(scrollbar_style.visual_width_px)
762024
            .min(scrollbar_style.visual_width_px)
762024
            .max(1.0);
        // How far in from each side the handle sits, so it stays centred.
762024
        let handle_inset = ((scrollbar_style.visual_width_px - handle_width) / 2.0).max(0.0);
        // Radius comes from the platform; a capsule is the fallback, not a law.
762024
        let thumb_radius = scrollbar_style
762024
            .handle_radius_px
762024
            .unwrap_or(handle_width / 2.0)
762024
            .max(0.0);
762024
        let thumb_border_radius = BorderRadius {
762024
            top_left: thumb_radius,
762024
            top_right: thumb_radius,
762024
            bottom_left: thumb_radius,
762024
            bottom_right: thumb_radius,
762024
        };
762024
        if scrollbar_info.needs_vertical {
            // Look up opacity key from GPU cache for GPU-animated opacity.
            // If a key already exists in the cache from a previous frame, reuse it.
            // Otherwise, create a new unique key. The key will be registered
            // in the GPU cache after layout_document returns (same pattern as
            // transform keys). This ensures the display list ALWAYS has an
            // opacity binding, so GPU-only scroll updates can animate it.
1031
            let opacity_key = node_id.map(|nid| {
1031
                self.gpu_value_cache
1031
                    .and_then(|cache| {
1031
                        cache
1031
                            .scrollbar_v_opacity_keys
1031
                            .get(&(self.dom_id, nid))
1031
                            .copied()
1031
                    })
1031
                    .unwrap_or_else(OpacityKey::unique)
1031
            });
            // Vertical scrollbar: use shared geometry computation
1031
            let button_size = if scrollbar_style.show_scroll_buttons {
751
                scrollbar_style.scroll_button_size_px
            } else {
280
                0.0
            };
1031
            let v_geom = compute_scrollbar_geometry_with_button_size(
1031
                ScrollbarOrientation::Vertical,
1031
                inner_rect,
1031
                content_size,
1031
                scroll_offset_y,
1031
                scrollbar_style.visual_width_px,
1031
                scrollbar_info.needs_horizontal,
1031
                button_size,
            );
            // Position thumb after the top button; GPU transform moves it within usable track
            // Inset horizontally so the handle is CENTRED in the groove
            // rather than filling it (Breeze: 6px handle, 21px groove).
1031
            let thumb_bounds = LogicalRect {
1031
                origin: LogicalPosition::new(
1031
                    v_geom.track_rect.origin.x + handle_inset,
1031
                    v_geom.track_rect.origin.y + v_geom.button_size,
1031
                ),
1031
                size: LogicalSize::new(
1031
                    (v_geom.width_px - 2.0 * handle_inset).max(1.0),
1031
                    v_geom.thumb_length,
1031
                ),
1031
            };
            // Look up transform key from GPU cache for GPU-animated thumb positioning.
            // If a key already exists in the cache from a previous frame, reuse it.
            // Otherwise, create a new unique key. The key will be registered
            // in the GPU cache after layout_document returns.
1031
            let thumb_transform_key = node_id.map(|nid| {
1031
                self.gpu_value_cache
1031
                    .and_then(|cache| cache.transform_keys.get(&nid).copied())
1031
                    .unwrap_or_else(TransformKey::unique)
1031
            });
            // Initial transform: translate thumb within usable region.
            // Quantised — see `quantize_thumb_offset`; the GPU updater that
            // overwrites this value rounds identically.
1031
            let thumb_initial_transform = ComputedTransform3D::new_translation(
                0.0,
1031
                crate::solver3::scrollbar::quantize_thumb_offset(v_geom.thumb_offset),
                0.0,
            );
            // Generate hit-test ID for vertical scrollbar thumb
1031
            let hit_id = node_id
1031
                .map(|nid| azul_core::hit_test::ScrollbarHitId::VerticalThumb(self.dom_id, nid));
            // Buttons at top/bottom of track (only if enabled in style)
1031
            let (button_decrement_bounds, button_increment_bounds) =
1031
                if scrollbar_style.show_scroll_buttons && v_geom.button_size > 0.0 {
751
                    (
751
                        Some(LogicalRect {
751
                            origin: v_geom.track_rect.origin,
751
                            size: LogicalSize::new(v_geom.button_size, v_geom.button_size),
751
                        }),
751
                        Some(LogicalRect {
751
                            origin: LogicalPosition::new(
751
                                v_geom.track_rect.origin.x,
751
                                v_geom.track_rect.origin.y + v_geom.track_rect.size.height
751
                                    - v_geom.button_size,
751
                            ),
751
                            size: LogicalSize::new(v_geom.button_size, v_geom.button_size),
751
                        }),
751
                    )
                } else {
280
                    (None, None)
                };
1031
            builder.push_scrollbar_styled(ScrollbarDrawInfo {
1031
                bounds: v_geom.track_rect.into(),
1031
                orientation: ScrollbarOrientation::Vertical,
1031
                track_bounds: v_geom.track_rect.into(),
1031
                track_color: scrollbar_style.track_color,
1031
                thumb_bounds: thumb_bounds.into(),
1031
                thumb_color: scrollbar_style.thumb_color,
1031
                thumb_border_radius,
1031
                button_decrement_bounds: button_decrement_bounds.map(Into::into),
1031
                button_increment_bounds: button_increment_bounds.map(Into::into),
1031
                button_color: scrollbar_style.button_color,
1031
                opacity_key,
1031
                thumb_transform_key,
1031
                thumb_initial_transform,
1031
                hit_id,
1031
                clip_to_container_border: scrollbar_style.clip_to_container_border,
1031
                container_border_radius,
1031
                visibility: scrollbar_style.visibility,
1031
            });
760993
        }
762024
        if scrollbar_info.needs_horizontal {
            // Look up horizontal opacity key from GPU cache (same pattern as vertical).
223
            let opacity_key = node_id.map(|nid| {
223
                self.gpu_value_cache
223
                    .and_then(|cache| {
223
                        cache
223
                            .scrollbar_h_opacity_keys
223
                            .get(&(self.dom_id, nid))
223
                            .copied()
223
                    })
223
                    .unwrap_or_else(OpacityKey::unique)
223
            });
            // Horizontal scrollbar: use shared geometry computation
223
            let h_button_size = if scrollbar_style.show_scroll_buttons {
223
                scrollbar_style.scroll_button_size_px
            } else {
                0.0
            };
223
            let h_geom = compute_scrollbar_geometry_with_button_size(
223
                ScrollbarOrientation::Horizontal,
223
                inner_rect,
223
                content_size,
223
                scroll_offset_x,
223
                scrollbar_style.visual_width_px,
223
                scrollbar_info.needs_vertical,
223
                h_button_size,
            );
            // Position thumb after the left button; GPU transform moves it within usable track
            // Same inset on the other axis: the handle is centred in the groove.
223
            let thumb_bounds = LogicalRect {
223
                origin: LogicalPosition::new(
223
                    h_geom.track_rect.origin.x + h_geom.button_size,
223
                    h_geom.track_rect.origin.y + handle_inset,
223
                ),
223
                size: LogicalSize::new(
223
                    h_geom.thumb_length,
223
                    (h_geom.width_px - 2.0 * handle_inset).max(1.0),
223
                ),
223
            };
            // Look up horizontal transform key from GPU cache for GPU-animated thumb positioning.
223
            let thumb_transform_key = node_id.map(|nid| {
223
                self.gpu_value_cache
223
                    .and_then(|cache| cache.h_transform_keys.get(&nid).copied())
223
                    .unwrap_or_else(TransformKey::unique)
223
            });
223
            let thumb_initial_transform = ComputedTransform3D::new_translation(
223
                crate::solver3::scrollbar::quantize_thumb_offset(h_geom.thumb_offset),
                0.0,
                0.0,
            );
            // Generate hit-test ID for horizontal scrollbar thumb
223
            let hit_id = node_id
223
                .map(|nid| azul_core::hit_test::ScrollbarHitId::HorizontalThumb(self.dom_id, nid));
            // Buttons at left/right of track (only if enabled in style)
223
            let (button_decrement_bounds, button_increment_bounds) =
223
                if scrollbar_style.show_scroll_buttons && h_geom.button_size > 0.0 {
223
                    (
223
                        Some(LogicalRect {
223
                            origin: h_geom.track_rect.origin,
223
                            size: LogicalSize::new(h_geom.button_size, h_geom.button_size),
223
                        }),
223
                        Some(LogicalRect {
223
                            origin: LogicalPosition::new(
223
                                h_geom.track_rect.origin.x + h_geom.track_rect.size.width
223
                                    - h_geom.button_size,
223
                                h_geom.track_rect.origin.y,
223
                            ),
223
                            size: LogicalSize::new(h_geom.button_size, h_geom.button_size),
223
                        }),
223
                    )
                } else {
                    (None, None)
                };
223
            builder.push_scrollbar_styled(ScrollbarDrawInfo {
223
                bounds: h_geom.track_rect.into(),
223
                orientation: ScrollbarOrientation::Horizontal,
223
                track_bounds: h_geom.track_rect.into(),
223
                track_color: scrollbar_style.track_color,
223
                thumb_bounds: thumb_bounds.into(),
223
                thumb_color: scrollbar_style.thumb_color,
223
                thumb_border_radius,
223
                button_decrement_bounds: button_decrement_bounds.map(Into::into),
223
                button_increment_bounds: button_increment_bounds.map(Into::into),
223
                button_color: scrollbar_style.button_color,
223
                opacity_key,
223
                thumb_transform_key,
223
                thumb_initial_transform,
223
                hit_id,
223
                clip_to_container_border: scrollbar_style.clip_to_container_border,
223
                container_border_radius,
223
                visibility: scrollbar_style.visibility,
223
            });
761801
        }
762024
        Ok(())
762444
    }
    /// Converts the rich layout information from `text3` into drawing commands.
    #[allow(clippy::suboptimal_flops)] // mul_add not guaranteed faster/available without target +fma; keep explicit a*b+c
    #[allow(clippy::too_many_lines)] // large but cohesive: single-purpose layout/render/parse
                                     // routine (one branch per case)
317291
    fn paint_inline_content(
317291
        &self,
317291
        builder: &mut DisplayListBuilder,
317291
        container_rect: LogicalRect,
317291
        viewport_clip_rect: LogicalRect,
317291
        layout: &Arc<UnifiedLayout>,
317291
        dense_view: Option<&crate::text3::dense::DenseText>,
317291
        payload: &Arc<dyn std::any::Any + Send + Sync>,
317291
        glyph_runs: &[crate::text3::glyphs::CompactGlyphRun],
317291
        source_node_index: usize,
317291
    ) {
317291
        let _p = crate::probe::Probe::span("dl_inline_text");
        // TODO: This will always paint images over the glyphs
        // TODO: Handle z-index within inline content (e.g. background images)
        // NOTE: Text decorations (underline, strikethrough, overline) are handled in
        // push_text_layout_to_display_list TODO: Text shadows not yet implemented
        // NOTE: Text-overflow ellipsis is handled via apply_text_overflow_ellipsis()
        // which can be called as a post-processing step on the display list when
        // the node has overflow:hidden and text-overflow:ellipsis CSS properties.
        // +spec:overflow:7807b1 - text-overflow ellipsis side depends on direction (RTL clips left,
        // LTR clips right); not yet implemented +spec:overflow:bbf9c1 - text-overflow
        // ellipsis should only truncate content that is actually clipped; as content
        // scrolls into view, show it instead of ellipsis TODO: Handle text overflowing
        // (based on container_rect and overflow behavior)
        // Calculate actual content bounds from the layout
        // Use these bounds instead of container_rect to avoid inflated bounds
        // that extend beyond actual text content
        // (d6h) Sentinel-aware: bounds() over the empty retirement
        // sentinel gated EVERY TextLayout DL item off — textless PDF
        // export and missing a11y metadata (caught by
        // dom_to_pdf_embeds_text_fonts under the d7 default flip). The
        // dense extent is the same math as the scroll-extent arm.
317291
        let layout_bounds = if layout.items.is_empty() {
316582
            match dense_view.filter(|d| !d.clusters.is_empty()) {
316286
                Some(d) => {
316286
                    let w = d
316286
                        .clusters
316286
                        .iter()
16853537
                        .map(|c| c.x + c.advance)
316286
                        .fold(0.0f32, f32::max);
316286
                    let h = d
316286
                        .lines
316286
                        .iter()
578556
                        .map(|l| l.top_y + l.height)
316286
                        .fold(0.0f32, f32::max);
316286
                    crate::text3::cache::Rect {
316286
                        x: 0.0,
316286
                        y: 0.0,
316286
                        width: w,
316286
                        height: h,
316286
                    }
                }
296
                None => layout.bounds(),
            }
        } else {
709
            layout.bounds()
        };
317291
        let actual_bounds = if layout_bounds.width > 0.0 && layout_bounds.height > 0.0 {
316984
            LogicalRect {
316984
                origin: container_rect.origin,
316984
                size: LogicalSize {
316984
                    width: layout_bounds.width,
316984
                    height: layout_bounds.height,
316984
                },
316984
            }
        } else {
            // If layout has no content, don't push TextLayout item at all
            // This prevents 0x0 TextLayout items that pollute height calculation
307
            LogicalRect {
307
                origin: container_rect.origin,
307
                size: LogicalSize::default(),
307
            }
        };
        // Only push TextLayout if layout has actual content
        // This prevents empty TextLayout items with 0x0 bounds at various Y positions
        // from affecting pagination height calculations
        //
        // (#25 / user ruling 2026-08-12) AND only for PAGED (PDF-export)
        // display lists: `TextLayout` is the type-erased shaped-layout
        // payload printpdf's bridge and the font-embedding walk consume.
        // The screen renderers all no-op it (raster: "metadata for
        // PDF/accessibility — skip"; compositor2: logs and moves on), so
        // a screen DL was carrying one dead item + payload-Arc clone per
        // painted IFC. `fragmentation_context.is_some()` IS the
        // screen-vs-paged discriminator (paged entries own it; the window
        // path never sets it) — no new target input needed.
317291
        let is_paged_target = self.ctx.fragmentation_context.is_some();
317291
        if is_paged_target && (layout_bounds.width > 0.0 || layout_bounds.height > 0.0) {
            // The item-level font is the layout's PRIMARY font: the first
            // shaped glyph that resolved one. This used to be a hardcoded
            // `FontHash::from_hash(0)` placeholder ("will be updated per
            // glyph run" — nothing ever did), so every TextLayout shipped
            // `font_hash: 0`, and once `push_item` began dropping hash-0
            // TextLayouts as unresolved, ALL of them vanished — text
            // disappeared from the PDF export and a11y metadata. Per-glyph
            // consumers still read each glyph's own hash; staying at 0 here
            // is now reserved for a layout in which NO glyph resolved, which
            // is exactly the case the drop guard exists for.
            // §3.2 (d3): from the dense runs when retained (runs carry
            // font_hash + style directly; hash-0 runs = unresolved, skipped
            // exactly like the sparse scan). Falls back to the sparse walk
            // for mixed layouts or when no dense view is retained.
980
            let mut primary: Option<(u64, f32)> = None;
980
            if let Some(d) = dense_view {
                // (d6h) Sentinel-aware: empty stored items + non-empty
                // dense = the retirement form, dense is authoritative.
980
                if !d.clusters.is_empty()
955
                    && (layout.items.is_empty() || d.clusters.len() == layout.items.len())
                {
941
                    primary = d
941
                        .runs
941
                        .iter()
941
                        .find(|r| r.font_hash != 0)
941
                        .map(|r| (r.font_hash, r.style.font_size_px));
39
                }
            }
980
            if primary.is_none() {
43
                for positioned in &layout.items {
43
                    let (glyphs, arm_style) = match &positioned.item {
14
                        ShapedItem::Cluster(c) => (&c.glyphs, &c.style),
                        ShapedItem::CombinedBlock { glyphs, style, .. } => (glyphs, style),
29
                        _ => continue,
                    };
14
                    if let Some(g) = glyphs.iter().find(|g| g.font_hash != 0) {
14
                        primary = Some((g.font_hash, arm_style.font_size_px));
14
                        break;
                    }
                }
941
            }
980
            let (primary_hash, primary_size) = primary.unwrap_or((0, 12.0));
            // Clone the CACHED Arc, do not re-wrap a deep clone: TextLayout
            // damage diffing is Arc::ptr_eq, so a fresh Arc per rebuild made
            // every blink / tween tick repaint the whole text run (and deep-
            // cloned all shaped glyphs per frame). Real text changes replace
            // the cached Arc, so ptr_eq still fires damage then.
980
            builder.push_text_layout(
                // (d5) The CACHED payload Arc — TextPayload{dense,sparse}
                // when the dense view is retained, the bare layout Arc
                // otherwise. Cloned from the cache entry, so ptr_eq damage
                // diffing sees the same allocation across paints exactly
                // as before.
980
                payload.clone(),
980
                actual_bounds,
980
                FontHash::from_hash(primary_hash),
980
                primary_size,
980
                ColorU {
980
                    r: 0,
980
                    g: 0,
980
                    b: 0,
980
                    a: 255,
980
                }, // Default color
            );
316311
        }
        // Precomputed at CachedInlineLayout store time — the run-grouping
        // walk used to re-run here on EVERY paint of every IFC.
        // FIRST PASS: Render backgrounds (solid colors, gradients) and borders for each glyph run
        // This must happen BEFORE rendering text so that backgrounds appear behind text.
899393
        for glyph_run in glyph_runs {
            // Calculate the bounding box for this glyph run
582102
            if let (Some(first_glyph), Some(last_glyph)) =
582102
                (glyph_run.glyphs.first(), glyph_run.glyphs.last())
            {
                // Calculate run bounds from glyph positions
582102
                let run_start_x = container_rect.origin.x + first_glyph.point.x;
582102
                let run_end_x = container_rect.origin.x + last_glyph.point.x;
582102
                let run_width = (run_end_x - run_start_x).max(0.0);
                // Skip if run has no width
582102
                if run_width <= 0.0 {
2412
                    continue;
579690
                }
                // Approximate height based on font size (baseline is at glyph.point.y)
579690
                let baseline_y = container_rect.origin.y + first_glyph.point.y;
579690
                let font_size = glyph_run.font_size_px;
579690
                let ascent = font_size * APPROX_ASCENT_RATIO;
579690
                let mut run_bounds = LogicalRect::new(
579690
                    LogicalPosition::new(run_start_x, baseline_y - ascent),
579690
                    LogicalSize::new(run_width, font_size),
                );
                // Expand run_bounds by padding + border so the background/border
                // rect covers the full inline box, not just the glyph area.
579690
                if let Some(border) = &glyph_run.border {
3
                    let left_inset = border.left_inset();
3
                    let right_inset = border.right_inset();
3
                    let top_inset = border.top_inset();
3
                    let bottom_inset = border.bottom_inset();
3

            
3
                    run_bounds.origin.x -= left_inset;
3
                    run_bounds.origin.y -= top_inset;
3
                    run_bounds.size.width += left_inset + right_inset;
3
                    run_bounds.size.height += top_inset + bottom_inset;
579687
                }
579690
                builder.push_inline_backgrounds_and_border(
579690
                    run_bounds,
579690
                    glyph_run.background_color,
579690
                    &glyph_run.background_content,
579690
                    glyph_run.border.as_ref(),
579690
                    self.ctx.image_cache,
                );
            }
        }
        // The IFC-level background proof, refined per run below (a run
        // carrying its OWN background paints it directly underneath).
317291
        let ifc_uniform_bg = self.compute_uniform_text_bg(source_node_index);
        // The `::selection` recolour band, resolved once for the whole IFC.
317291
        let selection_recolour = self.selection_recolour_for_ifc(source_node_index);
        // SECOND PASS: Render text runs
899393
        for glyph_run in glyph_runs {
            // Clip text to the viewport-sized content box, not the full scroll
            // content area. This prevents text from overflowing outside the
            // container when overflow is hidden/scroll/auto.
582102
            let clip_rect = viewport_clip_rect;
            // Offset glyph positions by the container origin (text layout is
            // relative to (0,0) of the IFC). (#25) The runs are stored
            // compact; this expansion builds the same Vec the pre-#25 code
            // built by copy-then-offset — construct instead of memcpy.
582102
            let offset_glyphs: Vec<GlyphInstance> = glyph_run
582102
                .glyphs
582102
                .to_vec_offset(container_rect.origin.x, container_rect.origin.y);
            // Store only the font hash in the display list to keep it lean
582102
            let uniform_bg = if glyph_run.background_content.is_empty() {
                match glyph_run.background_color {
                    // A span's own opaque background covers only the run —
                    // no cheap proven-RECT for the fringe boundary here, so
                    // the run takes the sweep. (The common body-text case is
                    // "no span background" → the ancestor proof below.)
                    Some(c) if c.a == 255 => {
                        let _ = c;
                        None
                    }
                    Some(c) if c.a > 0 => None, // translucent span bg
582098
                    _ => ifc_uniform_bg,
                }
            } else {
4
                None // gradient/image span background — unprovable
            };
            // Colour is paint-only and deliberately excluded from the text
            // layout hash, so a cached run can outlive the cascade that
            // resolved its colour (the deactivated-ribbon-tab KNOWN GAP:
            // a colour-only change never re-lays the IFC owner, and the
            // baked value painted stale). Re-resolve against the CURRENT
            // cascade at build time; the baked colour only serves runs
            // without a source node (markers, synthesized content).
582102
            let live_color = glyph_run
582102
                .source_node_id
582102
                .and_then(|nid| {
580888
                    let sd = self.ctx.styled_dom;
580888
                    let styled_nodes = sd.styled_nodes.as_container();
580888
                    if nid.index() >= styled_nodes.len() {
                        return None;
580888
                    }
580888
                    let cache = &sd.css_property_cache.ptr;
580888
                    let node_data = sd.node_data.as_container();
                    // ANCESTOR USER OVERRIDES participate in inheritance: an
                    // `animation: color ..` transition overrides `color` on a
                    // CONTAINER, and the precomputed inherited tables cannot
                    // see it — the text painted the stale colour (found by
                    // the css_anim_perf_transition damage law: the "colour
                    // transition" repainted nothing). Walk self -> root: the
                    // nearest override wins unless a closer node declares its
                    // OWN colour, which re-roots inheritance below it.
580888
                    let hierarchy = sd.node_hierarchy.as_container();
580888
                    let ty = azul_css::props::property::CssPropertyType::TextColor;
580888
                    let mut cur = Some(nid);
2281641
                    while let Some(n) = cur {
1
                        if let Some(azul_css::props::property::CssProperty::TextColor(v)) =
1766542
                            cache.get_user_override(&n, &ty)
                        {
1
                            if let Some(c) = v.get_property() {
1
                                return Some(c.inner);
                            }
                            break;
1766541
                        }
1766541
                        if n.index() < node_data.len()
1766541
                            && cache.has_own_declaration(&node_data[n], &n, &ty)
                        {
65788
                            break;
1700753
                        }
1700753
                        cur = hierarchy
1700753
                            .get(n)
1700753
                            .and_then(azul_core::styled_dom::NodeHierarchyItem::parent_id);
                    }
580887
                    let node_state = &styled_nodes[nid].styled_node_state;
                    // No declared `color` anywhere up the chain: the UA default
                    // applies, and that default depends on the theme. Black is
                    // right on a light window and invisible on a dark one. The
                    // themed default is CASCADED (the root's `cascaded_props`,
                    // every descendant's `computed_values`, the compact text
                    // tier), so on a cascaded DOM `get_text_color` answers it
                    // here; the fallback below re-derives it from the context
                    // only for a DOM no UA pass has run on, and asserts that.
                    Some(
580887
                        cache
580887
                            .get_text_color(&node_data[nid], &nid, node_state)
580887
                            .and_then(|c| c.get_property().copied())
580887
                            .unwrap_or_else(|| {
                                debug_assert!(
                                    !cache.ua_applied,
                                    "live_color: node {} has no `color` in its resolved style \
                                     although the UA pass ran — the themed root default did \
                                     not reach it (theme-chain analysis 2026-09-12, R1)",
                                    nid.index()
                                );
                                // The SAME context the cascade evaluated this
                                // DOM against — which carries the window's own
                                // theme — not a fresh system-only one: the two
                                // used to disagree after an in-app theme switch,
                                // leaving the widgets dark and the text black.
                                let ctx = cache.dynamic_context.as_deref().cloned().unwrap_or_else(|| {
                                    self.ctx.system_style.as_ref().map_or_else(
                                        azul_css::dynamic_selector::DynamicSelectorContext::default,
                                        |s| {
                                            azul_css::dynamic_selector::DynamicSelectorContext::from_system_style(s)
                                        },
                                    )
                                });
                                azul_core::ua_css::evaluate_ua_root_text_color(&ctx)
                            })
                            .inner,
                    )
580888
                })
582102
                .unwrap_or(glyph_run.color);
582102
            match &selection_recolour {
210
                Some((rects, selected_color)) => {
                    // A glyph's `point` is its pen position ON THE BASELINE at
                    // the left edge of its advance. A selection rect covers
                    // [start_x, end_x) of the clusters it spans and the whole
                    // line box vertically, so the origin of a selected glyph
                    // falls inside it while the origin of the first glyph
                    // AFTER the selection sits exactly on its right edge —
                    // hence the half-open x test. (A zero-advance mark sitting
                    // exactly on the right edge stays unselected; it is one
                    // combining mark at the very end of a selection.)
3140
                    let inside = |g: &GlyphInstance| {
3140
                        rects.iter().any(|r| {
3140
                            g.point.x >= r.min_x() - 0.5
2740
                                && g.point.x < r.max_x() - 0.5
1840
                                && g.point.y >= r.min_y()
1840
                                && g.point.y <= r.max_y()
3140
                        })
3140
                    };
210
                    let (selected, normal): (Vec<GlyphInstance>, Vec<GlyphInstance>) =
210
                        offset_glyphs.into_iter().partition(inside);
210
                    if !normal.is_empty() {
170
                        builder.next_text_selection_colors = Some((live_color, *selected_color));
170
                        builder.push_text_run(
170
                            normal,
170
                            FontHash::from_hash(glyph_run.font_hash),
170
                            glyph_run.font_size_px,
170
                            live_color,
170
                            clip_rect,
170
                            Some(source_node_index),
170
                            uniform_bg,
170
                        );
170
                    }
210
                    if !selected.is_empty() {
210
                        builder.next_text_selection_colors = Some((live_color, *selected_color));
210
                        builder.push_text_run(
210
                            selected,
210
                            FontHash::from_hash(glyph_run.font_hash),
210
                            glyph_run.font_size_px,
210
                            *selected_color,
210
                            clip_rect,
210
                            Some(source_node_index),
210
                            // The proven background under a selected glyph is
210
                            // the HIGHLIGHT, not the ancestor's colour.
210
                            None,
210
                        );
210
                    }
                }
581892
                None => {
581892
                    builder.push_text_run(
581892
                        offset_glyphs,
581892
                        FontHash::from_hash(glyph_run.font_hash),
581892
                        glyph_run.font_size_px,
581892
                        live_color,
581892
                        clip_rect,
581892
                        Some(source_node_index),
581892
                        uniform_bg,
581892
                    );
581892
                }
            }
            // Render text decorations if present OR if this is IME composition preview
582102
            let needs_underline = glyph_run.text_decoration.underline || glyph_run.is_ime_preview;
582102
            let needs_strikethrough = glyph_run.text_decoration.strikethrough;
582102
            let needs_overline = glyph_run.text_decoration.overline;
582102
            if needs_underline || needs_strikethrough || needs_overline {
                // Calculate the bounding box for this glyph run
420
                if let (Some(first_glyph), Some(last_glyph)) =
420
                    (glyph_run.glyphs.first(), glyph_run.glyphs.last())
                {
420
                    let decoration_start_x = container_rect.origin.x + first_glyph.point.x;
420
                    let decoration_end_x = container_rect.origin.x + last_glyph.point.x;
420
                    let decoration_width = decoration_end_x - decoration_start_x;
                    // Use font metrics to determine decoration positions
                    // Standard ratios based on CSS specification
420
                    let font_size = glyph_run.font_size_px;
420
                    let thickness = (font_size * APPROX_UNDERLINE_THICKNESS_RATIO).max(1.0);
                    // Baseline is at glyph.point.y
420
                    let baseline_y = container_rect.origin.y + first_glyph.point.y;
420
                    if needs_underline {
420
                        // Underline is typically 10-15% below baseline
420
                        // IME composition always gets underlined
420
                        let underline_y = baseline_y + (font_size * APPROX_UNDERLINE_OFFSET_RATIO);
420
                        let underline_bounds = LogicalRect::new(
420
                            LogicalPosition::new(decoration_start_x, underline_y),
420
                            LogicalSize::new(decoration_width, thickness),
420
                        );
420
                        builder.push_underline(underline_bounds, glyph_run.color, thickness);
420
                    }
420
                    if needs_strikethrough {
                        // Strikethrough is typically 40% above baseline (middle of x-height)
                        let strikethrough_y =
                            baseline_y - (font_size * APPROX_STRIKETHROUGH_OFFSET_RATIO);
                        let strikethrough_bounds = LogicalRect::new(
                            LogicalPosition::new(decoration_start_x, strikethrough_y),
                            LogicalSize::new(decoration_width, thickness),
                        );
                        builder.push_strikethrough(
                            strikethrough_bounds,
                            glyph_run.color,
                            thickness,
                        );
420
                    }
420
                    if needs_overline {
                        // Overline is typically at cap-height (75% above baseline)
                        let overline_y = baseline_y - (font_size * APPROX_OVERLINE_OFFSET_RATIO);
                        let overline_bounds = LogicalRect::new(
                            LogicalPosition::new(decoration_start_x, overline_y),
                            LogicalSize::new(decoration_width, thickness),
                        );
                        builder.push_overline(overline_bounds, glyph_run.color, thickness);
420
                    }
                }
581682
            }
        }
        // THIRD PASS: Generate hit-test areas for text runs
        // This enables cursor resolution directly on text nodes instead of their containers
899393
        for glyph_run in glyph_runs {
            // Only generate hit-test areas for runs with a source node id
582102
            let Some(source_node_id) = glyph_run.source_node_id else {
1214
                continue;
            };
            // Calculate the bounding box for this glyph run
580888
            if let (Some(first_glyph), Some(last_glyph)) =
580888
                (glyph_run.glyphs.first(), glyph_run.glyphs.last())
            {
580888
                let run_start_x = container_rect.origin.x + first_glyph.point.x;
580888
                let run_end_x = container_rect.origin.x + last_glyph.point.x;
580888
                let run_width = (run_end_x - run_start_x).max(0.0);
                // Skip if run has no width
580888
                if run_width <= 0.0 {
2362
                    continue;
578526
                }
                // Calculate run bounds using font metrics
578526
                let baseline_y = container_rect.origin.y + first_glyph.point.y;
578526
                let font_size = glyph_run.font_size_px;
578526
                let ascent = font_size * APPROX_ASCENT_RATIO;
578526
                let run_bounds = LogicalRect::new(
578526
                    LogicalPosition::new(run_start_x, baseline_y - ascent),
578526
                    LogicalSize::new(run_width, font_size),
                );
                // Query the cursor type for this text node from the CSS property cache
                // Default to Text cursor (I-beam) for text nodes
578526
                let cursor_type = self.get_cursor_type_for_text_node(source_node_id);
                // Construct the hit-test tag for cursor resolution
                // tag.0 = DomId (upper 32 bits) | NodeId (lower 32 bits)
                // tag.1 = TAG_TYPE_CURSOR | cursor_type
578526
                let tag_value =
578526
                    ((self.dom_id.inner as u64) << 32) | (source_node_id.index() as u64);
578526
                let tag_type = TAG_TYPE_CURSOR | (cursor_type as u16);
578526
                let tag_id = (tag_value, tag_type);
578526
                builder.push_hit_test_area(run_bounds, tag_id);
            }
        }
        // Render inline objects (images, shapes/inline-blocks, etc.)
        // These are positioned by the text3 engine and need to be rendered at their calculated
        // positions. §3.2 (d3): a pure-cluster layout (dense len == items
        // len) has no objects BY CONSTRUCTION — skip the walk entirely.
        // (d6h) Sentinel-aware: the retirement form (empty items, dense
        // non-empty) is pure-cluster by construction.
317291
        let pure_clusters = dense_view.is_some_and(|d| {
317291
            !d.clusters.is_empty()
316610
                && (layout.items.is_empty() || d.clusters.len() == layout.items.len())
317291
        });
317291
        if !pure_clusters {
6943
            for positioned_item in &layout.items {
6939
                self.paint_inline_object(builder, container_rect.origin, positioned_item);
6939
            }
316286
        }
317291
    }
    /// Paints a single inline object (image, shape, or inline-block)
6939
    fn paint_inline_object(
6939
        &self,
6939
        builder: &mut DisplayListBuilder,
6939
        base_pos: LogicalPosition,
6939
        positioned_item: &PositionedItem,
6939
    ) {
        let ShapedItem::Object {
391
            content, bounds, ..
6939
        } = &positioned_item.item
        else {
            // Other item types (e.g., breaks) don't produce painted output.
6548
            return;
        };
        // Calculate the absolute position of this object
        // positioned_item.position is relative to the container
391
        let object_bounds = LogicalRect::new(
391
            LogicalPosition::new(
391
                base_pos.x + positioned_item.position.x,
391
                base_pos.y + positioned_item.position.y,
            ),
391
            LogicalSize::new(bounds.width, bounds.height),
        );
391
        match content {
            InlineContent::Image(image) => {
                if let ImageSource::Node(image_node) = &image.source {
                    // Live overlay→DOM resolution: the IFC snapshotted only the
                    // NODE (see fc.rs), so a runtime image swap is visible on
                    // every DL build. Attribute the item to the image node —
                    // not the IFC root — so the chokepoint's in-place patch
                    // (`DisplayList::patch_node_image`) finds it.
                    if let Some(image_ref) =
                        self.ctx.resolved_content().image_for_paint(*image_node)
                    {
                        let prev_node = builder.current_node();
                        builder.set_current_node(Some(*image_node));
                        builder.push_image(object_bounds, image_ref, BorderRadius::default());
                        builder.set_current_node(prev_node);
                    }
                } else if let Some(image_ref) = get_image_ref_for_image_source(
                    &image.source,
                    self.ctx.image_cache,
                    object_bounds.size,
                ) {
                    builder.push_image(object_bounds, image_ref, BorderRadius::default());
                }
            }
391
            InlineContent::Shape(shape) => {
391
                self.paint_inline_shape(builder, object_bounds, shape, bounds);
391
            }
            _ => {}
        }
6939
    }
    // +spec:inline-block:a60a89 - inline-block painted atomically as pseudo-stacking-context per
    // E.2
    /// Paints an inline shape (inline-block background and border)
391
    fn paint_inline_shape(
391
        &self,
391
        builder: &mut DisplayListBuilder,
391
        object_bounds: LogicalRect,
391
        shape: &InlineShape,
391
        bounds: &crate::text3::cache::Rect,
391
    ) {
        // Render inline-block backgrounds and borders using their CSS styling
        // The text3 engine positions these correctly in the inline flow
391
        let Some(node_id) = shape.source_node_id else {
            return;
        };
        // If this inline-block establishes a stacking context, its background was
        // already painted by paint_node_background_and_border (called from
        // generate_for_stacking_context). Painting again here would cause
        // double-rendering. Skip it.
391
        if let Some(indices) = self.positioned_tree.tree.dom_to_layout.get(&node_id) {
391
            if let Some(&idx) = indices.first() {
391
                if self.establishes_stacking_context(idx.index()) {
                    return;
391
                }
            }
        }
391
        let styled_node_state =
391
            &self.ctx.styled_dom.styled_nodes.as_container()[node_id].styled_node_state;
        // Get all background layers (colors, gradients, images)
391
        let background_contents =
391
            get_background_contents(self.ctx.styled_dom, node_id, styled_node_state);
        // Get border information
391
        let border_info = get_border_info(self.ctx.styled_dom, node_id, styled_node_state);
        // FIX: object_bounds is the margin-box position from text3.
        // We need to convert to border-box for painting backgrounds/borders.
391
        let margins = self
391
            .positioned_tree
391
            .tree
391
            .dom_to_layout
391
            .get(&node_id)
391
            .map_or_else(crate::solver3::geometry::EdgeSizes::default, |indices| {
391
                indices
391
                    .first()
391
                    .map_or_else(crate::solver3::geometry::EdgeSizes::default, |&idx| {
391
                        self.positioned_tree.tree.nodes[idx.index()]
391
                            .box_props
391
                            .unpack()
391
                            .margin
391
                    })
391
            });
        // Convert margin-box bounds to border-box bounds
391
        let border_box_bounds = LogicalRect {
391
            origin: LogicalPosition {
391
                x: object_bounds.origin.x + margins.left,
391
                y: object_bounds.origin.y + margins.top,
391
            },
391
            size: LogicalSize {
391
                width: (object_bounds.size.width - margins.left - margins.right).max(0.0),
391
                height: (object_bounds.size.height - margins.top - margins.bottom).max(0.0),
391
            },
391
        };
391
        let element_size = PhysicalSizeImport {
391
            width: border_box_bounds.size.width,
391
            height: border_box_bounds.size.height,
391
        };
        // Get border radius for background clipping
391
        let simple_border_radius = get_border_radius(
391
            self.ctx.styled_dom,
391
            node_id,
391
            styled_node_state,
391
            element_size,
391
            self.ctx.viewport_size,
        );
        // Get style border radius for border rendering
391
        let style_border_radius =
391
            get_style_border_radius(self.ctx.styled_dom, node_id, styled_node_state);
        // Use unified background/border painting with border-box bounds
391
        builder.push_backgrounds_and_border(
391
            border_box_bounds,
391
            &background_contents,
391
            &border_info,
391
            simple_border_radius,
391
            style_border_radius,
391
            self.ctx.image_cache,
        );
        // Push hit-test area for this inline-block element
        // This is critical for buttons and other inline-block elements to receive
        // mouse events and display the correct cursor (e.g., cursor: pointer)
391
        if let Some(tag_id) = get_tag_id(self.ctx.styled_dom, Some(node_id)) {
213
            builder.push_hit_test_area(border_box_bounds, tag_id);
213
        }
391
    }
    // +spec:overflow:d1d5f6 - CSS 2.2 §9.9.1 stacking context creation and 7-layer paint order
    /// Determines if a node establishes a new stacking context based on CSS rules.
    // +spec:overflow:47b791 - z-index applies to positioned boxes; z-index:auto does not establish
    // stacking context +spec:positioning:8c6efd - Stacking contexts: positioned elements with
    // z-index != auto establish new stacking context +spec:positioning:b84cfa - z-index
    // stacking context creation: integer z-index on positioned elements creates SC; auto on
    // fixed/root creates SC +spec:positioning:d06368 - relative/absolute with z-index:auto do
    // not form stacking context but are painted as if they did
1496090
    fn establishes_stacking_context(&self, node_index: usize) -> bool {
1496090
        let Some(node) = self.positioned_tree.tree.get(LayoutNodeId::new(node_index)) else {
            return false;
        };
1496090
        let Some(dom_id) = node.dom_node_id else {
322
            return false;
        };
1495768
        let position = get_position_type(self.ctx.styled_dom, Some(dom_id));
1495768
        let z_auto = crate::solver3::getters::is_z_index_auto(self.ctx.styled_dom, Some(dom_id));
        // +spec:position-sticky:66ba22 - fixed and sticky positioned boxes form a stacking context
1495768
        if position == LayoutPosition::Fixed || position == LayoutPosition::Sticky {
            return true;
1495768
        }
        // +spec:positioning:d06368 - relative/absolute with z-index:auto do not form stacking
        // context z-index:auto on position:absolute does NOT establish stacking context
1495768
        if position == LayoutPosition::Absolute {
4816
            return !z_auto;
1490952
        }
        // position:relative with explicit z-index integer establishes stacking context
1490952
        if position == LayoutPosition::Relative && !z_auto {
            return true;
1490952
        }
1490952
        if let Some(styled_node) = self.ctx.styled_dom.styled_nodes.as_container().get(dom_id) {
1490952
            let node_data = &self.ctx.styled_dom.node_data.as_container()[dom_id];
1490952
            let node_state =
1490952
                &self.ctx.styled_dom.styled_nodes.as_container()[dom_id].styled_node_state;
            // Opacity < 1 (GPU: fast path via compact cache)
1490952
            if crate::solver3::getters::get_opacity(self.ctx.styled_dom, dom_id, node_state) < 1.0 {
186
                return true;
1490766
            }
            // Transform != none (GPU: has_transform bit check, then slow walk only if set)
2
            if let Some(t) =
1490766
                crate::solver3::getters::get_transform(self.ctx.styled_dom, dom_id, node_state)
            {
2
                if !t.is_empty() {
2
                    return true;
                }
1490764
            }
        }
1490764
        false
1496090
    }
}
/// Helper struct to pass layout results to the display list generator.
///
/// Combines the layout tree with pre-calculated absolute positions for each node.
/// The positions are stored separately because they are computed in a final
/// positioning pass after layout is complete.
#[derive(Debug)]
pub struct PositionedTree<'a> {
    /// The layout tree containing all nodes with their computed sizes
    pub tree: &'a LayoutTree,
    /// Map from node index to its absolute position in the document
    pub calculated_positions: &'a super::PositionVec,
}
/// Expands `clip_rect` outward by the `overflow-clip-margin` value on axes that use `overflow:
/// clip`.
///
/// Per CSS Overflow 3 §3.2, `overflow-clip-margin` only applies to `overflow: clip` —
/// it has no effect on `overflow: hidden`, `scroll`, or `auto`.
#[allow(clippy::trivially_copy_pass_by_ref)] // <=8B Copy param kept by-ref intentionally (hot
                                             // pixel/coord path or to avoid churning call sites for
                                             // a perf-neutral change)
8304
fn apply_overflow_clip_margin(
8304
    clip_rect: &mut LogicalRect,
8304
    overflow_x: &super::getters::MultiValue<LayoutOverflow>,
8304
    overflow_y: &super::getters::MultiValue<LayoutOverflow>,
8304
    styled_dom: &StyledDom,
8304
    dom_id: NodeId,
8304
    styled_node_state: &azul_core::styled_dom::StyledNodeState,
8304
) {
8304
    if !overflow_x.is_clip() && !overflow_y.is_clip() {
8304
        return;
    }
    let clip_margin = get_overflow_clip_margin_property(styled_dom, dom_id, styled_node_state);
    let Some(margin_val) = clip_margin.exact() else {
        return;
    };
    let m = margin_val.inner.to_pixels_internal(0.0, 0.0, 0.0).max(0.0);
    if m <= 0.0 {
        return;
    }
    if overflow_x.is_clip() {
        clip_rect.origin.x -= m;
        clip_rect.size.width += m * 2.0;
    }
    if overflow_y.is_clip() {
        clip_rect.origin.y -= m;
        clip_rect.size.height += m * 2.0;
    }
8304
}
5
fn get_scroll_id(id: Option<NodeId>) -> LocalScrollId {
5
    id.map_or(0, |i| i.index() as u64)
5
}
/// Calculates the actual content size of a node, including all children and text.
/// This is used to determine if scrollbars should appear for overflow: auto.
// +spec:overflow:c2ed94 - replaced element overflow is ink overflow (not scrollable);
// replaced elements (images) don't contribute scrollable overflow here
329389
fn get_scroll_content_size(node: &LayoutNodeHot, warm: Option<&LayoutNodeWarm>) -> LogicalSize {
    // The stored `overflow_content_size` participates but does NOT
    // early-return: it is a snapshot from some earlier pass, and for a node
    // whose IFC laid out after it was written (the absolutely positioned
    // placeholder <p> on the first device frame) it can be a few pixels
    // tall. The per-axis overflow-visible clip rescue takes THIS value as
    // the live extent, so the early return collapsed the placeholder's clip
    // to a strip of glyph tops until the next full restyle rebuilt it
    // (2026-08-31 first-draw report). Union it with the node size and the
    // live inline extent below - a cached scroll extent is not authoritative
    // for a node whose inline content is fresher.
329389
    let stored = warm.and_then(|w| w.overflow_content_size);
    // Start with the node's own size
329389
    let mut content_size = node.used_size.unwrap_or_default();
329389
    if let Some(st) = stored {
329356
        content_size.width = content_size.width.max(st.width);
329356
        content_size.height = content_size.height.max(st.height);
329356
    }
    // If this node has text layout, calculate the bounds of all text items
329389
    if let Some(cached_layout) = warm.and_then(|w| w.inline_layout_result.as_ref()) {
328056
        let text_layout = &cached_layout.layout;
        // §3.2 (d3): the extent from the DENSE arrays when retained and the
        // layout is pure clusters — width from base advances (== the sparse
        // bounds().width since d2), height from the d3-filled line heights.
        // Mixed layouts (objects/tabs) keep the sparse walk.
328056
        let dense_extent = cached_layout.dense.as_ref().and_then(|d| {
            // (d6h) Sentinel-aware: post-retirement the stored items are
            // EMPTY and dense IS the content — the old equality guard
            // read n != 0 and rejected the dense arm, zeroing the
            // extent (no scrollbar, dead caret-reveal; caught by
            // caret_scroll_glide under the d7 default flip). Mixed
            // layouts (flag-off with objects/tabs) still fall back.
328056
            if d.clusters.is_empty() {
974
                return None;
327082
            }
327082
            if !text_layout.items.is_empty() && d.clusters.len() != text_layout.items.len() {
450
                return None;
326632
            }
326632
            let max_x = d
326632
                .clusters
326632
                .iter()
17569440
                .map(|c| c.x + c.advance)
326632
                .fold(0.0f32, f32::max);
326632
            let max_y = d
326632
                .lines
326632
                .iter()
594478
                .map(|l| l.top_y + l.height)
326632
                .fold(0.0f32, f32::max);
326632
            Some((max_x, max_y))
328056
        });
328056
        let (max_x, max_y) = if let Some((dx, dy)) = dense_extent {
326632
            if std::env::var("AZ_DENSE_TEXT").as_deref() == Ok("verify") {
                let mut sx: f32 = 0.0;
                let mut sy: f32 = 0.0;
                for positioned_item in &text_layout.items {
                    let item_bounds = positioned_item.item.bounds();
                    sx = sx.max(positioned_item.position.x + item_bounds.width);
                    sy = sy.max(positioned_item.position.y + item_bounds.height);
                }
                assert!(
                    (sx - dx).abs() < 0.01 && (sy - dy).abs() < 0.01,
                    "d3 verify: scroll extent diverged (sparse {sx}x{sy} vs dense {dx}x{dy})"
                );
326632
            }
326632
            (dx, dy)
        } else {
1424
            let mut max_x: f32 = 0.0;
1424
            let mut max_y: f32 = 0.0;
8554
            for positioned_item in &text_layout.items {
8550
                let item_bounds = positioned_item.item.bounds();
8550
                let item_right = positioned_item.position.x + item_bounds.width;
8550
                let item_bottom = positioned_item.position.y + item_bounds.height;
8550
                max_x = max_x.max(item_right);
8550
                max_y = max_y.max(item_bottom);
8550
            }
1424
            (max_x, max_y)
        };
        // Use the maximum extent as content size if it's larger
328056
        content_size.width = content_size.width.max(max_x);
328056
        content_size.height = content_size.height.max(max_y);
1333
    }
329389
    content_size
329389
}
788245
fn get_tag_id(dom: &StyledDom, id: Option<NodeId>) -> Option<DisplayListTagId> {
788245
    let node_id = id?;
787994
    let tag_mapping = dom
787994
        .tag_ids_to_node_ids
787994
        .as_ref()
787994
        .iter()
84887125
        .find(|m| m.node_id.into_crate_internal() == Some(node_id))?;
379492
    Some((tag_mapping.tag_id.inner, TAG_TYPE_DOM_NODE))
788245
}
/// Resolve an [`ImageSource`] (as carried by an inline `InlineContent::Image`)
/// to a concrete [`ImageRef`] ready for `push_image`.
///
/// `target_size` is the object's logical box size, used only to size the raster
/// when rasterizing an SVG source.
#[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)] // bounded graphics/coord/font/
                                                                   // fixed-point/debug-marker cast
fn get_image_ref_for_image_source(
    source: &ImageSource,
    image_cache: &azul_core::resources::ImageCache,
    target_size: LogicalSize,
) -> Option<ImageRef> {
    match source {
        ImageSource::Ref(image_ref) => Some(image_ref.clone()),
        // Node-scoped content resolves through the overlay→DOM resolver, which
        // needs the LayoutContext — `paint_inline_object` handles that arm
        // BEFORE calling here. A caller without a resolver cannot paint it.
        ImageSource::Node(_) => None,
        ImageSource::Url(url) => {
            // CSS url() image — resolved exactly like `background-image`: look it
            // up in the ImageCache by its CSS id (see push_backgrounds_and_border).
            let css_id: azul_css::AzString = url.clone().into();
            image_cache.get_css_image_id(&css_id).cloned()
        }
        ImageSource::Data(bytes) => {
            // Encoded image bytes (PNG/JPEG/…): decode to a RawImage, then build
            // an ImageRef. The `decode` module is gated on `std` and the decoder
            // itself needs the `image` crate (`image_decoding`).
            #[cfg(all(feature = "std", feature = "image_decoding"))]
            {
                use crate::image::decode::{
                    decode_raw_image_from_any_bytes, ResultRawImageDecodeImageError,
                };
                if let ResultRawImageDecodeImageError::Ok(raw) =
                    decode_raw_image_from_any_bytes(bytes)
                {
                    return ImageRef::new_rawimage(raw);
                }
                None
            }
            #[cfg(not(all(feature = "std", feature = "image_decoding")))]
            {
                // The document handed us encoded image bytes and this build
                // cannot decode them — the image just vanishes. Say so once.
                static ANNOUNCE: std::sync::Once = std::sync::Once::new();
                ANNOUNCE.call_once(|| {
                    eprintln!(
                        "[azul][image] encoded image data present, but this build lacks the \
                         `image_decoding` (+`std`) feature — images from encoded bytes will NOT \
                         appear"
                    );
                });
                let _ = bytes;
                None
            }
        }
        ImageSource::Svg(svg) => {
            // Rasterize the SVG source to the object's box size using the CPU SVG
            // renderer. Needs the `cpurender` feature.
            #[cfg(feature = "cpurender")]
            {
                let w = (target_size.width.round() as u32).max(1);
                let h = (target_size.height.round() as u32).max(1);
                crate::cpurender::render_svg_to_imageref(svg.as_bytes(), w, h).ok()
            }
            #[cfg(not(feature = "cpurender"))]
            {
                // Inline SVG images rasterize through the CPU renderer; without
                // it they silently vanish from the frame. Say so once.
                static ANNOUNCE: std::sync::Once = std::sync::Once::new();
                ANNOUNCE.call_once(|| {
                    eprintln!(
                        "[azul][svg] an SVG image source is present, but this build has no \
                         `cpurender` feature — SVG images will NOT appear"
                    );
                });
                let _ = (svg, target_size);
                None
            }
        }
        ImageSource::Placeholder(_) => {
            // Layout-only placeholder: reserves space, paints nothing.
            None
        }
    }
}
/// Get the bounds of a display list item in window-logical coordinates.
137462
fn get_display_item_bounds(item: &DisplayListItem) -> Option<WindowLogicalRect> {
137462
    item.bounds().map(WindowLogicalRect::from)
137462
}
/// Clip a display list item to page bounds and offset to page-relative coordinates.
/// Returns None if the item is completely outside the page bounds.
#[allow(clippy::match_same_arms)]
// enum/value mapping/dispatch table: one arm per input variant (or cross-type bindings that can't
// merge)
#[allow(clippy::too_many_lines)] // large but cohesive: single-purpose layout/render/parse routine
                                 // (one branch per case)
23614
fn clip_and_offset_display_item(
23614
    item: &DisplayListItem,
23614
    page_top: f32,
23614
    page_bottom: f32,
23614
) -> Option<DisplayListItem> {
23614
    match item {
        // Pagination moves items between pages by translating their bounds.
        // A stroked path carries its geometry in USER SPACE and is mapped
        // into `bounds` by the renderer, so translating the box translates
        // the drawing with it - nothing else has to move.
        DisplayListItem::StrokedPath {
            bounds,
            path,
            view_box,
            color,
            width,
            mask,
        } => {
            let b = bounds.into_inner();
            if b.origin.y + b.size.height < page_top || b.origin.y > page_bottom {
                return None;
            }
            Some(DisplayListItem::StrokedPath {
                bounds: offset_rect_y(b, -page_top).into(),
                path: path.clone(),
                view_box: *view_box,
                color: *color,
                width: *width,
                mask: mask.clone(),
            })
        }
        DisplayListItem::Rect {
2233
            bounds,
2233
            color,
2233
            border_radius,
2233
        } => clip_rect_item(
2233
            bounds.into_inner(),
2233
            *color,
2233
            *border_radius,
2233
            page_top,
2233
            page_bottom,
        ),
        DisplayListItem::Border {
130
            bounds,
130
            widths,
130
            colors,
130
            styles,
130
            border_radius,
130
        } => clip_border_item(
130
            bounds.into_inner(),
130
            *widths,
130
            *colors,
130
            *styles,
130
            *border_radius,
130
            page_top,
130
            page_bottom,
        ),
        DisplayListItem::SelectionRect {
            bounds,
            border_radius,
            color,
        } => clip_selection_rect_item(
            bounds.into_inner(),
            *border_radius,
            *color,
            page_top,
            page_bottom,
        ),
        DisplayListItem::CursorRect { bounds, color } => {
            clip_cursor_rect_item(bounds.into_inner(), *color, page_top, page_bottom)
        }
        DisplayListItem::Image {
            bounds,
            image,
            border_radius,
        } => clip_image_item(
            bounds.into_inner(),
            image.clone(),
            *border_radius,
            page_top,
            page_bottom,
        ),
        DisplayListItem::TextLayout {
4870
            layout,
4870
            bounds,
4870
            font_hash,
4870
            font_size_px,
4870
            color,
4870
        } => clip_text_layout_item(
4870
            layout,
4870
            bounds.into_inner(),
4870
            *font_hash,
4870
            *font_size_px,
4870
            *color,
4870
            page_top,
4870
            page_bottom,
        ),
        DisplayListItem::Text {
5360
            glyphs,
5360
            font_hash,
5360
            font_size_px,
5360
            color,
5360
            clip_rect,
            ..
5360
        } => clip_text_item(
5360
            glyphs,
5360
            *font_hash,
5360
            *font_size_px,
5360
            *color,
5360
            clip_rect.into_inner(),
5360
            page_top,
5360
            page_bottom,
        ),
        DisplayListItem::Underline {
            bounds,
            color,
            thickness,
        } => clip_text_decoration_item(
            bounds.into_inner(),
            *color,
            *thickness,
            TextDecorationType::Underline,
            page_top,
            page_bottom,
        ),
        DisplayListItem::Strikethrough {
            bounds,
            color,
            thickness,
        } => clip_text_decoration_item(
            bounds.into_inner(),
            *color,
            *thickness,
            TextDecorationType::Strikethrough,
            page_top,
            page_bottom,
        ),
        DisplayListItem::Overline {
            bounds,
            color,
            thickness,
        } => clip_text_decoration_item(
            bounds.into_inner(),
            *color,
            *thickness,
            TextDecorationType::Overline,
            page_top,
            page_bottom,
        ),
        DisplayListItem::ScrollBar {
            bounds,
            color,
            orientation,
            opacity_key,
            hit_id,
        } => clip_scrollbar_item(
            bounds.into_inner(),
            *color,
            *orientation,
            *opacity_key,
            *hit_id,
            page_top,
            page_bottom,
        ),
10930
        DisplayListItem::HitTestArea { bounds, tag } => {
10930
            clip_hit_test_area_item(bounds.into_inner(), *tag, page_top, page_bottom)
        }
        DisplayListItem::VirtualView {
            child_dom_id,
            bounds,
            clip_rect,
            content_offset,
        } => clip_virtual_view_item(
            *child_dom_id,
            bounds.into_inner(),
            clip_rect.into_inner(),
            *content_offset,
            page_top,
            page_bottom,
        ),
        // ScrollBarStyled - clip based on overall bounds
        DisplayListItem::ScrollBarStyled { info } => {
            let bounds = info.bounds;
            if bounds.0.origin.y + bounds.0.size.height < page_top
                || bounds.0.origin.y > page_bottom
            {
                None
            } else {
                // Clone and offset all the internal bounds
                let mut clipped_info = (**info).clone();
                let y_offset = -page_top;
                clipped_info.bounds =
                    offset_rect_y(clipped_info.bounds.into_inner(), y_offset).into();
                clipped_info.track_bounds =
                    offset_rect_y(clipped_info.track_bounds.into_inner(), y_offset).into();
                clipped_info.thumb_bounds =
                    offset_rect_y(clipped_info.thumb_bounds.into_inner(), y_offset).into();
                if let Some(b) = clipped_info.button_decrement_bounds {
                    clipped_info.button_decrement_bounds =
                        Some(offset_rect_y(b.into_inner(), y_offset).into());
                }
                if let Some(b) = clipped_info.button_increment_bounds {
                    clipped_info.button_increment_bounds =
                        Some(offset_rect_y(b.into_inner(), y_offset).into());
                }
                Some(DisplayListItem::ScrollBarStyled {
                    info: Box::new(clipped_info),
                })
            }
        }
        // State management items - skip for now (would need proper per-page tracking)
        DisplayListItem::PushClip { .. }
        | DisplayListItem::PopClip
        | DisplayListItem::PushScrollFrame { .. }
        | DisplayListItem::PopScrollFrame
        | DisplayListItem::PushStackingContext { .. }
        | DisplayListItem::PopStackingContext
37
        | DisplayListItem::VirtualViewPlaceholder { .. } => None,
        // Gradient items - simple bounds check
        DisplayListItem::LinearGradient {
42
            bounds,
42
            gradient,
42
            border_radius,
        } => {
42
            if bounds.0.origin.y + bounds.0.size.height < page_top
41
                || bounds.0.origin.y > page_bottom
            {
1
                None
            } else {
41
                Some(DisplayListItem::LinearGradient {
41
                    bounds: offset_rect_y(bounds.into_inner(), -page_top).into(),
41
                    gradient: gradient.clone(),
41
                    border_radius: *border_radius,
41
                })
            }
        }
        DisplayListItem::RadialGradient {
10
            bounds,
10
            gradient,
10
            border_radius,
        } => {
10
            if bounds.0.origin.y + bounds.0.size.height < page_top
10
                || bounds.0.origin.y > page_bottom
            {
                None
            } else {
10
                Some(DisplayListItem::RadialGradient {
10
                    bounds: offset_rect_y(bounds.into_inner(), -page_top).into(),
10
                    gradient: gradient.clone(),
10
                    border_radius: *border_radius,
10
                })
            }
        }
        DisplayListItem::ConicGradient {
            bounds,
            gradient,
            border_radius,
        } => {
            if bounds.0.origin.y + bounds.0.size.height < page_top
                || bounds.0.origin.y > page_bottom
            {
                None
            } else {
                Some(DisplayListItem::ConicGradient {
                    bounds: offset_rect_y(bounds.into_inner(), -page_top).into(),
                    gradient: gradient.clone(),
                    border_radius: *border_radius,
                })
            }
        }
        // BoxShadow - simple bounds check
        DisplayListItem::BoxShadow {
            bounds,
            shadow,
            border_radius,
        } => {
            if bounds.0.origin.y + bounds.0.size.height < page_top
                || bounds.0.origin.y > page_bottom
            {
                None
            } else {
                Some(DisplayListItem::BoxShadow {
                    bounds: offset_rect_y(bounds.into_inner(), -page_top).into(),
                    shadow: *shadow,
                    border_radius: *border_radius,
                })
            }
        }
        // Filter effects - skip for now (would need proper per-page tracking)
        DisplayListItem::PushFilter { .. }
        | DisplayListItem::PopFilter
        | DisplayListItem::PushBackdropFilter { .. }
        | DisplayListItem::PopBackdropFilter
        | DisplayListItem::PushOpacity { .. }
        | DisplayListItem::PopOpacity
        | DisplayListItem::PushReferenceFrame { .. }
        | DisplayListItem::PopReferenceFrame
        | DisplayListItem::PushTextShadow { .. }
        | DisplayListItem::PopTextShadow
        | DisplayListItem::PushImageMaskClip { .. }
2
        | DisplayListItem::PopImageMaskClip => None,
    }
23614
}
// Helper functions for clip_and_offset_display_item
/// Internal enum for text decoration type dispatch
#[derive(Debug, Clone, Copy)]
enum TextDecorationType {
    Underline,
    Strikethrough,
    Overline,
}
/// Clips a filled rectangle to page bounds.
2235
fn clip_rect_item(
2235
    bounds: LogicalRect,
2235
    color: ColorU,
2235
    border_radius: BorderRadius,
2235
    page_top: f32,
2235
    page_bottom: f32,
2235
) -> Option<DisplayListItem> {
2235
    clip_rect_bounds(bounds, page_top, page_bottom).map(|clipped| DisplayListItem::Rect {
1331
        bounds: clipped.into(),
1331
        color,
1331
        border_radius,
1331
    })
2235
}
/// Clips a border to page bounds, hiding top/bottom borders when clipped.
131
fn clip_border_item(
131
    bounds: LogicalRect,
131
    widths: StyleBorderWidths,
131
    colors: StyleBorderColors,
131
    styles: StyleBorderStyles,
131
    border_radius: StyleBorderRadius,
131
    page_top: f32,
131
    page_bottom: f32,
131
) -> Option<DisplayListItem> {
131
    let original_bounds = bounds;
131
    clip_rect_bounds(bounds, page_top, page_bottom).map(|clipped| {
131
        let new_widths = adjust_border_widths_for_clipping(
131
            widths,
131
            original_bounds,
131
            clipped,
131
            page_top,
131
            page_bottom,
        );
131
        DisplayListItem::Border {
131
            bounds: clipped.into(),
131
            widths: new_widths,
131
            colors,
131
            styles,
131
            border_radius,
131
        }
131
    })
131
}
/// Adjusts border widths when a border is clipped at page boundaries.
/// Hides top border if clipped at top, bottom border if clipped at bottom.
133
fn adjust_border_widths_for_clipping(
133
    mut widths: StyleBorderWidths,
133
    original_bounds: LogicalRect,
133
    clipped: LogicalRect,
133
    page_top: f32,
133
    page_bottom: f32,
133
) -> StyleBorderWidths {
    // Hide top border if we clipped the top
133
    if clipped.origin.y > 0.0 && original_bounds.origin.y < page_top {
        widths.top = None;
133
    }
    // Hide bottom border if we clipped the bottom
133
    let original_bottom = original_bounds.origin.y + original_bounds.size.height;
133
    let clipped_bottom = clipped.origin.y + clipped.size.height;
133
    if original_bottom > page_bottom && clipped_bottom >= page_bottom - page_top - 1.0 {
1
        widths.bottom = None;
132
    }
133
    widths
133
}
/// Clips a selection rectangle to page bounds.
2
fn clip_selection_rect_item(
2
    bounds: LogicalRect,
2
    border_radius: BorderRadius,
2
    color: ColorU,
2
    page_top: f32,
2
    page_bottom: f32,
2
) -> Option<DisplayListItem> {
2
    clip_rect_bounds(bounds, page_top, page_bottom).map(|clipped| DisplayListItem::SelectionRect {
1
        bounds: clipped.into(),
1
        border_radius,
1
        color,
1
    })
2
}
/// Clips a cursor rectangle to page bounds.
2
fn clip_cursor_rect_item(
2
    bounds: LogicalRect,
2
    color: ColorU,
2
    page_top: f32,
2
    page_bottom: f32,
2
) -> Option<DisplayListItem> {
2
    clip_rect_bounds(bounds, page_top, page_bottom).map(|clipped| DisplayListItem::CursorRect {
1
        bounds: clipped.into(),
1
        color,
1
    })
2
}
/// Clips an image to page bounds if it overlaps the page.
2
fn clip_image_item(
2
    bounds: LogicalRect,
2
    image: ImageRef,
2
    border_radius: BorderRadius,
2
    page_top: f32,
2
    page_bottom: f32,
2
) -> Option<DisplayListItem> {
2
    if !rect_intersects(&bounds, page_top, page_bottom) {
1
        return None;
1
    }
1
    clip_rect_bounds(bounds, page_top, page_bottom).map(|clipped| DisplayListItem::Image {
1
        bounds: clipped.into(),
1
        image,
1
        border_radius,
1
    })
2
}
/// Clips a text layout block to page bounds, filtering individual text items.
4872
fn clip_text_layout_item(
4872
    layout: &Arc<dyn std::any::Any + Send + Sync>,
4872
    bounds: LogicalRect,
4872
    font_hash: FontHash,
4872
    font_size_px: f32,
4872
    color: ColorU,
4872
    page_top: f32,
4872
    page_bottom: f32,
4872
) -> Option<DisplayListItem> {
4872
    if !rect_intersects(&bounds, page_top, page_bottom) {
370
        return None;
4502
    }
    // (d5/d6h) TextPayload carries both forms. Post-retirement the
    // sparse half is the EMPTY sentinel — the clipper materializes the
    // items from the dense arrays on demand (transient, export-time
    // only; exactness pinned by the d6h expansion gate).
    #[cfg(feature = "text_layout")]
4502
    if let Some(p) = layout.downcast_ref::<crate::solver3::layout_tree::TextPayload>() {
4501
        if p.sparse.items.is_empty() && !p.dense.clusters.is_empty() {
4360
            let expanded = UnifiedLayout {
4360
                items: p.dense.to_unified_items(),
4360
                overflow: p.sparse.overflow.clone(),
4360
            };
4360
            return clip_unified_layout(
4360
                &expanded,
4360
                bounds,
4360
                font_hash,
4360
                font_size_px,
4360
                color,
4360
                page_top,
4360
                page_bottom,
            );
141
        }
141
        return clip_unified_layout(
141
            &p.sparse,
141
            bounds,
141
            font_hash,
141
            font_size_px,
141
            color,
141
            page_top,
141
            page_bottom,
        );
1
    }
    // Try to downcast and filter UnifiedLayout items
    #[cfg(feature = "text_layout")]
1
    if let Some(unified_layout) = layout.downcast_ref::<UnifiedLayout>() {
1
        return clip_unified_layout(
1
            unified_layout,
1
            bounds,
1
            font_hash,
1
            font_size_px,
1
            color,
1
            page_top,
1
            page_bottom,
        );
    }
    // Fallback: simple bounds offset (legacy behavior)
    Some(DisplayListItem::TextLayout {
        layout: layout.clone(),
        bounds: offset_rect_y(bounds, -page_top).into(),
        font_hash,
        font_size_px,
        color,
    })
4872
}
/// Clips a `UnifiedLayout` by filtering items to those on the current page.
#[cfg(feature = "text_layout")]
4502
fn clip_unified_layout(
4502
    unified_layout: &UnifiedLayout,
4502
    bounds: LogicalRect,
4502
    font_hash: FontHash,
4502
    font_size_px: f32,
4502
    color: ColorU,
4502
    page_top: f32,
4502
    page_bottom: f32,
4502
) -> Option<DisplayListItem> {
4502
    let layout_origin_y = bounds.origin.y;
4502
    let layout_origin_x = bounds.origin.x;
    // Filter items whose center falls within this page
4502
    let filtered_items: Vec<_> = unified_layout
4502
        .items
4502
        .iter()
37832
        .filter(|item| item_center_on_page(item, layout_origin_y, page_top, page_bottom))
4502
        .cloned()
4502
        .collect();
4502
    if filtered_items.is_empty() {
        return None;
4502
    }
    // Calculate new origin for page-relative positioning
4502
    let new_origin_y = (layout_origin_y - page_top).max(0.0);
    // Transform items to page-relative coordinates and calculate bounds
4502
    let (offset_items, min_y, max_y, max_width) =
4502
        transform_items_to_page_coords(filtered_items, layout_origin_y, page_top, new_origin_y);
4502
    let new_layout = UnifiedLayout {
4502
        items: offset_items,
4502
        overflow: unified_layout.overflow.clone(),
4502
    };
4502
    let new_bounds = LogicalRect {
4502
        origin: LogicalPosition {
4502
            x: layout_origin_x,
4502
            y: new_origin_y,
4502
        },
4502
        size: LogicalSize {
4502
            width: max_width.max(bounds.size.width),
4502
            height: (max_y - min_y.min(0.0)).max(0.0),
4502
        },
4502
    };
4502
    Some(DisplayListItem::TextLayout {
4502
        layout: Arc::new(new_layout),
4502
        bounds: new_bounds.into(),
4502
        font_hash,
4502
        font_size_px,
4502
        color,
4502
    })
4502
}
/// Checks if an item's center point falls within the page bounds.
#[cfg(feature = "text_layout")]
37839
fn item_center_on_page(
37839
    item: &PositionedItem,
37839
    layout_origin_y: f32,
37839
    page_top: f32,
37839
    page_bottom: f32,
37839
) -> bool {
37839
    let item_y_absolute = layout_origin_y + item.position.y;
37839
    let item_height = item.item.bounds().height;
37839
    let item_center_y = item_y_absolute + (item_height / 2.0);
37839
    item_center_y >= page_top && item_center_y < page_bottom
37839
}
/// Transforms filtered items to page-relative coordinates.
/// Returns (items, `min_y`, `max_y`, `max_width`).
#[cfg(feature = "text_layout")]
4504
fn transform_items_to_page_coords(
4504
    items: Vec<PositionedItem>,
4504
    layout_origin_y: f32,
4504
    page_top: f32,
4504
    new_origin_y: f32,
4504
) -> (Vec<PositionedItem>, f32, f32, f32) {
4504
    let mut min_y = f32::MAX;
4504
    let mut max_y = f32::MIN;
4504
    let mut max_width = 0.0f32;
4504
    let offset_items: Vec<_> = items
4504
        .into_iter()
37834
        .map(|mut item| {
37834
            let abs_y = layout_origin_y + item.position.y;
37834
            let page_y = abs_y - page_top;
37834
            let new_item_y = page_y - new_origin_y;
37834
            let item_bounds = item.item.bounds();
37834
            min_y = min_y.min(new_item_y);
37834
            max_y = max_y.max(new_item_y + item_bounds.height);
37834
            max_width = max_width.max(item.position.x + item_bounds.width);
37834
            item.position.y = new_item_y;
37834
            item
37834
        })
4504
        .collect();
4504
    (offset_items, min_y, max_y, max_width)
4504
}
/// Clips a text glyph run to page bounds, filtering individual glyphs.
5365
fn clip_text_item(
5365
    glyphs: &[GlyphInstance],
5365
    font_hash: FontHash,
5365
    font_size_px: f32,
5365
    color: ColorU,
5365
    clip_rect: LogicalRect,
5365
    page_top: f32,
5365
    page_bottom: f32,
5365
) -> Option<DisplayListItem> {
5365
    if !rect_intersects(&clip_rect, page_top, page_bottom) {
381
        return None;
4984
    }
    // Filter glyphs using center-point decision (baseline position)
4984
    let page_glyphs: Vec<_> = glyphs
4984
        .iter()
37638
        .filter(|g| g.point.y >= page_top && g.point.y < page_bottom)
4984
        .map(|g| GlyphInstance {
37632
            index: g.index,
37632
            point: LogicalPosition {
37632
                x: g.point.x,
37632
                y: g.point.y - page_top,
37632
            },
37632
            size: g.size,
37632
        })
4984
        .collect();
4984
    if page_glyphs.is_empty() {
3
        return None;
4981
    }
4981
    Some(DisplayListItem::Text {
4981
        glyphs: page_glyphs,
4981
        font_hash,
4981
        font_size_px,
4981
        color,
4981
        clip_rect: offset_rect_y(clip_rect, -page_top).into(),
4981
        source_node_index: None,
4981
    })
5365
}
/// Clips a text decoration (underline, strikethrough, or overline) to page bounds.
4
fn clip_text_decoration_item(
4
    bounds: LogicalRect,
4
    color: ColorU,
4
    thickness: f32,
4
    decoration_type: TextDecorationType,
4
    page_top: f32,
4
    page_bottom: f32,
4
) -> Option<DisplayListItem> {
4
    clip_rect_bounds(bounds, page_top, page_bottom).map(|clipped| match decoration_type {
1
        TextDecorationType::Underline => DisplayListItem::Underline {
1
            bounds: clipped.into(),
1
            color,
1
            thickness,
1
        },
1
        TextDecorationType::Strikethrough => DisplayListItem::Strikethrough {
1
            bounds: clipped.into(),
1
            color,
1
            thickness,
1
        },
1
        TextDecorationType::Overline => DisplayListItem::Overline {
1
            bounds: clipped.into(),
1
            color,
1
            thickness,
1
        },
3
    })
4
}
/// Clips a scrollbar to page bounds.
2
fn clip_scrollbar_item(
2
    bounds: LogicalRect,
2
    color: ColorU,
2
    orientation: ScrollbarOrientation,
2
    opacity_key: Option<OpacityKey>,
2
    hit_id: Option<azul_core::hit_test::ScrollbarHitId>,
2
    page_top: f32,
2
    page_bottom: f32,
2
) -> Option<DisplayListItem> {
2
    clip_rect_bounds(bounds, page_top, page_bottom).map(|clipped| DisplayListItem::ScrollBar {
1
        bounds: clipped.into(),
1
        color,
1
        orientation,
1
        opacity_key,
1
        hit_id,
1
    })
2
}
/// Clips a hit test area to page bounds.
10932
fn clip_hit_test_area_item(
10932
    bounds: LogicalRect,
10932
    tag: DisplayListTagId,
10932
    page_top: f32,
10932
    page_bottom: f32,
10932
) -> Option<DisplayListItem> {
10932
    clip_rect_bounds(bounds, page_top, page_bottom).map(|clipped| DisplayListItem::HitTestArea {
10361
        bounds: clipped.into(),
10361
        tag,
10361
    })
10932
}
/// Clips a virtualized view to page bounds.
2
fn clip_virtual_view_item(
2
    child_dom_id: DomId,
2
    bounds: LogicalRect,
2
    clip_rect: LogicalRect,
2
    content_offset: LogicalPosition,
2
    page_top: f32,
2
    page_bottom: f32,
2
) -> Option<DisplayListItem> {
2
    clip_rect_bounds(bounds, page_top, page_bottom).map(|clipped| DisplayListItem::VirtualView {
1
        child_dom_id,
1
        bounds: clipped.into(),
1
        clip_rect: offset_rect_y(clip_rect, -page_top).into(),
        // A page break moves the BOX, not the window the content sits in.
1
        content_offset,
1
    })
2
}
/// Clip a rectangle to page bounds and offset to page-relative coordinates.
/// Returns None if the rectangle is completely outside the page.
13326
fn clip_rect_bounds(bounds: LogicalRect, page_top: f32, page_bottom: f32) -> Option<LogicalRect> {
13326
    let item_top = bounds.origin.y;
13326
    let item_bottom = bounds.origin.y + bounds.size.height;
    // Check if completely outside page
13326
    if item_bottom <= page_top || item_top >= page_bottom {
1485
        return None;
11841
    }
    // Calculate clipped bounds
11841
    let clipped_top = item_top.max(page_top);
11841
    let clipped_bottom = item_bottom.min(page_bottom);
11841
    let clipped_height = clipped_bottom - clipped_top;
    // Offset to page-relative coordinates
11841
    let page_relative_y = clipped_top - page_top;
11841
    Some(LogicalRect {
11841
        origin: LogicalPosition {
11841
            x: bounds.origin.x,
11841
            y: page_relative_y,
11841
        },
11841
        size: LogicalSize {
11841
            width: bounds.size.width,
11841
            height: clipped_height,
11841
        },
11841
    })
13326
}
/// Check if a rectangle intersects the page bounds.
10252
fn rect_intersects(bounds: &LogicalRect, page_top: f32, page_bottom: f32) -> bool {
10252
    let item_top = bounds.origin.y;
10252
    let item_bottom = bounds.origin.y + bounds.size.height;
10252
    item_bottom > page_top && item_top < page_bottom
10252
}
/// Paint the two draggable selection handles of the primary range (U2-a).
///
/// The geometry is the same rule `LayoutWindow::selection_handle_geometry`
/// hit-tests against - a circle of `SELECTION_HANDLE_RADIUS` hanging under
/// the bottom corner of the caret rect at each end - so the thing the user
/// sees is the thing the press finds. The rects come from
/// `get_selection_rects`, whose first rect starts at the range's first
/// character and whose last rect ends at its last, in document order
/// whichever way the range was dragged.
///
/// The colour is the `::selection` background at full alpha: the handle is
/// a solid object the finger targets, and a translucent one over text reads
/// as more highlight.
130
fn paint_selection_handles(
130
    builder: &mut DisplayListBuilder,
130
    layout: &UnifiedLayout,
130
    text_selection: &azul_core::selection::TextSelection,
130
    content_box_offset_x: f32,
130
    content_box_offset_y: f32,
130
    selection_color: ColorU,
130
) {
    use azul_core::selection::SelectionRange;
    use crate::managers::text_edit::{SelectionHandleEnd, SelectionHandleGeometry};
130
    let primary = SelectionRange {
130
        start: text_selection.anchor.cursor,
130
        end: text_selection.focus.cursor,
130
    };
130
    let rects = layout.get_selection_rects(&primary);
130
    let (Some(first), Some(last)) = (rects.first(), rects.last()) else {
        return;
    };
130
    let color = ColorU {
130
        a: 255,
130
        ..selection_color
130
    };
130
    let radius = crate::managers::text_edit::SELECTION_HANDLE_RADIUS;
130
    let border_radius = BorderRadius {
130
        top_left: radius,
130
        top_right: radius,
130
        bottom_left: radius,
130
        bottom_right: radius,
130
    };
260
    for handle in [
130
        SelectionHandleGeometry::under(
130
            SelectionHandleEnd::Start,
130
            first.origin.x + content_box_offset_x,
130
            first.origin.y + first.size.height + content_box_offset_y,
        ),
130
        SelectionHandleGeometry::under(
130
            SelectionHandleEnd::End,
130
            last.origin.x + last.size.width + content_box_offset_x,
130
            last.origin.y + last.size.height + content_box_offset_y,
        ),
260
    ] {
260
        builder.push_selection_rect(handle.circle(), color, border_radius);
260
    }
130
}
/// The alpha a remote participant's selection fill is drawn at.
///
/// An owner colour is picked to be legible as a CARET - a 1px opaque bar - so
/// it is saturated and fully opaque. Filling a text run with that same colour
/// would hide the text behind it, which defeats the point of showing where
/// somebody else is working. 40% is the range every desktop editor's
/// collaborator highlight lands in, and leaves dark text readable through it.
pub const REMOTE_SELECTION_ALPHA: u8 = 0x66;
/// A remote participant's owner colour, turned into a fill that text stays
/// readable through.
///
/// Takes the MINIMUM of the two alphas rather than assigning
/// `REMOTE_SELECTION_ALPHA` outright: an app that deliberately picked a faint
/// colour for a participant asked for it to be faint, and this must not make
/// it louder.
#[must_use]
42
pub fn remote_selection_tint(owner_color: ColorU) -> ColorU {
42
    ColorU {
42
        a: owner_color.a.min(REMOTE_SELECTION_ALPHA),
42
        ..owner_color
42
    }
42
}
/// Offset a rectangle's Y coordinate.
5060
fn offset_rect_y(bounds: LogicalRect, offset_y: f32) -> LogicalRect {
5060
    LogicalRect {
5060
        origin: LogicalPosition {
5060
            x: bounds.origin.x,
5060
            y: bounds.origin.y + offset_y,
5060
        },
5060
        size: bounds.size,
5060
    }
5060
}
// Slicer based pagination: "Infinite Canvas with Clipping"
//
// This approach treats pages as "viewports" into a single infinite canvas:
//
// 1. Layout generates ONE display list on an infinite vertical strip
// 2. Each page is a clip rectangle that "views" a portion of that strip
// 3. Items that span page boundaries are clipped and appear on BOTH pages
use azul_css::props::layout::fragmentation::{BreakInside, PageBreak};
use crate::solver3::{
    page_breaks::{self, BreakPolicy},
    pagination::{
        HeaderFooterConfig, MarginBoxContent, PageInfo, TableHeaderInfo, TableHeaderTracker,
    },
};
/// Configuration for the slicer-based pagination.
#[derive(Debug, Clone, Default)]
pub struct SlicerConfig {
    /// Height of each page's content area (excludes margins, headers, footers)
    pub page_content_height: f32,
    /// Height of "dead zone" between pages (for margins, headers, footers)
    /// This represents space that content should NOT overlap with
    pub page_gap: f32,
    /// Whether to clip items that span page boundaries (true) or push them to next page (false)
    pub allow_clipping: bool,
    /// Header and footer configuration
    pub header_footer: HeaderFooterConfig,
    /// Width of the page content area (for centering headers/footers)
    pub page_width: f32,
    /// Table headers that need repetition across pages
    pub table_headers: TableHeaderTracker,
    /// Break-awareness policy (all-off default = plain interval slicing).
    pub break_policy: BreakPolicy,
    /// office-suite-style per-page setup (default + overrides + parity). `None`
    /// = every page uses `header_footer` / `page_content_height` uniformly.
    pub page_sequence: Option<crate::solver3::pagination::PageSequence>,
}
impl SlicerConfig {
    /// Create a simple slicer config with no gaps between pages.
    #[must_use]
23
    pub fn simple(page_height: f32) -> Self {
23
        Self {
23
            page_content_height: page_height,
23
            page_gap: 0.0,
23
            allow_clipping: true,
23
            header_footer: HeaderFooterConfig::default(),
23
            page_width: DEFAULT_A4_WIDTH_PT, // Default A4 width in points
23
            table_headers: TableHeaderTracker::default(),
23
            break_policy: BreakPolicy::default(),
23
            page_sequence: None,
23
        }
23
    }
    /// Create a slicer config with margins/gaps between pages.
    #[must_use]
6
    pub fn with_gap(page_height: f32, gap: f32) -> Self {
6
        Self {
6
            page_content_height: page_height,
6
            page_gap: gap,
6
            allow_clipping: true,
6
            header_footer: HeaderFooterConfig::default(),
6
            page_width: DEFAULT_A4_WIDTH_PT,
6
            table_headers: TableHeaderTracker::default(),
6
            break_policy: BreakPolicy::default(),
6
            page_sequence: None,
6
        }
6
    }
    /// Set the break-awareness policy.
    #[must_use]
    pub const fn with_break_policy(mut self, policy: BreakPolicy) -> Self {
        self.break_policy = policy;
        self
    }
    /// Add header/footer configuration.
    #[must_use]
    pub fn with_header_footer(mut self, config: HeaderFooterConfig) -> Self {
        self.header_footer = config;
        self
    }
    /// Set the page width (for header/footer positioning).
    #[must_use]
1
    pub const fn with_page_width(mut self, width: f32) -> Self {
1
        self.page_width = width;
1
        self
1
    }
    /// Add table headers for repetition.
    #[must_use]
    pub fn with_table_headers(mut self, tracker: TableHeaderTracker) -> Self {
        self.table_headers = tracker;
        self
    }
    /// Register a single table header.
    pub fn register_table_header(&mut self, info: TableHeaderInfo) {
        self.table_headers.register_table_header(info);
    }
    /// The total height of a page "slot" including the gap.
    #[must_use]
73
    pub fn page_slot_height(&self) -> f32 {
73
        self.page_content_height + self.page_gap
73
    }
    /// Calculate which page a Y coordinate falls on.
    #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)] // bounded graphics/coord/font/fixed-point/debug-marker cast
    #[must_use]
27
    pub fn page_for_y(&self, y: f32) -> usize {
27
        if self.page_slot_height() <= 0.0 {
6
            return 0;
21
        }
21
        (y / self.page_slot_height()).floor() as usize
27
    }
    /// Get the Y range for a specific page (in infinite canvas coordinates).
    #[allow(clippy::cast_precision_loss)] // bounded graphics/coord/font/fixed-point/debug-marker cast
    #[must_use]
17
    pub fn page_bounds(&self, page_index: usize) -> (f32, f32) {
17
        let start = page_index as f32 * self.page_slot_height();
17
        let end = start + self.page_content_height;
17
        (start, end)
17
    }
}
/// Paginate with CSS break property support.
///
/// This function calculates page boundaries based on CSS break-before, break-after,
/// and break-inside properties, then clips content to those boundaries.
///
/// **Key insight**: Items are NEVER shifted. Instead, page boundaries are adjusted
/// to honor break properties.
#[allow(clippy::too_many_lines)] // large but cohesive: single-purpose layout/render/parse routine (one branch per case)
/// # Errors
///
/// Returns a `LayoutError` if paginating the display list fails.
8
pub fn paginate_display_list_with_slicer_and_breaks(
8
    full_display_list: DisplayList,
8
    config: &SlicerConfig,
8
    renderer_resources: &RendererResources,
8
) -> Result<Vec<DisplayList>> {
8
    if config.page_content_height <= 0.0 || config.page_content_height >= f32::MAX {
4
        return Ok(vec![full_display_list]);
4
    }
    // Step 1: Calculate page break positions based on CSS properties
    // (forced break-before/after positions + regular interval breaks).
4
    let constraints = page_breaks::PageConstraints::from_slicer_config(config);
4
    let breaks =
4
        page_breaks::compute_page_breaks_from_display_list(&full_display_list, &constraints);
4
    paginate_display_list_with_breaks(full_display_list, config, &breaks, renderer_resources)
8
}
/// Paginate against a PRE-COMPUTED break analysis (see
/// [`page_breaks::compute_page_breaks_from_display_list`]).
///
/// The sibling of [`paginate_display_list_with_slicer_and_breaks`], which
/// computes the breaks itself and delegates here. Lets embedders analyze
/// pagination once and materialize pages separately.
/// # Errors
///
/// Returns a `LayoutError` if paginating the display list fails.
1342
pub fn paginate_display_list_with_breaks(
1342
    full_display_list: DisplayList,
1342
    config: &SlicerConfig,
1342
    breaks: &[page_breaks::PageBreakPosition],
1342
    renderer_resources: &RendererResources,
1342
) -> Result<Vec<DisplayList>> {
1342
    Ok(paginate_pages_impl(
1342
        full_display_list,
1342
        config,
1342
        breaks,
1342
        renderer_resources,
1342
        None,
1342
    ))
1342
}
/// Materialize ONE page of a paginated document — the lazy-viewer entry.
///
/// A document editor computes breaks once (`compute_page_breaks*`), then
/// materializes only the visible pages. Headers/footers still show the
/// correct "page N of TOTAL" because the total comes from `breaks`, not from
/// how many pages were materialized.
///
/// Returns an empty display list when `page_index` is out of range.
/// # Errors
///
/// Returns a `LayoutError` if paginating the display list fails.
5
pub fn paginate_single_page(
5
    full_display_list: DisplayList,
5
    config: &SlicerConfig,
5
    breaks: &[page_breaks::PageBreakPosition],
5
    renderer_resources: &RendererResources,
5
    page_index: usize,
5
) -> Result<DisplayList> {
5
    let mut pages = paginate_pages_impl(
5
        full_display_list,
5
        config,
5
        breaks,
5
        renderer_resources,
5
        Some(page_index),
    );
5
    Ok(pages.pop().unwrap_or_default())
5
}
#[allow(clippy::too_many_lines)] // large but cohesive: single-purpose layout/render/parse routine
                                 // (one branch per case)
1347
fn paginate_pages_impl(
1347
    full_display_list: DisplayList,
1347
    config: &SlicerConfig,
1347
    breaks: &[page_breaks::PageBreakPosition],
1347
    renderer_resources: &RendererResources,
1347
    only_page: Option<usize>,
1347
) -> Vec<DisplayList> {
1347
    if config.page_content_height <= 0.0 || config.page_content_height >= f32::MAX {
7
        return vec![full_display_list];
1340
    }
1340
    let total_height = calculate_display_list_height(&full_display_list);
1340
    let mut page_spans = page_breaks::page_spans(breaks, total_height);
1340
    if page_spans.is_empty() {
1
        // An empty/zero-height document still produces one page tall enough
1
        // for the first page, so headers/footers render on it.
1
        let constraints = page_breaks::PageConstraints::from_slicer_config(config);
1
        page_spans.push((0.0, total_height.max(constraints.first_page_content_height)));
1339
    }
1340
    let num_pages = page_spans.len();
    // Create per-page display lists by slicing the master list
1340
    let mut pages: Vec<DisplayList> =
1340
        Vec::with_capacity(num_pages.min(only_page.map_or(usize::MAX, |_| 1)));
1539
    for (page_idx, &(content_start_y, content_end_y)) in page_spans.iter().enumerate() {
        // Lazy single-page materialization: skip every other span. PageInfo
        // below still receives the TRUE total (num_pages).
1539
        if only_page.is_some_and(|p| p != page_idx) {
16
            continue;
1523
        }
        // Generate page info for header/footer content
1523
        let page_info = PageInfo::new(page_idx + 1, num_pages);
        // Calculate per-page header/footer space. With a page SEQUENCE the
        // decoration comes from THIS page's setup (override/first/parity/
        // default) — the classic office suites model.
1523
        let hf = config
1523
            .page_sequence
1523
            .as_ref()
1523
            .map_or(&config.header_footer, |s| {
                &s.setup_for_page(page_idx).header_footer
            });
1523
        let skip_this_page = hf.skip_first_page && page_info.is_first;
1523
        let header_space = if hf.show_header && !skip_this_page {
4
            hf.header_height
        } else {
1519
            0.0
        };
1523
        let footer_space = if hf.show_footer && !skip_this_page {
16
            hf.footer_height
        } else {
1507
            0.0
        };
1523
        let _ = footer_space; // Currently unused but reserved for future
1523
        let mut page_items = Vec::new();
1523
        let mut page_node_mapping = Vec::new();
        // 1. Add header if enabled
1523
        if hf.show_header && !skip_this_page {
4
            let header_text = hf.header_text(page_info);
4
            if !header_text.is_empty() {
4
                let header_items = generate_text_display_items(
4
                    &header_text,
4
                    LogicalRect {
4
                        origin: LogicalPosition { x: 0.0, y: 0.0 },
4
                        size: LogicalSize {
4
                            width: config.page_width,
4
                            height: hf.header_height,
4
                        },
4
                    },
4
                    hf.font_size,
4
                    hf.text_color,
4
                    TextAlignment::Center,
4
                    renderer_resources,
                );
4
                for item in header_items {
                    page_items.push(item);
                    page_node_mapping.push(None);
                }
            }
1519
        }
        // 2. Inject repeated table headers (if any). Placement is X-AWARE:
        // two sibling tables can only both straddle a page top when they sit
        // SIDE BY SIDE (columns) — each repeated thead then stays in its own
        // x-band at the page top, and each table's continued rows shift down
        // by the summed heights of the theads whose x-band OVERLAPS theirs
        // (side-by-side: their own thead only; nested tables: outer + inner
        // stack). The old code stacked every thead vertically AND shifted
        // ALL content by max(height) — two straddling tables overlapped.
        struct TheadBand {
            x_start: f32,
            x_end: f32,
            /// Cumulative shift for content whose x overlaps this band
            /// (this table's thead + every x-overlapping one injected
            /// above it).
            shift: f32,
            /// Rebased end of the table's content on this page (below it
            /// the SUM of all thead heights applies — matching the break
            /// pass's per-page reservation).
            table_end_page_local: f32,
        }
1523
        let straddlers = config.table_headers.straddling_tables_for_page(
1523
            page_idx,
1523
            content_start_y,
1523
            content_end_y,
        );
1523
        let mut bands: Vec<TheadBand> = Vec::new();
1523
        let mut sum_all_theads = 0.0f32;
1526
        for table in &straddlers {
            // The table's x-extent, from its thead's own geometry.
3
            let (mut x_start, mut x_end) = (f32::MAX, f32::MIN);
6
            for item in &table.thead_items {
3
                if let Some(b) = item.visual_bounds() {
3
                    x_start = x_start.min(b.origin.x);
3
                    x_end = x_end.max(b.origin.x + b.size.width);
3
                }
            }
3
            if x_start > x_end {
                (x_start, x_end) = (f32::MIN, f32::MAX); // no geometry: full width
3
            }
            // Stack below previously injected theads whose x-band overlaps
            // (nested tables); disjoint (side-by-side) theads sit at the top.
3
            let stacked_above: f32 = bands
3
                .iter()
3
                .filter(|b| b.x_start < x_end && x_start < b.x_end)
3
                .map(|b| b.shift)
3
                .fold(0.0, f32::max);
3
            let thead_y = header_space + stacked_above;
6
            for item in &table.thead_items {
3
                page_items.push(offset_display_item_y(item, thead_y));
3
                page_node_mapping.push(None);
3
            }
3
            bands.push(TheadBand {
3
                x_start,
3
                x_end,
3
                shift: stacked_above + table.thead_height,
3
                table_end_page_local: table.table_end_y - content_start_y,
3
            });
3
            sum_all_theads += table.thead_height;
        }
        // 3. Band-dependent shift for content items: inside a straddling
        // table's x-band and y-range → that band's shift; below EVERY
        // straddling table → the full sum (the break pass reserved it).
1523
        let below_all_y = bands
1523
            .iter()
1523
            .map(|b| b.table_end_page_local)
1523
            .fold(0.0f32, f32::max);
16849
        let thead_shift_for = |b: LogicalRect| -> f32 {
16849
            if bands.is_empty() {
16844
                return 0.0;
5
            }
5
            if b.origin.y >= below_all_y {
2
                return sum_all_theads;
3
            }
3
            let x_center = b.size.width.mul_add(0.5, b.origin.x);
3
            bands
3
                .iter()
5
                .filter(|band| x_center >= band.x_start && x_center < band.x_end)
3
                .map(|band| band.shift)
3
                .fold(0.0, f32::max)
16849
        };
        // 4. Slice and offset content items (skip fixed-position items, they are added in step 4b)
        //
        // E17: the clip / stacking / scroll-frame / text-shadow / image-mask
        // STRUCTURE is re-derived per page. Push/Pop markers are tracked in
        // a live stack and emitted LAZILY: a marker chain materializes only
        // when the first content item UNDER it survives this page's Y-band
        // (so pages without a subtree's content carry none of its markers,
        // and marker-free lists produce byte-identical output to before).
        // Balancing Pops are appended at the page end. Marker bounds get the
        // same rebase as the content they wrap (clip rects intersected with
        // the page band, so a partially-on-page clip keeps clipping).
        //
        // Previously EVERY marker was dropped at the page boundary: exports
        // showed unclipped overflow bleed and flattened z-order / opacity on
        // pages after the first affected one.
        struct OpenMarker {
            item_idx: usize,
            /// Already emitted into `page_items`?
            emitted: bool,
        }
1523
        let mut marker_stack: Vec<OpenMarker> = Vec::new();
        // Rebase a MARKER item into page-local space: intersect its rect
        // with the page band (a clip partially on this page keeps clipping;
        // an off-page clip collapses to an empty rect — its content is
        // off-page anyway), rebase to page-local Y, apply the header offset.
1563
        let rebase_band = |r: LogicalRect| -> LogicalRect {
1548
            let top = r.origin.y.max(content_start_y);
1548
            let bottom = (r.origin.y + r.size.height).min(content_end_y);
1548
            LogicalRect {
1548
                origin: LogicalPosition {
1548
                    x: r.origin.x,
1548
                    y: (top - content_start_y) + header_space,
1548
                },
1548
                size: LogicalSize {
1548
                    width: r.size.width,
1548
                    height: (bottom - top).max(0.0),
1548
                },
1548
            }
1548
        };
1563
        let rebase_marker = |item: &DisplayListItem| -> DisplayListItem {
1548
            match item {
                DisplayListItem::PushClip {
82
                    bounds,
82
                    border_radius,
82
                } => DisplayListItem::PushClip {
82
                    bounds: rebase_band(bounds.0).into(),
82
                    border_radius: *border_radius,
82
                },
1466
                DisplayListItem::PushStackingContext { z_index, bounds } => {
1466
                    DisplayListItem::PushStackingContext {
1466
                        z_index: *z_index,
1466
                        bounds: rebase_band(bounds.0).into(),
1466
                    }
                }
                DisplayListItem::PushScrollFrame {
                    clip_bounds,
                    content_size,
                    scroll_id,
                } => DisplayListItem::PushScrollFrame {
                    clip_bounds: rebase_band(clip_bounds.0).into(),
                    content_size: *content_size,
                    scroll_id: *scroll_id,
                },
                DisplayListItem::PushImageMaskClip {
                    bounds,
                    mask_image,
                    mask_rect,
                } => DisplayListItem::PushImageMaskClip {
                    bounds: rebase_band(bounds.0).into(),
                    mask_image: mask_image.clone(),
                    mask_rect: rebase_band(mask_rect.0).into(),
                },
                // PushTextShadow carries only the shadow definition.
                other => other.clone(),
            }
1548
        };
26843
        for (item_idx, item) in full_display_list.items.iter().enumerate() {
            // Maintain the live marker stack for EVERY item, retained or not.
26843
            if item.is_push_marker() {
1621
                marker_stack.push(OpenMarker {
1621
                    item_idx,
1621
                    emitted: false,
1621
                });
1621
                continue;
25222
            }
25222
            if item.is_pop_marker() {
1621
                if let Some(open) = marker_stack.pop() {
1621
                    if open.emitted {
1548
                        page_items.push(item.clone());
1548
                        page_node_mapping.push(None);
1548
                    }
                }
1621
                continue;
23601
            }
            // Skip items that belong to fixed-position elements (they are replicated separately)
23601
            let is_fixed = full_display_list
23601
                .fixed_position_item_ranges
23601
                .iter()
23601
                .any(|&(start, end)| item_idx >= start && item_idx < end);
23601
            if is_fixed {
                continue;
23601
            }
21349
            if let Some(clipped_item) =
23601
                clip_and_offset_display_item(item, content_start_y, content_end_y)
            {
                // The item survives this page: materialize its (not yet
                // emitted) enclosing marker chain, outermost first.
42783
                for open in &mut marker_stack {
21434
                    if !open.emitted {
1548
                        page_items.push(rebase_marker(&full_display_list.items[open.item_idx]));
1548
                        page_node_mapping.push(None);
1548
                        open.emitted = true;
19918
                    }
                }
                // Page-local y of the clipped item decides which thead band
                // shifts it (items without geometry keep the base offset).
21349
                let item_shift = clipped_item.visual_bounds().map_or(0.0, thead_shift_for);
21349
                let content_y_offset = header_space + item_shift;
21349
                let final_item = if content_y_offset > 0.0 {
16
                    offset_display_item_y(&clipped_item, content_y_offset)
                } else {
21333
                    clipped_item
                };
21349
                page_items.push(final_item);
21349
                let node_mapping = full_display_list
21349
                    .node_mapping
21349
                    .get(item_idx)
21349
                    .copied()
21349
                    .flatten();
21349
                page_node_mapping.push(node_mapping);
2252
            }
        }
        // Balance: close every marker still open AND emitted at the page end
        // (innermost first).
1523
        for open in marker_stack.iter().rev() {
            if open.emitted {
                if let Some(pop) = full_display_list.items[open.item_idx].matching_pop() {
                    page_items.push(pop);
                    page_node_mapping.push(None);
                }
            }
        }
        // 4b. Replicate fixed-position items on every page (CSS Positioned Layout §2.1)
        // Fixed-position boxes are fixed relative to the page box, so they appear
        // at the same position on every page without Y-offset adjustment.
1523
        for &(start, end) in &full_display_list.fixed_position_item_ranges {
            for item_idx in start..end {
                if let Some(item) = full_display_list.items.get(item_idx) {
                    // Fixed-position boxes anchor to the PAGE box: offset by
                    // the page header only, never by content thead shifts.
                    let final_item = if header_space > 0.0 {
                        offset_display_item_y(item, header_space)
                    } else {
                        item.clone()
                    };
                    page_items.push(final_item);
                    let node_mapping = full_display_list
                        .node_mapping
                        .get(item_idx)
                        .copied()
                        .flatten();
                    page_node_mapping.push(node_mapping);
                }
            }
        }
        // 5. Add footer if enabled
1523
        if hf.show_footer && !skip_this_page {
16
            let footer_text = hf.footer_text(page_info);
16
            if !footer_text.is_empty() {
                // THIS page's content height: under a PageSequence pages
                // differ (first/parity/override); the uniform config height
                // is only the no-sequence fallback.
16
                let page_h = config
16
                    .page_sequence
16
                    .as_ref()
16
                    .map_or(config.page_content_height, |s| {
                        s.setup_for_page(page_idx).content_height()
                    });
16
                let footer_y = page_h - hf.footer_height;
16
                let footer_items = generate_text_display_items(
16
                    &footer_text,
16
                    LogicalRect {
16
                        origin: LogicalPosition {
16
                            x: 0.0,
16
                            y: footer_y,
16
                        },
16
                        size: LogicalSize {
16
                            width: config.page_width,
16
                            height: hf.footer_height,
16
                        },
16
                    },
16
                    hf.font_size,
16
                    hf.text_color,
16
                    TextAlignment::Center,
16
                    renderer_resources,
                );
16
                for item in footer_items {
                    page_items.push(item);
                    page_node_mapping.push(None);
                }
            }
1507
        }
1523
        pages.push(DisplayList {
1523
            items: page_items,
1523
            node_mapping: page_node_mapping,
1523
            forced_page_breaks: Vec::new(),
1523
            fixed_position_item_ranges: Vec::new(), // Already handled during pagination
1523
            // Page slices are consumed by renderers only — patching operates
1523
            // on the WINDOWED cached DL, never on page slices.
1523
            layout_node_mapping: Vec::new(),
1523
            uniform_text_bgs: Vec::new(),
1523
            text_selection_colors: Vec::new(),
1523
        });
    }
    // Ensure at least one page
1340
    if pages.is_empty() {
1
        pages.push(DisplayList::default());
1339
    }
1340
    pages
1347
}
/// Calculate page break positions respecting CSS forced page breaks.
///
/// Returns a vector of (`start_y`, `end_y`) tuples representing each page's content bounds.
///
/// Shim over [`page_breaks::compute_page_breaks_from_display_list`] +
/// [`page_breaks::page_spans`], kept so the pre-extraction tests keep pinning
/// the observable spans through the same signature.
#[cfg(test)]
8
fn calculate_page_break_positions(
8
    display_list: &DisplayList,
8
    first_page_height: f32,
8
    normal_page_height: f32,
8
) -> Vec<(f32, f32)> {
8
    let total_height = calculate_display_list_height(display_list);
8
    if total_height <= 0.0 || first_page_height <= 0.0 {
3
        return vec![(0.0, total_height.max(first_page_height))];
5
    }
5
    let constraints = page_breaks::PageConstraints {
5
        first_page_content_height: first_page_height,
5
        normal_page_content_height: normal_page_height,
5
    };
5
    let breaks = page_breaks::compute_page_breaks_from_display_list(display_list, &constraints);
5
    let mut spans = page_breaks::page_spans(&breaks, total_height);
5
    if spans.is_empty() {
        spans.push((0.0, total_height.max(first_page_height)));
5
    }
5
    spans
8
}
/// Text alignment for generated header/footer text.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum TextAlignment {
    Left,
    Center,
    Right,
}
/// Helper to offset all Y coordinates of a display item.
#[allow(clippy::too_many_lines)] // large but cohesive: single-purpose layout/render/parse routine
                                 // (one branch per case)
26
pub(crate) fn offset_display_item_y(item: &DisplayListItem, y_offset: f32) -> DisplayListItem {
26
    if y_offset == 0.0 {
6
        return item.clone();
20
    }
20
    match item {
        DisplayListItem::StrokedPath {
            bounds,
            path,
            view_box,
            color,
            width,
            mask,
        } => DisplayListItem::StrokedPath {
            bounds: offset_rect_y(bounds.into_inner(), y_offset).into(),
            path: path.clone(),
            view_box: *view_box,
            color: *color,
            width: *width,
            mask: mask.clone(),
        },
        DisplayListItem::Rect {
19
            bounds,
19
            color,
19
            border_radius,
19
        } => DisplayListItem::Rect {
19
            bounds: offset_rect_y(bounds.into_inner(), y_offset).into(),
19
            color: *color,
19
            border_radius: *border_radius,
19
        },
        DisplayListItem::Border {
            bounds,
            widths,
            colors,
            styles,
            border_radius,
        } => DisplayListItem::Border {
            bounds: offset_rect_y(bounds.into_inner(), y_offset).into(),
            widths: *widths,
            colors: *colors,
            styles: *styles,
            border_radius: *border_radius,
        },
        DisplayListItem::Text {
1
            glyphs,
1
            font_hash,
1
            font_size_px,
1
            color,
1
            clip_rect,
            ..
        } => {
1
            let offset_glyphs: Vec<GlyphInstance> = glyphs
1
                .iter()
1
                .map(|g| GlyphInstance {
2
                    index: g.index,
2
                    point: LogicalPosition {
2
                        x: g.point.x,
2
                        y: g.point.y + y_offset,
2
                    },
2
                    size: g.size,
2
                })
1
                .collect();
1
            DisplayListItem::Text {
1
                glyphs: offset_glyphs,
1
                font_hash: *font_hash,
1
                font_size_px: *font_size_px,
1
                color: *color,
1
                clip_rect: offset_rect_y(clip_rect.into_inner(), y_offset).into(),
1
                source_node_index: None,
1
            }
        }
        DisplayListItem::TextLayout {
            layout,
            bounds,
            font_hash,
            font_size_px,
            color,
        } => DisplayListItem::TextLayout {
            layout: layout.clone(),
            bounds: offset_rect_y(bounds.into_inner(), y_offset).into(),
            font_hash: *font_hash,
            font_size_px: *font_size_px,
            color: *color,
        },
        DisplayListItem::Image {
            bounds,
            image,
            border_radius,
        } => DisplayListItem::Image {
            bounds: offset_rect_y(bounds.into_inner(), y_offset).into(),
            image: image.clone(),
            border_radius: *border_radius,
        },
        // Pass through other items with their bounds offset
        DisplayListItem::SelectionRect {
            bounds,
            border_radius,
            color,
        } => DisplayListItem::SelectionRect {
            bounds: offset_rect_y(bounds.into_inner(), y_offset).into(),
            border_radius: *border_radius,
            color: *color,
        },
        DisplayListItem::CursorRect { bounds, color } => DisplayListItem::CursorRect {
            bounds: offset_rect_y(bounds.into_inner(), y_offset).into(),
            color: *color,
        },
        DisplayListItem::Underline {
            bounds,
            color,
            thickness,
        } => DisplayListItem::Underline {
            bounds: offset_rect_y(bounds.into_inner(), y_offset).into(),
            color: *color,
            thickness: *thickness,
        },
        DisplayListItem::Strikethrough {
            bounds,
            color,
            thickness,
        } => DisplayListItem::Strikethrough {
            bounds: offset_rect_y(bounds.into_inner(), y_offset).into(),
            color: *color,
            thickness: *thickness,
        },
        DisplayListItem::Overline {
            bounds,
            color,
            thickness,
        } => DisplayListItem::Overline {
            bounds: offset_rect_y(bounds.into_inner(), y_offset).into(),
            color: *color,
            thickness: *thickness,
        },
        DisplayListItem::ScrollBar {
            bounds,
            color,
            orientation,
            opacity_key,
            hit_id,
        } => DisplayListItem::ScrollBar {
            bounds: offset_rect_y(bounds.into_inner(), y_offset).into(),
            color: *color,
            orientation: *orientation,
            opacity_key: *opacity_key,
            hit_id: *hit_id,
        },
        DisplayListItem::HitTestArea { bounds, tag } => DisplayListItem::HitTestArea {
            bounds: offset_rect_y(bounds.into_inner(), y_offset).into(),
            tag: *tag,
        },
        DisplayListItem::PushClip {
            bounds,
            border_radius,
        } => DisplayListItem::PushClip {
            bounds: offset_rect_y(bounds.into_inner(), y_offset).into(),
            border_radius: *border_radius,
        },
        DisplayListItem::PushScrollFrame {
            clip_bounds,
            content_size,
            scroll_id,
        } => DisplayListItem::PushScrollFrame {
            clip_bounds: offset_rect_y(clip_bounds.into_inner(), y_offset).into(),
            content_size: *content_size,
            scroll_id: *scroll_id,
        },
        DisplayListItem::PushStackingContext { bounds, z_index } => {
            DisplayListItem::PushStackingContext {
                bounds: offset_rect_y(bounds.into_inner(), y_offset).into(),
                z_index: *z_index,
            }
        }
        DisplayListItem::VirtualView {
            child_dom_id,
            bounds,
            clip_rect,
            content_offset,
        } => DisplayListItem::VirtualView {
            child_dom_id: *child_dom_id,
            bounds: offset_rect_y(bounds.into_inner(), y_offset).into(),
            clip_rect: offset_rect_y(clip_rect.into_inner(), y_offset).into(),
            // Paginating shifts the box down the page; the content's position
            // WITHIN its window is unrelated and must not move.
            content_offset: *content_offset,
        },
        DisplayListItem::VirtualViewPlaceholder {
            node_id,
            bounds,
            clip_rect,
        } => DisplayListItem::VirtualViewPlaceholder {
            node_id: *node_id,
            bounds: offset_rect_y(bounds.into_inner(), y_offset).into(),
            clip_rect: offset_rect_y(clip_rect.into_inner(), y_offset).into(),
        },
        // Pass through stateless items
        DisplayListItem::PopClip => DisplayListItem::PopClip,
        DisplayListItem::PopScrollFrame => DisplayListItem::PopScrollFrame,
        DisplayListItem::PopStackingContext => DisplayListItem::PopStackingContext,
        // Gradient items
        DisplayListItem::LinearGradient {
            bounds,
            gradient,
            border_radius,
        } => DisplayListItem::LinearGradient {
            bounds: offset_rect_y(bounds.into_inner(), y_offset).into(),
            gradient: gradient.clone(),
            border_radius: *border_radius,
        },
        DisplayListItem::RadialGradient {
            bounds,
            gradient,
            border_radius,
        } => DisplayListItem::RadialGradient {
            bounds: offset_rect_y(bounds.into_inner(), y_offset).into(),
            gradient: gradient.clone(),
            border_radius: *border_radius,
        },
        DisplayListItem::ConicGradient {
            bounds,
            gradient,
            border_radius,
        } => DisplayListItem::ConicGradient {
            bounds: offset_rect_y(bounds.into_inner(), y_offset).into(),
            gradient: gradient.clone(),
            border_radius: *border_radius,
        },
        // BoxShadow
        DisplayListItem::BoxShadow {
            bounds,
            shadow,
            border_radius,
        } => DisplayListItem::BoxShadow {
            bounds: offset_rect_y(bounds.into_inner(), y_offset).into(),
            shadow: *shadow,
            border_radius: *border_radius,
        },
        // Filter effects
        DisplayListItem::PushFilter { bounds, filters } => DisplayListItem::PushFilter {
            bounds: offset_rect_y(bounds.into_inner(), y_offset).into(),
            filters: filters.clone(),
        },
        DisplayListItem::PopFilter => DisplayListItem::PopFilter,
        DisplayListItem::PushBackdropFilter { bounds, filters } => {
            DisplayListItem::PushBackdropFilter {
                bounds: offset_rect_y(bounds.into_inner(), y_offset).into(),
                filters: filters.clone(),
            }
        }
        DisplayListItem::PopBackdropFilter => DisplayListItem::PopBackdropFilter,
        DisplayListItem::PushOpacity {
            bounds,
            opacity,
            opacity_key,
        } => DisplayListItem::PushOpacity {
            bounds: offset_rect_y(bounds.into_inner(), y_offset).into(),
            opacity: *opacity,
            opacity_key: *opacity_key,
        },
        DisplayListItem::PopOpacity => DisplayListItem::PopOpacity,
        DisplayListItem::ScrollBarStyled { info } => {
            let mut offset_info = (**info).clone();
            offset_info.bounds = offset_rect_y(offset_info.bounds.into_inner(), y_offset).into();
            offset_info.track_bounds =
                offset_rect_y(offset_info.track_bounds.into_inner(), y_offset).into();
            offset_info.thumb_bounds =
                offset_rect_y(offset_info.thumb_bounds.into_inner(), y_offset).into();
            if let Some(b) = offset_info.button_decrement_bounds {
                offset_info.button_decrement_bounds =
                    Some(offset_rect_y(b.into_inner(), y_offset).into());
            }
            if let Some(b) = offset_info.button_increment_bounds {
                offset_info.button_increment_bounds =
                    Some(offset_rect_y(b.into_inner(), y_offset).into());
            }
            DisplayListItem::ScrollBarStyled {
                info: Box::new(offset_info),
            }
        }
        // Reference frames - offset the bounds
        DisplayListItem::PushReferenceFrame {
            transform_key,
            initial_transform,
            bounds,
        } => DisplayListItem::PushReferenceFrame {
            transform_key: *transform_key,
            initial_transform: *initial_transform,
            bounds: offset_rect_y(bounds.into_inner(), y_offset).into(),
        },
        DisplayListItem::PopReferenceFrame => DisplayListItem::PopReferenceFrame,
        DisplayListItem::PushTextShadow { shadow } => {
            DisplayListItem::PushTextShadow { shadow: *shadow }
        }
        DisplayListItem::PopTextShadow => DisplayListItem::PopTextShadow,
        DisplayListItem::PushImageMaskClip {
            bounds,
            mask_image,
            mask_rect,
        } => DisplayListItem::PushImageMaskClip {
            bounds: offset_rect_y(bounds.into_inner(), y_offset).into(),
            mask_image: mask_image.clone(),
            mask_rect: offset_rect_y(mask_rect.into_inner(), y_offset).into(),
        },
        DisplayListItem::PopImageMaskClip => DisplayListItem::PopImageMaskClip,
    }
26
}
/// Generate display list items for simple text (paginated headers/footers).
///
/// Shapes `text` against a registered font (chosen from `renderer_resources`)
/// and emits a single [`DisplayListItem::Text`] whose glyph indices are the
/// font's real GIDs and whose `font_hash` is the font's registered hash, so the
/// renderer (`cpurender::render_text`) can resolve and paint it.
///
/// This is a deliberately simple shaper for short, single-line running
/// headers/footers (e.g. "Page 1 of 3"): per-character cmap lookup + horizontal
/// advance, no complex shaping / kerning / bidi. The full text pipeline is not
/// used because the pagination call site does not carry a styled run — only the
/// header/footer string and a font size/color.
///
/// History: a previous stub fabricated glyphs whose `index` was the Unicode
/// *codepoint* and whose `font_hash` was `0`, which matched no registered font
/// (the renderer logged "Font hash 0 not found" and painted nothing). A later
/// revision returned an empty list. Both rendered no header/footer text; this
/// emits real glyphs.
///
/// Returns an empty list only when `text` is empty, no font is registered, or
/// the chosen font has degenerate metrics (`units_per_em == 0`).
22
fn generate_text_display_items(
22
    text: &str,
22
    bounds: LogicalRect,
22
    font_size: f32,
22
    color: ColorU,
22
    alignment: TextAlignment,
22
    renderer_resources: &RendererResources,
22
) -> Vec<DisplayListItem> {
22
    if text.is_empty() || font_size <= 0.0 {
        return Vec::new();
22
    }
    // Pick the first registered font. Running headers/footers do not carry a
    // styled run, so there is no per-node font family to resolve; the document's
    // registered font is a reasonable choice for the page furniture.
1
    let Some((_font_key, (font_ref, _instances))) =
22
        renderer_resources.currently_registered_fonts.iter().next()
    else {
21
        return Vec::new();
    };
1
    let parsed = crate::font_ref_to_parsed_font(font_ref);
1
    let units_per_em = f32::from(parsed.font_metrics.units_per_em);
1
    if units_per_em <= 0.0 {
        return Vec::new();
1
    }
1
    let scale = font_size / units_per_em;
1
    let font_hash = parsed.hash;
    // First pass: shape (cmap lookup + advance) and accumulate total width.
1
    let mut shaped: Vec<(u16, f32)> = Vec::new(); // (glyph_id, advance_px)
1
    let mut total_width = 0.0f32;
11
    for c in text.chars() {
11
        let gid = parsed.lookup_glyph_index(c as u32).unwrap_or(0);
11
        let advance = f32::from(parsed.get_horizontal_advance(gid)) * scale;
11
        shaped.push((gid, advance));
11
        total_width += advance;
11
    }
1
    if shaped.is_empty() {
        return Vec::new();
1
    }
    // Horizontal placement within the box.
1
    let start_x = match alignment {
1
        TextAlignment::Center => (bounds.size.width - total_width).mul_add(0.5, bounds.origin.x),
        TextAlignment::Right => bounds.origin.x + (bounds.size.width - total_width),
        TextAlignment::Left => bounds.origin.x,
    };
    // Vertical placement: center the text's em-box in the header/footer band and
    // place the baseline accordingly (point.y is the glyph baseline).
1
    let ascent_px = parsed.font_metrics.ascent * scale;
1
    let descent_px = parsed.font_metrics.descent * scale; // hhea descender, usually negative
1
    let text_height = ascent_px - descent_px;
1
    let baseline_y = bounds.origin.y + (bounds.size.height - text_height).mul_add(0.5, ascent_px);
1
    let mut pen_x = start_x;
1
    let mut glyphs: Vec<GlyphInstance> = Vec::with_capacity(shaped.len());
12
    for (gid, advance) in shaped {
11
        let size = parsed
11
            .get_glyph_size(gid, font_size)
11
            .unwrap_or(LogicalSize {
11
                width: advance,
11
                height: font_size,
11
            });
11
        glyphs.push(GlyphInstance {
11
            index: u32::from(gid),
11
            point: LogicalPosition {
11
                x: pen_x,
11
                y: baseline_y,
11
            },
11
            size,
11
        });
11
        pen_x += advance;
11
    }
1
    vec![DisplayListItem::Text {
1
        glyphs,
1
        font_hash: FontHash::from_hash(font_hash),
1
        font_size_px: font_size,
1
        color,
1
        clip_rect: bounds.into(),
1
        source_node_index: None,
1
    }]
22
}
/// Calculate the total height of a display list (max Y + height of all items).
4664
pub(crate) fn calculate_display_list_height(display_list: &DisplayList) -> f32 {
4664
    let mut max_bottom = 0.0f32;
142124
    for item in &display_list.items {
137460
        if let Some(bounds) = get_display_item_bounds(item) {
            // Skip items with zero height - they don't contribute to visible content
132604
            if bounds.0.size.height < 0.1 {
1694
                continue;
130910
            }
130910
            let item_bottom = bounds.0.origin.y + bounds.0.size.height;
130910
            if item_bottom > max_bottom {
5672
                max_bottom = item_bottom;
125238
            }
4856
        }
    }
4664
    max_bottom
4664
}
/// Break property information for pagination decisions.
#[derive(Debug, Clone, Copy, Default)]
// fields mirror the CSS break-before / break-after / break-inside properties
#[allow(clippy::struct_field_names)]
struct BreakProperties {
    break_before: PageBreak,
    break_after: PageBreak,
    break_inside: BreakInside,
}
// ============================================================================
// TEXT-OVERFLOW STUB
// ============================================================================
/// Applies text-overflow ellipsis handling to a display list.
///
/// CSS UI Module Level 3, section 6.2 (text-overflow):
/// When inline content overflows a block container that has `overflow: hidden`
/// (or clip/scroll) and `text-overflow: ellipsis`, the overflowing text should
/// be replaced with an ellipsis character (U+2026) or a custom string.
///
/// This is a display-list post-processing step that modifies glyph runs
/// to show an ellipsis when text overflows its container. It operates on
/// the assumption that the container already has a `PushClip` that clips
/// the overflow -- this function additionally replaces the trailing glyphs
/// with an ellipsis so the user gets a visual indicator of truncation.
///
/// # Parameters
/// - `display_list`: The display list to modify (text items may be clipped/replaced)
/// - `container_bounds`: The bounds of the containing block (overflow boundary)
/// - `_ellipsis`: The ellipsis string (currently unused; U+2026 glyph index is used)
///
/// # Algorithm
/// 1. For each Text item in the display list, check if any glyphs extend past the container's right
///    edge (inline-end in LTR).
/// 2. If so, find the last glyph that fits entirely within the container, accounting for the width
///    of the ellipsis character.
/// 3. Remove all glyphs after that point.
/// 4. Append an ellipsis glyph (U+2026 = glyph index 0x2026 as a fallback; proper glyph lookup
///    requires font metrics not available here).
///
/// Note: This is a best-effort implementation. A pixel-perfect version would
/// need access to font metrics to measure the exact ellipsis glyph width and
/// to look up the correct glyph index for the ellipsis in each font.
// +spec:overflow:f175b9 - bidi ellipsis: characters visually at the end edge of the line are hidden
// for ellipsis
5
pub(crate) fn apply_text_overflow_ellipsis(
5
    display_list: &mut DisplayList,
5
    container_bounds: LogicalRect,
5
    _ellipsis: &str,
5
) {
5
    let container_right = container_bounds.origin.x + container_bounds.size.width;
    // Approximate ellipsis width as ~0.6 * font_size (typical for "..." in most fonts).
    // This is a heuristic; proper implementation requires font metric access.
12
    for item in &mut display_list.items {
        if let DisplayListItem::Text {
5
            glyphs,
5
            font_size_px,
5
            clip_rect,
            ..
7
        } = item
        {
5
            if glyphs.is_empty() {
1
                continue;
4
            }
            // Check if any glyph extends past the container right edge
4
            let last_glyph = &glyphs[glyphs.len() - 1];
4
            let last_glyph_right = last_glyph.point.x + last_glyph.size.width;
4
            if last_glyph_right <= container_right {
1
                continue; // No overflow, nothing to do
3
            }
            // Estimate ellipsis width
3
            let ellipsis_width = *font_size_px * APPROX_ELLIPSIS_WIDTH_RATIO;
3
            let truncation_edge = container_right - ellipsis_width;
            // Find the last glyph that fits before the truncation edge
3
            let mut keep_count = 0;
8
            for (i, glyph) in glyphs.iter().enumerate() {
8
                let glyph_right = glyph.point.x + glyph.size.width;
8
                if glyph_right > truncation_edge {
2
                    break;
6
                }
6
                keep_count = i + 1;
            }
            // Truncate the glyphs
3
            glyphs.truncate(keep_count);
            // Append an ellipsis glyph. We use Unicode codepoint U+2026
            // (HORIZONTAL ELLIPSIS) as the glyph index. This is a common
            // convention; renderers that use proper glyph IDs will need to
            // map this to the font's actual glyph index.
3
            let ellipsis_x = glyphs.last().map_or(container_bounds.origin.x, |last| {
2
                last.point.x + last.size.width
2
            });
3
            let ellipsis_glyph = GlyphInstance {
                index: 0x2026, // U+2026 HORIZONTAL ELLIPSIS
3
                point: LogicalPosition::new(
3
                    ellipsis_x,
3
                    glyphs
3
                        .first()
3
                        .map_or(container_bounds.origin.y, |g| g.point.y),
                ),
3
                size: LogicalSize::new(ellipsis_width, *font_size_px),
            };
3
            glyphs.push(ellipsis_glyph);
            // Update the clip rect to match the container bounds so
            // the ellipsis is visible but nothing past it is shown
3
            *clip_rect = container_bounds.into();
2
        }
    }
5
}
// ============================================================================
// CLIP-PATH STUB
// ============================================================================
/// Resolves a CSS clip-path shape to a clipping rectangle.
///
/// CSS Masking Module Level 1, section 3 (clip-path):
/// The clip-path property creates a clipping region that determines which parts
/// of an element are visible. Content outside the clipping region is hidden.
///
/// Currently supported clip-path values:
/// - `inset()` - rectangular clip with optional rounding
/// - `circle()` - approximated as bounding box rectangle
/// - `ellipse()` - approximated as bounding box rectangle
/// - `polygon()` - approximated as axis-aligned bounding box
/// - `none` - no clipping (returns None)
///
/// # Parameters
/// - `clip_path`: The resolved clip-path CSS property value
/// - `node_bounds`: The reference box for resolving clip-path values
///
/// # Returns
/// A `(LogicalRect, f32)` tuple: the clip rectangle and border radius,
/// or `None` if no clipping should be applied.
///
/// Note: Circle, ellipse, and polygon shapes are approximated as axis-aligned
/// bounding boxes. A full implementation would use path-based clipping in the
/// renderer, but rectangular clips work for the most common use cases.
#[allow(clippy::many_single_char_names)] // domain-standard coordinate/geometry/short-lived names
14
pub(crate) fn resolve_clip_path(
14
    clip_path: &azul_css::props::layout::shape::ClipPath,
14
    node_bounds: LogicalRect,
14
) -> Option<(LogicalRect, f32)> {
    use azul_css::{props::layout::shape::ClipPath, shape::CssShape};
14
    match clip_path {
2
        ClipPath::None => None,
12
        ClipPath::Shape(shape) => {
12
            match shape {
2
                CssShape::Inset(inset) => {
                    // CSS inset() creates a rectangular clip inset from each edge.
                    // inset(top right bottom left round border-radius)
2
                    let x = node_bounds.origin.x + inset.inset_left;
2
                    let y = node_bounds.origin.y + inset.inset_top;
2
                    let w =
2
                        (node_bounds.size.width - inset.inset_left - inset.inset_right).max(0.0);
2
                    let h =
2
                        (node_bounds.size.height - inset.inset_top - inset.inset_bottom).max(0.0);
2
                    let radius = match inset.border_radius {
1
                        azul_css::corety::OptionF32::Some(r) => r,
1
                        azul_css::corety::OptionF32::None => 0.0,
                    };
2
                    Some((
2
                        LogicalRect {
2
                            origin: LogicalPosition::new(x, y),
2
                            size: LogicalSize::new(w, h),
2
                        },
2
                        radius,
2
                    ))
                }
5
                CssShape::Circle(circle) => {
                    // Approximate circle as a square bounding box centered at the circle center.
                    // CSS circle(radius at cx cy). The center point coordinates are in
                    // absolute units (pre-resolved by the CSS parser).
5
                    let cx = node_bounds.origin.x + circle.center.x;
5
                    let cy = node_bounds.origin.y + circle.center.y;
5
                    let r = circle.radius;
5
                    Some((
5
                        LogicalRect {
5
                            origin: LogicalPosition::new(cx - r, cy - r),
5
                            size: LogicalSize::new(r * 2.0, r * 2.0),
5
                        },
5
                        r,
5
                    ))
                }
1
                CssShape::Ellipse(ellipse) => {
                    // Approximate ellipse as its bounding box.
1
                    let cx = node_bounds.origin.x + ellipse.center.x;
1
                    let cy = node_bounds.origin.y + ellipse.center.y;
1
                    let rx = ellipse.radius_x;
1
                    let ry = ellipse.radius_y;
1
                    let radius = rx.min(ry);
1
                    Some((
1
                        LogicalRect {
1
                            origin: LogicalPosition::new(cx - rx, cy - ry),
1
                            size: LogicalSize::new(rx * 2.0, ry * 2.0),
1
                        },
1
                        radius,
1
                    ))
                }
3
                CssShape::Polygon(polygon) => {
                    // Compute the axis-aligned bounding box of the polygon.
3
                    if polygon.points.is_empty() {
1
                        return None;
2
                    }
2
                    let mut min_x = f32::INFINITY;
2
                    let mut min_y = f32::INFINITY;
2
                    let mut max_x = f32::NEG_INFINITY;
2
                    let mut max_y = f32::NEG_INFINITY;
6
                    for point in &polygon.points {
4
                        // Polygon points are in absolute coordinates (pre-resolved)
4
                        let px = node_bounds.origin.x + point.x;
4
                        let py = node_bounds.origin.y + point.y;
4
                        min_x = min_x.min(px);
4
                        min_y = min_y.min(py);
4
                        max_x = max_x.max(px);
4
                        max_y = max_y.max(py);
4
                    }
2
                    Some((
2
                        LogicalRect {
2
                            origin: LogicalPosition::new(min_x, min_y),
2
                            size: LogicalSize::new(
2
                                (max_x - min_x).max(0.0),
2
                                (max_y - min_y).max(0.0),
2
                            ),
2
                        },
2
                        0.0,
2
                    ))
                }
                CssShape::Path(_) => {
                    // SVG paths are not supported for clip-path yet.
                    // Return the full node bounds (no clipping).
1
                    None
                }
            }
        }
    }
14
}
/// Applies a CSS clip-path to the display list by inserting PushClip/PopClip.
///
/// This is a post-processing step that wraps all items between `start_index`
/// and the current end of the display list in a clip region derived from
/// the clip-path shape.
///
/// # Parameters
/// - `display_list`: The display list to modify
/// - `start_index`: The index of the first item belonging to this node
/// - `clip_rect`: The resolved clip rectangle
/// - `border_radius`: The border radius for the clip (from inset round, or circle)
6
pub(crate) fn apply_clip_path(
6
    display_list: &mut DisplayList,
6
    start_index: usize,
6
    clip_rect: LogicalRect,
6
    border_radius: f32,
6
) {
6
    let br = if border_radius > 0.0 {
1
        BorderRadius {
1
            top_left: border_radius,
1
            top_right: border_radius,
1
            bottom_left: border_radius,
1
            bottom_right: border_radius,
1
        }
    } else {
5
        BorderRadius::default()
    };
    // Insert PushClip at start_index
6
    display_list.items.insert(
6
        start_index,
6
        DisplayListItem::PushClip {
6
            bounds: clip_rect.into(),
6
            border_radius: br,
6
        },
    );
    // Insert a corresponding None in node_mapping
6
    if display_list.node_mapping.len() >= start_index {
5
        display_list.node_mapping.insert(start_index, None);
5
    }
    // Append PopClip at the end
6
    display_list.items.push(DisplayListItem::PopClip);
6
    display_list.node_mapping.push(None);
6
}
/// The STROKE of a path, rasterised as an R8 coverage mask over `paint_rect`.
///
/// The GPU backend's half of `DisplayListItem::StrokedPath`: `WebRender` has no
/// vector rasteriser, so the stroke is painted as a colour through this mask.
/// The CPU backend does not use it - it strokes the outline directly, which
/// stays sharp at any zoom.
///
/// Rasterised at 2x the logical box for the same reason an icon is: the mask
/// is scaled to the element on screen, and a 1x mask is visibly soft on a
/// `HiDPI` display.
#[cfg(feature = "cpurender")]
#[allow(
    clippy::cast_possible_truncation,
    clippy::cast_possible_wrap,
    clippy::cast_sign_loss
)] // bounded graphics/coord/font/fixed-point/debug-marker cast
30
fn rasterize_svg_stroke_to_r8(
30
    path: &azul_core::svg::SvgMultiPolygon,
30
    paint_rect: &LogicalRect,
30
    view_box: Option<(f32, f32, f32, f32)>,
30
    width: f32,
30
) -> Option<ImageRef> {
    use agg_rust::{
        basics::FillingRule, color::Rgba8, conv_stroke::ConvStroke, pixfmt_rgba::PixfmtRgba32,
        rasterizer_scanline_aa::RasterizerScanlineAa, renderer_base::RendererBase,
        renderer_scanline::render_scanlines_aa_solid, rendering_buffer::RowAccessor,
        scanline_u::ScanlineU8,
    };
    use azul_core::resources::{ImageRef, RawImage, RawImageData, RawImageFormat};
    const OVERSAMPLE: f32 = 2.0;
30
    let w = (paint_rect.size.width * OVERSAMPLE).ceil() as u32;
30
    let h = (paint_rect.size.height * OVERSAMPLE).ceil() as u32;
30
    if w == 0 || h == 0 || !width.is_finite() || width <= 0.0 {
        return None;
30
    }
30
    let (sx, sy, tx, ty) =
30
        crate::cpurender::pixmap::svg_user_space_mapping(paint_rect, view_box, OVERSAMPLE);
90
    let mx = |x: f32| f64::from((x + tx) * sx);
90
    let my = |y: f32| f64::from((y + ty) * sy);
30
    let mut geometry = crate::cpurender::pixmap::svg_path_to_agg(path, &mx, &my);
30
    let scale = f64::from(f32::midpoint(sx, sy));
    // Flattened before stroking, for the same reason the fill is: the stroker
    // walks VERTICES, and a raw curve command has none to offset.
30
    let mut flattened = agg_rust::conv_curve::ConvCurve::new(&mut geometry);
30
    let mut stroke = ConvStroke::new(&mut flattened);
30
    stroke.set_width((f64::from(width) * scale).max(1.0));
30
    stroke.set_line_cap(agg_rust::math_stroke::LineCap::Round);
30
    stroke.set_line_join(agg_rust::math_stroke::LineJoin::Round);
30
    let mut rgba_buf = vec![0u8; (w * h * 4) as usize];
30
    {
30
        let stride = (w * 4) as i32;
30
        let mut ra = unsafe { RowAccessor::new_with_buf(rgba_buf.as_mut_ptr(), w, h, stride) };
30
        let pf = PixfmtRgba32::new(&mut ra);
30
        let mut rb = RendererBase::new(pf);
30
        let mut ras = RasterizerScanlineAa::new();
30
        ras.filling_rule(FillingRule::NonZero);
30
        ras.add_path(&mut stroke, 0);
30
        let mut sl = ScanlineU8::new();
30
        let white = Rgba8 {
30
            r: 255,
30
            g: 255,
30
            b: 255,
30
            a: 255,
30
        };
30
        render_scanlines_aa_solid(&mut ras, &mut sl, &mut rb, &white);
30
    }
30720
    let r8_data: Vec<u8> = rgba_buf.chunks_exact(4).map(|px| px[3]).collect();
30
    ImageRef::new_rawimage(RawImage {
30
        pixels: RawImageData::U8(r8_data.into()),
30
        width: w as usize,
30
        height: h as usize,
30
        premultiplied_alpha: false,
30
        data_format: RawImageFormat::R8,
30
        tag: Vec::new().into(),
30
    })
30
}
/// Rasterize an `SvgMultiPolygon` clip path into an R8 image mask at the given
/// paint rect size.
///
/// Returns `None` if the rect has zero size.
///
/// Gated on `cpurender`, the feature that owns the `agg-rust` rasteriser this
/// body is written against (`layout/Cargo.toml`: `cpurender = ["dep:agg-rust",
/// ...]`), and the same gate its ONLY caller (`push_image_mask_clip`) already
/// carries. Without `cpurender` a build has no vector rasteriser, so an SVG
/// `clip-path` does not clip - the caller's `#[cfg(not(feature =
/// "cpurender"))]` arm already says so on stderr, once.
#[cfg(feature = "cpurender")]
180
fn rasterize_svg_clip_to_r8(
180
    svg_clip: &azul_core::svg::SvgMultiPolygon,
180
    paint_rect: &LogicalRect,
180
    view_box: Option<(f32, f32, f32, f32)>,
180
) -> Option<ImageRef> {
    use agg_rust::{
        basics::FillingRule, color::Rgba8, path_storage::PathStorage, pixfmt_rgba::PixfmtRgba32,
        rasterizer_scanline_aa::RasterizerScanlineAa, renderer_base::RendererBase,
        renderer_scanline::render_scanlines_aa_solid, rendering_buffer::RowAccessor,
        scanline_u::ScanlineU8,
    };
    use azul_core::resources::{ImageRef, RawImage, RawImageData, RawImageFormat};
    // OVERSAMPLED, for the same reason the stroke mask is: the mask is
    // rasterised here in LOGICAL pixels and applied in DEVICE pixels, so on a
    // HiDPI display it is scaled UP. A 1x mask has no detail to scale, and a
    // circle arrives with a staircase edge no matter how it is resampled.
    const OVERSAMPLE: f32 = 2.0;
180
    let w = (paint_rect.size.width * OVERSAMPLE).ceil() as u32;
180
    let h = (paint_rect.size.height * OVERSAMPLE).ceil() as u32;
180
    if w == 0 || h == 0 {
        return None;
180
    }
    // USER SPACE -> MASK PIXELS.
    //
    // With a viewBox the geometry is in the `<svg>`'s own coordinate system
    // and has to be SCALED into the box the element ended up with: an icon
    // drawn at 16 units in a 64px slot must fill the slot, not a sixteenth of
    // it. Without one (a bare clip-path on an ordinary element) the geometry
    // is already in window-logical px, and only the paint rect's origin is
    // subtracted - the behaviour every existing clip mask relies on.
180
    let (sx, sy, tx, ty) = match view_box {
130
        Some((min_x, min_y, vb_w, vb_h)) if vb_w > 0.0 && vb_h > 0.0 => (
130
            paint_rect.size.width * OVERSAMPLE / vb_w,
130
            paint_rect.size.height * OVERSAMPLE / vb_h,
130
            -min_x,
130
            -min_y,
130
        ),
50
        _ => (
50
            OVERSAMPLE,
50
            OVERSAMPLE,
50
            -paint_rect.origin.x,
50
            -paint_rect.origin.y,
50
        ),
    };
1170
    let mx = |x: f32| f64::from((x + tx) * sx);
1170
    let my = |y: f32| f64::from((y + ty) * sy);
    // Build agg PathStorage from SvgMultiPolygon
180
    let mut path = PathStorage::new();
180
    for ring in svg_clip.rings.as_ref() {
180
        let mut first = true;
750
        for item in ring.items.as_ref() {
750
            match item {
630
                azul_core::svg::SvgPathElement::Line(l) => {
630
                    if first {
160
                        path.move_to(mx(l.start.x), my(l.start.y));
160
                        first = false;
470
                    }
630
                    path.line_to(mx(l.end.x), my(l.end.y));
                }
                azul_core::svg::SvgPathElement::QuadraticCurve(q) => {
                    if first {
                        path.move_to(mx(q.start.x), my(q.start.y));
                        first = false;
                    }
                    path.curve3(mx(q.ctrl.x), my(q.ctrl.y), mx(q.end.x), my(q.end.y));
                }
120
                azul_core::svg::SvgPathElement::CubicCurve(c) => {
120
                    if first {
20
                        path.move_to(mx(c.start.x), my(c.start.y));
20
                        first = false;
100
                    }
120
                    path.curve4(
120
                        mx(c.ctrl_1.x),
120
                        my(c.ctrl_1.y),
120
                        mx(c.ctrl_2.x),
120
                        my(c.ctrl_2.y),
120
                        mx(c.end.x),
120
                        my(c.end.y),
                    );
                }
            }
        }
    }
    // Rasterize to RGBA32 buffer
180
    let mut rgba_buf = vec![0u8; (w * h * 4) as usize];
180
    {
180
        let stride = (w * 4) as i32;
180
        let mut ra = unsafe { RowAccessor::new_with_buf(rgba_buf.as_mut_ptr(), w, h, stride) };
180
        let pf = PixfmtRgba32::new(&mut ra);
180
        let mut rb = RendererBase::new(pf);
180

            
180
        let mut ras = RasterizerScanlineAa::new();
180
        ras.filling_rule(FillingRule::NonZero);
180
        // FLATTENED first. `PathStorage` stores curve3/curve4 as COMMANDS;
180
        // the rasteriser does not subdivide them, so feeding it the raw
180
        // storage draws straight lines between the curve endpoints - a circle
180
        // built from four cubics came out as a four-sided blob. `ConvCurve` is
180
        // the adaptor that turns those commands into line segments.
180
        let mut flattened = agg_rust::conv_curve::ConvCurve::new(&mut path);
180
        ras.add_path(&mut flattened, 0);
180

            
180
        let mut sl = ScanlineU8::new();
180
        let white = Rgba8 {
180
            r: 255,
180
            g: 255,
180
            b: 255,
180
            a: 255,
180
        };
180
        render_scanlines_aa_solid(&mut ras, &mut sl, &mut rb, &white);
180
    }
    // Extract alpha channel as R8 mask
2671360
    let r8_data: Vec<u8> = rgba_buf.chunks_exact(4).map(|px| px[3]).collect();
180
    ImageRef::new_rawimage(RawImage {
180
        pixels: RawImageData::U8(r8_data.into()),
180
        width: w as usize,
180
        height: h as usize,
180
        premultiplied_alpha: false,
180
        data_format: RawImageFormat::R8,
180
        tag: Vec::new().into(),
180
    })
180
}
#[cfg(test)]
mod pagination_text_tests {
    use azul_core::resources::{FontKey, IdNamespace};
    use super::*;
    use crate::font::parsed::ParsedFont;
    /// Loads a system font for testing, retaining source bytes so advances work.
1
    fn load_test_font() -> Option<ParsedFont> {
1
        let candidates = [
1
            "/System/Library/Fonts/Supplemental/Times New Roman.ttf",
1
            "/System/Library/Fonts/Helvetica.ttc",
1
            "/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf",
1
            "/usr/share/fonts/truetype/liberation/LiberationSans-Regular.ttf",
1
            "C:/Windows/Fonts/arial.ttf",
1
        ];
3
        for path in candidates {
3
            if let Ok(bytes) = std::fs::read(path) {
1
                let arc = Arc::new(rust_fontconfig::FontBytes::Owned(Arc::from(
1
                    bytes.as_slice(),
1
                )));
1
                if let Some(font) = ParsedFont::from_bytes(&bytes, 0, &mut Vec::new())
1
                    .map(|f| f.with_source_bytes(arc))
                {
1
                    return Some(font);
                }
2
            }
        }
        None
1
    }
1
    fn renderer_resources_with(font: ParsedFont) -> RendererResources {
1
        let mut rr = RendererResources::default();
1
        let font_ref = crate::parsed_font_to_font_ref(font);
1
        let key = FontKey::unique(IdNamespace(0));
1
        let hash = crate::font_ref_to_parsed_font(&font_ref).hash;
1
        rr.font_hash_map.insert(hash, key);
1
        rr.currently_registered_fonts
1
            .insert(key, (font_ref, BTreeMap::default()));
1
        rr
1
    }
    /// The pagination header/footer text path must emit real glyph display items
    /// (the audit flagged it as a no-op rendering nothing).
    #[test]
1
    fn generate_text_display_items_emits_glyphs() {
1
        let Some(font) = load_test_font() else {
            eprintln!("[skip] no system font available");
            return;
        };
1
        let expected_hash = font.hash;
1
        let rr = renderer_resources_with(font);
1
        let bounds = LogicalRect {
1
            origin: LogicalPosition { x: 0.0, y: 0.0 },
1
            size: LogicalSize {
1
                width: 400.0,
1
                height: 30.0,
1
            },
1
        };
1
        let items = generate_text_display_items(
1
            "Page 1 of 3",
1
            bounds,
            14.0,
1
            ColorU {
1
                r: 0,
1
                g: 0,
1
                b: 0,
1
                a: 255,
1
            },
1
            TextAlignment::Center,
1
            &rr,
        );
1
        assert_eq!(items.len(), 1, "expected exactly one Text item");
1
        match &items[0] {
            DisplayListItem::Text {
1
                glyphs,
1
                font_hash,
1
                color,
                ..
            } => {
1
                assert_eq!(glyphs.len(), "Page 1 of 3".chars().count());
1
                assert_eq!(
                    font_hash.font_hash, expected_hash,
                    "must use registered font hash"
                );
1
                assert_ne!(font_hash.font_hash, 0, "hash 0 resolves no font");
1
                assert_eq!(color.a, 255);
                // Glyph IDs must be real (cmap-resolved), not raw codepoints.
1
                let p_gid = glyphs[0].index;
1
                assert_ne!(
                    p_gid, 'P' as u32,
                    "glyph index must be a GID, not a codepoint"
                );
                // Pen must advance: x coordinates strictly increase across the run.
1
                assert!(glyphs[1].point.x > glyphs[0].point.x, "pen did not advance");
            }
            other => panic!("expected DisplayListItem::Text, got {other:?}"),
        }
1
    }
    /// With no registered fonts there is nothing to shape against -> empty.
    #[test]
1
    fn generate_text_display_items_empty_without_font() {
1
        let rr = RendererResources::default();
1
        let bounds = LogicalRect {
1
            origin: LogicalPosition { x: 0.0, y: 0.0 },
1
            size: LogicalSize {
1
                width: 400.0,
1
                height: 30.0,
1
            },
1
        };
1
        let items = generate_text_display_items(
1
            "Header",
1
            bounds,
            14.0,
1
            ColorU {
1
                r: 0,
1
                g: 0,
1
                b: 0,
1
                a: 255,
1
            },
1
            TextAlignment::Center,
1
            &rr,
        );
1
        assert!(items.is_empty());
1
    }
}
#[cfg(test)]
#[allow(clippy::float_cmp, clippy::too_many_lines)]
mod autotest_generated {
    use super::*;
    // ---------------------------------------------------------------------
    // Construction helpers
    // ---------------------------------------------------------------------
    fn rect(x: f32, y: f32, w: f32, h: f32) -> LogicalRect {
        LogicalRect::new(LogicalPosition::new(x, y), LogicalSize::new(w, h))
    }
    fn opaque() -> ColorU {
        ColorU {
            r: 10,
            g: 20,
            b: 30,
            a: 255,
        }
    }
    fn glyph(index: u32, x: f32, y: f32) -> GlyphInstance {
        GlyphInstance {
            index,
            point: LogicalPosition::new(x, y),
            size: LogicalSize::new(8.0, 12.0),
        }
    }
    fn no_widths() -> StyleBorderWidths {
        StyleBorderWidths {
            top: None,
            right: None,
            bottom: None,
            left: None,
        }
    }
    fn all_widths() -> StyleBorderWidths {
        StyleBorderWidths {
            top: Some(CssPropertyValue::Exact(LayoutBorderTopWidth::default())),
            right: Some(CssPropertyValue::Exact(LayoutBorderRightWidth::default())),
            bottom: Some(CssPropertyValue::Exact(LayoutBorderBottomWidth::default())),
            left: Some(CssPropertyValue::Exact(LayoutBorderLeftWidth::default())),
        }
    }
    fn no_colors() -> StyleBorderColors {
        StyleBorderColors {
            top: None,
            right: None,
            bottom: None,
            left: None,
        }
    }
    fn no_styles() -> StyleBorderStyles {
        StyleBorderStyles {
            top: None,
            right: None,
            bottom: None,
            left: None,
        }
    }
    /// Every side `Some(none)` — the default style, and what the compact
    /// cache answers for an unset border.
    fn all_styles() -> StyleBorderStyles {
        StyleBorderStyles {
            top: Some(CssPropertyValue::Exact(StyleBorderTopStyle::default())),
            right: Some(CssPropertyValue::Exact(StyleBorderRightStyle::default())),
            bottom: Some(CssPropertyValue::Exact(StyleBorderBottomStyle::default())),
            left: Some(CssPropertyValue::Exact(StyleBorderLeftStyle::default())),
        }
    }
    fn all_solid_styles() -> StyleBorderStyles {
        StyleBorderStyles {
            top: Some(CssPropertyValue::Exact(StyleBorderTopStyle {
                inner: BorderStyle::Solid,
            })),
            right: Some(CssPropertyValue::Exact(StyleBorderRightStyle {
                inner: BorderStyle::Solid,
            })),
            bottom: Some(CssPropertyValue::Exact(StyleBorderBottomStyle {
                inner: BorderStyle::Solid,
            })),
            left: Some(CssPropertyValue::Exact(StyleBorderLeftStyle {
                inner: BorderStyle::Solid,
            })),
        }
    }
    /// Every side `Some(0px)` — what the compact cache answers for an unset
    /// border width.
    fn zero_widths() -> StyleBorderWidths {
        StyleBorderWidths {
            top: Some(CssPropertyValue::Exact(LayoutBorderTopWidth {
                inner: PixelValue::px(0.0),
            })),
            right: Some(CssPropertyValue::Exact(LayoutBorderRightWidth {
                inner: PixelValue::px(0.0),
            })),
            bottom: Some(CssPropertyValue::Exact(LayoutBorderBottomWidth {
                inner: PixelValue::px(0.0),
            })),
            left: Some(CssPropertyValue::Exact(LayoutBorderLeftWidth {
                inner: PixelValue::px(0.0),
            })),
        }
    }
    fn zero_style_radius() -> StyleBorderRadius {
        StyleBorderRadius {
            top_left: PixelValue::zero(),
            top_right: PixelValue::zero(),
            bottom_left: PixelValue::zero(),
            bottom_right: PixelValue::zero(),
        }
    }
    fn test_image() -> ImageRef {
        ImageRef::null_image(
            4,
            4,
            azul_core::resources::RawImageFormat::RGBA8,
            Vec::new(),
        )
    }
    fn text_item(
        src: Option<usize>,
        clip: LogicalRect,
        glyphs: Vec<GlyphInstance>,
    ) -> DisplayListItem {
        DisplayListItem::Text {
            glyphs,
            font_hash: FontHash::from_hash(7),
            font_size_px: 16.0,
            color: opaque(),
            clip_rect: clip.into(),
            source_node_index: src,
        }
    }
    fn list_of(items: Vec<DisplayListItem>) -> DisplayList {
        let node_mapping = vec![None; items.len()];
        DisplayList {
            items,
            node_mapping,
            ..DisplayList::default()
        }
    }
    #[cfg(feature = "text_layout")]
    fn positioned(line_index: usize, x: f32, y: f32, w: f32, h: f32) -> PositionedItem {
        PositionedItem {
            item: ShapedItem::Tab {
                source: azul_core::selection::ContentIndex {
                    run_index: 0,
                    item_index: 0,
                },
                bounds: text3::cache::Rect {
                    x: 0.0,
                    y: 0.0,
                    width: w,
                    height: h,
                },
            },
            position: text3::cache::Point { x, y },
            line_index,
        }
    }
    // ---------------------------------------------------------------------
    // WindowLogicalRect / BorderBoxRect / ContentBoxRect
    // ---------------------------------------------------------------------
    #[test]
    fn window_logical_rect_accessors_roundtrip() {
        let origin = LogicalPosition::new(-3.5, 12.25);
        let size = LogicalSize::new(100.0, 40.0);
        let w = WindowLogicalRect::new(origin, size);
        assert_eq!(w.origin(), origin);
        assert_eq!(w.size(), size);
        assert_eq!(*w.inner(), LogicalRect::new(origin, size));
        assert_eq!(w.into_inner(), LogicalRect::new(origin, size));
        // From/Into must be the identity on the wrapped rect.
        assert_eq!(WindowLogicalRect::from(w.into_inner()), w);
        assert_eq!(LogicalRect::from(w), w.into_inner());
    }
    #[test]
    fn window_logical_rect_zero_is_neutral() {
        let z = WindowLogicalRect::zero();
        assert_eq!(z, WindowLogicalRect::default());
        assert_eq!(z.origin(), LogicalPosition::zero());
        assert_eq!(z.size(), LogicalSize::zero());
        assert_eq!(z.into_inner(), LogicalRect::zero());
    }
    #[test]
    fn window_logical_rect_extreme_values_do_not_panic() {
        for (x, y, w, h) in [
            (f32::MAX, f32::MAX, f32::MAX, f32::MAX),
            (f32::MIN, f32::MIN, 0.0, 0.0),
            (f32::INFINITY, f32::NEG_INFINITY, f32::INFINITY, 0.0),
            (f32::NAN, f32::NAN, f32::NAN, f32::NAN),
        ] {
            let r = WindowLogicalRect::new(LogicalPosition::new(x, y), LogicalSize::new(w, h));
            // Accessors must round-trip the raw bits regardless of how odd they are.
            assert_eq!(r.origin().x.to_bits(), x.to_bits());
            assert_eq!(r.size().height.to_bits(), h.to_bits());
            let _ = format!("{r:?}");
        }
    }
    #[test]
    fn border_box_to_content_box_subtracts_padding_and_border() {
        let bb = BorderBoxRect(rect(10.0, 20.0, 100.0, 50.0));
        let padding = crate::solver3::geometry::EdgeSizes {
            top: 1.0,
            right: 2.0,
            bottom: 3.0,
            left: 4.0,
        };
        let border = crate::solver3::geometry::EdgeSizes {
            top: 5.0,
            right: 6.0,
            bottom: 7.0,
            left: 8.0,
        };
        let cb = bb.to_content_box(&padding, &border);
        assert_eq!(cb.rect(), rect(22.0, 26.0, 80.0, 34.0));
        assert_eq!(
            bb.rect(),
            rect(10.0, 20.0, 100.0, 50.0),
            "receiver copy is unchanged"
        );
    }
    #[test]
    fn border_box_to_content_box_zero_edges_is_identity() {
        let bb = BorderBoxRect(rect(1.0, 2.0, 3.0, 4.0));
        let zero = crate::solver3::geometry::EdgeSizes::default();
        assert_eq!(bb.to_content_box(&zero, &zero).rect(), bb.rect());
    }
    #[test]
    fn border_box_to_content_box_overinset_yields_negative_size_not_a_panic() {
        // padding + border exceed the box: the result is a NEGATIVE content box.
        // Nothing clamps it, so downstream code must tolerate it. Pin that here so
        // a future clamp is a deliberate, visible change.
        let bb = BorderBoxRect(rect(0.0, 0.0, 10.0, 10.0));
        let big = crate::solver3::geometry::EdgeSizes {
            top: 50.0,
            right: 50.0,
            bottom: 50.0,
            left: 50.0,
        };
        let cb = bb.to_content_box(&big, &big);
        assert!(cb.rect().size.width < 0.0);
        assert!(cb.rect().size.height < 0.0);
    }
    #[test]
    fn border_box_to_content_box_nan_and_inf_do_not_panic() {
        let bb = BorderBoxRect(rect(0.0, 0.0, f32::MAX, f32::MAX));
        let nan = crate::solver3::geometry::EdgeSizes {
            top: f32::NAN,
            right: f32::NAN,
            bottom: f32::NAN,
            left: f32::NAN,
        };
        let inf = crate::solver3::geometry::EdgeSizes {
            top: f32::INFINITY,
            right: f32::INFINITY,
            bottom: f32::INFINITY,
            left: f32::INFINITY,
        };
        assert!(bb.to_content_box(&nan, &nan).rect().size.width.is_nan());
        // MAX - inf - inf ... = -inf (defined, not a trap)
        assert!(bb
            .to_content_box(&inf, &inf)
            .rect()
            .size
            .width
            .is_infinite());
    }
    #[test]
    fn content_box_rect_getter_returns_wrapped_rect() {
        let r = rect(-1.0, -2.0, 0.0, 0.0);
        assert_eq!(ContentBoxRect(r).rect(), r);
        assert_eq!(
            ContentBoxRect(LogicalRect::zero()).rect(),
            LogicalRect::zero()
        );
    }
    // ---------------------------------------------------------------------
    // BorderRadius::is_zero
    // ---------------------------------------------------------------------
    #[test]
    fn border_radius_is_zero_basic() {
        assert!(BorderRadius::default().is_zero());
        assert!(!BorderRadius {
            top_left: 1.0,
            ..BorderRadius::default()
        }
        .is_zero());
        assert!(!BorderRadius {
            bottom_right: 0.001,
            ..BorderRadius::default()
        }
        .is_zero());
    }
    #[test]
    fn border_radius_is_zero_edge_floats() {
        // -0.0 == 0.0 in IEEE-754, so a negative zero radius still counts as zero.
        assert!(BorderRadius {
            top_left: -0.0,
            top_right: -0.0,
            bottom_left: -0.0,
            bottom_right: -0.0
        }
        .is_zero());
        // NaN != 0.0, so a NaN radius is (conservatively) *not* zero — no panic.
        assert!(!BorderRadius {
            top_left: f32::NAN,
            ..BorderRadius::default()
        }
        .is_zero());
        assert!(!BorderRadius {
            top_right: f32::INFINITY,
            ..BorderRadius::default()
        }
        .is_zero());
        // A negative radius is not zero either.
        assert!(!BorderRadius {
            bottom_left: -5.0,
            ..BorderRadius::default()
        }
        .is_zero());
    }
    // ---------------------------------------------------------------------
    // DisplayListItem predicates / getters
    // ---------------------------------------------------------------------
    #[test]
    fn is_state_management_true_for_push_pop_only() {
        let state = [
            DisplayListItem::PushClip {
                bounds: rect(0.0, 0.0, 1.0, 1.0).into(),
                border_radius: BorderRadius::default(),
            },
            DisplayListItem::PopClip,
            DisplayListItem::PopImageMaskClip,
            DisplayListItem::PopScrollFrame,
            DisplayListItem::PopStackingContext,
            DisplayListItem::PopReferenceFrame,
            DisplayListItem::PopFilter,
            DisplayListItem::PopBackdropFilter,
            DisplayListItem::PopOpacity,
            DisplayListItem::PopTextShadow,
            DisplayListItem::PushStackingContext {
                z_index: 0,
                bounds: WindowLogicalRect::zero(),
            },
            DisplayListItem::PushOpacity {
                bounds: WindowLogicalRect::zero(),
                opacity: 0.5,
                opacity_key: None,
            },
            DisplayListItem::PushTextShadow {
                shadow: StyleBoxShadow::default(),
            },
        ];
        for item in &state {
            assert!(
                item.is_state_management(),
                "{item:?} must be state management"
            );
        }
        let drawing = [
            DisplayListItem::Rect {
                bounds: WindowLogicalRect::zero(),
                color: opaque(),
                border_radius: BorderRadius::default(),
            },
            DisplayListItem::CursorRect {
                bounds: WindowLogicalRect::zero(),
                color: opaque(),
            },
            // HitTestArea paints nothing but is NOT a stack command — it must not be forced
            // through.
            DisplayListItem::HitTestArea {
                bounds: WindowLogicalRect::zero(),
                tag: (0, TAG_TYPE_DOM_NODE),
            },
            text_item(None, LogicalRect::zero(), Vec::new()),
        ];
        for item in &drawing {
            assert!(
                !item.is_state_management(),
                "{item:?} must NOT be state management"
            );
        }
    }
    #[test]
    fn bounds_reports_none_only_for_pop_and_text_shadow() {
        let r = rect(1.0, 2.0, 3.0, 4.0);
        assert_eq!(
            DisplayListItem::Rect {
                bounds: r.into(),
                color: opaque(),
                border_radius: BorderRadius::default()
            }
            .bounds(),
            Some(r)
        );
        // Text reports its CLIP rect as its bounds, not a glyph hull.
        assert_eq!(
            text_item(Some(0), r, vec![glyph(1, 999.0, 999.0)]).bounds(),
            Some(r)
        );
        assert_eq!(
            DisplayListItem::PushScrollFrame {
                clip_bounds: r.into(),
                content_size: LogicalSize::new(9.0, 9.0),
                scroll_id: 3,
            }
            .bounds(),
            Some(r)
        );
        assert_eq!(DisplayListItem::PopClip.bounds(), None);
        assert_eq!(DisplayListItem::PopOpacity.bounds(), None);
        assert_eq!(
            DisplayListItem::PushTextShadow {
                shadow: StyleBoxShadow::default()
            }
            .bounds(),
            None,
            "a text shadow has no bounds of its own"
        );
    }
    #[test]
    fn bounds_on_degenerate_rects_does_not_panic() {
        for r in [
            LogicalRect::zero(),
            rect(f32::NAN, f32::NAN, f32::NAN, f32::NAN),
            rect(f32::MIN, f32::MIN, f32::MAX, f32::MAX),
            rect(0.0, 0.0, -10.0, -10.0),
        ] {
            let item = DisplayListItem::Rect {
                bounds: r.into(),
                color: opaque(),
                border_radius: BorderRadius::default(),
            };
            assert!(item.bounds().is_some());
            assert!(item.visual_bounds().is_some());
        }
    }
    #[test]
    fn visual_bounds_matches_bounds_for_non_shadow_items() {
        let r = rect(5.0, 6.0, 7.0, 8.0);
        let item = DisplayListItem::Rect {
            bounds: r.into(),
            color: opaque(),
            border_radius: BorderRadius::default(),
        };
        assert_eq!(item.visual_bounds(), item.bounds());
        assert_eq!(DisplayListItem::PopClip.visual_bounds(), None);
    }
    #[test]
    fn visual_bounds_expands_box_shadow_by_offset_blur_and_spread() {
        use azul_css::props::basic::pixel::PixelValueNoPercent;
        let shadow = StyleBoxShadow {
            offset_x: PixelValueNoPercent {
                inner: PixelValue::const_px(2),
            },
            offset_y: PixelValueNoPercent {
                inner: PixelValue::const_px(3),
            },
            blur_radius: PixelValueNoPercent {
                inner: PixelValue::const_px(4),
            },
            spread_radius: PixelValueNoPercent {
                inner: PixelValue::const_px(5),
            },
            clip_mode: BoxShadowClipMode::default(),
            color: ColorU::BLACK,
        };
        let item = DisplayListItem::BoxShadow {
            bounds: rect(100.0, 100.0, 50.0, 50.0).into(),
            shadow,
            border_radius: BorderRadius::default(),
        };
        // expand = |2| + |3| + |4| + |5| = 14, applied on every side.
        let vb = item.visual_bounds().expect("box shadow has visual bounds");
        assert_eq!(vb, rect(86.0, 86.0, 78.0, 78.0));
        // The visual bounds must strictly contain the paint bounds.
        let b = item.bounds().unwrap();
        assert!(vb.origin.x < b.origin.x && vb.size.width > b.size.width);
    }
    #[test]
    fn visual_bounds_box_shadow_with_negative_offsets_uses_absolute_values() {
        use azul_css::props::basic::pixel::PixelValueNoPercent;
        let shadow = StyleBoxShadow {
            offset_x: PixelValueNoPercent {
                inner: PixelValue::const_px(-10),
            },
            offset_y: PixelValueNoPercent {
                inner: PixelValue::const_px(-10),
            },
            blur_radius: PixelValueNoPercent {
                inner: PixelValue::const_px(0),
            },
            spread_radius: PixelValueNoPercent {
                inner: PixelValue::const_px(0),
            },
            clip_mode: BoxShadowClipMode::default(),
            color: ColorU::BLACK,
        };
        let item = DisplayListItem::BoxShadow {
            bounds: rect(0.0, 0.0, 10.0, 10.0).into(),
            shadow,
            border_radius: BorderRadius::default(),
        };
        // .abs() is applied, so the shadow expands symmetrically by 20 in each direction.
        assert_eq!(
            item.visual_bounds().unwrap(),
            rect(-20.0, -20.0, 50.0, 50.0)
        );
    }
    // ---------------------------------------------------------------------
    // DisplayListItem::is_visually_equal
    // ---------------------------------------------------------------------
    #[test]
    fn is_visually_equal_reflexive_and_discriminant_guarded() {
        let a = DisplayListItem::Rect {
            bounds: rect(0.0, 0.0, 10.0, 10.0).into(),
            color: opaque(),
            border_radius: BorderRadius::default(),
        };
        assert!(a.is_visually_equal(&a));
        assert!(
            !a.is_visually_equal(&DisplayListItem::PopClip),
            "different variants are never equal"
        );
        assert!(!DisplayListItem::PopClip.is_visually_equal(&a));
    }
    #[test]
    fn is_visually_equal_detects_field_changes() {
        let base = DisplayListItem::Rect {
            bounds: rect(0.0, 0.0, 10.0, 10.0).into(),
            color: opaque(),
            border_radius: BorderRadius::default(),
        };
        let moved = DisplayListItem::Rect {
            bounds: rect(1.0, 0.0, 10.0, 10.0).into(),
            color: opaque(),
            border_radius: BorderRadius::default(),
        };
        let recolored = DisplayListItem::Rect {
            bounds: rect(0.0, 0.0, 10.0, 10.0).into(),
            color: ColorU {
                r: 255,
                g: 0,
                b: 0,
                a: 255,
            },
            border_radius: BorderRadius::default(),
        };
        let rounded = DisplayListItem::Rect {
            bounds: rect(0.0, 0.0, 10.0, 10.0).into(),
            color: opaque(),
            border_radius: BorderRadius {
                top_left: 4.0,
                ..BorderRadius::default()
            },
        };
        assert!(!base.is_visually_equal(&moved));
        assert!(!base.is_visually_equal(&recolored));
        assert!(!base.is_visually_equal(&rounded));
    }
    #[test]
    fn is_visually_equal_pops_are_always_equal() {
        for (a, b) in [
            (DisplayListItem::PopClip, DisplayListItem::PopClip),
            (
                DisplayListItem::PopScrollFrame,
                DisplayListItem::PopScrollFrame,
            ),
            (DisplayListItem::PopOpacity, DisplayListItem::PopOpacity),
            (
                DisplayListItem::PopTextShadow,
                DisplayListItem::PopTextShadow,
            ),
        ] {
            assert!(a.is_visually_equal(&b));
        }
        assert!(!DisplayListItem::PopClip.is_visually_equal(&DisplayListItem::PopOpacity));
    }
    #[test]
    fn is_visually_equal_hit_test_areas_never_damage() {
        // Documented: hit-test areas paint no pixels, so ANY two are visually equal
        // (regression guard for issue #12 — a moved hit region must not force a repaint).
        let a = DisplayListItem::HitTestArea {
            bounds: rect(0.0, 0.0, 1.0, 1.0).into(),
            tag: (1, TAG_TYPE_DOM_NODE),
        };
        let b = DisplayListItem::HitTestArea {
            bounds: rect(500.0, 900.0, 7.0, 7.0).into(),
            tag: (99, TAG_TYPE_CURSOR),
        };
        assert!(a.is_visually_equal(&b));
    }
    #[test]
    fn is_visually_equal_text_layout_uses_arc_pointer_identity() {
        let shared: Arc<dyn std::any::Any + Send + Sync> = Arc::new(42u32);
        let other: Arc<dyn std::any::Any + Send + Sync> = Arc::new(42u32);
        let make = |layout: Arc<dyn std::any::Any + Send + Sync>| DisplayListItem::TextLayout {
            layout,
            bounds: rect(0.0, 0.0, 10.0, 10.0).into(),
            font_hash: FontHash::from_hash(1),
            font_size_px: 16.0,
            color: opaque(),
        };
        assert!(
            make(shared.clone()).is_visually_equal(&make(shared)),
            "same Arc => reuse => no damage"
        );
        assert!(
            !make(Arc::new(42u32)).is_visually_equal(&make(other)),
            "distinct allocations => conservatively different"
        );
    }
    #[test]
    fn is_visually_equal_image_uses_pointer_identity_not_content() {
        let img = test_image();
        let a = DisplayListItem::Image {
            bounds: rect(0.0, 0.0, 4.0, 4.0).into(),
            image: img.clone(),
            border_radius: BorderRadius::default(),
        };
        let same_alloc = DisplayListItem::Image {
            bounds: rect(0.0, 0.0, 4.0, 4.0).into(),
            image: img,
            border_radius: BorderRadius::default(),
        };
        assert!(a.is_visually_equal(&same_alloc));
        // A byte-identical but separately allocated image is conservatively "different".
        let b = DisplayListItem::Image {
            bounds: rect(0.0, 0.0, 4.0, 4.0).into(),
            image: test_image(),
            border_radius: BorderRadius::default(),
        };
        assert!(!a.is_visually_equal(&b));
    }
    #[test]
    fn is_visually_equal_text_compares_glyph_ids_and_positions() {
        let clip = rect(0.0, 0.0, 100.0, 20.0);
        let a = text_item(
            Some(1),
            clip,
            vec![glyph(5, 0.0, 10.0), glyph(6, 8.0, 10.0)],
        );
        let same = text_item(
            Some(999),
            clip,
            vec![glyph(5, 0.0, 10.0), glyph(6, 8.0, 10.0)],
        );
        let diff_gid = text_item(
            Some(1),
            clip,
            vec![glyph(5, 0.0, 10.0), glyph(7, 8.0, 10.0)],
        );
        let diff_pos = text_item(
            Some(1),
            clip,
            vec![glyph(5, 0.0, 10.0), glyph(6, 9.0, 10.0)],
        );
        let shorter = text_item(Some(1), clip, vec![glyph(5, 0.0, 10.0)]);
        let empty = text_item(Some(1), clip, Vec::new());
        assert!(
            a.is_visually_equal(&same),
            "source_node_index is not a visual property"
        );
        assert!(!a.is_visually_equal(&diff_gid));
        assert!(!a.is_visually_equal(&diff_pos));
        assert!(
            !a.is_visually_equal(&shorter),
            "glyph count mismatch => different"
        );
        assert!(!a.is_visually_equal(&empty));
        assert!(
            empty.is_visually_equal(&empty),
            "empty glyph runs are equal to each other"
        );
    }
    #[test]
    fn is_visually_equal_nan_thickness_is_conservatively_unequal() {
        // Raw f32 `==` on thickness: NaN != NaN, so even a self-comparison of a NaN
        // thickness reports "changed". That is the SAFE direction (forces a repaint),
        // and it must not panic.
        let a = DisplayListItem::Underline {
            bounds: rect(0.0, 0.0, 10.0, 1.0).into(),
            color: opaque(),
            thickness: f32::NAN,
        };
        assert!(!a.is_visually_equal(&a));
    }
    #[test]
    fn is_visually_equal_bounds_are_quantized_to_a_thousandth_of_a_pixel() {
        // LogicalRect equality is fixed-point (1/1000 px). Sub-quantum jitter is
        // deliberately treated as "no visual change" so float noise cannot damage.
        let a = DisplayListItem::Rect {
            bounds: rect(0.0, 0.0, 10.0, 10.0).into(),
            color: opaque(),
            border_radius: BorderRadius::default(),
        };
        let jittered = DisplayListItem::Rect {
            bounds: rect(0.000_01, 0.0, 10.0, 10.0).into(),
            color: opaque(),
            border_radius: BorderRadius::default(),
        };
        assert!(a.is_visually_equal(&jittered));
        // A whole-pixel move is above the quantum and *is* reported.
        let moved = DisplayListItem::Rect {
            bounds: rect(1.0, 0.0, 10.0, 10.0).into(),
            color: opaque(),
            border_radius: BorderRadius::default(),
        };
        assert!(!a.is_visually_equal(&moved));
    }
    // ---------------------------------------------------------------------
    // DisplayListBuilder
    // ---------------------------------------------------------------------
    #[test]
    fn builder_new_is_empty_and_matches_with_debug_false() {
        let b = DisplayListBuilder::new();
        assert!(b.items.is_empty());
        assert!(b.node_mapping.is_empty());
        assert!(!b.debug_enabled);
        assert!(b.forced_page_breaks.is_empty());
        assert!(b.fixed_position_item_ranges.is_empty());
        assert!(b.fixed_position_start.is_none());
        let dl = DisplayListBuilder::new().build();
        assert!(dl.items.is_empty());
        assert!(dl.node_mapping.is_empty());
    }
    #[test]
    fn builder_with_debug_toggles_message_collection() {
        let mut off = DisplayListBuilder::with_debug(false);
        off.debug_log("dropped".to_string());
        assert!(off.debug_messages.is_empty());
        let mut on = DisplayListBuilder::with_debug(true);
        on.debug_log(String::new());
        on.debug_log("x".repeat(100_000)); // huge message must not panic
        on.debug_log("🦀 unicode \u{0}\u{FFFD} nul".to_string());
        assert_eq!(on.debug_messages.len(), 3);
    }
    #[test]
    fn builder_push_item_keeps_node_mapping_in_lockstep() {
        let mut b = DisplayListBuilder::new();
        b.set_current_node(Some(NodeId::new(4)));
        b.push_rect(rect(0.0, 0.0, 1.0, 1.0), opaque(), BorderRadius::default());
        b.set_current_node(None);
        b.pop_clip();
        let dl = b.build();
        assert_eq!(dl.items.len(), 2);
        assert_eq!(
            dl.items.len(),
            dl.node_mapping.len(),
            "node_mapping must parallel items"
        );
        assert_eq!(dl.node_mapping[0], Some(NodeId::new(4)));
        assert_eq!(dl.node_mapping[1], None);
    }
    #[test]
    fn builder_skips_fully_transparent_fills() {
        let mut b = DisplayListBuilder::new();
        b.push_rect(
            rect(0.0, 0.0, 10.0, 10.0),
            ColorU::TRANSPARENT,
            BorderRadius::default(),
        );
        b.push_selection_rect(
            rect(0.0, 0.0, 10.0, 10.0),
            ColorU::TRANSPARENT,
            BorderRadius::default(),
        );
        b.push_scrollbar(
            rect(0.0, 0.0, 10.0, 10.0),
            ColorU::TRANSPARENT,
            ScrollbarOrientation::Vertical,
            None,
            None,
        );
        assert!(
            b.items.is_empty(),
            "alpha == 0 with no opacity key paints nothing"
        );
        // An opacity key means the alpha is animated on the GPU — it must still be pushed.
        b.push_scrollbar(
            rect(0.0, 0.0, 10.0, 10.0),
            ColorU::TRANSPARENT,
            ScrollbarOrientation::Vertical,
            Some(OpacityKey::unique()),
            None,
        );
        assert_eq!(b.items.len(), 1);
    }
    #[test]
    fn builder_cursor_rect_is_emitted_even_when_invisible() {
        // Blink-off carets MUST still emit an item so the item count stays stable
        // across blink phases (otherwise damage falls back to a full-window repaint).
        let mut b = DisplayListBuilder::new();
        b.push_cursor_rect(rect(0.0, 0.0, 1.0, 16.0), ColorU::TRANSPARENT);
        assert_eq!(b.items.len(), 1);
        assert!(matches!(b.items[0], DisplayListItem::CursorRect { .. }));
    }
    #[test]
    fn builder_text_decorations_require_positive_thickness_and_alpha() {
        let bounds = rect(0.0, 0.0, 10.0, 2.0);
        for thickness in [0.0, -1.0, f32::NAN, f32::NEG_INFINITY] {
            let mut b = DisplayListBuilder::new();
            b.push_underline(bounds, opaque(), thickness);
            b.push_strikethrough(bounds, opaque(), thickness);
            b.push_overline(bounds, opaque(), thickness);
            assert!(b.items.is_empty(), "thickness {thickness} must not paint");
        }
        // +inf is > 0.0, so it *is* pushed (defined, no panic).
        let mut b = DisplayListBuilder::new();
        b.push_underline(bounds, opaque(), f32::INFINITY);
        assert_eq!(b.items.len(), 1);
        // Transparent decorations are skipped regardless of thickness.
        let mut b = DisplayListBuilder::new();
        b.push_overline(bounds, ColorU::TRANSPARENT, 3.0);
        assert!(b.items.is_empty());
    }
    #[test]
    fn builder_text_run_skips_empty_glyphs_and_transparent_color() {
        let clip = rect(0.0, 0.0, 100.0, 20.0);
        let mut b = DisplayListBuilder::new();
        b.push_text_run(
            Vec::new(),
            FontHash::invalid(),
            16.0,
            opaque(),
            clip,
            Some(0),
            None,
        );
        b.push_text_run(
            vec![glyph(1, 0.0, 0.0)],
            FontHash::invalid(),
            16.0,
            ColorU::TRANSPARENT,
            clip,
            Some(0),
            None,
        );
        assert!(b.items.is_empty());
        // NaN / huge font sizes are pass-through values, not a panic.
        b.push_text_run(
            vec![glyph(1, 0.0, 0.0)],
            FontHash::invalid(),
            f32::NAN,
            opaque(),
            clip,
            None,
            None,
        );
        b.push_text_run(
            vec![glyph(2, 0.0, 0.0)],
            FontHash::invalid(),
            f32::MAX,
            opaque(),
            clip,
            None,
            None,
        );
        assert_eq!(b.items.len(), 2);
    }
    #[test]
    fn builder_border_requires_a_positive_width_and_a_drawing_style() {
        let bounds = rect(0.0, 0.0, 10.0, 10.0);
        let mut b = DisplayListBuilder::new();
        b.push_border(
            bounds,
            no_widths(),
            no_colors(),
            no_styles(),
            zero_style_radius(),
        );
        assert!(
            b.items.is_empty(),
            "no widths + no styles => nothing to draw"
        );
        let mut b = DisplayListBuilder::new();
        b.push_border(
            bounds,
            all_widths(),
            no_colors(),
            no_styles(),
            zero_style_radius(),
        );
        assert!(b.items.is_empty(), "width without style => nothing to draw");
        let mut b = DisplayListBuilder::new();
        b.push_border(
            bounds,
            no_widths(),
            no_colors(),
            all_solid_styles(),
            zero_style_radius(),
        );
        assert!(b.items.is_empty(), "style without width => nothing to draw");
        // THE CLASS: the compact cache's answer for an UNSET border — every
        // side `Some(0px)` with style `Some(none)` — must not become an item,
        // or every normal-state node carries a phantom Border that its
        // hovered/focused self (slow path: `None`) does not.
        let mut b = DisplayListBuilder::new();
        b.push_border(
            bounds,
            zero_widths(),
            no_colors(),
            all_styles(),
            zero_style_radius(),
        );
        assert!(
            b.items.is_empty(),
            "0px + style none (the unset encoding) => nothing to draw"
        );
        let mut b = DisplayListBuilder::new();
        b.push_border(
            bounds,
            all_widths(),
            no_colors(),
            all_styles(),
            zero_style_radius(),
        );
        assert!(
            b.items.is_empty(),
            "3px + style none paints nothing (CSS: none zeroes the width)"
        );
        let mut b = DisplayListBuilder::new();
        b.push_border(
            bounds,
            zero_widths(),
            no_colors(),
            all_solid_styles(),
            zero_style_radius(),
        );
        assert!(b.items.is_empty(), "0px solid => nothing to draw");
        let mut b = DisplayListBuilder::new();
        b.push_border(
            bounds,
            all_widths(),
            no_colors(),
            all_solid_styles(),
            zero_style_radius(),
        );
        assert_eq!(b.items.len(), 1, "3px solid paints");
        // One painting side is enough.
        let mut one_side = zero_widths();
        one_side.left = Some(CssPropertyValue::Exact(LayoutBorderLeftWidth {
            inner: PixelValue::px(1.0),
        }));
        let mut b = DisplayListBuilder::new();
        b.push_border(
            bounds,
            one_side,
            no_colors(),
            all_solid_styles(),
            zero_style_radius(),
        );
        assert_eq!(b.items.len(), 1, "a single 1px solid side paints");
    }
    #[test]
    fn builder_forced_page_breaks_are_deduped_and_sorted() {
        let mut b = DisplayListBuilder::new();
        b.add_forced_page_break(300.0, None);
        b.add_forced_page_break(100.0, None);
        b.add_forced_page_break(300.0, None); // exact duplicate
        b.add_forced_page_break(200.0, None);
        b.add_forced_page_break(0.0, None);
        b.add_forced_page_break(-50.0, None); // negative is accepted verbatim
        b.add_forced_page_break(f32::INFINITY, None);
        b.add_forced_page_break(f32::NEG_INFINITY, None);
        assert_eq!(
            b.forced_page_breaks
                .iter()
                .map(|fb| fb.y)
                .collect::<Vec<_>>(),
            vec![
                f32::NEG_INFINITY,
                -50.0,
                0.0,
                100.0,
                200.0,
                300.0,
                f32::INFINITY
            ]
        );
    }
    #[test]
    fn builder_forced_page_break_nan_is_never_deduped() {
        // `contains(&NaN)` is always false (NaN != NaN), so NaN breaks are NOT deduped —
        // repeated calls accumulate. The sort uses partial_cmp().unwrap_or(Equal), so it
        // survives the non-total order rather than panicking on an `unwrap`.
        let mut b = DisplayListBuilder::new();
        b.add_forced_page_break(f32::NAN, None);
        b.add_forced_page_break(f32::NAN, None);
        b.add_forced_page_break(100.0, None);
        assert_eq!(
            b.forced_page_breaks.len(),
            3,
            "a NaN break is never deduped"
        );
        assert_eq!(
            b.forced_page_breaks.iter().filter(|v| v.y.is_nan()).count(),
            2
        );
    }
    #[test]
    fn builder_fixed_position_ranges_need_a_begin_and_at_least_one_item() {
        // end without begin: no-op, no panic.
        let mut b = DisplayListBuilder::new();
        b.end_fixed_position_element();
        assert!(b.fixed_position_item_ranges.is_empty());
        // begin + end with zero items in between: nothing recorded (end > start is false).
        let mut b = DisplayListBuilder::new();
        b.begin_fixed_position_element();
        b.end_fixed_position_element();
        assert!(b.fixed_position_item_ranges.is_empty());
        // begin + items + end: the half-open [start, end) range is recorded.
        let mut b = DisplayListBuilder::new();
        b.pop_clip(); // one pre-existing item at index 0
        b.begin_fixed_position_element();
        b.push_rect(rect(0.0, 0.0, 1.0, 1.0), opaque(), BorderRadius::default());
        b.push_rect(rect(0.0, 0.0, 2.0, 2.0), opaque(), BorderRadius::default());
        b.end_fixed_position_element();
        assert_eq!(b.fixed_position_item_ranges, vec![(1, 3)]);
        // A second end() without a matching begin() must not re-record.
        b.end_fixed_position_element();
        assert_eq!(b.fixed_position_item_ranges.len(), 1);
    }
    #[test]
    fn builder_build_with_debug_transfers_messages() {
        let mut b = DisplayListBuilder::with_debug(true);
        b.debug_log("hello".to_string());
        b.push_rect(rect(0.0, 0.0, 1.0, 1.0), opaque(), BorderRadius::default());
        let mut sink = Some(vec![LayoutDebugMessage::info("pre-existing".to_string())]);
        let dl = b.build_with_debug(&mut sink);
        let msgs = sink.expect("sink stays Some");
        assert_eq!(msgs.len(), 2, "messages are appended, not replaced");
        assert_eq!(dl.items.len(), 1);
        // A None sink must swallow the messages rather than panic.
        let mut b = DisplayListBuilder::with_debug(true);
        b.debug_log("dropped".to_string());
        let mut none_sink: Option<Vec<LayoutDebugMessage>> = None;
        let dl = b.build_with_debug(&mut none_sink);
        assert!(none_sink.is_none());
        assert!(dl.items.is_empty());
    }
    #[test]
    fn builder_stack_pushes_accept_extreme_arguments() {
        let mut b = DisplayListBuilder::new();
        // i32 extremes for z-index, degenerate bounds, and an all-NaN clip.
        b.push_stacking_context(i32::MIN, rect(f32::NAN, f32::NAN, f32::NAN, f32::NAN));
        b.push_stacking_context(i32::MAX, rect(0.0, 0.0, -1.0, -1.0));
        b.pop_stacking_context();
        b.push_clip(
            rect(f32::MIN, f32::MIN, f32::MAX, f32::MAX),
            BorderRadius {
                top_left: f32::INFINITY,
                ..BorderRadius::default()
            },
        );
        b.pop_clip();
        b.push_scroll_frame(
            LogicalRect::zero(),
            LogicalSize::new(f32::MAX, f32::MAX),
            u64::MAX,
        );
        b.pop_scroll_frame();
        b.push_image_mask_clip(
            LogicalRect::zero(),
            test_image(),
            rect(0.0, 0.0, -5.0, -5.0),
        );
        b.pop_image_mask_clip();
        b.push_reference_frame(
            TransformKey::unique(),
            ComputedTransform3D::IDENTITY,
            LogicalRect::zero(),
        );
        b.pop_reference_frame();
        b.push_virtual_view_placeholder(NodeId::ZERO, LogicalRect::zero(), LogicalRect::zero());
        b.push_hit_test_area(rect(0.0, 0.0, 1.0, 1.0), (u64::MAX, TAG_TYPE_CURSOR));
        b.push_image(LogicalRect::zero(), test_image(), BorderRadius::default());
        b.push_linear_gradient(
            LogicalRect::zero(),
            LinearGradient::default(),
            BorderRadius::default(),
        );
        b.push_radial_gradient(
            LogicalRect::zero(),
            RadialGradient::default(),
            BorderRadius::default(),
        );
        b.push_conic_gradient(
            LogicalRect::zero(),
            ConicGradient::default(),
            BorderRadius::default(),
        );
        let dl = b.build();
        // 17 until push_item started dropping items at the unassigned-position
        // sentinel. Two pushes above use NaN / f32::MIN ORIGINS — the NaN
        // stacking context and the f32::MIN clip — and those are exactly what
        // the drop exists to remove, so they no longer reach the list. The
        // point of this test is that extreme arguments do not PANIC and do not
        // desync the node mapping; both still hold.
        assert_eq!(
            dl.items.len(),
            15,
            "expected the NaN-origin stacking context and the f32::MIN-origin clip to be dropped \
             as unassigned positions; everything else is real geometry and must survive"
        );
        assert_eq!(dl.items.len(), dl.node_mapping.len());
        // The mapping must stay in lockstep — dropping an item without dropping
        // its node entry would misattribute every later item to the wrong node.
        assert!(
            !dl.items.is_empty(),
            "the drop must not swallow well-formed items"
        );
    }
    // ---------------------------------------------------------------------
    // Free geometry helpers: rect_intersects / clip_rect_bounds / offset_rect_y
    // ---------------------------------------------------------------------
    #[test]
    fn rect_intersects_uses_a_half_open_page_interval() {
        let page = (100.0f32, 200.0f32);
        // Fully inside.
        assert!(rect_intersects(
            &rect(0.0, 120.0, 10.0, 10.0),
            page.0,
            page.1
        ));
        // Straddling both edges.
        assert!(rect_intersects(
            &rect(0.0, 50.0, 10.0, 300.0),
            page.0,
            page.1
        ));
        // Entirely above / below.
        assert!(!rect_intersects(
            &rect(0.0, 0.0, 10.0, 10.0),
            page.0,
            page.1
        ));
        assert!(!rect_intersects(
            &rect(0.0, 500.0, 10.0, 10.0),
            page.0,
            page.1
        ));
        // Touching exactly: bottom edge == page_top is NOT an intersection...
        assert!(!rect_intersects(
            &rect(0.0, 90.0, 10.0, 10.0),
            page.0,
            page.1
        ));
        // ...and top edge == page_bottom is NOT either.
        assert!(!rect_intersects(
            &rect(0.0, 200.0, 10.0, 10.0),
            page.0,
            page.1
        ));
        // A zero-height rect strictly inside DOES intersect (its single edge is in range).
        assert!(rect_intersects(
            &rect(0.0, 150.0, 10.0, 0.0),
            page.0,
            page.1
        ));
        // ...but a zero-height rect sitting exactly on either page edge does not.
        assert!(!rect_intersects(
            &rect(0.0, 100.0, 10.0, 0.0),
            page.0,
            page.1
        ));
        assert!(!rect_intersects(
            &rect(0.0, 200.0, 10.0, 0.0),
            page.0,
            page.1
        ));
    }
    #[test]
    fn rect_intersects_with_nan_is_false_not_a_panic() {
        assert!(!rect_intersects(
            &rect(0.0, f32::NAN, 10.0, 10.0),
            0.0,
            100.0
        ));
        assert!(!rect_intersects(
            &rect(0.0, 10.0, 10.0, f32::NAN),
            0.0,
            100.0
        ));
        assert!(!rect_intersects(
            &rect(0.0, 10.0, 10.0, 10.0),
            f32::NAN,
            f32::NAN
        ));
        // Infinite page bounds cover everything finite.
        assert!(rect_intersects(
            &rect(0.0, 10.0, 10.0, 10.0),
            f32::NEG_INFINITY,
            f32::INFINITY
        ));
    }
    #[test]
    fn clip_rect_bounds_clips_and_rebases_to_page_relative_coords() {
        // Item straddles the top of page [100, 200): keep the visible slice, rebase to y=0.
        let clipped = clip_rect_bounds(rect(5.0, 50.0, 20.0, 100.0), 100.0, 200.0).unwrap();
        assert_eq!(clipped, rect(5.0, 0.0, 20.0, 50.0));
        // Item straddles the bottom: kept slice starts at its own offset into the page.
        let clipped = clip_rect_bounds(rect(5.0, 180.0, 20.0, 100.0), 100.0, 200.0).unwrap();
        assert_eq!(clipped, rect(5.0, 80.0, 20.0, 20.0));
        // Item strictly inside: only rebased, never resized.
        let clipped = clip_rect_bounds(rect(5.0, 120.0, 20.0, 30.0), 100.0, 200.0).unwrap();
        assert_eq!(clipped, rect(5.0, 20.0, 20.0, 30.0));
        // Item larger than the page on both sides: clamped to exactly the page height.
        let clipped = clip_rect_bounds(rect(0.0, 0.0, 20.0, 10_000.0), 100.0, 200.0).unwrap();
        assert_eq!(clipped, rect(0.0, 0.0, 20.0, 100.0));
    }
    #[test]
    fn clip_rect_bounds_rejects_off_page_and_edge_touching_rects() {
        assert_eq!(
            clip_rect_bounds(rect(0.0, 0.0, 10.0, 10.0), 100.0, 200.0),
            None
        );
        assert_eq!(
            clip_rect_bounds(rect(0.0, 300.0, 10.0, 10.0), 100.0, 200.0),
            None
        );
        // bottom == page_top -> outside (half-open interval).
        assert_eq!(
            clip_rect_bounds(rect(0.0, 90.0, 10.0, 10.0), 100.0, 200.0),
            None
        );
        // top == page_bottom -> outside.
        assert_eq!(
            clip_rect_bounds(rect(0.0, 200.0, 10.0, 10.0), 100.0, 200.0),
            None
        );
    }
    #[test]
    fn clip_rect_bounds_zero_height_rects() {
        // A zero-height rect sitting exactly on page_top is rejected (bottom <= top).
        assert_eq!(
            clip_rect_bounds(rect(0.0, 100.0, 10.0, 0.0), 100.0, 200.0),
            None
        );
        // A zero-height rect strictly inside survives as a zero-height slice.
        assert_eq!(
            clip_rect_bounds(rect(0.0, 150.0, 10.0, 0.0), 100.0, 200.0),
            Some(rect(0.0, 50.0, 10.0, 0.0))
        );
    }
    #[test]
    fn clip_rect_bounds_with_an_inverted_page_produces_a_degenerate_rect_not_a_panic() {
        // page_top > page_bottom is never produced by calculate_page_break_positions,
        // but nothing rejects it here: the height goes NEGATIVE. Pinned so the missing
        // guard is visible rather than silently feeding a negative rect downstream.
        let out = clip_rect_bounds(rect(0.0, 0.0, 10.0, 500.0), 200.0, 100.0)
            .expect("an inverted page is not rejected");
        assert!(
            out.size.height < 0.0,
            "no clamp: an inverted page yields a negative height"
        );
    }
    #[test]
    fn clip_rect_bounds_with_extreme_pages_does_not_panic() {
        // An unbounded page keeps the item intact (no clipping).
        let full = clip_rect_bounds(
            rect(0.0, 10.0, 10.0, 10.0),
            f32::NEG_INFINITY,
            f32::INFINITY,
        )
        .expect("an infinite page contains everything");
        assert_eq!(full.size, LogicalSize::new(10.0, 10.0));
        // NaN page bounds: every comparison is false, so the rect is kept. f32::max/min
        // drop the NaN operand, so the SIZE stays clean and only the rebased origin goes
        // NaN. Defined, total, and crucially NOT a panic.
        let nan_page = clip_rect_bounds(rect(0.0, 10.0, 10.0, 10.0), f32::NAN, f32::NAN)
            .expect("NaN bounds fail both rejection tests");
        assert!(
            nan_page.origin.y.is_nan(),
            "the page-relative rebase propagates NaN"
        );
        assert_eq!(
            nan_page.size.height, 10.0,
            "min/max ignore NaN, so the height survives"
        );
        // f32::MAX height must not overflow into a panic.
        assert_eq!(
            clip_rect_bounds(rect(0.0, 0.0, 10.0, f32::MAX), 0.0, 100.0),
            Some(rect(0.0, 0.0, 10.0, 100.0))
        );
    }
    #[test]
    fn offset_rect_y_only_moves_y_and_preserves_size() {
        assert_eq!(
            offset_rect_y(rect(1.0, 2.0, 3.0, 4.0), 0.0),
            rect(1.0, 2.0, 3.0, 4.0)
        );
        assert_eq!(
            offset_rect_y(rect(1.0, 2.0, 3.0, 4.0), 10.0),
            rect(1.0, 12.0, 3.0, 4.0)
        );
        assert_eq!(
            offset_rect_y(rect(1.0, 2.0, 3.0, 4.0), -10.0),
            rect(1.0, -8.0, 3.0, 4.0)
        );
        // Non-finite offsets are propagated, never trapped.
        assert!(offset_rect_y(rect(0.0, 0.0, 1.0, 1.0), f32::INFINITY)
            .origin
            .y
            .is_infinite());
        assert!(offset_rect_y(rect(0.0, 0.0, 1.0, 1.0), f32::NAN)
            .origin
            .y
            .is_nan());
        // MAX + MAX saturates to +inf under IEEE-754, not a wrap.
        assert!(offset_rect_y(rect(0.0, f32::MAX, 1.0, 1.0), f32::MAX)
            .origin
            .y
            .is_infinite());
        // The size is untouched in every case.
        assert_eq!(
            offset_rect_y(rect(0.0, 0.0, 3.0, 4.0), f32::NAN).size,
            LogicalSize::new(3.0, 4.0)
        );
    }
    // ---------------------------------------------------------------------
    // Per-item page clipping
    // ---------------------------------------------------------------------
    #[test]
    fn clip_rect_item_drops_off_page_and_rebases_on_page() {
        assert!(clip_rect_item(
            rect(0.0, 0.0, 10.0, 10.0),
            opaque(),
            BorderRadius::default(),
            100.0,
            200.0
        )
        .is_none());
        let item = clip_rect_item(
            rect(0.0, 150.0, 10.0, 100.0),
            opaque(),
            BorderRadius::default(),
            100.0,
            200.0,
        )
        .expect("overlaps the page");
        match item {
            DisplayListItem::Rect { bounds, color, .. } => {
                assert_eq!(bounds.into_inner(), rect(0.0, 50.0, 10.0, 50.0));
                assert_eq!(color, opaque());
            }
            other => panic!("expected Rect, got {other:?}"),
        }
    }
    #[test]
    fn clip_cursor_selection_hittest_and_scrollbar_items_share_the_page_test() {
        let off = rect(0.0, 0.0, 10.0, 10.0);
        let on = rect(0.0, 120.0, 10.0, 10.0);
        let (top, bottom) = (100.0, 200.0);
        assert!(clip_cursor_rect_item(off, opaque(), top, bottom).is_none());
        assert!(clip_cursor_rect_item(on, opaque(), top, bottom).is_some());
        assert!(
            clip_selection_rect_item(off, BorderRadius::default(), opaque(), top, bottom).is_none()
        );
        assert!(
            clip_selection_rect_item(on, BorderRadius::default(), opaque(), top, bottom).is_some()
        );
        assert!(clip_hit_test_area_item(off, (1, TAG_TYPE_DOM_NODE), top, bottom).is_none());
        assert!(clip_hit_test_area_item(on, (1, TAG_TYPE_DOM_NODE), top, bottom).is_some());
        assert!(clip_scrollbar_item(
            off,
            opaque(),
            ScrollbarOrientation::Vertical,
            None,
            None,
            top,
            bottom
        )
        .is_none());
        assert!(clip_scrollbar_item(
            on,
            opaque(),
            ScrollbarOrientation::Vertical,
            None,
            None,
            top,
            bottom
        )
        .is_some());
        assert!(clip_image_item(off, test_image(), BorderRadius::default(), top, bottom).is_none());
        assert!(clip_image_item(on, test_image(), BorderRadius::default(), top, bottom).is_some());
        let no_shift = LogicalPosition::zero();
        assert!(clip_virtual_view_item(DomId::ROOT_ID, off, off, no_shift, top, bottom).is_none());
        assert!(clip_virtual_view_item(DomId::ROOT_ID, on, on, no_shift, top, bottom).is_some());
    }
    #[test]
    fn clip_text_decoration_item_preserves_the_decoration_kind() {
        let on = rect(0.0, 120.0, 10.0, 2.0);
        let (top, bottom) = (100.0, 200.0);
        assert!(matches!(
            clip_text_decoration_item(
                on,
                opaque(),
                1.0,
                TextDecorationType::Underline,
                top,
                bottom
            ),
            Some(DisplayListItem::Underline { .. })
        ));
        assert!(matches!(
            clip_text_decoration_item(
                on,
                opaque(),
                1.0,
                TextDecorationType::Strikethrough,
                top,
                bottom
            ),
            Some(DisplayListItem::Strikethrough { .. })
        ));
        assert!(matches!(
            clip_text_decoration_item(on, opaque(), 1.0, TextDecorationType::Overline, top, bottom),
            Some(DisplayListItem::Overline { .. })
        ));
        // Off-page decorations are dropped even with a NaN thickness.
        assert!(clip_text_decoration_item(
            rect(0.0, 0.0, 10.0, 2.0),
            opaque(),
            f32::NAN,
            TextDecorationType::Underline,
            top,
            bottom
        )
        .is_none());
    }
    #[test]
    fn clip_text_item_filters_glyphs_by_baseline_into_a_half_open_page() {
        let clip = rect(0.0, 90.0, 200.0, 120.0);
        let glyphs = vec![
            glyph(1, 0.0, 99.0),   // above page  -> dropped
            glyph(2, 8.0, 100.0),  // exactly page_top -> KEPT (>= top)
            glyph(3, 16.0, 150.0), // inside -> kept
            glyph(4, 24.0, 200.0), // exactly page_bottom -> dropped (< bottom)
            glyph(5, 32.0, 250.0), // below -> dropped
        ];
        let item = clip_text_item(
            &glyphs,
            FontHash::from_hash(9),
            16.0,
            opaque(),
            clip,
            100.0,
            200.0,
        )
        .expect("some glyphs are on the page");
        match item {
            DisplayListItem::Text {
                glyphs: kept,
                clip_rect,
                source_node_index,
                ..
            } => {
                assert_eq!(kept.iter().map(|g| g.index).collect::<Vec<_>>(), vec![2, 3]);
                // Kept glyphs are rebased to page-relative Y.
                assert_eq!(kept[0].point.y, 0.0);
                assert_eq!(kept[1].point.y, 50.0);
                // X is never touched.
                assert_eq!(kept[0].point.x, 8.0);
                assert_eq!(clip_rect.into_inner().origin.y, -10.0);
                assert_eq!(
                    source_node_index, None,
                    "the paginated copy loses its source node"
                );
            }
            other => panic!("expected Text, got {other:?}"),
        }
    }
    #[test]
    fn clip_text_item_returns_none_when_nothing_survives() {
        let clip = rect(0.0, 90.0, 200.0, 120.0);
        // The clip rect overlaps the page but no glyph baseline does.
        let outside = vec![glyph(1, 0.0, 95.0), glyph(2, 8.0, 400.0)];
        assert!(clip_text_item(
            &outside,
            FontHash::from_hash(1),
            16.0,
            opaque(),
            clip,
            100.0,
            200.0
        )
        .is_none());
        // An empty glyph run is dropped too.
        assert!(clip_text_item(
            &[],
            FontHash::from_hash(1),
            16.0,
            opaque(),
            clip,
            100.0,
            200.0
        )
        .is_none());
        // A clip rect entirely off the page short-circuits before glyph filtering.
        assert!(clip_text_item(
            &[glyph(1, 0.0, 150.0)],
            FontHash::from_hash(1),
            16.0,
            opaque(),
            rect(0.0, 0.0, 10.0, 10.0),
            100.0,
            200.0
        )
        .is_none());
        // NaN glyph baselines never satisfy either bound -> filtered out -> None.
        let nan_glyphs = vec![glyph(1, 0.0, f32::NAN)];
        assert!(clip_text_item(
            &nan_glyphs,
            FontHash::from_hash(1),
            16.0,
            opaque(),
            clip,
            100.0,
            200.0
        )
        .is_none());
    }
    #[test]
    fn clip_border_item_hides_the_bottom_border_when_clipped_at_the_bottom() {
        let (top, bottom) = (100.0f32, 200.0f32);
        // Spans past the bottom of the page.
        let original = rect(0.0, 50.0, 100.0, 200.0);
        let item = clip_border_item(
            original,
            all_widths(),
            no_colors(),
            all_styles(),
            zero_style_radius(),
            top,
            bottom,
        )
        .expect("overlaps the page");
        match item {
            DisplayListItem::Border { widths, .. } => {
                assert!(
                    widths.bottom.is_none(),
                    "a border cut by the page edge must not draw its bottom rule"
                );
                assert!(
                    widths.left.is_some() && widths.right.is_some(),
                    "side borders survive"
                );
            }
            other => panic!("expected Border, got {other:?}"),
        }
    }
    #[test]
    fn adjust_border_widths_keeps_every_side_for_a_fully_contained_border() {
        let (top, bottom) = (100.0f32, 200.0f32);
        let original = rect(0.0, 110.0, 100.0, 50.0); // strictly inside the page
        let clipped = clip_rect_bounds(original, top, bottom).unwrap();
        assert_eq!(
            clipped,
            rect(0.0, 10.0, 100.0, 50.0),
            "unclipped => only rebased"
        );
        let widths =
            adjust_border_widths_for_clipping(all_widths(), original, clipped, top, bottom);
        assert!(widths.top.is_some());
        assert!(widths.bottom.is_some());
        assert!(widths.left.is_some());
        assert!(widths.right.is_some());
    }
    #[test]
    fn adjust_border_widths_with_nan_page_bounds_does_not_panic() {
        let original = rect(0.0, 0.0, 10.0, 10.0);
        let clipped = rect(0.0, 0.0, 10.0, 10.0);
        let w =
            adjust_border_widths_for_clipping(all_widths(), original, clipped, f32::NAN, f32::NAN);
        // Every NaN comparison is false, so nothing is hidden — defined and total.
        assert!(w.top.is_some() && w.bottom.is_some());
    }
    #[test]
    fn clip_and_offset_display_item_drops_state_management_commands() {
        // Pagination cannot re-derive a clip/scroll/stacking stack per page, so those
        // items are deliberately dropped. Pin it so a change is visible.
        for item in [
            DisplayListItem::PushClip {
                bounds: rect(0.0, 120.0, 10.0, 10.0).into(),
                border_radius: BorderRadius::default(),
            },
            DisplayListItem::PopClip,
            DisplayListItem::PushScrollFrame {
                clip_bounds: rect(0.0, 120.0, 10.0, 10.0).into(),
                content_size: LogicalSize::new(10.0, 10.0),
                scroll_id: 1,
            },
            DisplayListItem::PopScrollFrame,
            DisplayListItem::PushStackingContext {
                z_index: 0,
                bounds: rect(0.0, 120.0, 10.0, 10.0).into(),
            },
            DisplayListItem::PopStackingContext,
            DisplayListItem::PopOpacity,
            DisplayListItem::PopTextShadow,
            DisplayListItem::VirtualViewPlaceholder {
                node_id: NodeId::ZERO,
                bounds: rect(0.0, 120.0, 10.0, 10.0).into(),
                clip_rect: rect(0.0, 120.0, 10.0, 10.0).into(),
            },
        ] {
            assert!(
                clip_and_offset_display_item(&item, 100.0, 200.0).is_none(),
                "{item:?} must be dropped by the paginator"
            );
        }
    }
    #[test]
    fn clip_and_offset_display_item_dispatches_drawing_items() {
        let on_page = DisplayListItem::Rect {
            bounds: rect(0.0, 150.0, 10.0, 10.0).into(),
            color: opaque(),
            border_radius: BorderRadius::default(),
        };
        let clipped = clip_and_offset_display_item(&on_page, 100.0, 200.0).expect("on page");
        assert_eq!(clipped.bounds(), Some(rect(0.0, 50.0, 10.0, 10.0)));
        let off_page = DisplayListItem::Rect {
            bounds: rect(0.0, 0.0, 10.0, 10.0).into(),
            color: opaque(),
            border_radius: BorderRadius::default(),
        };
        assert!(clip_and_offset_display_item(&off_page, 100.0, 200.0).is_none());
        // Gradients use a plain bounds test (no sub-item filtering).
        let grad = DisplayListItem::LinearGradient {
            bounds: rect(0.0, 150.0, 10.0, 10.0).into(),
            gradient: LinearGradient::default(),
            border_radius: BorderRadius::default(),
        };
        assert!(clip_and_offset_display_item(&grad, 100.0, 200.0).is_some());
        assert!(clip_and_offset_display_item(&grad, 1000.0, 2000.0).is_none());
    }
    // ---------------------------------------------------------------------
    // get_display_item_bounds / offset_display_item_y / heights
    // ---------------------------------------------------------------------
    #[test]
    fn get_display_item_bounds_mirrors_item_bounds() {
        let r = rect(1.0, 2.0, 3.0, 4.0);
        let item = DisplayListItem::Rect {
            bounds: r.into(),
            color: opaque(),
            border_radius: BorderRadius::default(),
        };
        assert_eq!(
            get_display_item_bounds(&item),
            Some(WindowLogicalRect::from(r))
        );
        assert_eq!(get_display_item_bounds(&DisplayListItem::PopClip), None);
    }
    #[test]
    fn offset_display_item_y_zero_offset_is_a_pure_clone() {
        let item = text_item(
            Some(3),
            rect(0.0, 10.0, 100.0, 20.0),
            vec![glyph(1, 5.0, 15.0)],
        );
        let same = offset_display_item_y(&item, 0.0);
        assert!(item.is_visually_equal(&same));
        assert_eq!(same.bounds(), item.bounds());
    }
    #[test]
    fn offset_display_item_y_moves_glyphs_and_clip_together() {
        let item = text_item(
            Some(3),
            rect(0.0, 10.0, 100.0, 20.0),
            vec![glyph(1, 5.0, 15.0), glyph(2, 13.0, 15.0)],
        );
        match offset_display_item_y(&item, -10.0) {
            DisplayListItem::Text {
                glyphs, clip_rect, ..
            } => {
                assert_eq!(clip_rect.into_inner(), rect(0.0, 0.0, 100.0, 20.0));
                assert_eq!(glyphs[0].point.y, 5.0);
                assert_eq!(glyphs[1].point.y, 5.0);
                assert_eq!(glyphs[0].point.x, 5.0, "X must not move");
            }
            other => panic!("expected Text, got {other:?}"),
        }
    }
    #[test]
    fn offset_display_item_y_with_nonfinite_offsets_does_not_panic() {
        let item = DisplayListItem::Rect {
            bounds: rect(0.0, 10.0, 5.0, 5.0).into(),
            color: opaque(),
            border_radius: BorderRadius::default(),
        };
        assert!(offset_display_item_y(&item, f32::NAN)
            .bounds()
            .unwrap()
            .origin
            .y
            .is_nan());
        assert!(offset_display_item_y(&item, f32::INFINITY)
            .bounds()
            .unwrap()
            .origin
            .y
            .is_infinite());
        assert!(offset_display_item_y(&item, f32::MIN)
            .bounds()
            .unwrap()
            .origin
            .y
            .is_finite());
    }
    #[test]
    fn calculate_display_list_height_ignores_hairline_items() {
        assert_eq!(calculate_display_list_height(&DisplayList::default()), 0.0);
        // Items thinner than 0.1px do not contribute (they are not "visible content").
        let dl = list_of(vec![
            DisplayListItem::Rect {
                bounds: rect(0.0, 5000.0, 10.0, 0.05).into(),
                color: opaque(),
                border_radius: BorderRadius::default(),
            },
            DisplayListItem::Rect {
                bounds: rect(0.0, 10.0, 10.0, 40.0).into(),
                color: opaque(),
                border_radius: BorderRadius::default(),
            },
        ]);
        assert_eq!(calculate_display_list_height(&dl), 50.0);
    }
    #[test]
    fn calculate_display_list_height_never_returns_negative_or_nan() {
        // Negative and NaN geometry must floor at 0.0 rather than poison the height
        // (a NaN height would panic the paginator's `partial_cmp().unwrap()` sort).
        let dl = list_of(vec![
            DisplayListItem::Rect {
                bounds: rect(0.0, -500.0, 10.0, 100.0).into(),
                color: opaque(),
                border_radius: BorderRadius::default(),
            },
            DisplayListItem::Rect {
                bounds: rect(0.0, f32::NAN, 10.0, f32::NAN).into(),
                color: opaque(),
                border_radius: BorderRadius::default(),
            },
            DisplayListItem::PopClip, // no bounds at all
        ]);
        let h = calculate_display_list_height(&dl);
        assert!(
            !h.is_nan(),
            "a NaN total height would panic the page-break sort"
        );
        assert_eq!(h, 0.0);
    }
    // ---------------------------------------------------------------------
    // get_scroll_id
    // ---------------------------------------------------------------------
    #[test]
    fn get_scroll_id_maps_node_index_and_collides_none_with_node_zero() {
        assert_eq!(get_scroll_id(None), 0);
        assert_eq!(get_scroll_id(Some(NodeId::new(5))), 5);
        assert_eq!(
            get_scroll_id(Some(NodeId::new(usize::MAX))),
            usize::MAX as u64
        );
        // NOTE: the "no node" sentinel and the root node both map to 0.
        assert_eq!(get_scroll_id(Some(NodeId::ZERO)), get_scroll_id(None));
    }
    // ---------------------------------------------------------------------
    // SlicerConfig
    // ---------------------------------------------------------------------
    #[test]
    fn slicer_config_builders_set_the_fields_they_name() {
        let simple = SlicerConfig::simple(800.0);
        assert_eq!(simple.page_content_height, 800.0);
        assert_eq!(simple.page_gap, 0.0);
        assert!(simple.allow_clipping);
        assert_eq!(simple.page_width, DEFAULT_A4_WIDTH_PT);
        assert_eq!(simple.page_slot_height(), 800.0);
        let gapped = SlicerConfig::with_gap(800.0, 40.0);
        assert_eq!(gapped.page_gap, 40.0);
        assert_eq!(gapped.page_slot_height(), 840.0);
        let wide = SlicerConfig::simple(800.0).with_page_width(1000.0);
        assert_eq!(wide.page_width, 1000.0);
        assert_eq!(
            wide.page_content_height, 800.0,
            "with_page_width must not disturb the height"
        );
    }
    #[test]
    fn slicer_config_builders_accept_extreme_values() {
        for h in [0.0, -100.0, f32::MAX, f32::INFINITY, f32::NAN] {
            let c = SlicerConfig::simple(h);
            assert_eq!(c.page_content_height.to_bits(), h.to_bits());
            let _ = c.page_slot_height();
            let _ = c.page_for_y(10.0);
            let _ = c.page_bounds(0);
        }
        // NaN gap propagates into the slot height without panicking.
        assert!(SlicerConfig::with_gap(100.0, f32::NAN)
            .page_slot_height()
            .is_nan());
    }
    #[test]
    fn page_for_y_basic_and_boundary() {
        let c = SlicerConfig::simple(100.0);
        assert_eq!(c.page_for_y(0.0), 0);
        assert_eq!(c.page_for_y(99.999), 0);
        assert_eq!(
            c.page_for_y(100.0),
            1,
            "the page boundary belongs to the next page"
        );
        assert_eq!(c.page_for_y(250.0), 2);
        // The gap counts towards the slot: page 1 starts at 120, not 100.
        let g = SlicerConfig::with_gap(100.0, 20.0);
        assert_eq!(g.page_for_y(119.0), 0);
        assert_eq!(g.page_for_y(120.0), 1);
    }
    #[test]
    fn page_for_y_saturates_instead_of_wrapping_or_trapping() {
        let c = SlicerConfig::simple(100.0);
        // Negative Y floors to a negative page; the f32->usize cast SATURATES to 0
        // (Rust >= 1.45), it does not wrap to usize::MAX.
        assert_eq!(c.page_for_y(-1.0), 0);
        assert_eq!(c.page_for_y(-1e30), 0);
        assert_eq!(c.page_for_y(f32::NEG_INFINITY), 0);
        // NaN saturates to 0 as well.
        assert_eq!(c.page_for_y(f32::NAN), 0);
        // Enormous Y saturates to usize::MAX rather than overflowing.
        assert_eq!(c.page_for_y(f32::INFINITY), usize::MAX);
        assert_eq!(c.page_for_y(f32::MAX), usize::MAX);
    }
    #[test]
    fn page_for_y_with_a_nonpositive_slot_is_always_page_zero() {
        // Guard against a division by zero / infinite page index.
        assert_eq!(SlicerConfig::default().page_for_y(f32::MAX), 0);
        assert_eq!(SlicerConfig::simple(0.0).page_for_y(500.0), 0);
        assert_eq!(
            SlicerConfig::with_gap(100.0, -100.0).page_for_y(500.0),
            0,
            "slot == 0"
        );
        assert_eq!(
            SlicerConfig::with_gap(100.0, -500.0).page_for_y(500.0),
            0,
            "slot < 0"
        );
        // A NaN slot is not > 0.0, but it also fails the `<= 0.0` guard; the cast still
        // saturates NaN to 0 rather than trapping.
        assert_eq!(SlicerConfig::simple(f32::NAN).page_for_y(500.0), 0);
    }
    #[test]
    fn page_bounds_are_contiguous_without_a_gap_and_spaced_with_one() {
        let c = SlicerConfig::simple(100.0);
        assert_eq!(c.page_bounds(0), (0.0, 100.0));
        assert_eq!(c.page_bounds(1), (100.0, 200.0));
        assert_eq!(c.page_bounds(3), (300.0, 400.0));
        let g = SlicerConfig::with_gap(100.0, 20.0);
        assert_eq!(g.page_bounds(0), (0.0, 100.0));
        assert_eq!(
            g.page_bounds(2),
            (240.0, 340.0),
            "the gap is dead space between pages"
        );
        // page_for_y and page_bounds must agree.
        for page in 0..5usize {
            let (start, _end) = g.page_bounds(page);
            assert_eq!(g.page_for_y(start), page);
        }
    }
    #[test]
    fn page_bounds_at_extreme_indices_do_not_panic() {
        let c = SlicerConfig::simple(100.0);
        let (start, end) = c.page_bounds(usize::MAX);
        assert!(
            start.is_finite() && end.is_finite(),
            "usize::MAX as f32 * 100 stays in f32 range"
        );
        assert!(start > 0.0);
        // A zero-height config collapses every page onto (0, 0).
        assert_eq!(SlicerConfig::default().page_bounds(9999), (0.0, 0.0));
    }
    // ---------------------------------------------------------------------
    // calculate_page_break_positions
    // ---------------------------------------------------------------------
    #[test]
    fn page_breaks_for_an_empty_or_zero_height_list_is_a_single_page() {
        let pages = calculate_page_break_positions(&DisplayList::default(), 100.0, 100.0);
        assert_eq!(
            pages,
            vec![(0.0, 100.0)],
            "an empty document still has one page"
        );
        // first_page_height <= 0 short-circuits to a single page too.
        let dl = list_of(vec![DisplayListItem::Rect {
            bounds: rect(0.0, 0.0, 10.0, 250.0).into(),
            color: opaque(),
            border_radius: BorderRadius::default(),
        }]);
        assert_eq!(
            calculate_page_break_positions(&dl, 0.0, 100.0),
            vec![(0.0, 250.0)]
        );
        assert_eq!(
            calculate_page_break_positions(&dl, -50.0, 100.0),
            vec![(0.0, 250.0)]
        );
    }
    #[test]
    fn page_breaks_split_at_regular_intervals() {
        let dl = list_of(vec![DisplayListItem::Rect {
            bounds: rect(0.0, 0.0, 10.0, 250.0).into(),
            color: opaque(),
            border_radius: BorderRadius::default(),
        }]);
        let pages = calculate_page_break_positions(&dl, 100.0, 100.0);
        assert_eq!(pages, vec![(0.0, 100.0), (100.0, 200.0), (200.0, 250.0)]);
        // Pages must tile the document with no gaps and no overlaps.
        for w in pages.windows(2) {
            assert_eq!(w[0].1, w[1].0);
        }
        assert_eq!(pages.first().unwrap().0, 0.0);
        assert_eq!(pages.last().unwrap().1, 250.0);
    }
    #[test]
    fn page_breaks_honour_forced_breaks_and_merge_near_duplicates() {
        let mut dl = list_of(vec![DisplayListItem::Rect {
            bounds: rect(0.0, 0.0, 10.0, 250.0).into(),
            color: opaque(),
            border_radius: BorderRadius::default(),
        }]);
        dl.forced_page_breaks = vec![ForcedBreak {
            y: 50.0,
            causing_node: None,
        }];
        assert_eq!(
            calculate_page_break_positions(&dl, 100.0, 100.0),
            vec![(0.0, 50.0), (50.0, 100.0), (100.0, 200.0), (200.0, 250.0)]
        );
        // A forced break within 1px of a regular break is merged, not duplicated
        // (a duplicate would emit a zero-height page) — and the FORCED break's
        // position wins the merge (CSS Fragmentation: forced breaks always
        // apply; before the page_breaks extraction the interval break at 100.0
        // silently swallowed the author's break at 100.5).
        dl.forced_page_breaks = vec![ForcedBreak {
            y: 100.5,
            causing_node: None,
        }];
        let pages = calculate_page_break_positions(&dl, 100.0, 100.0);
        assert_eq!(pages, vec![(0.0, 100.5), (100.5, 200.0), (200.0, 250.0)]);
        assert!(pages.iter().all(|(s, e)| e > s), "no zero-height pages");
    }
    #[test]
    fn page_breaks_ignore_out_of_range_and_nan_forced_breaks() {
        // A NaN forced break is filtered by the range check (NaN fails both
        // comparisons); the sort itself is total_cmp since the page_breaks
        // extraction, so even an unfiltered NaN could no longer panic.
        let mut dl = list_of(vec![DisplayListItem::Rect {
            bounds: rect(0.0, 0.0, 10.0, 250.0).into(),
            color: opaque(),
            border_radius: BorderRadius::default(),
        }]);
        dl.forced_page_breaks = [f32::NAN, -10.0, 0.0, 250.0, 9999.0, f32::INFINITY]
            .into_iter()
            .map(|y| ForcedBreak {
                y,
                causing_node: None,
            })
            .collect();
        let pages = calculate_page_break_positions(&dl, 100.0, 100.0);
        // Only the regular interval breaks survive.
        assert_eq!(pages, vec![(0.0, 100.0), (100.0, 200.0), (200.0, 250.0)]);
    }
    #[test]
    fn page_breaks_with_a_nan_first_page_height_still_yields_one_page() {
        let dl = list_of(vec![DisplayListItem::Rect {
            bounds: rect(0.0, 0.0, 10.0, 250.0).into(),
            color: opaque(),
            border_radius: BorderRadius::default(),
        }]);
        // `while NaN < total` is immediately false, so no regular breaks are produced
        // and the whole document lands on one page. Defined, and NOT a hang.
        let pages = calculate_page_break_positions(&dl, f32::NAN, 100.0);
        assert_eq!(pages, vec![(0.0, 250.0)]);
    }
    // ---------------------------------------------------------------------
    // paginate_display_list_with_slicer_and_breaks (public entry point)
    // ---------------------------------------------------------------------
    #[test]
    fn paginate_with_a_degenerate_page_height_returns_the_list_unsliced() {
        let rr = RendererResources::default();
        let dl = list_of(vec![DisplayListItem::Rect {
            bounds: rect(0.0, 0.0, 10.0, 250.0).into(),
            color: opaque(),
            border_radius: BorderRadius::default(),
        }]);
        for h in [0.0, -1.0, f32::MAX, f32::INFINITY] {
            let pages = paginate_display_list_with_slicer_and_breaks(
                dl.clone(),
                &SlicerConfig::simple(h),
                &rr,
            )
            .expect("degenerate page height must not error");
            assert_eq!(pages.len(), 1, "page height {h} => no slicing");
            assert_eq!(pages[0].items.len(), 1);
        }
    }
    #[test]
    fn paginate_single_page_matches_the_full_pagination_page_for_page() {
        let rr = RendererResources::default();
        let mut dl = list_of(vec![DisplayListItem::Rect {
            bounds: rect(0.0, 0.0, 10.0, 250.0).into(),
            color: opaque(),
            border_radius: BorderRadius::default(),
        }]);
        dl.forced_page_breaks = vec![ForcedBreak {
            y: 50.0,
            causing_node: None,
        }];
        let cfg = SlicerConfig::simple(100.0);
        let constraints = page_breaks::PageConstraints::from_slicer_config(&cfg);
        let breaks = page_breaks::compute_page_breaks_from_display_list(&dl, &constraints);
        let all = paginate_display_list_with_breaks(dl.clone(), &cfg, &breaks, &rr)
            .expect("full pagination");
        assert_eq!(all.len(), 4);
        for (idx, expected_page) in all.iter().enumerate() {
            let single =
                paginate_single_page(dl.clone(), &cfg, &breaks, &rr, idx).expect("single page");
            assert_eq!(
                single.items.len(),
                expected_page.items.len(),
                "page {idx}: lazy materialization must produce the same page"
            );
            let bounds = |p: &DisplayList| p.items.iter().find_map(DisplayListItem::bounds);
            assert_eq!(
                bounds(&single),
                bounds(expected_page),
                "page {idx} geometry"
            );
        }
        // Out of range: empty, not a panic and not page 0.
        let oob = paginate_single_page(dl, &cfg, &breaks, &rr, 99).expect("oob");
        assert!(oob.items.is_empty());
    }
    #[test]
    fn paginate_slices_content_into_pages() {
        let rr = RendererResources::default();
        let dl = list_of(vec![DisplayListItem::Rect {
            bounds: rect(0.0, 0.0, 10.0, 250.0).into(),
            color: opaque(),
            border_radius: BorderRadius::default(),
        }]);
        let pages =
            paginate_display_list_with_slicer_and_breaks(dl, &SlicerConfig::simple(100.0), &rr)
                .expect("pagination succeeds");
        assert_eq!(pages.len(), 3);
        // The tall rect is clipped onto every page it crosses, always rebased to y=0.
        for page in &pages {
            let r = page
                .items
                .iter()
                .find_map(DisplayListItem::bounds)
                .expect("each page keeps a slice");
            assert_eq!(r.origin.y, 0.0);
            assert!(r.size.height > 0.0 && r.size.height <= 100.0);
        }
    }
    // ---------------------------------------------------------------------
    // DisplayList::patch_text_glyphs
    // ---------------------------------------------------------------------
    #[test]
    fn patch_text_glyphs_replaces_matching_runs_and_returns_their_damage() {
        let clip = rect(10.0, 20.0, 100.0, 30.0);
        let mut dl = list_of(vec![text_item(Some(7), clip, vec![glyph(1, 0.0, 0.0)])]);
        let damage = dl.patch_text_glyphs(7, &[vec![glyph(42, 5.0, 6.0), glyph(43, 13.0, 6.0)]]);
        assert_eq!(damage, Some(clip), "damage covers the run's clip rect");
        match &dl.items[0] {
            DisplayListItem::Text { glyphs, .. } => {
                assert_eq!(
                    glyphs.iter().map(|g| g.index).collect::<Vec<_>>(),
                    vec![42, 43]
                );
            }
            other => panic!("expected Text, got {other:?}"),
        }
    }
    #[test]
    fn patch_text_glyphs_unions_damage_across_runs() {
        let a = rect(0.0, 0.0, 50.0, 10.0);
        let b = rect(100.0, 200.0, 50.0, 10.0);
        let mut dl = list_of(vec![
            text_item(Some(3), a, vec![glyph(1, 0.0, 0.0)]),
            text_item(Some(3), b, vec![glyph(2, 0.0, 0.0)]),
        ]);
        let damage = dl
            .patch_text_glyphs(3, &[vec![glyph(9, 0.0, 0.0)], vec![glyph(10, 0.0, 0.0)]])
            .expect("both runs matched");
        // The union spans from a's top-left to b's bottom-right.
        assert_eq!(damage, rect(0.0, 0.0, 150.0, 210.0));
    }
    #[test]
    fn patch_text_glyphs_returns_none_when_nothing_matches() {
        let clip = rect(0.0, 0.0, 10.0, 10.0);
        let mut dl = list_of(vec![
            text_item(Some(7), clip, vec![glyph(1, 0.0, 0.0)]),
            text_item(None, clip, vec![glyph(2, 0.0, 0.0)]), // no source node => never patched
            DisplayListItem::PopClip,
        ]);
        assert_eq!(
            dl.patch_text_glyphs(8, &[vec![glyph(9, 0.0, 0.0)]]),
            None,
            "wrong node index"
        );
        assert_eq!(
            dl.patch_text_glyphs(usize::MAX, &[vec![glyph(9, 0.0, 0.0)]]),
            None
        );
        assert_eq!(
            dl.patch_text_glyphs(7, &[]),
            None,
            "no replacement runs => nothing to do"
        );
        // Nothing was mutated by any of the failed patches.
        match &dl.items[0] {
            DisplayListItem::Text { glyphs, .. } => assert_eq!(glyphs[0].index, 1),
            other => panic!("expected Text, got {other:?}"),
        }
    }
    #[test]
    fn patch_text_glyphs_stops_when_it_runs_out_of_replacement_runs() {
        let clip = rect(0.0, 0.0, 10.0, 10.0);
        let mut dl = list_of(vec![
            text_item(Some(1), clip, vec![glyph(100, 0.0, 0.0)]),
            text_item(Some(1), clip, vec![glyph(200, 0.0, 0.0)]),
            text_item(Some(1), clip, vec![glyph(300, 0.0, 0.0)]),
        ]);
        // Only one replacement run for three matching items: patch the first, leave the rest.
        assert!(dl
            .patch_text_glyphs(1, &[vec![glyph(999, 0.0, 0.0)]])
            .is_some());
        let ids: Vec<u32> = dl
            .items
            .iter()
            .map(|i| match i {
                DisplayListItem::Text { glyphs, .. } => glyphs[0].index,
                other => panic!("expected Text, got {other:?}"),
            })
            .collect();
        assert_eq!(ids, vec![999, 200, 300]);
    }
    #[test]
    fn patch_text_glyphs_accepts_an_empty_replacement_run() {
        let clip = rect(0.0, 0.0, 10.0, 10.0);
        let mut dl = list_of(vec![text_item(Some(0), clip, vec![glyph(1, 0.0, 0.0)])]);
        // An empty run erases the glyphs but still reports damage over the old area.
        assert_eq!(dl.patch_text_glyphs(0, &[Vec::new()]), Some(clip));
        match &dl.items[0] {
            DisplayListItem::Text { glyphs, .. } => assert!(glyphs.is_empty()),
            other => panic!("expected Text, got {other:?}"),
        }
    }
    // ---------------------------------------------------------------------
    // DisplayList::compute_text_damage_rect (text_layout)
    // ---------------------------------------------------------------------
    #[cfg(feature = "text_layout")]
    #[test]
    fn compute_text_damage_rect_empty_inputs_yield_the_zero_rect() {
        let r =
            DisplayList::compute_text_damage_rect(&[], &[], LogicalPosition::new(100.0, 200.0), 0);
        assert_eq!(
            r,
            LogicalRect::zero(),
            "no items => no damage (not a MAX..MIN garbage rect)"
        );
    }
    #[cfg(feature = "text_layout")]
    #[test]
    fn compute_text_damage_rect_translates_by_the_container_origin() {
        let old = vec![positioned(0, 10.0, 20.0, 30.0, 40.0)];
        let r =
            DisplayList::compute_text_damage_rect(&old, &[], LogicalPosition::new(100.0, 200.0), 0);
        assert_eq!(r, rect(110.0, 220.0, 30.0, 40.0));
    }
    #[cfg(feature = "text_layout")]
    #[test]
    fn compute_text_damage_rect_unions_old_and_new() {
        let old = vec![positioned(0, 0.0, 0.0, 10.0, 10.0)];
        let new = vec![positioned(0, 90.0, 190.0, 10.0, 10.0)];
        let r = DisplayList::compute_text_damage_rect(&old, &new, LogicalPosition::zero(), 0);
        assert_eq!(
            r,
            rect(0.0, 0.0, 100.0, 200.0),
            "damage must cover both the before and after ink"
        );
    }
    #[cfg(feature = "text_layout")]
    #[test]
    fn compute_text_damage_rect_skips_lines_before_the_affected_line() {
        let items = vec![
            positioned(0, 0.0, 0.0, 1000.0, 10.0), // line 0 — untouched, must be excluded
            positioned(5, 10.0, 50.0, 20.0, 10.0), // line 5 — the reflowed line
        ];
        let r = DisplayList::compute_text_damage_rect(&items, &items, LogicalPosition::zero(), 5);
        assert_eq!(r, rect(10.0, 50.0, 20.0, 10.0));
        // An affected_line past every line damages nothing.
        let none = DisplayList::compute_text_damage_rect(
            &items,
            &items,
            LogicalPosition::zero(),
            usize::MAX,
        );
        assert_eq!(none, LogicalRect::zero());
    }
    #[cfg(feature = "text_layout")]
    #[test]
    fn compute_text_damage_rect_nan_positions_are_ignored_not_propagated() {
        // f32::min/max drop NaN operands, so a NaN-positioned item contributes nothing.
        let nan_only = vec![positioned(0, f32::NAN, f32::NAN, 10.0, 10.0)];
        let r = DisplayList::compute_text_damage_rect(&nan_only, &[], LogicalPosition::zero(), 0);
        assert_eq!(
            r,
            LogicalRect::zero(),
            "an all-NaN run must not produce a NaN damage rect"
        );
        // Mixed: min/max are applied PER AXIS, so the half-NaN item is not dropped
        // wholesale -- its NaN x contributes nothing, but its finite y=0.0 still
        // widens the union. The result is a safe non-NaN superset: y spans [0,15].
        let mixed = vec![
            positioned(0, f32::NAN, 0.0, 10.0, 10.0),
            positioned(0, 5.0, 5.0, 10.0, 10.0),
        ];
        let r = DisplayList::compute_text_damage_rect(&mixed, &[], LogicalPosition::zero(), 0);
        assert!(!r.origin.x.is_nan() && !r.size.width.is_nan());
        assert_eq!(r, rect(5.0, 0.0, 10.0, 15.0));
    }
    // ---------------------------------------------------------------------
    // item_center_on_page / transform_items_to_page_coords (text_layout)
    // ---------------------------------------------------------------------
    #[cfg(feature = "text_layout")]
    #[test]
    fn item_center_on_page_uses_the_item_midpoint_half_open() {
        let item = positioned(0, 0.0, 0.0, 10.0, 20.0); // height 20 => center at +10
                                                        // layout_origin_y 90 => absolute y 90,
                                                        // center 100 == page_top => on page.
        assert!(item_center_on_page(&item, 90.0, 100.0, 200.0));
        // center 99.99 => just above the page.
        assert!(!item_center_on_page(&item, 89.99, 100.0, 200.0));
        // center exactly page_bottom => OFF page (half-open interval).
        assert!(!item_center_on_page(&item, 190.0, 100.0, 200.0));
        assert!(item_center_on_page(&item, 189.0, 100.0, 200.0));
    }
    #[cfg(feature = "text_layout")]
    #[test]
    fn item_center_on_page_with_nonfinite_values_is_false_not_a_panic() {
        let item = positioned(0, 0.0, f32::NAN, 10.0, 20.0);
        assert!(!item_center_on_page(&item, 0.0, 100.0, 200.0));
        let inf = positioned(0, 0.0, f32::INFINITY, 10.0, 20.0);
        assert!(!item_center_on_page(&inf, 0.0, 100.0, 200.0));
        let ok = positioned(0, 0.0, 150.0, 10.0, 20.0);
        assert!(!item_center_on_page(&ok, 0.0, f32::NAN, f32::NAN));
    }
    #[cfg(feature = "text_layout")]
    #[test]
    fn transform_items_to_page_coords_rebases_and_reports_extents() {
        let items = vec![
            positioned(0, 0.0, 10.0, 30.0, 20.0),
            positioned(1, 5.0, 40.0, 50.0, 20.0),
        ];
        // layout starts at y=100; the page starts at y=100, so new_origin_y = 0.
        let (out, min_y, max_y, max_width) =
            transform_items_to_page_coords(items, 100.0, 100.0, 0.0);
        assert_eq!(out.len(), 2);
        assert_eq!(out[0].position.y, 10.0);
        assert_eq!(out[1].position.y, 40.0);
        assert_eq!(out[0].position.x, 0.0, "X is never rebased");
        assert_eq!(min_y, 10.0);
        assert_eq!(max_y, 60.0);
        assert_eq!(max_width, 55.0, "max_width is position.x + item width");
    }
    #[cfg(feature = "text_layout")]
    #[test]
    fn transform_items_to_page_coords_on_an_empty_input_returns_sentinel_extents() {
        let (out, min_y, max_y, max_width) =
            transform_items_to_page_coords(Vec::new(), 0.0, 0.0, 0.0);
        assert!(out.is_empty());
        // The seeds are returned untouched — callers MUST NOT treat these as real bounds.
        assert_eq!(min_y, f32::MAX);
        assert_eq!(max_y, f32::MIN);
        assert_eq!(max_width, 0.0);
    }
    // ---------------------------------------------------------------------
    // DisplayList::to_debug_json
    // ---------------------------------------------------------------------
    #[test]
    fn to_debug_json_on_an_empty_list_reports_a_balanced_zero_item_list() {
        let json = DisplayList::default().to_debug_json();
        assert!(json.contains("\"total_items\": 0"));
        assert!(json.contains("\"balanced\": true"));
        assert!(json.contains("\"final_clip_depth\": 0"));
    }
    #[test]
    fn to_debug_json_flags_an_unbalanced_clip_stack() {
        // A PushClip with no PopClip must be reported as unbalanced.
        let dl = list_of(vec![DisplayListItem::PushClip {
            bounds: rect(0.0, 0.0, 10.0, 10.0).into(),
            border_radius: BorderRadius::default(),
        }]);
        let json = dl.to_debug_json();
        assert!(json.contains("\"final_clip_depth\": 1"));
        assert!(json.contains("\"balanced\": false"));
        // A stray PopClip drives the depth negative — also unbalanced, not a panic.
        let json = list_of(vec![DisplayListItem::PopClip]).to_debug_json();
        assert!(json.contains("\"final_clip_depth\": -1"));
        assert!(json.contains("\"balanced\": false"));
    }
    #[test]
    fn to_debug_json_survives_a_truncated_node_mapping_and_extreme_values() {
        // node_mapping shorter than items must not index out of bounds.
        let dl = DisplayList {
            items: vec![
                DisplayListItem::PushClip {
                    bounds: rect(f32::NAN, f32::INFINITY, f32::MAX, -1.0).into(),
                    border_radius: BorderRadius {
                        top_left: f32::NAN,
                        ..BorderRadius::default()
                    },
                },
                DisplayListItem::PopClip,
                DisplayListItem::PushStackingContext {
                    z_index: i32::MIN,
                    bounds: WindowLogicalRect::zero(),
                },
                DisplayListItem::PopStackingContext,
                DisplayListItem::PushScrollFrame {
                    clip_bounds: WindowLogicalRect::zero(),
                    content_size: LogicalSize::new(f32::MAX, f32::MAX),
                    scroll_id: u64::MAX,
                },
                DisplayListItem::PopScrollFrame,
                DisplayListItem::PopTextShadow, // exercises the `_ =>` fallback arm
            ],
            node_mapping: Vec::new(), // deliberately desynced
            ..DisplayList::default()
        };
        let json = dl.to_debug_json();
        assert!(json.contains("\"total_items\": 7"));
        assert!(
            json.contains("\"balanced\": true"),
            "every push is matched by a pop"
        );
    }
    // ---------------------------------------------------------------------
    // apply_text_overflow_ellipsis
    // ---------------------------------------------------------------------
    #[test]
    fn ellipsis_leaves_non_overflowing_text_alone() {
        let container = rect(0.0, 0.0, 100.0, 20.0);
        let glyphs = vec![glyph(1, 0.0, 10.0), glyph(2, 10.0, 10.0)]; // right edge 18 < 100
        let mut dl = list_of(vec![text_item(
            Some(0),
            rect(0.0, 0.0, 100.0, 20.0),
            glyphs.clone(),
        )]);
        apply_text_overflow_ellipsis(&mut dl, container, "…");
        match &dl.items[0] {
            DisplayListItem::Text { glyphs: g, .. } => {
                assert_eq!(g.len(), glyphs.len());
                assert_eq!(g.iter().map(|x| x.index).collect::<Vec<_>>(), vec![1, 2]);
            }
            other => panic!("expected Text, got {other:?}"),
        }
    }
    #[test]
    fn ellipsis_truncates_overflowing_text_and_appends_u2026() {
        let container = rect(0.0, 0.0, 50.0, 20.0);
        // Glyphs at x = 0,10,20,30,40,50 each 8 wide => right edges 8,18,28,38,48,58.
        let glyphs: Vec<_> = (0..6)
            .map(|i| glyph(i + 1, (i as f32) * 10.0, 10.0))
            .collect();
        let mut dl = list_of(vec![text_item(
            Some(0),
            rect(0.0, 0.0, 500.0, 20.0),
            glyphs,
        )]);
        apply_text_overflow_ellipsis(&mut dl, container, "…");
        match &dl.items[0] {
            DisplayListItem::Text {
                glyphs: g,
                clip_rect,
                ..
            } => {
                // font_size 16 => ellipsis width 9.6 => truncation edge 40.4;
                // glyph right edges 8/18/28/38 fit, 48 does not.
                assert_eq!(g.len(), 5, "4 kept glyphs + 1 ellipsis");
                assert_eq!(
                    g.last().unwrap().index,
                    0x2026,
                    "U+2026 HORIZONTAL ELLIPSIS"
                );
                assert_eq!(g[3].index, 4, "the last kept glyph");
                // The clip rect is retargeted to the container so nothing spills past it.
                assert_eq!(clip_rect.into_inner(), container);
            }
            other => panic!("expected Text, got {other:?}"),
        }
    }
    #[test]
    fn ellipsis_on_a_container_too_narrow_for_any_glyph_leaves_only_the_ellipsis() {
        // keep_count == 0 => glyphs.truncate(0) => `glyphs.last()` is None. The fallback
        // must anchor the ellipsis to the container origin instead of panicking.
        let container = rect(3.0, 4.0, 1.0, 20.0);
        let glyphs = vec![glyph(1, 0.0, 10.0), glyph(2, 10.0, 10.0)];
        let mut dl = list_of(vec![text_item(
            Some(0),
            rect(0.0, 0.0, 500.0, 20.0),
            glyphs,
        )]);
        apply_text_overflow_ellipsis(&mut dl, container, "…");
        match &dl.items[0] {
            DisplayListItem::Text { glyphs: g, .. } => {
                assert_eq!(g.len(), 1);
                assert_eq!(g[0].index, 0x2026);
                assert_eq!(
                    g[0].point,
                    LogicalPosition::new(3.0, 4.0),
                    "anchored to the container origin"
                );
            }
            other => panic!("expected Text, got {other:?}"),
        }
    }
    #[test]
    fn ellipsis_skips_empty_runs_and_non_text_items() {
        let container = rect(0.0, 0.0, 1.0, 20.0);
        let mut dl = list_of(vec![
            text_item(Some(0), rect(0.0, 0.0, 500.0, 20.0), Vec::new()),
            DisplayListItem::PopClip,
            DisplayListItem::Rect {
                bounds: rect(0.0, 0.0, 900.0, 20.0).into(),
                color: opaque(),
                border_radius: BorderRadius::default(),
            },
        ]);
        apply_text_overflow_ellipsis(&mut dl, container, "…");
        match &dl.items[0] {
            DisplayListItem::Text { glyphs, .. } => {
                assert!(glyphs.is_empty(), "an empty run is left alone")
            }
            other => panic!("expected Text, got {other:?}"),
        }
        assert_eq!(dl.items.len(), 3, "no items added or removed");
    }
    #[test]
    fn ellipsis_with_a_nan_font_size_does_not_panic() {
        // A NaN ellipsis width makes every `glyph_right > truncation_edge` comparison
        // false, so nothing is truncated — but an ellipsis is still appended.
        let container = rect(0.0, 0.0, 50.0, 20.0);
        let glyphs = vec![glyph(1, 0.0, 10.0), glyph(2, 100.0, 10.0)];
        let mut dl = list_of(vec![DisplayListItem::Text {
            glyphs,
            font_hash: FontHash::invalid(),
            font_size_px: f32::NAN,
            color: opaque(),
            clip_rect: rect(0.0, 0.0, 500.0, 20.0).into(),
            source_node_index: None,
        }]);
        apply_text_overflow_ellipsis(&mut dl, container, "…");
        match &dl.items[0] {
            DisplayListItem::Text { glyphs: g, .. } => {
                assert_eq!(g.len(), 3, "both glyphs kept + ellipsis");
                assert_eq!(g.last().unwrap().index, 0x2026);
                assert!(g.last().unwrap().size.width.is_nan());
            }
            other => panic!("expected Text, got {other:?}"),
        }
    }
    // ---------------------------------------------------------------------
    // resolve_clip_path
    // ---------------------------------------------------------------------
    #[test]
    fn resolve_clip_path_none_is_no_clip() {
        use azul_css::props::layout::shape::ClipPath;
        assert_eq!(
            resolve_clip_path(&ClipPath::None, rect(0.0, 0.0, 100.0, 100.0)),
            None
        );
        assert_eq!(
            resolve_clip_path(&ClipPath::default(), rect(0.0, 0.0, 100.0, 100.0)),
            None
        );
    }
    #[test]
    fn resolve_clip_path_inset_shrinks_from_every_edge() {
        use azul_css::{
            corety::OptionF32,
            props::layout::shape::ClipPath,
            shape::{CssShape, ShapeInset},
        };
        let path = ClipPath::Shape(CssShape::Inset(ShapeInset {
            inset_top: 10.0,
            inset_right: 20.0,
            inset_bottom: 30.0,
            inset_left: 40.0,
            border_radius: OptionF32::Some(6.0),
        }));
        let (r, radius) =
            resolve_clip_path(&path, rect(100.0, 200.0, 300.0, 400.0)).expect("inset clips");
        assert_eq!(r, rect(140.0, 210.0, 240.0, 360.0));
        assert_eq!(radius, 6.0);
    }
    #[test]
    fn resolve_clip_path_over_inset_clamps_the_size_to_zero() {
        use azul_css::{
            corety::OptionF32,
            props::layout::shape::ClipPath,
            shape::{CssShape, ShapeInset},
        };
        let path = ClipPath::Shape(CssShape::Inset(ShapeInset {
            inset_top: 500.0,
            inset_right: 500.0,
            inset_bottom: 500.0,
            inset_left: 500.0,
            border_radius: OptionF32::None,
        }));
        let (r, radius) =
            resolve_clip_path(&path, rect(0.0, 0.0, 100.0, 100.0)).expect("still returns a rect");
        assert_eq!(
            r.size,
            LogicalSize::zero(),
            "insets larger than the box collapse, they do not go negative"
        );
        assert_eq!(radius, 0.0, "OptionF32::None => radius 0");
    }
    #[test]
    fn resolve_clip_path_circle_and_ellipse_use_their_bounding_box() {
        use azul_css::{
            props::layout::shape::ClipPath,
            shape::{CssShape, ShapeCircle, ShapeEllipse, ShapePoint},
        };
        let circle = ClipPath::Shape(CssShape::Circle(ShapeCircle {
            center: ShapePoint { x: 50.0, y: 50.0 },
            radius: 20.0,
        }));
        let (r, radius) =
            resolve_clip_path(&circle, rect(100.0, 100.0, 200.0, 200.0)).expect("circle clips");
        assert_eq!(
            r,
            rect(130.0, 130.0, 40.0, 40.0),
            "centre is relative to the node origin"
        );
        assert_eq!(radius, 20.0);
        let ellipse = ClipPath::Shape(CssShape::Ellipse(ShapeEllipse {
            center: ShapePoint { x: 50.0, y: 50.0 },
            radius_x: 10.0,
            radius_y: 30.0,
        }));
        let (r, radius) =
            resolve_clip_path(&ellipse, rect(0.0, 0.0, 100.0, 100.0)).expect("ellipse clips");
        assert_eq!(r, rect(40.0, 20.0, 20.0, 60.0));
        assert_eq!(
            radius, 10.0,
            "the rounding uses the SMALLER of the two radii"
        );
    }
    #[test]
    fn resolve_clip_path_circle_with_a_degenerate_radius_does_not_panic() {
        use azul_css::{
            props::layout::shape::ClipPath,
            shape::{CssShape, ShapeCircle, ShapePoint},
        };
        for radius in [0.0, -10.0, f32::NAN, f32::INFINITY] {
            let path = ClipPath::Shape(CssShape::Circle(ShapeCircle {
                center: ShapePoint { x: 0.0, y: 0.0 },
                radius,
            }));
            // The value is passed through unclamped; the contract here is only that it
            // returns a value deterministically instead of panicking.
            let out = resolve_clip_path(&path, rect(0.0, 0.0, 100.0, 100.0));
            assert!(out.is_some(), "radius {radius} must still resolve");
        }
    }
    #[test]
    fn resolve_clip_path_polygon_bbox_and_empty_polygon() {
        use azul_css::{
            props::layout::shape::ClipPath,
            shape::{CssShape, ShapePoint, ShapePolygon},
        };
        // An empty polygon has no bounding box => no clip.
        let empty = ClipPath::Shape(CssShape::Polygon(ShapePolygon {
            points: Vec::new().into(),
        }));
        assert_eq!(
            resolve_clip_path(&empty, rect(0.0, 0.0, 100.0, 100.0)),
            None
        );
        // A real polygon collapses to its axis-aligned bounding box.
        let tri = ClipPath::Shape(CssShape::Polygon(ShapePolygon {
            points: vec![
                ShapePoint { x: 10.0, y: 90.0 },
                ShapePoint { x: 50.0, y: 10.0 },
                ShapePoint { x: 90.0, y: 90.0 },
            ]
            .into(),
        }));
        let (r, radius) =
            resolve_clip_path(&tri, rect(1000.0, 2000.0, 100.0, 100.0)).expect("polygon clips");
        assert_eq!(r, rect(1010.0, 2010.0, 80.0, 80.0));
        assert_eq!(radius, 0.0, "a polygon bbox is never rounded");
    }
    #[test]
    fn resolve_clip_path_polygon_with_nan_points_collapses_instead_of_panicking() {
        use azul_css::{
            props::layout::shape::ClipPath,
            shape::{CssShape, ShapePoint, ShapePolygon},
        };
        let nan_poly = ClipPath::Shape(CssShape::Polygon(ShapePolygon {
            points: vec![ShapePoint {
                x: f32::NAN,
                y: f32::NAN,
            }]
            .into(),
        }));
        let (r, _) =
            resolve_clip_path(&nan_poly, rect(0.0, 0.0, 100.0, 100.0)).expect("still resolves");
        // f32::min/max drop NaN, leaving the ±INFINITY seeds; the `.max(0.0)` on the size
        // keeps the result degenerate-but-finite rather than negative.
        assert_eq!(r.size, LogicalSize::zero());
    }
    #[test]
    fn resolve_clip_path_svg_path_is_unsupported_and_does_not_clip() {
        use azul_css::{
            props::layout::shape::ClipPath,
            shape::{CssShape, ShapePath},
        };
        let path = ClipPath::Shape(CssShape::Path(ShapePath {
            data: String::from("M 0 0 L 10 10 Z").into(),
        }));
        assert_eq!(
            resolve_clip_path(&path, rect(0.0, 0.0, 100.0, 100.0)),
            None,
            "path() clip-paths are not implemented => no clipping (rather than a wrong clip)"
        );
    }
    // ---------------------------------------------------------------------
    // apply_clip_path
    // ---------------------------------------------------------------------
    #[test]
    fn apply_clip_path_wraps_the_tail_of_the_list_and_keeps_the_mapping_in_sync() {
        let mut dl = list_of(vec![
            DisplayListItem::Rect {
                bounds: rect(0.0, 0.0, 10.0, 10.0).into(),
                color: opaque(),
                border_radius: BorderRadius::default(),
            },
            DisplayListItem::Rect {
                bounds: rect(0.0, 0.0, 20.0, 20.0).into(),
                color: opaque(),
                border_radius: BorderRadius::default(),
            },
        ]);
        apply_clip_path(&mut dl, 1, rect(5.0, 5.0, 50.0, 50.0), 8.0);
        assert_eq!(dl.items.len(), 4, "PushClip inserted + PopClip appended");
        assert_eq!(
            dl.items.len(),
            dl.node_mapping.len(),
            "node_mapping must stay parallel to items"
        );
        assert!(matches!(dl.items[1], DisplayListItem::PushClip { .. }));
        assert!(matches!(dl.items[3], DisplayListItem::PopClip));
        assert_eq!(dl.node_mapping[1], None);
        assert_eq!(dl.node_mapping[3], None);
        match &dl.items[1] {
            DisplayListItem::PushClip {
                bounds,
                border_radius,
            } => {
                assert_eq!(bounds.into_inner(), rect(5.0, 5.0, 50.0, 50.0));
                // A positive radius is applied uniformly to all four corners.
                assert_eq!(border_radius.top_left, 8.0);
                assert_eq!(border_radius.bottom_right, 8.0);
            }
            other => panic!("expected PushClip, got {other:?}"),
        }
    }
    #[test]
    fn apply_clip_path_with_a_nonpositive_radius_uses_square_corners() {
        for radius in [0.0, -5.0, f32::NAN] {
            let mut dl = list_of(vec![DisplayListItem::PopClip]);
            apply_clip_path(&mut dl, 0, rect(0.0, 0.0, 10.0, 10.0), radius);
            match &dl.items[0] {
                DisplayListItem::PushClip { border_radius, .. } => {
                    assert!(
                        border_radius.is_zero(),
                        "radius {radius} must not round the clip"
                    );
                }
                other => panic!("expected PushClip, got {other:?}"),
            }
        }
    }
    #[test]
    fn apply_clip_path_at_the_end_index_appends_rather_than_panicking() {
        let mut dl = list_of(vec![DisplayListItem::PopClip]);
        // start_index == items.len() is the boundary case and must be accepted.
        apply_clip_path(&mut dl, 1, rect(0.0, 0.0, 10.0, 10.0), 0.0);
        assert_eq!(dl.items.len(), 3);
        assert_eq!(dl.items.len(), dl.node_mapping.len());
        assert!(matches!(dl.items[1], DisplayListItem::PushClip { .. }));
        assert!(matches!(dl.items[2], DisplayListItem::PopClip));
    }
    #[test]
    #[should_panic(expected = "insertion index")]
    fn apply_clip_path_past_the_end_panics_on_the_vec_insert() {
        // BUG: `start_index` is not validated against `items.len()`, so an out-of-range
        // index panics inside `Vec::insert` instead of being rejected. Pinned so the
        // panic is a deliberate, visible contract rather than a latent crash.
        let mut dl = DisplayList::default();
        apply_clip_path(&mut dl, 3, rect(0.0, 0.0, 10.0, 10.0), 0.0);
    }
    // ======================================================================
    // E18: repeated theads for MULTIPLE straddling tables (side-by-side)
    // ======================================================================
    fn plain_rect(x: f32, y: f32, w: f32, h: f32) -> DisplayListItem {
        DisplayListItem::Rect {
            bounds: rect(x, y, w, h).into(),
            color: ColorU {
                r: 0,
                g: 0,
                b: 0,
                a: 255,
            },
            border_radius: BorderRadius::default(),
        }
    }
    fn item_y(item: &DisplayListItem) -> f32 {
        item.visual_bounds().map(|b| b.origin.y).unwrap_or(f32::NAN)
    }
    fn item_x(item: &DisplayListItem) -> f32 {
        item.visual_bounds().map(|b| b.origin.x).unwrap_or(f32::NAN)
    }
    /// Two side-by-side tables (columns) straddling the same page top: each
    /// repeated thead stays in its own x-band AT the page top, each table's
    /// continued rows shift by ITS OWN thead height, and content below both
    /// shifts by the SUM (the break pass reserves the sum per page).
    #[test]
    fn side_by_side_straddling_tables_keep_their_own_thead_offsets() {
        use crate::solver3::pagination::{TableHeaderInfo, TableHeaderTracker};
        // Table A: x 0..280, thead 20 tall. Table B: x 320..600, thead 30.
        // Both span content y 0..350 over 200-tall pages: page 1 (y 200..400)
        // is a continuation page for both.
        let thead_a = vec![plain_rect(0.0, 0.0, 280.0, 20.0)];
        let thead_b = vec![plain_rect(320.0, 0.0, 280.0, 30.0)];
        let mut tracker = TableHeaderTracker::new();
        tracker.register_table_header(TableHeaderInfo {
            table_node_index: 1,
            table_start_y: 0.0,
            table_end_y: 350.0,
            thead_items: thead_a,
            thead_height: 20.0,
            thead_offset_y: 0.0,
        });
        tracker.register_table_header(TableHeaderInfo {
            table_node_index: 2,
            table_start_y: 0.0,
            table_end_y: 350.0,
            thead_items: thead_b,
            thead_height: 30.0,
            thead_offset_y: 0.0,
        });
        // Content: one row of each table living on page 1 (content y
        // 200..240), plus a full-width paragraph BELOW both tables
        // (content y 360..380).
        let full = DisplayList {
            items: vec![
                plain_rect(0.0, 200.0, 280.0, 40.0),   // A's continued row
                plain_rect(320.0, 200.0, 280.0, 40.0), // B's continued row
                plain_rect(0.0, 360.0, 600.0, 20.0),   // below both
            ],
            node_mapping: vec![None, None, None],
            ..DisplayList::default()
        };
        let config = SlicerConfig {
            table_headers: tracker,
            ..SlicerConfig::simple(200.0)
        };
        let pages = paginate_display_list_with_slicer_and_breaks(
            full,
            &config,
            &RendererResources::default(),
        )
        .expect("paginate");
        assert!(
            pages.len() >= 2,
            "content spans two pages, got {}",
            pages.len()
        );
        let page1 = &pages[1];
        // Both theads sit AT the page top, in their own x-bands.
        let thead_a_y = page1
            .items
            .iter()
            .filter(|i| {
                item_x(i) < 300.0 && i.visual_bounds().is_some_and(|b| b.size.height == 20.0)
            })
            .map(item_y)
            .fold(f32::NAN, f32::min);
        let thead_b_y = page1
            .items
            .iter()
            .filter(|i| {
                item_x(i) >= 300.0 && i.visual_bounds().is_some_and(|b| b.size.height == 30.0)
            })
            .map(item_y)
            .fold(f32::NAN, f32::min);
        assert_eq!(thead_a_y, 0.0, "thead A at its column's page top");
        assert_eq!(
            thead_b_y, 0.0,
            "thead B at its OWN column's page top - NOT stacked below A"
        );
        // Each table's continued row shifts by ITS OWN thead height.
        let row_a = page1
            .items
            .iter()
            .find(|i| item_x(i) < 300.0 && i.visual_bounds().is_some_and(|b| b.size.height == 40.0))
            .expect("A's row on page 1");
        let row_b = page1
            .items
            .iter()
            .find(|i| {
                item_x(i) >= 300.0 && i.visual_bounds().is_some_and(|b| b.size.height == 40.0)
            })
            .expect("B's row on page 1");
        assert_eq!(item_y(row_a), 20.0, "A's row below A's 20px thead only");
        assert_eq!(
            item_y(row_b),
            30.0,
            "B's row below B's 30px thead only - the old max() collapse shifted both by 30 and \
             overlapped A"
        );
        // Content below BOTH tables shifts by the SUM (matches the break
        // pass's per-page reservation).
        let below = page1
            .items
            .iter()
            .find(|i| i.visual_bounds().is_some_and(|b| b.size.width == 600.0))
            .expect("below-both paragraph on page 1");
        assert_eq!(item_y(below), 160.0 + 50.0, "sum of both thead heights");
    }
    // ======================================================================
    // E17: clip / stacking structure is re-derived per page slice
    // ======================================================================
    /// A clipped, stacked subtree spanning pages 0-1: BOTH pages re-open the
    /// chain around the content that lands on them, balanced; a page without
    /// any of the subtree's content carries none of its markers.
    #[test]
    fn clip_and_stacking_chain_is_rederived_on_every_page_it_touches() {
        // Subtree: PushStackingContext > PushClip(y 50..350) > rect(60..340),
        // then a plain rect on page 2 (y 450..470) OUTSIDE the subtree.
        let full = DisplayList {
            items: vec![
                DisplayListItem::PushStackingContext {
                    z_index: 3,
                    bounds: rect(0.0, 50.0, 600.0, 300.0).into(),
                },
                DisplayListItem::PushClip {
                    bounds: rect(0.0, 50.0, 600.0, 300.0).into(),
                    border_radius: BorderRadius::default(),
                },
                plain_rect(0.0, 60.0, 600.0, 280.0),
                DisplayListItem::PopClip,
                DisplayListItem::PopStackingContext,
                plain_rect(0.0, 450.0, 600.0, 20.0),
            ],
            node_mapping: vec![None; 6],
            ..DisplayList::default()
        };
        let config = SlicerConfig::simple(200.0);
        let pages = paginate_display_list_with_slicer_and_breaks(
            full,
            &config,
            &RendererResources::default(),
        )
        .expect("paginate");
        assert!(pages.len() >= 3, "3 pages of content, got {}", pages.len());
        let structure = |page: &DisplayList| -> Vec<&'static str> {
            page.items
                .iter()
                .map(|i| match i {
                    DisplayListItem::PushStackingContext { .. } => "push_sc",
                    DisplayListItem::PopStackingContext => "pop_sc",
                    DisplayListItem::PushClip { .. } => "push_clip",
                    DisplayListItem::PopClip => "pop_clip",
                    DisplayListItem::Rect { .. } => "rect",
                    _ => "other",
                })
                .collect()
        };
        // Page 0: chain opens before the rect slice, closes after.
        assert_eq!(
            structure(&pages[0]),
            vec!["push_sc", "push_clip", "rect", "pop_clip", "pop_sc"],
            "page 0: {:?}",
            structure(&pages[0])
        );
        // Page 1: the SAME chain re-opens for the continued slice — this is
        // what the slicer used to drop entirely (unclipped bleed, flattened
        // z-order on continuation pages).
        assert_eq!(
            structure(&pages[1]),
            vec!["push_sc", "push_clip", "rect", "pop_clip", "pop_sc"],
            "page 1: {:?}",
            structure(&pages[1])
        );
        // The re-opened clip is INTERSECTED with page 1's band and rebased:
        // original clip 50..350 ∩ page [200, 400) → page-local 0..150.
        let clip_bounds = pages[1]
            .items
            .iter()
            .find_map(|i| match i {
                DisplayListItem::PushClip { bounds, .. } => Some(bounds.0),
                _ => None,
            })
            .expect("clip on page 1");
        assert_eq!(
            (clip_bounds.origin.y, clip_bounds.size.height),
            (0.0, 150.0),
            "clip clipped to the page band and rebased"
        );
        // Page 2: no subtree content — NO markers, just the plain rect.
        assert_eq!(
            structure(&pages[2]),
            vec!["rect"],
            "a page without the subtree's content carries none of its markers"
        );
        // The stacking context keeps its z-index on every page it touches.
        for page in &pages[..2] {
            let z = page.items.iter().find_map(|i| match i {
                DisplayListItem::PushStackingContext { z_index, .. } => Some(*z_index),
                _ => None,
            });
            assert_eq!(z, Some(3));
        }
    }
    /// One straddling table: everything shifts by exactly its thead height —
    /// the pre-E18 behavior, unchanged.
    #[test]
    fn single_straddling_table_keeps_the_uniform_shift() {
        use crate::solver3::pagination::{TableHeaderInfo, TableHeaderTracker};
        let mut tracker = TableHeaderTracker::new();
        tracker.register_table_header(TableHeaderInfo {
            table_node_index: 1,
            table_start_y: 0.0,
            table_end_y: 350.0,
            thead_items: vec![plain_rect(0.0, 0.0, 600.0, 25.0)],
            thead_height: 25.0,
            thead_offset_y: 0.0,
        });
        let full = DisplayList {
            items: vec![
                plain_rect(0.0, 200.0, 600.0, 40.0), // continued row
                plain_rect(0.0, 360.0, 600.0, 20.0), // below the table
            ],
            node_mapping: vec![None, None],
            ..DisplayList::default()
        };
        let config = SlicerConfig {
            table_headers: tracker,
            ..SlicerConfig::simple(200.0)
        };
        let pages = paginate_display_list_with_slicer_and_breaks(
            full,
            &config,
            &RendererResources::default(),
        )
        .expect("paginate");
        let page1 = &pages[1];
        let row = page1
            .items
            .iter()
            .find(|i| i.visual_bounds().is_some_and(|b| b.size.height == 40.0))
            .expect("row");
        let below = page1
            .items
            .iter()
            .find(|i| {
                i.visual_bounds()
                    .is_some_and(|b| b.size.height == 20.0 && b.size.width == 600.0)
            })
            .expect("below");
        assert_eq!(item_y(row), 25.0);
        assert_eq!(item_y(below), 160.0 + 25.0);
    }
}
#[cfg(test)]
mod dense_scroll_extent_tests {
    use alloc::sync::Arc;
    use super::*;
    use crate::text3::{
        cache::{
            BidiDirection, ClusterFlags, ContentIndex, GraphemeClusterId, LayoutFontMetrics,
            OverflowInfo, Point, PositionedItem, ShapedCluster, ShapedGlyph, ShapedItem,
            StyleProperties, UnifiedLayout,
        },
        dense::DenseText,
    };
    /// One real cluster with real metrics so the dense extent is NON-zero
    /// and the sparse-vs-dense A/B is meaningful (an empty layout passes
    /// the guard vacuously at 0x0 — that is exactly the coverage hole the
    /// d3 NC exposed: no lib/corpus test reached this path with a dense
    /// view, so the verify assert could not fire).
2
    fn one_cluster_layout() -> UnifiedLayout {
2
        let metrics = LayoutFontMetrics {
2
            ascent: 800.0,
2
            descent: -200.0,
2
            cap_height: None,
2
            x_height: None,
2
            line_gap: 0.0,
2
            units_per_em: 1000,
2
        };
2
        let glyph = ShapedGlyph {
2
            kind: text3::cache::GlyphKind::Character,
2
            glyph_id: 7,
2
            cluster_offset: 0,
2
            advance: 10.0,
2
            kerning: 0.0,
2
            offset: Point::default(),
2
            vertical_advance: 0.0,
2
            vertical_offset: Point::default(),
2
            script: text3::script::Script::Latin,
2
            font_hash: 42,
2
            font_metrics: metrics,
2
        };
2
        let cluster = ShapedCluster {
2
            flags: ClusterFlags::classify("a"),
2
            source_text: std::sync::Arc::from("a"),
            source_byte_len: 1,
2
            source_cluster_id: GraphemeClusterId {
2
                source_run: 0,
2
                start_byte_in_run: 0,
2
            },
2
            source_content_index: ContentIndex {
2
                run_index: 0,
2
                item_index: 0,
2
            },
2
            source_node_id: None,
2
            glyphs: smallvec::smallvec![glyph],
            advance: 10.0,
2
            direction: BidiDirection::Ltr,
2
            style: Arc::new(StyleProperties {
2
                font_size_px: 16.0,
2
                ..StyleProperties::default()
2
            }),
2
            marker_position_outside: None,
            is_first_fragment: true,
            is_last_fragment: true,
        };
2
        UnifiedLayout {
2
            items: vec![PositionedItem {
2
                item: ShapedItem::Cluster(cluster),
2
                position: Point { x: 5.0, y: 3.0 },
2
                line_index: 0,
2
            }],
2
            overflow: OverflowInfo::default(),
2
        }
2
    }
    /// (d5) The pagination clipper must treat a TextPayload payload
    /// EXACTLY like a bare UnifiedLayout payload — same clip decision,
    /// same output bounds. This is the only coverage the TextPayload
    /// arm has (it activates under AZ_DENSE_TEXT only, and no verify
    /// run paginates), so its NC is required to go red here.
    #[test]
1
    fn clip_text_layout_item_reads_through_the_text_payload() {
        use crate::solver3::layout_tree::TextPayload;
1
        let layout = Arc::new(one_cluster_layout());
1
        let dense = Arc::new(DenseText::from_unified(&layout));
1
        let bounds = LogicalRect::new(
1
            LogicalPosition::new(0.0, 0.0),
1
            LogicalSize::new(100.0, 40.0),
        );
1
        let bare: Arc<dyn std::any::Any + Send + Sync> = layout.clone();
1
        let wrapped: Arc<dyn std::any::Any + Send + Sync> = Arc::new(TextPayload {
1
            dense,
1
            sparse: layout,
1
        });
1
        let via_bare = clip_text_layout_item(
1
            &bare,
1
            bounds,
1
            FontHash::from_hash(42),
            16.0,
1
            ColorU {
1
                r: 0,
1
                g: 0,
1
                b: 0,
1
                a: 255,
1
            },
            0.0,
            1000.0,
        );
1
        let via_payload = clip_text_layout_item(
1
            &wrapped,
1
            bounds,
1
            FontHash::from_hash(42),
            16.0,
1
            ColorU {
1
                r: 0,
1
                g: 0,
1
                b: 0,
1
                a: 255,
1
            },
            0.0,
            1000.0,
        );
1
        match (via_bare, via_payload) {
            (
1
                Some(DisplayListItem::TextLayout { bounds: a, .. }),
1
                Some(DisplayListItem::TextLayout { bounds: b, .. }),
            ) => {
1
                assert_eq!(a, b, "payload route must produce identical clip bounds");
            }
            other => panic!("both routes must clip to TextLayout items, got {other:?}"),
        }
1
    }
    #[test]
1
    fn scroll_extent_from_dense_matches_the_sparse_walk() {
1
        let layout = one_cluster_layout();
1
        let dense = DenseText::from_unified(&layout);
1
        assert_eq!(
1
            dense.clusters.len(),
1
            layout.items.len(),
            "pure-cluster guard"
        );
        // Sparse reference extent.
1
        let mut sx: f32 = 0.0;
1
        let mut sy: f32 = 0.0;
2
        for it in &layout.items {
1
            let b = it.item.bounds();
1
            sx = sx.max(it.position.x + b.width);
1
            sy = sy.max(it.position.y + b.height);
1
        }
1
        assert!(sx > 14.0 && sy > 10.0, "non-trivial extent ({sx}x{sy})");
        // Dense extent — the exact computation get_scroll_content_size uses.
1
        let dx = dense
1
            .clusters
1
            .iter()
1
            .map(|c| c.x + c.advance)
1
            .fold(0.0f32, f32::max);
1
        let dy = dense
1
            .lines
1
            .iter()
1
            .map(|l| l.top_y + l.height)
1
            .fold(0.0f32, f32::max);
1
        assert!((sx - dx).abs() < 0.01, "width: sparse {sx} vs dense {dx}");
1
        assert!((sy - dy).abs() < 0.01, "height: sparse {sy} vs dense {dy}");
1
    }
}
/// The display list's INSERTION contract: `items` has three arrays parallel to
/// it plus index ranges pointing into it, and only an append can ignore them.
#[cfg(test)]
mod insert_item_tests {
    use super::*;
    /// A MID-LIST insert must keep every array parallel to `items` aligned and
    /// slide the index ranges that point into it.
    ///
    /// The focus ring is the first item the engine inserts anywhere but the
    /// end: it has to go INSIDE the focused node's scroll frame so it travels
    /// with the page. The first version used a bare `items.insert`, which left
    /// `uniform_text_bgs` and `layout_node_mapping` reading one item to the
    /// left of where they belong from the insertion point onwards, and every
    /// `fixed_position_item_ranges` entry pointing one item short.
    #[test]
1
    fn inserting_an_item_keeps_the_parallel_arrays_aligned() {
1
        let mut dl = DisplayList::default();
5
        for i in 0..4 {
4
            dl.items.push(DisplayListItem::PopClip);
4
            dl.node_mapping.push(Some(NodeId::new(i)));
4
            dl.uniform_text_bgs.push(None);
4
            dl.layout_node_mapping.push(Some((i, EmitPhase::Content)));
4
        }
        // A fixed-position range over items 2..4, i.e. the two after the
        // insertion point.
1
        dl.fixed_position_item_ranges.push((2, 4));
1
        dl.insert_item(1, DisplayListItem::PopClip, None);
1
        assert_eq!(dl.items.len(), 5);
3
        for len in [
1
            dl.node_mapping.len(),
1
            dl.uniform_text_bgs.len(),
1
            dl.layout_node_mapping.len(),
        ] {
3
            assert_eq!(len, dl.items.len(), "a side table fell out of step");
        }
        // The item that WAS at index 1 is now at 2, and its side entries moved
        // with it.
1
        assert_eq!(dl.node_mapping[2], Some(NodeId::new(1)));
1
        assert_eq!(dl.layout_node_mapping[2], Some((1, EmitPhase::Content)));
        // The inserted item owns index 1 and belongs to no node.
1
        assert_eq!(dl.node_mapping[1], None);
1
        assert_eq!(dl.layout_node_mapping[1], None);
        // The fixed-position range still covers the same two ITEMS.
1
        assert_eq!(dl.fixed_position_item_ranges[0], (3, 5));
1
    }
    /// A side table shorter than `items` (older code appended without growing
    /// them) must not make the insert panic or misplace the new entry.
    #[test]
1
    fn inserting_into_a_short_side_table_pads_it_first() {
1
        let mut dl = DisplayList::default();
4
        for _ in 0..3 {
3
            dl.items.push(DisplayListItem::PopClip);
3
        }
        // node_mapping is deliberately left empty.
1
        dl.insert_item(3, DisplayListItem::PopClip, None);
1
        assert_eq!(dl.items.len(), 4);
1
        assert_eq!(dl.node_mapping.len(), 4, "the table was padded to fit");
1
        assert!(dl.node_mapping.iter().all(Option::is_none));
1
    }
}