1
//! Hit-test result types for determining which DOM nodes are under the cursor,
2
//! scroll state tracking, and pipeline/document identification. These types
3
//! feed into the event dispatch system.
4

            
5
use alloc::{collections::BTreeMap, vec::Vec};
6
use core::{
7
    fmt,
8
    sync::atomic::{AtomicU32, Ordering as AtomicOrdering},
9
};
10

            
11
use crate::{
12
    dom::{
13
        DomId, DomNodeHash, DomNodeId, OptionDomNodeId, ScrollTagId, ScrollbarOrientation, TagId,
14
    },
15
    geom::{LogicalPosition, LogicalRect, LogicalSize},
16
    id::NodeId,
17
    resources::IdNamespace,
18
    window::MouseCursorType,
19
    OrderedMap,
20
};
21

            
22
/// Result of a hit test against a single DOM, containing all nodes hit
23
/// by the cursor along with scroll, scrollbar, and cursor-type information.
24
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd)]
25
pub struct HitTest {
26
    pub regular_hit_test_nodes: BTreeMap<NodeId, HitTestItem>,
27
    pub scroll_hit_test_nodes: BTreeMap<NodeId, ScrollHitTestItem>,
28
    /// Hit test results for scrollbar components.
29
    pub scrollbar_hit_test_nodes: BTreeMap<ScrollbarHitId, ScrollbarHitTestItem>,
30
    /// Hit test results for cursor areas (text runs with cursor property).
31
    /// Maps `NodeId` to (`CursorType`, `hit_depth`) - the cursor type and z-depth of the hit.
32
    pub cursor_hit_test_nodes: BTreeMap<NodeId, CursorHitTestItem>,
33
}
34

            
35
/// Hit test item for cursor areas (determines which cursor icon to show).
36
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd)]
37
#[repr(C)]
38
pub struct CursorHitTestItem {
39
    pub cursor_type: CursorType,
40
    pub hit_depth: u32,
41
    pub point_in_viewport: LogicalPosition,
42
}
43

            
44
impl HitTest {
45
    #[must_use]
46
68252
    pub const fn empty() -> Self {
47
68252
        Self {
48
68252
            regular_hit_test_nodes: BTreeMap::new(),
49
68252
            scroll_hit_test_nodes: BTreeMap::new(),
50
68252
            scrollbar_hit_test_nodes: BTreeMap::new(),
51
68252
            cursor_hit_test_nodes: BTreeMap::new(),
52
68252
        }
53
68252
    }
54
    #[must_use]
55
5
    pub fn is_empty(&self) -> bool {
56
5
        self.regular_hit_test_nodes.is_empty()
57
4
            && self.scroll_hit_test_nodes.is_empty()
58
3
            && self.scrollbar_hit_test_nodes.is_empty()
59
2
            && self.cursor_hit_test_nodes.is_empty()
60
5
    }
61
}
62

            
63
/// Unique identifier for a specific component of a scrollbar.
64
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
65
#[repr(C, u8)]
66
pub enum ScrollbarHitId {
67
    VerticalTrack(DomId, NodeId),
68
    VerticalThumb(DomId, NodeId),
69
    HorizontalTrack(DomId, NodeId),
70
    HorizontalThumb(DomId, NodeId),
71
}
72

            
73
/// Hit test item specifically for scrollbar components.
74
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd)]
75
#[repr(C)]
76
pub struct ScrollbarHitTestItem {
77
    pub point_in_viewport: LogicalPosition,
78
    pub point_relative_to_item: LogicalPosition,
79
    pub orientation: ScrollbarOrientation,
80
}
81

            
82
/// Scroll frame identifier combining a unique `u64` tag with its owning `PipelineId`.
83
#[derive(Copy, Clone, Eq, Hash, PartialEq, Ord, PartialOrd)]
84
#[repr(C)]
85
pub struct ExternalScrollId(pub u64, pub PipelineId);
86

            
87
impl ::core::fmt::Display for ExternalScrollId {
88
4
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
89
4
        write!(f, "ExternalScrollId({})", self.0)
90
4
    }
91
}
92

            
93
impl ::core::fmt::Debug for ExternalScrollId {
94
2
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
95
2
        write!(f, "{self}")
96
2
    }
97
}
98

            
99
/// A node whose content overflows its parent, requiring scroll handling.
100
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd)]
101
pub struct OverflowingScrollNode {
102
    pub parent_rect: LogicalRect,
103
    pub child_rect: LogicalRect,
104
    pub virtual_child_rect: LogicalRect,
105
    pub parent_external_scroll_id: ExternalScrollId,
106
    pub parent_dom_hash: DomNodeHash,
107
    pub scroll_tag_id: ScrollTagId,
108
}
109

            
110
impl Default for OverflowingScrollNode {
111
22
    fn default() -> Self {
112
        use crate::dom::TagId;
113
22
        Self {
114
22
            parent_rect: LogicalRect::zero(),
115
22
            child_rect: LogicalRect::zero(),
116
22
            virtual_child_rect: LogicalRect::zero(),
117
22
            parent_external_scroll_id: ExternalScrollId(0, PipelineId::DUMMY),
118
22
            parent_dom_hash: DomNodeHash { inner: 0 },
119
22
            scroll_tag_id: ScrollTagId {
120
22
                inner: TagId { inner: 0 },
121
22
            },
122
22
        }
123
22
    }
124
}
125

            
126
/// Extra source identifier within a pipeline, allowing multiple independent
127
/// subsystems to generate `PipelineId` values without collision.
128
///
129
/// All pipelines still share the same `IdNamespace` and `DocumentId`.
130
pub type PipelineSourceId = u32;
131

            
132
/// Information about a scroll frame, given to the user by the framework.
133
///
134
/// The two rects are NOT in the same coordinate space — never subtract one
135
/// origin from the other. That silent ambiguity put the scrollbar thumb
136
/// partway down the track for every container not at the window origin.
137
/// See `ScrollManager::get_scroll_states_for_dom` for the producer.
138
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd)]
139
pub struct ScrollPosition {
140
    /// The scroll container's border box in ABSOLUTE window coordinates.
141
    /// `size` is the scrollport ("how big is the parent container", so
142
    /// "scroll to left edge" can be implemented); `origin` is where that
143
    /// container sits on screen and is only meaningful to scroll-into-view.
144
    pub parent_rect: LogicalRect,
145
    /// `size` = the scrollable content ("the union of all children", or the
146
    /// `VirtualView` virtual size when one was reported).
147
    /// `origin` = the SCROLL OFFSET ITSELF — distance already scrolled from
148
    /// the scroll origin, normally clamped to `[0, content − container]`.
149
    /// It is NOT an absolute position and NOT relative to
150
    /// `parent_rect.origin`; content paints at `position − origin`.
151
    pub children_rect: LogicalRect,
152
}
153

            
154
/// Identifies a document within a namespace, used for multi-document rendering.
155
#[derive(Copy, Clone, Eq, Hash, PartialEq, PartialOrd, Ord)]
156
pub struct DocumentId {
157
    pub namespace_id: IdNamespace,
158
    pub id: u32,
159
}
160

            
161
impl ::core::fmt::Display for DocumentId {
162
5
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
163
5
        write!(
164
5
            f,
165
5
            "DocumentId {{ ns: {}, id: {} }}",
166
            self.namespace_id, self.id
167
        )
168
5
    }
169
}
170

            
171
impl ::core::fmt::Debug for DocumentId {
172
2
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
173
2
        write!(f, "{self}")
174
2
    }
175
}
176

            
177
/// Identifies a rendering pipeline by source and sequence number.
178
#[derive(Copy, Clone, Eq, Hash, PartialEq, PartialOrd, Ord)]
179
pub struct PipelineId(pub PipelineSourceId, pub u32);
180

            
181
impl ::core::fmt::Display for PipelineId {
182
3
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
183
3
        write!(f, "PipelineId({}, {})", self.0, self.1)
184
3
    }
185
}
186

            
187
impl ::core::fmt::Debug for PipelineId {
188
1
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
189
1
        write!(f, "{self}")
190
1
    }
191
}
192

            
193
static LAST_PIPELINE_ID: AtomicU32 = AtomicU32::new(0);
194

            
195
impl Default for PipelineId {
196
1
    fn default() -> Self {
197
1
        Self::new()
198
1
    }
199
}
200

            
201
impl PipelineId {
202
    pub const DUMMY: Self = Self(0, 0);
203

            
204
3
    pub fn new() -> Self {
205
3
        Self(LAST_PIPELINE_ID.fetch_add(1, AtomicOrdering::SeqCst), 0)
206
3
    }
207
}
208

            
209
/// A single hit-test result for a regular (non-scroll) DOM node.
210
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd)]
211
pub struct HitTestItem {
212
    /// The hit point in the coordinate space of the "viewport" of the display item.
213
    /// The viewport is the scroll node formed by the root reference frame of the display item's
214
    /// pipeline.
215
    pub point_in_viewport: LogicalPosition,
216
    /// The hit point relative to this node's static CONTENT-box origin, with
217
    /// the node's own scroll offset NOT applied.
218
    ///
219
    /// ## Why this space, and why it is typed
220
    ///
221
    /// The two hosts used to disagree here. `WebRender` reports the point
222
    /// relative to the hit RECT, which azul pushes before the scroll frame —
223
    /// i.e. [`BorderBoxLocal`](crate::spaces::BorderBoxLocal) — while the CPU
224
    /// tester used in headless E2E subtracted `padding + border` and reported
225
    /// [`ContentBoxLocal`]. Same click, two answers, differing by exactly the
226
    /// node's content inset. It stayed latent only because the default
227
    /// `TextInput`'s value `<p>` sets neither padding nor border; it goes live
228
    /// for any padded editable.
229
    ///
230
    /// Both producers now emit `ContentBoxLocal`, because that is the space
231
    /// the consumer that cares (`UnifiedLayout::hittest_cursor`, via
232
    /// `LayoutWindow::ifc_local_point`) actually needs. Consumers wanting the
233
    /// border-box-relative point the public
234
    /// `CallbackInfo::get_cursor_relative_to_node` promises convert back with
235
    /// [`ContentBoxLocal::to_border_box_local`].
236
    ///
237
    /// [`ContentBoxLocal`]: crate::spaces::ContentBoxLocal
238
    /// [`ContentBoxLocal::to_border_box_local`]: crate::spaces::ContentBoxLocal::to_border_box_local
239
    pub point_relative_to_item: crate::spaces::ContentBoxLocal,
240
    /// Necessary to easily get the nearest `VirtualView` node
241
    pub is_focusable: bool,
242
    /// If this hit is a `VirtualView` node, stores the `VirtualViews` `DomId` + the origin of the
243
    /// `VirtualView`
244
    pub is_virtual_view_hit: Option<(DomId, LogicalPosition)>,
245
    /// Z-order depth from `WebRender` hit test (0 = frontmost/topmost in z-order).
246
    /// Lower values are closer to the user. This preserves the ordering from
247
    /// `WebRender`'s hit test results which returns items front-to-back.
248
    pub hit_depth: u32,
249
}
250

            
251
/// A hit-test result for a scrollable DOM node.
252
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd)]
253
pub struct ScrollHitTestItem {
254
    /// The hit point in the coordinate space of the "viewport" of the display item.
255
    /// The viewport is the scroll node formed by the root reference frame of the display item's
256
    /// pipeline.
257
    pub point_in_viewport: LogicalPosition,
258
    /// The hit point relative to the container's static BORDER-box origin,
259
    /// with its own scroll NOT applied — i.e. where in its scrollPORT the
260
    /// pointer is.
261
    ///
262
    /// Deliberately a different space from [`HitTestItem::point_relative_to_item`]:
263
    /// this one is about the scroll box's chrome (which edge is the pointer
264
    /// near, is it over the scrollbar gutter), not about its text content, and
265
    /// scroll geometry is measured against the border box everywhere else.
266
    pub point_relative_to_item: crate::spaces::BorderBoxLocal,
267
    /// If this hit is a `VirtualView` node, stores the `VirtualViews` `DomId` + the origin of the
268
    /// `VirtualView`
269
    pub scroll_node: OverflowingScrollNode,
270
}
271

            
272
/// Map of active scroll states, keyed by their external scroll ID.
273
#[derive(Debug, Default)]
274
pub struct ScrollStates(pub OrderedMap<ExternalScrollId, ScrollState>);
275

            
276
impl ScrollStates {
277
    #[must_use]
278
6
    pub fn new() -> Self {
279
6
        Self::default()
280
6
    }
281

            
282
    #[must_use]
283
11
    pub fn get_scroll_position(&self, scroll_id: &ExternalScrollId) -> Option<LogicalPosition> {
284
11
        self.0.get(scroll_id).map(ScrollState::get)
285
11
    }
286

            
287
    /// Set the scroll amount - does not update the `entry.used_this_frame`,
288
    /// since that is only relevant when we are actually querying the renderer.
289
3
    pub fn set_scroll_position(
290
3
        &mut self,
291
3
        node: &OverflowingScrollNode,
292
3
        scroll_position: LogicalPosition,
293
3
    ) {
294
3
        let max_scroll = max_scroll_rect(node);
295
3
        self.0
296
3
            .entry(node.parent_external_scroll_id)
297
3
            .or_default()
298
3
            .set(scroll_position.x, scroll_position.y, &max_scroll);
299
3
    }
300

            
301
    /// Updating (add to) the existing scroll amount does not update the
302
    /// `entry.used_this_frame`, since that is only relevant when we are
303
    /// actually querying the renderer.
304
7
    pub fn scroll_node(
305
7
        &mut self,
306
7
        node: &OverflowingScrollNode,
307
7
        scroll_by_x: f32,
308
7
        scroll_by_y: f32,
309
7
    ) {
310
7
        let max_scroll = max_scroll_rect(node);
311
7
        self.0
312
7
            .entry(node.parent_external_scroll_id)
313
7
            .or_default()
314
7
            .add(scroll_by_x, scroll_by_y, &max_scroll);
315
7
    }
316
}
317

            
318
/// Compute the maximum scrollable range for a scroll node.
319
///
320
/// The maximum scroll offset is `content − viewport` (`child_rect − parent_rect`),
321
/// clamped to `>= 0`. Previously the scroll position was clamped to the full
322
/// content size, which let the content scroll entirely out of view. The returned
323
/// rect keeps `child_rect.origin` and stores the max offset in `size`.
324
18
fn max_scroll_rect(node: &OverflowingScrollNode) -> LogicalRect {
325
18
    LogicalRect::new(
326
18
        node.child_rect.origin,
327
18
        LogicalSize::new(
328
18
            (node.child_rect.size.width - node.parent_rect.size.width).max(0.0),
329
18
            (node.child_rect.size.height - node.parent_rect.size.height).max(0.0),
330
        ),
331
    )
332
18
}
333

            
334
/// Current scroll position for a single scroll frame.
335
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd)]
336
#[repr(C)]
337
pub struct ScrollState {
338
    /// Amount in pixel that the current node is scrolled
339
    pub scroll_position: LogicalPosition,
340
}
341

            
342
impl_option!(
343
    ScrollState,
344
    OptionScrollState,
345
    [Debug, Copy, Clone, PartialEq, Eq, PartialOrd]
346
);
347

            
348
impl ScrollState {
349
    /// Return the current position of the scroll state
350
    #[must_use]
351
44
    pub const fn get(&self) -> LogicalPosition {
352
44
        self.scroll_position
353
44
    }
354

            
355
    /// Add a scroll X / Y onto the existing scroll state.
356
    ///
357
    /// `max_scroll_rect` is the *scroll range* rect: its size is the maximum
358
    /// scrollable offset (`content − viewport`, clamped to `>= 0`), NOT the full
359
    /// content size. See [`ScrollStates::scroll_node`]. Clamping via `.max(0.0)`
360
    /// first also collapses any NaN input to `0.0` (`f32::max` returns the
361
    /// non-NaN operand), so a NaN delta can never poison the scroll position.
362
18
    pub fn add(&mut self, x: f32, y: f32, max_scroll_rect: &LogicalRect) {
363
18
        self.scroll_position.x = (self.scroll_position.x + x)
364
18
            .max(0.0)
365
18
            .min(max_scroll_rect.size.width.max(0.0));
366
18
        self.scroll_position.y = (self.scroll_position.y + y)
367
18
            .max(0.0)
368
18
            .min(max_scroll_rect.size.height.max(0.0));
369
18
    }
370

            
371
    /// Set the scroll state to a new position.
372
    ///
373
    /// `max_scroll_rect` is the *scroll range* rect (see [`ScrollState::add`]).
374
13
    pub const fn set(&mut self, x: f32, y: f32, max_scroll_rect: &LogicalRect) {
375
13
        self.scroll_position.x = x.max(0.0).min(max_scroll_rect.size.width.max(0.0));
376
13
        self.scroll_position.y = y.max(0.0).min(max_scroll_rect.size.height.max(0.0));
377
13
    }
378
}
379

            
380
impl Default for ScrollState {
381
17
    fn default() -> Self {
382
17
        Self {
383
17
            scroll_position: LogicalPosition::zero(),
384
17
        }
385
17
    }
386
}
387

            
388
/// Complete hit-test result across all DOMs, including the currently focused node.
389
#[derive(Debug, Clone, PartialEq, Eq)]
390
pub struct FullHitTest {
391
    pub hovered_nodes: BTreeMap<DomId, HitTest>,
392
    pub focused_node: OptionDomNodeId,
393
}
394

            
395
impl FullHitTest {
396
    /// Every node under the pointer, FRONT TO BACK (9g-ii-e).
397
    ///
398
    /// # Why this exists rather than the struct being exposed
399
    ///
400
    /// `FullHitTest` is a `BTreeMap` of `DomId` to a `HitTest` that is itself
401
    /// four more maps. Exposing that shape across the C ABI needs five map
402
    /// types nothing else would use, and no application wants the shape - it
403
    /// wants the ANSWER: what is under the cursor, nearest first. So the
404
    /// accessors return that, the same trade `get_hid_reports` makes by
405
    /// returning an owned vec rather than a borrowed slice.
406
    ///
407
    /// Ordered by `hit_depth`, which `WebRender` and the CPU tester both fill
408
    /// with a real z-order (0 = frontmost). That is a stronger ordering than
409
    /// the `NodeId` one some call sites use as a proxy: two overlapping
410
    /// absolutely-positioned nodes can have any id relationship, and the one
411
    /// on top is the one with the lower depth.
412
    ///
413
    /// Only the REGULAR hits: scroll frames, scrollbar parts and cursor areas
414
    /// are hit-tested separately and are not nodes an app would call "under
415
    /// the pointer" - a scrollbar is not the content beneath it.
416
    #[must_use]
417
5
    pub fn hovered_node_ids(&self) -> Vec<DomNodeId> {
418
5
        let mut with_depth: Vec<(u32, DomNodeId)> = Vec::new();
419
9
        for (dom_id, hit) in &self.hovered_nodes {
420
11
            for (node_id, item) in &hit.regular_hit_test_nodes {
421
7
                with_depth.push((
422
7
                    item.hit_depth,
423
7
                    DomNodeId {
424
7
                        dom: *dom_id,
425
7
                        node: crate::styled_dom::NodeHierarchyItemId::from_crate_internal(Some(
426
7
                            *node_id,
427
7
                        )),
428
7
                    },
429
7
                ));
430
7
            }
431
        }
432
        // Stable within a depth, so two nodes a backend reported at the same
433
        // z-order keep the order the maps gave them rather than an arbitrary
434
        // one that changes between frames.
435
5
        with_depth.sort_by_key(|(depth, _)| *depth);
436
5
        with_depth.into_iter().map(|(_, id)| id).collect()
437
5
    }
438

            
439
    /// The node nearest the user, or `None` when the pointer is over nothing.
440
    ///
441
    /// What an app almost always means by "the hit test": the topmost regular
442
    /// hit. Cheaper than [`Self::hovered_node_ids`] because it does not sort.
443
    #[must_use]
444
16
    pub fn topmost_node(&self) -> Option<DomNodeId> {
445
16
        let mut best: Option<(u32, DomNodeId)> = None;
446
43
        for (dom_id, hit) in &self.hovered_nodes {
447
57
            for (node_id, item) in &hit.regular_hit_test_nodes {
448
30
                let candidate = DomNodeId {
449
30
                    dom: *dom_id,
450
30
                    node: crate::styled_dom::NodeHierarchyItemId::from_crate_internal(Some(
451
30
                        *node_id,
452
30
                    )),
453
30
                };
454
                // STRICTLY less, so the first node at the frontmost depth wins
455
                // and the answer does not flip between frames for a tie.
456
30
                if best.is_none_or(|(d, _)| item.hit_depth < d) {
457
28
                    best = Some((item.hit_depth, candidate));
458
28
                }
459
            }
460
        }
461
16
        best.map(|(_, id)| id)
462
16
    }
463
}
464

            
465
impl FullHitTest {
466
    /// Create an empty hit-test result
467
    #[must_use]
468
12425
    pub fn empty(focused_node: Option<DomNodeId>) -> Self {
469
12425
        Self {
470
12425
            hovered_nodes: BTreeMap::new(),
471
12425
            focused_node: focused_node.into(),
472
12425
        }
473
12425
    }
474

            
475
    /// Returns `true` if no nodes were hovered (ignores `focused_node`).
476
    #[must_use]
477
5
    pub fn is_empty(&self) -> bool {
478
5
        self.hovered_nodes.is_empty()
479
5
    }
480
}
481

            
482
/// Result of determining which mouse cursor icon to display based on hit-test results.
483
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
484
pub struct CursorTypeHitTest {
485
    /// closest-node is used for determining the cursor: property
486
    /// The node is guaranteed to have a non-default cursor: property,
487
    /// so that the cursor icon can be set accordingly
488
    pub cursor_node: Option<(DomId, NodeId)>,
489
    /// Mouse cursor type to set (if `cursor_node` is None, this is set to
490
    /// `MouseCursorType::Default`)
491
    pub cursor_icon: MouseCursorType,
492
}
493

            
494
// ============================================================================
495
// Type-safe hit-test tag system (merged from the former `hit_test_tag` module).
496
//
497
// Encodes WebRender's ItemTag = (u64, u16): the tag *type* lives in the upper
498
// byte of tag.1 (DOM node / scrollbar / selection / cursor / scroll-container),
499
// keeping tag types free of bit-level conflicts. See the TAG_TYPE_* constants.
500
// ============================================================================
501
// ============================================================================
502
// Tag Type Markers (stored in upper byte of ItemTag.1)
503
// ============================================================================
504

            
505
/// Marker for DOM node tags (regular UI elements with callbacks, focus, etc.)
506
pub const TAG_TYPE_DOM_NODE: u16 = 0x0100;
507

            
508
/// Marker for scrollbar component tags
509
pub const TAG_TYPE_SCROLLBAR: u16 = 0x0200;
510

            
511
/// Marker for text selection hit-test areas (determines text selection regions)
512
///
513
/// These are pushed for text runs to enable text selection without affecting
514
/// other hit-test logic. Selection may trigger re-rendering.
515
///
516
/// NOTE: Text selection hit-testing currently uses `TAG_TYPE_CURSOR` (0x0400).
517
/// This constant is used by the `HitTestTag::Selection` variant for encoding
518
/// selection-specific tags (e.g., text run selection areas).
519
pub const TAG_TYPE_SELECTION: u16 = 0x0300;
520

            
521
/// Marker for cursor hit-test areas (determines which cursor icon to show)
522
///
523
/// These are separate from DOM node tags to allow efficient cursor resolution
524
/// without iterating over all DOM nodes. Cursor changes never require re-rendering.
525
pub const TAG_TYPE_CURSOR: u16 = 0x0400;
526

            
527
/// Marker for scroll container hit-test areas (for trackpad/wheel scrolling)
528
///
529
/// These identify scrollable containers even when no DOM node callbacks are registered.
530
/// Scroll containers push this tag so the scroll manager can find them during wheel events.
531
pub const TAG_TYPE_SCROLL_CONTAINER: u16 = 0x0500;
532

            
533
// ============================================================================
534
// Scrollbar Component Types (stored in lower byte of ItemTag.1 for scrollbar tags)
535
// ============================================================================
536

            
537
/// Scrollbar component type identifier.
538
///
539
/// Each scrollable container can have up to 2 scrollbars (vertical + horizontal),
540
/// and each scrollbar has 2 main hit regions (track + thumb).
541
///
542
/// Future extensions could add:
543
/// - `UpButton`, `DownButton`, `LeftButton`, `RightButton` for scroll arrows
544
/// - `PageUp`, `PageDown` for page-scroll regions
545
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
546
#[repr(u8)]
547
pub enum ScrollbarComponent {
548
    /// The vertical scrollbar track (background area)
549
    VerticalTrack = 0,
550
    /// The vertical scrollbar thumb (draggable handle)
551
    VerticalThumb = 1,
552
    /// The horizontal scrollbar track (background area)
553
    HorizontalTrack = 2,
554
    /// The horizontal scrollbar thumb (draggable handle)
555
    HorizontalThumb = 3,
556
    // Future: scroll arrow buttons
557
    // VerticalUpButton = 4,
558
    // VerticalDownButton = 5,
559
    // HorizontalLeftButton = 6,
560
    // HorizontalRightButton = 7,
561
}
562

            
563
impl ScrollbarComponent {
564
    /// Convert from raw u8 value
565
    #[must_use]
566
538
    pub const fn from_u8(value: u8) -> Option<Self> {
567
538
        match value {
568
9
            0 => Some(Self::VerticalTrack),
569
8
            1 => Some(Self::VerticalThumb),
570
6
            2 => Some(Self::HorizontalTrack),
571
7
            3 => Some(Self::HorizontalThumb),
572
508
            _ => None,
573
        }
574
538
    }
575
}
576

            
577
// ============================================================================
578
// WebRender Hit-Test Tag (unified type-safe representation)
579
// ============================================================================
580

            
581
/// Unified, type-safe representation of a `WebRender` hit-test tag.
582
///
583
/// This enum represents all possible types of hit-test targets. Each variant
584
/// can be encoded to and decoded from `WebRender`'s `(u64, u16)` `ItemTag` format.
585
///
586
/// ## Namespace Separation
587
///
588
/// Different tag types are kept in separate namespaces to:
589
/// - Enable efficient hit-test queries (only iterate over relevant tags)
590
/// - Get automatic depth sorting from `WebRender` per namespace
591
/// - Prevent accidental collisions between different hit-test purposes
592
///
593
/// | Namespace | Purpose                              |
594
/// |-----------|--------------------------------------|
595
/// | 0x0100    | DOM nodes (callbacks, focus, hover)  |
596
/// | 0x0200    | Scrollbar components                 |
597
/// | 0x0300    | Selection areas (text selection)     |
598
/// | 0x0400    | Cursor areas (cursor icon display)     |
599
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
600
pub enum HitTestTag {
601
    /// A regular DOM node (button, div, text container, etc.)
602
    ///
603
    /// These are nodes that have callbacks, are focusable, or have hover styles.
604
    /// The `TagId` is a sequential counter assigned during DOM styling.
605
    DomNode {
606
        /// The unique tag ID assigned to this DOM node
607
        tag_id: TagId,
608
    },
609

            
610
    /// A scrollbar component (track or thumb)
611
    ///
612
    /// Each scrollable container can have up to 2 scrollbars.
613
    /// The scrollbar is identified by the `DomId` and `NodeId` of the scrollable container.
614
    Scrollbar {
615
        /// The DOM that contains the scrollable container
616
        dom_id: DomId,
617
        /// The `NodeId` of the scrollable container (not the scrollbar itself)
618
        node_id: NodeId,
619
        /// Which component of the scrollbar was hit
620
        component: ScrollbarComponent,
621
    },
622

            
623
    /// A cursor hit-test area (determines which cursor icon to display)
624
    ///
625
    /// These are pushed separately from DOM nodes to allow efficient cursor
626
    /// resolution. The cursor type is encoded in the lower byte of tag.1.
627
    Cursor {
628
        /// The DOM node this cursor area belongs to
629
        dom_id: DomId,
630
        /// The `NodeId` of the element with the cursor property
631
        node_id: NodeId,
632
        /// The cursor type to display when hovering over this area
633
        cursor_type: CursorType,
634
    },
635

            
636
    /// A text selection hit-test area
637
    ///
638
    /// These are pushed for text runs to enable text selection.
639
    /// Separate from DOM nodes to prevent interference with other hit-testing.
640
    Selection {
641
        /// The DOM containing the text
642
        dom_id: DomId,
643
        /// The `NodeId` of the text container (not the Text node itself)
644
        container_node_id: NodeId,
645
        /// The index of the text run within the container (for multi-line text)
646
        text_run_index: u16,
647
    },
648
}
649

            
650
/// Cursor type encoded in cursor hit-test tags.
651
/// Stored in the lower byte of the ItemTag.1 field.
652
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
653
#[repr(u8)]
654
pub enum CursorType {
655
    #[default]
656
    Default = 0,
657
    Pointer = 1,
658
    Text = 2,
659
    Crosshair = 3,
660
    Move = 4,
661
    NotAllowed = 5,
662
    Grab = 6,
663
    Grabbing = 7,
664
    EResize = 8,
665
    WResize = 9,
666
    NResize = 10,
667
    SResize = 11,
668
    EwResize = 12,
669
    NsResize = 13,
670
    NeswResize = 14,
671
    NwseResize = 15,
672
    ColResize = 16,
673
    RowResize = 17,
674
    Wait = 18,
675
    Help = 19,
676
    Progress = 20,
677
    // Add more as needed, up to 255
678
}
679

            
680
impl CursorType {
681
    /// Convert from raw u8 value
682
    // Explicit u8 -> variant table documenting every discriminant; `0 => Default`
683
    // intentionally mirrors the `_ => Default` fallback (the `#[default]` is 0).
684
    #[allow(clippy::match_same_arms)]
685
    #[must_use]
686
15633
    pub const fn from_u8(value: u8) -> Self {
687
15633
        match value {
688
77
            0 => Self::Default,
689
76
            1 => Self::Pointer,
690
75
            2 => Self::Text,
691
76
            3 => Self::Crosshair,
692
76
            4 => Self::Move,
693
75
            5 => Self::NotAllowed,
694
75
            6 => Self::Grab,
695
75
            7 => Self::Grabbing,
696
75
            8 => Self::EResize,
697
75
            9 => Self::WResize,
698
75
            10 => Self::NResize,
699
75
            11 => Self::SResize,
700
75
            12 => Self::EwResize,
701
75
            13 => Self::NsResize,
702
75
            14 => Self::NeswResize,
703
75
            15 => Self::NwseResize,
704
75
            16 => Self::ColResize,
705
75
            17 => Self::RowResize,
706
75
            18 => Self::Wait,
707
75
            19 => Self::Help,
708
76
            20 => Self::Progress,
709
14052
            _ => Self::Default,
710
        }
711
15633
    }
712
}
713

            
714
impl HitTestTag {
715
    /// Encode this tag to `WebRender`'s `ItemTag` format.
716
    ///
717
    /// Returns `(u64, u16)` suitable for passing to `WebRender`'s `push_hit_test`.
718
    #[must_use]
719
56
    pub fn to_item_tag(&self) -> (u64, u16) {
720
56
        match self {
721
8
            Self::DomNode { tag_id } => {
722
                // tag.0 = TagId.inner (the sequential counter)
723
                // tag.1 = TAG_TYPE_DOM_NODE marker
724
8
                (tag_id.inner, TAG_TYPE_DOM_NODE)
725
            }
726
            Self::Scrollbar {
727
19
                dom_id,
728
19
                node_id,
729
19
                component,
730
            } => {
731
                // tag.0 = DomId (upper 32 bits) | NodeId (lower 32 bits)
732
19
                let tag_value = ((dom_id.inner as u64) << 32) | (node_id.index() as u64);
733
                // tag.1 = TAG_TYPE_SCROLLBAR | component type in lower byte
734
19
                let tag_type = TAG_TYPE_SCROLLBAR | (*component as u16);
735
19
                (tag_value, tag_type)
736
            }
737
            Self::Cursor {
738
22
                dom_id,
739
22
                node_id,
740
22
                cursor_type,
741
            } => {
742
                // tag.0 = DomId (upper 32 bits) | NodeId (lower 32 bits)
743
22
                let tag_value = ((dom_id.inner as u64) << 32) | (node_id.index() as u64);
744
                // tag.1 = TAG_TYPE_CURSOR | cursor type in lower byte
745
22
                let tag_type = TAG_TYPE_CURSOR | (*cursor_type as u16);
746
22
                (tag_value, tag_type)
747
            }
748
            Self::Selection {
749
7
                dom_id,
750
7
                container_node_id,
751
7
                text_run_index,
752
            } => {
753
                // tag.0 = DomId (upper 16 bits) | NodeId (middle 32 bits) | text_run_index (lower
754
                // 16 bits) AUDIT: mask each field to its bit width so an
755
                // out-of-range DomId / NodeId can never bleed into an adjacent
756
                // field (silent cross-field corruption). Masking clamps
757
                // consistently in debug and release — a >16-bit DomId is absurd but
758
                // must degrade gracefully, not panic.
759
7
                let dom_bits = (dom_id.inner as u64) & 0xFFFF;
760
7
                let node_bits = (container_node_id.index() as u64) & 0xFFFF_FFFF;
761
7
                let tag_value = (dom_bits << 48) | (node_bits << 16) | u64::from(*text_run_index);
762
7
                (tag_value, TAG_TYPE_SELECTION)
763
            }
764
        }
765
56
    }
766

            
767
    /// Decode a `WebRender` `ItemTag` back to a typed `HitTestTag`.
768
    ///
769
    /// Returns `None` if the tag format is invalid or unrecognized.
770
    #[must_use]
771
2364
    pub fn from_item_tag(tag: (u64, u16)) -> Option<Self> {
772
2364
        let (tag_value, tag_type) = tag;
773

            
774
        // Extract tag type from upper byte
775
2364
        let type_marker = tag_type & 0xFF00;
776

            
777
2364
        match type_marker {
778
            TAG_TYPE_DOM_NODE => {
779
                // DOM node tag: tag.0 is the TagId
780
19
                Some(Self::DomNode {
781
19
                    tag_id: TagId { inner: tag_value },
782
19
                })
783
            }
784
            TAG_TYPE_SCROLLBAR => {
785
                // Scrollbar tag: decode DomId, NodeId, and component
786
278
                let dom_id = DomId {
787
278
                    inner: ((tag_value >> 32) & 0xFFFF_FFFF) as usize,
788
278
                };
789
278
                let node_id = NodeId::new((tag_value & 0xFFFF_FFFF) as usize);
790
278
                let component_value = (tag_type & 0x00FF) as u8;
791
278
                let component = ScrollbarComponent::from_u8(component_value)?;
792

            
793
22
                Some(Self::Scrollbar {
794
22
                    dom_id,
795
22
                    node_id,
796
22
                    component,
797
22
                })
798
            }
799
            TAG_TYPE_CURSOR => {
800
                // Cursor tag: decode DomId, NodeId, and cursor type
801
32
                let dom_id = DomId {
802
32
                    inner: ((tag_value >> 32) & 0xFFFF_FFFF) as usize,
803
32
                };
804
32
                let node_id = NodeId::new((tag_value & 0xFFFF_FFFF) as usize);
805
32
                let cursor_value = (tag_type & 0x00FF) as u8;
806
32
                let cursor_type = CursorType::from_u8(cursor_value);
807

            
808
32
                Some(Self::Cursor {
809
32
                    dom_id,
810
32
                    node_id,
811
32
                    cursor_type,
812
32
                })
813
            }
814
            TAG_TYPE_SELECTION => {
815
                // Selection tag: decode DomId, NodeId, and text run index
816
12
                let dom_id = DomId {
817
12
                    inner: ((tag_value >> 48) & 0xFFFF) as usize,
818
12
                };
819
12
                let container_node_id = NodeId::new(((tag_value >> 16) & 0xFFFF_FFFF) as usize);
820
12
                let text_run_index = (tag_value & 0xFFFF) as u16;
821

            
822
12
                Some(Self::Selection {
823
12
                    dom_id,
824
12
                    container_node_id,
825
12
                    text_run_index,
826
12
                })
827
            }
828
            _ => {
829
                // Unknown tag type - could be a legacy tag or corruption
830
                // For backwards compatibility, treat tags with tag_type == 0
831
                // as legacy DOM node tags (old format before type markers)
832
2023
                if tag_type == 0 {
833
3
                    Some(Self::DomNode {
834
3
                        tag_id: TagId { inner: tag_value },
835
3
                    })
836
                } else {
837
2020
                    None
838
                }
839
            }
840
        }
841
2364
    }
842

            
843
    /// Check if this is a DOM node tag
844
    #[must_use]
845
15
    pub const fn is_dom_node(&self) -> bool {
846
15
        matches!(self, Self::DomNode { .. })
847
15
    }
848

            
849
    /// Check if this is a scrollbar tag
850
    #[must_use]
851
10
    pub const fn is_scrollbar(&self) -> bool {
852
10
        matches!(self, Self::Scrollbar { .. })
853
10
    }
854

            
855
    /// Check if this is a cursor tag
856
    #[must_use]
857
9
    pub const fn is_cursor(&self) -> bool {
858
9
        matches!(self, Self::Cursor { .. })
859
9
    }
860

            
861
    /// Check if this is a selection tag
862
    #[must_use]
863
9
    pub const fn is_selection(&self) -> bool {
864
9
        matches!(self, Self::Selection { .. })
865
9
    }
866

            
867
    /// Get the `TagId` if this is a DOM node tag
868
    #[must_use]
869
20
    pub const fn as_dom_node(&self) -> Option<TagId> {
870
20
        match self {
871
14
            Self::DomNode { tag_id } => Some(*tag_id),
872
6
            _ => None,
873
        }
874
20
    }
875

            
876
    /// Get cursor info if this is a cursor tag
877
    #[must_use]
878
12
    pub const fn as_cursor(&self) -> Option<(DomId, NodeId, CursorType)> {
879
12
        match self {
880
            Self::Cursor {
881
6
                dom_id,
882
6
                node_id,
883
6
                cursor_type,
884
6
            } => Some((*dom_id, *node_id, *cursor_type)),
885
6
            _ => None,
886
        }
887
12
    }
888

            
889
    /// Get selection info if this is a selection tag
890
    #[must_use]
891
9
    pub const fn as_selection(&self) -> Option<(DomId, NodeId, u16)> {
892
9
        match self {
893
            Self::Selection {
894
3
                dom_id,
895
3
                container_node_id,
896
3
                text_run_index,
897
3
            } => Some((*dom_id, *container_node_id, *text_run_index)),
898
6
            _ => None,
899
        }
900
9
    }
901

            
902
    /// Get scrollbar info if this is a scrollbar tag
903
    #[must_use]
904
10
    pub const fn as_scrollbar(&self) -> Option<(DomId, NodeId, ScrollbarComponent)> {
905
10
        match self {
906
            Self::Scrollbar {
907
4
                dom_id,
908
4
                node_id,
909
4
                component,
910
4
            } => Some((*dom_id, *node_id, *component)),
911
6
            _ => None,
912
        }
913
10
    }
914
}
915

            
916
impl fmt::Display for HitTestTag {
917
8
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
918
8
        match self {
919
2
            Self::DomNode { tag_id } => {
920
2
                write!(f, "DomNode(tag:{})", tag_id.inner)
921
            }
922
            Self::Scrollbar {
923
2
                dom_id,
924
2
                node_id,
925
2
                component,
926
            } => {
927
2
                write!(
928
2
                    f,
929
2
                    "Scrollbar(dom:{}, node:{}, {:?})",
930
                    dom_id.inner,
931
2
                    node_id.index(),
932
                    component
933
                )
934
            }
935
            Self::Cursor {
936
2
                dom_id,
937
2
                node_id,
938
2
                cursor_type,
939
            } => {
940
2
                write!(
941
2
                    f,
942
2
                    "Cursor(dom:{}, node:{}, {:?})",
943
                    dom_id.inner,
944
2
                    node_id.index(),
945
                    cursor_type
946
                )
947
            }
948
            Self::Selection {
949
2
                dom_id,
950
2
                container_node_id,
951
2
                text_run_index,
952
            } => {
953
2
                write!(
954
2
                    f,
955
2
                    "Selection(dom:{}, container:{}, run:{})",
956
                    dom_id.inner,
957
2
                    container_node_id.index(),
958
                    text_run_index
959
                )
960
            }
961
        }
962
8
    }
963
}
964

            
965
#[cfg(test)]
966
#[path = "hit_test_test.rs"]
967
mod tests;