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