platform.rs

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