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