use std::ffi::{CStr, c_char, c_void};
pub(crate) type Obj = *mut c_void;
pub(crate) type Sel = *const c_void;
pub(crate) type Bool = u8;
#[repr(C)]
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub(crate) struct NSPoint {
pub x: f64,
pub y: f64,
}
#[repr(C)]
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub(crate) struct NSSize {
pub width: f64,
pub height: f64,
}
#[repr(C)]
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub(crate) struct NSRect {
pub origin: NSPoint,
pub size: NSSize,
}
impl NSRect {
pub(crate) const fn new(x: f64, y: f64, width: f64, height: f64) -> NSRect {
NSRect { origin: NSPoint { x, y }, size: NSSize { width, height } }
}
}
#[repr(C)]
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub(crate) struct NSRange {
pub location: usize,
pub length: usize,
}
#[cfg_attr(target_os = "ios", allow(dead_code, reason = "iOS has no such part"))]
pub(crate) const NOT_FOUND: usize = isize::MAX as usize;
#[cfg(target_arch = "aarch64")]
pub(crate) const BOOL: &str = "B";
#[cfg(not(target_arch = "aarch64"))]
pub(crate) const BOOL: &str = "c";
pub(crate) const RECT: &str = "{CGRect={CGPoint=dd}{CGSize=dd}}";
pub(crate) const POINT: &str = "{CGPoint=dd}";
pub(crate) const RANGE: &str = "{_NSRange=QQ}";
#[link(name = "objc")]
unsafe extern "C" {
fn objc_getClass(name: *const c_char) -> Obj;
fn sel_registerName(name: *const c_char) -> Sel;
fn objc_msgSend();
#[cfg(target_arch = "x86_64")]
fn objc_msgSend_stret();
fn objc_allocateClassPair(superclass: Obj, name: *const c_char, extra: usize) -> Obj;
fn objc_registerClassPair(class: Obj);
fn class_addMethod(class: Obj, name: Sel, imp: *const c_void, types: *const c_char) -> Bool;
fn class_addProtocol(class: Obj, protocol: *const c_void) -> Bool;
fn objc_getProtocol(name: *const c_char) -> *const c_void;
pub(crate) fn objc_autoreleasePoolPush() -> *mut c_void;
pub(crate) fn objc_autoreleasePoolPop(pool: *mut c_void);
}
#[link(name = "Foundation", kind = "framework")]
unsafe extern "C" {}
#[link(name = "QuartzCore", kind = "framework")]
unsafe extern "C" {
pub(crate) static kCAGravityTopLeft: Obj;
}
#[cfg(target_os = "macos")]
#[link(name = "AppKit", kind = "framework")]
unsafe extern "C" {
pub(crate) static NSPasteboardTypeString: Obj;
pub(crate) static NSPasteboardTypePNG: Obj;
pub(crate) static NSPasteboardTypeTIFF: Obj;
pub(crate) static NSPasteboardTypeFileURL: Obj;
pub(crate) static NSDefaultRunLoopMode: Obj;
}
#[link(name = "CoreFoundation", kind = "framework")]
unsafe extern "C" {
pub(crate) fn CFRelease(object: *const c_void);
pub(crate) fn CFDataCreate(allocator: *const c_void, bytes: *const u8, length: isize) -> *const c_void;
pub(crate) fn CFStringCreateWithBytes(allocator: *const c_void, bytes: *const u8, length: isize, encoding: u32, external: Bool) -> *const c_void;
}
#[link(name = "CoreGraphics", kind = "framework")]
unsafe extern "C" {
pub(crate) fn CGColorSpaceCreateDeviceGray() -> *const c_void;
pub(crate) fn CGColorSpaceCreateWithName(name: *const c_void) -> *const c_void;
pub(crate) static kCGColorSpaceSRGB: *const c_void;
pub(crate) fn CGColorSpaceRelease(space: *const c_void);
pub(crate) fn CGDataProviderCreateWithCFData(data: *const c_void) -> *const c_void;
pub(crate) fn CGDataProviderRelease(provider: *const c_void);
pub(crate) fn CGImageCreate(
width: usize,
height: usize,
bits_per_component: usize,
bits_per_pixel: usize,
bytes_per_row: usize,
space: *const c_void,
info: u32,
provider: *const c_void,
decode: *const f64,
interpolate: bool,
intent: i32,
) -> *const c_void;
pub(crate) fn CGImageRelease(image: *const c_void);
pub(crate) fn CGBitmapContextCreate(data: *mut c_void, width: usize, height: usize, bits: usize, bytes_per_row: usize, space: *const c_void, info: u32) -> *mut c_void;
pub(crate) fn CGContextRelease(context: *mut c_void);
pub(crate) fn CGContextSetGrayFillColor(context: *mut c_void, gray: f64, alpha: f64);
pub(crate) fn CGContextSetShouldAntialias(context: *mut c_void, on: bool);
}
#[cfg_attr(target_os = "ios", allow(dead_code, reason = "iOS has no such part"))]
pub(crate) const PREMULTIPLIED: u32 = 2 << 12 | 2;
pub(crate) const SOLID: u32 = 2 << 12 | 6;
pub(crate) const UTF8: u32 = 0x0800_0100;
pub(crate) fn class(name: &CStr) -> Obj {
unsafe { objc_getClass(name.as_ptr()) }
}
pub(crate) fn sel(name: &CStr) -> Sel {
unsafe { sel_registerName(name.as_ptr()) }
}
pub(crate) trait Args {
unsafe fn send<R>(self, via: unsafe extern "C" fn(), to: Obj, name: Sel) -> R;
}
macro_rules! args {
($($arg:ident),*) => {
impl<$($arg),*> Args for ($($arg,)*) {
#[allow(non_snake_case)]
unsafe fn send<R>(self, via: unsafe extern "C" fn(), to: Obj, name: Sel) -> R {
let ($($arg,)*) = self;
let call = unsafe { std::mem::transmute::<unsafe extern "C" fn(), unsafe extern "C" fn(Obj, Sel $(, $arg)*) -> R>(via) };
unsafe { call(to, name $(, $arg)*) }
}
}
};
}
args!();
args!(A);
args!(A, B);
args!(A, B, C);
args!(A, B, C, D);
args!(A, B, C, D, E);
args!(A, B, C, D, E, F);
args!(A, B, C, D, E, F, G);
args!(A, B, C, D, E, F, G, H);
args!(A, B, C, D, E, F, G, H, I);
args!(A, B, C, D, E, F, G, H, I, J);
pub(crate) unsafe fn send<R>(to: Obj, name: &CStr, args: impl Args) -> R {
unsafe { args.send(objc_msgSend, to, sel(name)) }
}
pub(crate) unsafe fn send_rect(to: Obj, name: &CStr, args: impl Args) -> NSRect {
#[cfg(target_arch = "x86_64")]
let via = objc_msgSend_stret;
#[cfg(not(target_arch = "x86_64"))]
let via = objc_msgSend;
if to.is_null() { NSRect::default() } else { unsafe { args.send(via, to, sel(name)) } }
}
pub(crate) fn made_class(name: &CStr, superclass: &CStr, methods: &[(&CStr, *const c_void, &str)], protocols: &[&CStr]) -> Obj {
let known = class(name);
if !known.is_null() {
return known;
}
unsafe {
let made = objc_allocateClassPair(class(superclass), name.as_ptr(), 0);
for (name, imp, types) in methods {
let types = std::ffi::CString::new(*types).unwrap_or_default();
class_addMethod(made, sel(name), *imp, types.as_ptr());
}
for protocol in protocols {
let protocol = objc_getProtocol(protocol.as_ptr());
if !protocol.is_null() {
class_addProtocol(made, protocol);
}
}
objc_registerClassPair(made);
made
}
}
#[cfg_attr(target_os = "ios", allow(dead_code, reason = "iOS has no such part"))]
pub(crate) fn add_methods(class: Obj, methods: &[(&CStr, *const c_void, &str)]) {
for (name, imp, types) in methods {
let types = std::ffi::CString::new(*types).unwrap_or_default();
unsafe { class_addMethod(class, sel(name), *imp, types.as_ptr()) };
}
}
pub(crate) fn made(class_name: &CStr) -> Obj {
unsafe { send(send::<Obj>(class(class_name), c"alloc", ()), c"init", ()) }
}
pub(crate) fn ns_string(text: &str) -> Obj {
unsafe {
let made: Obj = send(class(c"NSString"), c"alloc", ());
let made: Obj = send(made, c"initWithBytes:length:encoding:", (text.as_ptr(), text.len(), 4usize));
send(made, c"autorelease", ())
}
}
pub(crate) fn rust_string(string: Obj) -> Option<String> {
if string.is_null() {
return None;
}
let bytes: *const c_char = unsafe { send(string, c"UTF8String", ()) };
(!bytes.is_null()).then(|| unsafe { CStr::from_ptr(bytes) }.to_string_lossy().into_owned())
}
pub(crate) fn bytes_of(data: Obj) -> Vec<u8> {
if data.is_null() {
return Vec::new();
}
unsafe {
let (at, long): (*const u8, usize) = (send(data, c"bytes", ()), send(data, c"length", ()));
if at.is_null() { Vec::new() } else { std::slice::from_raw_parts(at, long).to_vec() }
}
}
pub(crate) fn ns_data(bytes: &[u8]) -> Obj {
unsafe { send(class(c"NSData"), c"dataWithBytes:length:", (bytes.as_ptr(), bytes.len())) }
}
pub(crate) fn ns_array(objects: &[Obj]) -> Obj {
unsafe { send(class(c"NSArray"), c"arrayWithObjects:count:", (objects.as_ptr(), objects.len())) }
}
pub(crate) fn array_items(array: Obj) -> Vec<Obj> {
let count: usize = unsafe { send(array, c"count", ()) };
(0..count).map(|at| unsafe { send(array, c"objectAtIndex:", (at,)) }).collect()
}
pub(crate) struct Pool(*mut c_void);
impl Pool {
pub(crate) fn new() -> Pool {
Pool(unsafe { objc_autoreleasePoolPush() })
}
}
impl Drop for Pool {
fn drop(&mut self) {
unsafe { objc_autoreleasePoolPop(self.0) }
}
}