platform.rs

  1use super::{
  2    event::key_to_native, screen::Screen, status_item::StatusItem, BoolExt as _, Dispatcher,
  3    FontSystem, Window,
  4};
  5use crate::{
  6    executor, keymap,
  7    platform::{self, CursorStyle},
  8    Action, AppVersion, ClipboardItem, Event, Menu, MenuItem,
  9};
 10use anyhow::{anyhow, Result};
 11use block::ConcreteBlock;
 12use cocoa::{
 13    appkit::{
 14        NSApplication, NSApplicationActivationPolicy::NSApplicationActivationPolicyRegular,
 15        NSEventModifierFlags, NSMenu, NSMenuItem, NSModalResponse, NSOpenPanel, NSPasteboard,
 16        NSPasteboardTypeString, NSSavePanel, NSWindow,
 17    },
 18    base::{id, nil, selector, YES},
 19    foundation::{
 20        NSArray, NSAutoreleasePool, NSBundle, NSData, NSInteger, NSProcessInfo, NSString,
 21        NSUInteger, NSURL,
 22    },
 23};
 24use core_foundation::{
 25    base::{CFType, CFTypeRef, OSStatus, TCFType as _},
 26    boolean::CFBoolean,
 27    data::CFData,
 28    dictionary::{CFDictionary, CFDictionaryRef, CFMutableDictionary},
 29    string::{CFString, CFStringRef},
 30};
 31use ctor::ctor;
 32use objc::{
 33    class,
 34    declare::ClassDecl,
 35    msg_send,
 36    runtime::{Class, Object, Sel},
 37    sel, sel_impl,
 38};
 39use postage::oneshot;
 40use ptr::null_mut;
 41use std::{
 42    cell::{Cell, RefCell},
 43    convert::TryInto,
 44    ffi::{c_void, CStr, OsStr},
 45    os::{raw::c_char, unix::ffi::OsStrExt},
 46    path::{Path, PathBuf},
 47    ptr,
 48    rc::Rc,
 49    slice, str,
 50    sync::Arc,
 51};
 52use time::UtcOffset;
 53
 54#[allow(non_upper_case_globals)]
 55const NSUTF8StringEncoding: NSUInteger = 4;
 56
 57#[allow(non_upper_case_globals)]
 58pub const NSViewLayerContentsRedrawDuringViewResize: NSInteger = 2;
 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 screens(&self) -> Vec<Rc<dyn platform::Screen>> {
491        Screen::all()
492            .into_iter()
493            .map(|screen| Rc::new(screen) as Rc<_>)
494            .collect()
495    }
496
497    fn open_window(
498        &self,
499        id: usize,
500        options: platform::WindowOptions,
501        executor: Rc<executor::Foreground>,
502    ) -> Box<dyn platform::Window> {
503        Box::new(Window::open(id, options, executor, self.fonts()))
504    }
505
506    fn key_window_id(&self) -> Option<usize> {
507        Window::key_window_id()
508    }
509
510    fn add_status_item(&self) -> Box<dyn platform::Window> {
511        Box::new(StatusItem::add(self.fonts()))
512    }
513
514    fn fonts(&self) -> Arc<dyn platform::FontSystem> {
515        self.fonts.clone()
516    }
517
518    fn write_to_clipboard(&self, item: ClipboardItem) {
519        unsafe {
520            self.pasteboard.clearContents();
521
522            let text_bytes = NSData::dataWithBytes_length_(
523                nil,
524                item.text.as_ptr() as *const c_void,
525                item.text.len() as u64,
526            );
527            self.pasteboard
528                .setData_forType(text_bytes, NSPasteboardTypeString);
529
530            if let Some(metadata) = item.metadata.as_ref() {
531                let hash_bytes = ClipboardItem::text_hash(&item.text).to_be_bytes();
532                let hash_bytes = NSData::dataWithBytes_length_(
533                    nil,
534                    hash_bytes.as_ptr() as *const c_void,
535                    hash_bytes.len() as u64,
536                );
537                self.pasteboard
538                    .setData_forType(hash_bytes, self.text_hash_pasteboard_type);
539
540                let metadata_bytes = NSData::dataWithBytes_length_(
541                    nil,
542                    metadata.as_ptr() as *const c_void,
543                    metadata.len() as u64,
544                );
545                self.pasteboard
546                    .setData_forType(metadata_bytes, self.metadata_pasteboard_type);
547            }
548        }
549    }
550
551    fn read_from_clipboard(&self) -> Option<ClipboardItem> {
552        unsafe {
553            if let Some(text_bytes) = self.read_from_pasteboard(NSPasteboardTypeString) {
554                let text = String::from_utf8_lossy(text_bytes).to_string();
555                let hash_bytes = self
556                    .read_from_pasteboard(self.text_hash_pasteboard_type)
557                    .and_then(|bytes| bytes.try_into().ok())
558                    .map(u64::from_be_bytes);
559                let metadata_bytes = self
560                    .read_from_pasteboard(self.metadata_pasteboard_type)
561                    .and_then(|bytes| String::from_utf8(bytes.to_vec()).ok());
562
563                if let Some((hash, metadata)) = hash_bytes.zip(metadata_bytes) {
564                    if hash == ClipboardItem::text_hash(&text) {
565                        Some(ClipboardItem {
566                            text,
567                            metadata: Some(metadata),
568                        })
569                    } else {
570                        Some(ClipboardItem {
571                            text,
572                            metadata: None,
573                        })
574                    }
575                } else {
576                    Some(ClipboardItem {
577                        text,
578                        metadata: None,
579                    })
580                }
581            } else {
582                None
583            }
584        }
585    }
586
587    fn open_url(&self, url: &str) {
588        unsafe {
589            let url = NSURL::alloc(nil)
590                .initWithString_(ns_string(url))
591                .autorelease();
592            let workspace: id = msg_send![class!(NSWorkspace), sharedWorkspace];
593            msg_send![workspace, openURL: url]
594        }
595    }
596
597    fn write_credentials(&self, url: &str, username: &str, password: &[u8]) -> Result<()> {
598        let url = CFString::from(url);
599        let username = CFString::from(username);
600        let password = CFData::from_buffer(password);
601
602        unsafe {
603            use security::*;
604
605            // First, check if there are already credentials for the given server. If so, then
606            // update the username and password.
607            let mut verb = "updating";
608            let mut query_attrs = CFMutableDictionary::with_capacity(2);
609            query_attrs.set(kSecClass as *const _, kSecClassInternetPassword as *const _);
610            query_attrs.set(kSecAttrServer as *const _, url.as_CFTypeRef());
611
612            let mut attrs = CFMutableDictionary::with_capacity(4);
613            attrs.set(kSecClass as *const _, kSecClassInternetPassword as *const _);
614            attrs.set(kSecAttrServer as *const _, url.as_CFTypeRef());
615            attrs.set(kSecAttrAccount as *const _, username.as_CFTypeRef());
616            attrs.set(kSecValueData as *const _, password.as_CFTypeRef());
617
618            let mut status = SecItemUpdate(
619                query_attrs.as_concrete_TypeRef(),
620                attrs.as_concrete_TypeRef(),
621            );
622
623            // If there were no existing credentials for the given server, then create them.
624            if status == errSecItemNotFound {
625                verb = "creating";
626                status = SecItemAdd(attrs.as_concrete_TypeRef(), ptr::null_mut());
627            }
628
629            if status != errSecSuccess {
630                return Err(anyhow!("{} password failed: {}", verb, status));
631            }
632        }
633        Ok(())
634    }
635
636    fn read_credentials(&self, url: &str) -> Result<Option<(String, Vec<u8>)>> {
637        let url = CFString::from(url);
638        let cf_true = CFBoolean::true_value().as_CFTypeRef();
639
640        unsafe {
641            use security::*;
642
643            // Find any credentials for the given server URL.
644            let mut attrs = CFMutableDictionary::with_capacity(5);
645            attrs.set(kSecClass as *const _, kSecClassInternetPassword as *const _);
646            attrs.set(kSecAttrServer as *const _, url.as_CFTypeRef());
647            attrs.set(kSecReturnAttributes as *const _, cf_true);
648            attrs.set(kSecReturnData as *const _, cf_true);
649
650            let mut result = CFTypeRef::from(ptr::null_mut());
651            let status = SecItemCopyMatching(attrs.as_concrete_TypeRef(), &mut result);
652            match status {
653                security::errSecSuccess => {}
654                security::errSecItemNotFound | security::errSecUserCanceled => return Ok(None),
655                _ => return Err(anyhow!("reading password failed: {}", status)),
656            }
657
658            let result = CFType::wrap_under_create_rule(result)
659                .downcast::<CFDictionary>()
660                .ok_or_else(|| anyhow!("keychain item was not a dictionary"))?;
661            let username = result
662                .find(kSecAttrAccount as *const _)
663                .ok_or_else(|| anyhow!("account was missing from keychain item"))?;
664            let username = CFType::wrap_under_get_rule(*username)
665                .downcast::<CFString>()
666                .ok_or_else(|| anyhow!("account was not a string"))?;
667            let password = result
668                .find(kSecValueData as *const _)
669                .ok_or_else(|| anyhow!("password was missing from keychain item"))?;
670            let password = CFType::wrap_under_get_rule(*password)
671                .downcast::<CFData>()
672                .ok_or_else(|| anyhow!("password was not a string"))?;
673
674            Ok(Some((username.to_string(), password.bytes().to_vec())))
675        }
676    }
677
678    fn delete_credentials(&self, url: &str) -> Result<()> {
679        let url = CFString::from(url);
680
681        unsafe {
682            use security::*;
683
684            let mut query_attrs = CFMutableDictionary::with_capacity(2);
685            query_attrs.set(kSecClass as *const _, kSecClassInternetPassword as *const _);
686            query_attrs.set(kSecAttrServer as *const _, url.as_CFTypeRef());
687
688            let status = SecItemDelete(query_attrs.as_concrete_TypeRef());
689
690            if status != errSecSuccess {
691                return Err(anyhow!("delete password failed: {}", status));
692            }
693        }
694        Ok(())
695    }
696
697    fn set_cursor_style(&self, style: CursorStyle) {
698        unsafe {
699            let cursor: id = match style {
700                CursorStyle::Arrow => msg_send![class!(NSCursor), arrowCursor],
701                CursorStyle::ResizeLeftRight => msg_send![class!(NSCursor), resizeLeftRightCursor],
702                CursorStyle::ResizeUpDown => msg_send![class!(NSCursor), resizeUpDownCursor],
703                CursorStyle::PointingHand => msg_send![class!(NSCursor), pointingHandCursor],
704                CursorStyle::IBeam => msg_send![class!(NSCursor), IBeamCursor],
705            };
706            let _: () = msg_send![cursor, set];
707        }
708    }
709
710    fn should_auto_hide_scrollbars(&self) -> bool {
711        #[allow(non_upper_case_globals)]
712        const NSScrollerStyleOverlay: NSInteger = 1;
713
714        unsafe {
715            let style: NSInteger = msg_send![class!(NSScroller), preferredScrollerStyle];
716            style == NSScrollerStyleOverlay
717        }
718    }
719
720    fn local_timezone(&self) -> UtcOffset {
721        unsafe {
722            let local_timezone: id = msg_send![class!(NSTimeZone), localTimeZone];
723            let seconds_from_gmt: NSInteger = msg_send![local_timezone, secondsFromGMT];
724            UtcOffset::from_whole_seconds(seconds_from_gmt.try_into().unwrap()).unwrap()
725        }
726    }
727
728    fn path_for_auxiliary_executable(&self, name: &str) -> Result<PathBuf> {
729        unsafe {
730            let bundle: id = NSBundle::mainBundle();
731            if bundle.is_null() {
732                Err(anyhow!("app is not running inside a bundle"))
733            } else {
734                let name = ns_string(name);
735                let url: id = msg_send![bundle, URLForAuxiliaryExecutable: name];
736                if url.is_null() {
737                    Err(anyhow!("resource not found"))
738                } else {
739                    ns_url_to_path(url)
740                }
741            }
742        }
743    }
744
745    fn app_path(&self) -> Result<PathBuf> {
746        unsafe {
747            let bundle: id = NSBundle::mainBundle();
748            if bundle.is_null() {
749                Err(anyhow!("app is not running inside a bundle"))
750            } else {
751                Ok(path_from_objc(msg_send![bundle, bundlePath]))
752            }
753        }
754    }
755
756    fn app_version(&self) -> Result<platform::AppVersion> {
757        unsafe {
758            let bundle: id = NSBundle::mainBundle();
759            if bundle.is_null() {
760                Err(anyhow!("app is not running inside a bundle"))
761            } else {
762                let version: id = msg_send![bundle, objectForInfoDictionaryKey: ns_string("CFBundleShortVersionString")];
763                let len = msg_send![version, lengthOfBytesUsingEncoding: NSUTF8StringEncoding];
764                let bytes = version.UTF8String() as *const u8;
765                let version = str::from_utf8(slice::from_raw_parts(bytes, len)).unwrap();
766                version.parse()
767            }
768        }
769    }
770
771    fn os_name(&self) -> &'static str {
772        "macOS"
773    }
774
775    fn os_version(&self) -> Result<crate::AppVersion> {
776        unsafe {
777            let process_info = NSProcessInfo::processInfo(nil);
778            let version = process_info.operatingSystemVersion();
779            Ok(AppVersion {
780                major: version.majorVersion as usize,
781                minor: version.minorVersion as usize,
782                patch: version.patchVersion as usize,
783            })
784        }
785    }
786}
787
788unsafe fn path_from_objc(path: id) -> PathBuf {
789    let len = msg_send![path, lengthOfBytesUsingEncoding: NSUTF8StringEncoding];
790    let bytes = path.UTF8String() as *const u8;
791    let path = str::from_utf8(slice::from_raw_parts(bytes, len)).unwrap();
792    PathBuf::from(path)
793}
794
795unsafe fn get_foreground_platform(object: &mut Object) -> &MacForegroundPlatform {
796    let platform_ptr: *mut c_void = *object.get_ivar(MAC_PLATFORM_IVAR);
797    assert!(!platform_ptr.is_null());
798    &*(platform_ptr as *const MacForegroundPlatform)
799}
800
801extern "C" fn send_event(this: &mut Object, _sel: Sel, native_event: id) {
802    unsafe {
803        if let Some(event) = Event::from_native(native_event, None) {
804            let platform = get_foreground_platform(this);
805            if let Some(callback) = platform.0.borrow_mut().event.as_mut() {
806                if callback(event) {
807                    return;
808                }
809            }
810        }
811
812        msg_send![super(this, class!(NSApplication)), sendEvent: native_event]
813    }
814}
815
816extern "C" fn did_finish_launching(this: &mut Object, _: Sel, _: id) {
817    unsafe {
818        let app: id = msg_send![APP_CLASS, sharedApplication];
819        app.setActivationPolicy_(NSApplicationActivationPolicyRegular);
820
821        let platform = get_foreground_platform(this);
822        let callback = platform.0.borrow_mut().finish_launching.take();
823        if let Some(callback) = callback {
824            callback();
825        }
826    }
827}
828
829extern "C" fn did_become_active(this: &mut Object, _: Sel, _: id) {
830    let platform = unsafe { get_foreground_platform(this) };
831    if let Some(callback) = platform.0.borrow_mut().become_active.as_mut() {
832        callback();
833    }
834}
835
836extern "C" fn did_resign_active(this: &mut Object, _: Sel, _: id) {
837    let platform = unsafe { get_foreground_platform(this) };
838    if let Some(callback) = platform.0.borrow_mut().resign_active.as_mut() {
839        callback();
840    }
841}
842
843extern "C" fn will_terminate(this: &mut Object, _: Sel, _: id) {
844    let platform = unsafe { get_foreground_platform(this) };
845    if let Some(callback) = platform.0.borrow_mut().quit.as_mut() {
846        callback();
847    }
848}
849
850extern "C" fn open_urls(this: &mut Object, _: Sel, _: id, urls: id) {
851    let urls = unsafe {
852        (0..urls.count())
853            .into_iter()
854            .filter_map(|i| {
855                let path = urls.objectAtIndex(i);
856                match CStr::from_ptr(path.absoluteString().UTF8String() as *mut c_char).to_str() {
857                    Ok(string) => Some(string.to_string()),
858                    Err(err) => {
859                        log::error!("error converting path to string: {}", err);
860                        None
861                    }
862                }
863            })
864            .collect::<Vec<_>>()
865    };
866    let platform = unsafe { get_foreground_platform(this) };
867    if let Some(callback) = platform.0.borrow_mut().open_urls.as_mut() {
868        callback(urls);
869    }
870}
871
872extern "C" fn handle_menu_item(this: &mut Object, _: Sel, item: id) {
873    unsafe {
874        let platform = get_foreground_platform(this);
875        let mut platform = platform.0.borrow_mut();
876        if let Some(mut callback) = platform.menu_command.take() {
877            let tag: NSInteger = msg_send![item, tag];
878            let index = tag as usize;
879            if let Some(action) = platform.menu_actions.get(index) {
880                callback(action.as_ref());
881            }
882            platform.menu_command = Some(callback);
883        }
884    }
885}
886
887extern "C" fn validate_menu_item(this: &mut Object, _: Sel, item: id) -> bool {
888    unsafe {
889        let mut result = false;
890        let platform = get_foreground_platform(this);
891        let mut platform = platform.0.borrow_mut();
892        if let Some(mut callback) = platform.validate_menu_command.take() {
893            let tag: NSInteger = msg_send![item, tag];
894            let index = tag as usize;
895            if let Some(action) = platform.menu_actions.get(index) {
896                result = callback(action.as_ref());
897            }
898            platform.validate_menu_command = Some(callback);
899        }
900        result
901    }
902}
903
904extern "C" fn menu_will_open(this: &mut Object, _: Sel, _: id) {
905    unsafe {
906        let platform = get_foreground_platform(this);
907        let mut platform = platform.0.borrow_mut();
908        if let Some(mut callback) = platform.will_open_menu.take() {
909            callback();
910            platform.will_open_menu = Some(callback);
911        }
912    }
913}
914
915unsafe fn ns_string(string: &str) -> id {
916    NSString::alloc(nil).init_str(string).autorelease()
917}
918
919unsafe fn ns_url_to_path(url: id) -> Result<PathBuf> {
920    let path: *mut c_char = msg_send![url, fileSystemRepresentation];
921    if path.is_null() {
922        Err(anyhow!(
923            "url is not a file path: {}",
924            CStr::from_ptr(url.absoluteString().UTF8String()).to_string_lossy()
925        ))
926    } else {
927        Ok(PathBuf::from(OsStr::from_bytes(
928            CStr::from_ptr(path).to_bytes(),
929        )))
930    }
931}
932
933mod security {
934    #![allow(non_upper_case_globals)]
935    use super::*;
936
937    #[link(name = "Security", kind = "framework")]
938    extern "C" {
939        pub static kSecClass: CFStringRef;
940        pub static kSecClassInternetPassword: CFStringRef;
941        pub static kSecAttrServer: CFStringRef;
942        pub static kSecAttrAccount: CFStringRef;
943        pub static kSecValueData: CFStringRef;
944        pub static kSecReturnAttributes: CFStringRef;
945        pub static kSecReturnData: CFStringRef;
946
947        pub fn SecItemAdd(attributes: CFDictionaryRef, result: *mut CFTypeRef) -> OSStatus;
948        pub fn SecItemUpdate(query: CFDictionaryRef, attributes: CFDictionaryRef) -> OSStatus;
949        pub fn SecItemDelete(query: CFDictionaryRef) -> OSStatus;
950        pub fn SecItemCopyMatching(query: CFDictionaryRef, result: *mut CFTypeRef) -> OSStatus;
951    }
952
953    pub const errSecSuccess: OSStatus = 0;
954    pub const errSecUserCanceled: OSStatus = -128;
955    pub const errSecItemNotFound: OSStatus = -25300;
956}
957
958#[cfg(test)]
959mod tests {
960    use crate::platform::Platform;
961
962    use super::*;
963
964    #[test]
965    fn test_clipboard() {
966        let platform = build_platform();
967        assert_eq!(platform.read_from_clipboard(), None);
968
969        let item = ClipboardItem::new("1".to_string());
970        platform.write_to_clipboard(item.clone());
971        assert_eq!(platform.read_from_clipboard(), Some(item));
972
973        let item = ClipboardItem::new("2".to_string()).with_metadata(vec![3, 4]);
974        platform.write_to_clipboard(item.clone());
975        assert_eq!(platform.read_from_clipboard(), Some(item));
976
977        let text_from_other_app = "text from other app";
978        unsafe {
979            let bytes = NSData::dataWithBytes_length_(
980                nil,
981                text_from_other_app.as_ptr() as *const c_void,
982                text_from_other_app.len() as u64,
983            );
984            platform
985                .pasteboard
986                .setData_forType(bytes, NSPasteboardTypeString);
987        }
988        assert_eq!(
989            platform.read_from_clipboard(),
990            Some(ClipboardItem::new(text_from_other_app.to_string()))
991        );
992    }
993
994    fn build_platform() -> MacPlatform {
995        let mut platform = MacPlatform::new();
996        platform.pasteboard = unsafe { NSPasteboard::pasteboardWithUniqueName(nil) };
997        platform
998    }
999}