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