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