1
//! solver3/mod.rs
2
//!
3
//! Next-generation CSS layout engine with proper formatting context separation
4

            
5
pub mod cache;
6
pub mod calc;
7
pub mod counters;
8
pub mod display_list;
9
pub mod fc;
10
pub mod geometry;
11
pub mod getters;
12
pub mod layout_tree;
13
pub use layout_tree::LayoutNodeId;
14
pub mod break_token;
15
pub mod page_breaks;
16
pub mod paged_layout;
17
pub mod pagination;
18
pub mod positioning;
19
pub mod scrollbar;
20
pub mod sizing;
21
pub mod taffy_bridge;
22

            
23
/// Lazy `debug_info` macro - only evaluates format args when `debug_messages` is Some
24
#[macro_export]
25
macro_rules! debug_info {
26
    ($ctx:expr, $($arg:tt)*) => {
27
        if $ctx.debug_messages.is_some() {
28
            $ctx.debug_info_inner(format!($($arg)*));
29
        }
30
    };
31
}
32

            
33
/// Lazy `debug_warning` macro - only evaluates format args when `debug_messages` is Some
34
#[macro_export]
35
macro_rules! debug_warning {
36
    ($ctx:expr, $($arg:tt)*) => {
37
        if $ctx.debug_messages.is_some() {
38
            $ctx.debug_warning_inner(format!($($arg)*));
39
        }
40
    };
41
}
42

            
43
/// Lazy `debug_error` macro - only evaluates format args when `debug_messages` is Some
44
#[macro_export]
45
macro_rules! debug_error {
46
    ($ctx:expr, $($arg:tt)*) => {
47
        if $ctx.debug_messages.is_some() {
48
            $ctx.debug_error_inner(format!($($arg)*));
49
        }
50
    };
51
}
52

            
53
/// Lazy `debug_log` macro - only evaluates format args when `debug_messages` is Some
54
#[macro_export]
55
macro_rules! debug_log {
56
    ($ctx:expr, $($arg:tt)*) => {
57
        if $ctx.debug_messages.is_some() {
58
            $ctx.debug_log_inner(format!($($arg)*));
59
        }
60
    };
61
}
62

            
63
/// Lazy `debug_box_props` macro - only evaluates format args when `debug_messages` is Some
64
#[macro_export]
65
macro_rules! debug_box_props {
66
    ($ctx:expr, $($arg:tt)*) => {
67
        if $ctx.debug_messages.is_some() {
68
            $ctx.debug_box_props_inner(format!($($arg)*));
69
        }
70
    };
71
}
72

            
73
/// Lazy `debug_css_getter` macro - only evaluates format args when `debug_messages` is Some
74
#[macro_export]
75
macro_rules! debug_css_getter {
76
    ($ctx:expr, $($arg:tt)*) => {
77
        if $ctx.debug_messages.is_some() {
78
            $ctx.debug_css_getter_inner(format!($($arg)*));
79
        }
80
    };
81
}
82

            
83
/// Lazy `debug_bfc_layout` macro - only evaluates format args when `debug_messages` is Some
84
#[macro_export]
85
macro_rules! debug_bfc_layout {
86
    ($ctx:expr, $($arg:tt)*) => {
87
        if $ctx.debug_messages.is_some() {
88
            $ctx.debug_bfc_layout_inner(format!($($arg)*));
89
        }
90
    };
91
}
92

            
93
/// Lazy `debug_ifc_layout` macro - only evaluates format args when `debug_messages` is Some
94
#[macro_export]
95
macro_rules! debug_ifc_layout {
96
    ($ctx:expr, $($arg:tt)*) => {
97
        if $ctx.debug_messages.is_some() {
98
            $ctx.debug_ifc_layout_inner(format!($($arg)*));
99
        }
100
    };
101
}
102

            
103
/// Lazy `debug_table_layout` macro - only evaluates format args when `debug_messages` is Some
104
#[macro_export]
105
macro_rules! debug_table_layout {
106
    ($ctx:expr, $($arg:tt)*) => {
107
        if $ctx.debug_messages.is_some() {
108
            $ctx.debug_table_layout_inner(format!($($arg)*));
109
        }
110
    };
111
}
112

            
113
/// Lazy `debug_display_type` macro - only evaluates format args when `debug_messages` is Some
114
#[macro_export]
115
macro_rules! debug_display_type {
116
    ($ctx:expr, $($arg:tt)*) => {
117
        if $ctx.debug_messages.is_some() {
118
            $ctx.debug_display_type_inner(format!($($arg)*));
119
        }
120
    };
121
}
122

            
123
use std::{
124
    collections::{BTreeMap, HashMap},
125
    sync::Arc,
126
};
127

            
128
use azul_core::{
129
    dom::{DomId, NodeId},
130
    geom::{LogicalPosition, LogicalRect, LogicalSize},
131
    hit_test::{DocumentId, ScrollPosition},
132
    resources::RendererResources,
133
    selection::{TextCursor, TextSelection},
134
    styled_dom::StyledDom,
135
};
136

            
137
/// Sentinel value for "position not yet computed". No real position is ever `f32::MIN`.
138
pub(crate) const POSITION_UNSET: LogicalPosition = LogicalPosition {
139
    x: f32::MIN,
140
    y: f32::MIN,
141
};
142

            
143
/// Maximum number of scrollbar-induced reflow iterations before layout gives up.
144
/// Scrollbar appearance can change container size, which may trigger further scrollbar
145
/// changes. This limit prevents infinite loops in pathological layouts.
146
const MAX_SCROLLBAR_REFLOW_ITERATIONS: usize = 10;
147

            
148
/// Vec-based position storage indexed by layout-tree node index.
149
/// Replaces `BTreeMap<usize, LogicalPosition>` for O(1) access and cache-friendly iteration.
150
pub type PositionVec = Vec<LogicalPosition>;
151

            
152
/// Get position for node index, returning None if unset.
153
///
154
/// Note: only the `x` component is checked against the sentinel. This is sufficient
155
/// because `POSITION_UNSET` always sets both `x` and `y` to `f32::MIN`, and `pos_set`
156
/// always writes both components together.
157
#[inline]
158
#[must_use]
159
18511
pub fn pos_get(positions: &PositionVec, idx: usize) -> Option<LogicalPosition> {
160
18511
    positions.get(idx).copied().filter(|p| p.x != f32::MIN)
161
18511
}
162

            
163
/// Set position for node index. Grows the vec if needed.
164
#[inline]
165
528856
pub fn pos_set(positions: &mut PositionVec, idx: usize, pos: LogicalPosition) {
166
528856
    if idx >= positions.len() {
167
470645
        positions.resize(idx + 1, POSITION_UNSET);
168
470645
    }
169
528856
    positions[idx] = pos;
170
528856
}
171

            
172
/// Check if position has been set for node index.
173
#[inline]
174
#[must_use]
175
95291
pub fn pos_contains(positions: &PositionVec, idx: usize) -> bool {
176
95291
    positions.get(idx).is_some_and(|p| p.x != f32::MIN)
177
95291
}
178
use azul_css::{
179
    props::property::{CssProperty, CssPropertyCategory},
180
    LayoutDebugMessage, LayoutDebugMessageType,
181
};
182

            
183
use self::{
184
    display_list::generate_display_list,
185
    geometry::IntrinsicSizes,
186
    getters::get_writing_mode,
187
    layout_tree::{generate_layout_tree, LayoutTree},
188
    sizing::calculate_intrinsic_sizes,
189
};
190
#[cfg(feature = "text_layout")]
191
pub use crate::font_traits::TextLayoutCache;
192
use crate::{
193
    font_traits::ParsedFontTrait,
194
    solver3::{
195
        cache::LayoutCache, display_list::DisplayList, fc::LayoutConstraints,
196
        layout_tree::DirtyFlag,
197
    },
198
};
199

            
200
/// Central context for a single layout pass.
201
#[derive(Debug)]
202
pub struct LayoutContext<'a, T: ParsedFontTrait> {
203
    pub styled_dom: &'a StyledDom,
204
    /// Per-document memo for [`crate::solver3::getters::get_style_properties`].
205
    ///
206
    /// Resolving a node's style allocates ~6.5 KB (a font stack of heap
207
    /// `String`s, a background-content Vec, a font-features Vec, a cloned
208
    /// family list), and the sizing pass and the inline-layout pass each
209
    /// resolve the same node independently. heaptrack measured 6.33 MB of
210
    /// peak heap over 966 calls on a 3-page document.
211
    ///
212
    /// It lives HERE, on the context, so its lifetime is exactly the
213
    /// document's. An earlier attempt used a thread-local keyed on
214
    /// `ptr::from_ref(styled_dom)`, which passed every library test and
215
    /// reddened sixteen reftests: a `StyledDom` is dropped and the next one
216
    /// reuses the address, so the second document was served the first
217
    /// one's styles. Ownership makes that unrepresentable rather than
218
    /// merely unlikely.
219
    pub style_cache: getters::StyleCache,
220
    #[cfg(feature = "text_layout")]
221
    pub font_manager: &'a crate::font_traits::FontManager<T>,
222
    #[cfg(not(feature = "text_layout"))]
223
    pub font_manager: core::marker::PhantomData<&'a T>,
224
    /// Text selections for rendering highlights. Populated from `MultiCursorState`.
225
    pub text_selections: &'a BTreeMap<DomId, TextSelection>,
226
    pub debug_messages: &'a mut Option<Vec<LayoutDebugMessage>>,
227
    pub counters: &'a mut HashMap<(usize, String), i32>,
228
    pub viewport_size: LogicalSize,
229
    /// Fragmentation context for CSS Paged Media (PDF generation)
230
    /// When Some, layout respects page boundaries and generates one `DisplayList` per page
231
    pub fragmentation_context: Option<&'a mut crate::paged::FragmentationContext>,
232
    /// Per-pass record: layout-tree indices of IFC roots whose LINE LAYOUT
233
    /// was recomputed this pass (`layout_flow` ran — `GlyphSwap` reuse does
234
    /// NOT count). The DL-patching invalidation signal: a re-flowed IFC's
235
    /// text items changed shape and must re-emit; everything else can be
236
    /// copied+translated. Drained into the patch machinery by
237
    /// `layout_document`; empty on GlyphSwap-only passes.
238
    pub reflowed_ifcs: std::collections::BTreeSet<usize>,
239
    /// Whether the text cursor should be drawn (managed by `CursorManager` blink timer)
240
    /// When false, the cursor is in the "off" phase of blinking and should not be rendered.
241
    /// When true (default), the cursor is visible.
242
    pub cursor_is_visible: bool,
243
    /// All active cursor locations from `MultiCursorState` / `CursorManager`.
244
    /// Each entry is (`dom_id`, `node_id`, cursor). Multiple entries = multi-cursor mode.
245
    /// Empty = no active cursor. The last entry is the primary cursor.
246
    pub cursor_locations: Vec<crate::managers::text_edit::CursorLocation>,
247
    /// Per-participant caret colours (U1), keyed by `SelectionOwner`. Empty
248
    /// for a single-user app, where every caret falls back to `caret-color`.
249
    pub owner_colors:
250
        BTreeMap<azul_core::selection::SelectionOwner, azul_css::props::basic::color::ColorU>,
251
    /// Seat focus rings (9b-ii-a-i-d-iii, the overlay half): every node a
252
    /// NON-primary seat focuses, with that seat's colour - the same
253
    /// seat-coloured convention as the seat carets, painted as a 2px ring
254
    /// around the border box since `:focus` is the primary's alone.
255
    pub seat_focus_rings: Vec<(
256
        azul_core::dom::DomNodeId,
257
        azul_css::props::basic::color::ColorU,
258
    )>,
259
    /// Paint the draggable selection handles under the local primary
260
    /// range (U2-a). Set where the platform lends a custom view no handles
261
    /// of its own (Android); see `TextEditManager::selection_handles`.
262
    pub paint_selection_handles: bool,
263
    /// IME preedit (composition) text to render inline at the cursor position.
264
    /// When Some, the text should be rendered with an underline decoration.
265
    pub preedit_text: Option<String>,
266
    /// Per-node multi-slot cache (Taffy-inspired 9+1 architecture).
267
    /// Moved out of `LayoutCache` via `std::mem::take` for the duration of layout,
268
    /// then moved back after the layout pass completes.
269
    pub cache_map: cache::LayoutCacheMap,
270
    /// Image cache for resolving `background-image: url(...)` references.
271
    pub image_cache: &'a azul_core::resources::ImageCache,
272
    /// Content overlay for resolving quickly-mutable node content (swapped
273
    /// images, produced callback frames): readers resolve overlay→DOM via
274
    /// [`crate::overlay::ResolvedContent`]. `None` outside a live window
275
    /// (standalone paged/PDF layout, unit tests) — the DOM is then authoritative.
276
    pub content_overlay: Option<&'a crate::overlay::ContentOverlay>,
277
    /// System style containing colors, fonts, metrics, and theme information.
278
    /// Used for selection colors, caret styling, and other system-themed elements.
279
    pub system_style: Option<std::sync::Arc<azul_css::system::SystemStyle>>,
280
    /// Callback to get the current system time. Used for profiling inside layout.
281
    /// On WASM targets (where `std::time::Instant::now()` panics), callers should
282
    /// supply a no-op or platform-specific implementation.
283
    pub get_system_time_fn: azul_core::task::GetSystemTimeCallback,
284
    /// Memoised `get_scrollbar_style` results, keyed by DOM node id.
285
    /// `compute_scrollbar_info_core` is called many times per node
286
    /// per layout pass (BFC path + Taffy flex/grid path + display
287
    /// list), and each call previously did 9 cascade walks. Once
288
    /// populated, subsequent callers in the same `LayoutContext`
289
    /// (a single render) return a clone.
290
    ///
291
    /// Uses `RefCell` so shared `&self` borrows (e.g. in the Taffy
292
    /// bridge's `get_core_container_style`) can mutate the cache
293
    /// without lifting the ctx to `&mut`. Keyed by `NodeId` so
294
    /// entries span DOMs in iframe-style nested documents if that
295
    /// ever becomes a thing.
296
    /// What each `VirtualView` last MATERIALIZED, keyed by node.
297
    ///
298
    /// A `VirtualView` is a replaced element, and until now its intrinsic size
299
    /// was the hardcoded 300x150 of a replaced element with no natural size -
300
    /// even though the callback reports exactly how big its content is
301
    /// (`VirtualViewReturn::materialized`). That report only ever reached
302
    /// PLACEMENT and scrollbar geometry, so a view could not be sized by what
303
    /// it returned and every caller had to state a size up front.
304
    ///
305
    /// With this, `width: auto` on a view means what it means for an `<img>`:
306
    /// as big as the content. The first pass has nothing materialized yet and
307
    /// still falls back to 300x150 - a view is sized from the outside first,
308
    /// and by its content afterwards.
309
    pub virtual_view_sizes: Option<&'a BTreeMap<(DomId, NodeId), LogicalSize>>,
310
    pub scrollbar_style_cache:
311
        core::cell::RefCell<HashMap<NodeId, getters::ComputedScrollbarStyle>>,
312
}
313

            
314
impl<T: ParsedFontTrait> LayoutContext<'_, T> {
315
    /// The one overlay→DOM content read order for this context's DOM.
316
    /// Layout (intrinsic sizing) and display-list build resolve node content
317
    /// exclusively through this — never via `NodeType::Image` directly.
318
    #[must_use]
319
369
    pub const fn resolved_content(&self) -> crate::overlay::ResolvedContent<'_> {
320
369
        crate::overlay::ResolvedContent {
321
369
            overlay: self.content_overlay,
322
369
            styled_dom: self.styled_dom,
323
369
            dom_id: self.styled_dom.dom_id,
324
369
        }
325
369
    }
326

            
327
    /// Internal method - called by `debug_log`! macro after checking `debug_messages.is_some()`
328
    #[inline]
329
474496
    pub fn debug_log_inner(&mut self, message: String) {
330
474496
        if let Some(messages) = self.debug_messages.as_mut() {
331
474495
            messages.push(LayoutDebugMessage {
332
474495
                message: message.into(),
333
474495
                location: "solver3".into(),
334
474495
                message_type: LayoutDebugMessageType::default(),
335
474495
            });
336
474495
        }
337
474496
    }
338

            
339
    /// Internal method - called by `debug_info`! macro after checking `debug_messages.is_some()`
340
    #[inline]
341
6799888
    pub fn debug_info_inner(&mut self, message: String) {
342
6799888
        if let Some(messages) = self.debug_messages.as_mut() {
343
6799888
            messages.push(LayoutDebugMessage::info(message));
344
6799888
        }
345
6799888
    }
346

            
347
    /// Internal method - called by `debug_warning`! macro after checking `debug_messages.is_some()`
348
    #[inline]
349
71892
    pub fn debug_warning_inner(&mut self, message: String) {
350
71892
        if let Some(messages) = self.debug_messages.as_mut() {
351
71892
            messages.push(LayoutDebugMessage::warning(message));
352
71892
        }
353
71892
    }
354

            
355
    /// Internal method - called by `debug_error`! macro after checking `debug_messages.is_some()`
356
    #[inline]
357
3
    pub fn debug_error_inner(&mut self, message: String) {
358
3
        if let Some(messages) = self.debug_messages.as_mut() {
359
2
            messages.push(LayoutDebugMessage::error(message));
360
2
        }
361
3
    }
362

            
363
    /// Internal method - called by `debug_box_props`! macro after checking
364
    /// `debug_messages.is_some()`
365
    #[inline]
366
2
    pub fn debug_box_props_inner(&mut self, message: String) {
367
2
        if let Some(messages) = self.debug_messages.as_mut() {
368
2
            messages.push(LayoutDebugMessage::box_props(message));
369
2
        }
370
2
    }
371

            
372
    /// Internal method - called by `debug_css_getter`! macro after checking
373
    /// `debug_messages.is_some()`
374
    #[inline]
375
2
    pub fn debug_css_getter_inner(&mut self, message: String) {
376
2
        if let Some(messages) = self.debug_messages.as_mut() {
377
2
            messages.push(LayoutDebugMessage::css_getter(message));
378
2
        }
379
2
    }
380

            
381
    /// Internal method - called by `debug_bfc_layout`! macro after checking
382
    /// `debug_messages.is_some()`
383
    #[inline]
384
2
    pub fn debug_bfc_layout_inner(&mut self, message: String) {
385
2
        if let Some(messages) = self.debug_messages.as_mut() {
386
2
            messages.push(LayoutDebugMessage::bfc_layout(message));
387
2
        }
388
2
    }
389

            
390
    /// Internal method - called by `debug_ifc_layout`! macro after checking
391
    /// `debug_messages.is_some()`
392
    #[inline]
393
1499185
    pub fn debug_ifc_layout_inner(&mut self, message: String) {
394
1499185
        if let Some(messages) = self.debug_messages.as_mut() {
395
1499185
            messages.push(LayoutDebugMessage::ifc_layout(message));
396
1499185
        }
397
1499185
    }
398

            
399
    /// Internal method - called by `debug_table_layout`! macro after checking
400
    /// `debug_messages.is_some()`
401
    #[inline]
402
15023
    pub fn debug_table_layout_inner(&mut self, message: String) {
403
15023
        if let Some(messages) = self.debug_messages.as_mut() {
404
15022
            messages.push(LayoutDebugMessage::table_layout(message));
405
15022
        }
406
15023
    }
407

            
408
    /// Internal method - called by `debug_display_type`! macro after checking
409
    /// `debug_messages.is_some()`
410
    #[inline]
411
2
    pub fn debug_display_type_inner(&mut self, message: String) {
412
2
        if let Some(messages) = self.debug_messages.as_mut() {
413
2
            messages.push(LayoutDebugMessage::display_type(message));
414
2
        }
415
2
    }
416
}
417

            
418
/// Main entry point for the incremental, cached layout engine.
419
///
420
/// `new_dom` is borrowed, not owned — every use inside is `&new_dom`,
421
/// so taking ownership was a pure formality that forced every caller
422
/// to `styled_dom.clone()` the DOM before calling. The clone was
423
/// ~2 MiB per render on excel.html; kept at the borrow now.
424
#[cfg(feature = "text_layout")]
425
/// Web-backend opt-out for display-list generation.
426
///
427
/// When set, [`layout_document`] runs the full positioning pipeline
428
/// (intrinsic sizing, taffy block/flex/grid, relative/sticky/absolute
429
/// adjustment → `calculated_positions`) but **skips
430
/// `generate_display_list`**, returning an empty [`DisplayList`]. The
431
/// web backend emits TLV DOM patches, not a display list, so it needs
432
/// the geometry in `calculated_positions` but nothing the painter
433
/// produces. This also lets the AArch64→wasm lift drop the entire
434
/// `display_list` painter surface (those symbols are classified `Leaf`
435
/// in `dll/src/web/symbol_table.rs::classify_for_name`, so the
436
/// transitive lifter never descends into them). Defaults `false` →
437
/// desktop/native behaviour is unchanged.
438
pub static SKIP_DISPLAY_LIST: core::sync::atomic::AtomicBool =
439
    core::sync::atomic::AtomicBool::new(false);
440

            
441
/// Set [`SKIP_DISPLAY_LIST`].
442
///
443
/// Provided as a function (rather than the
444
/// caller touching the static directly) so the web backend's
445
/// `dll`-crate caller reaches it through a normal `bl` into this
446
/// `azul_layout` function — keeping the static's address computation
447
/// intra-crate (direct `adrp+add`) instead of a cross-crate GOT load,
448
/// which the AArch64→wasm lift mirrors more reliably.
449
/// Fingerprint of the scroll-snapshot GEOMETRY the display-list build consumes.
450
///
451
/// The emitted list is a function of `scroll_offsets` too — scrollbar
452
/// necessity and track layout read `children_rect.size` / `parent_rect`, and a
453
/// `VirtualView`'s published virtual size reaches the build ONLY through this
454
/// map (`get_scroll_states_for_dom` puts `virtual_scroll_size` into
455
/// `children_rect`). It is therefore part of the DL cache key: without it the
456
/// cache served the pre-publication list back on every later pass (a 13,000px
457
/// virtual document never grew a scrollbar).
458
///
459
/// Live scroll OFFSETS (`children_rect.origin`) are deliberately EXCLUDED:
460
/// offset changes are GPU-animated (scrollbar transform events) precisely so
461
/// that scrolling never re-emits the display list — keying on them would kill
462
/// the cache on every wheel tick.
463
/// Fingerprint of the display-list inputs that are NOT the DOM: caret
464
/// visibility + locations, text selections, IME preedit. The structural
465
/// cache key (`LayoutCache::cached_display_list`) must include it, or a
466
/// relayout serves a list built for a different caret/selection state -
467
/// the third instance of "a display-list input the cache key cannot see",
468
/// after the GPU-key population and the scroll geometry.
469
#[must_use]
470
15032
pub fn dl_input_fingerprint(
471
15032
    cursor_is_visible: bool,
472
15032
    cursor_locations: &[crate::managers::text_edit::CursorLocation],
473
15032
    text_selections: &BTreeMap<DomId, TextSelection>,
474
15032
    preedit_text: Option<&str>,
475
15032
    paint_selection_handles: bool,
476
15032
    seat_focus_rings: &[(
477
15032
        azul_core::dom::DomNodeId,
478
15032
        azul_css::props::basic::color::ColorU,
479
15032
    )],
480
15032
    dynamic_context: Option<&azul_css::dynamic_selector::DynamicSelectorContext>,
481
15032
    cascade_epoch: u64,
482
15032
) -> u64 {
483
    use core::hash::{Hash, Hasher};
484
15032
    let mut h = std::collections::hash_map::DefaultHasher::new();
485
15032
    cursor_is_visible.hash(&mut h);
486
    // The CASCADE GENERATION (`CssPropertyCache::cascade_epoch`): colour is
487
    // excluded from the relayout hash by design, so two cascades of one DOM
488
    // under two themes — or before/after a `color` override, or across an
489
    // `@media` restyle — hash identically at the subtree level. The epoch
490
    // is what tells them apart here.
491
15032
    cascade_epoch.hash(&mut h);
492
    // The theme, as a key of its own. Redundant with the epoch now that the
493
    // UA colour defaults are IN the resolved style (every theme flip bumps
494
    // the epoch) — kept because it is cheap and it keys the list on the
495
    // theme even for a DOM whose epoch some future path forgets to bump.
496
15032
    dynamic_context
497
15032
        .map(azul_css::dynamic_selector::DynamicSelectorContext::paint_defaults_fingerprint)
498
15032
        .hash(&mut h);
499
15032
    paint_selection_handles.hash(&mut h);
500
    // A seat's focus moving must miss the cache like a caret moving does.
501
15032
    format!("{seat_focus_rings:?}").hash(&mut h);
502
    // Debug renderings: small, change rarely per frame, and none of the
503
    // types implement Hash.
504
15032
    format!("{cursor_locations:?}").hash(&mut h);
505
15032
    format!("{text_selections:?}").hash(&mut h);
506
15032
    preedit_text.hash(&mut h);
507
15032
    h.finish()
508
15032
}
509

            
510
31804
pub(crate) fn scroll_geometry_fingerprint(
511
31804
    scroll_offsets: &BTreeMap<NodeId, ScrollPosition>,
512
31804
) -> u64 {
513
    use std::hash::{DefaultHasher, Hash, Hasher};
514
31804
    let mut h = DefaultHasher::new();
515
34841
    for (node, pos) in scroll_offsets {
516
3037
        node.hash(&mut h);
517
3037
        pos.parent_rect.origin.x.to_bits().hash(&mut h);
518
3037
        pos.parent_rect.origin.y.to_bits().hash(&mut h);
519
3037
        pos.parent_rect.size.width.to_bits().hash(&mut h);
520
3037
        pos.parent_rect.size.height.to_bits().hash(&mut h);
521
3037
        pos.children_rect.size.width.to_bits().hash(&mut h);
522
3037
        pos.children_rect.size.height.to_bits().hash(&mut h);
523
3037
    }
524
31804
    h.finish()
525
31804
}
526

            
527
4
pub fn set_skip_display_list(skip: bool) {
528
4
    SKIP_DISPLAY_LIST.store(skip, core::sync::atomic::Ordering::Relaxed);
529
4
}
530

            
531
// M12.7: keep this out-of-line so the web lift sees it as its own wasm fn
532
// (not inlined into layout_dom_recursive). An opt-folded infinite loop in the
533
// solver (a mis-lifted loop exit) is otherwise hidden inside the giant inlined
534
// layout_dom_recursive; de-inlining lets AZ_FUEL/AZ_WASM_DEBUG name the actual
535
// source fn — and may itself prevent the inlining-induced fold. No perf cost on
536
// desktop (called once per layout).
537
#[inline(never)]
538
// node counts / indices / tree-len values fed to az_mark debug markers as u32; bounded.
539
#[allow(clippy::cast_possible_truncation)]
540
#[allow(clippy::too_many_lines, clippy::cognitive_complexity)] // large but cohesive: single-purpose layout/render/parse routine (one branch per case)
541
/// # Errors
542
///
543
/// Returns a `LayoutError` if document layout fails.
544
9123
pub fn layout_document<T: ParsedFontTrait + Sync + 'static>(
545
9123
    cache: &mut LayoutCache,
546
9123
    text_cache: &mut TextLayoutCache,
547
9123
    new_dom: &StyledDom,
548
9123
    viewport: LogicalRect,
549
9123
    font_manager: &crate::font_traits::FontManager<T>,
550
9123
    scroll_offsets: &BTreeMap<NodeId, ScrollPosition>,
551
9123
    text_selections: &BTreeMap<DomId, TextSelection>,
552
9123
    debug_messages: &mut Option<Vec<LayoutDebugMessage>>,
553
9123
    gpu_value_cache: Option<&azul_core::gpu::GpuValueCache>,
554
9123
    renderer_resources: &azul_core::resources::RendererResources,
555
9123
    id_namespace: azul_core::resources::IdNamespace,
556
9123
    dom_id: DomId,
557
9123
    cursor_is_visible: bool,
558
9123
    cursor_locations: Vec<crate::managers::text_edit::CursorLocation>,
559
9123
    owner_colors: BTreeMap<
560
9123
        azul_core::selection::SelectionOwner,
561
9123
        azul_css::props::basic::color::ColorU,
562
9123
    >,
563
9123
    seat_focus_rings: Vec<(
564
9123
        azul_core::dom::DomNodeId,
565
9123
        azul_css::props::basic::color::ColorU,
566
9123
    )>,
567
9123
    paint_selection_handles: bool,
568
9123
    preedit_text: Option<String>,
569
9123
    image_cache: &azul_core::resources::ImageCache,
570
9123
    content_overlay: Option<&crate::overlay::ContentOverlay>,
571
9123
    system_style: Option<std::sync::Arc<azul_css::system::SystemStyle>>,
572
9123
    get_system_time_fn: azul_core::task::GetSystemTimeCallback,
573
9123
    // The CSS DIFF, folded into the solver's own dirtiness. The solver's
574
9123
    // reconcile compares DOM structure/content and is BLIND to a changed
575
9123
    // stylesheet over an identical tree — a CSS-only remount reused stale
576
9123
    // geometry (200px measured where the new sheet said 40px) and the
577
9123
    // structural-identity DL cache served stale paint. Each entry is a node
578
9123
    // whose computed style changed, with the WORST `RelayoutScope` across
579
9123
    // its changed properties; `RelayoutScope::None` entries are paint-only
580
9123
    // changes (colour/background/...) that must repaint without a single
581
9123
    // layout pass — the aggressive-caching half of this contract.
582
9123
    css_dirty: &[(NodeId, azul_css::props::property::RelayoutScope)],
583
9123
    // What each `VirtualView` last materialized - see
584
9123
    // `LayoutContext::virtual_view_sizes`.
585
9123
    virtual_view_sizes: &BTreeMap<(DomId, NodeId), LogicalSize>,
586
9123
) -> Result<std::sync::Arc<DisplayList>> {
587
    use crate::window::LayoutWindow;
588

            
589
    // Secondary mapping: anonymous wrappers (dom_node_id == None)
590
    // by (parent_new_idx, ordinal-among-anon-siblings). An
591
    // unchanged DOM produces the same anon wrappers in the same
592
    // order under the same parent — matching by position here
593
    // preserves their cache slots too. Without this, anon
594
    // wrappers re-allocate empty every reconcile and invalidate
595
    // their ancestors via `mark_dirty`.
596
2576
    fn collect_anon_children_by_parent(tree: &LayoutTree) -> HashMap<usize, Vec<usize>> {
597
2576
        let mut map: HashMap<usize, Vec<usize>> = HashMap::new();
598
73597
        for (idx, node) in tree.nodes.iter().enumerate() {
599
73597
            if node.dom_node_id.is_some() {
600
73570
                continue;
601
27
            }
602
27
            if let Some(parent) = node.parent {
603
27
                map.entry(parent).or_default().push(idx);
604
27
            }
605
        }
606
2576
        map
607
2576
    }
608

            
609
    // Reset IFC ID counter at the start of each layout pass
610
    // This ensures IFCs get consistent IDs across frames when the DOM structure is stable
611
9123
    layout_tree::IfcId::reset_counter();
612
    // in layout_document returns the rc=5 Err (the error enum can't be captured
613
    // reliably in the lift). The last value seen = the step that errored next.
614
9123
    {
615
9123
        let _ = (0xDD00_0001u32);
616
9123
    }
617
    // If 0 here → the LogicalRect HFA arg was lost across the lifted call.
618

            
619
9123
    if let Some(msgs) = debug_messages.as_mut() {
620
7311
        msgs.push(LayoutDebugMessage::info(format!(
621
7311
            "[Layout] layout_document called - viewport: ({:.1}, {:.1}) size ({:.1}x{:.1})",
622
7311
            viewport.origin.x, viewport.origin.y, viewport.size.width, viewport.size.height
623
7311
        )));
624
7311
        msgs.push(LayoutDebugMessage::info(format!(
625
7311
            "[Layout] DOM has {} nodes",
626
7311
            new_dom.node_data.len()
627
7311
        )));
628
7373
    }
629

            
630
    // Create temporary context without counters for tree generation
631
9123
    let mut counter_values = HashMap::new();
632
9123
    let mut ctx_temp = LayoutContext {
633
9123
        style_cache: Default::default(),
634
9123
        virtual_view_sizes: Some(virtual_view_sizes),
635
9123
        scrollbar_style_cache: core::cell::RefCell::new(HashMap::new()),
636
9123
        styled_dom: new_dom,
637
9123
        font_manager,
638
9123
        text_selections,
639
9123
        debug_messages,
640
9123
        counters: &mut counter_values,
641
9123
        viewport_size: viewport.size,
642
9123
        fragmentation_context: None,
643
9123
        reflowed_ifcs: std::collections::BTreeSet::new(),
644
9123
        cursor_is_visible,
645
9123
        cursor_locations: cursor_locations.clone(),
646
9123
        owner_colors: Default::default(),
647
9123
        seat_focus_rings: Vec::new(),
648
9123
        paint_selection_handles: false,
649
9123
        preedit_text: preedit_text.clone(),
650
9123
        cache_map: cache::LayoutCacheMap::default(), // temp context doesn't need real cache
651
9123
        image_cache,
652
9123
        content_overlay,
653
9123
        system_style: system_style.clone(),
654
9123
        get_system_time_fn,
655
9123
    };
656

            
657
9123
    crate::probe::sample_peak_rss("rss:enter_layout_document");
658

            
659
    // --- Step 0: record DOM pointer / viewport for diagnostics only ---
660
    //
661
    // NOTE: there is intentionally NO pointer-identity fast path here.
662
    // Comparing `new_dom as *const StyledDom as usize` against a stored
663
    // pointer is UNSOUND across layout passes: each `regenerate_layout`
664
    // builds a fresh `StyledDom`, and after the previous one is dropped
665
    // (e.g. `layout_and_generate_display_list` calls `layout_results.clear()`
666
    // before re-laying out), the allocator/stack frequently hands the new,
667
    // *different* StyledDom the SAME address. A pointer match therefore does
668
    // NOT prove the content is unchanged — it would return the previous
669
    // frame's display list for a structurally different DOM (e.g. an image
670
    // removed from the tree would still appear in `scan_used_images`,
671
    // breaking resource GC). The Step 1.1 structural-identity cache below
672
    // (root `subtree_hash` + viewport) is the correct, content-based skip;
673
    // it costs one ~600 µs reconcile pass but cannot be fooled by address
674
    // reuse.
675
9123
    let doc_setup_span = crate::probe::Probe::span("doc_setup_to_reconcile");
676
9123
    let dom_ptr = std::ptr::from_ref::<StyledDom>(new_dom) as usize;
677
9123
    cache.prev_dom_ptr = dom_ptr;
678
9123
    cache.prev_viewport = viewport;
679

            
680
    // --- Step 1: Reconciliation & Invalidation ---
681
9123
    crate::probe::reset_peak();
682
    // RESIZE-ONLY SKIP: the incremental-relayout resize path hands solver3
683
    // the SAME StyledDom object with zero DOM/style dirt — the viewport is
684
    // the only delta. Reconcile would walk 1209 nodes to rediscover
685
    // "everything reused, nothing dirty" (~9.6 ms/pass on big.md) and the
686
    // cache_map remap would rebuild an identity mapping. Take the retained
687
    // tree as-is instead: indices are unchanged (so the per-node size/layout
688
    // caches keep working WITHOUT a remap), layout_roots={root} re-runs the
689
    // top-down pass at the new size, and the censuses read full-reuse. The
690
    // hint is a one-shot latch set ONLY by the resize-latch call sites
691
    // (common/layout.rs incremental_relayout_for_resize); restyle-driven
692
    // incremental relayouts keep full reconcile — they NEED its fingerprint
693
    // diff for paint-dirty classification. The dom-id sanity check guards
694
    // against a stale hint meeting a swapped DOM.
695
9123
    drop(doc_setup_span);
696
9123
    let resize_only = core::mem::take(&mut cache.resize_only_hint);
697
9123
    let dom_len_for_hint = new_dom.node_data.as_ref().len();
698
9123
    let (new_tree_val, mut recon_result) = if resize_only
699
180
        && cache.tree.as_ref().is_some_and(|t| {
700
180
            t.dom_to_layout
701
180
                .last_key_value()
702
180
                .is_none_or(|(max_id, _)| max_id.index() < dom_len_for_hint)
703
180
        }) {
704
180
        let _p = crate::probe::Probe::span("reconcile_skipped_resize_only");
705
180
        cache.last_reconcile_was_skipped = true;
706
180
        let tree = cache.tree.take().expect("checked is_some above");
707
        // DL-patching input: the sizes the PREVIOUS pass computed — the
708
        // layout pass below overwrites used_size in place (same tree
709
        // object), so this is the only moment they can be captured.
710
180
        cache.previous_sizes = tree.nodes.iter().map(|n| n.used_size).collect();
711
180
        let mut r = cache::ReconciliationResult::default();
712
180
        r.layout_roots.insert(tree.root);
713
180
        r.reused_nodes = tree.nodes.len();
714
180
        r.fresh_nodes = 0;
715
180
        (tree, r)
716
    } else {
717
8943
        cache.last_reconcile_was_skipped = false;
718
        // DL-patching input for the STRUCTURE-PRESERVED case (a text edit):
719
        // the sizes the previous pass computed, captured before reconcile
720
        // consumes the old tree.
721
8943
        if let Some(t) = cache.tree.as_ref() {
722
1737
            cache.previous_sizes = t.nodes.iter().map(|n| n.used_size).collect();
723
7206
        }
724
8943
        let dom_diff_clean = cache.dom_diff_clean.take();
725
8943
        cache::reconcile_and_invalidate(&mut ctx_temp, cache, viewport, dom_diff_clean)?
726
    };
727
    // The reuse census, persisted where a test can read it — see the field
728
    // docs on LayoutCache for why this pair is the ONLY external observable
729
    // that distinguishes "reused the warm tree" from "rebuilt it from
730
    // scratch" (both produce identical pixels).
731
9123
    cache.last_reconcile_reused = recon_result.reused_nodes;
732
9123
    cache.last_reconcile_fresh = recon_result.fresh_nodes;
733
9123
    cache.last_fingerprint_skips = recon_result.fingerprint_skips;
734
    // Structure preserved = the same-shaped tree: full reuse+fresh
735
    // accounting at an UNCHANGED node count (content changes make their
736
    // node FRESH — a text edit — but assign the same indices in the same
737
    // traversal; adds/removes change the count and disqualify). Fresh nodes
738
    // are force-re-emitted by the DL patch below, so a same-count REPLACE is
739
    // sound too: its new content never splices stale items.
740
9123
    cache.last_reconcile_structure_preserved = !cache.last_reconcile_was_skipped
741
8943
        && recon_result.reused_nodes + recon_result.fresh_nodes == new_tree_val.nodes.len()
742
8341
        && cache.previous_sizes.len() == new_tree_val.nodes.len();
743
    // [g56 FIX] Box the LayoutTree onto the HEAP. The lifted `&mut new_tree` passed to
744
    // calculate_intrinsic_sizes was mis-lifted (callee saw nodes.len()=0 while the caller saw 2)
745
    // because a stack/SROA'd `new_tree`'s address doesn't survive the cross-function lifted call
746
    // (taking `&new_tree` lifted to 0x0). A heap allocation has a stable absolute wasm address
747
    // that lifts reliably (cf. M8.4 "heap allocations work fine"). Deref coercion handles the
748
    // `&new_tree`/`&mut new_tree`/`new_tree.field` sites unchanged.
749
9123
    let mut new_tree = Box::new(new_tree_val);
750
9123
    {
751
9123
        let _ = (0xDD00_0002u32);
752
9123
    }
753
    // [az-diag g51 REVERT] 0x71 = reconcile_and_invalidate returned OK (no InvalidTree in
754
    // reconcile).
755
9123
    unsafe {
756
9123
        crate::az_mark(0x60704_u32, (0x71u32));
757
9123
    }
758
    // [az-diag g54 REVERT] 0x40740 = new_tree.nodes.len() RIGHT AFTER reconcile. If 0 → reconcile
759
    // built an empty LayoutTree (the bug is in reconcile_recursive/create_node_from_dom). If 2 →
760
    // reconcile is fine and the tree gets emptied/mis-lifted downstream (check 0x40744 at the
761
    // loop).
762
9123
    unsafe {
763
9123
        crate::az_mark(0x60740_u32, (new_tree.nodes.len() as u32));
764
9123
    }
765
9123
    crate::probe::sample_peak_rss("rss:after_reconcile");
766
9123
    crate::probe::sample_phase_peak("rss:peak_during_reconcile");
767

            
768
    // --- Step 1.1: Structural-identity display-list cache ---
769
    //
770
    // If the reconciled root subtree_hash matches the cached one AND
771
    // the viewport is unchanged, nothing structural has moved — skip
772
    // layout, positioning, AND display-list generation and return
773
    // the cached display list verbatim.
774
    //
775
    // This fires on re-renders of an unchanged DOM: the reconcile
776
    // pass still walks and hashes the tree, but that's ~600 µs vs
777
    // the ~4 ms it would otherwise cost to re-emit the display list.
778
9123
    let scroll_fp = scroll_geometry_fingerprint(scroll_offsets);
779
9123
    let input_fp = dl_input_fingerprint(
780
9123
        cursor_is_visible,
781
9123
        &cursor_locations,
782
9123
        text_selections,
783
9123
        preedit_text.as_deref(),
784
9123
        paint_selection_handles,
785
9123
        &seat_focus_rings,
786
9123
        new_dom.get_css_property_cache().dynamic_context.as_deref(),
787
9123
        new_dom.get_css_property_cache().cascade_epoch,
788
    );
789
    if let Some((
790
1917
        cached_hash,
791
1917
        cached_viewport,
792
1917
        cached_gpu_fp,
793
1917
        cached_scroll_fp,
794
1917
        cached_input_fp,
795
1917
        cached_dl,
796
9123
    )) = &cache.cached_display_list
797
    {
798
1917
        let new_root_hash = new_tree
799
1917
            .cold(LayoutNodeId::new(new_tree.root))
800
1917
            .map(|c| c.subtree_hash);
801
        // The GPU-KEY-POPULATION fingerprint is the third key component. The
802
        // emitted list is a function of which nodes carry transform/opacity
803
        // keys (`PushReferenceFrame` exists exactly for keyed nodes), and
804
        // diff-driven animation mints its keys AFTER the first layout — so on
805
        // (hash, viewport) alone this hit served the PRE-KEY list back:
806
        // no reference frames, no GPU damage, a frozen animation. Population
807
        // only, not values: values change every tick, and serving this cached
808
        // list across ticks while values flow through the GPU channel is the
809
        // point of the design.
810
1917
        let gpu_fp =
811
1917
            gpu_value_cache.map_or(0, azul_core::gpu::GpuValueCache::dl_emission_fingerprint);
812
1917
        if css_dirty.is_empty()
813
1316
            && new_root_hash == Some(*cached_hash)
814
902
            && *cached_viewport == viewport
815
516
            && *cached_gpu_fp == gpu_fp
816
494
            && *cached_scroll_fp == scroll_fp
817
494
            && *cached_input_fp == input_fp
818
        {
819
449
            let _p = crate::probe::Probe::span("display_list_cache_hit");
820
            #[cfg(feature = "std")]
821
449
            if std::env::var_os("AZ_ANIM_DEBUG").is_some() {
822
                eprintln!(
823
                    "[dlcache] HIT fp={gpu_fp:x} items={}",
824
                    cached_dl.items.len()
825
                );
826
449
            }
827
449
            let dl = cached_dl.clone();
828
            // The served list is IDENTICAL to the previous frame — this is
829
            // NOT a splice. Left stale from the last real build, the
830
            // renderers' patched-build damage override would replay the old
831
            // patch rects on an idle frame (op_add_remove_timer step 30:
832
            // expected no damage, got rects).
833
449
            cache.last_build_was_patched = false;
834
449
            cache.last_patch_damage = None;
835
449
            return Ok(dl);
836
1468
        }
837
7206
    }
838

            
839
    // --- Step 1.15: fold the CSS DIFF into the solver's dirtiness ---
840
    //
841
    // Mirrors the reconcile classifier exactly (layout-affecting ->
842
    // intrinsic_dirty + layout_roots, the same pair a DirtyFlag::Layout node
843
    // gets). Paint-only entries (`RelayoutScope::None`) deliberately insert
844
    // NOTHING: with the Step 1.1 cache bypassed above, a clean reconcile
845
    // falls into the early-exit below, which reuses the whole tree and
846
    // re-emits the display list from the NEW styled_dom — repaint with zero
847
    // layout work. IfcOnly is treated as SizingOnly: over-invalidation is
848
    // correct (the IFC re-shapes inside the sizing pass); under-invalidation
849
    // is the 200px bug.
850
8674
    if !css_dirty.is_empty() {
851
602
        let needs_layout_work = css_dirty
852
602
            .iter()
853
603
            .any(|(_, scope)| *scope != azul_css::props::property::RelayoutScope::None);
854
602
        if needs_layout_work {
855
600
            let mut dom_to_tree: HashMap<NodeId, usize> =
856
600
                HashMap::with_capacity(new_tree.nodes.len());
857
2296
            for (idx, node) in new_tree.nodes.iter().enumerate() {
858
2296
                if let Some(d) = node.dom_node_id {
859
2296
                    dom_to_tree.insert(d, idx);
860
2296
                }
861
            }
862
600
            let mut dirty_roots = std::collections::BTreeSet::new();
863
1744
            for (dom_id_dirty, scope) in css_dirty {
864
1144
                if *scope == azul_css::props::property::RelayoutScope::None {
865
66
                    continue;
866
1078
                }
867
1078
                if let Some(&idx) = dom_to_tree.get(dom_id_dirty) {
868
1078
                    recon_result.intrinsic_dirty.insert(idx);
869
1078
                    dirty_roots.insert(idx);
870
1078
                }
871
            }
872
            // Same lift as the reconcile's own roots get: a flex item or an
873
            // inline-level box is re-solved by its container, or its
874
            // siblings keep the slots they had.
875
2558
            let promoted = cache::promote_layout_roots_to_containers(&dirty_roots, |idx| {
876
2558
                new_tree
877
2558
                    .nodes
878
2558
                    .get(idx)
879
2558
                    .map(|n| (n.parent, n.formatting_context))
880
2558
            });
881
600
            recon_result.layout_roots.extend(promoted);
882
2
        }
883
8072
    }
884

            
885
    // Step 1.2: Clear Taffy Caches for Dirty Nodes — and their ANCESTORS.
886
    //
887
    // The per-node `taffy_cache` persists across passes (it rides the warm
888
    // carry), keyed by taffy on (known_dimensions, available_space,
889
    // run_mode). Input changes miss by key on their own; what the key can
890
    // NOT see is a content change INSIDE the measured subtree — a deep text
891
    // edit changes what a flex item measures to at the SAME inputs. The
892
    // dirty node alone isn't enough: every ancestor's measure derives from
893
    // it, so the closure must be cleared (same propagation rule as
894
    // `calculate_intrinsic_sizes`' dirty_closure).
895
    //
896
    // This closure-clear is what made it safe to DELETE the unconditional
897
    // "clear every child before every flex layout" hammer in
898
    // `layout_taffy_subtree` (taffy_bridge.rs, from Nov 2025 — it predates
899
    // reconcile-driven dirtiness and was forcing 312 min/max-content
900
    // subtree re-layouts per pass on big.md, ~40% of a steady resize).
901
    {
902
8674
        let closure =
903
8674
            sizing::compute_dirty_ancestor_closure(&new_tree, &recon_result.intrinsic_dirty);
904
221972
        for &node_idx in &closure {
905
213298
            if let Some(warm) = new_tree.warm_mut(LayoutNodeId::new(node_idx)) {
906
213298
                warm.taffy_cache.clear();
907
213298
                warm.measured_content_sizes = (None, None);
908
213298
            }
909
        }
910
    }
911

            
912
    // Step 1.3: Compute CSS Counters
913
    // This must be done after tree generation but before layout,
914
    // as list markers need counter values during formatting context layout
915
8674
    if resize_only && !cache.counters.is_empty() {
916
        // CSS counters are a pure function of the DOM — on a resize-skip
917
        // pass the DOM is byte-identical, so last pass's values are THE
918
        // values (0.4 ms of ::marker recount per drag frame otherwise).
919
        counter_values.clone_from(&cache.counters);
920
8674
    } else {
921
8674
        let _p = crate::probe::Probe::span("compute_counters");
922
8674
        cache::compute_counters(new_dom, &new_tree, &mut counter_values);
923
8674
    }
924
    // [az-diag g51 REVERT] 0x72 = compute_counters done (InvalidTree, if any, is after here).
925
8674
    unsafe {
926
8674
        crate::az_mark(0x60704_u32, (0x72u32));
927
8674
    }
928

            
929
    // Step 1.4: Resize and invalidate per-node cache (Taffy-inspired 9+1 slot cache)
930
    // Move cache_map out of LayoutCache for the duration of layout (avoids borrow conflicts).
931
    // It will be moved back after the layout pass completes.
932
    //
933
    // Critically: the old `cache_map.entries` is indexed by OLD
934
    // layout-tree positions. The NEW tree may have re-ordered
935
    // indices (anonymous wrapper slots shifted, whitespace nodes
936
    // dropped, etc.). A plain `resize_with(default)` would silently
937
    // serve the wrong node's cached result for any shifted index.
938
    //
939
    // Re-map by stable identity: build `old_layout_idx → new_layout_idx`
940
    // via the `(dom_node_id → layout_idx)` tables on both trees,
941
    // then move each surviving cache entry into its new slot. Nodes
942
    // without a matching DOM id (pure anonymous wrappers) fall
943
    // through to the default (empty, i.e. dirty) entry.
944
8674
    let mut cache_map = std::mem::take(&mut cache.cache_map);
945
8674
    let probe_cache_remap = Some(crate::probe::Probe::span("cache_map_remap"));
946
8674
    if let Some(old_tree) = cache.tree.as_ref() {
947
1288
        let mut remapped = cache::LayoutCacheMap::default();
948
1288
        remapped
949
1288
            .entries
950
1288
            .resize_with(new_tree.nodes.len(), Default::default);
951

            
952
        // Primary mapping: DOM id → layout idx on both sides. This
953
        // covers every node that has a corresponding DOM node.
954
37236
        for (dom_id, new_indices) in &new_tree.dom_to_layout {
955
35948
            let Some(old_indices) = old_tree.dom_to_layout.get(dom_id) else {
956
270
                continue;
957
            };
958
36608
            for (pair_idx, &new_layout_idx) in new_indices.iter().enumerate() {
959
36608
                let Some(&old_layout_idx) = old_indices.get(pair_idx) else {
960
                    continue;
961
                };
962
36608
                if old_layout_idx >= LayoutNodeId::new(cache_map.entries.len())
963
35957
                    || new_layout_idx >= LayoutNodeId::new(remapped.entries.len())
964
                {
965
651
                    continue;
966
35957
                }
967
35957
                remapped.entries[new_layout_idx.index()] =
968
35957
                    core::mem::take(&mut cache_map.entries[old_layout_idx.index()]);
969
            }
970
        }
971

            
972
        // Build old-parent → [old_anon_indices] and
973
        // new-parent → [new_anon_indices]; match by pair position.
974
1288
        let old_anon_by_parent = collect_anon_children_by_parent(old_tree);
975
1288
        let new_anon_by_parent = collect_anon_children_by_parent(&new_tree);
976

            
977
        // For each new parent we know: look up its old twin by the
978
        // dom-id mapping we just populated, then match anon children
979
        // positionally within that parent.
980
        // Build a new→old layout-idx lookup from the primary pass.
981
1288
        let mut new_to_old_layout_idx: HashMap<LayoutNodeId, LayoutNodeId> = HashMap::new();
982
37236
        for (dom_id, new_indices) in &new_tree.dom_to_layout {
983
35948
            let Some(old_indices) = old_tree.dom_to_layout.get(dom_id) else {
984
270
                continue;
985
            };
986
36608
            for (pair_idx, &new_layout_idx) in new_indices.iter().enumerate() {
987
36608
                if let Some(&old_layout_idx) = old_indices.get(pair_idx) {
988
36608
                    new_to_old_layout_idx.insert(new_layout_idx, old_layout_idx);
989
36608
                }
990
            }
991
        }
992

            
993
1302
        for (new_parent_idx, new_anon_children) in new_anon_by_parent {
994
14
            let Some(&old_parent_idx) =
995
14
                new_to_old_layout_idx.get(&LayoutNodeId::new(new_parent_idx))
996
            else {
997
                continue;
998
            };
999
14
            let Some(old_anon_children) = old_anon_by_parent.get(&old_parent_idx.index()) else {
1
                continue;
            };
13
            for (ord, &new_anon_idx) in new_anon_children.iter().enumerate() {
13
                let Some(&old_anon_idx) = old_anon_children.get(ord) else {
                    continue;
                };
13
                if old_anon_idx >= cache_map.entries.len() || new_anon_idx >= remapped.entries.len()
                {
                    continue;
13
                }
13
                remapped.entries[new_anon_idx] =
13
                    core::mem::take(&mut cache_map.entries[old_anon_idx]);
            }
        }
1288
        cache_map = remapped;
7386
    } else {
7386
        cache_map.resize_to_tree(new_tree.nodes.len());
7386
    }
8674
    drop(probe_cache_remap);
8674
    crate::probe::sample_peak_rss("rss:after_cache_remap");
220600
    for &node_idx in &recon_result.intrinsic_dirty {
211926
        cache_map.mark_dirty(node_idx, &new_tree.nodes);
211926
    }
17322
    for &node_idx in &recon_result.layout_roots {
8648
        cache_map.mark_dirty(node_idx, &new_tree.nodes);
8648
    }
    // Now create the real context with computed counters
8674
    let mut ctx = LayoutContext {
8674
        // THE REGISTRY THE CALLER PASSED (U1, fixed in U2-a). This was
8674
        // `Default::default()` - the parameter was accepted and never read on
8674
        // the layout path, so a peer's caret colour reached the paint only
8674
        // through `regenerate_display_list_for_dom`; every relayout painted
8674
        // it in the CSS colour.
8674
        owner_colors,
8674
        seat_focus_rings,
8674
        paint_selection_handles,
8674
        style_cache: Default::default(),
8674
        // The report a `VirtualView` is sized by (sizing.rs). The commit that
8674
        // threaded this parameter through left the context at `None`, so no
8674
        // view was ever sized by what it returned - it stayed 300x150.
8674
        virtual_view_sizes: Some(virtual_view_sizes),
8674
        scrollbar_style_cache: core::cell::RefCell::new(HashMap::new()),
8674
        styled_dom: new_dom,
8674
        font_manager,
8674
        text_selections,
8674
        debug_messages,
8674
        counters: &mut counter_values,
8674
        viewport_size: viewport.size,
8674
        fragmentation_context: None,
8674
        reflowed_ifcs: std::collections::BTreeSet::new(),
8674
        cursor_is_visible,
8674
        cursor_locations,
8674
        preedit_text,
8674
        cache_map, // Moved from LayoutCache; will be moved back after layout
8674
        image_cache,
8674
        content_overlay,
8674
        system_style,
8674
        get_system_time_fn,
8674
    };
    // --- Step 1.5: Early Exit Optimization ---
    // M12.7: `&& cache.tree.is_some()` — this "nothing changed, reuse cached
    // layout" fast path REQUIRES a cached tree; on COLD layout cache.tree is
    // None, so entering here would hit `ok_or(InvalidTree)`. recon_result must
    // be dirty on cold (the viewport-resize dirties the root), but if
    // is_clean() mis-evaluates we'd wrongly early-exit → InvalidTree. Guarding
    // on a cached tree is both correct (can't reuse what isn't there) and
    // robust. (rc=5 post-reconcile, step=2: this was the failing `?`.)
8674
    if recon_result.is_clean() && cache.tree.is_some() {
67
        debug_log!(ctx, "No changes, returning existing display list");
        // The reuse census must describe THIS pass: zero sizing work, full
        // tree reuse. Leaving the previous pass's numbers in place made a
        // paint-only repaint look like it charged the cold pass's layout
        // work (the census is load-bearing — tests assert on it).
67
        cache.last_intrinsic_dirty = 0;
67
        cache.last_reconcile_reused = recon_result.reused_nodes;
67
        let tree = cache.tree.as_ref().ok_or(LayoutError::InvalidTree)?;
        // Use cached scroll IDs if available, otherwise compute them
67
        let scroll_ids = if cache.scroll_ids.is_empty() {
            use crate::window::LayoutWindow;
5
            let (scroll_ids, scroll_id_to_node_id) =
5
                LayoutWindow::compute_scroll_ids(tree, new_dom);
5
            cache.scroll_ids.clone_from(&scroll_ids);
5
            cache.scroll_id_to_node_id = scroll_id_to_node_id;
5
            scroll_ids
        } else {
62
            cache.scroll_ids.clone()
        };
67
        if SKIP_DISPLAY_LIST.load(core::sync::atomic::Ordering::Relaxed) {
            cache.record_full_emission();
            return Ok(std::sync::Arc::new(DisplayList::default()));
67
        }
67
        let dl = generate_display_list(
67
            &mut ctx,
67
            tree,
67
            &cache.calculated_positions,
67
            scroll_offsets,
67
            &scroll_ids,
67
            gpu_value_cache,
67
            renderer_resources,
67
            id_namespace,
67
            dom_id,
        )
67
        .map(std::sync::Arc::new)?;
        // Refresh the structural-identity cache with what was JUST emitted.
        // This early exit re-emits precisely because something the cache key
        // could not see changed (a paint-only CSS diff, a GPU-key mint):
        // leaving the old entry in place would serve STALE PAINT on the next
        // call, and not storing at all would re-emit every frame for the
        // whole life of an animation.
67
        let root_hash = tree
67
            .cold(LayoutNodeId::new(tree.root))
67
            .map(|c| c.subtree_hash);
67
        let gpu_fp =
67
            gpu_value_cache.map_or(0, azul_core::gpu::GpuValueCache::dl_emission_fingerprint);
67
        if let Some(h) = root_hash {
67
            cache.cached_display_list =
67
                Some((h, viewport, gpu_fp, scroll_fp, input_fp, dl.clone()));
67
        }
67
        cache.last_dynamic_context = ctx
67
            .styled_dom
67
            .get_css_property_cache()
67
            .dynamic_context
67
            .as_deref()
67
            .cloned();
67
        cache.last_cascade_epoch = ctx.styled_dom.get_css_property_cache().cascade_epoch;
        // Full re-emit, not a splice — clear the patched-build flags so the
        // renderers' damage override cannot replay stale patch rects, and
        // retire the patch log: the renderers' item diff against the list
        // they last presented covers everything from here.
67
        cache.record_full_emission();
67
        return Ok(dl);
8607
    }
8607
    {
8607
        let _ = (0xDD00_0003u32);
8607
    }
    // [az-diag g51 REVERT] 0x80 = reached the incremental layout loop (past early-exit + remap +
    // dirty loops).
8607
    unsafe {
8607
        crate::az_mark(0x60704_u32, (0x80u32));
8607
    }
    // [az-diag g65 PATH-B VALIDATION] new_tree is still valid here (=2). Clone it into the
    // HEAP-backed cache.tree (set AFTER the remap+early-exit which read the OLD cache.tree).
    // cache is the stable &mut arg (read correctly throughout), so cache.tree is NOT a
    // deep-SP-relative stack local. At the sizing call we read BOTH: stack new_tree (expect
    // 0=corrupted) vs heap cache.tree (expect 2 if path B sidesteps the SP-drift/wild-store).
    // If heap=2, the full cache.tree refactor will fix it.
8607
    cache.tree = Some((*new_tree).clone());
    // [az-diag g66] disambiguate the g65 heap=1: read BOTH right after the clone. 0x407C0 = stack
    // new_tree.nodes.len() (source), 0x407C4 = clone cache.tree.nodes.len(). If src=2 & clone=1 →
    // Vec::clone MIS-LIFTS (drops a node) → the full MOVE-based cache.tree refactor avoids it (do
    // it). If src=1=clone → corruption already reached line 758 (heisenbug) → move won't help.
    unsafe {
8607
        crate::az_mark(0x607C0_u32, (new_tree.nodes.len() as u32));
8607
        crate::az_mark(
            0x607C4_u32,
8607
            (cache.tree.as_ref().map_or(999, |t| t.nodes.len()) as u32),
        );
    }
    // --- Step 2: Incremental Layout Loop (handles scrollbar-induced reflows) ---
8607
    let mut calculated_positions = cache.calculated_positions.clone();
8607
    let mut loop_count = 0;
    loop {
8727
        loop_count += 1;
8727
        if loop_count > MAX_SCROLLBAR_REFLOW_ITERATIONS {
            debug_warning!(
                ctx,
                "Scrollbar reflow loop hit limit of {} iterations, breaking to avoid infinite loop",
                MAX_SCROLLBAR_REFLOW_ITERATIONS
            );
            break;
8727
        }
8727
        calculated_positions = {
8727
            let _p = crate::probe::Probe::span("clone_calculated_positions");
8727
            cache.calculated_positions.clone()
        };
        // [az-diag g70 RELIABLE free-band] 0x60780 = nodes.len AFTER the in-loop
        // calculated_positions.clone().
8727
        unsafe {
8727
            crate::az_mark(0x60780_u32, (new_tree.nodes.len() as u32));
8727
        }
8727
        let mut reflow_needed_for_scrollbars = false;
        {
8727
            crate::probe::reset_peak();
            // [az-diag g70 RELIABLE free-band] 0x60784 = nodes.len AFTER reset_peak (before the
            // calc Span).
8727
            unsafe {
8727
                crate::az_mark(0x60784_u32, (new_tree.nodes.len() as u32));
8727
            }
8727
            let _p = crate::probe::Probe::span("calc_intrinsic_sizes");
            // [az-diag g70 RELIABLE free-band] 0x60788 = nodes.len AFTER the calc_intrinsic_sizes
            // Span.
8727
            unsafe {
8727
                crate::az_mark(0x60788_u32, (new_tree.nodes.len() as u32));
8727
            }
            // [az-diag g72 FIX] REMOVED the g48 `#[cfg(feature="web_lift")] panic!(...)` that lived
            // here. web-transpiler => azul-layout?/web_lift IS enabled (dll/Cargo.toml:651), so
            // this panic WAS compiled in, and with `-Z
            // build-std-features=panic_immediate_abort` it lowered to a bare `brk #0x1`
            // right after the 0x90 marker — aborting BEFORE calculate_intrinsic_sizes.
            // The whole-session "new_tree 2→0 corruption" was a MIRAGE: the beforeCall marker store
            // was dead-code-eliminated (after the abort), so the harness read
            // uninitialized 0, not a corrupted tree. Native disasm of layout_document
            // proved it: 0x90 marker store → `brk #0x1` → no `bl
            // calculate_intrinsic_sizes` anywhere. (The prior "string absent ⇒ web_lift off" check
            // was wrong — panic_immediate_abort strips the message string.)
            // [az-diag g65 PATH-B VALIDATION] 0x40748 = stack new_tree.nodes.len() (expect 0),
            // 0x4074C = HEAP cache.tree.nodes.len() (expect 2 if path B sidesteps the corruption).
            unsafe {
8727
                crate::az_mark(0x60748_u32, (new_tree.nodes.len() as u32));
8727
                crate::az_mark(
                    0x6074C_u32,
8727
                    (cache.tree.as_ref().map_or(999, |t| t.nodes.len()) as u32),
                );
            }
8727
            cache.last_intrinsic_dirty = recon_result.intrinsic_dirty.len();
8727
            calculate_intrinsic_sizes(
8727
                &mut ctx,
8727
                &mut new_tree,
8727
                text_cache,
8727
                &recon_result.intrinsic_dirty,
            )?;
        }
8727
        crate::probe::sample_peak_rss("rss:after_calc_intrinsic");
8727
        crate::probe::sample_phase_peak("rss:peak_during_intrinsic");
        // divergence is inside calculate_intrinsic_sizes (the SIMD/text intrinsic pass).
8727
        {
8727
            let _ = (0xDD00_0005u32);
8727
        }
17495
        for &root_idx in &recon_result.layout_roots {
8768
            let (cb_pos, cb_size) = get_containing_block_for_node(
8768
                &new_tree,
8768
                new_dom,
8768
                root_idx,
8768
                &calculated_positions,
8768
                viewport,
8768
            );
            // 0x05, the divergence is INSIDE get_containing_block_for_node (or the for-loop
            // entry); if 0x53 but not 0x55, it's the margin logic / box_props.unpack below.
8768
            {
8768
                let _ = (0xDD00_0053u32);
8768
            }
            // get_containing_block_for_node(viewport)). 800 here but viewport=800 ⟹ OK;
            // 0 here with viewport=800 ⟹ get_containing_block_for_node lost it (HFA return).
            // For ROOT nodes (no parent), we need to account for their margin.
            // The containing block position from viewport is (0, 0), but the root's
            // content starts at (margin + border + padding, margin + border + padding).
            // We pass margin-adjusted position so calculate_content_box_pos works correctly.
8768
            let root_node = &new_tree.nodes[root_idx];
8768
            let root_bp = root_node.box_props.unpack();
8768
            {
8768
                let _ = (0xDD00_0054u32);
8768
            }
8768
            let is_tree_root = root_node.parent.is_none();
8768
            let is_root_with_margin =
8768
                is_tree_root && (root_bp.margin.left != 0.0 || root_bp.margin.top != 0.0);
            // A layout root BELOW the tree root is a dirty subtree re-solved
            // on its own, and it must be laid out exactly where and against
            // what its parent's pass laid it out: from its own slot (the
            // position `calculate_layout_for_subtree` places the children
            // from, which a clean parent keeps), inside the containing block
            // that pass handed it. The parent's content-box origin put the
            // subtree's children at the parent's corner — AzWidgets' body sits
            // below a menu bar, and every knob tick of a switch moved the
            // whole page up by the bar and left by the body's margin.
8768
            let adjusted_cb_pos = if is_root_with_margin {
2463
                LogicalPosition::new(
2463
                    cb_pos.x + root_bp.margin.left,
2463
                    cb_pos.y + root_bp.margin.top,
                )
6305
            } else if is_tree_root {
5705
                cb_pos
            } else {
600
                pos_get(&calculated_positions, root_idx).unwrap_or(cb_pos)
            };
8768
            let root_cb = if is_tree_root {
                // The root's containing block is the viewport — definite on
                // both axes, always.
8168
                geometry::ContainingBlock::definite(cb_size)
            } else {
600
                ctx.cache_map
600
                    .entries
600
                    .get(root_idx)
600
                    .and_then(|c| c.last_containing_block)
600
                    .unwrap_or_else(|| geometry::ContainingBlock::definite(cb_size))
            };
8768
            {
8768
                let _ = (0xDD00_0056u32);
8768
            }
            // DEBUG: Log containing block info for this root
8768
            if let Some(debug_msgs) = ctx.debug_messages.as_mut() {
7044
                let dom_name = root_node
7044
                    .dom_node_id
7044
                    .and_then(|id| new_dom.node_data.as_container().internal.get(id.index()))
7044
                    .map_or_else(|| "Unknown".to_string(), |n| format!("{:?}", n.node_type));
7044
                debug_msgs.push(LayoutDebugMessage::new(
7044
                    LayoutDebugMessageType::PositionCalculation,
7044
                    format!(
7044
                        "[LAYOUT ROOT {}] {} - CB pos=({:.2}, {:.2}), adjusted=({:.2}, {:.2}), CB \
7044
                         size=({:.2}x{:.2}), viewport=({:.2}x{:.2}), margin=({:.2}, {:.2})",
                        root_idx,
                        dom_name,
                        cb_pos.x,
                        cb_pos.y,
                        adjusted_cb_pos.x,
                        adjusted_cb_pos.y,
                        cb_size.width,
                        cb_size.height,
                        viewport.size.width,
                        viewport.size.height,
                        root_bp.margin.left,
                        root_bp.margin.top
                    ),
                ));
1724
            }
            // Purge after intrinsic sizing — frees child_intrinsics Vecs,
            // IntrinsicSizeCalculator temporaries, text measurement caches.
8768
            crate::probe::hint_purge_allocator();
8768
            crate::probe::sample_peak_rss("rss:before_root_layout");
8768
            crate::probe::reset_peak();
            // 0x57 = it RETURNED. If step stays 0x55, calculate_layout_for_subtree diverges.
8768
            {
8768
                let _ = (0xDD00_0055u32);
8768
            }
            // This is exactly what calc_used_size reads as `viewport`. 0 here pinpoints the
            // loss to the ctx build (viewport.size → ctx.viewport_size copy).
            // 0x5E = Err. Do NOT propagate (continue to the cache store) so layout-real can
            // see whether the geometry was computed regardless of a (possibly spurious,
            // niche-Result-mis-discriminated) Err.
8768
            let clr = {
8768
                let _p = crate::probe::Probe::span("root_layout_pass");
8768
                cache::calculate_layout_for_subtree(
8768
                    &mut ctx,
8768
                    &mut new_tree,
8768
                    text_cache,
8768
                    root_idx,
8768
                    adjusted_cb_pos,
8768
                    &root_cb,
8768
                    &mut calculated_positions,
8768
                    &mut reflow_needed_for_scrollbars,
8768
                    &mut cache.float_cache,
8768
                    cache::ComputeMode::PerformLayout,
                )
            };
            {
8768
                let _ = (if clr.is_ok() {
8768
                    0xDD00_0057u32
                } else {
                    0xDD00_005Eu32
                });
            }
8768
            crate::probe::sample_peak_rss("rss:after_root_layout");
8768
            crate::probe::sample_phase_peak("rss:peak_during_root_layout");
            // CRITICAL: Insert the root node's own position into calculated_positions
            // This is necessary because calculate_layout_for_subtree only inserts
            // positions for children, not for the root itself.
            //
            // For root nodes, the position should be at (margin.left, margin.top) relative
            // to the viewport origin, because the margin creates space between the viewport
            // edge and the element's border-box.
8768
            if !pos_contains(&calculated_positions, root_idx) {
7153
                let root_node = &new_tree.nodes[root_idx];
7153
                let root_bp2 = root_node.box_props.unpack();
                // Calculate the root's border-box position by adding margins to viewport origin
                // This is different from non-root nodes which inherit their position from
                // their containing block.
7153
                let root_position = LogicalPosition::new(
7153
                    cb_pos.x + root_bp2.margin.left,
7153
                    cb_pos.y + root_bp2.margin.top,
                );
                // DEBUG: Log root positioning
7153
                if let Some(debug_msgs) = ctx.debug_messages.as_mut() {
6039
                    let dom_name = root_node
6039
                        .dom_node_id
6039
                        .and_then(|id| new_dom.node_data.as_container().internal.get(id.index()))
6039
                        .map_or_else(|| "Unknown".to_string(), |n| format!("{:?}", n.node_type));
6039
                    debug_msgs.push(LayoutDebugMessage::new(
6039
                        LayoutDebugMessageType::PositionCalculation,
6039
                        format!(
6039
                            "[ROOT POSITION {}] {} - Inserting position=({:.2}, {:.2}) (viewport \
6039
                             origin + margin), margin=({:.2}, {:.2}, {:.2}, {:.2})",
                            root_idx,
                            dom_name,
                            root_position.x,
                            root_position.y,
                            root_bp2.margin.top,
                            root_bp2.margin.right,
                            root_bp2.margin.bottom,
                            root_bp2.margin.left
                        ),
                    ));
1114
                }
7153
                pos_set(&mut calculated_positions, root_idx, root_position);
1615
            }
        }
        // (step 6). If step stays 5, the divergence is in calculate_layout_for_subtree.
8727
        {
8727
            let _ = (0xDD00_0006u32);
8727
        }
8727
        {
8727
            let _p = crate::probe::Probe::span("reposition_clean_subtrees");
8727
            cache::reposition_clean_subtrees(
8727
                new_dom,
8727
                &new_tree,
8727
                &recon_result.layout_roots,
8727
                &mut calculated_positions,
8727
            );
8727
        }
8727
        if reflow_needed_for_scrollbars {
120
            debug_log!(
120
                ctx,
120
                "Scrollbars changed container size, starting full reflow (loop {})",
                loop_count
            );
120
            recon_result.layout_roots.clear();
120
            recon_result.layout_roots.insert(new_tree.root);
            // Deliberately NOT touching intrinsic_dirty. A scrollbar toggle
            // changes AVAILABLE SPACE (container inner width shrinks/grows by
            // scrollbar_width); intrinsic min/max-content widths are CONTENT-
            // derived and cannot change because a scrollbar appeared. This
            // line used to mark EVERY node intrinsic-dirty
            // (`(0..nodes.len()).collect()`), so any resize that toggled a
            // scrollbar re-measured the whole document's intrinsics — 75 ms
            // of the measured 166 ms on big.md's first in-range resize, and
            // the same sledgehammer pattern as the old drop-the-tree-on-
            // viewport-change. Nodes whose intrinsics genuinely changed are
            // already in the set from reconciliation; the root layout_root
            // above re-resolves every SIZE against the new inner width.
120
            continue;
8607
        }
8607
        break;
    }
    // +spec:positioning:8d1286 - normal flow, relative, float, absolute positioning dispatch
    // +spec:positioning:bdfc81 - Layout divided into sizing (Step 2) then positioning (Step 3)
    // --- Step 3: Adjust Relatively Positioned Elements ---
    // +spec:positioning:a831e8 - inline content width uses pre-relative-offset positions (satisfied
    // by post-layout relative adjustment) +spec:positioning:e2647b - Relative positioning
    // applied after line height calculation, so line height is not adjusted for relative offsets
    // +spec:positioning:77a2d2 - Relatively positioned boxes considered without their offset during
    // auto height +spec:positioning:b47ac2 - Relatively positioned boxes considered without
    // their offset for block auto height Relative offsets applied AFTER layout, so auto-height
    // calculation sees normal-flow positions. This must be done BEFORE positioning out-of-flow
    // elements, because relatively positioned elements establish containing blocks for their
    // absolutely positioned descendants. If we adjust relative positions after
    // positioning absolute elements, the absolute elements will be positioned
    // relative to the wrong (pre-adjustment) position of their containing block.
    // Pass the viewport to correctly resolve percentage offsets for the root element.
8607
    {
8607
        let _p = crate::probe::Probe::span("adjust_relative_positions");
8607
        positioning::adjust_relative_positions(
8607
            &mut ctx,
8607
            &new_tree,
8607
            &mut calculated_positions,
8607
            viewport,
8607
        );
8607
    }
    // --- Step 3.25: Adjust Sticky Positioned Elements ---
    // Sticky elements are laid out in normal flow, then their visual position
    // is clamped based on scroll offset and inset properties relative to the
    // nearest scrollport. Must happen after relative positioning but before
    // absolute positioning (sticky elements establish containing blocks).
8607
    {
8607
        let _p = crate::probe::Probe::span("adjust_sticky_positions");
8607
        positioning::adjust_sticky_positions(
8607
            &mut ctx,
8607
            &new_tree,
8607
            &mut calculated_positions,
8607
            scroll_offsets,
8607
            viewport,
8607
        );
8607
    }
    // --- Step 3.5: Position Out-of-Flow Elements ---
    // This must be done AFTER adjusting relative positions, so that absolutely
    // positioned elements are positioned relative to the final (post-adjustment)
    // position of their relatively positioned containing blocks.
8607
    {
8607
        let _p = crate::probe::Probe::span("position_out_of_flow");
8607
        positioning::position_out_of_flow_elements(
8607
            &mut ctx,
8607
            &mut new_tree,
8607
            text_cache,
8607
            &mut calculated_positions,
8607
            viewport,
8607
        );
8607
    }
    // --- Step 3.75: Compute Stable Scroll IDs ---
    // This must be done AFTER layout but BEFORE display list generation
8607
    let (scroll_ids, scroll_id_to_node_id) = {
8607
        let _p = crate::probe::Probe::span("compute_scroll_ids");
8607
        LayoutWindow::compute_scroll_ids(&new_tree, new_dom)
8607
    };
8607
    crate::probe::sample_peak_rss("rss:before_display_list");
8607
    crate::probe::reset_peak();
    // --- Step 4: Generate Display List & Update Cache ---
    // (changed-node set, geometry-base rects) of a PATCHED build; consumed
    // after the final list exists to add the changed nodes' ITEM visual
    // bounds from both the old and the new list (shadow fringes).
8607
    let mut patch_damage_pending: Option<(std::collections::BTreeSet<usize>, Vec<LogicalRect>)> =
8607
        None;
8607
    let display_list = if SKIP_DISPLAY_LIST.load(core::sync::atomic::Ordering::Relaxed) {
        // Web backend: positions are done; the painter is dead weight.
        DisplayList::default()
    } else {
8607
        let _p = crate::probe::Probe::span("generate_display_list");
        // DL PATCHING (task 12 round 2): on a resize-skip pass the tree
        // object and its indices are unchanged, so the previous display
        // list's per-node item runs can substitute for the paint calls of
        // every node that neither re-flowed its inline content nor changed
        // size — their items just translate by the node's position delta.
        // `AZ_NO_DL_PATCH=1` is the runtime escape hatch (and the A/B lever
        // for the golden-equality test).
8607
        let patch_disabled = !display_list::dl_patching_enabled();
        // Two ways in: the resize-skip pass (same tree object), or a
        // STRUCTURE-PRESERVED reconcile with no CSS dirt — a text edit
        // reflowed its IFC, everything else splices (per-IFC text patching,
        // USER mandate 2026-08-17). CSS-dirty passes must not splice: their
        // items changed paint without reflowing.
        // Cascade-context equality: an @media/theme/OS flip restyles REUSED
        // nodes without touching NodeData or css_dirty (the reconcile is
        // blind to the cascade), so the structure-preserved arm must also
        // prove the context the cached DL was built under is unchanged.
        // The resize-skip arm keeps its own contract (the harvested
        // breakpoints guarantee no answer flips between crossings).
8607
        let cascade_ctx_unchanged = {
8607
            let cur = ctx
8607
                .styled_dom
8607
                .get_css_property_cache()
8607
                .dynamic_context
8607
                .as_deref();
            #[cfg(feature = "std")]
8607
            if std::env::var_os("AZ_PATCH_DEBUG").is_some() {
                match (cur, cache.last_dynamic_context.as_ref()) {
                    (Some(a), Some(b)) if a != b => {
                        eprintln!(
                            "[CTXDIFF] vw={}/{} vh={}/{} theme={} media={} pseudo={} lang={} \
                             focus={}/{} os={} cont={}",
                            a.viewport_width,
                            b.viewport_width,
                            a.viewport_height,
                            b.viewport_height,
                            a.theme == b.theme,
                            a.media_type == b.media_type,
                            a.pseudo_state == b.pseudo_state,
                            a.language == b.language,
                            a.window_focused,
                            b.window_focused,
                            a.os == b.os
                                && a.os_version == b.os_version
                                && a.desktop_env == b.desktop_env,
                            a.container_width.to_bits() == b.container_width.to_bits()
                                && a.container_height.to_bits() == b.container_height.to_bits()
                                && a.container_name == b.container_name,
                        );
                    }
                    (a, b) if a.is_some() != b.is_some() => {
                        eprintln!(
                            "[CTXDIFF] presence cur={} stored={}",
                            a.is_some(),
                            b.is_some()
                        );
                    }
                    _ => {}
                }
8607
            }
            // The CASCADE EPOCH covers the restyles and user overrides a
            // context comparison could never see, and every context change
            // bumps it, but only WITHIN one StyledDom. The epoch counts per
            // instance from 0, and this arm compares ACROSS instances: the
            // app's `layout()` hands us a new StyledDom, and after a theme flip
            // that one can carry the old instance's epoch while cascading under
            // the other theme. The patch then spliced the light list into the
            // dark tree (AzWriter: page sheets over the ribbon, 23 chrome items
            // missing). So the context itself must match as well.
8607
            let context_unchanged = match (cur, cache.last_dynamic_context.as_ref()) {
1573
                (Some(a), Some(b)) => a == b,
466
                (None, None) => true,
6568
                _ => false,
            };
8607
            context_unchanged
1621
                && cache.last_cascade_epoch
1621
                    == ctx.styled_dom.get_css_property_cache().cascade_epoch
        };
8607
        let structure_ok = cache.last_reconcile_was_skipped
8427
            || (cache.last_reconcile_structure_preserved
867
                && css_dirty.is_empty()
268
                && cascade_ctx_unchanged);
        #[cfg(feature = "std")]
8607
        if std::env::var_os("AZ_PATCH_DEBUG").is_some() {
            eprintln!(
                "[PATCHGATE] skipped={} preserved={} css_dirty={} structure_ok={} disabled={} \
                 prev_sizes={} nodes={} prev_pos={} pos={} ctx_same={} reflowed_ifcs={:?} \
                 fresh={:?}",
                cache.last_reconcile_was_skipped,
                cache.last_reconcile_structure_preserved,
                css_dirty.len(),
                structure_ok,
                patch_disabled,
                cache.previous_sizes.len(),
                new_tree.nodes.len(),
                cache.calculated_positions.len(),
                calculated_positions.len(),
                cascade_ctx_unchanged,
                ctx.reflowed_ifcs,
                recon_result.fresh_indices,
            );
8607
        }
        // (previous_sizes vs NODES is intended: the cache keeps one entry
        // per node, so equal lengths mean the size snapshot covers the tree.)
        #[allow(clippy::suspicious_operation_groupings)]
8607
        let patch = if structure_ok
264
            && !patch_disabled
244
            && cache.previous_sizes.len() == new_tree.nodes.len()
244
            && cache.calculated_positions.len() == calculated_positions.len()
        {
244
            cache
244
                .cached_display_list
244
                .as_ref()
244
                .and_then(|(_, _, _, _, _, prev_dl)| {
224
                    let new_sizes: Vec<Option<LogicalSize>> =
224
                        new_tree.nodes.iter().map(|n| n.used_size).collect();
                    // Fresh/content-changed nodes must RE-EMIT, never splice —
                    // their previous items describe content that no longer
                    // exists (the text-edit case, and same-count replaces). The
                    // intrinsic-dirty ANCESTOR chain is deliberately not here:
                    // an ancestor whose geometry did not change splices its
                    // unchanged items (size/position changes re-emit via
                    // PatchState's own size diff).
224
                    let mut reemit = ctx.reflowed_ifcs.clone();
224
                    reemit.extend(recon_result.fresh_indices.iter().copied());
224
                    display_list::PatchState::build(
224
                        prev_dl,
224
                        &cache.calculated_positions, // last pass's positions (replaced later)
224
                        &calculated_positions,
224
                        &cache.previous_sizes,
224
                        &new_sizes,
224
                        &reemit,
                    )
224
                })
        } else {
8363
            None
        };
        // Field writes, not `cache.record_*()`: `patch` borrows
        // `cache.cached_display_list` for the rest of this build, and a
        // `&mut self` method call would conflict with it where disjoint
        // field writes do not. Same bookkeeping as `record_full_emission`.
8607
        if patch.is_some() {
224
            // The damage is recorded below, once the final list exists.
224
            cache.last_build_was_patched = true;
224
            cache.last_patch_damage = None;
8383
        } else {
8383
            cache.build_seq = cache.build_seq.wrapping_add(1);
8383
            cache.last_full_build_seq = cache.build_seq;
8383
            cache.last_build_was_patched = false;
8383
            cache.last_patch_damage = None;
8383
            cache.patch_damage_log.clear();
8383
        }
8607
        if patch.is_some() {
            // The patch's own damage, phase 1 of 2: the CHANGED-node set
            // (re-emitted OR moved/resized) plus old ∪ new NODE bounds as the
            // geometry base (covers vacated areas and items with no bounds).
            // Phase 2 — after the final list exists — unions the changed
            // nodes' ITEM visual bounds from BOTH lists on top: paint like
            // box-shadow extends OUTSIDE the node box, so node rects alone
            // under-damage a shadow fringe.
224
            let mut rects: Vec<LogicalRect> = Vec::new();
224
            let mut changed: std::collections::BTreeSet<usize> = ctx.reflowed_ifcs.clone();
224
            changed.extend(recon_result.fresh_indices.iter().copied());
1348
            for (idx, node) in new_tree.nodes.iter().enumerate() {
1348
                let old_pos = pos_get(&cache.calculated_positions, idx);
1348
                let new_pos = pos_get(&calculated_positions, idx);
1348
                let old_size = cache.previous_sizes.get(idx).copied().flatten();
1348
                let new_size = node.used_size;
1348
                if !(changed.contains(&idx) || old_pos != new_pos || old_size != new_size) {
669
                    continue;
679
                }
679
                changed.insert(idx);
679
                if let (Some(p), Some(sz)) = (old_pos, old_size) {
665
                    rects.push(LogicalRect::new(p, sz));
665
                }
679
                if let (Some(p), Some(sz)) = (new_pos, new_size) {
665
                    rects.push(LogicalRect::new(p, sz));
665
                }
            }
224
            patch_damage_pending = Some((changed, rects));
8383
        }
8607
        if patch.is_some() {
224
            drop(crate::probe::Probe::span("dl_patched_pass"));
            // Round-3 presentation hint from the SAME inputs the patch used.
            // The re-emit set must match PatchState's exactly: reflowed IFCs
            // PLUS size-changed nodes — a size-changed node re-emitted its
            // items, so blitting its old pixels without repainting is stale.
224
            let new_sizes: Vec<Option<LogicalSize>> =
224
                new_tree.nodes.iter().map(|n| n.used_size).collect();
224
            let mut reemit_full = ctx.reflowed_ifcs.clone();
224
            reemit_full.extend(recon_result.fresh_indices.iter().copied());
1348
            for (i, (prev, new)) in cache
224
                .previous_sizes
224
                .iter()
224
                .zip(new_sizes.iter())
224
                .enumerate()
            {
1348
                if prev != new {
501
                    reemit_full.insert(i);
847
                }
            }
224
            let parents: Vec<Option<usize>> = new_tree.nodes.iter().map(|n| n.parent).collect();
224
            let opaque_bg: Vec<bool> = (0..new_tree.nodes.len())
1348
                .map(|i| {
1348
                    new_tree
1348
                        .get(LayoutNodeId::new(i))
1348
                        .and_then(|node| node.dom_node_id)
1348
                        .is_some_and(|dom_id| {
1348
                            let state = &ctx.styled_dom.styled_nodes.as_container()[dom_id]
1348
                                .styled_node_state;
1348
                            getters::get_background_color(ctx.styled_dom, dom_id, state).a == 255
1348
                        })
1348
                })
224
                .collect();
224
            cache.last_patch_move = display_list::compute_patch_move_summary(
224
                &cache.calculated_positions,
224
                &calculated_positions,
224
                &cache.previous_sizes,
224
                &new_sizes,
224
                &reemit_full,
224
                &parents,
224
                &opaque_bg,
            );
8383
        } else {
8383
            cache.last_patch_move = None;
8383
        }
8607
        display_list::generate_display_list_impl(
8607
            &mut ctx,
8607
            &new_tree,
8607
            &calculated_positions,
8607
            scroll_offsets,
8607
            &scroll_ids,
8607
            gpu_value_cache,
8607
            renderer_resources,
8607
            id_namespace,
8607
            dom_id,
8607
            patch,
        )?
    };
8607
    crate::probe::sample_phase_peak("rss:peak_during_display_list");
    // Move cache_map back into LayoutCache before dropping ctx
8607
    let _p_writeback = crate::probe::Probe::span("cache_writeback");
8607
    let cache_map_back = std::mem::take(&mut ctx.cache_map);
    // Cache the freshly-generated display list keyed on the root's
    // subtree_hash + viewport. If the next `layout_document` call
    // sees matching values after reconcile, it returns this clone
    // directly and skips all downstream work.
8607
    let root_subtree_hash = new_tree
8607
        .cold(LayoutNodeId::new(new_tree.root))
8607
        .map_or(layout_tree::SubtreeHash(0), |c| c.subtree_hash);
    // The DL is shared, not copied: one allocation serves the cache slot, the
    // caller's `DomLayoutResult`, and any virtual-view snapshot maps. Rare
    // post-build patches (`patch_node_image` / `patch_text_glyphs` / the
    // virtual-view placeholder swap) go through `Arc::make_mut`.
8607
    let display_list = std::sync::Arc::new(display_list);
    // Record the population fingerprint of the SAME GpuValueCache the emission
    // above consumed (the &-param is immutable for the whole pass, so entry
    // fingerprint == emission fingerprint). Keys minted after this call — the
    // scrollbar registration in the caller, animation seeding — change the
    // manager's cache, the next call's fingerprint differs, and the cache
    // correctly misses once and re-seeds.
8607
    let gpu_fp = gpu_value_cache.map_or(0, azul_core::gpu::GpuValueCache::dl_emission_fingerprint);
    #[cfg(feature = "std")]
8607
    if std::env::var_os("AZ_ANIM_DEBUG").is_some() {
        eprintln!(
            "[dlcache] STORE fp={gpu_fp:x} items={}",
            display_list.items.len()
        );
8607
    }
    // Patched-build damage, phase 2: union the changed nodes' ITEM visual
    // bounds from the OLD list (still in the cache slot here) and the NEW
    // one on top of the geometry base. `visual_bounds()` includes paint
    // that extends outside the node box (box-shadow fringes) — the same
    // bounds the item diff damages with.
8607
    if let Some((changed, mut rects)) = patch_damage_pending.take() {
        {
448
            let mut add_items = |dl: &DisplayList| {
6758
                for (i, m) in dl.layout_node_mapping.iter().enumerate() {
6758
                    if let Some((idx, _)) = m {
3492
                        if changed.contains(idx) {
2422
                            if let Some(b) = dl.items[i].visual_bounds() {
2422
                                rects.push(b);
2422
                            }
1070
                        }
3266
                    }
                }
448
            };
224
            if let Some((_, _, _, _, _, old_dl)) = cache.cached_display_list.as_ref() {
224
                add_items(old_dl);
224
            }
224
            add_items(&display_list);
        }
        #[cfg(feature = "std")]
224
        if std::env::var_os("AZ_PATCH_DEBUG").is_some() {
            eprintln!("[PATCHDMG] rects={rects:?}");
224
        }
        // Onto the LOG, not just the slot: a second patched build before the
        // next present (a callback's css patch followed by the RefreshDom it
        // returns) must not erase this one's vacated rects. Field writes for
        // the same borrow reason as above; same bookkeeping as
        // `record_patch_damage`.
224
        cache.build_seq = cache.build_seq.wrapping_add(1);
224
        cache
224
            .patch_damage_log
224
            .push((cache.build_seq, rects.clone()));
224
        if cache.patch_damage_log.len() > cache::PATCH_DAMAGE_LOG_CAP {
            let excess = cache.patch_damage_log.len() - cache::PATCH_DAMAGE_LOG_CAP;
            cache.patch_damage_log.drain(..excess);
224
        }
224
        cache.last_patch_damage = Some(rects);
8383
    }
    // The context this build was made under — the structure-preserved patch
    // arm compares the NEXT pass's context against it. Clone only on CHANGE:
    // the steady state (every keystroke) is an equal context, and the clone
    // allocates (AzString language, container name).
    {
8607
        let cur = ctx
8607
            .styled_dom
8607
            .get_css_property_cache()
8607
            .dynamic_context
8607
            .as_deref();
8607
        let same = match (cur, cache.last_dynamic_context.as_ref()) {
1573
            (Some(a), Some(b)) => a == b,
466
            (None, None) => true,
6568
            _ => false,
        };
8607
        if !same {
6986
            cache.last_dynamic_context = cur.cloned();
6986
        }
8607
        cache.last_cascade_epoch = ctx.styled_dom.get_css_property_cache().cascade_epoch;
    }
8607
    cache.cached_display_list = Some((
8607
        root_subtree_hash,
8607
        viewport,
8607
        gpu_fp,
8607
        scroll_fp,
8607
        input_fp,
8607
        display_list.clone(),
8607
    ));
8607
    cache.tree = Some(*new_tree); // [g56] unbox the heap LayoutTree back into the cache
8607
    cache.previous_positions =
8607
        std::mem::replace(&mut cache.calculated_positions, calculated_positions);
8607
    cache.viewport = Some(viewport);
8607
    cache.scroll_ids = scroll_ids;
8607
    cache.scroll_id_to_node_id = scroll_id_to_node_id;
    // + calculated_positions.len in the low bits. If step stays 3, it diverged earlier.
8607
    {
8607
        let _ = (0xDD00_0004u32 | ((cache.calculated_positions.len() as u32 & 0xfff) << 4));
8607
    }
8607
    let _doc_tail_span = crate::probe::Probe::span("doc_tail_writeback");
8607
    cache.counters = counter_values;
8607
    cache.cache_map = cache_map_back;
8607
    crate::probe::sample_peak_rss("rss:after_layout_document");
8607
    Ok(display_list)
9123
}
// +spec:containing-block:159830 - Containing block chain: parent content-box for in-flow, viewport
// for initial containing block +spec:containing-block:22fbaa - computes the element's original
// containing block (before positioning effects) +spec:containing-block:238fc5 - containing block
// dimensions calculated here (CSS 2.2 §9.1.2 forward ref to §10) +spec:containing-block:263629 -
// block element's content-box establishes the containing block for its line boxes
// +spec:containing-block:2a5280 - boxes act as containing blocks for descendants; CB = parent's
// content box +spec:containing-block:6776cb - boxes positioned w.r.t. containing block but not
// confined; overflow allowed +spec:containing-block:718894 - CB derived from parent content-box
// edges; root uses initial CB (viewport) +spec:containing-block:a2aa37 - box edges act as
// containing block for descendants; initial containing block = viewport +spec:containing-block:
// e23b3f - CSS 2.2 §10.1: initial containing block = viewport; static/relative = parent
// content-box; fixed = viewport +spec:containing-block:e8fdb2 - Containing block resolution (CSS2
// §9.1.2, §10.1) +spec:overflow:9a2b11 - containing block is content-box of parent; boxes may
// overflow it +spec:positioning:acc663 - containing block definition: element boxes positioned
// relative to containing block
10513
pub(super) fn get_containing_block_for_node(
10513
    tree: &LayoutTree,
10513
    styled_dom: &StyledDom,
10513
    node_idx: usize,
10513
    calculated_positions: &PositionVec,
10513
    viewport: LogicalRect,
10513
) -> (LogicalPosition, LogicalSize) {
10513
    if let Some(parent_idx) = tree.get(LayoutNodeId::new(node_idx)).and_then(|n| n.parent) {
611
        if let Some(parent_node) = tree.get(LayoutNodeId::new(parent_idx)) {
610
            let pos = pos_get(calculated_positions, parent_idx).unwrap_or(viewport.origin);
            // The parent's size — or, when the parent has none yet (a node
            // the reconcile just rebuilt: an anonymous IFC wrapper created
            // for this pass, a container whose child list changed), the
            // nearest sized ancestor's content box. This used to be
            // `unwrap_or_default()`: a silent 0x0 containing block, under
            // which every shrink-to-fit box is min-content — the "Increase
            // counter" button breaking into two words after a theme switch
            // (an inline-level box dirtied by a colour twin, behind an
            // unchanged block sibling). The POSITION still comes from the
            // parent's own cached slot, which index reuse keeps current; only
            // the dimensions are borrowed, which is what a containing block
            // contributes to shrink-to-fit and percentage resolution.
610
            let size = parent_node.used_size.unwrap_or_else(|| {
2
                let mut cur = parent_node.parent;
                loop {
2
                    match cur.and_then(|i| tree.get(LayoutNodeId::new(i))) {
1
                        Some(n) => match n.used_size {
1
                            Some(s) => {
1
                                break n.box_props.unpack().inner_size(
1
                                    s,
1
                                    azul_css::props::layout::LayoutWritingMode::default(),
                                );
                            }
                            None => cur = n.parent,
                        },
1
                        None => break viewport.size,
                    }
                }
2
            });
            // Position in calculated_positions is the margin-box position
            // To get content-box, add: border + padding (NOT margin, that's already in pos)
610
            let pbp = parent_node.box_props.unpack();
610
            let content_pos = LogicalPosition::new(
610
                pos.x + pbp.border.left + pbp.padding.left,
610
                pos.y + pbp.border.top + pbp.padding.top,
            );
610
            if let Some(dom_id) = parent_node.dom_node_id {
608
                let styled_node_state = &styled_dom
608
                    .styled_nodes
608
                    .as_container()
608
                    .get(dom_id)
608
                    .map(|n| &n.styled_node_state)
608
                    .copied()
608
                    .unwrap_or_default();
                // +spec:containing-block:c205e5 - writing mode of containing block used for
                // inner_size (orthogonal flow awareness)
608
                let writing_mode =
608
                    get_writing_mode(styled_dom, dom_id, styled_node_state).unwrap_or_default();
608
                let content_size = pbp.inner_size(size, writing_mode);
608
                return (content_pos, content_size);
2
            }
2
            return (content_pos, size);
1
        }
9902
    }
    // +spec:containing-block:41bdfc - ICB equals viewport; overflow:hidden on root clips to ICB
    // +spec:containing-block:1eed60 - Initial containing block establishes a BFC; viewport is the
    // ICB +spec:containing-block:99866f - Containing block is a rectangle for
    // sizing/positioning; ICB from viewport +spec:containing-block:22f09b - viewport serves as
    // initial containing block for root element Root element's containing block is the initial
    // containing block (CSS 2.2 §10.1, CSS Display 3 §2.8). +spec:containing-block:2fd7b1 - ICB
    // equals viewport; principal writing mode propagated to ICB Root element's containing block
    // is the initial containing block (CSS 2.2 §10.1, CSS Display 3 §2.8). The principal
    // writing mode is propagated to the ICB and viewport (css-writing-modes-4 §8.1).
    // +spec:containing-block:5efb84 - Root element's containing block is the initial containing
    // block +spec:containing-block:6278fb - initial containing block is the viewport; also
    // serves as initial fixed containing block Root element's containing block is the initial
    // containing block (CSS 2.2 §10.1, CSS Display 3 §2.8). For ROOT nodes: the containing
    // block is the viewport (initial containing block). Do NOT subtract margin here - margins
    // are handled in calculate_used_size(). The margin creates space between viewport edge and
    // element's border-box, but the available space for calculating width/height percentages
    // is still the full viewport size.
9903
    (viewport.origin, viewport.size)
10513
}
// [g119 az-web-lift FIX] `#[repr(C, u8)]` (was repr(Rust)): the `Text(font_traits::LayoutError)`
// variant's String/FontSelector pointer gives `Result<T, LayoutError>` a POINTER-niche disc, which
// the web lift MIS-READS → every solver3 `?`/Result return flips Ok→Err (heisenbug; g118 =
// collect's Result<(),LayoutError> arrived as Err → rc=5 InvalidTree though the out-param content
// was correct). An explicit u8 tag (0..=4) moves the Result niche to unused tag values (5..) = a
// simple u8 compare the lift handles. Same disc-mis-lift class as
// InlineContent/LogicalItem/ShapedItem (g117/g118).
#[allow(variant_size_differences)]
// repr(C,u8) FFI enum: boxing the large variant would change the C ABI (api.json bindings); size
// disparity accepted
#[derive(Debug)]
#[repr(C, u8)]
pub enum LayoutError {
    InvalidTree,
    SizingFailed,
    PositioningFailed,
    DisplayListFailed,
    Text(crate::font_traits::LayoutError),
}
impl std::fmt::Display for LayoutError {
19
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
19
        match self {
5
            Self::InvalidTree => write!(f, "Invalid layout tree"),
2
            Self::SizingFailed => write!(f, "Sizing calculation failed"),
2
            Self::PositioningFailed => write!(f, "Position calculation failed"),
2
            Self::DisplayListFailed => write!(f, "Display list generation failed"),
8
            Self::Text(e) => write!(f, "Text layout error: {e:?}"),
        }
19
    }
}
impl From<crate::font_traits::LayoutError> for LayoutError {
2
    fn from(err: crate::font_traits::LayoutError) -> Self {
2
        Self::Text(err)
2
    }
}
impl std::error::Error for LayoutError {}
pub type Result<T> = std::result::Result<T, LayoutError>;
#[cfg(test)]
#[allow(clippy::float_cmp, clippy::too_many_lines)]
mod autotest_generated {
    use azul_core::dom::{Dom, FormattingContext};
    use super::*;
    use crate::solver3::{
        geometry::{EdgeSizes, PackedBoxProps, ResolvedBoxProps},
        layout_tree::{LayoutNodeCold, LayoutNodeHot, LayoutNodeWarm},
    };
    // ==================================================================
    // Fixtures
    // ==================================================================
    fn pos(x: f32, y: f32) -> LogicalPosition {
        LogicalPosition::new(x, y)
    }
    fn size(w: f32, h: f32) -> LogicalSize {
        LogicalSize::new(w, h)
    }
    fn rect(x: f32, y: f32, w: f32, h: f32) -> LogicalRect {
        LogicalRect {
            origin: pos(x, y),
            size: size(w, h),
        }
    }
    fn edges(top: f32, right: f32, bottom: f32, left: f32) -> EdgeSizes {
        EdgeSizes {
            top,
            right,
            bottom,
            left,
        }
    }
    /// `ResolvedBoxProps` with the given padding + border and no margin.
    fn bp(padding: EdgeSizes, border: EdgeSizes) -> ResolvedBoxProps {
        ResolvedBoxProps {
            margin: EdgeSizes::default(),
            padding,
            border,
            ..ResolvedBoxProps::default()
        }
    }
    fn hot(
        parent: Option<usize>,
        dom_node_id: Option<NodeId>,
        used_size: Option<LogicalSize>,
        props: &ResolvedBoxProps,
    ) -> LayoutNodeHot {
        LayoutNodeHot {
            box_props: PackedBoxProps::pack(props),
            dom_node_id,
            used_size,
            formatting_context: FormattingContext::default(),
            parent,
        }
    }
    /// A `LayoutTree` carrying only what `get_containing_block_for_node` reads:
    /// hot nodes (parent link, box props, `used_size`, `dom_node_id`).
    fn tree_of(nodes: Vec<LayoutNodeHot>) -> LayoutTree {
        let n = nodes.len();
        LayoutTree {
            nodes,
            warm: vec![LayoutNodeWarm::default(); n],
            cold: vec![LayoutNodeCold::default(); n],
            root: 0,
            dom_to_layout: BTreeMap::new(),
            children_arena: Vec::new(),
            children_offsets: vec![(0, 0); n],
            subtree_needs_intrinsic: vec![false; n],
        }
    }
    /// Box props survive a lossy i16×10 pack/unpack, so geometry derived from
    /// them is compared with a tolerance well under a tenth of a pixel.
    fn close(a: f32, b: f32) -> bool {
        (a - b).abs() < 1e-3
    }
    /// `body` — one real DOM node, so `NodeId::ZERO` is always in range.
    fn body_dom() -> StyledDom {
        let mut dom = Dom::create_body();
        let (css, _warnings) = azul_css::parser2::new_from_str("");
        StyledDom::create(&mut dom, css)
    }
    // ==================================================================
    // POSITION_UNSET — the sentinel the three pos_* helpers are built on
    // ==================================================================
    #[test]
    fn position_unset_sets_both_components_to_f32_min() {
        // `pos_get`/`pos_contains` only test `x`; that shortcut is only sound
        // while the sentinel writes BOTH components. Pin the invariant here.
        assert_eq!(POSITION_UNSET.x, f32::MIN);
        assert_eq!(POSITION_UNSET.y, f32::MIN);
    }
    // ==================================================================
    // pos_get / pos_contains — bounds + sentinel (numeric)
    // ==================================================================
    #[test]
    fn pos_get_on_an_empty_vec_is_none_for_every_index() {
        let positions: PositionVec = Vec::new();
        for idx in [0usize, 1, 7, 1_000, usize::MAX / 2, usize::MAX] {
            assert!(pos_get(&positions, idx).is_none(), "idx {idx}");
            assert!(!pos_contains(&positions, idx), "idx {idx}");
        }
    }
    #[test]
    fn pos_get_past_the_end_is_none_and_never_panics() {
        let mut positions: PositionVec = Vec::new();
        pos_set(&mut positions, 3, pos(1.0, 2.0));
        assert_eq!(positions.len(), 4);
        for idx in [4usize, 5, 100, usize::MAX] {
            assert!(pos_get(&positions, idx).is_none(), "idx {idx}");
            assert!(!pos_contains(&positions, idx), "idx {idx}");
        }
    }
    #[test]
    fn pos_get_at_zero_round_trips() {
        let mut positions: PositionVec = Vec::new();
        pos_set(&mut positions, 0, pos(0.0, 0.0));
        let got = pos_get(&positions, 0).expect("index 0 was set");
        assert_eq!(got.x, 0.0);
        assert_eq!(got.y, 0.0);
        assert!(pos_contains(&positions, 0));
    }
    #[test]
    fn an_explicitly_written_sentinel_reads_back_as_unset() {
        // Writing POSITION_UNSET is indistinguishable from never writing at all.
        // That is by design (it's how `pos_set`'s gap-fill works), but it means a
        // caller can never store the sentinel as a real position.
        let mut positions: PositionVec = Vec::new();
        pos_set(&mut positions, 0, POSITION_UNSET);
        assert_eq!(positions.len(), 1);
        assert!(pos_get(&positions, 0).is_none());
        assert!(!pos_contains(&positions, 0));
    }
    #[test]
    fn a_position_whose_x_is_f32_min_reads_back_as_unset_even_with_a_real_y() {
        // Only `x` is compared against the sentinel, so `y` is silently discarded
        // whenever `x` happens to land exactly on f32::MIN.
        let mut positions: PositionVec = Vec::new();
        pos_set(&mut positions, 0, pos(f32::MIN, 42.0));
        assert!(pos_get(&positions, 0).is_none());
        assert!(!pos_contains(&positions, 0));
        // ...even though the value really is in the vec.
        assert_eq!(positions[0].y, 42.0);
    }
    #[test]
    fn negative_f32_max_is_the_same_bit_pattern_as_the_sentinel() {
        // f32::MIN == -f32::MAX, so a genuinely computed x of -f32::MAX (e.g. a
        // wildly out-of-flow element) is swallowed by the sentinel check.
        assert_eq!(f32::MIN, -f32::MAX);
        let mut positions: PositionVec = Vec::new();
        pos_set(&mut positions, 0, pos(-f32::MAX, 0.0));
        assert!(pos_get(&positions, 0).is_none());
    }
    #[test]
    fn a_position_whose_y_is_f32_min_is_still_reported_as_set() {
        let mut positions: PositionVec = Vec::new();
        pos_set(&mut positions, 0, pos(0.0, f32::MIN));
        let got = pos_get(&positions, 0).expect("x is not the sentinel, so it is set");
        assert_eq!(got.x, 0.0);
        assert_eq!(got.y, f32::MIN);
        assert!(pos_contains(&positions, 0));
    }
    #[test]
    fn nan_positions_are_considered_set_and_survive_the_round_trip() {
        // NaN != f32::MIN is true, so a NaN position is "set" — it propagates into
        // layout rather than being filtered out as unset.
        let mut positions: PositionVec = Vec::new();
        pos_set(&mut positions, 0, pos(f32::NAN, f32::NAN));
        let got = pos_get(&positions, 0).expect("NaN passes the sentinel filter");
        assert!(got.x.is_nan());
        assert!(got.y.is_nan());
        assert!(pos_contains(&positions, 0));
    }
    #[test]
    fn infinite_and_extreme_positions_round_trip_unchanged() {
        let cases = [
            pos(f32::INFINITY, f32::NEG_INFINITY),
            pos(f32::MAX, -f32::MIN_POSITIVE),
            pos(-0.0, 0.0),
            pos(-1e30, 1e30),
            pos(f32::MIN_POSITIVE, f32::EPSILON),
        ];
        for (idx, case) in cases.iter().enumerate() {
            let mut positions: PositionVec = Vec::new();
            pos_set(&mut positions, idx, *case);
            let got = pos_get(&positions, idx).expect("non-sentinel x is set");
            assert_eq!(got.x.to_bits(), case.x.to_bits(), "case {idx} x");
            assert_eq!(got.y.to_bits(), case.y.to_bits(), "case {idx} y");
            assert!(pos_contains(&positions, idx), "case {idx}");
        }
    }
    #[test]
    fn pos_contains_always_agrees_with_pos_get() {
        // The predicate and the getter must never disagree — a divergence would
        // make `pos_get(..).unwrap()` guarded by `pos_contains` panic.
        let values = [
            pos(0.0, 0.0),
            pos(-0.0, -0.0),
            POSITION_UNSET,
            pos(f32::MIN, 1.0),
            pos(1.0, f32::MIN),
            pos(f32::NAN, 0.0),
            pos(f32::INFINITY, f32::INFINITY),
            pos(f32::NEG_INFINITY, 0.0),
            pos(f32::MAX, f32::MIN_POSITIVE),
            pos(-f32::MAX, 0.0),
        ];
        let mut positions: PositionVec = Vec::new();
        for (idx, v) in values.iter().enumerate() {
            pos_set(&mut positions, idx, *v);
        }
        for idx in 0..values.len() + 4 {
            assert_eq!(
                pos_contains(&positions, idx),
                pos_get(&positions, idx).is_some(),
                "idx {idx} disagrees"
            );
        }
    }
    // ==================================================================
    // pos_set — growth semantics (numeric)
    // ==================================================================
    #[test]
    fn pos_set_beyond_the_end_grows_and_fills_the_gap_with_the_sentinel() {
        let mut positions: PositionVec = Vec::new();
        pos_set(&mut positions, 3, pos(10.0, 20.0));
        assert_eq!(positions.len(), 4, "grows to exactly idx + 1");
        for idx in 0..3 {
            assert!(
                pos_get(&positions, idx).is_none(),
                "gap idx {idx} must be unset"
            );
            assert!(!pos_contains(&positions, idx), "gap idx {idx}");
            assert_eq!(positions[idx].x, POSITION_UNSET.x);
            assert_eq!(positions[idx].y, POSITION_UNSET.y);
        }
        let got = pos_get(&positions, 3).expect("idx 3 was set");
        assert_eq!(got.x, 10.0);
        assert_eq!(got.y, 20.0);
    }
    #[test]
    fn pos_set_inside_the_vec_neither_grows_nor_shrinks_it() {
        let mut positions: PositionVec = vec![POSITION_UNSET; 5];
        pos_set(&mut positions, 0, pos(1.0, 1.0));
        assert_eq!(positions.len(), 5);
        pos_set(&mut positions, 4, pos(2.0, 2.0));
        assert_eq!(positions.len(), 5);
        assert!(pos_contains(&positions, 0));
        assert!(pos_contains(&positions, 4));
        assert!(!pos_contains(&positions, 2), "untouched slots stay unset");
    }
    #[test]
    fn pos_set_overwrites_an_existing_entry_in_place() {
        let mut positions: PositionVec = Vec::new();
        pos_set(&mut positions, 1, pos(1.0, 1.0));
        pos_set(&mut positions, 1, pos(-5.5, -6.5));
        assert_eq!(positions.len(), 2);
        let got = pos_get(&positions, 1).expect("still set");
        assert_eq!(got.x, -5.5);
        assert_eq!(got.y, -6.5);
    }
    #[test]
    fn pos_set_can_reset_an_entry_back_to_unset() {
        let mut positions: PositionVec = Vec::new();
        pos_set(&mut positions, 0, pos(3.0, 4.0));
        assert!(pos_contains(&positions, 0));
        pos_set(&mut positions, 0, POSITION_UNSET);
        assert!(!pos_contains(&positions, 0));
        assert!(pos_get(&positions, 0).is_none());
    }
    #[test]
    fn repeated_growth_preserves_every_earlier_entry() {
        let mut positions: PositionVec = Vec::new();
        for idx in (0..64).rev() {
            // Descending order: the first call allocates the whole vec, the rest
            // write inside it — the reverse of the ascending growth path.
            pos_set(&mut positions, idx, pos(idx as f32, -(idx as f32)));
        }
        assert_eq!(positions.len(), 64);
        for idx in 0..64 {
            let got = pos_get(&positions, idx).expect("all 64 were written");
            assert_eq!(got.x, idx as f32);
            assert_eq!(got.y, -(idx as f32));
        }
        // A single jump far past the end must keep everything already written.
        pos_set(&mut positions, 4_095, pos(1.0, 1.0));
        assert_eq!(positions.len(), 4_096);
        for idx in 0..64 {
            assert!(pos_contains(&positions, idx), "idx {idx} lost after regrow");
        }
        for idx in 64..4_095 {
            assert!(
                !pos_contains(&positions, idx),
                "new slot {idx} must be unset"
            );
        }
        assert!(pos_contains(&positions, 4_095));
    }
    // ==================================================================
    // MAX_SCROLLBAR_REFLOW_ITERATIONS — the anti-infinite-loop bound
    // ==================================================================
    #[test]
    fn the_scrollbar_reflow_bound_is_a_usable_positive_limit() {
        // `loop_count > MAX` is the only thing standing between a pathological
        // scrollbar oscillation and a hung frame. 0 would mean "never lay out".
        const _: () = assert!(
            MAX_SCROLLBAR_REFLOW_ITERATIONS >= 1 && MAX_SCROLLBAR_REFLOW_ITERATIONS <= 64,
            "the scrollbar reflow bound must be a usable positive limit; an absurd bound = a hung \
             frame"
        );
    }
    // ==================================================================
    // get_containing_block_for_node (numeric, private)
    // ==================================================================
    #[test]
    fn a_root_node_gets_the_viewport_as_its_containing_block() {
        let dom = body_dom();
        let tree = tree_of(vec![hot(
            None,
            Some(NodeId::ZERO),
            Some(size(10.0, 10.0)),
            &ResolvedBoxProps::default(),
        )]);
        let viewport = rect(7.0, 9.0, 800.0, 600.0);
        let (cb_pos, cb_size) =
            get_containing_block_for_node(&tree, &dom, 0, &Vec::new(), viewport);
        assert_eq!(cb_pos.x, 7.0);
        assert_eq!(cb_pos.y, 9.0);
        assert_eq!(cb_size.width, 800.0);
        assert_eq!(cb_size.height, 600.0);
    }
    #[test]
    fn an_out_of_range_node_index_falls_back_to_the_viewport() {
        let dom = body_dom();
        let tree = tree_of(vec![hot(
            None,
            None,
            Some(size(10.0, 10.0)),
            &ResolvedBoxProps::default(),
        )]);
        let viewport = rect(0.0, 0.0, 800.0, 600.0);
        for idx in [1usize, 99, usize::MAX] {
            let (cb_pos, cb_size) =
                get_containing_block_for_node(&tree, &dom, idx, &Vec::new(), viewport);
            assert_eq!(cb_pos.x, 0.0, "idx {idx}");
            assert_eq!(cb_size.width, 800.0, "idx {idx}");
            assert_eq!(cb_size.height, 600.0, "idx {idx}");
        }
    }
    #[test]
    fn a_dangling_parent_index_falls_back_to_the_viewport() {
        // Node 1 claims parent 999, which does not exist. The function must take
        // the viewport branch rather than index out of bounds.
        let dom = body_dom();
        let tree = tree_of(vec![
            hot(
                None,
                None,
                Some(size(10.0, 10.0)),
                &ResolvedBoxProps::default(),
            ),
            hot(
                Some(999),
                None,
                Some(size(10.0, 10.0)),
                &ResolvedBoxProps::default(),
            ),
        ]);
        let viewport = rect(1.0, 2.0, 300.0, 400.0);
        let (cb_pos, cb_size) =
            get_containing_block_for_node(&tree, &dom, 1, &Vec::new(), viewport);
        assert_eq!(cb_pos.x, 1.0);
        assert_eq!(cb_pos.y, 2.0);
        assert_eq!(cb_size.width, 300.0);
        assert_eq!(cb_size.height, 400.0);
    }
    #[test]
    fn a_dom_backed_parent_shrinks_the_containing_block_by_border_and_padding() {
        let dom = body_dom();
        let parent_props = bp(edges(10.0, 10.0, 10.0, 10.0), edges(5.0, 5.0, 5.0, 5.0));
        let tree = tree_of(vec![
            hot(
                None,
                Some(NodeId::ZERO),
                Some(size(200.0, 100.0)),
                &parent_props,
            ),
            hot(Some(0), None, None, &ResolvedBoxProps::default()),
        ]);
        let mut positions: PositionVec = Vec::new();
        pos_set(&mut positions, 0, pos(30.0, 40.0));
        let (cb_pos, cb_size) =
            get_containing_block_for_node(&tree, &dom, 1, &positions, rect(0.0, 0.0, 800.0, 600.0));
        // content origin = margin-box pos + border + padding
        assert!(close(cb_pos.x, 45.0), "x was {}", cb_pos.x);
        assert!(close(cb_pos.y, 55.0), "y was {}", cb_pos.y);
        // content size = border-box - (border + padding) on both sides
        assert!(close(cb_size.width, 170.0), "width was {}", cb_size.width);
        assert!(close(cb_size.height, 70.0), "height was {}", cb_size.height);
    }
    #[test]
    fn an_anonymous_parent_offsets_the_origin_but_keeps_the_border_box_size() {
        // The `dom_node_id == None` arm returns `used_size` verbatim — it shifts the
        // origin inward by border+padding but does NOT shrink the size, unlike the
        // DOM-backed arm above. Asserted as-is so any future fix trips this test.
        let dom = body_dom();
        let parent_props = bp(edges(10.0, 10.0, 10.0, 10.0), edges(5.0, 5.0, 5.0, 5.0));
        let tree = tree_of(vec![
            hot(None, None, Some(size(200.0, 100.0)), &parent_props),
            hot(Some(0), None, None, &ResolvedBoxProps::default()),
        ]);
        let mut positions: PositionVec = Vec::new();
        pos_set(&mut positions, 0, pos(0.0, 0.0));
        let (cb_pos, cb_size) =
            get_containing_block_for_node(&tree, &dom, 1, &positions, rect(0.0, 0.0, 800.0, 600.0));
        assert!(close(cb_pos.x, 15.0), "x was {}", cb_pos.x);
        assert!(close(cb_pos.y, 15.0), "y was {}", cb_pos.y);
        assert_eq!(
            cb_size.width, 200.0,
            "anonymous arm does not subtract padding/border"
        );
        assert_eq!(cb_size.height, 100.0);
    }
    #[test]
    fn an_unpositioned_parent_falls_back_to_the_viewport_origin() {
        let dom = body_dom();
        let parent_props = bp(edges(1.0, 0.0, 0.0, 2.0), edges(3.0, 0.0, 0.0, 4.0));
        let tree = tree_of(vec![
            hot(
                None,
                Some(NodeId::ZERO),
                Some(size(200.0, 100.0)),
                &parent_props,
            ),
            hot(Some(0), None, None, &ResolvedBoxProps::default()),
        ]);
        let viewport = rect(100.0, 200.0, 800.0, 600.0);
        // `calculated_positions` is empty: the parent has no computed position yet.
        let (cb_pos, _) = get_containing_block_for_node(&tree, &dom, 1, &Vec::new(), viewport);
        // viewport origin + border.left + padding.left, and the same on the y axis.
        assert!(close(cb_pos.x, 106.0), "x was {}", cb_pos.x);
        assert!(close(cb_pos.y, 204.0), "y was {}", cb_pos.y);
    }
    #[test]
    fn a_parent_with_a_sentinel_position_is_treated_as_unpositioned() {
        // pos_get filters the sentinel, so a parent whose stored x is f32::MIN
        // resolves against the viewport origin instead.
        let dom = body_dom();
        let tree = tree_of(vec![
            hot(
                None,
                Some(NodeId::ZERO),
                Some(size(200.0, 100.0)),
                &ResolvedBoxProps::default(),
            ),
            hot(Some(0), None, None, &ResolvedBoxProps::default()),
        ]);
        let mut positions: PositionVec = Vec::new();
        pos_set(&mut positions, 0, POSITION_UNSET);
        let (cb_pos, _) = get_containing_block_for_node(
            &tree,
            &dom,
            1,
            &positions,
            rect(11.0, 13.0, 800.0, 600.0),
        );
        assert_eq!(cb_pos.x, 11.0);
        assert_eq!(cb_pos.y, 13.0);
    }
    /// A parent with no `used_size` yet (a node the reconcile just rebuilt)
    /// lends its child the nearest SIZED ancestor's content box — the
    /// viewport when there is none. It used to lend 0x0, under which every
    /// shrink-to-fit box beneath it came out min-content.
    #[test]
    fn a_parent_without_a_used_size_borrows_the_nearest_sized_ancestors_content_box() {
        let dom = body_dom();
        // Root parent, unsized: the viewport.
        let tree = tree_of(vec![
            hot(None, Some(NodeId::ZERO), None, &ResolvedBoxProps::default()),
            hot(Some(0), None, None, &ResolvedBoxProps::default()),
        ]);
        let mut positions: PositionVec = Vec::new();
        pos_set(&mut positions, 0, pos(0.0, 0.0));
        let (_, cb_size) =
            get_containing_block_for_node(&tree, &dom, 1, &positions, rect(0.0, 0.0, 800.0, 600.0));
        assert_eq!((cb_size.width, cb_size.height), (800.0, 600.0));
        // Sized grandparent (300x200, 10px padding all round), unsized parent:
        // the grandparent's content box, 280x180.
        let grand = bp(edges(0.0, 0.0, 0.0, 0.0), edges(10.0, 10.0, 10.0, 10.0));
        let tree = tree_of(vec![
            hot(None, Some(NodeId::ZERO), Some(size(300.0, 200.0)), &grand),
            hot(Some(0), None, None, &ResolvedBoxProps::default()),
            hot(Some(1), None, None, &ResolvedBoxProps::default()),
        ]);
        let mut positions: PositionVec = Vec::new();
        pos_set(&mut positions, 0, pos(0.0, 0.0));
        pos_set(&mut positions, 1, pos(10.0, 10.0));
        let (_, cb_size) =
            get_containing_block_for_node(&tree, &dom, 2, &positions, rect(0.0, 0.0, 800.0, 600.0));
        assert_eq!((cb_size.width, cb_size.height), (280.0, 180.0));
    }
    #[test]
    fn huge_parent_padding_saturates_instead_of_wrapping_the_origin() {
        // PackedBoxProps stores edges as i16 tenths-of-a-pixel: 1e30px clamps to
        // +3276.7px. Wrapping would push the containing block's origin NEGATIVE.
        let dom = body_dom();
        let parent_props = bp(edges(1e30, 1e30, 1e30, 1e30), edges(1e30, 1e30, 1e30, 1e30));
        let tree = tree_of(vec![
            hot(
                None,
                Some(NodeId::ZERO),
                Some(size(200.0, 100.0)),
                &parent_props,
            ),
            hot(Some(0), None, None, &ResolvedBoxProps::default()),
        ]);
        let mut positions: PositionVec = Vec::new();
        pos_set(&mut positions, 0, pos(0.0, 0.0));
        let (cb_pos, cb_size) =
            get_containing_block_for_node(&tree, &dom, 1, &positions, rect(0.0, 0.0, 800.0, 600.0));
        assert!(cb_pos.x.is_finite() && cb_pos.y.is_finite());
        assert!(
            cb_pos.x > 0.0,
            "saturated padding must stay positive, got {}",
            cb_pos.x
        );
        assert!(
            cb_pos.x <= 2.0 * 3276.7 + 1.0,
            "clamped to the i16 ×10 range"
        );
        // border + padding dwarf the border-box, so the content box floors at zero.
        assert_eq!(cb_size.width, 0.0);
        assert_eq!(cb_size.height, 0.0);
    }
    #[test]
    fn a_nan_parent_position_propagates_but_does_not_panic_or_corrupt_the_size() {
        let dom = body_dom();
        let parent_props = bp(edges(10.0, 10.0, 10.0, 10.0), EdgeSizes::default());
        let tree = tree_of(vec![
            hot(
                None,
                Some(NodeId::ZERO),
                Some(size(200.0, 100.0)),
                &parent_props,
            ),
            hot(Some(0), None, None, &ResolvedBoxProps::default()),
        ]);
        let mut positions: PositionVec = Vec::new();
        pos_set(&mut positions, 0, pos(f32::NAN, f32::NAN));
        let (cb_pos, cb_size) =
            get_containing_block_for_node(&tree, &dom, 1, &positions, rect(0.0, 0.0, 800.0, 600.0));
        assert!(
            cb_pos.x.is_nan() && cb_pos.y.is_nan(),
            "NaN flows through unchanged"
        );
        // The size path never touches the position, so it must stay clean.
        assert!(close(cb_size.width, 180.0), "width was {}", cb_size.width);
        assert!(close(cb_size.height, 80.0), "height was {}", cb_size.height);
    }
    #[test]
    fn a_nan_parent_used_size_floors_the_containing_block_at_zero() {
        // inner_size() ends in `.max(0.0)`, which discards NaN — the containing
        // block collapses to 0 rather than exporting NaN into sizing.
        let dom = body_dom();
        let tree = tree_of(vec![
            hot(
                None,
                Some(NodeId::ZERO),
                Some(size(f32::NAN, f32::NAN)),
                &ResolvedBoxProps::default(),
            ),
            hot(Some(0), None, None, &ResolvedBoxProps::default()),
        ]);
        let mut positions: PositionVec = Vec::new();
        pos_set(&mut positions, 0, pos(0.0, 0.0));
        let (_, cb_size) =
            get_containing_block_for_node(&tree, &dom, 1, &positions, rect(0.0, 0.0, 800.0, 600.0));
        assert!(!cb_size.width.is_nan() && !cb_size.height.is_nan());
        assert_eq!(cb_size.width, 0.0);
        assert_eq!(cb_size.height, 0.0);
    }
    #[test]
    fn an_infinite_parent_used_size_stays_infinite_rather_than_becoming_nan() {
        let dom = body_dom();
        let parent_props = bp(edges(10.0, 10.0, 10.0, 10.0), edges(5.0, 5.0, 5.0, 5.0));
        let tree = tree_of(vec![
            hot(
                None,
                Some(NodeId::ZERO),
                Some(size(f32::INFINITY, f32::INFINITY)),
                &parent_props,
            ),
            hot(Some(0), None, None, &ResolvedBoxProps::default()),
        ]);
        let mut positions: PositionVec = Vec::new();
        pos_set(&mut positions, 0, pos(0.0, 0.0));
        let (_, cb_size) =
            get_containing_block_for_node(&tree, &dom, 1, &positions, rect(0.0, 0.0, 800.0, 600.0));
        assert!(cb_size.width.is_infinite() && cb_size.width.is_sign_positive());
        assert!(cb_size.height.is_infinite() && cb_size.height.is_sign_positive());
    }
    #[test]
    fn degenerate_viewports_pass_through_the_root_arm_untouched() {
        // The root arm is a pure identity on the viewport — it neither clamps
        // negatives nor sanitises NaN. Pin that so callers know to pre-validate.
        let dom = body_dom();
        let tree = tree_of(vec![hot(None, None, None, &ResolvedBoxProps::default())]);
        let (p, s) =
            get_containing_block_for_node(&tree, &dom, 0, &Vec::new(), rect(0.0, 0.0, 0.0, 0.0));
        assert_eq!(s.width, 0.0);
        assert_eq!(s.height, 0.0);
        assert_eq!(p.x, 0.0);
        let (_, s) = get_containing_block_for_node(
            &tree,
            &dom,
            0,
            &Vec::new(),
            rect(0.0, 0.0, -800.0, -600.0),
        );
        assert_eq!(s.width, -800.0, "negative viewport is not clamped");
        let (p, s) = get_containing_block_for_node(
            &tree,
            &dom,
            0,
            &Vec::new(),
            rect(f32::NAN, f32::NAN, f32::NAN, f32::NAN),
        );
        assert!(
            p.x.is_nan() && s.width.is_nan(),
            "NaN viewport is not sanitised"
        );
        let (_, s) = get_containing_block_for_node(
            &tree,
            &dom,
            0,
            &Vec::new(),
            rect(0.0, 0.0, f32::MAX, f32::MAX),
        );
        assert_eq!(s.width, f32::MAX);
    }
    // ==================================================================
    // LayoutError — Display (serializer)
    // ==================================================================
    #[cfg(all(feature = "text_layout", feature = "font_loading"))]
    #[test]
    fn every_layout_error_variant_renders_a_distinct_non_empty_message() {
        let variants = [
            LayoutError::InvalidTree,
            LayoutError::SizingFailed,
            LayoutError::PositioningFailed,
            LayoutError::DisplayListFailed,
            LayoutError::Text(crate::font_traits::LayoutError::BidiError(
                "boom".to_string(),
            )),
        ];
        let rendered: Vec<String> = variants.iter().map(ToString::to_string).collect();
        for msg in &rendered {
            assert!(!msg.is_empty(), "empty Display output");
            assert!(!msg.trim().is_empty(), "whitespace-only Display output");
        }
        for i in 0..rendered.len() {
            for j in (i + 1)..rendered.len() {
                assert_ne!(
                    rendered[i], rendered[j],
                    "variants {i} and {j} render alike"
                );
            }
        }
    }
    #[test]
    fn layout_error_display_matches_the_documented_wording() {
        assert_eq!(LayoutError::InvalidTree.to_string(), "Invalid layout tree");
        assert_eq!(
            LayoutError::SizingFailed.to_string(),
            "Sizing calculation failed"
        );
        assert_eq!(
            LayoutError::PositioningFailed.to_string(),
            "Position calculation failed"
        );
        assert_eq!(
            LayoutError::DisplayListFailed.to_string(),
            "Display list generation failed"
        );
    }
    #[test]
    fn layout_error_display_ignores_width_and_precision_specifiers() {
        // `write!(f, "...")` bypasses the formatter's padding/truncation, so a
        // caller aligning errors in a table gets no alignment at all.
        let e = LayoutError::InvalidTree;
        assert_eq!(format!("{e:>60}"), "Invalid layout tree");
        assert_eq!(format!("{e:.3}"), "Invalid layout tree");
        assert_eq!(format!("{e:^5}"), "Invalid layout tree");
    }
    #[cfg(all(feature = "text_layout", feature = "font_loading"))]
    #[test]
    fn the_text_variant_embeds_the_inner_error_and_survives_hostile_payloads() {
        let payloads = [
            String::new(),
            "\u{202e}rtl-override \u{0}nul".to_string(),
            "日本語のエラー 🎉".to_string(),
            "x".repeat(100_000),
            "\"quotes\" and \\backslashes\\".to_string(),
        ];
        for payload in payloads {
            let err = LayoutError::Text(crate::font_traits::LayoutError::ShapingError(
                payload.clone(),
            ));
            let msg = err.to_string();
            assert!(
                msg.starts_with("Text layout error: "),
                "unexpected prefix for {} byte payload",
                payload.len()
            );
            // The inner error is rendered with `{:?}`, so it is escaped, not raw —
            // but it must never be truncated away entirely.
            assert!(msg.len() >= "Text layout error: ".len() + payload.len());
        }
    }
    #[cfg(all(feature = "text_layout", feature = "font_loading"))]
    #[test]
    fn the_text_variant_renders_a_default_font_selector_without_panicking() {
        let err = LayoutError::Text(crate::font_traits::LayoutError::FontNotFound(
            crate::font_traits::FontSelector::default(),
        ));
        let msg = err.to_string();
        assert!(msg.starts_with("Text layout error: "));
        assert!(
            msg.contains("serif"),
            "the default family should show up: {msg}"
        );
    }
    #[cfg(all(feature = "text_layout", feature = "font_loading"))]
    #[test]
    fn from_text_layout_error_wraps_into_the_text_variant() {
        let inner = crate::font_traits::LayoutError::InvalidText("bad".to_string());
        let wrapped: LayoutError = inner.into();
        assert!(matches!(wrapped, LayoutError::Text(_)));
        assert!(wrapped.to_string().contains("bad"));
        // The `?` sugar used all over solver3 goes through the same From impl.
        fn propagates() -> Result<()> {
            let failed: std::result::Result<(), crate::font_traits::LayoutError> = Err(
                crate::font_traits::LayoutError::HyphenationError("nope".to_string()),
            );
            failed?;
            Ok(())
        }
        assert!(matches!(propagates(), Err(LayoutError::Text(_))));
    }
    #[test]
    fn layout_error_is_a_std_error_without_a_source() {
        use std::error::Error;
        let e = LayoutError::SizingFailed;
        assert!(e.source().is_none());
        // Debug must also be usable (it is what `Result::unwrap` prints).
        assert!(!format!("{e:?}").is_empty());
    }
    // ==================================================================
    // LayoutContext debug sinks + the lazy debug_* macros
    // ==================================================================
    #[cfg(all(feature = "text_layout", feature = "font_loading"))]
    mod debug_sinks {
        use std::collections::{BTreeMap, HashMap};
        use azul_core::{dom::DomId, selection::TextSelection, styled_dom::StyledDom};
        use azul_css::{props::basic::FontRef, LayoutDebugMessage, LayoutDebugMessageType};
        use super::{body_dom, size};
        use crate::{
            font_traits::FontManager,
            solver3::{cache, LayoutContext},
        };
        /// Owns everything a `LayoutContext` borrows, so a test can build one,
        /// poke it, drop it, and then inspect the captured messages.
        struct Env {
            styled_dom: StyledDom,
            font_manager: FontManager<FontRef>,
            text_selections: BTreeMap<DomId, TextSelection>,
            counters: HashMap<(usize, String), i32>,
            image_cache: azul_core::resources::ImageCache,
            debug_messages: Option<Vec<LayoutDebugMessage>>,
        }
        impl Env {
            fn new(debug_messages: Option<Vec<LayoutDebugMessage>>) -> Self {
                Self {
                    styled_dom: body_dom(),
                    font_manager: FontManager::new(rust_fontconfig::FcFontCache::default())
                        .expect("FontManager over an empty font cache"),
                    text_selections: BTreeMap::new(),
                    counters: HashMap::new(),
                    image_cache: azul_core::resources::ImageCache::default(),
                    debug_messages,
                }
            }
            fn ctx(&mut self) -> LayoutContext<'_, FontRef> {
                LayoutContext {
                    style_cache: Default::default(),
                    virtual_view_sizes: None,
                    scrollbar_style_cache: core::cell::RefCell::new(HashMap::new()),
                    styled_dom: &self.styled_dom,
                    font_manager: &self.font_manager,
                    text_selections: &self.text_selections,
                    debug_messages: &mut self.debug_messages,
                    counters: &mut self.counters,
                    viewport_size: size(800.0, 600.0),
                    fragmentation_context: None,
                    reflowed_ifcs: std::collections::BTreeSet::new(),
                    cursor_is_visible: true,
                    cursor_locations: Vec::new(),
                    owner_colors: Default::default(),
                    seat_focus_rings: Vec::new(),
                    paint_selection_handles: false,
                    preedit_text: None,
                    cache_map: cache::LayoutCacheMap::default(),
                    image_cache: &self.image_cache,
                    content_overlay: None,
                    system_style: None,
                    get_system_time_fn: azul_core::task::GetSystemTimeCallback {
                        cb: azul_core::task::get_system_time_libstd,
                    },
                }
            }
        }
        #[test]
        fn each_debug_sink_appends_exactly_one_message_of_its_own_type() {
            let mut env = Env::new(Some(Vec::new()));
            {
                let mut ctx = env.ctx();
                ctx.debug_log_inner("log".to_string());
                ctx.debug_info_inner("info".to_string());
                ctx.debug_warning_inner("warning".to_string());
                ctx.debug_error_inner("error".to_string());
                ctx.debug_box_props_inner("box_props".to_string());
                ctx.debug_css_getter_inner("css_getter".to_string());
                ctx.debug_bfc_layout_inner("bfc".to_string());
                ctx.debug_ifc_layout_inner("ifc".to_string());
                ctx.debug_table_layout_inner("table".to_string());
                ctx.debug_display_type_inner("display".to_string());
            }
            let msgs = env.debug_messages.expect("Some(vec) was passed in");
            let expected = [
                ("log", LayoutDebugMessageType::Info),
                ("info", LayoutDebugMessageType::Info),
                ("warning", LayoutDebugMessageType::Warning),
                ("error", LayoutDebugMessageType::Error),
                ("box_props", LayoutDebugMessageType::BoxProps),
                ("css_getter", LayoutDebugMessageType::CssGetter),
                ("bfc", LayoutDebugMessageType::BfcLayout),
                ("ifc", LayoutDebugMessageType::IfcLayout),
                ("table", LayoutDebugMessageType::TableLayout),
                ("display", LayoutDebugMessageType::DisplayType),
            ];
            assert_eq!(msgs.len(), expected.len(), "one message per call, in order");
            for (msg, (text, ty)) in msgs.iter().zip(expected) {
                assert_eq!(msg.message.as_str(), text);
                assert_eq!(msg.message_type, ty);
                assert!(
                    !msg.location.as_str().is_empty(),
                    "location must be recorded"
                );
            }
        }
        #[test]
        fn debug_log_inner_tags_the_message_with_the_solver3_location() {
            // `debug_log_inner` builds the message by hand (location = "solver3");
            // every other sink goes through LayoutDebugMessage::* (#[track_caller]
            // → a file:line inside this module).
            let mut env = Env::new(Some(Vec::new()));
            {
                let mut ctx = env.ctx();
                ctx.debug_log_inner("hello".to_string());
                ctx.debug_info_inner("hello".to_string());
            }
            let msgs = env.debug_messages.expect("Some(vec)");
            assert_eq!(msgs[0].location.as_str(), "solver3");
            assert!(
                msgs[1].location.as_str().contains(".rs:"),
                "track_caller location, got {:?}",
                msgs[1].location.as_str()
            );
        }
        #[test]
        fn the_debug_sinks_are_no_ops_when_debug_messages_is_none() {
            // The macros guard on `is_some()`, but the inner fns must be safe when
            // called directly (they are `pub`).
            let mut env = Env::new(None);
            {
                let mut ctx = env.ctx();
                ctx.debug_log_inner("log".to_string());
                ctx.debug_error_inner("error".to_string());
                ctx.debug_table_layout_inner("table".to_string());
            }
            assert!(env.debug_messages.is_none(), "must not materialise a Vec");
        }
        #[test]
        fn debug_messages_preserve_hostile_payloads_byte_for_byte() {
            let payloads = [
                String::new(),
                "\u{0}\u{7}\u{1b}[31m".to_string(),
                "日本語 🎉 \u{202e}reversed".to_string(),
                "line\nbreak\ttab\r\n".to_string(),
                "{}{{}} {:?} %s %n".to_string(), // format-string lookalikes
                "x".repeat(200_000),
            ];
            let mut env = Env::new(Some(Vec::new()));
            {
                let mut ctx = env.ctx();
                for p in &payloads {
                    ctx.debug_info_inner(p.clone());
                }
            }
            let msgs = env.debug_messages.expect("Some(vec)");
            assert_eq!(msgs.len(), payloads.len());
            for (msg, payload) in msgs.iter().zip(&payloads) {
                assert_eq!(msg.message.as_str(), payload.as_str());
            }
        }
        #[test]
        fn the_debug_macros_push_one_message_each_when_capturing() {
            let mut env = Env::new(Some(Vec::new()));
            {
                let mut ctx = env.ctx();
                debug_log!(ctx, "log {}", 1);
                debug_info!(ctx, "info {}", 2);
                debug_warning!(ctx, "warning {}", 3);
                debug_error!(ctx, "error {}", 4);
                debug_box_props!(ctx, "box_props {}", 5);
                debug_css_getter!(ctx, "css_getter {}", 6);
                debug_bfc_layout!(ctx, "bfc {}", 7);
                debug_ifc_layout!(ctx, "ifc {}", 8);
                debug_table_layout!(ctx, "table {}", 9);
                debug_display_type!(ctx, "display {}", 10);
            }
            let msgs = env.debug_messages.expect("Some(vec)");
            assert_eq!(msgs.len(), 10);
            assert_eq!(msgs[0].message.as_str(), "log 1");
            assert_eq!(msgs[9].message.as_str(), "display 10");
        }
        #[test]
        fn the_debug_macros_do_not_evaluate_their_arguments_when_not_capturing() {
            // This laziness is the whole point of the macros: a `format!` per node
            // per pass would dominate a release layout. A regression here is silent.
            let evaluations = core::cell::Cell::new(0u32);
            let bump = |c: &core::cell::Cell<u32>| {
                c.set(c.get() + 1);
                c.get()
            };
            let mut env = Env::new(None);
            {
                let mut ctx = env.ctx();
                debug_log!(ctx, "{}", bump(&evaluations));
                debug_info!(ctx, "{}", bump(&evaluations));
                debug_warning!(ctx, "{}", bump(&evaluations));
                debug_error!(ctx, "{}", bump(&evaluations));
                debug_box_props!(ctx, "{}", bump(&evaluations));
                debug_css_getter!(ctx, "{}", bump(&evaluations));
                debug_bfc_layout!(ctx, "{}", bump(&evaluations));
                debug_ifc_layout!(ctx, "{}", bump(&evaluations));
                debug_table_layout!(ctx, "{}", bump(&evaluations));
                debug_display_type!(ctx, "{}", bump(&evaluations));
            }
            assert_eq!(evaluations.get(), 0, "format args must stay unevaluated");
            // ...and they ARE evaluated (exactly once) when capturing.
            let mut env = Env::new(Some(Vec::new()));
            {
                let mut ctx = env.ctx();
                debug_log!(ctx, "{}", bump(&evaluations));
            }
            assert_eq!(evaluations.get(), 1);
            assert_eq!(env.debug_messages.as_ref().map(Vec::len), Some(1));
        }
    }
    // ==================================================================
    // set_skip_display_list — the web-backend opt-out flag
    // ==================================================================
    #[cfg(all(feature = "text_layout", feature = "font_loading"))]
    #[test]
    fn set_skip_display_list_round_trips_and_is_idempotent() {
        use core::sync::atomic::Ordering;
        let previous = SKIP_DISPLAY_LIST.load(Ordering::Relaxed);
        set_skip_display_list(true);
        assert!(SKIP_DISPLAY_LIST.load(Ordering::Relaxed));
        set_skip_display_list(true);
        assert!(
            SKIP_DISPLAY_LIST.load(Ordering::Relaxed),
            "double-set is idempotent"
        );
        set_skip_display_list(false);
        assert!(!SKIP_DISPLAY_LIST.load(Ordering::Relaxed));
        // Restore whatever the process was using — other tests share this static.
        set_skip_display_list(previous);
        assert_eq!(SKIP_DISPLAY_LIST.load(Ordering::Relaxed), previous);
    }
    // ==================================================================
    // layout_document — the entry point, driven with degenerate viewports
    // ==================================================================
    #[cfg(all(feature = "text_layout", feature = "font_loading"))]
    mod document {
        use std::collections::BTreeMap;
        use azul_core::{
            dom::{Dom, DomId},
            geom::{LogicalPosition, LogicalRect, LogicalSize},
            resources::RendererResources,
            styled_dom::StyledDom,
        };
        use azul_css::props::basic::FontRef;
        use crate::{
            font_traits::{FontManager, TextLayoutCache},
            solver3::{cache::LayoutCache, display_list::DisplayList, layout_document, Result},
        };
        fn rect(x: f32, y: f32, w: f32, h: f32) -> LogicalRect {
            LogicalRect {
                origin: LogicalPosition::new(x, y),
                size: LogicalSize::new(w, h),
            }
        }
        /// `body > div` — no text nodes, so an empty (font-less) `FontManager` is
        /// enough to exercise the whole reconcile → size → position → paint chain.
        fn simple_dom() -> StyledDom {
            let mut dom = Dom::create_body().with_child(Dom::create_div());
            let (css, _warnings) =
                azul_css::parser2::new_from_str("div { width: 50px; height: 20px; }");
            StyledDom::create(&mut dom, css)
        }
        fn run(
            cache: &mut LayoutCache,
            dom: &StyledDom,
            viewport: LogicalRect,
        ) -> Result<std::sync::Arc<DisplayList>> {
            let mut text_cache = TextLayoutCache::new();
            let font_manager: FontManager<FontRef> =
                FontManager::new(rust_fontconfig::FcFontCache::default())
                    .expect("FontManager over an empty font cache");
            let renderer_resources = RendererResources::default();
            let image_cache = azul_core::resources::ImageCache::default();
            let mut debug_messages = None;
            layout_document(
                cache,
                &mut text_cache,
                dom,
                viewport,
                &font_manager,
                &BTreeMap::new(),
                &BTreeMap::new(),
                &mut debug_messages,
                None,
                &renderer_resources,
                azul_core::resources::IdNamespace(0),
                DomId::ROOT_ID,
                false,
                Vec::new(),
                Default::default(), // owner_colors (U1)
                Vec::new(),         /* seat_focus_rings (9b-ii-a-i-d-iii): no ring off the live
                                     * path */
                false, // paint_selection_handles (U2-a)
                None,
                &image_cache,
                None,
                None,
                azul_core::task::GetSystemTimeCallback {
                    cb: azul_core::task::get_system_time_libstd,
                },
                &[],
                &BTreeMap::new(),
            )
        }
        /// [`run`] with a caller-supplied `GpuValueCache` — for the tests that
        /// pin how the DL cache reacts to the KEY POPULATION changing.
        fn run_with_gpu(
            cache: &mut LayoutCache,
            dom: &StyledDom,
            viewport: LogicalRect,
            gpu: &azul_core::gpu::GpuValueCache,
        ) -> Result<std::sync::Arc<DisplayList>> {
            let mut text_cache = TextLayoutCache::new();
            let font_manager: FontManager<FontRef> =
                FontManager::new(rust_fontconfig::FcFontCache::default())
                    .expect("FontManager over an empty font cache");
            let renderer_resources = RendererResources::default();
            let image_cache = azul_core::resources::ImageCache::default();
            let mut debug_messages = None;
            layout_document(
                cache,
                &mut text_cache,
                dom,
                viewport,
                &font_manager,
                &BTreeMap::new(),
                &BTreeMap::new(),
                &mut debug_messages,
                Some(gpu),
                &renderer_resources,
                azul_core::resources::IdNamespace(0),
                DomId::ROOT_ID,
                false,
                Vec::new(),
                Default::default(), // owner_colors (U1)
                Vec::new(),         /* seat_focus_rings (9b-ii-a-i-d-iii): no ring off the live
                                     * path */
                false, // paint_selection_handles (U2-a)
                None,
                &image_cache,
                None,
                None,
                azul_core::task::GetSystemTimeCallback {
                    cb: azul_core::task::get_system_time_libstd,
                },
                &[],
                &BTreeMap::new(),
            )
        }
        /// [`run`] with a caller-supplied CSS diff — the css_dirty channel.
        fn run_with_css(
            cache: &mut LayoutCache,
            dom: &StyledDom,
            viewport: LogicalRect,
            css_dirty: &[(
                azul_core::dom::NodeId,
                azul_css::props::property::RelayoutScope,
            )],
        ) -> Result<std::sync::Arc<DisplayList>> {
            let mut text_cache = TextLayoutCache::new();
            let font_manager: FontManager<FontRef> =
                FontManager::new(rust_fontconfig::FcFontCache::default())
                    .expect("FontManager over an empty font cache");
            let renderer_resources = RendererResources::default();
            let image_cache = azul_core::resources::ImageCache::default();
            let mut debug_messages = None;
            layout_document(
                cache,
                &mut text_cache,
                dom,
                viewport,
                &font_manager,
                &BTreeMap::new(),
                &BTreeMap::new(),
                &mut debug_messages,
                None,
                &renderer_resources,
                azul_core::resources::IdNamespace(0),
                DomId::ROOT_ID,
                false,
                Vec::new(),
                Default::default(), // owner_colors (U1)
                Vec::new(),         /* seat_focus_rings (9b-ii-a-i-d-iii): no ring off the live
                                     * path */
                false, // paint_selection_handles (U2-a)
                None,
                &image_cache,
                None,
                None,
                azul_core::task::GetSystemTimeCallback {
                    cb: azul_core::task::get_system_time_libstd,
                },
                css_dirty,
                &BTreeMap::new(),
            )
        }
        /// The AGGRESSIVE-CACHING CONTRACT of the CSS-diff channel, both
        /// directions:
        ///
        /// A PAINT-ONLY diff (`RelayoutScope::None` — colour, background)
        /// must bypass the structural-identity DL cache (fresh paint) while
        /// charging ZERO layout work — geometry byte-identical, no intrinsic
        /// recomputation. A SIZING diff must actually re-solve. And an EMPTY
        /// diff over the unchanged DOM must still hit the cache (the same
        /// Arc) — including right after a paint-only pass, which requires the
        /// early-exit path to have refreshed the cache with what it emitted,
        /// or the NEXT hit would serve the stale-paint list.
        #[test]
        fn css_diff_paint_repaints_without_layout_and_sizing_relayouts() {
            use azul_css::props::property::RelayoutScope;
            let dom = simple_dom();
            let mut cache = LayoutCache::default();
            let viewport = rect(0.0, 0.0, 800.0, 600.0);
            let Ok(first) = run(&mut cache, &dom, viewport) else {
                return; // font-less environment
            };
            let positions_before = cache.calculated_positions.clone();
            // Paint-only: fresh list (repainted), identical geometry, zero
            // sizing work.
            let div = azul_core::dom::NodeId::new(1);
            let second = run_with_css(&mut cache, &dom, viewport, &[(div, RelayoutScope::None)])
                .expect("paint-only pass");
            assert!(
                !std::sync::Arc::ptr_eq(&first, &second),
                "a paint-only diff must re-emit the display list (stale paint otherwise)"
            );
            assert_eq!(
                cache.last_intrinsic_dirty, 0,
                "a paint-only diff must charge ZERO sizing work"
            );
            assert_eq!(
                cache.calculated_positions, positions_before,
                "a paint-only diff must not move anything"
            );
            // Unchanged pass right after: must HIT (same Arc as the SECOND
            // list — the early-exit refreshed the cache with what it emitted).
            let third = run(&mut cache, &dom, viewport).expect("unchanged pass");
            assert!(
                std::sync::Arc::ptr_eq(&second, &third),
                "an unchanged pass after a paint-only repaint must hit the DL cache with the \
                 REPAINTED list, not re-emit or serve the stale one"
            );
            // Sizing: must actually re-solve.
            let fourth = run_with_css(
                &mut cache,
                &dom,
                viewport,
                &[(div, RelayoutScope::SizingOnly)],
            )
            .expect("sizing pass");
            assert!(
                !std::sync::Arc::ptr_eq(&third, &fourth),
                "a sizing diff must not serve the cached list"
            );
            assert!(
                cache.last_intrinsic_dirty >= 1,
                "a sizing diff must charge sizing work for the dirty node"
            );
        }
        /// The structural-identity DL cache must MISS when the GPU-KEY
        /// POPULATION changes, in BOTH directions.
        ///
        /// Diff-driven animation mints its transform keys AFTER the first
        /// layout of the new DOM (First/Last need solved rects), then the
        /// shell regenerates the display list. The very next relayout of the
        /// UNCHANGED DOM used to hit this cache on (root hash, viewport)
        /// alone and serve the PRE-KEY list back — no `PushReferenceFrame`,
        /// so no GPU damage, so a frozen animation and byte-identical
        /// screenshots from the first tick on. The reverse direction is the
        /// retirement leak: a settled animation retires its key, and a cache
        /// hit would keep a reference frame whose fallback matrix is the
        /// BAKED mid-flight transform.
        #[test]
        fn dl_cache_misses_when_the_gpu_key_population_changes() {
            use azul_core::{
                gpu::GpuValueCache, resources::TransformKey, transform::ComputedTransform3D,
            };
            let count_refframes = |dl: &DisplayList| {
                dl.items
                    .iter()
                    .filter(|i| {
                        matches!(
                            i,
                            crate::solver3::display_list::DisplayListItem::PushReferenceFrame { .. }
                        )
                    })
                    .count()
            };
            let dom = simple_dom();
            let mut cache = LayoutCache::default();
            let viewport = rect(0.0, 0.0, 800.0, 600.0);
            let empty_gpu = GpuValueCache::default();
            let Ok(first) = run_with_gpu(&mut cache, &dom, viewport, &empty_gpu) else {
                // Font-less environment — nothing to compare (same escape as
                // the sibling tests).
                return;
            };
            assert!(
                cache.cached_display_list.is_some(),
                "cold pass must seed the DL cache"
            );
            assert_eq!(count_refframes(&first), 0, "no keys, no reference frames");
            // A key is minted for a node — as animation seeding does, AFTER
            // this DOM has already been laid out and cached.
            let mut animated_gpu = GpuValueCache::default();
            let animated_node = azul_core::dom::NodeId::new(1); // the div
            animated_gpu
                .anim_transform_keys
                .insert(animated_node, TransformKey::unique());
            animated_gpu.anim_current_transform_values.insert(
                animated_node,
                ComputedTransform3D::new_translation(120.0, 0.0, 0.0),
            );
            let second = run_with_gpu(&mut cache, &dom, viewport, &animated_gpu)
                .expect("warm relayout with keys");
            assert_eq!(
                count_refframes(&second),
                1,
                "a freshly keyed node must get a reference frame — 0 means the cache served the \
                 pre-key display list back"
            );
            // Retirement: the key goes away, the frame must too. A stale hit
            // here would leave a reference frame falling back to its BAKED
            // (mid-flight) matrix — a node permanently offset by its last
            // sampled position.
            let third = run_with_gpu(&mut cache, &dom, viewport, &empty_gpu)
                .expect("warm relayout after retirement");
            assert_eq!(
                count_refframes(&third),
                0,
                "a retired key must not leave a stale reference frame"
            );
            // And the cache still WORKS when nothing changed: same population
            // twice in a row is a hit (same Arc, not merely equal contents).
            let fourth = run_with_gpu(&mut cache, &dom, viewport, &empty_gpu)
                .expect("warm relayout, unchanged population");
            assert!(
                std::sync::Arc::ptr_eq(&third, &fourth),
                "an unchanged population must still hit the cache"
            );
        }
        /// Regression: an EMPTY, unstyled div (the MicrophoneWidget pattern —
        /// zero height, auto width, only there to carry a dataset + AfterMount
        /// callback) must still receive a computed position. It used to stay at
        /// the `POSITION_UNSET` sentinel, and its Border/HitTestArea items were
        /// emitted at (f32::MIN, f32::MIN) and dropped by the display-list
        /// guard — harmless for paint, but the hit area silently vanished.
        #[test]
        fn an_empty_div_still_receives_a_position() {
            // Text siblings force anonymous-box wrapping around the inline
            // runs — the empty divs sit BETWEEN anonymous blocks, which is
            // the arrangement that used to skip them.
            let mut dom = Dom::create_body()
                .with_child(Dom::create_text_do_not_use_without_block_level_wrapper(
                    "azul-self-test",
                ))
                .with_child(Dom::create_text_do_not_use_without_block_level_wrapper(
                    "probing platform APIs",
                ))
                .with_child(Dom::create_div())
                .with_child(Dom::create_div());
            let (css, _warnings) = azul_css::parser2::new_from_str("body { font-size: 14px; }");
            let dom = StyledDom::create(&mut dom, css);
            let mut cache = LayoutCache::default();
            if run(&mut cache, &dom, rect(0.0, 0.0, 800.0, 600.0)).is_err() {
                return; // font-less environment quirk — nothing to assert
            }
            let tree = cache.tree.as_ref().expect("tree must be cached");
            for (idx, node) in tree.nodes.iter().enumerate() {
                if node.dom_node_id.is_none() {
                    continue;
                }
                assert!(
                    super::pos_get(&cache.calculated_positions, idx).is_some(),
                    "layout node {idx} (dom {:?}, {} children) never received a position",
                    node.dom_node_id,
                    tree.children(idx).len(),
                );
            }
        }
        #[test]
        fn a_zero_sized_viewport_lays_out_without_panicking() {
            let dom = simple_dom();
            let mut cache = LayoutCache::default();
            // Err is acceptable (a font-less environment may legitimately fail);
            // a panic, an infinite scrollbar reflow, or a NaN position is not.
            if run(&mut cache, &dom, rect(0.0, 0.0, 0.0, 0.0)).is_ok() {
                for p in &cache.calculated_positions {
                    assert!(
                        !p.x.is_nan() && !p.y.is_nan(),
                        "NaN position from a 0×0 viewport"
                    );
                }
            }
        }
        #[test]
        fn degenerate_viewports_never_panic_or_hang() {
            // MAX_SCROLLBAR_REFLOW_ITERATIONS is the only guard against a reflow
            // oscillation, so each of these must terminate through it or earlier.
            let viewports = [
                rect(0.0, 0.0, f32::NAN, f32::NAN),
                rect(f32::NAN, f32::NAN, 800.0, 600.0),
                rect(0.0, 0.0, -800.0, -600.0),
                rect(0.0, 0.0, f32::MAX, f32::MAX),
                rect(0.0, 0.0, f32::INFINITY, f32::INFINITY),
                rect(-1e30, -1e30, 1.0, 1.0),
                rect(0.0, 0.0, f32::MIN_POSITIVE, f32::MIN_POSITIVE),
            ];
            for viewport in viewports {
                let dom = simple_dom();
                let mut cache = LayoutCache::default();
                let _ = run(&mut cache, &dom, viewport);
            }
        }
        #[test]
        fn laying_out_the_same_dom_twice_is_stable_and_populates_the_cache() {
            let dom = simple_dom();
            let mut cache = LayoutCache::default();
            let viewport = rect(0.0, 0.0, 800.0, 600.0);
            let first = run(&mut cache, &dom, viewport);
            if first.is_err() {
                // No fonts available in this environment — nothing to compare.
                return;
            }
            assert!(
                cache.cached_display_list.is_some(),
                "cold pass must seed the DL cache"
            );
            assert_eq!(cache.viewport, Some(viewport));
            let positions_after_first = cache.calculated_positions.clone();
            // Second pass: the structural-identity cache should short-circuit, and
            // must not corrupt the stored geometry on the way out.
            let second = run(&mut cache, &dom, viewport);
            assert!(
                second.is_ok(),
                "a warm relayout of an unchanged DOM must succeed"
            );
            assert_eq!(
                cache.calculated_positions.len(),
                positions_after_first.len(),
                "warm pass changed the node count"
            );
            for (warm, cold) in cache
                .calculated_positions
                .iter()
                .zip(&positions_after_first)
            {
                assert_eq!(warm.x.to_bits(), cold.x.to_bits(), "warm pass moved a node");
                assert_eq!(warm.y.to_bits(), cold.y.to_bits(), "warm pass moved a node");
            }
        }
    }
}
/// Theme-chain analysis 2026-09-12, item 4: the display-list cache key
/// carries the cascade epoch.
#[cfg(test)]
mod cascade_epoch_in_the_dl_key {
    use super::*;
6
    fn fp(epoch: u64, ctx: Option<&azul_css::dynamic_selector::DynamicSelectorContext>) -> u64 {
6
        dl_input_fingerprint(false, &[], &BTreeMap::new(), None, false, &[], ctx, epoch)
6
    }
    #[test]
1
    fn two_epochs_of_one_dom_get_different_keys() {
1
        let ctx = azul_css::dynamic_selector::DynamicSelectorContext::default();
1
        assert_ne!(fp(1, Some(&ctx)), fp(2, Some(&ctx)));
1
        assert_eq!(fp(7, Some(&ctx)), fp(7, Some(&ctx)), "deterministic");
1
    }
    #[test]
1
    fn the_theme_still_keys_on_its_own() {
1
        let light = azul_css::dynamic_selector::DynamicSelectorContext::default();
1
        let dark = azul_css::dynamic_selector::DynamicSelectorContext {
1
            theme: azul_css::dynamic_selector::ThemeCondition::Dark,
1
            ..Default::default()
1
        };
1
        assert_ne!(fp(1, Some(&light)), fp(1, Some(&dark)));
1
    }
}