1use super::{events::key_to_native, BoolExt};
2use crate::{
3 Action, AnyWindowHandle, BackgroundExecutor, ClipboardItem, CursorStyle, ForegroundExecutor,
4 Keymap, MacDispatcher, MacDisplay, MacTextSystem, MacWindow, Menu, MenuItem, PathPromptOptions,
5 Platform, PlatformDisplay, PlatformTextSystem, PlatformWindow, Result, SemanticVersion, Task,
6 WindowAppearance, WindowParams,
7};
8use anyhow::anyhow;
9use block::ConcreteBlock;
10use cocoa::{
11 appkit::{
12 NSApplication, NSApplicationActivationPolicy::NSApplicationActivationPolicyRegular,
13 NSEventModifierFlags, NSMenu, NSMenuItem, NSModalResponse, NSOpenPanel, NSPasteboard,
14 NSPasteboardTypeString, NSSavePanel, NSWindow,
15 },
16 base::{id, nil, selector, BOOL, YES},
17 foundation::{
18 NSArray, NSAutoreleasePool, NSBundle, NSData, NSInteger, NSProcessInfo, NSString,
19 NSUInteger, NSURL,
20 },
21};
22use core_foundation::{
23 base::{CFRelease, CFType, CFTypeRef, OSStatus, TCFType as _},
24 boolean::CFBoolean,
25 data::CFData,
26 dictionary::{CFDictionary, CFDictionaryRef, CFMutableDictionary},
27 runloop::CFRunLoopRun,
28 string::{CFString, CFStringRef},
29};
30use ctor::ctor;
31use futures::channel::oneshot;
32use objc::{
33 class,
34 declare::ClassDecl,
35 msg_send,
36 runtime::{Class, Object, Sel},
37 sel, sel_impl,
38};
39use parking_lot::Mutex;
40use ptr::null_mut;
41use std::{
42 cell::Cell,
43 convert::TryInto,
44 ffi::{c_void, CStr, OsStr},
45 os::{raw::c_char, unix::ffi::OsStrExt},
46 path::{Path, PathBuf},
47 process::Command,
48 ptr,
49 rc::Rc,
50 slice, str,
51 sync::Arc,
52};
53
54use super::renderer;
55
56#[allow(non_upper_case_globals)]
57const NSUTF8StringEncoding: NSUInteger = 4;
58
59const MAC_PLATFORM_IVAR: &str = "platform";
60static mut APP_CLASS: *const Class = ptr::null();
61static mut APP_DELEGATE_CLASS: *const Class = ptr::null();
62
63#[ctor]
64unsafe fn build_classes() {
65 APP_CLASS = {
66 let mut decl = ClassDecl::new("GPUIApplication", class!(NSApplication)).unwrap();
67 decl.add_ivar::<*mut c_void>(MAC_PLATFORM_IVAR);
68 decl.register()
69 };
70
71 APP_DELEGATE_CLASS = {
72 let mut decl = ClassDecl::new("GPUIApplicationDelegate", class!(NSResponder)).unwrap();
73 decl.add_ivar::<*mut c_void>(MAC_PLATFORM_IVAR);
74 decl.add_method(
75 sel!(applicationDidFinishLaunching:),
76 did_finish_launching as extern "C" fn(&mut Object, Sel, id),
77 );
78 decl.add_method(
79 sel!(applicationShouldHandleReopen:hasVisibleWindows:),
80 should_handle_reopen as extern "C" fn(&mut Object, Sel, id, bool),
81 );
82 decl.add_method(
83 sel!(applicationWillTerminate:),
84 will_terminate as extern "C" fn(&mut Object, Sel, id),
85 );
86 decl.add_method(
87 sel!(handleGPUIMenuItem:),
88 handle_menu_item as extern "C" fn(&mut Object, Sel, id),
89 );
90 // Add menu item handlers so that OS save panels have the correct key commands
91 decl.add_method(
92 sel!(cut:),
93 handle_menu_item as extern "C" fn(&mut Object, Sel, id),
94 );
95 decl.add_method(
96 sel!(copy:),
97 handle_menu_item as extern "C" fn(&mut Object, Sel, id),
98 );
99 decl.add_method(
100 sel!(paste:),
101 handle_menu_item as extern "C" fn(&mut Object, Sel, id),
102 );
103 decl.add_method(
104 sel!(selectAll:),
105 handle_menu_item as extern "C" fn(&mut Object, Sel, id),
106 );
107 decl.add_method(
108 sel!(undo:),
109 handle_menu_item as extern "C" fn(&mut Object, Sel, id),
110 );
111 decl.add_method(
112 sel!(redo:),
113 handle_menu_item as extern "C" fn(&mut Object, Sel, id),
114 );
115 decl.add_method(
116 sel!(validateMenuItem:),
117 validate_menu_item as extern "C" fn(&mut Object, Sel, id) -> bool,
118 );
119 decl.add_method(
120 sel!(menuWillOpen:),
121 menu_will_open as extern "C" fn(&mut Object, Sel, id),
122 );
123 decl.add_method(
124 sel!(applicationDockMenu:),
125 handle_dock_menu as extern "C" fn(&mut Object, Sel, id) -> id,
126 );
127 decl.add_method(
128 sel!(application:openURLs:),
129 open_urls as extern "C" fn(&mut Object, Sel, id, id),
130 );
131
132 decl.register()
133 }
134}
135
136pub(crate) struct MacPlatform(Mutex<MacPlatformState>);
137
138pub(crate) struct MacPlatformState {
139 background_executor: BackgroundExecutor,
140 foreground_executor: ForegroundExecutor,
141 text_system: Arc<MacTextSystem>,
142 renderer_context: renderer::Context,
143 headless: bool,
144 pasteboard: id,
145 text_hash_pasteboard_type: id,
146 metadata_pasteboard_type: id,
147 reopen: Option<Box<dyn FnMut()>>,
148 quit: Option<Box<dyn FnMut()>>,
149 menu_command: Option<Box<dyn FnMut(&dyn Action)>>,
150 validate_menu_command: Option<Box<dyn FnMut(&dyn Action) -> bool>>,
151 will_open_menu: Option<Box<dyn FnMut()>>,
152 menu_actions: Vec<Box<dyn Action>>,
153 open_urls: Option<Box<dyn FnMut(Vec<String>)>>,
154 finish_launching: Option<Box<dyn FnOnce()>>,
155 dock_menu: Option<id>,
156}
157
158impl Default for MacPlatform {
159 fn default() -> Self {
160 Self::new(false)
161 }
162}
163
164impl MacPlatform {
165 pub(crate) fn new(headless: bool) -> Self {
166 let dispatcher = Arc::new(MacDispatcher::new());
167 Self(Mutex::new(MacPlatformState {
168 background_executor: BackgroundExecutor::new(dispatcher.clone()),
169 headless,
170 foreground_executor: ForegroundExecutor::new(dispatcher),
171 text_system: Arc::new(MacTextSystem::new()),
172 renderer_context: renderer::Context::default(),
173 pasteboard: unsafe { NSPasteboard::generalPasteboard(nil) },
174 text_hash_pasteboard_type: unsafe { ns_string("zed-text-hash") },
175 metadata_pasteboard_type: unsafe { ns_string("zed-metadata") },
176 reopen: None,
177 quit: None,
178 menu_command: None,
179 validate_menu_command: None,
180 will_open_menu: None,
181 menu_actions: Default::default(),
182 open_urls: None,
183 finish_launching: None,
184 dock_menu: None,
185 }))
186 }
187
188 unsafe fn read_from_pasteboard(&self, pasteboard: *mut Object, kind: id) -> Option<&[u8]> {
189 let data = pasteboard.dataForType(kind);
190 if data == nil {
191 None
192 } else {
193 Some(slice::from_raw_parts(
194 data.bytes() as *mut u8,
195 data.length() as usize,
196 ))
197 }
198 }
199
200 unsafe fn create_menu_bar(
201 &self,
202 menus: Vec<Menu>,
203 delegate: id,
204 actions: &mut Vec<Box<dyn Action>>,
205 keymap: &Keymap,
206 ) -> id {
207 let application_menu = NSMenu::new(nil).autorelease();
208 application_menu.setDelegate_(delegate);
209
210 for menu_config in menus {
211 let menu = NSMenu::new(nil).autorelease();
212 menu.setTitle_(ns_string(&menu_config.name));
213 menu.setDelegate_(delegate);
214
215 for item_config in menu_config.items {
216 menu.addItem_(Self::create_menu_item(
217 item_config,
218 delegate,
219 actions,
220 keymap,
221 ));
222 }
223
224 let menu_item = NSMenuItem::new(nil).autorelease();
225 menu_item.setSubmenu_(menu);
226 application_menu.addItem_(menu_item);
227
228 if menu_config.name == "Window" {
229 let app: id = msg_send![APP_CLASS, sharedApplication];
230 app.setWindowsMenu_(menu);
231 }
232 }
233
234 application_menu
235 }
236
237 unsafe fn create_dock_menu(
238 &self,
239 menu_items: Vec<MenuItem>,
240 delegate: id,
241 actions: &mut Vec<Box<dyn Action>>,
242 keymap: &Keymap,
243 ) -> id {
244 let dock_menu = NSMenu::new(nil);
245 dock_menu.setDelegate_(delegate);
246 for item_config in menu_items {
247 dock_menu.addItem_(Self::create_menu_item(
248 item_config,
249 delegate,
250 actions,
251 keymap,
252 ));
253 }
254
255 dock_menu
256 }
257
258 unsafe fn create_menu_item(
259 item: MenuItem,
260 delegate: id,
261 actions: &mut Vec<Box<dyn Action>>,
262 keymap: &Keymap,
263 ) -> id {
264 match item {
265 MenuItem::Separator => NSMenuItem::separatorItem(nil),
266 MenuItem::Action {
267 name,
268 action,
269 os_action,
270 } => {
271 let keystrokes = keymap
272 .bindings_for_action(action.as_ref())
273 .next()
274 .map(|binding| binding.keystrokes());
275
276 let selector = match os_action {
277 Some(crate::OsAction::Cut) => selector("cut:"),
278 Some(crate::OsAction::Copy) => selector("copy:"),
279 Some(crate::OsAction::Paste) => selector("paste:"),
280 Some(crate::OsAction::SelectAll) => selector("selectAll:"),
281 Some(crate::OsAction::Undo) => selector("undo:"),
282 Some(crate::OsAction::Redo) => selector("redo:"),
283 None => selector("handleGPUIMenuItem:"),
284 };
285
286 let item;
287 if let Some(keystrokes) = keystrokes {
288 if keystrokes.len() == 1 {
289 let keystroke = &keystrokes[0];
290 let mut mask = NSEventModifierFlags::empty();
291 for (modifier, flag) in &[
292 (
293 keystroke.modifiers.platform,
294 NSEventModifierFlags::NSCommandKeyMask,
295 ),
296 (
297 keystroke.modifiers.control,
298 NSEventModifierFlags::NSControlKeyMask,
299 ),
300 (
301 keystroke.modifiers.alt,
302 NSEventModifierFlags::NSAlternateKeyMask,
303 ),
304 (
305 keystroke.modifiers.shift,
306 NSEventModifierFlags::NSShiftKeyMask,
307 ),
308 ] {
309 if *modifier {
310 mask |= *flag;
311 }
312 }
313
314 item = NSMenuItem::alloc(nil)
315 .initWithTitle_action_keyEquivalent_(
316 ns_string(&name),
317 selector,
318 ns_string(key_to_native(&keystroke.key).as_ref()),
319 )
320 .autorelease();
321 item.setKeyEquivalentModifierMask_(mask);
322 }
323 // For multi-keystroke bindings, render the keystroke as part of the title.
324 else {
325 use std::fmt::Write;
326
327 let mut name = format!("{name} [");
328 for (i, keystroke) in keystrokes.iter().enumerate() {
329 if i > 0 {
330 name.push(' ');
331 }
332 write!(&mut name, "{}", keystroke).unwrap();
333 }
334 name.push(']');
335
336 item = NSMenuItem::alloc(nil)
337 .initWithTitle_action_keyEquivalent_(
338 ns_string(&name),
339 selector,
340 ns_string(""),
341 )
342 .autorelease();
343 }
344 } else {
345 item = NSMenuItem::alloc(nil)
346 .initWithTitle_action_keyEquivalent_(
347 ns_string(&name),
348 selector,
349 ns_string(""),
350 )
351 .autorelease();
352 }
353
354 let tag = actions.len() as NSInteger;
355 let _: () = msg_send![item, setTag: tag];
356 actions.push(action);
357 item
358 }
359 MenuItem::Submenu(Menu { name, items }) => {
360 let item = NSMenuItem::new(nil).autorelease();
361 let submenu = NSMenu::new(nil).autorelease();
362 submenu.setDelegate_(delegate);
363 for item in items {
364 submenu.addItem_(Self::create_menu_item(item, delegate, actions, keymap));
365 }
366 item.setSubmenu_(submenu);
367 item.setTitle_(ns_string(&name));
368 item
369 }
370 }
371 }
372
373 fn os_version(&self) -> Result<SemanticVersion> {
374 unsafe {
375 let process_info = NSProcessInfo::processInfo(nil);
376 let version = process_info.operatingSystemVersion();
377 Ok(SemanticVersion::new(
378 version.majorVersion as usize,
379 version.minorVersion as usize,
380 version.patchVersion as usize,
381 ))
382 }
383 }
384}
385
386impl Platform for MacPlatform {
387 fn background_executor(&self) -> BackgroundExecutor {
388 self.0.lock().background_executor.clone()
389 }
390
391 fn foreground_executor(&self) -> crate::ForegroundExecutor {
392 self.0.lock().foreground_executor.clone()
393 }
394
395 fn text_system(&self) -> Arc<dyn PlatformTextSystem> {
396 self.0.lock().text_system.clone()
397 }
398
399 fn run(&self, on_finish_launching: Box<dyn FnOnce()>) {
400 let mut state = self.0.lock();
401 if state.headless {
402 drop(state);
403 on_finish_launching();
404 unsafe { CFRunLoopRun() };
405 } else {
406 state.finish_launching = Some(on_finish_launching);
407 drop(state);
408 }
409
410 unsafe {
411 let app: id = msg_send![APP_CLASS, sharedApplication];
412 let app_delegate: id = msg_send![APP_DELEGATE_CLASS, new];
413 app.setDelegate_(app_delegate);
414
415 let self_ptr = self as *const Self as *const c_void;
416 (*app).set_ivar(MAC_PLATFORM_IVAR, self_ptr);
417 (*app_delegate).set_ivar(MAC_PLATFORM_IVAR, self_ptr);
418
419 let pool = NSAutoreleasePool::new(nil);
420 app.run();
421 pool.drain();
422
423 (*app).set_ivar(MAC_PLATFORM_IVAR, null_mut::<c_void>());
424 (*app.delegate()).set_ivar(MAC_PLATFORM_IVAR, null_mut::<c_void>());
425 }
426 }
427
428 fn quit(&self) {
429 // Quitting the app causes us to close windows, which invokes `Window::on_close` callbacks
430 // synchronously before this method terminates. If we call `Platform::quit` while holding a
431 // borrow of the app state (which most of the time we will do), we will end up
432 // double-borrowing the app state in the `on_close` callbacks for our open windows. To solve
433 // this, we make quitting the application asynchronous so that we aren't holding borrows to
434 // the app state on the stack when we actually terminate the app.
435
436 use super::dispatcher::{dispatch_get_main_queue, dispatch_sys::dispatch_async_f};
437
438 unsafe {
439 dispatch_async_f(dispatch_get_main_queue(), ptr::null_mut(), Some(quit));
440 }
441
442 unsafe extern "C" fn quit(_: *mut c_void) {
443 let app = NSApplication::sharedApplication(nil);
444 let _: () = msg_send![app, terminate: nil];
445 }
446 }
447
448 fn restart(&self, _binary_path: Option<PathBuf>) {
449 use std::os::unix::process::CommandExt as _;
450
451 let app_pid = std::process::id().to_string();
452 let app_path = self
453 .app_path()
454 .ok()
455 // When the app is not bundled, `app_path` returns the
456 // directory containing the executable. Disregard this
457 // and get the path to the executable itself.
458 .and_then(|path| (path.extension()?.to_str()? == "app").then_some(path))
459 .unwrap_or_else(|| std::env::current_exe().unwrap());
460
461 // Wait until this process has exited and then re-open this path.
462 let script = r#"
463 while kill -0 $0 2> /dev/null; do
464 sleep 0.1
465 done
466 open "$1"
467 "#;
468
469 let restart_process = Command::new("/bin/bash")
470 .arg("-c")
471 .arg(script)
472 .arg(app_pid)
473 .arg(app_path)
474 .process_group(0)
475 .spawn();
476
477 match restart_process {
478 Ok(_) => self.quit(),
479 Err(e) => log::error!("failed to spawn restart script: {:?}", e),
480 }
481 }
482
483 fn activate(&self, ignoring_other_apps: bool) {
484 unsafe {
485 let app = NSApplication::sharedApplication(nil);
486 app.activateIgnoringOtherApps_(ignoring_other_apps.to_objc());
487 }
488 }
489
490 fn hide(&self) {
491 unsafe {
492 let app = NSApplication::sharedApplication(nil);
493 let _: () = msg_send![app, hide: nil];
494 }
495 }
496
497 fn hide_other_apps(&self) {
498 unsafe {
499 let app = NSApplication::sharedApplication(nil);
500 let _: () = msg_send![app, hideOtherApplications: nil];
501 }
502 }
503
504 fn unhide_other_apps(&self) {
505 unsafe {
506 let app = NSApplication::sharedApplication(nil);
507 let _: () = msg_send![app, unhideAllApplications: nil];
508 }
509 }
510
511 fn primary_display(&self) -> Option<Rc<dyn PlatformDisplay>> {
512 Some(Rc::new(MacDisplay::primary()))
513 }
514
515 fn displays(&self) -> Vec<Rc<dyn PlatformDisplay>> {
516 MacDisplay::all()
517 .map(|screen| Rc::new(screen) as Rc<_>)
518 .collect()
519 }
520
521 fn active_window(&self) -> Option<AnyWindowHandle> {
522 MacWindow::active_window()
523 }
524
525 fn open_window(
526 &self,
527 handle: AnyWindowHandle,
528 options: WindowParams,
529 ) -> Result<Box<dyn PlatformWindow>> {
530 // Clippy thinks that this evaluates to `()`, for some reason.
531 #[allow(clippy::unit_arg, clippy::clone_on_copy)]
532 let renderer_context = self.0.lock().renderer_context.clone();
533 Ok(Box::new(MacWindow::open(
534 handle,
535 options,
536 self.foreground_executor(),
537 renderer_context,
538 )))
539 }
540
541 fn window_appearance(&self) -> WindowAppearance {
542 unsafe {
543 let app = NSApplication::sharedApplication(nil);
544 let appearance: id = msg_send![app, effectiveAppearance];
545 WindowAppearance::from_native(appearance)
546 }
547 }
548
549 fn open_url(&self, url: &str) {
550 unsafe {
551 let url = NSURL::alloc(nil)
552 .initWithString_(ns_string(url))
553 .autorelease();
554 let workspace: id = msg_send![class!(NSWorkspace), sharedWorkspace];
555 msg_send![workspace, openURL: url]
556 }
557 }
558
559 fn register_url_scheme(&self, scheme: &str) -> Task<anyhow::Result<()>> {
560 // API only available post Monterey
561 // https://developer.apple.com/documentation/appkit/nsworkspace/3753004-setdefaultapplicationaturl
562 let (done_tx, done_rx) = oneshot::channel();
563 if self.os_version().ok() < Some(SemanticVersion::new(12, 0, 0)) {
564 return Task::ready(Err(anyhow!(
565 "macOS 12.0 or later is required to register URL schemes"
566 )));
567 }
568
569 let bundle_id = unsafe {
570 let bundle: id = msg_send![class!(NSBundle), mainBundle];
571 let bundle_id: id = msg_send![bundle, bundleIdentifier];
572 if bundle_id == nil {
573 return Task::ready(Err(anyhow!("Can only register URL scheme in bundled apps")));
574 }
575 bundle_id
576 };
577
578 unsafe {
579 let workspace: id = msg_send![class!(NSWorkspace), sharedWorkspace];
580 let scheme: id = ns_string(scheme);
581 let app: id = msg_send![workspace, URLForApplicationWithBundleIdentifier: bundle_id];
582 if app == nil {
583 return Task::ready(Err(anyhow!(
584 "Cannot register URL scheme until app is installed"
585 )));
586 }
587 let done_tx = Cell::new(Some(done_tx));
588 let block = ConcreteBlock::new(move |error: id| {
589 let result = if error == nil {
590 Ok(())
591 } else {
592 let msg: id = msg_send![error, localizedDescription];
593 Err(anyhow!("Failed to register: {:?}", msg))
594 };
595
596 if let Some(done_tx) = done_tx.take() {
597 let _ = done_tx.send(result);
598 }
599 });
600 let block = block.copy();
601 let _: () = msg_send![workspace, setDefaultApplicationAtURL: app toOpenURLsWithScheme: scheme completionHandler: block];
602 }
603
604 self.background_executor()
605 .spawn(async { crate::Flatten::flatten(done_rx.await.map_err(|e| anyhow!(e))) })
606 }
607
608 fn on_open_urls(&self, callback: Box<dyn FnMut(Vec<String>)>) {
609 self.0.lock().open_urls = Some(callback);
610 }
611
612 fn prompt_for_paths(
613 &self,
614 options: PathPromptOptions,
615 ) -> oneshot::Receiver<Result<Option<Vec<PathBuf>>>> {
616 let (done_tx, done_rx) = oneshot::channel();
617 self.foreground_executor()
618 .spawn(async move {
619 unsafe {
620 let panel = NSOpenPanel::openPanel(nil);
621 panel.setCanChooseDirectories_(options.directories.to_objc());
622 panel.setCanChooseFiles_(options.files.to_objc());
623 panel.setAllowsMultipleSelection_(options.multiple.to_objc());
624 panel.setCanCreateDirectories(true.to_objc());
625 panel.setResolvesAliases_(false.to_objc());
626 let done_tx = Cell::new(Some(done_tx));
627 let block = ConcreteBlock::new(move |response: NSModalResponse| {
628 let result = if response == NSModalResponse::NSModalResponseOk {
629 let mut result = Vec::new();
630 let urls = panel.URLs();
631 for i in 0..urls.count() {
632 let url = urls.objectAtIndex(i);
633 if url.isFileURL() == YES {
634 if let Ok(path) = ns_url_to_path(url) {
635 result.push(path)
636 }
637 }
638 }
639 Some(result)
640 } else {
641 None
642 };
643
644 if let Some(done_tx) = done_tx.take() {
645 let _ = done_tx.send(Ok(result));
646 }
647 });
648 let block = block.copy();
649 let _: () = msg_send![panel, beginWithCompletionHandler: block];
650 }
651 })
652 .detach();
653 done_rx
654 }
655
656 fn prompt_for_new_path(&self, directory: &Path) -> oneshot::Receiver<Result<Option<PathBuf>>> {
657 let directory = directory.to_owned();
658 let (done_tx, done_rx) = oneshot::channel();
659 self.foreground_executor()
660 .spawn(async move {
661 unsafe {
662 let panel = NSSavePanel::savePanel(nil);
663 let path = ns_string(directory.to_string_lossy().as_ref());
664 let url = NSURL::fileURLWithPath_isDirectory_(nil, path, true.to_objc());
665 panel.setDirectoryURL(url);
666
667 let done_tx = Cell::new(Some(done_tx));
668 let block = ConcreteBlock::new(move |response: NSModalResponse| {
669 let mut result = None;
670 if response == NSModalResponse::NSModalResponseOk {
671 let url = panel.URL();
672 if url.isFileURL() == YES {
673 result = ns_url_to_path(panel.URL()).ok()
674 }
675 }
676
677 if let Some(done_tx) = done_tx.take() {
678 let _ = done_tx.send(Ok(result));
679 }
680 });
681 let block = block.copy();
682 let _: () = msg_send![panel, beginWithCompletionHandler: block];
683 }
684 })
685 .detach();
686
687 done_rx
688 }
689
690 fn reveal_path(&self, path: &Path) {
691 unsafe {
692 let path = path.to_path_buf();
693 self.0
694 .lock()
695 .background_executor
696 .spawn(async move {
697 let full_path = ns_string(path.to_str().unwrap_or(""));
698 let root_full_path = ns_string("");
699 let workspace: id = msg_send![class!(NSWorkspace), sharedWorkspace];
700 let _: BOOL = msg_send![
701 workspace,
702 selectFile: full_path
703 inFileViewerRootedAtPath: root_full_path
704 ];
705 })
706 .detach();
707 }
708 }
709
710 fn on_quit(&self, callback: Box<dyn FnMut()>) {
711 self.0.lock().quit = Some(callback);
712 }
713
714 fn on_reopen(&self, callback: Box<dyn FnMut()>) {
715 self.0.lock().reopen = Some(callback);
716 }
717
718 fn on_app_menu_action(&self, callback: Box<dyn FnMut(&dyn Action)>) {
719 self.0.lock().menu_command = Some(callback);
720 }
721
722 fn on_will_open_app_menu(&self, callback: Box<dyn FnMut()>) {
723 self.0.lock().will_open_menu = Some(callback);
724 }
725
726 fn on_validate_app_menu_command(&self, callback: Box<dyn FnMut(&dyn Action) -> bool>) {
727 self.0.lock().validate_menu_command = Some(callback);
728 }
729
730 fn app_path(&self) -> Result<PathBuf> {
731 unsafe {
732 let bundle: id = NSBundle::mainBundle();
733 if bundle.is_null() {
734 Err(anyhow!("app is not running inside a bundle"))
735 } else {
736 Ok(path_from_objc(msg_send![bundle, bundlePath]))
737 }
738 }
739 }
740
741 fn set_menus(&self, menus: Vec<Menu>, keymap: &Keymap) {
742 unsafe {
743 let app: id = msg_send![APP_CLASS, sharedApplication];
744 let mut state = self.0.lock();
745 let actions = &mut state.menu_actions;
746 app.setMainMenu_(self.create_menu_bar(menus, app.delegate(), actions, keymap));
747 }
748 }
749
750 fn set_dock_menu(&self, menu: Vec<MenuItem>, keymap: &Keymap) {
751 unsafe {
752 let app: id = msg_send![APP_CLASS, sharedApplication];
753 let mut state = self.0.lock();
754 let actions = &mut state.menu_actions;
755 let new = self.create_dock_menu(menu, app.delegate(), actions, keymap);
756 if let Some(old) = state.dock_menu.replace(new) {
757 CFRelease(old as _)
758 }
759 }
760 }
761
762 fn add_recent_document(&self, path: &Path) {
763 if let Some(path_str) = path.to_str() {
764 unsafe {
765 let document_controller: id =
766 msg_send![class!(NSDocumentController), sharedDocumentController];
767 let url: id = NSURL::fileURLWithPath_(nil, ns_string(path_str));
768 let _: () = msg_send![document_controller, noteNewRecentDocumentURL:url];
769 }
770 }
771 }
772
773 fn path_for_auxiliary_executable(&self, name: &str) -> Result<PathBuf> {
774 unsafe {
775 let bundle: id = NSBundle::mainBundle();
776 if bundle.is_null() {
777 Err(anyhow!("app is not running inside a bundle"))
778 } else {
779 let name = ns_string(name);
780 let url: id = msg_send![bundle, URLForAuxiliaryExecutable: name];
781 if url.is_null() {
782 Err(anyhow!("resource not found"))
783 } else {
784 ns_url_to_path(url)
785 }
786 }
787 }
788 }
789
790 /// Match cursor style to one of the styles available
791 /// in macOS's [NSCursor](https://developer.apple.com/documentation/appkit/nscursor).
792 fn set_cursor_style(&self, style: CursorStyle) {
793 unsafe {
794 let new_cursor: id = match style {
795 CursorStyle::Arrow => msg_send![class!(NSCursor), arrowCursor],
796 CursorStyle::IBeam => msg_send![class!(NSCursor), IBeamCursor],
797 CursorStyle::Crosshair => msg_send![class!(NSCursor), crosshairCursor],
798 CursorStyle::ClosedHand => msg_send![class!(NSCursor), closedHandCursor],
799 CursorStyle::OpenHand => msg_send![class!(NSCursor), openHandCursor],
800 CursorStyle::PointingHand => msg_send![class!(NSCursor), pointingHandCursor],
801 CursorStyle::ResizeLeftRight => msg_send![class!(NSCursor), resizeLeftRightCursor],
802 CursorStyle::ResizeUpDown => msg_send![class!(NSCursor), resizeUpDownCursor],
803 CursorStyle::ResizeLeft => msg_send![class!(NSCursor), resizeLeftCursor],
804 CursorStyle::ResizeRight => msg_send![class!(NSCursor), resizeRightCursor],
805 CursorStyle::ResizeColumn => msg_send![class!(NSCursor), resizeLeftRightCursor],
806 CursorStyle::ResizeRow => msg_send![class!(NSCursor), resizeUpDownCursor],
807 CursorStyle::ResizeUp => msg_send![class!(NSCursor), resizeUpCursor],
808 CursorStyle::ResizeDown => msg_send![class!(NSCursor), resizeDownCursor],
809
810 // Undocumented, private class methods:
811 // https://stackoverflow.com/questions/27242353/cocoa-predefined-resize-mouse-cursor
812 CursorStyle::ResizeUpLeftDownRight => {
813 msg_send![class!(NSCursor), _windowResizeNorthWestSouthEastCursor]
814 }
815 CursorStyle::ResizeUpRightDownLeft => {
816 msg_send![class!(NSCursor), _windowResizeNorthEastSouthWestCursor]
817 }
818
819 CursorStyle::IBeamCursorForVerticalLayout => {
820 msg_send![class!(NSCursor), IBeamCursorForVerticalLayout]
821 }
822 CursorStyle::OperationNotAllowed => {
823 msg_send![class!(NSCursor), operationNotAllowedCursor]
824 }
825 CursorStyle::DragLink => msg_send![class!(NSCursor), dragLinkCursor],
826 CursorStyle::DragCopy => msg_send![class!(NSCursor), dragCopyCursor],
827 CursorStyle::ContextualMenu => msg_send![class!(NSCursor), contextualMenuCursor],
828 };
829
830 let old_cursor: id = msg_send![class!(NSCursor), currentCursor];
831 if new_cursor != old_cursor {
832 let _: () = msg_send![new_cursor, set];
833 }
834 }
835 }
836
837 fn should_auto_hide_scrollbars(&self) -> bool {
838 #[allow(non_upper_case_globals)]
839 const NSScrollerStyleOverlay: NSInteger = 1;
840
841 unsafe {
842 let style: NSInteger = msg_send![class!(NSScroller), preferredScrollerStyle];
843 style == NSScrollerStyleOverlay
844 }
845 }
846
847 fn write_to_clipboard(&self, item: ClipboardItem) {
848 let state = self.0.lock();
849 unsafe {
850 state.pasteboard.clearContents();
851
852 let text_bytes = NSData::dataWithBytes_length_(
853 nil,
854 item.text.as_ptr() as *const c_void,
855 item.text.len() as u64,
856 );
857 state
858 .pasteboard
859 .setData_forType(text_bytes, NSPasteboardTypeString);
860
861 if let Some(metadata) = item.metadata.as_ref() {
862 let hash_bytes = ClipboardItem::text_hash(&item.text).to_be_bytes();
863 let hash_bytes = NSData::dataWithBytes_length_(
864 nil,
865 hash_bytes.as_ptr() as *const c_void,
866 hash_bytes.len() as u64,
867 );
868 state
869 .pasteboard
870 .setData_forType(hash_bytes, state.text_hash_pasteboard_type);
871
872 let metadata_bytes = NSData::dataWithBytes_length_(
873 nil,
874 metadata.as_ptr() as *const c_void,
875 metadata.len() as u64,
876 );
877 state
878 .pasteboard
879 .setData_forType(metadata_bytes, state.metadata_pasteboard_type);
880 }
881 }
882 }
883
884 fn read_from_clipboard(&self) -> Option<ClipboardItem> {
885 let state = self.0.lock();
886 unsafe {
887 if let Some(text_bytes) =
888 self.read_from_pasteboard(state.pasteboard, NSPasteboardTypeString)
889 {
890 let text = String::from_utf8_lossy(text_bytes).to_string();
891 let hash_bytes = self
892 .read_from_pasteboard(state.pasteboard, state.text_hash_pasteboard_type)
893 .and_then(|bytes| bytes.try_into().ok())
894 .map(u64::from_be_bytes);
895 let metadata_bytes = self
896 .read_from_pasteboard(state.pasteboard, state.metadata_pasteboard_type)
897 .and_then(|bytes| String::from_utf8(bytes.to_vec()).ok());
898
899 if let Some((hash, metadata)) = hash_bytes.zip(metadata_bytes) {
900 if hash == ClipboardItem::text_hash(&text) {
901 Some(ClipboardItem {
902 text,
903 metadata: Some(metadata),
904 })
905 } else {
906 Some(ClipboardItem {
907 text,
908 metadata: None,
909 })
910 }
911 } else {
912 Some(ClipboardItem {
913 text,
914 metadata: None,
915 })
916 }
917 } else {
918 None
919 }
920 }
921 }
922
923 fn write_credentials(&self, url: &str, username: &str, password: &[u8]) -> Task<Result<()>> {
924 let url = url.to_string();
925 let username = username.to_string();
926 let password = password.to_vec();
927 self.background_executor().spawn(async move {
928 unsafe {
929 use security::*;
930
931 let url = CFString::from(url.as_str());
932 let username = CFString::from(username.as_str());
933 let password = CFData::from_buffer(&password);
934
935 // First, check if there are already credentials for the given server. If so, then
936 // update the username and password.
937 let mut verb = "updating";
938 let mut query_attrs = CFMutableDictionary::with_capacity(2);
939 query_attrs.set(kSecClass as *const _, kSecClassInternetPassword as *const _);
940 query_attrs.set(kSecAttrServer as *const _, url.as_CFTypeRef());
941
942 let mut attrs = CFMutableDictionary::with_capacity(4);
943 attrs.set(kSecClass as *const _, kSecClassInternetPassword as *const _);
944 attrs.set(kSecAttrServer as *const _, url.as_CFTypeRef());
945 attrs.set(kSecAttrAccount as *const _, username.as_CFTypeRef());
946 attrs.set(kSecValueData as *const _, password.as_CFTypeRef());
947
948 let mut status = SecItemUpdate(
949 query_attrs.as_concrete_TypeRef(),
950 attrs.as_concrete_TypeRef(),
951 );
952
953 // If there were no existing credentials for the given server, then create them.
954 if status == errSecItemNotFound {
955 verb = "creating";
956 status = SecItemAdd(attrs.as_concrete_TypeRef(), ptr::null_mut());
957 }
958
959 if status != errSecSuccess {
960 return Err(anyhow!("{} password failed: {}", verb, status));
961 }
962 }
963 Ok(())
964 })
965 }
966
967 fn read_credentials(&self, url: &str) -> Task<Result<Option<(String, Vec<u8>)>>> {
968 let url = url.to_string();
969 self.background_executor().spawn(async move {
970 let url = CFString::from(url.as_str());
971 let cf_true = CFBoolean::true_value().as_CFTypeRef();
972
973 unsafe {
974 use security::*;
975
976 // Find any credentials for the given server URL.
977 let mut attrs = CFMutableDictionary::with_capacity(5);
978 attrs.set(kSecClass as *const _, kSecClassInternetPassword as *const _);
979 attrs.set(kSecAttrServer as *const _, url.as_CFTypeRef());
980 attrs.set(kSecReturnAttributes as *const _, cf_true);
981 attrs.set(kSecReturnData as *const _, cf_true);
982
983 let mut result = CFTypeRef::from(ptr::null());
984 let status = SecItemCopyMatching(attrs.as_concrete_TypeRef(), &mut result);
985 match status {
986 security::errSecSuccess => {}
987 security::errSecItemNotFound | security::errSecUserCanceled => return Ok(None),
988 _ => return Err(anyhow!("reading password failed: {}", status)),
989 }
990
991 let result = CFType::wrap_under_create_rule(result)
992 .downcast::<CFDictionary>()
993 .ok_or_else(|| anyhow!("keychain item was not a dictionary"))?;
994 let username = result
995 .find(kSecAttrAccount as *const _)
996 .ok_or_else(|| anyhow!("account was missing from keychain item"))?;
997 let username = CFType::wrap_under_get_rule(*username)
998 .downcast::<CFString>()
999 .ok_or_else(|| anyhow!("account was not a string"))?;
1000 let password = result
1001 .find(kSecValueData as *const _)
1002 .ok_or_else(|| anyhow!("password was missing from keychain item"))?;
1003 let password = CFType::wrap_under_get_rule(*password)
1004 .downcast::<CFData>()
1005 .ok_or_else(|| anyhow!("password was not a string"))?;
1006
1007 Ok(Some((username.to_string(), password.bytes().to_vec())))
1008 }
1009 })
1010 }
1011
1012 fn delete_credentials(&self, url: &str) -> Task<Result<()>> {
1013 let url = url.to_string();
1014
1015 self.background_executor().spawn(async move {
1016 unsafe {
1017 use security::*;
1018
1019 let url = CFString::from(url.as_str());
1020 let mut query_attrs = CFMutableDictionary::with_capacity(2);
1021 query_attrs.set(kSecClass as *const _, kSecClassInternetPassword as *const _);
1022 query_attrs.set(kSecAttrServer as *const _, url.as_CFTypeRef());
1023
1024 let status = SecItemDelete(query_attrs.as_concrete_TypeRef());
1025
1026 if status != errSecSuccess {
1027 return Err(anyhow!("delete password failed: {}", status));
1028 }
1029 }
1030 Ok(())
1031 })
1032 }
1033}
1034
1035unsafe fn path_from_objc(path: id) -> PathBuf {
1036 let len = msg_send![path, lengthOfBytesUsingEncoding: NSUTF8StringEncoding];
1037 let bytes = path.UTF8String() as *const u8;
1038 let path = str::from_utf8(slice::from_raw_parts(bytes, len)).unwrap();
1039 PathBuf::from(path)
1040}
1041
1042unsafe fn get_mac_platform(object: &mut Object) -> &MacPlatform {
1043 let platform_ptr: *mut c_void = *object.get_ivar(MAC_PLATFORM_IVAR);
1044 assert!(!platform_ptr.is_null());
1045 &*(platform_ptr as *const MacPlatform)
1046}
1047
1048extern "C" fn did_finish_launching(this: &mut Object, _: Sel, _: id) {
1049 unsafe {
1050 let app: id = msg_send![APP_CLASS, sharedApplication];
1051 app.setActivationPolicy_(NSApplicationActivationPolicyRegular);
1052 let platform = get_mac_platform(this);
1053 let callback = platform.0.lock().finish_launching.take();
1054 if let Some(callback) = callback {
1055 callback();
1056 }
1057 }
1058}
1059
1060extern "C" fn should_handle_reopen(this: &mut Object, _: Sel, _: id, has_open_windows: bool) {
1061 if !has_open_windows {
1062 let platform = unsafe { get_mac_platform(this) };
1063 let mut lock = platform.0.lock();
1064 if let Some(mut callback) = lock.reopen.take() {
1065 drop(lock);
1066 callback();
1067 platform.0.lock().reopen.get_or_insert(callback);
1068 }
1069 }
1070}
1071
1072extern "C" fn will_terminate(this: &mut Object, _: Sel, _: id) {
1073 let platform = unsafe { get_mac_platform(this) };
1074 let mut lock = platform.0.lock();
1075 if let Some(mut callback) = lock.quit.take() {
1076 drop(lock);
1077 callback();
1078 platform.0.lock().quit.get_or_insert(callback);
1079 }
1080}
1081
1082extern "C" fn open_urls(this: &mut Object, _: Sel, _: id, urls: id) {
1083 let urls = unsafe {
1084 (0..urls.count())
1085 .filter_map(|i| {
1086 let url = urls.objectAtIndex(i);
1087 match CStr::from_ptr(url.absoluteString().UTF8String() as *mut c_char).to_str() {
1088 Ok(string) => Some(string.to_string()),
1089 Err(err) => {
1090 log::error!("error converting path to string: {}", err);
1091 None
1092 }
1093 }
1094 })
1095 .collect::<Vec<_>>()
1096 };
1097 let platform = unsafe { get_mac_platform(this) };
1098 let mut lock = platform.0.lock();
1099 if let Some(mut callback) = lock.open_urls.take() {
1100 drop(lock);
1101 callback(urls);
1102 platform.0.lock().open_urls.get_or_insert(callback);
1103 }
1104}
1105
1106extern "C" fn handle_menu_item(this: &mut Object, _: Sel, item: id) {
1107 unsafe {
1108 let platform = get_mac_platform(this);
1109 let mut lock = platform.0.lock();
1110 if let Some(mut callback) = lock.menu_command.take() {
1111 let tag: NSInteger = msg_send![item, tag];
1112 let index = tag as usize;
1113 if let Some(action) = lock.menu_actions.get(index) {
1114 let action = action.boxed_clone();
1115 drop(lock);
1116 callback(&*action);
1117 }
1118 platform.0.lock().menu_command.get_or_insert(callback);
1119 }
1120 }
1121}
1122
1123extern "C" fn validate_menu_item(this: &mut Object, _: Sel, item: id) -> bool {
1124 unsafe {
1125 let mut result = false;
1126 let platform = get_mac_platform(this);
1127 let mut lock = platform.0.lock();
1128 if let Some(mut callback) = lock.validate_menu_command.take() {
1129 let tag: NSInteger = msg_send![item, tag];
1130 let index = tag as usize;
1131 if let Some(action) = lock.menu_actions.get(index) {
1132 let action = action.boxed_clone();
1133 drop(lock);
1134 result = callback(action.as_ref());
1135 }
1136 platform
1137 .0
1138 .lock()
1139 .validate_menu_command
1140 .get_or_insert(callback);
1141 }
1142 result
1143 }
1144}
1145
1146extern "C" fn menu_will_open(this: &mut Object, _: Sel, _: id) {
1147 unsafe {
1148 let platform = get_mac_platform(this);
1149 let mut lock = platform.0.lock();
1150 if let Some(mut callback) = lock.will_open_menu.take() {
1151 drop(lock);
1152 callback();
1153 platform.0.lock().will_open_menu.get_or_insert(callback);
1154 }
1155 }
1156}
1157
1158extern "C" fn handle_dock_menu(this: &mut Object, _: Sel, _: id) -> id {
1159 unsafe {
1160 let platform = get_mac_platform(this);
1161 let mut state = platform.0.lock();
1162 if let Some(id) = state.dock_menu {
1163 id
1164 } else {
1165 nil
1166 }
1167 }
1168}
1169
1170unsafe fn ns_string(string: &str) -> id {
1171 NSString::alloc(nil).init_str(string).autorelease()
1172}
1173
1174unsafe fn ns_url_to_path(url: id) -> Result<PathBuf> {
1175 let path: *mut c_char = msg_send![url, fileSystemRepresentation];
1176 if path.is_null() {
1177 Err(anyhow!(
1178 "url is not a file path: {}",
1179 CStr::from_ptr(url.absoluteString().UTF8String()).to_string_lossy()
1180 ))
1181 } else {
1182 Ok(PathBuf::from(OsStr::from_bytes(
1183 CStr::from_ptr(path).to_bytes(),
1184 )))
1185 }
1186}
1187
1188mod security {
1189 #![allow(non_upper_case_globals)]
1190 use super::*;
1191
1192 #[link(name = "Security", kind = "framework")]
1193 extern "C" {
1194 pub static kSecClass: CFStringRef;
1195 pub static kSecClassInternetPassword: CFStringRef;
1196 pub static kSecAttrServer: CFStringRef;
1197 pub static kSecAttrAccount: CFStringRef;
1198 pub static kSecValueData: CFStringRef;
1199 pub static kSecReturnAttributes: CFStringRef;
1200 pub static kSecReturnData: CFStringRef;
1201
1202 pub fn SecItemAdd(attributes: CFDictionaryRef, result: *mut CFTypeRef) -> OSStatus;
1203 pub fn SecItemUpdate(query: CFDictionaryRef, attributes: CFDictionaryRef) -> OSStatus;
1204 pub fn SecItemDelete(query: CFDictionaryRef) -> OSStatus;
1205 pub fn SecItemCopyMatching(query: CFDictionaryRef, result: *mut CFTypeRef) -> OSStatus;
1206 }
1207
1208 pub const errSecSuccess: OSStatus = 0;
1209 pub const errSecUserCanceled: OSStatus = -128;
1210 pub const errSecItemNotFound: OSStatus = -25300;
1211}
1212
1213#[cfg(test)]
1214mod tests {
1215 use crate::ClipboardItem;
1216
1217 use super::*;
1218
1219 #[test]
1220 fn test_clipboard() {
1221 let platform = build_platform();
1222 assert_eq!(platform.read_from_clipboard(), None);
1223
1224 let item = ClipboardItem::new("1".to_string());
1225 platform.write_to_clipboard(item.clone());
1226 assert_eq!(platform.read_from_clipboard(), Some(item));
1227
1228 let item = ClipboardItem::new("2".to_string()).with_metadata(vec![3, 4]);
1229 platform.write_to_clipboard(item.clone());
1230 assert_eq!(platform.read_from_clipboard(), Some(item));
1231
1232 let text_from_other_app = "text from other app";
1233 unsafe {
1234 let bytes = NSData::dataWithBytes_length_(
1235 nil,
1236 text_from_other_app.as_ptr() as *const c_void,
1237 text_from_other_app.len() as u64,
1238 );
1239 platform
1240 .0
1241 .lock()
1242 .pasteboard
1243 .setData_forType(bytes, NSPasteboardTypeString);
1244 }
1245 assert_eq!(
1246 platform.read_from_clipboard(),
1247 Some(ClipboardItem::new(text_from_other_app.to_string()))
1248 );
1249 }
1250
1251 fn build_platform() -> MacPlatform {
1252 let platform = MacPlatform::new(false);
1253 platform.0.lock().pasteboard = unsafe { NSPasteboard::pasteboardWithUniqueName(nil) };
1254 platform
1255 }
1256}