11#![ allow( clippy:: let_unit_value) ] // `let () =` being used to constrain result type
22
33use std:: ffi:: c_uint;
4+ use std:: mem:: ManuallyDrop ;
45use std:: ptr:: NonNull ;
56use std:: sync:: Once ;
67use std:: thread;
@@ -10,6 +11,7 @@ use core_graphics_types::{
1011 geometry:: { CGRect , CGSize } ,
1112} ;
1213use metal:: foreign_types:: ForeignType ;
14+ use objc:: rc:: StrongPtr ;
1315use objc:: {
1416 class,
1517 declare:: ClassDecl ,
@@ -81,7 +83,9 @@ impl super::Surface {
8183 delegate : Option < & HalManagedMetalLayerDelegate > ,
8284 ) -> Self {
8385 let layer = unsafe { Self :: get_metal_layer ( view, delegate) } ;
84- // SAFETY: The layer is an initialized instance of `CAMetalLayer`.
86+ let layer = ManuallyDrop :: new ( layer) ;
87+ // SAFETY: The layer is an initialized instance of `CAMetalLayer`, and
88+ // we transfer the retain count to `MetalLayer` using `ManuallyDrop`.
8589 let layer = unsafe { metal:: MetalLayer :: from_ptr ( layer. cast ( ) ) } ;
8690 let view: * mut Object = msg_send ! [ view. as_ptr( ) , retain] ;
8791 let view = NonNull :: new ( view) . expect ( "retain should return the same object" ) ;
@@ -108,7 +112,7 @@ impl super::Surface {
108112 pub ( crate ) unsafe fn get_metal_layer (
109113 view : NonNull < Object > ,
110114 delegate : Option < & HalManagedMetalLayerDelegate > ,
111- ) -> * mut Object {
115+ ) -> StrongPtr {
112116 let is_main_thread: BOOL = msg_send ! [ class!( NSThread ) , isMainThread] ;
113117 if is_main_thread == NO {
114118 panic ! ( "get_metal_layer cannot be called in non-ui thread." ) ;
@@ -142,7 +146,7 @@ impl super::Surface {
142146 // render directly into that; after all, the user passed a view
143147 // with an explicit Metal layer to us, so this is very likely what
144148 // they expect us to do.
145- root_layer
149+ unsafe { StrongPtr :: retain ( root_layer) }
146150 } else {
147151 // The view does not have a `CAMetalLayer` as the root layer (this
148152 // is the default for most views).
@@ -247,7 +251,7 @@ impl super::Surface {
247251 if let Some ( delegate) = delegate {
248252 let ( ) = msg_send ! [ new_layer, setDelegate: delegate. 0 ] ;
249253 }
250- new_layer
254+ unsafe { StrongPtr :: new ( new_layer) }
251255 }
252256 }
253257
0 commit comments