use crate::macos::{Heard, heard};
use crate::macos_sys::*;
use crate::notifications::{NOTICES, Out};
use std::cell::Cell;
use std::ffi::{CStr, c_char, c_int, c_void};
const ALERTS_AND_SOUNDS: usize = 1 << 2 | 1 << 1;
const IN_FRONT: usize = 1 << 4 | 1 << 3 | 1 << 1;
unsafe extern "C" {
fn dlopen(path: *const c_char, mode: c_int) -> *mut c_void;
}
#[link(name = "System")]
unsafe extern "C" {
static _NSConcreteGlobalBlock: [usize; 0];
}
const LIVES_ON: i32 = 1 << 28;
#[repr(C)]
struct Descriptor {
reserved: usize,
size: usize,
}
#[repr(C)]
struct Block {
isa: *const c_void,
flags: i32,
reserved: i32,
invoke: *const c_void,
descriptor: *const Descriptor,
}
static DESCRIBED: Descriptor = Descriptor { reserved: 0, size: size_of::<Block>() };
thread_local! {
static CENTRE: Cell<Option<Obj>> = const { Cell::new(None) };
}
fn block(invoke: *const c_void) -> *const Block {
let isa = (&raw const _NSConcreteGlobalBlock).cast();
Box::leak(Box::new(Block { isa, flags: LIVES_ON, reserved: 0, invoke, descriptor: &DESCRIBED }))
}
fn bundled() -> bool {
unsafe { !send::<Obj>(send::<Obj>(class(c"NSBundle"), c"mainBundle", ()), c"bundleIdentifier", ()).is_null() }
}
fn centre() -> Obj {
if let Some(known) = CENTRE.get() {
return known;
}
let centre = if bundled() { opened() } else { std::ptr::null_mut() };
CENTRE.set(Some(centre));
centre
}
fn opened() -> Obj {
let path = c"/System/Library/Frameworks/UserNotifications.framework/UserNotifications";
if unsafe { dlopen(path.as_ptr(), 1) }.is_null() || class(c"UNUserNotificationCenter").is_null() {
return std::ptr::null_mut();
}
let methods: [(&CStr, *const c_void, &str); 2] = [
(c"userNotificationCenter:didReceiveNotificationResponse:withCompletionHandler:", clicked as *const c_void, "v@:@@@?"),
(c"userNotificationCenter:willPresentNotification:withCompletionHandler:", in_front as *const c_void, "v@:@@@?"),
];
add_methods(class(c"TautApplication"), &methods);
unsafe {
let centre: Obj = send(class(c"UNUserNotificationCenter"), c"currentNotificationCenter", ());
let app: Obj = send(class(c"NSApplication"), c"sharedApplication", ());
send::<()>(centre, c"setDelegate:", (send::<Obj>(app, c"delegate", ()),));
let answered = block(permitted as *const c_void);
send::<()>(centre, c"requestAuthorizationWithOptions:completionHandler:", (ALERTS_AND_SOUNDS, answered));
centre
}
}
extern "C" fn permitted(_: *const Block, _: Bool, _: Obj) {}
pub(crate) fn show(notices: Vec<Out>) {
if notices.is_empty() || centre().is_null() {
return;
}
let _pool = Pool::new();
let centre = centre();
for out in notices {
unsafe {
let content: Obj = send(made(c"UNMutableNotificationContent"), c"autorelease", ());
send::<()>(content, c"setTitle:", (ns_string(&out.title),));
send::<()>(content, c"setBody:", (ns_string(&out.text),));
if let Some(attached) = out.picture.and_then(|(width, pixels)| attachment(out.number, width, &pixels)) {
send::<()>(content, c"setAttachments:", (ns_array(&[attached]),));
}
let name = ns_string(&out.number.to_string());
let request: Obj = send(class(c"UNNotificationRequest"), c"requestWithIdentifier:content:trigger:", (name, content, std::ptr::null_mut::<c_void>()));
send::<()>(centre, c"addNotificationRequest:withCompletionHandler:", (request, std::ptr::null_mut::<c_void>()));
}
}
}
fn attachment(number: u32, width: usize, pixels: &[u32]) -> Option<Obj> {
let png = crate::png::encode_rgba(width, pixels)?;
let file = std::env::temp_dir().join(format!("taut-notification-{}-{number}.png", std::process::id()));
std::fs::write(&file, png).ok()?;
let attached: Obj = unsafe {
let address: Obj = send(class(c"NSURL"), c"fileURLWithPath:", (ns_string(&file.to_string_lossy()),));
send(class(c"UNNotificationAttachment"), c"attachmentWithIdentifier:URL:options:error:", (ns_string(""), address, std::ptr::null_mut::<c_void>(), std::ptr::null_mut::<Obj>()))
};
(!attached.is_null()).then_some(attached)
}
unsafe fn call(done: *const Block, number: usize) {
unsafe {
let invoke: extern "C" fn(*const Block, usize) = std::mem::transmute((*done).invoke);
invoke(done, number);
}
}
extern "C" fn clicked(_: Obj, _: Sel, _: Obj, response: Obj, done: *const Block) {
let named = unsafe { send::<Obj>(send::<Obj>(send::<Obj>(response, c"notification", ()), c"request", ()), c"identifier", ()) };
if let Some(number) = rust_string(named).and_then(|named| named.parse().ok()) {
NOTICES.with_borrow_mut(|notices| notices.clicked.push(number));
heard(Heard::Desktop);
}
if !done.is_null() {
unsafe { call(done, 0) };
}
}
extern "C" fn in_front(_: Obj, _: Sel, _: Obj, _: Obj, done: *const Block) {
if !done.is_null() {
unsafe { call(done, IN_FRONT) };
}
}