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},
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 let string = url.absoluteString();
248 let string = std::ffi::CStr::from_ptr(string.UTF8String())
249 .to_string_lossy()
250 .to_string();
251 if let Some(path) = string.strip_prefix("file://") {
252 result.push(PathBuf::from(path));
253 }
254 }
255 Some(result)
256 } else {
257 None
258 };
259
260 if let Some(done_fn) = done_fn.take() {
261 (done_fn)(result);
262 }
263 });
264 let block = block.copy();
265 let _: () = msg_send![panel, beginWithCompletionHandler: block];
266 }
267 }
268
269 fn prompt_for_new_path(
270 &self,
271 directory: &Path,
272 done_fn: Box<dyn FnOnce(Option<std::path::PathBuf>)>,
273 ) {
274 unsafe {
275 let panel = NSSavePanel::savePanel(nil);
276 let path = ns_string(directory.to_string_lossy().as_ref());
277 let url = NSURL::fileURLWithPath_isDirectory_(nil, path, true.to_objc());
278 panel.setDirectoryURL(url);
279
280 let done_fn = Cell::new(Some(done_fn));
281 let block = ConcreteBlock::new(move |response: NSModalResponse| {
282 let result = if response == NSModalResponse::NSModalResponseOk {
283 let url = panel.URL();
284 let string = url.absoluteString();
285 let string = std::ffi::CStr::from_ptr(string.UTF8String())
286 .to_string_lossy()
287 .to_string();
288 if let Some(path) = string.strip_prefix("file://") {
289 Some(PathBuf::from(path))
290 } else {
291 None
292 }
293 } else {
294 None
295 };
296
297 if let Some(done_fn) = done_fn.take() {
298 (done_fn)(result);
299 }
300 });
301 let block = block.copy();
302 let _: () = msg_send![panel, beginWithCompletionHandler: block];
303 }
304 }
305}
306
307pub struct MacPlatform {
308 dispatcher: Arc<Dispatcher>,
309 fonts: Arc<FontSystem>,
310 pasteboard: id,
311 text_hash_pasteboard_type: id,
312 metadata_pasteboard_type: id,
313}
314
315impl MacPlatform {
316 pub fn new() -> Self {
317 Self {
318 dispatcher: Arc::new(Dispatcher),
319 fonts: Arc::new(FontSystem::new()),
320 pasteboard: unsafe { NSPasteboard::generalPasteboard(nil) },
321 text_hash_pasteboard_type: unsafe { ns_string("zed-text-hash") },
322 metadata_pasteboard_type: unsafe { ns_string("zed-metadata") },
323 }
324 }
325
326 unsafe fn read_from_pasteboard(&self, kind: id) -> Option<&[u8]> {
327 let data = self.pasteboard.dataForType(kind);
328 if data == nil {
329 None
330 } else {
331 Some(slice::from_raw_parts(
332 data.bytes() as *mut u8,
333 data.length() as usize,
334 ))
335 }
336 }
337}
338
339unsafe impl Send for MacPlatform {}
340unsafe impl Sync for MacPlatform {}
341
342impl platform::Platform for MacPlatform {
343 fn dispatcher(&self) -> Arc<dyn platform::Dispatcher> {
344 self.dispatcher.clone()
345 }
346
347 fn activate(&self, ignoring_other_apps: bool) {
348 unsafe {
349 let app = NSApplication::sharedApplication(nil);
350 app.activateIgnoringOtherApps_(ignoring_other_apps.to_objc());
351 }
352 }
353
354 fn open_window(
355 &self,
356 id: usize,
357 options: platform::WindowOptions,
358 executor: Rc<executor::Foreground>,
359 ) -> Box<dyn platform::Window> {
360 Box::new(Window::open(id, options, executor, self.fonts()))
361 }
362
363 fn key_window_id(&self) -> Option<usize> {
364 Window::key_window_id()
365 }
366
367 fn fonts(&self) -> Arc<dyn platform::FontSystem> {
368 self.fonts.clone()
369 }
370
371 fn quit(&self) {
372 // Quitting the app causes us to close windows, which invokes `Window::on_close` callbacks
373 // synchronously before this method terminates. If we call `Platform::quit` while holding a
374 // borrow of the app state (which most of the time we will do), we will end up
375 // double-borrowing the app state in the `on_close` callbacks for our open windows. To solve
376 // this, we make quitting the application asynchronous so that we aren't holding borrows to
377 // the app state on the stack when we actually terminate the app.
378
379 use super::dispatcher::{dispatch_async_f, dispatch_get_main_queue};
380
381 unsafe {
382 dispatch_async_f(dispatch_get_main_queue(), ptr::null_mut(), Some(quit));
383 }
384
385 unsafe extern "C" fn quit(_: *mut c_void) {
386 let app = NSApplication::sharedApplication(nil);
387 let _: () = msg_send![app, terminate: nil];
388 }
389 }
390
391 fn write_to_clipboard(&self, item: ClipboardItem) {
392 unsafe {
393 self.pasteboard.clearContents();
394
395 let text_bytes = NSData::dataWithBytes_length_(
396 nil,
397 item.text.as_ptr() as *const c_void,
398 item.text.len() as u64,
399 );
400 self.pasteboard
401 .setData_forType(text_bytes, NSPasteboardTypeString);
402
403 if let Some(metadata) = item.metadata.as_ref() {
404 let hash_bytes = ClipboardItem::text_hash(&item.text).to_be_bytes();
405 let hash_bytes = NSData::dataWithBytes_length_(
406 nil,
407 hash_bytes.as_ptr() as *const c_void,
408 hash_bytes.len() as u64,
409 );
410 self.pasteboard
411 .setData_forType(hash_bytes, self.text_hash_pasteboard_type);
412
413 let metadata_bytes = NSData::dataWithBytes_length_(
414 nil,
415 metadata.as_ptr() as *const c_void,
416 metadata.len() as u64,
417 );
418 self.pasteboard
419 .setData_forType(metadata_bytes, self.metadata_pasteboard_type);
420 }
421 }
422 }
423
424 fn read_from_clipboard(&self) -> Option<ClipboardItem> {
425 unsafe {
426 if let Some(text_bytes) = self.read_from_pasteboard(NSPasteboardTypeString) {
427 let text = String::from_utf8_lossy(&text_bytes).to_string();
428 let hash_bytes = self
429 .read_from_pasteboard(self.text_hash_pasteboard_type)
430 .and_then(|bytes| bytes.try_into().ok())
431 .map(u64::from_be_bytes);
432 let metadata_bytes = self
433 .read_from_pasteboard(self.metadata_pasteboard_type)
434 .and_then(|bytes| String::from_utf8(bytes.to_vec()).ok());
435
436 if let Some((hash, metadata)) = hash_bytes.zip(metadata_bytes) {
437 if hash == ClipboardItem::text_hash(&text) {
438 Some(ClipboardItem {
439 text,
440 metadata: Some(metadata),
441 })
442 } else {
443 Some(ClipboardItem {
444 text,
445 metadata: None,
446 })
447 }
448 } else {
449 Some(ClipboardItem {
450 text,
451 metadata: None,
452 })
453 }
454 } else {
455 None
456 }
457 }
458 }
459
460 fn open_url(&self, url: &str) {
461 unsafe {
462 let url = NSURL::alloc(nil)
463 .initWithString_(ns_string(url))
464 .autorelease();
465 let workspace: id = msg_send![class!(NSWorkspace), sharedWorkspace];
466 msg_send![workspace, openURL: url]
467 }
468 }
469
470 fn write_credentials(&self, url: &str, username: &str, password: &[u8]) {
471 let url = CFString::from(url);
472 let username = CFString::from(username);
473 let password = CFData::from_buffer(password);
474
475 unsafe {
476 use security::*;
477
478 // First, check if there are already credentials for the given server. If so, then
479 // update the username and password.
480 let mut verb = "updating";
481 let mut query_attrs = CFMutableDictionary::with_capacity(2);
482 query_attrs.set(kSecClass as *const _, kSecClassInternetPassword as *const _);
483 query_attrs.set(kSecAttrServer as *const _, url.as_CFTypeRef());
484
485 let mut attrs = CFMutableDictionary::with_capacity(4);
486 attrs.set(kSecClass as *const _, kSecClassInternetPassword as *const _);
487 attrs.set(kSecAttrServer as *const _, url.as_CFTypeRef());
488 attrs.set(kSecAttrAccount as *const _, username.as_CFTypeRef());
489 attrs.set(kSecValueData as *const _, password.as_CFTypeRef());
490
491 let mut status = SecItemUpdate(
492 query_attrs.as_concrete_TypeRef(),
493 attrs.as_concrete_TypeRef(),
494 );
495
496 // If there were no existing credentials for the given server, then create them.
497 if status == errSecItemNotFound {
498 verb = "creating";
499 status = SecItemAdd(attrs.as_concrete_TypeRef(), ptr::null_mut());
500 }
501
502 if status != errSecSuccess {
503 panic!("{} password failed: {}", verb, status);
504 }
505 }
506 }
507
508 fn read_credentials(&self, url: &str) -> Option<(String, Vec<u8>)> {
509 let url = CFString::from(url);
510 let cf_true = CFBoolean::true_value().as_CFTypeRef();
511
512 unsafe {
513 use security::*;
514
515 // Find any credentials for the given server URL.
516 let mut attrs = CFMutableDictionary::with_capacity(5);
517 attrs.set(kSecClass as *const _, kSecClassInternetPassword as *const _);
518 attrs.set(kSecAttrServer as *const _, url.as_CFTypeRef());
519 attrs.set(kSecReturnAttributes as *const _, cf_true);
520 attrs.set(kSecReturnData as *const _, cf_true);
521
522 let mut result = CFTypeRef::from(ptr::null_mut());
523 let status = SecItemCopyMatching(attrs.as_concrete_TypeRef(), &mut result);
524 match status {
525 security::errSecSuccess => {}
526 security::errSecItemNotFound | security::errSecUserCanceled => return None,
527 _ => panic!("reading password failed: {}", status),
528 }
529
530 let result = CFType::wrap_under_create_rule(result)
531 .downcast::<CFDictionary>()
532 .expect("keychain item was not a dictionary");
533 let username = result
534 .find(kSecAttrAccount as *const _)
535 .expect("account was missing from keychain item");
536 let username = CFType::wrap_under_get_rule(*username)
537 .downcast::<CFString>()
538 .expect("account was not a string");
539 let password = result
540 .find(kSecValueData as *const _)
541 .expect("password was missing from keychain item");
542 let password = CFType::wrap_under_get_rule(*password)
543 .downcast::<CFData>()
544 .expect("password was not a string");
545
546 Some((username.to_string(), password.bytes().to_vec()))
547 }
548 }
549}
550
551unsafe fn get_foreground_platform(object: &mut Object) -> &MacForegroundPlatform {
552 let platform_ptr: *mut c_void = *object.get_ivar(MAC_PLATFORM_IVAR);
553 assert!(!platform_ptr.is_null());
554 &*(platform_ptr as *const MacForegroundPlatform)
555}
556
557extern "C" fn send_event(this: &mut Object, _sel: Sel, native_event: id) {
558 unsafe {
559 if let Some(event) = Event::from_native(native_event, None) {
560 let platform = get_foreground_platform(this);
561 if let Some(callback) = platform.0.borrow_mut().event.as_mut() {
562 if callback(event) {
563 return;
564 }
565 }
566 }
567
568 msg_send![super(this, class!(NSApplication)), sendEvent: native_event]
569 }
570}
571
572extern "C" fn did_finish_launching(this: &mut Object, _: Sel, _: id) {
573 unsafe {
574 let app: id = msg_send![APP_CLASS, sharedApplication];
575 app.setActivationPolicy_(NSApplicationActivationPolicyRegular);
576
577 let platform = get_foreground_platform(this);
578 let callback = platform.0.borrow_mut().finish_launching.take();
579 if let Some(callback) = callback {
580 callback();
581 }
582 }
583}
584
585extern "C" fn did_become_active(this: &mut Object, _: Sel, _: id) {
586 let platform = unsafe { get_foreground_platform(this) };
587 if let Some(callback) = platform.0.borrow_mut().become_active.as_mut() {
588 callback();
589 }
590}
591
592extern "C" fn did_resign_active(this: &mut Object, _: Sel, _: id) {
593 let platform = unsafe { get_foreground_platform(this) };
594 if let Some(callback) = platform.0.borrow_mut().resign_active.as_mut() {
595 callback();
596 }
597}
598
599extern "C" fn open_files(this: &mut Object, _: Sel, _: id, paths: id) {
600 let paths = unsafe {
601 (0..paths.count())
602 .into_iter()
603 .filter_map(|i| {
604 let path = paths.objectAtIndex(i);
605 match CStr::from_ptr(path.UTF8String() as *mut c_char).to_str() {
606 Ok(string) => Some(PathBuf::from(string)),
607 Err(err) => {
608 log::error!("error converting path to string: {}", err);
609 None
610 }
611 }
612 })
613 .collect::<Vec<_>>()
614 };
615 let platform = unsafe { get_foreground_platform(this) };
616 if let Some(callback) = platform.0.borrow_mut().open_files.as_mut() {
617 callback(paths);
618 }
619}
620
621extern "C" fn handle_menu_item(this: &mut Object, _: Sel, item: id) {
622 unsafe {
623 let platform = get_foreground_platform(this);
624 let mut platform = platform.0.borrow_mut();
625 if let Some(mut callback) = platform.menu_command.take() {
626 let tag: NSInteger = msg_send![item, tag];
627 let index = tag as usize;
628 if let Some((action, arg)) = platform.menu_actions.get(index) {
629 callback(action, arg.as_ref().map(Box::as_ref));
630 }
631 platform.menu_command = Some(callback);
632 }
633 }
634}
635
636unsafe fn ns_string(string: &str) -> id {
637 NSString::alloc(nil).init_str(string).autorelease()
638}
639
640mod security {
641 #![allow(non_upper_case_globals)]
642 use super::*;
643
644 #[link(name = "Security", kind = "framework")]
645 extern "C" {
646 pub static kSecClass: CFStringRef;
647 pub static kSecClassInternetPassword: CFStringRef;
648 pub static kSecAttrServer: CFStringRef;
649 pub static kSecAttrAccount: CFStringRef;
650 pub static kSecValueData: CFStringRef;
651 pub static kSecReturnAttributes: CFStringRef;
652 pub static kSecReturnData: CFStringRef;
653
654 pub fn SecItemAdd(attributes: CFDictionaryRef, result: *mut CFTypeRef) -> OSStatus;
655 pub fn SecItemUpdate(query: CFDictionaryRef, attributes: CFDictionaryRef) -> OSStatus;
656 pub fn SecItemCopyMatching(query: CFDictionaryRef, result: *mut CFTypeRef) -> OSStatus;
657 }
658
659 pub const errSecSuccess: OSStatus = 0;
660 pub const errSecUserCanceled: OSStatus = -128;
661 pub const errSecItemNotFound: OSStatus = -25300;
662}
663
664#[cfg(test)]
665mod tests {
666 use crate::platform::Platform;
667
668 use super::*;
669
670 #[test]
671 fn test_clipboard() {
672 let platform = build_platform();
673 assert_eq!(platform.read_from_clipboard(), None);
674
675 let item = ClipboardItem::new("1".to_string());
676 platform.write_to_clipboard(item.clone());
677 assert_eq!(platform.read_from_clipboard(), Some(item));
678
679 let item = ClipboardItem::new("2".to_string()).with_metadata(vec![3, 4]);
680 platform.write_to_clipboard(item.clone());
681 assert_eq!(platform.read_from_clipboard(), Some(item));
682
683 let text_from_other_app = "text from other app";
684 unsafe {
685 let bytes = NSData::dataWithBytes_length_(
686 nil,
687 text_from_other_app.as_ptr() as *const c_void,
688 text_from_other_app.len() as u64,
689 );
690 platform
691 .pasteboard
692 .setData_forType(bytes, NSPasteboardTypeString);
693 }
694 assert_eq!(
695 platform.read_from_clipboard(),
696 Some(ClipboardItem::new(text_from_other_app.to_string()))
697 );
698 }
699
700 fn build_platform() -> MacPlatform {
701 let mut platform = MacPlatform::new();
702 platform.pasteboard = unsafe { NSPasteboard::pasteboardWithUniqueName(nil) };
703 platform
704 }
705}