use crate::PixelFormat;
use crate::metal::Device;
use crate::metal::Texture;
use objc2::msg_send;
use objc2::rc::Retained;
use objc2::runtime::{AnyObject, ProtocolObject};
use objc2_core_graphics::{CGColorSpace, kCGColorSpaceSRGB};
use objc2_metal::{MTLDrawable, MTLPixelFormat};
use objc2_quartz_core::{CAMetalDrawable, CAMetalLayer};
use std::ffi::c_void;
pub struct Surface {
layer: Retained<CAMetalLayer>,
device: Device,
}
pub struct Drawable {
raw: Retained<ProtocolObject<dyn CAMetalDrawable>>,
pub texture: Texture,
}
impl Surface {
pub unsafe fn from_ns_view(device: &Device, ns_view: *mut c_void) -> Self {
let layer = CAMetalLayer::new();
layer.setDevice(Some(device.raw_device()));
layer.setPixelFormat(MTLPixelFormat::BGRA8Unorm);
layer.setFramebufferOnly(false);
if let Some(cs) = CGColorSpace::with_name(Some(unsafe { kCGColorSpaceSRGB })) {
layer.setColorspace(Some(&cs));
}
let view = ns_view as *mut AnyObject;
unsafe {
let _: () = msg_send![view, setWantsLayer: true];
let _: () = msg_send![view, setLayer: &*layer];
}
Self {
layer,
device: device.clone(),
}
}
pub fn resize(&self, width: u32, height: u32) {
self.layer.setDrawableSize(objc2_core_foundation::CGSize {
width: width.max(1) as f64,
height: height.max(1) as f64,
});
}
pub fn next(&self) -> Option<Drawable> {
let raw = self.layer.nextDrawable()?;
let tex = raw.texture();
let texture = self.device.wrap_texture(tex, PixelFormat::Bgra8Unorm);
Some(Drawable { raw, texture })
}
pub fn set_vsync(&self, on: bool) {
self.layer.setDisplaySyncEnabled(on);
}
}
impl Drawable {
pub(crate) fn as_mtl(&self) -> &ProtocolObject<dyn MTLDrawable> {
ProtocolObject::from_ref(&*self.raw)
}
}