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