platform.rs

  1use super::{BoolExt as _, Dispatcher, FontSystem, Window};
  2use crate::{
  3    executor, keymap,
  4    platform::{self, CursorStyle},
  5    Action, ClipboardItem, Event, Menu, MenuItem,
  6};
  7use anyhow::{anyhow, Result};
  8use block::ConcreteBlock;
  9use cocoa::{
 10    appkit::{
 11        NSApplication, NSApplicationActivationPolicy::NSApplicationActivationPolicyRegular,
 12        NSEventModifierFlags, NSMenu, NSMenuItem, NSModalResponse, NSOpenPanel, NSPasteboard,
 13        NSPasteboardTypeString, NSSavePanel, NSWindow,
 14    },
 15    base::{id, nil, selector, YES},
 16    foundation::{
 17        NSArray, NSAutoreleasePool, NSBundle, NSData, NSInteger, NSString, NSUInteger, NSURL,
 18    },
 19};
 20use core_foundation::{
 21    base::{CFType, CFTypeRef, OSStatus, TCFType as _},
 22    boolean::CFBoolean,
 23    data::CFData,
 24    dictionary::{CFDictionary, CFDictionaryRef, CFMutableDictionary},
 25    string::{CFString, CFStringRef},
 26};
 27use ctor::ctor;
 28use objc::{
 29    class,
 30    declare::ClassDecl,
 31    msg_send,
 32    runtime::{Class, Object, Sel},
 33    sel, sel_impl,
 34};
 35use postage::oneshot;
 36use ptr::null_mut;
 37use std::{
 38    cell::{Cell, RefCell},
 39    convert::TryInto,
 40    ffi::{c_void, CStr, OsStr},
 41    os::{raw::c_char, unix::ffi::OsStrExt},
 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!(validateMenuItem:),
 94            validate_menu_item as extern "C" fn(&mut Object, Sel, id) -> bool,
 95        );
 96        decl.add_method(
 97            sel!(application:openURLs:),
 98            open_urls as extern "C" fn(&mut Object, Sel, id, id),
 99        );
100        decl.register()
101    }
102}
103
104#[derive(Default)]
105pub struct MacForegroundPlatform(RefCell<MacForegroundPlatformState>);
106
107#[derive(Default)]
108pub struct MacForegroundPlatformState {
109    become_active: Option<Box<dyn FnMut()>>,
110    resign_active: Option<Box<dyn FnMut()>>,
111    quit: Option<Box<dyn FnMut()>>,
112    event: Option<Box<dyn FnMut(crate::Event) -> bool>>,
113    menu_command: Option<Box<dyn FnMut(&dyn Action)>>,
114    validate_menu_command: Option<Box<dyn FnMut(&dyn Action) -> bool>>,
115    open_urls: Option<Box<dyn FnMut(Vec<String>)>>,
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>, keystroke_matcher: &keymap::Matcher) -> 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 { name, action } => {
142                        let mut keystroke = None;
143                        if let Some(binding) = keystroke_matcher
144                            .bindings_for_action_type(action.as_any().type_id())
145                            .next()
146                        {
147                            if binding.keystrokes().len() == 1 {
148                                keystroke = binding.keystrokes().first()
149                            }
150                        }
151
152                        if let Some(keystroke) = keystroke {
153                            let mut mask = NSEventModifierFlags::empty();
154                            for (modifier, flag) in &[
155                                (keystroke.cmd, NSEventModifierFlags::NSCommandKeyMask),
156                                (keystroke.ctrl, NSEventModifierFlags::NSControlKeyMask),
157                                (keystroke.alt, NSEventModifierFlags::NSAlternateKeyMask),
158                            ] {
159                                if *modifier {
160                                    mask |= *flag;
161                                }
162                            }
163
164                            item = NSMenuItem::alloc(nil)
165                                .initWithTitle_action_keyEquivalent_(
166                                    ns_string(name),
167                                    selector("handleGPUIMenuItem:"),
168                                    ns_string(&keystroke.key),
169                                )
170                                .autorelease();
171                            item.setKeyEquivalentModifierMask_(mask);
172                        } else {
173                            item = NSMenuItem::alloc(nil)
174                                .initWithTitle_action_keyEquivalent_(
175                                    ns_string(name),
176                                    selector("handleGPUIMenuItem:"),
177                                    ns_string(""),
178                                )
179                                .autorelease();
180                        }
181
182                        let tag = state.menu_actions.len() as NSInteger;
183                        let _: () = msg_send![item, setTag: tag];
184                        state.menu_actions.push(action);
185                    }
186                }
187
188                menu.addItem_(item);
189            }
190
191            menu_bar_item.setSubmenu_(menu);
192            menu_bar.addItem_(menu_bar_item);
193        }
194
195        menu_bar
196    }
197}
198
199impl platform::ForegroundPlatform for MacForegroundPlatform {
200    fn on_become_active(&self, callback: Box<dyn FnMut()>) {
201        self.0.borrow_mut().become_active = Some(callback);
202    }
203
204    fn on_resign_active(&self, callback: Box<dyn FnMut()>) {
205        self.0.borrow_mut().resign_active = Some(callback);
206    }
207
208    fn on_quit(&self, callback: Box<dyn FnMut()>) {
209        self.0.borrow_mut().quit = Some(callback);
210    }
211
212    fn on_event(&self, callback: Box<dyn FnMut(crate::Event) -> bool>) {
213        self.0.borrow_mut().event = Some(callback);
214    }
215
216    fn on_open_urls(&self, callback: Box<dyn FnMut(Vec<String>)>) {
217        self.0.borrow_mut().open_urls = Some(callback);
218    }
219
220    fn run(&self, on_finish_launching: Box<dyn FnOnce() -> ()>) {
221        self.0.borrow_mut().finish_launching = Some(on_finish_launching);
222
223        unsafe {
224            let app: id = msg_send![APP_CLASS, sharedApplication];
225            let app_delegate: id = msg_send![APP_DELEGATE_CLASS, new];
226            app.setDelegate_(app_delegate);
227
228            let self_ptr = self as *const Self as *const c_void;
229            (*app).set_ivar(MAC_PLATFORM_IVAR, self_ptr);
230            (*app_delegate).set_ivar(MAC_PLATFORM_IVAR, self_ptr);
231
232            let pool = NSAutoreleasePool::new(nil);
233            app.run();
234            pool.drain();
235
236            (*app).set_ivar(MAC_PLATFORM_IVAR, null_mut::<c_void>());
237            (*app.delegate()).set_ivar(MAC_PLATFORM_IVAR, null_mut::<c_void>());
238        }
239    }
240
241    fn on_menu_command(&self, callback: Box<dyn FnMut(&dyn Action)>) {
242        self.0.borrow_mut().menu_command = Some(callback);
243    }
244
245    fn on_validate_menu_command(&self, callback: Box<dyn FnMut(&dyn Action) -> bool>) {
246        self.0.borrow_mut().validate_menu_command = Some(callback);
247    }
248
249    fn set_menus(&self, menus: Vec<Menu>, keystroke_matcher: &keymap::Matcher) {
250        unsafe {
251            let app: id = msg_send![APP_CLASS, sharedApplication];
252            app.setMainMenu_(self.create_menu_bar(menus, keystroke_matcher));
253        }
254    }
255
256    fn prompt_for_paths(
257        &self,
258        options: platform::PathPromptOptions,
259    ) -> oneshot::Receiver<Option<Vec<PathBuf>>> {
260        unsafe {
261            let panel = NSOpenPanel::openPanel(nil);
262            panel.setCanChooseDirectories_(options.directories.to_objc());
263            panel.setCanChooseFiles_(options.files.to_objc());
264            panel.setAllowsMultipleSelection_(options.multiple.to_objc());
265            panel.setResolvesAliases_(false.to_objc());
266            let (done_tx, done_rx) = oneshot::channel();
267            let done_tx = Cell::new(Some(done_tx));
268            let block = ConcreteBlock::new(move |response: NSModalResponse| {
269                let result = if response == NSModalResponse::NSModalResponseOk {
270                    let mut result = Vec::new();
271                    let urls = panel.URLs();
272                    for i in 0..urls.count() {
273                        let url = urls.objectAtIndex(i);
274                        if url.isFileURL() == YES {
275                            if let Ok(path) = ns_url_to_path(url) {
276                                result.push(path)
277                            }
278                        }
279                    }
280                    Some(result)
281                } else {
282                    None
283                };
284
285                if let Some(mut done_tx) = done_tx.take() {
286                    let _ = postage::sink::Sink::try_send(&mut done_tx, result);
287                }
288            });
289            let block = block.copy();
290            let _: () = msg_send![panel, beginWithCompletionHandler: block];
291            done_rx
292        }
293    }
294
295    fn prompt_for_new_path(&self, directory: &Path) -> oneshot::Receiver<Option<PathBuf>> {
296        unsafe {
297            let panel = NSSavePanel::savePanel(nil);
298            let path = ns_string(directory.to_string_lossy().as_ref());
299            let url = NSURL::fileURLWithPath_isDirectory_(nil, path, true.to_objc());
300            panel.setDirectoryURL(url);
301
302            let (done_tx, done_rx) = oneshot::channel();
303            let done_tx = Cell::new(Some(done_tx));
304            let block = ConcreteBlock::new(move |response: NSModalResponse| {
305                let mut result = None;
306                if response == NSModalResponse::NSModalResponseOk {
307                    let url = panel.URL();
308                    if url.isFileURL() == YES {
309                        result = ns_url_to_path(panel.URL()).ok()
310                    }
311                }
312
313                if let Some(mut done_tx) = done_tx.take() {
314                    let _ = postage::sink::Sink::try_send(&mut done_tx, result);
315                }
316            });
317            let block = block.copy();
318            let _: () = msg_send![panel, beginWithCompletionHandler: block];
319            done_rx
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                CursorStyle::IBeam => msg_send![class!(NSCursor), IBeamCursor],
594            };
595            let _: () = msg_send![cursor, set];
596        }
597    }
598
599    fn local_timezone(&self) -> UtcOffset {
600        unsafe {
601            let local_timezone: id = msg_send![class!(NSTimeZone), localTimeZone];
602            let seconds_from_gmt: NSInteger = msg_send![local_timezone, secondsFromGMT];
603            UtcOffset::from_whole_seconds(seconds_from_gmt.try_into().unwrap()).unwrap()
604        }
605    }
606
607    fn path_for_auxiliary_executable(&self, name: &str) -> Result<PathBuf> {
608        unsafe {
609            let bundle: id = NSBundle::mainBundle();
610            if bundle.is_null() {
611                Err(anyhow!("app is not running inside a bundle"))
612            } else {
613                let name = ns_string(name);
614                let url: id = msg_send![bundle, URLForAuxiliaryExecutable: name];
615                if url.is_null() {
616                    Err(anyhow!("resource not found"))
617                } else {
618                    ns_url_to_path(url)
619                }
620            }
621        }
622    }
623
624    fn app_path(&self) -> Result<PathBuf> {
625        unsafe {
626            let bundle: id = NSBundle::mainBundle();
627            if bundle.is_null() {
628                Err(anyhow!("app is not running inside a bundle"))
629            } else {
630                Ok(path_from_objc(msg_send![bundle, bundlePath]))
631            }
632        }
633    }
634
635    fn app_version(&self) -> Result<platform::AppVersion> {
636        unsafe {
637            let bundle: id = NSBundle::mainBundle();
638            if bundle.is_null() {
639                Err(anyhow!("app is not running inside a bundle"))
640            } else {
641                let version: id = msg_send![bundle, objectForInfoDictionaryKey: ns_string("CFBundleShortVersionString")];
642                let len = msg_send![version, lengthOfBytesUsingEncoding: NSUTF8StringEncoding];
643                let bytes = version.UTF8String() as *const u8;
644                let version = str::from_utf8(slice::from_raw_parts(bytes, len)).unwrap();
645                version.parse()
646            }
647        }
648    }
649}
650
651unsafe fn path_from_objc(path: id) -> PathBuf {
652    let len = msg_send![path, lengthOfBytesUsingEncoding: NSUTF8StringEncoding];
653    let bytes = path.UTF8String() as *const u8;
654    let path = str::from_utf8(slice::from_raw_parts(bytes, len)).unwrap();
655    PathBuf::from(path)
656}
657
658unsafe fn get_foreground_platform(object: &mut Object) -> &MacForegroundPlatform {
659    let platform_ptr: *mut c_void = *object.get_ivar(MAC_PLATFORM_IVAR);
660    assert!(!platform_ptr.is_null());
661    &*(platform_ptr as *const MacForegroundPlatform)
662}
663
664extern "C" fn send_event(this: &mut Object, _sel: Sel, native_event: id) {
665    unsafe {
666        if let Some(event) = Event::from_native(native_event, None) {
667            let platform = get_foreground_platform(this);
668            if let Some(callback) = platform.0.borrow_mut().event.as_mut() {
669                if callback(event) {
670                    return;
671                }
672            }
673        }
674
675        msg_send![super(this, class!(NSApplication)), sendEvent: native_event]
676    }
677}
678
679extern "C" fn did_finish_launching(this: &mut Object, _: Sel, _: id) {
680    unsafe {
681        let app: id = msg_send![APP_CLASS, sharedApplication];
682        app.setActivationPolicy_(NSApplicationActivationPolicyRegular);
683
684        let platform = get_foreground_platform(this);
685        let callback = platform.0.borrow_mut().finish_launching.take();
686        if let Some(callback) = callback {
687            callback();
688        }
689    }
690}
691
692extern "C" fn did_become_active(this: &mut Object, _: Sel, _: id) {
693    let platform = unsafe { get_foreground_platform(this) };
694    if let Some(callback) = platform.0.borrow_mut().become_active.as_mut() {
695        callback();
696    }
697}
698
699extern "C" fn did_resign_active(this: &mut Object, _: Sel, _: id) {
700    let platform = unsafe { get_foreground_platform(this) };
701    if let Some(callback) = platform.0.borrow_mut().resign_active.as_mut() {
702        callback();
703    }
704}
705
706extern "C" fn will_terminate(this: &mut Object, _: Sel, _: id) {
707    let platform = unsafe { get_foreground_platform(this) };
708    if let Some(callback) = platform.0.borrow_mut().quit.as_mut() {
709        callback();
710    }
711}
712
713extern "C" fn open_urls(this: &mut Object, _: Sel, _: id, urls: id) {
714    let urls = unsafe {
715        (0..urls.count())
716            .into_iter()
717            .filter_map(|i| {
718                let path = urls.objectAtIndex(i);
719                match CStr::from_ptr(path.absoluteString().UTF8String() as *mut c_char).to_str() {
720                    Ok(string) => Some(string.to_string()),
721                    Err(err) => {
722                        log::error!("error converting path to string: {}", err);
723                        None
724                    }
725                }
726            })
727            .collect::<Vec<_>>()
728    };
729    let platform = unsafe { get_foreground_platform(this) };
730    if let Some(callback) = platform.0.borrow_mut().open_urls.as_mut() {
731        callback(urls);
732    }
733}
734
735extern "C" fn handle_menu_item(this: &mut Object, _: Sel, item: id) {
736    unsafe {
737        let platform = get_foreground_platform(this);
738        let mut platform = platform.0.borrow_mut();
739        if let Some(mut callback) = platform.menu_command.take() {
740            let tag: NSInteger = msg_send![item, tag];
741            let index = tag as usize;
742            if let Some(action) = platform.menu_actions.get(index) {
743                callback(action.as_ref());
744            }
745            platform.menu_command = Some(callback);
746        }
747    }
748}
749
750extern "C" fn validate_menu_item(this: &mut Object, _: Sel, item: id) -> bool {
751    unsafe {
752        let mut result = false;
753        let platform = get_foreground_platform(this);
754        let mut platform = platform.0.borrow_mut();
755        if let Some(mut callback) = platform.validate_menu_command.take() {
756            let tag: NSInteger = msg_send![item, tag];
757            let index = tag as usize;
758            if let Some(action) = platform.menu_actions.get(index) {
759                result = callback(action.as_ref());
760            }
761            platform.validate_menu_command = Some(callback);
762        }
763        result
764    }
765}
766
767unsafe fn ns_string(string: &str) -> id {
768    NSString::alloc(nil).init_str(string).autorelease()
769}
770
771unsafe fn ns_url_to_path(url: id) -> Result<PathBuf> {
772    let path: *mut c_char = msg_send![url, fileSystemRepresentation];
773    if path.is_null() {
774        Err(anyhow!(
775            "url is not a file path: {}",
776            CStr::from_ptr(url.absoluteString().UTF8String()).to_string_lossy()
777        ))
778    } else {
779        Ok(PathBuf::from(OsStr::from_bytes(
780            CStr::from_ptr(path).to_bytes(),
781        )))
782    }
783}
784
785mod security {
786    #![allow(non_upper_case_globals)]
787    use super::*;
788
789    #[link(name = "Security", kind = "framework")]
790    extern "C" {
791        pub static kSecClass: CFStringRef;
792        pub static kSecClassInternetPassword: CFStringRef;
793        pub static kSecAttrServer: CFStringRef;
794        pub static kSecAttrAccount: CFStringRef;
795        pub static kSecValueData: CFStringRef;
796        pub static kSecReturnAttributes: CFStringRef;
797        pub static kSecReturnData: CFStringRef;
798
799        pub fn SecItemAdd(attributes: CFDictionaryRef, result: *mut CFTypeRef) -> OSStatus;
800        pub fn SecItemUpdate(query: CFDictionaryRef, attributes: CFDictionaryRef) -> OSStatus;
801        pub fn SecItemDelete(query: CFDictionaryRef) -> OSStatus;
802        pub fn SecItemCopyMatching(query: CFDictionaryRef, result: *mut CFTypeRef) -> OSStatus;
803    }
804
805    pub const errSecSuccess: OSStatus = 0;
806    pub const errSecUserCanceled: OSStatus = -128;
807    pub const errSecItemNotFound: OSStatus = -25300;
808}
809
810#[cfg(test)]
811mod tests {
812    use crate::platform::Platform;
813
814    use super::*;
815
816    #[test]
817    fn test_clipboard() {
818        let platform = build_platform();
819        assert_eq!(platform.read_from_clipboard(), None);
820
821        let item = ClipboardItem::new("1".to_string());
822        platform.write_to_clipboard(item.clone());
823        assert_eq!(platform.read_from_clipboard(), Some(item));
824
825        let item = ClipboardItem::new("2".to_string()).with_metadata(vec![3, 4]);
826        platform.write_to_clipboard(item.clone());
827        assert_eq!(platform.read_from_clipboard(), Some(item));
828
829        let text_from_other_app = "text from other app";
830        unsafe {
831            let bytes = NSData::dataWithBytes_length_(
832                nil,
833                text_from_other_app.as_ptr() as *const c_void,
834                text_from_other_app.len() as u64,
835            );
836            platform
837                .pasteboard
838                .setData_forType(bytes, NSPasteboardTypeString);
839        }
840        assert_eq!(
841            platform.read_from_clipboard(),
842            Some(ClipboardItem::new(text_from_other_app.to_string()))
843        );
844    }
845
846    fn build_platform() -> MacPlatform {
847        let mut platform = MacPlatform::new();
848        platform.pasteboard = unsafe { NSPasteboard::pasteboardWithUniqueName(nil) };
849        platform
850    }
851}