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
use std::convert::TryFrom;
use webkit2gtk::{SnapshotOptions, SnapshotRegion, WebView, WebViewExt, LoadEvent};
use cairo::{ImageSurface, Format};
use image::{ImageBuffer, DynamicImage, RgbaImage};

// TODO: Remove all `unwrap`s

pub trait WebViewSnapshotListener {
    fn page_load_snapshot_listener<F: 'static + FnMut(RgbaImage) + Send + Clone>(&self, callback: F) -> &Self;
}

impl WebViewSnapshotListener for WebView {
    fn page_load_snapshot_listener<F: 'static + FnMut(RgbaImage) + Send + Clone>(&self, callback: F) -> &Self {
        self.connect_load_changed(move |wv, load_event| {
            if load_event != LoadEvent::Finished {
                return;
            }

            let mut callback = callback.clone();
            wv.get_snapshot(
                SnapshotRegion::FullDocument,
                SnapshotOptions::empty(),
                None::<&gio::Cancellable>,
                move |snapshot| {
                    let surface = snapshot.unwrap();
                    let mut image_surface = ImageSurface::try_from(surface).unwrap();

                    let format = image_surface.get_format();
                    if format != Format::ARgb32 {
                        unimplemented!("Not implemented for image type {:?} yet", format)
                    }

                    let width = image_surface.get_width() as u32;
                    let height = image_surface.get_height() as u32;
                    let data = image_surface.get_data().unwrap().to_vec();

                    let image = DynamicImage::ImageBgra8(ImageBuffer::from_vec(width, height, data).unwrap()).to_rgba();

                    callback(image);
                },
            );
        });

        self
    }
}