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_open_files(&self, callback: Box<dyn FnMut(Vec<PathBuf>)>) {
187 self.0.borrow_mut().open_files = Some(callback);
188 }
189
190 fn run(&self, on_finish_launching: Box<dyn FnOnce() -> ()>) {
191 self.0.borrow_mut().finish_launching = Some(on_finish_launching);
192
193 unsafe {
194 let app: id = msg_send![APP_CLASS, sharedApplication];
195 let app_delegate: id = msg_send![APP_DELEGATE_CLASS, new];
196 app.setDelegate_(app_delegate);
197
198 let self_ptr = self as *const Self as *const c_void;
199 (*app).set_ivar(MAC_PLATFORM_IVAR, self_ptr);
200 (*app_delegate).set_ivar(MAC_PLATFORM_IVAR, self_ptr);
201
202 let pool = NSAutoreleasePool::new(nil);
203 app.run();
204 pool.drain();
205
206 (*app).set_ivar(MAC_PLATFORM_IVAR, null_mut::<c_void>());
207 (*app.delegate()).set_ivar(MAC_PLATFORM_IVAR, null_mut::<c_void>());
208 }
209 }
210
211 fn on_menu_command(&self, callback: Box<dyn FnMut(&str, Option<&dyn Any>)>) {
212 self.0.borrow_mut().menu_command = Some(callback);
213 }
214
215 fn set_menus(&self, menus: Vec<Menu>) {
216 unsafe {
217 let app: id = msg_send![APP_CLASS, sharedApplication];
218 app.setMainMenu_(self.create_menu_bar(menus));
219 }
220 }
221
222 fn prompt_for_paths(
223 &self,
224 options: platform::PathPromptOptions,
225 done_fn: Box<dyn FnOnce(Option<Vec<std::path::PathBuf>>)>,
226 ) {
227 unsafe {
228 let panel = NSOpenPanel::openPanel(nil);
229 panel.setCanChooseDirectories_(options.directories.to_objc());
230 panel.setCanChooseFiles_(options.files.to_objc());
231 panel.setAllowsMultipleSelection_(options.multiple.to_objc());
232 panel.setResolvesAliases_(false.to_objc());
233 let done_fn = Cell::new(Some(done_fn));
234 let block = ConcreteBlock::new(move |response: NSModalResponse| {
235 let result = if response == NSModalResponse::NSModalResponseOk {
236 let mut result = Vec::new();
237 let urls = panel.URLs();
238 for i in 0..urls.count() {
239 let url = urls.objectAtIndex(i);
240 let string = url.absoluteString();
241 let string = std::ffi::CStr::from_ptr(string.UTF8String())
242 .to_string_lossy()
243 .to_string();
244 if let Some(path) = string.strip_prefix("file://") {
245 result.push(PathBuf::from(path));
246 }
247 }
248 Some(result)
249 } else {
250 None
251 };
252
253 if let Some(done_fn) = done_fn.take() {
254 (done_fn)(result);
255 }
256 });
257 let block = block.copy();
258 let _: () = msg_send![panel, beginWithCompletionHandler: block];
259 }
260 }
261
262 fn prompt_for_new_path(
263 &self,
264 directory: &Path,
265 done_fn: Box<dyn FnOnce(Option<std::path::PathBuf>)>,
266 ) {
267 unsafe {
268 let panel = NSSavePanel::savePanel(nil);
269 let path = ns_string(directory.to_string_lossy().as_ref());
270 let url = NSURL::fileURLWithPath_isDirectory_(nil, path, true.to_objc());
271 panel.setDirectoryURL(url);
272
273 let done_fn = Cell::new(Some(done_fn));
274 let block = ConcreteBlock::new(move |response: NSModalResponse| {
275 let result = if response == NSModalResponse::NSModalResponseOk {
276 let url = panel.URL();
277 let string = url.absoluteString();
278 let string = std::ffi::CStr::from_ptr(string.UTF8String())
279 .to_string_lossy()
280 .to_string();
281 if let Some(path) = string.strip_prefix("file://") {
282 Some(PathBuf::from(path))
283 } else {
284 None
285 }
286 } else {
287 None
288 };
289
290 if let Some(done_fn) = done_fn.take() {
291 (done_fn)(result);
292 }
293 });
294 let block = block.copy();
295 let _: () = msg_send![panel, beginWithCompletionHandler: block];
296 }
297 }
298}
299
300pub struct MacPlatform {
301 dispatcher: Arc<Dispatcher>,
302 fonts: Arc<FontSystem>,
303 pasteboard: id,
304 text_hash_pasteboard_type: id,
305 metadata_pasteboard_type: id,
306}
307
308impl MacPlatform {
309 pub fn new() -> Self {
310 Self {
311 dispatcher: Arc::new(Dispatcher),
312 fonts: Arc::new(FontSystem::new()),
313 pasteboard: unsafe { NSPasteboard::generalPasteboard(nil) },
314 text_hash_pasteboard_type: unsafe { ns_string("zed-text-hash") },
315 metadata_pasteboard_type: unsafe { ns_string("zed-metadata") },
316 }
317 }
318
319 unsafe fn read_from_pasteboard(&self, kind: id) -> Option<&[u8]> {
320 let data = self.pasteboard.dataForType(kind);
321 if data == nil {
322 None
323 } else {
324 Some(slice::from_raw_parts(
325 data.bytes() as *mut u8,
326 data.length() as usize,
327 ))
328 }
329 }
330}
331
332impl platform::Platform for MacPlatform {
333 fn dispatcher(&self) -> Arc<dyn platform::Dispatcher> {
334 self.dispatcher.clone()
335 }
336
337 fn activate(&self, ignoring_other_apps: bool) {
338 unsafe {
339 let app = NSApplication::sharedApplication(nil);
340 app.activateIgnoringOtherApps_(ignoring_other_apps.to_objc());
341 }
342 }
343
344 fn open_window(
345 &self,
346 id: usize,
347 options: platform::WindowOptions,
348 executor: Rc<executor::Foreground>,
349 ) -> Box<dyn platform::Window> {
350 Box::new(Window::open(id, options, executor, self.fonts()))
351 }
352
353 fn key_window_id(&self) -> Option<usize> {
354 Window::key_window_id()
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}