Skip to main content

waft_embedder/
snapshot_delegate.rs

1//! Flutter counterpart: the engine's `SnapshotDelegate::MakeRasterSnapshotSync`
2//! (`lib/ui/snapshot_delegate.h`), which the rasterizer implements and `Picture.toImageSync`
3//! draws through: what a host answers [`Platform::picture_to_image_sync`](crate::Platform) with;
4//! and the read-back behind `Image.toByteData`, what it answers
5//! [`Platform::read_image_pixels`](crate::Platform) with.
6//!
7//! The invariant a later editor must keep: the picture is drawn with a renderer of the delegate's
8//! own, on the device the host's images belong to, so an image it makes draws in every view and
9//! no view's renderer is borrowed while the framework records a frame.
10
11use std::cell::{RefCell, RefMut};
12use std::sync::Arc;
13
14use crate::Rect;
15use crate::image_codecs::{ImageError, ImageErrorKind, ImageFuture};
16use crate::painting::{Canvas, Image, Paint, Picture, valo};
17
18/// Draws pictures into images on the device of a host's image store, with a renderer made at
19/// the first picture.
20pub struct SnapshotDelegate {
21    images: valo::ImageContext,
22    context: RefCell<Option<valo::Context>>,
23}
24
25impl SnapshotDelegate {
26    /// A delegate drawing on the device `images` belongs to.
27    pub fn new(images: valo::ImageContext) -> SnapshotDelegate {
28        SnapshotDelegate {
29            images,
30            context: RefCell::new(None),
31        }
32    }
33
34    /// `picture` drawn into a new image `width` by `height` pixels large over transparent black,
35    /// what lies past those bounds clipped: valo's `display_list_to_image`, Impeller's
36    /// `DisplayListToTexture`. The drawing is submitted now, and anything drawn with the image
37    /// waits for it on the GPU.
38    ///
39    /// # Panics
40    ///
41    /// Where `width` or `height` is zero, as Dart throws "Invalid image dimensions.".
42    pub fn make_raster_snapshot_sync(&self, picture: &Picture, width: u32, height: u32) -> Image {
43        assert!(width > 0 && height > 0, "Invalid image dimensions.");
44        self.context()
45            .display_list_to_image(picture, [width, height])
46    }
47
48    /// `image`'s pixels, read back from the device it lives on, `wait` waiting for the GPU's
49    /// answer as the host can: see [`read_image_pixels`].
50    pub fn read_pixels(
51        &self,
52        image: &Image,
53        wait: impl FnOnce(&wgpu::Device),
54    ) -> ImageFuture<valo::PixelBuffer> {
55        read_image_pixels(&mut self.context(), image, wait)
56    }
57
58    /// The delegate's renderer, made at its first use.
59    fn context(&self) -> RefMut<'_, valo::Context> {
60        RefMut::map(self.context.borrow_mut(), |context| {
61            context.get_or_insert_with(|| {
62                let mut context =
63                    valo::Context::new(self.images.device().clone(), self.images.queue().clone());
64                context.set_hide_missing_glyphs(true);
65                context
66            })
67        })
68    }
69}
70
71/// `image`'s pixels as straight-alpha RGBA, read back with `context`, a renderer on the device the
72/// image lives on: Dart's `Image.toByteData(format: ImageByteFormat.rawStraightRgba)`. valo reads
73/// back what a picture draws, so the image is drawn into one of its size and that is read.
74///
75/// The drawing and its copy go to the GPU now, and the answer comes once the device is polled.
76/// How to wait for it is the host's, which `wait` is given the device for: a native host polls it
77/// off the main thread, on its `Dispatcher`; a browser answers on its own, so its host waits on
78/// nothing; a test polls it at once.
79pub(crate) fn read_image_pixels(
80    context: &mut valo::Context,
81    image: &Image,
82    wait: impl FnOnce(&wgpu::Device),
83) -> ImageFuture<valo::PixelBuffer> {
84    let [width, height] = image.size();
85    let mut canvas = Canvas::new();
86    let whole = Rect::from_ltwh(0.0, 0.0, f64::from(width), f64::from(height));
87    canvas.draw_image(image, whole.into(), &Paint::default());
88    let request = context.request_pixels(
89        &Arc::new(canvas.build()),
90        [width, height],
91        Some(valo::Color::TRANSPARENT),
92    );
93    wait(context.device());
94    Box::pin(async move {
95        request
96            .await
97            .map_err(|error| ImageError::new(ImageErrorKind::Other, error.to_string()))
98    })
99}
100
101impl std::fmt::Debug for SnapshotDelegate {
102    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
103        f.debug_struct("SnapshotDelegate").finish_non_exhaustive()
104    }
105}