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