use std::cell::RefCell;
use std::path::PathBuf;
use block2::RcBlock;
use objc2::MainThreadMarker;
use objc2::rc::Retained;
use objc2_app_kit::{
NSAlert, NSAlertFirstButtonReturn, NSAlertStyle, NSModalResponse, NSModalResponseOK, NSOpenPanel, NSSavePanel,
NSWindow,
};
use objc2_foundation::{NSArray, NSString, NSURL};
use crate::Window;
fn mtm() -> MainThreadMarker {
MainThreadMarker::new().expect("main thread")
}
type Pending<T> = std::rc::Rc<RefCell<Option<crate::task::Responder<T>>>>;
fn once<A: 'static>(f: impl FnOnce(A) + 'static) -> impl Fn(A) + 'static {
let cell = RefCell::new(Some(f));
move |a| {
let f = cell.borrow_mut().take();
if let Some(f) = f {
crate::failure::entry("a sheet's or panel's completion", (), || f(a));
}
}
}
pub struct Alert {
title: String,
message: String,
buttons: Vec<String>,
destructive: Option<usize>,
warning: bool,
}
impl Alert {
pub fn new(title: &str, message: &str) -> Self {
Alert { title: title.into(), message: message.into(), buttons: Vec::new(), destructive: None, warning: false }
}
pub fn button(mut self, title: &str) -> Self {
self.buttons.push(title.into());
self
}
pub fn destructive(mut self, index: usize) -> Self {
self.destructive = Some(index);
self
}
pub fn warning(mut self) -> Self {
self.warning = true;
self
}
}
pub fn alert(window: &NSWindow, alert: Alert, on_response: impl FnOnce(usize) + 'static) {
show_alert(window, alert, move |i| {
if let Some(i) = i {
on_response(i);
}
});
}
pub fn alert_async(window: &NSWindow, alert: Alert) -> crate::Answer<Option<usize>> {
let cell: Pending<Option<usize>> = std::rc::Rc::default();
let c = cell.clone();
let shown = show_alert(window, alert, move |i| {
if let Some(r) = c.borrow_mut().take() {
r.send(i);
}
});
let (parent, sheet) = (window.retain(), shown.window());
let (answer, responder) = crate::task::answer(move || end_sheet(&parent, &sheet));
*cell.borrow_mut() = Some(responder);
answer
}
fn end_sheet(parent: &NSWindow, sheet: &NSWindow) {
if parent.attachedSheet().is_some_and(|s| std::ptr::eq(&*s, sheet)) {
parent.endSheet(sheet);
}
}
fn show_alert(window: &NSWindow, alert: Alert, on_response: impl FnOnce(Option<usize>) + 'static) -> Retained<NSAlert> {
let a = NSAlert::new(mtm());
a.setMessageText(&NSString::from_str(&alert.title));
a.setInformativeText(&NSString::from_str(&alert.message));
a.setAlertStyle(if alert.warning { NSAlertStyle::Warning } else { NSAlertStyle::Informational });
for (i, title) in alert.buttons.iter().enumerate() {
let b = a.addButtonWithTitle(&NSString::from_str(title));
if alert.destructive == Some(i) {
b.setHasDestructiveAction(true);
}
}
let respond = once(on_response);
let (count, cancel) = (alert.buttons.len(), alert.buttons.iter().position(|b| b == "Cancel" || *b == crate::t("Cancel")));
let block = RcBlock::new(move |r: NSModalResponse| {
respond(usize::try_from(r - NSAlertFirstButtonReturn).ok().filter(|i| *i < count).or(cancel));
});
a.beginSheetModalForWindow_completionHandler(window, Some(&block));
a
}
#[derive(Clone)]
pub struct SheetHandle {
parent: Retained<NSWindow>,
sheet: Retained<NSWindow>,
}
impl SheetHandle {
pub fn close(&self) {
self.parent.endSheet(&self.sheet);
}
pub fn window(&self) -> Retained<NSWindow> {
self.sheet.clone()
}
}
pub fn sheet(parent: &NSWindow, content: Window, on_close: impl FnOnce() + 'static) -> SheetHandle {
let sheet = objc2::rc::autoreleasepool(|_| content.open(mtm()));
let handle = SheetHandle { parent: parent.retain(), sheet: sheet.clone() };
let closed = once(move |()| on_close());
let s = sheet.clone();
let block = RcBlock::new(move |_r: NSModalResponse| {
s.orderOut(None);
crate::teardown(&s);
closed(());
});
parent.beginSheet_completionHandler(&sheet, Some(&block));
handle
}
pub fn sheet_with(parent: &NSWindow, make: impl FnOnce() -> crate::Window, on_close: impl FnOnce() + 'static) -> SheetHandle {
let owner = crate::signal::Owner::new();
let content = owner.with(make);
let handle = sheet(parent, content, on_close);
crate::keep_until_closed(&handle.sheet, owner);
handle
}
pub struct Reply<T> {
inner: std::rc::Rc<ReplyInner<T>>,
}
struct ReplyInner<T> {
value: RefCell<Option<T>>,
handle: RefCell<Option<SheetHandle>>,
}
impl<T> Clone for Reply<T> {
fn clone(&self) -> Self {
Reply { inner: self.inner.clone() }
}
}
impl<T> std::fmt::Debug for Reply<T> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Reply").field("sent", &self.inner.value.borrow().is_some()).finish()
}
}
impl<T> Reply<T> {
pub fn send(&self, value: T) {
{
let mut v = self.inner.value.borrow_mut();
if v.is_none() {
*v = Some(value);
}
}
self.close();
}
pub fn cancel(&self) {
self.close();
}
fn close(&self) {
let handle = self.inner.handle.borrow().clone();
if let Some(h) = handle {
end_sheet(&h.parent, &h.sheet);
}
}
}
pub fn sheet_async<T: 'static>(parent: &NSWindow, make: impl FnOnce(Reply<T>) -> crate::Window) -> crate::Answer<Option<T>> {
let inner = std::rc::Rc::new(ReplyInner { value: RefCell::new(None), handle: RefCell::new(None) });
let reply = Reply { inner: inner.clone() };
let cell: Pending<Option<T>> = std::rc::Rc::default();
let (c, i) = (cell.clone(), inner.clone());
let handle = sheet_with(parent, move || make(reply), move || {
let value = i.value.borrow_mut().take();
i.handle.borrow_mut().take();
if let Some(r) = c.borrow_mut().take() {
r.send(value);
}
});
*inner.handle.borrow_mut() = Some(handle.clone());
let (answer, responder) = crate::task::answer(move || end_sheet(&handle.parent, &handle.sheet));
*cell.borrow_mut() = Some(responder);
answer
}
use objc2::Message as _;
#[derive(Debug, Clone, Default)]
#[non_exhaustive]
pub struct OpenOptions {
pub extensions: Vec<String>,
pub multiple: bool,
pub directories: bool,
}
impl OpenOptions {
pub fn new() -> Self {
Self::default()
}
pub fn extensions(mut self, extensions: &[&str]) -> Self {
self.extensions = extensions.iter().map(|e| e.to_string()).collect();
self
}
pub fn multiple(mut self) -> Self {
self.multiple = true;
self
}
pub fn directories(mut self) -> Self {
self.directories = true;
self
}
}
fn content_types(extensions: &[String]) -> Option<Retained<NSArray<objc2_uniform_type_identifiers::UTType>>> {
if extensions.is_empty() {
return None;
}
let types: Vec<_> = extensions
.iter()
.filter_map(|e| objc2_uniform_type_identifiers::UTType::typeWithFilenameExtension(&NSString::from_str(e)))
.collect();
Some(NSArray::from_retained_slice(&types))
}
pub fn open_panel(window: &NSWindow, options: OpenOptions, on_done: impl FnOnce(Option<Vec<PathBuf>>) + 'static) {
let (panel, block) = open_panel_parts(options, on_done);
panel.beginSheetModalForWindow_completionHandler(window, &block);
}
pub fn open_panel_async(window: &NSWindow, options: OpenOptions) -> crate::Answer<Option<Vec<PathBuf>>> {
let cell: Pending<Option<Vec<PathBuf>>> = std::rc::Rc::default();
let c = cell.clone();
let (panel, block) = open_panel_parts(options, move |paths| {
if let Some(r) = c.borrow_mut().take() {
r.send(paths);
}
});
panel.beginSheetModalForWindow_completionHandler(window, &block);
let (parent, sheet) = (window.retain(), Retained::into_super(Retained::into_super(panel)));
let (answer, responder) = crate::task::answer(move || end_sheet(&parent, &sheet));
*cell.borrow_mut() = Some(responder);
answer
}
pub(crate) fn open_panel_alone(options: OpenOptions, on_done: impl FnOnce(Option<Vec<PathBuf>>) + 'static) {
let (panel, block) = open_panel_parts(options, on_done);
panel.beginWithCompletionHandler(&block);
}
type PanelDone = RcBlock<dyn Fn(NSModalResponse)>;
fn open_panel_parts(options: OpenOptions, on_done: impl FnOnce(Option<Vec<PathBuf>>) + 'static) -> (Retained<NSOpenPanel>, PanelDone) {
let panel = NSOpenPanel::openPanel(mtm());
panel.setAllowsMultipleSelection(options.multiple);
panel.setCanChooseDirectories(options.directories);
panel.setCanChooseFiles(!options.directories);
if let Some(types) = content_types(&options.extensions) {
panel.setAllowedContentTypes(&types);
}
let done = once(on_done);
let p = panel.clone();
let block = RcBlock::new(move |r: NSModalResponse| {
let paths = (r == NSModalResponseOK)
.then(|| p.URLs().iter().filter_map(|u| u.path()).map(|s| PathBuf::from(s.to_string())).collect());
done(paths);
});
(panel, block)
}
pub fn save_panel(window: &NSWindow, name: &str, directory: Option<&std::path::Path>, on_done: impl FnOnce(Option<PathBuf>) + 'static) {
show_save_panel(window, name, directory, on_done);
}
pub fn save_panel_async(window: &NSWindow, name: &str, directory: Option<&std::path::Path>) -> crate::Answer<Option<PathBuf>> {
let cell: Pending<Option<PathBuf>> = std::rc::Rc::default();
let c = cell.clone();
let panel = show_save_panel(window, name, directory, move |path| {
if let Some(r) = c.borrow_mut().take() {
r.send(path);
}
});
let (parent, sheet) = (window.retain(), Retained::into_super(panel));
let (answer, responder) = crate::task::answer(move || end_sheet(&parent, &sheet));
*cell.borrow_mut() = Some(responder);
answer
}
fn show_save_panel(window: &NSWindow, name: &str, directory: Option<&std::path::Path>, on_done: impl FnOnce(Option<PathBuf>) + 'static) -> Retained<NSSavePanel> {
let panel = NSSavePanel::savePanel(mtm());
panel.setNameFieldStringValue(&NSString::from_str(name));
if let Some(dir) = directory {
let url = NSURL::fileURLWithPath(&NSString::from_str(&dir.to_string_lossy()));
panel.setDirectoryURL(Some(&url));
}
let done = once(on_done);
let p = panel.clone();
let block = RcBlock::new(move |r: NSModalResponse| {
let path = (r == NSModalResponseOK).then(|| p.URL()).flatten().and_then(|u| u.path()).map(|s| PathBuf::from(s.to_string()));
done(path);
});
panel.beginSheetModalForWindow_completionHandler(window, &block);
panel
}