Skip to main content

waft_rendering/
binding.rs

1//! Flutter counterpart: `rendering/binding.dart` (`RendererBinding`).
2//!
3//! Semantics and `performReassemble` wait.
4
5use std::rc::Rc;
6
7use waft_embedder::{Offset, ViewId, ViewRef};
8use waft_foundation::{App, Handle, Listener};
9use waft_gestures::{GestureBinding, GestureBindingOverridesObject, HitTestResult, PointerEvent};
10use waft_scheduler::{FrameCallback, FrameTarget, PersistentFrameCallback, SchedulerBinding};
11
12use crate::mouse_tracker::MouseTracker;
13use crate::object::RenderHandle;
14use crate::pipeline_owner::{PipelineManifold, PipelineOwner};
15use crate::view::{RenderView, ViewConfiguration};
16use waft_foundation::OptionRetained;
17use waft_foundation::Ref;
18
19/// The object side of Flutter's `WidgetsBinding` overrides of `RendererBinding.drawFrame`:
20/// the widget layer builds before the renderer's frame and finalizes its tree after it.
21/// Implement it on the binding above and register `Rc::new(handle)` with
22/// [`RendererBinding::set_overrides`]; `Handle<T>` is then [`RendererBindingOverrides`].
23pub trait RendererBindingOverridesObject: Sized + 'static {
24    /// Runs at the start of [`RendererBinding::draw_frame`], before layout.
25    fn will_draw_frame(self: Handle<Self>, app: &mut App);
26
27    /// Runs at the end of [`RendererBinding::draw_frame`], after compositing.
28    fn did_draw_frame(self: Handle<Self>, app: &mut App);
29
30    /// Runs at the end of [`RendererBinding::handle_metrics_changed`]: Flutter's
31    /// `WidgetsBinding.handleMetricsChanged` override, which tells its observers.
32    fn did_handle_metrics_changed(self: Handle<Self>, app: &mut App) {
33        let _ = app;
34    }
35}
36
37/// What the binding above this one adds around `drawFrame`; kept erased.
38pub trait RendererBindingOverrides {
39    /// See [`RendererBindingOverridesObject::will_draw_frame`].
40    fn will_draw_frame(&self, app: &mut App);
41
42    /// See [`RendererBindingOverridesObject::did_draw_frame`].
43    fn did_draw_frame(&self, app: &mut App);
44
45    /// See [`RendererBindingOverridesObject::did_handle_metrics_changed`].
46    fn did_handle_metrics_changed(&self, app: &mut App);
47}
48
49impl<T: RendererBindingOverridesObject> RendererBindingOverrides for Handle<T> {
50    fn will_draw_frame(&self, app: &mut App) {
51        T::will_draw_frame(*self, app);
52    }
53
54    fn did_draw_frame(&self, app: &mut App) {
55        T::did_draw_frame(*self, app);
56    }
57
58    fn did_handle_metrics_changed(&self, app: &mut App) {
59        T::did_handle_metrics_changed(*self, app);
60    }
61}
62
63/// An override object the renderer binding keeps, for one nothing else keeps.
64impl<T: RendererBindingOverridesObject> RendererBindingOverrides for Ref<T> {
65    fn will_draw_frame(&self, app: &mut App) {
66        T::will_draw_frame(self.handle(), app);
67    }
68
69    fn did_draw_frame(&self, app: &mut App) {
70        T::did_draw_frame(self.handle(), app);
71    }
72
73    fn did_handle_metrics_changed(&self, app: &mut App) {
74        T::did_handle_metrics_changed(self.handle(), app);
75    }
76}
77
78/// Dart's `_BindingPipelineManifold`: the [`PipelineManifold`] the binding attaches its
79/// root [`PipelineOwner`] to. Its `semanticsEnabled` waits with semantics.
80struct BindingPipelineManifold;
81
82impl PipelineManifold for BindingPipelineManifold {
83    /// A frame of every view, for an owner that renders no view of its own.
84    fn request_visual_update(&self, app: &mut App) {
85        SchedulerBinding::ensure_visual_update(app, FrameTarget::EveryView);
86    }
87}
88
89#[derive(Default)]
90pub struct RendererBinding {
91    overrides: Option<Rc<dyn RendererBindingOverrides>>,
92    root_pipeline_owner: Option<Ref<PipelineOwner>>,
93    /// The render view [`init_render_view`](Self::init_render_view) made, which it answers again.
94    test_render_view: Option<RenderHandle<RenderView>>,
95    render_views: Vec<(ViewId, RenderHandle<RenderView>)>,
96    mouse_tracker: Option<Ref<MouseTracker>>,
97    debug_mouse_tracker_update_scheduled: bool,
98    first_frame_deferred_count: u32,
99    first_frame_sent: bool,
100    /// The view whose render view a test lays out at a surface size of its own, and that size:
101    /// flutter_test's `TestWidgetsFlutterBinding._surfaceSize`.
102    #[cfg(any(test, feature = "test-support"))]
103    surface_size: Option<(ViewId, waft_embedder::Size)>,
104}
105
106impl RendererBinding {
107    /// The current binding, initialized on first access (Flutter's `initInstances`).
108    pub fn instance(app: &mut App) -> Handle<RendererBinding> {
109        let this: Handle<RendererBinding> = app.singleton();
110        if app.get(this).root_pipeline_owner.is_none() {
111            let root_pipeline_owner = this.create_root_pipeline_owner(app);
112            app.get_mut(this).root_pipeline_owner = Some(root_pipeline_owner.clone());
113            root_pipeline_owner.attach(app, Rc::new(BindingPipelineManifold));
114            SchedulerBinding::add_persistent_frame_callback(
115                app,
116                PersistentFrameCallback::new(|app, views, _time_stamp| {
117                    RendererBinding::instance(app).handle_persistent_frame_callback(app, views)
118                }),
119            );
120            this.init_mouse_tracker(app, None);
121            // Flutter's `RendererBinding` overrides `GestureBinding.hitTestInView` and
122            // `dispatchEvent`.
123            GestureBinding::instance(app).set_overrides(app, Rc::new(this));
124        }
125        this
126    }
127
128    /// The object that manages state about currently connected mice, for hover
129    /// notification.
130    pub fn mouse_tracker(self: Handle<Self>, app: &App) -> Handle<MouseTracker> {
131        app.get(self)
132            .mouse_tracker
133            .handle()
134            .expect("RendererBinding::instance must run first")
135    }
136
137    /// Creates a [`MouseTracker`] which manages state about currently connected
138    /// mice, for hover notification.
139    ///
140    /// Used by testing framework to reinitialize the mouse tracker between tests.
141    pub fn init_mouse_tracker(
142        self: Handle<Self>,
143        app: &mut App,
144        tracker: Option<Ref<MouseTracker>>,
145    ) {
146        if let Some(previous) = app.get(self).mouse_tracker.handle() {
147            previous.dispose(app);
148        }
149        let tracker = tracker.unwrap_or_else(|| {
150            MouseTracker::new(
151                app,
152                Rc::new(move |app: &mut App, position: Offset, view_id: ViewId| {
153                    let mut result = HitTestResult::new();
154                    self.hit_test_in_view(app, &mut result, position, view_id);
155                    result
156                }),
157            )
158        });
159        app.get_mut(self).mouse_tracker = Some(tracker);
160    }
161
162    /// The [`PipelineOwner`] that is the root of the pipeline owner tree.
163    ///
164    /// Typically, this owner has no root render object (a `RenderView` is attached to the
165    /// owners the widget layer adds as children). A test that renders without widgets attaches
166    /// its view's here, through [`init_render_view`](Self::init_render_view).
167    pub fn root_pipeline_owner(self: Handle<Self>, app: &App) -> Handle<PipelineOwner> {
168        app.get(self)
169            .root_pipeline_owner
170            .handle()
171            .expect("RendererBinding::instance must run first")
172    }
173
174    /// Creates the [`PipelineOwner`] that serves as the root of the pipeline owner tree.
175    ///
176    /// When a test's render view is its root node ([`init_render_view`](Self::init_render_view)),
177    /// that view is marked to be composited after a paint that had work.
178    fn create_root_pipeline_owner(self: Handle<Self>, app: &mut App) -> Ref<PipelineOwner> {
179        PipelineOwner::new(
180            app,
181            Some(Listener::new(|app| {
182                SchedulerBinding::ensure_visual_update(app, FrameTarget::EveryView);
183            })),
184            Some(Rc::new(move |app: &mut App, is_dirty: bool| {
185                if is_dirty {
186                    let root_node = self.root_pipeline_owner(app).root_node(app);
187                    if let Some(render_view) =
188                        root_node.and_then(|root_node| root_node.downcast::<RenderView>(app))
189                    {
190                        render_view.mark_needs_composite_frame(app);
191                    }
192                }
193            })),
194        )
195    }
196
197    /// The [`RenderView`]s managed by this binding.
198    pub fn render_views(self: Handle<Self>, app: &App) -> Vec<RenderHandle<RenderView>> {
199        app.get(self)
200            .render_views
201            .iter()
202            .map(|(_, view)| *view)
203            .collect()
204    }
205
206    /// Adds a [`RenderView`] to this binding.
207    ///
208    /// The binding will interact with the [`RenderView`] in the following ways:
209    ///
210    /// - setting and updating [`RenderView::configuration`],
211    /// - calling [`RenderView::composite_frame`] when it is time to produce a new frame.
212    pub fn add_render_view(self: Handle<Self>, app: &mut App, view: RenderHandle<RenderView>) {
213        let view_id = view.flutter_view(app).id();
214        debug_assert!(
215            !app.get(self)
216                .render_views
217                .iter()
218                .any(|(id, existing)| *id == view_id || *existing == view)
219        );
220        app.get_mut(self).render_views.push((view_id, view));
221        let configuration = self.create_view_configuration_for(app, view);
222        view.set_configuration(app, configuration);
223        // Ensure the view composites at least once in a non-warm-up frame after
224        // being added, so its contents appear even if no descendants are dirty.
225        view.mark_needs_composite_frame(app);
226    }
227
228    /// Removes a [`RenderView`] previously added with [`add_render_view`](Self::add_render_view).
229    pub fn remove_render_view(self: Handle<Self>, app: &mut App, view: RenderHandle<RenderView>) {
230        let view_id = view.flutter_view(app).id();
231        let views = &mut app.get_mut(self).render_views;
232        debug_assert!(
233            views
234                .iter()
235                .any(|(id, existing)| *id == view_id && *existing == view)
236        );
237        views.retain(|(id, _)| *id != view_id);
238    }
239
240    /// Returns a [`ViewConfiguration`] configured for the provided [`RenderView`] based on
241    /// the current environment.
242    pub fn create_view_configuration_for(
243        self: Handle<Self>,
244        app: &App,
245        render_view: RenderHandle<RenderView>,
246    ) -> ViewConfiguration {
247        let view = render_view.flutter_view(app);
248        #[cfg(any(test, feature = "test-support"))]
249        if let Some((surface_view, size)) = app.get(self).surface_size
250            && surface_view == view.id()
251        {
252            // flutter_test's `TestWidgetsFlutterBinding.createViewConfigurationFor`.
253            let constraints = crate::BoxConstraints::tight(size);
254            let device_pixel_ratio = view.metrics().device_pixel_ratio;
255            return ViewConfiguration::new(
256                constraints * device_pixel_ratio,
257                constraints,
258                device_pixel_ratio,
259            );
260        }
261        ViewConfiguration::from_view(&*view)
262    }
263
264    /// flutter_test's `TestWidgetsFlutterBinding.setSurfaceSize`: lays the render view of `view`
265    /// out at `size` logical pixels, or at the view's own size again for `None`, leaving the
266    /// view's metrics, and so its `MediaQuery`, as they are.
267    #[cfg(any(test, feature = "test-support"))]
268    pub fn set_surface_size(
269        self: Handle<Self>,
270        app: &mut App,
271        view: ViewId,
272        size: Option<waft_embedder::Size>,
273    ) {
274        let surface_size = size.map(|size| (view, size));
275        if app.get(self).surface_size == surface_size {
276            return;
277        }
278        app.get_mut(self).surface_size = surface_size;
279        self.handle_metrics_changed(app);
280    }
281
282    /// Marks all views to require compositing, which will force them to re-render
283    /// on their next frame.
284    pub fn handle_mark_all_views_need_render(self: Handle<Self>, app: &mut App) {
285        for view in self.render_views(app) {
286            view.mark_needs_composite_frame(app);
287        }
288    }
289
290    /// Called when the system metrics change.
291    ///
292    /// See `View::metrics`.
293    pub fn handle_metrics_changed(self: Handle<Self>, app: &mut App) {
294        for view in self.render_views(app) {
295            let force_frame = view.child(app).is_some();
296            let configuration = self.create_view_configuration_for(app, view);
297            view.set_configuration(app, configuration);
298            if force_frame {
299                let view_id = view.flutter_view(app).id();
300                SchedulerBinding::schedule_forced_frame(app, FrameTarget::View(view_id));
301            }
302        }
303        if let Some(overrides) = app.get(self).overrides.clone() {
304            overrides.did_handle_metrics_changed(app);
305        }
306    }
307
308    fn handle_persistent_frame_callback(self: Handle<Self>, app: &mut App, views: &[ViewId]) {
309        self.draw_frame(app, views);
310        self.schedule_mouse_tracker_update(app);
311    }
312
313    fn schedule_mouse_tracker_update(self: Handle<Self>, app: &mut App) {
314        debug_assert!(!app.get(self).debug_mouse_tracker_update_scheduled);
315        if cfg!(debug_assertions) {
316            app.get_mut(self).debug_mouse_tracker_update_scheduled = true;
317        }
318        SchedulerBinding::add_post_frame_callback(
319            app,
320            FrameCallback::new(move |app, _duration| {
321                debug_assert!(app.get(self).debug_mouse_tracker_update_scheduled);
322                if cfg!(debug_assertions) {
323                    app.get_mut(self).debug_mouse_tracker_update_scheduled = false;
324                }
325                self.mouse_tracker(app).update_all_devices(app);
326            }),
327            None,
328        );
329    }
330
331    /// Whether frames produced by [`draw_frame`](Self::draw_frame) are sent to the host.
332    ///
333    /// If false the framework will do all the work to produce a frame, but the frame is never
334    /// sent to the host to actually appear on screen.
335    pub fn send_frames_to_engine(self: Handle<Self>, app: &App) -> bool {
336        let data = app.get(self);
337        data.first_frame_sent || data.first_frame_deferred_count == 0
338    }
339
340    /// Tell the framework to not send the first frames to the host until there is a
341    /// corresponding call to [`allow_first_frame`](Self::allow_first_frame).
342    pub fn defer_first_frame(self: Handle<Self>, app: &mut App) {
343        app.get_mut(self).first_frame_deferred_count += 1;
344    }
345
346    /// Called after [`defer_first_frame`](Self::defer_first_frame) to tell the framework that it
347    /// is ok to send the first frame to the host now.
348    pub fn allow_first_frame(self: Handle<Self>, app: &mut App) {
349        debug_assert!(app.get(self).first_frame_deferred_count > 0);
350        app.get_mut(self).first_frame_deferred_count -= 1;
351        if !app.get(self).first_frame_sent {
352            SchedulerBinding::schedule_forced_frame(app, FrameTarget::EveryView);
353        }
354    }
355
356    /// Call this to pretend that no frames have been sent to the host yet.
357    pub fn reset_first_frame_sent(self: Handle<Self>, app: &mut App) {
358        app.get_mut(self).first_frame_sent = false;
359    }
360
361    /// Registers the binding layered above this one, as Flutter's `WidgetsBinding` does by
362    /// overriding `drawFrame`.
363    pub fn set_overrides(
364        self: Handle<Self>,
365        app: &mut App,
366        overrides: Rc<dyn RendererBindingOverrides>,
367    ) {
368        app.get_mut(self).overrides = Some(overrides);
369    }
370
371    /// Pump the rendering pipeline to generate a frame of `views`.
372    ///
373    /// This method is called by `handle_draw_frame`, which itself is called automatically by
374    /// the host when it is time to lay out and paint a frame.
375    ///
376    /// Each frame consists of the following phases: layout and compositing bits for every
377    /// render tree, then paint and compositing for the [`RenderView`] of each of `views`. A view
378    /// paints its own render tree alone, not the views anchored in it, which paint at frames of
379    /// their own; it is composited only when it [needs it](RenderView::needs_composite_frame),
380    /// and otherwise keeps showing its last frame.
381    pub fn draw_frame(self: Handle<Self>, app: &mut App, views: &[ViewId]) {
382        let overrides = app.get(self).overrides.clone();
383        if let Some(overrides) = &overrides {
384            overrides.will_draw_frame(app);
385        }
386        let root_pipeline_owner = self.root_pipeline_owner(app);
387        root_pipeline_owner.flush_layout(app);
388        root_pipeline_owner.flush_compositing_bits(app);
389        let render_views: Vec<RenderHandle<RenderView>> = views
390            .iter()
391            .filter_map(|&view| self.render_view_of(app, view))
392            .collect();
393        for render_view in &render_views {
394            if let Some(owner) = render_view.as_object().owner(app) {
395                owner.flush_paint_without_children(app);
396            }
397        }
398        if self.send_frames_to_engine(app) {
399            for render_view in render_views {
400                if render_view.needs_composite_frame(app) {
401                    render_view.composite_frame(app); // this sends the bits to the GPU
402                }
403                if SchedulerBinding::is_warm_up_frame(app) {
404                    // Warm-up frame does not guarantee that the content is actually
405                    // painted (see [SchedulerBinding::schedule_warm_up_frame]). This is to
406                    // ensure that on the subsequent real frame the view is recomposited.
407                    render_view.mark_needs_composite_frame(app);
408                }
409            }
410            app.get_mut(self).first_frame_sent = true;
411        }
412        if let Some(overrides) = &overrides {
413            overrides.did_draw_frame(app);
414        }
415    }
416
417    /// The [`RenderView`] of `view`, if this binding has one.
418    fn render_view_of(
419        self: Handle<Self>,
420        app: &App,
421        view: ViewId,
422    ) -> Option<RenderHandle<RenderView>> {
423        app.get(self)
424            .render_views
425            .iter()
426            .find(|(id, _)| *id == view)
427            .map(|(_, render_view)| *render_view)
428    }
429
430    /// Flutter's `TestRenderingFlutterBinding.initRenderView`: makes a [`RenderView`] for `view`
431    /// the root of [`root_pipeline_owner`](Self::root_pipeline_owner), registers it, and
432    /// prepares its first frame. Idempotent, as `_ReusableRenderView` is: a later call answers
433    /// the first call's render view.
434    pub fn init_render_view(
435        self: Handle<Self>,
436        app: &mut App,
437        view: ViewRef,
438    ) -> RenderHandle<RenderView> {
439        if let Some(render_view) = app.get(self).test_render_view {
440            return render_view;
441        }
442        let render_view = RenderView::new(app, None, None, view);
443        app.get_mut(self).test_render_view = Some(render_view);
444        self.root_pipeline_owner(app)
445            .set_root_node(app, Some(render_view.as_object()));
446        self.add_render_view(app, render_view);
447        render_view.prepare_initial_frame(app);
448        render_view
449    }
450}
451
452/// Flutter's `RendererBinding.hitTestInView` override: the render view for `view_id` hit-tests
453/// first; `GestureBinding` then adds itself.
454/// Flutter's `RendererBinding` overrides of `GestureBinding`: `hitTestInView` walks the render
455/// trees, `dispatchEvent` updates the mouse tracker before routing.
456impl GestureBindingOverridesObject for RendererBinding {
457    fn hit_test_in_view(
458        self: Handle<Self>,
459        app: &mut App,
460        result: &mut HitTestResult,
461        position: Offset,
462        view_id: ViewId,
463    ) {
464        if let Some(render_view) = self.render_view_of(app, view_id) {
465            render_view.hit_test(app, result, position);
466        }
467    }
468
469    fn will_dispatch_event(
470        self: Handle<Self>,
471        app: &mut App,
472        event: &PointerEvent,
473        hit_test_result: Option<&HitTestResult>,
474    ) {
475        // When the button is pressed, normal hit test uses a cached
476        // result, but MouseTracker requires that the hit test is re-executed to
477        // update the hovering events.
478        let result = match event {
479            PointerEvent::Move(_) => None,
480            _ => hit_test_result,
481        };
482        self.mouse_tracker(app)
483            .update_with_event(app, event, result);
484    }
485}
486
487#[cfg(test)]
488mod tests {
489    use std::time::Duration;
490
491    use waft_embedder::{Size, TargetPlatform};
492    use waft_foundation::AppCell;
493    use waft_test::{IMPLICIT_VIEW_ID, TestPlatform, TestView};
494
495    use super::*;
496    use crate::box_::{BoxConstraints, RenderBox};
497    use crate::proxy_box::RenderConstrainedBox;
498
499    /// An [`App`] over one 800x600 view at 2x, with the view and the platform to read back.
500    fn app_with_view() -> (Rc<AppCell>, Rc<TestView>, Rc<TestPlatform>) {
501        let view = Rc::new(TestView::with_pixel_ratio(800.0, 600.0, 2.0));
502        let platform = Rc::new(
503            TestPlatform::new()
504                .on(TargetPlatform::MacOS)
505                .with_view(view.clone()),
506        );
507        (AppCell::with_platform(platform.clone()), view, platform)
508    }
509
510    /// A frame of `views` at `at`, with the microtasks drained after each half.
511    fn pump(app: &mut App, views: &[ViewId], at: Duration) {
512        SchedulerBinding::handle_begin_frame(app, views, Some(at));
513        app.drain_microtasks();
514        SchedulerBinding::handle_draw_frame(app, views);
515        app.drain_microtasks();
516    }
517
518    #[test]
519    fn a_frame_lays_out_paints_and_presents_the_view() {
520        let (cell, view, _platform) = app_with_view();
521        let mut app = cell.borrow_mut();
522        let binding = RendererBinding::instance(&mut app);
523        let render_view = binding.init_render_view(&mut app, view.clone());
524        assert_eq!(
525            render_view.configuration(&app).logical_constraints,
526            BoxConstraints::tight(Size::new(400.0, 300.0))
527        );
528        let child =
529            RenderConstrainedBox::new(&mut app, BoxConstraints::tight(Size::new(10.0, 10.0)), None);
530        render_view.set_child(&mut app, Some(child.as_box()));
531
532        pump(&mut app, &[IMPLICIT_VIEW_ID], Duration::ZERO);
533
534        assert_eq!(render_view.size(&app), Size::new(400.0, 300.0));
535        assert_eq!(child.size(&app), Size::new(400.0, 300.0));
536        assert_eq!(view.presented(), 1);
537        assert!(!child.debug_needs_layout(&app));
538        assert!(!child.as_object().debug_needs_paint(&app));
539    }
540
541    #[test]
542    fn a_dirty_node_requests_a_visual_update() {
543        let (cell, view, platform) = app_with_view();
544        let mut app = cell.borrow_mut();
545        let binding = RendererBinding::instance(&mut app);
546        let render_view = binding.init_render_view(&mut app, view.clone());
547        let child =
548            RenderConstrainedBox::new(&mut app, BoxConstraints::tight(Size::new(10.0, 10.0)), None);
549        render_view.set_child(&mut app, Some(child.as_box()));
550        pump(&mut app, &[IMPLICIT_VIEW_ID], Duration::ZERO);
551        platform.take_frame_requests();
552
553        child.mark_needs_layout(&mut app);
554        assert_eq!(
555            platform.take_frame_requests(),
556            [IMPLICIT_VIEW_ID],
557            "the root owner's visual update reaches the host"
558        );
559    }
560
561    #[test]
562    fn a_pointer_down_reaches_a_pointer_listener_through_the_gesture_binding() {
563        use waft_gestures::{PointerDownEvent, PointerEvent};
564
565        use crate::proxy_box::{HitTestBehavior, RenderPointerListener};
566
567        let (cell, view, _platform) = app_with_view();
568        let mut app = cell.borrow_mut();
569        let binding = RendererBinding::instance(&mut app);
570        let render_view = binding.init_render_view(&mut app, view.clone());
571        let listener = RenderPointerListener::new(&mut app, HitTestBehavior::Opaque, None);
572        let positions = Rc::new(std::cell::RefCell::new(Vec::new()));
573        let recorded = Rc::clone(&positions);
574        listener.set_on_pointer_down(
575            &mut app,
576            Some(Rc::new(move |_app: &mut App, event: PointerDownEvent| {
577                recorded.borrow_mut().push(event.local_position());
578            })),
579        );
580        render_view.set_child(&mut app, Some(listener.as_box()));
581        pump(&mut app, &[IMPLICIT_VIEW_ID], Duration::ZERO);
582
583        GestureBinding::instance(&mut app).handle_pointer_event(
584            &mut app,
585            PointerEvent::Down(PointerDownEvent {
586                position: Offset::new(30.0, 40.0),
587                ..PointerDownEvent::default()
588            }),
589        );
590        assert_eq!(*positions.borrow(), [Offset::new(30.0, 40.0)]);
591    }
592
593    #[test]
594    fn a_mouse_hover_enters_a_mouse_region_and_a_frame_notices_it_moving_away() {
595        use waft_embedder::PointerDeviceKind;
596        use waft_gestures::{PointerAddedEvent, PointerEnterEvent, PointerEvent, PointerExitEvent};
597        use waft_painting::EdgeInsetsGeometry;
598
599        use crate::proxy_box::{RenderMouseRegion, RenderMouseRegionBase};
600        use crate::shifted_box::RenderPadding;
601
602        let (cell, view, _platform) = app_with_view();
603        let mut app = cell.borrow_mut();
604        let binding = RendererBinding::instance(&mut app);
605        let render_view = binding.init_render_view(&mut app, view.clone());
606        let region = RenderMouseRegion::new(&mut app, true, None);
607        let log = Rc::new(std::cell::RefCell::new(Vec::new()));
608        let entered = Rc::clone(&log);
609        region.set_on_enter(
610            &mut app,
611            Some(Rc::new(move |_app: &mut App, event: PointerEnterEvent| {
612                entered
613                    .borrow_mut()
614                    .push(format!("enter {:?}", event.local_position()));
615            })),
616        );
617        let exited = Rc::clone(&log);
618        region.set_on_exit(
619            &mut app,
620            Some(Rc::new(move |_app: &mut App, event: PointerExitEvent| {
621                exited
622                    .borrow_mut()
623                    .push(format!("exit {:?}", event.local_position()));
624            })),
625        );
626        let padding = RenderPadding::new(
627            &mut app,
628            EdgeInsetsGeometry::all(100.0),
629            None,
630            Some(region.as_box()),
631        );
632        render_view.set_child(&mut app, Some(padding.as_box()));
633        pump(&mut app, &[IMPLICIT_VIEW_ID], Duration::ZERO);
634
635        GestureBinding::instance(&mut app).handle_pointer_event(
636            &mut app,
637            PointerEvent::Added(PointerAddedEvent {
638                kind: PointerDeviceKind::Mouse,
639                position: Offset::new(150.0, 150.0),
640                ..PointerAddedEvent::default()
641            }),
642        );
643        assert_eq!(*log.borrow(), ["enter Offset(50.0, 50.0)"]);
644        assert!(binding.mouse_tracker(&app).mouse_is_connected(&app));
645
646        // The tree moves under the still mouse; the post-frame update sends the exit.
647        padding.set_padding(&mut app, EdgeInsetsGeometry::only(300.0, 0.0, 0.0, 0.0));
648        pump(&mut app, &[IMPLICIT_VIEW_ID], Duration::from_millis(16));
649        assert_eq!(
650            *log.borrow(),
651            ["enter Offset(50.0, 50.0)", "exit Offset(50.0, 50.0)"],
652            "the exit is placed with the transform recorded when the region was entered"
653        );
654    }
655
656    #[test]
657    fn deferred_first_frame_is_not_presented() {
658        let (cell, view, _platform) = app_with_view();
659        let mut app = cell.borrow_mut();
660        let binding = RendererBinding::instance(&mut app);
661        binding.init_render_view(&mut app, view.clone());
662        binding.defer_first_frame(&mut app);
663        pump(&mut app, &[IMPLICIT_VIEW_ID], Duration::ZERO);
664        assert_eq!(view.presented(), 0);
665
666        binding.allow_first_frame(&mut app);
667        pump(&mut app, &[IMPLICIT_VIEW_ID], Duration::ZERO);
668        assert_eq!(view.presented(), 1);
669    }
670
671    const FIRST: ViewId = ViewId(1);
672    const SECOND: ViewId = ViewId(2);
673
674    /// An app whose platform has views [`FIRST`] and [`SECOND`], each with a render view under a
675    /// pipeline owner the root owner adopted, which marks its view to be composited after a
676    /// paint that had work, as `RawView`'s does.
677    fn app_with_render_views() -> (Rc<AppCell>, Rc<TestPlatform>, [RenderHandle<RenderView>; 2]) {
678        let platform = Rc::new(
679            TestPlatform::new()
680                .on(TargetPlatform::MacOS)
681                .with_views(&[FIRST, SECOND]),
682        );
683        let cell = AppCell::with_platform(platform.clone());
684        let render_views = {
685            let mut app = cell.borrow_mut();
686            [FIRST, SECOND].map(|view| add_render_view(&mut app, platform.test_view(view)))
687        };
688        (cell, platform, render_views)
689    }
690
691    /// A render view of `view` under a pipeline owner of its own, registered with the binding.
692    fn add_render_view(app: &mut App, view: Rc<TestView>) -> RenderHandle<RenderView> {
693        let binding = RendererBinding::instance(app);
694        let render_view = RenderView::new(app, None, None, view);
695        let owner = PipelineOwner::new(
696            app,
697            None,
698            Some(Rc::new(move |app: &mut App, is_dirty: bool| {
699                if is_dirty {
700                    render_view.mark_needs_composite_frame(app);
701                }
702            })),
703        );
704        owner.set_root_node(app, Some(render_view.as_object()));
705        binding.root_pipeline_owner(app).adopt_child(app, owner);
706        binding.add_render_view(app, render_view);
707        render_view.prepare_initial_frame(app);
708        render_view
709    }
710
711    /// How many frames each of [`FIRST`] and [`SECOND`] was presented.
712    fn presented(platform: &TestPlatform) -> [u32; 2] {
713        [FIRST, SECOND].map(|view| platform.test_view(view).presented())
714    }
715
716    // multi_view_binding_test.dart 'all registered renderviews are asked to composite frame',
717    // with a frame of each view's own where Flutter's one frame is of every view.
718    #[test]
719    fn every_registered_render_view_is_composited_at_its_frame() {
720        let (cell, platform, [first, second]) = app_with_render_views();
721        let mut app = cell.borrow_mut();
722        let binding = RendererBinding::instance(&mut app);
723        assert_eq!(presented(&platform), [0, 0]);
724
725        pump(&mut app, &[FIRST, SECOND], Duration::ZERO);
726        assert_eq!(presented(&platform), [1, 1]);
727
728        binding.remove_render_view(&mut app, first);
729        second.as_object().mark_needs_paint(&mut app);
730        pump(&mut app, &[FIRST, SECOND], Duration::ZERO);
731        assert_eq!(presented(&platform), [1, 2]);
732
733        binding.remove_render_view(&mut app, second);
734        pump(&mut app, &[FIRST, SECOND], Duration::ZERO);
735        assert_eq!(presented(&platform), [1, 2]);
736    }
737
738    // multi_view_binding_test.dart 'render views that are not dirty are not composited'.
739    #[test]
740    fn a_render_view_that_is_not_dirty_is_not_composited() {
741        let (cell, platform, [first, second]) = app_with_render_views();
742        let mut app = cell.borrow_mut();
743        let binding = RendererBinding::instance(&mut app);
744
745        // First frame: both views are composited (they are newly added).
746        pump(&mut app, &[FIRST, SECOND], Duration::ZERO);
747        assert_eq!(presented(&platform), [1, 1]);
748
749        // Second frame: neither view is dirty, so neither is composited.
750        pump(&mut app, &[FIRST, SECOND], Duration::ZERO);
751        assert_eq!(presented(&platform), [1, 1]);
752
753        // Only the second is marked dirty: only the second is composited.
754        second.as_object().mark_needs_paint(&mut app);
755        pump(&mut app, &[FIRST, SECOND], Duration::ZERO);
756        assert_eq!(presented(&platform), [1, 2]);
757
758        binding.remove_render_view(&mut app, first);
759        binding.remove_render_view(&mut app, second);
760    }
761
762    #[test]
763    fn a_frame_paints_and_composites_only_its_own_views() {
764        let (cell, platform, [first, second]) = app_with_render_views();
765        let mut app = cell.borrow_mut();
766        pump(&mut app, &[FIRST, SECOND], Duration::ZERO);
767
768        first.as_object().mark_needs_paint(&mut app);
769        second.as_object().mark_needs_paint(&mut app);
770        pump(&mut app, &[SECOND], Duration::ZERO);
771        assert_eq!(presented(&platform), [1, 2]);
772        assert!(
773            first.as_object().debug_needs_paint(&app),
774            "left for its own frame"
775        );
776    }
777
778    #[test]
779    fn a_view_drawn_in_the_warm_up_frame_is_composited_again_at_its_next_frame() {
780        let (cell, platform, _render_views) = app_with_render_views();
781        SchedulerBinding::schedule_warm_up_frame(&mut cell.borrow_mut());
782        cell.elapse(Duration::ZERO);
783        assert_eq!(presented(&platform), [1, 1]);
784
785        let mut app = cell.borrow_mut();
786        pump(&mut app, &[FIRST], Duration::ZERO);
787        assert_eq!(
788            presented(&platform),
789            [2, 1],
790            "a warm-up frame may not reach the screen: the next real frame composites again"
791        );
792        pump(&mut app, &[FIRST], Duration::ZERO);
793        assert_eq!(presented(&platform), [2, 1]);
794    }
795
796    #[test]
797    fn marking_every_view_to_be_rendered_composites_each_at_its_next_frame() {
798        let (cell, platform, _render_views) = app_with_render_views();
799        let mut app = cell.borrow_mut();
800        let binding = RendererBinding::instance(&mut app);
801        pump(&mut app, &[FIRST, SECOND], Duration::ZERO);
802
803        binding.handle_mark_all_views_need_render(&mut app);
804        pump(&mut app, &[FIRST, SECOND], Duration::ZERO);
805        assert_eq!(presented(&platform), [2, 2]);
806    }
807}