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