platform.rs

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