1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
//! # Interop between Metal and [`raw-window-handle`]
//!
//! Helpers for constructing a [`CAMetalLayer`] from a handle given by [`raw-window-handle`]. See
//! the [`Layer`] type for the full API.
//!
//! [`raw-window-handle`]: https://crates.io/crates/raw-window-handle
//!
//!
//! ## Example
//!
//! Create a layer from a window that implements [`HasWindowHandle`].
//!
//! ```
//! use objc2::rc::Retained;
//! use objc2_quartz_core::CAMetalLayer;
//! use raw_window_handle::{RawWindowHandle, HasWindowHandle};
//! use raw_window_metal::Layer;
//! #
//! # let mtm = objc2::MainThreadMarker::new().expect("doc tests to run on main thread");
//! #
//! # #[cfg(target_os = "macos")]
//! # let view = unsafe { objc2_app_kit::NSView::new(mtm) };
//! # #[cfg(target_os = "macos")]
//! # let handle = RawWindowHandle::AppKit(raw_window_handle::AppKitWindowHandle::new(std::ptr::NonNull::from(&*view).cast()));
//! #
//! # #[cfg(not(target_os = "macos"))]
//! # let view = unsafe { objc2_ui_kit::UIView::new(mtm) };
//! # #[cfg(not(target_os = "macos"))]
//! # let handle = RawWindowHandle::UiKit(raw_window_handle::UiKitWindowHandle::new(std::ptr::NonNull::from(&*view).cast()));
//! # let window = unsafe { raw_window_handle::WindowHandle::borrow_raw(handle) };
//!
//! let layer = match window.window_handle().expect("handle available").as_raw() {
//! // SAFETY: The handle is a valid `NSView` because it came from `WindowHandle<'_>`.
//! RawWindowHandle::AppKit(handle) => unsafe { Layer::from_ns_view(handle.ns_view) },
//! // SAFETY: The handle is a valid `UIView` because it came from `WindowHandle<'_>`.
//! RawWindowHandle::UiKit(handle) => unsafe { Layer::from_ui_view(handle.ui_view) },
//! _ => panic!("unsupported handle"),
//! };
//! let layer: *mut CAMetalLayer = layer.into_raw().as_ptr().cast();
//! // SAFETY: The pointer is a valid `CAMetalLayer`, and because we consumed `Layer` with
//! // `into_raw`, the pointer has +1 retain count.
//! let layer = unsafe { Retained::from_raw(layer).unwrap() };
//!
//! // Use `CAMetalLayer` here.
//! ```
//!
//! [`HasWindowHandle`]: https://docs.rs/raw-window-handle/0.6.2/raw_window_handle/trait.HasWindowHandle.html
//!
//!
//! ## Semantics
//!
//! As the user of this crate, you are likely creating a library yourself, and need to interface
//! with a layer provided by a windowing library like Winit or SDL.
//!
//! In that sense, when the user hands your library a view or a layer via. `raw-window-handle`, they
//! likely expect you to render into it. You should freely do that, but you should refrain from
//! doing things like resizing the layer by changing its `bounds`, changing its `contentsGravity`,
//! `opacity`, and similar such properties; semantically, these are things that are "outside" of
//! your library's control, and interferes with the platforms normal handling of such things (i.e.
//! the user creating a `MTKView`, and placing it inside a `NSStackView`. In such cases, you should
//! not change the bounds of the view, as that will be done automatically at a "higher" level).
//!
//! Properties specific to `CAMetalLayer` like `drawableSize`, `colorspace` and so on probably _are_
//! fine to change, because these are properties that the user _expects_ your library to change when
//! they've given it to you (and they won't be changed by e.g. the layer being inside a stack view).
//!
//!
//! ## Reasoning behind creating a sublayer
//!
//! If a view does not have a `CAMetalLayer` as the root layer (as is the default for most views),
//! then we're in a bit of a tricky position! We cannot use the existing layer with Metal, so we
//! must do something else. There are a few options:
//!
//! 1. Panic, and require the user to pass a view with a `CAMetalLayer` layer.
//!
//! While this would "work", it doesn't solve the problem, and instead passes the ball onwards to
//! the user and ecosystem to figure it out.
//!
//! 2. Override the existing layer with a newly created layer.
//!
//! If we overlook that this does not work in UIKit since `UIView`'s `layer` is `readonly`, and
//! that as such we will need to do something different there anyhow, this is actually a fairly
//! good solution, and was what the original implementation did.
//!
//! It has some problems though, due to:
//!
//! a. Consumers of `raw-window-metal` like Wgpu and Ash in their API design choosing not to
//! register a callback with `-[CALayerDelegate displayLayer:]`, but instead leaves it up to
//! the user to figure out when to redraw. That is, they rely on other libraries' callbacks
//! telling them when to render.
//!
//! (If you were to make an API only for Metal, you would probably make the user provide a
//! `render` closure that'd be called in the right situations).
//!
//! b. Overwriting the `layer` on `NSView` makes the view "layer-hosting", see [wantsLayer],
//! which disables drawing functionality on the view like `drawRect:`/`updateLayer`.
//!
//! These two in combination makes it basically impossible for crates like Winit to provide a
//! robust rendering callback that integrates with the system's built-in mechanisms for
//! redrawing, exactly because overwriting the layer would be disabling those mechanisms!
//!
//! [wantsLayer]: https://developer.apple.com/documentation/appkit/nsview/1483695-wantslayer?language=objc
//!
//! 3. Create a sublayer.
//!
//! `CALayer` has the concept of "sublayers", which we can use instead of overriding the layer.
//!
//! This is also the recommended solution on UIKit, so it's nice that we can use the same
//! implementation regardless of operating system.
//!
//! It _might_, however, perform ever so slightly worse than overriding the layer directly.
//!
//! 4. Create a new `MTKView` (or a custom view), and add it as a subview.
//!
//! Similar to creating a sublayer (see above), but also provides a bunch of event handling that
//! we don't need.
//!
//! Option 3 seems like the most robust solution, so this is what this crate does.
//!
//! Now we have another problem though: The `bounds` and `contentsScale` of sublayers are not
//! automatically updated from the super layer.
//!
//! We could again choose to let that be up to the user of our crate, but that would be very
//! cumbersome. Instead, this crate registers the necessary observers to make the sublayer track the
//! size and scale factor of its super layer automatically. This makes it extra important that you
//! do not modify common `CALayer` properties of the layer that `raw-window-metal` creates, since
//! they may just end up being overwritten (see also "Semantics" above).
// Update in Cargo.toml as well.
use ;
use hash;
use ;
use NonNull;
use Retained;
use AnyClass;
use ;
use ;
use ;
use crateObserverLayer;
compile_error!;
compile_error!;
/// A wrapper around [`CAMetalLayer`].
// SAFETY: `CAMetalLayer` is thread safe, like most things in Core Animation, see:
// https://developer.apple.com/documentation/quartzcore/catransaction/1448267-lock?language=objc
// https://stackoverflow.com/questions/76250226/how-to-render-content-of-calayer-on-a-background-thread
//
// TODO(madsmtm): Move this to `objc2-quartz-core`.
unsafe
// SAFETY: Same as above.
unsafe
// Layer methods may panic, but that won't leave the layer in an invalid state.
//
// TODO(madsmtm): Move this to `objc2-quartz-core`.