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 ctor::ctor;
14use objc::{
15 class,
16 declare::ClassDecl,
17 msg_send,
18 runtime::{Class, Object, Sel},
19 sel, sel_impl,
20};
21use ptr::null_mut;
22use std::{
23 any::Any,
24 cell::{Cell, RefCell},
25 convert::TryInto,
26 ffi::{c_void, CStr},
27 os::raw::c_char,
28 path::{Path, PathBuf},
29 ptr,
30 rc::Rc,
31 slice, str,
32 sync::Arc,
33};
34
35const MAC_PLATFORM_IVAR: &'static str = "platform";
36static mut APP_CLASS: *const Class = ptr::null();
37static mut APP_DELEGATE_CLASS: *const Class = ptr::null();
38
39#[ctor]
40unsafe fn build_classes() {
41 APP_CLASS = {
42 let mut decl = ClassDecl::new("GPUIApplication", class!(NSApplication)).unwrap();
43 decl.add_ivar::<*mut c_void>(MAC_PLATFORM_IVAR);
44 decl.add_method(
45 sel!(sendEvent:),
46 send_event as extern "C" fn(&mut Object, Sel, id),
47 );
48 decl.register()
49 };
50
51 APP_DELEGATE_CLASS = {
52 let mut decl = ClassDecl::new("GPUIApplicationDelegate", class!(NSResponder)).unwrap();
53 decl.add_ivar::<*mut c_void>(MAC_PLATFORM_IVAR);
54 decl.add_method(
55 sel!(applicationDidFinishLaunching:),
56 did_finish_launching as extern "C" fn(&mut Object, Sel, id),
57 );
58 decl.add_method(
59 sel!(applicationDidBecomeActive:),
60 did_become_active as extern "C" fn(&mut Object, Sel, id),
61 );
62 decl.add_method(
63 sel!(applicationDidResignActive:),
64 did_resign_active as extern "C" fn(&mut Object, Sel, id),
65 );
66 decl.add_method(
67 sel!(handleGPUIMenuItem:),
68 handle_menu_item as extern "C" fn(&mut Object, Sel, id),
69 );
70 decl.add_method(
71 sel!(application:openFiles:),
72 open_files as extern "C" fn(&mut Object, Sel, id, id),
73 );
74 decl.register()
75 }
76}
77
78#[derive(Default)]
79pub struct MacMainThreadPlatform(RefCell<MacMainThreadPlatformState>);
80
81#[derive(Default)]
82pub struct MacMainThreadPlatformState {
83 become_active: Option<Box<dyn FnMut()>>,
84 resign_active: Option<Box<dyn FnMut()>>,
85 event: Option<Box<dyn FnMut(crate::Event) -> bool>>,
86 menu_command: Option<Box<dyn FnMut(&str, Option<&dyn Any>)>>,
87 open_files: Option<Box<dyn FnMut(Vec<PathBuf>)>>,
88 finish_launching: Option<Box<dyn FnOnce() -> ()>>,
89 menu_actions: Vec<(String, Option<Box<dyn Any>>)>,
90}
91
92impl MacMainThreadPlatform {
93 unsafe fn create_menu_bar(&self, menus: Vec<Menu>) -> id {
94 let menu_bar = NSMenu::new(nil).autorelease();
95 let mut state = self.0.borrow_mut();
96
97 state.menu_actions.clear();
98
99 for menu_config in menus {
100 let menu_bar_item = NSMenuItem::new(nil).autorelease();
101 let menu = NSMenu::new(nil).autorelease();
102 let menu_name = menu_config.name;
103
104 menu.setTitle_(ns_string(menu_name));
105
106 for item_config in menu_config.items {
107 let item;
108
109 match item_config {
110 MenuItem::Separator => {
111 item = NSMenuItem::separatorItem(nil);
112 }
113 MenuItem::Action {
114 name,
115 keystroke,
116 action,
117 arg,
118 } => {
119 if let Some(keystroke) = keystroke {
120 let keystroke = Keystroke::parse(keystroke).unwrap_or_else(|err| {
121 panic!(
122 "Invalid keystroke for menu item {}:{} - {:?}",
123 menu_name, name, err
124 )
125 });
126
127 let mut mask = NSEventModifierFlags::empty();
128 for (modifier, flag) in &[
129 (keystroke.cmd, NSEventModifierFlags::NSCommandKeyMask),
130 (keystroke.ctrl, NSEventModifierFlags::NSControlKeyMask),
131 (keystroke.alt, NSEventModifierFlags::NSAlternateKeyMask),
132 ] {
133 if *modifier {
134 mask |= *flag;
135 }
136 }
137
138 item = NSMenuItem::alloc(nil)
139 .initWithTitle_action_keyEquivalent_(
140 ns_string(name),
141 selector("handleGPUIMenuItem:"),
142 ns_string(&keystroke.key),
143 )
144 .autorelease();
145 item.setKeyEquivalentModifierMask_(mask);
146 } else {
147 item = NSMenuItem::alloc(nil)
148 .initWithTitle_action_keyEquivalent_(
149 ns_string(name),
150 selector("handleGPUIMenuItem:"),
151 ns_string(""),
152 )
153 .autorelease();
154 }
155
156 let tag = state.menu_actions.len() as NSInteger;
157 let _: () = msg_send![item, setTag: tag];
158 state.menu_actions.push((action.to_string(), arg));
159 }
160 }
161
162 menu.addItem_(item);
163 }
164
165 menu_bar_item.setSubmenu_(menu);
166 menu_bar.addItem_(menu_bar_item);
167 }
168
169 menu_bar
170 }
171}
172
173impl platform::MainThreadPlatform for MacMainThreadPlatform {
174 fn on_become_active(&self, callback: Box<dyn FnMut()>) {
175 self.0.borrow_mut().become_active = Some(callback);
176 }
177
178 fn on_resign_active(&self, callback: Box<dyn FnMut()>) {
179 self.0.borrow_mut().resign_active = Some(callback);
180 }
181
182 fn on_event(&self, callback: Box<dyn FnMut(crate::Event) -> bool>) {
183 self.0.borrow_mut().event = Some(callback);
184 }
185
186 fn on_menu_command(&self, callback: Box<dyn FnMut(&str, Option<&dyn Any>)>) {
187 self.0.borrow_mut().menu_command = Some(callback);
188 }
189
190 fn on_open_files(&self, callback: Box<dyn FnMut(Vec<PathBuf>)>) {
191 self.0.borrow_mut().open_files = Some(callback);
192 }
193
194 fn set_menus(&self, menus: Vec<Menu>) {
195 unsafe {
196 let app: id = msg_send![APP_CLASS, sharedApplication];
197 app.setMainMenu_(self.create_menu_bar(menus));
198 }
199 }
200
201 fn run(&self, on_finish_launching: Box<dyn FnOnce() -> ()>) {
202 self.0.borrow_mut().finish_launching = Some(on_finish_launching);
203
204 unsafe {
205 let app: id = msg_send![APP_CLASS, sharedApplication];
206 let app_delegate: id = msg_send![APP_DELEGATE_CLASS, new];
207 app.setDelegate_(app_delegate);
208
209 let self_ptr = self as *const Self as *const c_void;
210 (*app).set_ivar(MAC_PLATFORM_IVAR, self_ptr);
211 (*app_delegate).set_ivar(MAC_PLATFORM_IVAR, self_ptr);
212
213 let pool = NSAutoreleasePool::new(nil);
214 app.run();
215 pool.drain();
216
217 (*app).set_ivar(MAC_PLATFORM_IVAR, null_mut::<c_void>());
218 (*app.delegate()).set_ivar(MAC_PLATFORM_IVAR, null_mut::<c_void>());
219 }
220 }
221}
222
223pub struct MacPlatform {
224 dispatcher: Arc<Dispatcher>,
225 fonts: Arc<FontSystem>,
226 pasteboard: id,
227 text_hash_pasteboard_type: id,
228 metadata_pasteboard_type: id,
229}
230
231impl MacPlatform {
232 pub fn new() -> Self {
233 Self {
234 dispatcher: Arc::new(Dispatcher),
235 fonts: Arc::new(FontSystem::new()),
236 pasteboard: unsafe { NSPasteboard::generalPasteboard(nil) },
237 text_hash_pasteboard_type: unsafe { ns_string("zed-text-hash") },
238 metadata_pasteboard_type: unsafe { ns_string("zed-metadata") },
239 }
240 }
241
242 unsafe fn read_from_pasteboard(&self, kind: id) -> Option<&[u8]> {
243 let data = self.pasteboard.dataForType(kind);
244 if data == nil {
245 None
246 } else {
247 Some(slice::from_raw_parts(
248 data.bytes() as *mut u8,
249 data.length() as usize,
250 ))
251 }
252 }
253}
254
255impl platform::Platform for MacPlatform {
256 fn dispatcher(&self) -> Arc<dyn platform::Dispatcher> {
257 self.dispatcher.clone()
258 }
259
260 fn activate(&self, ignoring_other_apps: bool) {
261 unsafe {
262 let app = NSApplication::sharedApplication(nil);
263 app.activateIgnoringOtherApps_(ignoring_other_apps.to_objc());
264 }
265 }
266
267 fn open_window(
268 &self,
269 id: usize,
270 options: platform::WindowOptions,
271 executor: Rc<executor::Foreground>,
272 ) -> Box<dyn platform::Window> {
273 Box::new(Window::open(id, options, executor, self.fonts()))
274 }
275
276 fn key_window_id(&self) -> Option<usize> {
277 Window::key_window_id()
278 }
279
280 fn prompt_for_paths(
281 &self,
282 options: platform::PathPromptOptions,
283 done_fn: Box<dyn FnOnce(Option<Vec<std::path::PathBuf>>)>,
284 ) {
285 unsafe {
286 let panel = NSOpenPanel::openPanel(nil);
287 panel.setCanChooseDirectories_(options.directories.to_objc());
288 panel.setCanChooseFiles_(options.files.to_objc());
289 panel.setAllowsMultipleSelection_(options.multiple.to_objc());
290 panel.setResolvesAliases_(false.to_objc());
291 let done_fn = Cell::new(Some(done_fn));
292 let block = ConcreteBlock::new(move |response: NSModalResponse| {
293 let result = if response == NSModalResponse::NSModalResponseOk {
294 let mut result = Vec::new();
295 let urls = panel.URLs();
296 for i in 0..urls.count() {
297 let url = urls.objectAtIndex(i);
298 let string = url.absoluteString();
299 let string = std::ffi::CStr::from_ptr(string.UTF8String())
300 .to_string_lossy()
301 .to_string();
302 if let Some(path) = string.strip_prefix("file://") {
303 result.push(PathBuf::from(path));
304 }
305 }
306 Some(result)
307 } else {
308 None
309 };
310
311 if let Some(done_fn) = done_fn.take() {
312 (done_fn)(result);
313 }
314 });
315 let block = block.copy();
316 let _: () = msg_send![panel, beginWithCompletionHandler: block];
317 }
318 }
319
320 fn prompt_for_new_path(
321 &self,
322 directory: &Path,
323 done_fn: Box<dyn FnOnce(Option<std::path::PathBuf>)>,
324 ) {
325 unsafe {
326 let panel = NSSavePanel::savePanel(nil);
327 let path = ns_string(directory.to_string_lossy().as_ref());
328 let url = NSURL::fileURLWithPath_isDirectory_(nil, path, true.to_objc());
329 panel.setDirectoryURL(url);
330
331 let done_fn = Cell::new(Some(done_fn));
332 let block = ConcreteBlock::new(move |response: NSModalResponse| {
333 let result = if response == NSModalResponse::NSModalResponseOk {
334 let url = panel.URL();
335 let string = url.absoluteString();
336 let string = std::ffi::CStr::from_ptr(string.UTF8String())
337 .to_string_lossy()
338 .to_string();
339 if let Some(path) = string.strip_prefix("file://") {
340 Some(PathBuf::from(path))
341 } else {
342 None
343 }
344 } else {
345 None
346 };
347
348 if let Some(done_fn) = done_fn.take() {
349 (done_fn)(result);
350 }
351 });
352 let block = block.copy();
353 let _: () = msg_send![panel, beginWithCompletionHandler: block];
354 }
355 }
356
357 fn fonts(&self) -> Arc<dyn platform::FontSystem> {
358 self.fonts.clone()
359 }
360
361 fn quit(&self) {
362 // Quitting the app causes us to close windows, which invokes `Window::on_close` callbacks
363 // synchronously before this method terminates. If we call `Platform::quit` while holding a
364 // borrow of the app state (which most of the time we will do), we will end up
365 // double-borrowing the app state in the `on_close` callbacks for our open windows. To solve
366 // this, we make quitting the application asynchronous so that we aren't holding borrows to
367 // the app state on the stack when we actually terminate the app.
368
369 use super::dispatcher::{dispatch_async_f, dispatch_get_main_queue};
370
371 unsafe {
372 dispatch_async_f(dispatch_get_main_queue(), ptr::null_mut(), Some(quit));
373 }
374
375 unsafe extern "C" fn quit(_: *mut c_void) {
376 let app = NSApplication::sharedApplication(nil);
377 let _: () = msg_send![app, terminate: nil];
378 }
379 }
380
381 fn write_to_clipboard(&self, item: ClipboardItem) {
382 unsafe {
383 self.pasteboard.clearContents();
384
385 let text_bytes = NSData::dataWithBytes_length_(
386 nil,
387 item.text.as_ptr() as *const c_void,
388 item.text.len() as u64,
389 );
390 self.pasteboard
391 .setData_forType(text_bytes, NSPasteboardTypeString);
392
393 if let Some(metadata) = item.metadata.as_ref() {
394 let hash_bytes = ClipboardItem::text_hash(&item.text).to_be_bytes();
395 let hash_bytes = NSData::dataWithBytes_length_(
396 nil,
397 hash_bytes.as_ptr() as *const c_void,
398 hash_bytes.len() as u64,
399 );
400 self.pasteboard
401 .setData_forType(hash_bytes, self.text_hash_pasteboard_type);
402
403 let metadata_bytes = NSData::dataWithBytes_length_(
404 nil,
405 metadata.as_ptr() as *const c_void,
406 metadata.len() as u64,
407 );
408 self.pasteboard
409 .setData_forType(metadata_bytes, self.metadata_pasteboard_type);
410 }
411 }
412 }
413
414 fn read_from_clipboard(&self) -> Option<ClipboardItem> {
415 unsafe {
416 if let Some(text_bytes) = self.read_from_pasteboard(NSPasteboardTypeString) {
417 let text = String::from_utf8_lossy(&text_bytes).to_string();
418 let hash_bytes = self
419 .read_from_pasteboard(self.text_hash_pasteboard_type)
420 .and_then(|bytes| bytes.try_into().ok())
421 .map(u64::from_be_bytes);
422 let metadata_bytes = self
423 .read_from_pasteboard(self.metadata_pasteboard_type)
424 .and_then(|bytes| String::from_utf8(bytes.to_vec()).ok());
425
426 if let Some((hash, metadata)) = hash_bytes.zip(metadata_bytes) {
427 if hash == ClipboardItem::text_hash(&text) {
428 Some(ClipboardItem {
429 text,
430 metadata: Some(metadata),
431 })
432 } else {
433 Some(ClipboardItem {
434 text,
435 metadata: None,
436 })
437 }
438 } else {
439 Some(ClipboardItem {
440 text,
441 metadata: None,
442 })
443 }
444 } else {
445 None
446 }
447 }
448 }
449}
450
451unsafe fn get_main_thread_platform(object: &mut Object) -> &MacMainThreadPlatform {
452 let platform_ptr: *mut c_void = *object.get_ivar(MAC_PLATFORM_IVAR);
453 assert!(!platform_ptr.is_null());
454 &*(platform_ptr as *const MacMainThreadPlatform)
455}
456
457extern "C" fn send_event(this: &mut Object, _sel: Sel, native_event: id) {
458 unsafe {
459 if let Some(event) = Event::from_native(native_event, None) {
460 let platform = get_main_thread_platform(this);
461 if let Some(callback) = platform.0.borrow_mut().event.as_mut() {
462 if callback(event) {
463 return;
464 }
465 }
466 }
467
468 msg_send![super(this, class!(NSApplication)), sendEvent: native_event]
469 }
470}
471
472extern "C" fn did_finish_launching(this: &mut Object, _: Sel, _: id) {
473 unsafe {
474 let app: id = msg_send![APP_CLASS, sharedApplication];
475 app.setActivationPolicy_(NSApplicationActivationPolicyRegular);
476
477 let platform = get_main_thread_platform(this);
478 let callback = platform.0.borrow_mut().finish_launching.take();
479 if let Some(callback) = callback {
480 callback();
481 }
482 }
483}
484
485extern "C" fn did_become_active(this: &mut Object, _: Sel, _: id) {
486 let platform = unsafe { get_main_thread_platform(this) };
487 if let Some(callback) = platform.0.borrow_mut().become_active.as_mut() {
488 callback();
489 }
490}
491
492extern "C" fn did_resign_active(this: &mut Object, _: Sel, _: id) {
493 let platform = unsafe { get_main_thread_platform(this) };
494 if let Some(callback) = platform.0.borrow_mut().resign_active.as_mut() {
495 callback();
496 }
497}
498
499extern "C" fn open_files(this: &mut Object, _: Sel, _: id, paths: id) {
500 let paths = unsafe {
501 (0..paths.count())
502 .into_iter()
503 .filter_map(|i| {
504 let path = paths.objectAtIndex(i);
505 match CStr::from_ptr(path.UTF8String() as *mut c_char).to_str() {
506 Ok(string) => Some(PathBuf::from(string)),
507 Err(err) => {
508 log::error!("error converting path to string: {}", err);
509 None
510 }
511 }
512 })
513 .collect::<Vec<_>>()
514 };
515 let platform = unsafe { get_main_thread_platform(this) };
516 if let Some(callback) = platform.0.borrow_mut().open_files.as_mut() {
517 callback(paths);
518 }
519}
520
521extern "C" fn handle_menu_item(this: &mut Object, _: Sel, item: id) {
522 unsafe {
523 let platform = get_main_thread_platform(this);
524 if let Some(callback) = platform.0.borrow_mut().menu_command.as_mut() {
525 let tag: NSInteger = msg_send![item, tag];
526 let index = tag as usize;
527 if let Some((action, arg)) = platform.0.borrow_mut().menu_actions.get(index) {
528 callback(action, arg.as_ref().map(Box::as_ref));
529 }
530 }
531 }
532}
533
534unsafe fn ns_string(string: &str) -> id {
535 NSString::alloc(nil).init_str(string).autorelease()
536}
537
538#[cfg(test)]
539mod tests {
540 use crate::platform::Platform;
541
542 use super::*;
543
544 #[test]
545 fn test_clipboard() {
546 let platform = build_platform();
547 assert_eq!(platform.read_from_clipboard(), None);
548
549 let item = ClipboardItem::new("1".to_string());
550 platform.write_to_clipboard(item.clone());
551 assert_eq!(platform.read_from_clipboard(), Some(item));
552
553 let item = ClipboardItem::new("2".to_string()).with_metadata(vec![3, 4]);
554 platform.write_to_clipboard(item.clone());
555 assert_eq!(platform.read_from_clipboard(), Some(item));
556
557 let text_from_other_app = "text from other app";
558 unsafe {
559 let bytes = NSData::dataWithBytes_length_(
560 nil,
561 text_from_other_app.as_ptr() as *const c_void,
562 text_from_other_app.len() as u64,
563 );
564 platform
565 .pasteboard
566 .setData_forType(bytes, NSPasteboardTypeString);
567 }
568 assert_eq!(
569 platform.read_from_clipboard(),
570 Some(ClipboardItem::new(text_from_other_app.to_string()))
571 );
572 }
573
574 fn build_platform() -> MacPlatform {
575 let mut platform = MacPlatform::new();
576 platform.pasteboard = unsafe { NSPasteboard::pasteboardWithUniqueName(nil) };
577 platform
578 }
579}