1
// +spec:box-model:b3a79e - box assigned same styles as generating element; getters read from styled
2
// DOM per node
3
//! Centralized CSS property getters for the layout solver pipeline
4

            
5
use azul_core::{
6
    dom::{NodeId, NodeType},
7
    geom::LogicalSize,
8
    id::NodeId as CoreNodeId,
9
    styled_dom::{StyledDom, StyledNodeState},
10
};
11
use azul_css::{
12
    css::CssPropertyValue,
13
    props::{
14
        basic::{
15
            font::{StyleFontFamily, StyleFontFamilyVec, StyleFontStyle, StyleFontWeight},
16
            pixel::{DEFAULT_FONT_SIZE, PT_TO_PX},
17
            time::CssDuration,
18
            ColorU, PhysicalSize, PixelValue, PropertyContext, ResolutionContext,
19
        },
20
        layout::{
21
            grid::GridTemplateAreas, BoxDecorationBreak, BreakInside, LayoutAlignContent,
22
            LayoutAlignItems, LayoutBoxSizing, LayoutClear, LayoutDisplay, LayoutFlexDirection,
23
            LayoutFlexWrap, LayoutFloat, LayoutHeight, LayoutJustifyContent, LayoutOverflow,
24
            LayoutPosition, LayoutWidth, LayoutWritingMode, Orphans, PageBreak,
25
            StyleOverflowClipMargin, StyleScrollbarGutter, Widows,
26
        },
27
        property::{
28
            CssProperty, CssPropertyType, LayoutAlignContentValue, LayoutAlignItemsValue,
29
            LayoutAlignSelfValue, LayoutFlexBasisValue, LayoutFlexDirectionValue,
30
            LayoutFlexGrowValue, LayoutFlexShrinkValue, LayoutFlexWrapValue, LayoutGapValue,
31
            LayoutGridAutoColumnsValue, LayoutGridAutoFlowValue, LayoutGridAutoRowsValue,
32
            LayoutGridColumnValue, LayoutGridRowValue, LayoutGridTemplateColumnsValue,
33
            LayoutGridTemplateRowsValue, LayoutJustifyContentValue, LayoutJustifyItemsValue,
34
            LayoutJustifySelfValue,
35
        },
36
        style::{
37
            border_radius::StyleBorderRadius,
38
            lists::{StyleListStylePosition, StyleListStyleType},
39
            StyleAlignmentBaseline, StyleBaselineSource, StyleDirection, StyleDominantBaseline,
40
            StyleInitialLetterAlign, StyleInitialLetterWrap, StyleLineFitEdge, StyleTextAlign,
41
            StyleTextBoxEdge, StyleTextBoxTrim, StyleUnicodeBidi, StyleUserSelect,
42
            StyleVerticalAlign, StyleVisibility, StyleWhiteSpace,
43
        },
44
    },
45
};
46

            
47
use crate::{
48
    font_traits::{ParsedFontTrait, StyleProperties},
49
    solver3::{
50
        display_list::{BorderRadius, PhysicalSizeImport},
51
        layout_tree::LayoutNode,
52
        scrollbar::ScrollbarRequirements,
53
    },
54
};
55

            
56
const DEFAULT_EM_SIZE: f32 = 16.0;
57
// The web model: the caret is a HAIRLINE — 1 CSS px in every browser (there
58
// is no standard property for its width; azul's `caret-width` can still
59
// thicken it). 2px read as a block next to 1px glyph stems.
60
const DEFAULT_CARET_WIDTH_PX: f32 = 1.0;
61
// ONE authority for the default blink period: the manager's constant.
62
// This and CURSOR_BLINK_INTERVAL_MS disagreeing (500 vs 530) is what made
63
// the "which default wins" question unanswerable — do not fork it again.
64
#[allow(clippy::cast_possible_truncation)]
65
const DEFAULT_CARET_BLINK_MS: u32 = crate::managers::text_edit::CURSOR_BLINK_INTERVAL_MS as u32;
66
const DEFAULT_TAB_SIZE: f32 = 8.0;
67
const SCROLLBAR_WIDTH_THIN: f32 = 8.0;
68
const SCROLLBAR_WIDTH_AUTO: f32 = 12.0;
69
const SCROLLBAR_HOVER_EXPAND_PX: f32 = 4.0;
70
const THUMB_HOVER_LIGHTEN: u8 = 30;
71
const THUMB_HOVER_ALPHA_ADD: u8 = 40;
72
const THUMB_ACTIVE_DARKEN: u8 = 15;
73

            
74
// Font-size resolution helper functions
75

            
76
/// Helper function to get element's computed font-size.
77
///
78
/// **Memoised** for the common `Normal` pseudo-state: the first
79
/// call on a given `StyledDom` populates
80
/// `css_property_cache.ptr.resolved_font_sizes_px` via a single
81
/// bottom-up DOM walk (N cascade walks total, stored as
82
/// `Vec<f32>`); every subsequent call is a single Vec index.
83
/// Non-normal state falls through to [`resolve_font_size_slow`].
84
///
85
/// Motivation: `AZ_PROP_COUNT=1` measured 329 629 `font-size`
86
/// cascade walks per cold layout on excel.html (~730 per node).
87
/// With this cache that collapses to ~500 total (one per node,
88
/// once), and subsequent layouts hit the Vec directly.
89
///
90
/// The semantics of the slow path are preserved exactly: the
91
/// `compute_all_font_sizes_px` walker mirrors the original's
92
/// `computed_values` → cascade → `DEFAULT_FONT_SIZE` ordering,
93
/// so rendered pixels are byte-identical.
94
#[must_use]
95
3662774
pub fn get_element_font_size(
96
3662774
    styled_dom: &StyledDom,
97
3662774
    dom_id: NodeId,
98
3662774
    node_state: &StyledNodeState,
99
3662774
) -> f32 {
100
    // M12.7 FIX: the OnceLock-cached fast path
101
    // (`is_normal → resolved_font_sizes_px.get_or_init(|| compute_all_font_sizes_px) →
102
    // sizes.get`) MIS-LIFTS to wasm — it diverges (create_node_from_dom never returns →
103
    // empty LayoutTree → 0 rects). PROVEN by isolation: skipping it lets
104
    // get_element_font_size reach + return via resolve_font_size_slow, and
105
    // create_resolution_context completes (sub-step 1→4). resolve_font_size_slow is the
106
    // same resolution unmemoized (correct), so we always use it. (Native desktop is
107
    // unaffected in correctness; it loses the per-DOM memoization — a minor perf cost
108
    // only on the lifted web path's small DOMs. The cache-block lift bug — likely the
109
    // compute_all_font_sizes_px closure's control/FP — is documented for a later remill
110
    // fix that can restore the fast path.)
111
3662774
    let _ = compute_all_font_sizes_px; // referenced so other callers / native keep it
112
3662774
    resolve_font_size_slow(styled_dom, dom_id, node_state)
113
3662774
}
114

            
115
/// Bottom-up single-pass resolve of every node's font-size.
116
/// Parents are computed before children (DFS pre-order invariant
117
/// on `NodeId::index()`), so `em` inherits via the parent's
118
/// already-stored pixel value. `rem` reads from `sizes[0]` once
119
/// the root is populated (the root's own size resolves via the
120
/// `computed_values` short-circuit if set, otherwise DEFAULT).
121
///
122
/// Preserves the original resolution order exactly:
123
///
124
/// 1. `computed_values` binary search → if `FontSize` is pre- resolved to a px value, use that.
125
/// 2. Full cascade via `cache.get_font_size(...)`; if an explicit value is present, resolve with
126
///    context.
127
/// 3. `DEFAULT_FONT_SIZE` fallback — NOT `parent_font_size`, because the `computed_values`
128
///    short-circuit at step 1 is the cascade's inheritance channel (pre-populated for every
129
///    inheriting node).
130
fn compute_all_font_sizes_px(styled_dom: &StyledDom) -> Vec<f32> {
131
    use azul_css::props::{
132
        basic::length::SizeMetric,
133
        property::{CssProperty, CssPropertyType},
134
    };
135

            
136
    let n = styled_dom.node_data.len();
137
    let mut sizes = alloc::vec![DEFAULT_FONT_SIZE; n];
138
    if n == 0 {
139
        return sizes;
140
    }
141

            
142
    let data_container = styled_dom.node_data.as_container();
143
    let state_container = styled_dom.styled_nodes.as_container();
144
    let hierarchy = styled_dom.node_hierarchy.as_container();
145
    let cache = &styled_dom.css_property_cache.ptr;
146

            
147
    for idx in 0..n {
148
        let dom_id = NodeId::new(idx);
149

            
150
        // Step 1: computed_values short-circuit (matches original).
151
        // Keyed lookup straight into the transposed store — no per-node vec to
152
        // materialise, and the bucket scan is over a handful of entries.
153
        if let Some(cv) = cache.computed_values.get(idx, CssPropertyType::FontSize) {
154
            {
155
                if let CssProperty::FontSize(css_val) = &cv.property {
156
                    if let Some(fs) = css_val.get_property() {
157
                        if fs.inner.metric == SizeMetric::Px {
158
                            sizes[idx] = fs.inner.number.get();
159
                            continue;
160
                        }
161
                    }
162
                }
163
            }
164
        }
165

            
166
        // Step 2: full cascade walk.
167
        let parent_font_size = hierarchy
168
            .get(dom_id)
169
            .and_then(azul_core::styled_dom::NodeHierarchyItem::parent_id)
170
            .map_or(DEFAULT_FONT_SIZE, |p| sizes[p.index()]);
171
        let root_font_size = sizes[0];
172

            
173
        let Some(node_data) = data_container.internal.get(idx) else {
174
            sizes[idx] = DEFAULT_FONT_SIZE;
175
            continue;
176
        };
177
        let Some(styled) = state_container.internal.get(idx) else {
178
            sizes[idx] = DEFAULT_FONT_SIZE;
179
            continue;
180
        };
181
        let node_state = &styled.styled_node_state;
182

            
183
        // Step 2.5: compact cache fast path — avoids a full cascade walk
184
        // per node. The build-time pass has already resolved em/% to px,
185
        // so the raw u32 here is the final pixel value when set.
186
        let mut fast_fs: Option<f32> = None;
187
        let mut compact_said_inherit = false;
188
        if node_state.is_normal() {
189
            if let Some(ref cc) = cache.compact_cache {
190
                let raw = cc.get_font_size_raw(idx);
191
                if raw == azul_css::compact_cache::U32_SENTINEL
192
                    || raw == azul_css::compact_cache::U32_INHERIT
193
                    || raw == azul_css::compact_cache::U32_INITIAL
194
                {
195
                    compact_said_inherit = true;
196
                } else if let Some(pv) = azul_css::compact_cache::decode_pixel_value_u32(raw) {
197
                    // Already-resolved pixel value (em/% eliminated during build).
198
                    if pv.metric == SizeMetric::Px {
199
                        fast_fs = Some(pv.number.get());
200
                    } else {
201
                        // Shouldn't normally happen post-resolve, but fall through safely.
202
                        let context = ResolutionContext {
203
                            vertical_writing_mode: false,
204
                            element_font_size: DEFAULT_FONT_SIZE,
205
                            parent_font_size,
206
                            root_font_size,
207
                            containing_block_size: PhysicalSize::new(0.0, 0.0),
208
                            element_size: None,
209
                            viewport_size: PhysicalSize::new(0.0, 0.0),
210
                        };
211
                        fast_fs =
212
                            Some(pv.resolve_with_context(&context, PropertyContext::FontSize));
213
                    }
214
                }
215
            }
216
        }
217
        if let Some(fs) = fast_fs {
218
            sizes[idx] = fs;
219
            continue;
220
        }
221
        if compact_said_inherit {
222
            sizes[idx] = parent_font_size;
223
            continue;
224
        }
225

            
226
        let resolved = cache
227
            .get_font_size(node_data, &dom_id, node_state)
228
            .and_then(|v| v.get_property().copied())
229
            .map(|v| {
230
                let context = ResolutionContext {
231
                    vertical_writing_mode: false,
232
                    element_font_size: DEFAULT_FONT_SIZE,
233
                    parent_font_size,
234
                    root_font_size,
235
                    containing_block_size: PhysicalSize::new(0.0, 0.0),
236
                    element_size: None,
237
                    viewport_size: PhysicalSize::new(0.0, 0.0),
238
                };
239
                v.inner
240
                    .resolve_with_context(&context, PropertyContext::FontSize)
241
            });
242

            
243
        // Step 3: fallback to DEFAULT (matches original .unwrap_or).
244
        sizes[idx] = resolved.unwrap_or(DEFAULT_FONT_SIZE);
245
    }
246
    sizes
247
}
248

            
249
/// Un-memoised recursive resolution, used as the fallback for
250
/// non-normal pseudo-states in [`get_element_font_size`] and
251
/// directly by tests that bypass the StyledDom-scoped cache.
252
/// Keeps the original semantics verbatim.
253
3662790
fn resolve_font_size_slow(
254
3662790
    styled_dom: &StyledDom,
255
3662790
    dom_id: NodeId,
256
3662790
    node_state: &StyledNodeState,
257
3662790
) -> f32 {
258
    // ITERATIVE resolution (was unbounded self-recursion up the parent chain, which
259
    // stack-overflowed on deeply nested DOMs and was O(N*depth)). We walk `parent_id`
260
    // in a loop to collect the ancestor chain, then resolve top-down so each node's
261
    // `em` inherits from its already-resolved parent. Result is identical to the old
262
    // recursive version for a well-formed tree, but bounded by the tree depth in
263
    // stack usage (a single Vec of ancestors instead of nested frames).
264
    //
265
    // Each ancestor is resolved against its OWN `styled_node_state` (previously the
266
    // recursion incorrectly threaded the *child's* state into parent/root resolution),
267
    // matching the sibling `get_parent_font_size` / `get_root_font_size` helpers.
268
3662790
    let hierarchy = styled_dom.node_hierarchy.as_container();
269
3662790
    let states = styled_dom.styled_nodes.as_container();
270
3662790
    let root_id = NodeId::new(0);
271

            
272
    // Root font-size, resolved from NodeId(0) with no parent and root == DEFAULT
273
    // (mirrors the original: for node 0 the root branch returned DEFAULT directly).
274
3662790
    let root_font_size = if dom_id == root_id {
275
1280038
        DEFAULT_FONT_SIZE
276
    } else {
277
2382752
        let root_state = &states[root_id].styled_node_state;
278
2382752
        resolve_font_size_one(
279
2382752
            styled_dom,
280
2382752
            root_id,
281
2382752
            root_state,
282
            DEFAULT_FONT_SIZE,
283
            DEFAULT_FONT_SIZE,
284
        )
285
    };
286

            
287
    // Collect the ancestor chain: chain[0] == dom_id, chain.last() == topmost ancestor.
288
3662790
    let mut chain = Vec::new();
289
3662790
    let mut cur = Some(dom_id);
290
19258642
    while let Some(id) = cur {
291
15595852
        chain.push(id);
292
15595852
        cur = hierarchy
293
15595852
            .get(id)
294
15595852
            .and_then(azul_core::styled_dom::NodeHierarchyItem::parent_id);
295
15595852
    }
296

            
297
    // Resolve top-down. The topmost ancestor has parent_font_size == DEFAULT; each
298
    // subsequent node inherits the previously-resolved value as its parent size.
299
3662790
    let mut parent_font_size = DEFAULT_FONT_SIZE;
300
3662790
    let mut resolved = DEFAULT_FONT_SIZE;
301
15595852
    for &id in chain.iter().rev() {
302
        // The target node keeps the caller-provided state (its own state, per the
303
        // public contract); ancestors use their own stored state.
304
15595852
        let this_state = if id == dom_id {
305
3662790
            node_state
306
        } else {
307
11933062
            &states[id].styled_node_state
308
        };
309
15595852
        let this_root_fs = if id == root_id {
310
3662790
            DEFAULT_FONT_SIZE
311
        } else {
312
11933062
            root_font_size
313
        };
314
15595852
        resolved =
315
15595852
            resolve_font_size_one(styled_dom, id, this_state, parent_font_size, this_root_fs);
316
15595852
        parent_font_size = resolved;
317
    }
318
3662790
    resolved
319
3662790
}
320

            
321
/// Resolves a single node's font-size given its already-resolved `parent_font_size`
322
/// and `root_font_size`. Contains the per-node logic that the old recursive
323
/// `resolve_font_size_slow` applied at each frame (computed-values px short-circuit,
324
/// then a full cascade walk), with no recursion of its own.
325
17978609
fn resolve_font_size_one(
326
17978609
    styled_dom: &StyledDom,
327
17978609
    dom_id: NodeId,
328
17978609
    node_state: &StyledNodeState,
329
17978609
    parent_font_size: f32,
330
17978609
    root_font_size: f32,
331
17978609
) -> f32 {
332
17978609
    let node_data = &styled_dom.node_data.as_container()[dom_id];
333
17978609
    let cache = &styled_dom.css_property_cache.ptr;
334

            
335
17978609
    if let Some(cv) = cache
336
17978609
        .computed_values
337
17978609
        .get(dom_id.index(), CssPropertyType::FontSize)
338
    {
339
11581028
        if let CssProperty::FontSize(css_val) = &cv.property {
340
11581028
            if let Some(fs) = css_val.get_property() {
341
11581028
                if fs.inner.metric == azul_css::props::basic::length::SizeMetric::Px {
342
11581028
                    return fs.inner.number.get();
343
                }
344
            }
345
        }
346
6397581
    }
347

            
348
6397581
    cache
349
6397581
        .get_font_size(node_data, &dom_id, node_state)
350
6397581
        .and_then(|v| v.get_property().copied())
351
6397581
        .map_or(DEFAULT_FONT_SIZE, |v| {
352
            let context = ResolutionContext {
353
                vertical_writing_mode: false,
354
                element_font_size: DEFAULT_FONT_SIZE,
355
                parent_font_size,
356
                root_font_size,
357
                containing_block_size: PhysicalSize::new(0.0, 0.0),
358
                element_size: None,
359
                viewport_size: PhysicalSize::new(0.0, 0.0),
360
            };
361
            v.inner
362
                .resolve_with_context(&context, PropertyContext::FontSize)
363
        })
364
17978609
}
365

            
366
/// Helper function to get parent's computed font-size.
367
///
368
/// Retrieves the parent's own `StyledNodeState` so that pseudo-class-specific
369
/// font-size rules (e.g. `div:hover { font-size: 32px }`) are resolved
370
/// against the parent's actual state, not the child's.
371
#[must_use]
372
431341
pub fn get_parent_font_size(
373
431341
    styled_dom: &StyledDom,
374
431341
    dom_id: NodeId,
375
431341
    _node_state: &StyledNodeState, // child's state — intentionally unused
376
431341
) -> f32 {
377
431341
    styled_dom
378
431341
        .node_hierarchy
379
431341
        .as_container()
380
431341
        .get(dom_id)
381
431341
        .and_then(azul_core::styled_dom::NodeHierarchyItem::parent_id)
382
431341
        .map_or(DEFAULT_FONT_SIZE, |parent_id| {
383
429964
            let parent_state = &styled_dom.styled_nodes.as_container()[parent_id].styled_node_state;
384
429964
            get_element_font_size(styled_dom, parent_id, parent_state)
385
429964
        })
386
431341
}
387

            
388
/// Helper function to get root element's font-size.
389
///
390
/// Uses the root element's own `StyledNodeState` so that pseudo-class-specific
391
/// rules are resolved correctly regardless of which node triggered the call.
392
#[must_use]
393
797172
pub fn get_root_font_size(styled_dom: &StyledDom, _node_state: &StyledNodeState) -> f32 {
394
797172
    let root_id = NodeId::new(0);
395
797172
    let root_state = &styled_dom.styled_nodes.as_container()[root_id].styled_node_state;
396
797172
    get_element_font_size(styled_dom, root_id, root_state)
397
797172
}
398

            
399
/// A value that can be Auto, Initial, Inherit, or an explicit value.
400
/// This preserves CSS cascade semantics better than Option<T>.
401
#[derive(Debug, Copy, Clone, PartialEq, Eq, Default)]
402
pub enum MultiValue<T> {
403
    /// CSS 'auto' keyword
404
    #[default]
405
    Auto,
406
    /// CSS 'initial' keyword - use initial value
407
    Initial,
408
    /// CSS 'inherit' keyword - inherit from parent
409
    Inherit,
410
    /// Explicit value (e.g., "10px", "50%")
411
    Exact(T),
412
}
413

            
414
impl<T> MultiValue<T> {
415
    /// Returns true if this is an Auto value
416
121345
    pub const fn is_auto(&self) -> bool {
417
121345
        matches!(self, Self::Auto)
418
121345
    }
419

            
420
    /// Returns true if this is an explicit value
421
6
    pub const fn is_exact(&self) -> bool {
422
6
        matches!(self, Self::Exact(_))
423
6
    }
424

            
425
    /// Gets the exact value if present
426
2011374
    pub fn exact(self) -> Option<T> {
427
2011374
        match self {
428
1342616
            Self::Exact(v) => Some(v),
429
668758
            _ => None,
430
        }
431
2011374
    }
432

            
433
    /// Gets the exact value or returns the provided default
434
4762263
    pub fn unwrap_or(self, default: T) -> T {
435
4762263
        match self {
436
4762191
            Self::Exact(v) => v,
437
72
            _ => default,
438
        }
439
4762263
    }
440

            
441
    /// Gets the exact value or returns `T::default()`
442
8227305
    pub fn unwrap_or_default(self) -> T
443
8227305
    where
444
8227305
        T: Default,
445
    {
446
8227305
        match self {
447
7636062
            Self::Exact(v) => v,
448
591243
            _ => T::default(),
449
        }
450
8227305
    }
451

            
452
    /// Maps the inner value if Exact, otherwise returns self unchanged
453
9
    pub fn map<U, F>(self, f: F) -> MultiValue<U>
454
9
    where
455
9
        F: FnOnce(T) -> U,
456
    {
457
9
        match self {
458
3
            Self::Exact(v) => MultiValue::Exact(f(v)),
459
2
            Self::Auto => MultiValue::Auto,
460
2
            Self::Initial => MultiValue::Initial,
461
2
            Self::Inherit => MultiValue::Inherit,
462
        }
463
9
    }
464
}
465

            
466
// Implement helper methods for LayoutOverflow specifically
467
impl MultiValue<LayoutOverflow> {
468
    /// Returns true if this overflow value causes content to be clipped.
469
    /// This includes Hidden, Clip, Auto, and Scroll (all values except Visible).
470
    #[must_use]
471
1655048
    pub const fn is_clipped(&self) -> bool {
472
1600763
        matches!(
473
1653097
            self,
474
54285
            Self::Exact(
475
54285
                LayoutOverflow::Hidden
476
54285
                    | LayoutOverflow::Clip
477
54285
                    | LayoutOverflow::Auto
478
54285
                    | LayoutOverflow::Scroll
479
54285
            )
480
        )
481
1655048
    }
482

            
483
    #[must_use]
484
848762
    pub const fn is_scroll(&self) -> bool {
485
836604
        matches!(
486
848582
            self,
487
12158
            Self::Exact(LayoutOverflow::Scroll | LayoutOverflow::Auto)
488
        )
489
848762
    }
490

            
491
    // +spec:overflow:3be57c - overflow:hidden disables user scrolling but programmatic scrolling
492
    // still works
493
    /// Does this value establish a SCROLL CONTAINER (css-overflow-3 §3.1)?
494
    /// `hidden | scroll | auto` — an `overflow: hidden` box is
495
    /// programmatically scrollable even though its user scrolling is
496
    /// disabled. The unset sentinel (initial = visible) does not.
497
    #[must_use]
498
540409
    pub const fn is_scroll_container(&self) -> bool {
499
534442
        matches!(
500
540320
            self,
501
5967
            Self::Exact(LayoutOverflow::Hidden | LayoutOverflow::Scroll | LayoutOverflow::Auto)
502
        )
503
540409
    }
504

            
505
    /// Does this value allow scrolling DIRECTLY TRIGGERED BY THE USER
506
    /// (wheel, scrollbar, keyboard)? `hidden` does not.
507
    #[must_use]
508
337878
    pub const fn allows_user_scrolling(&self) -> bool {
509
334971
        matches!(
510
337831
            self,
511
2907
            Self::Exact(LayoutOverflow::Scroll | LayoutOverflow::Auto)
512
        )
513
337878
    }
514

            
515
    #[must_use]
516
12985
    pub const fn is_auto_overflow(&self) -> bool {
517
12984
        matches!(self, Self::Exact(LayoutOverflow::Auto))
518
12985
    }
519

            
520
    #[must_use]
521
8
    pub const fn is_hidden(&self) -> bool {
522
7
        matches!(self, Self::Exact(LayoutOverflow::Hidden))
523
8
    }
524

            
525
    #[must_use]
526
9
    pub const fn is_hidden_or_clip(&self) -> bool {
527
6
        matches!(
528
6
            self,
529
3
            Self::Exact(LayoutOverflow::Hidden | LayoutOverflow::Clip)
530
        )
531
9
    }
532

            
533
    #[must_use]
534
13
    pub const fn is_scroll_explicit(&self) -> bool {
535
11
        matches!(self, Self::Exact(LayoutOverflow::Scroll))
536
13
    }
537

            
538
    #[must_use]
539
16621
    pub const fn is_clip(&self) -> bool {
540
16619
        matches!(self, Self::Exact(LayoutOverflow::Clip))
541
16621
    }
542

            
543
    #[must_use]
544
8
    pub const fn is_visible_or_clip(&self) -> bool {
545
6
        matches!(
546
5
            self,
547
2
            Self::Exact(LayoutOverflow::Visible | LayoutOverflow::Clip)
548
        )
549
8
    }
550

            
551
    /// True iff `overflow` is EXPLICITLY set to a value that establishes a block
552
    /// formatting context (CSS 2.2 §9.4.1: `hidden`/`scroll`/`auto`). `visible`,
553
    /// `clip`, and the unset/initial/inherit sentinel do NOT — the initial value
554
    /// is `visible`, so an unset overflow must not establish a BFC. Using
555
    /// `!is_visible_or_clip()` for this was wrong: the "not set" `MultiValue::Auto`
556
    /// sentinel is not visible/clip, so every plain block spuriously got a BFC on
557
    /// the slow cascade path (the fast path returns `Exact(Visible)` and did not).
558
    #[must_use]
559
38881
    pub const fn establishes_bfc(&self) -> bool {
560
36810
        matches!(
561
38870
            self,
562
2071
            Self::Exact(LayoutOverflow::Hidden | LayoutOverflow::Scroll | LayoutOverflow::Auto)
563
        )
564
38881
    }
565

            
566
    // +spec:overflow:833078 - visible/clip compute to auto/hidden if other axis is scrollable
567
    /// Resolves the computed value per CSS Overflow 3 § 3.1:
568
    /// visible/clip values compute to auto/hidden (respectively)
569
    /// if the other axis is neither visible nor clip.
570
    ///
571
    /// The UNSET sentinel means the initial value `visible`, and the rule
572
    /// applies to it the same way: an unset axis computes to `auto` when the
573
    /// other axis is scrollable. The old catch-all left it unresolved, so on
574
    /// the slow path (pseudo-states / no compact cache) callers treated the
575
    /// axis as visible instead of a scroll container - the compact fast path
576
    /// (which always materializes `Exact`) disagreed.
577
    #[must_use]
578
1929975
    pub const fn resolve_computed(&self, other_axis: &Self) -> Self {
579
1929975
        let this = match self {
580
1929727
            Self::Exact(v) => *v,
581
248
            _ => LayoutOverflow::Visible,
582
        };
583
1929975
        let other = match other_axis {
584
1929727
            Self::Exact(v) => *v,
585
248
            _ => LayoutOverflow::Visible,
586
        };
587
1929975
        let resolved = this.resolve_computed(other);
588
        // Keep the sentinel when nothing changed (an unset axis stays unset
589
        // unless the rule upgrades it), so downstream unset-vs-explicit
590
        // distinctions (BFC establishment) are preserved.
591
248
        match self {
592
1929727
            Self::Exact(_) => Self::Exact(resolved),
593
248
            _ if !matches!(resolved, LayoutOverflow::Visible) => Self::Exact(resolved),
594
235
            _ => *self,
595
        }
596
1929975
    }
597
}
598

            
599
// Implement helper methods for LayoutPosition
600
impl MultiValue<LayoutPosition> {
601
    #[must_use]
602
18349
    pub const fn is_absolute_or_fixed(&self) -> bool {
603
17114
        matches!(
604
18342
            self,
605
1235
            Self::Exact(LayoutPosition::Absolute | LayoutPosition::Fixed)
606
        )
607
18349
    }
608
}
609

            
610
// Implement helper methods for LayoutFloat
611
impl MultiValue<LayoutFloat> {
612
    #[must_use]
613
17115
    pub const fn is_none(&self) -> bool {
614
254
        matches!(
615
17107
            self,
616
16853
            Self::Auto | Self::Initial | Self::Inherit | Self::Exact(LayoutFloat::None)
617
        )
618
17115
    }
619
}
620

            
621
/// Helper macro to reduce boilerplate for simple CSS property getters
622
/// Returns the inner `PixelValue` wrapped in `MultiValue`
623
macro_rules! get_css_property_pixel {
624
    // Variant WITH compact cache fast path for i16-encoded resolved px properties
625
    (
626
        $fn_name:ident, $cache_method:ident, $ua_property:expr,compact_i16 = $compact_method:ident
627
    ) => {
628
        #[must_use]
629
5195276
        pub fn $fn_name(
630
5195276
            styled_dom: &StyledDom,
631
5195276
            node_id: NodeId,
632
5195276
            node_state: &StyledNodeState,
633
5195276
        ) -> MultiValue<PixelValue> {
634
            // FAST PATH: compact cache for normal state (O(1) array lookup)
635
5195276
            if node_state.is_normal() {
636
5195180
                if let Some(ref cc) = styled_dom.css_property_cache.ptr.compact_cache {
637
5195168
                    let raw = cc.$compact_method(node_id.index());
638
5195168
                    if raw == azul_css::compact_cache::I16_AUTO {
639
535994
                        return MultiValue::Auto;
640
4659174
                    }
641
4659174
                    if raw == azul_css::compact_cache::I16_INITIAL {
642
                        return MultiValue::Initial;
643
4659174
                    }
644
4659174
                    if raw < azul_css::compact_cache::I16_SENTINEL_THRESHOLD {
645
                        // Valid value: decode i16 ×10 → px
646
4653149
                        return MultiValue::Exact(PixelValue::px(f32::from(raw) / 10.0));
647
6025
                    }
648
                    // I16_SENTINEL or I16_INHERIT → fall through to slow path
649
12
                }
650
96
            }
651

            
652
6133
            let node_data = &styled_dom.node_data.as_container()[node_id];
653

            
654
6133
            let author_css = styled_dom
655
6133
                .css_property_cache
656
6133
                .ptr
657
6133
                .$cache_method(node_data, &node_id, node_state);
658

            
659
6133
            if let Some(ref val) = author_css {
660
6049
                if val.is_auto() {
661
                    return MultiValue::Auto;
662
6049
                }
663
6049
                if let Some(exact) = val.get_property().copied() {
664
6049
                    return MultiValue::Exact(exact.inner);
665
                }
666
84
            }
667

            
668
84
            let ua_css = azul_core::ua_css::get_ua_property(&node_data.node_type, $ua_property);
669

            
670
84
            if let Some(ua_prop) = ua_css {
671
                if let Some(inner) = ua_prop.get_pixel_inner() {
672
                    return MultiValue::Exact(inner);
673
                }
674
84
            }
675

            
676
84
            MultiValue::Initial
677
5195276
        }
678
    };
679
}
680

            
681
/// Helper trait to extract `PixelValue` from any `CssProperty` variant
682
trait CssPropertyPixelInner {
683
    fn get_pixel_inner(&self) -> Option<PixelValue>;
684
}
685

            
686
impl CssPropertyPixelInner for CssProperty {
687
    fn get_pixel_inner(&self) -> Option<PixelValue> {
688
        match self {
689
            Self::Left(CssPropertyValue::Exact(v)) => Some(v.inner),
690
            Self::Right(CssPropertyValue::Exact(v)) => Some(v.inner),
691
            Self::Top(CssPropertyValue::Exact(v)) => Some(v.inner),
692
            Self::Bottom(CssPropertyValue::Exact(v)) => Some(v.inner),
693
            Self::MarginLeft(CssPropertyValue::Exact(v)) => Some(v.inner),
694
            Self::MarginRight(CssPropertyValue::Exact(v)) => Some(v.inner),
695
            Self::MarginTop(CssPropertyValue::Exact(v)) => Some(v.inner),
696
            Self::MarginBottom(CssPropertyValue::Exact(v)) => Some(v.inner),
697
            Self::PaddingLeft(CssPropertyValue::Exact(v)) => Some(v.inner),
698
            Self::PaddingRight(CssPropertyValue::Exact(v)) => Some(v.inner),
699
            Self::PaddingTop(CssPropertyValue::Exact(v)) => Some(v.inner),
700
            Self::PaddingBottom(CssPropertyValue::Exact(v)) => Some(v.inner),
701
            _ => None,
702
        }
703
    }
704
}
705

            
706
/// Generic macro for CSS properties with UA CSS fallback - returns `MultiValue`<T>
707
macro_rules! get_css_property {
708
    // Variant WITH compact cache fast path (for enum properties in Tier 1)
709
    ($fn_name:ident, $cache_method:ident, $return_type:ty, $ua_property:expr, compact = $compact_method:ident) => {
710
24809066
        #[must_use] pub fn $fn_name(
711
24809066
            styled_dom: &StyledDom,
712
24809066
            node_id: NodeId,
713
24809066
            node_state: &StyledNodeState,
714
24809066
        ) -> MultiValue<$return_type> {
715
            // FAST PATH: compact cache for normal state (O(1) array + bitshift)
716
            // NOTE (M12.7): skipping this fast path does NOT fix get_display_type's
717
            // divergence — the slow path / the `match get_display_type(...)` on the
718
            // LayoutDisplay enum (a niche-discriminant) mis-lifts too. So this isn't the
719
            // cache (unlike the font-size fix); it's the deeper niche/enum decode. Kept.
720
24809066
            if node_state.is_normal() {
721
24802787
                if let Some(ref cc) = styled_dom.css_property_cache.ptr.compact_cache {
722
24802725
                    return MultiValue::Exact(cc.$compact_method(node_id.index()));
723
62
                }
724
6279
            }
725

            
726
            // SLOW PATH: full cascade resolution
727
6341
            let node_data = &styled_dom.node_data.as_container()[node_id];
728

            
729
            // 1. Check author CSS first
730
6341
            let author_css = styled_dom
731
6341
                .css_property_cache
732
6341
                .ptr
733
6341
                .$cache_method(node_data, &node_id, node_state);
734

            
735
6341
            if let Some(val) = author_css.and_then(|v| v.get_property().cloned()) {
736
532
                return MultiValue::Exact(val);
737
5809
            }
738

            
739
            // 2. Check User Agent CSS
740
5809
            let ua_css = azul_core::ua_css::get_ua_property(&node_data.node_type, $ua_property);
741

            
742
5809
            if let Some(ua_prop) = ua_css {
743
                if let Some(val) = extract_property_value::<$return_type>(ua_prop) {
744
                    return MultiValue::Exact(val);
745
                }
746
5809
            }
747

            
748
            // 3. Fallback to Auto (not set)
749
5809
            MultiValue::Auto
750
24809066
        }
751
    };
752
    // Variant WITH compact cache for u32-encoded dimension enums (LayoutWidth/LayoutHeight)
753
    // These types have Auto, Px(PixelValue), MinContent, MaxContent, Calc variants
754
    ($fn_name:ident, $cache_method:ident, $return_type:ty, $ua_property:expr, compact_u32_dim = $compact_raw_method:ident, $px_variant:path, $auto_variant:path, $min_content_variant:path, $max_content_variant:path) => {
755
2065745
        #[must_use] pub fn $fn_name(
756
2065745
            styled_dom: &StyledDom,
757
2065745
            node_id: NodeId,
758
2065745
            node_state: &StyledNodeState,
759
2065745
        ) -> MultiValue<$return_type> {
760
            // FAST PATH: compact cache for normal state
761
2065745
            if node_state.is_normal() {
762
2065680
                if let Some(ref cc) = styled_dom.css_property_cache.ptr.compact_cache {
763
2065675
                    let raw = cc.$compact_raw_method(node_id.index());
764
2065675
                    match raw {
765
1803313
                        azul_css::compact_cache::U32_AUTO => return MultiValue::Auto,
766
                        azul_css::compact_cache::U32_INITIAL => return MultiValue::Initial,
767
                        azul_css::compact_cache::U32_NONE => return MultiValue::Auto,
768
                        azul_css::compact_cache::U32_MIN_CONTENT => return MultiValue::Exact($min_content_variant),
769
                        azul_css::compact_cache::U32_MAX_CONTENT => return MultiValue::Exact($max_content_variant),
770
                        azul_css::compact_cache::U32_SENTINEL | azul_css::compact_cache::U32_INHERIT => {
771
                            // fall through to slow path
772
                        }
773
                        _ => {
774
                            // Valid encoded pixel value
775
262362
                            if let Some(pv) = azul_css::compact_cache::decode_pixel_value_u32(raw) {
776
262362
                                return MultiValue::Exact($px_variant(pv));
777
                            }
778
                            // decode failed → slow path
779
                        }
780
                    }
781
5
                }
782
65
            }
783

            
784
            // SLOW PATH: full cascade resolution
785
70
            let node_data = &styled_dom.node_data.as_container()[node_id];
786

            
787
70
            let author_css = styled_dom
788
70
                .css_property_cache
789
70
                .ptr
790
70
                .$cache_method(node_data, &node_id, node_state);
791

            
792
70
            if let Some(val) = author_css.and_then(|v| v.get_property().cloned()) {
793
30
                return MultiValue::Exact(val);
794
40
            }
795

            
796
40
            let ua_css = azul_core::ua_css::get_ua_property(&node_data.node_type, $ua_property);
797

            
798
40
            if let Some(ua_prop) = ua_css {
799
                if let Some(val) = extract_property_value::<$return_type>(ua_prop) {
800
                    return MultiValue::Exact(val);
801
                }
802
40
            }
803

            
804
40
            MultiValue::Auto
805
2065745
        }
806
    };
807
    // Variant WITH compact cache for u32-encoded dimension structs (LayoutMinWidth etc.)
808
    // These types are struct { inner: PixelValue }
809
    ($fn_name:ident, $cache_method:ident, $return_type:ty, $ua_property:expr, compact_u32_struct = $compact_raw_method:ident) => {
810
2113644
        #[must_use] pub fn $fn_name(
811
2113644
            styled_dom: &StyledDom,
812
2113644
            node_id: NodeId,
813
2113644
            node_state: &StyledNodeState,
814
2113644
        ) -> MultiValue<$return_type> {
815
            // FAST PATH: compact cache for normal state
816
2113644
            if node_state.is_normal() {
817
2113570
                if let Some(ref cc) = styled_dom.css_property_cache.ptr.compact_cache {
818
2113562
                    let raw = cc.$compact_raw_method(node_id.index());
819
2113562
                    match raw {
820
2095615
                        azul_css::compact_cache::U32_AUTO | azul_css::compact_cache::U32_NONE => return MultiValue::Auto,
821
                        azul_css::compact_cache::U32_INITIAL => return MultiValue::Initial,
822
                        azul_css::compact_cache::U32_SENTINEL | azul_css::compact_cache::U32_INHERIT => {
823
                            // fall through to slow path
824
                        }
825
                        _ => {
826
17947
                            if let Some(pv) = azul_css::compact_cache::decode_pixel_value_u32(raw) {
827
17947
                                return MultiValue::Exact(
828
17947
                                    <$return_type as azul_css::props::PixelValueTaker>::from_pixel_value(pv)
829
17947
                                );
830
                            }
831
                        }
832
                    }
833
8
                }
834
74
            }
835

            
836
            // SLOW PATH
837
82
            let node_data = &styled_dom.node_data.as_container()[node_id];
838

            
839
82
            let author_css = styled_dom
840
82
                .css_property_cache
841
82
                .ptr
842
82
                .$cache_method(node_data, &node_id, node_state);
843

            
844
82
            if let Some(val) = author_css.and_then(|v| v.get_property().cloned()) {
845
                return MultiValue::Exact(val);
846
82
            }
847

            
848
82
            let ua_css = azul_core::ua_css::get_ua_property(&node_data.node_type, $ua_property);
849

            
850
82
            if let Some(ua_prop) = ua_css {
851
                if let Some(val) = extract_property_value::<$return_type>(ua_prop) {
852
                    return MultiValue::Exact(val);
853
                }
854
82
            }
855

            
856
82
            MultiValue::Auto
857
2113644
        }
858
    };
859
    // Variant WITHOUT compact cache (original behavior)
860
    ($fn_name:ident, $cache_method:ident, $return_type:ty, $ua_property:expr) => {
861
189622
        #[must_use] pub fn $fn_name(
862
189622
            styled_dom: &StyledDom,
863
189622
            node_id: NodeId,
864
189622
            node_state: &StyledNodeState,
865
189622
        ) -> MultiValue<$return_type> {
866
189622
            let node_data = &styled_dom.node_data.as_container()[node_id];
867

            
868
            // 1. Check author CSS first
869
189622
            let author_css = styled_dom
870
189622
                .css_property_cache
871
189622
                .ptr
872
189622
                .$cache_method(node_data, &node_id, node_state);
873

            
874
189622
            if let Some(val) = author_css.and_then(|v| v.get_property().cloned()) {
875
185
                return MultiValue::Exact(val);
876
189437
            }
877

            
878
            // 2. Check User Agent CSS
879
189437
            let ua_css = azul_core::ua_css::get_ua_property(&node_data.node_type, $ua_property);
880

            
881
189437
            if let Some(ua_prop) = ua_css {
882
                if let Some(val) = extract_property_value::<$return_type>(ua_prop) {
883
                    return MultiValue::Exact(val);
884
                }
885
189437
            }
886

            
887
            // 3. Fallback to Auto (not set)
888
189437
            MultiValue::Auto
889
189622
        }
890
    };
891
}
892

            
893
/// Helper trait to extract typed values from UA CSS properties
894
trait ExtractPropertyValue<T> {
895
    fn extract(&self) -> Option<T>;
896
}
897

            
898
fn extract_property_value<T>(prop: &CssProperty) -> Option<T>
899
where
900
    CssProperty: ExtractPropertyValue<T>,
901
{
902
    prop.extract()
903
}
904

            
905
// Implement extraction for all layout types
906

            
907
impl ExtractPropertyValue<azul_css::props::style::transform::StyleAppRegion> for CssProperty {
908
    fn extract(&self) -> Option<azul_css::props::style::transform::StyleAppRegion> {
909
        match self {
910
            Self::AppRegion(CssPropertyValue::Exact(v)) => Some(*v),
911
            _ => None,
912
        }
913
    }
914
}
915

            
916
impl ExtractPropertyValue<azul_css::props::style::spatial_nav::StyleSpatialNavigationAction>
917
    for CssProperty
918
{
919
    fn extract(&self) -> Option<azul_css::props::style::spatial_nav::StyleSpatialNavigationAction> {
920
        match self {
921
            Self::SpatialNavigationAction(CssPropertyValue::Exact(v)) => Some(*v),
922
            _ => None,
923
        }
924
    }
925
}
926

            
927
impl ExtractPropertyValue<azul_css::props::style::spatial_nav::StyleSpatialNavigationContain>
928
    for CssProperty
929
{
930
    fn extract(
931
        &self,
932
    ) -> Option<azul_css::props::style::spatial_nav::StyleSpatialNavigationContain> {
933
        match self {
934
            Self::SpatialNavigationContain(CssPropertyValue::Exact(v)) => Some(*v),
935
            _ => None,
936
        }
937
    }
938
}
939

            
940
impl ExtractPropertyValue<LayoutWidth> for CssProperty {
941
    fn extract(&self) -> Option<LayoutWidth> {
942
        match self {
943
            Self::Width(CssPropertyValue::Exact(v)) => Some(v.clone()),
944
            _ => None,
945
        }
946
    }
947
}
948

            
949
impl ExtractPropertyValue<LayoutHeight> for CssProperty {
950
    fn extract(&self) -> Option<LayoutHeight> {
951
        match self {
952
            Self::Height(CssPropertyValue::Exact(v)) => Some(v.clone()),
953
            _ => None,
954
        }
955
    }
956
}
957

            
958
impl ExtractPropertyValue<LayoutMinWidth> for CssProperty {
959
    fn extract(&self) -> Option<LayoutMinWidth> {
960
        match self {
961
            Self::MinWidth(CssPropertyValue::Exact(v)) => Some(*v),
962
            _ => None,
963
        }
964
    }
965
}
966

            
967
impl ExtractPropertyValue<LayoutMinHeight> for CssProperty {
968
    fn extract(&self) -> Option<LayoutMinHeight> {
969
        match self {
970
            Self::MinHeight(CssPropertyValue::Exact(v)) => Some(*v),
971
            _ => None,
972
        }
973
    }
974
}
975

            
976
impl ExtractPropertyValue<LayoutMaxWidth> for CssProperty {
977
    fn extract(&self) -> Option<LayoutMaxWidth> {
978
        match self {
979
            Self::MaxWidth(CssPropertyValue::Exact(v)) => Some(*v),
980
            _ => None,
981
        }
982
    }
983
}
984

            
985
impl ExtractPropertyValue<LayoutMaxHeight> for CssProperty {
986
    fn extract(&self) -> Option<LayoutMaxHeight> {
987
        match self {
988
            Self::MaxHeight(CssPropertyValue::Exact(v)) => Some(*v),
989
            _ => None,
990
        }
991
    }
992
}
993

            
994
impl ExtractPropertyValue<LayoutDisplay> for CssProperty {
995
    fn extract(&self) -> Option<LayoutDisplay> {
996
        match self {
997
            Self::Display(CssPropertyValue::Exact(v)) => Some(*v),
998
            _ => None,
999
        }
    }
}
impl ExtractPropertyValue<LayoutWritingMode> for CssProperty {
    fn extract(&self) -> Option<LayoutWritingMode> {
        match self {
            Self::WritingMode(CssPropertyValue::Exact(v)) => Some(*v),
            _ => None,
        }
    }
}
impl ExtractPropertyValue<LayoutFlexWrap> for CssProperty {
    fn extract(&self) -> Option<LayoutFlexWrap> {
        match self {
            Self::FlexWrap(CssPropertyValue::Exact(v)) => Some(*v),
            _ => None,
        }
    }
}
impl ExtractPropertyValue<LayoutJustifyContent> for CssProperty {
    fn extract(&self) -> Option<LayoutJustifyContent> {
        match self {
            Self::JustifyContent(CssPropertyValue::Exact(v)) => Some(*v),
            _ => None,
        }
    }
}
impl ExtractPropertyValue<StyleTextAlign> for CssProperty {
    fn extract(&self) -> Option<StyleTextAlign> {
        match self {
            Self::TextAlign(CssPropertyValue::Exact(v)) => Some(*v),
            _ => None,
        }
    }
}
impl ExtractPropertyValue<LayoutFloat> for CssProperty {
    fn extract(&self) -> Option<LayoutFloat> {
        match self {
            Self::Float(CssPropertyValue::Exact(v)) => Some(*v),
            _ => None,
        }
    }
}
impl ExtractPropertyValue<LayoutClear> for CssProperty {
    fn extract(&self) -> Option<LayoutClear> {
        match self {
            Self::Clear(CssPropertyValue::Exact(v)) => Some(*v),
            _ => None,
        }
    }
}
impl ExtractPropertyValue<LayoutOverflow> for CssProperty {
    fn extract(&self) -> Option<LayoutOverflow> {
        match self {
            Self::OverflowX(CssPropertyValue::Exact(v))
            | Self::OverflowY(CssPropertyValue::Exact(v))
            | Self::OverflowBlock(CssPropertyValue::Exact(v))
            | Self::OverflowInline(CssPropertyValue::Exact(v)) => Some(*v),
            _ => None,
        }
    }
}
impl ExtractPropertyValue<LayoutPosition> for CssProperty {
    fn extract(&self) -> Option<LayoutPosition> {
        match self {
            Self::Position(CssPropertyValue::Exact(v)) => Some(*v),
            _ => None,
        }
    }
}
impl ExtractPropertyValue<LayoutBoxSizing> for CssProperty {
    fn extract(&self) -> Option<LayoutBoxSizing> {
        match self {
            Self::BoxSizing(CssPropertyValue::Exact(v)) => Some(*v),
            _ => None,
        }
    }
}
impl ExtractPropertyValue<PixelValue> for CssProperty {
    fn extract(&self) -> Option<PixelValue> {
        self.get_pixel_inner()
    }
}
impl ExtractPropertyValue<LayoutFlexDirection> for CssProperty {
    fn extract(&self) -> Option<LayoutFlexDirection> {
        match self {
            Self::FlexDirection(CssPropertyValue::Exact(v)) => Some(*v),
            _ => None,
        }
    }
}
impl ExtractPropertyValue<LayoutAlignItems> for CssProperty {
    fn extract(&self) -> Option<LayoutAlignItems> {
        match self {
            Self::AlignItems(CssPropertyValue::Exact(v)) => Some(*v),
            _ => None,
        }
    }
}
impl ExtractPropertyValue<LayoutAlignContent> for CssProperty {
    fn extract(&self) -> Option<LayoutAlignContent> {
        match self {
            Self::AlignContent(CssPropertyValue::Exact(v)) => Some(*v),
            _ => None,
        }
    }
}
impl ExtractPropertyValue<StyleFontWeight> for CssProperty {
    fn extract(&self) -> Option<StyleFontWeight> {
        match self {
            Self::FontWeight(CssPropertyValue::Exact(v)) => Some(*v),
            _ => None,
        }
    }
}
impl ExtractPropertyValue<StyleFontStyle> for CssProperty {
    fn extract(&self) -> Option<StyleFontStyle> {
        match self {
            Self::FontStyle(CssPropertyValue::Exact(v)) => Some(*v),
            _ => None,
        }
    }
}
impl ExtractPropertyValue<StyleVisibility> for CssProperty {
    fn extract(&self) -> Option<StyleVisibility> {
        match self {
            Self::Visibility(CssPropertyValue::Exact(v)) => Some(*v),
            _ => None,
        }
    }
}
impl ExtractPropertyValue<StyleWhiteSpace> for CssProperty {
    fn extract(&self) -> Option<StyleWhiteSpace> {
        match self {
            Self::WhiteSpace(CssPropertyValue::Exact(v)) => Some(*v),
            _ => None,
        }
    }
}
impl ExtractPropertyValue<StyleDirection> for CssProperty {
    fn extract(&self) -> Option<StyleDirection> {
        match self {
            Self::Direction(CssPropertyValue::Exact(v)) => Some(*v),
            _ => None,
        }
    }
}
impl ExtractPropertyValue<StyleUnicodeBidi> for CssProperty {
    fn extract(&self) -> Option<StyleUnicodeBidi> {
        match self {
            Self::UnicodeBidi(CssPropertyValue::Exact(v)) => Some(*v),
            _ => None,
        }
    }
}
impl ExtractPropertyValue<StyleTextBoxTrim> for CssProperty {
    fn extract(&self) -> Option<StyleTextBoxTrim> {
        match self {
            Self::TextBoxTrim(CssPropertyValue::Exact(v)) => Some(*v),
            _ => None,
        }
    }
}
impl ExtractPropertyValue<StyleTextBoxEdge> for CssProperty {
    fn extract(&self) -> Option<StyleTextBoxEdge> {
        match self {
            Self::TextBoxEdge(CssPropertyValue::Exact(v)) => Some(*v),
            _ => None,
        }
    }
}
impl ExtractPropertyValue<StyleDominantBaseline> for CssProperty {
    fn extract(&self) -> Option<StyleDominantBaseline> {
        match self {
            Self::DominantBaseline(CssPropertyValue::Exact(v)) => Some(*v),
            _ => None,
        }
    }
}
impl ExtractPropertyValue<StyleAlignmentBaseline> for CssProperty {
    fn extract(&self) -> Option<StyleAlignmentBaseline> {
        match self {
            Self::AlignmentBaseline(CssPropertyValue::Exact(v)) => Some(*v),
            _ => None,
        }
    }
}
impl ExtractPropertyValue<StyleBaselineSource> for CssProperty {
    fn extract(&self) -> Option<StyleBaselineSource> {
        match self {
            Self::BaselineSource(CssPropertyValue::Exact(v)) => Some(*v),
            _ => None,
        }
    }
}
impl ExtractPropertyValue<StyleLineFitEdge> for CssProperty {
    fn extract(&self) -> Option<StyleLineFitEdge> {
        match self {
            Self::LineFitEdge(CssPropertyValue::Exact(v)) => Some(*v),
            _ => None,
        }
    }
}
impl ExtractPropertyValue<StyleInitialLetterAlign> for CssProperty {
    fn extract(&self) -> Option<StyleInitialLetterAlign> {
        match self {
            Self::InitialLetterAlign(CssPropertyValue::Exact(v)) => Some(*v),
            _ => None,
        }
    }
}
impl ExtractPropertyValue<StyleInitialLetterWrap> for CssProperty {
    fn extract(&self) -> Option<StyleInitialLetterWrap> {
        match self {
            Self::InitialLetterWrap(CssPropertyValue::Exact(v)) => Some(*v),
            _ => None,
        }
    }
}
impl ExtractPropertyValue<StyleScrollbarGutter> for CssProperty {
    fn extract(&self) -> Option<StyleScrollbarGutter> {
        match self {
            Self::ScrollbarGutter(CssPropertyValue::Exact(v)) => Some(*v),
            _ => None,
        }
    }
}
impl ExtractPropertyValue<StyleOverflowClipMargin> for CssProperty {
    fn extract(&self) -> Option<StyleOverflowClipMargin> {
        match self {
            Self::OverflowClipMargin(CssPropertyValue::Exact(v)) => Some(*v),
            _ => None,
        }
    }
}
impl ExtractPropertyValue<StyleVerticalAlign> for CssProperty {
    fn extract(&self) -> Option<StyleVerticalAlign> {
        match self {
            Self::VerticalAlign(CssPropertyValue::Exact(v)) => Some(*v),
            _ => None,
        }
    }
}
get_css_property!(
    get_writing_mode,
    get_writing_mode,
    LayoutWritingMode,
    CssPropertyType::WritingMode,
    compact = get_writing_mode
);
get_css_property!(
    get_css_width,
    get_width,
    LayoutWidth,
    CssPropertyType::Width,
    compact_u32_dim = get_width_raw,
    LayoutWidth::Px,
    LayoutWidth::Auto,
    LayoutWidth::MinContent,
    LayoutWidth::MaxContent
);
get_css_property!(
    get_css_height,
    get_height,
    LayoutHeight,
    CssPropertyType::Height,
    compact_u32_dim = get_height_raw,
    LayoutHeight::Px,
    LayoutHeight::Auto,
    LayoutHeight::MinContent,
    LayoutHeight::MaxContent
);
get_css_property!(
    get_wrap,
    get_flex_wrap,
    LayoutFlexWrap,
    CssPropertyType::FlexWrap,
    compact = get_flex_wrap
);
get_css_property!(
    get_justify_content,
    get_justify_content,
    LayoutJustifyContent,
    CssPropertyType::JustifyContent,
    compact = get_justify_content
);
get_css_property!(
    get_text_align,
    get_text_align,
    StyleTextAlign,
    CssPropertyType::TextAlign,
    compact = get_text_align
);
get_css_property!(
    get_float,
    get_float,
    LayoutFloat,
    CssPropertyType::Float,
    compact = get_float
);
get_css_property!(
    get_clear,
    get_clear,
    LayoutClear,
    CssPropertyType::Clear,
    compact = get_clear
);
get_css_property!(
    get_overflow_x_declared,
    get_overflow_x,
    LayoutOverflow,
    CssPropertyType::OverflowX,
    compact = get_overflow_x
);
get_css_property!(
    get_overflow_y_declared,
    get_overflow_y,
    LayoutOverflow,
    CssPropertyType::OverflowY,
    compact = get_overflow_y
);
// +spec:overflow:17654b - overflow-block and overflow-inline logical properties resolve to physical
// overflow based on writing mode
/// Physical `overflow-x`, with the css-overflow-3 logical fallback: when the
/// physical property is unset, a declared `overflow-inline` (horizontal
/// writing modes) or `overflow-block` (vertical) supplies the value. On the
/// compact fast path the mapping already happened at build time, in
/// declaration order (equal-specificity last-wins); this slow-path fallback
/// uses "physical if declared, else logical" as the cascade approximation.
#[must_use]
3193652
pub fn get_overflow_x(
3193652
    styled_dom: &StyledDom,
3193652
    node_id: NodeId,
3193652
    node_state: &StyledNodeState,
3193652
) -> MultiValue<LayoutOverflow> {
3193652
    let phys = get_overflow_x_declared(styled_dom, node_id, node_state);
3193652
    if matches!(phys, MultiValue::Exact(_)) {
3192382
        return phys;
1270
    }
1270
    let vertical = matches!(
1270
        get_writing_mode(styled_dom, node_id, node_state),
        MultiValue::Exact(LayoutWritingMode::VerticalRl | LayoutWritingMode::VerticalLr)
    );
1270
    let logical = if vertical {
        get_overflow_block(styled_dom, node_id, node_state)
    } else {
1270
        get_overflow_inline(styled_dom, node_id, node_state)
    };
1270
    if matches!(logical, MultiValue::Exact(_)) {
        logical
    } else {
1270
        phys
    }
3193652
}
/// Physical `overflow-y`; see [`get_overflow_x`] for the logical fallback.
#[must_use]
2949004
pub fn get_overflow_y(
2949004
    styled_dom: &StyledDom,
2949004
    node_id: NodeId,
2949004
    node_state: &StyledNodeState,
2949004
) -> MultiValue<LayoutOverflow> {
2949004
    let phys = get_overflow_y_declared(styled_dom, node_id, node_state);
2949004
    if matches!(phys, MultiValue::Exact(_)) {
2947860
        return phys;
1144
    }
1144
    let vertical = matches!(
1144
        get_writing_mode(styled_dom, node_id, node_state),
        MultiValue::Exact(LayoutWritingMode::VerticalRl | LayoutWritingMode::VerticalLr)
    );
1144
    let logical = if vertical {
        get_overflow_inline(styled_dom, node_id, node_state)
    } else {
1144
        get_overflow_block(styled_dom, node_id, node_state)
    };
1144
    if matches!(logical, MultiValue::Exact(_)) {
        logical
    } else {
1144
        phys
    }
2949004
}
// +spec:overflow:17654b - overflow-block and overflow-inline logical properties resolve to physical
// overflow based on writing mode
get_css_property!(
    get_overflow_block,
    get_overflow_block,
    LayoutOverflow,
    CssPropertyType::OverflowBlock
);
get_css_property!(
    get_overflow_inline,
    get_overflow_inline,
    LayoutOverflow,
    CssPropertyType::OverflowInline
);
get_css_property!(
    get_position,
    get_position,
    LayoutPosition,
    CssPropertyType::Position,
    compact = get_position
);
get_css_property!(
    get_css_box_sizing,
    get_box_sizing,
    LayoutBoxSizing,
    CssPropertyType::BoxSizing,
    compact = get_box_sizing
);
get_css_property!(
    get_flex_direction,
    get_flex_direction,
    LayoutFlexDirection,
    CssPropertyType::FlexDirection,
    compact = get_flex_direction
);
get_css_property!(
    get_align_items,
    get_align_items,
    LayoutAlignItems,
    CssPropertyType::AlignItems,
    compact = get_align_items
);
get_css_property!(
    get_align_content,
    get_align_content,
    LayoutAlignContent,
    CssPropertyType::AlignContent,
    compact = get_align_content
);
get_css_property!(
    get_font_weight_property,
    get_font_weight,
    StyleFontWeight,
    CssPropertyType::FontWeight,
    compact = get_font_weight
);
get_css_property!(
    get_font_style_property,
    get_font_style,
    StyleFontStyle,
    CssPropertyType::FontStyle,
    compact = get_font_style
);
get_css_property!(
    get_visibility,
    get_visibility,
    StyleVisibility,
    CssPropertyType::Visibility,
    compact = get_visibility
);
get_css_property!(
    get_white_space_property,
    get_white_space,
    StyleWhiteSpace,
    CssPropertyType::WhiteSpace,
    compact = get_white_space
);
// +spec:writing-modes:3af12f - unicode-bidi does not affect direction for layout; we use direction
// property directly
get_css_property!(
    get_direction_property,
    get_direction,
    StyleDirection,
    CssPropertyType::Direction,
    compact = get_direction
);
// +spec:display-property:346799 - inline-level elements with unicode-bidi:normal have no effect on
// text ordering +spec:writing-modes:3e2632 - unicode-bidi property resolves embedding level for
// bidi algorithm (LRE/RLE/PDF) +spec:writing-modes:d2c94f - direction+unicode-bidi properties map
// to UAX#9 bidirectional algorithm
get_css_property!(
    get_unicode_bidi_property,
    get_unicode_bidi,
    StyleUnicodeBidi,
    CssPropertyType::UnicodeBidi
);
// +spec:display-property:db5125 - text-box-trim on inline boxes trims content box to text-box-edge
// metric +spec:display-property:dceb24 - text-box-trim on inline boxes: content edges coincide with
// text baselines
get_css_property!(
    get_text_box_trim_property,
    get_text_box_trim,
    StyleTextBoxTrim,
    CssPropertyType::TextBoxTrim
);
get_css_property!(
    get_text_box_edge_property,
    get_text_box_edge,
    StyleTextBoxEdge,
    CssPropertyType::TextBoxEdge
);
get_css_property!(
    get_dominant_baseline_property,
    get_dominant_baseline,
    StyleDominantBaseline,
    CssPropertyType::DominantBaseline
);
get_css_property!(
    get_alignment_baseline_property,
    get_alignment_baseline,
    StyleAlignmentBaseline,
    CssPropertyType::AlignmentBaseline
);
get_css_property!(
    get_baseline_source_property,
    get_baseline_source,
    StyleBaselineSource,
    CssPropertyType::BaselineSource
);
get_css_property!(
    get_line_fit_edge_property,
    get_line_fit_edge,
    StyleLineFitEdge,
    CssPropertyType::LineFitEdge
);
get_css_property!(
    get_initial_letter_align_property,
    get_initial_letter_align,
    StyleInitialLetterAlign,
    CssPropertyType::InitialLetterAlign
);
get_css_property!(
    get_initial_letter_wrap_property,
    get_initial_letter_wrap,
    StyleInitialLetterWrap,
    CssPropertyType::InitialLetterWrap
);
// +spec:overflow:5d15e2 - block-start/block-end scrollbar gutter follows same rules as inline
// gutters when auto
//
// Hand-rolled fast path: 99% of nodes don't set scrollbar-gutter, and the
// default is `auto`. The compact cache stores the enum in 2 bits of
// tier2_cold.hot_flags, so we can return the answer without a cascade walk.
#[allow(clippy::match_same_arms)]
// enum/value mapping/dispatch table: one arm per input variant (or cross-type bindings that can't
// merge)
#[must_use]
1185189
pub fn get_scrollbar_gutter_property(
1185189
    styled_dom: &StyledDom,
1185189
    node_id: NodeId,
1185189
    node_state: &StyledNodeState,
1185189
) -> MultiValue<StyleScrollbarGutter> {
    // FAST PATH: 2-bit enum in hot_flags
1185189
    if node_state.is_normal() {
1185074
        if let Some(ref cc) = styled_dom.css_property_cache.ptr.compact_cache {
1185073
            let bits = cc.get_scrollbar_gutter_bits(node_id.index());
1185073
            let val = match bits {
1185073
                azul_css::compact_cache::SCROLLBAR_GUTTER_AUTO => StyleScrollbarGutter::Auto,
                azul_css::compact_cache::SCROLLBAR_GUTTER_STABLE => StyleScrollbarGutter::Stable,
                azul_css::compact_cache::SCROLLBAR_GUTTER_BOTH_EDGES => {
                    StyleScrollbarGutter::StableBothEdges
                }
                _ => StyleScrollbarGutter::Auto,
            };
1185073
            return MultiValue::Exact(val);
1
        }
115
    }
    // SLOW PATH: cascade resolution for pseudo-states or missing cache
116
    let node_data = &styled_dom.node_data.as_container()[node_id];
116
    let author_css = styled_dom
116
        .css_property_cache
116
        .ptr
116
        .get_scrollbar_gutter(node_data, &node_id, node_state);
116
    if let Some(val) = author_css.and_then(|v| v.get_property().copied()) {
        return MultiValue::Exact(val);
116
    }
116
    MultiValue::Auto
1185189
}
get_css_property!(
    get_overflow_clip_margin_property,
    get_overflow_clip_margin,
    StyleOverflowClipMargin,
    CssPropertyType::OverflowClipMargin
);
get_css_property!(
    get_object_fit_property,
    get_object_fit,
    StyleObjectFit,
    CssPropertyType::ObjectFit
);
get_css_property!(
    get_text_overflow_property,
    get_text_overflow,
    StyleTextOverflow,
    CssPropertyType::TextOverflow
);
// +spec:writing-modes:257296 - text-orientation getter for vertical typesetting (upright/sideways)
//
// Hand-rolled (not macro-generated) to attach a negative fast-path: most
// nodes have no text-orientation declared (default = Mixed), so we avoid a
// cascade walk per fc.rs call (which is called ~2× per node).
#[must_use]
630810
pub fn get_text_orientation_property(
630810
    styled_dom: &StyledDom,
630810
    node_id: NodeId,
630810
    node_state: &StyledNodeState,
630810
) -> MultiValue<StyleTextOrientation> {
630810
    if node_state.is_normal() {
630790
        if let Some(ref cc) = styled_dom.css_property_cache.ptr.compact_cache {
630788
            if !cc.has_text_orientation(node_id.index()) {
630788
                return MultiValue::Auto;
            }
2
        }
20
    }
22
    let node_data = &styled_dom.node_data.as_container()[node_id];
22
    if let Some(val) = styled_dom
22
        .css_property_cache
22
        .ptr
22
        .get_text_orientation(node_data, &node_id, node_state)
22
        .and_then(|v| v.get_property().copied())
    {
        return MultiValue::Exact(val);
22
    }
22
    let ua =
22
        azul_core::ua_css::get_ua_property(&node_data.node_type, CssPropertyType::TextOrientation);
22
    if let Some(ua_prop) = ua {
        if let Some(val) = extract_property_value::<StyleTextOrientation>(ua_prop) {
            return MultiValue::Exact(val);
        }
22
    }
22
    MultiValue::Auto
630810
}
get_css_property!(
    get_object_position_property,
    get_object_position,
    StyleObjectPosition,
    CssPropertyType::ObjectPosition
);
get_css_property!(
    get_aspect_ratio_property,
    get_aspect_ratio,
    StyleAspectRatio,
    CssPropertyType::AspectRatio
);
// NOTE: vertical-align does NOT use the compact cache because the compact cache
// only stores keyword variants (3 bits = 8 values) and silently drops
// Percentage/Length values by mapping them to Baseline. Always use the slow path.
#[must_use]
84593
pub fn get_vertical_align_property(
84593
    styled_dom: &StyledDom,
84593
    node_id: NodeId,
84593
    node_state: &StyledNodeState,
84593
) -> MultiValue<StyleVerticalAlign> {
84593
    let node_data = &styled_dom.node_data.as_container()[node_id];
84593
    let author_css = styled_dom
84593
        .css_property_cache
84593
        .ptr
84593
        .get_vertical_align(node_data, &node_id, node_state);
84593
    if let Some(val) = author_css.and_then(|v| v.get_property().copied()) {
870
        return MultiValue::Exact(val);
83723
    }
83723
    let ua_css =
83723
        azul_core::ua_css::get_ua_property(&node_data.node_type, CssPropertyType::VerticalAlign);
83723
    if let Some(ua_prop) = ua_css {
        if let Some(val) = extract_property_value::<StyleVerticalAlign>(ua_prop) {
            return MultiValue::Exact(val);
        }
83723
    }
83723
    MultiValue::Auto
84593
}
// Complex Property Getters
/// Get border radius for all four corners (raw CSS property values)
#[must_use]
446069
pub fn get_style_border_radius(
446069
    styled_dom: &StyledDom,
446069
    node_id: NodeId,
446069
    node_state: &StyledNodeState,
446069
) -> StyleBorderRadius {
    use azul_css::props::basic::pixel::PixelValue;
    // FAST PATH: all four corners live in tier2_cold as i16 px × 10. The
    // common case (no rounded corners anywhere) reads four bytes and bails.
446069
    if node_state.is_normal() {
445969
        if let Some(ref cc) = styled_dom.css_property_cache.ptr.compact_cache {
445968
            let idx = node_id.index();
1783872
            let decode = |raw: i16| -> PixelValue {
1783872
                if raw >= azul_css::compact_cache::I16_SENTINEL_THRESHOLD {
1775244
                    PixelValue::px(0.0)
                } else {
8628
                    PixelValue::px(f32::from(raw) / 10.0)
                }
1783872
            };
445968
            return StyleBorderRadius {
445968
                top_left: decode(cc.get_border_top_left_radius_raw(idx)),
445968
                top_right: decode(cc.get_border_top_right_radius_raw(idx)),
445968
                bottom_right: decode(cc.get_border_bottom_right_radius_raw(idx)),
445968
                bottom_left: decode(cc.get_border_bottom_left_radius_raw(idx)),
445968
            };
1
        }
100
    }
101
    let node_data = &styled_dom.node_data.as_container()[node_id];
101
    let top_left = styled_dom
101
        .css_property_cache
101
        .ptr
101
        .get_border_top_left_radius(node_data, &node_id, node_state)
101
        .and_then(|br| br.get_property_or_default())
101
        .map(|v| v.inner)
101
        .unwrap_or_default();
101
    let top_right = styled_dom
101
        .css_property_cache
101
        .ptr
101
        .get_border_top_right_radius(node_data, &node_id, node_state)
101
        .and_then(|br| br.get_property_or_default())
101
        .map(|v| v.inner)
101
        .unwrap_or_default();
101
    let bottom_right = styled_dom
101
        .css_property_cache
101
        .ptr
101
        .get_border_bottom_right_radius(node_data, &node_id, node_state)
101
        .and_then(|br| br.get_property_or_default())
101
        .map(|v| v.inner)
101
        .unwrap_or_default();
101
    let bottom_left = styled_dom
101
        .css_property_cache
101
        .ptr
101
        .get_border_bottom_left_radius(node_data, &node_id, node_state)
101
        .and_then(|br| br.get_property_or_default())
101
        .map(|v| v.inner)
101
        .unwrap_or_default();
101
    StyleBorderRadius {
101
        top_left,
101
        top_right,
101
        bottom_right,
101
        bottom_left,
101
    }
446069
}
/// Get border radius for all four corners (resolved to pixels)
///
/// # Arguments
/// * `element_size` - The element's own size (width × height) for % resolution. According to CSS
///   spec, border-radius % uses element's own dimensions.
#[must_use]
2030207
pub fn get_border_radius(
2030207
    styled_dom: &StyledDom,
2030207
    node_id: NodeId,
2030207
    node_state: &StyledNodeState,
2030207
    element_size: PhysicalSizeImport,
2030207
    viewport_size: LogicalSize,
2030207
) -> BorderRadius {
    use azul_css::props::basic::{PhysicalSize, PropertyContext, ResolutionContext};
    // FAST PATH: all four corners as i16 px × 10 in tier2_cold. The
    // overwhelmingly common case (no rounded corners) reads four bytes and
    // returns zeros without a cascade walk.
2030207
    if node_state.is_normal() {
2029896
        if let Some(ref cc) = styled_dom.css_property_cache.ptr.compact_cache {
2029887
            let idx = node_id.index();
2029887
            let tl = cc.get_border_top_left_radius_raw(idx);
2029887
            let tr = cc.get_border_top_right_radius_raw(idx);
2029887
            let br = cc.get_border_bottom_right_radius_raw(idx);
2029887
            let bl = cc.get_border_bottom_left_radius_raw(idx);
            // sentinel = "unset" = 0 px (no corner radius)
2029887
            let thresh = azul_css::compact_cache::I16_SENTINEL_THRESHOLD;
8119548
            let decode = |raw: i16| -> f32 {
8119548
                if raw >= thresh {
8092544
                    0.0
                } else {
27004
                    f32::from(raw) / 10.0
                }
8119548
            };
2029887
            return BorderRadius {
2029887
                top_left: decode(tl),
2029887
                top_right: decode(tr),
2029887
                bottom_right: decode(br),
2029887
                bottom_left: decode(bl),
2029887
            };
9
        }
311
    }
320
    let node_data = &styled_dom.node_data.as_container()[node_id];
    // Get font sizes for em/rem resolution
320
    let element_font_size = get_element_font_size(styled_dom, node_id, node_state);
320
    let parent_font_size = styled_dom
320
        .node_hierarchy
320
        .as_container()
320
        .get(node_id)
320
        .and_then(azul_core::styled_dom::NodeHierarchyItem::parent_id)
320
        .map_or(DEFAULT_FONT_SIZE, |p| {
230
            get_element_font_size(styled_dom, p, node_state)
230
        });
320
    let root_font_size = get_root_font_size(styled_dom, node_state);
    // Create resolution context
320
    let context = ResolutionContext {
320
        vertical_writing_mode: false,
320
        element_font_size,
320
        parent_font_size,
320
        root_font_size,
320
        containing_block_size: PhysicalSize::new(0.0, 0.0), // Not used for border-radius
320
        element_size: Some(PhysicalSize::new(element_size.width, element_size.height)),
320
        viewport_size: PhysicalSize::new(viewport_size.width, viewport_size.height),
320
    };
320
    let top_left = styled_dom
320
        .css_property_cache
320
        .ptr
320
        .get_border_top_left_radius(node_data, &node_id, node_state)
320
        .and_then(|br| br.get_property().copied())
320
        .unwrap_or_default();
320
    let top_right = styled_dom
320
        .css_property_cache
320
        .ptr
320
        .get_border_top_right_radius(node_data, &node_id, node_state)
320
        .and_then(|br| br.get_property().copied())
320
        .unwrap_or_default();
320
    let bottom_right = styled_dom
320
        .css_property_cache
320
        .ptr
320
        .get_border_bottom_right_radius(node_data, &node_id, node_state)
320
        .and_then(|br| br.get_property().copied())
320
        .unwrap_or_default();
320
    let bottom_left = styled_dom
320
        .css_property_cache
320
        .ptr
320
        .get_border_bottom_left_radius(node_data, &node_id, node_state)
320
        .and_then(|br| br.get_property().copied())
320
        .unwrap_or_default();
320
    BorderRadius {
320
        top_left: top_left
320
            .inner
320
            .resolve_with_context(&context, PropertyContext::BorderRadius),
320
        top_right: top_right
320
            .inner
320
            .resolve_with_context(&context, PropertyContext::BorderRadius),
320
        bottom_right: bottom_right
320
            .inner
320
            .resolve_with_context(&context, PropertyContext::BorderRadius),
320
        bottom_left: bottom_left
320
            .inner
320
            .resolve_with_context(&context, PropertyContext::BorderRadius),
320
    }
2030207
}
// +spec:stacking-contexts:a93e62 - stack level from z-index for stacking context ordering
// +spec:stacking-contexts:ae50ae - z-index specifies stack level; auto resolves to 0 (inherited
// from parent stacking context)
/// Get z-index for stacking context ordering.
///
/// Returns the resolved integer z-index value:
/// - `z-index: auto` → 0 (participates in parent's stacking context)
/// - `z-index: <integer>` → that integer value
#[must_use]
16603
pub fn get_z_index(styled_dom: &StyledDom, node_id: Option<NodeId>) -> i32 {
    use azul_css::props::layout::position::LayoutZIndex;
16603
    let Some(node_id) = node_id else {
1
        return 0;
    };
16602
    let node_state = &styled_dom.styled_nodes.as_container()[node_id].styled_node_state;
    // FAST PATH: compact cache for normal state
16602
    if node_state.is_normal() {
16575
        if let Some(ref cc) = styled_dom.css_property_cache.ptr.compact_cache {
16574
            let raw = cc.get_z_index(node_id.index());
16574
            if raw == azul_css::compact_cache::I16_AUTO {
16566
                return 0;
8
            }
8
            if raw < azul_css::compact_cache::I16_SENTINEL_THRESHOLD {
5
                return i32::from(raw);
3
            }
            // I16_SENTINEL → fall through to slow path
1
        }
27
    }
    // SLOW PATH
31
    let node_data = &styled_dom.node_data.as_container()[node_id];
31
    styled_dom
31
        .css_property_cache
31
        .ptr
31
        .get_z_index(node_data, &node_id, node_state)
31
        .and_then(|v| v.get_property())
31
        .map_or(0, |z| match z {
            LayoutZIndex::Auto => 0,
3
            LayoutZIndex::Integer(i) => *i,
3
        })
16603
}
// +spec:positioning:c041c4 - positioned elements with z-index != auto establish stacking contexts
// z-index:<integer> ALWAYS establishes new stacking context on positioned elements
/// Returns true if z-index is `auto` (the initial value), false if it's an explicit `<integer>`.
/// This distinction matters for stacking context creation per §9.9.1.
#[must_use]
1544046
pub fn is_z_index_auto(styled_dom: &StyledDom, node_id: Option<NodeId>) -> bool {
    use azul_css::props::layout::position::LayoutZIndex;
1544046
    let Some(node_id) = node_id else {
1
        return true;
    };
1544045
    let node_state = &styled_dom.styled_nodes.as_container()[node_id].styled_node_state;
    // FAST PATH: compact cache for normal state
1544045
    if node_state.is_normal() {
1543899
        if let Some(ref cc) = styled_dom.css_property_cache.ptr.compact_cache {
1543899
            let raw = cc.get_z_index(node_id.index());
1543899
            if raw == azul_css::compact_cache::I16_AUTO {
1543891
                return true;
8
            }
8
            if raw < azul_css::compact_cache::I16_SENTINEL_THRESHOLD {
5
                return false; // explicit integer
3
            }
            // I16_SENTINEL → fall through to slow path
        }
146
    }
    // SLOW PATH
149
    let node_data = &styled_dom.node_data.as_container()[node_id];
149
    styled_dom
149
        .css_property_cache
149
        .ptr
149
        .get_z_index(node_data, &node_id, node_state)
149
        .and_then(|v| v.get_property())
149
        .is_none_or(|z| matches!(z, LayoutZIndex::Auto)) // no value = auto
1544046
}
// Rendering Property Getters
/// Information about background color for a node
///
/// # CSS Background Propagation (Special Case for HTML Root)
///
/// According to CSS Backgrounds and Borders Module Level 3, Section "The Canvas Background
/// and the HTML `<body>` Element":
///
/// For HTML documents where the root element is `<html>`, if the computed value of
/// `background-image` on the root element is `none` AND its `background-color` is `transparent`,
/// user agents **must propagate** the computed values of the background properties from the
/// first `<body>` child element to the root element.
///
/// This behavior exists for backwards compatibility with older HTML where backgrounds were
/// typically set on `<body>` using `bgcolor` attributes, and ensures that the `<body>`
/// background covers the entire viewport/canvas even when `<body>` itself has constrained
/// dimensions.
///
/// Implementation: When requesting the background of an `<html>` node, we first check if it
/// has a transparent background with no image. If so, we look for a `<body>` child and use
/// its background instead.
#[allow(clippy::match_same_arms)]
// enum/value mapping/dispatch table: one arm per input variant (or cross-type bindings that can't
// merge)
#[must_use]
101009
pub fn get_background_color(
101009
    styled_dom: &StyledDom,
101009
    node_id: NodeId,
101009
    node_state: &StyledNodeState,
101009
) -> ColorU {
101009
    let node_data = &styled_dom.node_data.as_container()[node_id];
101009
    let cache = &styled_dom.css_property_cache.ptr;
    // Fast path: Get this node's background.
    // Negative fast path: if compact cache says `has_background == 0` on a
    // normal-state node, skip the cascade walk entirely. Only declared backgrounds
    // set the bit, so `false` is a safe "unconditionally transparent" signal.
103584
    let get_node_bg = |nid: NodeId, ndata: &azul_core::dom::NodeData, state: &StyledNodeState| {
103584
        if state.is_normal() {
103529
            if let Some(ref cc) = cache.compact_cache {
103528
                if !cc.has_background(nid.index()) {
100343
                    return None;
3185
                }
1
            }
55
        }
3241
        cache
3241
            .get_background_content(ndata, &nid, state)
3241
            .and_then(|bg| bg.get_property())
3241
            .and_then(|bg_vec| bg_vec.get(0).cloned())
3241
            .and_then(|first_bg| match &first_bg {
3170
                azul_css::props::style::StyleBackgroundContent::Color(color) => Some(*color),
                azul_css::props::style::StyleBackgroundContent::Image(_) => None, // Has image, not transparent
20
                _ => None,
3190
            })
103584
    };
101009
    let own_bg = get_node_bg(node_id, node_data, node_state);
    // CSS Background Propagation: Special handling for <html> root element
    // Only check propagation if this is an Html node AND has transparent background (no
    // color/image)
101009
    if !matches!(node_data.node_type, NodeType::Html) || own_bg.is_some() {
        // Not Html or has its own background - return own background or transparent
98404
        return own_bg.unwrap_or(ColorU {
98404
            r: 0,
98404
            g: 0,
98404
            b: 0,
98404
            a: 0,
98404
        });
2605
    }
    // Html node with transparent background - check if we should propagate from <body>
2605
    let first_child = styled_dom
2605
        .node_hierarchy
2605
        .as_container()
2605
        .get(node_id)
2605
        .and_then(|node| node.first_child_id(node_id));
2605
    let Some(first_child) = first_child else {
        return ColorU {
            r: 0,
            g: 0,
            b: 0,
            a: 0,
        };
    };
2605
    let first_child_data = &styled_dom.node_data.as_container()[first_child];
    // Check if first child is <body>
2605
    if !matches!(first_child_data.node_type, NodeType::Body) {
30
        return ColorU {
30
            r: 0,
30
            g: 0,
30
            b: 0,
30
            a: 0,
30
        };
2575
    }
    // Propagate <body>'s background to <html> (canvas)
2575
    let first_child_state = &styled_dom.styled_nodes.as_container()[first_child].styled_node_state;
2575
    get_node_bg(first_child, first_child_data, first_child_state).unwrap_or(ColorU {
2575
        r: 0,
2575
        g: 0,
2575
        b: 0,
2575
        a: 0,
2575
    })
101009
}
/// Returns all background content layers for a node (colors, gradients, images).
/// This is used for rendering backgrounds that may include linear/radial/conic gradients.
///
/// CSS Background Propagation (CSS Backgrounds 3, Section 2.11.2):
/// For HTML documents, if the root `<html>` element has no background (transparent with no image),
/// propagate the background from the first `<body>` child element.
#[must_use]
1285629
pub fn get_background_contents(
1285629
    styled_dom: &StyledDom,
1285629
    node_id: NodeId,
1285629
    node_state: &StyledNodeState,
1285629
) -> Vec<azul_css::props::style::StyleBackgroundContent> {
    use azul_core::dom::NodeType;
    use azul_css::props::style::StyleBackgroundContent;
1285629
    let node_data = &styled_dom.node_data.as_container()[node_id];
1285629
    let cache = &styled_dom.css_property_cache.ptr;
    // Helper to get backgrounds for a node.
    // Negative fast path: if compact cache says `has_background == 0` on a normal
    // pseudo-state node, return empty without walking the cascade.
1285629
    let get_node_backgrounds = |nid: NodeId,
                                ndata: &azul_core::dom::NodeData,
                                state: &StyledNodeState|
1308888
     -> Vec<StyleBackgroundContent> {
1308888
        if state.is_normal() {
1308567
            if let Some(ref cc) = cache.compact_cache {
1308566
                if !cc.has_background(nid.index()) {
955727
                    return Vec::new();
352839
                }
1
            }
321
        }
353161
        cache
353161
            .get_background_content(ndata, &nid, state)
353161
            .and_then(|bg| bg.get_property())
353161
            .map(|bg_vec| bg_vec.iter().cloned().collect())
353161
            .unwrap_or_default()
1308888
    };
1285629
    let own_backgrounds = get_node_backgrounds(node_id, node_data, node_state);
    // CSS Background Propagation: Special handling for <html> root element
    // Only check propagation if this is an Html node AND has no backgrounds
1285629
    if !matches!(node_data.node_type, NodeType::Html) || !own_backgrounds.is_empty() {
1262340
        return own_backgrounds;
23289
    }
    // Html node with no backgrounds - check if we should propagate from <body>
23289
    let first_child = styled_dom
23289
        .node_hierarchy
23289
        .as_container()
23289
        .get(node_id)
23289
        .and_then(|node| node.first_child_id(node_id));
23289
    let Some(first_child) = first_child else {
        return own_backgrounds;
    };
23289
    let first_child_data = &styled_dom.node_data.as_container()[first_child];
    // Check if first child is <body>
23289
    if !matches!(first_child_data.node_type, NodeType::Body) {
30
        return own_backgrounds;
23259
    }
    // Propagate <body>'s backgrounds to <html> (canvas)
23259
    let first_child_state = &styled_dom.styled_nodes.as_container()[first_child].styled_node_state;
23259
    get_node_backgrounds(first_child, first_child_data, first_child_state)
1285629
}
/// Information about border rendering
#[derive(Copy, Clone, Debug)]
pub struct BorderInfo {
    pub widths: crate::solver3::display_list::StyleBorderWidths,
    pub colors: crate::solver3::display_list::StyleBorderColors,
    pub styles: crate::solver3::display_list::StyleBorderStyles,
}
#[allow(clippy::too_many_lines)] // large but cohesive: single-purpose layout/render/parse routine (one branch per case)
#[must_use]
1315328
pub fn get_border_info(
1315328
    styled_dom: &StyledDom,
1315328
    node_id: NodeId,
1315328
    node_state: &StyledNodeState,
1315328
) -> BorderInfo {
    use azul_css::{
        css::CssPropertyValue,
        props::{
            basic::{color::ColorU, pixel::PixelValue},
            style::{
                border::{
                    BorderStyle, StyleBorderBottomColor, StyleBorderBottomStyle,
                    StyleBorderLeftColor, StyleBorderLeftStyle, StyleBorderRightColor,
                    StyleBorderRightStyle, StyleBorderTopColor, StyleBorderTopStyle,
                },
                LayoutBorderBottomWidth, LayoutBorderLeftWidth, LayoutBorderRightWidth,
                LayoutBorderTopWidth,
            },
        },
    };
    use crate::solver3::display_list::{StyleBorderColors, StyleBorderStyles, StyleBorderWidths};
    // FAST PATH: compact cache for normal state
1315328
    if node_state.is_normal() {
1315127
        if let Some(ref cc) = styled_dom.css_property_cache.ptr.compact_cache {
1315125
            let idx = node_id.index();
            // Border widths: decode from compact i16 (resolved px × 10).
            // Previously this block called the slow convenience getters
            // despite being in the "fast path" branch — 2014 slow walks
            // per width × 4 widths per cold excel.html layout. Fixed
            // 2026-04-17.
5260500
            let make_width_px = |raw: i16| -> Option<PixelValue> {
5260500
                if raw == azul_css::compact_cache::I16_AUTO
5260500
                    || raw == azul_css::compact_cache::I16_INITIAL
5260500
                    || raw >= azul_css::compact_cache::I16_SENTINEL_THRESHOLD
                {
                    None
                } else {
5260500
                    Some(PixelValue::px(f32::from(raw) / 10.0))
                }
5260500
            };
1315125
            let widths = StyleBorderWidths {
1315125
                top: make_width_px(cc.get_border_top_width_raw(idx))
1315125
                    .map(|px| CssPropertyValue::Exact(LayoutBorderTopWidth { inner: px })),
1315125
                right: make_width_px(cc.get_border_right_width_raw(idx))
1315125
                    .map(|px| CssPropertyValue::Exact(LayoutBorderRightWidth { inner: px })),
1315125
                bottom: make_width_px(cc.get_border_bottom_width_raw(idx))
1315125
                    .map(|px| CssPropertyValue::Exact(LayoutBorderBottomWidth { inner: px })),
1315125
                left: make_width_px(cc.get_border_left_width_raw(idx))
1315125
                    .map(|px| CssPropertyValue::Exact(LayoutBorderLeftWidth { inner: px })),
            };
            // Border colors from compact cache.
            //
            // SENTINEL COLLISION: the cache packs RGBA into one u32 and uses
            // raw == 0 as "unset" — which is the same encoding as explicit
            // transparent black {0,0,0,0}. Both therefore decode to `None`.
            // That is safe ONLY because every consumer treats a missing
            // border color as "paint nothing" (see the transparent
            // `default_color` in cpurender/raster.rs); do not map `None`
            // to any visible color downstream.
5260500
            let make_color = |raw: u32| -> Option<ColorU> {
5260500
                if raw == 0 {
5103688
                    None
                } else {
156812
                    Some(ColorU {
156812
                        r: ((raw >> 24) & 0xFF) as u8,
156812
                        g: ((raw >> 16) & 0xFF) as u8,
156812
                        b: ((raw >> 8) & 0xFF) as u8,
156812
                        a: (raw & 0xFF) as u8,
156812
                    })
                }
5260500
            };
1315125
            let colors = StyleBorderColors {
1315125
                top: make_color(cc.get_border_top_color_raw(idx))
1315125
                    .map(|c| CssPropertyValue::Exact(StyleBorderTopColor { inner: c })),
1315125
                right: make_color(cc.get_border_right_color_raw(idx))
1315125
                    .map(|c| CssPropertyValue::Exact(StyleBorderRightColor { inner: c })),
1315125
                bottom: make_color(cc.get_border_bottom_color_raw(idx))
1315125
                    .map(|c| CssPropertyValue::Exact(StyleBorderBottomColor { inner: c })),
1315125
                left: make_color(cc.get_border_left_color_raw(idx))
1315125
                    .map(|c| CssPropertyValue::Exact(StyleBorderLeftColor { inner: c })),
            };
            // Border styles from compact cache
1315125
            let styles = StyleBorderStyles {
1315125
                top: Some(CssPropertyValue::Exact(StyleBorderTopStyle {
1315125
                    inner: cc.get_border_top_style(idx),
1315125
                })),
1315125
                right: Some(CssPropertyValue::Exact(StyleBorderRightStyle {
1315125
                    inner: cc.get_border_right_style(idx),
1315125
                })),
1315125
                bottom: Some(CssPropertyValue::Exact(StyleBorderBottomStyle {
1315125
                    inner: cc.get_border_bottom_style(idx),
1315125
                })),
1315125
                left: Some(CssPropertyValue::Exact(StyleBorderLeftStyle {
1315125
                    inner: cc.get_border_left_style(idx),
1315125
                })),
1315125
            };
1315125
            return BorderInfo {
1315125
                widths,
1315125
                colors,
1315125
                styles,
1315125
            };
2
        }
201
    }
    // SLOW PATH: full cascade
203
    let node_data = &styled_dom.node_data.as_container()[node_id];
    // Get all border widths
203
    let widths = StyleBorderWidths {
203
        top: styled_dom
203
            .css_property_cache
203
            .ptr
203
            .get_border_top_width(node_data, &node_id, node_state)
203
            .copied(),
203
        right: styled_dom
203
            .css_property_cache
203
            .ptr
203
            .get_border_right_width(node_data, &node_id, node_state)
203
            .copied(),
203
        bottom: styled_dom
203
            .css_property_cache
203
            .ptr
203
            .get_border_bottom_width(node_data, &node_id, node_state)
203
            .copied(),
203
        left: styled_dom
203
            .css_property_cache
203
            .ptr
203
            .get_border_left_width(node_data, &node_id, node_state)
203
            .copied(),
203
    };
    // Get all border colors
203
    let colors = StyleBorderColors {
203
        top: styled_dom
203
            .css_property_cache
203
            .ptr
203
            .get_border_top_color(node_data, &node_id, node_state)
203
            .copied(),
203
        right: styled_dom
203
            .css_property_cache
203
            .ptr
203
            .get_border_right_color(node_data, &node_id, node_state)
203
            .copied(),
203
        bottom: styled_dom
203
            .css_property_cache
203
            .ptr
203
            .get_border_bottom_color(node_data, &node_id, node_state)
203
            .copied(),
203
        left: styled_dom
203
            .css_property_cache
203
            .ptr
203
            .get_border_left_color(node_data, &node_id, node_state)
203
            .copied(),
203
    };
    // Get all border styles
203
    let styles = StyleBorderStyles {
203
        top: styled_dom
203
            .css_property_cache
203
            .ptr
203
            .get_border_top_style(node_data, &node_id, node_state)
203
            .copied(),
203
        right: styled_dom
203
            .css_property_cache
203
            .ptr
203
            .get_border_right_style(node_data, &node_id, node_state)
203
            .copied(),
203
        bottom: styled_dom
203
            .css_property_cache
203
            .ptr
203
            .get_border_bottom_style(node_data, &node_id, node_state)
203
            .copied(),
203
        left: styled_dom
203
            .css_property_cache
203
            .ptr
203
            .get_border_left_style(node_data, &node_id, node_state)
203
            .copied(),
203
    };
203
    BorderInfo {
203
        widths,
203
        colors,
203
        styles,
203
    }
1315328
}
/// Convert `BorderInfo` to `InlineBorderInfo` for inline elements
///
/// This resolves the CSS property values to concrete pixel values and colors
/// that can be used during text rendering.
#[allow(clippy::too_many_lines)] // large but cohesive: single-purpose layout/render/parse routine
                                 // (one branch per case)
81438
fn get_inline_border_info(
81438
    styled_dom: &StyledDom,
81438
    node_id: NodeId,
81438
    node_state: &StyledNodeState,
81438
    border_info: &BorderInfo,
81438
    viewport: PhysicalSize,
81438
) -> Option<crate::text3::cache::InlineBorderInfo> {
    use crate::text3::cache::InlineBorderInfo;
    // Fetch padding values for inline elements. Viewport units (vw/vh/...) resolve
    // against the real viewport instead of being treated as raw pixels.
325752
    fn resolve_padding(mv: MultiValue<PixelValue>, viewport: PhysicalSize) -> f32 {
325752
        match mv {
325752
            MultiValue::Exact(pv) => super::calc::resolve_pixel_value_with_viewport(
325752
                &pv,
                0.0,
                DEFAULT_FONT_SIZE,
                DEFAULT_FONT_SIZE,
325752
                viewport.width,
325752
                viewport.height,
            ),
            _ => 0.0,
        }
325752
    }
    macro_rules! border_width_px {
        ($field:expr) => {
            $field
                .as_ref()
325752
                .and_then(|v| v.get_property())
325752
                .map(|w| w.inner.number.get())
                .unwrap_or(0.0)
        };
    }
    macro_rules! border_color {
        ($field:expr) => {
            $field
                .as_ref()
48
                .and_then(|v| v.get_property())
                .map(|c| c.inner)
                .unwrap_or(ColorU::BLACK)
        };
    }
    // Extract border-radius (simplified - uses the average of all corners if uniform)
32
    fn get_border_radius_px(
32
        styled_dom: &StyledDom,
32
        node_id: NodeId,
32
        node_state: &StyledNodeState,
32
    ) -> Option<f32> {
32
        let node_data = &styled_dom.node_data.as_container()[node_id];
32
        let top_left = styled_dom
32
            .css_property_cache
32
            .ptr
32
            .get_border_top_left_radius(node_data, &node_id, node_state)
32
            .and_then(|br| br.get_property().copied())
32
            .map(|v| v.inner.number.get());
32
        let top_right = styled_dom
32
            .css_property_cache
32
            .ptr
32
            .get_border_top_right_radius(node_data, &node_id, node_state)
32
            .and_then(|br| br.get_property().copied())
32
            .map(|v| v.inner.number.get());
32
        let bottom_left = styled_dom
32
            .css_property_cache
32
            .ptr
32
            .get_border_bottom_left_radius(node_data, &node_id, node_state)
32
            .and_then(|br| br.get_property().copied())
32
            .map(|v| v.inner.number.get());
32
        let bottom_right = styled_dom
32
            .css_property_cache
32
            .ptr
32
            .get_border_bottom_right_radius(node_data, &node_id, node_state)
32
            .and_then(|br| br.get_property().copied())
32
            .map(|v| v.inner.number.get());
        // If any radius is defined, use the maximum (for inline, uniform radius is most common)
32
        let radii: Vec<f32> = [top_left, top_right, bottom_left, bottom_right]
32
            .into_iter()
32
            .flatten()
32
            .collect();
32
        if radii.is_empty() {
32
            None
        } else {
            Some(radii.into_iter().fold(0.0f32, f32::max))
        }
32
    }
81438
    let top = border_width_px!(&border_info.widths.top);
81438
    let right = border_width_px!(&border_info.widths.right);
81438
    let bottom = border_width_px!(&border_info.widths.bottom);
81438
    let left = border_width_px!(&border_info.widths.left);
81438
    let p_top = resolve_padding(
81438
        get_css_padding_top(styled_dom, node_id, node_state),
81438
        viewport,
    );
81438
    let p_right = resolve_padding(
81438
        get_css_padding_right(styled_dom, node_id, node_state),
81438
        viewport,
    );
81438
    let p_bottom = resolve_padding(
81438
        get_css_padding_bottom(styled_dom, node_id, node_state),
81438
        viewport,
    );
81438
    let p_left = resolve_padding(
81438
        get_css_padding_left(styled_dom, node_id, node_state),
81438
        viewport,
    );
    // Only return Some if there's actually a border or padding
81438
    let has_border = top > 0.0 || right > 0.0 || bottom > 0.0 || left > 0.0;
81438
    let has_padding = p_top > 0.0 || p_right > 0.0 || p_bottom > 0.0 || p_left > 0.0;
81438
    if !has_border && !has_padding {
81406
        return None;
32
    }
    // CSS 2.2 §8.6: detect direction for visual-order border/padding rendering in bidi
32
    let is_rtl = matches!(
32
        get_direction_property(styled_dom, node_id, node_state),
        MultiValue::Exact(StyleDirection::Rtl)
    );
32
    Some(InlineBorderInfo {
32
        top,
32
        right,
32
        bottom,
32
        left,
32
        top_color: border_color!(&border_info.colors.top),
32
        right_color: border_color!(&border_info.colors.right),
32
        bottom_color: border_color!(&border_info.colors.bottom),
32
        left_color: border_color!(&border_info.colors.left),
32
        radius: get_border_radius_px(styled_dom, node_id, node_state),
32
        padding_top: p_top,
32
        padding_right: p_right,
32
        padding_bottom: p_bottom,
32
        padding_left: p_left,
32
        is_first_fragment: true,
32
        is_last_fragment: true,
32
        is_rtl,
32
    })
81438
}
// Selection and Caret Styling
/// Style information for text selection rendering
#[derive(Debug, Clone, Copy, Default)]
pub struct SelectionStyle {
    /// Background color of the selection highlight
    pub bg_color: ColorU,
    /// Text color when selected (overrides normal text color).
    ///
    /// `None` means "no authority said anything" — neither
    /// `-azul-selection-color` nor the system style — and the painter must then
    /// leave the glyph's normal colour alone. Use [`Self::text_color_or`]
    /// rather than testing this field, so that rule lives in one place.
    pub text_color: Option<ColorU>,
    /// Border radius for selection rectangles
    pub radius: f32,
}
impl SelectionStyle {
    /// The colour to paint a glyph that falls INSIDE the selection, given the
    /// colour it would otherwise have.
    ///
    /// The selection painter draws `bg_color` behind the glyphs, so with an
    /// opaque system highlight the unrecoloured glyphs are dark-on-dark; the
    /// text pass has to apply this to every glyph covered by a selection rect
    /// (see `HANDOFF-text-fix.md` — `paint_inline_content`).
    #[must_use]
2
    pub fn text_color_or(&self, normal: ColorU) -> ColorU {
2
        self.text_color.unwrap_or(normal)
2
    }
}
/// Get selection style for a node
#[must_use]
1993
pub fn get_selection_style(
1993
    styled_dom: &StyledDom,
1993
    node_id: Option<NodeId>,
1993
    system_style: Option<&std::sync::Arc<azul_css::system::SystemStyle>>,
1993
) -> SelectionStyle {
1993
    let Some(node_id) = node_id else {
1
        return SelectionStyle::default();
    };
1992
    let node_data = &styled_dom.node_data.as_container()[node_id];
1992
    let node_state = &StyledNodeState::default();
    // Try to get selection background from CSS, otherwise use system color, otherwise hard-coded
    // default
1992
    let default_bg = system_style
1992
        .and_then(|ss| ss.colors.selection_background.as_option().copied())
1992
        .unwrap_or(ColorU {
1992
            r: 51,
1992
            g: 153,
1992
            b: 255, // Standard blue selection color
1992
            a: 128, // Semi-transparent
1992
        });
1992
    let bg_color = styled_dom
1992
        .css_property_cache
1992
        .ptr
1992
        .get_selection_background_color(node_data, &node_id, node_state)
1992
        .and_then(|c| c.get_property().copied())
1992
        .map_or(default_bg, |c| c.inner);
    // Try to get selection text color from CSS, otherwise use system color
1992
    let default_text = system_style.and_then(|ss| ss.colors.selection_text.as_option().copied());
1992
    let text_color = styled_dom
1992
        .css_property_cache
1992
        .ptr
1992
        .get_selection_color(node_data, &node_id, node_state)
1992
        .and_then(|c| c.get_property().copied())
1992
        .map(|c| c.inner)
1992
        .or(default_text);
1992
    let radius = styled_dom
1992
        .css_property_cache
1992
        .ptr
1992
        .get_selection_radius(node_data, &node_id, node_state)
1992
        .and_then(|r| r.get_property().copied())
1992
        .map_or(0.0, |r| {
            r.inner
                .to_pixels_internal(0.0, DEFAULT_EM_SIZE, DEFAULT_EM_SIZE)
        });
1992
    SelectionStyle {
1992
        bg_color,
1992
        text_color,
1992
        radius,
1992
    }
1993
}
/// Style information for caret rendering.
#[derive(Debug, Clone, Copy)]
pub struct CaretStyle {
    /// Color of the caret bar
    pub color: ColorU,
    /// Width of the caret bar in pixels
    pub width: f32,
    /// Blink animation duration (0 = no blink).
    ///
    /// A [`CssDuration`], not a bare millisecond count, so a stylesheet written
    /// in the clockless `t` unit (`caret-animation-duration: 5t`) keeps its FRAME
    /// count all the way to the blink timer. Flattening it to milliseconds here
    /// would silently reintroduce wall-clock rounding.
    pub animation_duration: CssDuration,
}
impl Default for CaretStyle {
2
    fn default() -> Self {
2
        Self {
2
            color: ColorU::BLACK,
2
            width: DEFAULT_CARET_WIDTH_PX,
2
            animation_duration: CssDuration::from_millis(DEFAULT_CARET_BLINK_MS),
2
        }
2
    }
}
/// Get caret style for a node
#[must_use]
7298
pub fn get_caret_style(styled_dom: &StyledDom, node_id: Option<NodeId>) -> CaretStyle {
7298
    let Some(node_id) = node_id else {
2
        return CaretStyle::default();
    };
7296
    let node_data = &styled_dom.node_data.as_container()[node_id];
7296
    let node_state = &StyledNodeState::default();
7296
    let color = styled_dom
7296
        .css_property_cache
7296
        .ptr
7296
        .get_caret_color(node_data, &node_id, node_state)
7296
        .and_then(|c| c.get_property().copied())
        // CSS `caret-color: auto` (the initial value) resolves to currentColor — the
        // element's text color — which by construction contrasts with the background.
        // Falling back to BLACK made the caret invisible on dark backgrounds / dark
        // system themes (and `color` IS inherited while `caret-color` may not be, so a
        // child text node still gets the right colour here).
7296
        .map_or_else(|| {
7296
            styled_dom
7296
                .css_property_cache
7296
                .ptr
7296
                .get_text_color_or_default(node_data, &node_id, node_state)
7296
                .inner
7296
        }, |c| c.inner);
7296
    let width = styled_dom
7296
        .css_property_cache
7296
        .ptr
7296
        .get_caret_width(node_data, &node_id, node_state)
7296
        .and_then(|w| w.get_property().copied())
7296
        .map_or(DEFAULT_CARET_WIDTH_PX, |w| {
            w.inner
                .to_pixels_internal(0.0, DEFAULT_EM_SIZE, DEFAULT_EM_SIZE)
        });
    // Bound first so the fallback is neither a lazy closure nor an inline call
    // in `map_or` — both shapes trip a clippy lint, and neither reads better.
7296
    let default_blink = CssDuration::from_millis(DEFAULT_CARET_BLINK_MS);
7296
    let animation_duration = styled_dom
7296
        .css_property_cache
7296
        .ptr
7296
        .get_caret_animation_duration(node_data, &node_id, node_state)
7296
        .and_then(|d| d.get_property().copied())
7296
        .map_or(default_blink, |d| d.inner);
7296
    CaretStyle {
7296
        color,
7296
        width,
7296
        animation_duration,
7296
    }
7298
}
// Scrollbar Information
/// Get scrollbar information from a layout node.
///
/// Scrollbar requirements are computed during the layout phase in two paths:
/// - BFC layout: `compute_scrollbar_info()` in cache.rs
/// - Taffy layout: set in the measure callback in `taffy_bridge.rs`
///
/// If neither path set `scrollbar_info`, the node genuinely does not need
/// scrollbars. The previous heuristic (>3 children = force overflow) caused
/// false-positive scrollbars on normal containers.
#[must_use]
2
pub fn get_scrollbar_info_from_layout(node: &LayoutNode) -> ScrollbarRequirements {
2
    node.scrollbar_info.unwrap_or_default()
2
}
/// Resolve the **layout-effective** scrollbar width for a node, in pixels.
///
/// This combines three inputs:
/// 1. CSS `scrollbar-width` property on the node (`auto` → 16, `thin` → 8, `none` → 0)
/// 2. OS-level `ScrollbarPreferences.visibility` (overlay scrollbars → 0 layout reservation)
/// 3. Custom `-azul-scrollbar-style` width override
///
/// For **overlay** scrollbars (macOS `WhenScrolling`, or equivalent), this returns `0.0`
/// because overlay scrollbars are painted on top of content and do not consume layout space.
/// The scrollbar is still *rendered*, but no space is reserved during layout.
// +spec:overflow:b83014 - overlay scrollbars do not create scrollbar gutters
///
/// During display-list generation, use `get_scrollbar_style()` instead — that returns
/// the full visual style including the *paint* width (which may be non-zero for overlay).
174
pub fn get_layout_scrollbar_width_px<T: ParsedFontTrait>(
174
    ctx: &crate::solver3::LayoutContext<'_, T>,
174
    dom_id: NodeId,
174
    styled_node_state: &StyledNodeState,
174
) -> f32 {
    // Resolve the full scrollbar style (includes per-node CSS overrides + system style).
    // `reserve_width_px` already accounts for overlay vs legacy:
    //   overlay (WhenScrolling) → 0.0
    //   legacy (Always)         → visual_width_px
174
    let style = get_scrollbar_style(
174
        ctx.styled_dom,
174
        dom_id,
174
        styled_node_state,
174
        ctx.system_style.as_deref(),
    );
174
    style.reserve_width_px
174
}
get_css_property!(
    get_display_property_internal,
    get_display,
    LayoutDisplay,
    CssPropertyType::Display,
    compact = get_display
);
#[must_use]
6977034
pub fn get_display_property(
6977034
    styled_dom: &StyledDom,
6977034
    dom_id: Option<NodeId>,
6977034
) -> MultiValue<LayoutDisplay> {
6977034
    let Some(id) = dom_id else {
242
        return MultiValue::Exact(LayoutDisplay::Inline);
    };
6976792
    let node_state = &styled_dom.styled_nodes.as_container()[id].styled_node_state;
6976792
    get_display_property_internal(styled_dom, id, node_state)
6977034
}
/// CSS Display Module Level 3: Blockification of display values.
///
/// When an element is floated, absolutely positioned, or is the root element,
/// its computed display value may be "blockified" per the table in CSS Display 3 §2.7.
/// This function returns the blockified display value without mutating any state.
#[allow(clippy::match_same_arms)]
// enum/value mapping/dispatch table: one arm per input variant (or cross-type bindings that can't
// merge)
#[must_use]
131171
pub const fn blockify_display(raw_display: LayoutDisplay) -> LayoutDisplay {
131171
    match raw_display {
        // Inline-level display types become their block-level equivalents
5683
        LayoutDisplay::Inline => LayoutDisplay::Block,
        // Per CSS Display 3 §2.7: inline-block blockifies to block
        // (for legacy reasons, loses its flow-root nature)
15744
        LayoutDisplay::InlineBlock => LayoutDisplay::Block,
32
        LayoutDisplay::InlineFlex => LayoutDisplay::Flex,
32
        LayoutDisplay::InlineTable => LayoutDisplay::Table,
32
        LayoutDisplay::InlineGrid => LayoutDisplay::Grid,
        // CSS 2.2 §9.7: table-internal display values blockify to block
        // for absolutely positioned, floated, or root elements
        LayoutDisplay::TableRowGroup
        | LayoutDisplay::TableColumn
        | LayoutDisplay::TableColumnGroup
        | LayoutDisplay::TableHeaderGroup
        | LayoutDisplay::TableFooterGroup
        | LayoutDisplay::TableRow
        | LayoutDisplay::TableCell
259
        | LayoutDisplay::TableCaption => LayoutDisplay::Block,
        // css-display-3 §2.7: run-in blockifies to block.
32
        LayoutDisplay::RunIn => LayoutDisplay::Block,
        // Already block-level types are unchanged. NOTE: `display: contents`
        // on the ROOT element must compute to `block` (css-display-3 §2.5) -
        // that special case is the CALLER's to apply, since only it knows
        // whether the node is the root; for non-root elements `contents`
        // must pass through untouched.
109357
        other => other,
    }
131171
}
// +spec:positioning:c31c24 - blockification is a computed-value change for absolute/float/root
// elements
/// Resolves the computed display value for an element, applying blockification
/// rules per CSS Display Module Level 3 §2.7.
// +spec:display-property:641ac5 - computed display value applies blockification/inlinification (not
// "as specified")
///
/// This centralizes the blockification decision so that all layout phases
/// (`layout_tree`, sizing, positioning) use consistent display values.
// +spec:floats:52aea6 - computed display blockified for floated/positioned/root elements
// +spec:positioning:ce02a1 - out-of-flow boxes (floated or absolutely positioned) get blockified
// display four independent layout-state flags drive the blockification decision; bundling them
// into a struct would add ceremony without clarifying this pure decision function.
#[allow(clippy::fn_params_excessive_bools)]
#[must_use]
230943
pub fn get_computed_display(
230943
    raw_display: LayoutDisplay,
230943
    is_absolute_or_fixed: bool,
230943
    is_floated: bool,
230943
    is_root: bool,
230943
    is_flex_grid_child: bool,
230943
) -> LayoutDisplay {
230943
    if raw_display == LayoutDisplay::None {
17
        return LayoutDisplay::None;
230926
    }
    // +spec:positioning:69468c - absolute/fixed blockifies the box
230926
    if is_absolute_or_fixed || is_floated || is_root || is_flex_grid_child {
130772
        blockify_display(raw_display)
    } else {
100154
        raw_display
    }
230943
}
// +spec:font-metrics:f7affa - vertical-align shorthand: maps CSS vertical-align values to inline
// layout alignment
/// Reads the CSS `vertical-align` property for a DOM node and converts it to
/// the text3 `VerticalAlign` enum used during inline layout.
// +spec:display-property:24c160 - vertical-align aligns inline-level box within the line
#[must_use]
83649
pub fn get_vertical_align_for_node(
83649
    styled_dom: &StyledDom,
83649
    dom_id: NodeId,
83649
) -> crate::text3::cache::VerticalAlign {
83649
    let node_state = &styled_dom.styled_nodes.as_container()[dom_id].styled_node_state;
83649
    let va = match get_vertical_align_property(styled_dom, dom_id, node_state) {
20
        MultiValue::Exact(v) => v,
83629
        _ => StyleVerticalAlign::default(),
    };
83649
    match va {
83629
        StyleVerticalAlign::Baseline => crate::text3::cache::VerticalAlign::Baseline,
        StyleVerticalAlign::Top => crate::text3::cache::VerticalAlign::Top,
        StyleVerticalAlign::Middle => crate::text3::cache::VerticalAlign::Middle,
        StyleVerticalAlign::Bottom => crate::text3::cache::VerticalAlign::Bottom,
10
        StyleVerticalAlign::Sub => crate::text3::cache::VerticalAlign::Sub,
10
        StyleVerticalAlign::Superscript => crate::text3::cache::VerticalAlign::Super,
        StyleVerticalAlign::TextTop => crate::text3::cache::VerticalAlign::TextTop,
        StyleVerticalAlign::TextBottom => crate::text3::cache::VerticalAlign::TextBottom,
        // +spec:line-height:b41ee3 - percentage vertical-align: raise/lower by % of line-height, 0%
        // = baseline
        StyleVerticalAlign::Percentage(p) => {
            let font_size = get_element_font_size(styled_dom, dom_id, node_state);
            // Line-height uses the parser convention (see `get_line_height_value` /
            // the LineHeight::Px path): a NEGATIVE normalized value is an absolute
            // px length, a positive one is a unitless multiple of font-size. The
            // old `normalized() * font_size` scaled (and sign-flipped) absolute
            // line-heights — e.g. `line-height: 30px` + `vertical-align: 50%` gave
            // -240px instead of +15px.
            let line_height = get_line_height_value(styled_dom, dom_id, node_state).map_or(
                font_size * 1.2,
                |lh| {
                    let n = lh.inner.normalized();
                    if n < 0.0 {
                        -n
                    } else {
                        n * font_size
                    }
                },
            );
            crate::text3::cache::VerticalAlign::Offset(p.normalized() * line_height)
        }
        // §10.8.1: <length> is absolute offset from baseline
        StyleVerticalAlign::Length(l) => {
            let font_size = get_element_font_size(styled_dom, dom_id, node_state);
            // TODO(superplan): viewport units (vw/vh/...) in a vertical-align <length>
            // fall back to raw pixels here because this getter has no viewport ctx.
            // Threading `viewport_size` requires changing this fn's signature, but one
            // of its callers (`sizing.rs::process_layout_children`) lives outside
            // Group 2's file ownership — deferred. (The sibling path in
            // fc.rs::translate_to_text3_constraints already resolves it via
            // `resolve_pixel_value_with_viewport`.)
            let px = super::calc::resolve_pixel_value(&l, 0.0, font_size, font_size);
            crate::text3::cache::VerticalAlign::Offset(px)
        }
    }
83649
}
/// Per-document memo for [`get_style_properties`], owned by
/// [`crate::solver3::LayoutContext`].
///
/// Keyed on everything that can change the answer for a node: its index,
/// its `StyledNodeState` (`:hover`/`:focus`/`:disabled` select different
/// declarations) and the viewport (`vw`/`vh` and percentages resolve
/// against it). The DOCUMENT is not part of the key because the cache
/// belongs to one — see the field docs for why that matters.
/// Per-document memo for [`get_style_properties_cached`].
///
/// TWO maps on purpose. `by_node` answers "what is this node's style?" and
/// `by_value` answers "has anyone already built this exact style?".
///
/// With only the first, every node got its OWN `Arc` even when the computed
/// style was byte-identical — sharing by PRODUCER IDENTITY rather than by
/// RESULT VALUE. Measured before this: 672 distinct `Arc<StyleProperties>`
/// backing 31,086 glyphs on one markdown document, where the document has
/// on the order of ten distinct text styles. Stylo shipped the same defect
/// (109k `ComputedValues` where 2,200 were expected) and it is invisible
/// without counting the pointers, which is what `AZ_PROFILE=memory` now
/// does.
#[derive(Default, Debug)]
pub struct StyleCache {
    /// Key: (node, pseudo-state, viewport w/h bits, cascade epoch). The epoch
    /// (`CssPropertyCache::cascade_epoch`) makes a restyle, a context change
    /// or a user override within one pass miss instead of serving the style
    /// resolved before it.
    by_node: HashMap<(u32, StyledNodeState, u32, u32, u64), std::sync::Arc<StyleProperties>>,
    by_value: HashMap<u64, Vec<std::sync::Arc<StyleProperties>>>,
}
/// [`get_style_properties`], memoised in a caller-owned per-document cache
/// and shared behind an `Arc`.
///
/// The cache is passed separately from `styled_dom` rather than taking the
/// whole `LayoutContext`, so callers can hand over two disjoint fields of
/// the same context without a borrow conflict.
#[must_use]
212596
pub fn get_style_properties_cached(
212596
    cache: &mut StyleCache,
212596
    styled_dom: &StyledDom,
212596
    dom_id: NodeId,
212596
    system_style: Option<&std::sync::Arc<azul_css::system::SystemStyle>>,
212596
    viewport_size: PhysicalSize,
212596
) -> std::sync::Arc<StyleProperties> {
212596
    let node_state = styled_dom
212596
        .styled_nodes
212596
        .as_container()
212596
        .get(dom_id)
212596
        .map(|n| n.styled_node_state)
212596
        .unwrap_or_default();
212596
    let key = (
212596
        dom_id.index() as u32,
212596
        node_state,
212596
        viewport_size.width.to_bits(),
212596
        viewport_size.height.to_bits(),
212596
        styled_dom.get_css_property_cache().cascade_epoch,
212596
    );
212596
    if let Some(v) = cache.by_node.get(&key) {
134201
        drop(crate::probe::Probe::span("style_props_memo_hit"));
134201
        return std::sync::Arc::clone(v);
78395
    }
78395
    let _p = crate::probe::Probe::span("style_props_build");
78395
    let built = get_style_properties(styled_dom, dom_id, system_style, viewport_size);
    // Share by VALUE. Nodes that resolve to the same computed style get the
    // same allocation, so a thousand paragraphs cost one StyleProperties
    // rather than a thousand.
    //
    // The bucket is a Vec and the match is a real `==`, never the hash
    // alone: a 64-bit collision would otherwise hand two DIFFERENT styles
    // the same allocation and silently repaint text in the wrong font. The
    // Vec is length 1 in every non-colliding case.
78395
    let value_hash = {
        use core::hash::{Hash, Hasher};
78395
        let mut h = std::collections::hash_map::DefaultHasher::new();
78395
        built.hash(&mut h);
78395
        h.finish()
    };
78395
    let bucket = cache.by_value.entry(value_hash).or_default();
78395
    let shared = if let Some(existing) = bucket.iter().find(|existing| ***existing == built) {
61426
        drop(crate::probe::Probe::span("style_props_value_shared"));
61426
        std::sync::Arc::clone(existing)
    } else {
16969
        let fresh = std::sync::Arc::new(built);
16969
        bucket.push(std::sync::Arc::clone(&fresh));
16969
        fresh
    };
78395
    cache.by_node.insert(key, std::sync::Arc::clone(&shared));
78395
    shared
212596
}
#[allow(clippy::cast_possible_truncation)] // bounded graphics/coord/font/fixed-point/debug-marker cast
#[allow(clippy::too_many_lines, clippy::cognitive_complexity)] // large but cohesive: single-purpose layout/render/parse routine (one branch per case)
/// # Panics
///
/// Panics only on an internal indexing invariant (an in-range `get().unwrap()` over the font-family
/// list).
#[must_use]
82042
pub fn get_style_properties(
82042
    styled_dom: &StyledDom,
82042
    dom_id: NodeId,
82042
    system_style: Option<&std::sync::Arc<azul_css::system::SystemStyle>>,
82042
    viewport_size: PhysicalSize,
82042
) -> StyleProperties {
82042
    let node_state = styled_dom.styled_nodes.as_container()[dom_id].styled_node_state;
82042
    get_style_properties_for_state(styled_dom, dom_id, system_style, viewport_size, &node_state)
82042
}
/// [`get_style_properties`] resolved against an EXPLICIT pseudo-state rather
/// than the node's own.
///
/// The engine's `::placeholder` painter is the caller: the prompt is painted
/// GLYPHS, not a node, so no node's state can carry the pseudo-element.
/// Passing the state in lets the prompt's style come out of the SAME cascade
/// every other property uses, instead of a parallel lookup that would drift.
#[allow(clippy::cast_possible_truncation)] // bounded graphics/coord/font/fixed-point/debug-marker cast
#[allow(clippy::too_many_lines, clippy::cognitive_complexity)] // large but cohesive: single-purpose layout/render/parse routine (one branch per case)
/// # Panics
///
/// Panics only on an internal indexing invariant (an in-range `get().unwrap()` over the font-family
/// list).
82085
pub fn get_style_properties_for_state(
82085
    styled_dom: &StyledDom,
82085
    dom_id: NodeId,
82085
    system_style: Option<&std::sync::Arc<azul_css::system::SystemStyle>>,
82085
    viewport_size: PhysicalSize,
82085
    node_state: &StyledNodeState,
82085
) -> StyleProperties {
    use azul_css::props::basic::{PhysicalSize, PropertyContext, ResolutionContext};
82085
    let node_data = &styled_dom.node_data.as_container()[dom_id];
82085
    let cache = &styled_dom.css_property_cache.ptr;
    // Fast path: use compact cache reverse map (works for inherited values on text nodes).
    // Slow path: only for non-normal pseudo states (:hover, :focus, etc.)
82085
    let font_families = if node_state.is_normal() {
82042
        cache
82042
            .compact_cache
82042
            .as_ref()
82042
            .and_then(|cc| {
82042
                let fh = cc.tier2b_text[dom_id.index()].font_family_hash;
82042
                if fh == 0 {
18298
                    return None;
63744
                }
63744
                cc.font_hash_to_families.get(&fh).cloned()
82042
            })
82042
            .unwrap_or_else(|| {
18298
                StyleFontFamilyVec::from_vec(vec![StyleFontFamily::System("serif".into())])
18298
            })
    } else {
43
        cache
43
            .get_font_family(node_data, &dom_id, node_state)
43
            .and_then(|v| v.get_property().cloned())
43
            .unwrap_or_else(|| {
3
                StyleFontFamilyVec::from_vec(vec![StyleFontFamily::System("serif".into())])
3
            })
    };
    // Get parent's font-size for proper em resolution in font-size property.
    // FAST PATH: `get_parent_font_size` goes through `get_element_font_size`
    // which hits the memoised `resolved_font_sizes_px` Vec (O(1) array index).
    // The old code here walked the full CSS cascade for every call — 1485
    // slow walks per cold excel.html layout. Replaced 2026-04-17.
82085
    let parent_font_size = get_parent_font_size(styled_dom, dom_id, node_state);
82085
    let root_font_size = get_root_font_size(styled_dom, node_state);
    // Create resolution context for font-size (em refers to parent)
82085
    let font_size_context = ResolutionContext {
82085
        vertical_writing_mode: false,
82085
        element_font_size: DEFAULT_FONT_SIZE, /* Not used for font-size property */
82085
        parent_font_size,
82085
        root_font_size,
82085
        containing_block_size: PhysicalSize::new(0.0, 0.0),
82085
        element_size: None,
82085
        viewport_size,
82085
    };
    // Get font-size: either from this node's CSS, or inherit from parent
    // font-size is an inheritable property, so if the node doesn't have
    // an explicit font-size, it should inherit from the parent (not default to 16px)
82085
    let font_size = {
        // FAST PATH: compact cache for normal state.
        // Sentinel/inherit/initial → inherit from parent directly (which is
        // what the slow cascade walk would fall back to via `.unwrap_or(parent_font_size)`
        // anyway — avoid the walk entirely).
82085
        let mut fast_font_size: Option<f32> = None;
82085
        let mut compact_said_inherit = false;
82085
        if node_state.is_normal() {
82042
            if let Some(ref cc) = cache.compact_cache {
82042
                let raw = cc.get_font_size_raw(dom_id.index());
82042
                if raw == azul_css::compact_cache::U32_SENTINEL
82042
                    || raw == azul_css::compact_cache::U32_INHERIT
82042
                    || raw == azul_css::compact_cache::U32_INITIAL
10218
                {
10218
                    compact_said_inherit = true;
71824
                } else if let Some(pv) = azul_css::compact_cache::decode_pixel_value_u32(raw) {
71824
                    fast_font_size = Some(
71824
                        pv.resolve_with_context(&font_size_context, PropertyContext::FontSize),
71824
                    );
71824
                }
            }
43
        }
82085
        fast_font_size.unwrap_or_else(|| {
10261
            if compact_said_inherit {
10218
                parent_font_size
            } else {
43
                cache
43
                    .get_font_size(node_data, &dom_id, node_state)
43
                    .and_then(|v| v.get_property().copied())
43
                    .map_or(parent_font_size, |v| {
40
                        v.inner
40
                            .resolve_with_context(&font_size_context, PropertyContext::FontSize)
40
                    })
            }
10261
        })
    };
82085
    let color_from_cache = {
        // FAST PATH: compact cache for text color
82085
        let mut fast_color = None;
82085
        if node_state.is_normal() {
82042
            if let Some(ref cc) = cache.compact_cache {
82042
                let raw = cc.get_text_color_raw(dom_id.index());
82042
                if raw != 0 {
82042
                    // Decode 0xRRGGBBAA → ColorU
82042
                    fast_color = Some(ColorU {
82042
                        r: (raw >> 24) as u8,
82042
                        g: (raw >> 16) as u8,
82042
                        b: (raw >> 8) as u8,
82042
                        a: raw as u8,
82042
                    });
82042
                }
            }
43
        }
82085
        fast_color.or_else(|| {
43
            cache
43
                .get_text_color(node_data, &dom_id, node_state)
43
                .and_then(|v| v.get_property().copied())
43
                .map(|v| v.inner)
43
        })
    };
    // The UA's `color` default is THEMED and CASCADED (the root's
    // `cascaded_props`, every descendant's `computed_values`, the compact
    // text tier — `ua_css::get_ua_root_property_themed`), so on a cascaded
    // DOM one of the two reads above always answers. The seed below exists
    // for a cache no UA pass has run on, and asserts that it is one.
    // Do NOT use system_style.colors.text here — that reflects the OS theme
    // (e.g. white on macOS dark mode) and would produce white text on
    // explicitly light-colored backgrounds.  System colors (CanvasText etc.)
    // should only be used when referenced through CSS system-color keywords.
82085
    let color = color_from_cache.unwrap_or_else(|| {
        debug_assert!(
            !cache.ua_applied,
            "get_style_properties: node {} has no `color` in its resolved style although the UA \
             pass ran — the themed root default did not reach it (theme-chain analysis \
             2026-09-12, R1)",
            dom_id.index()
        );
        ColorU::BLACK
    });
    // +spec:font-metrics:e480da - line-height: normal/number/length/percentage resolution
82085
    let line_height = {
        // FAST PATH: compact cache for line-height (stored as normalized × 1000 i16).
        // When the cache returns Some → we have a resolved value.
        // When it returns None AND node_state is normal → the compact cache stored
        // the sentinel, which means "line-height: normal" (the spec default).
        // Previously we fell through to a cascade walk here — but the default
        // has already been authoritatively decided by the builder, so the walk
        // would only ever re-confirm "no value, normal". 1600 pure-waste walks
        // per cold excel.html layout. Short-circuit to Normal directly.
82085
        let mut fast_lh = None;
82085
        let mut sentinel_normal = false;
82085
        if node_state.is_normal() {
82042
            if let Some(ref cc) = cache.compact_cache {
82042
                if let Some(decoded) = cc.get_line_height(dom_id.index()) {
                    // get_line_height returns stored/10. The builder's split
                    // scale (see core/src/compact.rs): NEGATIVE = absolute px
                    // stored as -px x 10, so decoded == -px directly;
                    // positive = multiple x 1000, so decoded == multiple x 100.
4640
                    fast_lh = Some(crate::text3::cache::LineHeight::Px(if decoded < 0.0 {
870
                        -decoded
                    } else {
3770
                        (decoded / 100.0) * font_size
                    }));
77402
                } else {
77402
                    // Sentinel in compact cache = "normal" (CSS default).
77402
                    sentinel_normal = true;
77402
                }
            }
43
        }
82085
        if sentinel_normal {
77402
            crate::text3::cache::LineHeight::Normal
        } else {
4683
            fast_lh.unwrap_or_else(|| {
43
                cache
43
                    .get_line_height(node_data, &dom_id, node_state)
43
                    .and_then(|v| v.get_property().copied())
43
                    .map_or(crate::text3::cache::LineHeight::Normal, |v| {
                        // Negative normalized() = absolute px value (parser convention
                        // for "50px" etc.); positive = multiple of font-size.
                        let n = v.inner.normalized();
                        crate::text3::cache::LineHeight::Px(if n < 0.0 {
                            -n
                        } else {
                            n * font_size
                        })
                    })
43
            })
        }
    };
    // Get background color for INLINE elements only
    // CSS background-color is NOT inherited. For block-level elements (th, td, div, etc.),
    // the background is painted separately by paint_element_background() in display_list.rs.
    // Only inline elements (span, em, strong, a, etc.) should have their background color
    // propagated through StyleProperties for the text rendering pipeline.
    //
    // FAST PATH: use the compact-cache-backed display getter. The old code
    // here called `cache.get_display(..)` (the 3-arg convenience method on
    // CssPropertyCache) which routes through `get_property_slow` — 1485 slow
    // walks per cold excel.html layout. Replaced 2026-04-17.
82085
    let display = match get_display_property(styled_dom, Some(dom_id)) {
82085
        MultiValue::Exact(v) => v,
        _ => LayoutDisplay::Inline,
    };
    // For inline and inline-block elements, get background content and border info
    // Block elements have their backgrounds/borders painted by display_list.rs
82085
    let (background_color, background_content, border) =
82085
        if matches!(display, LayoutDisplay::Inline | LayoutDisplay::InlineBlock) {
81431
            let bg = get_background_color(styled_dom, dom_id, node_state);
81431
            let bg_color = if bg.a > 0 { Some(bg) } else { None };
            // Get full background contents (including gradients)
81431
            let bg_contents = get_background_contents(styled_dom, dom_id, node_state);
            // Get border info for inline elements
81431
            let border_info = get_border_info(styled_dom, dom_id, node_state);
81431
            let inline_border =
81431
                get_inline_border_info(styled_dom, dom_id, node_state, &border_info, viewport_size);
81431
            (bg_color, bg_contents, inline_border)
        } else {
            // Block-level elements: background/border is painted by display_list.rs
            // via push_backgrounds_and_border() in DisplayListBuilder
654
            (None, Vec::new(), None)
        };
    // Query font-weight from CSS cache
82085
    let font_weight = match get_font_weight_property(styled_dom, dom_id, node_state) {
82042
        MultiValue::Exact(v) => v,
43
        _ => StyleFontWeight::Normal,
    };
    // Query font-style from CSS cache
82085
    let font_style = match get_font_style_property(styled_dom, dom_id, node_state) {
82042
        MultiValue::Exact(v) => v,
43
        _ => StyleFontStyle::Normal,
    };
    // Convert StyleFontWeight/StyleFontStyle to fontconfig types
82085
    let fc_weight = super::fc::convert_font_weight(font_weight);
82085
    let fc_style = super::fc::convert_font_style(font_style);
    // Check if any font family is a FontRef - if so, use FontStack::Ref
    // This allows embedded fonts (like Material Icons) to bypass fontconfig
82085
    let font_stack = {
85906
        let font_ref = (0..font_families.len()).find_map(|i| match font_families.get(i).unwrap() {
20
            StyleFontFamily::Ref(r) => Some(r.clone()),
85886
            _ => None,
85906
        });
82085
        font_ref.map_or_else(
82065
            || {
                // Get platform for resolving system font types. None on the paged /
                // PDF layout path (system_style is hard-coded None there);
                // build_font_selector_stack then resolves via Platform::current() so
                // the names stay in lock-step with the font-loading pass.
82065
                let platform = system_style.map(|ss| &ss.platform);
82065
                FontStack::Stack(build_font_selector_stack_memo(
82065
                    &font_families,
82065
                    platform,
82065
                    fc_weight,
82065
                    fc_style,
82065
                ))
82065
            },
            FontStack::Ref,
        )
    };
    // Get letter-spacing from CSS
82085
    let letter_spacing = {
        // FAST PATH: compact cache for letter-spacing (i16 resolved px × 10)
82085
        let mut fast_ls = None;
82085
        if node_state.is_normal() {
82042
            if let Some(ref cc) = cache.compact_cache {
82042
                if let Some(px_val) = cc.get_letter_spacing(dom_id.index()) {
82042
                    fast_ls = Some(crate::text3::cache::Spacing::PxF(px_val));
82042
                }
            }
43
        }
82085
        fast_ls.unwrap_or_else(|| {
43
            cache
43
                .get_letter_spacing(node_data, &dom_id, node_state)
43
                .and_then(|v| v.get_property().copied())
43
                .map(|v| {
                    let px_value = v
                        .inner
                        .resolve_with_context(&font_size_context, PropertyContext::FontSize);
                    crate::text3::cache::Spacing::PxF(px_value)
                })
43
                .unwrap_or_default()
43
        })
    };
    // Get word-spacing from CSS
82085
    let word_spacing = {
        // FAST PATH: compact cache for word-spacing (i16 resolved px × 10)
82085
        let mut fast_ws = None;
82085
        if node_state.is_normal() {
82042
            if let Some(ref cc) = cache.compact_cache {
82042
                if let Some(px_val) = cc.get_word_spacing(dom_id.index()) {
82042
                    fast_ws = Some(crate::text3::cache::Spacing::PxF(px_val));
82042
                }
            }
43
        }
82085
        fast_ws.unwrap_or_else(|| {
43
            cache
43
                .get_word_spacing(node_data, &dom_id, node_state)
43
                .and_then(|v| v.get_property().copied())
43
                .map(|v| {
                    let px_value = v
                        .inner
                        .resolve_with_context(&font_size_context, PropertyContext::FontSize);
                    crate::text3::cache::Spacing::PxF(px_value)
                })
43
                .unwrap_or_default()
43
        })
    };
    // Get text-decoration from CSS.
    //
    // Fast path: the compact cache keeps a `has_text_decoration` flag. If
    // unset (the overwhelmingly common case — plain body text has no
    // decoration set), skip the 4-pseudo-state × 6-layer cascade walk
    // entirely. Only nodes that actually set text-decoration pay the walk.
82085
    let text_decoration = {
82085
        let mut skip_walk = false;
82085
        if node_state.is_normal() {
82042
            if let Some(ref cc) = cache.compact_cache {
82042
                if !cc.has_text_decoration(dom_id.index()) {
81622
                    skip_walk = true;
81622
                }
            }
43
        }
82085
        if skip_walk {
81622
            crate::text3::cache::TextDecoration::default()
        } else {
463
            cache
463
                .get_text_decoration(node_data, &dom_id, node_state)
463
                .and_then(|v| v.get_property().copied())
463
                .map(crate::text3::cache::TextDecoration::from_css)
463
                .unwrap_or_default()
        }
    };
    // Get tab-size (tab-size) from CSS.
    //
    // tab-size defaults to `I16_SENTINEL` in the compact cache builder
    // (spec default is "8", meaning 8 space widths). The old fallback
    // called `cache.get_tab_size(..)` (slow cascade) for every node whose
    // raw was SENTINEL — virtually every node, because almost nothing sets
    // tab-size. That was 1485 pure-waste slow walks per cold layout.
    //
    // New behaviour: sentinel → 8.0 directly. Only walk the cascade when
    // the compact cache is genuinely unavailable (no `compact_cache`) or
    // the node is in a pseudo-state that bypassed the cache.
82085
    let tab_size = {
82085
        let mut fast_tab = None;
82085
        if node_state.is_normal() {
82042
            if let Some(ref cc) = cache.compact_cache {
82042
                let raw = cc.get_tab_size_raw(dom_id.index());
82042
                if raw < azul_css::compact_cache::I16_SENTINEL_THRESHOLD {
                    fast_tab = Some(f32::from(raw) / 10.0);
82042
                } else {
82042
                    // Sentinel / Inherit / Initial → spec default is 8.
82042
                    fast_tab = Some(8.0);
82042
                }
            }
43
        }
82085
        fast_tab.unwrap_or_else(|| {
43
            cache
43
                .get_tab_size(node_data, &dom_id, node_state)
43
                .and_then(|v| v.get_property().copied())
43
                .map_or(DEFAULT_TAB_SIZE, |v| v.inner.number.get())
43
        })
    };
    // Get text-transform from CSS (uppercase / lowercase / capitalize / full-width).
    // Applied to the run text before shaping (fc.rs::apply_text_transform) so that
    // intrinsic widths reflect the transformed glyphs.
82085
    let text_transform = cache
82085
        .get_text_transform(node_data, &dom_id, node_state)
82085
        .and_then(|v| v.get_property().copied())
82085
        .map(|t| {
            use azul_css::props::style::text::StyleTextTransform as Css;
            use crate::text3::cache::TextTransform as T3;
20
            match t {
                Css::None => T3::None,
10
                Css::Uppercase => T3::Uppercase,
10
                Css::Lowercase => T3::Lowercase,
                Css::Capitalize => T3::Capitalize,
                Css::FullWidth => T3::FullWidth,
            }
20
        })
82085
        .unwrap_or_default();
82085
    StyleProperties {
82085
        font_stack,
82085
        font_size_px: font_size,
82085
        color,
82085
        background_color,
82085
        background_content,
82085
        border,
82085
        line_height,
82085
        letter_spacing,
82085
        word_spacing,
82085
        text_decoration,
82085
        tab_size,
82085
        text_transform,
82085
        // Per-run vertical-align so a `<span style="vertical-align:super/sub">` shifts
82085
        // its text clusters (get_item_vertical_align reads this). Without it every text
82085
        // cluster fell back to the IFC root's alignment (baseline), so sub/super/length
82085
        // vertical-align on inline spans had no effect.
82085
        vertical_align: get_vertical_align_for_node(styled_dom, dom_id),
82085
        // These still use defaults - could be extended in future:
82085
        // font_features, font_variations, writing_mode,
82085
        // text_orientation, text_combine_upright, font_variant_*
82085
        ..Default::default()
82085
    }
82085
}
#[must_use]
961
pub fn get_list_style_type(styled_dom: &StyledDom, dom_id: Option<NodeId>) -> StyleListStyleType {
961
    let Some(id) = dom_id else {
1
        return StyleListStyleType::default();
    };
960
    let node_data = &styled_dom.node_data.as_container()[id];
960
    let node_state = &styled_dom.styled_nodes.as_container()[id].styled_node_state;
960
    styled_dom
960
        .css_property_cache
960
        .ptr
960
        .get_list_style_type(node_data, &id, node_state)
960
        .and_then(|v| v.get_property().copied())
960
        .unwrap_or_default()
961
}
#[must_use]
481
pub fn get_list_style_position(
481
    styled_dom: &StyledDom,
481
    dom_id: Option<NodeId>,
481
) -> StyleListStylePosition {
481
    let Some(id) = dom_id else {
1
        return StyleListStylePosition::default();
    };
480
    let node_data = &styled_dom.node_data.as_container()[id];
480
    let node_state = &styled_dom.styled_nodes.as_container()[id].styled_node_state;
480
    styled_dom
480
        .css_property_cache
480
        .ptr
480
        .get_list_style_position(node_data, &id, node_state)
480
        .and_then(|v| v.get_property().copied())
480
        .unwrap_or_default()
481
}
// New: Taffy Bridge Getters - Box Model Properties with Ua Css Fallback
use azul_css::props::layout::{
    LayoutInsetBottom, LayoutLeft, LayoutMarginBottom, LayoutMarginLeft, LayoutMarginRight,
    LayoutMarginTop, LayoutMaxHeight, LayoutMaxWidth, LayoutMinHeight, LayoutMinWidth,
    LayoutPaddingBottom, LayoutPaddingLeft, LayoutPaddingRight, LayoutPaddingTop, LayoutRight,
    LayoutTop,
};
/// Get inset (position) properties - returns MultiValue<PixelValue>
get_css_property_pixel!(
    get_css_left,
    get_left,
    CssPropertyType::Left,
    compact_i16 = get_left
);
get_css_property_pixel!(
    get_css_right,
    get_right,
    CssPropertyType::Right,
    compact_i16 = get_right
);
get_css_property_pixel!(
    get_css_top,
    get_top,
    CssPropertyType::Top,
    compact_i16 = get_top
);
get_css_property_pixel!(
    get_css_bottom,
    get_bottom,
    CssPropertyType::Bottom,
    compact_i16 = get_bottom
);
/// Get margin properties - returns MultiValue<PixelValue>
get_css_property_pixel!(
    get_css_margin_left,
    get_margin_left,
    CssPropertyType::MarginLeft,
    compact_i16 = get_margin_left_raw
);
get_css_property_pixel!(
    get_css_margin_right,
    get_margin_right,
    CssPropertyType::MarginRight,
    compact_i16 = get_margin_right_raw
);
get_css_property_pixel!(
    get_css_margin_top,
    get_margin_top,
    CssPropertyType::MarginTop,
    compact_i16 = get_margin_top_raw
);
get_css_property_pixel!(
    get_css_margin_bottom,
    get_margin_bottom,
    CssPropertyType::MarginBottom,
    compact_i16 = get_margin_bottom_raw
);
/// Get padding properties - returns MultiValue<PixelValue>
get_css_property_pixel!(
    get_css_padding_left,
    get_padding_left,
    CssPropertyType::PaddingLeft,
    compact_i16 = get_padding_left_raw
);
get_css_property_pixel!(
    get_css_padding_right,
    get_padding_right,
    CssPropertyType::PaddingRight,
    compact_i16 = get_padding_right_raw
);
get_css_property_pixel!(
    get_css_padding_top,
    get_padding_top,
    CssPropertyType::PaddingTop,
    compact_i16 = get_padding_top_raw
);
get_css_property_pixel!(
    get_css_padding_bottom,
    get_padding_bottom,
    CssPropertyType::PaddingBottom,
    compact_i16 = get_padding_bottom_raw
);
/// Get min/max size properties
get_css_property!(
    get_css_min_width,
    get_min_width,
    LayoutMinWidth,
    CssPropertyType::MinWidth,
    compact_u32_struct = get_min_width_raw
);
get_css_property!(
    get_css_min_height,
    get_min_height,
    LayoutMinHeight,
    CssPropertyType::MinHeight,
    compact_u32_struct = get_min_height_raw
);
get_css_property!(
    get_css_max_width,
    get_max_width,
    LayoutMaxWidth,
    CssPropertyType::MaxWidth,
    compact_u32_struct = get_max_width_raw
);
get_css_property!(
    get_css_max_height,
    get_max_height,
    LayoutMaxHeight,
    CssPropertyType::MaxHeight,
    compact_u32_struct = get_max_height_raw
);
/// Get border width properties (no UA CSS fallback needed, defaults to 0)
get_css_property_pixel!(
    get_css_border_left_width,
    get_border_left_width,
    CssPropertyType::BorderLeftWidth,
    compact_i16 = get_border_left_width_raw
);
get_css_property_pixel!(
    get_css_border_right_width,
    get_border_right_width,
    CssPropertyType::BorderRightWidth,
    compact_i16 = get_border_right_width_raw
);
get_css_property_pixel!(
    get_css_border_top_width,
    get_border_top_width,
    CssPropertyType::BorderTopWidth,
    compact_i16 = get_border_top_width_raw
);
get_css_property_pixel!(
    get_css_border_bottom_width,
    get_border_bottom_width,
    CssPropertyType::BorderBottomWidth,
    compact_i16 = get_border_bottom_width_raw
);
// Fragmentation (page breaking) properties
/// Get break-before property for paged media
#[must_use]
787535
pub fn get_break_before(styled_dom: &StyledDom, dom_id: Option<NodeId>) -> PageBreak {
787535
    let Some(id) = dom_id else {
1
        return PageBreak::Auto;
    };
787534
    let node_state = &styled_dom.styled_nodes.as_container()[id].styled_node_state;
    // UA fallback: node types with intrinsic break behavior (the canonical
    // `<pagebreak/>` element carries UA `break-before: page`). The author
    // bitset below knows nothing about UA properties, so this must be the
    // miss path on BOTH branches, not `Auto`.
787534
    let ua_fallback = |styled_dom: &StyledDom| -> PageBreak {
787464
        let node_data = &styled_dom.node_data.as_container()[id];
787464
        azul_core::ua_css::get_ua_property(node_data.get_node_type(), CssPropertyType::BreakBefore)
787464
            .and_then(|p| {
                if let CssProperty::BreakBefore(v) = p {
                    v.get_property().copied()
                } else {
                    None
                }
            })
787464
            .unwrap_or(PageBreak::Auto)
787464
    };
    // Negative fast path: break-* is almost never declared by authors.
787534
    if node_state.is_normal() {
787434
        if let Some(ref cc) = styled_dom.css_property_cache.ptr.compact_cache {
787433
            if !cc.has_break(id.index()) {
786653
                return ua_fallback(styled_dom);
780
            }
1
        }
100
    }
881
    let node_data = &styled_dom.node_data.as_container()[id];
881
    styled_dom
881
        .css_property_cache
881
        .ptr
881
        .get_break_before(node_data, &id, node_state)
881
        .and_then(|v| v.get_property().copied())
881
        .unwrap_or_else(|| ua_fallback(styled_dom))
787535
}
/// Get break-after property for paged media
#[must_use]
787155
pub fn get_break_after(styled_dom: &StyledDom, dom_id: Option<NodeId>) -> PageBreak {
787155
    let Some(id) = dom_id else {
1
        return PageBreak::Auto;
    };
787154
    let node_state = &styled_dom.styled_nodes.as_container()[id].styled_node_state;
787154
    if node_state.is_normal() {
787054
        if let Some(ref cc) = styled_dom.css_property_cache.ptr.compact_cache {
787053
            if !cc.has_break(id.index()) {
786283
                return PageBreak::Auto;
770
            }
1
        }
100
    }
871
    let node_data = &styled_dom.node_data.as_container()[id];
871
    styled_dom
871
        .css_property_cache
871
        .ptr
871
        .get_break_after(node_data, &id, node_state)
871
        .and_then(|v| v.get_property().copied())
871
        .unwrap_or(PageBreak::Auto)
787155
}
/// Check if a `PageBreak` value forces a page break (always, page, left, right, etc.)
#[must_use]
1574335
pub const fn is_forced_page_break(page_break: PageBreak) -> bool {
1574261
    matches!(
1574335
        page_break,
        PageBreak::Always
            | PageBreak::Page
            | PageBreak::Left
            | PageBreak::Right
            | PageBreak::Recto
            | PageBreak::Verso
            | PageBreak::All
    )
1574335
}
/// Get break-inside property for paged media
#[must_use]
7
pub fn get_break_inside(styled_dom: &StyledDom, dom_id: Option<NodeId>) -> BreakInside {
7
    let Some(id) = dom_id else {
1
        return BreakInside::Auto;
    };
6
    let node_data = &styled_dom.node_data.as_container()[id];
6
    let node_state = &styled_dom.styled_nodes.as_container()[id].styled_node_state;
6
    styled_dom
6
        .css_property_cache
6
        .ptr
6
        .get_break_inside(node_data, &id, node_state)
6
        .and_then(|v| v.get_property().copied())
6
        .unwrap_or(BreakInside::Auto)
7
}
/// Get orphans property (minimum lines at bottom of page)
#[must_use]
3
pub fn get_orphans(styled_dom: &StyledDom, dom_id: Option<NodeId>) -> u32 {
3
    let Some(id) = dom_id else {
1
        return 2; // Default value
    };
2
    let node_data = &styled_dom.node_data.as_container()[id];
2
    let node_state = &styled_dom.styled_nodes.as_container()[id].styled_node_state;
2
    styled_dom
2
        .css_property_cache
2
        .ptr
2
        .get_orphans(node_data, &id, node_state)
2
        .and_then(|v| v.get_property().copied())
2
        .map_or(2, |o| o.inner)
3
}
/// Get widows property (minimum lines at top of page)
#[must_use]
3
pub fn get_widows(styled_dom: &StyledDom, dom_id: Option<NodeId>) -> u32 {
3
    let Some(id) = dom_id else {
1
        return 2; // Default value
    };
2
    let node_data = &styled_dom.node_data.as_container()[id];
2
    let node_state = &styled_dom.styled_nodes.as_container()[id].styled_node_state;
2
    styled_dom
2
        .css_property_cache
2
        .ptr
2
        .get_widows(node_data, &id, node_state)
2
        .and_then(|v| v.get_property().copied())
2
        .map_or(2, |w| w.inner)
3
}
/// Get box-decoration-break property
#[must_use]
1
pub fn get_box_decoration_break(
1
    styled_dom: &StyledDom,
1
    dom_id: Option<NodeId>,
1
) -> BoxDecorationBreak {
1
    let Some(id) = dom_id else {
1
        return BoxDecorationBreak::Slice;
    };
    let node_data = &styled_dom.node_data.as_container()[id];
    let node_state = &styled_dom.styled_nodes.as_container()[id].styled_node_state;
    styled_dom
        .css_property_cache
        .ptr
        .get_box_decoration_break(node_data, &id, node_state)
        .and_then(|v| v.get_property().copied())
        .unwrap_or(BoxDecorationBreak::Slice)
1
}
// Helper functions for break properties
/// Check if a `PageBreak` value is avoid
#[must_use]
20
pub const fn is_avoid_page_break(page_break: &PageBreak) -> bool {
20
    matches!(page_break, PageBreak::Avoid | PageBreak::AvoidPage)
20
}
/// Check if a `BreakInside` value prevents breaks
#[must_use]
5
pub const fn is_avoid_break_inside(break_inside: &BreakInside) -> bool {
2
    matches!(
5
        break_inside,
        BreakInside::Avoid | BreakInside::AvoidPage | BreakInside::AvoidColumn
    )
5
}
// Font Chain Resolution - Pre-Layout Font Loading
use std::collections::HashMap;
use rust_fontconfig::{
    config::is_generic_family, FcFontCache, FcWeight, FontFallbackChain, PatternMatch,
    UnicodeRange, DEFAULT_UNICODE_FALLBACK_SCRIPTS,
};
use crate::text3::cache::{FontChainKey, FontChainKeyOrRef, FontSelector, FontStack, FontStyle};
/// Memoised [`build_font_selector_stack`].
///
/// Building the stack is PURE — the same (families, platform, weight,
/// style) always yields the same selectors — but it was being rebuilt for
/// every text node during intrinsic sizing and again during inline layout.
/// On a document whose body sets one `font-family` that every block
/// inherits, that is the identical eight-selector stack constructed 82
/// times per pagination, each build allocating a `String` per selector plus
/// a lowercase copy and a fontconfig alias lookup per generic. It measured
/// 18% of a warm release-mode pagination (`bfss_*` spans) and was the
/// single largest source of short-lived allocations in the layout pass.
///
/// The memo is per-thread (layout is single-threaded per document, so no
/// lock) and keyed on everything the builder reads, so a document that
/// changes family, weight, style or platform gets a fresh build — see the
/// `memo_is_keyed_on_*` tests.
#[allow(clippy::implicit_hasher)]
82073
fn build_font_selector_stack_memo(
82073
    font_families: &StyleFontFamilyVec,
82073
    platform: Option<&azul_css::system::Platform>,
82073
    fc_weight: FcWeight,
82073
    fc_style: FontStyle,
82073
) -> Vec<FontSelector> {
    use core::hash::{Hash, Hasher};
    use std::{cell::RefCell, collections::HashMap};
    // Bounded so a pathological document (thousands of distinct
    // family/weight combinations) cannot grow the memo without limit; the
    // realistic working set is single digits.
    const MAX_ENTRIES: usize = 256;
    thread_local! {
        static MEMO: RefCell<HashMap<u64, Vec<FontSelector>>> =
            RefCell::new(HashMap::new());
    }
82073
    let key = {
82073
        let mut h = std::collections::hash_map::DefaultHasher::new();
85894
        for i in 0..font_families.len() {
85894
            font_families.get(i).unwrap().hash(&mut h);
85894
        }
        // `Platform` is a repr(C) FFI enum without `Hash`; hash its
        // discriminant plus the one payload the builder can read (the
        // Linux desktop-environment name).
82073
        match platform {
81635
            None => 0u8.hash(&mut h),
438
            Some(p) => {
438
                1u8.hash(&mut h);
438
                core::mem::discriminant(p).hash(&mut h);
438
                if let azul_css::system::Platform::Linux(de) = p {
150
                    core::mem::discriminant(de).hash(&mut h);
150
                    if let azul_css::system::DesktopEnvironment::Other(name) = de {
                        name.as_str().hash(&mut h);
150
                    }
288
                }
            }
        }
82073
        core::mem::discriminant(&fc_weight).hash(&mut h);
82073
        core::mem::discriminant(&fc_style).hash(&mut h);
82073
        h.finish()
    };
82073
    if let Some(hit) = MEMO.with(|m| m.borrow().get(&key).cloned()) {
77699
        drop(crate::probe::Probe::span("font_stack_memo_hit"));
77699
        return hit;
4374
    }
4374
    let _p = crate::probe::Probe::span("font_stack_build");
4374
    let built = build_font_selector_stack(font_families, platform, fc_weight, fc_style);
4374
    MEMO.with(|m| {
4374
        let mut m = m.borrow_mut();
4374
        if m.len() >= MAX_ENTRIES {
            m.clear();
4374
        }
4374
        m.insert(key, built.clone());
4374
    });
4374
    built
82073
}
/// Build a fontconfig `FontSelector` stack from a list of CSS font families.
///
/// Shared by `get_style_properties` and `collect_font_stacks_from_styled_dom`.
/// `Ref` families are skipped (callers handle embedded fonts via `FontStack::Ref`),
/// `SystemType` families expand to the platform's fallback chain, and the generic
/// `sans-serif`/`serif`/`monospace` fallbacks are appended if not already present.
///
/// Generic families are pushed AS generics. rust-fontconfig expands them
/// through its `FcFallbackConfig` - the platform's `fonts.conf`
/// `<alias><prefer>` lists merged over the per-OS tables, see
/// `FcFontRegistry::new` - so azul does no alias expansion of its own: ONE
/// model decides what `sans-serif` means, and an alias family the system
/// does not have costs a map lookup, not a resolver query.
///
/// When `platform` is `None` (e.g. the paged / PDF layout path that hard-codes
/// `system_style = None`), system fonts resolve via `Platform::current()` so the
/// names stay in lock-step with the font-loading pass (which always uses
/// `Platform::current()`); diverging to a bare "sans-serif" would not match the
/// names the loader registered → zero glyphs → text collapses to 0 width.
// The `platform` binding uses a pre-declared `let current;` so the else branch can
// extend the lifetime of a freshly-computed Platform and hand back a reference to it;
// map_or_else cannot express this (the closure would return a dangling local ref).
#[allow(clippy::option_if_let_else)]
11363
fn build_font_selector_stack(
11363
    font_families: &StyleFontFamilyVec,
11363
    platform: Option<&azul_css::system::Platform>,
11363
    fc_weight: FcWeight,
11363
    fc_style: FontStyle,
11363
) -> Vec<FontSelector> {
11363
    let mut stack = Vec::with_capacity(font_families.len() + 3);
11560
    for i in 0..font_families.len() {
11560
        let family = font_families.get(i).unwrap();
11560
        if matches!(family, StyleFontFamily::Ref(_)) {
            continue;
11560
        }
        // Both spellings of a system font expand to the platform fallback
        // chain: the typed `SystemType(..)` variant AND the magic-string
        // form `System("system:ui")` used by the widget style tables — no
        // fontconfig database knows a family literally called "system:ui".
11560
        let system_type = match family {
112
            StyleFontFamily::SystemType(s) => Some(*s),
11448
            StyleFontFamily::System(name) => {
11448
                azul_css::system::SystemFontType::from_css_str(name.as_str())
            }
            _ => None,
        };
11560
        if let Some(system_type) = system_type {
            let current;
995
            let platform = if let Some(p) = platform {
594
                p
            } else {
401
                current = azul_css::system::Platform::current();
401
                &current
            };
995
            let font_names = system_type.get_fallback_chain(platform);
995
            let system_weight = if system_type.is_bold() {
1
                FcWeight::Bold
            } else {
994
                fc_weight
            };
995
            let system_style = if system_type.is_italic() {
                FontStyle::Italic
            } else {
995
                fc_style
            };
6794
            for font_name in font_names {
5799
                stack.push(FontSelector {
5799
                    family: font_name.to_string(),
5799
                    weight: system_weight,
5799
                    style: system_style,
5799
                    unicode_ranges: Vec::new(),
5799
                });
5799
            }
10565
        } else {
10565
            // as_query_string, NOT as_string: FontManager queries fontconfig with the
10565
            // RAW name. as_string() CSS-quotes whitespace names ("Times New Roman" ->
10565
            // "\"Times New Roman\""), which corrupts the query for every multi-word font.
10565
            stack.push(FontSelector {
10565
                family: family.as_query_string(),
10565
                weight: fc_weight,
10565
                style: fc_style,
10565
                unicode_ranges: Vec::new(),
10565
            });
10565
        }
    }
45452
    for fallback in &["sans-serif", "serif", "monospace"] {
34089
        if !stack
34089
            .iter()
66913
            .any(|f| f.family.eq_ignore_ascii_case(fallback))
25955
        {
25955
            stack.push(FontSelector {
25955
                family: (*fallback).to_string(),
25955
                weight: FcWeight::Normal,
25955
                style: FontStyle::Normal,
25955
                unicode_ranges: Vec::new(),
25955
            });
25955
        }
    }
11363
    stack
11363
}
/// Result of collecting font stacks from a `StyledDom`
/// Contains all unique font stacks and the mapping from `StyleFontFamiliesHash` to `FontChainKey`
#[derive(Debug, Clone)]
pub struct CollectedFontStacks {
    /// All unique font stacks found in the document (system/file fonts via fontconfig)
    pub font_stacks: Vec<Vec<FontSelector>>,
    /// Map from the font stack hash to the index in `font_stacks`
    pub hash_to_index: HashMap<u64, usize>,
    /// Direct `FontRefs` that bypass fontconfig (e.g., embedded icon fonts)
    /// These are keyed by their pointer address for uniqueness
    pub font_refs: HashMap<usize, azul_css::props::basic::font::FontRef>,
}
/// Resolved font chains ready for use in layout
/// This is the result of resolving font stacks against `FcFontCache`
#[derive(Debug, Clone, Default)]
pub struct ResolvedFontChains {
    /// Map from `FontChainKeyOrRef` to the resolved `FontFallbackChain`
    /// For `FontChainKeyOrRef::Ref` variants, the `FontFallbackChain` contains
    /// a single-font chain that covers the entire Unicode range.
    pub chains: HashMap<FontChainKeyOrRef, FontFallbackChain>,
    /// CSS families that were REQUESTED but could not be matched to any
    /// font (not on disk, not registered in memory).
    ///
    /// This used to be swallowed: the resolver moved on to the next family
    /// and, if the whole stack failed, `ensure_chains_nonempty` quietly
    /// attached an arbitrary system font. Every unmatched family therefore
    /// collapsed onto the SAME `FontId`, text rendered in a font nobody
    /// asked for, and no test could tell. A failed family match is now a
    /// first-class output: it is recorded here and logged once
    /// (see `report_unresolved_families`).
    pub unresolved_families: std::collections::BTreeSet<String>,
    /// Chains that matched NOTHING at all and only render because
    /// `ensure_chains_nonempty` attached a last-resort font. These are
    /// rendering in a font the stylesheet never asked for.
    pub last_resort_chains: usize,
}
impl ResolvedFontChains {
    /// Get a font chain by its key
    #[must_use]
2
    pub fn get(&self, key: &FontChainKeyOrRef) -> Option<&FontFallbackChain> {
2
        self.chains.get(key)
2
    }
    /// Get a font chain by `FontChainKey` (for system fonts)
    #[must_use]
4
    pub fn get_by_chain_key(&self, key: &FontChainKey) -> Option<&FontFallbackChain> {
4
        self.chains.get(&FontChainKeyOrRef::Chain(key.clone()))
4
    }
    /// Get a font chain for a font stack (via fontconfig)
    #[must_use]
3
    pub fn get_for_font_stack(&self, font_stack: &[FontSelector]) -> Option<&FontFallbackChain> {
3
        let key = FontChainKeyOrRef::Chain(FontChainKey::from_selectors(font_stack));
3
        self.chains.get(&key)
3
    }
    /// Get a font chain for a `FontRef` pointer
    #[must_use]
6
    pub fn get_for_font_ref(&self, ptr: usize) -> Option<&FontFallbackChain> {
6
        self.chains.get(&FontChainKeyOrRef::Ref(ptr))
6
    }
    /// Consume self and return the inner `HashMap` with `FontChainKeyOrRef` keys
    ///
    /// This is useful when you need access to both Chain and Ref variants.
    #[must_use]
1
    pub fn into_inner(self) -> HashMap<FontChainKeyOrRef, FontFallbackChain> {
1
        self.chains
1
    }
    /// Consume self and return only the fontconfig-resolved chains
    ///
    /// This filters out `FontRef` entries and returns only the chains
    /// resolved via fontconfig. This is what `FontManager` expects.
    #[must_use]
9098
    pub fn into_fontconfig_chains(self) -> HashMap<FontChainKey, FontFallbackChain> {
        // (2026-06-10: reverted to HashMap end-to-end — the empty-hashbrown RawIter hang behind
        // the 2026-06-05 BTreeMap migration was the un-mirrored EMPTY_GROUP static, fixed
        // transpiler-side in symbol_table.rs::compute_hashbrown_empty_group_ranges.)
9098
        let mut out: HashMap<FontChainKey, FontFallbackChain> = HashMap::new();
9098
        if self.chains.is_empty() {
2514
            return out;
6584
        }
13505
        for (key, chain) in self.chains {
6921
            if let FontChainKeyOrRef::Chain(chain_key) = key {
6919
                out.insert(chain_key, chain);
6919
            }
        }
6584
        out
9098
    }
    /// Get the number of resolved chains
    #[must_use]
6654
    pub fn len(&self) -> usize {
6654
        self.chains.len()
6654
    }
    /// Check if there are no resolved chains
    #[must_use]
4
    pub fn is_empty(&self) -> bool {
4
        self.chains.is_empty()
4
    }
    /// Get the number of direct `FontRefs`
    #[must_use]
2
    pub fn font_refs_len(&self) -> usize {
3
        self.chains.keys().filter(|k| k.is_ref()).count()
2
    }
}
/// Collect all unique font stacks from a `StyledDom`
///
/// This is a pure function that iterates over all nodes in the DOM and
/// extracts the font-family property from each node that has text content.
///
/// # Arguments
/// * `styled_dom` - The styled DOM to extract font stacks from
/// * `platform` - The current platform for resolving system font types
///
/// # Returns
/// A `CollectedFontStacks` containing all unique font stacks and a hash-to-index mapping
#[allow(clippy::cast_possible_truncation)] // bounded graphics/coord/font/fixed-point/debug-marker cast
#[allow(clippy::too_many_lines)] // large but cohesive: single-purpose layout/render/parse routine (one branch per case)
#[must_use]
9100
pub fn collect_font_stacks_from_styled_dom(
9100
    styled_dom: &StyledDom,
9100
    platform: &azul_css::system::Platform,
9100
) -> CollectedFontStacks {
    use azul_css::compact_cache::{
        FONT_STYLE_MASK, FONT_STYLE_SHIFT, FONT_WEIGHT_MASK, FONT_WEIGHT_SHIFT,
    };
9100
    let mut font_stacks = Vec::new();
9100
    let mut hash_to_index: HashMap<u64, usize> = HashMap::new();
9100
    let mut font_refs: HashMap<usize, azul_css::props::basic::font::FontRef> = HashMap::new();
9100
    let node_data = styled_dom.node_data.as_container();
9100
    let cache = &styled_dom.css_property_cache.ptr;
9100
    let Some(compact) = cache.compact_cache.as_ref() else {
2
        return CollectedFontStacks {
2
            font_stacks,
2
            hash_to_index,
2
            font_refs,
2
        };
    };
    // Phase 1: Scan compact cache arrays (just u64 reads) to find unique
    // (font_family_hash, weight, style) tuples. Record one representative
    // node index per unique tuple for the expensive CSS lookup in Phase 2.
    // Key: (font_family_hash, weight_encoded, style_encoded) → representative node index
    // (2026-06-10: reverted to HashMap — the historic g81/g47 empty-hashbrown mis-lift was the
    // un-mirrored EMPTY_GROUP static, fixed transpiler-side in symbol_table.rs::
    // compute_hashbrown_empty_group_ranges. std HashMap lifts correctly now; RandomState seeds
    // via the transpiler's HashmapRandomKeys fixed-seed body.)
9098
    let mut unique_font_keys: HashMap<(u64, u8, u8), usize> = HashMap::new();
9098
    let node_count = node_data.internal.len();
    // WEB-LIFT: probe node_type bytes (NodeType #[repr(C,u8)], Text=177 per AzDom_createText).
    // 0x406D0..DC = n1.node_type bytes[0,1,2,4]; 0x406E0 = n0.node_type byte[0] (body disc).
9098
    if node_count > 1 {
8774
        let p1 = (&raw const node_data.internal[1].node_type).cast::<u8>();
8774
        let p0 = (&raw const node_data.internal[0].node_type).cast::<u8>();
8774
        unsafe {
8774
            crate::az_mark(0x606D0_u32, u32::from(core::ptr::read(p1)));
8774
            crate::az_mark(0x606D4_u32, u32::from(core::ptr::read(p1.add(1))));
8774
            crate::az_mark(0x606D8_u32, u32::from(core::ptr::read(p1.add(2))));
8774
            crate::az_mark(0x606DC_u32, u32::from(core::ptr::read(p1.add(4))));
8774
            crate::az_mark(0x606E0_u32, u32::from(core::ptr::read(p0)));
8774
        }
324
    }
9098
    let styled_nodes_phase1 = styled_dom.styled_nodes.as_container();
254007
    for i in 0..node_count {
        // Only text nodes need fonts. WEB-LIFT: the lifted `matches!(node_type,
        // NodeType::Text(_))` MIS-LIFTS (compares against a mis-lifted discriminant
        // constant) — text nodes never match → no font stack → no chain → text h=0.
        // NodeType is #[repr(C,u8)] so the discriminant is the u8 at offset 0; Text=177
        // (per AzDom_createText: `mov w8,#0xb1; strb w8,[x19]`). Compare the raw
        // discriminant to the literal 177 (a source literal lifts correctly).
254007
        let nt_disc =
254007
            unsafe { core::ptr::read((&raw const node_data.internal[i].node_type).cast::<u8>()) };
        // A node carrying a PLACEHOLDER attribute needs a font exactly like a
        // text node: the engine paints the prompt with the node's own style,
        // and without this its family never resolved a chain (placeholder-only
        // documents shaped to nothing, 2026-08-31).
254007
        let is_text = nt_disc == 177
165561
            || matches!(node_data.internal[i].node_type, NodeType::Text(_))
165561
            || node_data.internal[i].get_placeholder().is_some();
254007
        if !is_text {
165359
            continue;
88648
        }
88648
        let fh = compact.tier2b_text[i].font_family_hash;
88648
        let t1 = compact.tier1_enums[i];
88648
        let mut weight_bits = ((t1 >> FONT_WEIGHT_SHIFT) & FONT_WEIGHT_MASK) as u8;
88648
        let mut style_bits = ((t1 >> FONT_STYLE_SHIFT) & FONT_STYLE_MASK) as u8;
        // The compact bits see only AUTHOR css. Two text nodes with all-
        // default bits can still resolve to DIFFERENT weights/styles through
        // UA rules on their parents (an h1's bold vs a p's normal), and
        // deduping them into one bucket resolved+loaded only the
        // REPRESENTATIVE's chain — every run asking for the other weight was
        // unshapeable (skipped: zero lines) and its font never loaded.
        // Whenever the fast bits are at their defaults, key on the real
        // cascade instead (the same reads Phase 2 does on representatives).
88648
        if weight_bits == 0 && style_bits == 0 {
88408
            if let Some(dom_id) = NodeId::from_usize(i) {
88408
                let node_state = &styled_nodes_phase1[dom_id].styled_node_state;
88408
                if let MultiValue::Exact(w) =
88408
                    get_font_weight_property(styled_dom, dom_id, node_state)
88408
                {
88408
                    weight_bits = super::fc::convert_font_weight(w) as u8;
88408
                }
88408
                if let MultiValue::Exact(st) =
88408
                    get_font_style_property(styled_dom, dom_id, node_state)
88408
                {
88408
                    style_bits = st as u8;
88408
                }
            }
240
        }
88648
        let key = (fh, weight_bits, style_bits);
88648
        unique_font_keys.entry(key).or_insert(i);
    }
    // WASM-ONLY PROBE (REVERT): why 0 chains? 0x406C0=tag(5E5E0003), C4=node_count,
    // C8=unique_font_keys.len() (#text nodes matched in Phase 1). If C8=0 → the lifted
    // `matches!(node_type, NodeType::Text(_))` FAILS for the text node (node_type mis-lift)
    // → no font stack → no chain → text h=0. C is the count of NodeType::Text via a raw
    // discriminant byte read (node_type tag), to compare against the matches! result.
    {
9098
        let mut raw_text = 0u32;
254007
        for i in 0..node_count {
            // NodeType is repr(C,u8)-ish; read the leading discriminant byte directly.
254007
            let nt_ptr = (&raw const node_data.internal[i].node_type).cast::<u8>();
254007
            let disc = unsafe { core::ptr::read_volatile(nt_ptr) };
            // Text is one specific discriminant; count whatever the body node ISN'T.
254007
            if disc
254007
                != unsafe {
254007
                    core::ptr::read_volatile(
254007
                        (&raw const node_data.internal[0].node_type).cast::<u8>(),
254007
                    )
254007
                }
239927
            {
239927
                raw_text += 1;
239927
            }
        }
9098
        unsafe {
9098
            crate::az_mark(0x606C0_u32, (0x5E5E_0003_u32));
9098
            crate::az_mark(0x606C4_u32, (node_count as u32));
9098
            crate::az_mark(0x606C8_u32, (unique_font_keys.len() as u32));
9098
            crate::az_mark(0x606CC_u32, (raw_text));
9098
        }
    }
    // Phase 2: For each unique tuple, do ONE expensive CSS lookup on the
    // representative node to get the actual font-family names.
9098
    let styled_nodes = styled_dom.styled_nodes.as_container();
16099
    for (&(fh, _wb, _sb), &repr_idx) in &unique_font_keys {
7001
        let Some(dom_id) = NodeId::from_usize(repr_idx) else {
            continue;
        };
7001
        let node_state = &styled_nodes[dom_id].styled_node_state;
        // Use reverse map from compact cache: hash → actual font families.
        // This works for ALL nodes including text nodes that inherit font-family
        // via compact cache (where get_property_slow would return None).
7001
        let font_families = compact
7001
            .font_hash_to_families
7001
            .get(&fh)
7001
            .cloned()
7001
            .unwrap_or_else(|| {
4248
                StyleFontFamilyVec::from_vec(vec![StyleFontFamily::System("serif".into())])
4248
            });
        // Check for embedded FontRef
7001
        if let Some(StyleFontFamily::Ref(font_ref)) = font_families.get(0) {
21
            let ptr = font_ref.parsed as usize;
21
            font_refs.entry(ptr).or_insert_with(|| font_ref.clone());
21
            continue;
6980
        }
6980
        let font_weight = match get_font_weight_property(styled_dom, dom_id, node_state) {
6980
            MultiValue::Exact(v) => v,
            _ => StyleFontWeight::Normal,
        };
6980
        let font_style = match get_font_style_property(styled_dom, dom_id, node_state) {
6980
            MultiValue::Exact(v) => v,
            _ => StyleFontStyle::Normal,
        };
6980
        let fc_weight = super::fc::convert_font_weight(font_weight);
6980
        let fc_style = super::fc::convert_font_style(font_style);
6980
        let font_stack =
6980
            build_font_selector_stack(&font_families, Some(platform), fc_weight, fc_style);
6980
        if font_stack.is_empty() {
            continue;
6980
        }
6980
        let key = FontChainKey::from_selectors(&font_stack);
6980
        let hash = {
            use std::hash::{Hash, Hasher};
6980
            let mut hasher = std::collections::hash_map::DefaultHasher::new();
6980
            key.hash(&mut hasher);
6980
            hasher.finish()
        };
6980
        hash_to_index.entry(hash).or_insert_with(|| {
6919
            let idx = font_stacks.len();
6919
            font_stacks.push(font_stack);
6919
            idx
6919
        });
    }
9098
    CollectedFontStacks {
9098
        font_stacks,
9098
        hash_to_index,
9098
        font_refs,
9098
    }
9100
}
/// Resolve all font chains for the collected font stacks
///
/// This is a pure function that takes the collected font stacks and resolves
/// them against the `FcFontCache` to produce `FontFallbackChains`.
///
/// # Arguments
/// * `collected` - The collected font stacks from `collect_font_stacks_from_styled_dom`
/// * `fc_cache` - The fontconfig cache to resolve fonts against
///
/// # Returns
/// A `ResolvedFontChains` containing all resolved font chains
/// Walk every text node in `styled_dom` and collect the set of
/// non-ASCII codepoints actually present in the document.
///
/// Used by [`prune_chain_to_used_chars`] to drop CSS-fallback fonts
/// from a resolved chain when the *first* match in a `css_fallbacks`
/// group already covers everything the page asks for. ASCII (`< 0x80`)
/// is universally covered by every Latin font we'd resolve, so we
/// skip it here to keep the set small. Unicode characters in the
/// returned set are deduped + sorted via `BTreeSet`.
///
/// Cost: O(total text length). Cheap relative to layout itself.
#[must_use]
9041
pub fn collect_used_codepoints(styled_dom: &StyledDom) -> std::collections::BTreeSet<u32> {
9041
    let mut out = std::collections::BTreeSet::new();
9041
    let node_data = styled_dom.node_data.as_container();
262513
    for node in node_data.internal {
        // A node's PLACEHOLDER attribute is rendered text too (the engine
        // paints it while the host is empty): without it, a document whose
        // only visible text is a prompt collected NO codepoints, the chain
        // prune stripped every font, and the prompt shaped to nothing.
253472
        let node_text = if let NodeType::Text(s) = &node.node_type {
88168
            Some(s.as_str())
        } else {
165304
            None
        };
253472
        for s in node_text.into_iter().chain(node.get_placeholder()) {
965436
            for c in s.chars() {
965436
                let cp = c as u32;
965436
                if cp >= 0x80 {
2166
                    out.insert(cp);
963270
                }
            }
        }
    }
9041
    out
9041
}
/// Like [`collect_used_codepoints`] but keeps ASCII.
///
/// The fast-probe
/// path (`FcFontRegistry::request_fonts_fast`) *does* need ASCII:
/// "the font has to cover every codepoint I will render" is only
/// true if we tell it every codepoint, and "Segoe UI" not being
/// installed on macOS means even ASCII has to fall through to a
/// system default.
///
/// `collect_used_codepoints` strips ASCII because its caller
/// (`prune_chain_to_used_chars`) runs *after* resolution to trim an
/// already-resolved chain and every Latin-covering font passes ASCII
/// trivially. That assumption doesn't hold during probing.
#[must_use]
63
pub fn collect_used_codepoints_all(styled_dom: &StyledDom) -> std::collections::BTreeSet<char> {
63
    let mut out = std::collections::BTreeSet::new();
63
    let node_data = styled_dom.node_data.as_container();
609
    for node in node_data.internal {
        // Placeholder attributes count as rendered text - see
        // `collect_used_codepoints`.
546
        let node_text = if let NodeType::Text(s) = &node.node_type {
283
            Some(s.as_str())
        } else {
263
            None
        };
546
        for s in node_text.into_iter().chain(node.get_placeholder()) {
1515
            for c in s.chars() {
1515
                out.insert(c);
1515
            }
        }
    }
63
    out
63
}
/// Trim a [`FontFallbackChain`] down to the minimum set of `FontMatch`
/// entries needed to cover `used_chars` (typically from
/// [`collect_used_codepoints`]).
///
/// For each `css_fallbacks` group, walk matches in the resolver's
/// preferred order and keep them until every codepoint in
/// `used_chars` is covered (per the OS/2 unicode-range bits cached
/// in `FontMatch.unicode_ranges`). Always keeps at least the first
/// match per group so a font listed in CSS doesn't disappear.
///
/// The script tiers - each css group's `script_fonts` and the chain's
/// `unicode_fallbacks` - are filtered to the fonts whose ranges intersect a
/// used codepoint INSIDE the group's script range, and a group left with no
/// fonts is dropped. Phase-6's [`scripts_present_in_styled_dom`] already
/// scopes the *script blocks* but a single block (e.g. CJK Unified,
/// U+4E00..U+9FFF) can have hundreds of matching system fonts; this prunes
/// them down to the few that actually cover the codepoints used.
///
/// `last_resort` is never pruned: it is the "draw SOMETHING" tier
/// (`ensure_chains_nonempty`), kept regardless of coverage.
///
/// On excel.html (~ASCII-only) this drops the per-chain
/// `css_fallbacks` from 5 → 1 in each group, eliminating ~20 of
/// the 26 fonts that would otherwise be parsed by
/// `load_fonts_from_disk`.
6787
pub fn prune_chain_to_used_chars(
6787
    chain: &mut FontFallbackChain,
6787
    used_chars: &std::collections::BTreeSet<u32>,
6787
) {
5320
    fn fm_covers(fm: &rust_fontconfig::FontMatch, cp: u32) -> bool {
5320
        fm.unicode_ranges
5320
            .iter()
712940
            .any(|r| cp >= r.start && cp <= r.end)
5320
    }
32057
    fn prune_script_groups(
32057
        groups: &mut Vec<rust_fontconfig::ScriptFallbackGroup>,
32057
        used_chars: &std::collections::BTreeSet<u32>,
32057
    ) {
32057
        for group in groups.iter_mut() {
46
            let range = group.range;
108
            group.fonts.retain(|fm| {
108
                used_chars
108
                    .iter()
208
                    .any(|&cp| cp >= range.start && cp <= range.end && fm_covers(fm, cp))
108
            });
        }
32057
        groups.retain(|g| !g.fonts.is_empty());
32057
    }
32057
    for group in &mut chain.css_fallbacks {
25270
        prune_script_groups(&mut group.script_fonts, used_chars);
25270
        if group.fonts.is_empty() {
3171
            continue;
22099
        }
        // Track which non-ASCII chars still need coverage as we walk
        // matches in order. We always keep at least the first match.
22099
        let mut needed: Vec<u32> = used_chars.iter().copied().collect();
22099
        needed.retain(|&cp| !fm_covers(&group.fonts[0], cp));
22099
        let mut keep = 1;
22100
        for fm in group.fonts.iter().skip(1) {
21891
            if needed.is_empty() {
21469
                break;
422
            }
422
            keep += 1;
1742
            needed.retain(|&cp| !fm_covers(fm, cp));
        }
22099
        group.fonts.truncate(keep);
    }
6787
    prune_script_groups(&mut chain.unicode_fallbacks, used_chars);
6787
}
/// Scan text-node content in `styled_dom` and return the subset of
/// [`rust_fontconfig::DEFAULT_UNICODE_FALLBACK_SCRIPTS`] whose code-point
/// ranges actually appear in any text.
///
/// Short-circuits once all seven
/// ranges have been seen.
///
/// Callers pass the result as `scripts_hint` to
/// [`resolve_font_chains`] / [`collect_and_resolve_font_chains_with_registration`];
/// `rust_fontconfig::FcFontCache::resolve_font_chain_with_scripts` then
/// only pulls in Unicode-fallback fonts for scripts the document
/// actually uses. An ASCII-only page returns an empty vector, which
/// avoids dragging Arial Unicode MS, CJK fonts, etc. into the
/// resolved chain and therefore into the eager-load step.
#[must_use]
9039
pub fn scripts_present_in_styled_dom(styled_dom: &StyledDom) -> Vec<UnicodeRange> {
9039
    let scripts = DEFAULT_UNICODE_FALLBACK_SCRIPTS;
9039
    let mut seen = vec![false; scripts.len()];
9039
    let mut hits = 0usize;
9039
    let node_data = styled_dom.node_data.as_container();
262504
    'outer: for node in node_data.internal {
253465
        let text: &str = match &node.node_type {
88166
            NodeType::Text(s) => s.as_str(),
165299
            _ => continue,
        };
964963
        for c in text.chars() {
964963
            let cp = c as u32;
            // Cheap reject: everything below the first fallback-script
            // range (Cyrillic starts at U+0400) is covered by the CSS
            // fallbacks' own glyphs — no reason to probe.
964963
            if cp < 0x0400 {
963111
                continue;
1852
            }
12843
            for (idx, r) in scripts.iter().enumerate() {
12843
                if !seen[idx] && cp >= r.start && cp <= r.end {
41
                    seen[idx] = true;
41
                    hits += 1;
41
                    if hits == scripts.len() {
                        break 'outer;
41
                    }
41
                    break;
12802
                }
            }
        }
    }
9039
    scripts
9039
        .iter()
9039
        .enumerate()
63273
        .filter_map(|(i, r)| if seen[i] { Some(*r) } else { None })
9039
        .collect()
9039
}
/// Resolve font chains for a collected set of stacks.
///
/// `scripts_hint`:
/// - `None` keeps the original "all 7 default scripts" behaviour (Cyrillic / Arabic / Devanagari /
///   Hiragana / Katakana / CJK / Hangul) — equivalent to passing
///   `Some(rust_fontconfig::DEFAULT_UNICODE_FALLBACK_SCRIPTS)`.
/// - `Some(&[])` attaches *no* Unicode fallbacks, suitable for ASCII-only documents. Combined with
///   `prune_chain_to_used_chars` this is what eliminates Arial Unicode MS / CJK / Arabic font loads
///   on Latin-only pages.
/// - `Some(ranges)` attaches fallbacks only for the listed scripts. Production callers compute this
///   via [`scripts_present_in_styled_dom`].
#[must_use]
2
pub fn resolve_font_chains(
2
    collected: &CollectedFontStacks,
2
    fc_cache: &FcFontCache,
2
    scripts_hint: Option<&[UnicodeRange]>,
2
) -> ResolvedFontChains {
2
    resolve_font_chains_with_registry(collected, fc_cache, None, scripts_hint, &HashMap::new())
2
}
/// Split a CSS font stack into (a) the groups that resolve to an in-memory
/// font registered BY FAMILY NAME and (b) the families that still have to
/// be looked up on disk.
///
/// In-memory fonts are the bundled/embedder/test fonts registered with
/// [`crate::text3::cache::FontManager::register_named_font`]. They must be
/// matched here, in azul, because the fast disk resolver
/// (`FcFontRegistry::request_fonts_fast`) only walks file paths and cannot
/// see them at all. Matching is on the NORMALIZED family name, which also
/// makes `font-family: "Foo Bar"` (the CSS parser keeps the quotes) match
/// the registered `Foo Bar`.
6922
fn split_memory_matches(
6922
    font_families: &[String],
6922
    memory_families: &HashMap<String, Vec<crate::text3::cache::MemoryFace>>,
6922
    weight: FcWeight,
6922
    italic: bool,
6922
    oblique: bool,
6922
) -> (
6922
    Vec<rust_fontconfig::CssFallbackGroup>,
6922
    Vec<String>,
6922
    Vec<rust_fontconfig::CssFallbackGroup>,
6922
) {
    use crate::text3::cache::MemoryFontTier;
6922
    let mut groups = Vec::new();
6922
    let mut disk = Vec::new();
6922
    let mut fallback = Vec::new();
32703
    for family in font_families {
25781
        let norm = rust_fontconfig::utils::normalize_family_name(family);
25781
        let faces = memory_families.get(&norm);
        // A primary face IS the family: it wins outright, disk never consulted.
25781
        if let Some(face) = faces
25781
            .and_then(|f| pick_memory_face(f, weight, italic, oblique, MemoryFontTier::Primary))
        {
382
            groups.push(rust_fontconfig::CssFallbackGroup {
382
                css_name: family.clone(),
382
                fonts: vec![face.font_match.clone()],
382
                script_fonts: Vec::new(),
382
            });
382
            continue;
25399
        }
        // Otherwise the disk gets first refusal, and a fallback face - if the
        // caller registered one - waits behind whatever the disk turns up.
25399
        disk.push(family.clone());
25399
        if let Some(face) = faces
25399
            .and_then(|f| pick_memory_face(f, weight, italic, oblique, MemoryFontTier::Fallback))
2
        {
2
            fallback.push(rust_fontconfig::CssFallbackGroup {
2
                css_name: family.clone(),
2
                fonts: vec![face.font_match.clone()],
2
                script_fonts: Vec::new(),
2
            });
25397
        }
    }
6922
    (groups, disk, fallback)
6922
}
/// Choose the registered in-memory face that best matches a CSS
/// `(weight, italic/oblique)` query. Prefers faces whose slant matches the
/// request, then the nearest weight via [`rust_fontconfig::FcWeight::find_best_match`]
/// (the CSS weight-fallback order). A variable face whose `wght` axis spans the
/// requested weight is treated as an exact match.
///
/// This is what makes `font-weight: bold` actually select a registered bold
/// face: several faces (regular, bold, oblique…) share one family name, and this
/// picks among them instead of taking whichever registered last.
386
fn pick_memory_face(
386
    faces: &[crate::text3::cache::MemoryFace],
386
    weight: FcWeight,
386
    italic: bool,
386
    oblique: bool,
386
    tier: crate::text3::cache::MemoryFontTier,
386
) -> Option<&crate::text3::cache::MemoryFace> {
386
    let faces: Vec<&crate::text3::cache::MemoryFace> =
387
        faces.iter().filter(|f| f.tier == tier).collect();
386
    if faces.is_empty() {
2
        return None;
384
    }
384
    let want_slanted = italic || oblique;
    // Prefer faces matching the requested slant; fall back to all faces so a
    // family with only an upright face still resolves for `font-style: italic`.
384
    let slant_pool: Vec<&crate::text3::cache::MemoryFace> = faces
384
        .iter()
384
        .copied()
384
        .filter(|f| (f.italic || f.oblique) == want_slanted)
384
        .collect();
384
    let pool: Vec<&crate::text3::cache::MemoryFace> = if slant_pool.is_empty() {
        faces.clone()
    } else {
384
        slant_pool
    };
    // A variable face whose wght axis covers the request satisfies it exactly.
384
    let req = f32::from(weight as u16);
384
    if let Some(vf) = pool.iter().copied().find(|f| {
384
        f.weight_axis
384
            .is_some_and(|(min, max)| req >= min && req <= max)
384
    }) {
        return Some(vf);
384
    }
    // Otherwise pick the nearest static weight (CSS fallback order).
384
    let avail: Vec<FcWeight> = pool.iter().map(|f| f.weight).collect();
384
    let best = weight.find_best_match(&avail).unwrap_or(weight);
384
    pool.iter()
384
        .copied()
384
        .find(|f| f.weight == best)
384
        .or_else(|| pool.first().copied())
386
}
/// Registry-aware variant of [`resolve_font_chains`].
///
/// When `registry`
/// is `Some`, each chain resolution goes through
/// [`rust_fontconfig::registry::FcFontRegistry::request_and_resolve_with_scripts`]
/// which priority-bumps the builder for families not yet in the
/// snapshot and waits for them — the "scout-on-demand" path that
/// avoids the eager common-stack pre-parse.
///
/// When `registry` is `None`, falls back to
/// [`rust_fontconfig::FcFontCache::resolve_font_chain_with_scripts`]
/// against the passed-in snapshot, which is what
/// [`resolve_font_chains`] does and what every code path did before
/// Phase 3.
#[allow(clippy::implicit_hasher)] // internal; memory_families always uses the default hasher
#[must_use]
9038
pub fn resolve_font_chains_with_registry(
9038
    collected: &CollectedFontStacks,
9038
    fc_cache: &FcFontCache,
9038
    registry: Option<&rust_fontconfig::registry::FcFontRegistry>,
9038
    scripts_hint: Option<&[UnicodeRange]>,
9038
    memory_families: &HashMap<String, Vec<crate::text3::cache::MemoryFace>>,
9038
) -> ResolvedFontChains {
9038
    let _probe = crate::probe::Probe::span("font_chain_resolve");
9038
    let mut chains = HashMap::new();
9038
    let trace_t0 = std::env::var_os("AZ_PAGINATE_TRACE")
9038
        .is_some()
9038
        .then(std::time::Instant::now);
9038
    let mut unresolved: std::collections::BTreeSet<String> = std::collections::BTreeSet::new();
    // Resolve system/file font stacks via fontconfig
15817
    for font_stack in &collected.font_stacks {
6779
        if font_stack.is_empty() {
1
            continue;
6778
        }
        // Build font families list
        // (2026-06-10) Build the key through the ONE canonical constructor
        // (FontChainKey::from_selectors — first-wins dedup + the same empty-stack
        // fallback) so the stored key always matches the shaping-time lookup key.
6778
        let canonical_key = FontChainKey::from_selectors(font_stack);
6778
        let font_families = canonical_key.font_families.clone();
6778
        let weight = font_stack[0].weight;
6778
        let is_italic = font_stack[0].style == FontStyle::Italic;
6778
        let is_oblique = font_stack[0].style == FontStyle::Oblique;
6778
        let cache_key = FontChainKeyOrRef::Chain(FontChainKey {
6778
            font_families: font_families.clone(),
6778
            weight,
6778
            italic: is_italic,
6778
            oblique: is_oblique,
6778
        });
6778
        if std::env::var("TEXTDBG").is_ok() {
            eprintln!("[TEXTDBG] CHAIN STORE key={cache_key:?}");
6778
        }
        // Skip if already resolved
6778
        if chains.contains_key(&cache_key) {
            continue;
6778
        }
        // Resolve the font chain
        // IMPORTANT: Use False (not DontCare) when style is Normal.
        // DontCare means "accept italic too" which can match italic fonts.
        // False means "must NOT be italic" which correctly prefers Normal.
6778
        let italic = if is_italic {
20
            PatternMatch::True
        } else {
6758
            PatternMatch::False
        };
6778
        let oblique = if is_oblique {
            PatternMatch::True
        } else {
6778
            PatternMatch::False
        };
        // MEMORY FONTS FIRST (see `split_memory_matches`): a family
        // registered by name into the cache's in-memory table wins over
        // anything on disk, exactly as CSS says.
6778
        let (mem_groups, disk_families, mem_fallbacks) = split_memory_matches(
6778
            &font_families,
6778
            memory_families,
6778
            weight,
6778
            is_italic,
6778
            is_oblique,
6778
        );
        // Registry-aware resolve: scout-on-demand path when available.
        // See `resolve_font_chains_with_registry` doc for rationale.
6778
        let mut chain = if disk_families.is_empty() {
            FontFallbackChain::empty(&font_families)
        } else {
6778
            registry.map_or_else(
6778
                || {
6778
                    let mut trace = Vec::new();
6778
                    fc_cache.resolve_font_chain_with_scripts(
6778
                        &disk_families,
6778
                        weight,
6778
                        italic,
6778
                        oblique,
6778
                        scripts_hint,
6778
                        &mut trace,
                    )
6778
                },
                |reg| {
                    reg.request_and_resolve_with_scripts(
                        &disk_families,
                        weight,
                        italic,
                        oblique,
                        scripts_hint,
                    )
                },
            )
        };
6778
        if !mem_groups.is_empty() {
279
            let mut merged = mem_groups;
279
            merged.append(&mut chain.css_fallbacks);
279
            chain.css_fallbacks = merged;
6499
        }
        // Fallback-tier faces go on the END: the disk has already had its turn,
        // so on a desktop these sit harmlessly behind the installed fonts, and
        // on a target with nothing installed they are what is left.
6778
        chain.css_fallbacks.extend(mem_fallbacks);
        // A family that produced no group matched NOTHING — record it (see
        // `ResolvedFontChains::unresolved_families`). Generics are exempt:
        // rust-fontconfig expands them itself, and a generic with no faces
        // is the empty-system case `ensure_chains_nonempty` handles, not an
        // authoring mistake.
32043
        for family in &font_families {
25265
            let matched = chain
25265
                .css_fallbacks
25265
                .iter()
82784
                .any(|g| g.css_name.eq_ignore_ascii_case(family) && !g.fonts.is_empty());
25265
            if !matched && !is_generic_family(family) {
2210
                unresolved.insert(family.clone());
23055
            }
        }
6778
        chains.insert(cache_key, chain);
    }
    // NOTE: FontRefs bypass fontconfig entirely — the shaping code checks
    // style.font_stack for FontStack::Ref and uses the font data directly.
    // No entries are inserted into `chains` for them.
9038
    let mut out = ResolvedFontChains {
9038
        chains,
9038
        unresolved_families: unresolved,
9038
        last_resort_chains: 0,
9038
    };
9038
    ensure_chains_nonempty(&mut out, fc_cache);
9038
    if let Some(t0) = trace_t0 {
        eprintln!(
            "[paginate]   resolve_font_chains_with_registry {:?}: {} chain(s), {} unresolved \
             family name(s), {} last-resort chain(s)",
            t0.elapsed(),
            out.chains.len(),
            out.unresolved_families.len(),
            out.last_resort_chains,
        );
9038
    }
9038
    report_unresolved_families(&out);
9038
    out
9038
}
/// The first `(pattern, id)` in the font cache, WITHOUT cloning the whole
/// database.
///
/// `FcFontCache::list()` allocates a `Vec<(FcPattern, FontId)>` and clones
/// every pattern in it — and each `FcPattern` owns several `String`s. Call
/// sites here only ever wanted `.first()`, so the entire font database was
/// being deep-copied to read one entry. heaptrack on a 3-page document
/// counted 717429 `String::clone` calls with `FcPattern::clone` /
/// `FcFontMetadata::clone` on the backtrace, retaining 2.3 MB.
///
/// rust-fontconfig documents `for_each_pattern` as "avoids the per-entry
/// clone that `list` incurs"; it has no early exit, so this keeps the first
/// hit and ignores the rest — one clone instead of N.
9098
fn first_font_in_cache(fc_cache: &FcFontCache) -> Option<(rust_fontconfig::FcPattern, FontId)> {
9098
    let mut first = None;
516534
    fc_cache.for_each_pattern(|pattern, id| {
516534
        if first.is_none() {
9086
            first = Some((pattern.clone(), *id));
507448
        }
516534
    });
9098
    first
9098
}
/// The ONE last-resort rule: a chain that matched nothing at all gets the
/// first font in the cache as its `last_resort`, so text renders in SOME
/// font instead of measuring 0 (`LayoutError::InvalidTree`).
///
/// Both resolvers call this before returning, so no caller has to remember
/// to. The face goes on `FontFallbackChain::last_resort`, the tier
/// rust-fontconfig 5 reserves for exactly this - `resolve_codepoint` hands
/// it out tagged `LAST_RESORT_SOURCE`, so coverage decisions
/// (`crate::text3::cache::covering_font`) can tell "this font has the glyph"
/// from "nothing has it, draw something" - and `prune_chain_to_used_chars`
/// never touches that tier, so pruning cannot re-empty the chain.
///
/// azul does NOT populate `FcFallbackConfig::last_resort` for this: that
/// tier is resolved eagerly into EVERY chain and its faces are loaded with
/// the chain, whereas this only touches chains that came back empty.
///
/// Applied LIFT-SAFELY: the lifted (web) backend drops in-place mutations
/// made through `values_mut()` - the pushed `FontMatch` is silently lost,
/// same class as the cascade `From` mapped-collect drop - and mis-lifts the
/// `pattern.unicode_ranges.clone()` Vec-clone. So this rebuilds the map with
/// an explicit `for` loop and pushes a face with `Vec::new()` ranges (the
/// convention across this file for "no range restriction").
9098
fn ensure_chains_nonempty(resolved: &mut ResolvedFontChains, fc_cache: &FcFontCache) {
9098
    let Some((_pattern, fallback_id)) = first_font_in_cache(fc_cache) else {
12
        return;
    };
9086
    let keys: Vec<FontChainKeyOrRef> = resolved.chains.keys().cloned().collect();
9086
    let mut rebuilt: HashMap<FontChainKeyOrRef, FontFallbackChain> = HashMap::new();
9086
    let mut last_resort = 0usize;
15994
    for key in keys {
6908
        if let Some(mut chain) = resolved.chains.remove(&key) {
6908
            if chain.fonts().next().is_none() {
                // NOT SILENT: this chain matched nothing at all. Every such
                // chain gets the SAME arbitrary `fallback_id` — which is
                // precisely how N distinct font-families collapsed onto one
                // FontId. It still renders (a missing font must never be a
                // blank screen), but it is now counted and reported.
                last_resort += 1;
                if let FontChainKeyOrRef::Chain(k) = &key {
                    eprintln!(
                        "[azul][font] LAST-RESORT fallback for font stack {:?}: nothing in the \
                         stack matched, rendering in an arbitrary system font.",
                        k.font_families
                    );
                }
                chain.last_resort.push(rust_fontconfig::FontMatch {
                    id: fallback_id,
                    unicode_ranges: Vec::new(),
                    fallbacks: Vec::new(),
                });
6908
            }
6908
            rebuilt.insert(key, chain);
        }
    }
9086
    resolved.chains = rebuilt;
9086
    resolved.last_resort_chains = last_resort;
9098
}
/// Convenience function that collects and resolves font chains in one call
///
/// # Arguments
/// * `styled_dom` - The styled DOM to extract font stacks from
/// * `fc_cache` - The fontconfig cache to resolve fonts against
/// * `platform` - The current platform for resolving system font types
///
/// # Returns
/// A `ResolvedFontChains` containing all resolved font chains
/// Collect font stacks, register embedded fonts, and resolve font chains
/// in a single pass over the DOM nodes. Replaces the old two-pass approach
/// where `register_embedded_fonts_from_styled_dom` + `collect_and_resolve_font_chains`
/// each independently scanned all nodes.
#[must_use]
7710
pub fn collect_and_resolve_font_chains_with_registration<T: ParsedFontTrait>(
7710
    styled_dom: &StyledDom,
7710
    fc_cache: &FcFontCache,
7710
    font_manager: &crate::text3::cache::FontManager<T>,
7710
    platform: &azul_css::system::Platform,
7710
) -> ResolvedFontChains {
7710
    let collected = collect_font_stacks_from_styled_dom(styled_dom, platform);
    // Register embedded FontRefs (from the same scan, no second pass)
7710
    for font_ref in collected.font_refs.values() {
20
        font_manager.register_embedded_font(font_ref);
20
    }
    // Fast path (rust-fontconfig 4.2): when a registry is attached
    // we can resolve each stack by cmap-probing candidate files
    // against the codepoints the DOM actually uses, instead of
    // letting `request_fonts` eagerly parse every CSS fallback
    // via allsorts. On excel.html this drops `font_chain_resolve`
    // from ~128 ms / 49 faces parsed to ~5 ms / 3 faces.
    //
    // Falls back to the legacy pattern-map resolver when:
    //   - no registry is present (offline `FcFontCache` callers)
    //   - the DOM has no text codepoints (no shaping to be done, so cmap-probing has nothing to
    //     check and partial-cover entries would be surprising)
7710
    if let Some(registry) = font_manager.registry.as_deref() {
15
        let used_chars = collect_used_codepoints_all(styled_dom);
15
        if !used_chars.is_empty() {
15
            let mut fast = resolve_font_chains_fast(
15
                &collected,
15
                registry,
15
                &used_chars,
15
                &font_manager.memory_families,
            );
15
            extend_chains_to_cover(&mut fast, &used_chars, fc_cache, Some(registry));
15
            return fast;
        }
7695
    }
    // Legacy path: pattern-map resolver. Only reached when the
    // caller passes an `FcFontCache` without a live registry
    // (ad-hoc tests, the PDF writer, etc.).
7695
    let scripts = scripts_present_in_styled_dom(styled_dom);
7695
    let mut resolved = resolve_font_chains_with_registry(
7695
        &collected,
7695
        fc_cache,
7695
        font_manager.registry.as_deref(),
7695
        Some(&scripts),
7695
        &font_manager.memory_families,
    );
7695
    let used_chars = collect_used_codepoints(styled_dom);
7707
    for chain in resolved.chains.values_mut() {
5419
        prune_chain_to_used_chars(chain, &used_chars);
5419
    }
    // AFTER the prune (the prune keeps faces for the chars the DOM uses; this
    // adds faces for the chars nothing in the chain covers — Hebrew, Thai,
    // anything outside the seven `scripts_present_in_styled_dom` blocks).
7695
    let used_chars: std::collections::BTreeSet<char> = used_chars
7695
        .iter()
7695
        .filter_map(|cp| char::from_u32(*cp))
7695
        .collect();
7695
    extend_chains_to_cover(
7695
        &mut resolved,
7695
        &used_chars,
7695
        fc_cache,
7695
        font_manager.registry.as_deref(),
    );
    // No last-resort step here: the resolver already applied
    // `ensure_chains_nonempty`, and the face it added sits on
    // `last_resort`, which the prune above never touches.
7695
    resolved
7710
}
/// Fast-path resolver backed by [`FcFontRegistry::request_fonts_fast`].
///
/// Iterates `collected.font_stacks`, shapes each `(stack, weight,
/// italic, oblique)` combo into a cmap-probe request carrying the
/// DOM's codepoint set, calls the registry, and returns a
/// `ResolvedFontChains` keyed by `FontChainKeyOrRef::Chain` — the
/// same keys the legacy resolver emits, so downstream code
/// (`load_missing_for_chains`, `shape_with_font_fallback`) is
/// unchanged.
#[allow(clippy::implicit_hasher)] // internal; memory_families always uses the default hasher
60
pub fn resolve_font_chains_fast(
60
    collected: &CollectedFontStacks,
60
    registry: &rust_fontconfig::registry::FcFontRegistry,
60
    codepoints: &std::collections::BTreeSet<char>,
60
    memory_families: &HashMap<String, Vec<crate::text3::cache::MemoryFace>>,
60
) -> ResolvedFontChains {
    use rust_fontconfig::PatternMatch;
    static DBG: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
60
    let dbg = *DBG.get_or_init(|| std::env::var_os("AZ_FAST_RESOLVE_DEBUG").is_some());
60
    let mut chains: HashMap<FontChainKeyOrRef, FontFallbackChain> = HashMap::new();
60
    let mut unresolved: std::collections::BTreeSet<String> = std::collections::BTreeSet::new();
200
    for font_stack in &collected.font_stacks {
140
        if font_stack.is_empty() {
            continue;
140
        }
        // (2026-06-10) Build the key through the ONE canonical constructor
        // (FontChainKey::from_selectors — first-wins dedup + the same empty-stack
        // fallback) so the stored key always matches the shaping-time lookup key.
140
        let canonical_key = FontChainKey::from_selectors(font_stack);
140
        let font_families = canonical_key.font_families.clone();
140
        let weight = font_stack[0].weight;
140
        let is_italic = font_stack[0].style == FontStyle::Italic;
140
        let is_oblique = font_stack[0].style == FontStyle::Oblique;
140
        let cache_key = FontChainKeyOrRef::Chain(FontChainKey {
140
            font_families: font_families.clone(),
140
            weight,
140
            italic: is_italic,
140
            oblique: is_oblique,
140
        });
140
        if chains.contains_key(&cache_key) {
            continue;
140
        }
140
        let italic_match = if is_italic {
            PatternMatch::True
        } else {
140
            PatternMatch::False
        };
        // ── MEMORY FONTS FIRST ──────────────────────────────────────────
        // `request_fonts_fast` only knows about fonts that exist as FILES
        // (it walks the registry's `known_paths`). A family registered via
        // `FontManager::register_named_font` (bundled embedder font, the
        // built-in mock test fonts) lives only in the `FcFontCache`'s
        // memory-font table and is INVISIBLE to it — such a family silently
        // fell through to a system fallback on every production build
        // (production always has a live registry, so it always took this
        // path). Match memory families by name here, in CSS order, and only
        // hand the remaining families to the disk probe.
140
        let (mut css_fallbacks, disk_families, mem_fallbacks) = split_memory_matches(
140
            &font_families,
140
            memory_families,
140
            weight,
140
            is_italic,
140
            is_oblique,
140
        );
140
        let request = vec![(disk_families.clone(), codepoints.clone())];
140
        let mut chains_out = if disk_families.is_empty() {
            Vec::new()
        } else {
140
            registry.request_fonts_fast(&request, weight, italic_match)
        };
140
        if dbg {
            let total_fonts: usize = chains_out
                .iter()
                .map(|c| c.css_fallbacks.iter().map(|g| g.fonts.len()).sum::<usize>())
                .sum();
            eprintln!(
                "[FAST] stack {:?} w={:?} i={:?} → {} groups, {} faces",
                font_families,
                weight,
                italic_match,
                chains_out.first().map_or(0, |c| c.css_fallbacks.len()),
                total_fonts,
            );
140
        }
        // Merge: memory-matched groups (in CSS order) + whatever the disk
        // probe found for the remaining families.
140
        let mut chain = chains_out
140
            .pop()
140
            .unwrap_or_else(|| FontFallbackChain::empty(&font_families));
140
        if !css_fallbacks.is_empty() {
90
            css_fallbacks.append(&mut chain.css_fallbacks);
90
            chain.css_fallbacks = css_fallbacks;
90
        }
        // Fallback-tier faces go on the END: the disk has already had its turn,
        // so on a desktop these sit harmlessly behind the installed fonts, and
        // on a target with nothing installed they are what is left.
140
        chain.css_fallbacks.extend(mem_fallbacks);
        // A family AHEAD of the first matched one produced no group: it
        // matched NOTHING, and the text renders in a later family instead.
        // Record it — a silently-unmatched family is the root cause of
        // "every font-family renders in the same fallback font".
        //
        // Families BEHIND the first match are not judged: the probe stops as
        // soon as the requested chars are covered and skips a family whose
        // faces add no new coverage, so an installed "DejaVu Sans" listed
        // after "Liberation Sans" produces no group either. Reporting those
        // was a wall of false "UNRESOLVED" lines for fonts that are on disk.
240
        let matched = |family: &String| {
240
            chain
240
                .css_fallbacks
240
                .iter()
240
                .any(|g| g.css_name.eq_ignore_ascii_case(family) && !g.fonts.is_empty())
240
        };
240
        for family in font_families.iter().take_while(|f| !matched(f)) {
150
            if !is_generic_family(family) {
                unresolved.insert(family.clone());
150
            }
        }
140
        chains.insert(cache_key, chain);
    }
60
    let mut out = ResolvedFontChains {
60
        chains,
60
        unresolved_families: unresolved,
60
        last_resort_chains: 0,
60
    };
60
    ensure_chains_nonempty(&mut out, &registry.shared_cache());
60
    report_unresolved_families(&out);
60
    out
60
}
/// Give every chain a face for each of the DOM's codepoints it cannot draw.
///
/// Both resolvers leave gaps. `request_fonts_fast` expands the stack through
/// the fallback config (the generic's families plus the script candidates
/// for the SEVEN default scripts) and probes those files' cmaps against the
/// DOM's codepoints; a codepoint outside those scripts that no listed family
/// covers is a miss for the shaper's .notdef - Hebrew or Thai in a Latin
/// `sans-serif` stack, on a machine whose sans list has no such face. The
/// legacy resolver attaches script fallbacks only for the blocks
/// `scripts_present_in_styled_dom` reports, with the same gap. And neither
/// resolver knows the in-memory fonts. [`faces_covering`] runs the
/// script-aware lookup for exactly the chars left uncovered and what it
/// finds is appended as one more unicode-fallback group; the steady state
/// for a document in a script its stack covers is no work at all.
///
/// Coverage is judged by [`covering_font`], which does NOT count the
/// last-resort face: that face is there so SOMETHING draws, not because it
/// has the glyph. Whitespace, controls and default-ignorables are not asked
/// for (see `needs_own_glyph`); a face's coverage is judged by the
/// `unicode_ranges` its match carries, since nothing is loaded yet at this
/// point. Under rust-fontconfig 5 those ranges are the font's exact cmap
/// segments - OS/2's `ulUnicodeRange` is no longer consulted, and the block
/// probes that used to round a single glyph up to its whole Unicode block
/// are gone.
9096
fn extend_chains_to_cover(
9096
    resolved: &mut ResolvedFontChains,
9096
    used_chars: &std::collections::BTreeSet<char>,
9096
    fc_cache: &FcFontCache,
9096
    registry: Option<&rust_fontconfig::registry::FcFontRegistry>,
9096
) {
    use crate::text3::cache::{
        append_coverage_faces, covering_font, faces_covering, needs_own_glyph,
    };
9096
    let wanted: Vec<char> = used_chars
9096
        .iter()
9096
        .copied()
9096
        .filter(|c| needs_own_glyph(*c))
9096
        .collect();
9096
    if wanted.is_empty() {
8776
        return;
320
    }
790
    for (key, chain) in &mut resolved.chains {
470
        let FontChainKeyOrRef::Chain(key) = key else {
            continue;
        };
470
        let uncovered: std::collections::BTreeSet<char> = wanted
470
            .iter()
470
            .copied()
1610
            .filter(|c| covering_font(chain, *c).is_none())
470
            .collect();
470
        if uncovered.is_empty() {
450
            continue;
20
        }
20
        let added = faces_covering(key, chain, uncovered, fc_cache, registry, &|_, _| None);
20
        append_coverage_faces(chain, added);
    }
9096
}
/// Log every family the resolver could not match, ONCE per process per
/// family name.
///
/// This is the diagnostic that was missing. Before this, a stylesheet
/// asking for `font-family: Arial` on a box with no Arial installed got a
/// system fallback and said nothing — so eight different families rendering
/// identically looked like correct behaviour to every test we had.
9099
fn report_unresolved_families(resolved: &ResolvedFontChains) {
    use std::sync::{Mutex, OnceLock};
    static SEEN: OnceLock<Mutex<std::collections::BTreeSet<String>>> = OnceLock::new();
9099
    if resolved.unresolved_families.is_empty() {
8514
        return;
585
    }
585
    let seen = SEEN.get_or_init(|| Mutex::new(std::collections::BTreeSet::new()));
585
    let Ok(mut seen) = seen.lock() else { return };
2796
    for family in &resolved.unresolved_families {
2211
        if seen.insert(family.clone()) {
129
            // Through the diagnostics sink, like every other azul warning:
129
            // `eprintln!` PANICS when stderr has gone away (piping a running
129
            // app into `head` is enough), and a bare print is invisible to the
129
            // ring, so nothing could assert that a missing family was reported.
129
            azul_core::diagnostics::emit(alloc::format!(
129
                "[azul][font] UNRESOLVED font-family {family:?}: no font file and no registered \
129
                 in-memory font matches this family. Text that asks for it renders in a FALLBACK \
129
                 font. Register it with FontManager::register_named_font(), or install it."
129
            ));
2084
        }
    }
9099
}
/// Legacy wrapper: collect + resolve without registration. Kept for
/// backward compatibility; defaults to the full 7-script unicode
/// fallback set.
#[must_use]
pub fn collect_and_resolve_font_chains(
    styled_dom: &StyledDom,
    fc_cache: &FcFontCache,
    platform: &azul_css::system::Platform,
) -> ResolvedFontChains {
    let collected = collect_font_stacks_from_styled_dom(styled_dom, platform);
    resolve_font_chains(&collected, fc_cache, None)
}
/// Legacy wrapper: register only. Prefer `collect_and_resolve_font_chains_with_registration`.
pub fn register_embedded_fonts_from_styled_dom<T: ParsedFontTrait>(
    styled_dom: &StyledDom,
    font_manager: &crate::text3::cache::FontManager<T>,
    platform: &azul_css::system::Platform,
) {
    let collected = collect_font_stacks_from_styled_dom(styled_dom, platform);
    for font_ref in collected.font_refs.values() {
        font_manager.register_embedded_font(font_ref);
    }
}
// Font Loading Functions
use std::collections::HashSet;
use rust_fontconfig::FontId;
/// Extract all unique `FontIds` from resolved font chains
///
/// This function collects all `FontIds` that are referenced in the font chains,
/// which represents the complete set of fonts that may be needed for rendering.
#[must_use]
18551
pub fn collect_font_ids_from_chains(chains: &ResolvedFontChains) -> HashSet<FontId> {
18551
    let mut font_ids = HashSet::new();
    // M12.7: hashbrown's RawIterRange (the .values() iterator below) mis-lifts
    // to wasm and loops forever on an empty map; is_empty() is len-based, so
    // bail out before iterating when there are no chains (web bare-body case).
18551
    if chains.chains.is_empty() {
4513
        return font_ids;
14038
    }
14458
    for chain in chains.chains.values() {
        // Every tier: css groups (+ their script fonts), unicode fallbacks,
        // last resort. `fonts()` dedups within a chain; the set dedups across.
47614
        for font in chain.fonts() {
47614
            font_ids.insert(font.id);
47614
        }
    }
14038
    font_ids
18551
}
/// Compute which fonts need to be loaded (diff with already loaded fonts)
///
/// # Arguments
/// * `required_fonts` - Set of `FontIds` that are needed
/// * `already_loaded` - Set of `FontIds` that are already loaded
///
/// # Returns
/// Set of `FontIds` that need to be loaded
#[allow(clippy::implicit_hasher)] // internal helper; only ever called with the default-hasher HashMap/HashSet
#[must_use]
12264
pub fn compute_fonts_to_load(
12264
    required_fonts: &HashSet<FontId>,
12264
    already_loaded: &HashSet<FontId>,
12264
) -> HashSet<FontId> {
    // M12.7: `.difference()` drives hashbrown's RawIterRange, which mis-lifts
    // to wasm and loops on an empty map. Nothing required → nothing to load.
12264
    if required_fonts.is_empty() {
2517
        return HashSet::new();
9747
    }
9747
    required_fonts.difference(already_loaded).copied().collect()
12264
}
/// Result of loading fonts
#[derive(Debug)]
pub struct FontLoadResult<T> {
    /// Successfully loaded fonts
    pub loaded: HashMap<FontId, T>,
    /// `FontIds` that failed to load, with error messages
    pub failed: Vec<(FontId, String)>,
}
/// Load fonts from disk using the provided loader function
///
/// This is a generic function that works with any font loading implementation.
/// The `load_fn` parameter should be a function that takes font bytes and an index,
/// and returns a parsed font or an error.
///
/// # Arguments
/// * `font_ids` - Set of `FontIds` to load
/// * `fc_cache` - The fontconfig cache to get font paths from
/// * `load_fn` - Function to load and parse font bytes
///
/// # Returns
/// A `FontLoadResult` containing successfully loaded fonts and any failures
#[allow(clippy::implicit_hasher)] // internal helper; only ever called with the default-hasher
                                  // HashMap/HashSet
4999
pub fn load_fonts_from_disk<T, F>(
4999
    font_ids: &HashSet<FontId>,
4999
    fc_cache: &FcFontCache,
4999
    load_fn: F,
4999
) -> FontLoadResult<T>
4999
where
4999
    // Bytes come in as `Arc<FontBytes>` so the loader can retain
4999
    // them cheaply (one `Arc::clone` per retained copy). On disk the
4999
    // backing is an mmap, so untouched glyf/CFF pages don't count
4999
    // toward RSS — the layout shaper only faults in pages it reads.
4999
    F: Fn(
4999
        std::sync::Arc<rust_fontconfig::FontBytes>,
4999
        usize,
4999
    ) -> Result<T, crate::text3::cache::LayoutError>,
{
4999
    let mut loaded = HashMap::new();
4999
    let mut failed = Vec::new();
22758
    for font_id in font_ids {
        // Get font bytes from fc_cache as a shared mmap. Faces backed
        // by the same .ttc all observe the same `Arc<FontBytes>` via
        // rust_fontconfig's `shared_bytes` dedup.
17759
        let Some(font_bytes) = fc_cache.get_font_bytes(font_id) else {
13
            failed.push((
13
                *font_id,
13
                format!("Could not get font bytes for {font_id:?}"),
13
            ));
13
            continue;
        };
        // Get font index (for font collections like .ttc files)
17746
        let font_index = fc_cache
17746
            .get_font_by_id(font_id)
17746
            .map_or(0, |source| match source {
17445
                rust_fontconfig::OwnedFontSource::Disk(path) => path.font_index,
301
                rust_fontconfig::OwnedFontSource::Memory(font) => font.font_index,
17746
            });
        // Load the font using the provided function
17746
        match load_fn(font_bytes, font_index) {
17746
            Ok(font) => {
17746
                loaded.insert(*font_id, font);
17746
            }
            Err(e) => {
                failed.push((*font_id, format!("Failed to parse font {font_id:?}: {e:?}")));
            }
        }
    }
4999
    FontLoadResult { loaded, failed }
4999
}
/// Convenience function to load all required fonts for a styled DOM
///
/// This function:
/// 1. Collects all font stacks from the DOM
/// 2. Resolves them to font chains
/// 3. Extracts all required `FontIds`
/// 4. Computes which fonts need to be loaded (diff with already loaded)
/// 5. Loads the missing fonts
///
/// # Arguments
/// * `styled_dom` - The styled DOM to extract font requirements from
/// * `fc_cache` - The fontconfig cache
/// * `already_loaded` - Set of `FontIds` that are already loaded
/// * `load_fn` - Function to load and parse font bytes
/// * `platform` - The current platform for resolving system font types
///
/// # Returns
/// A tuple of (`ResolvedFontChains`, `FontLoadResult`)
#[allow(clippy::implicit_hasher)] // internal helper; only ever called with the default-hasher
                                  // HashMap/HashSet
pub fn resolve_and_load_fonts<T, F>(
    styled_dom: &StyledDom,
    fc_cache: &FcFontCache,
    already_loaded: &HashSet<FontId>,
    load_fn: F,
    platform: &azul_css::system::Platform,
) -> (ResolvedFontChains, FontLoadResult<T>)
where
    F: Fn(
        std::sync::Arc<rust_fontconfig::FontBytes>,
        usize,
    ) -> Result<T, crate::text3::cache::LayoutError>,
{
    // Step 1-2: Collect and resolve font chains
    let chains = collect_and_resolve_font_chains(styled_dom, fc_cache, platform);
    // Step 3: Extract all required FontIds
    let required_fonts = collect_font_ids_from_chains(&chains);
    // Step 4: Compute diff
    let fonts_to_load = compute_fonts_to_load(&required_fonts, already_loaded);
    // Step 5: Load missing fonts
    let load_result = load_fonts_from_disk(&fonts_to_load, fc_cache, load_fn);
    (chains, load_result)
}
// ============================================================================
// Scrollbar Style Getters
// ============================================================================
use azul_css::props::style::scrollbar::{
    LayoutScrollbarWidth, ScrollbarVisibilityMode, StyleScrollbarColor,
};
/// Computed scrollbar style for a node.
///
/// All visual defaults (colors, width) come from the UA CSS conditional rules
/// in `core/src/ua_css.rs` — individual `CssPropertyWithConditions` entries for
/// `scrollbar-color` and `scrollbar-width`, keyed on `@os` / `@theme`.
///
/// Overlay behaviour (fade timing, visibility, clip) is derived from the
/// resolved `scrollbar-width` mode:
///   - `thin`  → overlay:  fade 500/200 ms, `WhenScrolling`, clip = true
///   - `auto`  → classic:  no fade, `Always`, clip = false
///   - `none`  → hidden:   no fade, `Always`, clip = false
///
/// Per-node CSS overrides (in priority order):
///   1. `-azul-scrollbar-style`  (full `ScrollbarInfo` override)
///   2. `scrollbar-width`        (overrides width + overlay mode)
///   3. `scrollbar-color`        (overrides thumb / track colours)
#[derive(Copy, Debug, Clone)]
pub struct ComputedScrollbarStyle {
    /// The scrollbar width mode (auto/thin/none)
    pub width_mode: LayoutScrollbarWidth,
    /// Visual width in pixels — used for rendering track + thumb.
    /// Non-zero even for overlay scrollbars.
    pub visual_width_px: f32,
    /// Reserve width in pixels — layout space subtracted from content area.
    /// 0 for overlay scrollbars, equal to `visual_width_px` for legacy.
    pub reserve_width_px: f32,
    /// Thumb color
    pub thumb_color: ColorU,
    /// Track color
    pub track_color: ColorU,
    /// Button color (for scroll arrows)
    pub button_color: ColorU,
    /// Corner color (where scrollbars meet)
    pub corner_color: ColorU,
    /// Whether to clip the scrollbar to the container's border-radius
    pub clip_to_container_border: bool,
    /// Delay in ms before scrollbar starts fading out (0 = never fade)
    pub fade_delay_ms: u32,
    /// Duration of fade-out animation in ms (0 = instant)
    pub fade_duration_ms: u32,
    /// Scrollbar visibility mode (always / when-scrolling / auto)
    pub visibility: ScrollbarVisibilityMode,
    /// Whether to show top/bottom (or left/right) arrow buttons.
    /// When false, the track spans the entire scrollbar length.
    pub show_scroll_buttons: bool,
    /// Size of each arrow button in px (square: width = height).
    /// Only used when `show_scroll_buttons == true`.
    pub scroll_button_size_px: f32,
    /// How wide the HANDLE is, in logical px. `None` = fill the groove.
    /// Breeze centres a 6px handle in a 21px groove; deriving the handle from
    /// the groove made every azul scrollbar a fat pill next to a native one.
    pub handle_width_px: Option<f32>,
    /// The handle's corner radius in logical px. `None` = half the handle
    /// width (a capsule).
    pub handle_radius_px: Option<f32>,
    /// Whether to show the corner rect where V and H scrollbars meet.
    pub show_corner_rect: bool,
    /// Thumb color when hovered (None = use `thumb_color`)
    pub thumb_color_hover: Option<ColorU>,
    /// Thumb color when pressed/active (None = use `thumb_color`)
    pub thumb_color_active: Option<ColorU>,
    /// Track color when hovered (None = use `track_color`)
    pub track_color_hover: Option<ColorU>,
    /// Visual width when hovered (None = use `visual_width_px`)
    pub visual_width_px_hover: Option<f32>,
    /// Visual width when pressed (None = use `visual_width_px`)
    pub visual_width_px_active: Option<f32>,
}
impl Default for ComputedScrollbarStyle {
252
    fn default() -> Self {
        // Evaluate UA CSS rules with a default context (no OS info).
        // Picks the unconditional fallback: classic light, auto width.
252
        let ctx = azul_css::dynamic_selector::DynamicSelectorContext::default();
252
        let ua = azul_core::ua_css::evaluate_ua_scrollbar_css(&ctx);
252
        Self::from_ua_resolved(&ua)
252
    }
}
impl ComputedScrollbarStyle {
    /// Build from resolved UA scrollbar CSS properties.
    ///
    /// Each property is read individually from the resolved UA CSS.
787301
    fn from_ua_resolved(ua: &azul_core::ua_css::ResolvedUaScrollbar) -> Self {
787301
        let width_mode = ua.width;
787301
        let visibility = ua.visibility;
787301
        let fade_delay_ms = ua.fade_delay.ms;
787301
        let fade_duration_ms = ua.fade_duration.ms;
787301
        let visual_width_px = match width_mode {
1785
            LayoutScrollbarWidth::Thin => SCROLLBAR_WIDTH_THIN,
785513
            LayoutScrollbarWidth::Auto => SCROLLBAR_WIDTH_AUTO,
3
            LayoutScrollbarWidth::None => 0.0,
        };
        // Overlay scrollbars don't reserve layout space and hide buttons / corner.
787301
        let is_overlay = visibility == ScrollbarVisibilityMode::WhenScrolling;
787301
        let reserve_width_px = if is_overlay { 0.0 } else { visual_width_px };
787301
        let show_scroll_buttons = !is_overlay;
787301
        let scroll_button_size_px = if is_overlay { 0.0 } else { visual_width_px };
787301
        let show_corner_rect = !is_overlay;
787301
        let (thumb_color, track_color) = match ua.color {
787289
            StyleScrollbarColor::Custom(c) => (c.thumb, c.track),
12
            StyleScrollbarColor::Auto => (ColorU::TRANSPARENT, ColorU::TRANSPARENT),
        };
        // Compute hover / active variants:
        // Hover: lighten thumb, widen by +SCROLLBAR_HOVER_EXPAND_PX
        // Active: darken thumb, widen by +SCROLLBAR_HOVER_EXPAND_PX
787301
        let thumb_hover = ColorU {
787301
            r: thumb_color.r.saturating_add(THUMB_HOVER_LIGHTEN),
787301
            g: thumb_color.g.saturating_add(THUMB_HOVER_LIGHTEN),
787301
            b: thumb_color.b.saturating_add(THUMB_HOVER_LIGHTEN),
787301
            a: thumb_color.a.saturating_add(THUMB_HOVER_ALPHA_ADD),
787301
        };
787301
        let thumb_active = ColorU {
787301
            r: thumb_color.r.saturating_sub(THUMB_ACTIVE_DARKEN),
787301
            g: thumb_color.g.saturating_sub(THUMB_ACTIVE_DARKEN),
787301
            b: thumb_color.b.saturating_sub(THUMB_ACTIVE_DARKEN),
787301
            a: 255,
787301
        };
787301
        let track_hover = ColorU {
787301
            r: track_color.r,
787301
            g: track_color.g,
787301
            b: track_color.b,
787301
            a: track_color.a.saturating_add(THUMB_HOVER_ALPHA_ADD),
787301
        };
787301
        let hover_width = visual_width_px + SCROLLBAR_HOVER_EXPAND_PX;
787301
        let active_width = visual_width_px + SCROLLBAR_HOVER_EXPAND_PX;
787301
        Self {
787301
            // The UA sheet has no handle geometry to state; the platform fills
787301
            // these in below, and `None` keeps the renderer's derived default.
787301
            handle_width_px: None,
787301
            handle_radius_px: None,
787301
            width_mode,
787301
            visual_width_px,
787301
            reserve_width_px,
787301
            thumb_color,
787301
            track_color,
787301
            button_color: ColorU::TRANSPARENT,
787301
            corner_color: ColorU::TRANSPARENT,
787301
            clip_to_container_border: is_overlay,
787301
            fade_delay_ms,
787301
            fade_duration_ms,
787301
            visibility,
787301
            show_scroll_buttons,
787301
            scroll_button_size_px,
787301
            show_corner_rect,
787301
            thumb_color_hover: Some(thumb_hover),
787301
            thumb_color_active: Some(thumb_active),
787301
            track_color_hover: Some(track_hover),
787301
            visual_width_px_hover: Some(hover_width),
787301
            visual_width_px_active: Some(active_width),
787301
        }
787301
    }
}
/// Get the computed scrollbar style for a node.
///
/// Resolution order (later wins):
///   1. UA scrollbar CSS (`CssPropertyWithConditions` in `ua_css.rs`, evaluated via `@os` /
///      `@theme` conditions)
///   2. CSS `-azul-scrollbar-style` (full `ScrollbarInfo` customisation)
///   3. CSS `scrollbar-width`  (overrides width only)
///   4. CSS `scrollbar-color`  (overrides thumb / track colours)
///   5. CSS `-azul-scrollbar-visibility` (overrides visibility + clip)
///   6. CSS `-azul-scrollbar-fade-delay` (overrides fade delay)
///   7. CSS `-azul-scrollbar-fade-duration` (overrides fade duration)
///
/// When `system_style` is `None`, falls back to the unconditional UA rule
/// (classic light scrollbar).
#[allow(clippy::too_many_lines)] // large but cohesive: single-purpose layout/render/parse routine (one branch per case)
#[must_use]
787035
pub fn get_scrollbar_style(
787035
    styled_dom: &StyledDom,
787035
    node_id: NodeId,
787035
    node_state: &StyledNodeState,
787035
    system_style: Option<&azul_css::system::SystemStyle>,
787035
) -> ComputedScrollbarStyle {
787035
    let node_data = &styled_dom.node_data.as_container()[node_id];
    // Step 1: Evaluate UA scrollbar CSS using the DynamicSelector system —
    // against the context the DOM was CASCADED under (it carries the
    // window's own theme, viewport and OS), so the scrollbar follows an
    // in-app theme switch like everything else does. A DOM no window has
    // adopted yet falls back to a system-style-only context.
787035
    let ctx = styled_dom
787035
        .get_css_property_cache()
787035
        .dynamic_context
787035
        .as_deref()
787035
        .cloned()
787035
        .unwrap_or_else(|| {
30777
            system_style.map_or_else(
                azul_css::dynamic_selector::DynamicSelectorContext::default,
                azul_css::dynamic_selector::DynamicSelectorContext::from_system_style,
            )
30777
        });
    // AZ_DUMP_SCROLLBAR_OS=1 prints, once, which OS the UA cascade actually
    // resolved against. `DynamicSelectorContext::default()` carries
    // `OsCondition::Any`, which matches NO `@os(...)` arm — so a window built
    // from `SystemStyle::default()` silently takes every fallback branch and
    // there is no way to tell from the rendering alone whether you are looking
    // at "the platform's scrollbars" or "the fallback that happens to render".
    #[cfg(feature = "std")]
    {
        use core::sync::atomic::{AtomicBool, Ordering};
        static DUMPED: AtomicBool = AtomicBool::new(false);
787035
        if !DUMPED.swap(true, Ordering::Relaxed)
42
            && std::env::var_os("AZ_DUMP_SCROLLBAR_OS").is_some()
        {
            std::eprintln!(
                "[azul][scrollbar] system_style={} os={:?} visibility={:?} width={:?}",
                if system_style.is_some() {
                    "Some"
                } else {
                    "NONE"
                },
                ctx.os,
                azul_core::ua_css::evaluate_ua_scrollbar_css(&ctx).visibility,
                azul_core::ua_css::evaluate_ua_scrollbar_css(&ctx).width,
            );
787035
        }
    }
787035
    let ua = azul_core::ua_css::evaluate_ua_scrollbar_css(&ctx);
787035
    let mut result = ComputedScrollbarStyle::from_ua_resolved(&ua);
    // `scrollbar-color: auto` means "the platform's own scrollbar colours",
    // and `from_ua_resolved` can only answer TRANSPARENT for it — it has no
    // system style to ask. So an app that sets no scrollbar CSS (almost all of
    // them) drew a fully transparent thumb on a fully transparent track: an
    // invisible scrollbar that only "appears" where a hover/active variant
    // happens to add alpha. `SystemStyle::scrollbar` has carried the right
    // colours the whole time (Breeze/Adwaita/Aqua/Windows presets, or whatever
    // discovery read off the desktop) and nothing consumed them.
    //
    // Applied BEFORE the author-CSS steps below, so an explicit
    // `::-webkit-scrollbar-thumb { background: … }` still wins.
    // The UA sheet carries GENERIC constants (`@theme dark { scrollbar-color:
    // #646464 #2d2d2d }`), which it emits as a `Custom` value — so gating this
    // on `Auto` meant the UA fallback silently beat the real desktop palette
    // on every themed platform, and a detected KDE/GNOME scrollbar never
    // reached the screen. A detected palette outranks a hardcoded UA constant;
    // AUTHOR css still wins, because it is applied in the steps below.
    {
787035
        if let Some(sys) = system_style.and_then(|s| s.scrollbar.as_deref()) {
1330
            if let Some(thumb) = sys.thumb_color {
1330
                result.thumb_color = thumb;
1330
            }
1330
            if let Some(track) = sys.track_color {
1330
                result.track_color = track;
1330
                // The buttons and the corner are part of the track furniture.
1330
                result.button_color = track;
1330
                result.corner_color = track;
1330
            }
            // The platform's HANDLE geometry — a Breeze handle is 6px in a
            // 21px groove, not a pill filling the track.
1330
            if sys.handle_width.is_some() {
                result.handle_width_px = sys.handle_width;
1330
            }
1330
            if sys.handle_radius.is_some() {
                result.handle_radius_px = sys.handle_radius;
1330
            }
785705
        }
    }
787035
    let result = result;
    // FAST PATH: 99% of nodes have no scrollbar CSS. Bail before walking 8 × cascade.
787035
    if node_state.is_normal() {
786932
        if let Some(ref cc) = styled_dom.css_property_cache.ptr.compact_cache {
786931
            if !cc.has_scrollbar_css(node_id.index()) {
786401
                return result;
530
            }
1
        }
103
    }
634
    let mut result = result;
    // Step 2: Check individual scrollbar part backgrounds
634
    if let Some(track) = styled_dom
634
        .css_property_cache
634
        .ptr
634
        .get_scrollbar_track(node_data, &node_id, node_state)
634
        .and_then(|v| v.get_property())
    {
        result.track_color = extract_color_from_background(track);
634
    }
634
    if let Some(thumb) = styled_dom
634
        .css_property_cache
634
        .ptr
634
        .get_scrollbar_thumb(node_data, &node_id, node_state)
634
        .and_then(|v| v.get_property())
    {
        result.thumb_color = extract_color_from_background(thumb);
634
    }
634
    if let Some(button) = styled_dom
634
        .css_property_cache
634
        .ptr
634
        .get_scrollbar_button(node_data, &node_id, node_state)
634
        .and_then(|v| v.get_property())
    {
        result.button_color = extract_color_from_background(button);
634
    }
634
    if let Some(corner) = styled_dom
634
        .css_property_cache
634
        .ptr
634
        .get_scrollbar_corner(node_data, &node_id, node_state)
634
        .and_then(|v| v.get_property())
    {
        result.corner_color = extract_color_from_background(corner);
634
    }
    // Step 3: Check for scrollbar-width (overrides width only, not overlay)
634
    if let Some(scrollbar_width) = styled_dom
634
        .css_property_cache
634
        .ptr
634
        .get_scrollbar_width(node_data, &node_id, node_state)
634
        .and_then(|v| v.get_property())
    {
530
        result.width_mode = *scrollbar_width;
530
        let w = match scrollbar_width {
            LayoutScrollbarWidth::Auto => SCROLLBAR_WIDTH_AUTO,
            LayoutScrollbarWidth::Thin => SCROLLBAR_WIDTH_THIN,
530
            LayoutScrollbarWidth::None => 0.0,
        };
530
        result.visual_width_px = w;
530
        if result.visibility != ScrollbarVisibilityMode::WhenScrolling {
530
            result.reserve_width_px = w;
530
        }
104
    }
    // Step 4: Check for scrollbar-color (overrides thumb/track colors)
634
    if let Some(scrollbar_color) = styled_dom
634
        .css_property_cache
634
        .ptr
634
        .get_scrollbar_color(node_data, &node_id, node_state)
634
        .and_then(|v| v.get_property())
    {
        match scrollbar_color {
            StyleScrollbarColor::Auto => { /* keep */ }
            StyleScrollbarColor::Custom(custom) => {
                result.thumb_color = custom.thumb;
                result.track_color = custom.track;
            }
        }
634
    }
    // Step 5: Check for -azul-scrollbar-visibility
634
    if let Some(vis) = styled_dom
634
        .css_property_cache
634
        .ptr
634
        .get_scrollbar_visibility(node_data, &node_id, node_state)
634
        .and_then(|v| v.get_property())
    {
        result.visibility = *vis;
        result.clip_to_container_border = *vis == ScrollbarVisibilityMode::WhenScrolling;
        // Overlay mode: no reserved layout space, hide buttons and corner
        let is_overlay = *vis == ScrollbarVisibilityMode::WhenScrolling;
        if is_overlay {
            result.reserve_width_px = 0.0;
            result.show_scroll_buttons = false;
            result.scroll_button_size_px = 0.0;
            result.show_corner_rect = false;
        } else {
            result.reserve_width_px = result.visual_width_px;
        }
634
    }
    // Step 6: Check for -azul-scrollbar-fade-delay
634
    if let Some(delay) = styled_dom
634
        .css_property_cache
634
        .ptr
634
        .get_scrollbar_fade_delay(node_data, &node_id, node_state)
634
        .and_then(|v| v.get_property())
    {
        result.fade_delay_ms = delay.ms;
634
    }
    // Step 7: Check for -azul-scrollbar-fade-duration
634
    if let Some(dur) = styled_dom
634
        .css_property_cache
634
        .ptr
634
        .get_scrollbar_fade_duration(node_data, &node_id, node_state)
634
        .and_then(|v| v.get_property())
    {
        result.fade_duration_ms = dur.ms;
634
    }
634
    result
787035
}
/// Cached wrapper for [`get_scrollbar_style`] that reuses the
/// memo stored on `LayoutContext`.
///
/// The underlying call performs
/// 9 cascade walks per node (track/thumb/button/corner/width/
/// color/visibility/fade-delay/fade-duration). The BFC, Taffy,
/// and display-list callers all hit the same node many times
/// inside a single layout pass, so caching turns ~21 rebuilds per
/// node into one.
///
/// Falls back to the uncached `get_scrollbar_style` when no ctx
/// is available (shouldn't happen in the current code paths).
1159523
pub fn get_scrollbar_style_cached<T: ParsedFontTrait>(
1159523
    ctx: &crate::solver3::LayoutContext<'_, T>,
1159523
    node_id: NodeId,
1159523
    node_state: &StyledNodeState,
1159523
) -> ComputedScrollbarStyle {
1159523
    if let Some(s) = ctx.scrollbar_style_cache.borrow().get(&node_id) {
398442
        return *s;
761081
    }
761081
    let style = get_scrollbar_style(
761081
        ctx.styled_dom,
761081
        node_id,
761081
        node_state,
761081
        ctx.system_style.as_deref(),
    );
761081
    ctx.scrollbar_style_cache
761081
        .borrow_mut()
761081
        .insert(node_id, style);
761081
    style
1159523
}
/// Helper to extract a solid color from a `StyleBackgroundContent`
8
const fn extract_color_from_background(
8
    bg: &azul_css::props::style::background::StyleBackgroundContent,
8
) -> ColorU {
    use azul_css::props::style::background::StyleBackgroundContent;
8
    match bg {
5
        StyleBackgroundContent::Color(c) => *c,
3
        _ => ColorU::TRANSPARENT,
    }
8
}
/// Check if a node should clip its scrollbar to the container's border-radius
#[must_use]
pub fn should_clip_scrollbar_to_border(
    styled_dom: &StyledDom,
    node_id: NodeId,
    node_state: &StyledNodeState,
) -> bool {
    let style = get_scrollbar_style(styled_dom, node_id, node_state, None);
    style.clip_to_container_border
}
/// Get the scrollbar visual width in pixels for a node (used for rendering)
#[must_use]
4
pub fn get_scrollbar_width_px(
4
    styled_dom: &StyledDom,
4
    node_id: NodeId,
4
    node_state: &StyledNodeState,
4
) -> f32 {
4
    let style = get_scrollbar_style(styled_dom, node_id, node_state, None);
4
    style.visual_width_px
4
}
/// Checks if text in a node is selectable based on CSS `user-select` property.
///
/// Returns `true` if the text can be selected (default behavior),
/// `false` if `user-select: none` is set.
#[must_use]
345347
pub fn is_text_selectable(
345347
    styled_dom: &StyledDom,
345347
    node_id: NodeId,
345347
    node_state: &StyledNodeState,
345347
) -> bool {
345347
    let node_data = &styled_dom.node_data.as_container()[node_id];
345347
    styled_dom
345347
        .css_property_cache
345347
        .ptr
345347
        .get_user_select(node_data, &node_id, node_state)
345347
        .and_then(|v| v.get_property())
345347
        .is_none_or(|us| *us != StyleUserSelect::None) // Default: text is selectable
345347
}
/// Checks if a node has the `contenteditable` attribute set directly.
///
/// Returns `true` if:
/// - The node has `contenteditable: true` set via `.set_contenteditable(true)`
/// - OR the node has `contenteditable` attribute set to `true`
///
/// This does NOT check inheritance - use `is_node_contenteditable_inherited` for that.
#[must_use]
13
pub fn is_node_contenteditable(styled_dom: &StyledDom, node_id: NodeId) -> bool {
    use azul_core::dom::AttributeType;
13
    let node_data = &styled_dom.node_data.as_container()[node_id];
    // First check the direct contenteditable field (primary method)
13
    if node_data.is_contenteditable() {
2
        return true;
11
    }
    // Also check the attribute for backwards compatibility
    // Only return true if the attribute value is explicitly true
11
    node_data
11
        .attributes()
11
        .as_ref()
11
        .iter()
11
        .any(|attr| matches!(attr, AttributeType::ContentEditable(true)))
13
}
// =============================================================================
// Additional ExtractPropertyValue impls (not in compact cache tier 1/2)
// =============================================================================
use azul_css::props::{
    layout::{
        overflow::StyleTextOverflow,
        table::{LayoutTableLayout, StyleBorderCollapse, StyleCaptionSide, StyleEmptyCells},
        text::LayoutTextJustify,
    },
    style::{
        effects::{
            StyleAspectRatio, StyleCursor, StyleObjectFit, StyleObjectPosition,
            StyleTextOrientation,
        },
        text::{
            StyleHyphens, StyleLineBreak, StyleOverflowWrap, StyleTextAlignLast, StyleWordBreak,
        },
    },
};
impl ExtractPropertyValue<LayoutTextJustify> for CssProperty {
    fn extract(&self) -> Option<LayoutTextJustify> {
        match self {
            Self::TextJustify(CssPropertyValue::Exact(v)) => Some(*v),
            _ => None,
        }
    }
}
impl ExtractPropertyValue<StyleHyphens> for CssProperty {
    fn extract(&self) -> Option<StyleHyphens> {
        match self {
            Self::Hyphens(CssPropertyValue::Exact(v)) => Some(*v),
            _ => None,
        }
    }
}
impl ExtractPropertyValue<StyleWordBreak> for CssProperty {
    fn extract(&self) -> Option<StyleWordBreak> {
        match self {
            Self::WordBreak(CssPropertyValue::Exact(v)) => Some(*v),
            _ => None,
        }
    }
}
impl ExtractPropertyValue<StyleOverflowWrap> for CssProperty {
    fn extract(&self) -> Option<StyleOverflowWrap> {
        match self {
            Self::OverflowWrap(CssPropertyValue::Exact(v)) => Some(*v),
            _ => None,
        }
    }
}
impl ExtractPropertyValue<StyleLineBreak> for CssProperty {
    fn extract(&self) -> Option<StyleLineBreak> {
        match self {
            Self::LineBreak(CssPropertyValue::Exact(v)) => Some(*v),
            _ => None,
        }
    }
}
impl ExtractPropertyValue<StyleTextAlignLast> for CssProperty {
    fn extract(&self) -> Option<StyleTextAlignLast> {
        match self {
            Self::TextAlignLast(CssPropertyValue::Exact(v)) => Some(*v),
            _ => None,
        }
    }
}
impl ExtractPropertyValue<StyleObjectFit> for CssProperty {
    fn extract(&self) -> Option<StyleObjectFit> {
        match self {
            Self::ObjectFit(CssPropertyValue::Exact(v)) => Some(*v),
            _ => None,
        }
    }
}
impl ExtractPropertyValue<StyleTextOverflow> for CssProperty {
    fn extract(&self) -> Option<StyleTextOverflow> {
        match self {
            Self::TextOverflow(CssPropertyValue::Exact(v)) => Some(*v),
            _ => None,
        }
    }
}
impl ExtractPropertyValue<StyleTextOrientation> for CssProperty {
    fn extract(&self) -> Option<StyleTextOrientation> {
        match self {
            Self::TextOrientation(CssPropertyValue::Exact(v)) => Some(*v),
            _ => None,
        }
    }
}
impl ExtractPropertyValue<StyleObjectPosition> for CssProperty {
    fn extract(&self) -> Option<StyleObjectPosition> {
        match self {
            Self::ObjectPosition(CssPropertyValue::Exact(v)) => Some(*v),
            _ => None,
        }
    }
}
impl ExtractPropertyValue<StyleAspectRatio> for CssProperty {
    fn extract(&self) -> Option<StyleAspectRatio> {
        match self {
            Self::AspectRatio(CssPropertyValue::Exact(v)) => Some(*v),
            _ => None,
        }
    }
}
impl ExtractPropertyValue<LayoutTableLayout> for CssProperty {
    fn extract(&self) -> Option<LayoutTableLayout> {
        match self {
            Self::TableLayout(CssPropertyValue::Exact(v)) => Some(*v),
            _ => None,
        }
    }
}
impl ExtractPropertyValue<StyleBorderCollapse> for CssProperty {
    fn extract(&self) -> Option<StyleBorderCollapse> {
        match self {
            Self::BorderCollapse(CssPropertyValue::Exact(v)) => Some(*v),
            _ => None,
        }
    }
}
impl ExtractPropertyValue<StyleCaptionSide> for CssProperty {
    fn extract(&self) -> Option<StyleCaptionSide> {
        match self {
            Self::CaptionSide(CssPropertyValue::Exact(v)) => Some(*v),
            _ => None,
        }
    }
}
impl ExtractPropertyValue<StyleEmptyCells> for CssProperty {
    fn extract(&self) -> Option<StyleEmptyCells> {
        match self {
            Self::EmptyCells(CssPropertyValue::Exact(v)) => Some(*v),
            _ => None,
        }
    }
}
impl ExtractPropertyValue<StyleCursor> for CssProperty {
    fn extract(&self) -> Option<StyleCursor> {
        match self {
            Self::Cursor(CssPropertyValue::Exact(v)) => Some(*v),
            _ => None,
        }
    }
}
// =============================================================================
// Additional macro-based getters (not covered by compact cache fast-path getters)
// =============================================================================
get_css_property!(
    get_text_justify,
    get_text_justify,
    LayoutTextJustify,
    CssPropertyType::TextJustify
);
get_css_property!(
    get_hyphens,
    get_hyphens,
    StyleHyphens,
    CssPropertyType::Hyphens
);
get_css_property!(
    get_word_break,
    get_word_break,
    StyleWordBreak,
    CssPropertyType::WordBreak
);
get_css_property!(
    get_overflow_wrap,
    get_overflow_wrap,
    StyleOverflowWrap,
    CssPropertyType::OverflowWrap
);
get_css_property!(
    get_line_break,
    get_line_break,
    StyleLineBreak,
    CssPropertyType::LineBreak
);
get_css_property!(
    get_text_align_last,
    get_text_align_last,
    StyleTextAlignLast,
    CssPropertyType::TextAlignLast
);
get_css_property!(
    get_table_layout,
    get_table_layout,
    LayoutTableLayout,
    CssPropertyType::TableLayout
);
get_css_property!(
    get_border_collapse,
    get_border_collapse,
    StyleBorderCollapse,
    CssPropertyType::BorderCollapse,
    compact = get_border_collapse
);
get_css_property!(
    get_caption_side,
    get_caption_side,
    StyleCaptionSide,
    CssPropertyType::CaptionSide
);
get_css_property!(
    get_empty_cells,
    get_empty_cells,
    StyleEmptyCells,
    CssPropertyType::EmptyCells
);
get_css_property!(
    get_cursor_property,
    get_cursor,
    StyleCursor,
    CssPropertyType::Cursor
);
// `overscroll-behavior-x` / `-y` — read by `register_scroll_nodes` when a node
// becomes a scroll box, so the physics can stop scroll CHAINING (`contain`) or
// suppress the bounce entirely (`none`). The enum and every physics branch that
// consumes it already existed; nothing ever SET it, so `contain`/`none` were
// unreachable until these getters were wired.
// Handwritten rather than `get_css_property!`: that macro resolves the UA
// sheet through `ExtractPropertyValue<T>`, which is keyed on the VALUE type —
// and `overscroll-behavior-x` and `-y` share one value type, so a single
// `extract()` could not tell them apart. No UA rule declares either property
// anyway (the initial value is `auto`, which is what absence means), so the
// author-CSS lookup is the whole cascade here.
#[must_use]
938
pub fn get_overscroll_behavior_x(
938
    styled_dom: &StyledDom,
938
    node_id: NodeId,
938
    node_state: &StyledNodeState,
938
) -> MultiValue<azul_css::props::style::scrollbar::OverscrollBehavior> {
938
    let node_data = &styled_dom.node_data.as_container()[node_id];
938
    styled_dom
938
        .css_property_cache
938
        .ptr
938
        .get_overscroll_behavior_x(node_data, &node_id, node_state)
938
        .and_then(|v| v.get_property().copied())
938
        .map_or(MultiValue::Auto, MultiValue::Exact)
938
}
#[must_use]
938
pub fn get_overscroll_behavior_y(
938
    styled_dom: &StyledDom,
938
    node_id: NodeId,
938
    node_state: &StyledNodeState,
938
) -> MultiValue<azul_css::props::style::scrollbar::OverscrollBehavior> {
938
    let node_data = &styled_dom.node_data.as_container()[node_id];
938
    styled_dom
938
        .css_property_cache
938
        .ptr
938
        .get_overscroll_behavior_y(node_data, &node_id, node_state)
938
        .and_then(|v| v.get_property().copied())
938
        .map_or(MultiValue::Auto, MultiValue::Exact)
938
}
// `-azul-app-region: drag` — read by the event dispatcher to decide whether a
// drag on this node moves the WINDOW. See `node_is_window_drag_region`.
get_css_property!(
    get_app_region,
    get_app_region,
    azul_css::props::style::transform::StyleAppRegion,
    CssPropertyType::AppRegion
);
// CSS Spatial Navigation Level 1 — read by the arrow-key decision, not by
// layout or paint. See `default_actions.rs`.
get_css_property!(
    get_spatial_navigation_action,
    get_spatial_navigation_action,
    azul_css::props::style::spatial_nav::StyleSpatialNavigationAction,
    CssPropertyType::SpatialNavigationAction
);
get_css_property!(
    get_spatial_navigation_contain,
    get_spatial_navigation_contain,
    azul_css::props::style::spatial_nav::StyleSpatialNavigationContain,
    CssPropertyType::SpatialNavigationContain
);
// =============================================================================
// Handwritten getters (Option<T>, special logic, or non-standard returns)
// =============================================================================
/// Get height property value for IFC text layout height reference.
#[must_use]
2
pub fn get_height_value(
2
    styled_dom: &StyledDom,
2
    node_id: NodeId,
2
    node_state: &StyledNodeState,
2
) -> Option<LayoutHeight> {
2
    let node_data = &styled_dom.node_data.as_container()[node_id];
2
    styled_dom
2
        .css_property_cache
2
        .ptr
2
        .get_height(node_data, &node_id, node_state)
2
        .and_then(|v| v.get_property())
2
        .cloned()
2
}
/// Get shape-inside property. Returns Option<ShapeInside> (cloned).
#[must_use]
2
pub fn get_shape_inside(
2
    styled_dom: &StyledDom,
2
    node_id: NodeId,
2
    node_state: &StyledNodeState,
2
) -> Option<azul_css::props::layout::shape::ShapeInside> {
2
    let node_data = &styled_dom.node_data.as_container()[node_id];
2
    styled_dom
2
        .css_property_cache
2
        .ptr
2
        .get_shape_inside(node_data, &node_id, node_state)
2
        .and_then(|v| v.get_property())
2
        .cloned()
2
}
/// Get shape-outside property. Returns Option<ShapeOutside> (cloned).
#[must_use]
2
pub fn get_shape_outside(
2
    styled_dom: &StyledDom,
2
    node_id: NodeId,
2
    node_state: &StyledNodeState,
2
) -> Option<azul_css::props::layout::shape::ShapeOutside> {
2
    let node_data = &styled_dom.node_data.as_container()[node_id];
2
    styled_dom
2
        .css_property_cache
2
        .ptr
2
        .get_shape_outside(node_data, &node_id, node_state)
2
        .and_then(|v| v.get_property())
2
        .cloned()
2
}
/// Get line-height as the full `StyleLineHeight` value for caller resolution.
#[must_use]
738
pub fn get_line_height_value(
738
    styled_dom: &StyledDom,
738
    node_id: NodeId,
738
    node_state: &StyledNodeState,
738
) -> Option<azul_css::props::style::text::StyleLineHeight> {
738
    let node_data = &styled_dom.node_data.as_container()[node_id];
738
    styled_dom
738
        .css_property_cache
738
        .ptr
738
        .get_line_height(node_data, &node_id, node_state)
738
        .and_then(|v| v.get_property())
738
        .copied()
738
}
/// Get text-indent as the full `StyleTextIndent` value for caller resolution.
#[must_use]
2
pub fn get_text_indent_value(
2
    styled_dom: &StyledDom,
2
    node_id: NodeId,
2
    node_state: &StyledNodeState,
2
) -> Option<azul_css::props::style::text::StyleTextIndent> {
2
    let node_data = &styled_dom.node_data.as_container()[node_id];
2
    styled_dom
2
        .css_property_cache
2
        .ptr
2
        .get_text_indent(node_data, &node_id, node_state)
2
        .and_then(|v| v.get_property())
2
        .copied()
2
}
/// Get column-count property. Returns Option<ColumnCount>.
#[must_use]
2
pub fn get_column_count(
2
    styled_dom: &StyledDom,
2
    node_id: NodeId,
2
    node_state: &StyledNodeState,
2
) -> Option<azul_css::props::layout::column::ColumnCount> {
2
    let node_data = &styled_dom.node_data.as_container()[node_id];
2
    styled_dom
2
        .css_property_cache
2
        .ptr
2
        .get_column_count(node_data, &node_id, node_state)
2
        .and_then(|v| v.get_property())
2
        .copied()
2
}
/// Get initial-letter property. Returns Option<StyleInitialLetter>.
#[must_use]
2
pub fn get_initial_letter(
2
    styled_dom: &StyledDom,
2
    node_id: NodeId,
2
    node_state: &StyledNodeState,
2
) -> Option<azul_css::props::style::text::StyleInitialLetter> {
2
    let node_data = &styled_dom.node_data.as_container()[node_id];
2
    styled_dom
2
        .css_property_cache
2
        .ptr
2
        .get_initial_letter(node_data, &node_id, node_state)
2
        .and_then(|v| v.get_property())
2
        .copied()
2
}
/// Get line-clamp property. Returns Option<StyleLineClamp>.
#[must_use]
2
pub fn get_line_clamp(
2
    styled_dom: &StyledDom,
2
    node_id: NodeId,
2
    node_state: &StyledNodeState,
2
) -> Option<azul_css::props::style::text::StyleLineClamp> {
2
    let node_data = &styled_dom.node_data.as_container()[node_id];
2
    styled_dom
2
        .css_property_cache
2
        .ptr
2
        .get_line_clamp(node_data, &node_id, node_state)
2
        .and_then(|v| v.get_property())
2
        .copied()
2
}
/// Get hanging-punctuation property. Returns Option<StyleHangingPunctuation>.
#[must_use]
2
pub fn get_hanging_punctuation(
2
    styled_dom: &StyledDom,
2
    node_id: NodeId,
2
    node_state: &StyledNodeState,
2
) -> Option<azul_css::props::style::text::StyleHangingPunctuation> {
2
    let node_data = &styled_dom.node_data.as_container()[node_id];
2
    styled_dom
2
        .css_property_cache
2
        .ptr
2
        .get_hanging_punctuation(node_data, &node_id, node_state)
2
        .and_then(|v| v.get_property())
2
        .copied()
2
}
/// Get text-combine-upright property. Returns Option<StyleTextCombineUpright>.
#[must_use]
2
pub fn get_text_combine_upright(
2
    styled_dom: &StyledDom,
2
    node_id: NodeId,
2
    node_state: &StyledNodeState,
2
) -> Option<azul_css::props::style::text::StyleTextCombineUpright> {
2
    let node_data = &styled_dom.node_data.as_container()[node_id];
2
    styled_dom
2
        .css_property_cache
2
        .ptr
2
        .get_text_combine_upright(node_data, &node_id, node_state)
2
        .and_then(|v| v.get_property())
2
        .copied()
2
}
/// Get exclusion-margin value. Returns f32 (default 0.0).
#[must_use]
2
pub fn get_exclusion_margin(
2
    styled_dom: &StyledDom,
2
    node_id: NodeId,
2
    node_state: &StyledNodeState,
2
) -> f32 {
2
    let node_data = &styled_dom.node_data.as_container()[node_id];
2
    styled_dom
2
        .css_property_cache
2
        .ptr
2
        .get_exclusion_margin(node_data, &node_id, node_state)
2
        .and_then(|v| v.get_property())
2
        .map_or(0.0, |v| v.inner.get())
2
}
/// Get hyphenation-language property. Returns Option<StyleHyphenationLanguage>.
#[must_use]
2
pub fn get_hyphenation_language(
2
    styled_dom: &StyledDom,
2
    node_id: NodeId,
2
    node_state: &StyledNodeState,
2
) -> Option<azul_css::props::style::exclusion::StyleHyphenationLanguage> {
2
    let node_data = &styled_dom.node_data.as_container()[node_id];
2
    styled_dom
2
        .css_property_cache
2
        .ptr
2
        .get_hyphenation_language(node_data, &node_id, node_state)
2
        .and_then(|v| v.get_property())
2
        .cloned()
2
}
/// Get border-spacing property.
#[must_use]
2
pub fn get_border_spacing(
2
    styled_dom: &StyledDom,
2
    node_id: NodeId,
2
    node_state: &StyledNodeState,
2
) -> azul_css::props::layout::table::LayoutBorderSpacing {
    use azul_css::props::basic::pixel::PixelValue;
    // FAST PATH: compact cache for normal state
2
    if node_state.is_normal() {
1
        if let Some(ref cc) = styled_dom.css_property_cache.ptr.compact_cache {
1
            let h_raw = cc.get_border_spacing_h_raw(node_id.index());
1
            let v_raw = cc.get_border_spacing_v_raw(node_id.index());
            // Both 0 means no border-spacing set (default)
            // Sentinel means non-px unit → slow path
1
            if h_raw < azul_css::compact_cache::I16_SENTINEL_THRESHOLD
1
                && v_raw < azul_css::compact_cache::I16_SENTINEL_THRESHOLD
            {
1
                return azul_css::props::layout::table::LayoutBorderSpacing {
1
                    horizontal: PixelValue::px(f32::from(h_raw) / 10.0),
1
                    vertical: PixelValue::px(f32::from(v_raw) / 10.0),
1
                };
            }
        }
1
    }
    // SLOW PATH
1
    let node_data = &styled_dom.node_data.as_container()[node_id];
1
    styled_dom
1
        .css_property_cache
1
        .ptr
1
        .get_border_spacing(node_data, &node_id, node_state)
1
        .and_then(|v| v.get_property())
1
        .copied()
1
        .unwrap_or_default()
2
}
/// Get opacity value. Returns f32 (default 1.0).
///
/// GPU fast path: the compact cache encodes opacity as a u8 (0-254, 255 = unset).
/// Avoids the 4-pseudo-state × 6-layer cascade walk for animations reading opacity
/// across every node each frame.
#[must_use]
1555793
pub fn get_opacity(styled_dom: &StyledDom, node_id: NodeId, node_state: &StyledNodeState) -> f32 {
    // FAST PATH: compact cache for normal state
1555793
    if node_state.is_normal() {
1555613
        if let Some(ref cc) = styled_dom.css_property_cache.ptr.compact_cache {
1555612
            let raw = cc.get_opacity_raw(node_id.index());
1555612
            if raw == azul_css::compact_cache::OPACITY_SENTINEL {
1555235
                return 1.0;
377
            }
377
            return f32::from(raw) / 254.0;
1
        }
180
    }
    // SLOW PATH: fall back to cascade walk (state != normal, or no compact cache)
181
    let node_data = &styled_dom.node_data.as_container()[node_id];
181
    styled_dom
181
        .css_property_cache
181
        .ptr
181
        .get_opacity(node_data, &node_id, node_state)
181
        .and_then(|v| v.get_property())
181
        .map_or(1.0, |v| v.inner.normalized())
1555793
}
/// Get filter property. Returns Option with cloned filter list.
#[must_use]
2
pub fn get_filter(
2
    styled_dom: &StyledDom,
2
    node_id: NodeId,
2
    node_state: &StyledNodeState,
2
) -> Option<azul_css::props::style::filter::StyleFilterVec> {
2
    if node_state.is_normal() {
1
        if let Some(ref cc) = styled_dom.css_property_cache.ptr.compact_cache {
1
            if !cc.has_filter(node_id.index()) {
1
                return None;
            }
        }
1
    }
1
    let node_data = &styled_dom.node_data.as_container()[node_id];
1
    styled_dom
1
        .css_property_cache
1
        .ptr
1
        .get_filter(node_data, &node_id, node_state)
1
        .and_then(|v| v.get_property())
1
        .cloned()
2
}
/// Get backdrop-filter property. Returns Option with cloned filter list.
#[must_use]
2
pub fn get_backdrop_filter(
2
    styled_dom: &StyledDom,
2
    node_id: NodeId,
2
    node_state: &StyledNodeState,
2
) -> Option<azul_css::props::style::filter::StyleFilterVec> {
2
    if node_state.is_normal() {
1
        if let Some(ref cc) = styled_dom.css_property_cache.ptr.compact_cache {
1
            if !cc.has_backdrop_filter(node_id.index()) {
1
                return None;
            }
        }
1
    }
1
    let node_data = &styled_dom.node_data.as_container()[node_id];
1
    styled_dom
1
        .css_property_cache
1
        .ptr
1
        .get_backdrop_filter(node_data, &node_id, node_state)
1
        .and_then(|v| v.get_property())
1
        .cloned()
2
}
/// Compact-cache negative fast path for all 4 box-shadow sides.
/// Most nodes have no shadow; cheap to check one bit vs. 4 cascade walks.
#[inline]
1781600
fn box_shadow_fast_bail(
1781600
    styled_dom: &StyledDom,
1781600
    node_id: NodeId,
1781600
    node_state: &StyledNodeState,
1781600
) -> bool {
1781600
    if !node_state.is_normal() {
404
        return false;
1781196
    }
1781196
    if let Some(ref cc) = styled_dom.css_property_cache.ptr.compact_cache {
1781192
        return !cc.has_box_shadow(node_id.index());
4
    }
4
    false
1781600
}
/// Get box-shadow for left side. Returns Option<StyleBoxShadow> (cloned).
#[must_use]
445400
pub fn get_box_shadow_left(
445400
    styled_dom: &StyledDom,
445400
    node_id: NodeId,
445400
    node_state: &StyledNodeState,
445400
) -> Option<azul_css::props::style::box_shadow::StyleBoxShadow> {
445400
    if box_shadow_fast_bail(styled_dom, node_id, node_state) {
445128
        return None;
272
    }
272
    let node_data = &styled_dom.node_data.as_container()[node_id];
272
    styled_dom
272
        .css_property_cache
272
        .ptr
272
        .get_box_shadow_left(node_data, &node_id, node_state)
272
        .and_then(|v| v.get_property())
272
        .map(|v| (**v))
445400
}
/// Get box-shadow for right side. Returns Option<StyleBoxShadow> (cloned).
#[must_use]
445400
pub fn get_box_shadow_right(
445400
    styled_dom: &StyledDom,
445400
    node_id: NodeId,
445400
    node_state: &StyledNodeState,
445400
) -> Option<azul_css::props::style::box_shadow::StyleBoxShadow> {
445400
    if box_shadow_fast_bail(styled_dom, node_id, node_state) {
445128
        return None;
272
    }
272
    let node_data = &styled_dom.node_data.as_container()[node_id];
272
    styled_dom
272
        .css_property_cache
272
        .ptr
272
        .get_box_shadow_right(node_data, &node_id, node_state)
272
        .and_then(|v| v.get_property())
272
        .map(|v| (**v))
445400
}
/// Get box-shadow for top side. Returns Option<StyleBoxShadow> (cloned).
#[must_use]
445400
pub fn get_box_shadow_top(
445400
    styled_dom: &StyledDom,
445400
    node_id: NodeId,
445400
    node_state: &StyledNodeState,
445400
) -> Option<azul_css::props::style::box_shadow::StyleBoxShadow> {
445400
    if box_shadow_fast_bail(styled_dom, node_id, node_state) {
445128
        return None;
272
    }
272
    let node_data = &styled_dom.node_data.as_container()[node_id];
272
    styled_dom
272
        .css_property_cache
272
        .ptr
272
        .get_box_shadow_top(node_data, &node_id, node_state)
272
        .and_then(|v| v.get_property())
272
        .map(|v| (**v))
445400
}
/// Get box-shadow for bottom side. Returns Option<StyleBoxShadow> (cloned).
#[must_use]
445400
pub fn get_box_shadow_bottom(
445400
    styled_dom: &StyledDom,
445400
    node_id: NodeId,
445400
    node_state: &StyledNodeState,
445400
) -> Option<azul_css::props::style::box_shadow::StyleBoxShadow> {
445400
    if box_shadow_fast_bail(styled_dom, node_id, node_state) {
445128
        return None;
272
    }
272
    let node_data = &styled_dom.node_data.as_container()[node_id];
272
    styled_dom
272
        .css_property_cache
272
        .ptr
272
        .get_box_shadow_bottom(node_data, &node_id, node_state)
272
        .and_then(|v| v.get_property())
272
        .map(|v| (**v))
445400
}
/// Get text-shadow property. Returns Option<StyleBoxShadow> (cloned).
#[must_use]
2
pub fn get_text_shadow(
2
    styled_dom: &StyledDom,
2
    node_id: NodeId,
2
    node_state: &StyledNodeState,
2
) -> Option<azul_css::props::style::box_shadow::StyleBoxShadow> {
2
    if node_state.is_normal() {
1
        if let Some(ref cc) = styled_dom.css_property_cache.ptr.compact_cache {
1
            if !cc.has_text_shadow(node_id.index()) {
1
                return None;
            }
        }
1
    }
1
    let node_data = &styled_dom.node_data.as_container()[node_id];
1
    styled_dom
1
        .css_property_cache
1
        .ptr
1
        .get_text_shadow(node_data, &node_id, node_state)
1
        .and_then(|v| v.get_property())
1
        .map(|v| (**v))
2
}
/// Get transform property. Returns Option (non-empty transform list, cloned).
///
/// GPU fast path: the compact cache keeps a `has_transform` flag. If unset,
/// skips the cascade walk entirely — which is the overwhelming case since most
/// nodes have no transform. Only nodes that actually have a transform pay the
/// slow-walk cost to retrieve the parsed value.
#[must_use]
1538999
pub fn get_transform(
1538999
    styled_dom: &StyledDom,
1538999
    node_id: NodeId,
1538999
    node_state: &StyledNodeState,
1538999
) -> Option<azul_css::props::style::transform::StyleTransformVec> {
    // FAST PATH: bit check in compact cache
1538999
    if node_state.is_normal() {
1538852
        if let Some(ref cc) = styled_dom.css_property_cache.ptr.compact_cache {
1538852
            if !cc.has_transform(node_id.index()) {
1538850
                return None;
2
            }
            // has_transform set → fall through to cascade walk for the value
        }
147
    }
149
    let node_data = &styled_dom.node_data.as_container()[node_id];
149
    styled_dom
149
        .css_property_cache
149
        .ptr
149
        .get_transform(node_data, &node_id, node_state)
149
        .and_then(|v| v.get_property())
149
        .cloned()
1538999
}
/// Get counter-reset property. Returns Option<CounterReset> (cloned).
#[must_use]
2
pub fn get_counter_reset(
2
    styled_dom: &StyledDom,
2
    node_id: NodeId,
2
    node_state: &StyledNodeState,
2
) -> Option<azul_css::props::style::content::CounterReset> {
2
    let node_data = &styled_dom.node_data.as_container()[node_id];
2
    styled_dom
2
        .css_property_cache
2
        .ptr
2
        .get_counter_reset(node_data, &node_id, node_state)
2
        .and_then(|v| v.get_property())
2
        .cloned()
2
}
/// Get counter-increment property. Returns Option<CounterIncrement> (cloned).
#[must_use]
2
pub fn get_counter_increment(
2
    styled_dom: &StyledDom,
2
    node_id: NodeId,
2
    node_state: &StyledNodeState,
2
) -> Option<azul_css::props::style::content::CounterIncrement> {
2
    let node_data = &styled_dom.node_data.as_container()[node_id];
2
    styled_dom
2
        .css_property_cache
2
        .ptr
2
        .get_counter_increment(node_data, &node_id, node_state)
2
        .and_then(|v| v.get_property())
2
        .cloned()
2
}
/// W3C-conformant contenteditable inheritance check.
///
/// In the W3C model, the `contenteditable` attribute is **inherited**:
/// - A node is editable if it has `contenteditable="true"` set directly
/// - OR if its parent has `isContentEditable` as true
/// - UNLESS the node explicitly sets `contenteditable="false"`
///
/// This function traverses up the DOM tree to determine editability.
///
/// # Returns
///
/// - `true` if the node is editable (either directly or via inheritance)
/// - `false` if the node is not editable or has `contenteditable="false"`
///
/// # Example
///
/// ```html
/// <div contenteditable="true">
///   A                              <!-- editable (inherited) -->
///   <div contenteditable="false">
///     B                            <!-- NOT editable (explicitly false) -->
///   </div>
///   C                              <!-- editable (inherited) -->
/// </div>
/// ```
#[must_use]
589268
pub fn is_node_contenteditable_inherited(styled_dom: &StyledDom, node_id: NodeId) -> bool {
    use azul_core::dom::AttributeType;
589268
    let node_data_container = styled_dom.node_data.as_container();
589268
    let hierarchy = styled_dom.node_hierarchy.as_container();
589268
    let mut current_node_id = Some(node_id);
2448922
    while let Some(nid) = current_node_id {
1879998
        let node_data = &node_data_container[nid];
        // First check the direct contenteditable field (set via set_contenteditable())
        // This takes precedence as it's the API-level setting
1879998
        if node_data.is_contenteditable() {
20343
            return true;
1859655
        }
        // Then check for explicit contenteditable attribute on this node
        // This handles HTML-style contenteditable="true" or contenteditable="false"
1859655
        for attr in node_data.attributes().as_ref() {
616582
            if let AttributeType::ContentEditable(is_editable) = attr {
                // If explicitly set to true, node is editable
                // If explicitly set to false, node is NOT editable (blocks inheritance)
1
                return *is_editable;
616581
            }
        }
        // No explicit setting on this node, check parent for inheritance
1859654
        current_node_id = hierarchy
1859654
            .get(nid)
1859654
            .and_then(azul_core::styled_dom::NodeHierarchyItem::parent_id);
    }
    // Reached root without finding contenteditable - not editable
568924
    false
589268
}
/// Whether `host` or anything INSIDE it holds focus.
///
/// The companion to [`is_focus_within_or_above`], and the other half of the
/// same question. Focus can land above the prompt-carrying line (on the
/// editable container) or below it (on the exact line the pointer hit), and
/// which one happens is a function of where the value line ends up — so a
/// purely upward walk answered "unfocused" for a field the user was plainly
/// typing in as soon as the line moved. Centring a text input's value line
/// inside its `min-height` did exactly that, and the focused empty field
/// started painting its placeholder again.
///
/// Mirrors the emptiness walk in `maybe_paint_placeholder_prompt`, which
/// already asks its question of the whole host subtree.
43
pub(crate) fn is_focus_within_subtree(styled_dom: &StyledDom, host: NodeId) -> bool {
43
    let styled = styled_dom.styled_nodes.as_container();
43
    if styled
43
        .get(host)
43
        .is_some_and(|n| n.styled_node_state.focused)
    {
        return true;
43
    }
43
    let hierarchy = styled_dom.node_hierarchy.as_container();
43
    let mut stack = hierarchy
43
        .get(host)
43
        .and_then(|h| h.first_child_id(host))
43
        .into_iter()
43
        .collect::<Vec<_>>();
129
    while let Some(n) = stack.pop() {
86
        if styled.get(n).is_some_and(|s| s.styled_node_state.focused) {
            return true;
86
        }
86
        if let Some(h) = hierarchy.get(n) {
86
            if let Some(c) = h.first_child_id(n) {
43
                stack.push(c);
43
            }
86
            if let Some(sib) = h.next_sibling_id() {
                stack.push(sib);
86
            }
        }
    }
43
    false
43
}
/// Whether the focused node is this node ITSELF or one of its ANCESTORS.
///
/// The engine placeholder's hide rule: widget focus lands on the editable
/// CONTAINER above the prompt-carrying line, so "the host is focused" means
/// "me or something above me is focused". Recomputed per display-list build,
/// which makes the rule latch-free by construction (the 2026-08-31
/// whack-a-mole class: imperative show/hide overrides stuck forever).
///
/// See [`is_focus_within_subtree`] for the downward half of the question.
43
pub(crate) fn is_focus_within_or_above(styled_dom: &StyledDom, node_id: NodeId) -> bool {
43
    let styled = styled_dom.styled_nodes.as_container();
43
    if styled
43
        .get(node_id)
43
        .is_some_and(|n| n.styled_node_state.focused)
    {
        return true;
43
    }
43
    let hierarchy = styled_dom.node_hierarchy.as_container();
43
    let mut cur = hierarchy
43
        .get(node_id)
43
        .and_then(azul_core::styled_dom::NodeHierarchyItem::parent_id);
129
    while let Some(p) = cur {
86
        if styled.get(p).is_some_and(|n| n.styled_node_state.focused) {
            return true;
86
        }
86
        cur = hierarchy
86
            .get(p)
86
            .and_then(azul_core::styled_dom::NodeHierarchyItem::parent_id);
    }
43
    false
43
}
/// Find the contenteditable ancestor of a node.
///
/// When focus lands on a text node inside a contenteditable container,
/// we need to find the actual container that has the `contenteditable` attribute.
///
/// # Returns
///
/// - `Some(node_id)` of the contenteditable ancestor (may be the node itself)
/// - `None` if no contenteditable ancestor exists
#[must_use]
6
pub fn find_contenteditable_ancestor(styled_dom: &StyledDom, node_id: NodeId) -> Option<NodeId> {
    use azul_core::dom::AttributeType;
6
    let node_data_container = styled_dom.node_data.as_container();
6
    let hierarchy = styled_dom.node_hierarchy.as_container();
6
    let mut current_node_id = Some(node_id);
13
    while let Some(nid) = current_node_id {
9
        let node_data = &node_data_container[nid];
        // First check the direct contenteditable field (set via set_contenteditable())
9
        if node_data.is_contenteditable() {
2
            return Some(nid);
7
        }
        // Then check for contenteditable attribute on this node
7
        for attr in node_data.attributes().as_ref() {
            if let AttributeType::ContentEditable(is_editable) = attr {
                if *is_editable {
                    return Some(nid);
                }
                // Explicitly not editable - stop search
                return None;
            }
        }
        // Check parent
7
        current_node_id = hierarchy
7
            .get(nid)
7
            .and_then(azul_core::styled_dom::NodeHierarchyItem::parent_id);
    }
4
    None
6
}
// --- Taffy bridge property getters ---
//
// These getters return `Option<CssPropertyValue<T>>` (cloned from cache) for use
// by taffy_bridge.rs. The conversion from CssPropertyValue to taffy types is done
// in taffy_bridge.rs itself. Routing access through these functions centralizes
// all CSS property lookups for future cache optimizations (e.g., FxHash migration).
macro_rules! get_css_property_value {
    ($fn_name:ident, $cache_method:ident, $ret_type:ty) => {
        #[must_use]
63159
        pub fn $fn_name(
63159
            styled_dom: &StyledDom,
63159
            node_id: NodeId,
63159
            node_state: &StyledNodeState,
63159
        ) -> Option<$ret_type> {
63159
            let node_data = &styled_dom.node_data.as_container()[node_id];
63159
            styled_dom
63159
                .css_property_cache
63159
                .ptr
63159
                .$cache_method(node_data, &node_id, node_state)
63159
                .cloned()
63159
        }
    };
}
// Flexbox properties
get_css_property_value!(
    get_flex_direction_prop,
    get_flex_direction,
    LayoutFlexDirectionValue
);
get_css_property_value!(get_flex_wrap_prop, get_flex_wrap, LayoutFlexWrapValue);
get_css_property_value!(get_flex_grow_prop, get_flex_grow, LayoutFlexGrowValue);
get_css_property_value!(get_flex_shrink_prop, get_flex_shrink, LayoutFlexShrinkValue);
get_css_property_value!(get_flex_basis_prop, get_flex_basis, LayoutFlexBasisValue);
// Alignment properties
get_css_property_value!(get_align_items_prop, get_align_items, LayoutAlignItemsValue);
get_css_property_value!(get_align_self_prop, get_align_self, LayoutAlignSelfValue);
get_css_property_value!(
    get_align_content_prop,
    get_align_content,
    LayoutAlignContentValue
);
get_css_property_value!(
    get_justify_content_prop,
    get_justify_content,
    LayoutJustifyContentValue
);
get_css_property_value!(
    get_justify_items_prop,
    get_justify_items,
    LayoutJustifyItemsValue
);
get_css_property_value!(
    get_justify_self_prop,
    get_justify_self,
    LayoutJustifySelfValue
);
// Gap
get_css_property_value!(get_gap_prop, get_gap, LayoutGapValue);
// Grid properties
get_css_property_value!(
    get_grid_template_rows_prop,
    get_grid_template_rows,
    LayoutGridTemplateRowsValue
);
get_css_property_value!(
    get_grid_template_columns_prop,
    get_grid_template_columns,
    LayoutGridTemplateColumnsValue
);
get_css_property_value!(
    get_grid_auto_rows_prop,
    get_grid_auto_rows,
    LayoutGridAutoRowsValue
);
get_css_property_value!(
    get_grid_auto_columns_prop,
    get_grid_auto_columns,
    LayoutGridAutoColumnsValue
);
get_css_property_value!(
    get_grid_auto_flow_prop,
    get_grid_auto_flow,
    LayoutGridAutoFlowValue
);
get_css_property_value!(get_grid_column_prop, get_grid_column, LayoutGridColumnValue);
get_css_property_value!(get_grid_row_prop, get_grid_row, LayoutGridRowValue);
/// Get grid-template-areas property.
///
/// Uses the generic `get_property()` since `CssPropertyCache` lacks a specific getter.
/// Returns the inner `GridTemplateAreas` value (already unwrapped from `CssPropertyValue`).
#[must_use]
2
pub fn get_grid_template_areas_prop(
2
    styled_dom: &StyledDom,
2
    node_id: NodeId,
2
    node_state: &StyledNodeState,
2
) -> Option<GridTemplateAreas> {
2
    let node_data = &styled_dom.node_data.as_container()[node_id];
2
    styled_dom
2
        .css_property_cache
2
        .ptr
2
        .get_property(
2
            node_data,
2
            &node_id,
2
            node_state,
2
            &CssPropertyType::GridTemplateAreas,
2
        )
2
        .and_then(|p| {
            if let CssProperty::GridTemplateAreas(v) = p {
                v.get_property().cloned()
            } else {
                None
            }
        })
2
}
/// Get clip-path property. Returns the `ClipPath` value for the node.
///
/// CSS Masking Module Level 1, section 3:
/// The clip-path property creates a clipping region that determines which parts
/// of an element are visible. Returns None for `clip-path: none` (default).
#[must_use]
796131
pub fn get_clip_path(
796131
    styled_dom: &StyledDom,
796131
    node_id: NodeId,
796131
    node_state: &StyledNodeState,
796131
) -> Option<azul_css::props::layout::shape::ClipPath> {
    // Negative fast path: most nodes have `clip-path: none`.
796131
    if node_state.is_normal() {
796024
        if let Some(ref cc) = styled_dom.css_property_cache.ptr.compact_cache {
796023
            if !cc.has_clip_path(node_id.index()) {
796023
                return None;
            }
1
        }
107
    }
108
    let node_data = &styled_dom.node_data.as_container()[node_id];
108
    styled_dom
108
        .css_property_cache
108
        .ptr
108
        .get_clip_path(node_data, &node_id, node_state)
108
        .and_then(|v| v.get_property())
108
        .cloned()
796131
}
#[cfg(test)]
#[allow(clippy::float_cmp, clippy::too_many_lines)]
mod autotest_generated {
    use azul_core::{dom::Dom, ua_css::ResolvedUaScrollbar};
    use azul_css::{
        css::Css,
        props::style::{
            background::StyleBackgroundContent,
            scrollbar::{ScrollbarColorCustom, ScrollbarFadeDelay, ScrollbarFadeDuration},
        },
    };
    use rust_fontconfig::{CssFallbackGroup, FontMatch, ScriptFallbackGroup};
    use super::*;
    // ---------------------------------------------------------------------
    // helpers
    // ---------------------------------------------------------------------
    /// Every `LayoutOverflow` variant.
    const ALL_OVERFLOW: [LayoutOverflow; 5] = [
        LayoutOverflow::Scroll,
        LayoutOverflow::Auto,
        LayoutOverflow::Hidden,
        LayoutOverflow::Visible,
        LayoutOverflow::Clip,
    ];
    /// Every `LayoutDisplay` variant.
    const ALL_DISPLAY: [LayoutDisplay; 23] = [
        LayoutDisplay::None,
        LayoutDisplay::Block,
        LayoutDisplay::Inline,
        LayoutDisplay::InlineBlock,
        LayoutDisplay::Flex,
        LayoutDisplay::InlineFlex,
        LayoutDisplay::Table,
        LayoutDisplay::InlineTable,
        LayoutDisplay::TableRowGroup,
        LayoutDisplay::TableHeaderGroup,
        LayoutDisplay::TableFooterGroup,
        LayoutDisplay::TableRow,
        LayoutDisplay::TableColumnGroup,
        LayoutDisplay::TableColumn,
        LayoutDisplay::TableCell,
        LayoutDisplay::TableCaption,
        LayoutDisplay::FlowRoot,
        LayoutDisplay::ListItem,
        LayoutDisplay::RunIn,
        LayoutDisplay::Marker,
        LayoutDisplay::Grid,
        LayoutDisplay::InlineGrid,
        LayoutDisplay::Contents,
    ];
    /// Every `PageBreak` variant.
    const ALL_PAGE_BREAK: [PageBreak; 12] = [
        PageBreak::Auto,
        PageBreak::Avoid,
        PageBreak::Always,
        PageBreak::All,
        PageBreak::Page,
        PageBreak::AvoidPage,
        PageBreak::Left,
        PageBreak::Right,
        PageBreak::Recto,
        PageBreak::Verso,
        PageBreak::Column,
        PageBreak::AvoidColumn,
    ];
    /// Every `BreakInside` variant.
    const ALL_BREAK_INSIDE: [BreakInside; 4] = [
        BreakInside::Auto,
        BreakInside::Avoid,
        BreakInside::AvoidPage,
        BreakInside::AvoidColumn,
    ];
    /// Every `LayoutScrollbarWidth` variant.
    const ALL_SCROLLBAR_WIDTH: [LayoutScrollbarWidth; 3] = [
        LayoutScrollbarWidth::Auto,
        LayoutScrollbarWidth::Thin,
        LayoutScrollbarWidth::None,
    ];
    /// Every `ScrollbarVisibilityMode` variant.
    const ALL_VISIBILITY: [ScrollbarVisibilityMode; 3] = [
        ScrollbarVisibilityMode::Always,
        ScrollbarVisibilityMode::WhenScrolling,
        ScrollbarVisibilityMode::Auto,
    ];
    fn parse(css: &str) -> Css {
        azul_css::parser2::new_from_str(css).0
    }
    /// `<body>` with `n` `<div>` children, cascaded against `css`.
    /// Node ids are pre-order: `0` = body, `1..=n` = the children.
    fn body_with_divs(n: usize, css: &str) -> StyledDom {
        let children: Vec<Dom> = (0..n).map(|_| Dom::create_div()).collect();
        let mut dom = Dom::create_body().with_children(children.into());
        StyledDom::create(&mut dom, parse(css))
    }
    /// `<body>` with a single text child.
    fn body_with_text(text: &str) -> StyledDom {
        let mut dom = Dom::create_body().with_children(
            vec![Dom::create_text_do_not_use_without_block_level_wrapper(
                text,
            )]
            .into(),
        );
        StyledDom::create(&mut dom, Css::empty())
    }
    fn normal() -> StyledNodeState {
        StyledNodeState::default()
    }
    /// A non-`Normal` pseudo-state; forces every getter off its compact-cache
    /// fast path and onto the full cascade walk.
    fn hovered() -> StyledNodeState {
        StyledNodeState {
            hover: true,
            ..StyledNodeState::default()
        }
    }
    fn state_of(sd: &StyledDom, id: NodeId) -> StyledNodeState {
        sd.get_styled_node_state(&id)
    }
    fn empty_chains() -> ResolvedFontChains {
        ResolvedFontChains {
            chains: HashMap::new(),
            ..Default::default()
        }
    }
    fn chain_key(family: &str) -> FontChainKey {
        FontChainKey {
            font_families: vec![family.to_string()],
            weight: FcWeight::Normal,
            italic: false,
            oblique: false,
        }
    }
    /// A `FontMatch` covering exactly `ranges`.
    fn font_match(id: u128, ranges: &[(u32, u32)]) -> FontMatch {
        FontMatch {
            id: FontId(id),
            unicode_ranges: ranges
                .iter()
                .map(|&(start, end)| UnicodeRange { start, end })
                .collect(),
            fallbacks: Vec::new(),
        }
    }
    /// A chain with `groups` as its css tier and `unicode` as ONE
    /// full-range unicode-fallback group (none when `unicode` is empty).
    fn chain_with(groups: Vec<CssFallbackGroup>, unicode: Vec<FontMatch>) -> FontFallbackChain {
        FontFallbackChain {
            css_fallbacks: groups,
            unicode_fallbacks: if unicode.is_empty() {
                Vec::new()
            } else {
                vec![ScriptFallbackGroup {
                    range: UnicodeRange {
                        start: 0,
                        end: 0x10FFFF,
                    },
                    fonts: unicode,
                }]
            },
            last_resort: Vec::new(),
            original_stack: Vec::new(),
        }
    }
    /// A `LayoutNode` carrying nothing but the `scrollbar_info` under test.
    fn bare_layout_node(scrollbar_info: Option<ScrollbarRequirements>) -> LayoutNode {
        use azul_core::{diff::NodeDataFingerprint, dom::FormattingContext};
        use crate::solver3::{
            geometry::{BoxProps, UnresolvedBoxProps},
            layout_tree::{ComputedLayoutStyle, DirtyFlag, SubtreeHash},
        };
        LayoutNode {
            box_props: BoxProps::default(),
            dom_node_id: None,
            children: Vec::new(),
            used_size: None,
            formatting_context: FormattingContext::Inline,
            parent: None,
            intrinsic_sizes: None,
            baseline: None,
            inline_layout_result: None,
            inline_content_cache: None,
            scrollbar_info,
            relative_position: None,
            overflow_content_size: None,
            taffy_cache: taffy::Cache::new(),
            measured_content_sizes: (None, None),
            computed_style: ComputedLayoutStyle::default(),
            pseudo_element: None,
            escaped_top_margin: None,
            escaped_bottom_margin: None,
            parent_formatting_context: None,
            ifc_membership: None,
            containing_block_index: None,
            anonymous_type: None,
            preview_byte_range: None,
            node_data_fingerprint: NodeDataFingerprint::default(),
            subtree_hash: SubtreeHash(0),
            dirty_flag: DirtyFlag::Layout,
            unresolved_box_props: UnresolvedBoxProps::default(),
            ifc_id: None,
        }
    }
    // =====================================================================
    // MultiValue<T> — generic predicates and combinators
    // =====================================================================
    #[test]
    fn multivalue_default_is_auto() {
        let v: MultiValue<i32> = MultiValue::default();
        assert!(v.is_auto());
        assert!(!v.is_exact());
    }
    #[test]
    fn multivalue_is_auto_and_is_exact_are_mutually_exclusive() {
        let cases: [MultiValue<i32>; 4] = [
            MultiValue::Auto,
            MultiValue::Initial,
            MultiValue::Inherit,
            MultiValue::Exact(7),
        ];
        for v in cases {
            assert!(
                !(v.is_auto() && v.is_exact()),
                "a value cannot be both Auto and Exact: {v:?}"
            );
        }
        assert!(MultiValue::<i32>::Auto.is_auto());
        assert!(!MultiValue::<i32>::Initial.is_auto());
        assert!(!MultiValue::<i32>::Inherit.is_auto());
        assert!(!MultiValue::Exact(7).is_auto());
        assert!(MultiValue::Exact(7).is_exact());
        assert!(!MultiValue::<i32>::Auto.is_exact());
        assert!(!MultiValue::<i32>::Initial.is_exact());
        assert!(!MultiValue::<i32>::Inherit.is_exact());
    }
    #[test]
    fn multivalue_exact_returns_some_only_for_the_exact_variant() {
        assert_eq!(MultiValue::Exact(42_i32).exact(), Some(42));
        assert_eq!(MultiValue::<i32>::Auto.exact(), None);
        assert_eq!(MultiValue::<i32>::Initial.exact(), None);
        assert_eq!(MultiValue::<i32>::Inherit.exact(), None);
    }
    #[test]
    fn multivalue_exact_round_trips_extreme_payloads() {
        // Boundary integers survive Exact() → exact() unchanged.
        for probe in [i32::MIN, -1, 0, 1, i32::MAX] {
            assert_eq!(MultiValue::Exact(probe).exact(), Some(probe));
        }
        // NaN is not equal to itself: assert the *shape*, not equality.
        let nan = MultiValue::Exact(f32::NAN).exact().unwrap();
        assert!(nan.is_nan());
        assert_eq!(
            MultiValue::Exact(f32::INFINITY).exact(),
            Some(f32::INFINITY)
        );
        assert_eq!(
            MultiValue::Exact(f32::NEG_INFINITY).exact(),
            Some(f32::NEG_INFINITY)
        );
    }
    #[test]
    fn multivalue_unwrap_or_uses_the_default_for_every_non_exact_variant() {
        assert_eq!(MultiValue::Exact(5_i32).unwrap_or(99), 5);
        assert_eq!(MultiValue::<i32>::Auto.unwrap_or(99), 99);
        assert_eq!(MultiValue::<i32>::Initial.unwrap_or(99), 99);
        assert_eq!(MultiValue::<i32>::Inherit.unwrap_or(99), 99);
        // The default is returned verbatim, even when it is a degenerate float.
        assert!(MultiValue::<f32>::Auto.unwrap_or(f32::NAN).is_nan());
    }
    #[test]
    fn multivalue_unwrap_or_default_falls_back_to_t_default() {
        assert_eq!(MultiValue::Exact(5_i32).unwrap_or_default(), 5);
        assert_eq!(MultiValue::<i32>::Auto.unwrap_or_default(), 0);
        assert_eq!(MultiValue::<i32>::Initial.unwrap_or_default(), 0);
        assert_eq!(MultiValue::<i32>::Inherit.unwrap_or_default(), 0);
        // T = LayoutOverflow → Default is Visible (the CSS initial value).
        assert_eq!(
            MultiValue::<LayoutOverflow>::Inherit.unwrap_or_default(),
            LayoutOverflow::Visible
        );
    }
    #[test]
    fn multivalue_map_transforms_exact_and_preserves_the_keyword_variants() {
        assert_eq!(
            MultiValue::Exact(2_i32).map(|v| v * 2),
            MultiValue::Exact(4)
        );
        assert_eq!(MultiValue::<i32>::Auto.map(|v| v * 2), MultiValue::Auto);
        assert_eq!(
            MultiValue::<i32>::Initial.map(|v| v * 2),
            MultiValue::Initial
        );
        assert_eq!(
            MultiValue::<i32>::Inherit.map(|v| v * 2),
            MultiValue::Inherit
        );
    }
    #[test]
    fn multivalue_map_never_invokes_the_closure_for_keyword_variants() {
        // A keyword variant carries no T, so the mapper must not be called at all.
        let auto: MultiValue<i32> = MultiValue::Auto;
        let _ = auto.map(|_| -> i32 { panic!("map() called f() on MultiValue::Auto") });
        let initial: MultiValue<i32> = MultiValue::Initial;
        let _ = initial.map(|_| -> i32 { panic!("map() called f() on MultiValue::Initial") });
        let inherit: MultiValue<i32> = MultiValue::Inherit;
        let _ = inherit.map(|_| -> i32 { panic!("map() called f() on MultiValue::Inherit") });
    }
    #[test]
    fn multivalue_map_can_change_the_payload_type() {
        let mapped: MultiValue<usize> = MultiValue::Exact("hello").map(str::len);
        assert_eq!(mapped, MultiValue::Exact(5));
        // Overflow-adjacent payload: i32::MIN mapped to its (wrapping) absolute value
        // must not debug-panic inside map itself.
        let abs: MultiValue<i32> = MultiValue::Exact(i32::MIN).map(i32::wrapping_abs);
        assert_eq!(abs, MultiValue::Exact(i32::MIN));
    }
    // =====================================================================
    // MultiValue<LayoutOverflow> — overflow predicates
    // =====================================================================
    #[test]
    fn overflow_predicates_match_the_spec_for_every_exact_variant() {
        for o in ALL_OVERFLOW {
            let v = MultiValue::Exact(o);
            assert_eq!(
                v.is_clipped(),
                o != LayoutOverflow::Visible,
                "is_clipped is every value except Visible ({o:?})"
            );
            assert_eq!(
                v.is_scroll(),
                matches!(o, LayoutOverflow::Scroll | LayoutOverflow::Auto),
                "is_scroll ({o:?})"
            );
            assert_eq!(
                v.is_auto_overflow(),
                o == LayoutOverflow::Auto,
                "is_auto_overflow ({o:?})"
            );
            assert_eq!(
                v.is_hidden(),
                o == LayoutOverflow::Hidden,
                "is_hidden ({o:?})"
            );
            assert_eq!(
                v.is_hidden_or_clip(),
                matches!(o, LayoutOverflow::Hidden | LayoutOverflow::Clip),
                "is_hidden_or_clip ({o:?})"
            );
            assert_eq!(
                v.is_scroll_explicit(),
                o == LayoutOverflow::Scroll,
                "is_scroll_explicit ({o:?})"
            );
            assert_eq!(v.is_clip(), o == LayoutOverflow::Clip, "is_clip ({o:?})");
            assert_eq!(
                v.is_visible_or_clip(),
                matches!(o, LayoutOverflow::Visible | LayoutOverflow::Clip),
                "is_visible_or_clip ({o:?})"
            );
            assert_eq!(
                v.establishes_bfc(),
                matches!(
                    o,
                    LayoutOverflow::Hidden | LayoutOverflow::Scroll | LayoutOverflow::Auto
                ),
                "establishes_bfc ({o:?})"
            );
        }
    }
    #[test]
    fn overflow_predicates_are_false_for_every_keyword_variant() {
        // Gotcha guard: MultiValue::Auto is the CSS *keyword* `auto`, which is NOT
        // the same thing as Exact(LayoutOverflow::Auto). None of the LayoutOverflow
        // predicates may fire for a keyword variant.
        let keywords: [MultiValue<LayoutOverflow>; 3] =
            [MultiValue::Auto, MultiValue::Initial, MultiValue::Inherit];
        for v in keywords {
            assert!(!v.is_clipped(), "{v:?}");
            assert!(!v.is_scroll(), "{v:?}");
            assert!(!v.is_auto_overflow(), "{v:?}");
            assert!(!v.is_hidden(), "{v:?}");
            assert!(!v.is_hidden_or_clip(), "{v:?}");
            assert!(!v.is_scroll_explicit(), "{v:?}");
            assert!(!v.is_clip(), "{v:?}");
            assert!(!v.is_visible_or_clip(), "{v:?}");
            // The unset/initial/inherit sentinel is `visible` (initial) => no BFC.
            assert!(!v.establishes_bfc(), "{v:?}");
        }
    }
    #[test]
    fn overflow_scroll_implies_clipped_and_clip_implies_hidden_or_clip() {
        for o in ALL_OVERFLOW {
            let v = MultiValue::Exact(o);
            assert!(
                !v.is_scroll() || v.is_clipped(),
                "anything that scrolls also clips ({o:?})"
            );
            assert!(
                !v.is_clip() || v.is_hidden_or_clip(),
                "clip is a subset of hidden_or_clip ({o:?})"
            );
            assert!(
                !v.is_scroll_explicit() || v.is_scroll(),
                "explicit scroll is a subset of scroll ({o:?})"
            );
        }
    }
    /// Exercises the rule tagged `+spec:overflow:833078` on `resolve_computed`.
    #[test]
    fn overflow_resolve_computed_matches_css_overflow_3_section_3_1() {
        for this in ALL_OVERFLOW {
            for other in ALL_OVERFLOW {
                let got = MultiValue::Exact(this).resolve_computed(&MultiValue::Exact(other));
                let other_is_scrollable =
                    !matches!(other, LayoutOverflow::Visible | LayoutOverflow::Clip);
                let want = if other_is_scrollable {
                    match this {
                        LayoutOverflow::Visible => LayoutOverflow::Auto,
                        LayoutOverflow::Clip => LayoutOverflow::Hidden,
                        keep => keep,
                    }
                } else {
                    this
                };
                assert_eq!(
                    got,
                    MultiValue::Exact(want),
                    "resolve_computed({this:?}, {other:?})"
                );
            }
        }
    }
    #[test]
    fn overflow_resolve_computed_treats_unset_as_the_initial_visible() {
        let keywords: [MultiValue<LayoutOverflow>; 3] =
            [MultiValue::Auto, MultiValue::Initial, MultiValue::Inherit];
        // css-overflow-3 §3.1 applies to the UNSET sentinel too (it means
        // the initial `visible`): an unset axis computes to `auto` when the
        // other axis is scrollable, and stays the sentinel otherwise.
        for v in keywords {
            for other in ALL_OVERFLOW {
                let resolved = v.resolve_computed(&MultiValue::Exact(other));
                let expected_upgrade =
                    !matches!(other, LayoutOverflow::Visible | LayoutOverflow::Clip);
                if expected_upgrade {
                    assert_eq!(
                        resolved,
                        MultiValue::Exact(LayoutOverflow::Auto),
                        "unset + scrollable {other:?} computes to auto"
                    );
                } else {
                    assert_eq!(resolved, v, "unset + {other:?} stays unset");
                }
            }
            assert_eq!(v.resolve_computed(&MultiValue::Auto), v);
        }
        // An unset OTHER axis acts as the initial `visible`: an Exact self
        // resolves exactly as it would against Exact(Visible).
        for this in ALL_OVERFLOW {
            let v = MultiValue::Exact(this);
            for other in keywords {
                assert_eq!(
                    v.resolve_computed(&other),
                    v.resolve_computed(&MultiValue::Exact(LayoutOverflow::Visible)),
                    "{this:?} vs unset {other:?}"
                );
            }
        }
    }
    #[test]
    fn overflow_resolve_computed_is_idempotent() {
        for this in ALL_OVERFLOW {
            for other in ALL_OVERFLOW {
                let other_mv = MultiValue::Exact(other);
                let once = MultiValue::Exact(this).resolve_computed(&other_mv);
                let twice = once.resolve_computed(&other_mv);
                assert_eq!(once, twice, "resolve_computed({this:?}, {other:?}) twice");
            }
        }
    }
    // =====================================================================
    // MultiValue<LayoutPosition> / MultiValue<LayoutFloat>
    // =====================================================================
    #[test]
    fn position_is_absolute_or_fixed_only_for_absolute_and_fixed() {
        let all = [
            LayoutPosition::Static,
            LayoutPosition::Relative,
            LayoutPosition::Absolute,
            LayoutPosition::Fixed,
            LayoutPosition::Sticky,
        ];
        for p in all {
            assert_eq!(
                MultiValue::Exact(p).is_absolute_or_fixed(),
                matches!(p, LayoutPosition::Absolute | LayoutPosition::Fixed),
                "{p:?}"
            );
        }
        // Keyword variants carry no position → never out-of-flow.
        assert!(!MultiValue::<LayoutPosition>::Auto.is_absolute_or_fixed());
        assert!(!MultiValue::<LayoutPosition>::Initial.is_absolute_or_fixed());
        assert!(!MultiValue::<LayoutPosition>::Inherit.is_absolute_or_fixed());
    }
    #[test]
    fn float_is_none_treats_every_keyword_variant_as_not_floated() {
        assert!(MultiValue::Exact(LayoutFloat::None).is_none());
        assert!(!MultiValue::Exact(LayoutFloat::Left).is_none());
        assert!(!MultiValue::Exact(LayoutFloat::Right).is_none());
        // Unlike the overflow predicates, `is_none` deliberately folds the keyword
        // variants in: an unset float is not a float.
        assert!(MultiValue::<LayoutFloat>::Auto.is_none());
        assert!(MultiValue::<LayoutFloat>::Initial.is_none());
        assert!(MultiValue::<LayoutFloat>::Inherit.is_none());
        assert!(MultiValue::<LayoutFloat>::default().is_none());
    }
    // =====================================================================
    // blockify_display / get_computed_display
    // =====================================================================
    #[test]
    fn blockify_display_follows_the_css_display_3_table() {
        for d in ALL_DISPLAY {
            let want = match d {
                LayoutDisplay::Inline | LayoutDisplay::InlineBlock => LayoutDisplay::Block,
                LayoutDisplay::InlineFlex => LayoutDisplay::Flex,
                LayoutDisplay::InlineTable => LayoutDisplay::Table,
                LayoutDisplay::InlineGrid => LayoutDisplay::Grid,
                LayoutDisplay::TableRowGroup
                | LayoutDisplay::TableColumn
                | LayoutDisplay::TableColumnGroup
                | LayoutDisplay::TableHeaderGroup
                | LayoutDisplay::TableFooterGroup
                | LayoutDisplay::TableRow
                | LayoutDisplay::TableCell
                | LayoutDisplay::TableCaption => LayoutDisplay::Block,
                // css-display-3 §2.7: run-in blockifies to block.
                LayoutDisplay::RunIn => LayoutDisplay::Block,
                other => other,
            };
            assert_eq!(blockify_display(d), want, "blockify_display({d:?})");
        }
    }
    #[test]
    fn blockify_display_is_idempotent_and_never_produces_an_inline_level_value() {
        for d in ALL_DISPLAY {
            let once = blockify_display(d);
            assert_eq!(
                blockify_display(once),
                once,
                "blockify_display is not idempotent for {d:?}"
            );
            assert!(
                !matches!(
                    once,
                    LayoutDisplay::Inline
                        | LayoutDisplay::InlineBlock
                        | LayoutDisplay::InlineFlex
                        | LayoutDisplay::InlineTable
                        | LayoutDisplay::InlineGrid
                ),
                "blockified {d:?} is still inline-level: {once:?}"
            );
        }
    }
    #[test]
    fn get_computed_display_keeps_none_regardless_of_the_flags() {
        // display:none boxes are never generated, so no flag may resurrect them.
        for flags in 0_u8..16 {
            let got = get_computed_display(
                LayoutDisplay::None,
                flags & 1 != 0,
                flags & 2 != 0,
                flags & 4 != 0,
                flags & 8 != 0,
            );
            assert_eq!(got, LayoutDisplay::None, "flags={flags:#06b}");
        }
    }
    #[test]
    fn get_computed_display_is_the_identity_when_no_flag_is_set() {
        for d in ALL_DISPLAY {
            assert_eq!(
                get_computed_display(d, false, false, false, false),
                d,
                "an in-flow, non-root, non-flex-child box keeps its specified display ({d:?})"
            );
        }
    }
    #[test]
    fn get_computed_display_blockifies_whenever_any_flag_is_set() {
        for d in ALL_DISPLAY {
            if d == LayoutDisplay::None {
                continue; // covered by the dedicated None test
            }
            // Each of the four flags on its own must blockify, and so must every
            // combination of them.
            for flags in 1_u8..16 {
                let got = get_computed_display(
                    d,
                    flags & 1 != 0,
                    flags & 2 != 0,
                    flags & 4 != 0,
                    flags & 8 != 0,
                );
                assert_eq!(
                    got,
                    blockify_display(d),
                    "get_computed_display({d:?}, flags={flags:#06b})"
                );
            }
        }
    }
    // =====================================================================
    // Fragmentation predicates
    // =====================================================================
    #[test]
    fn is_forced_page_break_covers_exactly_the_forcing_keywords() {
        for pb in ALL_PAGE_BREAK {
            let want = matches!(
                pb,
                PageBreak::Always
                    | PageBreak::Page
                    | PageBreak::Left
                    | PageBreak::Right
                    | PageBreak::Recto
                    | PageBreak::Verso
                    | PageBreak::All
            );
            assert_eq!(is_forced_page_break(pb), want, "{pb:?}");
        }
        // `column` forces a *column* break, not a page break.
        assert!(!is_forced_page_break(PageBreak::Column));
        assert!(!is_forced_page_break(PageBreak::Auto));
        assert!(!is_forced_page_break(PageBreak::default()));
    }
    #[test]
    fn is_avoid_page_break_covers_exactly_avoid_and_avoid_page() {
        for pb in ALL_PAGE_BREAK {
            let want = matches!(pb, PageBreak::Avoid | PageBreak::AvoidPage);
            assert_eq!(is_avoid_page_break(&pb), want, "{pb:?}");
        }
        // `avoid-column` avoids a column break, not a page break.
        assert!(!is_avoid_page_break(&PageBreak::AvoidColumn));
    }
    #[test]
    fn forced_and_avoid_page_break_are_never_both_true() {
        for pb in ALL_PAGE_BREAK {
            assert!(
                !(is_forced_page_break(pb) && is_avoid_page_break(&pb)),
                "{pb:?} is simultaneously forced and avoided"
            );
        }
    }
    #[test]
    fn is_avoid_break_inside_is_true_for_every_variant_except_auto() {
        for bi in ALL_BREAK_INSIDE {
            assert_eq!(
                is_avoid_break_inside(&bi),
                bi != BreakInside::Auto,
                "{bi:?}"
            );
        }
        assert!(!is_avoid_break_inside(&BreakInside::default()));
    }
    // =====================================================================
    // ComputedScrollbarStyle::from_ua_resolved
    // =====================================================================
    fn ua(
        width: LayoutScrollbarWidth,
        visibility: ScrollbarVisibilityMode,
        color: StyleScrollbarColor,
        delay_ms: u32,
        duration_ms: u32,
    ) -> ResolvedUaScrollbar {
        ResolvedUaScrollbar {
            color,
            width,
            visibility,
            fade_delay: ScrollbarFadeDelay { ms: delay_ms },
            fade_duration: ScrollbarFadeDuration { ms: duration_ms },
        }
    }
    #[test]
    fn from_ua_resolved_holds_its_invariants_across_the_whole_width_visibility_matrix() {
        for width in ALL_SCROLLBAR_WIDTH {
            for visibility in ALL_VISIBILITY {
                let s = ComputedScrollbarStyle::from_ua_resolved(&ua(
                    width,
                    visibility,
                    StyleScrollbarColor::Auto,
                    0,
                    0,
                ));
                assert_eq!(s.width_mode, width);
                assert_eq!(s.visibility, visibility);
                let expected_visual = match width {
                    LayoutScrollbarWidth::Thin => SCROLLBAR_WIDTH_THIN,
                    LayoutScrollbarWidth::Auto => SCROLLBAR_WIDTH_AUTO,
                    LayoutScrollbarWidth::None => 0.0,
                };
                assert_eq!(s.visual_width_px, expected_visual, "{width:?}");
                // Only `WhenScrolling` is an overlay scrollbar. `Auto` is NOT.
                let is_overlay = visibility == ScrollbarVisibilityMode::WhenScrolling;
                assert_eq!(s.clip_to_container_border, is_overlay);
                assert_eq!(s.show_scroll_buttons, !is_overlay);
                assert_eq!(s.show_corner_rect, !is_overlay);
                if is_overlay {
                    assert_eq!(s.reserve_width_px, 0.0, "overlay reserves no layout space");
                    assert_eq!(s.scroll_button_size_px, 0.0);
                } else {
                    assert_eq!(s.reserve_width_px, s.visual_width_px);
                    assert_eq!(s.scroll_button_size_px, s.visual_width_px);
                }
                // Hover/active widths are always the visual width plus the expand delta.
                assert_eq!(
                    s.visual_width_px_hover,
                    Some(s.visual_width_px + SCROLLBAR_HOVER_EXPAND_PX)
                );
                assert_eq!(
                    s.visual_width_px_active,
                    Some(s.visual_width_px + SCROLLBAR_HOVER_EXPAND_PX)
                );
                assert!(s.reserve_width_px <= s.visual_width_px);
                assert!(s.visual_width_px.is_finite());
            }
        }
    }
    #[test]
    fn from_ua_resolved_saturates_the_hover_and_active_colour_maths_at_the_u8_boundaries() {
        // Max channels: +30 lighten / +40 alpha must saturate, not wrap or panic.
        let white = ColorU {
            r: 255,
            g: 255,
            b: 255,
            a: 255,
        };
        let s = ComputedScrollbarStyle::from_ua_resolved(&ua(
            LayoutScrollbarWidth::Auto,
            ScrollbarVisibilityMode::Always,
            StyleScrollbarColor::Custom(ScrollbarColorCustom {
                thumb: white,
                track: white,
            }),
            0,
            0,
        ));
        let hover = s.thumb_color_hover.expect("hover thumb colour");
        assert_eq!((hover.r, hover.g, hover.b, hover.a), (255, 255, 255, 255));
        let track_hover = s.track_color_hover.expect("hover track colour");
        assert_eq!(track_hover.a, 255);
        // Min channels: -15 darken must saturate at 0, and the active alpha is pinned
        // to 255 regardless of the source alpha.
        let black0 = ColorU {
            r: 0,
            g: 0,
            b: 0,
            a: 0,
        };
        let s = ComputedScrollbarStyle::from_ua_resolved(&ua(
            LayoutScrollbarWidth::Auto,
            ScrollbarVisibilityMode::Always,
            StyleScrollbarColor::Custom(ScrollbarColorCustom {
                thumb: black0,
                track: black0,
            }),
            0,
            0,
        ));
        let active = s.thumb_color_active.expect("active thumb colour");
        assert_eq!((active.r, active.g, active.b), (0, 0, 0));
        assert_eq!(active.a, 255, "the active thumb is always fully opaque");
        let hover = s.thumb_color_hover.expect("hover thumb colour");
        assert_eq!(
            (hover.r, hover.g, hover.b, hover.a),
            (
                THUMB_HOVER_LIGHTEN,
                THUMB_HOVER_LIGHTEN,
                THUMB_HOVER_LIGHTEN,
                THUMB_HOVER_ALPHA_ADD
            )
        );
    }
    #[test]
    fn from_ua_resolved_passes_extreme_fade_timings_through_without_overflow() {
        let s = ComputedScrollbarStyle::from_ua_resolved(&ua(
            LayoutScrollbarWidth::Thin,
            ScrollbarVisibilityMode::WhenScrolling,
            StyleScrollbarColor::Auto,
            u32::MAX,
            u32::MAX,
        ));
        assert_eq!(s.fade_delay_ms, u32::MAX);
        assert_eq!(s.fade_duration_ms, u32::MAX);
        let s = ComputedScrollbarStyle::from_ua_resolved(&ua(
            LayoutScrollbarWidth::Thin,
            ScrollbarVisibilityMode::WhenScrolling,
            StyleScrollbarColor::Auto,
            0,
            0,
        ));
        assert_eq!(s.fade_delay_ms, 0);
        assert_eq!(s.fade_duration_ms, 0);
    }
    #[test]
    fn from_ua_resolved_maps_scrollbar_color_auto_to_transparent() {
        let s = ComputedScrollbarStyle::from_ua_resolved(&ua(
            LayoutScrollbarWidth::Auto,
            ScrollbarVisibilityMode::Always,
            StyleScrollbarColor::Auto,
            0,
            0,
        ));
        assert_eq!(s.thumb_color, ColorU::TRANSPARENT);
        assert_eq!(s.track_color, ColorU::TRANSPARENT);
        assert_eq!(s.button_color, ColorU::TRANSPARENT);
        assert_eq!(s.corner_color, ColorU::TRANSPARENT);
    }
    #[test]
    fn computed_scrollbar_style_default_is_internally_consistent() {
        let d = ComputedScrollbarStyle::default();
        assert!(d.visual_width_px.is_finite() && d.visual_width_px >= 0.0);
        assert!(d.reserve_width_px.is_finite() && d.reserve_width_px >= 0.0);
        assert!(d.reserve_width_px <= d.visual_width_px);
        let overlay = d.visibility == ScrollbarVisibilityMode::WhenScrolling;
        assert_eq!(d.show_scroll_buttons, !overlay);
        assert_eq!(d.clip_to_container_border, overlay);
    }
    // =====================================================================
    // extract_color_from_background
    // =====================================================================
    #[test]
    fn extract_color_from_background_returns_the_solid_colour_verbatim() {
        for probe in [
            ColorU::TRANSPARENT,
            ColorU::BLACK,
            ColorU::WHITE,
            ColorU {
                r: 1,
                g: 2,
                b: 3,
                a: 4,
            },
            ColorU {
                r: 255,
                g: 0,
                b: 255,
                a: 0,
            },
        ] {
            assert_eq!(
                extract_color_from_background(&StyleBackgroundContent::Color(probe)),
                probe
            );
        }
    }
    #[test]
    fn extract_color_from_background_falls_back_to_transparent_for_non_colour_layers() {
        // An image layer has no solid colour to extract → transparent, not a panic.
        let img = StyleBackgroundContent::Image("does-not-exist.png".into());
        assert_eq!(extract_color_from_background(&img), ColorU::TRANSPARENT);
        // Empty / unicode image names are still just "not a colour".
        let empty = StyleBackgroundContent::Image(String::new().into());
        assert_eq!(extract_color_from_background(&empty), ColorU::TRANSPARENT);
        let unicode = StyleBackgroundContent::Image("картинка-🎉.png".into());
        assert_eq!(extract_color_from_background(&unicode), ColorU::TRANSPARENT);
    }
    // =====================================================================
    // get_scrollbar_info_from_layout
    // =====================================================================
    #[test]
    fn get_scrollbar_info_from_layout_defaults_to_no_scrollbars_when_layout_never_set_it() {
        let node = bare_layout_node(None);
        let got = get_scrollbar_info_from_layout(&node);
        assert!(!got.needs_horizontal);
        assert!(!got.needs_vertical);
        assert_eq!(got.scrollbar_width, 0.0);
        assert_eq!(got.scrollbar_height, 0.0);
        assert_eq!(got.visual_width_px, 0.0);
    }
    #[test]
    fn get_scrollbar_info_from_layout_returns_whatever_layout_stored_including_degenerate_floats() {
        let stored = ScrollbarRequirements {
            needs_horizontal: true,
            needs_vertical: true,
            scrollbar_width: f32::NAN,
            scrollbar_height: f32::INFINITY,
            visual_width_px: -1.0,
        };
        let got = get_scrollbar_info_from_layout(&bare_layout_node(Some(stored)));
        assert!(got.needs_horizontal && got.needs_vertical);
        assert!(got.scrollbar_width.is_nan(), "the getter must not sanitise");
        assert_eq!(got.scrollbar_height, f32::INFINITY);
        assert_eq!(got.visual_width_px, -1.0);
    }
    // =====================================================================
    // ResolvedFontChains
    // =====================================================================
    #[test]
    fn resolved_font_chains_empty_instance_answers_every_query_with_none() {
        let r = empty_chains();
        assert_eq!(r.len(), 0);
        assert!(r.is_empty());
        assert_eq!(r.font_refs_len(), 0);
        assert!(r.get(&FontChainKeyOrRef::Ref(0)).is_none());
        assert!(r.get_by_chain_key(&chain_key("Arial")).is_none());
        assert!(r.get_for_font_stack(&[]).is_none());
        assert!(r.get_for_font_ref(0).is_none());
        assert!(r.get_for_font_ref(usize::MAX).is_none());
        assert!(r.get_for_font_ref(usize::MAX / 2).is_none());
        assert!(r.clone().into_inner().is_empty());
        assert!(r.into_fontconfig_chains().is_empty());
    }
    #[test]
    fn resolved_font_chains_get_by_chain_key_round_trips_the_inserted_key() {
        let key = chain_key("Iosevka");
        let mut chains = HashMap::new();
        chains.insert(
            FontChainKeyOrRef::Chain(key.clone()),
            chain_with(Vec::new(), Vec::new()),
        );
        let r = ResolvedFontChains {
            chains,
            ..Default::default()
        };
        assert!(r.get_by_chain_key(&key).is_some());
        assert!(r.get(&FontChainKeyOrRef::Chain(key.clone())).is_some());
        // A key that differs only in weight is a different key.
        let heavier = FontChainKey {
            weight: FcWeight::Bold,
            ..key.clone()
        };
        assert!(r.get_by_chain_key(&heavier).is_none());
        // …and so is one that differs only in the italic flag.
        let italic = FontChainKey {
            italic: true,
            ..key
        };
        assert!(r.get_by_chain_key(&italic).is_none());
    }
    #[test]
    fn resolved_font_chains_counts_and_filters_ref_entries() {
        let mut chains = HashMap::new();
        chains.insert(
            FontChainKeyOrRef::Chain(chain_key("Arial")),
            chain_with(Vec::new(), Vec::new()),
        );
        chains.insert(
            FontChainKeyOrRef::Ref(0xDEAD_BEEF),
            chain_with(Vec::new(), Vec::new()),
        );
        chains.insert(
            FontChainKeyOrRef::Ref(usize::MAX),
            chain_with(Vec::new(), Vec::new()),
        );
        let r = ResolvedFontChains {
            chains,
            ..Default::default()
        };
        assert_eq!(r.len(), 3);
        assert!(!r.is_empty());
        assert_eq!(r.font_refs_len(), 2, "two Ref keys, one Chain key");
        assert!(r.get_for_font_ref(0xDEAD_BEEF).is_some());
        assert!(r.get_for_font_ref(usize::MAX).is_some());
        assert!(r.get_for_font_ref(0).is_none());
        // into_fontconfig_chains drops every Ref entry.
        let fc_only = r.into_fontconfig_chains();
        assert_eq!(fc_only.len(), 1);
        assert!(fc_only.contains_key(&chain_key("Arial")));
    }
    #[test]
    fn resolved_font_chains_get_for_font_stack_uses_the_canonical_selector_key() {
        let selectors = vec![FontSelector {
            family: "Arial".to_string(),
            weight: FcWeight::Normal,
            style: FontStyle::Normal,
            unicode_ranges: Vec::new(),
        }];
        let key = FontChainKey::from_selectors(&selectors);
        let mut chains = HashMap::new();
        chains.insert(
            FontChainKeyOrRef::Chain(key),
            chain_with(Vec::new(), Vec::new()),
        );
        let r = ResolvedFontChains {
            chains,
            ..Default::default()
        };
        assert!(r.get_for_font_stack(&selectors).is_some());
        // An empty stack must not accidentally alias the "Arial" key.
        assert!(r.get_for_font_stack(&[]).is_none());
    }
    // =====================================================================
    // collect_font_ids_from_chains / compute_fonts_to_load
    // =====================================================================
    #[test]
    fn collect_font_ids_from_chains_dedupes_across_groups_and_unicode_fallbacks() {
        let mut chains = HashMap::new();
        chains.insert(
            FontChainKeyOrRef::Chain(chain_key("Arial")),
            chain_with(
                vec![
                    CssFallbackGroup {
                        css_name: "Arial".to_string(),
                        fonts: vec![font_match(1, &[]), font_match(2, &[])],
                        script_fonts: Vec::new(),
                    },
                    CssFallbackGroup {
                        css_name: "sans-serif".to_string(),
                        // FontId(1) also appears in the first group.
                        fonts: vec![font_match(1, &[]), font_match(3, &[])],
                        script_fonts: Vec::new(),
                    },
                ],
                vec![font_match(3, &[]), font_match(u128::MAX, &[])],
            ),
        );
        let ids = collect_font_ids_from_chains(&ResolvedFontChains {
            chains,
            ..Default::default()
        });
        assert_eq!(ids.len(), 4, "ids 1, 2, 3 and u128::MAX, each exactly once");
        for probe in [1_u128, 2, 3, u128::MAX] {
            assert!(ids.contains(&FontId(probe)), "missing FontId({probe})");
        }
        assert!(!ids.contains(&FontId(0)));
    }
    #[test]
    fn collect_font_ids_from_chains_returns_empty_for_an_empty_or_fontless_chain_set() {
        assert!(collect_font_ids_from_chains(&empty_chains()).is_empty());
        // A chain that exists but carries no fonts at all (the empty-fc_cache result).
        let mut chains = HashMap::new();
        chains.insert(
            FontChainKeyOrRef::Chain(chain_key("Nonexistent")),
            chain_with(
                vec![CssFallbackGroup {
                    css_name: "Nonexistent".to_string(),
                    fonts: Vec::new(),
                    script_fonts: Vec::new(),
                }],
                Vec::new(),
            ),
        );
        assert!(collect_font_ids_from_chains(&ResolvedFontChains {
            chains,
            ..Default::default()
        })
        .is_empty());
    }
    #[test]
    fn compute_fonts_to_load_is_the_set_difference_and_bails_early_on_an_empty_requirement() {
        let a = FontId(0);
        let b = FontId(1);
        let c = FontId(u128::MAX);
        let empty: HashSet<FontId> = HashSet::new();
        let all: HashSet<FontId> = [a, b, c].into_iter().collect();
        let loaded_b: HashSet<FontId> = [b].into_iter().collect();
        // Nothing required → nothing to load, regardless of what is loaded.
        assert!(compute_fonts_to_load(&empty, &empty).is_empty());
        assert!(compute_fonts_to_load(&empty, &all).is_empty());
        // Nothing loaded → load everything.
        assert_eq!(compute_fonts_to_load(&all, &empty), all);
        // Partial overlap → only the missing ones.
        let todo = compute_fonts_to_load(&all, &loaded_b);
        assert_eq!(todo.len(), 2);
        assert!(todo.contains(&a) && todo.contains(&c));
        assert!(!todo.contains(&b));
        // Already-loaded is a superset → nothing to do (and no underflow).
        assert!(compute_fonts_to_load(&loaded_b, &all).is_empty());
        assert!(compute_fonts_to_load(&all, &all).is_empty());
    }
    // =====================================================================
    // prune_chain_to_used_chars
    // =====================================================================
    #[test]
    fn prune_chain_to_used_chars_keeps_the_first_match_of_every_group_when_nothing_is_needed() {
        let mut chain = chain_with(
            vec![
                CssFallbackGroup {
                    css_name: "A".to_string(),
                    fonts: vec![
                        font_match(1, &[(0, 0x10_FFFF)]),
                        font_match(2, &[]),
                        font_match(3, &[]),
                    ],
                    script_fonts: Vec::new(),
                },
                CssFallbackGroup {
                    css_name: "B".to_string(),
                    fonts: vec![font_match(4, &[]), font_match(5, &[])],
                    script_fonts: Vec::new(),
                },
            ],
            vec![font_match(6, &[(0x4E00, 0x9FFF)])],
        );
        prune_chain_to_used_chars(&mut chain, &std::collections::BTreeSet::new());
        // Nothing to cover → every group collapses to its single best match…
        assert_eq!(chain.css_fallbacks[0].fonts.len(), 1);
        assert_eq!(chain.css_fallbacks[0].fonts[0].id, FontId(1));
        assert_eq!(chain.css_fallbacks[1].fonts.len(), 1);
        assert_eq!(chain.css_fallbacks[1].fonts[0].id, FontId(4));
        // …and no unicode fallback can intersect an empty codepoint set.
        assert!(chain.unicode_fallbacks.is_empty());
    }
    #[test]
    fn prune_chain_to_used_chars_keeps_walking_until_every_codepoint_is_covered() {
        // 'é' (U+00E9) is only covered by the *second* font in the group.
        let mut chain = chain_with(
            vec![CssFallbackGroup {
                css_name: "A".to_string(),
                fonts: vec![
                    font_match(1, &[(0x20, 0x7F)]),     // ASCII only
                    font_match(2, &[(0x80, 0x24F)]),    // Latin-1 supplement + extended
                    font_match(3, &[(0x0, 0x10_FFFF)]), // everything (must be dropped)
                ],
                script_fonts: Vec::new(),
            }],
            Vec::new(),
        );
        let used: std::collections::BTreeSet<u32> = [0xE9_u32].into_iter().collect();
        prune_chain_to_used_chars(&mut chain, &used);
        assert_eq!(
            chain.css_fallbacks[0].fonts.len(),
            2,
            "walk stops as soon as the needed codepoints are covered"
        );
        assert_eq!(chain.css_fallbacks[0].fonts[1].id, FontId(2));
    }
    #[test]
    fn prune_chain_to_used_chars_keeps_the_whole_group_when_nothing_ever_covers_the_codepoint() {
        let mut chain = chain_with(
            vec![CssFallbackGroup {
                css_name: "A".to_string(),
                fonts: vec![
                    font_match(1, &[(0x20, 0x7F)]),
                    font_match(2, &[(0x20, 0x7F)]),
                ],
                script_fonts: Vec::new(),
            }],
            vec![font_match(3, &[(0x20, 0x7F)])],
        );
        // A codepoint no font claims — and the numeric boundary of the u32 space.
        let used: std::collections::BTreeSet<u32> = [u32::MAX].into_iter().collect();
        prune_chain_to_used_chars(&mut chain, &used);
        assert_eq!(
            chain.css_fallbacks[0].fonts.len(),
            2,
            "an uncoverable codepoint must not silently drop CSS fonts"
        );
        assert!(
            chain.unicode_fallbacks.is_empty(),
            "no unicode fallback intersects U+FFFFFFFF"
        );
    }
    #[test]
    fn prune_chain_to_used_chars_treats_unicode_ranges_as_inclusive_on_both_ends() {
        for probe in [0x4E00_u32, 0x9FFF] {
            let mut chain = chain_with(
                Vec::new(),
                vec![
                    font_match(1, &[(0x4E00, 0x9FFF)]),
                    font_match(2, &[(0x20, 0x7F)]),
                ],
            );
            let used: std::collections::BTreeSet<u32> = [probe].into_iter().collect();
            prune_chain_to_used_chars(&mut chain, &used);
            assert_eq!(
                chain.unicode_fallbacks.len(),
                1,
                "U+{probe:04X} is inside the inclusive CJK range"
            );
            assert_eq!(chain.unicode_fallbacks[0].fonts.len(), 1);
            assert_eq!(chain.unicode_fallbacks[0].fonts[0].id, FontId(1));
        }
        // One past each end of the range → no intersection.
        for probe in [0x4DFF_u32, 0xA000] {
            let mut chain = chain_with(Vec::new(), vec![font_match(1, &[(0x4E00, 0x9FFF)])]);
            let used: std::collections::BTreeSet<u32> = [probe].into_iter().collect();
            prune_chain_to_used_chars(&mut chain, &used);
            assert!(chain.unicode_fallbacks.is_empty(), "U+{probe:04X}");
        }
    }
    #[test]
    fn prune_chain_to_used_chars_survives_empty_chains_and_empty_groups() {
        let mut empty = chain_with(Vec::new(), Vec::new());
        prune_chain_to_used_chars(&mut empty, &std::collections::BTreeSet::new());
        assert!(empty.css_fallbacks.is_empty());
        assert!(empty.unicode_fallbacks.is_empty());
        // A group with zero fonts is skipped rather than truncated to a phantom entry.
        let mut fontless = chain_with(
            vec![CssFallbackGroup {
                css_name: "A".to_string(),
                fonts: Vec::new(),
                script_fonts: Vec::new(),
            }],
            Vec::new(),
        );
        let used: std::collections::BTreeSet<u32> = [0x1F389_u32].into_iter().collect();
        prune_chain_to_used_chars(&mut fontless, &used);
        assert_eq!(fontless.css_fallbacks.len(), 1);
        assert!(fontless.css_fallbacks[0].fonts.is_empty());
    }
    // =====================================================================
    // build_font_selector_stack
    // =====================================================================
    #[test]
    fn build_font_selector_stack_always_appends_the_three_generic_fallbacks() {
        let families = StyleFontFamilyVec::from_vec(Vec::new());
        let stack = build_font_selector_stack(&families, None, FcWeight::Normal, FontStyle::Normal);
        let names: Vec<&str> = stack.iter().map(|s| s.family.as_str()).collect();
        assert_eq!(names, ["sans-serif", "serif", "monospace"]);
        for s in &stack {
            assert_eq!(s.weight, FcWeight::Normal);
            assert_eq!(s.style, FontStyle::Normal);
        }
    }
    /// Two DIFFERENT documents must not share a style answer for the same
    /// `NodeId`.
    ///
    /// This exists because of a bug it would have caught. An
    /// `Arc<StyleProperties>` memo (worth a measured 6.3 MB of peak heap)
    /// was written keyed on `ptr::from_ref(styled_dom) as usize` as the
    /// document identity. A pointer address is not an identity: a
    /// `StyledDom` is created, rendered, dropped, and the next one lands at
    /// the same address — so the second document was served the first
    /// one's cached styles. Sixteen reftests went red.
    ///
    /// Every per-node style cache added here must keep this green. It
    /// asserts CONCRETE VALUES (11px, 29px) rather than mere inequality, so
    /// it cannot pass by both sides being equally wrong.
    ///
    /// Its control is the incident itself rather than a synthetic break:
    /// the pointer-keyed memo really was written, really did compile and
    /// pass every lib test, and really did turn sixteen reftests red. This
    /// asserts the axis those reftests were the only thing watching.
    #[test]
    fn two_documents_do_not_share_a_style_answer_for_the_same_node_id() {
        use azul_core::dom::Dom;
        use azul_css::props::basic::PhysicalSize;
        fn resolve(css: &str) -> f32 {
            let mut dom = Dom::create_body().with_child(Dom::create_div());
            let styled = StyledDom::create(&mut dom, Css::from_string(css.into()));
            get_style_properties(
                &styled,
                NodeId::new(1),
                None,
                PhysicalSize::new(800.0, 600.0),
            )
            .font_size_px
            // `styled` is dropped here on purpose: the NEXT call may well
            // reuse this exact allocation, which is the aliasing hazard.
        }
        let a = resolve("div { font-size: 11px; }");
        let b = resolve("div { font-size: 29px; }");
        assert!(
            (a - 11.0).abs() < 0.5,
            "first document must resolve to its OWN 11px, got {a}"
        );
        assert!(
            (b - 29.0).abs() < 0.5,
            "second document must resolve to its OWN 29px, got {b} — if this is 11 the second \
             document was served the first one's cached style, which is what a pointer-address \
             cache key does once the allocator reuses the address"
        );
    }
    #[test]
    fn build_font_selector_stack_puts_the_authored_families_first() {
        let families = StyleFontFamilyVec::from_vec(vec![
            StyleFontFamily::System("Iosevka".to_string().into()),
            StyleFontFamily::System("Menlo".to_string().into()),
        ]);
        let stack = build_font_selector_stack(&families, None, FcWeight::Bold, FontStyle::Italic);
        assert_eq!(stack.len(), 5, "2 authored + 3 generic fallbacks");
        assert_eq!(stack[0].family, "Iosevka");
        assert_eq!(stack[1].family, "Menlo");
        // Authored families carry the requested weight/style…
        assert_eq!(stack[0].weight, FcWeight::Bold);
        assert_eq!(stack[0].style, FontStyle::Italic);
        // …while the appended generics are always the neutral Normal/Normal.
        assert_eq!(stack[4].family, "monospace");
        assert_eq!(stack[4].weight, FcWeight::Normal);
        assert_eq!(stack[4].style, FontStyle::Normal);
    }
    #[test]
    fn font_stack_memo_returns_what_the_builder_would_have_built() {
        let families = StyleFontFamilyVec::from_vec(vec![StyleFontFamily::System(
            "Iosevka".to_string().into(),
        )]);
        let direct =
            build_font_selector_stack(&families, None, FcWeight::Normal, FontStyle::Normal);
        // Twice: the first call fills the memo, the second must be served
        // from it — and both must equal the unmemoised build.
        for _ in 0..2 {
            let memoed = build_font_selector_stack_memo(
                &families,
                None,
                FcWeight::Normal,
                FontStyle::Normal,
            );
            assert_eq!(memoed, direct, "the memo must not alter the stack");
        }
    }
    /// NEGATIVE CONTROL for the memo key.
    ///
    /// A memo whose key omits an input silently serves the previous
    /// document's fonts — the same class of defect as the font-resolver
    /// skip (see `changing_the_font_family_still_resolves_after_the_skip`).
    /// Each case below changes exactly ONE input and requires the result to
    /// change; if the key ever loses a field, the corresponding case fails.
    #[test]
    fn font_stack_memo_is_keyed_on_every_input_it_reads() {
        let iosevka = StyleFontFamilyVec::from_vec(vec![StyleFontFamily::System(
            "Iosevka".to_string().into(),
        )]);
        let menlo =
            StyleFontFamilyVec::from_vec(vec![StyleFontFamily::System("Menlo".to_string().into())]);
        let base =
            build_font_selector_stack_memo(&iosevka, None, FcWeight::Normal, FontStyle::Normal);
        assert_eq!(base[0].family, "Iosevka");
        // 1. different FAMILY
        let other_family =
            build_font_selector_stack_memo(&menlo, None, FcWeight::Normal, FontStyle::Normal);
        assert_eq!(
            other_family[0].family, "Menlo",
            "a different family must not be served the memoised stack"
        );
        // 2. different WEIGHT
        let bold =
            build_font_selector_stack_memo(&iosevka, None, FcWeight::Bold, FontStyle::Normal);
        assert_eq!(
            bold[0].weight,
            FcWeight::Bold,
            "weight is part of every FontSelector, so it must be part of the key"
        );
        // 3. different STYLE
        let italic =
            build_font_selector_stack_memo(&iosevka, None, FcWeight::Normal, FontStyle::Italic);
        assert_eq!(
            italic[0].style,
            FontStyle::Italic,
            "style is part of every FontSelector, so it must be part of the key"
        );
        // 4. different PLATFORM — only observable through a system font, whose fallback chain is
        //    platform-specific.
        let sys = StyleFontFamilyVec::from_vec(vec![StyleFontFamily::System(
            "system:ui".to_string().into(),
        )]);
        let mac = build_font_selector_stack_memo(
            &sys,
            Some(&azul_css::system::Platform::MacOs),
            FcWeight::Normal,
            FontStyle::Normal,
        );
        let win = build_font_selector_stack_memo(
            &sys,
            Some(&azul_css::system::Platform::Windows),
            FcWeight::Normal,
            FontStyle::Normal,
        );
        assert_ne!(
            mac[0].family, win[0].family,
            "the platform selects the system fallback chain, so it must be part of the key — got \
             {:?} for both",
            mac[0].family
        );
    }
    #[test]
    fn build_font_selector_stack_expands_the_system_magic_string_like_the_typed_variant() {
        // "system:ui" as a plain family STRING (the widget const-table idiom)
        // must expand to the same platform chain as SystemType(Ui) — no
        // fontconfig database knows a family literally called "system:ui".
        let typed = StyleFontFamilyVec::from_vec(vec![StyleFontFamily::SystemType(
            azul_css::system::SystemFontType::Ui,
        )]);
        let magic = StyleFontFamilyVec::from_vec(vec![StyleFontFamily::System(
            "system:ui".to_string().into(),
        )]);
        let typed_stack =
            build_font_selector_stack(&typed, None, FcWeight::Normal, FontStyle::Normal);
        let magic_stack =
            build_font_selector_stack(&magic, None, FcWeight::Normal, FontStyle::Normal);
        let typed_families: Vec<&str> = typed_stack.iter().map(|s| s.family.as_str()).collect();
        let magic_families: Vec<&str> = magic_stack.iter().map(|s| s.family.as_str()).collect();
        assert_eq!(
            magic_families, typed_families,
            "both spellings expand identically"
        );
        assert!(
            !magic_families.contains(&"system:ui"),
            "the literal magic string must never reach fontconfig: {magic_families:?}"
        );
        // "system:ui:bold" carries the bold weight exactly like the variant.
        let bold = StyleFontFamilyVec::from_vec(vec![StyleFontFamily::System(
            "system:ui:bold".to_string().into(),
        )]);
        let bold_stack =
            build_font_selector_stack(&bold, None, FcWeight::Normal, FontStyle::Normal);
        assert_eq!(bold_stack[0].weight, FcWeight::Bold);
    }
    #[test]
    fn build_font_selector_stack_does_not_duplicate_a_generic_the_author_already_listed() {
        // Case-insensitive: "MONOSPACE" must suppress the "monospace" fallback.
        let families = StyleFontFamilyVec::from_vec(vec![StyleFontFamily::System(
            "MONOSPACE".to_string().into(),
        )]);
        let stack = build_font_selector_stack(&families, None, FcWeight::Normal, FontStyle::Normal);
        assert_eq!(stack.len(), 3, "MONOSPACE + sans-serif + serif");
        assert_eq!(stack[0].family, "MONOSPACE");
        let lower: Vec<String> = stack.iter().map(|s| s.family.to_lowercase()).collect();
        assert_eq!(
            lower.iter().filter(|f| f.as_str() == "monospace").count(),
            1,
            "the generic must appear exactly once"
        );
        // All three generics authored → nothing is appended.
        let families = StyleFontFamilyVec::from_vec(vec![
            StyleFontFamily::System("serif".to_string().into()),
            StyleFontFamily::System("Sans-Serif".to_string().into()),
            StyleFontFamily::System("monospace".to_string().into()),
        ]);
        let stack = build_font_selector_stack(&families, None, FcWeight::Normal, FontStyle::Normal);
        assert_eq!(stack.len(), 3);
    }
    #[test]
    fn build_font_selector_stack_passes_hostile_family_names_through_untouched() {
        let huge = "A".repeat(10_000);
        let families = StyleFontFamilyVec::from_vec(vec![
            StyleFontFamily::System(String::new().into()),
            StyleFontFamily::System("  \t\n  ".to_string().into()),
            StyleFontFamily::System("M🎉 ǝɔɐɟdʎʇ — «Шрифт»".to_string().into()),
            StyleFontFamily::System(huge.clone().into()),
        ]);
        let stack = build_font_selector_stack(&families, None, FcWeight::Normal, FontStyle::Normal);
        assert_eq!(stack.len(), 7, "4 authored + 3 generic fallbacks");
        assert_eq!(stack[0].family, "");
        assert_eq!(stack[2].family, "M🎉 ǝɔɐɟdʎʇ — «Шрифт»");
        assert_eq!(stack[3].family.len(), huge.len());
        assert_eq!(stack[6].family, "monospace");
    }
    // =====================================================================
    // Font chain resolution against an empty FcFontCache
    // =====================================================================
    #[test]
    fn resolve_font_chains_yields_nothing_for_an_empty_or_degenerate_collection() {
        let fc = FcFontCache::default();
        let collected = CollectedFontStacks {
            font_stacks: Vec::new(),
            hash_to_index: HashMap::new(),
            font_refs: HashMap::new(),
        };
        assert!(resolve_font_chains(&collected, &fc, Some(&[])).is_empty());
        // An empty *inner* stack is skipped, not turned into a phantom chain.
        let collected = CollectedFontStacks {
            font_stacks: vec![Vec::new()],
            hash_to_index: HashMap::new(),
            font_refs: HashMap::new(),
        };
        assert!(resolve_font_chains(&collected, &fc, Some(&[])).is_empty());
    }
    // =====================================================================
    // Font-size resolution against a real StyledDom
    // =====================================================================
    #[test]
    fn font_size_getters_return_the_default_for_an_unstyled_dom() {
        let sd = StyledDom::default();
        let root = NodeId::new(0);
        let st = normal();
        assert_eq!(get_element_font_size(&sd, root, &st), DEFAULT_FONT_SIZE);
        assert_eq!(get_root_font_size(&sd, &st), DEFAULT_FONT_SIZE);
        // The root has no parent → the parent size falls back to the default.
        assert_eq!(get_parent_font_size(&sd, root, &st), DEFAULT_FONT_SIZE);
        assert_eq!(
            resolve_font_size_slow(&sd, root, &st),
            DEFAULT_FONT_SIZE,
            "the slow path must agree with the memoised one"
        );
    }
    #[test]
    fn font_size_resolution_is_identical_on_the_normal_and_the_pseudo_state_paths() {
        // A non-normal state skips every compact-cache fast path; with no :hover rule
        // in the stylesheet it must still land on exactly the same pixel value.
        let sd = body_with_divs(1, "body { font-size: 32px; }");
        let child = NodeId::new(1);
        assert_eq!(
            get_element_font_size(&sd, child, &normal()),
            get_element_font_size(&sd, child, &hovered()),
        );
    }
    #[test]
    fn font_size_em_resolves_against_the_parent_and_not_the_default() {
        let sd = body_with_divs(1, "body { font-size: 32px; } div { font-size: 2em; }");
        let root = NodeId::new(0);
        let child = NodeId::new(1);
        assert_eq!(get_element_font_size(&sd, root, &state_of(&sd, root)), 32.0);
        assert_eq!(
            get_element_font_size(&sd, child, &state_of(&sd, child)),
            64.0,
            "2em under a 32px parent is 64px — resolving against DEFAULT_FONT_SIZE would give 32"
        );
        assert_eq!(
            get_parent_font_size(&sd, child, &state_of(&sd, child)),
            32.0
        );
        assert_eq!(get_root_font_size(&sd, &state_of(&sd, child)), 32.0);
    }
    #[test]
    fn font_size_getters_stay_finite_for_hostile_stylesheet_values() {
        // Zero, huge and negative authored font sizes must not produce NaN/inf, and
        // must not panic on the em-inheritance walk.
        for css in [
            "body { font-size: 0px; }",
            "body { font-size: 0; }",
            "body { font-size: 999999px; }",
            "body { font-size: -10px; }",
            "body { font-size: 1e30px; }",
            "div { font-size: 1000em; }",
            "div { font-size: 0em; }",
        ] {
            let sd = body_with_divs(1, css);
            for id in [NodeId::new(0), NodeId::new(1)] {
                let st = state_of(&sd, id);
                let px = get_element_font_size(&sd, id, &st);
                assert!(
                    px.is_finite(),
                    "{css:?} produced a non-finite font-size ({px}) on node {id:?}"
                );
                assert_eq!(
                    px,
                    resolve_font_size_slow(&sd, id, &st),
                    "memoised and slow paths disagree for {css:?}"
                );
            }
        }
    }
    #[test]
    fn font_size_resolution_walks_a_deep_ancestor_chain_without_recursing() {
        // resolve_font_size_slow used to self-recurse up the parent chain and blow the
        // stack. Build a 64-deep chain and check the iterative walk survives it.
        const DEPTH: usize = 64;
        let mut dom = Dom::create_div();
        for _ in 0..DEPTH {
            dom = Dom::create_div().with_children(vec![dom].into());
        }
        let mut root = Dom::create_body().with_children(vec![dom].into());
        let sd = StyledDom::create(&mut root, parse("body { font-size: 20px; }"));
        let deepest = NodeId::new(sd.node_data.len() - 1);
        let st = state_of(&sd, deepest);
        let px = get_element_font_size(&sd, deepest, &st);
        assert!(px.is_finite() && px > 0.0);
        assert_eq!(px, resolve_font_size_slow(&sd, deepest, &st));
    }
    #[test]
    fn resolve_font_size_one_is_stable_under_nan_and_infinite_context_sizes() {
        // parent/root font sizes are f32 inputs the caller supplies; degenerate values
        // must not panic, and (with no authored font-size) must not leak into the result.
        let sd = StyledDom::default();
        let root = NodeId::new(0);
        let st = normal();
        for (parent, rootsz) in [
            (0.0_f32, 0.0_f32),
            (f32::NAN, f32::NAN),
            (f32::INFINITY, f32::NEG_INFINITY),
            (f32::MAX, f32::MIN),
            (-1.0, -1.0),
        ] {
            let px = resolve_font_size_one(&sd, root, &st, parent, rootsz);
            assert_eq!(
                px, DEFAULT_FONT_SIZE,
                "an unstyled node ignores the context and falls back to the default \
                 (parent={parent}, root={rootsz})"
            );
        }
    }
    // =====================================================================
    // Option<NodeId> getters — the None branch
    // =====================================================================
    #[test]
    fn optional_node_getters_return_their_documented_defaults_for_none() {
        let sd = StyledDom::default();
        assert_eq!(get_z_index(&sd, None), 0);
        assert!(is_z_index_auto(&sd, None));
        assert_eq!(get_break_before(&sd, None), PageBreak::Auto);
        assert_eq!(get_break_after(&sd, None), PageBreak::Auto);
        assert_eq!(get_break_inside(&sd, None), BreakInside::Auto);
        assert_eq!(get_orphans(&sd, None), 2);
        assert_eq!(get_widows(&sd, None), 2);
        assert_eq!(
            get_box_decoration_break(&sd, None),
            BoxDecorationBreak::Slice
        );
        assert_eq!(
            get_display_property(&sd, None),
            MultiValue::Exact(LayoutDisplay::Inline),
            "a missing node is treated as anonymous inline content"
        );
        assert_eq!(
            get_list_style_type(&sd, None),
            StyleListStyleType::default()
        );
        assert_eq!(
            get_list_style_position(&sd, None),
            StyleListStylePosition::default()
        );
        assert_eq!(get_caret_style(&sd, None).width, DEFAULT_CARET_WIDTH_PX);
        assert_eq!(
            get_caret_style(&sd, None).animation_duration,
            CssDuration::from_millis(DEFAULT_CARET_BLINK_MS)
        );
        let sel = get_selection_style(&sd, None, None);
        assert_eq!(sel.radius, 0.0);
        assert_eq!(sel.text_color, None);
    }
    /// `caret-animation-duration` has to reach the caret style in the UNIT the
    /// stylesheet used. A `5t` that arrived here as 5 *milliseconds* would blink
    /// ~16x too fast and would be indistinguishable, at this layer, from a
    /// deliberate wall-clock value.
    #[test]
    fn caret_animation_duration_preserves_the_unit_the_stylesheet_used() {
        let child = Some(NodeId::new(1));
        let sd = body_with_divs(1, "div { caret-animation-duration: 5t; }");
        assert_eq!(
            get_caret_style(&sd, child).animation_duration,
            CssDuration::from_ticks(5)
        );
        let sd = body_with_divs(1, "div { caret-animation-duration: 250ms; }");
        assert_eq!(
            get_caret_style(&sd, child).animation_duration,
            CssDuration::from_millis(250)
        );
        let sd = body_with_divs(1, "div { caret-animation-duration: 1s; }");
        assert_eq!(
            get_caret_style(&sd, child).animation_duration,
            CssDuration::from_millis(1000)
        );
        // 60 frames and 1000ms are the same span but NOT the same value: the
        // unit is preserved, not normalised.
        let sd = body_with_divs(1, "div { caret-animation-duration: 60t; }");
        assert_ne!(
            get_caret_style(&sd, child).animation_duration,
            CssDuration::from_millis(1000)
        );
    }
    /// `text_color` is the `::selection` colour the text pass must paint
    /// selected glyphs in. Both authorities have to arrive intact — a stylesheet
    /// `-azul-selection-color`, and the OS highlight colour when the stylesheet
    /// is silent — because the alternative (leaving glyphs their normal colour
    /// under an OPAQUE highlight) is dark-on-dark.
    #[test]
    fn selection_style_carries_the_css_text_colour_and_the_system_fallback() {
        let child = Some(NodeId::new(1));
        let red = ColorU {
            r: 255,
            g: 0,
            b: 0,
            a: 255,
        };
        let green = ColorU {
            r: 0,
            g: 255,
            b: 0,
            a: 255,
        };
        let sd = body_with_divs(
            1,
            "div { -azul-selection-color: #ff0000; -azul-selection-background-color: #00ff00; }",
        );
        let sel = get_selection_style(&sd, child, None);
        assert_eq!(
            sel.text_color,
            Some(red),
            "the stylesheet is the top authority"
        );
        assert_eq!(sel.bg_color, green);
        assert_eq!(sel.text_color_or(ColorU::BLACK), red);
        // No stylesheet opinion: the system style answers for BOTH halves.
        let system = std::sync::Arc::new(azul_css::system::defaults::windows_11_light());
        let sd = body_with_divs(1, "");
        let sel = get_selection_style(&sd, child, Some(&system));
        assert_eq!(
            sel.text_color,
            Some(ColorU::new_rgb(255, 255, 255)),
            "the OS highlight text colour"
        );
        assert_eq!(sel.bg_color, ColorU::new_rgb(0, 120, 215));
        // The stylesheet still wins over the system style.
        let sd = body_with_divs(1, "div { -azul-selection-color: #ff0000; }");
        assert_eq!(
            get_selection_style(&sd, child, Some(&system)).text_color,
            Some(red)
        );
    }
    /// No authority at all ⇒ `None`, and the painter must leave the glyph's own
    /// colour untouched rather than substituting a default.
    #[test]
    fn selection_style_without_any_text_colour_keeps_the_normal_glyph_colour() {
        let sd = body_with_divs(1, "");
        let sel = get_selection_style(&sd, Some(NodeId::new(1)), None);
        assert_eq!(sel.text_color, None);
        let normal = ColorU {
            r: 17,
            g: 34,
            b: 51,
            a: 255,
        };
        assert_eq!(sel.text_color_or(normal), normal);
    }
    #[test]
    fn z_index_defaults_to_auto_and_reads_back_explicit_integers() {
        let sd = body_with_divs(1, "");
        let root = NodeId::new(0);
        assert_eq!(get_z_index(&sd, Some(root)), 0);
        assert!(is_z_index_auto(&sd, Some(root)));
        for (css, want) in [
            ("div { z-index: 0; }", 0_i32),
            ("div { z-index: 7; }", 7),
            ("div { z-index: -7; }", -7),
        ] {
            let sd = body_with_divs(1, css);
            let child = Some(NodeId::new(1));
            assert_eq!(get_z_index(&sd, child), want, "{css:?}");
            assert!(
                !is_z_index_auto(&sd, child),
                "an explicit integer is not auto ({css:?})"
            );
        }
        // `z-index: auto` reads back as 0 but is still reported as auto.
        let sd = body_with_divs(1, "div { z-index: auto; }");
        let child = Some(NodeId::new(1));
        assert_eq!(get_z_index(&sd, child), 0);
        assert!(is_z_index_auto(&sd, child));
    }
    #[test]
    fn z_index_reads_back_the_i16_encoding_boundaries_and_falls_through_above_them() {
        // The compact cache packs z-index into an i16 whose top four values are
        // sentinels (I16_SENTINEL_THRESHOLD = 32764). Values at or above the threshold
        // must be stored as the sentinel and re-read via the cascade, NOT truncated.
        for (css, want) in [
            ("div { z-index: 32763; }", 32_763_i32), // largest directly encodable
            ("div { z-index: -32768; }", -32_768),   // i16 lower bound
            ("div { z-index: 32764; }", 32_764),     // == threshold → sentinel → cascade
            ("div { z-index: 99999; }", 99_999),     // far above → sentinel → cascade
            ("div { z-index: 2147483647; }", i32::MAX),
        ] {
            let sd = body_with_divs(1, css);
            let child = Some(NodeId::new(1));
            assert_eq!(
                get_z_index(&sd, child),
                want,
                "{css:?} must survive the i16 compact encoding"
            );
            assert!(
                !is_z_index_auto(&sd, child),
                "an explicit (if huge) integer is not auto ({css:?})"
            );
        }
    }
    // =====================================================================
    // Border radius
    // =====================================================================
    #[test]
    fn border_radius_is_zero_by_default_for_every_degenerate_element_and_viewport_size() {
        let sd = StyledDom::default();
        let root = NodeId::new(0);
        let st = normal();
        let sizes = [
            (0.0_f32, 0.0_f32),
            (-100.0, -100.0),
            (f32::NAN, f32::NAN),
            (f32::INFINITY, f32::INFINITY),
            (f32::MAX, f32::MAX),
            (f32::MIN_POSITIVE, f32::MIN_POSITIVE),
        ];
        for (w, h) in sizes {
            let element = PhysicalSizeImport {
                width: w,
                height: h,
            };
            let viewport = LogicalSize::new(w, h);
            let r = get_border_radius(&sd, root, &st, element, viewport);
            assert_eq!(r.top_left, 0.0, "element=({w}, {h})");
            assert_eq!(r.top_right, 0.0, "element=({w}, {h})");
            assert_eq!(r.bottom_left, 0.0, "element=({w}, {h})");
            assert_eq!(r.bottom_right, 0.0, "element=({w}, {h})");
        }
    }
    #[test]
    fn border_radius_resolves_authored_pixels_on_both_the_normal_and_the_pseudo_path() {
        let sd = body_with_divs(1, "div { border-radius: 12px; }");
        let child = NodeId::new(1);
        let element = PhysicalSizeImport {
            width: 100.0,
            height: 50.0,
        };
        let viewport = LogicalSize::new(800.0, 600.0);
        for st in [normal(), hovered()] {
            let r = get_border_radius(&sd, child, &st, element, viewport);
            for corner in [r.top_left, r.top_right, r.bottom_left, r.bottom_right] {
                assert!(corner.is_finite(), "corner must stay finite");
                assert_eq!(corner, 12.0);
            }
        }
        let raw = get_style_border_radius(&sd, child, &normal());
        assert!(raw.top_left.number.get().is_finite());
    }
    #[test]
    fn border_radius_percentages_stay_finite_for_zero_and_infinite_element_sizes() {
        let sd = body_with_divs(1, "div { border-radius: 50%; }");
        let child = NodeId::new(1);
        let viewport = LogicalSize::new(0.0, 0.0);
        for (w, h) in [
            (0.0_f32, 0.0_f32),
            (f32::MAX, f32::MAX),
            (-10.0, -10.0),
            (f32::INFINITY, 1.0),
        ] {
            let element = PhysicalSizeImport {
                width: w,
                height: h,
            };
            // Only the pseudo-state path actually resolves the % (the compact cache
            // stores pre-resolved px), so exercise it explicitly.
            let r = get_border_radius(&sd, child, &hovered(), element, viewport);
            for corner in [r.top_left, r.top_right, r.bottom_left, r.bottom_right] {
                assert!(
                    !corner.is_nan(),
                    "a {w}x{h} element produced a NaN corner radius"
                );
            }
        }
    }
    // =====================================================================
    // Smoke coverage for the remaining StyledDom getters
    // =====================================================================
    #[test]
    fn optional_style_getters_are_all_none_on_an_unstyled_node() {
        let sd = body_with_divs(1, "");
        let id = NodeId::new(1);
        for st in [normal(), hovered()] {
            assert!(get_shape_inside(&sd, id, &st).is_none());
            assert!(get_shape_outside(&sd, id, &st).is_none());
            assert!(get_line_clamp(&sd, id, &st).is_none());
            assert!(get_initial_letter(&sd, id, &st).is_none());
            assert!(get_hanging_punctuation(&sd, id, &st).is_none());
            assert!(get_text_combine_upright(&sd, id, &st).is_none());
            assert!(get_hyphenation_language(&sd, id, &st).is_none());
            assert!(get_column_count(&sd, id, &st).is_none());
            assert!(get_filter(&sd, id, &st).is_none());
            assert!(get_backdrop_filter(&sd, id, &st).is_none());
            assert!(get_box_shadow_left(&sd, id, &st).is_none());
            assert!(get_box_shadow_right(&sd, id, &st).is_none());
            assert!(get_box_shadow_top(&sd, id, &st).is_none());
            assert!(get_box_shadow_bottom(&sd, id, &st).is_none());
            assert!(get_text_shadow(&sd, id, &st).is_none());
            assert!(get_transform(&sd, id, &st).is_none());
            assert!(get_counter_reset(&sd, id, &st).is_none());
            assert!(get_counter_increment(&sd, id, &st).is_none());
            assert!(get_clip_path(&sd, id, &st).is_none());
            assert!(get_grid_template_areas_prop(&sd, id, &st).is_none());
        }
    }
    #[test]
    fn numeric_style_getters_use_their_documented_defaults() {
        let sd = body_with_divs(1, "");
        let id = NodeId::new(1);
        for st in [normal(), hovered()] {
            assert_eq!(get_opacity(&sd, id, &st), 1.0, "opacity defaults to 1.0");
            assert_eq!(
                get_exclusion_margin(&sd, id, &st),
                0.0,
                "exclusion-margin defaults to 0.0"
            );
            assert!(get_scrollbar_width_px(&sd, id, &st).is_finite());
            assert!(get_scrollbar_width_px(&sd, id, &st) >= 0.0);
        }
    }
    #[test]
    fn opacity_in_range_agrees_on_the_compact_and_the_cascade_path() {
        for css in [
            "div { opacity: 0; }",
            "div { opacity: 1; }",
            "div { opacity: 0.5; }",
        ] {
            let sd = body_with_divs(1, css);
            let id = NodeId::new(1);
            let fast = get_opacity(&sd, id, &normal()); // compact-cache u8 path
            let slow = get_opacity(&sd, id, &hovered()); // full cascade path
            assert!(fast.is_finite() && slow.is_finite(), "{css:?}");
            assert!(
                (0.0..=1.0).contains(&fast),
                "{css:?} read back out of range on the compact path: {fast}"
            );
            assert!(
                (fast - slow).abs() < 0.01,
                "{css:?}: compact path says {fast}, cascade path says {slow}"
            );
        }
        // A mid-range value must actually take effect (i.e. differ from the 1.0 default).
        let half = get_opacity(
            &body_with_divs(1, "div { opacity: 0.5; }"),
            NodeId::new(1),
            &normal(),
        );
        assert!(half < 1.0 && half > 0.0, "opacity: 0.5 read back as {half}");
    }
    #[test]
    fn opacity_never_returns_nan_or_infinity_for_out_of_range_authored_values() {
        // NOTE: CSS Color 3 clamps opacity to [0,1]. The compact-cache encoder does
        // clamp (`normalized().clamp(0.0, 1.0)`), but `get_opacity`'s cascade path
        // returns `inner.normalized()` unclamped — so a non-Normal pseudo-state can
        // report an out-of-range opacity. That divergence is reported separately; the
        // invariant asserted here (always a finite number) must hold on BOTH paths.
        for css in [
            "div { opacity: 5; }",
            "div { opacity: -3; }",
            "div { opacity: 1e30; }",
        ] {
            let sd = body_with_divs(1, css);
            let id = NodeId::new(1);
            for st in [normal(), hovered()] {
                let o = get_opacity(&sd, id, &st);
                assert!(o.is_finite(), "{css:?} produced a non-finite opacity: {o}");
            }
            // The compact path is the one the encoder clamps, so it is always in range.
            let fast = get_opacity(&sd, id, &normal());
            assert!(
                (0.0..=1.0).contains(&fast),
                "{css:?} escaped the compact-cache clamp: {fast}"
            );
        }
    }
    #[test]
    fn enum_property_getters_stay_deterministic_across_pseudo_states() {
        let sd = body_with_divs(1, "");
        let id = NodeId::new(1);
        for st in [normal(), hovered()] {
            // These may be Auto or Exact depending on the UA sheet; the contract under
            // test is only that they answer without panicking and answer consistently.
            let gutter = get_scrollbar_gutter_property(&sd, id, &st);
            assert_eq!(gutter, get_scrollbar_gutter_property(&sd, id, &st));
            let orientation = get_text_orientation_property(&sd, id, &st);
            assert_eq!(orientation, get_text_orientation_property(&sd, id, &st));
            let valign = get_vertical_align_property(&sd, id, &st);
            assert_eq!(valign, get_vertical_align_property(&sd, id, &st));
            let _ = get_background_color(&sd, id, &st);
            let _ = get_background_contents(&sd, id, &st);
            let _ = get_border_info(&sd, id, &st);
            let _ = get_border_spacing(&sd, id, &st);
            let _ = get_height_value(&sd, id, &st);
            let _ = get_line_height_value(&sd, id, &st);
            let _ = get_text_indent_value(&sd, id, &st);
        }
        // vertical-align defaults to the baseline for an unstyled div.
        assert!(matches!(
            get_vertical_align_for_node(&sd, id),
            crate::text3::cache::VerticalAlign::Baseline
        ));
    }
    #[test]
    fn get_inline_border_info_is_none_without_borders_and_survives_a_degenerate_viewport() {
        let sd = body_with_divs(1, "");
        let id = NodeId::new(1);
        let st = normal();
        let info = get_border_info(&sd, id, &st);
        for viewport in [
            PhysicalSize::new(0.0, 0.0),
            PhysicalSize::new(f32::NAN, f32::NAN),
            PhysicalSize::new(f32::INFINITY, f32::INFINITY),
            PhysicalSize::new(-1.0, -1.0),
            PhysicalSize::new(f32::MAX, f32::MAX),
        ] {
            assert!(
                get_inline_border_info(&sd, id, &st, &info, viewport).is_none(),
                "a node with neither border nor padding has no inline border box"
            );
        }
    }
    #[test]
    fn get_inline_border_info_reports_finite_widths_for_a_bordered_node() {
        let sd = body_with_divs(1, "div { border: 3px solid red; padding: 5px; }");
        let id = NodeId::new(1);
        let st = normal();
        let info = get_border_info(&sd, id, &st);
        let inline = get_inline_border_info(&sd, id, &st, &info, PhysicalSize::new(800.0, 600.0))
            .expect("a bordered + padded node must produce an InlineBorderInfo");
        for w in [inline.top, inline.right, inline.bottom, inline.left] {
            assert!(w.is_finite() && w >= 0.0, "border width {w}");
        }
        for p in [
            inline.padding_top,
            inline.padding_right,
            inline.padding_bottom,
            inline.padding_left,
        ] {
            assert!(p.is_finite() && p >= 0.0, "padding {p}");
        }
        assert!(inline.is_first_fragment && inline.is_last_fragment);
        assert!(!inline.is_rtl, "the default direction is ltr");
        // The same node under a NaN viewport: px lengths do not consult the viewport,
        // so the result must stay finite rather than turn into NaN.
        let nan_vp =
            get_inline_border_info(&sd, id, &st, &info, PhysicalSize::new(f32::NAN, f32::NAN))
                .expect("px borders do not depend on the viewport");
        assert!(nan_vp.top.is_finite() && nan_vp.padding_top.is_finite());
    }
    #[test]
    fn get_style_properties_stays_finite_for_every_degenerate_viewport() {
        let sd = body_with_text("hello");
        for viewport in [
            PhysicalSize::new(0.0, 0.0),
            PhysicalSize::new(-1.0, -1.0),
            PhysicalSize::new(f32::NAN, f32::NAN),
            PhysicalSize::new(f32::INFINITY, f32::INFINITY),
            PhysicalSize::new(f32::MAX, f32::MAX),
        ] {
            for id in [NodeId::new(0), NodeId::new(1)] {
                let props = get_style_properties(&sd, id, None, viewport);
                assert!(
                    props.font_size_px.is_finite(),
                    "viewport {viewport:?} produced a non-finite font size"
                );
                assert!(props.font_size_px > 0.0);
            }
        }
    }
    // =====================================================================
    // user-select / contenteditable predicates
    // =====================================================================
    #[test]
    fn is_text_selectable_is_true_by_default_and_false_for_user_select_none() {
        let sd = body_with_divs(1, "");
        assert!(
            is_text_selectable(&sd, NodeId::new(1), &normal()),
            "text is selectable unless user-select says otherwise"
        );
        let sd = body_with_divs(1, "div { user-select: none; }");
        assert!(!is_text_selectable(&sd, NodeId::new(1), &normal()));
        let sd = body_with_divs(1, "div { user-select: text; }");
        assert!(is_text_selectable(&sd, NodeId::new(1), &normal()));
    }
    #[test]
    fn contenteditable_is_false_everywhere_on_a_plain_dom() {
        let sd = body_with_divs(2, "");
        for idx in 0..sd.node_data.len() {
            let id = NodeId::new(idx);
            assert!(!is_node_contenteditable(&sd, id), "node {idx}");
            assert!(!is_node_contenteditable_inherited(&sd, id), "node {idx}");
            assert_eq!(find_contenteditable_ancestor(&sd, id), None, "node {idx}");
        }
    }
    #[test]
    fn contenteditable_is_inherited_by_descendants_but_not_reported_as_direct() {
        // body(0) > editable div(1) > plain div(2)
        let mut editable = Dom::create_div().with_children(vec![Dom::create_div()].into());
        editable.root.set_contenteditable(true);
        let mut dom = Dom::create_body().with_children(vec![editable].into());
        let sd = StyledDom::create(&mut dom, Css::empty());
        assert_eq!(sd.node_data.len(), 3);
        let (body, editable, child) = (NodeId::new(0), NodeId::new(1), NodeId::new(2));
        assert!(!is_node_contenteditable(&sd, body));
        assert!(is_node_contenteditable(&sd, editable));
        assert!(
            !is_node_contenteditable(&sd, child),
            "the direct check must not walk up the tree"
        );
        assert!(!is_node_contenteditable_inherited(&sd, body));
        assert!(is_node_contenteditable_inherited(&sd, editable));
        assert!(
            is_node_contenteditable_inherited(&sd, child),
            "editability is inherited from the ancestor"
        );
        assert_eq!(find_contenteditable_ancestor(&sd, body), None);
        assert_eq!(find_contenteditable_ancestor(&sd, editable), Some(editable));
        assert_eq!(
            find_contenteditable_ancestor(&sd, child),
            Some(editable),
            "a nested node resolves to its editable container, not to itself"
        );
    }
    // =====================================================================
    // Codepoint / script collection
    // =====================================================================
    #[test]
    fn collect_used_codepoints_strips_ascii_while_the_all_variant_keeps_it() {
        // ASCII + Latin-1 + CJK + an astral-plane emoji (a surrogate pair in UTF-16).
        let sd = body_with_text("aé漢🎉");
        let non_ascii = collect_used_codepoints(&sd);
        assert_eq!(non_ascii.len(), 3, "the ASCII 'a' is dropped");
        assert!(non_ascii.contains(&0x00E9));
        assert!(non_ascii.contains(&0x6F22));
        assert!(non_ascii.contains(&0x0001_F389), "astral plane codepoint");
        assert!(!non_ascii.contains(&u32::from(b'a')));
        let all = collect_used_codepoints_all(&sd);
        assert_eq!(all.len(), 4);
        assert!(all.contains(&'a'));
        assert!(all.contains(&'🎉'));
    }
    #[test]
    fn collect_used_codepoints_dedupes_and_handles_empty_and_ascii_only_text() {
        // Repeats collapse (BTreeSet), and a DOM with no text at all yields nothing.
        let sd = body_with_text("ααα");
        assert_eq!(collect_used_codepoints(&sd).len(), 1);
        let sd = body_with_text("");
        assert!(collect_used_codepoints(&sd).is_empty());
        assert!(collect_used_codepoints_all(&sd).is_empty());
        let sd = body_with_divs(3, "");
        assert!(
            collect_used_codepoints(&sd).is_empty(),
            "element nodes carry no codepoints"
        );
        let sd = body_with_text("plain ascii");
        assert!(collect_used_codepoints(&sd).is_empty());
        assert!(!collect_used_codepoints_all(&sd).is_empty());
    }
    #[test]
    fn scripts_present_in_styled_dom_is_empty_for_ascii_and_bounded_by_the_default_set() {
        let ascii = body_with_text("hello world");
        assert!(
            scripts_present_in_styled_dom(&ascii).is_empty(),
            "an ASCII-only page must not drag in any unicode fallback script"
        );
        let empty = StyledDom::default();
        assert!(scripts_present_in_styled_dom(&empty).is_empty());
        let cjk = body_with_text("漢字");
        let scripts = scripts_present_in_styled_dom(&cjk);
        assert!(
            !scripts.is_empty(),
            "CJK text must report at least one script"
        );
        assert!(
            scripts.len() <= DEFAULT_UNICODE_FALLBACK_SCRIPTS.len(),
            "the result is always a subset of the default script set"
        );
        for r in &scripts {
            assert!(r.start <= r.end, "a script range must not be inverted");
        }
    }
    #[test]
    fn collect_font_stacks_from_styled_dom_keeps_its_index_map_consistent() {
        let platform = azul_css::system::Platform::current();
        for sd in [
            StyledDom::default(),
            body_with_text("hello"),
            body_with_divs(3, "div { font-family: Iosevka, monospace; }"),
        ] {
            let collected = collect_font_stacks_from_styled_dom(&sd, &platform);
            assert_eq!(
                collected.hash_to_index.len(),
                collected.font_stacks.len(),
                "every recorded hash must map to exactly one stack"
            );
            for &idx in collected.hash_to_index.values() {
                assert!(
                    idx < collected.font_stacks.len(),
                    "hash_to_index points past the end of font_stacks"
                );
            }
            for stack in &collected.font_stacks {
                assert!(!stack.is_empty(), "an empty font stack is never recorded");
            }
        }
    }
}
#[cfg(test)]
mod memory_font_tier_tests {
    use super::*;
    use crate::text3::cache::{MemoryFace, MemoryFontTier};
6
    fn face(tier: MemoryFontTier) -> MemoryFace {
6
        MemoryFace {
6
            tier,
6
            font_match: rust_fontconfig::FontMatch {
6
                id: FontId::new(),
6
                unicode_ranges: Vec::new(),
6
                fallbacks: Vec::new(),
6
            },
6
            weight: FcWeight::Normal,
6
            italic: false,
6
            oblique: false,
6
            stretch: rust_fontconfig::FcStretch::Normal,
6
            weight_axis: None,
6
        }
6
    }
4
    fn split(
4
        stack: &[&str],
4
        registered: &[(&str, MemoryFontTier)],
4
    ) -> (Vec<String>, Vec<String>, Vec<String>) {
4
        let mut memory_families: HashMap<String, Vec<MemoryFace>> = HashMap::new();
10
        for (family, tier) in registered {
6
            memory_families
6
                .entry(rust_fontconfig::utils::normalize_family_name(family))
6
                .or_default()
6
                .push(face(*tier));
6
        }
6
        let families: Vec<String> = stack.iter().map(|s| (*s).to_string()).collect();
4
        let (primary, disk, fallback) =
4
            split_memory_matches(&families, &memory_families, FcWeight::Normal, false, false);
        (
4
            primary.into_iter().map(|g| g.css_name).collect(),
4
            disk,
4
            fallback.into_iter().map(|g| g.css_name).collect(),
        )
4
    }
    /// A primary face is the family: the disk is never asked about it.
    #[test]
1
    fn a_primary_face_takes_the_family_from_the_disk() {
1
        let (primary, disk, fallback) =
1
            split(&["Helvetica"], &[("Helvetica", MemoryFontTier::Primary)]);
1
        assert_eq!(primary, ["Helvetica"]);
1
        assert!(disk.is_empty());
1
        assert!(fallback.is_empty());
1
    }
    /// A fallback face does NOT take the family - the disk still gets asked, and
    /// the face only waits behind whatever the disk turns up. This is what lets
    /// printpdf offer the 14 standard PDF fonts for `sans-serif` without those
    /// Win-1252 subsets displacing the system's Unicode faces on a desktop.
    #[test]
1
    fn a_fallback_face_leaves_the_family_to_the_disk() {
1
        let (primary, disk, fallback) =
1
            split(&["sans-serif"], &[("sans-serif", MemoryFontTier::Fallback)]);
1
        assert!(primary.is_empty());
1
        assert_eq!(
            disk,
            ["sans-serif"],
            "the disk must still get first refusal"
        );
1
        assert_eq!(fallback, ["sans-serif"]);
1
    }
    /// With nothing installed - wasm - the disk probe comes back empty and the
    /// fallback face is what is left, which is the whole point of the tier.
    #[test]
1
    fn both_tiers_can_appear_in_one_stack() {
1
        let (primary, disk, fallback) = split(
1
            &["Helvetica", "Arial", "sans-serif"],
1
            &[
1
                ("Helvetica", MemoryFontTier::Primary),
1
                ("sans-serif", MemoryFontTier::Fallback),
1
            ],
1
        );
1
        assert_eq!(primary, ["Helvetica"]);
1
        assert_eq!(disk, ["Arial", "sans-serif"]);
1
        assert_eq!(fallback, ["sans-serif"]);
1
    }
    /// Registering both tiers for one family must not make it ambiguous: the
    /// primary face wins and the fallback is not also offered.
    #[test]
1
    fn primary_beats_fallback_for_the_same_family() {
1
        let (primary, disk, fallback) = split(
1
            &["Helvetica"],
1
            &[
1
                ("Helvetica", MemoryFontTier::Fallback),
1
                ("Helvetica", MemoryFontTier::Primary),
1
            ],
1
        );
1
        assert_eq!(primary, ["Helvetica"]);
1
        assert!(disk.is_empty());
1
        assert!(fallback.is_empty());
1
    }
}
#[cfg(test)]
mod style_interning_tests {
    use super::*;
    /// Nodes that resolve to the SAME computed style must share one
    /// allocation.
    ///
    /// The cache used to be keyed on `(node_id, state, viewport)` alone, so
    /// every node got its own `Arc` even when the style was byte-identical
    /// — sharing by producer identity, not by result value. Measured on one
    /// markdown document: 672 distinct `Arc<StyleProperties>` behind 31,086
    /// glyphs, for a document with ~10 distinct text styles. Stylo shipped
    /// the same defect (109k ComputedValues where 2,200 were expected).
    ///
    /// NEGATIVE CONTROL: dropping the `by_value` lookup (always
    /// `Arc::new`) makes the pointer-equality assertion fail — run and
    /// seen.
    #[test]
1
    fn identical_styles_share_one_allocation() {
        use azul_core::{
            dom::{Dom, NodeId},
            styled_dom::StyledDom,
        };
        // Three sibling texts with no styling of their own: identical
        // computed style, three different nodes.
1
        let dom = Dom::create_body()
1
            .with_child(Dom::create_text_do_not_use_without_block_level_wrapper(
                "one",
            ))
1
            .with_child(Dom::create_text_do_not_use_without_block_level_wrapper(
                "two",
            ))
1
            .with_child(Dom::create_text_do_not_use_without_block_level_wrapper(
                "three",
            ));
1
        let sd = StyledDom::create_from_dom(dom);
1
        let viewport = PhysicalSize::new(800.0, 600.0);
1
        let mut cache = StyleCache::default();
1
        let n = sd.node_data.as_container().internal.len();
1
        let mut arcs = Vec::new();
4
        for i in 0..n {
4
            arcs.push(get_style_properties_cached(
4
                &mut cache,
4
                &sd,
4
                NodeId::new(i),
4
                None,
4
                viewport,
4
            ));
4
        }
1
        let distinct: std::collections::BTreeSet<usize> = arcs
1
            .iter()
4
            .map(|a| std::sync::Arc::as_ptr(a) as usize)
1
            .collect();
1
        assert!(
1
            distinct.len() < arcs.len(),
            "{} nodes produced {} DISTINCT StyleProperties allocations — identical computed \
             styles are not being shared, which is the defect this cache exists to prevent",
            arcs.len(),
            distinct.len()
        );
        // Asking for the same node twice must not build anything new.
1
        let again = get_style_properties_cached(&mut cache, &sd, NodeId::new(0), None, viewport);
1
        assert!(
1
            std::sync::Arc::ptr_eq(&arcs[0], &again),
            "a repeat query for the same node must hit the by-node memo"
        );
1
    }
    /// A hash collision must NEVER merge two different styles.
    ///
    /// `by_value` buckets on a 64-bit hash. If the bucket were trusted
    /// without an equality check, two distinct styles landing in one bucket
    /// would share an allocation and text would silently render in the
    /// wrong font/colour — a corruption far worse than the memory it saves.
    /// This forces the collision directly by planting a foreign entry under
    /// the hash the next build will compute.
    #[test]
1
    fn a_hash_collision_never_merges_two_different_styles() {
        use azul_core::{
            dom::{Dom, NodeId},
            styled_dom::StyledDom,
        };
1
        let sd = StyledDom::create_from_dom(
1
            Dom::create_body()
1
                .with_child(Dom::create_text_do_not_use_without_block_level_wrapper("x")),
        );
1
        let viewport = PhysicalSize::new(800.0, 600.0);
1
        let mut cache = StyleCache::default();
1
        let real = get_style_properties_cached(&mut cache, &sd, NodeId::new(0), None, viewport);
        // A style that differs from `real`, planted in EVERY bucket so the
        // next lookup is guaranteed to meet a colliding entry.
1
        let mut impostor = (*real).clone();
1
        impostor.font_size_px += 7.0;
1
        assert_ne!(impostor, *real, "the impostor must actually differ");
1
        let impostor = std::sync::Arc::new(impostor);
1
        for bucket in cache.by_value.values_mut() {
1
            bucket.insert(0, std::sync::Arc::clone(&impostor));
1
        }
1
        cache.by_node.clear();
1
        let rebuilt = get_style_properties_cached(&mut cache, &sd, NodeId::new(0), None, viewport);
1
        assert_ne!(
1
            *rebuilt, *impostor,
            "a colliding bucket entry must be rejected by the equality check, not returned"
        );
1
        assert_eq!(*rebuilt, *real, "the correct style is still produced");
1
    }
}
#[cfg(test)]
mod unresolved_family_reporting_tests {
    use super::*;
    /// The unresolved-family warning must go through the DIAGNOSTICS SINK like
    /// every other azul warning, not through a bare `eprintln!`.
    ///
    /// Two things were wrong with printing directly. It panics: `eprintln!`
    /// aborts the process when the write fails, and a closed stderr is
    /// ordinary - piping a running app into `head` killed it exactly that way
    /// (see `azul_core::diagnostics::write_diagnostic`). And it is invisible
    /// to the ring, so no test can assert that a missing family was reported,
    /// which is the whole reason the diagnostic was added.
    ///
    /// Kept through the rust-fontconfig 5.0 merge: the ALIAS-PRUNE tests that
    /// used to sit beside this one were deleted with `should_prune_family`,
    /// which 5.0's `prune_script_groups` / `prune_chain_to_used_chars`
    /// replaced. This test is about the diagnostic, not the pruning, and the
    /// fix it guards is still in `report_unresolved_families`.
    #[test]
1
    fn a_missing_family_is_reported_through_the_diagnostics_ring() {
1
        let _g = azul_core::diagnostics::test_lock().lock();
1
        azul_core::diagnostics::clear();
1
        let mut resolved = ResolvedFontChains::default();
1
        resolved
1
            .unresolved_families
1
            .insert("Totally Not Installed Sans".to_string());
1
        report_unresolved_families(&resolved);
1
        assert!(
1
            azul_core::diagnostics::any_contains("Totally Not Installed Sans"),
            "the warning must be recorded, not just printed: {:?}",
            azul_core::diagnostics::recorded()
        );
1
    }
}