platform.rs

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