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