inset-rendering 0.16.0

Render-object tree and layout for Inset
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
//! Flutter counterpart: `rendering/view.dart` (`ViewConfiguration`, `RenderView`).
//!
//! `applyPaintTransform` and semantics wait.

use std::rc::Rc;

use inset_embedder::{
    Matrix4, Offset, Rect, SceneBuilder, Size, SystemUiOverlayStyle, TargetPlatform, View, ViewRef,
};
use inset_foundation::{App, Handle};
use inset_gestures::{HitTestEntry, HitTestResult, HitTestTarget, PointerEvent};
use inset_services::SystemChrome;

use crate::box_::{AnyRenderBox, BoxConstraints, BoxHitTestResult};
use crate::layer::{ContainerLayer, ErasedLayer, OffsetLayerMixin, TransformLayer};
use crate::object::{
    AnyRenderObject, Constraints, RenderHandle, RenderObject, RenderObjectData, RenderObjectVTable,
    resolve,
};
use crate::painting_context::PaintingContext;

/// The layout constraints for the root render object.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct ViewConfiguration {
    /// The constraints of the output surface in logical pixels.
    pub logical_constraints: BoxConstraints,
    /// The constraints of the output surface in physical pixels.
    pub physical_constraints: BoxConstraints,
    /// The pixel density of the output surface.
    pub device_pixel_ratio: f64,
}

impl ViewConfiguration {
    /// Creates a view configuration.
    ///
    /// By default, the view has zero constraints and a pixel ratio of 1.0.
    pub const fn new(
        physical_constraints: BoxConstraints,
        logical_constraints: BoxConstraints,
        device_pixel_ratio: f64,
    ) -> ViewConfiguration {
        ViewConfiguration {
            logical_constraints,
            physical_constraints,
            device_pixel_ratio,
        }
    }

    /// Creates a view configuration that matches `view`.
    pub fn from_view(view: &dyn View) -> ViewConfiguration {
        let metrics = view.metrics();
        let physical_constraints =
            BoxConstraints::from_view_constraints(metrics.physical_constraints);
        let device_pixel_ratio = metrics.device_pixel_ratio;
        ViewConfiguration {
            logical_constraints: physical_constraints / device_pixel_ratio,
            physical_constraints,
            device_pixel_ratio,
        }
    }

    /// Creates a transformation matrix that applies the
    /// [`device_pixel_ratio`](Self::device_pixel_ratio).
    pub fn to_matrix(&self) -> Matrix4 {
        Matrix4::scale(
            self.device_pixel_ratio as f32,
            self.device_pixel_ratio as f32,
        )
    }

    /// Returns whether [`to_matrix`](Self::to_matrix) would return a different value for
    /// this configuration than it would for the given `old_configuration`.
    pub fn should_update_matrix(&self, old_configuration: &ViewConfiguration) -> bool {
        old_configuration.device_pixel_ratio != self.device_pixel_ratio
    }

    /// Transforms the provided `logical_size` to physical pixels.
    pub fn to_physical_size(&self, logical_size: Size) -> Size {
        self.physical_constraints
            .constrain(logical_size * self.device_pixel_ratio)
    }
}

impl Default for ViewConfiguration {
    fn default() -> ViewConfiguration {
        ViewConfiguration::new(
            BoxConstraints::new().max_width(0.0).max_height(0.0),
            BoxConstraints::new().max_width(0.0).max_height(0.0),
            1.0,
        )
    }
}

/// The root of the render tree.
///
/// The view represents the total output surface of the render tree and handles
/// bootstrapping the rendering pipeline. The view has a unique child
/// [`crate::RenderBox`], which is required to fill the entire output surface.
///
/// Not a box: its constraints come from its [`configuration`](Self::configuration), and its
/// child is the one slot Flutter's `RenderObjectWithChildMixin` gives it.
pub struct RenderView {
    render_object: RenderObjectData,
    child: Option<AnyRenderBox>,
    size: Size,
    configuration: Option<ViewConfiguration>,
    view: ViewRef,
    root_transform: Option<Matrix4>,
    needs_composite_frame: bool,
    /// Whether the system overlays are styled from the layer tree at every frame.
    ///
    /// An application that would rather drive them itself, through
    /// [`SystemChrome::set_system_ui_overlay_style`], turns this off so its own style is
    /// not overwritten by whatever happens to be annotated under the bars.
    pub automatic_system_ui_adjustment: bool,
}

impl RenderView {
    /// Creates the root of the render tree.
    ///
    /// Typically created by the binding (e.g., `RendererBinding`).
    ///
    /// Providing a `configuration` is optional, but a configuration must be set
    /// before calling [`prepare_initial_frame`](Self::prepare_initial_frame).
    pub fn new(
        app: &mut App,
        child: Option<AnyRenderBox>,
        configuration: Option<ViewConfiguration>,
        view: ViewRef,
    ) -> RenderHandle<RenderView> {
        let this = RenderHandle::from_handle(app.create(RenderView {
            render_object: RenderObjectData::new(),
            child: None,
            size: Size::ZERO,
            configuration: None,
            view,
            root_transform: None,
            needs_composite_frame: false,
            automatic_system_ui_adjustment: true,
        }));
        let data = this.render_object_data_mut(app);
        data.object_vtable = Some(&VTABLE);
        data.was_repaint_boundary = true;
        data.needs_compositing = true;
        if let Some(configuration) = configuration {
            this.set_configuration(app, configuration);
        }
        this.set_child(app, child);
        this
    }

    /// The type-erased `RenderObject` handle.
    pub fn as_object(self: RenderHandle<Self>) -> AnyRenderObject {
        AnyRenderObject::from_vtable(self.id(), const { &VTABLE })
    }

    /// The render object's unique child. Flutter's `RenderObjectWithChildMixin.child`.
    pub fn child(self: RenderHandle<Self>, app: &App) -> Option<AnyRenderBox> {
        self.get(app).child
    }

    /// Sets the unique child, adopting or dropping as Flutter's setter does.
    pub fn set_child(self: RenderHandle<Self>, app: &mut App, value: Option<AnyRenderBox>) {
        if let Some(old) = self.get(app).child {
            self.as_object().drop_child(app, old.as_object());
        }
        self.get_mut(app).child = value;
        if let Some(new) = value {
            self.as_object().adopt_child(app, new.as_object());
        }
    }

    /// The current layout size of the view.
    pub fn size(self: RenderHandle<Self>, app: &App) -> Size {
        self.get(app).size
    }

    /// The constraints used for the root layout.
    ///
    /// Typically, this configuration is set by the `RendererBinding`, when the
    /// [`RenderView`] is registered with it. It will also update the configuration
    /// if necessary. Therefore, if used in conjunction with the `RendererBinding`
    /// this property must not be set manually as the `RendererBinding` will just
    /// override it.
    ///
    /// # Panics
    ///
    /// If no configuration has been set.
    pub fn configuration(self: RenderHandle<Self>, app: &App) -> ViewConfiguration {
        self.get(app)
            .configuration
            .expect("RenderView has not been given a configuration yet")
    }

    /// Sets [`configuration`](Self::configuration).
    pub fn set_configuration(self: RenderHandle<Self>, app: &mut App, value: ViewConfiguration) {
        if self.get(app).configuration == Some(value) {
            return;
        }
        let old_configuration = self.get(app).configuration;
        self.get_mut(app).configuration = Some(value);
        if self.get(app).root_transform.is_none() {
            // [prepare_initial_frame] has not been called yet, nothing more to do for now.
            return;
        }
        if old_configuration.is_none_or(|old| value.should_update_matrix(&old)) {
            let root_layer = self.update_matrices_and_create_new_root_layer(app);
            self.as_object()
                .replace_root_layer(app, root_layer.as_offset_layer());
        }
        debug_assert!(self.get(app).root_transform.is_some());
        self.as_object().mark_needs_layout(app);
    }

    /// Whether a [`configuration`](Self::configuration) has been set.
    pub fn has_configuration(self: RenderHandle<Self>, app: &App) -> bool {
        self.get(app).configuration.is_some()
    }

    /// The constraints most recently supplied for layout: the configuration's logical
    /// constraints.
    ///
    /// # Panics
    ///
    /// If no configuration has been set.
    pub fn constraints(self: RenderHandle<Self>, app: &App) -> BoxConstraints {
        debug_assert!(
            self.has_configuration(app),
            "Constraints are not available because RenderView has not been given a configuration yet."
        );
        self.configuration(app).logical_constraints
    }

    /// The host view into which this render tree is rendered.
    pub fn flutter_view(self: RenderHandle<Self>, app: &App) -> ViewRef {
        self.get(app).view.clone()
    }

    /// Bootstrap the rendering pipeline by preparing the first frame.
    ///
    /// This should only be called once, and must be called before changing
    /// [`configuration`](Self::configuration). It is typically called immediately after calling
    /// the constructor.
    ///
    /// This does not actually schedule the first frame. Call
    /// `SchedulerBinding::ensure_visual_update` for that.
    pub fn prepare_initial_frame(self: RenderHandle<Self>, app: &mut App) {
        debug_assert!(
            self.as_object().owner(app).is_some(),
            "attach the RenderView to a PipelineOwner before calling prepare_initial_frame"
        );
        debug_assert!(
            self.get(app).root_transform.is_none(),
            "prepare_initial_frame must only be called once"
        );
        debug_assert!(
            self.has_configuration(app),
            "set a configuration before calling prepare_initial_frame"
        );
        self.as_object().schedule_initial_layout(app);
        let root_layer = self.update_matrices_and_create_new_root_layer(app);
        self.as_object()
            .schedule_initial_paint(app, root_layer.as_container_layer());
        debug_assert!(self.get(app).root_transform.is_some());
    }

    /// Whether this view must be composited on the next frame.
    ///
    /// This flag is cleared once the view gets successfully composited.
    pub fn needs_composite_frame(self: RenderHandle<Self>, app: &App) -> bool {
        self.get(app).needs_composite_frame
    }

    /// Marks this view required to be composited on the next frame.
    ///
    /// This happens by the [`PipelineOwner`](crate::PipelineOwner) during
    /// [`flush_paint`](crate::PipelineOwner::flush_paint) if there are any render objects that
    /// need to be painted. It is also set for a new view, for the warm-up frame, and when the
    /// app is resumed from the background.
    pub fn mark_needs_composite_frame(self: RenderHandle<Self>, app: &mut App) {
        self.get_mut(app).needs_composite_frame = true;
    }

    fn update_matrices_and_create_new_root_layer(
        self: RenderHandle<Self>,
        app: &mut App,
    ) -> Handle<TransformLayer> {
        debug_assert!(self.has_configuration(app));
        let root_transform = self.configuration(app).to_matrix();
        self.get_mut(app).root_transform = Some(root_transform);
        let root_layer = TransformLayer::new(app);
        root_layer.set_transform(app, root_transform);
        root_layer.attach(app, self.id());
        debug_assert!(self.get(app).root_transform.is_some());
        root_layer
    }

    /// Determines the set of render objects located at the given position.
    ///
    /// Returns true if the given point is contained in this render object or one of its
    /// descendants. Adds any render objects that contain the point to the given hit test result.
    ///
    /// The `position` argument is in the coordinate system of the render view, which is to say,
    /// in logical pixels. This is not necessarily the same coordinate system as that expected by
    /// the root layer (which is in physical pixels).
    pub fn hit_test(
        self: RenderHandle<Self>,
        app: &mut App,
        result: &mut HitTestResult,
        position: Offset,
    ) -> bool {
        if let Some(child) = self.child(app) {
            child.hit_test(app, &mut BoxHitTestResult::wrap(result), position);
        }
        result.add(HitTestEntry::new(self));
        true
    }

    /// Uploads the composited layer tree to the host.
    ///
    /// Actually causes the output of the rendering pipeline to appear on screen.
    pub fn composite_frame(self: RenderHandle<Self>, app: &mut App) {
        debug_assert!(
            self.has_configuration(app),
            "set the RenderView configuration before calling composite_frame"
        );
        debug_assert!(
            self.get(app).root_transform.is_some(),
            "call prepare_initial_frame before calling composite_frame"
        );
        let layer = self
            .as_object()
            .layer(app)
            .expect("call prepare_initial_frame before calling composite_frame");
        let scene = layer.build_scene(app, SceneBuilder::new());
        if self.get(app).automatic_system_ui_adjustment {
            self.update_system_chrome(app);
        }
        debug_assert!(
            self.configuration(app)
                .logical_constraints
                .is_satisfied_by(self.size(app))
        );
        self.get(app).view.present(std::sync::Arc::new(scene));
        self.get_mut(app).needs_composite_frame = false;
    }

    /// Styles the system overlays from whatever the layer tree annotates beneath them.
    ///
    /// Takes the overlay style from the place where a system status bar and system
    /// navigation bar are placed to update system style overlay. The center of the system
    /// navigation bar and the center of the status bar are used to get
    /// `SystemUiOverlayStyle`'s to update system overlay appearance.
    ///
    /// ```text
    ///         Horizontal center of the screen
    ///                 V
    ///    ++++++++++++++++++++++++++
    ///    |                        |
    ///    |    System status bar   |  <- Vertical center of the status bar
    ///    |                        |
    ///    ++++++++++++++++++++++++++
    ///    |                        |
    ///    |        Content         |
    ///    ~                        ~
    ///    |                        |
    ///    ++++++++++++++++++++++++++
    ///    |                        |
    ///    |  System navigation bar | <- Vertical center of the navigation bar
    ///    |                        |
    ///    ++++++++++++++++++++++++++ <- bounds.bottom
    /// ```
    fn update_system_chrome(self: RenderHandle<Self>, app: &mut App) {
        let Some(layer) = self.as_object().layer(app) else {
            return;
        };
        let bounds = self.paint_bounds(app);
        let padding = self.get(app).view.metrics().padding;
        // Center of the status bar
        let top = Offset::new(
            // Horizontal center of the screen
            bounds.center().dx(),
            // The vertical center of the system status bar. The system status bar height
            // is kept as top window padding.
            padding.top / 2.0,
        );
        // Center of the navigation bar
        let bottom = Offset::new(
            // Horizontal center of the screen
            bounds.center().dx(),
            // Vertical center of the system navigation bar. The system navigation bar
            // height is kept as bottom window padding. The "1" needs to be subtracted from
            // the bottom because available pixels are in (0..bottom) range. I.e. for a
            // device with 1920 height, bound.bottom is 1920, but the most bottom drawn
            // pixel is at 1919 position.
            bounds.bottom - 1.0 - padding.bottom / 2.0,
        );
        let layer = layer.as_layer();
        let upper = layer.find::<SystemUiOverlayStyle>(app, top);
        // Only Android has a customizable system navigation bar.
        let is_android = app.platform().target_platform() == TargetPlatform::Android;
        let lower = is_android
            .then(|| layer.find::<SystemUiOverlayStyle>(app, bottom))
            .flatten();
        // If there are no overlay style in the UI don't bother updating.
        let Some(style) = merged_overlay_style(upper, lower, is_android) else {
            return;
        };
        SystemChrome::set_system_ui_overlay_style(app, &style);
    }

    /// An estimate of the bounds within which this render object will paint, in physical
    /// pixels.
    pub fn paint_bounds(self: RenderHandle<Self>, app: &App) -> Rect {
        Offset::ZERO & (self.size(app) * self.configuration(app).device_pixel_ratio)
    }
}

/// The style the two sampled points make between them, and `None` where the tree annotates
/// neither: nothing was said about the overlays, so nothing is said to the host.
///
/// When both are annotated the upper provides the status bar properties and the lower
/// provides the system navigation bar properties. This is for the case where a widget at
/// the top, an app bar say, annotates the status bar's style while another at the bottom
/// annotates the navigation bar's. When only one of them is, it provides every property,
/// which lets one annotated region set both.
fn merged_overlay_style(
    upper: Option<Rc<SystemUiOverlayStyle>>,
    lower: Option<Rc<SystemUiOverlayStyle>>,
    is_android: bool,
) -> Option<SystemUiOverlayStyle> {
    if let (Some(upper), Some(lower)) = (&upper, &lower) {
        return Some(SystemUiOverlayStyle {
            status_bar_brightness: upper.status_bar_brightness,
            status_bar_icon_brightness: upper.status_bar_icon_brightness,
            status_bar_color: upper.status_bar_color,
            system_status_bar_contrast_enforced: upper.system_status_bar_contrast_enforced,
            system_navigation_bar_color: lower.system_navigation_bar_color,
            system_navigation_bar_divider_color: lower.system_navigation_bar_divider_color,
            system_navigation_bar_icon_brightness: lower.system_navigation_bar_icon_brightness,
            system_navigation_bar_contrast_enforced: lower.system_navigation_bar_contrast_enforced,
        });
    }
    let defined = upper.or(lower)?;
    if !is_android {
        // Only Android has a system navigation bar to style.
        return Some(SystemUiOverlayStyle {
            status_bar_brightness: defined.status_bar_brightness,
            status_bar_icon_brightness: defined.status_bar_icon_brightness,
            status_bar_color: defined.status_bar_color,
            system_status_bar_contrast_enforced: defined.system_status_bar_contrast_enforced,
            ..SystemUiOverlayStyle::new()
        });
    }
    Some(*defined)
}

impl RenderObject for RenderView {
    fn render_object_data(self: RenderHandle<Self>, app: &App) -> &RenderObjectData {
        &self.get(app).render_object
    }

    fn render_object_data_mut(self: RenderHandle<Self>, app: &mut App) -> &mut RenderObjectData {
        &mut self.get_mut(app).render_object
    }

    fn perform_resize(self: RenderHandle<Self>, _app: &mut App) {
        panic!("RenderView is never sized by its parent");
    }

    fn perform_layout(self: RenderHandle<Self>, app: &mut App) {
        debug_assert!(self.get(app).root_transform.is_some());
        let constraints = self.constraints(app);
        let sized_by_child = !constraints.is_tight();
        let child = self.child(app);
        if let Some(child) = child {
            child.layout(app, constraints, sized_by_child);
        }
        let size = match child {
            Some(child) if sized_by_child => child.size(app),
            _ => constraints.smallest(),
        };
        self.get_mut(app).size = size;
        debug_assert!(size.is_finite());
        debug_assert!(constraints.is_satisfied_by(size));
    }

    fn visit_children(
        self: RenderHandle<Self>,
        app: &App,
        visitor: &mut dyn FnMut(AnyRenderObject),
    ) {
        if let Some(child) = self.child(app) {
            visitor(child.as_object());
        }
    }

    fn apply_paint_transform(
        self: RenderHandle<Self>,
        app: &App,
        child: AnyRenderObject,
        transform: &mut Matrix4,
    ) {
        let root_transform = self
            .get(app)
            .root_transform
            .as_ref()
            .expect("the view has a configuration");
        crate::object::multiply(transform, root_transform);
        debug_assert!(child.parent(app).map(AnyRenderObject::id) == Some(self.id()));
    }

    fn is_repaint_boundary(self: RenderHandle<Self>, _app: &App) -> bool {
        true
    }

    fn paint(
        self: RenderHandle<Self>,
        app: &mut App,
        context: &mut PaintingContext,
        offset: Offset,
    ) {
        if let Some(child) = self.child(app) {
            context.paint_child(app, child.as_object(), offset);
        }
    }
}

/// Flutter's `RenderObject.handleEvent` default: the view itself does nothing with events.
impl HitTestTarget for RenderHandle<RenderView> {
    fn handle_event(&self, _app: &mut App, _event: &PointerEvent, _entry: &HitTestEntry) {}
}

/// The view is its own protocol: not a box, one object, so its vtable is a plain constant.
static VTABLE: RenderObjectVTable = RenderObjectVTable::of::<RenderView>(
    |app, id, child| <RenderView as RenderObject>::setup_parent_data(resolve(id), app, child),
    |app, id| RenderView::paint_bounds(resolve(id), app),
    |app, id, child, transform| {
        <RenderView as RenderObject>::apply_paint_transform(resolve(id), app, child, transform)
    },
    |app, id| <RenderView as RenderObject>::perform_resize(resolve(id), app),
    |app, id| crate::object::RenderObjectBase::mark_needs_layout(resolve::<RenderView>(id), app),
    None,
    None,
);

#[cfg(test)]
mod tests {
    use inset_foundation::AppCell;
    use std::cell::Cell;
    use std::rc::Rc;

    use inset_embedder::{ViewId, ViewMetrics};

    use super::*;
    use crate::box_::RenderBox;
    use crate::layer::TransformLayer;
    use crate::pipeline_owner::PipelineOwner;
    use crate::proxy_box::RenderConstrainedBox;
    use crate::shifted_box::RenderPadding;
    use inset_painting::EdgeInsetsGeometry;

    struct TestView {
        metrics: ViewMetrics,
        presented: Rc<Cell<u32>>,
    }

    impl View for TestView {
        fn id(&self) -> ViewId {
            ViewId(0)
        }

        fn metrics(&self) -> ViewMetrics {
            self.metrics
        }

        fn present(&self, _scene: std::sync::Arc<inset_embedder::Scene>) {
            self.presented.set(self.presented.get() + 1);
        }
    }

    fn test_view(presented: &Rc<Cell<u32>>) -> ViewRef {
        Rc::new(TestView {
            metrics: ViewMetrics::default(),
            presented: Rc::clone(presented),
        })
    }

    /// `view_test.dart`'s `createViewConfiguration`.
    fn create_view_configuration(size: Size, device_pixel_ratio: f64) -> ViewConfiguration {
        let constraints = BoxConstraints::tight(size);
        ViewConfiguration::new(
            constraints * device_pixel_ratio,
            constraints,
            device_pixel_ratio,
        )
    }

    /// `view_test.dart`: `ViewConfiguration == and hashCode`.
    #[test]
    fn view_configuration_equality() {
        let a = create_view_configuration(Size::new(800.0, 600.0), 1.0);
        let b = create_view_configuration(Size::new(800.0, 600.0), 1.0);
        let c = create_view_configuration(Size::new(800.0, 600.0), 3.0);
        assert_eq!(a, b);
        assert_ne!(a, c);
    }

    /// `view_test.dart`: `Constraints are derived from configuration`.
    #[test]
    fn constraints_are_derived_from_configuration() {
        let cell = AppCell::new();
        let mut app = cell.borrow_mut();
        let presented = Rc::new(Cell::new(0));
        let view = RenderView::new(&mut app, None, None, test_view(&presented));
        assert!(!view.has_configuration(&app));
        let constraints = BoxConstraints::new()
            .min_width(1.0)
            .max_width(2.0)
            .min_height(3.0)
            .max_height(4.0);
        view.set_configuration(
            &mut app,
            ViewConfiguration::new(constraints * 3.0, constraints, 3.0),
        );
        assert_eq!(view.constraints(&app), constraints);
    }

    /// `view_test.dart`: `Config can be set and changed after instantiation without calling
    /// prepareInitialFrame first`.
    #[test]
    fn configuration_can_change_before_prepare_initial_frame() {
        let cell = AppCell::new();
        let mut app = cell.borrow_mut();
        let presented = Rc::new(Cell::new(0));
        let view = RenderView::new(&mut app, None, None, test_view(&presented));
        view.set_configuration(
            &mut app,
            create_view_configuration(Size::new(100.0, 200.0), 3.0),
        );
        view.set_configuration(
            &mut app,
            create_view_configuration(Size::new(200.0, 300.0), 2.0),
        );
        let owner = PipelineOwner::new(&mut app, None, None);
        owner.set_root_node(&mut app, Some(view.as_object()));
        view.prepare_initial_frame(&mut app);
    }

    /// `view_test.dart`: `does not replace the root layer unnecessarily` (and when the view
    /// resizes). Ours observes the replacement through the paint mark.
    #[test]
    fn does_not_replace_the_root_layer_unnecessarily() {
        let cell = AppCell::new();
        let mut app = cell.borrow_mut();
        let presented = Rc::new(Cell::new(0));
        let view = RenderView::new(
            &mut app,
            None,
            Some(create_view_configuration(Size::new(100.0, 100.0), 1.0)),
            test_view(&presented),
        );
        let owner = PipelineOwner::new(&mut app, None, None);
        owner.set_root_node(&mut app, Some(view.as_object()));
        view.prepare_initial_frame(&mut app);
        owner.flush_layout(&mut app);
        owner.flush_compositing_bits(&mut app);
        owner.flush_paint(&mut app);
        assert!(!view.as_object().debug_needs_paint(&app));

        view.set_configuration(
            &mut app,
            create_view_configuration(Size::new(100.0, 1117.0), 1.0),
        );
        assert!(
            !view.as_object().debug_needs_paint(&app),
            "a resize keeps the root layer"
        );

        view.set_configuration(
            &mut app,
            create_view_configuration(Size::new(100.0, 1117.0), 5.0),
        );
        assert!(
            view.as_object().debug_needs_paint(&app),
            "a new ratio replaces it"
        );
        let layer = view.as_object().debug_layer(&app).expect("root layer");
        let transform = app
            .handle::<TransformLayer>(layer.id())
            .expect("the root is a TransformLayer");
        assert_eq!(transform.transform(&app), Some(Matrix4::scale(5.0, 5.0)));
    }

    /// `view_test.dart`: `accounts for device pixel ratio in paintBounds`, plus one frame
    /// composited to the host.
    #[test]
    fn accounts_for_device_pixel_ratio_in_paint_bounds_and_presents() {
        let cell = AppCell::new();
        let mut app = cell.borrow_mut();
        let presented = Rc::new(Cell::new(0));
        let child =
            RenderConstrainedBox::new(&mut app, BoxConstraints::tight(Size::new(10.0, 10.0)), None);
        let view = RenderView::new(
            &mut app,
            Some(child.as_box()),
            Some(create_view_configuration(Size::new(800.0, 600.0), 2.0)),
            test_view(&presented),
        );
        let owner = PipelineOwner::new(&mut app, None, None);
        owner.set_root_node(&mut app, Some(view.as_object()));
        view.prepare_initial_frame(&mut app);
        owner.flush_layout(&mut app);
        owner.flush_compositing_bits(&mut app);
        owner.flush_paint(&mut app);
        view.composite_frame(&mut app);

        assert_eq!(view.size(&app), Size::new(800.0, 600.0));
        assert_eq!(
            view.paint_bounds(&app),
            Offset::ZERO & Size::new(1600.0, 1200.0)
        );
        assert_eq!(presented.get(), 1);
    }

    #[test]
    fn coordinates_convert_through_the_paint_transforms_below_the_view() {
        let cell = AppCell::new();
        let mut app = cell.borrow_mut();
        let presented = Rc::new(Cell::new(0));
        let child =
            RenderConstrainedBox::new(&mut app, BoxConstraints::tight(Size::new(30.0, 40.0)), None);
        let padding = RenderPadding::new(
            &mut app,
            EdgeInsetsGeometry::from_ltrb(10.0, 20.0, 0.0, 0.0),
            None,
            Some(child.as_box()),
        );
        let view = RenderView::new(
            &mut app,
            Some(padding.as_box()),
            Some(create_view_configuration(Size::new(800.0, 600.0), 2.0)),
            test_view(&presented),
        );
        let owner = PipelineOwner::new(&mut app, None, None);
        owner.set_root_node(&mut app, Some(view.as_object()));
        view.prepare_initial_frame(&mut app);
        owner.flush_layout(&mut app);

        // The root view's own transform (logical to physical) is left out, as in Dart.
        let child = child.as_box();
        assert_eq!(
            child.local_to_global(&app, Offset::ZERO, None),
            Offset::new(10.0, 20.0)
        );
        assert_eq!(
            child.global_to_local(&app, Offset::new(15.0, 25.0), None),
            Offset::new(5.0, 5.0)
        );
        assert_eq!(
            child.local_to_global(&app, Offset::new(1.0, 1.0), Some(padding.as_object())),
            Offset::new(11.0, 21.0)
        );
        assert_eq!(
            padding.as_box().global_to_local(
                &app,
                Offset::new(10.0, 20.0),
                Some(child.as_object())
            ),
            Offset::new(20.0, 40.0)
        );
        assert!(
            child
                .as_object()
                .paint_bounds(&app)
                .inflate(70.0)
                .contains(child.global_to_local(&app, Offset::new(100.0, 100.0), None))
        );
    }

    #[test]
    fn a_proxy_box_adds_no_paint_transform() {
        let cell = AppCell::new();
        let mut app = cell.borrow_mut();
        let presented = Rc::new(Cell::new(0));
        let child =
            RenderConstrainedBox::new(&mut app, BoxConstraints::tight(Size::new(30.0, 40.0)), None);
        let proxy =
            RenderConstrainedBox::new(&mut app, BoxConstraints::new(), Some(child.as_box()));
        let padding = RenderPadding::new(
            &mut app,
            EdgeInsetsGeometry::from_ltrb(10.0, 20.0, 0.0, 0.0),
            None,
            Some(proxy.as_box()),
        );
        let view = RenderView::new(
            &mut app,
            Some(padding.as_box()),
            Some(create_view_configuration(Size::new(800.0, 600.0), 2.0)),
            test_view(&presented),
        );
        let owner = PipelineOwner::new(&mut app, None, None);
        owner.set_root_node(&mut app, Some(view.as_object()));
        view.prepare_initial_frame(&mut app);
        owner.flush_layout(&mut app);

        assert_eq!(
            child.as_box().local_to_global(&app, Offset::ZERO, None),
            Offset::new(10.0, 20.0)
        );
        assert_eq!(
            child
                .as_box()
                .global_to_local(&app, Offset::new(15.0, 25.0), None),
            Offset::new(5.0, 5.0)
        );
    }
}