platform.rs

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