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