1use std::sync::Arc;
6
7use app_units::Au;
8use embedder_traits::Cursor;
9use euclid::{Box2D, Vector2D};
10use kurbo::{Ellipse, Shape};
11use layout_api::ElementsFromPointResult;
12use rustc_hash::FxHashMap;
13use servo_base::id::ScrollTreeNodeId;
14use servo_geometry::FastLayoutTransform;
15use style::computed_values::backface_visibility::T as BackfaceVisibility;
16use style::computed_values::pointer_events::T as PointerEvents;
17use style::computed_values::visibility::T as Visibility;
18use style::properties::ComputedValues;
19use style::values::computed::ui::CursorKind;
20use webrender_api::BorderRadius;
21use webrender_api::units::{LayoutPoint, LayoutRect, LayoutSize, RectExt};
22
23use crate::display_list::clip::{Clip, ClipId};
24use crate::display_list::paint_traversal::{PaintTraversal, PaintTraversalHandler};
25use crate::display_list::{StackingContext, StackingContextTree, ToWebRender, TraversalState};
26use crate::fragment_tree::{BoxFragmentWithStyle, Fragment, FragmentFlags, TextFragment};
27use crate::geom::PhysicalRect;
28
29pub(crate) struct HitTest<'a> {
30 point_to_test: LayoutPoint,
32 projected_point_to_test: Option<(ScrollTreeNodeId, LayoutPoint, FastLayoutTransform)>,
35 stacking_context_tree: &'a StackingContextTree,
37 results: Vec<ElementsFromPointResult>,
39 clip_hit_test_results: FxHashMap<ClipId, bool>,
41 collected_reference_frame_clips: Vec<ClipId>,
45}
46
47impl<'a> HitTest<'a> {
48 pub(crate) fn run(
49 stacking_context_tree: &'a StackingContextTree,
50 point_to_test: LayoutPoint,
51 ) -> Vec<ElementsFromPointResult> {
52 let mut hit_test = Self {
53 point_to_test,
54 projected_point_to_test: None,
55 stacking_context_tree,
56 results: Vec::new(),
57 clip_hit_test_results: FxHashMap::default(),
58 collected_reference_frame_clips: Default::default(),
59 };
60
61 PaintTraversal::traverse(&stacking_context_tree.root_stacking_context, &mut hit_test);
62
63 hit_test.results.reverse();
70
71 hit_test.results
72 }
73
74 fn hit_test_clip_id(&mut self, clip_id: ClipId) -> bool {
77 for index in 0..self.collected_reference_frame_clips.len() {
79 if !self.hit_test_individual_clip_id(self.collected_reference_frame_clips[index]) {
80 return false;
81 }
82 }
83 self.hit_test_individual_clip_id(clip_id)
84 }
85
86 fn hit_test_individual_clip_id(&mut self, clip_id: ClipId) -> bool {
87 if clip_id == ClipId::INVALID {
88 return true;
89 }
90
91 if let Some(result) = self.clip_hit_test_results.get(&clip_id) {
92 return *result;
93 }
94
95 let clip = self.stacking_context_tree.clip_store.get(clip_id);
96 let result = self
97 .location_in_spatial_node(clip.parent_scroll_node_id)
98 .is_some_and(|(point, _)| {
99 clip.contains(point) && self.hit_test_individual_clip_id(clip.parent_clip_id)
100 });
101 self.clip_hit_test_results.insert(clip_id, result);
102 result
103 }
104
105 fn location_in_spatial_node(
109 &mut self,
110 scroll_tree_node_id: ScrollTreeNodeId,
111 ) -> Option<(LayoutPoint, FastLayoutTransform)> {
112 match self.projected_point_to_test {
113 Some((cached_scroll_tree_node_id, projected_point, transform))
114 if cached_scroll_tree_node_id == scroll_tree_node_id =>
115 {
116 return Some((projected_point, transform));
117 },
118 _ => {},
119 }
120
121 let transform = self
122 .stacking_context_tree
123 .paint_info
124 .scroll_tree
125 .cumulative_root_to_node_transform(scroll_tree_node_id)?;
126
127 let projected_point = transform.project_point2d(self.point_to_test)?;
128
129 self.projected_point_to_test = Some((scroll_tree_node_id, projected_point, transform));
130 Some((projected_point, transform))
131 }
132}
133
134impl PaintTraversalHandler for HitTest<'_> {
135 type StackingContextState = bool;
137
138 fn visit_stacking_context(
139 &mut self,
140 stacking_context: &StackingContext,
141 ) -> Self::StackingContextState {
142 if let Some(reference_frame_info) = stacking_context.reference_frame_info.as_ref() &&
143 reference_frame_info.captured_clip_id != ClipId::INVALID
144 {
145 self.collected_reference_frame_clips
146 .push(reference_frame_info.captured_clip_id);
147 return true;
148 }
149 false
150 }
151
152 fn leave_stacking_context(
153 &mut self,
154 _: &TraversalState,
155 pushed_reference_frame_clip: Self::StackingContextState,
156 ) {
157 if pushed_reference_frame_clip {
158 self.collected_reference_frame_clips.pop();
159 }
160 }
161 fn visit_box(&mut self, state: &TraversalState, fragment: &BoxFragmentWithStyle<'_>) {
162 Fragment::Box(fragment.box_fragment.clone()).hit_test(state, self);
163 }
164 fn visit_text(
165 &mut self,
166 state: &TraversalState,
167 _: PhysicalRect<Au>,
168 fragment: &Arc<TextFragment>,
169 ) {
170 Fragment::Text(fragment.clone()).hit_test(state, self);
171 }
172}
173
174impl Clip {
175 fn contains(&self, point: LayoutPoint) -> bool {
176 rounded_rect_contains_point(self.rect, &self.radii, point)
177 }
178}
179
180impl Fragment {
181 pub(crate) fn hit_test(&self, state: &TraversalState, hit_test: &mut HitTest) -> bool {
182 let Some(tag) = self.tag() else {
183 return false;
184 };
185 if !hit_test.hit_test_clip_id(state.clip_id) {
186 return false;
187 }
188
189 let mut hit_test_fragment_inner =
190 |style: &ComputedValues,
191 fragment_rect: PhysicalRect<Au>,
192 border_radius: BorderRadius,
193 fragment_flags: FragmentFlags,
194 auto_cursor: Cursor| {
195 let is_root_element = fragment_flags.contains(FragmentFlags::IS_ROOT_ELEMENT);
196
197 if !is_root_element {
198 if style.get_inherited_ui().pointer_events == PointerEvents::None {
199 return false;
200 }
201 if style.get_inherited_box().visibility != Visibility::Visible {
202 return false;
203 }
204 }
205
206 let (point_in_spatial_node, transform) =
207 match hit_test.location_in_spatial_node(state.spatial_id) {
208 Some(point) => point,
209 None => return false,
210 };
211
212 if !is_root_element &&
213 style.get_box().backface_visibility == BackfaceVisibility::Hidden &&
214 transform.is_backface_visible()
215 {
216 return false;
217 }
218
219 let fragment_rect = fragment_rect.translate(state.origin.to_vector());
220 if is_root_element {
221 let viewport_size = hit_test
222 .stacking_context_tree
223 .paint_info
224 .viewport_details
225 .size;
226 let viewport_rect = LayoutRect::from_origin_and_size(
227 Default::default(),
228 viewport_size.cast_unit(),
229 );
230 if !viewport_rect.contains(hit_test.point_to_test) {
231 return false;
232 }
233 } else if !rounded_rect_contains_point(
234 fragment_rect.to_webrender(),
235 &border_radius,
236 point_in_spatial_node,
237 ) {
238 return false;
239 }
240
241 let point_in_target = point_in_spatial_node.cast_unit() -
242 Vector2D::new(
243 fragment_rect.origin.x.to_f32_px(),
244 fragment_rect.origin.y.to_f32_px(),
245 );
246
247 hit_test.results.push(ElementsFromPointResult {
248 node: tag.node,
249 point_in_target,
250 cursor: cursor(style.get_inherited_ui().cursor.keyword, auto_cursor),
251 });
252
253 false
259 };
260
261 match self {
262 Fragment::LayoutRoot(layout_root_fragment) => {
263 layout_root_fragment.inner().hit_test(state, hit_test)
264 },
265 Fragment::Box(box_fragment) | Fragment::Float(box_fragment) => hit_test_fragment_inner(
266 &box_fragment.style(),
267 box_fragment.border_rect(),
268 box_fragment.border_radius(),
269 box_fragment.base.flags,
270 Cursor::Default,
271 ),
272 Fragment::Text(text) => hit_test_fragment_inner(
273 &text.base.style(),
274 text.base.rect(),
275 BorderRadius::zero(),
276 FragmentFlags::empty(),
277 Cursor::Text,
278 ),
279 _ => false,
280 }
281 }
282}
283
284fn rounded_rect_contains_point(
285 rect: LayoutRect,
286 border_radius: &BorderRadius,
287 point: LayoutPoint,
288) -> bool {
289 if !rect.contains(point) {
290 return false;
291 }
292
293 if border_radius.is_zero() {
294 return true;
295 }
296
297 let check_corner = |corner: LayoutPoint, radius: &LayoutSize, is_right, is_bottom| {
298 let mut origin = corner;
299 if is_right {
300 origin.x -= radius.width;
301 }
302 if is_bottom {
303 origin.y -= radius.height;
304 }
305 if !Box2D::from_origin_and_size(origin, *radius).contains(point) {
306 return true;
307 }
308 let center = (
309 if is_right {
310 corner.x - radius.width
311 } else {
312 corner.x + radius.width
313 },
314 if is_bottom {
315 corner.y - radius.height
316 } else {
317 corner.y + radius.height
318 },
319 );
320 let radius = (radius.width as f64, radius.height as f64);
321 Ellipse::new(center, radius, 0.0).contains((point.x, point.y).into())
322 };
323
324 check_corner(rect.top_left(), &border_radius.top_left, false, false) &&
325 check_corner(rect.top_right(), &border_radius.top_right, true, false) &&
326 check_corner(rect.bottom_right(), &border_radius.bottom_right, true, true) &&
327 check_corner(rect.bottom_left(), &border_radius.bottom_left, false, true)
328}
329
330fn cursor(kind: CursorKind, auto_cursor: Cursor) -> Cursor {
331 match kind {
332 CursorKind::Auto => auto_cursor,
333 CursorKind::None => Cursor::None,
334 CursorKind::Default => Cursor::Default,
335 CursorKind::Pointer => Cursor::Pointer,
336 CursorKind::ContextMenu => Cursor::ContextMenu,
337 CursorKind::Help => Cursor::Help,
338 CursorKind::Progress => Cursor::Progress,
339 CursorKind::Wait => Cursor::Wait,
340 CursorKind::Cell => Cursor::Cell,
341 CursorKind::Crosshair => Cursor::Crosshair,
342 CursorKind::Text => Cursor::Text,
343 CursorKind::VerticalText => Cursor::VerticalText,
344 CursorKind::Alias => Cursor::Alias,
345 CursorKind::Copy => Cursor::Copy,
346 CursorKind::Move => Cursor::Move,
347 CursorKind::NoDrop => Cursor::NoDrop,
348 CursorKind::NotAllowed => Cursor::NotAllowed,
349 CursorKind::Grab => Cursor::Grab,
350 CursorKind::Grabbing => Cursor::Grabbing,
351 CursorKind::EResize => Cursor::EResize,
352 CursorKind::NResize => Cursor::NResize,
353 CursorKind::NeResize => Cursor::NeResize,
354 CursorKind::NwResize => Cursor::NwResize,
355 CursorKind::SResize => Cursor::SResize,
356 CursorKind::SeResize => Cursor::SeResize,
357 CursorKind::SwResize => Cursor::SwResize,
358 CursorKind::WResize => Cursor::WResize,
359 CursorKind::EwResize => Cursor::EwResize,
360 CursorKind::NsResize => Cursor::NsResize,
361 CursorKind::NeswResize => Cursor::NeswResize,
362 CursorKind::NwseResize => Cursor::NwseResize,
363 CursorKind::ColResize => Cursor::ColResize,
364 CursorKind::RowResize => Cursor::RowResize,
365 CursorKind::AllScroll => Cursor::AllScroll,
366 CursorKind::ZoomIn => Cursor::ZoomIn,
367 CursorKind::ZoomOut => Cursor::ZoomOut,
368 }
369}