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