platform.rs

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