platform.rs

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