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