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