Skip to main content

layout/display_list/
hit_test.rs

1/* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */
4
5use std::sync::Arc;
6
7use app_units::Au;
8use embedder_traits::Cursor;
9use euclid::{Box2D, Point2D, Vector2D};
10use kurbo::{Ellipse, Shape};
11use layout_api::{HitTestFlags, HitTestResult, HitTestResultItem};
12use rustc_hash::FxHashMap;
13use servo_base::id::ScrollTreeNodeId;
14use servo_base::text::Utf32CodeUnits;
15use servo_geometry::FastLayoutTransform;
16use style::computed_values::backface_visibility::T as BackfaceVisibility;
17use style::computed_values::pointer_events::T as PointerEvents;
18use style::computed_values::visibility::T as Visibility;
19use style::dom::OpaqueNode;
20use style::properties::ComputedValues;
21use style::values::computed::ui::CursorKind;
22use style_traits::CSSPixel;
23use webrender_api::BorderRadius;
24use webrender_api::units::{LayoutPoint, LayoutRect, LayoutSize, RectExt};
25
26use crate::display_list::clip::{Clip, ClipId};
27use crate::display_list::paint_traversal::{PaintTraversal, PaintTraversalHandler};
28use crate::display_list::{StackingContext, StackingContextTree, ToWebRender, TraversalState};
29use crate::fragment_tree::{BoxFragmentWithStyle, Fragment, FragmentFlags, TextFragment};
30use crate::geom::PhysicalRect;
31
32struct DomPositionCandidate {
33    fragment: Fragment,
34    node: OpaqueNode,
35    point_in_target: Point2D<f32, CSSPixel>,
36}
37
38pub(crate) struct HitTest<'a> {
39    /// The flags which describe how to perform this [`HitTest`]
40    flags: HitTestFlags,
41    /// The point to test for this hit test, relative to the page.
42    point_to_test: LayoutPoint,
43    /// A cached version of [`Self::point_to_test`] projected to a spatial node, to avoid
44    /// doing a lot of matrix math over and over.
45    projected_point_to_test: Option<(ScrollTreeNodeId, LayoutPoint, FastLayoutTransform)>,
46    /// The stacking context tree against which to perform the hit test.
47    stacking_context_tree: &'a StackingContextTree,
48    /// The resulting [`HitTestResultItems`] for this hit test.
49    items: Vec<HitTestResultItem>,
50    /// Candidate for `HitTestResult::dom_position_for_selection`
51    dom_position_candidate: Option<DomPositionCandidate>,
52    /// A cache of hit test results for shared clip nodes.
53    clip_hit_test_results: FxHashMap<ClipId, bool>,
54    /// Collected reference frame clips. For painting, reference frame clips are handled
55    /// by enclosing reference frames in stacking contexts, but we don't have that option
56    /// here, so we must handle them manually.
57    collected_reference_frame_clips: Vec<ClipId>,
58}
59
60impl<'a> HitTest<'a> {
61    pub(crate) fn run(
62        flags: HitTestFlags,
63        stacking_context_tree: &'a StackingContextTree,
64        point_to_test: LayoutPoint,
65    ) -> HitTestResult {
66        let mut hit_test = Self {
67            flags,
68            point_to_test,
69            projected_point_to_test: None,
70            stacking_context_tree,
71            items: Vec::new(),
72            dom_position_candidate: None,
73            clip_hit_test_results: FxHashMap::default(),
74            collected_reference_frame_clips: Default::default(),
75        };
76
77        PaintTraversal::traverse(&stacking_context_tree.root_stacking_context, &mut hit_test);
78
79        // PaintTraversal::traverse walks forward through all fragments via the stacking
80        // context tree, so results will be in back-to-front order. We want results to be
81        // front-to-back order, so reverse them.
82        //
83        // TODO: Eventually PaintTraversal should support walking backward through
84        // fragments.
85        hit_test.items.reverse();
86
87        HitTestResult {
88            dom_position_for_selection: hit_test.dom_position(),
89            items: hit_test.items,
90        }
91    }
92
93    fn dom_position(&self) -> Option<(OpaqueNode, Utf32CodeUnits)> {
94        let hit = self.dom_position_candidate.as_ref()?;
95        if let Fragment::Text(text_fragment) = &hit.fragment {
96            let character_offset =
97                text_fragment.character_offset(hit.point_in_target.map(Au::from_f32_px))?;
98            return Some((hit.node, character_offset));
99        }
100
101        let mut search = ClosestFragmentSearch::default();
102        if let Some(point_in_fragment) = self.stacking_context_tree.offset_in_fragment(
103            &hit.fragment,
104            self.point_to_test.map(Au::from_f32_px).cast_unit(),
105        ) {
106            search.collect_relevant_children(&hit.fragment, point_in_fragment);
107        }
108        search.into_dom_position()
109    }
110
111    /// Perform a hit test against the clip node for the given [`ClipId`], returning
112    /// true if it is not clipped out or false if is clipped out.
113    fn hit_test_clip_id(&mut self, clip_id: ClipId) -> bool {
114        // Using the index here is necessary to avoid a double borrow of `self`.
115        for index in 0..self.collected_reference_frame_clips.len() {
116            if !self.hit_test_individual_clip_id(self.collected_reference_frame_clips[index]) {
117                return false;
118            }
119        }
120        self.hit_test_individual_clip_id(clip_id)
121    }
122
123    fn hit_test_individual_clip_id(&mut self, clip_id: ClipId) -> bool {
124        if clip_id == ClipId::INVALID {
125            return true;
126        }
127
128        if let Some(result) = self.clip_hit_test_results.get(&clip_id) {
129            return *result;
130        }
131
132        let clip = self.stacking_context_tree.clip_store.get(clip_id);
133        let result = self
134            .location_in_spatial_node(clip.parent_scroll_node_id)
135            .is_some_and(|(point, _)| {
136                clip.contains(point) && self.hit_test_individual_clip_id(clip.parent_clip_id)
137            });
138        self.clip_hit_test_results.insert(clip_id, result);
139        result
140    }
141
142    /// Get the hit test location in the coordinate system of the given spatial node,
143    /// returning `None` if the transformation is uninvertible or the point cannot be
144    /// projected into the spatial node.
145    fn location_in_spatial_node(
146        &mut self,
147        scroll_tree_node_id: ScrollTreeNodeId,
148    ) -> Option<(LayoutPoint, FastLayoutTransform)> {
149        match self.projected_point_to_test {
150            Some((cached_scroll_tree_node_id, projected_point, transform))
151                if cached_scroll_tree_node_id == scroll_tree_node_id =>
152            {
153                return Some((projected_point, transform));
154            },
155            _ => {},
156        }
157
158        let transform = self
159            .stacking_context_tree
160            .paint_info
161            .scroll_tree
162            .cumulative_root_to_node_transform(scroll_tree_node_id)?;
163
164        let projected_point = transform.project_point2d(self.point_to_test)?;
165
166        self.projected_point_to_test = Some((scroll_tree_node_id, projected_point, transform));
167        Some((projected_point, transform))
168    }
169}
170
171impl PaintTraversalHandler for HitTest<'_> {
172    /// `true` if we pushed a reference frame clip and `false` otherwise.
173    type StackingContextState = bool;
174
175    fn visit_stacking_context(
176        &mut self,
177        stacking_context: &StackingContext,
178    ) -> Self::StackingContextState {
179        if let Some(reference_frame_info) = stacking_context.reference_frame_info.as_ref() &&
180            reference_frame_info.captured_clip_id != ClipId::INVALID
181        {
182            self.collected_reference_frame_clips
183                .push(reference_frame_info.captured_clip_id);
184            return true;
185        }
186        false
187    }
188
189    fn leave_stacking_context(
190        &mut self,
191        _: &TraversalState,
192        pushed_reference_frame_clip: Self::StackingContextState,
193    ) {
194        if pushed_reference_frame_clip {
195            self.collected_reference_frame_clips.pop();
196        }
197    }
198
199    fn visit_box(&mut self, state: &TraversalState, fragment: &BoxFragmentWithStyle<'_>) {
200        Fragment::Box(fragment.box_fragment.clone()).hit_test(state, self);
201    }
202
203    fn visit_text(
204        &mut self,
205        state: &TraversalState,
206        _: PhysicalRect<Au>,
207        fragment: &Arc<TextFragment>,
208    ) {
209        Fragment::Text(fragment.clone()).hit_test(state, self);
210    }
211}
212
213impl Clip {
214    fn contains(&self, point: LayoutPoint) -> bool {
215        rounded_rect_contains_point(self.rect, &self.radii, point)
216    }
217}
218
219impl Fragment {
220    pub(crate) fn hit_test(&self, state: &TraversalState, hit_test: &mut HitTest) -> bool {
221        let Some(tag) = self.tag() else {
222            return false;
223        };
224        if !hit_test.hit_test_clip_id(state.clip_id) {
225            return false;
226        }
227
228        let mut hit_test_fragment_inner =
229            |style: &ComputedValues,
230             fragment_rect: PhysicalRect<Au>,
231             border_radius: BorderRadius,
232             fragment_flags: FragmentFlags,
233             auto_cursor: Cursor| {
234                let is_root_element = fragment_flags.contains(FragmentFlags::IS_ROOT_ELEMENT);
235
236                if !is_root_element {
237                    if style.get_inherited_ui().pointer_events == PointerEvents::None {
238                        return false;
239                    }
240                    if style.get_inherited_box().visibility != Visibility::Visible {
241                        return false;
242                    }
243                }
244
245                let (point_in_spatial_node, transform) =
246                    match hit_test.location_in_spatial_node(state.spatial_id) {
247                        Some(point) => point,
248                        None => return false,
249                    };
250
251                if !is_root_element &&
252                    style.get_box().backface_visibility == BackfaceVisibility::Hidden &&
253                    transform.is_backface_visible()
254                {
255                    return false;
256                }
257
258                let fragment_rect = fragment_rect.translate(state.origin.to_vector());
259                if is_root_element {
260                    let viewport_size = hit_test
261                        .stacking_context_tree
262                        .paint_info
263                        .viewport_details
264                        .size;
265                    let viewport_rect = LayoutRect::from_origin_and_size(
266                        Default::default(),
267                        viewport_size.cast_unit(),
268                    );
269                    if !viewport_rect.contains(hit_test.point_to_test) {
270                        return false;
271                    }
272                } else if !rounded_rect_contains_point(
273                    fragment_rect.to_webrender(),
274                    &border_radius,
275                    point_in_spatial_node,
276                ) {
277                    return false;
278                }
279
280                let point_in_target = point_in_spatial_node.cast_unit() -
281                    Vector2D::new(
282                        fragment_rect.origin.x.to_f32_px(),
283                        fragment_rect.origin.y.to_f32_px(),
284                    );
285
286                hit_test.items.push(HitTestResultItem {
287                    node: tag.node,
288                    point_in_target,
289                    cursor: cursor(style.get_inherited_ui().cursor.keyword, auto_cursor),
290                });
291
292                if hit_test.flags.intersects(HitTestFlags::IncludeDomPosition) {
293                    hit_test.dom_position_candidate = Some(DomPositionCandidate {
294                        fragment: self.clone(),
295                        node: tag.node,
296                        point_in_target,
297                    });
298                }
299
300                // Since there is no reverse PaintTraversal, hit testing always searches
301                // the entire fragment tree (in stacking context order), which is why this
302                // is always returning `false` (keep looking). Once PaintTraversal can
303                // walk backward through fragments, this can return `true` if FindAll
304                // isn't specified.
305                false
306            };
307
308        match self {
309            Fragment::LayoutRoot(layout_root_fragment) => {
310                layout_root_fragment.inner().hit_test(state, hit_test)
311            },
312            Fragment::Box(box_fragment) | Fragment::Float(box_fragment) => hit_test_fragment_inner(
313                &box_fragment.style(),
314                box_fragment.border_rect(),
315                box_fragment.border_radius(),
316                box_fragment.base.flags,
317                Cursor::Default,
318            ),
319            Fragment::Text(text) => hit_test_fragment_inner(
320                &text.style(),
321                text.base.rect(),
322                BorderRadius::zero(),
323                FragmentFlags::empty(),
324                Cursor::Text,
325            ),
326            _ => false,
327        }
328    }
329}
330
331fn rounded_rect_contains_point(
332    rect: LayoutRect,
333    border_radius: &BorderRadius,
334    point: LayoutPoint,
335) -> bool {
336    if !rect.contains(point) {
337        return false;
338    }
339
340    if border_radius.is_zero() {
341        return true;
342    }
343
344    let check_corner = |corner: LayoutPoint, radius: &LayoutSize, is_right, is_bottom| {
345        let mut origin = corner;
346        if is_right {
347            origin.x -= radius.width;
348        }
349        if is_bottom {
350            origin.y -= radius.height;
351        }
352        if !Box2D::from_origin_and_size(origin, *radius).contains(point) {
353            return true;
354        }
355        let center = (
356            if is_right {
357                corner.x - radius.width
358            } else {
359                corner.x + radius.width
360            },
361            if is_bottom {
362                corner.y - radius.height
363            } else {
364                corner.y + radius.height
365            },
366        );
367        let radius = (radius.width as f64, radius.height as f64);
368        Ellipse::new(center, radius, 0.0).contains((point.x, point.y).into())
369    };
370
371    check_corner(rect.top_left(), &border_radius.top_left, false, false) &&
372        check_corner(rect.top_right(), &border_radius.top_right, true, false) &&
373        check_corner(rect.bottom_right(), &border_radius.bottom_right, true, true) &&
374        check_corner(rect.bottom_left(), &border_radius.bottom_left, false, true)
375}
376
377fn cursor(kind: CursorKind, auto_cursor: Cursor) -> Cursor {
378    match kind {
379        CursorKind::Auto => auto_cursor,
380        CursorKind::None => Cursor::None,
381        CursorKind::Default => Cursor::Default,
382        CursorKind::Pointer => Cursor::Pointer,
383        CursorKind::ContextMenu => Cursor::ContextMenu,
384        CursorKind::Help => Cursor::Help,
385        CursorKind::Progress => Cursor::Progress,
386        CursorKind::Wait => Cursor::Wait,
387        CursorKind::Cell => Cursor::Cell,
388        CursorKind::Crosshair => Cursor::Crosshair,
389        CursorKind::Text => Cursor::Text,
390        CursorKind::VerticalText => Cursor::VerticalText,
391        CursorKind::Alias => Cursor::Alias,
392        CursorKind::Copy => Cursor::Copy,
393        CursorKind::Move => Cursor::Move,
394        CursorKind::NoDrop => Cursor::NoDrop,
395        CursorKind::NotAllowed => Cursor::NotAllowed,
396        CursorKind::Grab => Cursor::Grab,
397        CursorKind::Grabbing => Cursor::Grabbing,
398        CursorKind::EResize => Cursor::EResize,
399        CursorKind::NResize => Cursor::NResize,
400        CursorKind::NeResize => Cursor::NeResize,
401        CursorKind::NwResize => Cursor::NwResize,
402        CursorKind::SResize => Cursor::SResize,
403        CursorKind::SeResize => Cursor::SeResize,
404        CursorKind::SwResize => Cursor::SwResize,
405        CursorKind::WResize => Cursor::WResize,
406        CursorKind::EwResize => Cursor::EwResize,
407        CursorKind::NsResize => Cursor::NsResize,
408        CursorKind::NeswResize => Cursor::NeswResize,
409        CursorKind::NwseResize => Cursor::NwseResize,
410        CursorKind::ColResize => Cursor::ColResize,
411        CursorKind::RowResize => Cursor::RowResize,
412        CursorKind::AllScroll => Cursor::AllScroll,
413        CursorKind::ZoomIn => Cursor::ZoomIn,
414        CursorKind::ZoomOut => Cursor::ZoomOut,
415    }
416}
417
418pub(crate) struct ClosestFragment {
419    fragment: Arc<TextFragment>,
420    node: OpaqueNode,
421    point_in_fragment: Point2D<Au, CSSPixel>,
422    distance: Au,
423    point_in_vertical_bounds: bool,
424}
425
426impl ClosestFragment {
427    fn should_replace(&self, new_distance: Au, point_in_vertical_bounds: bool) -> bool {
428        if point_in_vertical_bounds && !self.point_in_vertical_bounds {
429            return true;
430        }
431        if self.point_in_vertical_bounds && !point_in_vertical_bounds {
432            return false;
433        }
434        new_distance <= self.distance
435    }
436
437    pub(crate) fn dom_position(&self) -> Option<(OpaqueNode, Utf32CodeUnits)> {
438        let character_offset = self.fragment.character_offset(self.point_in_fragment)?;
439        Some((self.node, character_offset))
440    }
441}
442
443#[derive(Default)]
444pub(crate) struct ClosestFragmentSearch {
445    closest: Option<ClosestFragment>,
446}
447
448impl ClosestFragmentSearch {
449    pub(crate) fn into_dom_position(self) -> Option<(OpaqueNode, Utf32CodeUnits)> {
450        self.closest?.dom_position()
451    }
452
453    fn maybe_update(&mut self, fragment: &Fragment, point_in_fragment: Point2D<Au, CSSPixel>) {
454        let Fragment::Text(text_fragment) = fragment else {
455            return;
456        };
457
458        let (distance, point_in_vertical_bounds) = {
459            (
460                text_fragment.distance_to_point_for_glyph_offset(point_in_fragment),
461                text_fragment.point_is_within_vertical_boundaries(point_in_fragment),
462            )
463        };
464
465        if let Some(tag) = text_fragment.base.tag.as_ref() &&
466            self.closest.as_ref().is_none_or(|closest_fragment| {
467                closest_fragment.should_replace(distance, point_in_vertical_bounds)
468            })
469        {
470            self.closest = Some(ClosestFragment {
471                fragment: text_fragment.clone(),
472                node: tag.node,
473                point_in_fragment,
474                distance,
475                point_in_vertical_bounds,
476            });
477        }
478    }
479
480    pub(crate) fn collect_relevant_children(
481        &mut self,
482        fragment: &Fragment,
483        point_in_fragment: Point2D<Au, CSSPixel>,
484    ) {
485        self.maybe_update(fragment, point_in_fragment);
486        if let Some(children) = fragment.children() {
487            for child in children.iter() {
488                let offset = child
489                    .base()
490                    .map(|base| base.rect().origin)
491                    .unwrap_or_default();
492                let point = point_in_fragment - offset.to_vector();
493                self.collect_relevant_children(child, point);
494            }
495        }
496    }
497}