use core::ptr;
use objc2::runtime::AnyObject;
use objc2_app_kit::NSView;
use objc2_core_foundation::{CFData, CFRetained};
use objc2_core_graphics::{
CGBitmapInfo, CGColorRenderingIntent, CGColorSpace, CGDataProvider, CGImage, CGImageAlphaInfo,
};
use crate::render::Framebuffer;
pub(super) fn framebuffer_to_cgimage(fb: &Framebuffer) -> Option<CFRetained<CGImage>> {
let w = fb.width() as usize;
let h = fb.height() as usize;
if w == 0 || h == 0 {
return None;
}
let data = fb.pixels();
let cfdata = unsafe { CFData::new(None, data.as_ptr(), data.len() as isize) }?;
let provider = CGDataProvider::with_cf_data(Some(&cfdata))?;
let color_space = CGColorSpace::new_device_rgb()?;
let bitmap_info = CGBitmapInfo(CGImageAlphaInfo::PremultipliedLast.0);
unsafe {
CGImage::new(
w,
h,
8,
32,
w * 4,
Some(&color_space),
bitmap_info,
Some(&provider),
ptr::null(),
false,
CGColorRenderingIntent::RenderingIntentDefault,
)
}
}
pub(super) fn set_layer_contents(view: &NSView, image: &CGImage, scale: f32) {
let Some(layer) = view.layer() else {
return;
};
let obj: *const AnyObject = (image as *const CGImage).cast();
unsafe {
layer.setContents(Some(&*obj));
}
layer.setContentsScale(scale as f64);
}