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