platform.rs

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