1
//! Hit-testing logic for layout windows
2
//!
3
//! This module handles determining which DOM nodes are under the mouse cursor
4
//! and resolving the cursor icon based on CSS cursor properties.
5
//!
6
//! ## Cursor Resolution Algorithm
7
//!
8
//! WebRender returns hit-test results in **front-to-back** order:
9
//! - `depth = 0` is the frontmost/topmost element (closest to the user)
10
//! - Higher depth values are further back in the z-order
11
//!
12
//! The algorithm finds the **frontmost** node that has an explicit CSS `cursor`
13
//! property set. If no node has a cursor property, we check if the node has
14
//! text children and use their cursor property (typically `cursor:text`).
15
//!
16
//! ## Design Principles
17
//!
18
//! 1. **Frontmost priority**: The node closest to the user (lowest depth) takes precedence. This
19
//!    matches browser behavior where a button's cursor:pointer overrides any parent's cursor
20
//!    setting.
21
//!
22
//! 2. **Text-child inheritance**: Text nodes are inline and don't get hit-test areas. Their
23
//!    container inherits the text node's cursor if the container has no explicit cursor property.
24
//!    This shows I-beam cursor over text containers.
25
//!
26
//! 3. **Explicit cursor wins**: If a container has an explicit cursor property (like
27
//!    `cursor:pointer` on a button), it overrides any text-child cursor.
28

            
29
// Re-export FullHitTest for use by other layout modules
30
pub use azul_core::hit_test::FullHitTest;
31
use azul_core::{
32
    dom::{DomId, DomNodeId, NodeId},
33
    hit_test::{HitTest, HitTestItem},
34
    window::MouseCursorType,
35
};
36
use azul_css::props::style::StyleCursor;
37

            
38
use crate::window::LayoutWindow;
39

            
40
/// Result of cursor type hit-testing, determines which mouse cursor to display
41
#[derive(Copy, Debug, Clone, Default, PartialEq, Eq)]
42
pub struct CursorTypeHitTest {
43
    /// The node that has a non-default cursor property (if any)
44
    pub cursor_node: Option<(DomId, NodeId)>,
45
    /// The mouse cursor type to display
46
    pub cursor_icon: MouseCursorType,
47
}
48

            
49
impl CursorTypeHitTest {
50
    /// Create a new cursor type hit-test from a full hit-test and layout window.
51
    ///
52
    /// Finds the frontmost (lowest depth) node with a cursor property by checking
53
    /// `cursor_hit_test_nodes` (text runs) and `regular_hit_test_nodes` (DOM nodes).
54
28
    pub fn new(hit_test: &FullHitTest, layout_window: &LayoutWindow) -> Self {
55
        use azul_core::hit_test::CursorType;
56

            
57
28
        let mut cursor_node = None;
58
28
        let mut cursor_icon = MouseCursorType::Default;
59
        // Start with MAX so any node with a cursor property will be selected
60
28
        let mut best_depth: u32 = u32::MAX;
61

            
62
        // Iterate through all hovered nodes across all DOMs
63
58
        for (dom_id, hit_nodes) in &hit_test.hovered_nodes {
64
            // Get the layout result for this DOM
65
30
            let Some(layout_result) = layout_window.get_layout_result(dom_id) else {
66
3
                continue;
67
            };
68

            
69
27
            let styled_dom = &layout_result.styled_dom;
70
27
            let node_data_container = styled_dom.node_data.as_container();
71
27
            let styled_nodes = styled_dom.styled_nodes.as_container();
72

            
73
            // Check cursor_hit_test_nodes (direct text run hits with cursor
74
            // type encoded in the tag, no CSS lookup needed)
75
2033
            for (node_id, cursor_hit) in &hit_nodes.cursor_hit_test_nodes {
76
2006
                let node_depth = cursor_hit.hit_depth;
77

            
78
                // Only consider if it's in front of our current best
79
2006
                if node_depth >= best_depth {
80
1992
                    continue;
81
14
                }
82

            
83
                // Convert CursorType to MouseCursorType
84
14
                let mouse_cursor = translate_cursor_type(cursor_hit.cursor_type);
85

            
86
                // Only use this cursor if it's not the default
87
                // (allows containers behind text to show their cursor if text has default)
88
14
                if mouse_cursor != MouseCursorType::Default {
89
11
                    cursor_node = Some((*dom_id, *node_id));
90
11
                    cursor_icon = mouse_cursor;
91
11
                    best_depth = node_depth;
92
11
                }
93
            }
94

            
95
            // Check regular_hit_test_nodes (DOM nodes with CSS cursor property)
96
2063
            for (node_id, hit_item) in &hit_nodes.regular_hit_test_nodes {
97
2036
                let node_depth = hit_item.hit_depth;
98

            
99
                // Only consider this node if it's in front of our current best
100
2036
                if node_depth >= best_depth {
101
2008
                    continue;
102
28
                }
103

            
104
                // CHECKED access: hit-test results can reference a PREVIOUS
105
                // generation of a VirtualView child DOM — the child is rebuilt
106
                // in place with fresh (possibly fewer) NodeIds while the hover
107
                // state / CPU hit-tester still hold last frame's ids (e.g.
108
                // panning the MapWidget shrinks the tile grid). Blind indexing
109
                // panicked here ("len is 25 but the index is 27"); a stale id is
110
                // skipped instead — the next pointer move re-hit-tests against
111
                // the fresh tree.
112
23
                let (Some(node_data), Some(styled_node)) = (
113
28
                    node_data_container.get(*node_id),
114
28
                    styled_nodes.get(*node_id),
115
                ) else {
116
5
                    continue;
117
                };
118

            
119
                // Query the CSS cursor property for this node
120
23
                let cursor_prop = styled_dom.get_css_property_cache().get_cursor(
121
23
                    node_data,
122
23
                    node_id,
123
23
                    &styled_node.styled_node_state,
124
                );
125

            
126
                // If this node has an explicit cursor property, use it
127
23
                if let Some(cursor_prop) = cursor_prop {
128
19
                    let css_cursor = cursor_prop.get_property().copied().unwrap_or_default();
129
19
                    cursor_node = Some((*dom_id, *node_id));
130
19
                    cursor_icon = translate_cursor(css_cursor);
131
19
                    best_depth = node_depth;
132
19
                } else {
133
                    // No explicit `cursor`: editable text (contenteditable / a
134
                    // <textarea>) defaults to the I-beam, like browsers — so a
135
                    // multi-line textarea shows the text cursor on hover even
136
                    // without `cursor: text` in CSS. (A single-line input already
137
                    // gets the I-beam from its text-run cursor tag / explicit CSS;
138
                    // this makes them consistent. Does NOT affect the text_input
139
                    // widget, which sets cursor:text explicitly and so takes the
140
                    // branch above.)
141
4
                    if node_data.is_contenteditable()
142
2
                        || matches!(node_data.node_type, azul_core::dom::NodeType::TextArea)
143
2
                    {
144
2
                        cursor_node = Some((*dom_id, *node_id));
145
2
                        cursor_icon = MouseCursorType::Text;
146
2
                        best_depth = node_depth;
147
2
                    }
148
                }
149
            }
150
        }
151

            
152
28
        Self {
153
28
            cursor_node,
154
28
            cursor_icon,
155
28
        }
156
28
    }
157
}
158

            
159
/// Translate `CursorType` (from hit-test tag) to `MouseCursorType`
160
353
const fn translate_cursor_type(cursor_type: azul_core::hit_test::CursorType) -> MouseCursorType {
161
    use azul_core::hit_test::CursorType;
162

            
163
353
    match cursor_type {
164
243
        CursorType::Default => MouseCursorType::Default,
165
5
        CursorType::Pointer => MouseCursorType::Hand,
166
12
        CursorType::Text => MouseCursorType::Text,
167
7
        CursorType::Crosshair => MouseCursorType::Crosshair,
168
7
        CursorType::Move => MouseCursorType::Move,
169
4
        CursorType::NotAllowed => MouseCursorType::NotAllowed,
170
5
        CursorType::Grab => MouseCursorType::Grab,
171
5
        CursorType::Grabbing => MouseCursorType::Grabbing,
172
5
        CursorType::EResize => MouseCursorType::EResize,
173
5
        CursorType::WResize => MouseCursorType::WResize,
174
5
        CursorType::NResize => MouseCursorType::NResize,
175
5
        CursorType::SResize => MouseCursorType::SResize,
176
5
        CursorType::EwResize => MouseCursorType::EwResize,
177
5
        CursorType::NsResize => MouseCursorType::NsResize,
178
5
        CursorType::NeswResize => MouseCursorType::NeswResize,
179
5
        CursorType::NwseResize => MouseCursorType::NwseResize,
180
5
        CursorType::ColResize => MouseCursorType::ColResize,
181
5
        CursorType::RowResize => MouseCursorType::RowResize,
182
5
        CursorType::Wait => MouseCursorType::Wait,
183
5
        CursorType::Help => MouseCursorType::Help,
184
5
        CursorType::Progress => MouseCursorType::Progress,
185
    }
186
353
}
187

            
188
/// Translate CSS cursor value to `MouseCursorType`
189
#[allow(clippy::match_same_arms)] // enum/value mapping/dispatch table: one arm per input variant
190
                                  // (or cross-type bindings that can't merge)
191
104
const fn translate_cursor(cursor: StyleCursor) -> MouseCursorType {
192
    use azul_css::props::style::effects::StyleCursor;
193

            
194
104
    match cursor {
195
6
        StyleCursor::Default => MouseCursorType::Default,
196
7
        StyleCursor::Crosshair => MouseCursorType::Crosshair,
197
17
        StyleCursor::Pointer => MouseCursorType::Hand,
198
4
        StyleCursor::Move => MouseCursorType::Move,
199
5
        StyleCursor::Text => MouseCursorType::Text,
200
3
        StyleCursor::Wait => MouseCursorType::Wait,
201
3
        StyleCursor::Help => MouseCursorType::Help,
202
3
        StyleCursor::Progress => MouseCursorType::Progress,
203
2
        StyleCursor::ContextMenu => MouseCursorType::ContextMenu,
204
2
        StyleCursor::Cell => MouseCursorType::Cell,
205
2
        StyleCursor::VerticalText => MouseCursorType::VerticalText,
206
2
        StyleCursor::Alias => MouseCursorType::Alias,
207
2
        StyleCursor::Copy => MouseCursorType::Copy,
208
3
        StyleCursor::Grab => MouseCursorType::Grab,
209
3
        StyleCursor::Grabbing => MouseCursorType::Grabbing,
210
2
        StyleCursor::AllScroll => MouseCursorType::AllScroll,
211
2
        StyleCursor::ZoomIn => MouseCursorType::ZoomIn,
212
2
        StyleCursor::ZoomOut => MouseCursorType::ZoomOut,
213
3
        StyleCursor::EResize => MouseCursorType::EResize,
214
3
        StyleCursor::NResize => MouseCursorType::NResize,
215
3
        StyleCursor::SResize => MouseCursorType::SResize,
216
2
        StyleCursor::SeResize => MouseCursorType::SeResize,
217
3
        StyleCursor::WResize => MouseCursorType::WResize,
218
3
        StyleCursor::EwResize => MouseCursorType::EwResize,
219
3
        StyleCursor::NsResize => MouseCursorType::NsResize,
220
3
        StyleCursor::NeswResize => MouseCursorType::NeswResize,
221
3
        StyleCursor::NwseResize => MouseCursorType::NwseResize,
222
3
        StyleCursor::ColResize => MouseCursorType::ColResize,
223
3
        StyleCursor::RowResize => MouseCursorType::RowResize,
224
2
        StyleCursor::Unset => MouseCursorType::Default,
225
    }
226
104
}
227

            
228
#[cfg(test)]
229
mod tests {
230
    use azul_core::dom::{DomNodeId, OptionDomNodeId};
231

            
232
    use super::*;
233

            
234
    #[test]
235
1
    fn test_full_hit_test_empty() {
236
1
        let hit_test = FullHitTest::empty(None);
237
1
        assert!(hit_test.is_empty());
238
1
        assert!(hit_test.focused_node.is_none());
239
1
    }
240

            
241
    #[test]
242
1
    fn test_full_hit_test_with_focused_node() {
243
1
        let focused = DomNodeId {
244
1
            dom: DomId { inner: 0 },
245
1
            node: azul_core::styled_dom::NodeHierarchyItemId::from_crate_internal(Some(
246
1
                NodeId::new(5),
247
1
            )),
248
1
        };
249
1
        let hit_test = FullHitTest::empty(Some(focused));
250
1
        assert!(hit_test.is_empty()); // No hovered nodes
251
1
        assert_eq!(
252
            hit_test.focused_node,
253
1
            OptionDomNodeId::Some(DomNodeId {
254
1
                dom: DomId { inner: 0 },
255
1
                node: azul_core::styled_dom::NodeHierarchyItemId::from_crate_internal(Some(
256
1
                    NodeId::new(5),
257
1
                )),
258
1
            })
259
        );
260
1
    }
261

            
262
    #[test]
263
1
    fn test_cursor_type_hit_test_default() {
264
1
        let cursor_test = CursorTypeHitTest::default();
265
1
        assert_eq!(cursor_test.cursor_icon, MouseCursorType::Default);
266
1
        assert!(cursor_test.cursor_node.is_none());
267
1
    }
268

            
269
    #[test]
270
1
    fn test_translate_cursor_mapping() {
271
        use azul_css::props::style::effects::StyleCursor;
272

            
273
1
        assert_eq!(
274
1
            translate_cursor(StyleCursor::Default),
275
            MouseCursorType::Default
276
        );
277
1
        assert_eq!(
278
1
            translate_cursor(StyleCursor::Pointer),
279
            MouseCursorType::Hand
280
        );
281
1
        assert_eq!(translate_cursor(StyleCursor::Text), MouseCursorType::Text);
282
1
        assert_eq!(translate_cursor(StyleCursor::Move), MouseCursorType::Move);
283
1
        assert_eq!(
284
1
            translate_cursor(StyleCursor::Crosshair),
285
            MouseCursorType::Crosshair
286
        );
287
1
    }
288
}
289

            
290
#[cfg(test)]
291
mod autotest_generated {
292
    use std::collections::{BTreeMap, HashMap};
293

            
294
    use azul_core::{
295
        dom::{Dom, NodeData, NodeType},
296
        geom::{LogicalPosition, LogicalRect},
297
        hit_test::{CursorHitTestItem, CursorType},
298
        styled_dom::StyledDom,
299
    };
300
    use rust_fontconfig::FcFontCache;
301

            
302
    use super::*;
303
    use crate::{
304
        solver3::{display_list::DisplayList, layout_tree::LayoutTree},
305
        window::DomLayoutResult,
306
    };
307

            
308
    // ------------------------------------------------------------------
309
    // Fixture
310
    // ------------------------------------------------------------------
311

            
312
    // Flatten indices of `fixture_dom()` (pre-order, body first).
313
    const BODY: usize = 0;
314
    /// explicit `cursor: pointer`
315
    const POINTER_DIV: usize = 1;
316
    /// explicit `cursor: crosshair`
317
    const CROSSHAIR_DIV: usize = 2;
318
    /// no cursor property at all
319
    const PLAIN_DIV: usize = 3;
320
    /// no cursor property, but `contenteditable`
321
    const EDITABLE_DIV: usize = 4;
322
    /// UA stylesheet gives it `cursor: text`
323
    const TEXTAREA: usize = 5;
324
    /// explicit `cursor: default`
325
    const DEFAULT_CURSOR_DIV: usize = 6;
326
    /// UA stylesheet gives it `cursor: pointer`
327
    const BUTTON: usize = 7;
328
    /// One past the last node — every id >= this is stale.
329
    const NODE_COUNT: usize = 8;
330

            
331
    /// A DOM covering every branch of `CursorTypeHitTest::new`: explicit CSS
332
    /// cursors, a UA-stylesheet cursor, a node with no cursor at all, and the
333
    /// two "editable text implies I-beam" node kinds. All cursor-carrying nodes
334
    /// are *leaves* and *siblings*, so CSS inheritance (cursor is an inherited
335
    /// property) can never make one of them bleed into another.
336
    fn fixture_dom() -> StyledDom {
337
        let dom = Dom::create_body()
338
            .with_child(Dom::create_div().with_css("cursor: pointer;"))
339
            .with_child(Dom::create_div().with_css("cursor: crosshair;"))
340
            .with_child(Dom::create_div())
341
            .with_child(Dom::create_div().with_contenteditable(true))
342
            .with_child(Dom::create_node(NodeType::TextArea))
343
            .with_child(Dom::create_div().with_css("cursor: default;"))
344
            .with_child(Dom::create_from_data(NodeData::create_button_no_a11y()));
345
        StyledDom::create_from_dom(dom)
346
    }
347

            
348
    /// A `DomLayoutResult` with an *empty* layout tree: `CursorTypeHitTest::new`
349
    /// only ever reads `styled_dom`, so no real layout (and no font) is needed.
350
    fn layout_result(styled_dom: StyledDom) -> DomLayoutResult {
351
        DomLayoutResult {
352
            styled_dom,
353
            layout_tree: LayoutTree {
354
                nodes: Vec::new(),
355
                warm: Vec::new(),
356
                cold: Vec::new(),
357
                root: 0,
358
                dom_to_layout: BTreeMap::new(),
359
                children_arena: Vec::new(),
360
                children_offsets: Vec::new(),
361
                subtree_needs_intrinsic: Vec::new(),
362
            },
363
            calculated_positions: Vec::new(),
364
            viewport: LogicalRect::zero(),
365
            display_list: std::sync::Arc::new(DisplayList::default()),
366
            scroll_ids: HashMap::new(),
367
            scroll_id_to_node_id: HashMap::new(),
368
        }
369
    }
370

            
371
    /// A window holding the fixture under every one of `dom_ids`.
372
    fn window_with(dom_ids: &[DomId]) -> LayoutWindow {
373
        let mut lw = LayoutWindow::new(FcFontCache::default()).expect("LayoutWindow::new failed");
374
        for dom_id in dom_ids {
375
            lw.layout_results
376
                .insert(*dom_id, layout_result(fixture_dom()));
377
        }
378
        lw
379
    }
380

            
381
    fn dom(inner: usize) -> DomId {
382
        DomId { inner }
383
    }
384

            
385
    /// `(node index, hit depth)` regular hits + `(node index, cursor type, hit
386
    /// depth)` text-run hits, grouped per DOM.
387
    type DomHits<'a> = (DomId, &'a [(usize, u32)], &'a [(usize, CursorType, u32)]);
388

            
389
    fn make_hit_test(entries: &[DomHits<'_>]) -> FullHitTest {
390
        let mut full = FullHitTest::empty(None);
391
        for (dom_id, regular, cursors) in entries {
392
            let mut ht = HitTest::empty();
393
            for (idx, depth) in *regular {
394
                ht.regular_hit_test_nodes.insert(
395
                    NodeId::new(*idx),
396
                    HitTestItem {
397
                        point_in_viewport: LogicalPosition::zero(),
398
                        point_relative_to_item: Default::default(),
399
                        is_focusable: false,
400
                        is_virtual_view_hit: None,
401
                        hit_depth: *depth,
402
                    },
403
                );
404
            }
405
            for (idx, cursor_type, depth) in *cursors {
406
                ht.cursor_hit_test_nodes.insert(
407
                    NodeId::new(*idx),
408
                    CursorHitTestItem {
409
                        cursor_type: *cursor_type,
410
                        hit_depth: *depth,
411
                        point_in_viewport: LogicalPosition::zero(),
412
                    },
413
                );
414
            }
415
            full.hovered_nodes.insert(*dom_id, ht);
416
        }
417
        full
418
    }
419

            
420
    /// Hit-test the fixture (loaded as the root DOM) and return the resolved cursor.
421
    fn resolve(
422
        regular: &[(usize, u32)],
423
        cursors: &[(usize, CursorType, u32)],
424
    ) -> CursorTypeHitTest {
425
        let lw = window_with(&[DomId::ROOT_ID]);
426
        let hit = make_hit_test(&[(DomId::ROOT_ID, regular, cursors)]);
427
        CursorTypeHitTest::new(&hit, &lw)
428
    }
429

            
430
    fn root_node(idx: usize) -> Option<(DomId, NodeId)> {
431
        Some((DomId::ROOT_ID, NodeId::new(idx)))
432
    }
433

            
434
    /// The one invariant every result must satisfy: no node selected => no cursor.
435
    fn assert_invariant(result: &CursorTypeHitTest) {
436
        if result.cursor_node.is_none() {
437
            assert_eq!(
438
                result.cursor_icon,
439
                MouseCursorType::Default,
440
                "cursor_node == None must imply the default icon"
441
            );
442
        }
443
    }
444

            
445
    const ALL_CURSOR_TYPES: [CursorType; 21] = [
446
        CursorType::Default,
447
        CursorType::Pointer,
448
        CursorType::Text,
449
        CursorType::Crosshair,
450
        CursorType::Move,
451
        CursorType::NotAllowed,
452
        CursorType::Grab,
453
        CursorType::Grabbing,
454
        CursorType::EResize,
455
        CursorType::WResize,
456
        CursorType::NResize,
457
        CursorType::SResize,
458
        CursorType::EwResize,
459
        CursorType::NsResize,
460
        CursorType::NeswResize,
461
        CursorType::NwseResize,
462
        CursorType::ColResize,
463
        CursorType::RowResize,
464
        CursorType::Wait,
465
        CursorType::Help,
466
        CursorType::Progress,
467
    ];
468

            
469
    const ALL_STYLE_CURSORS: [StyleCursor; 30] = [
470
        StyleCursor::Alias,
471
        StyleCursor::AllScroll,
472
        StyleCursor::Cell,
473
        StyleCursor::ColResize,
474
        StyleCursor::ContextMenu,
475
        StyleCursor::Copy,
476
        StyleCursor::Crosshair,
477
        StyleCursor::Default,
478
        StyleCursor::EResize,
479
        StyleCursor::EwResize,
480
        StyleCursor::Grab,
481
        StyleCursor::Grabbing,
482
        StyleCursor::Help,
483
        StyleCursor::Move,
484
        StyleCursor::NResize,
485
        StyleCursor::NsResize,
486
        StyleCursor::NeswResize,
487
        StyleCursor::NwseResize,
488
        StyleCursor::Pointer,
489
        StyleCursor::Progress,
490
        StyleCursor::RowResize,
491
        StyleCursor::SResize,
492
        StyleCursor::SeResize,
493
        StyleCursor::Text,
494
        StyleCursor::Unset,
495
        StyleCursor::VerticalText,
496
        StyleCursor::WResize,
497
        StyleCursor::Wait,
498
        StyleCursor::ZoomIn,
499
        StyleCursor::ZoomOut,
500
    ];
501

            
502
    // ==================================================================
503
    // Fixture preconditions — if these fail, every assertion below is
504
    // meaningless, so they are asserted separately and up front.
505
    // ==================================================================
506

            
507
    #[test]
508
    fn fixture_node_ids_and_cursor_properties_are_what_the_tests_assume() {
509
        let styled = fixture_dom();
510
        let node_data = styled.node_data.as_container();
511
        assert_eq!(
512
            node_data.internal.len(),
513
            NODE_COUNT,
514
            "fixture flatten order changed — the node index constants are stale"
515
        );
516
        assert!(matches!(node_data.internal[BODY].node_type, NodeType::Body));
517
        assert!(node_data.internal[EDITABLE_DIV].is_contenteditable());
518
        assert!(matches!(
519
            node_data.internal[TEXTAREA].node_type,
520
            NodeType::TextArea
521
        ));
522
        assert!(matches!(
523
            node_data.internal[BUTTON].node_type,
524
            NodeType::Button
525
        ));
526

            
527
        // The CSS cascade must actually deliver `cursor` to the property cache,
528
        // otherwise CursorTypeHitTest can never see it.
529
        let styled_nodes = styled.styled_nodes.as_container();
530
        let cache = styled.get_css_property_cache();
531
        let cursor_of = |idx: usize| {
532
            let nid = NodeId::new(idx);
533
            cache
534
                .get_cursor(
535
                    &node_data.internal[idx],
536
                    &nid,
537
                    &styled_nodes.internal[idx].styled_node_state,
538
                )
539
                .and_then(|p| p.get_property().copied())
540
        };
541
        assert_eq!(cursor_of(POINTER_DIV), Some(StyleCursor::Pointer));
542
        assert_eq!(cursor_of(CROSSHAIR_DIV), Some(StyleCursor::Crosshair));
543
        assert_eq!(cursor_of(DEFAULT_CURSOR_DIV), Some(StyleCursor::Default));
544
        assert_eq!(
545
            cursor_of(PLAIN_DIV),
546
            None,
547
            "a plain div must have no cursor property, or the contenteditable / text-child \
548
             fallbacks are unreachable"
549
        );
550
        assert_eq!(
551
            cursor_of(EDITABLE_DIV),
552
            None,
553
            "contenteditable must NOT get a cursor from CSS — the I-beam has to come from the \
554
             node-data fallback branch"
555
        );
556
    }
557

            
558
    // ==================================================================
559
    // translate_cursor_type — total, injective, u8-saturating
560
    // ==================================================================
561

            
562
    #[test]
563
    fn translate_cursor_type_maps_every_variant_to_its_documented_icon() {
564
        let expected = [
565
            (CursorType::Default, MouseCursorType::Default),
566
            (CursorType::Pointer, MouseCursorType::Hand),
567
            (CursorType::Text, MouseCursorType::Text),
568
            (CursorType::Crosshair, MouseCursorType::Crosshair),
569
            (CursorType::Move, MouseCursorType::Move),
570
            (CursorType::NotAllowed, MouseCursorType::NotAllowed),
571
            (CursorType::Grab, MouseCursorType::Grab),
572
            (CursorType::Grabbing, MouseCursorType::Grabbing),
573
            (CursorType::EResize, MouseCursorType::EResize),
574
            (CursorType::WResize, MouseCursorType::WResize),
575
            (CursorType::NResize, MouseCursorType::NResize),
576
            (CursorType::SResize, MouseCursorType::SResize),
577
            (CursorType::EwResize, MouseCursorType::EwResize),
578
            (CursorType::NsResize, MouseCursorType::NsResize),
579
            (CursorType::NeswResize, MouseCursorType::NeswResize),
580
            (CursorType::NwseResize, MouseCursorType::NwseResize),
581
            (CursorType::ColResize, MouseCursorType::ColResize),
582
            (CursorType::RowResize, MouseCursorType::RowResize),
583
            (CursorType::Wait, MouseCursorType::Wait),
584
            (CursorType::Help, MouseCursorType::Help),
585
            (CursorType::Progress, MouseCursorType::Progress),
586
        ];
587
        assert_eq!(expected.len(), ALL_CURSOR_TYPES.len());
588
        for (input, want) in expected {
589
            assert_eq!(translate_cursor_type(input), want, "{input:?}");
590
        }
591
    }
592

            
593
    #[test]
594
    fn translate_cursor_type_is_injective_so_no_hit_tag_is_aliased() {
595
        // Two distinct hit-test tags must never collapse onto the same icon:
596
        // `CursorTypeHitTest::new` treats `MouseCursorType::Default` as "no
597
        // cursor here", so an accidental alias onto Default would silently drop
598
        // a text run's cursor.
599
        let mut seen = std::collections::BTreeSet::new();
600
        for ct in ALL_CURSOR_TYPES {
601
            assert!(
602
                seen.insert(translate_cursor_type(ct)),
603
                "{ct:?} aliases an icon already produced by another CursorType"
604
            );
605
        }
606
        assert_eq!(seen.len(), ALL_CURSOR_TYPES.len());
607
    }
608

            
609
    #[test]
610
    fn only_cursor_type_default_translates_to_the_default_icon() {
611
        for ct in ALL_CURSOR_TYPES {
612
            let is_default_icon = translate_cursor_type(ct) == MouseCursorType::Default;
613
            assert_eq!(
614
                is_default_icon,
615
                ct == CursorType::Default,
616
                "{ct:?}: a non-Default CursorType that maps to the Default icon would be silently \
617
                 skipped by CursorTypeHitTest::new"
618
            );
619
        }
620
    }
621

            
622
    #[test]
623
    fn cursor_type_round_trips_through_its_u8_discriminant() {
624
        for ct in ALL_CURSOR_TYPES {
625
            assert_eq!(CursorType::from_u8(ct as u8), ct, "{ct:?}");
626
        }
627
    }
628

            
629
    #[test]
630
    fn every_u8_tag_byte_decodes_and_translates_without_panicking() {
631
        // The cursor type is carried in the low byte of a WebRender ItemTag, so
632
        // any of the 256 byte values can reach `from_u8` from a stale/corrupt
633
        // display list. Out-of-range bytes must saturate to Default, not panic.
634
        for byte in 0u8..=u8::MAX {
635
            let ct = CursorType::from_u8(byte);
636
            let icon = translate_cursor_type(ct);
637
            if byte > 20 {
638
                assert_eq!(ct, CursorType::Default, "byte {byte} should saturate");
639
                assert_eq!(icon, MouseCursorType::Default, "byte {byte}");
640
            } else {
641
                assert_eq!(ct as u8, byte, "byte {byte} must decode to itself");
642
            }
643
        }
644
    }
645

            
646
    // ==================================================================
647
    // translate_cursor — total over StyleCursor
648
    // ==================================================================
649

            
650
    #[test]
651
    fn translate_cursor_maps_every_style_cursor_to_its_documented_icon() {
652
        let expected = [
653
            (StyleCursor::Alias, MouseCursorType::Alias),
654
            (StyleCursor::AllScroll, MouseCursorType::AllScroll),
655
            (StyleCursor::Cell, MouseCursorType::Cell),
656
            (StyleCursor::ColResize, MouseCursorType::ColResize),
657
            (StyleCursor::ContextMenu, MouseCursorType::ContextMenu),
658
            (StyleCursor::Copy, MouseCursorType::Copy),
659
            (StyleCursor::Crosshair, MouseCursorType::Crosshair),
660
            (StyleCursor::Default, MouseCursorType::Default),
661
            (StyleCursor::EResize, MouseCursorType::EResize),
662
            (StyleCursor::EwResize, MouseCursorType::EwResize),
663
            (StyleCursor::Grab, MouseCursorType::Grab),
664
            (StyleCursor::Grabbing, MouseCursorType::Grabbing),
665
            (StyleCursor::Help, MouseCursorType::Help),
666
            (StyleCursor::Move, MouseCursorType::Move),
667
            (StyleCursor::NResize, MouseCursorType::NResize),
668
            (StyleCursor::NsResize, MouseCursorType::NsResize),
669
            (StyleCursor::NeswResize, MouseCursorType::NeswResize),
670
            (StyleCursor::NwseResize, MouseCursorType::NwseResize),
671
            (StyleCursor::Pointer, MouseCursorType::Hand),
672
            (StyleCursor::Progress, MouseCursorType::Progress),
673
            (StyleCursor::RowResize, MouseCursorType::RowResize),
674
            (StyleCursor::SResize, MouseCursorType::SResize),
675
            (StyleCursor::SeResize, MouseCursorType::SeResize),
676
            (StyleCursor::Text, MouseCursorType::Text),
677
            (StyleCursor::Unset, MouseCursorType::Default),
678
            (StyleCursor::VerticalText, MouseCursorType::VerticalText),
679
            (StyleCursor::WResize, MouseCursorType::WResize),
680
            (StyleCursor::Wait, MouseCursorType::Wait),
681
            (StyleCursor::ZoomIn, MouseCursorType::ZoomIn),
682
            (StyleCursor::ZoomOut, MouseCursorType::ZoomOut),
683
        ];
684
        assert_eq!(expected.len(), ALL_STYLE_CURSORS.len());
685
        for (input, want) in expected {
686
            assert_eq!(translate_cursor(input), want, "{input:?}");
687
        }
688
    }
689

            
690
    #[test]
691
    fn default_and_unset_are_the_only_style_cursors_that_yield_the_default_icon() {
692
        for sc in ALL_STYLE_CURSORS {
693
            let is_default_icon = translate_cursor(sc) == MouseCursorType::Default;
694
            let expected = matches!(sc, StyleCursor::Default | StyleCursor::Unset);
695
            assert_eq!(is_default_icon, expected, "{sc:?}");
696
        }
697
    }
698

            
699
    #[test]
700
    fn the_two_translators_agree_on_the_cursors_they_both_understand() {
701
        // A text run's cursor comes from the hit-test tag (CursorType) while its
702
        // container's comes from CSS (StyleCursor). If the two tables disagreed,
703
        // the icon would flicker depending on which one won the depth race.
704
        let shared = [
705
            (CursorType::Default, StyleCursor::Default),
706
            (CursorType::Pointer, StyleCursor::Pointer),
707
            (CursorType::Text, StyleCursor::Text),
708
            (CursorType::Crosshair, StyleCursor::Crosshair),
709
            (CursorType::Move, StyleCursor::Move),
710
            (CursorType::Grab, StyleCursor::Grab),
711
            (CursorType::Grabbing, StyleCursor::Grabbing),
712
            (CursorType::EResize, StyleCursor::EResize),
713
            (CursorType::WResize, StyleCursor::WResize),
714
            (CursorType::NResize, StyleCursor::NResize),
715
            (CursorType::SResize, StyleCursor::SResize),
716
            (CursorType::EwResize, StyleCursor::EwResize),
717
            (CursorType::NsResize, StyleCursor::NsResize),
718
            (CursorType::NeswResize, StyleCursor::NeswResize),
719
            (CursorType::NwseResize, StyleCursor::NwseResize),
720
            (CursorType::ColResize, StyleCursor::ColResize),
721
            (CursorType::RowResize, StyleCursor::RowResize),
722
            (CursorType::Wait, StyleCursor::Wait),
723
            (CursorType::Help, StyleCursor::Help),
724
            (CursorType::Progress, StyleCursor::Progress),
725
        ];
726
        for (ct, sc) in shared {
727
            assert_eq!(
728
                translate_cursor_type(ct),
729
                translate_cursor(sc),
730
                "{ct:?} / {sc:?} disagree"
731
            );
732
        }
733
    }
734

            
735
    // ==================================================================
736
    // CursorTypeHitTest::new — degenerate inputs
737
    // ==================================================================
738

            
739
    #[test]
740
    fn empty_hit_test_against_an_empty_window_yields_the_default_cursor() {
741
        let lw = LayoutWindow::new(FcFontCache::default()).expect("LayoutWindow::new failed");
742
        let result = CursorTypeHitTest::new(&FullHitTest::empty(None), &lw);
743
        assert_eq!(result, CursorTypeHitTest::default());
744
        assert_invariant(&result);
745
    }
746

            
747
    #[test]
748
    fn hits_against_a_dom_without_a_layout_result_are_skipped() {
749
        // A hovered DomId with no layout result (child DOM torn down between
750
        // frames) must be skipped, not indexed into.
751
        let lw = window_with(&[DomId::ROOT_ID]);
752
        let hit = make_hit_test(&[
753
            (dom(1), &[(POINTER_DIV, 0)], &[]),
754
            (
755
                dom(usize::MAX),
756
                &[(BUTTON, 0)],
757
                &[(PLAIN_DIV, CursorType::Text, 0)],
758
            ),
759
        ]);
760
        let result = CursorTypeHitTest::new(&hit, &lw);
761
        assert_eq!(result.cursor_node, None);
762
        assert_eq!(result.cursor_icon, MouseCursorType::Default);
763
        assert_invariant(&result);
764
    }
765

            
766
    #[test]
767
    fn stale_node_ids_past_the_end_of_the_dom_are_skipped_instead_of_panicking() {
768
        // Regression: a VirtualView child rebuilt with fewer nodes leaves the
769
        // hover state holding last frame's (larger) NodeIds. Blind indexing
770
        // panicked with "len is 25 but the index is 27".
771
        let stale = [
772
            (NODE_COUNT, 0u32),
773
            (NODE_COUNT + 1, 1),
774
            (9_999, 2),
775
            (usize::MAX, 3),
776
        ];
777
        let result = resolve(&stale, &[]);
778
        assert_eq!(result.cursor_node, None);
779
        assert_eq!(result.cursor_icon, MouseCursorType::Default);
780
        assert_invariant(&result);
781
    }
782

            
783
    #[test]
784
    fn a_live_node_behind_a_stale_one_still_resolves() {
785
        // The stale id is frontmost (depth 0) but must not consume the search:
786
        // the live pointer div behind it still gets to set the cursor.
787
        let result = resolve(&[(usize::MAX, 0), (POINTER_DIV, 1)], &[]);
788
        assert_eq!(result.cursor_node, root_node(POINTER_DIV));
789
        assert_eq!(result.cursor_icon, MouseCursorType::Hand);
790
    }
791

            
792
    #[test]
793
    fn a_stale_node_id_in_a_text_run_hit_is_reported_verbatim() {
794
        // cursor_hit_test_nodes are NOT bounds-checked against the DOM (the
795
        // cursor type is carried in the tag, so no node lookup happens). A stale
796
        // id therefore surfaces as `cursor_node` — harmless for the icon, but
797
        // callers must not assume `cursor_node` indexes a live node.
798
        let result = resolve(&[], &[(usize::MAX, CursorType::Text, 0)]);
799
        assert_eq!(result.cursor_icon, MouseCursorType::Text);
800
        assert_eq!(result.cursor_node, root_node(usize::MAX));
801
    }
802

            
803
    #[test]
804
    fn a_thousand_hits_with_extreme_depths_do_not_panic() {
805
        let mut regular = Vec::new();
806
        let mut cursors = Vec::new();
807
        for i in 0..1000usize {
808
            // Mostly stale ids, alternating extreme depths.
809
            let depth = match i % 4 {
810
                0 => 0,
811
                1 => u32::MAX,
812
                2 => u32::MAX - 1,
813
                _ => i as u32,
814
            };
815
            regular.push((i, depth));
816
            cursors.push((i, CursorType::from_u8((i % 256) as u8), depth));
817
        }
818
        let result = resolve(&regular, &cursors);
819
        assert_invariant(&result);
820
        // Whatever wins the depth race, the resolution must be a decision and
821
        // not a crash — and it must be stable across runs.
822
        assert_eq!(result, resolve(&regular, &cursors));
823
    }
824

            
825
    // ==================================================================
826
    // CursorTypeHitTest::new — depth resolution
827
    // ==================================================================
828

            
829
    #[test]
830
    fn the_frontmost_node_wins_regardless_of_iteration_order() {
831
        // Lower NodeId iterated first, but the deeper one must lose either way.
832
        let front_is_last = resolve(&[(POINTER_DIV, 5), (CROSSHAIR_DIV, 0)], &[]);
833
        assert_eq!(front_is_last.cursor_node, root_node(CROSSHAIR_DIV));
834
        assert_eq!(front_is_last.cursor_icon, MouseCursorType::Crosshair);
835

            
836
        let front_is_first = resolve(&[(POINTER_DIV, 0), (CROSSHAIR_DIV, 5)], &[]);
837
        assert_eq!(front_is_first.cursor_node, root_node(POINTER_DIV));
838
        assert_eq!(front_is_first.cursor_icon, MouseCursorType::Hand);
839
    }
840

            
841
    #[test]
842
    fn on_a_depth_tie_the_first_iterated_node_keeps_the_cursor() {
843
        // The guard is `node_depth >= best_depth`, so a tie never replaces the
844
        // incumbent: with equal depths the lowest NodeId (BTreeMap order) wins.
845
        let result = resolve(&[(POINTER_DIV, 3), (CROSSHAIR_DIV, 3)], &[]);
846
        assert_eq!(result.cursor_node, root_node(POINTER_DIV));
847
        assert_eq!(result.cursor_icon, MouseCursorType::Hand);
848
    }
849

            
850
    #[test]
851
    fn a_hit_at_depth_u32_max_can_never_be_selected() {
852
        // BOUNDARY: best_depth is seeded with u32::MAX and the guard is `>=`, so
853
        // depth == u32::MAX is unreachable while u32::MAX - 1 is fine. Depths
854
        // that large are not producible by the real hit-tester, but the seed is
855
        // an in-band sentinel — worth pinning down.
856
        let at_max = resolve(&[(POINTER_DIV, u32::MAX)], &[]);
857
        assert_eq!(at_max.cursor_node, None);
858
        assert_eq!(at_max.cursor_icon, MouseCursorType::Default);
859
        assert_invariant(&at_max);
860

            
861
        let below_max = resolve(&[(POINTER_DIV, u32::MAX - 1)], &[]);
862
        assert_eq!(below_max.cursor_node, root_node(POINTER_DIV));
863
        assert_eq!(below_max.cursor_icon, MouseCursorType::Hand);
864
    }
865

            
866
    #[test]
867
    fn a_text_run_cursor_shadows_a_regular_node_at_the_same_depth() {
868
        // cursor_hit_test_nodes are processed first, so at equal depth the text
869
        // run's tag wins and the CSS cursor behind it never applies.
870
        let result = resolve(&[(POINTER_DIV, 2)], &[(PLAIN_DIV, CursorType::Text, 2)]);
871
        assert_eq!(result.cursor_icon, MouseCursorType::Text);
872
        assert_eq!(result.cursor_node, root_node(PLAIN_DIV));
873
    }
874

            
875
    #[test]
876
    fn a_regular_node_strictly_in_front_of_a_text_run_wins() {
877
        let result = resolve(&[(POINTER_DIV, 1)], &[(PLAIN_DIV, CursorType::Text, 2)]);
878
        assert_eq!(result.cursor_icon, MouseCursorType::Hand);
879
        assert_eq!(result.cursor_node, root_node(POINTER_DIV));
880
    }
881

            
882
    #[test]
883
    fn a_default_text_run_cursor_does_not_shadow_the_container_behind_it() {
884
        // A frontmost text run tagged `CursorType::Default` must neither set the
885
        // icon nor lower best_depth — otherwise the button behind it (depth 5)
886
        // would lose its cursor:pointer.
887
        let result = resolve(&[(POINTER_DIV, 5)], &[(PLAIN_DIV, CursorType::Default, 0)]);
888
        assert_eq!(result.cursor_icon, MouseCursorType::Hand);
889
        assert_eq!(result.cursor_node, root_node(POINTER_DIV));
890
    }
891

            
892
    // ==================================================================
893
    // CursorTypeHitTest::new — per-node cursor sources
894
    // ==================================================================
895

            
896
    #[test]
897
    fn a_node_without_any_cursor_property_leaves_the_cursor_unset() {
898
        let result = resolve(&[(BODY, 1), (PLAIN_DIV, 0)], &[]);
899
        assert_eq!(result.cursor_node, None);
900
        assert_eq!(result.cursor_icon, MouseCursorType::Default);
901
        assert_invariant(&result);
902
    }
903

            
904
    #[test]
905
    fn a_contenteditable_node_gets_the_ibeam_without_any_css() {
906
        let result = resolve(&[(EDITABLE_DIV, 0)], &[]);
907
        assert_eq!(result.cursor_node, root_node(EDITABLE_DIV));
908
        assert_eq!(result.cursor_icon, MouseCursorType::Text);
909
    }
910

            
911
    #[test]
912
    fn a_textarea_gets_the_ibeam() {
913
        let result = resolve(&[(TEXTAREA, 0)], &[]);
914
        assert_eq!(result.cursor_node, root_node(TEXTAREA));
915
        assert_eq!(result.cursor_icon, MouseCursorType::Text);
916
    }
917

            
918
    #[test]
919
    fn a_button_gets_the_hand_from_the_ua_stylesheet() {
920
        let result = resolve(&[(BUTTON, 0)], &[]);
921
        assert_eq!(result.cursor_node, root_node(BUTTON));
922
        assert_eq!(result.cursor_icon, MouseCursorType::Hand);
923
    }
924

            
925
    #[test]
926
    fn an_explicit_cursor_default_is_recorded_and_shadows_nodes_behind_it() {
927
        // Contradicts the doc comment ("The node that has a NON-DEFAULT cursor
928
        // property"): an explicit `cursor: default` sets cursor_node = Some(..)
929
        // with the Default icon. Behaviourally it is still right — the frontmost
930
        // explicit cursor must win — but consumers cannot rely on
931
        // `cursor_node.is_some()` meaning "non-default cursor".
932
        let alone = resolve(&[(DEFAULT_CURSOR_DIV, 0)], &[]);
933
        assert_eq!(alone.cursor_node, root_node(DEFAULT_CURSOR_DIV));
934
        assert_eq!(alone.cursor_icon, MouseCursorType::Default);
935

            
936
        let over_pointer = resolve(&[(DEFAULT_CURSOR_DIV, 0), (POINTER_DIV, 1)], &[]);
937
        assert_eq!(over_pointer.cursor_node, root_node(DEFAULT_CURSOR_DIV));
938
        assert_eq!(over_pointer.cursor_icon, MouseCursorType::Default);
939
    }
940

            
941
    #[test]
942
    fn an_editable_node_in_front_of_a_pointer_node_still_wins() {
943
        let result = resolve(&[(EDITABLE_DIV, 0), (BUTTON, 1)], &[]);
944
        assert_eq!(result.cursor_node, root_node(EDITABLE_DIV));
945
        assert_eq!(result.cursor_icon, MouseCursorType::Text);
946
    }
947

            
948
    // ==================================================================
949
    // CursorTypeHitTest::new — multiple DOMs
950
    // ==================================================================
951

            
952
    #[test]
953
    fn the_frontmost_dom_wins_not_the_lowest_dom_id() {
954
        let lw = window_with(&[DomId::ROOT_ID, dom(1)]);
955

            
956
        // Frontmost hit lives in the *second* DOM.
957
        let hit = make_hit_test(&[
958
            (DomId::ROOT_ID, &[(POINTER_DIV, 4)], &[]),
959
            (dom(1), &[(CROSSHAIR_DIV, 0)], &[]),
960
        ]);
961
        let result = CursorTypeHitTest::new(&hit, &lw);
962
        assert_eq!(
963
            result.cursor_node,
964
            Some((dom(1), NodeId::new(CROSSHAIR_DIV)))
965
        );
966
        assert_eq!(result.cursor_icon, MouseCursorType::Crosshair);
967

            
968
        // ... and in the *first* DOM: the later DOM must not clobber it.
969
        let hit = make_hit_test(&[
970
            (DomId::ROOT_ID, &[(CROSSHAIR_DIV, 0)], &[]),
971
            (dom(1), &[(POINTER_DIV, 4)], &[]),
972
        ]);
973
        let result = CursorTypeHitTest::new(&hit, &lw);
974
        assert_eq!(result.cursor_node, root_node(CROSSHAIR_DIV));
975
        assert_eq!(result.cursor_icon, MouseCursorType::Crosshair);
976
    }
977

            
978
    #[test]
979
    fn a_dom_with_a_layout_result_is_used_even_when_a_sibling_dom_is_missing() {
980
        let lw = window_with(&[dom(2)]);
981
        let hit = make_hit_test(&[
982
            (DomId::ROOT_ID, &[(POINTER_DIV, 0)], &[]),
983
            (dom(2), &[(BUTTON, 7)], &[]),
984
        ]);
985
        let result = CursorTypeHitTest::new(&hit, &lw);
986
        assert_eq!(result.cursor_node, Some((dom(2), NodeId::new(BUTTON))));
987
        assert_eq!(result.cursor_icon, MouseCursorType::Hand);
988
    }
989

            
990
    #[test]
991
    fn the_result_is_a_pure_function_of_the_hit_test() {
992
        // Same input twice => same output (no interior mutation of the window).
993
        let lw = window_with(&[DomId::ROOT_ID]);
994
        let hit = make_hit_test(&[(
995
            DomId::ROOT_ID,
996
            &[(POINTER_DIV, 3), (BUTTON, 9)],
997
            &[(TEXTAREA, CursorType::Text, 4)],
998
        )]);
999
        let first = CursorTypeHitTest::new(&hit, &lw);
        let second = CursorTypeHitTest::new(&hit, &lw);
        assert_eq!(first, second);
        assert_eq!(first.cursor_icon, MouseCursorType::Hand);
    }
}