Skip to main content

waft_rendering/
view.rs

1//! Flutter counterpart: `rendering/view.dart` (`ViewConfiguration`, `RenderView`).
2//!
3//! `applyPaintTransform` and semantics wait.
4
5use std::rc::Rc;
6
7use waft_embedder::{
8    Matrix4, Offset, Rect, SceneBuilder, Size, SystemUiOverlayStyle, TargetPlatform, View, ViewRef,
9};
10use waft_foundation::{App, Handle};
11use waft_gestures::{HitTestEntry, HitTestResult, HitTestTarget, PointerEvent};
12use waft_services::SystemChrome;
13
14use crate::box_::{AnyRenderBox, BoxConstraints, BoxHitTestResult};
15use crate::layer::{ContainerLayer, ErasedLayer, OffsetLayerMixin, TransformLayer};
16use crate::object::{
17    AnyRenderObject, Constraints, RenderHandle, RenderObject, RenderObjectData, RenderObjectVTable,
18    resolve,
19};
20use crate::painting_context::PaintingContext;
21
22/// The layout constraints for the root render object.
23#[derive(Clone, Copy, Debug, PartialEq)]
24pub struct ViewConfiguration {
25    /// The constraints of the output surface in logical pixels.
26    pub logical_constraints: BoxConstraints,
27    /// The constraints of the output surface in physical pixels.
28    pub physical_constraints: BoxConstraints,
29    /// The pixel density of the output surface.
30    pub device_pixel_ratio: f64,
31}
32
33impl ViewConfiguration {
34    /// Creates a view configuration.
35    ///
36    /// By default, the view has zero constraints and a pixel ratio of 1.0.
37    pub const fn new(
38        physical_constraints: BoxConstraints,
39        logical_constraints: BoxConstraints,
40        device_pixel_ratio: f64,
41    ) -> ViewConfiguration {
42        ViewConfiguration {
43            logical_constraints,
44            physical_constraints,
45            device_pixel_ratio,
46        }
47    }
48
49    /// Creates a view configuration that matches `view`.
50    pub fn from_view(view: &dyn View) -> ViewConfiguration {
51        let metrics = view.metrics();
52        let physical_constraints =
53            BoxConstraints::from_view_constraints(metrics.physical_constraints);
54        let device_pixel_ratio = metrics.device_pixel_ratio;
55        ViewConfiguration {
56            logical_constraints: physical_constraints / device_pixel_ratio,
57            physical_constraints,
58            device_pixel_ratio,
59        }
60    }
61
62    /// Creates a transformation matrix that applies the
63    /// [`device_pixel_ratio`](Self::device_pixel_ratio).
64    pub fn to_matrix(&self) -> Matrix4 {
65        Matrix4::scale(
66            self.device_pixel_ratio as f32,
67            self.device_pixel_ratio as f32,
68        )
69    }
70
71    /// Returns whether [`to_matrix`](Self::to_matrix) would return a different value for
72    /// this configuration than it would for the given `old_configuration`.
73    pub fn should_update_matrix(&self, old_configuration: &ViewConfiguration) -> bool {
74        old_configuration.device_pixel_ratio != self.device_pixel_ratio
75    }
76
77    /// Transforms the provided `logical_size` to physical pixels.
78    pub fn to_physical_size(&self, logical_size: Size) -> Size {
79        self.physical_constraints
80            .constrain(logical_size * self.device_pixel_ratio)
81    }
82}
83
84impl Default for ViewConfiguration {
85    fn default() -> ViewConfiguration {
86        ViewConfiguration::new(
87            BoxConstraints::new().max_width(0.0).max_height(0.0),
88            BoxConstraints::new().max_width(0.0).max_height(0.0),
89            1.0,
90        )
91    }
92}
93
94/// The root of the render tree.
95///
96/// The view represents the total output surface of the render tree and handles
97/// bootstrapping the rendering pipeline. The view has a unique child
98/// [`crate::RenderBox`], which is required to fill the entire output surface.
99///
100/// Not a box: its constraints come from its [`configuration`](Self::configuration), and its
101/// child is the one slot Flutter's `RenderObjectWithChildMixin` gives it.
102pub struct RenderView {
103    render_object: RenderObjectData,
104    child: Option<AnyRenderBox>,
105    size: Size,
106    configuration: Option<ViewConfiguration>,
107    view: ViewRef,
108    root_transform: Option<Matrix4>,
109    needs_composite_frame: bool,
110    /// Whether the system overlays are styled from the layer tree at every frame.
111    ///
112    /// An application that would rather drive them itself, through
113    /// [`SystemChrome::set_system_ui_overlay_style`], turns this off so its own style is
114    /// not overwritten by whatever happens to be annotated under the bars.
115    pub automatic_system_ui_adjustment: bool,
116}
117
118impl RenderView {
119    /// Creates the root of the render tree.
120    ///
121    /// Typically created by the binding (e.g., `RendererBinding`).
122    ///
123    /// Providing a `configuration` is optional, but a configuration must be set
124    /// before calling [`prepare_initial_frame`](Self::prepare_initial_frame).
125    pub fn new(
126        app: &mut App,
127        child: Option<AnyRenderBox>,
128        configuration: Option<ViewConfiguration>,
129        view: ViewRef,
130    ) -> RenderHandle<RenderView> {
131        let this = crate::object::create(
132            app,
133            RenderView {
134                render_object: RenderObjectData::new(),
135                child: None,
136                size: Size::ZERO,
137                configuration: None,
138                view,
139                root_transform: None,
140                needs_composite_frame: false,
141                automatic_system_ui_adjustment: true,
142            },
143        );
144        let data = this.render_object_data_mut(app);
145        data.object_vtable = Some(&VTABLE);
146        data.was_repaint_boundary = true;
147        data.needs_compositing = true;
148        if let Some(configuration) = configuration {
149            this.set_configuration(app, configuration);
150        }
151        this.set_child(app, child);
152        this
153    }
154
155    /// The type-erased `RenderObject` handle.
156    pub fn as_object(self: RenderHandle<Self>) -> AnyRenderObject {
157        AnyRenderObject::from_vtable(self.id(), const { &VTABLE })
158    }
159
160    /// The render object's unique child. Flutter's `RenderObjectWithChildMixin.child`.
161    pub fn child(self: RenderHandle<Self>, app: &App) -> Option<AnyRenderBox> {
162        self.get(app).child
163    }
164
165    /// Sets the unique child, adopting or dropping as Flutter's setter does.
166    pub fn set_child(self: RenderHandle<Self>, app: &mut App, value: Option<AnyRenderBox>) {
167        if let Some(old) = self.get(app).child {
168            self.as_object().drop_child(app, old.as_object());
169        }
170        self.get_mut(app).child = value;
171        if let Some(new) = value {
172            self.as_object().adopt_child(app, new.as_object());
173        }
174    }
175
176    /// The current layout size of the view.
177    pub fn size(self: RenderHandle<Self>, app: &App) -> Size {
178        self.get(app).size
179    }
180
181    /// The constraints used for the root layout.
182    ///
183    /// Typically, this configuration is set by the `RendererBinding`, when the
184    /// [`RenderView`] is registered with it. It will also update the configuration
185    /// if necessary. Therefore, if used in conjunction with the `RendererBinding`
186    /// this property must not be set manually as the `RendererBinding` will just
187    /// override it.
188    ///
189    /// # Panics
190    ///
191    /// If no configuration has been set.
192    pub fn configuration(self: RenderHandle<Self>, app: &App) -> ViewConfiguration {
193        self.get(app)
194            .configuration
195            .expect("RenderView has not been given a configuration yet")
196    }
197
198    /// Sets [`configuration`](Self::configuration).
199    pub fn set_configuration(self: RenderHandle<Self>, app: &mut App, value: ViewConfiguration) {
200        if self.get(app).configuration == Some(value) {
201            return;
202        }
203        let old_configuration = self.get(app).configuration;
204        self.get_mut(app).configuration = Some(value);
205        if self.get(app).root_transform.is_none() {
206            // [prepare_initial_frame] has not been called yet, nothing more to do for now.
207            return;
208        }
209        if old_configuration.is_none_or(|old| value.should_update_matrix(&old)) {
210            let root_layer = self.update_matrices_and_create_new_root_layer(app);
211            self.as_object()
212                .replace_root_layer(app, root_layer.as_offset_layer());
213        }
214        debug_assert!(self.get(app).root_transform.is_some());
215        self.as_object().mark_needs_layout(app);
216    }
217
218    /// Whether a [`configuration`](Self::configuration) has been set.
219    pub fn has_configuration(self: RenderHandle<Self>, app: &App) -> bool {
220        self.get(app).configuration.is_some()
221    }
222
223    /// The constraints most recently supplied for layout: the configuration's logical
224    /// constraints.
225    ///
226    /// # Panics
227    ///
228    /// If no configuration has been set.
229    pub fn constraints(self: RenderHandle<Self>, app: &App) -> BoxConstraints {
230        debug_assert!(
231            self.has_configuration(app),
232            "Constraints are not available because RenderView has not been given a configuration yet."
233        );
234        self.configuration(app).logical_constraints
235    }
236
237    /// The host view into which this render tree is rendered.
238    pub fn flutter_view(self: RenderHandle<Self>, app: &App) -> ViewRef {
239        self.get(app).view.clone()
240    }
241
242    /// Bootstrap the rendering pipeline by preparing the first frame.
243    ///
244    /// This should only be called once, and must be called before changing
245    /// [`configuration`](Self::configuration). It is typically called immediately after calling
246    /// the constructor.
247    ///
248    /// This does not actually schedule the first frame. Call
249    /// `SchedulerBinding::ensure_visual_update` for that.
250    pub fn prepare_initial_frame(self: RenderHandle<Self>, app: &mut App) {
251        debug_assert!(
252            self.as_object().owner(app).is_some(),
253            "attach the RenderView to a PipelineOwner before calling prepare_initial_frame"
254        );
255        debug_assert!(
256            self.get(app).root_transform.is_none(),
257            "prepare_initial_frame must only be called once"
258        );
259        debug_assert!(
260            self.has_configuration(app),
261            "set a configuration before calling prepare_initial_frame"
262        );
263        self.as_object().schedule_initial_layout(app);
264        let root_layer = self.update_matrices_and_create_new_root_layer(app);
265        self.as_object()
266            .schedule_initial_paint(app, root_layer.as_container_layer());
267        debug_assert!(self.get(app).root_transform.is_some());
268    }
269
270    /// Whether this view must be composited on the next frame.
271    ///
272    /// This flag is cleared once the view gets successfully composited.
273    pub fn needs_composite_frame(self: RenderHandle<Self>, app: &App) -> bool {
274        self.get(app).needs_composite_frame
275    }
276
277    /// Marks this view required to be composited on the next frame.
278    ///
279    /// This happens by the [`PipelineOwner`](crate::PipelineOwner) during
280    /// [`flush_paint`](crate::PipelineOwner::flush_paint) if there are any render objects that
281    /// need to be painted. It is also set for a new view, for the warm-up frame, and when the
282    /// app is resumed from the background.
283    pub fn mark_needs_composite_frame(self: RenderHandle<Self>, app: &mut App) {
284        self.get_mut(app).needs_composite_frame = true;
285    }
286
287    fn update_matrices_and_create_new_root_layer(
288        self: RenderHandle<Self>,
289        app: &mut App,
290    ) -> Handle<TransformLayer> {
291        debug_assert!(self.has_configuration(app));
292        let root_transform = self.configuration(app).to_matrix();
293        self.get_mut(app).root_transform = Some(root_transform);
294        let root_layer = TransformLayer::new(app);
295        root_layer.set_transform(app, root_transform);
296        root_layer.attach(app, self.id());
297        debug_assert!(self.get(app).root_transform.is_some());
298        root_layer
299    }
300
301    /// Determines the set of render objects located at the given position.
302    ///
303    /// Returns true if the given point is contained in this render object or one of its
304    /// descendants. Adds any render objects that contain the point to the given hit test result.
305    ///
306    /// The `position` argument is in the coordinate system of the render view, which is to say,
307    /// in logical pixels. This is not necessarily the same coordinate system as that expected by
308    /// the root layer (which is in physical pixels).
309    pub fn hit_test(
310        self: RenderHandle<Self>,
311        app: &mut App,
312        result: &mut HitTestResult,
313        position: Offset,
314    ) -> bool {
315        if let Some(child) = self.child(app) {
316            child.hit_test(app, &mut BoxHitTestResult::wrap(result), position);
317        }
318        result.add(HitTestEntry::new(self));
319        true
320    }
321
322    /// Uploads the composited layer tree to the host.
323    ///
324    /// Actually causes the output of the rendering pipeline to appear on screen.
325    pub fn composite_frame(self: RenderHandle<Self>, app: &mut App) {
326        debug_assert!(
327            self.has_configuration(app),
328            "set the RenderView configuration before calling composite_frame"
329        );
330        debug_assert!(
331            self.get(app).root_transform.is_some(),
332            "call prepare_initial_frame before calling composite_frame"
333        );
334        let layer = self
335            .as_object()
336            .layer(app)
337            .expect("call prepare_initial_frame before calling composite_frame");
338        let scene = layer.build_scene(app, SceneBuilder::new());
339        if self.get(app).automatic_system_ui_adjustment {
340            self.update_system_chrome(app);
341        }
342        debug_assert!(
343            self.configuration(app)
344                .logical_constraints
345                .is_satisfied_by(self.size(app))
346        );
347        self.get(app).view.present(std::sync::Arc::new(scene));
348        self.get_mut(app).needs_composite_frame = false;
349    }
350
351    /// Styles the system overlays from whatever the layer tree annotates beneath them.
352    ///
353    /// Takes the overlay style from the place where a system status bar and system
354    /// navigation bar are placed to update system style overlay. The center of the system
355    /// navigation bar and the center of the status bar are used to get
356    /// `SystemUiOverlayStyle`'s to update system overlay appearance.
357    ///
358    /// ```text
359    ///         Horizontal center of the screen
360    ///                 V
361    ///    ++++++++++++++++++++++++++
362    ///    |                        |
363    ///    |    System status bar   |  <- Vertical center of the status bar
364    ///    |                        |
365    ///    ++++++++++++++++++++++++++
366    ///    |                        |
367    ///    |        Content         |
368    ///    ~                        ~
369    ///    |                        |
370    ///    ++++++++++++++++++++++++++
371    ///    |                        |
372    ///    |  System navigation bar | <- Vertical center of the navigation bar
373    ///    |                        |
374    ///    ++++++++++++++++++++++++++ <- bounds.bottom
375    /// ```
376    fn update_system_chrome(self: RenderHandle<Self>, app: &mut App) {
377        let Some(layer) = self.as_object().layer(app) else {
378            return;
379        };
380        let bounds = self.paint_bounds(app);
381        let padding = self.get(app).view.metrics().padding;
382        // Center of the status bar
383        let top = Offset::new(
384            // Horizontal center of the screen
385            bounds.center().dx(),
386            // The vertical center of the system status bar. The system status bar height
387            // is kept as top window padding.
388            padding.top / 2.0,
389        );
390        // Center of the navigation bar
391        let bottom = Offset::new(
392            // Horizontal center of the screen
393            bounds.center().dx(),
394            // Vertical center of the system navigation bar. The system navigation bar
395            // height is kept as bottom window padding. The "1" needs to be subtracted from
396            // the bottom because available pixels are in (0..bottom) range. I.e. for a
397            // device with 1920 height, bound.bottom is 1920, but the most bottom drawn
398            // pixel is at 1919 position.
399            bounds.bottom - 1.0 - padding.bottom / 2.0,
400        );
401        let layer = layer.as_layer();
402        let upper = layer.find::<SystemUiOverlayStyle>(app, top);
403        // Only Android has a customizable system navigation bar.
404        let is_android = app.platform().target_platform() == TargetPlatform::Android;
405        let lower = is_android
406            .then(|| layer.find::<SystemUiOverlayStyle>(app, bottom))
407            .flatten();
408        // If there are no overlay style in the UI don't bother updating.
409        let Some(style) = merged_overlay_style(upper, lower, is_android) else {
410            return;
411        };
412        let view = self.get(app).view.id();
413        SystemChrome::set_system_ui_overlay_style(app, view, &style);
414    }
415
416    /// An estimate of the bounds within which this render object will paint, in physical
417    /// pixels.
418    pub fn paint_bounds(self: RenderHandle<Self>, app: &App) -> Rect {
419        Offset::ZERO & (self.size(app) * self.configuration(app).device_pixel_ratio)
420    }
421}
422
423/// The style the two sampled points make between them, and `None` where the tree annotates
424/// neither: nothing was said about the overlays, so nothing is said to the host.
425///
426/// When both are annotated the upper provides the status bar properties and the lower
427/// provides the system navigation bar properties. This is for the case where a widget at
428/// the top, an app bar say, annotates the status bar's style while another at the bottom
429/// annotates the navigation bar's. When only one of them is, it provides every property,
430/// which lets one annotated region set both.
431fn merged_overlay_style(
432    upper: Option<Rc<SystemUiOverlayStyle>>,
433    lower: Option<Rc<SystemUiOverlayStyle>>,
434    is_android: bool,
435) -> Option<SystemUiOverlayStyle> {
436    if let (Some(upper), Some(lower)) = (&upper, &lower) {
437        return Some(SystemUiOverlayStyle {
438            status_bar_brightness: upper.status_bar_brightness,
439            status_bar_icon_brightness: upper.status_bar_icon_brightness,
440            status_bar_color: upper.status_bar_color,
441            system_status_bar_contrast_enforced: upper.system_status_bar_contrast_enforced,
442            system_navigation_bar_color: lower.system_navigation_bar_color,
443            system_navigation_bar_divider_color: lower.system_navigation_bar_divider_color,
444            system_navigation_bar_icon_brightness: lower.system_navigation_bar_icon_brightness,
445            system_navigation_bar_contrast_enforced: lower.system_navigation_bar_contrast_enforced,
446        });
447    }
448    let defined = upper.or(lower)?;
449    if !is_android {
450        // Only Android has a system navigation bar to style.
451        return Some(SystemUiOverlayStyle {
452            status_bar_brightness: defined.status_bar_brightness,
453            status_bar_icon_brightness: defined.status_bar_icon_brightness,
454            status_bar_color: defined.status_bar_color,
455            system_status_bar_contrast_enforced: defined.system_status_bar_contrast_enforced,
456            ..SystemUiOverlayStyle::new()
457        });
458    }
459    Some(*defined)
460}
461
462impl RenderObject for RenderView {
463    fn render_object_data(self: RenderHandle<Self>, app: &App) -> &RenderObjectData {
464        &self.get(app).render_object
465    }
466
467    fn render_object_data_mut(self: RenderHandle<Self>, app: &mut App) -> &mut RenderObjectData {
468        &mut self.get_mut(app).render_object
469    }
470
471    fn perform_resize(self: RenderHandle<Self>, _app: &mut App) {
472        panic!("RenderView is never sized by its parent");
473    }
474
475    fn perform_layout(self: RenderHandle<Self>, app: &mut App) {
476        debug_assert!(self.get(app).root_transform.is_some());
477        let constraints = self.constraints(app);
478        let sized_by_child = !constraints.is_tight();
479        let child = self.child(app);
480        if let Some(child) = child {
481            child.layout(app, constraints, sized_by_child);
482        }
483        let size = match child {
484            Some(child) if sized_by_child => child.size(app),
485            _ => constraints.smallest(),
486        };
487        self.get_mut(app).size = size;
488        debug_assert!(size.is_finite());
489        debug_assert!(constraints.is_satisfied_by(size));
490    }
491
492    fn visit_children(
493        self: RenderHandle<Self>,
494        app: &App,
495        visitor: &mut dyn FnMut(AnyRenderObject),
496    ) {
497        if let Some(child) = self.child(app) {
498            visitor(child.as_object());
499        }
500    }
501
502    fn apply_paint_transform(
503        self: RenderHandle<Self>,
504        app: &App,
505        child: AnyRenderObject,
506        transform: &mut Matrix4,
507    ) {
508        let root_transform = self
509            .get(app)
510            .root_transform
511            .as_ref()
512            .expect("the view has a configuration");
513        crate::object::multiply(transform, root_transform);
514        debug_assert!(child.parent(app).map(AnyRenderObject::id) == Some(self.id()));
515    }
516
517    fn is_repaint_boundary(self: RenderHandle<Self>, _app: &App) -> bool {
518        true
519    }
520
521    fn paint(
522        self: RenderHandle<Self>,
523        app: &mut App,
524        context: &mut PaintingContext,
525        offset: Offset,
526    ) {
527        if let Some(child) = self.child(app) {
528            context.paint_child(app, child.as_object(), offset);
529        }
530    }
531}
532
533/// Flutter's `RenderObject.handleEvent` default: the view itself does nothing with events.
534impl HitTestTarget for RenderHandle<RenderView> {
535    fn handle_event(&self, _app: &mut App, _event: &PointerEvent, _entry: &HitTestEntry) {}
536}
537
538/// The view is its own protocol: not a box, one object, so its vtable is a plain constant.
539static VTABLE: RenderObjectVTable = RenderObjectVTable::of::<RenderView>(
540    |app, id, child| <RenderView as RenderObject>::setup_parent_data(resolve(id), app, child),
541    |app, id| RenderView::paint_bounds(resolve(id), app),
542    |app, id, child, transform| {
543        <RenderView as RenderObject>::apply_paint_transform(resolve(id), app, child, transform)
544    },
545    |app, id| <RenderView as RenderObject>::perform_resize(resolve(id), app),
546    |app, id| crate::object::RenderObjectBase::mark_needs_layout(resolve::<RenderView>(id), app),
547    None,
548    None,
549);
550
551#[cfg(test)]
552mod tests {
553    use std::cell::Cell;
554    use std::rc::Rc;
555    use waft_foundation::AppCell;
556
557    use waft_embedder::{ViewId, ViewMetrics};
558
559    use super::*;
560    use crate::box_::RenderBox;
561    use crate::layer::TransformLayer;
562    use crate::pipeline_owner::PipelineOwner;
563    use crate::proxy_box::RenderConstrainedBox;
564    use crate::shifted_box::RenderPadding;
565    use waft_embedder::ViewHost;
566    use waft_painting::EdgeInsetsGeometry;
567    use waft_test::TestViewHost;
568
569    struct TestView {
570        metrics: ViewMetrics,
571        presented: Rc<Cell<u32>>,
572        host: TestViewHost,
573    }
574
575    impl View for TestView {
576        fn id(&self) -> ViewId {
577            ViewId(0)
578        }
579
580        fn metrics(&self) -> ViewMetrics {
581            self.metrics
582        }
583
584        fn present(&self, _scene: std::sync::Arc<waft_embedder::Scene>) {
585            self.presented.set(self.presented.get() + 1);
586        }
587
588        fn host(&self) -> &dyn ViewHost {
589            &self.host
590        }
591    }
592
593    fn test_view(presented: &Rc<Cell<u32>>) -> ViewRef {
594        Rc::new(TestView {
595            metrics: ViewMetrics::default(),
596            presented: Rc::clone(presented),
597            host: TestViewHost::default(),
598        })
599    }
600
601    /// `view_test.dart`'s `createViewConfiguration`.
602    fn create_view_configuration(size: Size, device_pixel_ratio: f64) -> ViewConfiguration {
603        let constraints = BoxConstraints::tight(size);
604        ViewConfiguration::new(
605            constraints * device_pixel_ratio,
606            constraints,
607            device_pixel_ratio,
608        )
609    }
610
611    /// `view_test.dart`: `ViewConfiguration == and hashCode`.
612    #[test]
613    fn view_configuration_equality() {
614        let a = create_view_configuration(Size::new(800.0, 600.0), 1.0);
615        let b = create_view_configuration(Size::new(800.0, 600.0), 1.0);
616        let c = create_view_configuration(Size::new(800.0, 600.0), 3.0);
617        assert_eq!(a, b);
618        assert_ne!(a, c);
619    }
620
621    /// `view_test.dart`: `Constraints are derived from configuration`.
622    #[test]
623    fn constraints_are_derived_from_configuration() {
624        let cell = AppCell::new();
625        let mut app = cell.borrow_mut();
626        let presented = Rc::new(Cell::new(0));
627        let view = RenderView::new(&mut app, None, None, test_view(&presented));
628        assert!(!view.has_configuration(&app));
629        let constraints = BoxConstraints::new()
630            .min_width(1.0)
631            .max_width(2.0)
632            .min_height(3.0)
633            .max_height(4.0);
634        view.set_configuration(
635            &mut app,
636            ViewConfiguration::new(constraints * 3.0, constraints, 3.0),
637        );
638        assert_eq!(view.constraints(&app), constraints);
639    }
640
641    /// `view_test.dart`: `Config can be set and changed after instantiation without calling
642    /// prepareInitialFrame first`.
643    #[test]
644    fn configuration_can_change_before_prepare_initial_frame() {
645        let cell = AppCell::new();
646        let mut app = cell.borrow_mut();
647        let presented = Rc::new(Cell::new(0));
648        let view = RenderView::new(&mut app, None, None, test_view(&presented));
649        view.set_configuration(
650            &mut app,
651            create_view_configuration(Size::new(100.0, 200.0), 3.0),
652        );
653        view.set_configuration(
654            &mut app,
655            create_view_configuration(Size::new(200.0, 300.0), 2.0),
656        );
657        let owner = PipelineOwner::new(&mut app, None, None);
658        owner.set_root_node(&mut app, Some(view.as_object()));
659        view.prepare_initial_frame(&mut app);
660    }
661
662    /// `view_test.dart`: `does not replace the root layer unnecessarily` (and when the view
663    /// resizes). Ours observes the replacement through the paint mark.
664    #[test]
665    fn does_not_replace_the_root_layer_unnecessarily() {
666        let cell = AppCell::new();
667        let mut app = cell.borrow_mut();
668        let presented = Rc::new(Cell::new(0));
669        let view = RenderView::new(
670            &mut app,
671            None,
672            Some(create_view_configuration(Size::new(100.0, 100.0), 1.0)),
673            test_view(&presented),
674        );
675        let owner = PipelineOwner::new(&mut app, None, None);
676        owner.set_root_node(&mut app, Some(view.as_object()));
677        view.prepare_initial_frame(&mut app);
678        owner.flush_layout(&mut app);
679        owner.flush_compositing_bits(&mut app);
680        owner.flush_paint(&mut app);
681        assert!(!view.as_object().debug_needs_paint(&app));
682
683        view.set_configuration(
684            &mut app,
685            create_view_configuration(Size::new(100.0, 1117.0), 1.0),
686        );
687        assert!(
688            !view.as_object().debug_needs_paint(&app),
689            "a resize keeps the root layer"
690        );
691
692        view.set_configuration(
693            &mut app,
694            create_view_configuration(Size::new(100.0, 1117.0), 5.0),
695        );
696        assert!(
697            view.as_object().debug_needs_paint(&app),
698            "a new ratio replaces it"
699        );
700        let layer = view.as_object().debug_layer(&app).expect("root layer");
701        let transform = app
702            .handle::<TransformLayer>(layer.id())
703            .expect("the root is a TransformLayer");
704        assert_eq!(transform.transform(&app), Some(Matrix4::scale(5.0, 5.0)));
705    }
706
707    /// `view_test.dart`: `accounts for device pixel ratio in paintBounds`, plus one frame
708    /// composited to the host.
709    #[test]
710    fn accounts_for_device_pixel_ratio_in_paint_bounds_and_presents() {
711        let cell = AppCell::new();
712        let mut app = cell.borrow_mut();
713        let presented = Rc::new(Cell::new(0));
714        let child =
715            RenderConstrainedBox::new(&mut app, BoxConstraints::tight(Size::new(10.0, 10.0)), None);
716        let view = RenderView::new(
717            &mut app,
718            Some(child.as_box()),
719            Some(create_view_configuration(Size::new(800.0, 600.0), 2.0)),
720            test_view(&presented),
721        );
722        let owner = PipelineOwner::new(&mut app, None, None);
723        owner.set_root_node(&mut app, Some(view.as_object()));
724        view.prepare_initial_frame(&mut app);
725        owner.flush_layout(&mut app);
726        owner.flush_compositing_bits(&mut app);
727        owner.flush_paint(&mut app);
728        view.composite_frame(&mut app);
729
730        assert_eq!(view.size(&app), Size::new(800.0, 600.0));
731        assert_eq!(
732            view.paint_bounds(&app),
733            Offset::ZERO & Size::new(1600.0, 1200.0)
734        );
735        assert_eq!(presented.get(), 1);
736    }
737
738    #[test]
739    fn coordinates_convert_through_the_paint_transforms_below_the_view() {
740        let cell = AppCell::new();
741        let mut app = cell.borrow_mut();
742        let presented = Rc::new(Cell::new(0));
743        let child =
744            RenderConstrainedBox::new(&mut app, BoxConstraints::tight(Size::new(30.0, 40.0)), None);
745        let padding = RenderPadding::new(
746            &mut app,
747            EdgeInsetsGeometry::from_ltrb(10.0, 20.0, 0.0, 0.0),
748            None,
749            Some(child.as_box()),
750        );
751        let view = RenderView::new(
752            &mut app,
753            Some(padding.as_box()),
754            Some(create_view_configuration(Size::new(800.0, 600.0), 2.0)),
755            test_view(&presented),
756        );
757        let owner = PipelineOwner::new(&mut app, None, None);
758        owner.set_root_node(&mut app, Some(view.as_object()));
759        view.prepare_initial_frame(&mut app);
760        owner.flush_layout(&mut app);
761
762        // The root view's own transform (logical to physical) is left out, as in Dart.
763        let child = child.as_box();
764        assert_eq!(
765            child.local_to_global(&app, Offset::ZERO, None),
766            Offset::new(10.0, 20.0)
767        );
768        assert_eq!(
769            child.global_to_local(&app, Offset::new(15.0, 25.0), None),
770            Offset::new(5.0, 5.0)
771        );
772        assert_eq!(
773            child.local_to_global(&app, Offset::new(1.0, 1.0), Some(padding.as_object())),
774            Offset::new(11.0, 21.0)
775        );
776        assert_eq!(
777            padding.as_box().global_to_local(
778                &app,
779                Offset::new(10.0, 20.0),
780                Some(child.as_object())
781            ),
782            Offset::new(20.0, 40.0)
783        );
784        assert!(
785            child
786                .as_object()
787                .paint_bounds(&app)
788                .inflate(70.0)
789                .contains(child.global_to_local(&app, Offset::new(100.0, 100.0), None))
790        );
791    }
792
793    #[test]
794    fn a_proxy_box_adds_no_paint_transform() {
795        let cell = AppCell::new();
796        let mut app = cell.borrow_mut();
797        let presented = Rc::new(Cell::new(0));
798        let child =
799            RenderConstrainedBox::new(&mut app, BoxConstraints::tight(Size::new(30.0, 40.0)), None);
800        let proxy =
801            RenderConstrainedBox::new(&mut app, BoxConstraints::new(), Some(child.as_box()));
802        let padding = RenderPadding::new(
803            &mut app,
804            EdgeInsetsGeometry::from_ltrb(10.0, 20.0, 0.0, 0.0),
805            None,
806            Some(proxy.as_box()),
807        );
808        let view = RenderView::new(
809            &mut app,
810            Some(padding.as_box()),
811            Some(create_view_configuration(Size::new(800.0, 600.0), 2.0)),
812            test_view(&presented),
813        );
814        let owner = PipelineOwner::new(&mut app, None, None);
815        owner.set_root_node(&mut app, Some(view.as_object()));
816        view.prepare_initial_frame(&mut app);
817        owner.flush_layout(&mut app);
818
819        assert_eq!(
820            child.as_box().local_to_global(&app, Offset::ZERO, None),
821            Offset::new(10.0, 20.0)
822        );
823        assert_eq!(
824            child
825                .as_box()
826                .global_to_local(&app, Offset::new(15.0, 25.0), None),
827            Offset::new(5.0, 5.0)
828        );
829    }
830}