use nadir_sys::macos::appkit::{NSAlertStyleCritical, NSApplicationActivationPolicyRegular};
use nadir_sys::macos::foundation::{NSInteger, NSUInteger};
use nadir_sys::macos::objc::{BOOL, Id, YES};
use nadir_sys::msg_send;
use super::runtime::{self, AutoreleasePool, Owned, as_id, class, ns_string, sel};
use crate::PlatformError;
pub(crate) fn alert(title: &str, message: &str) {
let _pool = AutoreleasePool::new();
if !runtime::is_main_thread() {
return;
}
let _ = show(title, message);
}
fn show(title: &str, message: &str) -> Result<(), PlatformError> {
let app =
unsafe { msg_send![as_id(class(c"NSApplication")?), sel(c"sharedApplication"), () -> Id] };
unsafe {
msg_send![
app,
sel(c"setActivationPolicy:"),
(NSApplicationActivationPolicyRegular => NSInteger) -> BOOL
]
};
unsafe { msg_send![app, sel(c"activateIgnoringOtherApps:"), (YES => BOOL) -> ()] };
let (title, message) = (ns_string(title)?, ns_string(message)?);
let alert_class = as_id(class(c"NSAlert")?);
let blank = unsafe { msg_send![alert_class, sel(c"alloc"), () -> Id] };
let alert = unsafe { msg_send![blank, sel(c"init"), () -> Id] };
let alert = unsafe { Owned::new(alert) };
if alert.id().is_null() {
return Err(PlatformError::CallFailed {
call: "-[NSAlert init]",
});
}
unsafe { msg_send![alert.id(), sel(c"setMessageText:"), (title.id() => Id) -> ()] };
unsafe { msg_send![alert.id(), sel(c"setInformativeText:"), (message.id() => Id) -> ()] };
unsafe {
msg_send![alert.id(), sel(c"setAlertStyle:"), (NSAlertStyleCritical => NSUInteger) -> ()]
};
unsafe { msg_send![alert.id(), sel(c"runModal"), () -> NSInteger] };
Ok(())
}