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