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