Skip to main content

waft_rendering/
mouse_tracker.rs

1//! Flutter counterpart: `rendering/mouse_tracker.dart`.
2
3use std::any::Any;
4use std::hash::{Hash, Hasher};
5use std::rc::Rc;
6
7use indexmap::IndexMap;
8use waft_embedder::{Matrix4, Offset, PointerDeviceKind, ViewId};
9use waft_foundation::{AnyRef, App, ChangeNotifier, ChangeNotifierData, Handle, Ref};
10use waft_gestures::{
11    HitTestEntry, HitTestResult, PointerEnterEvent, PointerEvent, PointerExitEvent,
12};
13use waft_painting::{InlineSpan, TextSpan};
14use waft_services::{
15    MouseCursorManager, MouseCursorRef, MouseTrackerAnnotation, SystemMouseCursors,
16};
17
18use crate::box_::BoxHitTestEntry;
19use crate::object::AnyRenderObject;
20
21/// Signature for hit testing at the given offset for the specified view.
22///
23/// It is used by the [`MouseTracker`] to fetch annotations for the mouse
24/// position.
25pub type MouseTrackerHitTest = Rc<dyn Fn(&mut App, Offset, ViewId) -> HitTestResult>;
26
27/// The annotations under a mouse, front to back, each with the transform of its hit test
28/// entry.
29///
30/// Dart keys this map by the annotation object, compared with `==`. Here the key is the object
31/// that implements the annotation, and the annotation itself is read from it when needed.
32type Annotations = IndexMap<TrackedAnnotation, Matrix4>;
33
34/// An object that implements `MouseTrackerAnnotation`, as a key of [`Annotations`].
35#[derive(Clone, Debug)]
36enum TrackedAnnotation {
37    /// A render object that answers [`crate::RenderObject::mouse_tracker_annotation`].
38    RenderObject(AnyRenderObject),
39    /// A [`TextSpan`] that a paragraph's hit test added. Two equal spans are one key, as
40    /// they are in Dart, so a span hit on each of the lines it wraps over stays one annotation.
41    Span(Rc<TextSpan>),
42}
43
44impl TrackedAnnotation {
45    /// The annotation's current values; `None` for a render object that is not an annotation
46    /// or has left the arena.
47    fn annotation(&self, app: &App) -> Option<MouseTrackerAnnotation> {
48        match self {
49            TrackedAnnotation::RenderObject(target) => target.mouse_tracker_annotation(app),
50            TrackedAnnotation::Span(span) => Some(span.mouse_tracker_annotation()),
51        }
52    }
53
54    /// The render object to keep in the arena while the tracker remembers it; a span is kept
55    /// by the key itself.
56    fn render_object(&self) -> Option<AnyRenderObject> {
57        match self {
58            TrackedAnnotation::RenderObject(target) => Some(*target),
59            TrackedAnnotation::Span(_) => None,
60        }
61    }
62}
63
64impl PartialEq for TrackedAnnotation {
65    fn eq(&self, other: &TrackedAnnotation) -> bool {
66        match (self, other) {
67            (TrackedAnnotation::RenderObject(a), TrackedAnnotation::RenderObject(b)) => a == b,
68            (TrackedAnnotation::Span(a), TrackedAnnotation::Span(b)) => a.eq_span(&**b),
69            _ => false,
70        }
71    }
72}
73
74impl Eq for TrackedAnnotation {}
75
76impl Hash for TrackedAnnotation {
77    fn hash<H: Hasher>(&self, state: &mut H) {
78        match self {
79            TrackedAnnotation::RenderObject(target) => target.hash(state),
80            // Equal spans have equal text; the rest of `==` is left to `eq`.
81            TrackedAnnotation::Span(span) => span.text.hash(state),
82        }
83    }
84}
85
86// Various states of a connected mouse device used by [MouseTracker].
87struct MouseState {
88    /// The references that keep the annotations' render objects past a rebuild.
89    retained: Vec<AnyRef>,
90    // The list of annotations that contains this device.
91    //
92    // It uses [IndexMap] to keep the insertion order.
93    annotations: Annotations,
94    // The most recently processed mouse event observed from this device.
95    latest_event: PointerEvent,
96}
97
98impl MouseState {
99    fn new(initial_event: PointerEvent) -> MouseState {
100        MouseState {
101            retained: Vec::new(),
102            annotations: Annotations::new(),
103            latest_event: initial_event,
104        }
105    }
106
107    fn replace_annotations(
108        &mut self,
109        value: Annotations,
110        retained: Vec<AnyRef>,
111    ) -> (Annotations, Vec<AnyRef>) {
112        (
113            std::mem::replace(&mut self.annotations, value),
114            std::mem::replace(&mut self.retained, retained),
115        )
116    }
117
118    fn replace_latest_event(&mut self, value: PointerEvent) -> PointerEvent {
119        debug_assert_eq!(value.device(), self.latest_event.device());
120        std::mem::replace(&mut self.latest_event, value)
121    }
122}
123
124// The details of an update of a mouse device.
125//
126// This class contains the information needed to handle the update that might
127// change the state of a mouse device, or the [MouseTrackerAnnotation]s that
128// the mouse device is hovering.
129struct MouseTrackerUpdateDetails {
130    // The annotations that the device is hovering before the update.
131    //
132    // It is never null.
133    last_annotations: Annotations,
134    // The annotations that the device is hovering after the update.
135    //
136    // It is never null.
137    next_annotations: Annotations,
138    // The last event that the device observed before the update.
139    //
140    // If the update is triggered by a frame, the [previous_event] is never null,
141    // since the pointer must have been added before it can move.
142    //
143    // If the update is triggered by a pointer event, the [previous_event] is not
144    // null except for cases where the event is the first event observed by the
145    // pointer (which is not necessarily a [PointerEvent::Added]).
146    previous_event: Option<PointerEvent>,
147    // The event that triggered this update.
148    //
149    // It is non-null if and only if the update is triggered by a pointer event.
150    triggering_event: Option<PointerEvent>,
151}
152
153impl MouseTrackerUpdateDetails {
154    // When device update is triggered by a new frame.
155    //
156    // All parameters are required.
157    fn by_new_frame(
158        last_annotations: Annotations,
159        next_annotations: Annotations,
160        previous_event: PointerEvent,
161    ) -> MouseTrackerUpdateDetails {
162        MouseTrackerUpdateDetails {
163            last_annotations,
164            next_annotations,
165            previous_event: Some(previous_event),
166            triggering_event: None,
167        }
168    }
169
170    // When device update is triggered by a pointer event.
171    //
172    // The [last_annotations], [next_annotations], and [triggering_event] are
173    // required.
174    fn by_pointer_event(
175        last_annotations: Annotations,
176        next_annotations: Annotations,
177        previous_event: Option<PointerEvent>,
178        triggering_event: PointerEvent,
179    ) -> MouseTrackerUpdateDetails {
180        MouseTrackerUpdateDetails {
181            last_annotations,
182            next_annotations,
183            previous_event,
184            triggering_event: Some(triggering_event),
185        }
186    }
187
188    // The pointing device of this update.
189    fn device(&self) -> i64 {
190        self.previous_event
191            .as_ref()
192            .or(self.triggering_event.as_ref())
193            .expect("an update has an event")
194            .device()
195    }
196
197    // The last event that the device observed after the update.
198    //
199    // The [latest_event] is never null.
200    fn latest_event(&self) -> &PointerEvent {
201        self.triggering_event
202            .as_ref()
203            .or(self.previous_event.as_ref())
204            .expect("an update has an event")
205    }
206}
207
208/// Tracks the relationship between mouse devices and annotations, and
209/// triggers mouse events and cursor changes accordingly.
210///
211/// The [`MouseTracker`] tracks the relationship between mouse devices and
212/// [`MouseTrackerAnnotation`](waft_services::MouseTrackerAnnotation), notified by [`update_with_event`] and
213/// [`update_all_devices`]. At every update, [`MouseTracker`] triggers the
214/// following changes if applicable:
215///
216///  * Dispatches mouse-related pointer events (pointer enter, hover, and exit).
217///  * Changes mouse cursors.
218///  * Notifies when [`mouse_is_connected`] changes.
219///
220/// This class is a `ChangeNotifier` that notifies its listeners if the value of
221/// [`mouse_is_connected`] changes.
222///
223/// An instance of [`MouseTracker`] is owned by the global singleton
224/// `RendererBinding`.
225///
226/// [`update_with_event`]: MouseTracker::update_with_event
227/// [`update_all_devices`]: MouseTracker::update_all_devices
228/// [`mouse_is_connected`]: MouseTracker::mouse_is_connected
229pub struct MouseTracker {
230    change_notifier: ChangeNotifierData,
231    hit_test_in_view: MouseTrackerHitTest,
232    mouse_cursor_mixin: MouseCursorManager,
233    mouse_states: IndexMap<i64, MouseState>,
234    debug_during_device_update: bool,
235}
236
237impl ChangeNotifier for MouseTracker {
238    fn change_notifier_data(&self) -> &ChangeNotifierData {
239        &self.change_notifier
240    }
241
242    fn change_notifier_data_mut(&mut self) -> &mut ChangeNotifierData {
243        &mut self.change_notifier
244    }
245}
246
247impl MouseTracker {
248    /// Create a mouse tracker.
249    ///
250    /// The `hit_test_in_view` is used to find the render objects on a given
251    /// position in the specific view. It is typically provided by the
252    /// `RendererBinding`.
253    pub fn new(app: &mut App, hit_test_in_view: MouseTrackerHitTest) -> Ref<MouseTracker> {
254        app.create(MouseTracker {
255            change_notifier: ChangeNotifierData::new(),
256            hit_test_in_view,
257            mouse_cursor_mixin: MouseCursorManager::new(SystemMouseCursors::BASIC.into()),
258            mouse_states: IndexMap::new(),
259            debug_during_device_update: false,
260        })
261    }
262
263    /// Discards any resources used by the object. After this is called, the
264    /// object is not in a usable state and should be discarded.
265    pub fn dispose(self: Handle<Self>, app: &mut App) {
266        ChangeNotifierData::dispose(app, self);
267    }
268
269    /// The remembered annotations keep their render objects past a rebuild, as Dart's map holds
270    /// the annotation objects: an exit is still delivered to a region that just left the tree.
271    fn retain_annotations(app: &mut App, annotations: &Annotations) -> Vec<AnyRef> {
272        annotations
273            .keys()
274            .filter_map(TrackedAnnotation::render_object)
275            .filter_map(|target| target.id().upgrade(app))
276            .collect()
277    }
278
279    // Whether an observed event might update a device.
280    //
281    // For example, a [PointerEvent::Move] would always update a device, while
282    // a [PointerEvent::Scroll] would not.
283    fn should_mark_state_dirty(state: Option<&MouseState>, event: &PointerEvent) -> bool {
284        let Some(state) = state else {
285            return true;
286        };
287        let last_event = &state.latest_event;
288        debug_assert_eq!(event.device(), last_event.device());
289        // An Added can only follow a Removed, and a Removed can only follow an Added.
290        debug_assert_eq!(
291            matches!(event, PointerEvent::Added(_)),
292            matches!(last_event, PointerEvent::Removed(_))
293        );
294        // Ignore events that are unrelated to mouse tracking.
295        if is_signal_event(event) {
296            return false;
297        }
298        matches!(last_event, PointerEvent::Added(_))
299            || matches!(event, PointerEvent::Removed(_))
300            || last_event.position() != event.position()
301    }
302
303    fn hit_test_in_view_result_to_annotations(app: &App, result: &HitTestResult) -> Annotations {
304        let mut annotations = Annotations::new();
305        for entry in result.path() {
306            if let Some(target) = annotation_target(app, entry) {
307                annotations.insert(target, entry.transform().expect("an added entry is placed"));
308            }
309        }
310        annotations
311    }
312
313    // Find the annotations that is hovered by the device of the `state`.
314    //
315    // If the device is not connected or not a mouse, an empty map is returned
316    // without calling `hit_test_in_view`.
317    fn find_annotations(
318        self: Handle<Self>,
319        app: &mut App,
320        latest_event: &PointerEvent,
321    ) -> Annotations {
322        let global_position = latest_event.position();
323        let device = latest_event.device();
324        let view_id = latest_event.view_id();
325        if !app.get(self).mouse_states.contains_key(&device) {
326            return Annotations::new();
327        }
328        let result = self.run_hit_test(app, global_position, view_id);
329        MouseTracker::hit_test_in_view_result_to_annotations(app, &result)
330    }
331
332    fn run_hit_test(
333        self: Handle<Self>,
334        app: &mut App,
335        position: Offset,
336        view_id: ViewId,
337    ) -> HitTestResult {
338        let hit_test_in_view = Rc::clone(&app.get(self).hit_test_in_view);
339        hit_test_in_view(app, position, view_id)
340    }
341
342    // A callback that is called on the update of a device.
343    //
344    // An event (not necessarily a pointer event) that might change the
345    // relationship between mouse devices and [MouseTrackerAnnotation]s is called
346    // a _device update_. This method should be called at each such update.
347    //
348    // The update can be caused by a pointer event, in which case
349    // `triggering_event` should not be null, or by other changes, such as when a
350    // widget has moved under a still mouse, which is detected after the current
351    // frame is complete.
352    fn handle_device_update(self: Handle<Self>, app: &mut App, details: MouseTrackerUpdateDetails) {
353        debug_assert!(app.get(self).debug_during_device_update);
354        MouseTracker::handle_device_update_mouse_events(app, &details);
355        let cursors: Vec<MouseCursorRef> = details
356            .next_annotations
357            .keys()
358            .filter_map(|target| target.annotation(app))
359            .map(|annotation| annotation.cursor)
360            .collect();
361        let platform = app.platform();
362        app.get_mut(self)
363            .mouse_cursor_mixin
364            .handle_device_cursor_update(
365                &*platform,
366                details.latest_event().view_id(),
367                details.device(),
368                details.triggering_event.as_ref(),
369                cursors,
370            );
371    }
372
373    /// Whether or not at least one mouse is connected and has produced events.
374    pub fn mouse_is_connected(self: Handle<Self>, app: &App) -> bool {
375        !app.get(self).mouse_states.is_empty()
376    }
377
378    /// Perform a device update for one device according to the given new event.
379    ///
380    /// The [`update_with_event`] is typically called by the `RendererBinding` during
381    /// the handler of a pointer event. All pointer events should call this
382    /// method, and let [`MouseTracker`] filter which to react to.
383    ///
384    /// The `hit_test_result` serves as an optional optimization, and is the hit
385    /// test result already performed by the `RendererBinding` for other gestures.
386    /// It can be `None`, but when it's not `None`, it should be identical to the
387    /// result from directly calling `hit_test_in_view` given in the constructor
388    /// (which means that it must not use the cached result for
389    /// [`PointerEvent::Move`]).
390    ///
391    /// The `update_with_event` is one of the two ways of updating mouse
392    /// states, the other one being [`update_all_devices`].
393    ///
394    /// [`update_with_event`]: MouseTracker::update_with_event
395    /// [`update_all_devices`]: MouseTracker::update_all_devices
396    pub fn update_with_event(
397        self: Handle<Self>,
398        app: &mut App,
399        event: &PointerEvent,
400        hit_test_result: Option<&HitTestResult>,
401    ) {
402        if event.kind() != PointerDeviceKind::Mouse && event.kind() != PointerDeviceKind::Stylus {
403            // Only track mouse and stylus events.
404            return;
405        }
406        if is_signal_event(event) {
407            // Ignore signal events, which are not tracked by the mouse tracker.
408            return;
409        }
410        let is_removed = matches!(event, PointerEvent::Removed(_));
411        let owned_result;
412        let result: Option<&HitTestResult> = if is_removed {
413            None
414        } else if let Some(result) = hit_test_result {
415            Some(result)
416        } else {
417            owned_result = self.run_hit_test(app, event.position(), event.view_id());
418            Some(&owned_result)
419        };
420        let device = event.device();
421        if !MouseTracker::should_mark_state_dirty(app.get(self).mouse_states.get(&device), event) {
422            return;
423        }
424
425        self.monitor_mouse_connection(app, |app| {
426            self.device_update_phase(app, |app| {
427                // Update mouse_states
428                if !app.get(self).mouse_states.contains_key(&device) {
429                    if is_removed {
430                        return;
431                    }
432                    app.get_mut(self)
433                        .mouse_states
434                        .insert(device, MouseState::new(event.clone()));
435                } else {
436                    debug_assert!(!matches!(event, PointerEvent::Added(_)));
437                }
438                let next_annotations = match result {
439                    Some(result) => {
440                        MouseTracker::hit_test_in_view_result_to_annotations(app, result)
441                    }
442                    None => Annotations::new(),
443                };
444                let target_state = app
445                    .get_mut(self)
446                    .mouse_states
447                    .get_mut(&device)
448                    .expect("the state was just found or created");
449                let last_event = target_state.replace_latest_event(event.clone());
450                let retained = MouseTracker::retain_annotations(app, &next_annotations);
451                let target_state = app
452                    .get_mut(self)
453                    .mouse_states
454                    .get_mut(&device)
455                    .expect("the state was just found or created");
456                let (last_annotations, last_retained) =
457                    target_state.replace_annotations(next_annotations.clone(), retained);
458                if is_removed {
459                    app.get_mut(self).mouse_states.shift_remove(&device);
460                }
461                self.handle_device_update(
462                    app,
463                    MouseTrackerUpdateDetails::by_pointer_event(
464                        last_annotations,
465                        next_annotations,
466                        Some(last_event),
467                        event.clone(),
468                    ),
469                );
470                drop(last_retained);
471            });
472        });
473    }
474
475    /// Perform a device update for all devices.
476    ///
477    /// This is called by the `RendererBinding` after a frame, since the render
478    /// tree might have changed under a still mouse.
479    ///
480    /// The `update_all_devices` is one of the two ways of updating mouse
481    /// states, the other one being [`update_with_event`].
482    ///
483    /// [`update_with_event`]: MouseTracker::update_with_event
484    pub fn update_all_devices(self: Handle<Self>, app: &mut App) {
485        self.device_update_phase(app, |app| {
486            let devices: Vec<i64> = app.get(self).mouse_states.keys().copied().collect();
487            for device in devices {
488                let Some(last_event) = app
489                    .get(self)
490                    .mouse_states
491                    .get(&device)
492                    .map(|state| state.latest_event.clone())
493                else {
494                    continue;
495                };
496                let next_annotations = self.find_annotations(app, &last_event);
497                if !app.get(self).mouse_states.contains_key(&device) {
498                    continue;
499                }
500                let retained = MouseTracker::retain_annotations(app, &next_annotations);
501                let Some(dirty_state) = app.get_mut(self).mouse_states.get_mut(&device) else {
502                    continue;
503                };
504                let (last_annotations, last_retained) =
505                    dirty_state.replace_annotations(next_annotations.clone(), retained);
506                self.handle_device_update(
507                    app,
508                    MouseTrackerUpdateDetails::by_new_frame(
509                        last_annotations,
510                        next_annotations,
511                        last_event,
512                    ),
513                );
514                drop(last_retained);
515            }
516        });
517    }
518
519    /// Returns the active mouse cursor for a device.
520    ///
521    /// The return value is the last [`MouseCursorRef`] activated onto this
522    /// device, even if the activation failed.
523    ///
524    /// This function is only active in debug mode: in release it returns `None`.
525    pub fn debug_device_active_cursor(
526        self: Handle<Self>,
527        app: &App,
528        device: i64,
529    ) -> Option<MouseCursorRef> {
530        app.get(self)
531            .mouse_cursor_mixin
532            .debug_device_active_cursor(device)
533    }
534
535    // Used to wrap any procedures that might change `mouse_is_connected`.
536    //
537    // This method records `mouse_is_connected` before and after the `task`, and
538    // notifies listeners if the value changed.
539    fn monitor_mouse_connection(self: Handle<Self>, app: &mut App, task: impl FnOnce(&mut App)) {
540        let mouse_was_connected = self.mouse_is_connected(app);
541        task(app);
542        if mouse_was_connected != self.mouse_is_connected(app) {
543            self.notify_listeners(app);
544        }
545    }
546
547    // Used to wrap any procedures that might change the state of a device.
548    //
549    // A device update, i.e. a change that might affect which annotations a
550    // device hovers, must not happen during another device update.
551    fn device_update_phase(self: Handle<Self>, app: &mut App, task: impl FnOnce(&mut App)) {
552        debug_assert!(!app.get(self).debug_during_device_update);
553        if cfg!(debug_assertions) {
554            app.get_mut(self).debug_during_device_update = true;
555        }
556        task(app);
557        if cfg!(debug_assertions) {
558            app.get_mut(self).debug_during_device_update = false;
559        }
560    }
561
562    // Handles device update and dispatches mouse event callbacks.
563    fn handle_device_update_mouse_events(app: &mut App, details: &MouseTrackerUpdateDetails) {
564        let latest_event = details.latest_event();
565        let last_annotations = &details.last_annotations;
566        let next_annotations = &details.next_annotations;
567
568        // Order is important for mouse event callbacks. The
569        // `hit_test_in_view_result_to_annotations` returns annotations in the visual order
570        // from front to back, called the "hit-test order". The algorithm here is
571        // explained in https://github.com/flutter/flutter/issues/41420
572
573        // Send exit events to annotations that are in last but not in next, in
574        // hit-test order.
575        let base_exit_event = PointerExitEvent::from_mouse_event(latest_event);
576        for (target, transform) in last_annotations {
577            if next_annotations.contains_key(target) {
578                continue;
579            }
580            let Some(annotation) = target.annotation(app) else {
581                continue;
582            };
583            if annotation.valid_for_mouse_tracker
584                && let Some(on_exit) = annotation.on_exit
585            {
586                on_exit(app, base_exit_event.transformed(Some(*transform)));
587            }
588        }
589
590        // Send enter events to annotations that are not in last but in next, in
591        // reverse hit-test order.
592        let entering_annotations: Vec<(TrackedAnnotation, Matrix4)> = next_annotations
593            .iter()
594            .filter(|(target, _)| !last_annotations.contains_key(*target))
595            .map(|(target, transform)| (target.clone(), *transform))
596            .collect();
597        let base_enter_event = PointerEnterEvent::from_mouse_event(latest_event);
598        for (target, transform) in entering_annotations.into_iter().rev() {
599            let Some(annotation) = target.annotation(app) else {
600                continue;
601            };
602            if annotation.valid_for_mouse_tracker
603                && let Some(on_enter) = annotation.on_enter
604            {
605                on_enter(app, base_enter_event.transformed(Some(transform)));
606            }
607        }
608    }
609}
610
611/// Dart's `event is PointerSignalEvent`.
612fn is_signal_event(event: &PointerEvent) -> bool {
613    matches!(
614        event,
615        PointerEvent::Scroll(_) | PointerEvent::ScrollInertiaCancel(_) | PointerEvent::Scale(_)
616    )
617}
618
619/// Dart's `entry.target is MouseTrackerAnnotation`: the object behind a hit test entry, when it
620/// implements the annotation. That is a render object answering
621/// [`crate::RenderObject::mouse_tracker_annotation`], or a [`TextSpan`].
622fn annotation_target(app: &App, entry: &HitTestEntry) -> Option<TrackedAnnotation> {
623    let target: Rc<dyn Any> = entry.shared_target().clone();
624    let target = match target.downcast::<TextSpan>() {
625        Ok(span) => return Some(TrackedAnnotation::Span(span)),
626        Err(target) => target,
627    };
628    let target = target
629        .downcast_ref::<BoxHitTestEntry>()?
630        .target()
631        .as_object();
632    target
633        .mouse_tracker_annotation(app)
634        .map(|_| TrackedAnnotation::RenderObject(target))
635}
636
637#[cfg(test)]
638mod tests {
639    use std::cell::{Cell, RefCell};
640    use waft_foundation::AppCell;
641
642    use waft_embedder::{Size, SystemMouseCursorKind, ViewRef};
643    use waft_gestures::{
644        PointerAddedEvent, PointerHoverEvent, PointerRemovedEvent, PointerScrollEvent,
645    };
646    use waft_test::{TestPlatform, TestView};
647
648    use waft_foundation::{Listenable, Listener};
649    use waft_painting::AlignmentGeometry;
650
651    use super::*;
652    use crate::box_::{AnyRenderBox, BoxConstraints, BoxHitTestResult, RenderBox};
653    use crate::object::RenderObject;
654    use crate::object::RenderObjectWithChildMixin;
655    use crate::pipeline_owner::PipelineOwner;
656    use crate::proxy_box::{RenderConstrainedBox, RenderMouseRegion, RenderMouseRegionBase};
657    use crate::shifted_box::RenderPadding;
658    use crate::testing::{EnginePhase, layout_with, pump_frame, test_render_root};
659
660    /// An app on a platform with views 0 and 2, whose hosts record the cursors they are asked
661    /// for, and those views.
662    fn app_with_cursor_host() -> (Rc<AppCell>, Rc<TestView>, Rc<TestView>) {
663        let first = Rc::new(TestView::new(200.0, 200.0).with_id(ViewId(0)));
664        let second = Rc::new(TestView::new(200.0, 200.0).with_id(ViewId(2)));
665        let platform = TestPlatform::new()
666            .with_view(Rc::clone(&first) as ViewRef)
667            .with_view(Rc::clone(&second) as ViewRef);
668        (AppCell::with_platform(Rc::new(platform)), first, second)
669    }
670
671    /// A laid-out tree: a 200×200 padding at the test view's top left holding a mouse region
672    /// padded 50 on each side, so the region covers (50..150, 50..150).
673    struct RegionTree {
674        padding: crate::RenderHandle<RenderPadding>,
675        region: crate::RenderHandle<RenderMouseRegion>,
676    }
677
678    fn tree_with_region(app: &mut App) -> RegionTree {
679        let region = RenderMouseRegion::new(app, true, None);
680        let padding = RenderPadding::new(
681            app,
682            waft_painting::EdgeInsets::all(50.0).into(),
683            None,
684            Some(region.as_box()),
685        );
686        lay_out_at_the_top_left(app, padding.as_box(), Size::new(200.0, 200.0));
687        RegionTree { padding, region }
688    }
689
690    /// Lays `render_box` out at `size`, at the test view's top left, so that its positions are
691    /// the view's.
692    fn lay_out_at_the_top_left(app: &mut App, render_box: AnyRenderBox, size: Size) {
693        layout_with(
694            app,
695            render_box,
696            Some(BoxConstraints::tight(size)),
697            AlignmentGeometry::TOP_LEFT,
698            EnginePhase::Layout,
699        );
700    }
701
702    /// A tracker that hit-tests the test view.
703    fn tracker_for(app: &mut App) -> Ref<MouseTracker> {
704        let root = test_render_root(app);
705        MouseTracker::new(
706            app,
707            Rc::new(move |app: &mut App, position: Offset, _view_id: ViewId| {
708                let mut result = HitTestResult::new();
709                root.hit_test(app, &mut BoxHitTestResult::wrap(&mut result), position);
710                result
711            }),
712        )
713    }
714
715    fn mouse_hover(position: Offset) -> PointerEvent {
716        PointerEvent::Hover(PointerHoverEvent {
717            kind: PointerDeviceKind::Mouse,
718            position,
719            ..PointerHoverEvent::default()
720        })
721    }
722
723    fn mouse_added(position: Offset) -> PointerEvent {
724        PointerEvent::Added(PointerAddedEvent {
725            kind: PointerDeviceKind::Mouse,
726            position,
727            ..PointerAddedEvent::default()
728        })
729    }
730
731    fn mouse_removed(position: Offset) -> PointerEvent {
732        PointerEvent::Removed(PointerRemovedEvent {
733            kind: PointerDeviceKind::Mouse,
734            position,
735            ..PointerRemovedEvent::default()
736        })
737    }
738
739    /// Records the events a region's callbacks receive.
740    fn record_events(
741        app: &mut App,
742        region: crate::RenderHandle<RenderMouseRegion>,
743    ) -> Rc<RefCell<Vec<String>>> {
744        let log = Rc::new(RefCell::new(Vec::new()));
745        let enter_log = Rc::clone(&log);
746        region.set_on_enter(
747            app,
748            Some(Rc::new(move |_app: &mut App, event: PointerEnterEvent| {
749                enter_log
750                    .borrow_mut()
751                    .push(format!("enter {:?}", event.local_position()));
752            })),
753        );
754        let hover_log = Rc::clone(&log);
755        region.set_on_hover(
756            app,
757            Some(Rc::new(move |_app: &mut App, event: PointerHoverEvent| {
758                hover_log
759                    .borrow_mut()
760                    .push(format!("hover {:?}", event.local_position()));
761            })),
762        );
763        let exit_log = Rc::clone(&log);
764        region.set_on_exit(
765            app,
766            Some(Rc::new(move |_app: &mut App, event: PointerExitEvent| {
767                exit_log
768                    .borrow_mut()
769                    .push(format!("exit {:?}", event.local_position()));
770            })),
771        );
772        log
773    }
774
775    #[test]
776    fn entering_and_leaving_a_region_sends_enter_then_exit_in_local_coordinates() {
777        let cell = AppCell::new();
778        let mut app = cell.borrow_mut();
779        let RegionTree { region, .. } = tree_with_region(&mut app);
780        let tracker = tracker_for(&mut app);
781        let log = record_events(&mut app, region);
782
783        tracker.update_with_event(&mut app, &mouse_added(Offset::new(10.0, 10.0)), None);
784        assert!(log.borrow().is_empty(), "outside the region: nothing");
785
786        tracker.update_with_event(&mut app, &mouse_hover(Offset::new(60.0, 70.0)), None);
787        assert_eq!(*log.borrow(), ["enter Offset(10.0, 20.0)"]);
788
789        tracker.update_with_event(&mut app, &mouse_hover(Offset::new(160.0, 70.0)), None);
790        assert_eq!(
791            *log.borrow(),
792            ["enter Offset(10.0, 20.0)", "exit Offset(110.0, 20.0)"]
793        );
794    }
795
796    #[test]
797    fn a_still_mouse_notices_the_tree_moving_under_it_after_a_frame() {
798        let cell = AppCell::new();
799        let mut app = cell.borrow_mut();
800        let RegionTree { padding, region } = tree_with_region(&mut app);
801        let tracker = tracker_for(&mut app);
802        let log = record_events(&mut app, region);
803        tracker.update_with_event(&mut app, &mouse_added(Offset::new(100.0, 100.0)), None);
804        assert_eq!(*log.borrow(), ["enter Offset(50.0, 50.0)"]);
805
806        // Move the region to the right of the still mouse, then run the frame's update.
807        padding.set_padding(
808            &mut app,
809            waft_painting::EdgeInsetsGeometry::only(150.0, 0.0, 0.0, 0.0),
810        );
811        pump_frame(&mut app, EnginePhase::Layout);
812        tracker.update_all_devices(&mut app);
813        assert_eq!(
814            *log.borrow(),
815            ["enter Offset(50.0, 50.0)", "exit Offset(50.0, 50.0)"],
816            "the exit is placed with the transform recorded when the region was entered"
817        );
818    }
819
820    #[test]
821    fn a_region_removed_from_the_tree_sends_no_exit() {
822        let cell = AppCell::new();
823        let mut app = cell.borrow_mut();
824        let RegionTree { padding, region } = tree_with_region(&mut app);
825        let tracker = tracker_for(&mut app);
826        let log = record_events(&mut app, region);
827        tracker.update_with_event(&mut app, &mouse_added(Offset::new(100.0, 100.0)), None);
828        assert_eq!(*log.borrow(), ["enter Offset(50.0, 50.0)"]);
829
830        padding.set_child(&mut app, None);
831        pump_frame(&mut app, EnginePhase::Layout);
832        tracker.update_all_devices(&mut app);
833        assert_eq!(
834            *log.borrow(),
835            ["enter Offset(50.0, 50.0)"],
836            "Flutter: a detached region is no longer valid for the tracker, so no exit is sent"
837        );
838    }
839
840    #[test]
841    fn a_detached_region_is_invalid_for_the_tracker() {
842        let cell = AppCell::new();
843        let mut app = cell.borrow_mut();
844        let region = RenderMouseRegion::new(&mut app, true, None);
845        assert!(region.valid_for_mouse_tracker(&app));
846        let owner = PipelineOwner::new(&mut app, None, None);
847        region.as_object().attach(&mut app, owner.handle());
848        assert!(region.valid_for_mouse_tracker(&app));
849        region.as_object().detach(&mut app);
850        assert!(!region.valid_for_mouse_tracker(&app));
851        assert!(
852            !RenderObject::mouse_tracker_annotation(region, &app)
853                .unwrap()
854                .valid_for_mouse_tracker
855        );
856    }
857
858    #[test]
859    fn a_removed_mouse_exits_and_disconnects() {
860        let cell = AppCell::new();
861        let mut app = cell.borrow_mut();
862        let RegionTree { region, .. } = tree_with_region(&mut app);
863        let tracker = tracker_for(&mut app);
864        let log = record_events(&mut app, region);
865        let notifications = Rc::new(Cell::new(0));
866        let counted = Rc::clone(&notifications);
867        tracker.add_listener(
868            &mut app,
869            Listener::new(move |_app| counted.set(counted.get() + 1)),
870        );
871
872        assert!(!tracker.mouse_is_connected(&app));
873        tracker.update_with_event(&mut app, &mouse_added(Offset::new(100.0, 100.0)), None);
874        assert!(tracker.mouse_is_connected(&app));
875        assert_eq!(notifications.get(), 1);
876
877        tracker.update_with_event(&mut app, &mouse_removed(Offset::new(100.0, 100.0)), None);
878        assert!(!tracker.mouse_is_connected(&app));
879        assert_eq!(notifications.get(), 2);
880        assert_eq!(
881            *log.borrow(),
882            ["enter Offset(50.0, 50.0)", "exit Offset(50.0, 50.0)"]
883        );
884    }
885
886    #[test]
887    fn touch_and_signal_events_are_ignored() {
888        let cell = AppCell::new();
889        let mut app = cell.borrow_mut();
890        let RegionTree { region, .. } = tree_with_region(&mut app);
891        let tracker = tracker_for(&mut app);
892        let log = record_events(&mut app, region);
893
894        tracker.update_with_event(
895            &mut app,
896            &PointerEvent::Hover(PointerHoverEvent {
897                position: Offset::new(100.0, 100.0),
898                ..PointerHoverEvent::default()
899            }),
900            None,
901        );
902        assert!(!tracker.mouse_is_connected(&app), "touch: not tracked");
903
904        tracker.update_with_event(
905            &mut app,
906            &PointerEvent::Scroll(PointerScrollEvent {
907                kind: PointerDeviceKind::Mouse,
908                position: Offset::new(100.0, 100.0),
909                ..PointerScrollEvent::default()
910            }),
911            None,
912        );
913        assert!(!tracker.mouse_is_connected(&app), "a signal: not tracked");
914        assert!(log.borrow().is_empty());
915    }
916
917    #[test]
918    fn the_front_regions_cursor_wins_and_deferring_regions_let_the_one_behind_decide() {
919        let (cell, first, _) = app_with_cursor_host();
920        let mut app = cell.borrow_mut();
921        let RegionTree { region, .. } = tree_with_region(&mut app);
922        region.set_cursor(&mut app, SystemMouseCursors::TEXT.into());
923        // A deferring region in front of the text region, sharing its bounds.
924        let front = RenderMouseRegion::new(&mut app, true, None);
925        region.set_child(&mut app, Some(front.as_box()));
926        pump_frame(&mut app, EnginePhase::Layout);
927        let tracker = tracker_for(&mut app);
928
929        tracker.update_with_event(&mut app, &mouse_added(Offset::new(100.0, 100.0)), None);
930        assert_eq!(
931            first.test_host().cursors(),
932            [(0, SystemMouseCursorKind::Text)]
933        );
934
935        front.set_cursor(&mut app, SystemMouseCursors::CLICK.into());
936        tracker.update_all_devices(&mut app);
937        assert_eq!(
938            first.test_host().cursors(),
939            [
940                (0, SystemMouseCursorKind::Text),
941                (0, SystemMouseCursorKind::Click)
942            ]
943        );
944        let click: MouseCursorRef = SystemMouseCursors::CLICK.into();
945        assert!(*tracker.debug_device_active_cursor(&app, 0).unwrap() == *click);
946
947        tracker.update_with_event(&mut app, &mouse_hover(Offset::new(10.0, 10.0)), None);
948        assert_eq!(
949            first.test_host().cursors().last().unwrap().1,
950            SystemMouseCursorKind::Basic,
951            "over nothing, the fallback cursor"
952        );
953    }
954
955    #[test]
956    fn the_cursor_goes_to_the_view_the_pointer_was_last_seen_on() {
957        let (cell, first, second) = app_with_cursor_host();
958        let mut app = cell.borrow_mut();
959        let RegionTree { region, .. } = tree_with_region(&mut app);
960        region.set_cursor(&mut app, SystemMouseCursors::TEXT.into());
961        let tracker = tracker_for(&mut app);
962
963        let added = PointerEvent::Added(PointerAddedEvent {
964            kind: PointerDeviceKind::Mouse,
965            position: Offset::new(100.0, 100.0),
966            view_id: ViewId(2),
967            ..PointerAddedEvent::default()
968        });
969        tracker.update_with_event(&mut app, &added, None);
970        assert_eq!(
971            second.test_host().cursors(),
972            [(0, SystemMouseCursorKind::Text)]
973        );
974        assert!(first.test_host().cursors().is_empty());
975
976        region.set_cursor(&mut app, SystemMouseCursors::CLICK.into());
977        tracker.update_all_devices(&mut app);
978        assert_eq!(
979            second.test_host().cursors().last(),
980            Some(&(0, SystemMouseCursorKind::Click)),
981            "a frame-triggered update has no event of its own; the device's last one names the view"
982        );
983    }
984
985    #[test]
986    fn an_opaque_region_hides_the_region_behind_it_and_a_transparent_one_does_not() {
987        let cell = AppCell::new();
988        let mut app = cell.borrow_mut();
989        let back = RenderMouseRegion::new(&mut app, true, None);
990        let front = RenderMouseRegion::new(&mut app, true, Some(back.as_box()));
991        lay_out_at_the_top_left(&mut app, front.as_box(), Size::new(100.0, 100.0));
992        let tracker = tracker_for(&mut app);
993        let back_log = record_events(&mut app, back);
994        let front_log = record_events(&mut app, front);
995
996        tracker.update_with_event(&mut app, &mouse_added(Offset::new(10.0, 10.0)), None);
997        assert_eq!(*front_log.borrow(), ["enter Offset(10.0, 10.0)"]);
998        assert_eq!(
999            *back_log.borrow(),
1000            ["enter Offset(10.0, 10.0)"],
1001            "the front region's hit test still visits its child; opacity only stops what is behind the region in the parent's hit test"
1002        );
1003    }
1004
1005    #[test]
1006    fn hover_reaches_the_region_through_handle_event() {
1007        let cell = AppCell::new();
1008        let mut app = cell.borrow_mut();
1009        let region = RenderMouseRegion::new(&mut app, true, None);
1010        let log = record_events(&mut app, region);
1011        let event = mouse_hover(Offset::new(3.0, 4.0));
1012        let entry = BoxHitTestEntry::new(region.as_box(), Offset::new(3.0, 4.0));
1013        RenderBox::handle_event(region, &mut app, &event, &entry);
1014        assert_eq!(*log.borrow(), ["hover Offset(3.0, 4.0)"]);
1015    }
1016
1017    #[test]
1018    fn an_opaque_region_absorbs_the_hit_test_for_what_is_behind_it() {
1019        let cell = AppCell::new();
1020        let mut app = cell.borrow_mut();
1021        let region = RenderMouseRegion::new(&mut app, true, None);
1022        lay_out_at_the_top_left(&mut app, region.as_box(), Size::new(100.0, 100.0));
1023
1024        let mut result = HitTestResult::new();
1025        assert!(RenderBox::hit_test(
1026            region,
1027            &mut app,
1028            &mut BoxHitTestResult::wrap(&mut result),
1029            Offset::new(5.0, 5.0)
1030        ));
1031        region.set_opaque(&mut app, false);
1032        let mut result = HitTestResult::new();
1033        assert!(!RenderBox::hit_test(
1034            region,
1035            &mut app,
1036            &mut BoxHitTestResult::wrap(&mut result),
1037            Offset::new(5.0, 5.0)
1038        ));
1039        assert_eq!(
1040            result.path().len(),
1041            1,
1042            "the region is still on the path; it just does not claim the hit"
1043        );
1044    }
1045
1046    #[test]
1047    fn a_region_with_no_annotation_neighbours_still_uses_the_fallback_cursor() {
1048        let (cell, first, _) = app_with_cursor_host();
1049        let mut app = cell.borrow_mut();
1050        let child =
1051            RenderConstrainedBox::new(&mut app, BoxConstraints::tight(Size::new(10.0, 10.0)), None);
1052        lay_out_at_the_top_left(&mut app, child.as_box(), Size::new(100.0, 100.0));
1053        let tracker = tracker_for(&mut app);
1054        tracker.update_with_event(&mut app, &mouse_added(Offset::new(5.0, 5.0)), None);
1055        assert_eq!(
1056            first.test_host().cursors(),
1057            [(0, SystemMouseCursorKind::Basic)]
1058        );
1059    }
1060}