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