1use super::{
2 BoolExt, MacKeyboardLayout, MacKeyboardMapper,
3 attributed_string::{NSAttributedString, NSMutableAttributedString},
4 events::key_to_native,
5 renderer,
6};
7use crate::{
8 Action, AnyWindowHandle, BackgroundExecutor, ClipboardEntry, ClipboardItem, ClipboardString,
9 CursorStyle, ForegroundExecutor, Image, ImageFormat, KeyContext, Keymap, MacDispatcher,
10 MacDisplay, MacWindow, Menu, MenuItem, OsMenu, OwnedMenu, PathPromptOptions, Platform,
11 PlatformDisplay, PlatformKeyboardLayout, PlatformKeyboardMapper, PlatformTextSystem,
12 PlatformWindow, Result, SemanticVersion, SystemMenuType, Task, WindowAppearance, WindowParams,
13 hash,
14};
15use anyhow::{Context as _, anyhow};
16use block::ConcreteBlock;
17use cocoa::{
18 appkit::{
19 NSApplication, NSApplicationActivationPolicy::NSApplicationActivationPolicyRegular,
20 NSEventModifierFlags, NSMenu, NSMenuItem, NSModalResponse, NSOpenPanel, NSPasteboard,
21 NSPasteboardTypePNG, NSPasteboardTypeRTF, NSPasteboardTypeRTFD, NSPasteboardTypeString,
22 NSPasteboardTypeTIFF, NSSavePanel, NSWindow,
23 },
24 base::{BOOL, NO, YES, id, nil, selector},
25 foundation::{
26 NSArray, NSAutoreleasePool, NSBundle, NSData, NSInteger, NSProcessInfo, NSRange, NSString,
27 NSUInteger, NSURL,
28 },
29};
30use core_foundation::{
31 base::{CFRelease, CFType, CFTypeRef, OSStatus, TCFType},
32 boolean::CFBoolean,
33 data::CFData,
34 dictionary::{CFDictionary, CFDictionaryRef, CFMutableDictionary},
35 runloop::CFRunLoopRun,
36 string::{CFString, CFStringRef},
37};
38use ctor::ctor;
39use futures::channel::oneshot;
40use itertools::Itertools;
41use objc::{
42 class,
43 declare::ClassDecl,
44 msg_send,
45 runtime::{Class, Object, Sel},
46 sel, sel_impl,
47};
48use parking_lot::Mutex;
49use ptr::null_mut;
50use std::{
51 cell::Cell,
52 convert::TryInto,
53 ffi::{CStr, OsStr, c_void},
54 os::{raw::c_char, unix::ffi::OsStrExt},
55 path::{Path, PathBuf},
56 process::Command,
57 ptr,
58 rc::Rc,
59 slice, str,
60 sync::{Arc, OnceLock},
61};
62use strum::IntoEnumIterator;
63use util::ResultExt;
64
65#[allow(non_upper_case_globals)]
66const NSUTF8StringEncoding: NSUInteger = 4;
67
68const MAC_PLATFORM_IVAR: &str = "platform";
69static mut APP_CLASS: *const Class = ptr::null();
70static mut APP_DELEGATE_CLASS: *const Class = ptr::null();
71
72#[ctor]
73unsafe fn build_classes() {
74 unsafe {
75 APP_CLASS = {
76 let mut decl = ClassDecl::new("GPUIApplication", class!(NSApplication)).unwrap();
77 decl.add_ivar::<*mut c_void>(MAC_PLATFORM_IVAR);
78 decl.register()
79 }
80 };
81 unsafe {
82 APP_DELEGATE_CLASS = unsafe {
83 let mut decl = ClassDecl::new("GPUIApplicationDelegate", class!(NSResponder)).unwrap();
84 decl.add_ivar::<*mut c_void>(MAC_PLATFORM_IVAR);
85 decl.add_method(
86 sel!(applicationWillFinishLaunching:),
87 will_finish_launching as extern "C" fn(&mut Object, Sel, id),
88 );
89 decl.add_method(
90 sel!(applicationDidFinishLaunching:),
91 did_finish_launching as extern "C" fn(&mut Object, Sel, id),
92 );
93 decl.add_method(
94 sel!(applicationShouldHandleReopen:hasVisibleWindows:),
95 should_handle_reopen as extern "C" fn(&mut Object, Sel, id, bool),
96 );
97 decl.add_method(
98 sel!(applicationWillTerminate:),
99 will_terminate as extern "C" fn(&mut Object, Sel, id),
100 );
101 decl.add_method(
102 sel!(handleGPUIMenuItem:),
103 handle_menu_item as extern "C" fn(&mut Object, Sel, id),
104 );
105 // Add menu item handlers so that OS save panels have the correct key commands
106 decl.add_method(
107 sel!(cut:),
108 handle_menu_item as extern "C" fn(&mut Object, Sel, id),
109 );
110 decl.add_method(
111 sel!(copy:),
112 handle_menu_item as extern "C" fn(&mut Object, Sel, id),
113 );
114 decl.add_method(
115 sel!(paste:),
116 handle_menu_item as extern "C" fn(&mut Object, Sel, id),
117 );
118 decl.add_method(
119 sel!(selectAll:),
120 handle_menu_item as extern "C" fn(&mut Object, Sel, id),
121 );
122 decl.add_method(
123 sel!(undo:),
124 handle_menu_item as extern "C" fn(&mut Object, Sel, id),
125 );
126 decl.add_method(
127 sel!(redo:),
128 handle_menu_item as extern "C" fn(&mut Object, Sel, id),
129 );
130 decl.add_method(
131 sel!(validateMenuItem:),
132 validate_menu_item as extern "C" fn(&mut Object, Sel, id) -> bool,
133 );
134 decl.add_method(
135 sel!(menuWillOpen:),
136 menu_will_open as extern "C" fn(&mut Object, Sel, id),
137 );
138 decl.add_method(
139 sel!(applicationDockMenu:),
140 handle_dock_menu as extern "C" fn(&mut Object, Sel, id) -> id,
141 );
142 decl.add_method(
143 sel!(application:openURLs:),
144 open_urls as extern "C" fn(&mut Object, Sel, id, id),
145 );
146
147 decl.add_method(
148 sel!(onKeyboardLayoutChange:),
149 on_keyboard_layout_change as extern "C" fn(&mut Object, Sel, id),
150 );
151
152 decl.register()
153 }
154 }
155}
156
157pub(crate) struct MacPlatform(Mutex<MacPlatformState>);
158
159pub(crate) struct MacPlatformState {
160 background_executor: BackgroundExecutor,
161 foreground_executor: ForegroundExecutor,
162 text_system: Arc<dyn PlatformTextSystem>,
163 renderer_context: renderer::Context,
164 headless: bool,
165 pasteboard: id,
166 text_hash_pasteboard_type: id,
167 metadata_pasteboard_type: id,
168 reopen: Option<Box<dyn FnMut()>>,
169 on_keyboard_layout_change: Option<Box<dyn FnMut()>>,
170 quit: Option<Box<dyn FnMut()>>,
171 menu_command: Option<Box<dyn FnMut(&dyn Action)>>,
172 validate_menu_command: Option<Box<dyn FnMut(&dyn Action) -> bool>>,
173 will_open_menu: Option<Box<dyn FnMut()>>,
174 menu_actions: Vec<Box<dyn Action>>,
175 open_urls: Option<Box<dyn FnMut(Vec<String>)>>,
176 finish_launching: Option<Box<dyn FnOnce()>>,
177 dock_menu: Option<id>,
178 menus: Option<Vec<OwnedMenu>>,
179 keyboard_mapper: Rc<MacKeyboardMapper>,
180}
181
182impl Default for MacPlatform {
183 fn default() -> Self {
184 Self::new(false)
185 }
186}
187
188impl MacPlatform {
189 pub(crate) fn new(headless: bool) -> Self {
190 let dispatcher = Arc::new(MacDispatcher);
191
192 #[cfg(feature = "font-kit")]
193 let text_system = Arc::new(crate::MacTextSystem::new());
194
195 #[cfg(not(feature = "font-kit"))]
196 let text_system = Arc::new(crate::NoopTextSystem::new());
197
198 let keyboard_layout = MacKeyboardLayout::new();
199 let keyboard_mapper = Rc::new(MacKeyboardMapper::new(keyboard_layout.id()));
200
201 Self(Mutex::new(MacPlatformState {
202 headless,
203 text_system,
204 background_executor: BackgroundExecutor::new(dispatcher.clone()),
205 foreground_executor: ForegroundExecutor::new(dispatcher),
206 renderer_context: renderer::Context::default(),
207 pasteboard: unsafe { NSPasteboard::generalPasteboard(nil) },
208 text_hash_pasteboard_type: unsafe { ns_string("zed-text-hash") },
209 metadata_pasteboard_type: unsafe { ns_string("zed-metadata") },
210 reopen: None,
211 quit: None,
212 menu_command: None,
213 validate_menu_command: None,
214 will_open_menu: None,
215 menu_actions: Default::default(),
216 open_urls: None,
217 finish_launching: None,
218 dock_menu: None,
219 on_keyboard_layout_change: None,
220 menus: None,
221 keyboard_mapper,
222 }))
223 }
224
225 unsafe fn read_from_pasteboard(&self, pasteboard: *mut Object, kind: id) -> Option<&[u8]> {
226 unsafe {
227 let data = pasteboard.dataForType(kind);
228 if data == nil {
229 None
230 } else {
231 Some(slice::from_raw_parts(
232 data.bytes() as *mut u8,
233 data.length() as usize,
234 ))
235 }
236 }
237 }
238
239 unsafe fn create_menu_bar(
240 &self,
241 menus: &Vec<Menu>,
242 delegate: id,
243 actions: &mut Vec<Box<dyn Action>>,
244 keymap: &Keymap,
245 ) -> id {
246 unsafe {
247 let application_menu = NSMenu::new(nil).autorelease();
248 application_menu.setDelegate_(delegate);
249
250 for menu_config in menus {
251 let menu = NSMenu::new(nil).autorelease();
252 let menu_title = ns_string(&menu_config.name);
253 menu.setTitle_(menu_title);
254 menu.setDelegate_(delegate);
255
256 for item_config in &menu_config.items {
257 menu.addItem_(Self::create_menu_item(
258 item_config,
259 delegate,
260 actions,
261 keymap,
262 ));
263 }
264
265 let menu_item = NSMenuItem::new(nil).autorelease();
266 menu_item.setTitle_(menu_title);
267 menu_item.setSubmenu_(menu);
268 application_menu.addItem_(menu_item);
269
270 if menu_config.name == "Window" {
271 let app: id = msg_send![APP_CLASS, sharedApplication];
272 app.setWindowsMenu_(menu);
273 }
274 }
275
276 application_menu
277 }
278 }
279
280 unsafe fn create_dock_menu(
281 &self,
282 menu_items: Vec<MenuItem>,
283 delegate: id,
284 actions: &mut Vec<Box<dyn Action>>,
285 keymap: &Keymap,
286 ) -> id {
287 unsafe {
288 let dock_menu = NSMenu::new(nil);
289 dock_menu.setDelegate_(delegate);
290 for item_config in menu_items {
291 dock_menu.addItem_(Self::create_menu_item(
292 &item_config,
293 delegate,
294 actions,
295 keymap,
296 ));
297 }
298
299 dock_menu
300 }
301 }
302
303 unsafe fn create_menu_item(
304 item: &MenuItem,
305 delegate: id,
306 actions: &mut Vec<Box<dyn Action>>,
307 keymap: &Keymap,
308 ) -> id {
309 static DEFAULT_CONTEXT: OnceLock<Vec<KeyContext>> = OnceLock::new();
310
311 unsafe {
312 match item {
313 MenuItem::Separator => NSMenuItem::separatorItem(nil),
314 MenuItem::Action {
315 name,
316 action,
317 os_action,
318 } => {
319 // Note that this is intentionally using earlier bindings, whereas typically
320 // later ones take display precedence. See the discussion on
321 // https://github.com/zed-industries/zed/issues/23621
322 let keystrokes = keymap
323 .bindings_for_action(action.as_ref())
324 .find_or_first(|binding| {
325 binding.predicate().is_none_or(|predicate| {
326 predicate.eval(DEFAULT_CONTEXT.get_or_init(|| {
327 let mut workspace_context = KeyContext::new_with_defaults();
328 workspace_context.add("Workspace");
329 let mut pane_context = KeyContext::new_with_defaults();
330 pane_context.add("Pane");
331 let mut editor_context = KeyContext::new_with_defaults();
332 editor_context.add("Editor");
333
334 pane_context.extend(&editor_context);
335 workspace_context.extend(&pane_context);
336 vec![workspace_context]
337 }))
338 })
339 })
340 .map(|binding| binding.keystrokes());
341
342 let selector = match os_action {
343 Some(crate::OsAction::Cut) => selector("cut:"),
344 Some(crate::OsAction::Copy) => selector("copy:"),
345 Some(crate::OsAction::Paste) => selector("paste:"),
346 Some(crate::OsAction::SelectAll) => selector("selectAll:"),
347 // "undo:" and "redo:" are always disabled in our case, as
348 // we don't have a NSTextView/NSTextField to enable them on.
349 Some(crate::OsAction::Undo) => selector("handleGPUIMenuItem:"),
350 Some(crate::OsAction::Redo) => selector("handleGPUIMenuItem:"),
351 None => selector("handleGPUIMenuItem:"),
352 };
353
354 let item;
355 if let Some(keystrokes) = keystrokes {
356 if keystrokes.len() == 1 {
357 let keystroke = &keystrokes[0];
358 let mut mask = NSEventModifierFlags::empty();
359 for (modifier, flag) in &[
360 (
361 keystroke.modifiers().platform,
362 NSEventModifierFlags::NSCommandKeyMask,
363 ),
364 (
365 keystroke.modifiers().control,
366 NSEventModifierFlags::NSControlKeyMask,
367 ),
368 (
369 keystroke.modifiers().alt,
370 NSEventModifierFlags::NSAlternateKeyMask,
371 ),
372 (
373 keystroke.modifiers().shift,
374 NSEventModifierFlags::NSShiftKeyMask,
375 ),
376 ] {
377 if *modifier {
378 mask |= *flag;
379 }
380 }
381
382 item = NSMenuItem::alloc(nil)
383 .initWithTitle_action_keyEquivalent_(
384 ns_string(name),
385 selector,
386 ns_string(key_to_native(keystroke.key()).as_ref()),
387 )
388 .autorelease();
389 if Self::os_version() >= SemanticVersion::new(12, 0, 0) {
390 let _: () = msg_send![item, setAllowsAutomaticKeyEquivalentLocalization: NO];
391 }
392 item.setKeyEquivalentModifierMask_(mask);
393 } else {
394 item = NSMenuItem::alloc(nil)
395 .initWithTitle_action_keyEquivalent_(
396 ns_string(name),
397 selector,
398 ns_string(""),
399 )
400 .autorelease();
401 }
402 } else {
403 item = NSMenuItem::alloc(nil)
404 .initWithTitle_action_keyEquivalent_(
405 ns_string(name),
406 selector,
407 ns_string(""),
408 )
409 .autorelease();
410 }
411
412 let tag = actions.len() as NSInteger;
413 let _: () = msg_send![item, setTag: tag];
414 actions.push(action.boxed_clone());
415 item
416 }
417 MenuItem::Submenu(Menu { name, items }) => {
418 let item = NSMenuItem::new(nil).autorelease();
419 let submenu = NSMenu::new(nil).autorelease();
420 submenu.setDelegate_(delegate);
421 for item in items {
422 submenu.addItem_(Self::create_menu_item(item, delegate, actions, keymap));
423 }
424 item.setSubmenu_(submenu);
425 item.setTitle_(ns_string(name));
426 item
427 }
428 MenuItem::SystemMenu(OsMenu { name, menu_type }) => {
429 let item = NSMenuItem::new(nil).autorelease();
430 let submenu = NSMenu::new(nil).autorelease();
431 submenu.setDelegate_(delegate);
432 item.setSubmenu_(submenu);
433 item.setTitle_(ns_string(name));
434
435 match menu_type {
436 SystemMenuType::Services => {
437 let app: id = msg_send![APP_CLASS, sharedApplication];
438 app.setServicesMenu_(item);
439 }
440 }
441
442 item
443 }
444 }
445 }
446 }
447
448 fn os_version() -> SemanticVersion {
449 let version = unsafe {
450 let process_info = NSProcessInfo::processInfo(nil);
451 process_info.operatingSystemVersion()
452 };
453 SemanticVersion::new(
454 version.majorVersion as usize,
455 version.minorVersion as usize,
456 version.patchVersion as usize,
457 )
458 }
459}
460
461impl Platform for MacPlatform {
462 fn background_executor(&self) -> BackgroundExecutor {
463 self.0.lock().background_executor.clone()
464 }
465
466 fn foreground_executor(&self) -> crate::ForegroundExecutor {
467 self.0.lock().foreground_executor.clone()
468 }
469
470 fn text_system(&self) -> Arc<dyn PlatformTextSystem> {
471 self.0.lock().text_system.clone()
472 }
473
474 fn run(&self, on_finish_launching: Box<dyn FnOnce()>) {
475 let mut state = self.0.lock();
476 if state.headless {
477 drop(state);
478 on_finish_launching();
479 unsafe { CFRunLoopRun() };
480 } else {
481 state.finish_launching = Some(on_finish_launching);
482 drop(state);
483 }
484
485 unsafe {
486 let app: id = msg_send![APP_CLASS, sharedApplication];
487 let app_delegate: id = msg_send![APP_DELEGATE_CLASS, new];
488 app.setDelegate_(app_delegate);
489
490 let self_ptr = self as *const Self as *const c_void;
491 (*app).set_ivar(MAC_PLATFORM_IVAR, self_ptr);
492 (*app_delegate).set_ivar(MAC_PLATFORM_IVAR, self_ptr);
493
494 let pool = NSAutoreleasePool::new(nil);
495 app.run();
496 pool.drain();
497
498 (*app).set_ivar(MAC_PLATFORM_IVAR, null_mut::<c_void>());
499 (*NSWindow::delegate(app)).set_ivar(MAC_PLATFORM_IVAR, null_mut::<c_void>());
500 }
501 }
502
503 fn quit(&self) {
504 // Quitting the app causes us to close windows, which invokes `Window::on_close` callbacks
505 // synchronously before this method terminates. If we call `Platform::quit` while holding a
506 // borrow of the app state (which most of the time we will do), we will end up
507 // double-borrowing the app state in the `on_close` callbacks for our open windows. To solve
508 // this, we make quitting the application asynchronous so that we aren't holding borrows to
509 // the app state on the stack when we actually terminate the app.
510
511 use super::dispatcher::{dispatch_get_main_queue, dispatch_sys::dispatch_async_f};
512
513 unsafe {
514 dispatch_async_f(dispatch_get_main_queue(), ptr::null_mut(), Some(quit));
515 }
516
517 unsafe extern "C" fn quit(_: *mut c_void) {
518 unsafe {
519 let app = NSApplication::sharedApplication(nil);
520 let _: () = msg_send![app, terminate: nil];
521 }
522 }
523 }
524
525 fn restart(&self, _binary_path: Option<PathBuf>) {
526 use std::os::unix::process::CommandExt as _;
527
528 let app_pid = std::process::id().to_string();
529 let app_path = self
530 .app_path()
531 .ok()
532 // When the app is not bundled, `app_path` returns the
533 // directory containing the executable. Disregard this
534 // and get the path to the executable itself.
535 .and_then(|path| (path.extension()?.to_str()? == "app").then_some(path))
536 .unwrap_or_else(|| std::env::current_exe().unwrap());
537
538 // Wait until this process has exited and then re-open this path.
539 let script = r#"
540 while kill -0 $0 2> /dev/null; do
541 sleep 0.1
542 done
543 open "$1"
544 "#;
545
546 #[allow(
547 clippy::disallowed_methods,
548 reason = "We are restarting ourselves, using std command thus is fine"
549 )]
550 let restart_process = Command::new("/bin/bash")
551 .arg("-c")
552 .arg(script)
553 .arg(app_pid)
554 .arg(app_path)
555 .process_group(0)
556 .spawn();
557
558 match restart_process {
559 Ok(_) => self.quit(),
560 Err(e) => log::error!("failed to spawn restart script: {:?}", e),
561 }
562 }
563
564 fn activate(&self, ignoring_other_apps: bool) {
565 unsafe {
566 let app = NSApplication::sharedApplication(nil);
567 app.activateIgnoringOtherApps_(ignoring_other_apps.to_objc());
568 }
569 }
570
571 fn hide(&self) {
572 unsafe {
573 let app = NSApplication::sharedApplication(nil);
574 let _: () = msg_send![app, hide: nil];
575 }
576 }
577
578 fn hide_other_apps(&self) {
579 unsafe {
580 let app = NSApplication::sharedApplication(nil);
581 let _: () = msg_send![app, hideOtherApplications: nil];
582 }
583 }
584
585 fn unhide_other_apps(&self) {
586 unsafe {
587 let app = NSApplication::sharedApplication(nil);
588 let _: () = msg_send![app, unhideAllApplications: nil];
589 }
590 }
591
592 fn primary_display(&self) -> Option<Rc<dyn PlatformDisplay>> {
593 Some(Rc::new(MacDisplay::primary()))
594 }
595
596 fn displays(&self) -> Vec<Rc<dyn PlatformDisplay>> {
597 MacDisplay::all()
598 .map(|screen| Rc::new(screen) as Rc<_>)
599 .collect()
600 }
601
602 #[cfg(feature = "screen-capture")]
603 fn is_screen_capture_supported(&self) -> bool {
604 let min_version = cocoa::foundation::NSOperatingSystemVersion::new(12, 3, 0);
605 super::is_macos_version_at_least(min_version)
606 }
607
608 #[cfg(feature = "screen-capture")]
609 fn screen_capture_sources(
610 &self,
611 ) -> oneshot::Receiver<Result<Vec<Rc<dyn crate::ScreenCaptureSource>>>> {
612 super::screen_capture::get_sources()
613 }
614
615 fn active_window(&self) -> Option<AnyWindowHandle> {
616 MacWindow::active_window()
617 }
618
619 // Returns the windows ordered front-to-back, meaning that the active
620 // window is the first one in the returned vec.
621 fn window_stack(&self) -> Option<Vec<AnyWindowHandle>> {
622 Some(MacWindow::ordered_windows())
623 }
624
625 fn open_window(
626 &self,
627 handle: AnyWindowHandle,
628 options: WindowParams,
629 ) -> Result<Box<dyn PlatformWindow>> {
630 let renderer_context = self.0.lock().renderer_context.clone();
631 Ok(Box::new(MacWindow::open(
632 handle,
633 options,
634 self.foreground_executor(),
635 renderer_context,
636 )))
637 }
638
639 fn window_appearance(&self) -> WindowAppearance {
640 unsafe {
641 let app = NSApplication::sharedApplication(nil);
642 let appearance: id = msg_send![app, effectiveAppearance];
643 WindowAppearance::from_native(appearance)
644 }
645 }
646
647 fn open_url(&self, url: &str) {
648 unsafe {
649 let url = NSURL::alloc(nil)
650 .initWithString_(ns_string(url))
651 .autorelease();
652 let workspace: id = msg_send![class!(NSWorkspace), sharedWorkspace];
653 msg_send![workspace, openURL: url]
654 }
655 }
656
657 fn register_url_scheme(&self, scheme: &str) -> Task<anyhow::Result<()>> {
658 // API only available post Monterey
659 // https://developer.apple.com/documentation/appkit/nsworkspace/3753004-setdefaultapplicationaturl
660 let (done_tx, done_rx) = oneshot::channel();
661 if Self::os_version() < SemanticVersion::new(12, 0, 0) {
662 return Task::ready(Err(anyhow!(
663 "macOS 12.0 or later is required to register URL schemes"
664 )));
665 }
666
667 let bundle_id = unsafe {
668 let bundle: id = msg_send![class!(NSBundle), mainBundle];
669 let bundle_id: id = msg_send![bundle, bundleIdentifier];
670 if bundle_id == nil {
671 return Task::ready(Err(anyhow!("Can only register URL scheme in bundled apps")));
672 }
673 bundle_id
674 };
675
676 unsafe {
677 let workspace: id = msg_send![class!(NSWorkspace), sharedWorkspace];
678 let scheme: id = ns_string(scheme);
679 let app: id = msg_send![workspace, URLForApplicationWithBundleIdentifier: bundle_id];
680 if app == nil {
681 return Task::ready(Err(anyhow!(
682 "Cannot register URL scheme until app is installed"
683 )));
684 }
685 let done_tx = Cell::new(Some(done_tx));
686 let block = ConcreteBlock::new(move |error: id| {
687 let result = if error == nil {
688 Ok(())
689 } else {
690 let msg: id = msg_send![error, localizedDescription];
691 Err(anyhow!("Failed to register: {msg:?}"))
692 };
693
694 if let Some(done_tx) = done_tx.take() {
695 let _ = done_tx.send(result);
696 }
697 });
698 let block = block.copy();
699 let _: () = msg_send![workspace, setDefaultApplicationAtURL: app toOpenURLsWithScheme: scheme completionHandler: block];
700 }
701
702 self.background_executor()
703 .spawn(async { crate::Flatten::flatten(done_rx.await.map_err(|e| anyhow!(e))) })
704 }
705
706 fn on_open_urls(&self, callback: Box<dyn FnMut(Vec<String>)>) {
707 self.0.lock().open_urls = Some(callback);
708 }
709
710 fn prompt_for_paths(
711 &self,
712 options: PathPromptOptions,
713 ) -> oneshot::Receiver<Result<Option<Vec<PathBuf>>>> {
714 let (done_tx, done_rx) = oneshot::channel();
715 self.foreground_executor()
716 .spawn(async move {
717 unsafe {
718 let panel = NSOpenPanel::openPanel(nil);
719 panel.setCanChooseDirectories_(options.directories.to_objc());
720 panel.setCanChooseFiles_(options.files.to_objc());
721 panel.setAllowsMultipleSelection_(options.multiple.to_objc());
722
723 panel.setCanCreateDirectories(true.to_objc());
724 panel.setResolvesAliases_(false.to_objc());
725 let done_tx = Cell::new(Some(done_tx));
726 let block = ConcreteBlock::new(move |response: NSModalResponse| {
727 let result = if response == NSModalResponse::NSModalResponseOk {
728 let mut result = Vec::new();
729 let urls = panel.URLs();
730 for i in 0..urls.count() {
731 let url = urls.objectAtIndex(i);
732 if url.isFileURL() == YES
733 && let Ok(path) = ns_url_to_path(url)
734 {
735 result.push(path)
736 }
737 }
738 Some(result)
739 } else {
740 None
741 };
742
743 if let Some(done_tx) = done_tx.take() {
744 let _ = done_tx.send(Ok(result));
745 }
746 });
747 let block = block.copy();
748
749 if let Some(prompt) = options.prompt {
750 let _: () = msg_send![panel, setPrompt: ns_string(&prompt)];
751 }
752
753 let _: () = msg_send![panel, beginWithCompletionHandler: block];
754 }
755 })
756 .detach();
757 done_rx
758 }
759
760 fn prompt_for_new_path(
761 &self,
762 directory: &Path,
763 suggested_name: Option<&str>,
764 ) -> oneshot::Receiver<Result<Option<PathBuf>>> {
765 let directory = directory.to_owned();
766 let suggested_name = suggested_name.map(|s| s.to_owned());
767 let (done_tx, done_rx) = oneshot::channel();
768 self.foreground_executor()
769 .spawn(async move {
770 unsafe {
771 let panel = NSSavePanel::savePanel(nil);
772 let path = ns_string(directory.to_string_lossy().as_ref());
773 let url = NSURL::fileURLWithPath_isDirectory_(nil, path, true.to_objc());
774 panel.setDirectoryURL(url);
775
776 if let Some(suggested_name) = suggested_name {
777 let name_string = ns_string(&suggested_name);
778 let _: () = msg_send![panel, setNameFieldStringValue: name_string];
779 }
780
781 let done_tx = Cell::new(Some(done_tx));
782 let block = ConcreteBlock::new(move |response: NSModalResponse| {
783 let mut result = None;
784 if response == NSModalResponse::NSModalResponseOk {
785 let url = panel.URL();
786 if url.isFileURL() == YES {
787 result = ns_url_to_path(panel.URL()).ok().map(|mut result| {
788 let Some(filename) = result.file_name() else {
789 return result;
790 };
791 let chunks = filename
792 .as_bytes()
793 .split(|&b| b == b'.')
794 .collect::<Vec<_>>();
795
796 // https://github.com/zed-industries/zed/issues/16969
797 // Workaround a bug in macOS Sequoia that adds an extra file-extension
798 // sometimes. e.g. `a.sql` becomes `a.sql.s` or `a.txtx` becomes `a.txtx.txt`
799 //
800 // This is conditional on OS version because I'd like to get rid of it, so that
801 // you can manually create a file called `a.sql.s`. That said it seems better
802 // to break that use-case than breaking `a.sql`.
803 if chunks.len() == 3
804 && chunks[1].starts_with(chunks[2])
805 && Self::os_version() >= SemanticVersion::new(15, 0, 0)
806 {
807 let new_filename = OsStr::from_bytes(
808 &filename.as_bytes()
809 [..chunks[0].len() + 1 + chunks[1].len()],
810 )
811 .to_owned();
812 result.set_file_name(&new_filename);
813 }
814 result
815 })
816 }
817 }
818
819 if let Some(done_tx) = done_tx.take() {
820 let _ = done_tx.send(Ok(result));
821 }
822 });
823 let block = block.copy();
824 let _: () = msg_send![panel, beginWithCompletionHandler: block];
825 }
826 })
827 .detach();
828
829 done_rx
830 }
831
832 fn can_select_mixed_files_and_dirs(&self) -> bool {
833 true
834 }
835
836 fn reveal_path(&self, path: &Path) {
837 unsafe {
838 let path = path.to_path_buf();
839 self.0
840 .lock()
841 .background_executor
842 .spawn(async move {
843 let full_path = ns_string(path.to_str().unwrap_or(""));
844 let root_full_path = ns_string("");
845 let workspace: id = msg_send![class!(NSWorkspace), sharedWorkspace];
846 let _: BOOL = msg_send![
847 workspace,
848 selectFile: full_path
849 inFileViewerRootedAtPath: root_full_path
850 ];
851 })
852 .detach();
853 }
854 }
855
856 fn open_with_system(&self, path: &Path) {
857 let path = path.to_owned();
858 self.0
859 .lock()
860 .background_executor
861 .spawn(async move {
862 if let Some(mut child) = smol::process::Command::new("open")
863 .arg(path)
864 .spawn()
865 .context("invoking open command")
866 .log_err()
867 {
868 child.status().await.log_err();
869 }
870 })
871 .detach();
872 }
873
874 fn on_quit(&self, callback: Box<dyn FnMut()>) {
875 self.0.lock().quit = Some(callback);
876 }
877
878 fn on_reopen(&self, callback: Box<dyn FnMut()>) {
879 self.0.lock().reopen = Some(callback);
880 }
881
882 fn on_keyboard_layout_change(&self, callback: Box<dyn FnMut()>) {
883 self.0.lock().on_keyboard_layout_change = Some(callback);
884 }
885
886 fn on_app_menu_action(&self, callback: Box<dyn FnMut(&dyn Action)>) {
887 self.0.lock().menu_command = Some(callback);
888 }
889
890 fn on_will_open_app_menu(&self, callback: Box<dyn FnMut()>) {
891 self.0.lock().will_open_menu = Some(callback);
892 }
893
894 fn on_validate_app_menu_command(&self, callback: Box<dyn FnMut(&dyn Action) -> bool>) {
895 self.0.lock().validate_menu_command = Some(callback);
896 }
897
898 fn keyboard_layout(&self) -> Box<dyn PlatformKeyboardLayout> {
899 Box::new(MacKeyboardLayout::new())
900 }
901
902 fn keyboard_mapper(&self) -> Rc<dyn PlatformKeyboardMapper> {
903 self.0.lock().keyboard_mapper.clone()
904 }
905
906 fn app_path(&self) -> Result<PathBuf> {
907 unsafe {
908 let bundle: id = NSBundle::mainBundle();
909 anyhow::ensure!(!bundle.is_null(), "app is not running inside a bundle");
910 Ok(path_from_objc(msg_send![bundle, bundlePath]))
911 }
912 }
913
914 fn set_menus(&self, menus: Vec<Menu>, keymap: &Keymap) {
915 unsafe {
916 let app: id = msg_send![APP_CLASS, sharedApplication];
917 let mut state = self.0.lock();
918 let actions = &mut state.menu_actions;
919 let menu = self.create_menu_bar(&menus, NSWindow::delegate(app), actions, keymap);
920 drop(state);
921 app.setMainMenu_(menu);
922 }
923 self.0.lock().menus = Some(menus.into_iter().map(|menu| menu.owned()).collect());
924 }
925
926 fn get_menus(&self) -> Option<Vec<OwnedMenu>> {
927 self.0.lock().menus.clone()
928 }
929
930 fn set_dock_menu(&self, menu: Vec<MenuItem>, keymap: &Keymap) {
931 unsafe {
932 let app: id = msg_send![APP_CLASS, sharedApplication];
933 let mut state = self.0.lock();
934 let actions = &mut state.menu_actions;
935 let new = self.create_dock_menu(menu, NSWindow::delegate(app), actions, keymap);
936 if let Some(old) = state.dock_menu.replace(new) {
937 CFRelease(old as _)
938 }
939 }
940 }
941
942 fn add_recent_document(&self, path: &Path) {
943 if let Some(path_str) = path.to_str() {
944 unsafe {
945 let document_controller: id =
946 msg_send![class!(NSDocumentController), sharedDocumentController];
947 let url: id = NSURL::fileURLWithPath_(nil, ns_string(path_str));
948 let _: () = msg_send![document_controller, noteNewRecentDocumentURL:url];
949 }
950 }
951 }
952
953 fn path_for_auxiliary_executable(&self, name: &str) -> Result<PathBuf> {
954 unsafe {
955 let bundle: id = NSBundle::mainBundle();
956 anyhow::ensure!(!bundle.is_null(), "app is not running inside a bundle");
957 let name = ns_string(name);
958 let url: id = msg_send![bundle, URLForAuxiliaryExecutable: name];
959 anyhow::ensure!(!url.is_null(), "resource not found");
960 ns_url_to_path(url)
961 }
962 }
963
964 /// Match cursor style to one of the styles available
965 /// in macOS's [NSCursor](https://developer.apple.com/documentation/appkit/nscursor).
966 fn set_cursor_style(&self, style: CursorStyle) {
967 unsafe {
968 if style == CursorStyle::None {
969 let _: () = msg_send![class!(NSCursor), setHiddenUntilMouseMoves:YES];
970 return;
971 }
972
973 let new_cursor: id = match style {
974 CursorStyle::Arrow => msg_send![class!(NSCursor), arrowCursor],
975 CursorStyle::IBeam => msg_send![class!(NSCursor), IBeamCursor],
976 CursorStyle::Crosshair => msg_send![class!(NSCursor), crosshairCursor],
977 CursorStyle::ClosedHand => msg_send![class!(NSCursor), closedHandCursor],
978 CursorStyle::OpenHand => msg_send![class!(NSCursor), openHandCursor],
979 CursorStyle::PointingHand => msg_send![class!(NSCursor), pointingHandCursor],
980 CursorStyle::ResizeLeftRight => msg_send![class!(NSCursor), resizeLeftRightCursor],
981 CursorStyle::ResizeUpDown => msg_send![class!(NSCursor), resizeUpDownCursor],
982 CursorStyle::ResizeLeft => msg_send![class!(NSCursor), resizeLeftCursor],
983 CursorStyle::ResizeRight => msg_send![class!(NSCursor), resizeRightCursor],
984 CursorStyle::ResizeColumn => msg_send![class!(NSCursor), resizeLeftRightCursor],
985 CursorStyle::ResizeRow => msg_send![class!(NSCursor), resizeUpDownCursor],
986 CursorStyle::ResizeUp => msg_send![class!(NSCursor), resizeUpCursor],
987 CursorStyle::ResizeDown => msg_send![class!(NSCursor), resizeDownCursor],
988
989 // Undocumented, private class methods:
990 // https://stackoverflow.com/questions/27242353/cocoa-predefined-resize-mouse-cursor
991 CursorStyle::ResizeUpLeftDownRight => {
992 msg_send![class!(NSCursor), _windowResizeNorthWestSouthEastCursor]
993 }
994 CursorStyle::ResizeUpRightDownLeft => {
995 msg_send![class!(NSCursor), _windowResizeNorthEastSouthWestCursor]
996 }
997
998 CursorStyle::IBeamCursorForVerticalLayout => {
999 msg_send![class!(NSCursor), IBeamCursorForVerticalLayout]
1000 }
1001 CursorStyle::OperationNotAllowed => {
1002 msg_send![class!(NSCursor), operationNotAllowedCursor]
1003 }
1004 CursorStyle::DragLink => msg_send![class!(NSCursor), dragLinkCursor],
1005 CursorStyle::DragCopy => msg_send![class!(NSCursor), dragCopyCursor],
1006 CursorStyle::ContextualMenu => msg_send![class!(NSCursor), contextualMenuCursor],
1007 CursorStyle::None => unreachable!(),
1008 };
1009
1010 let old_cursor: id = msg_send![class!(NSCursor), currentCursor];
1011 if new_cursor != old_cursor {
1012 let _: () = msg_send![new_cursor, set];
1013 }
1014 }
1015 }
1016
1017 fn should_auto_hide_scrollbars(&self) -> bool {
1018 #[allow(non_upper_case_globals)]
1019 const NSScrollerStyleOverlay: NSInteger = 1;
1020
1021 unsafe {
1022 let style: NSInteger = msg_send![class!(NSScroller), preferredScrollerStyle];
1023 style == NSScrollerStyleOverlay
1024 }
1025 }
1026
1027 fn write_to_clipboard(&self, item: ClipboardItem) {
1028 use crate::ClipboardEntry;
1029
1030 unsafe {
1031 // We only want to use NSAttributedString if there are multiple entries to write.
1032 if item.entries.len() <= 1 {
1033 match item.entries.first() {
1034 Some(entry) => match entry {
1035 ClipboardEntry::String(string) => {
1036 self.write_plaintext_to_clipboard(string);
1037 }
1038 ClipboardEntry::Image(image) => {
1039 self.write_image_to_clipboard(image);
1040 }
1041 },
1042 None => {
1043 // Writing an empty list of entries just clears the clipboard.
1044 let state = self.0.lock();
1045 state.pasteboard.clearContents();
1046 }
1047 }
1048 } else {
1049 let mut any_images = false;
1050 let attributed_string = {
1051 let mut buf = NSMutableAttributedString::alloc(nil)
1052 // TODO can we skip this? Or at least part of it?
1053 .init_attributed_string(NSString::alloc(nil).init_str(""));
1054
1055 for entry in item.entries {
1056 if let ClipboardEntry::String(ClipboardString { text, metadata: _ }) = entry
1057 {
1058 let to_append = NSAttributedString::alloc(nil)
1059 .init_attributed_string(NSString::alloc(nil).init_str(&text));
1060
1061 buf.appendAttributedString_(to_append);
1062 }
1063 }
1064
1065 buf
1066 };
1067
1068 let state = self.0.lock();
1069 state.pasteboard.clearContents();
1070
1071 // Only set rich text clipboard types if we actually have 1+ images to include.
1072 if any_images {
1073 let rtfd_data = attributed_string.RTFDFromRange_documentAttributes_(
1074 NSRange::new(0, msg_send![attributed_string, length]),
1075 nil,
1076 );
1077 if rtfd_data != nil {
1078 state
1079 .pasteboard
1080 .setData_forType(rtfd_data, NSPasteboardTypeRTFD);
1081 }
1082
1083 let rtf_data = attributed_string.RTFFromRange_documentAttributes_(
1084 NSRange::new(0, attributed_string.length()),
1085 nil,
1086 );
1087 if rtf_data != nil {
1088 state
1089 .pasteboard
1090 .setData_forType(rtf_data, NSPasteboardTypeRTF);
1091 }
1092 }
1093
1094 let plain_text = attributed_string.string();
1095 state
1096 .pasteboard
1097 .setString_forType(plain_text, NSPasteboardTypeString);
1098 }
1099 }
1100 }
1101
1102 fn read_from_clipboard(&self) -> Option<ClipboardItem> {
1103 let state = self.0.lock();
1104 let pasteboard = state.pasteboard;
1105
1106 // First, see if it's a string.
1107 unsafe {
1108 let types: id = pasteboard.types();
1109 let string_type: id = ns_string("public.utf8-plain-text");
1110
1111 if msg_send![types, containsObject: string_type] {
1112 let data = pasteboard.dataForType(string_type);
1113 if data == nil {
1114 return None;
1115 } else if data.bytes().is_null() {
1116 // https://developer.apple.com/documentation/foundation/nsdata/1410616-bytes?language=objc
1117 // "If the length of the NSData object is 0, this property returns nil."
1118 return Some(self.read_string_from_clipboard(&state, &[]));
1119 } else {
1120 let bytes =
1121 slice::from_raw_parts(data.bytes() as *mut u8, data.length() as usize);
1122
1123 return Some(self.read_string_from_clipboard(&state, bytes));
1124 }
1125 }
1126
1127 // Next, check for URL flavors (including file URLs). Some tools only provide a URL
1128 // with no plain text entry.
1129 {
1130 // Try the modern UTType identifiers first.
1131 let file_url_type: id = ns_string("public.file-url");
1132 let url_type: id = ns_string("public.url");
1133
1134 let url_data = if msg_send![types, containsObject: file_url_type] {
1135 pasteboard.dataForType(file_url_type)
1136 } else if msg_send![types, containsObject: url_type] {
1137 pasteboard.dataForType(url_type)
1138 } else {
1139 nil
1140 };
1141
1142 if url_data != nil && !url_data.bytes().is_null() {
1143 let bytes = slice::from_raw_parts(
1144 url_data.bytes() as *mut u8,
1145 url_data.length() as usize,
1146 );
1147
1148 return Some(self.read_string_from_clipboard(&state, bytes));
1149 }
1150 }
1151
1152 // If it wasn't a string or URL, try the various supported image types.
1153 for format in ImageFormat::iter() {
1154 if let Some(item) = try_clipboard_image(pasteboard, format) {
1155 return Some(item);
1156 }
1157 }
1158 }
1159
1160 // If it wasn't a string, URL, or a supported image type, give up.
1161 None
1162 }
1163
1164 fn write_credentials(&self, url: &str, username: &str, password: &[u8]) -> Task<Result<()>> {
1165 let url = url.to_string();
1166 let username = username.to_string();
1167 let password = password.to_vec();
1168 self.background_executor().spawn(async move {
1169 unsafe {
1170 use security::*;
1171
1172 let url = CFString::from(url.as_str());
1173 let username = CFString::from(username.as_str());
1174 let password = CFData::from_buffer(&password);
1175
1176 // First, check if there are already credentials for the given server. If so, then
1177 // update the username and password.
1178 let mut verb = "updating";
1179 let mut query_attrs = CFMutableDictionary::with_capacity(2);
1180 query_attrs.set(kSecClass as *const _, kSecClassInternetPassword as *const _);
1181 query_attrs.set(kSecAttrServer as *const _, url.as_CFTypeRef());
1182
1183 let mut attrs = CFMutableDictionary::with_capacity(4);
1184 attrs.set(kSecClass as *const _, kSecClassInternetPassword as *const _);
1185 attrs.set(kSecAttrServer as *const _, url.as_CFTypeRef());
1186 attrs.set(kSecAttrAccount as *const _, username.as_CFTypeRef());
1187 attrs.set(kSecValueData as *const _, password.as_CFTypeRef());
1188
1189 let mut status = SecItemUpdate(
1190 query_attrs.as_concrete_TypeRef(),
1191 attrs.as_concrete_TypeRef(),
1192 );
1193
1194 // If there were no existing credentials for the given server, then create them.
1195 if status == errSecItemNotFound {
1196 verb = "creating";
1197 status = SecItemAdd(attrs.as_concrete_TypeRef(), ptr::null_mut());
1198 }
1199 anyhow::ensure!(status == errSecSuccess, "{verb} password failed: {status}");
1200 }
1201 Ok(())
1202 })
1203 }
1204
1205 fn read_credentials(&self, url: &str) -> Task<Result<Option<(String, Vec<u8>)>>> {
1206 let url = url.to_string();
1207 self.background_executor().spawn(async move {
1208 let url = CFString::from(url.as_str());
1209 let cf_true = CFBoolean::true_value().as_CFTypeRef();
1210
1211 unsafe {
1212 use security::*;
1213
1214 // Find any credentials for the given server URL.
1215 let mut attrs = CFMutableDictionary::with_capacity(5);
1216 attrs.set(kSecClass as *const _, kSecClassInternetPassword as *const _);
1217 attrs.set(kSecAttrServer as *const _, url.as_CFTypeRef());
1218 attrs.set(kSecReturnAttributes as *const _, cf_true);
1219 attrs.set(kSecReturnData as *const _, cf_true);
1220
1221 let mut result = CFTypeRef::from(ptr::null());
1222 let status = SecItemCopyMatching(attrs.as_concrete_TypeRef(), &mut result);
1223 match status {
1224 security::errSecSuccess => {}
1225 security::errSecItemNotFound | security::errSecUserCanceled => return Ok(None),
1226 _ => anyhow::bail!("reading password failed: {status}"),
1227 }
1228
1229 let result = CFType::wrap_under_create_rule(result)
1230 .downcast::<CFDictionary>()
1231 .context("keychain item was not a dictionary")?;
1232 let username = result
1233 .find(kSecAttrAccount as *const _)
1234 .context("account was missing from keychain item")?;
1235 let username = CFType::wrap_under_get_rule(*username)
1236 .downcast::<CFString>()
1237 .context("account was not a string")?;
1238 let password = result
1239 .find(kSecValueData as *const _)
1240 .context("password was missing from keychain item")?;
1241 let password = CFType::wrap_under_get_rule(*password)
1242 .downcast::<CFData>()
1243 .context("password was not a string")?;
1244
1245 Ok(Some((username.to_string(), password.bytes().to_vec())))
1246 }
1247 })
1248 }
1249
1250 fn delete_credentials(&self, url: &str) -> Task<Result<()>> {
1251 let url = url.to_string();
1252
1253 self.background_executor().spawn(async move {
1254 unsafe {
1255 use security::*;
1256
1257 let url = CFString::from(url.as_str());
1258 let mut query_attrs = CFMutableDictionary::with_capacity(2);
1259 query_attrs.set(kSecClass as *const _, kSecClassInternetPassword as *const _);
1260 query_attrs.set(kSecAttrServer as *const _, url.as_CFTypeRef());
1261
1262 let status = SecItemDelete(query_attrs.as_concrete_TypeRef());
1263 anyhow::ensure!(status == errSecSuccess, "delete password failed: {status}");
1264 }
1265 Ok(())
1266 })
1267 }
1268}
1269
1270impl MacPlatform {
1271 unsafe fn read_string_from_clipboard(
1272 &self,
1273 state: &MacPlatformState,
1274 text_bytes: &[u8],
1275 ) -> ClipboardItem {
1276 unsafe {
1277 let text = String::from_utf8_lossy(text_bytes).to_string();
1278 let metadata = self
1279 .read_from_pasteboard(state.pasteboard, state.text_hash_pasteboard_type)
1280 .and_then(|hash_bytes| {
1281 let hash_bytes = hash_bytes.try_into().ok()?;
1282 let hash = u64::from_be_bytes(hash_bytes);
1283 let metadata = self
1284 .read_from_pasteboard(state.pasteboard, state.metadata_pasteboard_type)?;
1285
1286 if hash == ClipboardString::text_hash(&text) {
1287 String::from_utf8(metadata.to_vec()).ok()
1288 } else {
1289 None
1290 }
1291 });
1292
1293 ClipboardItem {
1294 entries: vec![ClipboardEntry::String(ClipboardString { text, metadata })],
1295 }
1296 }
1297 }
1298
1299 unsafe fn write_plaintext_to_clipboard(&self, string: &ClipboardString) {
1300 unsafe {
1301 let state = self.0.lock();
1302 state.pasteboard.clearContents();
1303
1304 let text_bytes = NSData::dataWithBytes_length_(
1305 nil,
1306 string.text.as_ptr() as *const c_void,
1307 string.text.len() as u64,
1308 );
1309 state
1310 .pasteboard
1311 .setData_forType(text_bytes, NSPasteboardTypeString);
1312
1313 if let Some(metadata) = string.metadata.as_ref() {
1314 let hash_bytes = ClipboardString::text_hash(&string.text).to_be_bytes();
1315 let hash_bytes = NSData::dataWithBytes_length_(
1316 nil,
1317 hash_bytes.as_ptr() as *const c_void,
1318 hash_bytes.len() as u64,
1319 );
1320 state
1321 .pasteboard
1322 .setData_forType(hash_bytes, state.text_hash_pasteboard_type);
1323
1324 let metadata_bytes = NSData::dataWithBytes_length_(
1325 nil,
1326 metadata.as_ptr() as *const c_void,
1327 metadata.len() as u64,
1328 );
1329 state
1330 .pasteboard
1331 .setData_forType(metadata_bytes, state.metadata_pasteboard_type);
1332 }
1333 }
1334 }
1335
1336 unsafe fn write_image_to_clipboard(&self, image: &Image) {
1337 unsafe {
1338 let state = self.0.lock();
1339 state.pasteboard.clearContents();
1340
1341 let bytes = NSData::dataWithBytes_length_(
1342 nil,
1343 image.bytes.as_ptr() as *const c_void,
1344 image.bytes.len() as u64,
1345 );
1346
1347 state
1348 .pasteboard
1349 .setData_forType(bytes, Into::<UTType>::into(image.format).inner_mut());
1350 }
1351 }
1352}
1353
1354fn try_clipboard_image(pasteboard: id, format: ImageFormat) -> Option<ClipboardItem> {
1355 let mut ut_type: UTType = format.into();
1356
1357 unsafe {
1358 let types: id = pasteboard.types();
1359 if msg_send![types, containsObject: ut_type.inner()] {
1360 let data = pasteboard.dataForType(ut_type.inner_mut());
1361 if data == nil {
1362 None
1363 } else {
1364 let bytes = Vec::from(slice::from_raw_parts(
1365 data.bytes() as *mut u8,
1366 data.length() as usize,
1367 ));
1368 let id = hash(&bytes);
1369
1370 Some(ClipboardItem {
1371 entries: vec![ClipboardEntry::Image(Image { format, bytes, id })],
1372 })
1373 }
1374 } else {
1375 None
1376 }
1377 }
1378}
1379
1380unsafe fn path_from_objc(path: id) -> PathBuf {
1381 let len = msg_send![path, lengthOfBytesUsingEncoding: NSUTF8StringEncoding];
1382 let bytes = unsafe { path.UTF8String() as *const u8 };
1383 let path = str::from_utf8(unsafe { slice::from_raw_parts(bytes, len) }).unwrap();
1384 PathBuf::from(path)
1385}
1386
1387unsafe fn get_mac_platform(object: &mut Object) -> &MacPlatform {
1388 unsafe {
1389 let platform_ptr: *mut c_void = *object.get_ivar(MAC_PLATFORM_IVAR);
1390 assert!(!platform_ptr.is_null());
1391 &*(platform_ptr as *const MacPlatform)
1392 }
1393}
1394
1395extern "C" fn will_finish_launching(_this: &mut Object, _: Sel, _: id) {
1396 unsafe {
1397 let user_defaults: id = msg_send![class!(NSUserDefaults), standardUserDefaults];
1398
1399 // The autofill heuristic controller causes slowdown and high CPU usage.
1400 // We don't know exactly why. This disables the full heuristic controller.
1401 //
1402 // Adapted from: https://github.com/ghostty-org/ghostty/pull/8625
1403 let name = ns_string("NSAutoFillHeuristicControllerEnabled");
1404 let existing_value: id = msg_send![user_defaults, objectForKey: name];
1405 if existing_value == nil {
1406 let false_value: id = msg_send![class!(NSNumber), numberWithBool:false];
1407 let _: () = msg_send![user_defaults, setObject: false_value forKey: name];
1408 }
1409 }
1410}
1411
1412extern "C" fn did_finish_launching(this: &mut Object, _: Sel, _: id) {
1413 unsafe {
1414 let app: id = msg_send![APP_CLASS, sharedApplication];
1415 app.setActivationPolicy_(NSApplicationActivationPolicyRegular);
1416
1417 let notification_center: *mut Object =
1418 msg_send![class!(NSNotificationCenter), defaultCenter];
1419 let name = ns_string("NSTextInputContextKeyboardSelectionDidChangeNotification");
1420 let _: () = msg_send![notification_center, addObserver: this as id
1421 selector: sel!(onKeyboardLayoutChange:)
1422 name: name
1423 object: nil
1424 ];
1425
1426 let platform = get_mac_platform(this);
1427 let callback = platform.0.lock().finish_launching.take();
1428 if let Some(callback) = callback {
1429 callback();
1430 }
1431 }
1432}
1433
1434extern "C" fn should_handle_reopen(this: &mut Object, _: Sel, _: id, has_open_windows: bool) {
1435 if !has_open_windows {
1436 let platform = unsafe { get_mac_platform(this) };
1437 let mut lock = platform.0.lock();
1438 if let Some(mut callback) = lock.reopen.take() {
1439 drop(lock);
1440 callback();
1441 platform.0.lock().reopen.get_or_insert(callback);
1442 }
1443 }
1444}
1445
1446extern "C" fn will_terminate(this: &mut Object, _: Sel, _: id) {
1447 let platform = unsafe { get_mac_platform(this) };
1448 let mut lock = platform.0.lock();
1449 if let Some(mut callback) = lock.quit.take() {
1450 drop(lock);
1451 callback();
1452 platform.0.lock().quit.get_or_insert(callback);
1453 }
1454}
1455
1456extern "C" fn on_keyboard_layout_change(this: &mut Object, _: Sel, _: id) {
1457 let platform = unsafe { get_mac_platform(this) };
1458 let mut lock = platform.0.lock();
1459 let keyboard_layout = MacKeyboardLayout::new();
1460 lock.keyboard_mapper = Rc::new(MacKeyboardMapper::new(keyboard_layout.id()));
1461 if let Some(mut callback) = lock.on_keyboard_layout_change.take() {
1462 drop(lock);
1463 callback();
1464 platform
1465 .0
1466 .lock()
1467 .on_keyboard_layout_change
1468 .get_or_insert(callback);
1469 }
1470}
1471
1472extern "C" fn open_urls(this: &mut Object, _: Sel, _: id, urls: id) {
1473 let urls = unsafe {
1474 (0..urls.count())
1475 .filter_map(|i| {
1476 let url = urls.objectAtIndex(i);
1477 match CStr::from_ptr(url.absoluteString().UTF8String() as *mut c_char).to_str() {
1478 Ok(string) => Some(string.to_string()),
1479 Err(err) => {
1480 log::error!("error converting path to string: {}", err);
1481 None
1482 }
1483 }
1484 })
1485 .collect::<Vec<_>>()
1486 };
1487 let platform = unsafe { get_mac_platform(this) };
1488 let mut lock = platform.0.lock();
1489 if let Some(mut callback) = lock.open_urls.take() {
1490 drop(lock);
1491 callback(urls);
1492 platform.0.lock().open_urls.get_or_insert(callback);
1493 }
1494}
1495
1496extern "C" fn handle_menu_item(this: &mut Object, _: Sel, item: id) {
1497 unsafe {
1498 let platform = get_mac_platform(this);
1499 let mut lock = platform.0.lock();
1500 if let Some(mut callback) = lock.menu_command.take() {
1501 let tag: NSInteger = msg_send![item, tag];
1502 let index = tag as usize;
1503 if let Some(action) = lock.menu_actions.get(index) {
1504 let action = action.boxed_clone();
1505 drop(lock);
1506 callback(&*action);
1507 }
1508 platform.0.lock().menu_command.get_or_insert(callback);
1509 }
1510 }
1511}
1512
1513extern "C" fn validate_menu_item(this: &mut Object, _: Sel, item: id) -> bool {
1514 unsafe {
1515 let mut result = false;
1516 let platform = get_mac_platform(this);
1517 let mut lock = platform.0.lock();
1518 if let Some(mut callback) = lock.validate_menu_command.take() {
1519 let tag: NSInteger = msg_send![item, tag];
1520 let index = tag as usize;
1521 if let Some(action) = lock.menu_actions.get(index) {
1522 let action = action.boxed_clone();
1523 drop(lock);
1524 result = callback(action.as_ref());
1525 }
1526 platform
1527 .0
1528 .lock()
1529 .validate_menu_command
1530 .get_or_insert(callback);
1531 }
1532 result
1533 }
1534}
1535
1536extern "C" fn menu_will_open(this: &mut Object, _: Sel, _: id) {
1537 unsafe {
1538 let platform = get_mac_platform(this);
1539 let mut lock = platform.0.lock();
1540 if let Some(mut callback) = lock.will_open_menu.take() {
1541 drop(lock);
1542 callback();
1543 platform.0.lock().will_open_menu.get_or_insert(callback);
1544 }
1545 }
1546}
1547
1548extern "C" fn handle_dock_menu(this: &mut Object, _: Sel, _: id) -> id {
1549 unsafe {
1550 let platform = get_mac_platform(this);
1551 let mut state = platform.0.lock();
1552 if let Some(id) = state.dock_menu {
1553 id
1554 } else {
1555 nil
1556 }
1557 }
1558}
1559
1560unsafe fn ns_string(string: &str) -> id {
1561 unsafe { NSString::alloc(nil).init_str(string).autorelease() }
1562}
1563
1564unsafe fn ns_url_to_path(url: id) -> Result<PathBuf> {
1565 let path: *mut c_char = msg_send![url, fileSystemRepresentation];
1566 anyhow::ensure!(!path.is_null(), "url is not a file path: {}", unsafe {
1567 CStr::from_ptr(url.absoluteString().UTF8String()).to_string_lossy()
1568 });
1569 Ok(PathBuf::from(OsStr::from_bytes(unsafe {
1570 CStr::from_ptr(path).to_bytes()
1571 })))
1572}
1573
1574#[link(name = "Carbon", kind = "framework")]
1575unsafe extern "C" {
1576 pub(super) fn TISCopyCurrentKeyboardLayoutInputSource() -> *mut Object;
1577 pub(super) fn TISGetInputSourceProperty(
1578 inputSource: *mut Object,
1579 propertyKey: *const c_void,
1580 ) -> *mut Object;
1581
1582 pub(super) fn UCKeyTranslate(
1583 keyLayoutPtr: *const ::std::os::raw::c_void,
1584 virtualKeyCode: u16,
1585 keyAction: u16,
1586 modifierKeyState: u32,
1587 keyboardType: u32,
1588 keyTranslateOptions: u32,
1589 deadKeyState: *mut u32,
1590 maxStringLength: usize,
1591 actualStringLength: *mut usize,
1592 unicodeString: *mut u16,
1593 ) -> u32;
1594 pub(super) fn LMGetKbdType() -> u16;
1595 pub(super) static kTISPropertyUnicodeKeyLayoutData: CFStringRef;
1596 pub(super) static kTISPropertyInputSourceID: CFStringRef;
1597 pub(super) static kTISPropertyLocalizedName: CFStringRef;
1598}
1599
1600mod security {
1601 #![allow(non_upper_case_globals)]
1602 use super::*;
1603
1604 #[link(name = "Security", kind = "framework")]
1605 unsafe extern "C" {
1606 pub static kSecClass: CFStringRef;
1607 pub static kSecClassInternetPassword: CFStringRef;
1608 pub static kSecAttrServer: CFStringRef;
1609 pub static kSecAttrAccount: CFStringRef;
1610 pub static kSecValueData: CFStringRef;
1611 pub static kSecReturnAttributes: CFStringRef;
1612 pub static kSecReturnData: CFStringRef;
1613
1614 pub fn SecItemAdd(attributes: CFDictionaryRef, result: *mut CFTypeRef) -> OSStatus;
1615 pub fn SecItemUpdate(query: CFDictionaryRef, attributes: CFDictionaryRef) -> OSStatus;
1616 pub fn SecItemDelete(query: CFDictionaryRef) -> OSStatus;
1617 pub fn SecItemCopyMatching(query: CFDictionaryRef, result: *mut CFTypeRef) -> OSStatus;
1618 }
1619
1620 pub const errSecSuccess: OSStatus = 0;
1621 pub const errSecUserCanceled: OSStatus = -128;
1622 pub const errSecItemNotFound: OSStatus = -25300;
1623}
1624
1625impl From<ImageFormat> for UTType {
1626 fn from(value: ImageFormat) -> Self {
1627 match value {
1628 ImageFormat::Png => Self::png(),
1629 ImageFormat::Jpeg => Self::jpeg(),
1630 ImageFormat::Tiff => Self::tiff(),
1631 ImageFormat::Webp => Self::webp(),
1632 ImageFormat::Gif => Self::gif(),
1633 ImageFormat::Bmp => Self::bmp(),
1634 ImageFormat::Svg => Self::svg(),
1635 ImageFormat::Ico => Self::ico(),
1636 }
1637 }
1638}
1639
1640// See https://developer.apple.com/documentation/uniformtypeidentifiers/uttype-swift.struct/
1641struct UTType(id);
1642
1643impl UTType {
1644 pub fn png() -> Self {
1645 // https://developer.apple.com/documentation/uniformtypeidentifiers/uttype-swift.struct/png
1646 Self(unsafe { NSPasteboardTypePNG }) // This is a rare case where there's a built-in NSPasteboardType
1647 }
1648
1649 pub fn jpeg() -> Self {
1650 // https://developer.apple.com/documentation/uniformtypeidentifiers/uttype-swift.struct/jpeg
1651 Self(unsafe { ns_string("public.jpeg") })
1652 }
1653
1654 pub fn gif() -> Self {
1655 // https://developer.apple.com/documentation/uniformtypeidentifiers/uttype-swift.struct/gif
1656 Self(unsafe { ns_string("com.compuserve.gif") })
1657 }
1658
1659 pub fn webp() -> Self {
1660 // https://developer.apple.com/documentation/uniformtypeidentifiers/uttype-swift.struct/webp
1661 Self(unsafe { ns_string("org.webmproject.webp") })
1662 }
1663
1664 pub fn bmp() -> Self {
1665 // https://developer.apple.com/documentation/uniformtypeidentifiers/uttype-swift.struct/bmp
1666 Self(unsafe { ns_string("com.microsoft.bmp") })
1667 }
1668
1669 pub fn svg() -> Self {
1670 // https://developer.apple.com/documentation/uniformtypeidentifiers/uttype-swift.struct/svg
1671 Self(unsafe { ns_string("public.svg-image") })
1672 }
1673
1674 pub fn ico() -> Self {
1675 // https://developer.apple.com/documentation/uniformtypeidentifiers/uttype-swift.struct/ico
1676 Self(unsafe { ns_string("com.microsoft.ico") })
1677 }
1678
1679 pub fn tiff() -> Self {
1680 // https://developer.apple.com/documentation/uniformtypeidentifiers/uttype-swift.struct/tiff
1681 Self(unsafe { NSPasteboardTypeTIFF }) // This is a rare case where there's a built-in NSPasteboardType
1682 }
1683
1684 fn inner(&self) -> *const Object {
1685 self.0
1686 }
1687
1688 fn inner_mut(&self) -> *mut Object {
1689 self.0 as *mut _
1690 }
1691}
1692
1693#[cfg(test)]
1694mod tests {
1695 use crate::ClipboardItem;
1696
1697 use super::*;
1698
1699 #[test]
1700 fn test_clipboard() {
1701 let platform = build_platform();
1702 assert_eq!(platform.read_from_clipboard(), None);
1703
1704 let item = ClipboardItem::new_string("1".to_string());
1705 platform.write_to_clipboard(item.clone());
1706 assert_eq!(platform.read_from_clipboard(), Some(item));
1707
1708 let item = ClipboardItem {
1709 entries: vec![ClipboardEntry::String(
1710 ClipboardString::new("2".to_string()).with_json_metadata(vec![3, 4]),
1711 )],
1712 };
1713 platform.write_to_clipboard(item.clone());
1714 assert_eq!(platform.read_from_clipboard(), Some(item));
1715
1716 let text_from_other_app = "text from other app";
1717 unsafe {
1718 let bytes = NSData::dataWithBytes_length_(
1719 nil,
1720 text_from_other_app.as_ptr() as *const c_void,
1721 text_from_other_app.len() as u64,
1722 );
1723 platform
1724 .0
1725 .lock()
1726 .pasteboard
1727 .setData_forType(bytes, NSPasteboardTypeString);
1728 }
1729 assert_eq!(
1730 platform.read_from_clipboard(),
1731 Some(ClipboardItem::new_string(text_from_other_app.to_string()))
1732 );
1733 }
1734
1735 #[test]
1736 fn test_file_url_reads_as_url_string() {
1737 let platform = build_platform();
1738
1739 // Create a file URL for an arbitrary test path and write it to the pasteboard.
1740 // This path does not need to exist; we only validate URL→path conversion.
1741 let mock_path = "/tmp/zed-clipboard-file-url-test";
1742 unsafe {
1743 // Build an NSURL from the file path
1744 let url: id = msg_send![class!(NSURL), fileURLWithPath: ns_string(mock_path)];
1745 let abs: id = msg_send![url, absoluteString];
1746
1747 // Encode the URL string as UTF-8 bytes
1748 let len: usize = msg_send![abs, lengthOfBytesUsingEncoding: NSUTF8StringEncoding];
1749 let bytes_ptr = abs.UTF8String() as *const u8;
1750 let data = NSData::dataWithBytes_length_(nil, bytes_ptr as *const c_void, len as u64);
1751
1752 // Write as public.file-url to the unique pasteboard
1753 let file_url_type: id = ns_string("public.file-url");
1754 platform
1755 .0
1756 .lock()
1757 .pasteboard
1758 .setData_forType(data, file_url_type);
1759 }
1760
1761 // Ensure the clipboard read returns the URL string, not a converted path
1762 let expected_url = format!("file://{}", mock_path);
1763 assert_eq!(
1764 platform.read_from_clipboard(),
1765 Some(ClipboardItem::new_string(expected_url))
1766 );
1767 }
1768
1769 fn build_platform() -> MacPlatform {
1770 let platform = MacPlatform::new(false);
1771 platform.0.lock().pasteboard = unsafe { NSPasteboard::pasteboardWithUniqueName(nil) };
1772 platform
1773 }
1774}