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