Skip to content

Use objc2 #210

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Apr 29, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 4 additions & 3 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -47,10 +47,12 @@ features = ["Win32_Graphics_Gdi", "Win32_UI_WindowsAndMessaging", "Win32_Foundat

[target.'cfg(target_os = "macos")'.dependencies]
bytemuck = { version = "1.12.3", features = ["extern_crate_alloc"] }
cocoa = "0.25.0"
core-graphics = "0.23.1"
foreign-types = "0.5.0"
objc = "0.2.7"
objc2 = "0.5.1"
objc2-foundation = { version = "0.2.0", features = ["NSThread"] }
objc2-app-kit = { version = "0.2.0", features = ["NSResponder", "NSView", "NSWindow"] }
objc2-quartz-core = { version = "0.2.0", features = ["CALayer", "CATransaction"] }

[target.'cfg(target_arch = "wasm32")'.dependencies]
js-sys = "0.3.63"
Expand Down Expand Up @@ -119,4 +121,3 @@ targets = [
"x86_64-unknown-linux-gnu",
"wasm32-unknown-unknown",
]

72 changes: 41 additions & 31 deletions src/backends/cg.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,15 @@ use core_graphics::base::{
use core_graphics::color_space::CGColorSpace;
use core_graphics::data_provider::CGDataProvider;
use core_graphics::image::CGImage;
use objc2::runtime::AnyObject;
use raw_window_handle::{HasDisplayHandle, HasWindowHandle, RawWindowHandle};

use cocoa::appkit::{NSView, NSViewHeightSizable, NSViewWidthSizable, NSWindow};
use cocoa::base::{id, nil};
use cocoa::quartzcore::{transaction, CALayer, ContentsGravity};
use foreign_types::ForeignType;
use objc2::msg_send;
use objc2::rc::Id;
use objc2_app_kit::{NSAutoresizingMaskOptions, NSView, NSWindow};
use objc2_foundation::MainThreadMarker;
use objc2_quartz_core::{kCAGravityTopLeft, CALayer, CATransaction};

use std::marker::PhantomData;
use std::num::NonZeroU32;
Expand All @@ -27,14 +30,19 @@ impl AsRef<[u8]> for Buffer {
}

pub struct CGImpl<D, W> {
layer: CALayer,
window: id,
layer: Id<CALayer>,
window: Id<NSWindow>,
color_space: CGColorSpace,
size: Option<(NonZeroU32, NonZeroU32)>,
window_handle: W,
_display: PhantomData<D>,
}

// TODO(madsmtm): Expose this in `objc2_app_kit`.
fn set_layer(view: &NSView, layer: &CALayer) {
unsafe { msg_send![view, setLayer: layer] }
}

impl<D: HasDisplayHandle, W: HasWindowHandle> SurfaceInterface<D, W> for CGImpl<D, W> {
type Context = D;
type Buffer<'a> = BufferImpl<'a, D, W> where Self: 'a;
Expand All @@ -45,24 +53,31 @@ impl<D: HasDisplayHandle, W: HasWindowHandle> SurfaceInterface<D, W> for CGImpl<
RawWindowHandle::AppKit(handle) => handle,
_ => return Err(InitError::Unsupported(window_src)),
};
let view = handle.ns_view.as_ptr() as id;
let window: id = unsafe { msg_send![view, window] };
let window: id = unsafe { msg_send![window, retain] };

let mtm =
MainThreadMarker::new().expect("can only access AppKit handles on the main thread");
let view = handle.ns_view.as_ptr();
// SAFETY: The pointer came from `WindowHandle`, which ensures that
// the `AppKitWindowHandle` contains a valid pointer to an `NSView`.
// Unwrap is fine, since the pointer came from `NonNull`.
let view: Id<NSView> = unsafe { Id::retain(view.cast()) }.unwrap();
let layer = CALayer::new();
let subview = unsafe { NSView::initWithFrame(mtm.alloc(), view.frame()) };
layer.setContentsGravity(unsafe { kCAGravityTopLeft });
layer.setNeedsDisplayOnBoundsChange(false);
set_layer(&subview, &layer);
unsafe {
let subview: id = NSView::alloc(nil).initWithFrame_(NSView::frame(view));
layer.set_contents_gravity(ContentsGravity::TopLeft);
layer.set_needs_display_on_bounds_change(false);
subview.setLayer(layer.id());
subview.setAutoresizingMask_(NSViewWidthSizable | NSViewHeightSizable);

view.addSubview_(subview); // retains subview (+1) = 2
let _: () = msg_send![subview, release]; // releases subview (-1) = 1
}
subview.setAutoresizingMask(NSAutoresizingMaskOptions(
NSAutoresizingMaskOptions::NSViewWidthSizable.0
| NSAutoresizingMaskOptions::NSViewHeightSizable.0,
))
};

unsafe { view.addSubview(&subview) };
let color_space = CGColorSpace::create_device_rgb();
Ok(Self {
layer,
window,
window: view.window().expect("view to be inside a window"),
color_space,
size: None,
_display: PhantomData,
Expand Down Expand Up @@ -131,17 +146,20 @@ impl<'a, D: HasDisplayHandle, W: HasWindowHandle> BufferInterface for BufferImpl
// The CALayer has a default action associated with a change in the layer contents, causing
// a quarter second fade transition to happen every time a new buffer is applied. This can
// be mitigated by wrapping the operation in a transaction and disabling all actions.
transaction::begin();
transaction::set_disable_actions(true);
CATransaction::begin();
CATransaction::setDisableActions(true);

self.imp
.layer
.setContentsScale(self.imp.window.backingScaleFactor());

unsafe {
self.imp
.layer
.set_contents_scale(self.imp.window.backingScaleFactor());
self.imp.layer.set_contents(image.as_ptr() as id);
.setContents((image.as_ptr() as *mut AnyObject).as_ref());
};

transaction::commit();
CATransaction::commit();

Ok(())
}
Expand All @@ -150,11 +168,3 @@ impl<'a, D: HasDisplayHandle, W: HasWindowHandle> BufferInterface for BufferImpl
self.present()
}
}

impl<D, W> Drop for CGImpl<D, W> {
fn drop(&mut self) {
unsafe {
let _: () = msg_send![self.window, release];
}
}
}
3 changes: 0 additions & 3 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,6 @@
#![warn(missing_docs)]
#![cfg_attr(docsrs, feature(doc_auto_cfg))]

#[cfg(target_os = "macos")]
#[macro_use]
extern crate objc;
extern crate core;

mod backend_dispatch;
Expand Down