1
//! Headless backend for CPU-only rendering without a display server.
2
//!
3
//! This module provides the resource management and rendering pipeline for
4
//! running Azul applications without any platform windowing APIs. It works
5
//! in combination with `HeadlessWindow` (in `dll/src/desktop/shell2/headless/`) which
6
//! provides the `PlatformWindow` trait implementation.
7
//!
8
//! # Architecture
9
//!
10
//! The headless path replaces the WebRender GPU pipeline with `cpurender`:
11
//! `LayoutWindow → solver3 DisplayList → cpurender → PNG/Pixmap`. Compared to the
12
//! GPU path there is no GL context, `webrender::Renderer`, or `RenderApi`; fonts
13
//! and images are managed by `FontManager`/`ImageCache` and read directly by
14
//! cpurender (no GPU texture atlas or upload), hit testing uses the layout-side
15
//! `CpuHitTester` instead of WebRender's `AsyncHitTester`, and present/swap is a
16
//! no-op.
17
//!
18
//! Activated with `AZUL_HEADLESS=1` (optionally `AZ_DEBUG=1` for the debug server).
19

            
20
use std::collections::BTreeMap;
21

            
22
use azul_core::{
23
    dom::{DomId, DomNodeId, NodeId},
24
    geom::{LogicalPosition, LogicalRect, LogicalSize},
25
    hit_test::FullHitTest,
26
    spaces::{BorderBoxLocal, ContentBoxLocal, Inclusivity, StaticLayoutPoint},
27
    styled_dom::StyledDom,
28
};
29

            
30
use crate::{
31
    solver3::{
32
        getters::{get_overflow_x, get_overflow_y},
33
        layout_tree::{LayoutNodeHot, LayoutNodeId},
34
        PositionVec,
35
    },
36
    window::DomLayoutResult,
37
};
38

            
39
/// Large finite half-extent used in place of `f32::INFINITY` for clip axes that
40
/// are not constrained by any ancestor. Keeping it finite avoids `NaN` in
41
/// `point_in_rect` (`origin + size` would be `inf - inf = NaN`) while staying
42
/// far outside any realistic logical-pixel coordinate.
43
const CLIP_UNBOUNDED: f32 = 1.0e7;
44

            
45
/// CPU-based hit tester that works without `WebRender`.
46
///
47
/// In the GPU path, hit testing is done by `AsyncHitTester` which queries
48
/// `WebRender`'s spatial tree. In headless mode, we do hit testing directly
49
/// against the layout results (positioned rectangles).
50
///
51
/// This is actually simpler and faster than the `WebRender` path, since we
52
/// don't need to go through the compositor's spatial tree — we just walk
53
/// the layout result nodes and check point-in-rect.
54
#[derive(Debug)]
55
pub struct CpuHitTester {
56
    /// Cached hit test results from the last layout.
57
    /// Maps `DomId` -> list of (`NodeId`, positioned rect) sorted by paint order.
58
    node_rects: BTreeMap<DomId, Vec<HitTestEntry>>,
59
    /// Interned ancestor chains (scroll frames + reference frames). Index 0
60
    /// is always the empty chain. Entry / clip `chain` values index into
61
    /// this. A node's on-screen position is
62
    /// `T_total(static_pos − scroll_total)` — the same rule
63
    /// `cpurender::raster` paints with (accumulated scroll subtraction, then
64
    /// the composed reference-frame transform), so pixels and pointer
65
    /// targets cannot disagree.
66
    chains: Vec<Vec<HitChainLink>>,
67
    /// Every node that got a `PushScrollFrame` (from
68
    /// `DomLayoutResult::scroll_ids`, the same set the display list uses),
69
    /// translated into window space, with the chain of its STRICT scroll
70
    /// ancestors (a container's own viewport box does not move when it
71
    /// scrolls — only its content does).
72
    scroll_containers: Vec<ScrollContainerEntry>,
73
    /// `VirtualView` child-DOM placements in window space (static coords).
74
    dom_placements: BTreeMap<DomId, LogicalRect>,
75
}
76

            
77
/// A node's clip geometry together with the `viewBox`
78
/// (`min_x`, `min_y`, `width`, `height`) it was authored in, if any.
79
///
80
/// Deliberately NOT called `ClipPath`: `azul_css` already exports a
81
/// `ClipPath` (the CSS property), and the C-API safety scanner rejects two
82
/// types of the same name in different files as a collision.
83
type HitClipGeometry = (
84
    azul_core::svg::SvgMultiPolygon,
85
    Option<(f32, f32, f32, f32)>,
86
);
87

            
88
/// A single entry in the CPU hit test acceleration structure.
89
#[derive(Debug, Clone)]
90
struct HitTestEntry {
91
    /// The DOM node that this entry corresponds to.
92
    node_id: NodeId,
93
    /// Static (unscrolled) position and size of this node in logical pixels,
94
    /// window space (`VirtualView` placement already applied).
95
    rect: LogicalRect,
96
    /// Ancestor scroll frames whose offsets shift this node on screen
97
    /// (index into [`CpuHitTester::chains`]).
98
    chain: u32,
99
    /// Clip boxes from `overflow`-clipping ancestors and the `VirtualView`
100
    /// composite bounds. Each clip carries the chain of ITS owner's strict
101
    /// scroll ancestors — a clip box inside a scrolled frame moves with that
102
    /// frame, while the clipping container's own scroll does not move its
103
    /// viewport. Axis-only clips (`overflow-x`/`overflow-y` independent) are
104
    /// stored with the unclipped axis widened to [`CLIP_UNBOUNDED`].
105
    clips: Vec<(LogicalRect, u32)>,
106
    /// Whether this node is pointer-events: none
107
    pointer_events_none: bool,
108
    /// This node's CLIP PATH - its own SVG geometry, plus the `viewBox` of the
109
    /// `<svg>` that geometry is drawn in.
110
    ///
111
    /// A clip path is not decoration: what it clips AWAY is not part of the
112
    /// element any more, and that has to include its pointer target. Without
113
    /// this, the transparent corners of a circular button stayed clickable and
114
    /// - worse - kept SHADOWING whatever was behind them, which is precisely
115
    /// the thing a clip-path is asked for.
116
    clip_path: Option<HitClipGeometry>,
117
}
118

            
119
/// A scroll container (`PushScrollFrame` owner) for wheel-target resolution.
120
#[derive(Debug, Clone)]
121
struct ScrollContainerEntry {
122
    dom_id: DomId,
123
    node_id: NodeId,
124
    /// Index of this node in its DOM's layout tree (for content-size lookup).
125
    layout_idx: LayoutNodeId,
126
    scroll_id: u64,
127
    /// Static viewport box, window space (placement-translated).
128
    rect: LogicalRect,
129
    /// Chain of STRICT scroll ancestors (index into [`CpuHitTester::chains`]).
130
    chain: u32,
131
}
132

            
133
/// One link in a node's ancestor chain: something between the node and the
134
/// window root that moves the node's on-screen position at runtime.
135
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
136
pub enum HitChainLink {
137
    /// An ancestor scroll frame — shifts content by the CURRENT scroll
138
    /// offset (`ScrollManager::get_current_offset`), painted as
139
    /// `pos - offset`.
140
    Scroll(DomId, NodeId),
141
    /// An ancestor wrapped in a `PushReferenceFrame` (CSS transform / drag /
142
    /// animation) — the CURRENT matrix lives in the GPU value cache
143
    /// (`css_current_transform_values`), the same source the CPU raster
144
    /// reads at paint time.
145
    Transform(DomId, NodeId),
146
}
147

            
148
/// Minimal 2D affine mirroring `agg_rust::trans_affine::TransAffine`.
149
///
150
/// Row-vector convention: `x' = x·sx + y·shx + tx; y' = x·shy + y·sy + ty`.
151
/// Local copy because `agg-rust` is optional (svg/cpurender features) and
152
/// hit-testing must exist in every configuration. The multiply/invert bodies
153
/// are transcribed from agg so composition matches the raster EXACTLY.
154
#[derive(Debug, Clone, Copy)]
155
pub struct ScreenMapAffine {
156
    pub sx: f32,
157
    pub shy: f32,
158
    pub shx: f32,
159
    pub sy: f32,
160
    pub tx: f32,
161
    pub ty: f32,
162
}
163

            
164
impl ScreenMapAffine {
165
    pub const IDENTITY: Self = Self {
166
        sx: 1.0,
167
        shy: 0.0,
168
        shx: 0.0,
169
        sy: 1.0,
170
        tx: 0.0,
171
        ty: 0.0,
172
    };
173

            
174
    /// The 2D-affine slice of a `ComputedTransform3D`, exactly the elements
175
    /// the CPU raster feeds `TransAffine::new_custom`
176
    /// (`m[0][0], m[0][1], m[1][0], m[1][1], m[3][0], m[3][1]`).
177
    #[must_use]
178
6
    pub const fn from_transform_3d(t: &azul_core::transform::ComputedTransform3D) -> Self {
179
6
        Self {
180
6
            sx: t.m[0][0],
181
6
            shy: t.m[0][1],
182
6
            shx: t.m[1][0],
183
6
            sy: t.m[1][1],
184
6
            tx: t.m[3][0],
185
6
            ty: t.m[3][1],
186
6
        }
187
6
    }
188

            
189
    /// `self = self · m` (agg `multiply`).
190
6
    pub fn multiply(&mut self, m: &Self) {
191
6
        let t0 = self.sx.mul_add(m.sx, self.shy * m.shx);
192
6
        let t2 = self.shx.mul_add(m.sx, self.sy * m.shx);
193
6
        let t4 = self.tx.mul_add(m.sx, self.ty * m.shx) + m.tx;
194
6
        self.shy = self.sx.mul_add(m.shy, self.shy * m.sy);
195
6
        self.sy = self.shx.mul_add(m.shy, self.sy * m.sy);
196
6
        self.ty = self.tx.mul_add(m.shy, self.ty * m.sy) + m.ty;
197
6
        self.sx = t0;
198
6
        self.shx = t2;
199
6
        self.tx = t4;
200
6
    }
201

            
202
    /// `self = m · self` (agg `premultiply`) — the raster's per-push step is
203
    /// `composed = tf; composed.premultiply(&current)`.
204
6
    pub fn premultiply(&mut self, m: &Self) {
205
6
        let mut t = *m;
206
6
        t.multiply(self);
207
6
        *self = t;
208
6
    }
209

            
210
    /// In-place inverse (agg `invert`). Degenerate matrices (determinant 0)
211
    /// leave a non-finite result; callers treat non-finite mapped points as
212
    /// misses, which matches "a zero-scale transform is unclickable".
213
6
    pub fn invert(&mut self) {
214
6
        let d = 1.0 / self.sx.mul_add(self.sy, -(self.shy * self.shx));
215
6
        let t0 = self.sy * d;
216
6
        self.sy = self.sx * d;
217
6
        self.shy = -self.shy * d;
218
6
        self.shx = -self.shx * d;
219
6
        let t4 = (-self.tx).mul_add(t0, -(self.ty * self.shx));
220
6
        self.ty = (-self.tx).mul_add(self.shy, -(self.ty * self.sy));
221
6
        self.sx = t0;
222
6
        self.tx = t4;
223
6
    }
224

            
225
    #[must_use]
226
6
    pub fn apply(&self, p: LogicalPosition) -> LogicalPosition {
227
6
        LogicalPosition {
228
6
            x: p.x.mul_add(self.sx, p.y * self.shx) + self.tx,
229
6
            y: p.x.mul_add(self.shy, p.y * self.sy) + self.ty,
230
6
        }
231
6
    }
232

            
233
    #[allow(clippy::float_cmp)]
234
    // exact equality is correct here: identity is a fast-path gate; a near-identity matrix must
235
    // still be applied
236
    #[must_use]
237
    pub fn is_identity(&self) -> bool {
238
        self.sx == 1.0
239
            && self.shy == 0.0
240
            && self.shx == 0.0
241
            && self.sy == 1.0
242
            && self.tx == 0.0
243
            && self.ty == 0.0
244
    }
245
}
246

            
247
/// A chain resolved against the CURRENT scroll offsets and transform values.
248
///
249
/// The CPU raster paints `screen = T_total(pos − scroll_total)` — one
250
/// accumulated scroll translation and one composed transform stack, in that
251
/// order. The inverse mapping used for hit-testing is therefore
252
/// `local = T_total⁻¹(screen) + scroll_total`.
253
#[derive(Debug, Clone, Copy)]
254
struct ResolvedChain {
255
    scroll: LogicalPosition,
256
    /// FORWARD composed transform (identity when the chain has none).
257
    forward: ScreenMapAffine,
258
    has_transform: bool,
259
}
260

            
261
impl ResolvedChain {
262
846
    fn map_screen_to_local(&self, p: LogicalPosition) -> LogicalPosition {
263
846
        let p = if self.has_transform {
264
6
            let mut inv = self.forward;
265
6
            inv.invert();
266
6
            inv.apply(p)
267
        } else {
268
840
            p
269
        };
270
846
        LogicalPosition {
271
846
            x: p.x + self.scroll.x,
272
846
            y: p.y + self.scroll.y,
273
846
        }
274
846
    }
275

            
276
840
    fn map_local_to_screen(&self, p: LogicalPosition) -> LogicalPosition {
277
840
        let shifted = LogicalPosition {
278
840
            x: p.x - self.scroll.x,
279
840
            y: p.y - self.scroll.y,
280
840
        };
281
840
        if self.has_transform {
282
            self.forward.apply(shifted)
283
        } else {
284
840
            shifted
285
        }
286
840
    }
287
}
288

            
289
1166
fn resolve_chain(
290
1166
    chain: &[HitChainLink],
291
1166
    resolve_scroll: &dyn Fn(DomId, NodeId) -> Option<LogicalPosition>,
292
1166
    resolve_transform: &dyn Fn(DomId, NodeId) -> Option<azul_core::transform::ComputedTransform3D>,
293
1166
) -> ResolvedChain {
294
1166
    let mut scroll = LogicalPosition::zero();
295
1166
    let mut forward = ScreenMapAffine::IDENTITY;
296
1166
    let mut has_transform = false;
297
1955
    for link in chain {
298
789
        match link {
299
783
            HitChainLink::Scroll(d, n) => {
300
783
                if let Some(o) = resolve_scroll(*d, *n) {
301
36
                    scroll.x += o.x;
302
36
                    scroll.y += o.y;
303
747
                }
304
            }
305
6
            HitChainLink::Transform(d, n) => {
306
6
                if let Some(t) = resolve_transform(*d, *n) {
307
6
                    // Mirror the raster's per-push composition:
308
6
                    // composed = tf.premultiply(current)
309
6
                    let mut tf = ScreenMapAffine::from_transform_3d(&t);
310
6
                    tf.premultiply(&forward);
311
6
                    forward = tf;
312
6
                    has_transform = true;
313
6
                }
314
            }
315
        }
316
    }
317
1166
    ResolvedChain {
318
1166
        scroll,
319
1166
        forward,
320
1166
        has_transform,
321
1166
    }
322
1166
}
323

            
324
/// Map a node's STATIC rect to its ON-SCREEN axis-aligned bounds.
325
///
326
/// Walks the node's ancestors, accumulates scroll offsets and reference-frame
327
/// transforms, and applies the raster's forward rule
328
/// `screen = T_total(corner − scroll_total)` to all four corners (result is
329
/// their AABB).
330
///
331
/// This is THE shared answer to "where is this node on screen right now" —
332
/// menu positioning (`LayoutWindow::get_node_hit_test_bounds`) and the a11y
333
/// snapshot both go through it, so what a screen reader is told and where a
334
/// context menu opens can never disagree with painted pixels.
335
///
336
/// Transform membership is decided by `resolve_transform` returning `Some`
337
/// — pass the same GPU-cache lookup the raster paints from.
338
711
pub fn node_rect_to_screen(
339
711
    layout_result: &DomLayoutResult,
340
711
    dom_id: DomId,
341
711
    layout_idx: usize,
342
711
    rect: LogicalRect,
343
711
    resolve_scroll: &dyn Fn(DomId, NodeId) -> Option<LogicalPosition>,
344
711
    resolve_transform: &dyn Fn(DomId, NodeId) -> Option<azul_core::transform::ComputedTransform3D>,
345
711
) -> LogicalRect {
346
711
    let nodes = &layout_result.layout_tree.nodes;
347

            
348
    // Collect links walking child→root; reversing yields outermost-first
349
    // with, per ancestor, Transform before Scroll (the builder nests the
350
    // reference frame OUTSIDE the scroll frame).
351
    //
352
    // ANCESTORS ONLY, and now said so out loud: a scroll container's own
353
    // offset moves its CONTENT, so it must not move the container's own box.
354
    // `LayoutWindow::accumulated_scroll` answers the same question with an
355
    // explicit `Inclusivity`; the two used to differ only in a loop's
356
    // starting value.
357
711
    let mut links_rev: Vec<HitChainLink> = Vec::new();
358
4283
    for anc in layout_result
359
711
        .layout_tree
360
711
        .ancestor_chain(LayoutNodeId::new(layout_idx), Inclusivity::AncestorsOnly)
361
    {
362
4283
        let Some(anc_node) = nodes.get(anc.index()) else {
363
            break;
364
        };
365
4283
        if let Some(anid) = anc_node.dom_node_id {
366
4283
            if layout_result.scroll_ids.contains_key(&anc) {
367
370
                links_rev.push(HitChainLink::Scroll(dom_id, anid));
368
3913
            }
369
4283
            if resolve_transform(dom_id, anid).is_some() {
370
                links_rev.push(HitChainLink::Transform(dom_id, anid));
371
4283
            }
372
        }
373
    }
374
711
    if links_rev.is_empty() {
375
501
        return rect;
376
210
    }
377
210
    let chain: Vec<HitChainLink> = links_rev.into_iter().rev().collect();
378
210
    let resolved = resolve_chain(&chain, resolve_scroll, resolve_transform);
379

            
380
210
    let corners = [
381
210
        rect.origin,
382
210
        LogicalPosition {
383
210
            x: rect.origin.x + rect.size.width,
384
210
            y: rect.origin.y,
385
210
        },
386
210
        LogicalPosition {
387
210
            x: rect.origin.x,
388
210
            y: rect.origin.y + rect.size.height,
389
210
        },
390
210
        LogicalPosition {
391
210
            x: rect.origin.x + rect.size.width,
392
210
            y: rect.origin.y + rect.size.height,
393
210
        },
394
210
    ];
395
210
    let mut min_x = f32::INFINITY;
396
210
    let mut min_y = f32::INFINITY;
397
210
    let mut max_x = f32::NEG_INFINITY;
398
210
    let mut max_y = f32::NEG_INFINITY;
399
1050
    for c in corners {
400
840
        let s = resolved.map_local_to_screen(c);
401
840
        min_x = min_x.min(s.x);
402
840
        min_y = min_y.min(s.y);
403
840
        max_x = max_x.max(s.x);
404
840
        max_y = max_y.max(s.y);
405
840
    }
406
210
    if !(min_x.is_finite() && min_y.is_finite() && max_x.is_finite() && max_y.is_finite()) {
407
        return rect;
408
210
    }
409
210
    LogicalRect {
410
210
        origin: LogicalPosition { x: min_x, y: min_y },
411
210
        size: LogicalSize {
412
210
            width: (max_x - min_x).max(0.0),
413
210
            height: (max_y - min_y).max(0.0),
414
210
        },
415
210
    }
416
711
}
417

            
418
/// Intern a chain into the table, returning its index.
419
3285
fn intern_chain(
420
3285
    chains: &mut Vec<Vec<HitChainLink>>,
421
3285
    lookup: &mut std::collections::HashMap<Vec<HitChainLink>, u32>,
422
3285
    v: Vec<HitChainLink>,
423
3285
) -> u32 {
424
3285
    if let Some(&i) = lookup.get(&v) {
425
2573
        return i;
426
712
    }
427
712
    let i = u32::try_from(chains.len()).unwrap_or(u32::MAX);
428
712
    chains.push(v.clone());
429
712
    lookup.insert(v, i);
430
712
    i
431
3285
}
432

            
433
impl Default for CpuHitTester {
434
1
    fn default() -> Self {
435
1
        Self::new()
436
1
    }
437
}
438

            
439
/// Resolve each layout node's ancestor chain index into `chains`.
440
///
441
/// `chain(n) = chain(parent) (+ parent's links)` — an ancestor shifts its
442
/// CONTENT, not itself. Scroll membership comes from `scroll_ids` (the exact
443
/// set the display-list builder emitted `PushScrollFrame` for); transform
444
/// membership from the GPU value cache's `css_transform_keys` via
445
/// `has_transform` (the exact set it wrapped in `PushReferenceFrame`). A node
446
/// with both nests the reference frame OUTSIDE the scroll frame, same as the
447
/// builder.
448
1237
fn compute_node_chains(
449
1237
    layout_result: &DomLayoutResult,
450
1237
    dom_id: DomId,
451
1237
    base_chain: u32,
452
1237
    has_transform: &dyn Fn(NodeId) -> bool,
453
1237
    chains: &mut Vec<Vec<HitChainLink>>,
454
1237
    chain_lookup: &mut std::collections::HashMap<Vec<HitChainLink>, u32>,
455
1237
) -> Vec<u32> {
456
1237
    let nodes = &layout_result.layout_tree.nodes;
457
1237
    let scroll_ids = &layout_result.scroll_ids;
458
1237
    let mut chain_of: Vec<u32> = vec![u32::MAX; nodes.len()];
459
1237
    let mut path: Vec<usize> = Vec::new();
460
10512
    for start in 0..nodes.len() {
461
10512
        if chain_of[start] != u32::MAX {
462
            continue;
463
10512
        }
464
10512
        path.clear();
465
10512
        path.push(start);
466
10512
        let mut cur = nodes[start].parent;
467
10512
        while let Some(p) = cur {
468
9277
            if chain_of[p] != u32::MAX || path.len() > nodes.len() {
469
9277
                break;
470
            }
471
            path.push(p);
472
            cur = nodes[p].parent;
473
        }
474
10512
        for &idx in path.iter().rev() {
475
10512
            let c = nodes[idx].parent.map_or(base_chain, |p| {
476
9277
                let pc = if chain_of[p] == u32::MAX {
477
                    base_chain // cycle guard tripped; degrade gracefully
478
                } else {
479
9277
                    chain_of[p]
480
                };
481
9277
                let is_scroll = scroll_ids.contains_key(&LayoutNodeId::new(p));
482
9277
                let pnid = nodes[p].dom_node_id;
483
9277
                let parent_transforms = pnid.is_some_and(has_transform);
484
9277
                match (pnid, is_scroll || parent_transforms) {
485
1948
                    (Some(pnid), true) => {
486
1948
                        let mut v = chains[pc as usize].clone();
487
1948
                        if parent_transforms {
488
10
                            v.push(HitChainLink::Transform(dom_id, pnid));
489
1938
                        }
490
1948
                        if is_scroll {
491
1938
                            v.push(HitChainLink::Scroll(dom_id, pnid));
492
1938
                        }
493
1948
                        intern_chain(chains, chain_lookup, v)
494
                    }
495
7329
                    _ => pc,
496
                }
497
9277
            });
498
10512
            chain_of[idx] = c;
499
        }
500
    }
501
1237
    chain_of
502
1237
}
503

            
504
/// A resolved `VirtualView` child-DOM placement.
505
///
506
/// TWO rectangles, and they are not the same one:
507
///
508
/// * `rect` — where the child dom's 0-relative boxes LAND, i.e. `bounds.origin + content_offset`.
509
///   Scrolling moves this.
510
/// * `clips` — the VIEWPORTS the child is visible through: every enclosing `VirtualView`'s own
511
///   `bounds`, each paired with the host-side chain active where that viewport lives. Scrolling
512
///   does NOT move these.
513
///
514
/// Plus the host-side chain (scroll frames AND reference frames) active at
515
/// the innermost `VirtualView` item.
516
struct Placement {
517
    rect: LogicalRect,
518
    clips: Vec<(LogicalRect, Vec<HitChainLink>)>,
519
    chain: Vec<HitChainLink>,
520
}
521

            
522
/// Resolve where each `VirtualView` / iframe child DOM lives on screen.
523
///
524
/// Child DOMs lay out in CHILD-LOCAL coordinates (origin 0,0) but live on
525
/// screen at the host `VirtualView` item's bounds. Hit entries must be
526
/// TRANSLATED there and CLIPPED to the composite bounds — otherwise the
527
/// child's nodes claim pointer events across the whole window (live bug:
528
/// azul-maps' tile grid ate every click on the header toolbar, so the
529
/// buttons never fired; the same escape the renderer had before
530
/// `intersect_clips()`).
531
///
532
/// Placements resolve iteratively so nested `VirtualView`s accumulate their
533
/// host offsets (a child's own `VirtualView` item is in that child's local
534
/// space). They also carry the host-side chain active at the `VirtualView`
535
/// item: if the host scrolls or transforms, the child viewport (and all of
536
/// the child's content) moves on screen with it. The chain is read off the
537
/// host display list by tracking `PushScrollFrame`/`PopScrollFrame` and
538
/// `PushReferenceFrame`/`PopReferenceFrame` nesting around the
539
/// `VirtualView` item — the same nesting the renderer applies when it
540
/// composites the child. Reference-frame owners come from
541
/// `DisplayList::node_mapping` (item index → source node).
542
/// WINDOW-space origin of a nested (VirtualView-mounted) dom's 0-relative
543
/// coordinate space, by the raster's own composition rule
544
/// `screen = T_total(pos − scroll_total)`.
545
///
546
/// THE one cross-dom lift: it reads the host display lists' `VirtualView`
547
/// items via [`resolve_virtual_view_placements`] — the same records the CPU
548
/// raster composites from and the hit-tester translates by — so an IME caret
549
/// rect, a transient-window anchor and the painted pixels cannot disagree.
550
/// (`LayoutWindow::window_space_offset_of_dom` used to re-derive this from
551
/// `calculated_positions`, which knows nothing of ancestor scroll frames or
552
/// reference-frame transforms in the host.)
553
///
554
/// `None` for the root dom or a dom no display list currently mounts.
555
170
pub fn nested_dom_window_origin(
556
170
    layout_results: &BTreeMap<DomId, DomLayoutResult>,
557
170
    dom_id: DomId,
558
170
    resolve_scroll: &dyn Fn(DomId, NodeId) -> Option<LogicalPosition>,
559
170
    resolve_transform: &dyn Fn(DomId, NodeId) -> Option<azul_core::transform::ComputedTransform3D>,
560
170
) -> Option<LogicalPosition> {
561
170
    let placements = resolve_virtual_view_placements(layout_results);
562
170
    let p = placements.get(&dom_id)?;
563
110
    let resolved = resolve_chain(&p.chain, resolve_scroll, resolve_transform);
564
110
    let shifted = LogicalPosition {
565
110
        x: p.rect.origin.x - resolved.scroll.x,
566
110
        y: p.rect.origin.y - resolved.scroll.y,
567
110
    };
568
110
    Some(if resolved.has_transform {
569
        resolved.forward.apply(shifted)
570
    } else {
571
110
        shifted
572
    })
573
170
}
574

            
575
1374
fn resolve_virtual_view_placements(
576
1374
    layout_results: &BTreeMap<DomId, DomLayoutResult>,
577
1374
) -> BTreeMap<DomId, Placement> {
578
1374
    let mut placements: BTreeMap<DomId, Placement> = BTreeMap::new();
579
1613
    for _ in 0..4 {
580
        // bounded depth; each pass resolves one nesting level
581
1613
        let mut changed = false;
582
3638
        for (host_dom, lr) in layout_results {
583
2025
            let (host_offset, host_clips, host_chain) = if host_dom.inner == 0 {
584
1544
                (LogicalPosition::zero(), Vec::new(), Vec::new())
585
481
            } else if let Some(p) = placements.get(host_dom) {
586
478
                (p.rect.origin, p.clips.clone(), p.chain.clone())
587
            } else {
588
3
                continue;
589
            };
590
2022
            let base_depth = host_chain.len();
591
2022
            let mut stack = host_chain;
592
28924
            for (item_idx, item) in lr.display_list.items.iter().enumerate() {
593
                use crate::solver3::display_list::DisplayListItem as I;
594
28887
                match item {
595
452
                    I::PushScrollFrame { scroll_id, .. } => {
596
                        // `scroll_id` is the owning node's layout index by
597
                        // construction (`get_scroll_id`); the reverse map
598
                        // is authoritative, the index a safe fallback.
599
452
                        let nid = lr
600
452
                            .scroll_id_to_node_id
601
452
                            .get(scroll_id)
602
452
                            .copied()
603
452
                            .unwrap_or_else(|| {
604
                                NodeId::new(usize::try_from(*scroll_id).unwrap_or(usize::MAX))
605
                            });
606
452
                        stack.push(HitChainLink::Scroll(*host_dom, nid));
607
                    }
608
                    I::PopScrollFrame => {
609
                        // Never pop below the host's own chain.
610
452
                        if matches!(stack.last(), Some(HitChainLink::Scroll(..)))
611
452
                            && stack.len() > base_depth
612
452
                        {
613
452
                            stack.pop();
614
452
                        }
615
                    }
616
115
                    I::PushReferenceFrame { .. } => {
617
115
                        // The owner node comes from node_mapping; a frame
618
115
                        // with no source node (scrollbar thumbs) still
619
115
                        // needs a stack entry for pop symmetry — use a
620
115
                        // link that resolves to no transform.
621
115
                        let nid = lr
622
115
                            .display_list
623
115
                            .node_mapping
624
115
                            .get(item_idx)
625
115
                            .copied()
626
115
                            .flatten()
627
115
                            .unwrap_or(NodeId::ZERO);
628
115
                        stack.push(HitChainLink::Transform(*host_dom, nid));
629
115
                    }
630
                    I::PopReferenceFrame => {
631
115
                        if matches!(stack.last(), Some(HitChainLink::Transform(..)))
632
115
                            && stack.len() > base_depth
633
115
                        {
634
115
                            stack.pop();
635
115
                        }
636
                    }
637
                    I::VirtualView {
638
480
                        child_dom_id,
639
480
                        bounds,
640
480
                        content_offset,
641
                        ..
642
                    } => {
643
480
                        let b = *bounds.inner();
644
                        // THREE rects decide where a VirtualView's child lives:
645
                        // the outer `bounds`, the MATERIALIZED window inside it,
646
                        // and the virtual document. The renderer places the
647
                        // child at `bounds.origin + content_offset`, where
648
                        // content_offset is `materialized_origin -
649
                        // scroll_offset` (raster.rs subtracts exactly those two
650
                        // terms). This hit-test placement used `bounds.origin`
651
                        // alone and dropped content_offset on the floor, so
652
                        // clicks were mapped into the child as if the
653
                        // materialized window began at row 0 and nothing had
654
                        // scrolled.
655
                        //
656
                        // The caret still landed — the right text node was hit —
657
                        // just at the wrong CHARACTER, off by exactly
658
                        // `materialized_origin - scroll_offset`. That is zero on
659
                        // the first screenful and grows as you scroll, which is
660
                        // why clicking looked "heavily broken" further down a
661
                        // document and why dragging selected the wrong range.
662
480
                        let absolute = LogicalRect {
663
480
                            origin: LogicalPosition {
664
480
                                x: b.origin.x + host_offset.x + content_offset.x,
665
480
                                y: b.origin.y + host_offset.y + content_offset.y,
666
480
                            },
667
480
                            size: b.size,
668
480
                        };
669
                        // …and the VIEWPORT it shows through, which is the
670
                        // host box itself. `content_offset` moves the CONTENT
671
                        // through the viewport; it does not move the viewport.
672
                        // Clipping to `absolute` instead made the visible
673
                        // window travel with the scroll: on a document scrolled
674
                        // one page down, `content_offset.y` is a whole page
675
                        // NEGATIVE, so the clip sat a page ABOVE the canvas and
676
                        // rejected every node of the child dom. Clicks in the
677
                        // page then hit nothing at all — no caret, no
678
                        // selection, no typing — while the renderer (which
679
                        // clips to `bounds`, see cpurender/raster.rs) went on
680
                        // drawing the text the user was aiming at.
681
480
                        let viewport = LogicalRect {
682
480
                            origin: LogicalPosition {
683
480
                                x: b.origin.x + host_offset.x,
684
480
                                y: b.origin.y + host_offset.y,
685
480
                            },
686
480
                            size: b.size,
687
480
                        };
688
480
                        let mut clips = host_clips.clone();
689
480
                        clips.push((viewport, stack.clone()));
690
480
                        let differs = placements.get(child_dom_id).is_none_or(|p| {
691
240
                            p.rect != absolute || p.clips != clips || p.chain != stack
692
240
                        });
693
480
                        if differs {
694
240
                            placements.insert(
695
240
                                *child_dom_id,
696
240
                                Placement {
697
240
                                    rect: absolute,
698
240
                                    clips,
699
240
                                    chain: stack.clone(),
700
240
                                },
701
240
                            );
702
240
                            changed = true;
703
240
                        }
704
                    }
705
27273
                    _ => {}
706
                }
707
            }
708
        }
709
1613
        if !changed {
710
1374
            break;
711
239
        }
712
    }
713
1374
    placements
714
1374
}
715

            
716
impl CpuHitTester {
717
    /// Create a new empty hit tester.
718
    #[must_use]
719
279
    pub fn new() -> Self {
720
279
        Self {
721
279
            node_rects: BTreeMap::new(),
722
279
            chains: vec![Vec::new()],
723
279
            scroll_containers: Vec::new(),
724
279
            dom_placements: BTreeMap::new(),
725
279
        }
726
279
    }
727

            
728
    /// Resolve an interned chain against the current scroll offsets and
729
    /// transform values, then map a screen point into the chain's local
730
    /// (static layout) space.
731
123
    fn map_point_through_chain(
732
123
        &self,
733
123
        chain: u32,
734
123
        p: LogicalPosition,
735
123
        resolve_scroll: &dyn Fn(DomId, NodeId) -> Option<LogicalPosition>,
736
123
        resolve_transform: &dyn Fn(
737
123
            DomId,
738
123
            NodeId,
739
123
        ) -> Option<azul_core::transform::ComputedTransform3D>,
740
123
    ) -> LogicalPosition {
741
123
        self.chains.get(chain as usize).map_or(p, |elems| {
742
123
            resolve_chain(elems, resolve_scroll, resolve_transform).map_screen_to_local(p)
743
123
        })
744
123
    }
745

            
746
    /// Sum of `HitTestEntry` counts across all `DomIds` (for leak probes).
747
    #[must_use]
748
29
    pub fn node_rects_total(&self) -> usize {
749
29
        self.node_rects.values().map(Vec::len).sum()
750
29
    }
751

            
752
    /// Rebuild the hit test structure from layout results.
753
    ///
754
    /// Called after each layout pass. Extracts positioned rectangles from
755
    /// `LayoutWindow::layout_results` and builds a flat list for fast
756
    /// point-in-rect testing.
757
83
    pub fn rebuild_from_layout(&mut self, layout_results: &BTreeMap<DomId, DomLayoutResult>) {
758
83
        self.rebuild_from_layout_with_gpu(layout_results, None);
759
83
    }
760

            
761
    /// Like [`Self::rebuild_from_layout`], but transform-aware: `gpu` is the
762
    /// window's [`GpuStateManager`](crate::managers::gpu_state::GpuStateManager),
763
    /// whose per-DOM `css_transform_keys` is the EXACT set of nodes the
764
    /// display list wrapped in `PushReferenceFrame` (the display-list builder
765
    /// reads the same cache) — so hit-test chains and painted frames cannot
766
    /// disagree about which nodes transform. Pass `None` only when no
767
    /// transforms can exist (unit tests, static popups).
768
    /// The DOM node ids currently registered as USER-wheel scroll targets.
769
    /// Test/introspection helper: programmatically-scrollable-only containers
770
    /// (`overflow: hidden`) must never appear here.
771
    #[must_use]
772
10
    pub fn debug_scroll_container_nodes(&self) -> Vec<NodeId> {
773
10
        self.scroll_containers.iter().map(|e| e.node_id).collect()
774
10
    }
775

            
776
    /// Test/introspection helper: every registered entry for `node` in `dom`
777
    /// as `(rect, chain-index, clip-rects)`. A DOM node can own several
778
    /// layout nodes, hence several entries.
779
    #[must_use]
780
    pub fn debug_entries_for(
781
        &self,
782
        dom: DomId,
783
        node: NodeId,
784
    ) -> Vec<(LogicalRect, u32, Vec<LogicalRect>)> {
785
        self.node_rects
786
            .get(&dom)
787
            .into_iter()
788
            .flatten()
789
            .filter(|e| e.node_id == node)
790
            .map(|e| (e.rect, e.chain, e.clips.iter().map(|(r, _)| *r).collect()))
791
            .collect()
792
    }
793

            
794
1204
    pub fn rebuild_from_layout_with_gpu(
795
1204
        &mut self,
796
1204
        layout_results: &BTreeMap<DomId, DomLayoutResult>,
797
1204
        gpu: Option<&crate::managers::gpu_state::GpuStateManager>,
798
1204
    ) {
799
1204
        self.node_rects.clear();
800
1204
        self.chains.clear();
801
1204
        self.chains.push(Vec::new()); // chain 0 = empty
802
1204
        self.scroll_containers.clear();
803
1204
        self.dom_placements.clear();
804

            
805
1204
        let placements = resolve_virtual_view_placements(layout_results);
806

            
807
1204
        let mut chain_lookup: std::collections::HashMap<Vec<HitChainLink>, u32> =
808
1204
            std::collections::HashMap::new();
809
1204
        chain_lookup.insert(Vec::new(), 0);
810
1304
        for (dom_id, p) in &placements {
811
100
            self.dom_placements.insert(*dom_id, p.rect);
812
100
        }
813

            
814
2441
        for (dom_id, layout_result) in layout_results {
815
1237
            let mut entries = Vec::new();
816

            
817
1237
            let positions = &layout_result.calculated_positions;
818
1237
            let nodes = &layout_result.layout_tree.nodes;
819
1237
            let styled_dom = &layout_result.styled_dom;
820

            
821
            // Child DOM: shift into window space by the placement origin, and
822
            // clip to the host VIEWPORTS — a different rect, see `Placement`.
823
1237
            let (offset, dom_clip_rects, base_chain_vec) = placements.get(dom_id).map_or_else(
824
1138
                || (LogicalPosition::zero(), Vec::new(), Vec::new()),
825
99
                |p| (p.rect.origin, p.clips.clone(), p.chain.clone()),
826
            );
827
1237
            let base_chain = intern_chain(&mut self.chains, &mut chain_lookup, base_chain_vec);
828
1237
            let dom_clips: Vec<(LogicalRect, u32)> = dom_clip_rects
829
1237
                .into_iter()
830
1237
                .map(|(rect, chain)| {
831
100
                    let interned = intern_chain(&mut self.chains, &mut chain_lookup, chain);
832
100
                    (rect, interned)
833
100
                })
834
1237
                .collect();
835

            
836
1237
            let scroll_ids = &layout_result.scroll_ids;
837
1237
            let transform_nodes = gpu
838
1237
                .and_then(|g| g.caches.get(dom_id))
839
1237
                .map(|c| &c.css_transform_keys);
840
1237
            let chain_of = compute_node_chains(
841
1237
                layout_result,
842
1237
                *dom_id,
843
1237
                base_chain,
844
9257
                &|n| transform_nodes.is_some_and(|t| t.contains_key(&n)),
845
1237
                &mut self.chains,
846
1237
                &mut chain_lookup,
847
            );
848

            
849
            // Scroll containers of this DOM, for wheel-target containment.
850
            // Only USER-scrollable containers become wheel targets:
851
            // overflow:hidden boxes carry scroll ids (programmatic
852
            // scrolling - scroll-into-view, callback offsets - reaches
853
            // them), but css-overflow-3 disables their user-triggered
854
            // scrolling, so the hit-tester must not route the wheel there.
855
2029
            for (&layout_idx, &scroll_id) in scroll_ids {
856
792
                let Some(n) = nodes.get(layout_idx.index()) else {
857
                    continue;
858
                };
859
792
                let Some(node_id) = n.dom_node_id else {
860
                    continue;
861
                };
862
792
                let (Some(pos), Some(size)) = (positions.get(layout_idx.index()), n.used_size)
863
                else {
864
                    continue;
865
                };
866
792
                let user_scrollable = styled_dom
867
792
                    .styled_nodes
868
792
                    .as_container()
869
792
                    .get(node_id)
870
792
                    .is_some_and(|sn| {
871
792
                        let st = &sn.styled_node_state;
872
792
                        get_overflow_x(styled_dom, node_id, st).allows_user_scrolling()
873
501
                            || get_overflow_y(styled_dom, node_id, st).allows_user_scrolling()
874
792
                    });
875
792
                if !user_scrollable {
876
350
                    continue;
877
442
                }
878
442
                self.scroll_containers.push(ScrollContainerEntry {
879
442
                    dom_id: *dom_id,
880
442
                    node_id,
881
442
                    layout_idx,
882
442
                    scroll_id,
883
442
                    rect: LogicalRect {
884
442
                        origin: LogicalPosition {
885
442
                            x: pos.x + offset.x,
886
442
                            y: pos.y + offset.y,
887
442
                        },
888
442
                        size,
889
442
                    },
890
442
                    chain: chain_of[layout_idx.index()],
891
442
                });
892
            }
893

            
894
            // Walk the layout nodes and their computed positions
895
10512
            for (idx, node) in nodes.iter().enumerate() {
896
                // Only include nodes that map to a real DOM node
897
10512
                let Some(node_id) = node.dom_node_id else {
898
9
                    continue; // skip anonymous boxes
899
                };
900

            
901
                // Get the position for this layout node
902
10503
                let pos = match positions.get(idx) {
903
10501
                    Some(p) => *p,
904
2
                    None => continue,
905
                };
906

            
907
                // Get the computed size
908
10501
                let Some(size) = node.used_size else {
909
2120
                    continue;
910
                };
911

            
912
8381
                let rect = LogicalRect {
913
8381
                    origin: LogicalPosition {
914
8381
                        x: pos.x + offset.x,
915
8381
                        y: pos.y + offset.y,
916
8381
                    },
917
8381
                    size,
918
8381
                };
919

            
920
                // Clip this node to the VirtualView composite bounds
921
                // (`dom_clip`) and every `overflow: hidden | clip | scroll |
922
                // auto` ancestor's box — otherwise a node that is scrolled or
923
                // clipped out of its ancestor would still claim pointer events.
924
8381
                let clips = compute_node_clips(
925
8381
                    styled_dom, nodes, positions, idx, offset, &dom_clips, &chain_of,
926
                );
927

            
928
8381
                entries.push(HitTestEntry {
929
8381
                    node_id,
930
8381
                    rect,
931
8381
                    chain: chain_of[idx],
932
8381
                    clips,
933
8381
                    // azul has no `pointer-events` CSS property yet, so every laid-out
934
8381
                    // node is hit-testable. Populate this from the styled DOM once such
935
8381
                    // a property is added to `azul_css`.
936
8381
                    pointer_events_none: false,
937
8381
                    clip_path: node_clip_path(styled_dom, node_id),
938
8381
                });
939
            }
940

            
941
1237
            self.node_rects.insert(*dom_id, entries);
942
        }
943
1204
    }
944

            
945
    /// Perform a hit test at the given position, ignoring scroll offsets.
946
    ///
947
    /// Only correct for content that cannot scroll (e.g. menu popups) and for
948
    /// unit tests. Interactive windows must use [`Self::hit_test_scrolled`] —
949
    /// this wrapper tests the STATIC layout geometry, which is exactly the
950
    /// "clicks land on pre-scroll targets" bug for anything inside a scroll
951
    /// frame.
952
    #[must_use]
953
172
    pub fn hit_test(&self, position: LogicalPosition) -> Vec<(DomId, NodeId)> {
954
172
        self.hit_test_scrolled(position, &|_, _| None, &|_, _| None)
955
172
            .into_iter()
956
432
            .map(|(d, n, _)| (d, n))
957
172
            .collect()
958
172
    }
959

            
960
    /// Perform a hit test at the given position with live scroll offsets and
961
    /// transform values.
962
    ///
963
    /// `resolve_scroll` returns the CURRENT scroll offset of a scroll
964
    /// container (`ScrollManager::get_current_offset`); `resolve_transform`
965
    /// the CURRENT matrix of a reference-frame owner
966
    /// (`GpuValueCache::css_current_transform_values` — the same map the CPU
967
    /// raster reads at paint time). Content painted at
968
    /// `T_total(static_pos − scroll_total)` is hit at the same place: a
969
    /// point `p` hits a node iff `T⁻¹(p) + scroll_total` lands in the node's
970
    /// static rect. Clip boxes are shifted by the clip OWNER's chain — a
971
    /// scroller's viewport clips where the viewport IS, not where its
972
    /// content went.
973
    ///
974
    /// Returns `(dom, node, local_point)` triples in reverse paint order
975
    /// (topmost first) ACROSS DOMs as well as within one - a child DOM's hits
976
    /// precede its host's, as they do in `WebRender`'s result - where
977
    /// `local_point` is the query point mapped into
978
    /// that node's STATIC layout space — callers use it directly for
979
    /// node-relative points (caret placement, `point_relative_to_item`).
980
    #[must_use]
981
404
    pub fn hit_test_scrolled(
982
404
        &self,
983
404
        position: LogicalPosition,
984
404
        resolve_scroll: &dyn Fn(DomId, NodeId) -> Option<LogicalPosition>,
985
404
        resolve_transform: &dyn Fn(
986
404
            DomId,
987
404
            NodeId,
988
404
        ) -> Option<azul_core::transform::ComputedTransform3D>,
989
404
    ) -> Vec<(DomId, NodeId, LogicalPosition)> {
990
404
        let mut results = Vec::new();
991

            
992
        // Resolve every chain once per query, then map the point through it.
993
404
        let mapped: Vec<LogicalPosition> = self
994
404
            .chains
995
404
            .iter()
996
723
            .map(|chain| {
997
723
                resolve_chain(chain, resolve_scroll, resolve_transform)
998
723
                    .map_screen_to_local(position)
999
723
            })
404
            .collect();
4530
        let local = |chain: u32| -> LogicalPosition {
4481
            mapped.get(chain as usize).copied().unwrap_or(position)
4481
        };
        // DOMs FRONT-MOST FIRST (9g-ii-e-i): a child DOM (a `VirtualView` page,
        // an iframe) always has a higher `DomId` than its host and is
        // composited ON TOP of it, so the hits of the highest DOM are the
        // nearest to the user. Visiting the map in ascending order gave the
        // HOST's nodes the lower depth numbers, while WebRender - one scene
        // for every DOM, walked in reverse paint order - numbers the page's
        // nodes first. The two producers disagreed exactly where a page sat
        // over its host, which is the only place the order matters.
494
        for (dom_id, entries) in self.node_rects.iter().rev() {
            // Walk in reverse (last painted = topmost)
3793
            for entry in entries.iter().rev() {
3779
                if entry.pointer_events_none {
                    continue;
3779
                }
                // Every clip box must contain the point (each in its owner's
                // space).
3779
                if !entry
3779
                    .clips
3779
                    .iter()
3779
                    .all(|(clip, chain)| point_in_rect(local(*chain), clip))
                {
831
                    continue;
2948
                }
                // Check node rect in the node's local (static) space.
2948
                let p_local = local(entry.chain);
2948
                if point_in_rect(p_local, &entry.rect)
1246
                    && point_in_clip_path(p_local, &entry.rect, entry.clip_path.as_ref())
1226
                {
1226
                    results.push((*dom_id, entry.node_id, p_local));
1746
                }
            }
        }
404
        results
404
    }
}
/// A node's clip path: its own SVG geometry, with the `viewBox` it is drawn
/// in.
///
/// `None` for the overwhelming majority of nodes, which is why this is looked
/// up once at build time rather than per hit test.
8381
fn node_clip_path(styled_dom: &StyledDom, node_id: NodeId) -> Option<HitClipGeometry> {
8381
    let node_data = styled_dom.node_data.as_container();
8381
    let azul_core::dom::SvgNodeData::Path(path) = node_data.get(node_id)?.get_svg_data()? else {
10
        return None;
    };
    // The coordinate system the geometry was authored in - the same walk the
    // display list does to place the clip mask, so pixels and pointer targets
    // cannot disagree.
10
    let hierarchy = styled_dom.node_hierarchy.as_container();
10
    let mut cursor = Some(node_id);
10
    let mut view_box = None;
20
    while let Some(id) = cursor {
        if let Some(azul_core::dom::SvgNodeData::ViewBox {
10
            min_x,
10
            min_y,
10
            width,
10
            height,
20
        }) = node_data
20
            .get(id)
20
            .and_then(azul_core::dom::NodeData::get_svg_data)
        {
10
            view_box = Some((*min_x, *min_y, *width, *height));
10
            break;
10
        }
10
        cursor = hierarchy
10
            .get(id)
10
            .and_then(azul_core::styled_dom::NodeHierarchyItem::parent_id);
    }
10
    Some((path.clone(), view_box))
8381
}
/// Is the point inside the node's clip path, if it has one?
///
/// `true` when there is no clip path: a node without one is bounded by its box
/// and the caller has already checked that.
1246
fn point_in_clip_path(
1246
    point: LogicalPosition,
1246
    rect: &LogicalRect,
1246
    clip_path: Option<&HitClipGeometry>,
1246
) -> bool {
1246
    let Some((path, view_box)) = clip_path else {
1216
        return true;
    };
    // Window space -> the path's own user space. With a viewBox the geometry
    // was scaled into the box; without one it is already in logical px
    // relative to the box's origin.
30
    let (local_x, local_y) = match view_box {
30
        Some((min_x, min_y, vb_w, vb_h))
30
            if *vb_w > 0.0 && *vb_h > 0.0 && rect.size.width > 0.0 && rect.size.height > 0.0 =>
        {
30
            (
30
                (point.x - rect.origin.x) * vb_w / rect.size.width + min_x,
30
                (point.y - rect.origin.y) * vb_h / rect.size.height + min_y,
30
            )
        }
        _ => (point.x, point.y),
    };
30
    path.contains_point(local_x, local_y)
1246
}
/// Simple point-in-rect test.
5079
fn point_in_rect(point: LogicalPosition, rect: &LogicalRect) -> bool {
5079
    point.x >= rect.origin.x
4439
        && point.x < rect.origin.x + rect.size.width
2509
        && point.y >= rect.origin.y
2213
        && point.y < rect.origin.y + rect.size.height
5079
}
/// Convert CPU hit test results to `FullHitTest` format.
///
/// Maps `(DomId, NodeId)` pairs from [`CpuHitTester::hit_test`] into the same
/// `FullHitTest` structure that `WebRender`'s `fullhittest_new_webrender`
/// produces, so the event dispatch code works identically for both backends.
///
/// This lives HERE (next to the tester that produces its input) rather than in
/// the DLL, because two hosts consume it: the desktop shells
/// (`wr_translate2::convert_cpu_hit_test_to_full`, which now delegates) and the
/// headless E2E runner (`crate::e2e::runner`). Two copies of "which node did
/// the pointer land on" is exactly the divergence that makes a scenario pass in
/// one host and fail in the other.
#[allow(clippy::cast_possible_truncation)] // bounded: DomId/NodeId indices, hit depth
#[allow(clippy::too_many_lines)] // moved verbatim from the DLL; one pass per hit-test kind
#[must_use]
234
pub fn convert_cpu_hit_test_to_full(
234
    tester: &CpuHitTester,
234
    hits: &[(DomId, NodeId, LogicalPosition)],
234
    old_focus_node: Option<DomNodeId>,
234
    layout_results: &BTreeMap<DomId, DomLayoutResult>,
234
    cursor_position: LogicalPosition,
234
    resolve_scroll: &dyn Fn(DomId, NodeId) -> Option<LogicalPosition>,
234
    resolve_transform: &dyn Fn(DomId, NodeId) -> Option<azul_core::transform::ComputedTransform3D>,
234
) -> FullHitTest {
    use azul_core::{
        dom::OptionDomNodeId,
        hit_test::{HitTest, HitTestItem, OverflowingScrollNode, ScrollHitTestItem},
    };
234
    let focused_node = old_focus_node.map_or(OptionDomNodeId::None, OptionDomNodeId::Some);
234
    let mut hovered_nodes: BTreeMap<DomId, HitTest> = BTreeMap::new();
882
    for (depth, (dom_id, node_id, local_point)) in hits.iter().enumerate() {
        // `local_point` is the cursor already mapped into this node's STATIC
        // layout space (ancestor scroll offsets added back, ancestor
        // transforms inverted) — the same space the entry rects live in,
        // which is the node's static position translated by its VirtualView
        // placement. Two named steps take it to the ONE documented space
        // `HitTestItem::point_relative_to_item` carries: subtract the node's
        // static border-box origin (plus placement), then step in by the
        // content inset. `fullhittest_new_webrender` performs the identical
        // second step on WebRender's border-box-relative point, so the two
        // hosts now answer the same question the same way.
882
        let placement = tester
882
            .dom_placements
882
            .get(dom_id)
882
            .map_or_else(LogicalPosition::zero, |r| r.origin);
882
        let point_relative = layout_results
882
            .get(dom_id)
882
            .and_then(|lr| {
882
                lr.layout_tree
882
                    .dom_to_layout
882
                    .get(node_id)
882
                    .and_then(|indices| indices.first())
882
                    .and_then(|&idx| {
880
                        let node_pos = lr.calculated_positions.get(idx.index())?;
880
                        let border_box_origin = LogicalPosition::new(
880
                            node_pos.x + placement.x,
880
                            node_pos.y + placement.y,
                        );
880
                        Some(
880
                            StaticLayoutPoint::new(*local_point)
880
                                .to_border_box_local(border_box_origin)
880
                                .to_content_box_local(lr.layout_tree.content_inset(idx)),
880
                        )
880
                    })
882
            })
882
            .unwrap_or_else(ContentBoxLocal::zero);
882
        let hit_test = hovered_nodes.entry(*dom_id).or_insert_with(|| HitTest {
276
            regular_hit_test_nodes: BTreeMap::new(),
276
            scroll_hit_test_nodes: BTreeMap::new(),
276
            scrollbar_hit_test_nodes: BTreeMap::new(),
276
            cursor_hit_test_nodes: BTreeMap::new(),
276
        });
882
        hit_test.regular_hit_test_nodes.insert(
882
            *node_id,
882
            HitTestItem {
882
                point_in_viewport: cursor_position,
882
                point_relative_to_item: point_relative,
882
                is_focusable: false,
882
                is_virtual_view_hit: None,
882
                hit_depth: depth as u32,
882
            },
        );
    }
    // Scroll containers: the CPU hit tester reports only regular DOM nodes,
    // so mirror the WR converter's TAG_TYPE_SCROLL_CONTAINER pass by rect
    // containment. Without this, scroll_hit_test_nodes stays empty on the
    // CPU-render path and wheel/trackpad scrolling never finds a target
    // (a11y scrolling still worked - it targets nodes directly - which is
    // how this stayed unnoticed).
    //
    // Containment tests the container's ON-SCREEN viewport box: the static
    // box from the hit tester (already placement-translated for VirtualView
    // child DOMs), shifted by the container's OWN ancestors' current scroll
    // offsets — a scroller nested in a scrolled frame moves with that frame,
    // while its own scrolling never moves its viewport. `parent_rect` /
    // `child_rect` stay in static layout coordinates: downstream only uses
    // their relative geometry (scroll ranges), which translation cannot
    // change.
357
    for sc in &tester.scroll_containers {
123
        let dom_id = &sc.dom_id;
123
        let node_id = sc.node_id;
123
        let scroll_id = sc.scroll_id;
123
        let Some(lr) = layout_results.get(dom_id) else {
            continue;
        };
123
        let layout_idx = sc.layout_idx;
123
        let p_local = tester.map_point_through_chain(
123
            sc.chain,
123
            cursor_position,
123
            resolve_scroll,
123
            resolve_transform,
        );
123
        let adj_x = p_local.x;
123
        let adj_y = p_local.y;
        {
123
            let node_pos = sc.rect.origin;
123
            let node_size = sc.rect.size;
123
            let inside = adj_x >= node_pos.x
123
                && adj_x <= node_pos.x + node_size.width
123
                && adj_y >= node_pos.y
123
                && adj_y <= node_pos.y + node_size.height;
123
            if !inside {
                continue;
123
            }
123
            let parent_rect = LogicalRect::new(node_pos, node_size);
123
            let child_rect = compute_scroll_child_rect(lr, layout_idx.index(), parent_rect);
123
            let scroll_node = OverflowingScrollNode {
123
                parent_rect,
123
                child_rect,
123
                virtual_child_rect: child_rect,
123
                // CPU path has no WebRender document; the pipeline half of the
123
                // external id is only used for WR scroll-layer sync.
123
                parent_external_scroll_id: azul_core::hit_test::ExternalScrollId(
123
                    scroll_id,
123
                    azul_core::hit_test::PipelineId(dom_id.inner as u32, 0),
123
                ),
123
                parent_dom_hash: azul_core::dom::DomNodeHash {
123
                    inner: node_id.index() as u64,
123
                },
123
                scroll_tag_id: azul_core::dom::ScrollTagId {
123
                    inner: azul_core::dom::TagId {
123
                        inner: node_id.index() as u64,
123
                    },
123
                },
123
            };
123
            hovered_nodes
123
                .entry(*dom_id)
123
                .or_insert_with(HitTest::empty)
123
                .scroll_hit_test_nodes
123
                .insert(
123
                    node_id,
123
                    ScrollHitTestItem {
123
                        point_in_viewport: cursor_position,
123
                        // Relative to the container's ON-SCREEN viewport box
123
                        // (static box shifted by the container's ancestors) —
123
                        // BORDER-box-local, unlike the regular hit item above:
123
                        // scroll geometry is measured against the border box.
123
                        point_relative_to_item: StaticLayoutPoint::new(LogicalPosition::new(
123
                            adj_x, adj_y,
123
                        ))
123
                        .to_border_box_local(node_pos),
123
                        scroll_node,
123
                    },
                );
        }
    }
234
    FullHitTest {
234
        hovered_nodes,
234
        focused_node,
234
    }
234
}
/// Compute the `child_rect` (scrollable content bounds) of an overflowing scroll
/// node from the layout tree.
///
/// The content rect is anchored at the node's own border-box origin and sized to
/// the node's overflow content size (`LayoutTree::get_content_size`, which honors
/// `overflow_content_size` / inline text overflow). It is clamped to be at least
/// as large as the viewport (`parent_rect`), so a node whose content does *not*
/// overflow yields `child_rect == parent_rect` and the `ScrollState` clamping
/// produces a zero scroll range (the prior, always-no-scroll behavior).
#[must_use]
123
pub fn compute_scroll_child_rect(
123
    layout_result: &DomLayoutResult,
123
    layout_idx: usize,
123
    parent_rect: LogicalRect,
123
) -> LogicalRect {
123
    let content_size = layout_result
123
        .layout_tree
123
        .get_content_size(LayoutNodeId::new(layout_idx));
123
    LogicalRect::new(
123
        parent_rect.origin,
123
        LogicalSize::new(
123
            content_size.width.max(parent_rect.size.width),
123
            content_size.height.max(parent_rect.size.height),
        ),
    )
123
}
/// Compute the hit-test clip boxes for a layout node: the enclosing
/// `VirtualView` VIEWPORTS (`dom_clips`, outermost host first) plus every
/// clipping ancestor's border box (any `overflow` other than `visible`), each
/// tagged with the chain of the clip OWNER's strict scroll ancestors so the
/// query can shift each box into its own scrolled space.
///
/// Clipping is tracked per-axis because `overflow-x` / `overflow-y` are
/// independent — an axis the ancestor does not clip is widened to
/// [`CLIP_UNBOUNDED`] (kept finite so `origin + size` arithmetic never
/// produces `inf - inf = NaN`). The ancestor box used is the border box
/// (`used_size`); CSS clips at the padding edge, but the slightly larger
/// border box is a safe over-inclusion for point hit-testing and avoids
/// resolving padding/border here.
#[allow(clippy::similar_names)] // domain-standard coordinate/geometry/short-lived names
8416
fn compute_node_clips(
8416
    styled_dom: &StyledDom,
8416
    nodes: &[LayoutNodeHot],
8416
    positions: &PositionVec,
8416
    node_index: usize,
8416
    offset: LogicalPosition,
8416
    dom_clips: &[(LogicalRect, u32)],
8416
    chain_of: &[u32],
8416
) -> Vec<(LogicalRect, u32)> {
    // A non-finite edge must degrade to "unclipped on that side", never be
    // stored: `point_in_rect` against a NaN rect is always false, which would
    // make every node under a corrupt clip silently unhittable.
3227
    fn sanitize_clip_rect(r: LogicalRect) -> LogicalRect {
3227
        let min_x = if r.min_x().is_finite() {
3218
            r.min_x()
        } else {
9
            -CLIP_UNBOUNDED
        };
3227
        let min_y = if r.min_y().is_finite() {
3218
            r.min_y()
        } else {
9
            -CLIP_UNBOUNDED
        };
3227
        let max_x = if r.max_x().is_finite() {
3213
            r.max_x()
        } else {
14
            CLIP_UNBOUNDED
        };
3227
        let max_y = if r.max_y().is_finite() {
3213
            r.max_y()
        } else {
14
            CLIP_UNBOUNDED
        };
3227
        LogicalRect {
3227
            origin: LogicalPosition { x: min_x, y: min_y },
3227
            size: LogicalSize {
3227
                width: (max_x - min_x).max(0.0),
3227
                height: (max_y - min_y).max(0.0),
3227
            },
3227
        }
3227
    }
8416
    let mut clips = Vec::new();
8869
    for (dc, chain) in dom_clips {
453
        clips.push((sanitize_clip_rect(*dc), *chain));
453
    }
    // Walk ancestors. A node's own overflow clips its descendants, not itself, so
    // we start at the parent. `guard` bounds the loop in case `parent` links ever
    // form a cycle (they shouldn't, but a hit-test rebuild must never hang).
8416
    let styled_nodes = styled_dom.styled_nodes.as_container();
8416
    let mut cur = nodes.get(node_index).and_then(|n| n.parent);
8416
    let mut guard = 0usize;
31507
    while let Some(anc) = cur {
23095
        guard += 1;
23095
        if guard > nodes.len() {
3
            break;
23092
        }
23092
        let Some(anc_node) = nodes.get(anc) else {
1
            break;
        };
23091
        cur = anc_node.parent;
23091
        let Some(anc_dom_id) = anc_node.dom_node_id else {
5
            continue;
        };
23086
        let node_state = &styled_nodes[anc_dom_id].styled_node_state;
23086
        let clips_x = get_overflow_x(styled_dom, anc_dom_id, node_state).is_clipped();
23086
        let clips_y = get_overflow_y(styled_dom, anc_dom_id, node_state).is_clipped();
23086
        if !clips_x && !clips_y {
20311
            continue;
2775
        }
2775
        let (Some(pos), Some(size)) = (positions.get(anc), anc_node.used_size) else {
1
            continue;
        };
2774
        let (ax0, ay0) = (pos.x + offset.x, pos.y + offset.y);
2774
        let (min_x, max_x) = if clips_x {
1680
            (ax0, ax0 + size.width)
        } else {
1094
            (-CLIP_UNBOUNDED, CLIP_UNBOUNDED)
        };
2774
        let (min_y, max_y) = if clips_y {
2773
            (ay0, ay0 + size.height)
        } else {
1
            (-CLIP_UNBOUNDED, CLIP_UNBOUNDED)
        };
2774
        clips.push((
2774
            sanitize_clip_rect(LogicalRect {
2774
                origin: LogicalPosition { x: min_x, y: min_y },
2774
                size: LogicalSize {
2774
                    width: (max_x - min_x).max(0.0),
2774
                    height: (max_y - min_y).max(0.0),
2774
                },
2774
            }),
2774
            chain_of.get(anc).copied().unwrap_or(0),
2774
        ));
    }
8416
    clips
8416
}
/// Test-compat shim for the pre-scroll-aware single-rect clip API: the static
/// intersection of every clip box from [`compute_node_clips`] — exactly what
/// the query evaluates when nothing is scrolled. Kept so the generated clip
/// tests keep asserting the per-axis clip semantics they were written for.
#[cfg(test)]
35
fn compute_node_clip(
35
    styled_dom: &StyledDom,
35
    nodes: &[LayoutNodeHot],
35
    positions: &PositionVec,
35
    node_index: usize,
35
    offset: LogicalPosition,
35
    dom_clip: Option<LogicalRect>,
35
) -> Option<LogicalRect> {
35
    let chain_of = vec![0u32; nodes.len()];
35
    let clips = compute_node_clips(
35
        styled_dom,
35
        nodes,
35
        positions,
35
        node_index,
35
        offset,
35
        &dom_clip.map(|r| (r, 0)).into_iter().collect::<Vec<_>>(),
35
        &chain_of,
    );
35
    if clips.is_empty() {
9
        return None;
26
    }
26
    let (mut min_x, mut min_y, mut max_x, mut max_y) = (
26
        -CLIP_UNBOUNDED,
26
        -CLIP_UNBOUNDED,
26
        CLIP_UNBOUNDED,
26
        CLIP_UNBOUNDED,
26
    );
53
    for (r, _) in &clips {
27
        min_x = min_x.max(r.min_x());
27
        min_y = min_y.max(r.min_y());
27
        max_x = max_x.min(r.max_x());
27
        max_y = max_y.min(r.max_y());
27
    }
26
    Some(LogicalRect {
26
        origin: LogicalPosition { x: min_x, y: min_y },
26
        size: LogicalSize {
26
            width: (max_x - min_x).max(0.0),
26
            height: (max_y - min_y).max(0.0),
26
        },
26
    })
35
}
#[cfg(test)]
mod tests {
    use super::*;
    #[test]
1
    fn test_cpu_hit_tester_empty() {
1
        let tester = CpuHitTester::new();
1
        let results = tester.hit_test(LogicalPosition { x: 100.0, y: 100.0 });
1
        assert!(results.is_empty());
1
    }
    #[test]
1
    fn test_point_in_rect() {
1
        let rect = LogicalRect {
1
            origin: LogicalPosition { x: 10.0, y: 10.0 },
1
            size: LogicalSize {
1
                width: 100.0,
1
                height: 50.0,
1
            },
1
        };
        // Inside
1
        assert!(point_in_rect(LogicalPosition { x: 50.0, y: 30.0 }, &rect));
        // On edge
1
        assert!(point_in_rect(LogicalPosition { x: 10.0, y: 10.0 }, &rect));
        // Outside
1
        assert!(!point_in_rect(LogicalPosition { x: 5.0, y: 5.0 }, &rect));
1
        assert!(!point_in_rect(LogicalPosition { x: 200.0, y: 30.0 }, &rect));
1
    }
}
#[cfg(test)]
#[allow(clippy::float_cmp)] // clip/hit geometry must round-trip bit-exactly, not "approximately"
mod autotest_generated {
    use std::collections::HashMap;
    use azul_core::dom::{Dom, FormattingContext};
    use super::*;
    use crate::{
        solver3::{
            display_list::{DisplayList, DisplayListItem, WindowLogicalRect},
            layout_tree::LayoutTree,
        },
        window::DomLayoutResult,
    };
    // -----------------------------------------------------------------------
    // fixtures
    // -----------------------------------------------------------------------
    fn p(x: f32, y: f32) -> LogicalPosition {
        LogicalPosition { x, y }
    }
    fn r(x: f32, y: f32, width: f32, height: f32) -> LogicalRect {
        LogicalRect {
            origin: p(x, y),
            size: LogicalSize { width, height },
        }
    }
    fn dom(inner: usize) -> DomId {
        DomId { inner }
    }
    /// A layout node: `dom_node_id` as a raw index (`None` = anonymous box),
    /// `size` as (w, h) (`None` = never laid out), `parent` as a node index.
    fn hot(
        dom_node_id: Option<usize>,
        size: Option<(f32, f32)>,
        parent: Option<usize>,
    ) -> LayoutNodeHot {
        LayoutNodeHot {
            box_props: Default::default(),
            dom_node_id: dom_node_id.map(NodeId::new),
            used_size: size.map(|(width, height)| LogicalSize { width, height }),
            formatting_context: FormattingContext::default(),
            parent,
        }
    }
    /// `body > div.clip > div` (`NodeId` 0, 1, 2), styled by `css_src`.
    fn styled(css_src: &str) -> StyledDom {
        let css = azul_css::parser2::new_from_str(css_src).0;
        let mut d = Dom::create_body().with_children(
            vec![Dom::create_div()
                .with_class("clip".to_string().into())
                .with_children(vec![Dom::create_div()].into())]
            .into(),
        );
        StyledDom::create(&mut d, css)
    }
    fn layout_result(
        styled_dom: StyledDom,
        nodes: Vec<LayoutNodeHot>,
        calculated_positions: PositionVec,
        items: Vec<DisplayListItem>,
    ) -> DomLayoutResult {
        DomLayoutResult {
            styled_dom,
            layout_tree: LayoutTree {
                nodes,
                warm: Vec::new(),
                cold: Vec::new(),
                root: 0,
                dom_to_layout: BTreeMap::new(),
                children_arena: Vec::new(),
                children_offsets: Vec::new(),
                subtree_needs_intrinsic: Vec::new(),
            },
            calculated_positions,
            viewport: LogicalRect::zero(),
            display_list: std::sync::Arc::new(DisplayList {
                items,
                ..Default::default()
            }),
            scroll_ids: HashMap::new(),
            scroll_id_to_node_id: HashMap::new(),
        }
    }
    fn virtual_view(child: usize, bounds: LogicalRect) -> DisplayListItem {
        DisplayListItem::VirtualView {
            child_dom_id: dom(child),
            bounds: WindowLogicalRect::new(bounds.origin, bounds.size),
            clip_rect: WindowLogicalRect::new(bounds.origin, bounds.size),
            content_offset: Default::default(),
        }
    }
    /// A `VirtualView` whose materialized window is offset from the viewport —
    /// what a scrolled virtual document produces
    /// (`materialized_origin - scroll_offset`).
    fn virtual_view_scrolled(
        child: usize,
        bounds: LogicalRect,
        content_offset: LogicalPosition,
    ) -> DisplayListItem {
        DisplayListItem::VirtualView {
            child_dom_id: dom(child),
            bounds: WindowLogicalRect::new(bounds.origin, bounds.size),
            clip_rect: WindowLogicalRect::new(bounds.origin, bounds.size),
            content_offset,
        }
    }
    /// Every f32 that can plausibly reach a hit test from a broken input event.
    const HOSTILE_F32: [f32; 8] = [
        0.0,
        -0.0,
        f32::NAN,
        f32::INFINITY,
        f32::NEG_INFINITY,
        f32::MAX,
        f32::MIN,
        f32::MIN_POSITIVE,
    ];
    // -----------------------------------------------------------------------
    // point_in_rect  (numeric)
    // -----------------------------------------------------------------------
    #[test]
    fn point_in_rect_is_half_open_top_left_inclusive_bottom_right_exclusive() {
        let rect = r(10.0, 10.0, 100.0, 50.0);
        assert!(point_in_rect(p(10.0, 10.0), &rect), "top-left is inclusive");
        assert!(point_in_rect(p(109.999, 59.999), &rect));
        assert!(
            !point_in_rect(p(110.0, 30.0), &rect),
            "right edge is exclusive"
        );
        assert!(
            !point_in_rect(p(50.0, 60.0), &rect),
            "bottom edge is exclusive"
        );
        assert!(!point_in_rect(p(110.0, 60.0), &rect));
    }
    #[test]
    fn point_in_rect_zero_sized_rect_contains_nothing_not_even_its_origin() {
        let rect = r(0.0, 0.0, 0.0, 0.0);
        assert!(!point_in_rect(p(0.0, 0.0), &rect));
        assert!(!point_in_rect(p(-0.0, -0.0), &rect));
        let elsewhere = r(7.0, 9.0, 0.0, 0.0);
        assert!(!point_in_rect(p(7.0, 9.0), &elsewhere));
    }
    #[test]
    fn point_in_rect_negative_size_rect_is_empty() {
        // A rect whose size is negative has max < min on both axes: nothing is
        // "inside" it, and in particular the test must not silently swap the
        // edges and report a hit.
        let rect = r(100.0, 100.0, -50.0, -50.0);
        for x in [50.0_f32, 75.0, 99.0, 100.0, 125.0] {
            for y in [50.0_f32, 75.0, 99.0, 100.0, 125.0] {
                assert!(!point_in_rect(p(x, y), &rect), "({x}, {y}) must not hit");
            }
        }
    }
    #[test]
    fn point_in_rect_negative_zero_origin_still_contains_zero() {
        // -0.0 >= 0.0 and 0.0 >= -0.0 both hold: signed zero must not flip a hit.
        let rect = r(-0.0, -0.0, 10.0, 10.0);
        assert!(point_in_rect(p(0.0, 0.0), &rect));
        assert!(point_in_rect(p(-0.0, -0.0), &rect));
        let zero_origin = r(0.0, 0.0, 10.0, 10.0);
        assert!(point_in_rect(p(-0.0, -0.0), &zero_origin));
    }
    #[test]
    fn point_in_rect_nan_point_never_hits() {
        let rect = r(-1000.0, -1000.0, 5000.0, 5000.0);
        assert!(!point_in_rect(p(f32::NAN, 0.0), &rect));
        assert!(!point_in_rect(p(0.0, f32::NAN), &rect));
        assert!(!point_in_rect(p(f32::NAN, f32::NAN), &rect));
    }
    #[test]
    fn point_in_rect_nan_rect_never_hits() {
        for bad in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY] {
            let nan_origin = r(bad, 0.0, 10.0, 10.0);
            let nan_size = r(0.0, 0.0, bad, 10.0);
            // NaN origin/size makes every comparison false except the trivially
            // true ones; the only thing that matters is that it doesn't panic and
            // that a NaN box can't claim an arbitrary point.
            let _ = point_in_rect(p(5.0, 5.0), &nan_origin);
            let _ = point_in_rect(p(5.0, 5.0), &nan_size);
        }
        assert!(!point_in_rect(p(5.0, 5.0), &r(f32::NAN, 0.0, 10.0, 10.0)));
        assert!(!point_in_rect(p(5.0, 5.0), &r(0.0, 0.0, f32::NAN, 10.0)));
    }
    #[test]
    fn point_in_rect_infinite_extent_is_empty_which_is_why_clip_unbounded_exists() {
        // origin = -inf, size = +inf  =>  origin + size = NaN  =>  `x < NaN` is
        // false  =>  nothing is inside. This is exactly the trap CLIP_UNBOUNDED
        // documents; the assertion pins the failure mode so nobody "optimizes"
        // CLIP_UNBOUNDED back into f32::INFINITY.
        let infinite = LogicalRect {
            origin: p(f32::NEG_INFINITY, f32::NEG_INFINITY),
            size: LogicalSize {
                width: f32::INFINITY,
                height: f32::INFINITY,
            },
        };
        assert!(!point_in_rect(p(0.0, 0.0), &infinite));
        assert!(!point_in_rect(p(-1.0e6, 1.0e6), &infinite));
    }
    #[test]
    fn point_in_rect_clip_unbounded_extent_contains_every_realistic_coordinate() {
        // The finite stand-in that compute_node_clip uses must behave like
        // "unbounded" for any coordinate a real window can produce.
        let unbounded = r(
            -CLIP_UNBOUNDED,
            -CLIP_UNBOUNDED,
            2.0 * CLIP_UNBOUNDED,
            2.0 * CLIP_UNBOUNDED,
        );
        for c in [0.0_f32, -0.0, 1.0, -1.0, 99_999.0, -99_999.0, 1.0e6, -1.0e6] {
            assert!(point_in_rect(p(c, c), &unbounded), "{c} must be inside");
        }
        // ...but it is finite, so it does NOT swallow f32::MAX.
        assert!(!point_in_rect(p(f32::MAX, 0.0), &unbounded));
    }
    #[test]
    fn point_in_rect_saturates_at_f32_max_without_panicking() {
        // origin + size overflows to +inf here; `x < inf` is true, so the point
        // is reported inside. No debug-panic, no wraparound.
        let huge = r(f32::MAX, f32::MAX, f32::MAX, f32::MAX);
        assert!(point_in_rect(p(f32::MAX, f32::MAX), &huge));
        assert!(!point_in_rect(p(0.0, 0.0), &huge));
        let from_zero = r(0.0, 0.0, f32::MAX, f32::MAX);
        assert!(point_in_rect(p(0.0, 0.0), &from_zero));
        assert!(
            !point_in_rect(p(f32::MAX, f32::MAX), &from_zero),
            "the far edge stays exclusive even at f32::MAX"
        );
    }
    #[test]
    fn point_in_rect_never_panics_for_any_hostile_f32_combination() {
        for &x in &HOSTILE_F32 {
            for &y in &HOSTILE_F32 {
                for &w in &HOSTILE_F32 {
                    let rect = r(x, y, w, w);
                    let _ = point_in_rect(p(y, x), &rect);
                }
            }
        }
    }
    // -----------------------------------------------------------------------
    // CpuHitTester::new / node_rects_total  (constructor + getter)
    // -----------------------------------------------------------------------
    #[test]
    fn new_hit_tester_is_empty_and_matches_default() {
        let tester = CpuHitTester::new();
        assert_eq!(tester.node_rects_total(), 0);
        assert!(tester.hit_test(p(0.0, 0.0)).is_empty());
        let defaulted = CpuHitTester::default();
        assert_eq!(defaulted.node_rects_total(), tester.node_rects_total());
    }
    #[test]
    fn node_rects_total_sums_entries_across_doms_and_skips_unlaid_nodes() {
        let mut results = BTreeMap::new();
        // dom 0: 2 hit-testable nodes + 1 anonymous + 1 without a used_size
        results.insert(
            dom(0),
            layout_result(
                styled(""),
                vec![
                    hot(Some(0), Some((10.0, 10.0)), None),
                    hot(Some(1), Some((10.0, 10.0)), None),
                    hot(None, Some((10.0, 10.0)), None), // anonymous box
                    hot(Some(2), None, None),            // never laid out
                ],
                vec![p(0.0, 0.0), p(0.0, 0.0), p(0.0, 0.0), p(0.0, 0.0)],
                Vec::new(),
            ),
        );
        // dom 1: 1 hit-testable node
        results.insert(
            dom(1),
            layout_result(
                styled(""),
                vec![hot(Some(0), Some((10.0, 10.0)), None)],
                vec![p(0.0, 0.0)],
                Vec::new(),
            ),
        );
        let mut tester = CpuHitTester::new();
        tester.rebuild_from_layout(&results);
        assert_eq!(tester.node_rects_total(), 3);
    }
    #[test]
    fn node_rects_total_does_not_grow_when_the_same_layout_is_rebuilt() {
        // Leak probe: rebuild_from_layout must clear, not append.
        let mut results = BTreeMap::new();
        results.insert(
            dom(0),
            layout_result(
                styled(""),
                vec![hot(Some(0), Some((10.0, 10.0)), None)],
                vec![p(0.0, 0.0)],
                Vec::new(),
            ),
        );
        let mut tester = CpuHitTester::new();
        for _ in 0..16 {
            tester.rebuild_from_layout(&results);
            assert_eq!(tester.node_rects_total(), 1);
        }
        tester.rebuild_from_layout(&BTreeMap::new());
        assert_eq!(tester.node_rects_total(), 0);
        assert!(tester.hit_test(p(1.0, 1.0)).is_empty());
    }
    // -----------------------------------------------------------------------
    // CpuHitTester::hit_test  (numeric)
    // -----------------------------------------------------------------------
    #[test]
    fn hit_test_on_empty_tester_never_panics_for_hostile_positions() {
        let tester = CpuHitTester::new();
        for &x in &HOSTILE_F32 {
            for &y in &HOSTILE_F32 {
                assert!(tester.hit_test(p(x, y)).is_empty());
            }
        }
    }
    #[test]
    fn hit_test_with_hostile_positions_against_a_real_node_returns_no_spurious_hits() {
        let mut results = BTreeMap::new();
        results.insert(
            dom(0),
            layout_result(
                styled(""),
                vec![hot(Some(0), Some((100.0, 100.0)), None)],
                vec![p(0.0, 0.0)],
                Vec::new(),
            ),
        );
        let mut tester = CpuHitTester::new();
        tester.rebuild_from_layout(&results);
        // Sanity: the node IS hittable at a normal coordinate.
        assert_eq!(tester.hit_test(p(50.0, 50.0)).len(), 1);
        for pos in [
            p(f32::NAN, f32::NAN),
            p(f32::NAN, 50.0),
            p(50.0, f32::NAN),
            p(f32::INFINITY, f32::INFINITY),
            p(f32::NEG_INFINITY, f32::NEG_INFINITY),
            p(f32::MAX, f32::MAX),
            p(f32::MIN, f32::MIN),
        ] {
            assert!(
                tester.hit_test(pos).is_empty(),
                "({}, {}) must not hit a 0,0,100x100 node",
                pos.x,
                pos.y
            );
        }
        // Zero and negative zero are inside (origin is inclusive).
        assert_eq!(tester.hit_test(p(0.0, 0.0)).len(), 1);
        assert_eq!(tester.hit_test(p(-0.0, -0.0)).len(), 1);
        // The exclusive far edge.
        assert!(tester.hit_test(p(100.0, 100.0)).is_empty());
        assert_eq!(tester.hit_test(p(99.999, 99.999)).len(), 1);
    }
    #[test]
    fn hit_test_returns_topmost_first() {
        // Two fully overlapping siblings: the one that paints last (higher index)
        // must come back first.
        let mut results = BTreeMap::new();
        results.insert(
            dom(0),
            layout_result(
                styled(""),
                vec![
                    hot(Some(1), Some((100.0, 100.0)), None),
                    hot(Some(2), Some((100.0, 100.0)), None),
                ],
                vec![p(0.0, 0.0), p(0.0, 0.0)],
                Vec::new(),
            ),
        );
        let mut tester = CpuHitTester::new();
        tester.rebuild_from_layout(&results);
        assert_eq!(
            tester.hit_test(p(50.0, 50.0)),
            vec![(dom(0), NodeId::new(2)), (dom(0), NodeId::new(1))]
        );
    }
    #[test]
    fn a_child_dom_on_top_of_its_host_comes_first_and_gets_the_lower_depth() {
        // Host dom 0: one node covering (0,0)-(300,300), showing child dom 1
        // through a VirtualView at (100,100)-(150,150). Child dom 1: one node
        // covering its whole 200x200. A point inside the page is over BOTH.
        //
        // WebRender answers page first (front to back, one scene for every
        // DOM). The CPU tester visited DOMs in ascending id order, so the
        // HOST came first and `FullHitTest::topmost_node` - the smallest
        // `hit_depth` - named the node the page was covering.
        let mut results = BTreeMap::new();
        results.insert(
            dom(0),
            layout_result(
                styled(""),
                vec![hot(Some(1), Some((300.0, 300.0)), None)],
                vec![p(0.0, 0.0)],
                vec![virtual_view(1, r(100.0, 100.0, 50.0, 50.0))],
            ),
        );
        results.insert(
            dom(1),
            layout_result(
                styled(""),
                vec![hot(Some(1), Some((200.0, 200.0)), None)],
                vec![p(0.0, 0.0)],
                Vec::new(),
            ),
        );
        let mut tester = CpuHitTester::new();
        tester.rebuild_from_layout(&results);
        let hits = tester.hit_test_scrolled(p(120.0, 120.0), &|_, _| None, &|_, _| None);
        let order: Vec<(DomId, NodeId)> = hits.iter().map(|(d, n, _)| (*d, *n)).collect();
        assert_eq!(
            order,
            vec![(dom(1), NodeId::new(1)), (dom(0), NodeId::new(1))],
            "the page over the host is nearer the user"
        );
        let full = convert_cpu_hit_test_to_full(
            &tester,
            &hits,
            None,
            &results,
            p(120.0, 120.0),
            &|_, _| None,
            &|_, _| None,
        );
        let depth = |d: usize| {
            full.hovered_nodes[&dom(d)].regular_hit_test_nodes[&NodeId::new(1)].hit_depth
        };
        assert_eq!(depth(1), 0, "front-most");
        assert_eq!(depth(0), 1);
        let top = full.topmost_node().expect("something is hit");
        assert_eq!(
            top.dom,
            dom(1),
            "topmost_node agrees with WebRender's rule now"
        );
        // Outside the page, only the host - and it is then the front-most.
        let outside = tester.hit_test(p(20.0, 20.0));
        assert_eq!(outside, vec![(dom(0), NodeId::new(1))]);
    }
    #[test]
    fn hit_test_skips_nodes_with_no_calculated_position() {
        // `calculated_positions` shorter than `nodes` is a torn/partial layout:
        // the extra nodes must be dropped, not indexed out of bounds.
        let mut results = BTreeMap::new();
        results.insert(
            dom(0),
            layout_result(
                styled(""),
                vec![
                    hot(Some(0), Some((100.0, 100.0)), None),
                    hot(Some(1), Some((100.0, 100.0)), None),
                    hot(Some(2), Some((100.0, 100.0)), None),
                ],
                vec![p(0.0, 0.0)], // only node 0 has a position
                Vec::new(),
            ),
        );
        let mut tester = CpuHitTester::new();
        tester.rebuild_from_layout(&results);
        assert_eq!(tester.node_rects_total(), 1);
        assert_eq!(tester.hit_test(p(50.0, 50.0)), vec![(dom(0), NodeId::ZERO)]);
    }
    #[test]
    fn hit_test_respects_an_overflow_hidden_ancestor() {
        // body(0) 500x500 > div.clip(1) 100x100 overflow:hidden > div(2) 400x400.
        // A point at (200,200) is inside node 2's rect but scrolled/clipped out of
        // its ancestor, so only the body may claim it.
        let mut results = BTreeMap::new();
        results.insert(
            dom(0),
            layout_result(
                styled("div.clip { overflow: hidden; }"),
                vec![
                    hot(Some(0), Some((500.0, 500.0)), None),
                    hot(Some(1), Some((100.0, 100.0)), Some(0)),
                    hot(Some(2), Some((400.0, 400.0)), Some(1)),
                ],
                vec![p(0.0, 0.0), p(0.0, 0.0), p(0.0, 0.0)],
                Vec::new(),
            ),
        );
        let mut tester = CpuHitTester::new();
        tester.rebuild_from_layout(&results);
        assert_eq!(
            tester.hit_test(p(50.0, 50.0)),
            vec![
                (dom(0), NodeId::new(2)),
                (dom(0), NodeId::new(1)),
                (dom(0), NodeId::new(0)),
            ],
            "inside the clip: all three nodes are hit, topmost first"
        );
        assert_eq!(
            tester.hit_test(p(200.0, 200.0)),
            vec![(dom(0), NodeId::new(0))],
            "outside the clip: the clipped-out child must not eat the event"
        );
    }
    // -----------------------------------------------------------------------
    // CpuHitTester::rebuild_from_layout  (VirtualView placement)
    // -----------------------------------------------------------------------
    #[test]
    fn rebuild_from_layout_with_no_doms_is_a_no_op() {
        let mut tester = CpuHitTester::new();
        tester.rebuild_from_layout(&BTreeMap::new());
        assert_eq!(tester.node_rects_total(), 0);
        assert!(tester.hit_test(p(0.0, 0.0)).is_empty());
    }
    #[test]
    fn rebuild_translates_and_clips_virtual_view_child_doms() {
        // Host dom 0 hosts child dom 1 at (100,100) 50x50. The child lays out in
        // local coordinates with a 200x200 node at (0,0): it must be translated to
        // (100,100) AND clipped to the 50x50 composite box, otherwise it claims
        // pointer events across the whole window (the azul-maps tile-grid bug).
        let mut results = BTreeMap::new();
        results.insert(
            dom(0),
            layout_result(
                styled(""),
                Vec::new(),
                Vec::new(),
                vec![virtual_view(1, r(100.0, 100.0, 50.0, 50.0))],
            ),
        );
        results.insert(
            dom(1),
            layout_result(
                styled(""),
                vec![hot(Some(1), Some((200.0, 200.0)), None)],
                vec![p(0.0, 0.0)],
                Vec::new(),
            ),
        );
        let mut tester = CpuHitTester::new();
        tester.rebuild_from_layout(&results);
        assert!(
            tester.hit_test(p(10.0, 10.0)).is_empty(),
            "the child's local (10,10) is not its window position"
        );
        assert_eq!(
            tester.hit_test(p(120.0, 120.0)),
            vec![(dom(1), NodeId::new(1))],
            "translated into the host's VirtualView bounds"
        );
        assert!(
            tester.hit_test(p(180.0, 180.0)).is_empty(),
            "inside the child's 200x200 rect but outside the 50x50 composite clip"
        );
    }
    #[test]
    fn a_scrolled_virtual_views_clip_stays_on_the_viewport_it_does_not_travel_with_the_content() {
        // Host dom 0 shows child dom 1 through a 50x50 VIEWPORT at (100,100).
        // The child is scrolled: `content_offset` is (0,-80), so the renderer
        // draws the child's local (0,0) at (100,20) — 80px of it above the
        // viewport, the rest visible from y=100 down (cpurender/raster.rs
        // pushes `-vv_origin - content_offset` and clips to `bounds`).
        //
        // The hit test used the SHIFTED rect as the clip too, which moves the
        // window the user is looking through. Both directions are wrong and
        // both are asserted here.
        let mut results = BTreeMap::new();
        results.insert(
            dom(0),
            layout_result(
                styled(""),
                Vec::new(),
                Vec::new(),
                vec![virtual_view_scrolled(
                    1,
                    r(100.0, 100.0, 50.0, 50.0),
                    p(0.0, -80.0),
                )],
            ),
        );
        results.insert(
            dom(1),
            layout_result(
                styled(""),
                vec![hot(Some(1), Some((200.0, 200.0)), None)],
                vec![p(0.0, 0.0)],
                Vec::new(),
            ),
        );
        let mut tester = CpuHitTester::new();
        tester.rebuild_from_layout(&results);
        assert_eq!(
            tester.hit_test(p(120.0, 120.0)),
            vec![(dom(1), NodeId::new(1))],
            "a point inside BOTH the viewport and the drawn child must hit it — clipping to \
             `bounds.origin + content_offset` moved the viewport 80px up and rejected it, which \
             is a page canvas that goes dead as soon as you scroll"
        );
        assert!(
            tester.hit_test(p(120.0, 60.0)).is_empty(),
            "the part of the child scrolled ABOVE the viewport is not visible, so it must not \
             take the click either"
        );
    }
    #[test]
    fn rebuild_accumulates_offsets_through_nested_virtual_views() {
        // dom0 --VV(10,10)--> dom1 --VV(5,5 local)--> dom2, whose node sits at
        // local (0,0): absolute origin must be (15,15).
        let mut results = BTreeMap::new();
        results.insert(
            dom(0),
            layout_result(
                styled(""),
                Vec::new(),
                Vec::new(),
                vec![virtual_view(1, r(10.0, 10.0, 200.0, 200.0))],
            ),
        );
        results.insert(
            dom(1),
            layout_result(
                styled(""),
                Vec::new(),
                Vec::new(),
                vec![virtual_view(2, r(5.0, 5.0, 100.0, 100.0))],
            ),
        );
        results.insert(
            dom(2),
            layout_result(
                styled(""),
                vec![hot(Some(1), Some((20.0, 20.0)), None)],
                vec![p(0.0, 0.0)],
                Vec::new(),
            ),
        );
        let mut tester = CpuHitTester::new();
        tester.rebuild_from_layout(&results);
        assert_eq!(
            tester.hit_test(p(16.0, 16.0)),
            vec![(dom(2), NodeId::new(1))]
        );
        assert!(
            tester.hit_test(p(14.0, 14.0)).is_empty(),
            "(14,14) is before the doubly-offset origin (15,15)"
        );
        assert!(tester.hit_test(p(36.0, 36.0)).is_empty());
    }
    #[test]
    fn rebuild_ignores_virtual_views_pointing_at_a_missing_child_dom() {
        let mut results = BTreeMap::new();
        results.insert(
            dom(0),
            layout_result(
                styled(""),
                vec![hot(Some(0), Some((10.0, 10.0)), None)],
                vec![p(0.0, 0.0)],
                vec![virtual_view(42, r(0.0, 0.0, 10.0, 10.0))],
            ),
        );
        let mut tester = CpuHitTester::new();
        tester.rebuild_from_layout(&results);
        assert_eq!(tester.node_rects_total(), 1);
        assert_eq!(tester.hit_test(p(5.0, 5.0)), vec![(dom(0), NodeId::ZERO)]);
    }
    #[test]
    fn rebuild_terminates_on_a_cyclic_virtual_view_graph() {
        // dom1 hosts dom2 and dom2 hosts dom1: neither is reachable from the root
        // dom, so neither gets placed. The placement loop is bounded, so this must
        // terminate (a hang here would freeze every layout pass).
        let mut results = BTreeMap::new();
        results.insert(
            dom(1),
            layout_result(
                styled(""),
                vec![hot(Some(1), Some((10.0, 10.0)), None)],
                vec![p(0.0, 0.0)],
                vec![virtual_view(2, r(1.0, 1.0, 10.0, 10.0))],
            ),
        );
        results.insert(
            dom(2),
            layout_result(
                styled(""),
                vec![hot(Some(1), Some((10.0, 10.0)), None)],
                vec![p(0.0, 0.0)],
                vec![virtual_view(1, r(2.0, 2.0, 10.0, 10.0))],
            ),
        );
        let mut tester = CpuHitTester::new();
        tester.rebuild_from_layout(&results);
        assert_eq!(tester.node_rects_total(), 2);
    }
    #[test]
    fn rebuild_handles_a_virtual_view_with_hostile_bounds() {
        // A NaN/infinite composite box must not produce a NaN clip that panics or
        // makes the child hit-testable everywhere.
        for bad in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY, f32::MAX] {
            let mut results = BTreeMap::new();
            results.insert(
                dom(0),
                layout_result(
                    styled(""),
                    Vec::new(),
                    Vec::new(),
                    vec![virtual_view(1, r(bad, bad, bad, bad))],
                ),
            );
            results.insert(
                dom(1),
                layout_result(
                    styled(""),
                    vec![hot(Some(1), Some((20.0, 20.0)), None)],
                    vec![p(0.0, 0.0)],
                    Vec::new(),
                ),
            );
            let mut tester = CpuHitTester::new();
            tester.rebuild_from_layout(&results);
            assert_eq!(tester.node_rects_total(), 1);
            // Whatever the clip degenerates to, hit testing must not panic.
            let _ = tester.hit_test(p(10.0, 10.0));
            let _ = tester.hit_test(p(f32::NAN, 0.0));
        }
    }
    // -----------------------------------------------------------------------
    // compute_node_clip  (numeric)
    // -----------------------------------------------------------------------
    #[test]
    fn compute_node_clip_without_ancestors_or_dom_clip_is_unclipped() {
        let styled_dom = styled("");
        let nodes = vec![hot(Some(0), Some((10.0, 10.0)), None)];
        let positions: PositionVec = vec![p(0.0, 0.0)];
        assert_eq!(
            compute_node_clip(&styled_dom, &nodes, &positions, 0, p(0.0, 0.0), None),
            None
        );
    }
    #[test]
    fn compute_node_clip_out_of_bounds_node_index_does_not_panic() {
        let styled_dom = styled("");
        let nodes: Vec<LayoutNodeHot> = Vec::new();
        let positions: PositionVec = Vec::new();
        for idx in [0_usize, 1, 999, usize::MAX] {
            assert_eq!(
                compute_node_clip(&styled_dom, &nodes, &positions, idx, p(0.0, 0.0), None),
                None
            );
            // ...and with a DOM clip it still returns exactly that clip.
            let clip = compute_node_clip(
                &styled_dom,
                &nodes,
                &positions,
                idx,
                p(0.0, 0.0),
                Some(r(1.0, 2.0, 3.0, 4.0)),
            );
            assert_eq!(clip, Some(r(1.0, 2.0, 3.0, 4.0)));
        }
    }
    #[test]
    fn compute_node_clip_round_trips_a_dom_clip_when_no_ancestor_clips() {
        // encode == decode: with no clipping ancestor the composite box must come
        // back byte-identical, offset included (the offset is already baked into
        // the placement, so it must NOT be applied twice).
        let styled_dom = styled("");
        let nodes = vec![hot(Some(0), Some((10.0, 10.0)), None)];
        let positions: PositionVec = vec![p(0.0, 0.0)];
        let dom_clip = r(100.0, 200.0, 50.0, 25.0);
        let clip = compute_node_clip(
            &styled_dom,
            &nodes,
            &positions,
            0,
            p(100.0, 200.0),
            Some(dom_clip),
        )
        .expect("dom_clip must survive");
        assert_eq!(clip.origin.x, dom_clip.origin.x);
        assert_eq!(clip.origin.y, dom_clip.origin.y);
        assert_eq!(clip.size.width, dom_clip.size.width);
        assert_eq!(clip.size.height, dom_clip.size.height);
    }
    #[test]
    fn compute_node_clip_never_lets_nan_escape_into_the_clip_rect() {
        let styled_dom = styled("");
        let nodes = vec![hot(Some(0), Some((10.0, 10.0)), None)];
        let positions: PositionVec = vec![p(0.0, 0.0)];
        for bad in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY] {
            for dom_clip in [
                r(bad, 0.0, 10.0, 10.0),
                r(0.0, bad, 10.0, 10.0),
                r(0.0, 0.0, bad, 10.0),
                r(0.0, 0.0, 10.0, bad),
                r(bad, bad, bad, bad),
            ] {
                let clip = compute_node_clip(
                    &styled_dom,
                    &nodes,
                    &positions,
                    0,
                    p(0.0, 0.0),
                    Some(dom_clip),
                )
                .expect("a dom_clip always yields a clip");
                assert!(
                    clip.origin.x.is_finite()
                        && clip.origin.y.is_finite()
                        && clip.size.width.is_finite()
                        && clip.size.height.is_finite(),
                    "clip {clip:?} from dom_clip {dom_clip:?} must stay finite"
                );
                assert!(clip.size.width >= 0.0 && clip.size.height >= 0.0);
                assert!(
                    clip.max_x().is_finite() && clip.max_y().is_finite(),
                    "origin + size must not overflow to inf/NaN"
                );
                // point_in_rect over the result must be a real answer, not a NaN
                // comparison that silently drops every event.
                let _ = point_in_rect(p(0.0, 0.0), &clip);
            }
        }
    }
    #[test]
    fn compute_node_clip_clamps_an_infinite_dom_clip_to_clip_unbounded() {
        let styled_dom = styled("");
        let nodes = vec![hot(Some(0), Some((10.0, 10.0)), None)];
        let positions: PositionVec = vec![p(0.0, 0.0)];
        let clip = compute_node_clip(
            &styled_dom,
            &nodes,
            &positions,
            0,
            p(0.0, 0.0),
            Some(LogicalRect {
                origin: p(0.0, 0.0),
                size: LogicalSize {
                    width: f32::INFINITY,
                    height: f32::INFINITY,
                },
            }),
        )
        .expect("a dom_clip always yields a clip");
        assert_eq!(clip.origin.x, 0.0);
        assert_eq!(clip.origin.y, 0.0);
        assert_eq!(clip.size.width, CLIP_UNBOUNDED);
        assert_eq!(clip.size.height, CLIP_UNBOUNDED);
        assert!(point_in_rect(p(1.0e6, 1.0e6), &clip));
    }
    #[test]
    fn compute_node_clip_saturates_a_negative_sized_dom_clip_to_zero_not_negative() {
        let styled_dom = styled("");
        let nodes = vec![hot(Some(0), Some((10.0, 10.0)), None)];
        let positions: PositionVec = vec![p(0.0, 0.0)];
        let clip = compute_node_clip(
            &styled_dom,
            &nodes,
            &positions,
            0,
            p(0.0, 0.0),
            Some(r(100.0, 100.0, -50.0, -50.0)),
        )
        .expect("a dom_clip always yields a clip");
        assert_eq!(clip.size.width, 0.0);
        assert_eq!(clip.size.height, 0.0);
        assert!(!point_in_rect(p(100.0, 100.0), &clip));
        assert!(!point_in_rect(p(75.0, 75.0), &clip));
    }
    #[test]
    fn compute_node_clip_intersects_a_clipping_ancestor_with_the_dom_clip() {
        // ancestor div.clip at (10,10) 100x50; dom_clip (0,0) 60x60
        // => intersection (10,10) 50x50
        let styled_dom = styled("div.clip { overflow: hidden; }");
        let nodes = vec![
            hot(Some(0), Some((500.0, 500.0)), None),
            hot(Some(1), Some((100.0, 50.0)), Some(0)),
            hot(Some(2), Some((400.0, 400.0)), Some(1)),
        ];
        let positions: PositionVec = vec![p(0.0, 0.0), p(10.0, 10.0), p(10.0, 10.0)];
        let clip = compute_node_clip(
            &styled_dom,
            &nodes,
            &positions,
            2,
            p(0.0, 0.0),
            Some(r(0.0, 0.0, 60.0, 60.0)),
        )
        .expect("an overflow:hidden ancestor must clip");
        assert_eq!(clip.origin.x, 10.0);
        assert_eq!(clip.origin.y, 10.0);
        assert_eq!(clip.size.width, 50.0);
        assert_eq!(clip.size.height, 50.0);
    }
    #[test]
    fn compute_node_clip_applies_the_offset_to_the_ancestor_box() {
        let styled_dom = styled("div.clip { overflow: hidden; }");
        let nodes = vec![
            hot(Some(0), Some((500.0, 500.0)), None),
            hot(Some(1), Some((100.0, 50.0)), Some(0)),
            hot(Some(2), Some((400.0, 400.0)), Some(1)),
        ];
        let positions: PositionVec = vec![p(0.0, 0.0), p(10.0, 10.0), p(10.0, 10.0)];
        let clip = compute_node_clip(&styled_dom, &nodes, &positions, 2, p(1000.0, 2000.0), None)
            .expect("an overflow:hidden ancestor must clip");
        assert_eq!(clip.origin.x, 1010.0);
        assert_eq!(clip.origin.y, 2010.0);
        assert_eq!(clip.size.width, 100.0);
        assert_eq!(clip.size.height, 50.0);
    }
    #[test]
    fn compute_node_clip_leaves_the_unclipped_axis_unbounded() {
        // overflow-x: hidden / overflow-y: visible — the y axis must stay
        // unbounded (finite stand-in), not collapse onto the ancestor's box.
        let styled_dom = styled("div.clip { overflow-x: hidden; }");
        let nodes = vec![
            hot(Some(0), Some((500.0, 500.0)), None),
            hot(Some(1), Some((100.0, 50.0)), Some(0)),
            hot(Some(2), Some((400.0, 400.0)), Some(1)),
        ];
        let positions: PositionVec = vec![p(0.0, 0.0), p(10.0, 10.0), p(10.0, 10.0)];
        let clip = compute_node_clip(&styled_dom, &nodes, &positions, 2, p(0.0, 0.0), None)
            .expect("overflow-x: hidden must clip the x axis");
        assert_eq!(clip.origin.x, 10.0);
        assert_eq!(clip.size.width, 100.0);
        assert_eq!(clip.origin.y, -CLIP_UNBOUNDED);
        assert_eq!(clip.size.height, 2.0 * CLIP_UNBOUNDED);
        assert!(clip.max_y().is_finite());
        // A point far below the ancestor is still inside the clip (y unbounded),
        // but a point to the right of it is not.
        assert!(point_in_rect(p(50.0, 900_000.0), &clip));
        assert!(!point_in_rect(p(500.0, 20.0), &clip));
    }
    #[test]
    fn compute_node_clip_skips_a_clipping_ancestor_that_was_never_laid_out() {
        // used_size: None on the clipping ancestor => nothing to intersect with;
        // it must be skipped rather than contributing a garbage/zero box.
        let styled_dom = styled("div.clip { overflow: hidden; }");
        let nodes = vec![
            hot(Some(0), Some((500.0, 500.0)), None),
            hot(Some(1), None, Some(0)), // clips, but has no used_size
            hot(Some(2), Some((400.0, 400.0)), Some(1)),
        ];
        let positions: PositionVec = vec![p(0.0, 0.0), p(10.0, 10.0), p(10.0, 10.0)];
        assert_eq!(
            compute_node_clip(&styled_dom, &nodes, &positions, 2, p(0.0, 0.0), None),
            None
        );
    }
    #[test]
    fn compute_node_clip_terminates_on_a_parent_cycle() {
        // Two anonymous boxes that are each other's parent. The `guard` counter is
        // the only thing standing between this and an infinite loop inside a
        // hit-test rebuild.
        let styled_dom = styled("");
        let nodes = vec![
            hot(None, Some((10.0, 10.0)), Some(1)),
            hot(None, Some((10.0, 10.0)), Some(0)),
        ];
        let positions: PositionVec = vec![p(0.0, 0.0), p(0.0, 0.0)];
        assert_eq!(
            compute_node_clip(&styled_dom, &nodes, &positions, 0, p(0.0, 0.0), None),
            None
        );
        // The DOM clip still survives the bounded walk.
        assert_eq!(
            compute_node_clip(
                &styled_dom,
                &nodes,
                &positions,
                1,
                p(0.0, 0.0),
                Some(r(0.0, 0.0, 5.0, 5.0))
            ),
            Some(r(0.0, 0.0, 5.0, 5.0))
        );
    }
    #[test]
    fn compute_node_clip_terminates_on_a_self_parent_cycle() {
        let styled_dom = styled("");
        let nodes = vec![hot(None, Some((10.0, 10.0)), Some(0))];
        let positions: PositionVec = vec![p(0.0, 0.0)];
        assert_eq!(
            compute_node_clip(&styled_dom, &nodes, &positions, 0, p(0.0, 0.0), None),
            None
        );
    }
    #[test]
    fn compute_node_clip_tolerates_a_parent_index_past_the_end_of_the_node_slice() {
        let styled_dom = styled("");
        let nodes = vec![hot(Some(0), Some((10.0, 10.0)), Some(usize::MAX))];
        let positions: PositionVec = vec![p(0.0, 0.0)];
        assert_eq!(
            compute_node_clip(&styled_dom, &nodes, &positions, 0, p(0.0, 0.0), None),
            None
        );
    }
    // -----------------------------------------------------------------------
    // convert_cpu_hit_test_to_full — the CPU half of the ONE documented space
    // -----------------------------------------------------------------------
    /// `HitTestItem::point_relative_to_item` is CONTENT-box-relative on BOTH
    /// hosts. This pins the CPU half; the WebRender half applies the same
    /// `LayoutTree::content_inset` in `wr_translate2::fullhittest_new_webrender`.
    ///
    /// Before this, WebRender reported the point relative to the hit RECT
    /// (border box) while the CPU tester subtracted padding+border, so the
    /// SAME click resolved to different characters in headless E2E and in
    /// production — latent only because the default TextInput's value <p> has
    /// neither padding nor border.
    #[test]
    fn convert_cpu_hit_test_emits_content_box_relative_points() {
        use crate::solver3::geometry::{EdgeSizes, PackedBoxProps, ResolvedBoxProps};
        let inset = |left: f32, top: f32| {
            PackedBoxProps::pack(&ResolvedBoxProps {
                padding: EdgeSizes {
                    top,
                    right: 0.0,
                    bottom: 0.0,
                    left,
                },
                border: EdgeSizes {
                    top: 1.0,
                    right: 0.0,
                    bottom: 0.0,
                    left: 1.0,
                },
                ..Default::default()
            })
        };
        let styled_dom = styled("");
        let mut node = hot(Some(0), Some((100.0, 40.0)), None);
        node.box_props = inset(5.0, 2.0); // + 1px border on each of left/top
        let mut lr = layout_result(styled_dom, vec![node], vec![p(10.0, 20.0)], Vec::new());
        lr.layout_tree
            .dom_to_layout
            .insert(NodeId::new(0), vec![LayoutNodeId::new(0)]);
        let mut layout_results = BTreeMap::new();
        layout_results.insert(dom(0), lr);
        // The hit tester reports the point in STATIC layout space; the node's
        // border box starts at (10, 20) and its content box 6/3 further in.
        let hits = vec![(dom(0), NodeId::new(0), p(40.0, 50.0))];
        let full = convert_cpu_hit_test_to_full(
            &CpuHitTester::new(),
            &hits,
            None,
            &layout_results,
            p(40.0, 50.0),
            &|_, _| None,
            &|_, _| None,
        );
        let item = full.hovered_nodes[&dom(0)].regular_hit_test_nodes[&NodeId::new(0)];
        assert_eq!(
            item.point_relative_to_item.get(),
            p(40.0 - 10.0 - 6.0, 50.0 - 20.0 - 3.0),
            "content-box-relative: static point minus border-box origin minus content inset"
        );
        // ...and the round trip back out to the border box, which is what
        // `get_cursor_relative_to_node` hands widgets, is exact.
        assert_eq!(
            item.point_relative_to_item
                .to_border_box_local(azul_core::spaces::ContentInset::new(6.0, 3.0))
                .get(),
            p(30.0, 30.0),
        );
    }
    /// A node with no padding and no border: the two boxes coincide, which is
    /// why the divergence above stayed invisible in the default widget set.
    #[test]
    fn convert_cpu_hit_test_on_an_unpadded_node_is_plain_border_box_local() {
        let styled_dom = styled("");
        let mut lr = layout_result(
            styled_dom,
            vec![hot(Some(0), Some((100.0, 40.0)), None)],
            vec![p(10.0, 20.0)],
            Vec::new(),
        );
        lr.layout_tree
            .dom_to_layout
            .insert(NodeId::new(0), vec![LayoutNodeId::new(0)]);
        let mut layout_results = BTreeMap::new();
        layout_results.insert(dom(0), lr);
        let hits = vec![(dom(0), NodeId::new(0), p(40.0, 50.0))];
        let full = convert_cpu_hit_test_to_full(
            &CpuHitTester::new(),
            &hits,
            None,
            &layout_results,
            p(40.0, 50.0),
            &|_, _| None,
            &|_, _| None,
        );
        assert_eq!(
            full.hovered_nodes[&dom(0)].regular_hit_test_nodes[&NodeId::new(0)]
                .point_relative_to_item
                .get(),
            p(30.0, 30.0),
        );
    }
}