platform.rs

  1use super::{BoolExt as _, Dispatcher, FontSystem, Window};
  2use crate::{
  3    executor,
  4    keymap::Keystroke,
  5    platform::{self, CursorStyle},
  6    Action, ClipboardItem, Event, Menu, MenuItem,
  7};
  8use anyhow::{anyhow, Result};
  9use block::ConcreteBlock;
 10use cocoa::{
 11    appkit::{
 12        NSApplication, NSApplicationActivationPolicy::NSApplicationActivationPolicyRegular,
 13        NSEventModifierFlags, NSMenu, NSMenuItem, NSModalResponse, NSOpenPanel, NSPasteboard,
 14        NSPasteboardTypeString, NSSavePanel, NSWindow,
 15    },
 16    base::{id, nil, selector, YES},
 17    foundation::{NSArray, NSAutoreleasePool, NSBundle, NSData, NSInteger, NSString, NSURL},
 18};
 19use core_foundation::{
 20    base::{CFType, CFTypeRef, OSStatus, TCFType as _},
 21    boolean::CFBoolean,
 22    data::CFData,
 23    dictionary::{CFDictionary, CFDictionaryRef, CFMutableDictionary},
 24    string::{CFString, CFStringRef},
 25};
 26use ctor::ctor;
 27use objc::{
 28    class,
 29    declare::ClassDecl,
 30    msg_send,
 31    runtime::{Class, Object, Sel},
 32    sel, sel_impl,
 33};
 34use postage::oneshot;
 35use ptr::null_mut;
 36use std::{
 37    cell::{Cell, RefCell},
 38    convert::TryInto,
 39    ffi::{c_void, CStr, OsStr},
 40    os::{raw::c_char, unix::ffi::OsStrExt},
 41    path::{Path, PathBuf},
 42    ptr,
 43    rc::Rc,
 44    slice, str,
 45    sync::Arc,
 46};
 47use time::UtcOffset;
 48
 49const MAC_PLATFORM_IVAR: &'static str = "platform";
 50static mut APP_CLASS: *const Class = ptr::null();
 51static mut APP_DELEGATE_CLASS: *const Class = ptr::null();
 52
 53#[ctor]
 54unsafe fn build_classes() {
 55    APP_CLASS = {
 56        let mut decl = ClassDecl::new("GPUIApplication", class!(NSApplication)).unwrap();
 57        decl.add_ivar::<*mut c_void>(MAC_PLATFORM_IVAR);
 58        decl.add_method(
 59            sel!(sendEvent:),
 60            send_event as extern "C" fn(&mut Object, Sel, id),
 61        );
 62        decl.register()
 63    };
 64
 65    APP_DELEGATE_CLASS = {
 66        let mut decl = ClassDecl::new("GPUIApplicationDelegate", class!(NSResponder)).unwrap();
 67        decl.add_ivar::<*mut c_void>(MAC_PLATFORM_IVAR);
 68        decl.add_method(
 69            sel!(applicationDidFinishLaunching:),
 70            did_finish_launching as extern "C" fn(&mut Object, Sel, id),
 71        );
 72        decl.add_method(
 73            sel!(applicationDidBecomeActive:),
 74            did_become_active as extern "C" fn(&mut Object, Sel, id),
 75        );
 76        decl.add_method(
 77            sel!(applicationDidResignActive:),
 78            did_resign_active as extern "C" fn(&mut Object, Sel, id),
 79        );
 80        decl.add_method(
 81            sel!(applicationWillTerminate:),
 82            will_terminate as extern "C" fn(&mut Object, Sel, id),
 83        );
 84        decl.add_method(
 85            sel!(handleGPUIMenuItem:),
 86            handle_menu_item as extern "C" fn(&mut Object, Sel, id),
 87        );
 88        decl.add_method(
 89            sel!(application:openURLs:),
 90            open_urls as extern "C" fn(&mut Object, Sel, id, id),
 91        );
 92        decl.register()
 93    }
 94}
 95
 96#[derive(Default)]
 97pub struct MacForegroundPlatform(RefCell<MacForegroundPlatformState>);
 98
 99#[derive(Default)]
100pub struct MacForegroundPlatformState {
101    become_active: Option<Box<dyn FnMut()>>,
102    resign_active: Option<Box<dyn FnMut()>>,
103    quit: Option<Box<dyn FnMut()>>,
104    event: Option<Box<dyn FnMut(crate::Event) -> bool>>,
105    menu_command: Option<Box<dyn FnMut(&dyn Action)>>,
106    open_urls: Option<Box<dyn FnMut(Vec<String>)>>,
107    finish_launching: Option<Box<dyn FnOnce() -> ()>>,
108    menu_actions: Vec<Box<dyn Action>>,
109}
110
111impl MacForegroundPlatform {
112    unsafe fn create_menu_bar(&self, menus: Vec<Menu>) -> id {
113        let menu_bar = NSMenu::new(nil).autorelease();
114        let mut state = self.0.borrow_mut();
115
116        state.menu_actions.clear();
117
118        for menu_config in menus {
119            let menu_bar_item = NSMenuItem::new(nil).autorelease();
120            let menu = NSMenu::new(nil).autorelease();
121            let menu_name = menu_config.name;
122
123            menu.setTitle_(ns_string(menu_name));
124
125            for item_config in menu_config.items {
126                let item;
127
128                match item_config {
129                    MenuItem::Separator => {
130                        item = NSMenuItem::separatorItem(nil);
131                    }
132                    MenuItem::Action {
133                        name,
134                        keystroke,
135                        action,
136                    } => {
137                        if let Some(keystroke) = keystroke {
138                            let keystroke = Keystroke::parse(keystroke).unwrap_or_else(|err| {
139                                panic!(
140                                    "Invalid keystroke for menu item {}:{} - {:?}",
141                                    menu_name, name, err
142                                )
143                            });
144
145                            let mut mask = NSEventModifierFlags::empty();
146                            for (modifier, flag) in &[
147                                (keystroke.cmd, NSEventModifierFlags::NSCommandKeyMask),
148                                (keystroke.ctrl, NSEventModifierFlags::NSControlKeyMask),
149                                (keystroke.alt, NSEventModifierFlags::NSAlternateKeyMask),
150                            ] {
151                                if *modifier {
152                                    mask |= *flag;
153                                }
154                            }
155
156                            item = NSMenuItem::alloc(nil)
157                                .initWithTitle_action_keyEquivalent_(
158                                    ns_string(name),
159                                    selector("handleGPUIMenuItem:"),
160                                    ns_string(&keystroke.key),
161                                )
162                                .autorelease();
163                            item.setKeyEquivalentModifierMask_(mask);
164                        } else {
165                            item = NSMenuItem::alloc(nil)
166                                .initWithTitle_action_keyEquivalent_(
167                                    ns_string(name),
168                                    selector("handleGPUIMenuItem:"),
169                                    ns_string(""),
170                                )
171                                .autorelease();
172                        }
173
174                        let tag = state.menu_actions.len() as NSInteger;
175                        let _: () = msg_send![item, setTag: tag];
176                        state.menu_actions.push(action);
177                    }
178                }
179
180                menu.addItem_(item);
181            }
182
183            menu_bar_item.setSubmenu_(menu);
184            menu_bar.addItem_(menu_bar_item);
185        }
186
187        menu_bar
188    }
189}
190
191impl platform::ForegroundPlatform for MacForegroundPlatform {
192    fn on_become_active(&self, callback: Box<dyn FnMut()>) {
193        self.0.borrow_mut().become_active = Some(callback);
194    }
195
196    fn on_resign_active(&self, callback: Box<dyn FnMut()>) {
197        self.0.borrow_mut().resign_active = Some(callback);
198    }
199
200    fn on_quit(&self, callback: Box<dyn FnMut()>) {
201        self.0.borrow_mut().quit = Some(callback);
202    }
203
204    fn on_event(&self, callback: Box<dyn FnMut(crate::Event) -> bool>) {
205        self.0.borrow_mut().event = Some(callback);
206    }
207
208    fn on_open_urls(&self, callback: Box<dyn FnMut(Vec<String>)>) {
209        self.0.borrow_mut().open_urls = Some(callback);
210    }
211
212    fn run(&self, on_finish_launching: Box<dyn FnOnce() -> ()>) {
213        self.0.borrow_mut().finish_launching = Some(on_finish_launching);
214
215        unsafe {
216            let app: id = msg_send![APP_CLASS, sharedApplication];
217            let app_delegate: id = msg_send![APP_DELEGATE_CLASS, new];
218            app.setDelegate_(app_delegate);
219
220            let self_ptr = self as *const Self as *const c_void;
221            (*app).set_ivar(MAC_PLATFORM_IVAR, self_ptr);
222            (*app_delegate).set_ivar(MAC_PLATFORM_IVAR, self_ptr);
223
224            let pool = NSAutoreleasePool::new(nil);
225            app.run();
226            pool.drain();
227
228            (*app).set_ivar(MAC_PLATFORM_IVAR, null_mut::<c_void>());
229            (*app.delegate()).set_ivar(MAC_PLATFORM_IVAR, null_mut::<c_void>());
230        }
231    }
232
233    fn on_menu_command(&self, callback: Box<dyn FnMut(&dyn Action)>) {
234        self.0.borrow_mut().menu_command = Some(callback);
235    }
236
237    fn set_menus(&self, menus: Vec<Menu>) {
238        unsafe {
239            let app: id = msg_send![APP_CLASS, sharedApplication];
240            app.setMainMenu_(self.create_menu_bar(menus));
241        }
242    }
243
244    fn prompt_for_paths(
245        &self,
246        options: platform::PathPromptOptions,
247    ) -> oneshot::Receiver<Option<Vec<PathBuf>>> {
248        unsafe {
249            let panel = NSOpenPanel::openPanel(nil);
250            panel.setCanChooseDirectories_(options.directories.to_objc());
251            panel.setCanChooseFiles_(options.files.to_objc());
252            panel.setAllowsMultipleSelection_(options.multiple.to_objc());
253            panel.setResolvesAliases_(false.to_objc());
254            let (done_tx, done_rx) = oneshot::channel();
255            let done_tx = Cell::new(Some(done_tx));
256            let block = ConcreteBlock::new(move |response: NSModalResponse| {
257                let result = if response == NSModalResponse::NSModalResponseOk {
258                    let mut result = Vec::new();
259                    let urls = panel.URLs();
260                    for i in 0..urls.count() {
261                        let url = urls.objectAtIndex(i);
262                        if url.isFileURL() == YES {
263                            if let Ok(path) = ns_url_to_path(url) {
264                                result.push(path)
265                            }
266                        }
267                    }
268                    Some(result)
269                } else {
270                    None
271                };
272
273                if let Some(mut done_tx) = done_tx.take() {
274                    let _ = postage::sink::Sink::try_send(&mut done_tx, result);
275                }
276            });
277            let block = block.copy();
278            let _: () = msg_send![panel, beginWithCompletionHandler: block];
279            done_rx
280        }
281    }
282
283    fn prompt_for_new_path(&self, directory: &Path) -> oneshot::Receiver<Option<PathBuf>> {
284        unsafe {
285            let panel = NSSavePanel::savePanel(nil);
286            let path = ns_string(directory.to_string_lossy().as_ref());
287            let url = NSURL::fileURLWithPath_isDirectory_(nil, path, true.to_objc());
288            panel.setDirectoryURL(url);
289
290            let (done_tx, done_rx) = oneshot::channel();
291            let done_tx = Cell::new(Some(done_tx));
292            let block = ConcreteBlock::new(move |response: NSModalResponse| {
293                let mut result = None;
294                if response == NSModalResponse::NSModalResponseOk {
295                    let url = panel.URL();
296                    if url.isFileURL() == YES {
297                        result = ns_url_to_path(panel.URL()).ok()
298                    }
299                }
300
301                if let Some(mut done_tx) = done_tx.take() {
302                    let _ = postage::sink::Sink::try_send(&mut done_tx, result);
303                }
304            });
305            let block = block.copy();
306            let _: () = msg_send![panel, beginWithCompletionHandler: block];
307            done_rx
308        }
309    }
310}
311
312pub struct MacPlatform {
313    dispatcher: Arc<Dispatcher>,
314    fonts: Arc<FontSystem>,
315    pasteboard: id,
316    text_hash_pasteboard_type: id,
317    metadata_pasteboard_type: id,
318}
319
320impl MacPlatform {
321    pub fn new() -> Self {
322        Self {
323            dispatcher: Arc::new(Dispatcher),
324            fonts: Arc::new(FontSystem::new()),
325            pasteboard: unsafe { NSPasteboard::generalPasteboard(nil) },
326            text_hash_pasteboard_type: unsafe { ns_string("zed-text-hash") },
327            metadata_pasteboard_type: unsafe { ns_string("zed-metadata") },
328        }
329    }
330
331    unsafe fn read_from_pasteboard(&self, kind: id) -> Option<&[u8]> {
332        let data = self.pasteboard.dataForType(kind);
333        if data == nil {
334            None
335        } else {
336            Some(slice::from_raw_parts(
337                data.bytes() as *mut u8,
338                data.length() as usize,
339            ))
340        }
341    }
342}
343
344unsafe impl Send for MacPlatform {}
345unsafe impl Sync for MacPlatform {}
346
347impl platform::Platform for MacPlatform {
348    fn dispatcher(&self) -> Arc<dyn platform::Dispatcher> {
349        self.dispatcher.clone()
350    }
351
352    fn activate(&self, ignoring_other_apps: bool) {
353        unsafe {
354            let app = NSApplication::sharedApplication(nil);
355            app.activateIgnoringOtherApps_(ignoring_other_apps.to_objc());
356        }
357    }
358
359    fn open_window(
360        &self,
361        id: usize,
362        options: platform::WindowOptions,
363        executor: Rc<executor::Foreground>,
364    ) -> Box<dyn platform::Window> {
365        Box::new(Window::open(id, options, executor, self.fonts()))
366    }
367
368    fn key_window_id(&self) -> Option<usize> {
369        Window::key_window_id()
370    }
371
372    fn fonts(&self) -> Arc<dyn platform::FontSystem> {
373        self.fonts.clone()
374    }
375
376    fn quit(&self) {
377        // Quitting the app causes us to close windows, which invokes `Window::on_close` callbacks
378        // synchronously before this method terminates. If we call `Platform::quit` while holding a
379        // borrow of the app state (which most of the time we will do), we will end up
380        // double-borrowing the app state in the `on_close` callbacks for our open windows. To solve
381        // this, we make quitting the application asynchronous so that we aren't holding borrows to
382        // the app state on the stack when we actually terminate the app.
383
384        use super::dispatcher::{dispatch_async_f, dispatch_get_main_queue};
385
386        unsafe {
387            dispatch_async_f(dispatch_get_main_queue(), ptr::null_mut(), Some(quit));
388        }
389
390        unsafe extern "C" fn quit(_: *mut c_void) {
391            let app = NSApplication::sharedApplication(nil);
392            let _: () = msg_send![app, terminate: nil];
393        }
394    }
395
396    fn write_to_clipboard(&self, item: ClipboardItem) {
397        unsafe {
398            self.pasteboard.clearContents();
399
400            let text_bytes = NSData::dataWithBytes_length_(
401                nil,
402                item.text.as_ptr() as *const c_void,
403                item.text.len() as u64,
404            );
405            self.pasteboard
406                .setData_forType(text_bytes, NSPasteboardTypeString);
407
408            if let Some(metadata) = item.metadata.as_ref() {
409                let hash_bytes = ClipboardItem::text_hash(&item.text).to_be_bytes();
410                let hash_bytes = NSData::dataWithBytes_length_(
411                    nil,
412                    hash_bytes.as_ptr() as *const c_void,
413                    hash_bytes.len() as u64,
414                );
415                self.pasteboard
416                    .setData_forType(hash_bytes, self.text_hash_pasteboard_type);
417
418                let metadata_bytes = NSData::dataWithBytes_length_(
419                    nil,
420                    metadata.as_ptr() as *const c_void,
421                    metadata.len() as u64,
422                );
423                self.pasteboard
424                    .setData_forType(metadata_bytes, self.metadata_pasteboard_type);
425            }
426        }
427    }
428
429    fn read_from_clipboard(&self) -> Option<ClipboardItem> {
430        unsafe {
431            if let Some(text_bytes) = self.read_from_pasteboard(NSPasteboardTypeString) {
432                let text = String::from_utf8_lossy(&text_bytes).to_string();
433                let hash_bytes = self
434                    .read_from_pasteboard(self.text_hash_pasteboard_type)
435                    .and_then(|bytes| bytes.try_into().ok())
436                    .map(u64::from_be_bytes);
437                let metadata_bytes = self
438                    .read_from_pasteboard(self.metadata_pasteboard_type)
439                    .and_then(|bytes| String::from_utf8(bytes.to_vec()).ok());
440
441                if let Some((hash, metadata)) = hash_bytes.zip(metadata_bytes) {
442                    if hash == ClipboardItem::text_hash(&text) {
443                        Some(ClipboardItem {
444                            text,
445                            metadata: Some(metadata),
446                        })
447                    } else {
448                        Some(ClipboardItem {
449                            text,
450                            metadata: None,
451                        })
452                    }
453                } else {
454                    Some(ClipboardItem {
455                        text,
456                        metadata: None,
457                    })
458                }
459            } else {
460                None
461            }
462        }
463    }
464
465    fn open_url(&self, url: &str) {
466        unsafe {
467            let url = NSURL::alloc(nil)
468                .initWithString_(ns_string(url))
469                .autorelease();
470            let workspace: id = msg_send![class!(NSWorkspace), sharedWorkspace];
471            msg_send![workspace, openURL: url]
472        }
473    }
474
475    fn write_credentials(&self, url: &str, username: &str, password: &[u8]) -> Result<()> {
476        let url = CFString::from(url);
477        let username = CFString::from(username);
478        let password = CFData::from_buffer(password);
479
480        unsafe {
481            use security::*;
482
483            // First, check if there are already credentials for the given server. If so, then
484            // update the username and password.
485            let mut verb = "updating";
486            let mut query_attrs = CFMutableDictionary::with_capacity(2);
487            query_attrs.set(kSecClass as *const _, kSecClassInternetPassword as *const _);
488            query_attrs.set(kSecAttrServer as *const _, url.as_CFTypeRef());
489
490            let mut attrs = CFMutableDictionary::with_capacity(4);
491            attrs.set(kSecClass as *const _, kSecClassInternetPassword as *const _);
492            attrs.set(kSecAttrServer as *const _, url.as_CFTypeRef());
493            attrs.set(kSecAttrAccount as *const _, username.as_CFTypeRef());
494            attrs.set(kSecValueData as *const _, password.as_CFTypeRef());
495
496            let mut status = SecItemUpdate(
497                query_attrs.as_concrete_TypeRef(),
498                attrs.as_concrete_TypeRef(),
499            );
500
501            // If there were no existing credentials for the given server, then create them.
502            if status == errSecItemNotFound {
503                verb = "creating";
504                status = SecItemAdd(attrs.as_concrete_TypeRef(), ptr::null_mut());
505            }
506
507            if status != errSecSuccess {
508                return Err(anyhow!("{} password failed: {}", verb, status));
509            }
510        }
511        Ok(())
512    }
513
514    fn read_credentials(&self, url: &str) -> Result<Option<(String, Vec<u8>)>> {
515        let url = CFString::from(url);
516        let cf_true = CFBoolean::true_value().as_CFTypeRef();
517
518        unsafe {
519            use security::*;
520
521            // Find any credentials for the given server URL.
522            let mut attrs = CFMutableDictionary::with_capacity(5);
523            attrs.set(kSecClass as *const _, kSecClassInternetPassword as *const _);
524            attrs.set(kSecAttrServer as *const _, url.as_CFTypeRef());
525            attrs.set(kSecReturnAttributes as *const _, cf_true);
526            attrs.set(kSecReturnData as *const _, cf_true);
527
528            let mut result = CFTypeRef::from(ptr::null_mut());
529            let status = SecItemCopyMatching(attrs.as_concrete_TypeRef(), &mut result);
530            match status {
531                security::errSecSuccess => {}
532                security::errSecItemNotFound | security::errSecUserCanceled => return Ok(None),
533                _ => return Err(anyhow!("reading password failed: {}", status)),
534            }
535
536            let result = CFType::wrap_under_create_rule(result)
537                .downcast::<CFDictionary>()
538                .ok_or_else(|| anyhow!("keychain item was not a dictionary"))?;
539            let username = result
540                .find(kSecAttrAccount as *const _)
541                .ok_or_else(|| anyhow!("account was missing from keychain item"))?;
542            let username = CFType::wrap_under_get_rule(*username)
543                .downcast::<CFString>()
544                .ok_or_else(|| anyhow!("account was not a string"))?;
545            let password = result
546                .find(kSecValueData as *const _)
547                .ok_or_else(|| anyhow!("password was missing from keychain item"))?;
548            let password = CFType::wrap_under_get_rule(*password)
549                .downcast::<CFData>()
550                .ok_or_else(|| anyhow!("password was not a string"))?;
551
552            Ok(Some((username.to_string(), password.bytes().to_vec())))
553        }
554    }
555
556    fn delete_credentials(&self, url: &str) -> Result<()> {
557        let url = CFString::from(url);
558
559        unsafe {
560            use security::*;
561
562            let mut query_attrs = CFMutableDictionary::with_capacity(2);
563            query_attrs.set(kSecClass as *const _, kSecClassInternetPassword as *const _);
564            query_attrs.set(kSecAttrServer as *const _, url.as_CFTypeRef());
565
566            let status = SecItemDelete(query_attrs.as_concrete_TypeRef());
567
568            if status != errSecSuccess {
569                return Err(anyhow!("delete password failed: {}", status));
570            }
571        }
572        Ok(())
573    }
574
575    fn set_cursor_style(&self, style: CursorStyle) {
576        unsafe {
577            let cursor: id = match style {
578                CursorStyle::Arrow => msg_send![class!(NSCursor), arrowCursor],
579                CursorStyle::ResizeLeftRight => msg_send![class!(NSCursor), resizeLeftRightCursor],
580                CursorStyle::PointingHand => msg_send![class!(NSCursor), pointingHandCursor],
581            };
582            let _: () = msg_send![cursor, set];
583        }
584    }
585
586    fn local_timezone(&self) -> UtcOffset {
587        unsafe {
588            let local_timezone: id = msg_send![class!(NSTimeZone), localTimeZone];
589            let seconds_from_gmt: NSInteger = msg_send![local_timezone, secondsFromGMT];
590            UtcOffset::from_whole_seconds(seconds_from_gmt.try_into().unwrap()).unwrap()
591        }
592    }
593
594    fn path_for_auxiliary_executable(&self, name: &str) -> Result<PathBuf> {
595        unsafe {
596            let bundle: id = NSBundle::mainBundle();
597            if bundle.is_null() {
598                Err(anyhow!("app is not running inside a bundle"))
599            } else {
600                let name = ns_string(name);
601                let url: id = msg_send![bundle, URLForAuxiliaryExecutable: name];
602                if url.is_null() {
603                    Err(anyhow!("resource not found"))
604                } else {
605                    ns_url_to_path(url)
606                }
607            }
608        }
609    }
610}
611
612unsafe fn get_foreground_platform(object: &mut Object) -> &MacForegroundPlatform {
613    let platform_ptr: *mut c_void = *object.get_ivar(MAC_PLATFORM_IVAR);
614    assert!(!platform_ptr.is_null());
615    &*(platform_ptr as *const MacForegroundPlatform)
616}
617
618extern "C" fn send_event(this: &mut Object, _sel: Sel, native_event: id) {
619    unsafe {
620        if let Some(event) = Event::from_native(native_event, None) {
621            let platform = get_foreground_platform(this);
622            if let Some(callback) = platform.0.borrow_mut().event.as_mut() {
623                if callback(event) {
624                    return;
625                }
626            }
627        }
628
629        msg_send![super(this, class!(NSApplication)), sendEvent: native_event]
630    }
631}
632
633extern "C" fn did_finish_launching(this: &mut Object, _: Sel, _: id) {
634    unsafe {
635        let app: id = msg_send![APP_CLASS, sharedApplication];
636        app.setActivationPolicy_(NSApplicationActivationPolicyRegular);
637
638        let platform = get_foreground_platform(this);
639        let callback = platform.0.borrow_mut().finish_launching.take();
640        if let Some(callback) = callback {
641            callback();
642        }
643    }
644}
645
646extern "C" fn did_become_active(this: &mut Object, _: Sel, _: id) {
647    let platform = unsafe { get_foreground_platform(this) };
648    if let Some(callback) = platform.0.borrow_mut().become_active.as_mut() {
649        callback();
650    }
651}
652
653extern "C" fn did_resign_active(this: &mut Object, _: Sel, _: id) {
654    let platform = unsafe { get_foreground_platform(this) };
655    if let Some(callback) = platform.0.borrow_mut().resign_active.as_mut() {
656        callback();
657    }
658}
659
660extern "C" fn will_terminate(this: &mut Object, _: Sel, _: id) {
661    let platform = unsafe { get_foreground_platform(this) };
662    if let Some(callback) = platform.0.borrow_mut().quit.as_mut() {
663        callback();
664    }
665}
666
667extern "C" fn open_urls(this: &mut Object, _: Sel, _: id, urls: id) {
668    let urls = unsafe {
669        (0..urls.count())
670            .into_iter()
671            .filter_map(|i| {
672                let path = urls.objectAtIndex(i);
673                match CStr::from_ptr(path.absoluteString().UTF8String() as *mut c_char).to_str() {
674                    Ok(string) => Some(string.to_string()),
675                    Err(err) => {
676                        log::error!("error converting path to string: {}", err);
677                        None
678                    }
679                }
680            })
681            .collect::<Vec<_>>()
682    };
683    let platform = unsafe { get_foreground_platform(this) };
684    if let Some(callback) = platform.0.borrow_mut().open_urls.as_mut() {
685        callback(urls);
686    }
687}
688
689extern "C" fn handle_menu_item(this: &mut Object, _: Sel, item: id) {
690    unsafe {
691        let platform = get_foreground_platform(this);
692        let mut platform = platform.0.borrow_mut();
693        if let Some(mut callback) = platform.menu_command.take() {
694            let tag: NSInteger = msg_send![item, tag];
695            let index = tag as usize;
696            if let Some(action) = platform.menu_actions.get(index) {
697                callback(action.as_ref());
698            }
699            platform.menu_command = Some(callback);
700        }
701    }
702}
703
704unsafe fn ns_string(string: &str) -> id {
705    NSString::alloc(nil).init_str(string).autorelease()
706}
707
708unsafe fn ns_url_to_path(url: id) -> Result<PathBuf> {
709    let path: *mut c_char = msg_send![url, fileSystemRepresentation];
710    if path.is_null() {
711        Err(anyhow!(
712            "url is not a file path: {}",
713            CStr::from_ptr(url.absoluteString().UTF8String()).to_string_lossy()
714        ))
715    } else {
716        Ok(PathBuf::from(OsStr::from_bytes(
717            CStr::from_ptr(path).to_bytes(),
718        )))
719    }
720}
721
722mod security {
723    #![allow(non_upper_case_globals)]
724    use super::*;
725
726    #[link(name = "Security", kind = "framework")]
727    extern "C" {
728        pub static kSecClass: CFStringRef;
729        pub static kSecClassInternetPassword: CFStringRef;
730        pub static kSecAttrServer: CFStringRef;
731        pub static kSecAttrAccount: CFStringRef;
732        pub static kSecValueData: CFStringRef;
733        pub static kSecReturnAttributes: CFStringRef;
734        pub static kSecReturnData: CFStringRef;
735
736        pub fn SecItemAdd(attributes: CFDictionaryRef, result: *mut CFTypeRef) -> OSStatus;
737        pub fn SecItemUpdate(query: CFDictionaryRef, attributes: CFDictionaryRef) -> OSStatus;
738        pub fn SecItemDelete(query: CFDictionaryRef) -> OSStatus;
739        pub fn SecItemCopyMatching(query: CFDictionaryRef, result: *mut CFTypeRef) -> OSStatus;
740    }
741
742    pub const errSecSuccess: OSStatus = 0;
743    pub const errSecUserCanceled: OSStatus = -128;
744    pub const errSecItemNotFound: OSStatus = -25300;
745}
746
747#[cfg(test)]
748mod tests {
749    use crate::platform::Platform;
750
751    use super::*;
752
753    #[test]
754    fn test_clipboard() {
755        let platform = build_platform();
756        assert_eq!(platform.read_from_clipboard(), None);
757
758        let item = ClipboardItem::new("1".to_string());
759        platform.write_to_clipboard(item.clone());
760        assert_eq!(platform.read_from_clipboard(), Some(item));
761
762        let item = ClipboardItem::new("2".to_string()).with_metadata(vec![3, 4]);
763        platform.write_to_clipboard(item.clone());
764        assert_eq!(platform.read_from_clipboard(), Some(item));
765
766        let text_from_other_app = "text from other app";
767        unsafe {
768            let bytes = NSData::dataWithBytes_length_(
769                nil,
770                text_from_other_app.as_ptr() as *const c_void,
771                text_from_other_app.len() as u64,
772            );
773            platform
774                .pasteboard
775                .setData_forType(bytes, NSPasteboardTypeString);
776        }
777        assert_eq!(
778            platform.read_from_clipboard(),
779            Some(ClipboardItem::new(text_from_other_app.to_string()))
780        );
781    }
782
783    fn build_platform() -> MacPlatform {
784        let mut platform = MacPlatform::new();
785        platform.pasteboard = unsafe { NSPasteboard::pasteboardWithUniqueName(nil) };
786        platform
787    }
788}