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
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 let string = url.absoluteString();
287 let string = std::ffi::CStr::from_ptr(string.UTF8String())
288 .to_string_lossy()
289 .to_string();
290 if let Some(path) = string.strip_prefix("file://") {
291 result.push(PathBuf::from(path));
292 }
293 }
294 Some(result)
295 } else {
296 None
297 };
298
299 if let Some(done_fn) = done_fn.take() {
300 (done_fn)(result);
301 }
302 });
303 let block = block.copy();
304 let _: () = msg_send![panel, beginWithCompletionHandler: block];
305 }
306 }
307
308 fn prompt_for_new_path(
309 &self,
310 directory: &Path,
311 done_fn: Box<dyn FnOnce(Option<std::path::PathBuf>)>,
312 ) {
313 unsafe {
314 let panel = NSSavePanel::savePanel(nil);
315 let path = ns_string(directory.to_string_lossy().as_ref());
316 let url = NSURL::fileURLWithPath_isDirectory_(nil, path, true.to_objc());
317 panel.setDirectoryURL(url);
318
319 let done_fn = Cell::new(Some(done_fn));
320 let block = ConcreteBlock::new(move |response: NSModalResponse| {
321 let result = if response == NSModalResponse::NSModalResponseOk {
322 let url = panel.URL();
323 let string = url.absoluteString();
324 let string = std::ffi::CStr::from_ptr(string.UTF8String())
325 .to_string_lossy()
326 .to_string();
327 if let Some(path) = string.strip_prefix("file://") {
328 Some(PathBuf::from(path))
329 } else {
330 None
331 }
332 } else {
333 None
334 };
335
336 if let Some(done_fn) = done_fn.take() {
337 (done_fn)(result);
338 }
339 });
340 let block = block.copy();
341 let _: () = msg_send![panel, beginWithCompletionHandler: block];
342 }
343 }
344
345 fn fonts(&self) -> Arc<dyn platform::FontSystem> {
346 self.fonts.clone()
347 }
348
349 fn quit(&self) {
350 unsafe {
351 let app = NSApplication::sharedApplication(nil);
352 let _: () = msg_send![app, terminate: nil];
353 }
354 }
355
356 fn write_to_clipboard(&self, item: ClipboardItem) {
357 unsafe {
358 self.pasteboard.clearContents();
359
360 let text_bytes = NSData::dataWithBytes_length_(
361 nil,
362 item.text.as_ptr() as *const c_void,
363 item.text.len() as u64,
364 );
365 self.pasteboard
366 .setData_forType(text_bytes, NSPasteboardTypeString);
367
368 if let Some(metadata) = item.metadata.as_ref() {
369 let hash_bytes = ClipboardItem::text_hash(&item.text).to_be_bytes();
370 let hash_bytes = NSData::dataWithBytes_length_(
371 nil,
372 hash_bytes.as_ptr() as *const c_void,
373 hash_bytes.len() as u64,
374 );
375 self.pasteboard
376 .setData_forType(hash_bytes, self.text_hash_pasteboard_type);
377
378 let metadata_bytes = NSData::dataWithBytes_length_(
379 nil,
380 metadata.as_ptr() as *const c_void,
381 metadata.len() as u64,
382 );
383 self.pasteboard
384 .setData_forType(metadata_bytes, self.metadata_pasteboard_type);
385 }
386 }
387 }
388
389 fn read_from_clipboard(&self) -> Option<ClipboardItem> {
390 unsafe {
391 if let Some(text_bytes) = self.read_from_pasteboard(NSPasteboardTypeString) {
392 let text = String::from_utf8_lossy(&text_bytes).to_string();
393 let hash_bytes = self
394 .read_from_pasteboard(self.text_hash_pasteboard_type)
395 .and_then(|bytes| bytes.try_into().ok())
396 .map(u64::from_be_bytes);
397 let metadata_bytes = self
398 .read_from_pasteboard(self.metadata_pasteboard_type)
399 .and_then(|bytes| String::from_utf8(bytes.to_vec()).ok());
400
401 if let Some((hash, metadata)) = hash_bytes.zip(metadata_bytes) {
402 if hash == ClipboardItem::text_hash(&text) {
403 Some(ClipboardItem {
404 text,
405 metadata: Some(metadata),
406 })
407 } else {
408 Some(ClipboardItem {
409 text,
410 metadata: None,
411 })
412 }
413 } else {
414 Some(ClipboardItem {
415 text,
416 metadata: None,
417 })
418 }
419 } else {
420 None
421 }
422 }
423 }
424
425 fn set_menus(&self, menus: Vec<Menu>) {
426 unsafe {
427 let app: id = msg_send![APP_CLASS, sharedApplication];
428 app.setMainMenu_(self.create_menu_bar(menus));
429 }
430 }
431}
432
433unsafe fn get_platform(object: &mut Object) -> &MacPlatform {
434 let platform_ptr: *mut c_void = *object.get_ivar(MAC_PLATFORM_IVAR);
435 assert!(!platform_ptr.is_null());
436 &*(platform_ptr as *const MacPlatform)
437}
438
439extern "C" fn send_event(this: &mut Object, _sel: Sel, native_event: id) {
440 unsafe {
441 if let Some(event) = Event::from_native(native_event, None) {
442 let platform = get_platform(this);
443 if let Some(callback) = platform.callbacks.borrow_mut().event.as_mut() {
444 if callback(event) {
445 return;
446 }
447 }
448 }
449
450 msg_send![super(this, class!(NSApplication)), sendEvent: native_event]
451 }
452}
453
454extern "C" fn did_finish_launching(this: &mut Object, _: Sel, _: id) {
455 unsafe {
456 let app: id = msg_send![APP_CLASS, sharedApplication];
457 app.setActivationPolicy_(NSApplicationActivationPolicyRegular);
458
459 let platform = get_platform(this);
460 if let Some(callback) = platform.callbacks.borrow_mut().finish_launching.take() {
461 callback();
462 }
463 }
464}
465
466extern "C" fn did_become_active(this: &mut Object, _: Sel, _: id) {
467 let platform = unsafe { get_platform(this) };
468 if let Some(callback) = platform.callbacks.borrow_mut().become_active.as_mut() {
469 callback();
470 }
471}
472
473extern "C" fn did_resign_active(this: &mut Object, _: Sel, _: id) {
474 let platform = unsafe { get_platform(this) };
475 if let Some(callback) = platform.callbacks.borrow_mut().resign_active.as_mut() {
476 callback();
477 }
478}
479
480extern "C" fn open_files(this: &mut Object, _: Sel, _: id, paths: id) {
481 let paths = unsafe {
482 (0..paths.count())
483 .into_iter()
484 .filter_map(|i| {
485 let path = paths.objectAtIndex(i);
486 match CStr::from_ptr(path.UTF8String() as *mut c_char).to_str() {
487 Ok(string) => Some(PathBuf::from(string)),
488 Err(err) => {
489 log::error!("error converting path to string: {}", err);
490 None
491 }
492 }
493 })
494 .collect::<Vec<_>>()
495 };
496 let platform = unsafe { get_platform(this) };
497 if let Some(callback) = platform.callbacks.borrow_mut().open_files.as_mut() {
498 callback(paths);
499 }
500}
501
502extern "C" fn handle_menu_item(this: &mut Object, _: Sel, item: id) {
503 unsafe {
504 let platform = get_platform(this);
505 if let Some(callback) = platform.callbacks.borrow_mut().menu_command.as_mut() {
506 let tag: NSInteger = msg_send![item, tag];
507 let index = tag as usize;
508 if let Some((action, arg)) = platform.menu_item_actions.borrow().get(index) {
509 callback(action, arg.as_ref().map(Box::as_ref));
510 }
511 }
512 }
513}
514
515unsafe fn ns_string(string: &str) -> id {
516 NSString::alloc(nil).init_str(string).autorelease()
517}
518
519#[cfg(test)]
520mod tests {
521 use crate::platform::Platform;
522
523 use super::*;
524
525 #[test]
526 fn test_clipboard() {
527 let platform = build_platform();
528 assert_eq!(platform.read_from_clipboard(), None);
529
530 let item = ClipboardItem::new("1".to_string());
531 platform.write_to_clipboard(item.clone());
532 assert_eq!(platform.read_from_clipboard(), Some(item));
533
534 let item = ClipboardItem::new("2".to_string()).with_metadata(vec![3, 4]);
535 platform.write_to_clipboard(item.clone());
536 assert_eq!(platform.read_from_clipboard(), Some(item));
537
538 let text_from_other_app = "text from other app";
539 unsafe {
540 let bytes = NSData::dataWithBytes_length_(
541 nil,
542 text_from_other_app.as_ptr() as *const c_void,
543 text_from_other_app.len() as u64,
544 );
545 platform
546 .pasteboard
547 .setData_forType(bytes, NSPasteboardTypeString);
548 }
549 assert_eq!(
550 platform.read_from_clipboard(),
551 Some(ClipboardItem::new(text_from_other_app.to_string()))
552 );
553 }
554
555 fn build_platform() -> MacPlatform {
556 let mut platform = MacPlatform::new();
557 platform.pasteboard = unsafe { NSPasteboard::pasteboardWithUniqueName(nil) };
558 platform
559 }
560}