use std::ffi::{c_char, c_void, CStr, CString};
#[repr(C)]
pub struct Object {
_private: [u8; 0],
}
pub type Id = *mut Object;
pub const NIL: Id = std::ptr::null_mut();
#[derive(Clone, Copy, Debug)]
#[repr(transparent)]
pub struct Sel(pub *const c_void);
pub type Bool = i8;
pub const YES: Bool = 1;
pub const NO: Bool = 0;
unsafe extern "C" {
fn pthread_main_np() -> i32;
}
pub fn is_main_thread() -> bool {
unsafe { pthread_main_np() != 0 }
}
#[link(name = "objc", kind = "dylib")]
unsafe extern "C" {
fn objc_getClass(name: *const c_char) -> Id;
fn sel_registerName(name: *const c_char) -> Sel;
fn objc_msgSend();
fn objc_retain(obj: Id) -> Id;
fn objc_release(obj: Id);
fn objc_autoreleasePoolPush() -> *mut c_void;
fn objc_autoreleasePoolPop(pool: *mut c_void);
}
pub fn get_class(name: &str) -> Id {
debug_assert!(name.ends_with('\0'), "class name must be NUL-terminated");
unsafe { objc_getClass(name.as_ptr().cast()) }
}
pub fn get_sel(name: &str) -> Sel {
debug_assert!(name.ends_with('\0'), "selector must be NUL-terminated");
unsafe { sel_registerName(name.as_ptr().cast()) }
}
macro_rules! msg_fn {
($name:ident; $($p:ident : $t:ident),*) => {
#[inline]
#[allow(clippy::too_many_arguments)] pub unsafe fn $name<R, $($t),*>(recv: Id, sel: Sel, $($p: $t),*) -> R {
let send: unsafe extern "C" fn(Id, Sel, $($t),*) -> R =
unsafe { std::mem::transmute(objc_msgSend as unsafe extern "C" fn()) };
unsafe { send(recv, sel, $($p),*) }
}
};
}
msg_fn!(msg0;);
msg_fn!(msg1; a: A);
msg_fn!(msg2; a: A, b: B);
msg_fn!(msg3; a: A, b: B, c: C);
msg_fn!(msg4; a: A, b: B, c: C, d: D);
msg_fn!(msg5; a: A, b: B, c: C, d: D, e: E);
msg_fn!(msg6; a: A, b: B, c: C, d: D, e: E, f: F);
msg_fn!(msg7; a: A, b: B, c: C, d: D, e: E, f: F, g: G);
msg_fn!(msg8; a: A, b: B, c: C, d: D, e: E, f: F, g: G, h: H);
msg_fn!(msg9; a: A, b: B, c: C, d: D, e: E, f: F, g: G, h: H, i: I);
macro_rules! sel {
($name:literal) => {{
static CACHE: ::std::sync::OnceLock<usize> = ::std::sync::OnceLock::new();
$crate::metal::objc::Sel(
*CACHE.get_or_init(|| $crate::metal::objc::get_sel(concat!($name, "\0")).0 as usize)
as *const ::std::ffi::c_void,
)
}};
}
macro_rules! class {
($name:literal) => {{
static CACHE: ::std::sync::OnceLock<usize> = ::std::sync::OnceLock::new();
*CACHE.get_or_init(|| $crate::metal::objc::get_class(concat!($name, "\0")) as usize)
as $crate::metal::objc::Id
}};
}
pub(crate) use class;
pub(crate) use sel;
pub unsafe fn alloc_init(cls: Id) -> Id {
let obj: Id = unsafe { msg0(cls, sel!("alloc")) };
unsafe { msg0(obj, sel!("init")) }
}
pub struct Owned(Id);
impl Owned {
pub unsafe fn from_retained(id: Id) -> Option<Self> {
if id.is_null() {
None
} else {
Some(Self(id))
}
}
pub unsafe fn retain(id: Id) -> Option<Self> {
if id.is_null() {
None
} else {
Some(Self(unsafe { objc_retain(id) }))
}
}
#[inline]
pub fn id(&self) -> Id {
self.0
}
}
impl Clone for Owned {
fn clone(&self) -> Self {
Self(unsafe { objc_retain(self.0) })
}
}
impl Drop for Owned {
fn drop(&mut self) {
let _pool = AutoreleasePool::new();
unsafe { objc_release(self.0) }
}
}
impl std::fmt::Debug for Owned {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "Owned({:p})", self.0)
}
}
pub struct AutoreleasePool(*mut c_void);
impl AutoreleasePool {
pub fn new() -> Self {
Self(unsafe { objc_autoreleasePoolPush() })
}
}
impl Default for AutoreleasePool {
fn default() -> Self {
Self::new()
}
}
impl Drop for AutoreleasePool {
fn drop(&mut self) {
unsafe { objc_autoreleasePoolPop(self.0) }
}
}
pub fn nsstring(s: &str) -> Id {
let Ok(c) = CString::new(s) else {
return NIL;
};
let cls = class!("NSString");
unsafe { msg1(cls, sel!("stringWithUTF8String:"), c.as_ptr()) }
}
pub unsafe fn error_message(err: Id) -> String {
if err.is_null() {
return "unknown error (nil NSError)".into();
}
let desc: Id = unsafe { msg0(err, sel!("localizedDescription")) };
if desc.is_null() {
return "unknown error (no description)".into();
}
let utf8: *const c_char = unsafe { msg0(desc, sel!("UTF8String")) };
if utf8.is_null() {
return "unknown error (no UTF-8 description)".into();
}
unsafe { CStr::from_ptr(utf8) }
.to_string_lossy()
.into_owned()
}
pub unsafe fn nsstring_to_string(s: Id) -> Option<String> {
if s.is_null() {
return None;
}
let utf8: *const c_char = unsafe { msg0(s, sel!("UTF8String")) };
if utf8.is_null() {
return None;
}
Some(unsafe { CStr::from_ptr(utf8) }.to_string_lossy().into_owned())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn selectors_and_classes_resolve() {
assert!(!get_class("NSObject\0").is_null());
assert!(!get_sel("init\0").0.is_null());
assert_eq!(get_sel("description\0").0, get_sel("description\0").0);
}
#[test]
fn unknown_class_is_nil() {
assert!(get_class("ThreersNoSuchClass\0").is_null());
}
#[test]
fn nsstring_round_trips() {
let _pool = AutoreleasePool::new();
unsafe {
let s = nsstring("metal backend");
assert_eq!(nsstring_to_string(s).as_deref(), Some("metal backend"));
}
}
#[test]
fn owned_retains_and_releases() {
let _pool = AutoreleasePool::new();
unsafe {
let obj = alloc_init(class!("NSObject"));
let owned = Owned::from_retained(obj).expect("NSObject alloc/init");
let count: usize = msg0(owned.id(), sel!("retainCount"));
let clone = owned.clone();
let after: usize = msg0(owned.id(), sel!("retainCount"));
assert_eq!(after, count + 1);
drop(clone);
let back: usize = msg0(owned.id(), sel!("retainCount"));
assert_eq!(back, count);
}
}
}