platform.rs

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