Skip to main content

waft_rendering/
composition_layer_view.rs

1//! A box that shows a composition layer the host composites: Flutter's platform view render
2//! object, over the `CompositionLayer` a producer feeds.
3//!
4//! It paints nothing of its own: it adds a [`EmbeddedLayer`] at its place in paint order, and
5//! whoever composites the scene makes room for the composition layer there, so what the
6//! framework paints above it stays and what it painted beneath is gone. It fills what it is
7//! given: the layer's producer is told the size by whoever built this widget, not by the
8//! compositor. It always needs compositing, as Flutter's platform views do, so a transform, a
9//! clip or an opacity above it is a layer the composition layer is placed under rather than a
10//! change to the canvas alone. The invariant: the layer added is the box, at the offset it is
11//! painted at.
12
13use std::sync::Arc;
14
15use waft_embedder::{CompositionLayer, Offset, Size};
16use waft_foundation::App;
17
18use crate::box_::{BoxConstraints, RenderBox, RenderBoxData};
19use crate::layer::{EmbeddedLayer, ErasedLayer};
20use crate::object::{RenderHandle, RenderObject, RenderObjectData};
21use crate::painting_context::PaintingContext;
22
23/// Shows a composition layer in the box it is given.
24pub struct RenderCompositionLayerView {
25    render_object: RenderObjectData,
26    render_box: RenderBoxData,
27    composition_layer: Arc<dyn CompositionLayer>,
28}
29
30impl RenderCompositionLayerView {
31    pub fn new(
32        app: &mut App,
33        composition_layer: Arc<dyn CompositionLayer>,
34    ) -> RenderHandle<RenderCompositionLayerView> {
35        RenderHandle::new_box(
36            app,
37            RenderCompositionLayerView {
38                render_object: RenderObjectData::new(),
39                render_box: RenderBoxData::new(),
40                composition_layer,
41            },
42        )
43    }
44
45    /// The composition layer shown.
46    pub fn composition_layer(self: RenderHandle<Self>, app: &App) -> &Arc<dyn CompositionLayer> {
47        &self.get(app).composition_layer
48    }
49
50    /// Shows `composition_layer` instead, from the next paint.
51    pub fn set_composition_layer(
52        self: RenderHandle<Self>,
53        app: &mut App,
54        composition_layer: Arc<dyn CompositionLayer>,
55    ) {
56        if Arc::ptr_eq(&self.get(app).composition_layer, &composition_layer) {
57            return;
58        }
59        self.get_mut(app).composition_layer = composition_layer;
60        self.mark_needs_paint(app);
61    }
62}
63
64impl RenderObject for RenderCompositionLayerView {
65    crate::render_object_accessors!();
66
67    fn always_needs_compositing(self: RenderHandle<Self>, _app: &App) -> bool {
68        true
69    }
70
71    fn perform_layout(self: RenderHandle<Self>, app: &mut App) {
72        let size = self.constraints(app).biggest();
73        self.set_size(app, size);
74    }
75
76    /// The composition layer placed at the box: the layer splits the picture there, so what is
77    /// painted after it lies above the composition layer.
78    fn paint(
79        self: RenderHandle<Self>,
80        app: &mut App,
81        context: &mut PaintingContext,
82        offset: Offset,
83    ) {
84        let composition_layer = Arc::clone(&self.get(app).composition_layer);
85        let layer = EmbeddedLayer::new(app, composition_layer, offset & self.size(app));
86        context.add_layer(app, layer.as_layer());
87    }
88}
89
90impl RenderBox for RenderCompositionLayerView {
91    crate::render_box_accessors!();
92
93    fn compute_dry_layout(
94        self: RenderHandle<Self>,
95        _app: &mut App,
96        constraints: BoxConstraints,
97    ) -> Size {
98        constraints.biggest()
99    }
100
101    /// A composition layer takes a hit anywhere in its box, so a listener around it hears the
102    /// pointer.
103    fn hit_test_self(self: RenderHandle<Self>, _app: &App, _position: Offset) -> bool {
104        true
105    }
106}
107
108#[cfg(test)]
109mod tests {
110    use waft_embedder::test_support::idle_layer;
111    use waft_embedder::{Clip, Matrix4, Mutator, Part, Rect, SceneBuilder};
112    use waft_foundation::AppCell;
113    use waft_painting::AlignmentGeometry;
114
115    use super::*;
116    use crate::object::AnyRenderObject;
117    use crate::testing::{EnginePhase, layout_with, test_render_root};
118
119    /// Where a [`Parent`] paints its child.
120    const CHILD_OFFSET: Offset = Offset::new(10.0, 5.0);
121
122    /// A parent that lays its one child out at a fixed size and paints it as `painting` says.
123    struct Parent {
124        render_object: RenderObjectData,
125        render_box: RenderBoxData,
126        child: RenderHandle<RenderCompositionLayerView>,
127        painting: ChildPainting,
128    }
129
130    /// How a [`Parent`] paints its child.
131    #[derive(Clone, Copy)]
132    enum ChildPainting {
133        /// At [`CHILD_OFFSET`].
134        AtOffset,
135        /// At [`CHILD_OFFSET`], at half its size, clipped to the parent's top ten pixels.
136        HalvedUnderAClip,
137    }
138
139    impl RenderObject for Parent {
140        crate::render_object_accessors!();
141
142        fn perform_layout(self: RenderHandle<Self>, app: &mut App) {
143            let child = self.get(app).child;
144            child.layout(app, BoxConstraints::tight(Size::new(30.0, 20.0)), false);
145            self.set_size(app, Size::new(100.0, 100.0));
146        }
147
148        fn visit_children(
149            self: RenderHandle<Self>,
150            app: &App,
151            visitor: &mut dyn FnMut(AnyRenderObject),
152        ) {
153            visitor(self.get(app).child.as_object());
154        }
155
156        fn paint(
157            self: RenderHandle<Self>,
158            app: &mut App,
159            context: &mut PaintingContext,
160            offset: Offset,
161        ) {
162            let child = self.get(app).child.as_object();
163            match self.get(app).painting {
164                ChildPainting::AtOffset => context.paint_child(app, child, offset + CHILD_OFFSET),
165                ChildPainting::HalvedUnderAClip => {
166                    let needs_compositing = self.as_object().needs_compositing(app);
167                    context.push_clip_rect(
168                        app,
169                        needs_compositing,
170                        offset,
171                        Rect::from_ltwh(0.0, 0.0, 100.0, 10.0),
172                        |app, context, offset| {
173                            context.push_transform(
174                                app,
175                                needs_compositing,
176                                offset + CHILD_OFFSET,
177                                Matrix4::scale(0.5, 0.5),
178                                |app, context, offset| context.paint_child(app, child, offset),
179                                None,
180                            );
181                        },
182                        Clip::HardEdge,
183                        None,
184                    );
185                }
186            }
187        }
188    }
189
190    impl RenderBox for Parent {
191        crate::render_box_accessors!();
192    }
193
194    /// Lays out and paints a view of `composition_layer` under a parent that paints it as
195    /// `painting` says, at the test view's top left, and answers the scene.
196    fn scene_of_one_frame(
197        app: &mut App,
198        composition_layer: Arc<dyn CompositionLayer>,
199        painting: ChildPainting,
200    ) -> waft_embedder::Scene {
201        let child = RenderCompositionLayerView::new(app, composition_layer);
202        let parent = RenderHandle::new_box(
203            app,
204            Parent {
205                render_object: RenderObjectData::new(),
206                render_box: RenderBoxData::new(),
207                child,
208                painting,
209            },
210        );
211        parent.adopt_child(app, child.as_object());
212        layout_with(
213            app,
214            parent.as_box(),
215            Some(BoxConstraints::tight(Size::new(100.0, 100.0))),
216            AlignmentGeometry::TOP_LEFT,
217            EnginePhase::Paint,
218        );
219        test_render_root(app)
220            .as_object()
221            .debug_layer(app)
222            .expect("painted")
223            .build_scene(app, SceneBuilder::new())
224    }
225
226    #[test]
227    fn the_box_is_placed_and_nothing_is_painted() {
228        let cell = AppCell::new();
229        let mut app = cell.borrow_mut();
230        let composition_layer = idle_layer();
231        let scene = scene_of_one_frame(
232            &mut app,
233            Arc::clone(&composition_layer),
234            ChildPainting::AtOffset,
235        );
236        let slices = waft_embedder::slices(&scene, |_| None);
237        let [Part::CompositionLayer { layer, placement }] = slices.parts() else {
238            panic!("the composition layer alone: {:?}", slices.parts());
239        };
240        assert!(Arc::ptr_eq(layer, &composition_layer));
241        let placed = Rect::from_ltwh(10.0, 5.0, 30.0, 20.0);
242        assert_eq!(placement.bounds(), placed);
243        assert_eq!(placement.visible_bounds(), placed);
244        assert!(!slices.paints());
245    }
246
247    /// A transform and a clip above a composition layer are layers of their own, as they are
248    /// above Flutter's platform views, so the scene places the composition layer under both.
249    #[test]
250    fn a_composition_layer_is_placed_under_the_transform_and_the_clip_above_it() {
251        let cell = AppCell::new();
252        let mut app = cell.borrow_mut();
253        let scene = scene_of_one_frame(&mut app, idle_layer(), ChildPainting::HalvedUnderAClip);
254        let slices = waft_embedder::slices(&scene, |_| None);
255        let (_, placement) = slices.composition_layers().next().expect("placed");
256        assert!(
257            placement
258                .mutators
259                .contains(&Mutator::ClipRect(Rect::from_ltwh(0.0, 0.0, 100.0, 10.0)))
260        );
261        assert_eq!(placement.scale(), 0.5);
262        assert_eq!(placement.bounds(), Rect::from_ltwh(10.0, 5.0, 15.0, 10.0));
263        assert_eq!(
264            placement.visible_bounds(),
265            Rect::from_ltrb(10.0, 5.0, 25.0, 10.0)
266        );
267    }
268}