Skip to main content

waft_rendering/
screenshot.rs

1//! A picture of one render object as it last painted, apart from what paints around it: the
2//! widget inspector's screenshot (`_ScreenshotPaintingContext.toImage`,
3//! `_calculateSubtreeBounds`).
4//!
5//! As in Dart, the nearest repaint boundary at or above the object repaints in place through a
6//! painting context that notes what the object paints, and the screenshot borrows those layers
7//! through proxy layers, which add a layer of the real tree to another scene without taking it
8//! as a child. Dart's context also copies the object's canvas into a recording of its own
9//! (`_MulticastCanvas`); this one closes its picture before and after the object paints instead,
10//! so the object's drawing is in picture layers of its own, which the screenshot borrows as it
11//! borrows the object's other layers. The real tree draws the same; its picture is split where
12//! the object starts and ends.
13
14use std::cell::RefCell;
15use std::rc::Rc;
16
17use waft_embedder::{Matrix4, Offset, Picture, Rect, SceneBuilder};
18use waft_foundation::{App, Handle};
19use waft_painting::transform_rect;
20
21use crate::layer::{
22    AnnotationSearch, AnyLayer, ContainerLayer, ErasedLayer, Layer, LayerData, OffsetLayer,
23    scene_picture,
24};
25use crate::object::AnyRenderObject;
26use crate::painting_context::PaintingContext;
27
28/// Dart's `_ScreenshotData`: what the painting contexts recording one screenshot share.
29pub(crate) struct ScreenshotRecording {
30    /// The object a picture is taken of.
31    pub(crate) target: AnyRenderObject,
32    /// The root of the screenshot's layers: proxies of the target's.
33    container: Handle<OffsetLayer>,
34    /// Whether the target has been reached in the paint.
35    pub(crate) found_target: bool,
36    /// Whether the layers the context appends now are the target's.
37    pub(crate) include_in_screenshot: bool,
38    /// Where the target was painted in the context that painted it.
39    screenshot_offset: Offset,
40}
41
42/// The recording, as the painting contexts hold it.
43pub(crate) type SharedRecording = Rc<RefCell<ScreenshotRecording>>;
44
45impl ScreenshotRecording {
46    fn new(app: &mut App, target: AnyRenderObject) -> SharedRecording {
47        Rc::new(RefCell::new(ScreenshotRecording {
48            target,
49            container: OffsetLayer::new(app, Offset::ZERO),
50            found_target: false,
51            include_in_screenshot: false,
52            screenshot_offset: Offset::ZERO,
53        }))
54    }
55
56    /// The target is about to paint at `offset`: Dart's `paintChild` before `super`.
57    pub(crate) fn start_target(&mut self, offset: Offset) {
58        debug_assert!(!self.include_in_screenshot && !self.found_target);
59        self.found_target = true;
60        self.screenshot_offset = offset;
61        self.include_in_screenshot = true;
62    }
63
64    /// The target has painted: Dart's `paintChild` after `super`.
65    pub(crate) fn end_target(&mut self) {
66        self.include_in_screenshot = false;
67    }
68
69    /// Adds `layer`, which the target painted into the real tree, to the screenshot.
70    pub(crate) fn borrow_layer(&self, app: &mut App, layer: AnyLayer) {
71        let proxy = ProxyLayer::new(app, layer);
72        self.container
73            .as_container_layer()
74            .append(app, proxy.as_layer());
75    }
76}
77
78/// Dart's `_ProxyLayer`: a layer of another tree added to this one's scene, which stays a child of
79/// its own parent.
80pub(crate) struct ProxyLayer {
81    layer: LayerData,
82    proxied: AnyLayer,
83}
84
85impl ProxyLayer {
86    fn new(app: &mut App, proxied: AnyLayer) -> Handle<ProxyLayer> {
87        app.create(ProxyLayer {
88            layer: LayerData::new(),
89            proxied,
90        })
91        .into_tree_node(app)
92    }
93}
94
95impl Layer for ProxyLayer {
96    crate::layer_accessors!();
97
98    fn add_to_scene(self: Handle<Self>, app: &mut App, builder: &mut SceneBuilder) {
99        let proxied = app.get(self).proxied;
100        proxied.add_to_scene(app, builder);
101    }
102
103    fn find_annotations(
104        self: Handle<Self>,
105        app: &App,
106        result: &mut AnnotationSearch,
107        local_position: Offset,
108        only_first: bool,
109    ) -> bool {
110        app.get(self)
111            .proxied
112            .find_annotations(app, result, local_position, only_first)
113    }
114}
115
116/// Dart's `_ScreenshotPaintingContext.toImage`, as the picture the host draws into an image: what
117/// `render_object` and its descendants paint within `render_bounds`, in its own coordinates,
118/// scaled by `pixel_ratio`. The repaint boundary at or above the object is repainted, as Dart's
119/// is; an object that is its own boundary shows the layer it last painted. `None` where Dart's
120/// throws: no boundary above the object has a layer yet, as before its first paint.
121pub fn screenshot_picture(
122    app: &mut App,
123    render_object: AnyRenderObject,
124    render_bounds: Rect,
125    pixel_ratio: f64,
126) -> Option<Picture> {
127    let boundary = std::iter::successors(Some(render_object), |object| object.parent(app))
128        .find(|object| object.is_repaint_boundary(app))?;
129    let boundary_layer = boundary.layer(app)?.as_offset_layer()?;
130    let recording = ScreenshotRecording::new(app, render_object);
131    if boundary == render_object {
132        let mut data = recording.borrow_mut();
133        data.borrow_layer(app, boundary_layer.as_layer());
134        data.found_target = true;
135        data.screenshot_offset = boundary_layer.offset(app);
136    } else {
137        let context = PaintingContext::recording_screenshot(
138            boundary_layer.as_container_layer(),
139            boundary.paint_bounds(app),
140            Rc::clone(&recording),
141        );
142        PaintingContext::debug_instrument_repaint_composited_child(app, boundary, context);
143    }
144    // The boundary repainted in place: Dart's `repaintBoundary.debugLayer!.buildScene`.
145    let _ = boundary_layer
146        .as_container_layer()
147        .build_scene(app, SceneBuilder::new());
148    let (container, offset, found_target) = {
149        let data = recording.borrow();
150        (data.container, data.screenshot_offset, data.found_target)
151    };
152    let picture = found_target.then(|| {
153        scene_picture(
154            app,
155            container.as_container_layer(),
156            render_bounds,
157            offset,
158            pixel_ratio,
159        )
160    });
161    container.as_layer().dispose(app);
162    picture
163}
164
165/// Dart's `_calculateSubtreeBounds`: the bounds `object` and its descendants paint in, in its
166/// own coordinates, each child's within what its parent says it clips to. A box's paint bounds
167/// stand in for Dart's `semanticBounds`, which are the same for a box.
168pub fn subtree_bounds(app: &App, object: AnyRenderObject) -> Rect {
169    subtree_bounds_in(app, object, Matrix4::IDENTITY)
170}
171
172fn subtree_bounds_in(app: &App, object: AnyRenderObject, transform: Matrix4) -> Rect {
173    let mut bounds = transform_rect(&transform, object.paint_bounds(app));
174    object.visit_children(app, &mut |child| {
175        let mut child_transform = transform;
176        object.apply_paint_transform(app, child, &mut child_transform);
177        let mut child_bounds = subtree_bounds_in(app, child, child_transform);
178        if let Some(paint_clip) = object.describe_approximate_paint_clip(app, child) {
179            child_bounds = child_bounds.intersect(transform_rect(&transform, paint_clip));
180        }
181        if child_bounds.is_finite() && !child_bounds.is_empty() {
182            bounds = if bounds.is_empty() {
183                child_bounds
184            } else {
185                bounds.expand_to_include(child_bounds)
186            };
187        }
188    });
189    bounds
190}
191
192#[cfg(test)]
193mod tests {
194    use waft_embedder::valo::Op;
195    use waft_embedder::{Color, flattened_ops};
196    use waft_foundation::AppCell;
197    use waft_painting::{AlignmentGeometry, EdgeInsets};
198
199    use super::*;
200    use crate::box_::{BoxConstraints, RenderBox};
201    use crate::proxy_box::{RenderColoredBox, RenderConstrainedBox};
202    use crate::shifted_box::RenderPadding;
203    use crate::testing::{EnginePhase, layout_with};
204
205    const RED: Color = Color::new(0xFFFF0000);
206    const GREEN: Color = Color::new(0xFF00FF00);
207
208    /// A red box, padded, around a green one: the green one's screenshot is its own drawing
209    /// alone, at its own origin, though both paint into the one picture of the root's boundary.
210    #[test]
211    fn a_screenshot_holds_the_object_alone_in_its_own_coordinates() {
212        let cell = AppCell::new();
213        let mut app = cell.borrow_mut();
214        let square = RenderConstrainedBox::new(
215            &mut app,
216            BoxConstraints::tight_for(Some(20.0), Some(20.0)),
217            None,
218        );
219        let green = RenderColoredBox::new(&mut app, GREEN, true, Some(square.as_box()));
220        let padding = RenderPadding::new(
221            &mut app,
222            EdgeInsets::all(10.0).into(),
223            None,
224            Some(green.as_box()),
225        );
226        let red = RenderColoredBox::new(&mut app, RED, true, Some(padding.as_box()));
227        layout_with(
228            &mut app,
229            red.as_box(),
230            Some(BoxConstraints::tight(waft_embedder::Size::new(60.0, 60.0))),
231            AlignmentGeometry::TOP_LEFT,
232            EnginePhase::Paint,
233        );
234        let bounds = subtree_bounds(&app, green.as_object());
235        assert_eq!(bounds, Rect::from_ltwh(0.0, 0.0, 40.0, 40.0));
236        let picture =
237            screenshot_picture(&mut app, green.as_object(), bounds, 1.0).expect("painted");
238        let ops = flattened_ops(&picture);
239        let colors: Vec<_> = ops
240            .iter()
241            .filter_map(|op| match op {
242                Op::DrawRect { paint, .. } => Some(paint.color),
243                _ => None,
244            })
245            .collect();
246        assert!(!colors.is_empty(), "the green box is in the screenshot");
247        assert!(
248            colors.iter().all(|&color| color == GREEN.into()),
249            "and the red one around it is not: {colors:?}"
250        );
251        let moved_to_its_origin = ops.iter().any(|op| match op {
252            Op::Transform(matrix) => {
253                let translation = matrix.to_flutter_array();
254                (translation[12], translation[13]) == (-10.0, -10.0)
255            }
256            _ => false,
257        });
258        assert!(moved_to_its_origin, "drawn at the green box's own origin");
259    }
260
261    /// The object's own paint bounds, where nothing paints outside them.
262    #[test]
263    fn a_boxes_subtree_bounds_are_its_own_where_its_children_stay_inside() {
264        let cell = AppCell::new();
265        let mut app = cell.borrow_mut();
266        let inner = RenderConstrainedBox::new(
267            &mut app,
268            BoxConstraints::tight_for(Some(20.0), Some(20.0)),
269            None,
270        );
271        let outer = RenderPadding::new(
272            &mut app,
273            EdgeInsets::all(5.0).into(),
274            None,
275            Some(inner.as_box()),
276        );
277        layout_with(
278            &mut app,
279            outer.as_box(),
280            Some(BoxConstraints::tight(waft_embedder::Size::new(30.0, 30.0))),
281            AlignmentGeometry::TOP_LEFT,
282            EnginePhase::Layout,
283        );
284        assert_eq!(
285            subtree_bounds(&app, outer.as_object()),
286            Rect::from_ltwh(0.0, 0.0, 30.0, 30.0)
287        );
288    }
289}