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