use core::ffi::{c_char, c_void, CStr};
pub type Id = *mut c_void;
pub type Sel = *const c_void;
pub const NIL: Id = core::ptr::null_mut();
unsafe extern "C" {
pub fn objc_msgSend(receiver: Id, sel: Sel, ...) -> Id;
pub fn sel_registerName(name: *const c_char) -> Sel;
fn objc_getClass(name: *const c_char) -> Id;
fn objc_getProtocol(name: *const c_char) -> *mut c_void;
fn objc_allocateClassPair(sup: Id, name: *const c_char, extra: usize) -> Id;
fn objc_registerClassPair(cls: Id);
fn class_addMethod(cls: Id, sel: Sel, imp: *const c_void, types: *const c_char) -> bool;
fn class_addProtocol(cls: Id, protocol: *mut c_void) -> bool;
fn objc_retain(obj: Id) -> Id;
fn objc_release(obj: Id);
fn objc_autoreleasePoolPush() -> *mut c_void;
fn objc_autoreleasePoolPop(ctx: *mut c_void);
fn dlsym(handle: *mut c_void, symbol: *const c_char) -> *mut c_void;
}
const RTLD_DEFAULT: *mut c_void = -2isize as *mut c_void;
#[inline]
pub fn sel(name: &CStr) -> Sel {
unsafe { sel_registerName(name.as_ptr()) }
}
#[inline]
pub fn class(name: &CStr) -> Id {
unsafe { objc_getClass(name.as_ptr()) }
}
#[inline]
pub fn require_class(name: &CStr) -> Id {
let c = class(name);
assert!(!c.is_null(), "Objective-C class not found: {name:?}");
c
}
#[inline]
pub fn protocol(name: &CStr) -> *mut c_void {
unsafe { objc_getProtocol(name.as_ptr()) }
}
pub fn global_nsstring(symbol: &CStr) -> Id {
unsafe {
let p = dlsym(RTLD_DEFAULT, symbol.as_ptr());
if p.is_null() {
NIL
} else {
*(p as *const Id)
}
}
}
#[derive(Debug)]
pub struct Retained(Id);
impl Retained {
pub unsafe fn retain(ptr: Id) -> Option<Self> {
if ptr.is_null() {
return None;
}
Some(Self(unsafe { objc_retain(ptr) }))
}
pub unsafe fn adopt(ptr: Id) -> Option<Self> {
if ptr.is_null() {
return None;
}
Some(Self(ptr))
}
#[inline]
pub fn as_ptr(&self) -> Id {
self.0
}
#[inline]
pub fn key(&self) -> usize {
self.0 as usize
}
}
impl Clone for Retained {
fn clone(&self) -> Self {
Self(unsafe { objc_retain(self.0) })
}
}
impl Drop for Retained {
fn drop(&mut self) {
unsafe { objc_release(self.0) }
}
}
impl PartialEq for Retained {
fn eq(&self, other: &Self) -> bool {
self.0 == other.0
}
}
impl Eq for Retained {}
unsafe impl Send for Retained {}
unsafe impl Sync for Retained {}
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 unsafe fn nsstring(s: &str) -> Id {
unsafe {
let alloc = msg_send![require_class(c"NSString"), alloc];
type InitBytes = unsafe extern "C" fn(Id, Sel, *const u8, usize, usize) -> Id;
let f: InitBytes = core::mem::transmute(objc_msgSend as *const ());
f(
alloc,
sel(c"initWithBytes:length:encoding:"),
s.as_ptr(),
s.len(),
4,
)
}
}
pub unsafe fn to_string(s: Id) -> Option<String> {
if s.is_null() {
return None;
}
unsafe {
let c: *const c_char = msg_send_t![*const c_char; s, UTF8String];
if c.is_null() {
return None;
}
Some(CStr::from_ptr(c).to_string_lossy().into_owned())
}
}
pub unsafe fn array_count(array: Id) -> usize {
if array.is_null() {
return 0;
}
unsafe { msg_send_t![usize; array, count] }
}
pub unsafe fn array_get(array: Id, i: usize) -> Id {
unsafe { msg_send![array, objectAtIndex: i] }
}
pub unsafe fn array_map<T>(array: Id, mut f: impl FnMut(Id) -> T) -> Vec<T> {
let n = unsafe { array_count(array) };
(0..n).map(|i| f(unsafe { array_get(array, i) })).collect()
}
pub unsafe fn nsarray(items: &[Id]) -> Id {
unsafe {
type WithObjects = unsafe extern "C" fn(Id, Sel, *const Id, usize) -> Id;
let f: WithObjects = core::mem::transmute(objc_msgSend as *const ());
let arr = f(
require_class(c"NSArray"),
sel(c"arrayWithObjects:count:"),
items.as_ptr(),
items.len(),
);
objc_retain(arr)
}
}
pub unsafe fn nsdictionary(keys: &[Id], values: &[Id]) -> Option<Retained> {
debug_assert_eq!(keys.len(), values.len());
unsafe {
let k = Retained::adopt(nsarray(keys))?;
let v = Retained::adopt(nsarray(values))?;
let d: Id = msg_send![
require_class(c"NSDictionary"),
dictionaryWithObjects: v.as_ptr(),
forKeys: k.as_ptr()
];
Retained::retain(d)
}
}
pub unsafe fn dict_get(dict: Id, key: Id) -> Id {
if dict.is_null() || key.is_null() {
return NIL;
}
unsafe { msg_send![dict, objectForKey: key] }
}
pub unsafe fn dict_keys(dict: Id) -> Id {
if dict.is_null() {
return NIL;
}
unsafe { msg_send![dict, allKeys] }
}
pub unsafe fn data_bytes(data: Id) -> Option<Vec<u8>> {
if data.is_null() {
return None;
}
unsafe {
let len = msg_send_t![usize; data, length];
let ptr = msg_send_t![*const u8; data, bytes];
if ptr.is_null() || len == 0 {
return Some(Vec::new());
}
Some(core::slice::from_raw_parts(ptr, len).to_vec())
}
}
pub unsafe fn nsdata(bytes: &[u8]) -> Id {
unsafe {
let alloc = msg_send![crate::cached_class!(c"NSData"), alloc];
type InitBytes = unsafe extern "C" fn(Id, Sel, *const u8, usize) -> Id;
let f: InitBytes = core::mem::transmute(objc_msgSend as *const ());
f(
alloc,
crate::cached_sel!("initWithBytes:length:\0"),
bytes.as_ptr(),
bytes.len(),
)
}
}
pub unsafe fn number_i64(n: Id) -> Option<i64> {
if n.is_null() {
return None;
}
Some(unsafe { msg_send_t![isize; n, integerValue] } as i64)
}
pub unsafe fn number_bool(n: Id) -> Option<bool> {
if n.is_null() {
return None;
}
Some(unsafe { msg_send_t![bool; n, boolValue] })
}
pub unsafe fn error_message(err: Id) -> Option<(i64, String)> {
if err.is_null() {
return None;
}
unsafe {
let code = msg_send_t![isize; err, code] as i64;
let desc = to_string(msg_send![err, localizedDescription])
.unwrap_or_else(|| "unknown CoreBluetooth error".into());
Some((code, desc))
}
}
pub struct ClassBuilder {
class: Id,
}
impl ClassBuilder {
pub unsafe fn new(superclass: &CStr, name: &CStr) -> Option<Self> {
unsafe {
let sup = objc_getClass(superclass.as_ptr());
assert!(!sup.is_null(), "superclass not found: {superclass:?}");
let class = objc_allocateClassPair(sup, name.as_ptr(), 0);
if class.is_null() {
return None;
}
Some(Self { class })
}
}
pub unsafe fn method(self, selector: &CStr, imp: *const c_void, types: &CStr) -> Self {
unsafe {
let ok = class_addMethod(self.class, sel(selector), imp, types.as_ptr());
assert!(ok, "could not add method {selector:?}");
}
self
}
pub unsafe fn conforms(self, name: &CStr) -> Self {
unsafe {
let p = objc_getProtocol(name.as_ptr());
if !p.is_null() {
class_addProtocol(self.class, p);
}
}
self
}
pub fn register(self) -> Id {
unsafe { objc_registerClassPair(self.class) };
self.class
}
}