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