1use whisker_protocol::{
2 ClipShape, FillRule, HitTestBehavior, InputPoint, LayoutRect, NodeId, OverflowClip, PaintBox,
3 PaintCoordinate, PaintCornerRadius, PaintCorners, PaintLengthPercentage, PaintPosition,
4 PathCommand, Transform, Visibility,
5};
6
7use super::{Scene, SceneError, SceneNode};
8
9impl Scene {
10 pub fn hit_test(&self, root: NodeId, point: InputPoint) -> Result<Option<NodeId>, SceneError> {
12 self.require_node(root)?;
13 Ok(self.hit_test_node(root, point, [0.0; 2]))
14 }
15
16 pub fn text_span_at(
18 &self,
19 node: NodeId,
20 mut point: InputPoint,
21 ) -> Option<whisker_protocol::TextSpanId> {
22 let content = self.nodes.get(&node)?.text.as_ref()?;
23 let paragraph = content.paragraph.as_ref()?;
24 let chain_geometry = self.nodes.get(&node).expect("retained paragraph").layout?;
25 let mut chain = Vec::new();
26 let mut current = Some(node);
27 while let Some(node) = current {
28 let state = self.nodes.get(&node).expect("retained paragraph ancestor");
29 chain.push(state.as_ref());
30 current = state.parent;
31 }
32 let mut origin = [0.0; 2];
33 for state in chain.into_iter().rev() {
34 let geometry = state.layout?;
35 let border = [
36 origin[0] + geometry.border_box.x,
37 origin[1] + geometry.border_box.y,
38 ];
39 point = inverse_map_around(state.transform, point, border)?;
40 origin = [
41 border[0] - state.host_scroll_offset[0],
42 border[1] - state.host_scroll_offset[1],
43 ];
44 }
45 let geometry = chain_geometry;
46 let local = [
47 point.x - origin[0] - geometry.content_box.x,
48 point.y - origin[1] - geometry.content_box.y,
49 ];
50 let fragment = paragraph.fragments.iter().find(|fragment| {
51 contains_axis(local[0], fragment.bounds.x, fragment.bounds.width)
52 && contains_axis(local[1], fragment.bounds.y, fragment.bounds.height)
53 })?;
54 let bytes = fragment
55 .range
56 .to_utf8(&content.payload.text)
57 .expect("validated paragraph fragment");
58 content
59 .runs
60 .iter()
61 .find(|run| {
62 run.range.start as usize <= bytes.start && bytes.start < run.range.end as usize
63 })
64 .map(|run| run.span)
65 }
66
67 fn hit_test_node(
68 &self,
69 node: NodeId,
70 point: InputPoint,
71 parent_origin: [f32; 2],
72 ) -> Option<NodeId> {
73 let state = self
74 .nodes
75 .get(&node)
76 .expect("hit-test traversal only visits retained nodes");
77 if state.hit_test == Some(HitTestBehavior::None) {
78 return None;
79 }
80
81 let layout = state.layout?;
82 let border = LayoutRect {
83 x: parent_origin[0] + layout.border_box.x,
84 y: parent_origin[1] + layout.border_box.y,
85 width: layout.border_box.width,
86 height: layout.border_box.height,
87 };
88 let point = inverse_map_around(state.transform, point, [border.x, border.y])?;
89 let contains_x = contains_axis(point.x, border.x, border.width);
90 let contains_y = contains_axis(point.y, border.y, border.height);
91 let contains = contains_x && contains_y;
92
93 if !clip_path_contains(state, layout.content_box, border, point) {
96 return None;
97 }
98
99 let children_clipped = state.clip.is_some_and(|clip| {
100 let [clip_x, clip_y] = overflow_clip_contains(state, border, point);
101 (clip.horizontal == OverflowClip::Hidden && !clip_x)
102 || (clip.vertical == OverflowClip::Hidden && !clip_y)
103 });
104 if state.hit_test != Some(HitTestBehavior::BoxOnly) && !children_clipped {
105 let child_origin = [
106 border.x - state.host_scroll_offset[0],
107 border.y - state.host_scroll_offset[1],
108 ];
109 if let Some(target) = self.hit_test_children(state, point, child_origin) {
110 return Some(target);
111 }
112 }
113
114 (state.visibility != Some(Visibility::Hidden)
115 && contains
116 && state.hit_test != Some(HitTestBehavior::DescendantsOnly))
117 .then_some(node)
118 }
119
120 fn hit_test_children(
121 &self,
122 state: &SceneNode,
123 point: InputPoint,
124 child_origin: [f32; 2],
125 ) -> Option<NodeId> {
126 let first_z = state
127 .children
128 .first()
129 .and_then(|child| self.nodes.get(child))
130 .and_then(|child| child.z_order)
131 .unwrap_or(0);
132 let uniform_z = state.children.iter().all(|child| {
133 self.nodes
134 .get(child)
135 .and_then(|child| child.z_order)
136 .unwrap_or(0)
137 == first_z
138 });
139
140 if uniform_z {
143 return state
144 .children
145 .iter()
146 .rev()
147 .find_map(|child| self.hit_test_node(*child, point, child_origin));
148 }
149
150 let mut best = None;
153 for (index, child) in state.children.iter().copied().enumerate() {
154 let Some(target) = self.hit_test_node(child, point, child_origin) else {
155 continue;
156 };
157 let z = self
158 .nodes
159 .get(&child)
160 .and_then(|child| child.z_order)
161 .unwrap_or(0);
162 if best.is_none_or(|((best_z, best_index), _)| (z, index) > (best_z, best_index)) {
163 best = Some(((z, index), target));
164 }
165 }
166 best.map(|(_, target)| target)
167 }
168}
169
170fn contains_axis(value: f32, start: f32, length: f32) -> bool {
171 value >= start && value <= start + length
172}
173
174fn inverse_map_around(
175 transform: Option<Transform>,
176 point: InputPoint,
177 origin: [f32; 2],
178) -> Option<InputPoint> {
179 let Some(transform) = transform.filter(|transform| *transform != Transform::IDENTITY) else {
180 return Some(point);
181 };
182 let [x, y] = [point.x - origin[0], point.y - origin[1]];
183 let matrix = transform.0;
184 let [a, c, tx] = [matrix[0], matrix[4], matrix[12]];
185 let [b, d, ty] = [matrix[1], matrix[5], matrix[13]];
186 let [p, q, r] = [matrix[3], matrix[7], matrix[15]];
187 let determinant = a * (d * r - ty * q) - c * (b * r - ty * p) + tx * (b * q - d * p);
188 if determinant.abs() <= f32::EPSILON {
189 return None;
190 }
191
192 let inverse_x = (d * r - ty * q) * x + (tx * q - c * r) * y + (c * ty - tx * d);
194 let inverse_y = (ty * p - b * r) * x + (a * r - tx * p) * y + (tx * b - a * ty);
195 let inverse_w = (b * q - d * p) * x + (c * p - a * q) * y + (a * d - c * b);
196 if inverse_w.abs() <= f32::EPSILON {
197 return None;
198 }
199 let mapped = InputPoint {
200 x: origin[0] + inverse_x / inverse_w,
201 y: origin[1] + inverse_y / inverse_w,
202 };
203 mapped.is_valid().then_some(mapped)
204}
205
206fn overflow_clip_contains(state: &SceneNode, border: LayoutRect, point: InputPoint) -> [bool; 2] {
207 let clip = state
208 .clip
209 .expect("overflow geometry is queried only for a clip");
210 let Some(paint) = state.box_paint.as_ref() else {
211 return [
212 contains_axis(point.x, border.x, border.width),
213 contains_axis(point.y, border.y, border.height),
214 ];
215 };
216 let top = resolve_length(paint.border_widths.top, border.height).min(border.height);
217 let right = resolve_length(paint.border_widths.right, border.width).min(border.width);
218 let bottom = resolve_length(paint.border_widths.bottom, border.height).min(border.height);
219 let left = resolve_length(paint.border_widths.left, border.width).min(border.width);
220 let inner = LayoutRect {
221 x: border.x + left,
222 y: border.y + top,
223 width: (border.width - left - right).max(0.0),
224 height: (border.height - top - bottom).max(0.0),
225 };
226 if clip.horizontal == OverflowClip::Hidden && clip.vertical == OverflowClip::Hidden {
227 let (outer_x, outer_y) = resolve_radii(&paint.border_radii, border);
228 let inner_x = [
229 (outer_x[0] - left).max(0.0),
230 (outer_x[1] - right).max(0.0),
231 (outer_x[2] - right).max(0.0),
232 (outer_x[3] - left).max(0.0),
233 ];
234 let inner_y = [
235 (outer_y[0] - top).max(0.0),
236 (outer_y[1] - top).max(0.0),
237 (outer_y[2] - bottom).max(0.0),
238 (outer_y[3] - bottom).max(0.0),
239 ];
240 let contains = rounded_rect_contains(inner, (inner_x, inner_y), point);
241 return [contains; 2];
242 }
243 [
244 contains_axis(point.x, inner.x, inner.width),
245 contains_axis(point.y, inner.y, inner.height),
246 ]
247}
248
249fn clip_path_contains(
250 state: &SceneNode,
251 content: LayoutRect,
252 border: LayoutRect,
253 point: InputPoint,
254) -> bool {
255 let Some((reference_box, shape)) = state.visual_effects.clip_path.as_ref() else {
256 return true;
257 };
258 let reference = match reference_box {
259 PaintBox::Content => LayoutRect {
260 x: border.x + content.x,
261 y: border.y + content.y,
262 width: content.width,
263 height: content.height,
264 },
265 PaintBox::Padding => padding_box(state, border),
266 _ => border,
267 };
268 shape_contains(shape, reference, point)
269}
270
271fn padding_box(state: &SceneNode, border: LayoutRect) -> LayoutRect {
272 let Some(paint) = state.box_paint.as_ref() else {
273 return border;
274 };
275 let top = resolve_length(paint.border_widths.top, border.height).min(border.height);
276 let right = resolve_length(paint.border_widths.right, border.width).min(border.width);
277 let bottom = resolve_length(paint.border_widths.bottom, border.height).min(border.height);
278 let left = resolve_length(paint.border_widths.left, border.width).min(border.width);
279 LayoutRect {
280 x: border.x + left,
281 y: border.y + top,
282 width: (border.width - left - right).max(0.0),
283 height: (border.height - top - bottom).max(0.0),
284 }
285}
286
287fn shape_contains(shape: &ClipShape, reference: LayoutRect, point: InputPoint) -> bool {
288 match shape {
289 ClipShape::Inset { edges, radii } => {
290 let top = resolve_coordinate(edges.top, reference.height);
291 let right = resolve_coordinate(edges.right, reference.width);
292 let bottom = resolve_coordinate(edges.bottom, reference.height);
293 let left = resolve_coordinate(edges.left, reference.width);
294 let rect = LayoutRect {
295 x: reference.x + left,
296 y: reference.y + top,
297 width: (reference.width - left - right).max(0.0),
298 height: (reference.height - top - bottom).max(0.0),
299 };
300 rounded_rect_contains(rect, resolve_radii(radii, rect), point)
301 }
302 ClipShape::Circle { radius, center } => {
303 let center = resolve_position(*center, reference);
304 let diagonal = reference.width.hypot(reference.height) / 2.0_f32.sqrt();
305 ellipse_contains(center, [resolve_length(*radius, diagonal); 2], point)
306 }
307 ClipShape::Ellipse {
308 radius_x,
309 radius_y,
310 center,
311 } => ellipse_contains(
312 resolve_position(*center, reference),
313 [
314 resolve_length(*radius_x, reference.width),
315 resolve_length(*radius_y, reference.height),
316 ],
317 point,
318 ),
319 ClipShape::Polygon { fill_rule, points } => {
320 let mut winding = Winding::new(*fill_rule, point);
321 let Some(first) = points.first().copied() else {
322 return false;
323 };
324 let first = resolve_position(first, reference);
325 let mut previous = first;
326 for position in &points[1..] {
327 let current = resolve_position(*position, reference);
328 winding.segment(previous, current);
329 previous = current;
330 }
331 winding.segment(previous, first);
332 winding.contains()
333 }
334 ClipShape::Path {
335 fill_rule,
336 commands,
337 } => path_contains(*fill_rule, commands, reference, point),
338 }
339}
340
341fn ellipse_contains(center: [f32; 2], radii: [f32; 2], point: InputPoint) -> bool {
342 if radii[0] <= 0.0 || radii[1] <= 0.0 {
343 return false;
344 }
345 let x = (point.x - center[0]) / radii[0];
346 let y = (point.y - center[1]) / radii[1];
347 x * x + y * y <= 1.0
348}
349
350fn rounded_rect_contains(rect: LayoutRect, radii: ([f32; 4], [f32; 4]), point: InputPoint) -> bool {
351 if !contains_axis(point.x, rect.x, rect.width) || !contains_axis(point.y, rect.y, rect.height) {
352 return false;
353 }
354 let (horizontal, vertical) = radii;
355 let corners = [
356 (
357 0,
358 [rect.x + horizontal[0], rect.y + vertical[0]],
359 -1.0,
360 -1.0,
361 ),
362 (
363 1,
364 [rect.x + rect.width - horizontal[1], rect.y + vertical[1]],
365 1.0,
366 -1.0,
367 ),
368 (
369 2,
370 [
371 rect.x + rect.width - horizontal[2],
372 rect.y + rect.height - vertical[2],
373 ],
374 1.0,
375 1.0,
376 ),
377 (
378 3,
379 [rect.x + horizontal[3], rect.y + rect.height - vertical[3]],
380 -1.0,
381 1.0,
382 ),
383 ];
384 for (index, center, x_sign, y_sign) in corners {
385 let in_x_corner = (point.x - center[0]) * x_sign > 0.0;
386 let in_y_corner = (point.y - center[1]) * y_sign > 0.0;
387 if in_x_corner && in_y_corner {
388 return ellipse_contains(center, [horizontal[index], vertical[index]], point);
389 }
390 }
391 true
392}
393
394fn resolve_radii(
395 radii: &PaintCorners<PaintCornerRadius>,
396 rect: LayoutRect,
397) -> ([f32; 4], [f32; 4]) {
398 let values = [
399 radii.top_left,
400 radii.top_right,
401 radii.bottom_right,
402 radii.bottom_left,
403 ];
404 let mut horizontal = values.map(|radius| resolve_length(radius.horizontal, rect.width));
405 let mut vertical = values.map(|radius| resolve_length(radius.vertical, rect.height));
406 let scale = [
407 radius_scale(rect.width, horizontal[0] + horizontal[1]),
408 radius_scale(rect.width, horizontal[3] + horizontal[2]),
409 radius_scale(rect.height, vertical[0] + vertical[3]),
410 radius_scale(rect.height, vertical[1] + vertical[2]),
411 ]
412 .into_iter()
413 .fold(1.0_f32, f32::min);
414 for value in &mut horizontal {
415 *value *= scale;
416 }
417 for value in &mut vertical {
418 *value *= scale;
419 }
420 (horizontal, vertical)
421}
422
423fn radius_scale(available: f32, required: f32) -> f32 {
424 if required > available && required > 0.0 {
425 available / required
426 } else {
427 1.0
428 }
429}
430
431fn resolve_length(value: PaintLengthPercentage, available: f32) -> f32 {
432 value.length + value.fraction * available
433}
434
435fn resolve_coordinate(value: PaintCoordinate, available: f32) -> f32 {
436 value.length + value.fraction * available
437}
438
439fn resolve_position(position: PaintPosition, reference: LayoutRect) -> [f32; 2] {
440 [
441 reference.x + resolve_coordinate(position.x, reference.width),
442 reference.y + resolve_coordinate(position.y, reference.height),
443 ]
444}
445
446struct Winding {
447 rule: FillRule,
448 point: InputPoint,
449 winding: i32,
450 parity: bool,
451}
452
453impl Winding {
454 const fn new(rule: FillRule, point: InputPoint) -> Self {
455 Self {
456 rule,
457 point,
458 winding: 0,
459 parity: false,
460 }
461 }
462
463 fn segment(&mut self, from: [f32; 2], to: [f32; 2]) {
464 let crosses = (from[1] <= self.point.y && to[1] > self.point.y)
465 || (from[1] > self.point.y && to[1] <= self.point.y);
466 if !crosses {
467 return;
468 }
469 let intersection =
470 from[0] + (self.point.y - from[1]) * (to[0] - from[0]) / (to[1] - from[1]);
471 if intersection <= self.point.x {
472 return;
473 }
474 self.parity = !self.parity;
475 self.winding += if to[1] > from[1] { 1 } else { -1 };
476 }
477
478 const fn contains(&self) -> bool {
479 match self.rule {
480 FillRule::NonZero => self.winding != 0,
481 FillRule::EvenOdd => self.parity,
482 }
483 }
484}
485
486fn path_contains(
487 fill_rule: FillRule,
488 commands: &[PathCommand],
489 reference: LayoutRect,
490 point: InputPoint,
491) -> bool {
492 const CURVE_STEPS: usize = 16;
493 let mut winding = Winding::new(fill_rule, point);
494 let mut current = None;
495 let mut start = None;
496 let close = |winding: &mut Winding, current: &mut Option<[f32; 2]>, start| {
497 if let (Some(from), Some(to)) = (*current, start) {
498 winding.segment(from, to);
499 *current = Some(to);
500 }
501 };
502 for command in commands {
503 match command {
504 PathCommand::MoveTo(position) => {
505 close(&mut winding, &mut current, start);
506 let next = resolve_position(*position, reference);
507 current = Some(next);
508 start = Some(next);
509 }
510 PathCommand::LineTo(position) => {
511 let next = resolve_position(*position, reference);
512 if let Some(previous) = current {
513 winding.segment(previous, next);
514 }
515 current = Some(next);
516 }
517 PathCommand::QuadraticTo { control, end } => {
518 let Some(from) = current else { continue };
519 let control = resolve_position(*control, reference);
520 let end = resolve_position(*end, reference);
521 let mut previous = from;
522 for step in 1..=CURVE_STEPS {
523 let t = step as f32 / CURVE_STEPS as f32;
524 let inverse = 1.0 - t;
525 let next = [
526 inverse * inverse * from[0]
527 + 2.0 * inverse * t * control[0]
528 + t * t * end[0],
529 inverse * inverse * from[1]
530 + 2.0 * inverse * t * control[1]
531 + t * t * end[1],
532 ];
533 winding.segment(previous, next);
534 previous = next;
535 }
536 current = Some(end);
537 }
538 PathCommand::CubicTo {
539 control_1,
540 control_2,
541 end,
542 } => {
543 let Some(from) = current else { continue };
544 let control_1 = resolve_position(*control_1, reference);
545 let control_2 = resolve_position(*control_2, reference);
546 let end = resolve_position(*end, reference);
547 let mut previous = from;
548 for step in 1..=CURVE_STEPS {
549 let t = step as f32 / CURVE_STEPS as f32;
550 let inverse = 1.0 - t;
551 let next = [
552 inverse.powi(3) * from[0]
553 + 3.0 * inverse * inverse * t * control_1[0]
554 + 3.0 * inverse * t * t * control_2[0]
555 + t.powi(3) * end[0],
556 inverse.powi(3) * from[1]
557 + 3.0 * inverse * inverse * t * control_1[1]
558 + 3.0 * inverse * t * t * control_2[1]
559 + t.powi(3) * end[1],
560 ];
561 winding.segment(previous, next);
562 previous = next;
563 }
564 current = Some(end);
565 }
566 PathCommand::Close => close(&mut winding, &mut current, start),
567 }
568 }
569 close(&mut winding, &mut current, start);
570 winding.contains()
571}
572
573#[cfg(test)]
574mod tests {
575 use whisker_protocol::{
576 BorderLineStyle, BoxClip, BoxPaint, ElementTypeId, LayoutRect, PaintColor, PaintEdges,
577 SurfaceId, VisualEffects,
578 };
579
580 use super::*;
581
582 fn scene_with_child() -> (Scene, NodeId, NodeId) {
583 let mut scene = Scene::new(SurfaceId::new(1).unwrap());
584 let element = ElementTypeId::new(1).unwrap();
585 let root = scene.create_node(element).unwrap();
586 let child = scene.create_node(element).unwrap();
587 scene.insert_child(root, child, 0).unwrap();
588 scene
589 .set_layout(
590 root,
591 LayoutRect {
592 x: 0.0,
593 y: 0.0,
594 width: 300.0,
595 height: 300.0,
596 },
597 )
598 .unwrap();
599 scene
600 .set_layout(
601 child,
602 LayoutRect {
603 x: 0.0,
604 y: 0.0,
605 width: 50.0,
606 height: 50.0,
607 },
608 )
609 .unwrap();
610 (scene, root, child)
611 }
612
613 fn length(value: f32) -> PaintLengthPercentage {
614 PaintLengthPercentage {
615 length: value,
616 fraction: 0.0,
617 }
618 }
619
620 fn coordinate(x: f32, y: f32) -> PaintPosition {
621 PaintPosition {
622 x: PaintCoordinate {
623 length: x,
624 fraction: 0.0,
625 },
626 y: PaintCoordinate {
627 length: y,
628 fraction: 0.0,
629 },
630 }
631 }
632
633 fn radii(value: f32) -> PaintCorners<PaintCornerRadius> {
634 let radius = PaintCornerRadius::circular(length(value));
635 PaintCorners {
636 top_left: radius,
637 top_right: radius,
638 bottom_right: radius,
639 bottom_left: radius,
640 }
641 }
642
643 fn bordered_paint(width: f32, radius: f32) -> BoxPaint {
644 let transparent = PaintColor::Named("transparent".into());
645 BoxPaint {
646 background_color: transparent.clone(),
647 border_widths: PaintEdges {
648 top: length(width),
649 right: length(width),
650 bottom: length(width),
651 left: length(width),
652 },
653 border_colors: PaintEdges {
654 top: transparent.clone(),
655 right: transparent.clone(),
656 bottom: transparent.clone(),
657 left: transparent,
658 },
659 border_styles: PaintEdges {
660 top: BorderLineStyle::None,
661 right: BorderLineStyle::None,
662 bottom: BorderLineStyle::None,
663 left: BorderLineStyle::None,
664 },
665 border_radii: radii(radius),
666 }
667 }
668
669 #[test]
670 fn transforms_hit_geometry_and_hidden_parents_keep_visible_descendants() {
671 let (mut scene, root, child) = scene_with_child();
672 let mut translated = Transform::IDENTITY;
673 translated.0[12] = 100.0;
674 scene.set_transform(child, translated).unwrap();
675
676 assert_eq!(
677 scene.hit_test(root, InputPoint { x: 110.0, y: 10.0 }),
678 Ok(Some(child))
679 );
680 assert_eq!(
681 scene.hit_test(root, InputPoint { x: 10.0, y: 10.0 }),
682 Ok(Some(root))
683 );
684
685 scene.set_visibility(root, Visibility::Hidden).unwrap();
686 scene.set_visibility(child, Visibility::Visible).unwrap();
687 assert_eq!(
688 scene.hit_test(root, InputPoint { x: 110.0, y: 10.0 }),
689 Ok(Some(child))
690 );
691 }
692
693 #[test]
694 fn host_scroll_offset_tracks_native_presentation_without_dirtying_a_frame() {
695 let (mut scene, root, child) = scene_with_child();
696 assert_eq!(
697 scene.update_host_scroll_offset(root, [f32::NAN, 0.0]),
698 Err(SceneError::NonFiniteNumber)
699 );
700 scene
701 .set_layout(
702 child,
703 LayoutRect {
704 x: 0.0,
705 y: 120.0,
706 width: 50.0,
707 height: 50.0,
708 },
709 )
710 .unwrap();
711 scene
712 .set_clip(
713 root,
714 BoxClip {
715 horizontal: OverflowClip::Hidden,
716 vertical: OverflowClip::Hidden,
717 },
718 )
719 .unwrap();
720 scene.update_host_scroll_offset(root, [0.0, 100.0]).unwrap();
721
722 assert_eq!(scene.node(root).unwrap().host_scroll_offset(), [0.0, 100.0]);
723 assert_eq!(
724 scene.hit_test(root, InputPoint { x: 10.0, y: 30.0 }),
725 Ok(Some(child))
726 );
727 }
728
729 #[test]
730 fn clip_paths_and_rounded_overflow_restrict_descendant_hits() {
731 let (mut scene, root, child) = scene_with_child();
732 scene
733 .set_layout(
734 child,
735 LayoutRect {
736 x: 0.0,
737 y: 0.0,
738 width: 300.0,
739 height: 300.0,
740 },
741 )
742 .unwrap();
743 let effects = VisualEffects {
744 clip_path: Some((
745 PaintBox::Border,
746 ClipShape::Circle {
747 radius: PaintLengthPercentage {
748 length: 50.0,
749 fraction: 0.0,
750 },
751 center: PaintPosition {
752 x: PaintCoordinate {
753 length: 0.0,
754 fraction: 0.5,
755 },
756 y: PaintCoordinate {
757 length: 0.0,
758 fraction: 0.5,
759 },
760 },
761 },
762 )),
763 ..VisualEffects::default()
764 };
765 scene.set_visual_effects(root, effects).unwrap();
766 assert_eq!(
767 scene.hit_test(root, InputPoint { x: 150.0, y: 150.0 }),
768 Ok(Some(child))
769 );
770 assert_eq!(
771 scene.hit_test(root, InputPoint { x: 10.0, y: 10.0 }),
772 Ok(None)
773 );
774
775 scene
776 .set_visual_effects(root, VisualEffects::default())
777 .unwrap();
778 scene
779 .set_clip(
780 root,
781 BoxClip {
782 horizontal: OverflowClip::Hidden,
783 vertical: OverflowClip::Hidden,
784 },
785 )
786 .unwrap();
787 let radius = PaintCornerRadius::circular(PaintLengthPercentage {
788 length: 100.0,
789 fraction: 0.0,
790 });
791 scene
792 .set_box_paint(
793 root,
794 whisker_protocol::BoxPaint {
795 background_color: PaintColor::Named("transparent".into()),
796 border_widths: PaintEdges {
797 top: PaintLengthPercentage::default(),
798 right: PaintLengthPercentage::default(),
799 bottom: PaintLengthPercentage::default(),
800 left: PaintLengthPercentage::default(),
801 },
802 border_colors: PaintEdges {
803 top: PaintColor::Named("transparent".into()),
804 right: PaintColor::Named("transparent".into()),
805 bottom: PaintColor::Named("transparent".into()),
806 left: PaintColor::Named("transparent".into()),
807 },
808 border_styles: PaintEdges {
809 top: whisker_protocol::BorderLineStyle::None,
810 right: whisker_protocol::BorderLineStyle::None,
811 bottom: whisker_protocol::BorderLineStyle::None,
812 left: whisker_protocol::BorderLineStyle::None,
813 },
814 border_radii: PaintCorners {
815 top_left: radius,
816 top_right: radius,
817 bottom_right: radius,
818 bottom_left: radius,
819 },
820 },
821 )
822 .unwrap();
823 assert_eq!(
824 scene.hit_test(root, InputPoint { x: 10.0, y: 10.0 }),
825 Ok(Some(root))
826 );
827 }
828
829 #[test]
830 fn inverse_mapping_rejects_singular_and_projective_horizon_matrices() {
831 let point = InputPoint { x: 1.0, y: 1.0 };
832 assert_eq!(
833 inverse_map_around(Some(Transform([0.0; 16])), point, [0.0; 2]),
834 None
835 );
836
837 let mut projective = Transform::IDENTITY;
838 projective.0[3] = 1.0;
839 assert_eq!(inverse_map_around(Some(projective), point, [0.0; 2]), None);
840 assert_eq!(inverse_map_around(None, point, [0.0; 2]), Some(point));
841 assert_eq!(
842 inverse_map_around(Some(Transform::IDENTITY), point, [0.0; 2]),
843 Some(point)
844 );
845
846 let (mut scene, root, _) = scene_with_child();
847 scene.set_transform(root, Transform([0.0; 16])).unwrap();
848 assert_eq!(scene.hit_test(root, point), Ok(None));
849 }
850
851 #[test]
852 fn clip_reference_boxes_and_shape_families_are_resolved_in_rust() {
853 let (mut scene, root, _) = scene_with_child();
854 let border = LayoutRect {
855 x: 10.0,
856 y: 20.0,
857 width: 100.0,
858 height: 80.0,
859 };
860 let content = LayoutRect {
861 x: 10.0,
862 y: 10.0,
863 width: 80.0,
864 height: 60.0,
865 };
866 assert_eq!(padding_box(scene.node(root).unwrap(), border), border);
867
868 scene
869 .set_box_paint(root, bordered_paint(5.0, 10.0))
870 .unwrap();
871 assert_eq!(
872 padding_box(scene.node(root).unwrap(), border),
873 LayoutRect {
874 x: 15.0,
875 y: 25.0,
876 width: 90.0,
877 height: 70.0,
878 }
879 );
880
881 for reference_box in [PaintBox::Content, PaintBox::Padding] {
882 scene
883 .set_visual_effects(
884 root,
885 VisualEffects {
886 clip_path: Some((
887 reference_box,
888 ClipShape::Ellipse {
889 radius_x: length(100.0),
890 radius_y: length(100.0),
891 center: coordinate(50.0, 40.0),
892 },
893 )),
894 ..VisualEffects::default()
895 },
896 )
897 .unwrap();
898 assert!(clip_path_contains(
899 scene.node(root).unwrap(),
900 content,
901 border,
902 InputPoint { x: 60.0, y: 60.0 },
903 ));
904 }
905
906 let reference = LayoutRect {
907 width: 100.0,
908 height: 100.0,
909 ..LayoutRect::default()
910 };
911 let point = InputPoint { x: 50.0, y: 50.0 };
912 assert!(shape_contains(
913 &ClipShape::Inset {
914 edges: PaintEdges {
915 top: PaintCoordinate::default(),
916 right: PaintCoordinate::default(),
917 bottom: PaintCoordinate::default(),
918 left: PaintCoordinate::default(),
919 },
920 radii: radii(0.0),
921 },
922 reference,
923 point,
924 ));
925 assert!(shape_contains(
926 &ClipShape::Ellipse {
927 radius_x: length(50.0),
928 radius_y: length(25.0),
929 center: coordinate(50.0, 50.0),
930 },
931 reference,
932 point,
933 ));
934 assert!(!shape_contains(
935 &ClipShape::Polygon {
936 fill_rule: FillRule::NonZero,
937 points: Vec::new(),
938 },
939 reference,
940 point,
941 ));
942 let square = vec![
943 coordinate(0.0, 0.0),
944 coordinate(100.0, 0.0),
945 coordinate(100.0, 100.0),
946 coordinate(0.0, 100.0),
947 ];
948 for fill_rule in [FillRule::NonZero, FillRule::EvenOdd] {
949 assert!(shape_contains(
950 &ClipShape::Polygon {
951 fill_rule,
952 points: square.clone(),
953 },
954 reference,
955 point,
956 ));
957 }
958 assert!(!ellipse_contains([0.0, 0.0], [0.0, 1.0], point));
959 }
960
961 #[test]
962 fn path_hit_testing_flattens_lines_and_curves() {
963 let reference = LayoutRect {
964 width: 100.0,
965 height: 100.0,
966 ..LayoutRect::default()
967 };
968 let inside = InputPoint { x: 50.0, y: 50.0 };
969 assert!(!path_contains(
970 FillRule::NonZero,
971 &[PathCommand::QuadraticTo {
972 control: coordinate(1.0, 1.0),
973 end: coordinate(2.0, 2.0),
974 }],
975 reference,
976 inside,
977 ));
978 assert!(!path_contains(
979 FillRule::NonZero,
980 &[PathCommand::CubicTo {
981 control_1: coordinate(1.0, 1.0),
982 control_2: coordinate(2.0, 2.0),
983 end: coordinate(3.0, 3.0),
984 }],
985 reference,
986 inside,
987 ));
988 assert!(!path_contains(
989 FillRule::NonZero,
990 &[PathCommand::LineTo(coordinate(1.0, 1.0))],
991 reference,
992 inside,
993 ));
994
995 let curved_box = ClipShape::Path {
996 fill_rule: FillRule::EvenOdd,
997 commands: vec![
998 PathCommand::MoveTo(coordinate(0.0, 0.0)),
999 PathCommand::MoveTo(coordinate(0.0, 0.0)),
1000 PathCommand::LineTo(coordinate(100.0, 0.0)),
1001 PathCommand::QuadraticTo {
1002 control: coordinate(100.0, 50.0),
1003 end: coordinate(100.0, 100.0),
1004 },
1005 PathCommand::CubicTo {
1006 control_1: coordinate(50.0, 100.0),
1007 control_2: coordinate(0.0, 100.0),
1008 end: coordinate(0.0, 0.0),
1009 },
1010 PathCommand::Close,
1011 ],
1012 };
1013 assert!(shape_contains(&curved_box, reference, inside));
1014 }
1015
1016 #[test]
1017 fn winding_rounding_and_one_axis_overflow_cover_edge_geometry() {
1018 let point = InputPoint { x: 0.0, y: 0.0 };
1019 let mut winding = Winding::new(FillRule::NonZero, point);
1020 winding.segment([-2.0, -2.0], [-2.0, 2.0]);
1021 winding.segment([-2.0, 2.0], [2.0, 2.0]);
1022 winding.segment([2.0, 2.0], [2.0, -2.0]);
1023 assert!(winding.contains());
1024 winding.segment([2.0, -2.0], [-2.0, -2.0]);
1025 assert!(winding.contains());
1026 let mut even_odd = Winding::new(FillRule::EvenOdd, point);
1027 even_odd.segment([2.0, -2.0], [2.0, 2.0]);
1028 assert!(even_odd.contains());
1029
1030 let rect = LayoutRect {
1031 width: 100.0,
1032 height: 100.0,
1033 ..LayoutRect::default()
1034 };
1035 assert!(!rounded_rect_contains(
1036 rect,
1037 ([10.0; 4], [10.0; 4]),
1038 InputPoint { x: -1.0, y: 50.0 },
1039 ));
1040 for point in [
1041 InputPoint { x: 1.0, y: 1.0 },
1042 InputPoint { x: 99.0, y: 1.0 },
1043 InputPoint { x: 99.0, y: 99.0 },
1044 InputPoint { x: 1.0, y: 99.0 },
1045 ] {
1046 assert!(!rounded_rect_contains(rect, ([10.0; 4], [10.0; 4]), point));
1047 }
1048 assert!(rounded_rect_contains(
1049 rect,
1050 ([10.0; 4], [10.0; 4]),
1051 InputPoint { x: 50.0, y: 50.0 },
1052 ));
1053 let (horizontal, vertical) = resolve_radii(&radii(80.0), rect);
1054 assert_eq!(horizontal, [50.0; 4]);
1055 assert_eq!(vertical, [50.0; 4]);
1056 assert_eq!(radius_scale(0.0, 0.0), 1.0);
1057
1058 let (mut scene, root, _) = scene_with_child();
1059 scene.set_box_paint(root, bordered_paint(5.0, 0.0)).unwrap();
1060 scene
1061 .set_clip(
1062 root,
1063 BoxClip {
1064 horizontal: OverflowClip::Hidden,
1065 vertical: OverflowClip::Visible,
1066 },
1067 )
1068 .unwrap();
1069 assert_eq!(
1070 overflow_clip_contains(
1071 scene.node(root).unwrap(),
1072 rect,
1073 InputPoint { x: 50.0, y: 50.0 },
1074 ),
1075 [true, true]
1076 );
1077 }
1078}