Debian Codegraph @

third_party/rust/metal/src/lib.rs

raw
1 // Copyright 2023 GFX developers
2 //
3 // Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
4 // http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
5 // http://opensource.org/licenses/MIT>, at your option. This file may not be
6 // copied, modified, or distributed except according to those terms.
7
8 #![allow(deprecated)]
9 #![allow(non_snake_case)]
10 #![allow(non_upper_case_globals)]
11 #![allow(clippy::new_without_default, clippy::new_ret_no_self)]
12
13 #[macro_use]
14 pub extern crate objc;
15 #[macro_use]
16 pub extern crate foreign_types;
17 #[macro_use]
18 pub extern crate paste;
19
20 use std::{
21 borrow::Borrow,
22 ffi::{c_char, c_void},
23 marker::PhantomData,
24 mem,
25 ops::Deref,
26 };
27
28 use core_graphics_types::{base::CGFloat, geometry::CGSize};
29 use foreign_types::ForeignType;
30 use objc::runtime::{Object, NO, YES};
31
32 /// See <https://developer.apple.com/documentation/objectivec/nsinteger>
33 #[cfg(target_pointer_width = "64")]
34 pub type NSInteger = i64;
35
36 /// See <https://developer.apple.com/documentation/objectivec/nsinteger>
37 #[cfg(not(target_pointer_width = "64"))]
38 pub type NSInteger = i32;
39
40 /// See <https://developer.apple.com/documentation/objectivec/nsuinteger>
41 #[cfg(target_pointer_width = "64")]
42 pub type NSUInteger = u64;
43
44 /// See <https://developer.apple.com/documentation/objectivec/nsuinteger>
45 #[cfg(target_pointer_width = "32")]
46 pub type NSUInteger = u32;
47
48 /// See <https://developer.apple.com/documentation/foundation/nsrange>
49 #[repr(C)]
50 #[derive(Copy, Clone)]
51 pub struct NSRange {
52 pub location: NSUInteger,
53 pub length: NSUInteger,
54 }
55
56 impl NSRange {
57 #[inline]
58 pub fn new(location: NSUInteger, length: NSUInteger) -> NSRange {
59 NSRange { location, length }
60 }
61 }
62
63 fn nsstring_as_str(nsstr: &objc::runtime::Object) -> &str {
64 let bytes = unsafe {
65 let bytes: *const c_char = msg_send![nsstr, UTF8String];
66 bytes.cast()
67 };
68 let len: NSUInteger = unsafe { msg_send![nsstr, length] };
69 unsafe {
70 let bytes = std::slice::from_raw_parts(bytes, len as usize);
71 std::str::from_utf8(bytes).unwrap()
72 }
73 }
74
75 fn nsstring_from_str(string: &str) -> *mut objc::runtime::Object {
76 const UTF8_ENCODING: usize = 4;
77
78 let cls = class!(NSString);
79 let bytes = string.as_ptr().cast::<c_void>();
80 unsafe {
81 let obj: *mut objc::runtime::Object = msg_send![cls, alloc];
82 let obj: *mut objc::runtime::Object = msg_send![
83 obj,
84 initWithBytes:bytes
85 length:string.len()
86 encoding:UTF8_ENCODING
87 ];
88 let _: *mut c_void = msg_send![obj, autorelease];
89 obj
90 }
91 }
92
93 /// Define a Rust wrapper for an Objective-C opaque type.
94 ///
95 /// This macro adapts the `foreign-types` crate's [`foreign_type!`]
96 /// macro to Objective-C, defining Rust types that represent owned and
97 /// borrowed forms of some underlying Objective-C type, using
98 /// Objective-C's reference counting to manage its lifetime.
99 ///
100 /// Given a use of the form:
101 ///
102 /// ```ignore
103 /// foreign_obj_type! {
104 /// type CType = MTLBuffer; // underlying Objective-C type
105 /// pub struct Buffer; // owned Rust type
106 /// pub struct BufferRef; // borrowed Rust type
107 /// type ParentType = ResourceRef; // borrowed parent class
108 /// }
109 /// ```
110 ///
111 /// This defines the types `Buffer` and `BufferRef` as owning and
112 /// non-owning types, analogous to `String` and `str`, that manage
113 /// some underlying `*mut MTLBuffer`:
114 ///
115 /// - Both `Buffer` and `BufferRef` implement [`obj::Message`], indicating
116 /// that they can be sent Objective-C messages.
117 ///
118 /// - Dropping a `Buffer` sends the underlying `MTLBuffer` a `release`
119 /// message, and cloning a `BufferRef` sends a `retain` message and
120 /// returns a new `Buffer`.
121 ///
122 /// - `Buffer` dereferences to `BufferRef`.
123 ///
124 /// - `BufferRef` dereferences to its parent type `ResourceRef`. The
125 /// `ParentType` component is optional; if omitted, the `Ref` type
126 /// doesn't implement `Deref` or `DerefMut`.
127 ///
128 /// - Both `Buffer` and `BufferRef` implement `std::fmt::Debug`,
129 /// sending an Objective-C `debugDescription` message to the
130 /// underlying `MTLBuffer`.
131 ///
132 /// Following the `foreign_types` crate's nomenclature, the `Ref`
133 /// suffix indicates that `BufferRef` and `ResourceRef` are non-owning
134 /// types, used *by reference*, like `&BufferRef` or `&ResourceRef`.
135 /// These types are not, themselves, references.
136 macro_rules! foreign_obj_type {
137 {
138 type CType = $raw_ident:ident;
139 pub struct $owned_ident:ident;
140 type ParentType = $parent_ident:ident;
141 } => {
142 foreign_obj_type! {
143 type CType = $raw_ident;
144 pub struct $owned_ident;
145 }
146
147 impl ::std::ops::Deref for paste!{[<$owned_ident Ref>]} {
148 type Target = paste!{[<$parent_ident Ref>]};
149
150 #[inline]
151 fn deref(&self) -> &Self::Target {
152 unsafe { std::mem::transmute(self) }
153 }
154 }
155
156 impl ::std::convert::From<$owned_ident> for $parent_ident {
157 fn from(item: $owned_ident) -> Self {
158 unsafe { Self::from_ptr(item.into_ptr().cast()) }
159 }
160 }
161 };
162 {
163 type CType = $raw_ident:ident;
164 pub struct $owned_ident:ident;
165 } => {
166 foreign_type! {
167 pub unsafe type $owned_ident: Sync + Send {
168 type CType = $raw_ident;
169 fn drop = crate::obj_drop;
170 fn clone = crate::obj_clone;
171 }
172 }
173
174 unsafe impl ::objc::Message for $raw_ident {
175 }
176 unsafe impl ::objc::Message for paste!{[<$owned_ident Ref>]} {
177 }
178
179 impl ::std::fmt::Debug for paste!{[<$owned_ident Ref>]} {
180 fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
181 unsafe {
182 let string: *mut ::objc::runtime::Object = msg_send![self, debugDescription];
183 write!(f, "{}", crate::nsstring_as_str(&*string))
184 }
185 }
186 }
187
188 impl ::std::fmt::Debug for $owned_ident {
189 fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
190 ::std::ops::Deref::deref(self).fmt(f)
191 }
192 }
193 };
194 }
195
196 macro_rules! try_objc {
197 {
198 $err_name: ident => $body:expr
199 } => {
200 {
201 let mut $err_name: *mut Object = ::std::ptr::null_mut();
202 let value = $body;
203 if !$err_name.is_null() {
204 let desc: *mut Object = msg_send![$err_name, localizedDescription];
205 let compile_error: *const c_char = msg_send![desc, UTF8String];
206 let message = CStr::from_ptr(compile_error).to_string_lossy().into_owned();
207 return Err(message);
208 }
209 value
210 }
211 };
212 }
213
214 macro_rules! msg_send_bool {
215 ($obj:expr, $name:ident) => {{
216 match msg_send![$obj, $name] {
217 YES => true,
218 NO => false,
219 #[cfg(not(target_arch = "aarch64"))]
220 _ => unreachable!(),
221 }
222 }};
223 ($obj:expr, $name:ident : $arg:expr) => {{
224 match msg_send![$obj, $name: $arg] {
225 YES => true,
226 NO => false,
227 #[cfg(not(target_arch = "aarch64"))]
228 _ => unreachable!(),
229 }
230 }};
231 }
232
233 macro_rules! msg_send_bool_error_check {
234 ($obj:expr, $name:ident: $arg:expr) => {{
235 let mut err: *mut Object = ptr::null_mut();
236 let result: BOOL = msg_send![$obj, $name:$arg
237 error:&mut err];
238 if !err.is_null() {
239 let desc: *mut Object = msg_send![err, localizedDescription];
240 let c_msg: *const c_char = msg_send![desc, UTF8String];
241 let message = CStr::from_ptr(c_msg).to_string_lossy().into_owned();
242 Err(message)
243 } else {
244 match result {
245 YES => Ok(true),
246 NO => Ok(false),
247 #[cfg(not(target_arch = "aarch64"))]
248 _ => unreachable!(),
249 }
250 }
251 }};
252 }
253
254 /// See <https://developer.apple.com/documentation/foundation/nsarray>
255 pub struct NSArray<T> {
256 _phantom: PhantomData<T>,
257 }
258
259 pub struct Array<T>(*mut NSArray<T>)
260 where
261 T: ForeignType + 'static,
262 T::Ref: objc::Message + 'static;
263
264 pub struct ArrayRef<T>(foreign_types::Opaque, PhantomData<T>)
265 where
266 T: ForeignType + 'static,
267 T::Ref: objc::Message + 'static;
268
269 impl<T> Drop for Array<T>
270 where
271 T: ForeignType + 'static,
272 T::Ref: objc::Message + 'static,
273 {
274 fn drop(&mut self) {
275 unsafe {
276 let () = msg_send![self.0, release];
277 }
278 }
279 }
280
281 impl<T> Clone for Array<T>
282 where
283 T: ForeignType + 'static,
284 T::Ref: objc::Message + 'static,
285 {
286 fn clone(&self) -> Self {
287 unsafe { Array(msg_send![self.0, retain]) }
288 }
289 }
290
291 unsafe impl<T> objc::Message for NSArray<T>
292 where
293 T: ForeignType + 'static,
294 T::Ref: objc::Message + 'static,
295 {
296 }
297
298 unsafe impl<T> objc::Message for ArrayRef<T>
299 where
300 T: ForeignType + 'static,
301 T::Ref: objc::Message + 'static,
302 {
303 }
304
305 impl<T> Array<T>
306 where
307 T: ForeignType + 'static,
308 T::Ref: objc::Message + 'static,
309 {
310 pub fn from_slice<'a>(s: &[&T::Ref]) -> &'a ArrayRef<T> {
311 unsafe {
312 let class = class!(NSArray);
313 msg_send![class, arrayWithObjects: s.as_ptr() count: s.len()]
314 }
315 }
316
317 pub fn from_owned_slice<'a>(s: &[T]) -> &'a ArrayRef<T> {
318 unsafe {
319 let class = class!(NSArray);
320 msg_send![class, arrayWithObjects: s.as_ptr() count: s.len()]
321 }
322 }
323 }
324
325 unsafe impl<T> foreign_types::ForeignType for Array<T>
326 where
327 T: ForeignType + 'static,
328 T::Ref: objc::Message + 'static,
329 {
330 type CType = NSArray<T>;
331 type Ref = ArrayRef<T>;
332
333 unsafe fn from_ptr(p: *mut NSArray<T>) -> Self {
334 Array(p)
335 }
336
337 fn as_ptr(&self) -> *mut NSArray<T> {
338 self.0
339 }
340 }
341
342 unsafe impl<T> foreign_types::ForeignTypeRef for ArrayRef<T>
343 where
344 T: ForeignType + 'static,
345 T::Ref: objc::Message + 'static,
346 {
347 type CType = NSArray<T>;
348 }
349
350 impl<T> Deref for Array<T>
351 where
352 T: ForeignType + 'static,
353 T::Ref: objc::Message + 'static,
354 {
355 type Target = ArrayRef<T>;
356
357 #[inline]
358 fn deref(&self) -> &ArrayRef<T> {
359 unsafe { std::mem::transmute(self) }
360 }
361 }
362
363 impl<T> Borrow<ArrayRef<T>> for Array<T>
364 where
365 T: ForeignType + 'static,
366 T::Ref: objc::Message + 'static,
367 {
368 fn borrow(&self) -> &ArrayRef<T> {
369 unsafe { std::mem::transmute(self) }
370 }
371 }
372
373 impl<T> ToOwned for ArrayRef<T>
374 where
375 T: ForeignType + 'static,
376 T::Ref: objc::Message + 'static,
377 {
378 type Owned = Array<T>;
379
380 fn to_owned(&self) -> Array<T> {
381 unsafe { Array::from_ptr(msg_send![self, retain]) }
382 }
383 }
384
385 /// See <https://developer.apple.com/documentation/quartzcore/cametaldrawable>
386 pub enum CAMetalDrawable {}
387
388 foreign_obj_type! {
389 type CType = CAMetalDrawable;
390 pub struct MetalDrawable;
391 type ParentType = Drawable;
392 }
393
394 impl MetalDrawableRef {
395 pub fn texture(&self) -> &TextureRef {
396 unsafe { msg_send![self, texture] }
397 }
398 }
399
400 pub enum NSObject {}
401
402 foreign_obj_type! {
403 type CType = NSObject;
404 pub struct NsObject;
405 }
406
407 impl NsObjectRef {
408 pub fn conforms_to_protocol<T>(&self) -> Result<bool, String> {
409 let name = ::std::any::type_name::<T>();
410 if let Some(name) = name.split("::").last() {
411 if let Some(protocol) = objc::runtime::Protocol::get(name) {
412 Ok(unsafe { msg_send![self, conformsToProtocol: protocol] })
413 } else {
414 Err(format!("Can not find the protocol for type: {}.", name))
415 }
416 } else {
417 Err(format!("Unexpected type name: {}.", name))
418 }
419 }
420 }
421
422 // See <https://developer.apple.com/documentation/quartzcore/cametallayer>
423 pub enum CAMetalLayer {}
424
425 foreign_obj_type! {
426 type CType = CAMetalLayer;
427 pub struct MetalLayer;
428 }
429
430 impl MetalLayer {
431 pub fn new() -> Self {
432 unsafe {
433 let class = class!(CAMetalLayer);
434 msg_send![class, new]
435 }
436 }
437 }
438
439 impl MetalLayerRef {
440 pub fn device(&self) -> &DeviceRef {
441 unsafe { msg_send![self, device] }
442 }
443
444 pub fn set_device(&self, device: &DeviceRef) {
445 unsafe { msg_send![self, setDevice: device] }
446 }
447
448 pub fn pixel_format(&self) -> MTLPixelFormat {
449 unsafe { msg_send![self, pixelFormat] }
450 }
451
452 pub fn set_pixel_format(&self, pixel_format: MTLPixelFormat) {
453 unsafe { msg_send![self, setPixelFormat: pixel_format] }
454 }
455
456 pub fn drawable_size(&self) -> CGSize {
457 unsafe { msg_send![self, drawableSize] }
458 }
459
460 pub fn set_drawable_size(&self, size: CGSize) {
461 unsafe { msg_send![self, setDrawableSize: size] }
462 }
463
464 pub fn presents_with_transaction(&self) -> bool {
465 unsafe { msg_send_bool![self, presentsWithTransaction] }
466 }
467
468 pub fn set_presents_with_transaction(&self, transaction: bool) {
469 unsafe { msg_send![self, setPresentsWithTransaction: transaction] }
470 }
471
472 pub fn display_sync_enabled(&self) -> bool {
473 unsafe { msg_send_bool![self, displaySyncEnabled] }
474 }
475
476 pub fn set_display_sync_enabled(&self, enabled: bool) {
477 unsafe { msg_send![self, setDisplaySyncEnabled: enabled] }
478 }
479
480 pub fn maximum_drawable_count(&self) -> NSUInteger {
481 unsafe { msg_send![self, maximumDrawableCount] }
482 }
483
484 pub fn set_maximum_drawable_count(&self, count: NSUInteger) {
485 unsafe { msg_send![self, setMaximumDrawableCount: count] }
486 }
487
488 pub fn set_edge_antialiasing_mask(&self, mask: u64) {
489 unsafe { msg_send![self, setEdgeAntialiasingMask: mask] }
490 }
491
492 pub fn set_masks_to_bounds(&self, masks: bool) {
493 unsafe { msg_send![self, setMasksToBounds: masks] }
494 }
495
496 pub fn remove_all_animations(&self) {
497 unsafe { msg_send![self, removeAllAnimations] }
498 }
499
500 pub fn next_drawable(&self) -> Option<&MetalDrawableRef> {
501 unsafe { msg_send![self, nextDrawable] }
502 }
503
504 pub fn contents_scale(&self) -> CGFloat {
505 unsafe { msg_send![self, contentsScale] }
506 }
507
508 pub fn set_contents_scale(&self, scale: CGFloat) {
509 unsafe { msg_send![self, setContentsScale: scale] }
510 }
511
512 /// [framebufferOnly Apple Docs](https://developer.apple.com/documentation/metal/mtltexture/1515749-framebufferonly?language=objc)
513 pub fn framebuffer_only(&self) -> bool {
514 unsafe { msg_send_bool!(self, framebufferOnly) }
515 }
516
517 pub fn set_framebuffer_only(&self, framebuffer_only: bool) {
518 unsafe { msg_send![self, setFramebufferOnly: framebuffer_only] }
519 }
520
521 pub fn is_opaque(&self) -> bool {
522 unsafe { msg_send_bool!(self, isOpaque) }
523 }
524
525 pub fn set_opaque(&self, opaque: bool) {
526 unsafe { msg_send![self, setOpaque: opaque] }
527 }
528
529 pub fn wants_extended_dynamic_range_content(&self) -> bool {
530 unsafe { msg_send_bool![self, wantsExtendedDynamicRangeContent] }
531 }
532
533 pub fn set_wants_extended_dynamic_range_content(
534 &self,
535 wants_extended_dynamic_range_content: bool,
536 ) {
537 unsafe {
538 msg_send![
539 self,
540 setWantsExtendedDynamicRangeContent: wants_extended_dynamic_range_content
541 ]
542 }
543 }
544 }
545
546 mod acceleration_structure;
547 mod acceleration_structure_pass;
548 mod argument;
549 mod blitpass;
550 mod buffer;
551 mod capturedescriptor;
552 mod capturemanager;
553 mod commandbuffer;
554 mod commandqueue;
555 mod computepass;
556 mod constants;
557 mod counters;
558 mod depthstencil;
559 mod device;
560 mod drawable;
561 mod encoder;
562 mod heap;
563 mod indirect_encoder;
564 mod library;
565 #[cfg(feature = "mps")]
566 pub mod mps;
567 mod pipeline;
568 mod renderpass;
569 mod resource;
570 mod sampler;
571 mod sync;
572 mod texture;
573 mod types;
574 mod vertexdescriptor;
575
576 #[rustfmt::skip]
577 pub use {
578 acceleration_structure::*,
579 acceleration_structure_pass::*,
580 argument::*,
581 blitpass::*,
582 buffer::*,
583 counters::*,
584 computepass::*,
585 capturedescriptor::*,
586 capturemanager::*,
587 commandbuffer::*,
588 commandqueue::*,
589 constants::*,
590 depthstencil::*,
591 device::*,
592 drawable::*,
593 encoder::*,
594 heap::*,
595 indirect_encoder::*,
596 library::*,
597 pipeline::*,
598 renderpass::*,
599 resource::*,
600 sampler::*,
601 texture::*,
602 types::*,
603 vertexdescriptor::*,
604 sync::*,
605 };
606
607 #[inline]
608 unsafe fn obj_drop<T>(p: *mut T) {
609 msg_send![p.cast::<Object>(), release]
610 }
611
612 #[inline]
613 unsafe fn obj_clone<T: 'static>(p: *mut T) -> *mut T {
614 msg_send![p.cast::<Object>(), retain]
615 }
616
617 #[allow(non_camel_case_types)]
618 type c_size_t = usize;
619
620 // TODO: expand supported interface
621 /// See <https://developer.apple.com/documentation/foundation/nsurl>
622 pub enum NSURL {}
623
624 foreign_obj_type! {
625 type CType = NSURL;
626 pub struct URL;
627 }
628
629 impl URL {
630 pub fn new_with_string(string: &str) -> Self {
631 unsafe {
632 let ns_str = crate::nsstring_from_str(string);
633 let class = class!(NSURL);
634 msg_send![class, URLWithString: ns_str]
635 }
636 }
637 }
638
639 impl URLRef {
640 pub fn absolute_string(&self) -> &str {
641 unsafe {
642 let absolute_string = msg_send![self, absoluteString];
643 crate::nsstring_as_str(absolute_string)
644 }
645 }
646
647 pub fn path(&self) -> &str {
648 unsafe {
649 let path = msg_send![self, path];
650 crate::nsstring_as_str(path)
651 }
652 }
653 }