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