Skip to main content

ferrokit_core/
snapshot.rs

1//! Pictures of native views, for drawing in the host while the real view is
2//! hidden under a host overlay (risk 1, "snapshot in place").
3
4use crate::ViewId;
5use crate::host::with_host;
6
7/// RGBA8 pixels, unpremultiplied as AppKit returns them, at backing resolution.
8#[derive(Clone)]
9pub struct Snapshot {
10    /// Width in pixels.
11    pub width: u32,
12    /// Height in pixels.
13    pub height: u32,
14    /// Pixels, row by row from the top.
15    pub rgba: Vec<u8>,
16}
17
18impl std::fmt::Debug for Snapshot {
19    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
20        write!(f, "Snapshot({}x{})", self.width, self.height)
21    }
22}
23
24/// Renders the mounted view into a bitmap, as it currently looks.
25pub fn snapshot(id: ViewId) -> Option<Snapshot> {
26    with_host(|host| {
27        let view = &host.views.get(&id)?.view;
28        let bounds = view.bounds();
29        let rep = view.bitmapImageRepForCachingDisplayInRect(bounds)?;
30        view.cacheDisplayInRect_toBitmapImageRep(bounds, &rep);
31
32        let (w, h) = (rep.pixelsWide() as usize, rep.pixelsHigh() as usize);
33        let (bpr, spp) = (rep.bytesPerRow() as usize, rep.samplesPerPixel() as usize);
34        let data = rep.bitmapData();
35        if data.is_null() || rep.bitsPerSample() != 8 || !(3..=4).contains(&spp) {
36            return None;
37        }
38        let alpha_first = rep.bitmapFormat().contains(objc2_app_kit::NSBitmapFormat::AlphaFirst);
39        // SAFETY: bitmapData points at bytesPerRow * pixelsHigh bytes owned by `rep`.
40        let src = unsafe { std::slice::from_raw_parts(data, bpr * h) };
41        let mut rgba = Vec::with_capacity(w * h * 4);
42        for row in src.chunks(bpr).take(h) {
43            for px in row[..w * spp].chunks(spp) {
44                let (r, g, b, a) = match (spp, alpha_first) {
45                    (4, true) => (px[1], px[2], px[3], px[0]),
46                    (4, false) => (px[0], px[1], px[2], px[3]),
47                    _ => (px[0], px[1], px[2], 255),
48                };
49                rgba.extend_from_slice(&[r, g, b, a]);
50            }
51        }
52        Some(Snapshot { width: w as u32, height: h as u32, rgba })
53    })
54    .flatten()
55}