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        self.get(app).view.present(std::sync::Arc::new(scene));
363        self.get_mut(app).needs_composite_frame = false;
364    }
365
366    /// Styles the system overlays from whatever the layer tree annotates beneath them.
367    ///
368    /// Takes the overlay style from the place where a system status bar and system
369    /// navigation bar are placed to update system style overlay. The center of the system
370    /// navigation bar and the center of the status bar are used to get
371    /// `SystemUiOverlayStyle`'s to update system overlay appearance.
372    ///
373    /// ```text
374    ///         Horizontal center of the screen
375    ///                 V
376    ///    ++++++++++++++++++++++++++
377    ///    |                        |
378    ///    |    System status bar   |  <- Vertical center of the status bar
379    ///    |                        |
380    ///    ++++++++++++++++++++++++++
381    ///    |                        |
382    ///    |        Content         |
383    ///    ~                        ~
384    ///    |                        |
385    ///    ++++++++++++++++++++++++++
386    ///    |                        |
387    ///    |  System navigation bar | <- Vertical center of the navigation bar
388    ///    |                        |
389    ///    ++++++++++++++++++++++++++ <- bounds.bottom
390    /// ```
391    fn update_system_chrome(self: RenderHandle<Self>, app: &mut App) {
392        let Some(layer) = self.as_object().layer(app) else {
393            return;
394        };
395        let bounds = self.paint_bounds(app);
396        let padding = self.get(app).view.metrics().padding;
397        // Center of the status bar
398        let top = Offset::new(
399            // Horizontal center of the screen
400            bounds.center().dx(),
401            // The vertical center of the system status bar. The system status bar height
402            // is kept as top window padding.
403            padding.top / 2.0,
404        );
405        // Center of the navigation bar
406        let bottom = Offset::new(
407            // Horizontal center of the screen
408            bounds.center().dx(),
409            // Vertical center of the system navigation bar. The system navigation bar
410            // height is kept as bottom window padding. The "1" needs to be subtracted from
411            // the bottom because available pixels are in (0..bottom) range. I.e. for a
412            // device with 1920 height, bound.bottom is 1920, but the most bottom drawn
413            // pixel is at 1919 position.
414            bounds.bottom - 1.0 - padding.bottom / 2.0,
415        );
416        let layer = layer.as_layer();
417        let upper = layer.find::<SystemUiOverlayStyle>(app, top);
418        // Only Android has a customizable system navigation bar.
419        let is_android = app.platform().target_platform() == TargetPlatform::Android;
420        let lower = is_android
421            .then(|| layer.find::<SystemUiOverlayStyle>(app, bottom))
422            .flatten();
423        // If there are no overlay style in the UI don't bother updating.
424        let Some(style) = merged_overlay_style(upper, lower, is_android) else {
425            return;
426        };
427        let view = self.get(app).view.id();
428        SystemChrome::set_system_ui_overlay_style(app, view, &style);
429    }
430
431    /// An estimate of the bounds within which this render object will paint, in physical
432    /// pixels.
433    pub fn paint_bounds(self: RenderHandle<Self>, app: &App) -> Rect {
434        Offset::ZERO & (self.size(app) * self.configuration(app).device_pixel_ratio)
435    }
436}
437
438/// The style the two sampled points make between them, and `None` where the tree annotates
439/// neither: nothing was said about the overlays, so nothing is said to the host.
440///
441/// When both are annotated the upper provides the status bar properties and the lower
442/// provides the system navigation bar properties. This is for the case where a widget at
443/// the top, an app bar say, annotates the status bar's style while another at the bottom
444/// annotates the navigation bar's. When only one of them is, it provides every property,
445/// which lets one annotated region set both.
446fn merged_overlay_style(
447    upper: Option<Rc<SystemUiOverlayStyle>>,
448    lower: Option<Rc<SystemUiOverlayStyle>>,
449    is_android: bool,
450) -> Option<SystemUiOverlayStyle> {
451    if let (Some(upper), Some(lower)) = (&upper, &lower) {
452        return Some(SystemUiOverlayStyle {
453            status_bar_brightness: upper.status_bar_brightness,
454            status_bar_icon_brightness: upper.status_bar_icon_brightness,
455            status_bar_color: upper.status_bar_color,
456            system_status_bar_contrast_enforced: upper.system_status_bar_contrast_enforced,
457            system_navigation_bar_color: lower.system_navigation_bar_color,
458            system_navigation_bar_divider_color: lower.system_navigation_bar_divider_color,
459            system_navigation_bar_icon_brightness: lower.system_navigation_bar_icon_brightness,
460            system_navigation_bar_contrast_enforced: lower.system_navigation_bar_contrast_enforced,
461        });
462    }
463    let defined = upper.or(lower)?;
464    if !is_android {
465        // Only Android has a system navigation bar to style.
466        return Some(SystemUiOverlayStyle {
467            status_bar_brightness: defined.status_bar_brightness,
468            status_bar_icon_brightness: defined.status_bar_icon_brightness,
469            status_bar_color: defined.status_bar_color,
470            system_status_bar_contrast_enforced: defined.system_status_bar_contrast_enforced,
471            ..SystemUiOverlayStyle::new()
472        });
473    }
474    Some(*defined)
475}
476
477impl RenderObject for RenderView {
478    fn render_object_data(self: RenderHandle<Self>, app: &App) -> &RenderObjectData {
479        &self.get(app).render_object
480    }
481
482    /// Dart's override leaves out `super.debugFillProperties`: "the root superclasses don't
483    /// include any interesting information for this class".
484    fn debug_fill_base_properties(
485        self: RenderHandle<Self>,
486        _app: &App,
487        _properties: &mut DiagnosticPropertiesBuilder,
488    ) {
489        let _ = self;
490    }
491
492    fn debug_fill_properties(
493        self: RenderHandle<Self>,
494        app: &App,
495        properties: &mut DiagnosticPropertiesBuilder,
496    ) {
497        if cfg!(debug_assertions) {
498            let system = match std::env::consts::OS {
499                "" => "Web",
500                system => system,
501            };
502            properties.add(message(format!("debug mode enabled - {system}")));
503        }
504        let metrics = self.get(app).view.metrics();
505        let [width, height] = metrics.physical_size;
506        properties.add(
507            DiagnosticsProperty::new("view size", Size::new(width, height))
508                .tooltip("in physical pixels"),
509        );
510        properties.add(
511            DoubleProperty::new("device pixel ratio", metrics.device_pixel_ratio)
512                .tooltip("physical pixels per logical pixel"),
513        );
514        properties.add(
515            DiagnosticsProperty::<ViewConfiguration>::new(
516                "configuration",
517                self.get(app).configuration,
518            )
519            .tooltip("in logical pixels"),
520        );
521    }
522
523    fn render_object_data_mut(self: RenderHandle<Self>, app: &mut App) -> &mut RenderObjectData {
524        &mut self.get_mut(app).render_object
525    }
526
527    fn perform_resize(self: RenderHandle<Self>, _app: &mut App) {
528        panic!("RenderView is never sized by its parent");
529    }
530
531    fn perform_layout(self: RenderHandle<Self>, app: &mut App) {
532        debug_assert!(self.get(app).root_transform.is_some());
533        let constraints = self.constraints(app);
534        let sized_by_child = !constraints.is_tight();
535        let child = self.child(app);
536        if let Some(child) = child {
537            child.layout(app, constraints, sized_by_child);
538        }
539        let size = match child {
540            Some(child) if sized_by_child => child.size(app),
541            _ => constraints.smallest(),
542        };
543        self.get_mut(app).size = size;
544        debug_assert!(size.is_finite());
545        debug_assert!(constraints.is_satisfied_by(size));
546    }
547
548    fn visit_children(
549        self: RenderHandle<Self>,
550        app: &App,
551        visitor: &mut dyn FnMut(AnyRenderObject),
552    ) {
553        if let Some(child) = self.child(app) {
554            visitor(child.as_object());
555        }
556    }
557
558    fn apply_paint_transform(
559        self: RenderHandle<Self>,
560        app: &App,
561        child: AnyRenderObject,
562        transform: &mut Matrix4,
563    ) {
564        let root_transform = self
565            .get(app)
566            .root_transform
567            .as_ref()
568            .expect("the view has a configuration");
569        crate::object::multiply(transform, root_transform);
570        debug_assert!(child.parent(app).map(AnyRenderObject::id) == Some(self.id()));
571    }
572
573    fn is_repaint_boundary(self: RenderHandle<Self>, _app: &App) -> bool {
574        true
575    }
576
577    fn paint(
578        self: RenderHandle<Self>,
579        app: &mut App,
580        context: &mut PaintingContext,
581        offset: Offset,
582    ) {
583        if let Some(child) = self.child(app) {
584            context.paint_child(app, child.as_object(), offset);
585        }
586    }
587}
588
589/// Flutter's `RenderObject.handleEvent` default: the view itself does nothing with events.
590impl HitTestTarget for RenderHandle<RenderView> {
591    fn handle_event(&self, _app: &mut App, _event: &PointerEvent, _entry: &HitTestEntry) {}
592}
593
594/// The view is its own protocol: not a box, one object, so its vtable is a plain constant.
595static VTABLE: RenderObjectVTable = RenderObjectVTable::of::<RenderView>(
596    |app, id, child| <RenderView as RenderObject>::setup_parent_data(resolve(id), app, child),
597    |app, id| RenderView::paint_bounds(resolve(id), app),
598    |app, id, child, transform| {
599        <RenderView as RenderObject>::apply_paint_transform(resolve(id), app, child, transform)
600    },
601    |app, id| <RenderView as RenderObject>::perform_resize(resolve(id), app),
602    |app, id| crate::object::RenderObjectBase::mark_needs_layout(resolve::<RenderView>(id), app),
603    None,
604    None,
605);
606
607#[cfg(test)]
608mod tests {
609    use std::cell::Cell;
610    use std::rc::Rc;
611    use waft_foundation::AppCell;
612
613    use waft_embedder::{ViewId, ViewMetrics};
614
615    use super::*;
616    use crate::box_::RenderBox;
617    use crate::layer::TransformLayer;
618    use crate::pipeline_owner::PipelineOwner;
619    use crate::proxy_box::RenderConstrainedBox;
620    use crate::shifted_box::RenderPadding;
621    use waft_embedder::ViewHost;
622    use waft_painting::EdgeInsetsGeometry;
623    use waft_test::TestViewHost;
624
625    struct TestView {
626        metrics: ViewMetrics,
627        presented: Rc<Cell<u32>>,
628        host: TestViewHost,
629    }
630
631    impl View for TestView {
632        fn id(&self) -> ViewId {
633            ViewId(0)
634        }
635
636        fn metrics(&self) -> ViewMetrics {
637            self.metrics
638        }
639
640        fn present(&self, _scene: std::sync::Arc<waft_embedder::Scene>) {
641            self.presented.set(self.presented.get() + 1);
642        }
643
644        fn host(&self) -> &dyn ViewHost {
645            &self.host
646        }
647    }
648
649    fn test_view(presented: &Rc<Cell<u32>>) -> ViewRef {
650        Rc::new(TestView {
651            metrics: ViewMetrics::default(),
652            presented: Rc::clone(presented),
653            host: TestViewHost::default(),
654        })
655    }
656
657    /// `view_test.dart`'s `createViewConfiguration`.
658    fn create_view_configuration(size: Size, device_pixel_ratio: f64) -> ViewConfiguration {
659        let constraints = BoxConstraints::tight(size);
660        ViewConfiguration::new(
661            constraints * device_pixel_ratio,
662            constraints,
663            device_pixel_ratio,
664        )
665    }
666
667    /// `view_test.dart`: `ViewConfiguration == and hashCode`.
668    #[test]
669    fn view_configuration_equality() {
670        let a = create_view_configuration(Size::new(800.0, 600.0), 1.0);
671        let b = create_view_configuration(Size::new(800.0, 600.0), 1.0);
672        let c = create_view_configuration(Size::new(800.0, 600.0), 3.0);
673        assert_eq!(a, b);
674        assert_ne!(a, c);
675    }
676
677    /// `view_test.dart`: `Constraints are derived from configuration`.
678    #[test]
679    fn constraints_are_derived_from_configuration() {
680        let cell = AppCell::new();
681        let mut app = cell.borrow_mut();
682        let presented = Rc::new(Cell::new(0));
683        let view = RenderView::new(&mut app, None, None, test_view(&presented));
684        assert!(!view.has_configuration(&app));
685        let constraints = BoxConstraints::new()
686            .min_width(1.0)
687            .max_width(2.0)
688            .min_height(3.0)
689            .max_height(4.0);
690        view.set_configuration(
691            &mut app,
692            ViewConfiguration::new(constraints * 3.0, constraints, 3.0),
693        );
694        assert_eq!(view.constraints(&app), constraints);
695    }
696
697    /// `view_test.dart`: `Config can be set and changed after instantiation without calling
698    /// prepareInitialFrame first`.
699    #[test]
700    fn configuration_can_change_before_prepare_initial_frame() {
701        let cell = AppCell::new();
702        let mut app = cell.borrow_mut();
703        let presented = Rc::new(Cell::new(0));
704        let view = RenderView::new(&mut app, None, None, test_view(&presented));
705        view.set_configuration(
706            &mut app,
707            create_view_configuration(Size::new(100.0, 200.0), 3.0),
708        );
709        view.set_configuration(
710            &mut app,
711            create_view_configuration(Size::new(200.0, 300.0), 2.0),
712        );
713        let owner = PipelineOwner::new(&mut app, None, None);
714        owner.set_root_node(&mut app, Some(view.as_object()));
715        view.prepare_initial_frame(&mut app);
716    }
717
718    /// `view_test.dart`: `does not replace the root layer unnecessarily` (and when the view
719    /// resizes). Ours observes the replacement through the paint mark.
720    #[test]
721    fn does_not_replace_the_root_layer_unnecessarily() {
722        let cell = AppCell::new();
723        let mut app = cell.borrow_mut();
724        let presented = Rc::new(Cell::new(0));
725        let view = RenderView::new(
726            &mut app,
727            None,
728            Some(create_view_configuration(Size::new(100.0, 100.0), 1.0)),
729            test_view(&presented),
730        );
731        let owner = PipelineOwner::new(&mut app, None, None);
732        owner.set_root_node(&mut app, Some(view.as_object()));
733        view.prepare_initial_frame(&mut app);
734        owner.flush_layout(&mut app);
735        owner.flush_compositing_bits(&mut app);
736        owner.flush_paint(&mut app);
737        assert!(!view.as_object().debug_needs_paint(&app));
738
739        view.set_configuration(
740            &mut app,
741            create_view_configuration(Size::new(100.0, 1117.0), 1.0),
742        );
743        assert!(
744            !view.as_object().debug_needs_paint(&app),
745            "a resize keeps the root layer"
746        );
747
748        view.set_configuration(
749            &mut app,
750            create_view_configuration(Size::new(100.0, 1117.0), 5.0),
751        );
752        assert!(
753            view.as_object().debug_needs_paint(&app),
754            "a new ratio replaces it"
755        );
756        let layer = view.as_object().debug_layer(&app).expect("root layer");
757        let transform = app
758            .handle::<TransformLayer>(layer.id())
759            .expect("the root is a TransformLayer");
760        assert_eq!(transform.transform(&app), Some(Matrix4::scale(5.0, 5.0)));
761    }
762
763    /// `view_test.dart`: `accounts for device pixel ratio in paintBounds`, plus one frame
764    /// composited to the host.
765    #[test]
766    fn accounts_for_device_pixel_ratio_in_paint_bounds_and_presents() {
767        let cell = AppCell::new();
768        let mut app = cell.borrow_mut();
769        let presented = Rc::new(Cell::new(0));
770        let child =
771            RenderConstrainedBox::new(&mut app, BoxConstraints::tight(Size::new(10.0, 10.0)), None);
772        let view = RenderView::new(
773            &mut app,
774            Some(child.as_box()),
775            Some(create_view_configuration(Size::new(800.0, 600.0), 2.0)),
776            test_view(&presented),
777        );
778        let owner = PipelineOwner::new(&mut app, None, None);
779        owner.set_root_node(&mut app, Some(view.as_object()));
780        view.prepare_initial_frame(&mut app);
781        owner.flush_layout(&mut app);
782        owner.flush_compositing_bits(&mut app);
783        owner.flush_paint(&mut app);
784        view.composite_frame(&mut app);
785
786        assert_eq!(view.size(&app), Size::new(800.0, 600.0));
787        assert_eq!(
788            view.paint_bounds(&app),
789            Offset::ZERO & Size::new(1600.0, 1200.0)
790        );
791        assert_eq!(presented.get(), 1);
792    }
793
794    #[test]
795    fn coordinates_convert_through_the_paint_transforms_below_the_view() {
796        let cell = AppCell::new();
797        let mut app = cell.borrow_mut();
798        let presented = Rc::new(Cell::new(0));
799        let child =
800            RenderConstrainedBox::new(&mut app, BoxConstraints::tight(Size::new(30.0, 40.0)), None);
801        let padding = RenderPadding::new(
802            &mut app,
803            EdgeInsetsGeometry::from_ltrb(10.0, 20.0, 0.0, 0.0),
804            None,
805            Some(child.as_box()),
806        );
807        let view = RenderView::new(
808            &mut app,
809            Some(padding.as_box()),
810            Some(create_view_configuration(Size::new(800.0, 600.0), 2.0)),
811            test_view(&presented),
812        );
813        let owner = PipelineOwner::new(&mut app, None, None);
814        owner.set_root_node(&mut app, Some(view.as_object()));
815        view.prepare_initial_frame(&mut app);
816        owner.flush_layout(&mut app);
817
818        // The root view's own transform (logical to physical) is left out, as in Dart.
819        let child = child.as_box();
820        assert_eq!(
821            child.local_to_global(&app, Offset::ZERO, None),
822            Offset::new(10.0, 20.0)
823        );
824        assert_eq!(
825            child.global_to_local(&app, Offset::new(15.0, 25.0), None),
826            Offset::new(5.0, 5.0)
827        );
828        assert_eq!(
829            child.local_to_global(&app, Offset::new(1.0, 1.0), Some(padding.as_object())),
830            Offset::new(11.0, 21.0)
831        );
832        assert_eq!(
833            padding.as_box().global_to_local(
834                &app,
835                Offset::new(10.0, 20.0),
836                Some(child.as_object())
837            ),
838            Offset::new(20.0, 40.0)
839        );
840        assert!(
841            child
842                .as_object()
843                .paint_bounds(&app)
844                .inflate(70.0)
845                .contains(child.global_to_local(&app, Offset::new(100.0, 100.0), None))
846        );
847    }
848
849    #[test]
850    fn a_proxy_box_adds_no_paint_transform() {
851        let cell = AppCell::new();
852        let mut app = cell.borrow_mut();
853        let presented = Rc::new(Cell::new(0));
854        let child =
855            RenderConstrainedBox::new(&mut app, BoxConstraints::tight(Size::new(30.0, 40.0)), None);
856        let proxy =
857            RenderConstrainedBox::new(&mut app, BoxConstraints::new(), Some(child.as_box()));
858        let padding = RenderPadding::new(
859            &mut app,
860            EdgeInsetsGeometry::from_ltrb(10.0, 20.0, 0.0, 0.0),
861            None,
862            Some(proxy.as_box()),
863        );
864        let view = RenderView::new(
865            &mut app,
866            Some(padding.as_box()),
867            Some(create_view_configuration(Size::new(800.0, 600.0), 2.0)),
868            test_view(&presented),
869        );
870        let owner = PipelineOwner::new(&mut app, None, None);
871        owner.set_root_node(&mut app, Some(view.as_object()));
872        view.prepare_initial_frame(&mut app);
873        owner.flush_layout(&mut app);
874
875        assert_eq!(
876            child.as_box().local_to_global(&app, Offset::ZERO, None),
877            Offset::new(10.0, 20.0)
878        );
879        assert_eq!(
880            child
881                .as_box()
882                .global_to_local(&app, Offset::new(15.0, 25.0), None),
883            Offset::new(5.0, 5.0)
884        );
885    }
886}