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