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 // Returns the windows ordered front-to-back, meaning that the active
526 // window is the first one in the returned vec.
527 fn window_stack(&self) -> Option<Vec<AnyWindowHandle>> {
528 Some(MacWindow::ordered_windows())
529 }
530
531 fn open_window(
532 &self,
533 handle: AnyWindowHandle,
534 options: WindowParams,
535 ) -> Result<Box<dyn PlatformWindow>> {
536 // Clippy thinks that this evaluates to `()`, for some reason.
537 #[allow(clippy::unit_arg, clippy::clone_on_copy)]
538 let renderer_context = self.0.lock().renderer_context.clone();
539 Ok(Box::new(MacWindow::open(
540 handle,
541 options,
542 self.foreground_executor(),
543 renderer_context,
544 )))
545 }
546
547 fn window_appearance(&self) -> WindowAppearance {
548 unsafe {
549 let app = NSApplication::sharedApplication(nil);
550 let appearance: id = msg_send![app, effectiveAppearance];
551 WindowAppearance::from_native(appearance)
552 }
553 }
554
555 fn open_url(&self, url: &str) {
556 unsafe {
557 let url = NSURL::alloc(nil)
558 .initWithString_(ns_string(url))
559 .autorelease();
560 let workspace: id = msg_send![class!(NSWorkspace), sharedWorkspace];
561 msg_send![workspace, openURL: url]
562 }
563 }
564
565 fn register_url_scheme(&self, scheme: &str) -> Task<anyhow::Result<()>> {
566 // API only available post Monterey
567 // https://developer.apple.com/documentation/appkit/nsworkspace/3753004-setdefaultapplicationaturl
568 let (done_tx, done_rx) = oneshot::channel();
569 if self.os_version().ok() < Some(SemanticVersion::new(12, 0, 0)) {
570 return Task::ready(Err(anyhow!(
571 "macOS 12.0 or later is required to register URL schemes"
572 )));
573 }
574
575 let bundle_id = unsafe {
576 let bundle: id = msg_send![class!(NSBundle), mainBundle];
577 let bundle_id: id = msg_send![bundle, bundleIdentifier];
578 if bundle_id == nil {
579 return Task::ready(Err(anyhow!("Can only register URL scheme in bundled apps")));
580 }
581 bundle_id
582 };
583
584 unsafe {
585 let workspace: id = msg_send![class!(NSWorkspace), sharedWorkspace];
586 let scheme: id = ns_string(scheme);
587 let app: id = msg_send![workspace, URLForApplicationWithBundleIdentifier: bundle_id];
588 if app == nil {
589 return Task::ready(Err(anyhow!(
590 "Cannot register URL scheme until app is installed"
591 )));
592 }
593 let done_tx = Cell::new(Some(done_tx));
594 let block = ConcreteBlock::new(move |error: id| {
595 let result = if error == nil {
596 Ok(())
597 } else {
598 let msg: id = msg_send![error, localizedDescription];
599 Err(anyhow!("Failed to register: {:?}", msg))
600 };
601
602 if let Some(done_tx) = done_tx.take() {
603 let _ = done_tx.send(result);
604 }
605 });
606 let block = block.copy();
607 let _: () = msg_send![workspace, setDefaultApplicationAtURL: app toOpenURLsWithScheme: scheme completionHandler: block];
608 }
609
610 self.background_executor()
611 .spawn(async { crate::Flatten::flatten(done_rx.await.map_err(|e| anyhow!(e))) })
612 }
613
614 fn on_open_urls(&self, callback: Box<dyn FnMut(Vec<String>)>) {
615 self.0.lock().open_urls = Some(callback);
616 }
617
618 fn prompt_for_paths(
619 &self,
620 options: PathPromptOptions,
621 ) -> oneshot::Receiver<Result<Option<Vec<PathBuf>>>> {
622 let (done_tx, done_rx) = oneshot::channel();
623 self.foreground_executor()
624 .spawn(async move {
625 unsafe {
626 let panel = NSOpenPanel::openPanel(nil);
627 panel.setCanChooseDirectories_(options.directories.to_objc());
628 panel.setCanChooseFiles_(options.files.to_objc());
629 panel.setAllowsMultipleSelection_(options.multiple.to_objc());
630 panel.setCanCreateDirectories(true.to_objc());
631 panel.setResolvesAliases_(false.to_objc());
632 let done_tx = Cell::new(Some(done_tx));
633 let block = ConcreteBlock::new(move |response: NSModalResponse| {
634 let result = if response == NSModalResponse::NSModalResponseOk {
635 let mut result = Vec::new();
636 let urls = panel.URLs();
637 for i in 0..urls.count() {
638 let url = urls.objectAtIndex(i);
639 if url.isFileURL() == YES {
640 if let Ok(path) = ns_url_to_path(url) {
641 result.push(path)
642 }
643 }
644 }
645 Some(result)
646 } else {
647 None
648 };
649
650 if let Some(done_tx) = done_tx.take() {
651 let _ = done_tx.send(Ok(result));
652 }
653 });
654 let block = block.copy();
655 let _: () = msg_send![panel, beginWithCompletionHandler: block];
656 }
657 })
658 .detach();
659 done_rx
660 }
661
662 fn prompt_for_new_path(&self, directory: &Path) -> oneshot::Receiver<Result<Option<PathBuf>>> {
663 let directory = directory.to_owned();
664 let (done_tx, done_rx) = oneshot::channel();
665 self.foreground_executor()
666 .spawn(async move {
667 unsafe {
668 let panel = NSSavePanel::savePanel(nil);
669 let path = ns_string(directory.to_string_lossy().as_ref());
670 let url = NSURL::fileURLWithPath_isDirectory_(nil, path, true.to_objc());
671 panel.setDirectoryURL(url);
672
673 let done_tx = Cell::new(Some(done_tx));
674 let block = ConcreteBlock::new(move |response: NSModalResponse| {
675 let mut result = None;
676 if response == NSModalResponse::NSModalResponseOk {
677 let url = panel.URL();
678 if url.isFileURL() == YES {
679 result = ns_url_to_path(panel.URL()).ok()
680 }
681 }
682
683 if let Some(done_tx) = done_tx.take() {
684 let _ = done_tx.send(Ok(result));
685 }
686 });
687 let block = block.copy();
688 let _: () = msg_send![panel, beginWithCompletionHandler: block];
689 }
690 })
691 .detach();
692
693 done_rx
694 }
695
696 fn reveal_path(&self, path: &Path) {
697 unsafe {
698 let path = path.to_path_buf();
699 self.0
700 .lock()
701 .background_executor
702 .spawn(async move {
703 let full_path = ns_string(path.to_str().unwrap_or(""));
704 let root_full_path = ns_string("");
705 let workspace: id = msg_send![class!(NSWorkspace), sharedWorkspace];
706 let _: BOOL = msg_send![
707 workspace,
708 selectFile: full_path
709 inFileViewerRootedAtPath: root_full_path
710 ];
711 })
712 .detach();
713 }
714 }
715
716 fn on_quit(&self, callback: Box<dyn FnMut()>) {
717 self.0.lock().quit = Some(callback);
718 }
719
720 fn on_reopen(&self, callback: Box<dyn FnMut()>) {
721 self.0.lock().reopen = Some(callback);
722 }
723
724 fn on_app_menu_action(&self, callback: Box<dyn FnMut(&dyn Action)>) {
725 self.0.lock().menu_command = Some(callback);
726 }
727
728 fn on_will_open_app_menu(&self, callback: Box<dyn FnMut()>) {
729 self.0.lock().will_open_menu = Some(callback);
730 }
731
732 fn on_validate_app_menu_command(&self, callback: Box<dyn FnMut(&dyn Action) -> bool>) {
733 self.0.lock().validate_menu_command = Some(callback);
734 }
735
736 fn app_path(&self) -> Result<PathBuf> {
737 unsafe {
738 let bundle: id = NSBundle::mainBundle();
739 if bundle.is_null() {
740 Err(anyhow!("app is not running inside a bundle"))
741 } else {
742 Ok(path_from_objc(msg_send![bundle, bundlePath]))
743 }
744 }
745 }
746
747 fn set_menus(&self, menus: Vec<Menu>, keymap: &Keymap) {
748 unsafe {
749 let app: id = msg_send![APP_CLASS, sharedApplication];
750 let mut state = self.0.lock();
751 let actions = &mut state.menu_actions;
752 app.setMainMenu_(self.create_menu_bar(menus, app.delegate(), actions, keymap));
753 }
754 }
755
756 fn set_dock_menu(&self, menu: Vec<MenuItem>, keymap: &Keymap) {
757 unsafe {
758 let app: id = msg_send![APP_CLASS, sharedApplication];
759 let mut state = self.0.lock();
760 let actions = &mut state.menu_actions;
761 let new = self.create_dock_menu(menu, app.delegate(), actions, keymap);
762 if let Some(old) = state.dock_menu.replace(new) {
763 CFRelease(old as _)
764 }
765 }
766 }
767
768 fn add_recent_document(&self, path: &Path) {
769 if let Some(path_str) = path.to_str() {
770 unsafe {
771 let document_controller: id =
772 msg_send![class!(NSDocumentController), sharedDocumentController];
773 let url: id = NSURL::fileURLWithPath_(nil, ns_string(path_str));
774 let _: () = msg_send![document_controller, noteNewRecentDocumentURL:url];
775 }
776 }
777 }
778
779 fn path_for_auxiliary_executable(&self, name: &str) -> Result<PathBuf> {
780 unsafe {
781 let bundle: id = NSBundle::mainBundle();
782 if bundle.is_null() {
783 Err(anyhow!("app is not running inside a bundle"))
784 } else {
785 let name = ns_string(name);
786 let url: id = msg_send![bundle, URLForAuxiliaryExecutable: name];
787 if url.is_null() {
788 Err(anyhow!("resource not found"))
789 } else {
790 ns_url_to_path(url)
791 }
792 }
793 }
794 }
795
796 /// Match cursor style to one of the styles available
797 /// in macOS's [NSCursor](https://developer.apple.com/documentation/appkit/nscursor).
798 fn set_cursor_style(&self, style: CursorStyle) {
799 unsafe {
800 let new_cursor: id = match style {
801 CursorStyle::Arrow => msg_send![class!(NSCursor), arrowCursor],
802 CursorStyle::IBeam => msg_send![class!(NSCursor), IBeamCursor],
803 CursorStyle::Crosshair => msg_send![class!(NSCursor), crosshairCursor],
804 CursorStyle::ClosedHand => msg_send![class!(NSCursor), closedHandCursor],
805 CursorStyle::OpenHand => msg_send![class!(NSCursor), openHandCursor],
806 CursorStyle::PointingHand => msg_send![class!(NSCursor), pointingHandCursor],
807 CursorStyle::ResizeLeftRight => msg_send![class!(NSCursor), resizeLeftRightCursor],
808 CursorStyle::ResizeUpDown => msg_send![class!(NSCursor), resizeUpDownCursor],
809 CursorStyle::ResizeLeft => msg_send![class!(NSCursor), resizeLeftCursor],
810 CursorStyle::ResizeRight => msg_send![class!(NSCursor), resizeRightCursor],
811 CursorStyle::ResizeColumn => msg_send![class!(NSCursor), resizeLeftRightCursor],
812 CursorStyle::ResizeRow => msg_send![class!(NSCursor), resizeUpDownCursor],
813 CursorStyle::ResizeUp => msg_send![class!(NSCursor), resizeUpCursor],
814 CursorStyle::ResizeDown => msg_send![class!(NSCursor), resizeDownCursor],
815
816 // Undocumented, private class methods:
817 // https://stackoverflow.com/questions/27242353/cocoa-predefined-resize-mouse-cursor
818 CursorStyle::ResizeUpLeftDownRight => {
819 msg_send![class!(NSCursor), _windowResizeNorthWestSouthEastCursor]
820 }
821 CursorStyle::ResizeUpRightDownLeft => {
822 msg_send![class!(NSCursor), _windowResizeNorthEastSouthWestCursor]
823 }
824
825 CursorStyle::IBeamCursorForVerticalLayout => {
826 msg_send![class!(NSCursor), IBeamCursorForVerticalLayout]
827 }
828 CursorStyle::OperationNotAllowed => {
829 msg_send![class!(NSCursor), operationNotAllowedCursor]
830 }
831 CursorStyle::DragLink => msg_send![class!(NSCursor), dragLinkCursor],
832 CursorStyle::DragCopy => msg_send![class!(NSCursor), dragCopyCursor],
833 CursorStyle::ContextualMenu => msg_send![class!(NSCursor), contextualMenuCursor],
834 };
835
836 let old_cursor: id = msg_send![class!(NSCursor), currentCursor];
837 if new_cursor != old_cursor {
838 let _: () = msg_send![new_cursor, set];
839 }
840 }
841 }
842
843 fn should_auto_hide_scrollbars(&self) -> bool {
844 #[allow(non_upper_case_globals)]
845 const NSScrollerStyleOverlay: NSInteger = 1;
846
847 unsafe {
848 let style: NSInteger = msg_send![class!(NSScroller), preferredScrollerStyle];
849 style == NSScrollerStyleOverlay
850 }
851 }
852
853 fn write_to_clipboard(&self, item: ClipboardItem) {
854 let state = self.0.lock();
855 unsafe {
856 state.pasteboard.clearContents();
857
858 let text_bytes = NSData::dataWithBytes_length_(
859 nil,
860 item.text.as_ptr() as *const c_void,
861 item.text.len() as u64,
862 );
863 state
864 .pasteboard
865 .setData_forType(text_bytes, NSPasteboardTypeString);
866
867 if let Some(metadata) = item.metadata.as_ref() {
868 let hash_bytes = ClipboardItem::text_hash(&item.text).to_be_bytes();
869 let hash_bytes = NSData::dataWithBytes_length_(
870 nil,
871 hash_bytes.as_ptr() as *const c_void,
872 hash_bytes.len() as u64,
873 );
874 state
875 .pasteboard
876 .setData_forType(hash_bytes, state.text_hash_pasteboard_type);
877
878 let metadata_bytes = NSData::dataWithBytes_length_(
879 nil,
880 metadata.as_ptr() as *const c_void,
881 metadata.len() as u64,
882 );
883 state
884 .pasteboard
885 .setData_forType(metadata_bytes, state.metadata_pasteboard_type);
886 }
887 }
888 }
889
890 fn read_from_clipboard(&self) -> Option<ClipboardItem> {
891 let state = self.0.lock();
892 unsafe {
893 if let Some(text_bytes) =
894 self.read_from_pasteboard(state.pasteboard, NSPasteboardTypeString)
895 {
896 let text = String::from_utf8_lossy(text_bytes).to_string();
897 let hash_bytes = self
898 .read_from_pasteboard(state.pasteboard, state.text_hash_pasteboard_type)
899 .and_then(|bytes| bytes.try_into().ok())
900 .map(u64::from_be_bytes);
901 let metadata_bytes = self
902 .read_from_pasteboard(state.pasteboard, state.metadata_pasteboard_type)
903 .and_then(|bytes| String::from_utf8(bytes.to_vec()).ok());
904
905 if let Some((hash, metadata)) = hash_bytes.zip(metadata_bytes) {
906 if hash == ClipboardItem::text_hash(&text) {
907 Some(ClipboardItem {
908 text,
909 metadata: Some(metadata),
910 })
911 } else {
912 Some(ClipboardItem {
913 text,
914 metadata: None,
915 })
916 }
917 } else {
918 Some(ClipboardItem {
919 text,
920 metadata: None,
921 })
922 }
923 } else {
924 None
925 }
926 }
927 }
928
929 fn write_credentials(&self, url: &str, username: &str, password: &[u8]) -> Task<Result<()>> {
930 let url = url.to_string();
931 let username = username.to_string();
932 let password = password.to_vec();
933 self.background_executor().spawn(async move {
934 unsafe {
935 use security::*;
936
937 let url = CFString::from(url.as_str());
938 let username = CFString::from(username.as_str());
939 let password = CFData::from_buffer(&password);
940
941 // First, check if there are already credentials for the given server. If so, then
942 // update the username and password.
943 let mut verb = "updating";
944 let mut query_attrs = CFMutableDictionary::with_capacity(2);
945 query_attrs.set(kSecClass as *const _, kSecClassInternetPassword as *const _);
946 query_attrs.set(kSecAttrServer as *const _, url.as_CFTypeRef());
947
948 let mut attrs = CFMutableDictionary::with_capacity(4);
949 attrs.set(kSecClass as *const _, kSecClassInternetPassword as *const _);
950 attrs.set(kSecAttrServer as *const _, url.as_CFTypeRef());
951 attrs.set(kSecAttrAccount as *const _, username.as_CFTypeRef());
952 attrs.set(kSecValueData as *const _, password.as_CFTypeRef());
953
954 let mut status = SecItemUpdate(
955 query_attrs.as_concrete_TypeRef(),
956 attrs.as_concrete_TypeRef(),
957 );
958
959 // If there were no existing credentials for the given server, then create them.
960 if status == errSecItemNotFound {
961 verb = "creating";
962 status = SecItemAdd(attrs.as_concrete_TypeRef(), ptr::null_mut());
963 }
964
965 if status != errSecSuccess {
966 return Err(anyhow!("{} password failed: {}", verb, status));
967 }
968 }
969 Ok(())
970 })
971 }
972
973 fn read_credentials(&self, url: &str) -> Task<Result<Option<(String, Vec<u8>)>>> {
974 let url = url.to_string();
975 self.background_executor().spawn(async move {
976 let url = CFString::from(url.as_str());
977 let cf_true = CFBoolean::true_value().as_CFTypeRef();
978
979 unsafe {
980 use security::*;
981
982 // Find any credentials for the given server URL.
983 let mut attrs = CFMutableDictionary::with_capacity(5);
984 attrs.set(kSecClass as *const _, kSecClassInternetPassword as *const _);
985 attrs.set(kSecAttrServer as *const _, url.as_CFTypeRef());
986 attrs.set(kSecReturnAttributes as *const _, cf_true);
987 attrs.set(kSecReturnData as *const _, cf_true);
988
989 let mut result = CFTypeRef::from(ptr::null());
990 let status = SecItemCopyMatching(attrs.as_concrete_TypeRef(), &mut result);
991 match status {
992 security::errSecSuccess => {}
993 security::errSecItemNotFound | security::errSecUserCanceled => return Ok(None),
994 _ => return Err(anyhow!("reading password failed: {}", status)),
995 }
996
997 let result = CFType::wrap_under_create_rule(result)
998 .downcast::<CFDictionary>()
999 .ok_or_else(|| anyhow!("keychain item was not a dictionary"))?;
1000 let username = result
1001 .find(kSecAttrAccount as *const _)
1002 .ok_or_else(|| anyhow!("account was missing from keychain item"))?;
1003 let username = CFType::wrap_under_get_rule(*username)
1004 .downcast::<CFString>()
1005 .ok_or_else(|| anyhow!("account was not a string"))?;
1006 let password = result
1007 .find(kSecValueData as *const _)
1008 .ok_or_else(|| anyhow!("password was missing from keychain item"))?;
1009 let password = CFType::wrap_under_get_rule(*password)
1010 .downcast::<CFData>()
1011 .ok_or_else(|| anyhow!("password was not a string"))?;
1012
1013 Ok(Some((username.to_string(), password.bytes().to_vec())))
1014 }
1015 })
1016 }
1017
1018 fn delete_credentials(&self, url: &str) -> Task<Result<()>> {
1019 let url = url.to_string();
1020
1021 self.background_executor().spawn(async move {
1022 unsafe {
1023 use security::*;
1024
1025 let url = CFString::from(url.as_str());
1026 let mut query_attrs = CFMutableDictionary::with_capacity(2);
1027 query_attrs.set(kSecClass as *const _, kSecClassInternetPassword as *const _);
1028 query_attrs.set(kSecAttrServer as *const _, url.as_CFTypeRef());
1029
1030 let status = SecItemDelete(query_attrs.as_concrete_TypeRef());
1031
1032 if status != errSecSuccess {
1033 return Err(anyhow!("delete password failed: {}", status));
1034 }
1035 }
1036 Ok(())
1037 })
1038 }
1039}
1040
1041unsafe fn path_from_objc(path: id) -> PathBuf {
1042 let len = msg_send![path, lengthOfBytesUsingEncoding: NSUTF8StringEncoding];
1043 let bytes = path.UTF8String() as *const u8;
1044 let path = str::from_utf8(slice::from_raw_parts(bytes, len)).unwrap();
1045 PathBuf::from(path)
1046}
1047
1048unsafe fn get_mac_platform(object: &mut Object) -> &MacPlatform {
1049 let platform_ptr: *mut c_void = *object.get_ivar(MAC_PLATFORM_IVAR);
1050 assert!(!platform_ptr.is_null());
1051 &*(platform_ptr as *const MacPlatform)
1052}
1053
1054extern "C" fn did_finish_launching(this: &mut Object, _: Sel, _: id) {
1055 unsafe {
1056 let app: id = msg_send![APP_CLASS, sharedApplication];
1057 app.setActivationPolicy_(NSApplicationActivationPolicyRegular);
1058 let platform = get_mac_platform(this);
1059 let callback = platform.0.lock().finish_launching.take();
1060 if let Some(callback) = callback {
1061 callback();
1062 }
1063 }
1064}
1065
1066extern "C" fn should_handle_reopen(this: &mut Object, _: Sel, _: id, has_open_windows: bool) {
1067 if !has_open_windows {
1068 let platform = unsafe { get_mac_platform(this) };
1069 let mut lock = platform.0.lock();
1070 if let Some(mut callback) = lock.reopen.take() {
1071 drop(lock);
1072 callback();
1073 platform.0.lock().reopen.get_or_insert(callback);
1074 }
1075 }
1076}
1077
1078extern "C" fn will_terminate(this: &mut Object, _: Sel, _: id) {
1079 let platform = unsafe { get_mac_platform(this) };
1080 let mut lock = platform.0.lock();
1081 if let Some(mut callback) = lock.quit.take() {
1082 drop(lock);
1083 callback();
1084 platform.0.lock().quit.get_or_insert(callback);
1085 }
1086}
1087
1088extern "C" fn open_urls(this: &mut Object, _: Sel, _: id, urls: id) {
1089 let urls = unsafe {
1090 (0..urls.count())
1091 .filter_map(|i| {
1092 let url = urls.objectAtIndex(i);
1093 match CStr::from_ptr(url.absoluteString().UTF8String() as *mut c_char).to_str() {
1094 Ok(string) => Some(string.to_string()),
1095 Err(err) => {
1096 log::error!("error converting path to string: {}", err);
1097 None
1098 }
1099 }
1100 })
1101 .collect::<Vec<_>>()
1102 };
1103 let platform = unsafe { get_mac_platform(this) };
1104 let mut lock = platform.0.lock();
1105 if let Some(mut callback) = lock.open_urls.take() {
1106 drop(lock);
1107 callback(urls);
1108 platform.0.lock().open_urls.get_or_insert(callback);
1109 }
1110}
1111
1112extern "C" fn handle_menu_item(this: &mut Object, _: Sel, item: id) {
1113 unsafe {
1114 let platform = get_mac_platform(this);
1115 let mut lock = platform.0.lock();
1116 if let Some(mut callback) = lock.menu_command.take() {
1117 let tag: NSInteger = msg_send![item, tag];
1118 let index = tag as usize;
1119 if let Some(action) = lock.menu_actions.get(index) {
1120 let action = action.boxed_clone();
1121 drop(lock);
1122 callback(&*action);
1123 }
1124 platform.0.lock().menu_command.get_or_insert(callback);
1125 }
1126 }
1127}
1128
1129extern "C" fn validate_menu_item(this: &mut Object, _: Sel, item: id) -> bool {
1130 unsafe {
1131 let mut result = false;
1132 let platform = get_mac_platform(this);
1133 let mut lock = platform.0.lock();
1134 if let Some(mut callback) = lock.validate_menu_command.take() {
1135 let tag: NSInteger = msg_send![item, tag];
1136 let index = tag as usize;
1137 if let Some(action) = lock.menu_actions.get(index) {
1138 let action = action.boxed_clone();
1139 drop(lock);
1140 result = callback(action.as_ref());
1141 }
1142 platform
1143 .0
1144 .lock()
1145 .validate_menu_command
1146 .get_or_insert(callback);
1147 }
1148 result
1149 }
1150}
1151
1152extern "C" fn menu_will_open(this: &mut Object, _: Sel, _: id) {
1153 unsafe {
1154 let platform = get_mac_platform(this);
1155 let mut lock = platform.0.lock();
1156 if let Some(mut callback) = lock.will_open_menu.take() {
1157 drop(lock);
1158 callback();
1159 platform.0.lock().will_open_menu.get_or_insert(callback);
1160 }
1161 }
1162}
1163
1164extern "C" fn handle_dock_menu(this: &mut Object, _: Sel, _: id) -> id {
1165 unsafe {
1166 let platform = get_mac_platform(this);
1167 let mut state = platform.0.lock();
1168 if let Some(id) = state.dock_menu {
1169 id
1170 } else {
1171 nil
1172 }
1173 }
1174}
1175
1176unsafe fn ns_string(string: &str) -> id {
1177 NSString::alloc(nil).init_str(string).autorelease()
1178}
1179
1180unsafe fn ns_url_to_path(url: id) -> Result<PathBuf> {
1181 let path: *mut c_char = msg_send![url, fileSystemRepresentation];
1182 if path.is_null() {
1183 Err(anyhow!(
1184 "url is not a file path: {}",
1185 CStr::from_ptr(url.absoluteString().UTF8String()).to_string_lossy()
1186 ))
1187 } else {
1188 Ok(PathBuf::from(OsStr::from_bytes(
1189 CStr::from_ptr(path).to_bytes(),
1190 )))
1191 }
1192}
1193
1194mod security {
1195 #![allow(non_upper_case_globals)]
1196 use super::*;
1197
1198 #[link(name = "Security", kind = "framework")]
1199 extern "C" {
1200 pub static kSecClass: CFStringRef;
1201 pub static kSecClassInternetPassword: CFStringRef;
1202 pub static kSecAttrServer: CFStringRef;
1203 pub static kSecAttrAccount: CFStringRef;
1204 pub static kSecValueData: CFStringRef;
1205 pub static kSecReturnAttributes: CFStringRef;
1206 pub static kSecReturnData: CFStringRef;
1207
1208 pub fn SecItemAdd(attributes: CFDictionaryRef, result: *mut CFTypeRef) -> OSStatus;
1209 pub fn SecItemUpdate(query: CFDictionaryRef, attributes: CFDictionaryRef) -> OSStatus;
1210 pub fn SecItemDelete(query: CFDictionaryRef) -> OSStatus;
1211 pub fn SecItemCopyMatching(query: CFDictionaryRef, result: *mut CFTypeRef) -> OSStatus;
1212 }
1213
1214 pub const errSecSuccess: OSStatus = 0;
1215 pub const errSecUserCanceled: OSStatus = -128;
1216 pub const errSecItemNotFound: OSStatus = -25300;
1217}
1218
1219#[cfg(test)]
1220mod tests {
1221 use crate::ClipboardItem;
1222
1223 use super::*;
1224
1225 #[test]
1226 fn test_clipboard() {
1227 let platform = build_platform();
1228 assert_eq!(platform.read_from_clipboard(), None);
1229
1230 let item = ClipboardItem::new("1".to_string());
1231 platform.write_to_clipboard(item.clone());
1232 assert_eq!(platform.read_from_clipboard(), Some(item));
1233
1234 let item = ClipboardItem::new("2".to_string()).with_metadata(vec![3, 4]);
1235 platform.write_to_clipboard(item.clone());
1236 assert_eq!(platform.read_from_clipboard(), Some(item));
1237
1238 let text_from_other_app = "text from other app";
1239 unsafe {
1240 let bytes = NSData::dataWithBytes_length_(
1241 nil,
1242 text_from_other_app.as_ptr() as *const c_void,
1243 text_from_other_app.len() as u64,
1244 );
1245 platform
1246 .0
1247 .lock()
1248 .pasteboard
1249 .setData_forType(bytes, NSPasteboardTypeString);
1250 }
1251 assert_eq!(
1252 platform.read_from_clipboard(),
1253 Some(ClipboardItem::new(text_from_other_app.to_string()))
1254 );
1255 }
1256
1257 fn build_platform() -> MacPlatform {
1258 let platform = MacPlatform::new(false);
1259 platform.0.lock().pasteboard = unsafe { NSPasteboard::pasteboardWithUniqueName(nil) };
1260 platform
1261 }
1262}