waft_gestures/hit_test.rs
1//! Flutter counterpart: `gestures/hit_test.dart`.
2
3use std::any::Any;
4use std::fmt::{self, Debug};
5use std::rc::Rc;
6
7use waft_embedder::{Matrix4, Offset, ViewId};
8use waft_foundation::{AnyRef, App, HandleId};
9
10use crate::events::PointerEvent;
11
12/// How far an entry of [`HitTestResult::push_transform`]'s third row or column may be from
13/// `(0, 0, 1, 0)`.
14///
15/// Dart checks against `precisionErrorTolerance` (1e-10), which suits vector_math's f64
16/// matrices. [`Matrix4`] is f32, and a single f32 inverse already leaves the diagonal entry
17/// one ulp below 1 (6e-8). Eight f32 epsilons (about 1e-6) is sixteen times the worst a
18/// million inverted scale, rotation, skew and translation chains produced, and still catches
19/// any perspective a transform could carry.
20const MATRIX_PRECISION_ERROR_TOLERANCE: f64 = 8.0 * f32::EPSILON as f64;
21
22/// An object that can hit-test pointers.
23pub trait HitTestable {
24 /// Fills the provided [`HitTestResult`] with [`HitTestEntry`]s for objects that
25 /// are hit at the given `position` in the view identified by `view_id`.
26 fn hit_test_in_view(
27 &self,
28 app: &mut App,
29 result: &mut HitTestResult,
30 position: Offset,
31 view_id: ViewId,
32 );
33}
34
35/// An object that can dispatch events.
36pub trait HitTestDispatcher {
37 /// Override this method to dispatch events.
38 fn dispatch_event(&self, app: &mut App, event: PointerEvent, result: &HitTestResult);
39}
40
41/// An object that can handle events.
42pub trait HitTestTarget: Debug + Any {
43 /// Override this method to receive events.
44 fn handle_event(&self, app: &mut App, event: &PointerEvent, entry: &HitTestEntry);
45
46 /// The arena object this target delivers to, if it is one, so a result kept across turns
47 /// keeps it ([`HitTestResult::keep_targets`]): Dart keeps the object alive by holding it in
48 /// the path.
49 fn arena_id(&self) -> Option<HandleId> {
50 None
51 }
52}
53
54/// Data collected during a hit test about a specific [`HitTestTarget`].
55///
56/// Subclass this object to pass additional information from the hit test phase
57/// to the event propagation phase.
58pub struct HitTestEntry {
59 target: Rc<dyn HitTestTarget>,
60 transform: Option<Matrix4>,
61}
62
63impl HitTestEntry {
64 /// Creates a hit test entry.
65 pub fn new(target: impl HitTestTarget + 'static) -> HitTestEntry {
66 HitTestEntry {
67 target: Rc::new(target),
68 transform: None,
69 }
70 }
71
72 /// The [`HitTestTarget`] encountered during the hit test.
73 pub fn target(&self) -> &dyn HitTestTarget {
74 &*self.target
75 }
76
77 /// The [`target`](Self::target) as the `Rc` that holds it, to keep it past the hit test.
78 pub fn shared_target(&self) -> &Rc<dyn HitTestTarget> {
79 &self.target
80 }
81
82 /// Returns a matrix describing how [`PointerEvent`]s delivered to this
83 /// [`HitTestEntry`] should be transformed from the global coordinate space of
84 /// the screen to the local coordinate space of [`target`](Self::target).
85 ///
86 /// See also:
87 ///
88 /// * `BoxHitTestResult.addWithPaintTransform`, which is used during hit testing
89 /// to build up this transform.
90 pub fn transform(&self) -> Option<Matrix4> {
91 self.transform
92 }
93}
94
95/// An entry for a target that others hold too, such as a span of a paragraph's text.
96impl From<Rc<dyn HitTestTarget>> for HitTestEntry {
97 fn from(target: Rc<dyn HitTestTarget>) -> HitTestEntry {
98 HitTestEntry {
99 target,
100 transform: None,
101 }
102 }
103}
104
105impl Debug for HitTestEntry {
106 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
107 write!(f, "HitTestEntry({:?})", self.target)
108 }
109}
110
111/// A type of data that can be applied to a matrix by left-multiplication.
112enum TransformPart {
113 Matrix(Matrix4),
114 Offset(Offset),
115}
116
117impl TransformPart {
118 /// Apply this transform part to `rhs` from the left.
119 ///
120 /// This should work as if this transform part is first converted to a matrix
121 /// and then left-multiplied to `rhs`.
122 fn multiply(&self, rhs: Matrix4) -> Matrix4 {
123 match *self {
124 TransformPart::Matrix(matrix) => matrix.then(&rhs),
125 TransformPart::Offset(offset) => {
126 Matrix4::translation(offset.dx() as f32, offset.dy() as f32).then(&rhs)
127 }
128 }
129 }
130}
131
132/// The result of performing a hit test.
133///
134/// Dart's `HitTestResult.wrap` shares one result between a base and a subtype
135/// view; here that view is `&mut HitTestResult` (or a newtype over it, such as
136/// `BoxHitTestResult`).
137pub struct HitTestResult {
138 path: Vec<HitTestEntry>,
139 /// The references that keep the path's targets while the result outlives its turn;
140 /// empty until [`keep_targets`](Self::keep_targets).
141 kept: Vec<AnyRef>,
142 // A stack of transform parts.
143 //
144 // The transform part stack leading from global to the current object is stored
145 // in 2 parts:
146 //
147 // * `transforms` are globalized matrices, meaning they have been multiplied
148 // by the ancestors and are thus relative to the global coordinate space.
149 // * `local_transforms` are local transform parts, which are relative to the
150 // parent's coordinate space.
151 //
152 // When new transform parts are added they're appended to `local_transforms`,
153 // and are converted to global ones and moved to `transforms` only when used.
154 transforms: Vec<Matrix4>,
155 local_transforms: Vec<TransformPart>,
156}
157
158impl HitTestResult {
159 /// Creates an empty hit test result.
160 pub fn new() -> HitTestResult {
161 HitTestResult {
162 path: Vec::new(),
163 kept: Vec::new(),
164 transforms: vec![Matrix4::IDENTITY],
165 local_transforms: Vec::new(),
166 }
167 }
168
169 /// Keeps every object on the path, for a result kept past this turn (Dart keeps them alive
170 /// by holding the path). The references live in the result: dropping it lets go of them.
171 pub fn keep_targets(&mut self, app: &App) {
172 if !self.kept.is_empty() {
173 return;
174 }
175 self.kept = self
176 .path
177 .iter()
178 .filter_map(|entry| entry.target.arena_id())
179 .filter_map(|id| id.upgrade(app))
180 .collect();
181 }
182
183 /// An unmodifiable list of [`HitTestEntry`] objects recorded during the hit test.
184 ///
185 /// The first entry in the path is the most specific, typically the one at
186 /// the leaf of tree being hit tested. Event propagation starts with the most
187 /// specific (i.e., first) entry and proceeds in order through the path.
188 pub fn path(&self) -> &[HitTestEntry] {
189 &self.path
190 }
191
192 // Globalize all transform parts in `local_transforms` and move them to
193 // `transforms`.
194 fn globalize_transforms(&mut self) {
195 if self.local_transforms.is_empty() {
196 return;
197 }
198 let mut last = *self.transforms.last().unwrap();
199 for part in self.local_transforms.drain(..) {
200 last = part.multiply(last);
201 self.transforms.push(last);
202 }
203 }
204
205 fn last_transform(&mut self) -> Matrix4 {
206 self.globalize_transforms();
207 debug_assert!(self.local_transforms.is_empty());
208 *self.transforms.last().unwrap()
209 }
210
211 /// Add a [`HitTestEntry`] to the path.
212 ///
213 /// The new entry is added at the end of the path, which means entries should
214 /// be added in order from most specific to least specific, typically during an
215 /// upward walk of the tree being hit tested.
216 pub fn add(&mut self, mut entry: HitTestEntry) {
217 debug_assert!(entry.transform.is_none());
218 entry.transform = Some(self.last_transform());
219 self.path.push(entry);
220 }
221
222 /// Pushes a new transform matrix that is to be applied to all future
223 /// [`HitTestEntry`]s added via [`add`](Self::add) until it is removed via [`pop_transform`](Self::pop_transform).
224 ///
225 /// This method is only to be used by subclasses, which must provide
226 /// coordinate space specific public wrappers around this function for their
227 /// users (see `BoxHitTestResult.addWithPaintTransform` for such an example).
228 ///
229 /// The provided `transform` matrix should describe how to transform
230 /// [`PointerEvent`]s from the coordinate space of the method caller to the
231 /// coordinate space of its children. In most cases `transform` is derived
232 /// from running the inverted result of `RenderObject.applyPaintTransform`
233 /// through [`remove_perspective_transform`](crate::remove_perspective_transform) to remove
234 /// the perspective component.
235 ///
236 /// If the provided `transform` is a translation matrix, it is much faster
237 /// to use [`push_offset`](Self::push_offset) with the translation offset instead.
238 ///
239 /// [`HitTestable`]s need to call this method indirectly through a convenience
240 /// method defined on a subclass before hit testing a child that does not
241 /// have the same origin as the parent. After hit testing the child,
242 /// [`pop_transform`](Self::pop_transform) has to be called to remove the child-specific `transform`.
243 ///
244 /// See also:
245 ///
246 /// * [`push_offset`](Self::push_offset), which is similar to [`push_transform`](Self::push_transform) but is limited to
247 /// translations, and is faster in such cases.
248 /// * `BoxHitTestResult.addWithPaintTransform`, which is a public wrapper
249 /// around this function for hit testing on `RenderBox`s.
250 pub fn push_transform(&mut self, transform: Matrix4) {
251 debug_assert!(
252 {
253 let values = transform.to_flutter_array();
254 let row2 = [values[2], values[6], values[10], values[14]];
255 let col2 = [values[8], values[9], values[10], values[11]];
256 debug_vector_more_or_less_equals(
257 row2,
258 [0.0, 0.0, 1.0, 0.0],
259 MATRIX_PRECISION_ERROR_TOLERANCE,
260 ) && debug_vector_more_or_less_equals(
261 col2,
262 [0.0, 0.0, 1.0, 0.0],
263 MATRIX_PRECISION_ERROR_TOLERANCE,
264 )
265 },
266 "The third row and third column of a transform matrix for pointer \
267 events must be Vector4(0, 0, 1, 0) to ensure that a transformed \
268 point is directly under the pointing device. Did you forget to run the paint \
269 matrix through remove_perspective_transform? \
270 The provided matrix is:\n{transform:?}"
271 );
272 self.local_transforms.push(TransformPart::Matrix(transform));
273 }
274
275 /// Pushes a new translation offset that is to be applied to all future
276 /// [`HitTestEntry`]s added via [`add`](Self::add) until it is removed via [`pop_transform`](Self::pop_transform).
277 ///
278 /// This method is only to be used by subclasses, which must provide
279 /// coordinate space specific public wrappers around this function for their
280 /// users (see `BoxHitTestResult.addWithPaintOffset` for such an example).
281 ///
282 /// The provided `offset` should describe how to transform [`PointerEvent`]s from
283 /// the coordinate space of the method caller to the coordinate space of its
284 /// children. Usually `offset` is the inverse of the offset of the child
285 /// relative to the parent.
286 ///
287 /// [`HitTestable`]s need to call this method indirectly through a convenience
288 /// method defined on a subclass before hit testing a child that does not
289 /// have the same origin as the parent. After hit testing the child,
290 /// [`pop_transform`](Self::pop_transform) has to be called to remove the child-specific `transform`.
291 ///
292 /// See also:
293 ///
294 /// * [`push_transform`](Self::push_transform), which is similar to [`push_offset`](Self::push_offset) but allows general
295 /// transform besides translation.
296 /// * `BoxHitTestResult.addWithPaintOffset`, which is a public wrapper
297 /// around this function for hit testing on `RenderBox`s.
298 /// * `SliverHitTestResult.addWithAxisOffset`, which is a public wrapper
299 /// around this function for hit testing on `RenderSliver`s.
300 pub fn push_offset(&mut self, offset: Offset) {
301 self.local_transforms.push(TransformPart::Offset(offset));
302 }
303
304 /// Removes the last transform added via [`push_transform`](Self::push_transform) or [`push_offset`](Self::push_offset).
305 ///
306 /// This method is only to be used by subclasses, which must provide
307 /// coordinate space specific public wrappers around this function for their
308 /// users (see `BoxHitTestResult.addWithPaintTransform` for such an example).
309 ///
310 /// This method must be called after hit testing is done on a child that
311 /// required a call to [`push_transform`](Self::push_transform) or [`push_offset`](Self::push_offset).
312 ///
313 /// See also:
314 ///
315 /// * [`push_transform`](Self::push_transform) and [`push_offset`](Self::push_offset), which describes the use case of this
316 /// function pair in more details.
317 pub fn pop_transform(&mut self) {
318 if !self.local_transforms.is_empty() {
319 self.local_transforms.pop();
320 } else {
321 self.transforms.pop();
322 }
323 debug_assert!(!self.transforms.is_empty());
324 }
325}
326
327impl Default for HitTestResult {
328 fn default() -> HitTestResult {
329 HitTestResult::new()
330 }
331}
332
333impl Debug for HitTestResult {
334 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
335 if self.path.is_empty() {
336 return write!(f, "HitTestResult(<empty path>)");
337 }
338 write!(f, "HitTestResult(")?;
339 for (i, entry) in self.path.iter().enumerate() {
340 if i > 0 {
341 write!(f, ", ")?;
342 }
343 write!(f, "{entry:?}")?;
344 }
345 write!(f, ")")
346 }
347}
348
349fn debug_vector_more_or_less_equals(a: [f32; 4], b: [f32; 4], epsilon: f64) -> bool {
350 let mut result = true;
351 if cfg!(debug_assertions) {
352 result = a
353 .iter()
354 .zip(b)
355 .all(|(component, expected)| (*component as f64 - expected as f64).abs() < epsilon);
356 }
357 result
358}
359
360#[cfg(test)]
361mod tests {
362 use super::*;
363
364 #[derive(Debug)]
365 struct DummyHitTestTarget;
366
367 impl HitTestTarget for DummyHitTestTarget {
368 fn handle_event(&self, _app: &mut App, _event: &PointerEvent, _entry: &HitTestEntry) {}
369 }
370
371 fn current_transform(result: &mut HitTestResult) -> Matrix4 {
372 result.add(HitTestEntry::new(DummyHitTestTarget));
373 result.path().last().unwrap().transform().unwrap()
374 }
375
376 #[test]
377 fn add_records_the_current_transform_on_the_entry() {
378 let transform = Matrix4::translation(40.0, 150.0);
379 let mut result = HitTestResult::new();
380 result.push_transform(transform);
381 result.add(HitTestEntry::new(DummyHitTestTarget));
382 result.add(HitTestEntry::new(DummyHitTestTarget));
383 assert_eq!(result.path().len(), 2);
384 assert!(
385 result
386 .path()
387 .iter()
388 .all(|entry| entry.transform() == Some(transform))
389 );
390 }
391
392 #[test]
393 fn push_and_pop_transforms() {
394 let mut result = HitTestResult::new();
395
396 let m1 = Matrix4::translation(10.0, 20.0);
397 let m2 = Matrix4::rotation(1.0);
398 let m3 = Matrix4::scale(1.1, 1.2);
399
400 result.push_transform(m1);
401 assert_eq!(current_transform(&mut result), m1);
402
403 result.push_transform(m2);
404 assert_eq!(current_transform(&mut result), m2.then(&m1));
405 assert_eq!(current_transform(&mut result), m2.then(&m1)); // Test repeated add
406
407 result.push_transform(m3);
408 assert_eq!(current_transform(&mut result), m3.then(&m2.then(&m1)));
409
410 result.pop_transform();
411 result.pop_transform();
412 assert_eq!(current_transform(&mut result), m1);
413
414 result.pop_transform();
415 result.push_transform(m3);
416 assert_eq!(current_transform(&mut result), m3);
417
418 result.push_transform(m2);
419 assert_eq!(current_transform(&mut result), m2.then(&m3));
420 }
421
422 #[test]
423 fn push_and_pop_offsets() {
424 let mut result = HitTestResult::new();
425
426 let m1 = Matrix4::rotation(1.0);
427 let m2 = Matrix4::scale(1.1, 1.2);
428 let o3 = Offset::new(10.0, 20.0);
429 let m3 = Matrix4::translation(o3.dx() as f32, o3.dy() as f32);
430
431 // Test pushing offset as the first element
432 result.push_offset(o3);
433 assert_eq!(current_transform(&mut result), m3);
434 result.pop_transform();
435
436 result.push_offset(o3);
437 result.push_transform(m1);
438 assert_eq!(current_transform(&mut result), m1.then(&m3));
439 assert_eq!(current_transform(&mut result), m1.then(&m3)); // Test repeated add
440
441 result.push_transform(m2);
442 assert_eq!(current_transform(&mut result), m2.then(&m1.then(&m3)));
443
444 result.pop_transform();
445 result.pop_transform();
446 result.pop_transform();
447 assert_eq!(current_transform(&mut result), Matrix4::IDENTITY);
448
449 result.push_transform(m2);
450 result.push_offset(o3);
451 result.push_transform(m1);
452 assert_eq!(current_transform(&mut result), m1.then(&m3.then(&m2)));
453
454 result.pop_transform();
455 assert_eq!(current_transform(&mut result), m3.then(&m2));
456 }
457
458 /// The inverse of the card scale the tab prototype hit-tested through. f32 rounding puts
459 /// its third-row diagonal at 0.99999994, which Dart's 1e-10 tolerance rejected.
460 #[test]
461 fn an_inverted_f32_scale_is_accepted() {
462 let inverse = Matrix4::scale(0.432_428_2, 0.432_428_2)
463 .invert()
464 .expect("a scale is invertible");
465 let values = inverse.to_flutter_array();
466 assert_eq!(values[0], 2.312_522_6);
467 assert_eq!(values[10], 0.999_999_94, "the rounding this test is about");
468
469 let mut result = HitTestResult::new();
470 result.push_transform(inverse);
471 assert_eq!(current_transform(&mut result), inverse);
472 }
473
474 #[test]
475 #[cfg(debug_assertions)]
476 #[should_panic(expected = "The third row and third column of a transform matrix")]
477 fn a_perspective_transform_is_still_rejected() {
478 let mut values = Matrix4::IDENTITY.to_flutter_array();
479 // vector_math's `setEntry(3, 2, 0.001)`, the usual perspective.
480 values[11] = 0.001;
481 HitTestResult::new().push_transform(Matrix4::from_flutter_array(&values));
482 }
483}