ferrokit_core/
snapshot.rs1use crate::ViewId;
5use crate::host::with_host;
6
7#[derive(Clone)]
9pub struct Snapshot {
10 pub width: u32,
12 pub height: u32,
14 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
24pub 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 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}