1use super::{events::key_to_native, BoolExt};
2use crate::{
3 Action, AnyWindowHandle, BackgroundExecutor, ClipboardItem, CursorStyle, DisplayId,
4 ForegroundExecutor, InputEvent, Keymap, MacDispatcher, MacDisplay, MacDisplayLinker,
5 MacTextSystem, MacWindow, Menu, MenuItem, PathPromptOptions, Platform, PlatformDisplay,
6 PlatformTextSystem, PlatformWindow, Result, Scene, SemanticVersion, VideoTimestamp,
7 WindowOptions,
8};
9use anyhow::anyhow;
10use block::ConcreteBlock;
11use cocoa::{
12 appkit::{
13 NSApplication, NSApplicationActivationPolicy::NSApplicationActivationPolicyRegular,
14 NSEventModifierFlags, NSMenu, NSMenuItem, NSModalResponse, NSOpenPanel, NSPasteboard,
15 NSPasteboardTypeString, NSSavePanel, NSWindow,
16 },
17 base::{id, nil, selector, BOOL, YES},
18 foundation::{
19 NSArray, NSAutoreleasePool, NSBundle, NSData, NSInteger, NSProcessInfo, NSString,
20 NSUInteger, NSURL,
21 },
22};
23use core_foundation::{
24 base::{CFType, CFTypeRef, OSStatus, TCFType as _},
25 boolean::CFBoolean,
26 data::CFData,
27 dictionary::{CFDictionary, CFDictionaryRef, CFMutableDictionary},
28 string::{CFString, CFStringRef},
29};
30use ctor::ctor;
31use futures::channel::oneshot;
32use objc::{
33 class,
34 declare::ClassDecl,
35 msg_send,
36 runtime::{Class, Object, Sel},
37 sel, sel_impl,
38};
39use parking_lot::Mutex;
40use ptr::null_mut;
41use std::{
42 cell::Cell,
43 convert::TryInto,
44 ffi::{c_void, CStr, OsStr},
45 os::{raw::c_char, unix::ffi::OsStrExt},
46 path::{Path, PathBuf},
47 process::Command,
48 ptr,
49 rc::Rc,
50 slice, str,
51 sync::Arc,
52 time::Duration,
53};
54use time::UtcOffset;
55
56#[allow(non_upper_case_globals)]
57const NSUTF8StringEncoding: NSUInteger = 4;
58
59#[allow(non_upper_case_globals)]
60pub const NSViewLayerContentsRedrawDuringViewResize: NSInteger = 2;
61
62const MAC_PLATFORM_IVAR: &str = "platform";
63static mut APP_CLASS: *const Class = ptr::null();
64static mut APP_DELEGATE_CLASS: *const Class = ptr::null();
65
66#[ctor]
67unsafe fn build_classes() {
68 APP_CLASS = {
69 let mut decl = ClassDecl::new("GPUIApplication", class!(NSApplication)).unwrap();
70 decl.add_ivar::<*mut c_void>(MAC_PLATFORM_IVAR);
71 decl.add_method(
72 sel!(sendEvent:),
73 send_event as extern "C" fn(&mut Object, Sel, id),
74 );
75 decl.register()
76 };
77
78 APP_DELEGATE_CLASS = {
79 let mut decl = ClassDecl::new("GPUIApplicationDelegate", class!(NSResponder)).unwrap();
80 decl.add_ivar::<*mut c_void>(MAC_PLATFORM_IVAR);
81 decl.add_method(
82 sel!(applicationDidFinishLaunching:),
83 did_finish_launching as extern "C" fn(&mut Object, Sel, id),
84 );
85 decl.add_method(
86 sel!(applicationShouldHandleReopen:hasVisibleWindows:),
87 should_handle_reopen as extern "C" fn(&mut Object, Sel, id, bool),
88 );
89 decl.add_method(
90 sel!(applicationDidBecomeActive:),
91 did_become_active as extern "C" fn(&mut Object, Sel, id),
92 );
93 decl.add_method(
94 sel!(applicationDidResignActive:),
95 did_resign_active as extern "C" fn(&mut Object, Sel, id),
96 );
97 decl.add_method(
98 sel!(applicationWillTerminate:),
99 will_terminate as extern "C" fn(&mut Object, Sel, id),
100 );
101 decl.add_method(
102 sel!(handleGPUIMenuItem:),
103 handle_menu_item as extern "C" fn(&mut Object, Sel, id),
104 );
105 // Add menu item handlers so that OS save panels have the correct key commands
106 decl.add_method(
107 sel!(cut:),
108 handle_menu_item as extern "C" fn(&mut Object, Sel, id),
109 );
110 decl.add_method(
111 sel!(copy:),
112 handle_menu_item as extern "C" fn(&mut Object, Sel, id),
113 );
114 decl.add_method(
115 sel!(paste:),
116 handle_menu_item as extern "C" fn(&mut Object, Sel, id),
117 );
118 decl.add_method(
119 sel!(selectAll:),
120 handle_menu_item as extern "C" fn(&mut Object, Sel, id),
121 );
122 decl.add_method(
123 sel!(undo:),
124 handle_menu_item as extern "C" fn(&mut Object, Sel, id),
125 );
126 decl.add_method(
127 sel!(redo:),
128 handle_menu_item as extern "C" fn(&mut Object, Sel, id),
129 );
130 decl.add_method(
131 sel!(validateMenuItem:),
132 validate_menu_item as extern "C" fn(&mut Object, Sel, id) -> bool,
133 );
134 decl.add_method(
135 sel!(menuWillOpen:),
136 menu_will_open as extern "C" fn(&mut Object, Sel, id),
137 );
138 decl.add_method(
139 sel!(application:openURLs:),
140 open_urls as extern "C" fn(&mut Object, Sel, id, id),
141 );
142 decl.register()
143 }
144}
145
146pub struct MacPlatform(Mutex<MacPlatformState>);
147
148pub struct MacPlatformState {
149 background_executor: BackgroundExecutor,
150 foreground_executor: ForegroundExecutor,
151 text_system: Arc<MacTextSystem>,
152 display_linker: MacDisplayLinker,
153 pasteboard: id,
154 text_hash_pasteboard_type: id,
155 metadata_pasteboard_type: id,
156 become_active: Option<Box<dyn FnMut()>>,
157 resign_active: Option<Box<dyn FnMut()>>,
158 reopen: Option<Box<dyn FnMut()>>,
159 quit: Option<Box<dyn FnMut()>>,
160 event: Option<Box<dyn FnMut(InputEvent) -> bool>>,
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}
168
169impl Default for MacPlatform {
170 fn default() -> Self {
171 Self::new()
172 }
173}
174
175impl MacPlatform {
176 pub fn new() -> Self {
177 let dispatcher = Arc::new(MacDispatcher::new());
178 Self(Mutex::new(MacPlatformState {
179 background_executor: BackgroundExecutor::new(dispatcher.clone()),
180 foreground_executor: ForegroundExecutor::new(dispatcher),
181 text_system: Arc::new(MacTextSystem::new()),
182 display_linker: MacDisplayLinker::new(),
183 pasteboard: unsafe { NSPasteboard::generalPasteboard(nil) },
184 text_hash_pasteboard_type: unsafe { ns_string("zed-text-hash") },
185 metadata_pasteboard_type: unsafe { ns_string("zed-metadata") },
186 become_active: None,
187 resign_active: None,
188 reopen: None,
189 quit: None,
190 event: None,
191 menu_command: None,
192 validate_menu_command: None,
193 will_open_menu: None,
194 menu_actions: Default::default(),
195 open_urls: None,
196 finish_launching: None,
197 }))
198 }
199
200 unsafe fn read_from_pasteboard(&self, pasteboard: *mut Object, kind: id) -> Option<&[u8]> {
201 let data = pasteboard.dataForType(kind);
202 if data == nil {
203 None
204 } else {
205 Some(slice::from_raw_parts(
206 data.bytes() as *mut u8,
207 data.length() as usize,
208 ))
209 }
210 }
211
212 unsafe fn create_menu_bar(
213 &self,
214 menus: Vec<Menu>,
215 delegate: id,
216 actions: &mut Vec<Box<dyn Action>>,
217 keymap: &Keymap,
218 ) -> id {
219 let application_menu = NSMenu::new(nil).autorelease();
220 application_menu.setDelegate_(delegate);
221
222 for menu_config in menus {
223 let menu = NSMenu::new(nil).autorelease();
224 menu.setTitle_(ns_string(menu_config.name));
225 menu.setDelegate_(delegate);
226
227 for item_config in menu_config.items {
228 menu.addItem_(Self::create_menu_item(
229 item_config,
230 delegate,
231 actions,
232 keymap,
233 ));
234 }
235
236 let menu_item = NSMenuItem::new(nil).autorelease();
237 menu_item.setSubmenu_(menu);
238 application_menu.addItem_(menu_item);
239
240 if menu_config.name == "Window" {
241 let app: id = msg_send![APP_CLASS, sharedApplication];
242 app.setWindowsMenu_(menu);
243 }
244 }
245
246 application_menu
247 }
248
249 unsafe fn create_menu_item(
250 item: MenuItem,
251 delegate: id,
252 actions: &mut Vec<Box<dyn Action>>,
253 keymap: &Keymap,
254 ) -> id {
255 match item {
256 MenuItem::Separator => NSMenuItem::separatorItem(nil),
257 MenuItem::Action {
258 name,
259 action,
260 os_action,
261 } => {
262 let keystrokes = keymap
263 .bindings_for_action(action.type_id())
264 .find(|binding| binding.action().partial_eq(action.as_ref()))
265 .map(|binding| binding.keystrokes());
266
267 let selector = match os_action {
268 Some(crate::OsAction::Cut) => selector("cut:"),
269 Some(crate::OsAction::Copy) => selector("copy:"),
270 Some(crate::OsAction::Paste) => selector("paste:"),
271 Some(crate::OsAction::SelectAll) => selector("selectAll:"),
272 Some(crate::OsAction::Undo) => selector("undo:"),
273 Some(crate::OsAction::Redo) => selector("redo:"),
274 None => selector("handleGPUIMenuItem:"),
275 };
276
277 let item;
278 if let Some(keystrokes) = keystrokes {
279 if keystrokes.len() == 1 {
280 let keystroke = &keystrokes[0];
281 let mut mask = NSEventModifierFlags::empty();
282 for (modifier, flag) in &[
283 (
284 keystroke.modifiers.command,
285 NSEventModifierFlags::NSCommandKeyMask,
286 ),
287 (
288 keystroke.modifiers.control,
289 NSEventModifierFlags::NSControlKeyMask,
290 ),
291 (
292 keystroke.modifiers.alt,
293 NSEventModifierFlags::NSAlternateKeyMask,
294 ),
295 (
296 keystroke.modifiers.shift,
297 NSEventModifierFlags::NSShiftKeyMask,
298 ),
299 ] {
300 if *modifier {
301 mask |= *flag;
302 }
303 }
304
305 item = NSMenuItem::alloc(nil)
306 .initWithTitle_action_keyEquivalent_(
307 ns_string(name),
308 selector,
309 ns_string(key_to_native(&keystroke.key).as_ref()),
310 )
311 .autorelease();
312 item.setKeyEquivalentModifierMask_(mask);
313 }
314 // For multi-keystroke bindings, render the keystroke as part of the title.
315 else {
316 use std::fmt::Write;
317
318 let mut name = format!("{name} [");
319 for (i, keystroke) in keystrokes.iter().enumerate() {
320 if i > 0 {
321 name.push(' ');
322 }
323 write!(&mut name, "{}", keystroke).unwrap();
324 }
325 name.push(']');
326
327 item = NSMenuItem::alloc(nil)
328 .initWithTitle_action_keyEquivalent_(
329 ns_string(&name),
330 selector,
331 ns_string(""),
332 )
333 .autorelease();
334 }
335 } else {
336 item = NSMenuItem::alloc(nil)
337 .initWithTitle_action_keyEquivalent_(
338 ns_string(name),
339 selector,
340 ns_string(""),
341 )
342 .autorelease();
343 }
344
345 let tag = actions.len() as NSInteger;
346 let _: () = msg_send![item, setTag: tag];
347 actions.push(action);
348 item
349 }
350 MenuItem::Submenu(Menu { name, items }) => {
351 let item = NSMenuItem::new(nil).autorelease();
352 let submenu = NSMenu::new(nil).autorelease();
353 submenu.setDelegate_(delegate);
354 for item in items {
355 submenu.addItem_(Self::create_menu_item(item, delegate, actions, keymap));
356 }
357 item.setSubmenu_(submenu);
358 item.setTitle_(ns_string(name));
359 item
360 }
361 }
362 }
363}
364
365impl Platform for MacPlatform {
366 fn background_executor(&self) -> BackgroundExecutor {
367 self.0.lock().background_executor.clone()
368 }
369
370 fn foreground_executor(&self) -> crate::ForegroundExecutor {
371 self.0.lock().foreground_executor.clone()
372 }
373
374 fn text_system(&self) -> Arc<dyn PlatformTextSystem> {
375 self.0.lock().text_system.clone()
376 }
377
378 fn run(&self, on_finish_launching: Box<dyn FnOnce()>) {
379 self.0.lock().finish_launching = Some(on_finish_launching);
380
381 unsafe {
382 let app: id = msg_send![APP_CLASS, sharedApplication];
383 let app_delegate: id = msg_send![APP_DELEGATE_CLASS, new];
384 app.setDelegate_(app_delegate);
385
386 let self_ptr = self as *const Self as *const c_void;
387 (*app).set_ivar(MAC_PLATFORM_IVAR, self_ptr);
388 (*app_delegate).set_ivar(MAC_PLATFORM_IVAR, self_ptr);
389
390 let pool = NSAutoreleasePool::new(nil);
391 app.run();
392 pool.drain();
393
394 (*app).set_ivar(MAC_PLATFORM_IVAR, null_mut::<c_void>());
395 (*app.delegate()).set_ivar(MAC_PLATFORM_IVAR, null_mut::<c_void>());
396 }
397 }
398
399 fn quit(&self) {
400 // Quitting the app causes us to close windows, which invokes `Window::on_close` callbacks
401 // synchronously before this method terminates. If we call `Platform::quit` while holding a
402 // borrow of the app state (which most of the time we will do), we will end up
403 // double-borrowing the app state in the `on_close` callbacks for our open windows. To solve
404 // this, we make quitting the application asynchronous so that we aren't holding borrows to
405 // the app state on the stack when we actually terminate the app.
406
407 use super::dispatcher::{dispatch_async_f, dispatch_get_main_queue};
408
409 unsafe {
410 dispatch_async_f(dispatch_get_main_queue(), ptr::null_mut(), Some(quit));
411 }
412
413 unsafe extern "C" fn quit(_: *mut c_void) {
414 let app = NSApplication::sharedApplication(nil);
415 let _: () = msg_send![app, terminate: nil];
416 }
417 }
418
419 fn restart(&self) {
420 use std::os::unix::process::CommandExt as _;
421
422 let app_pid = std::process::id().to_string();
423 let app_path = self
424 .app_path()
425 .ok()
426 // When the app is not bundled, `app_path` returns the
427 // directory containing the executable. Disregard this
428 // and get the path to the executable itself.
429 .and_then(|path| (path.extension()?.to_str()? == "app").then_some(path))
430 .unwrap_or_else(|| std::env::current_exe().unwrap());
431
432 // Wait until this process has exited and then re-open this path.
433 let script = r#"
434 while kill -0 $0 2> /dev/null; do
435 sleep 0.1
436 done
437 open "$1"
438 "#;
439
440 let restart_process = Command::new("/bin/bash")
441 .arg("-c")
442 .arg(script)
443 .arg(app_pid)
444 .arg(app_path)
445 .process_group(0)
446 .spawn();
447
448 match restart_process {
449 Ok(_) => self.quit(),
450 Err(e) => log::error!("failed to spawn restart script: {:?}", e),
451 }
452 }
453
454 fn activate(&self, ignoring_other_apps: bool) {
455 unsafe {
456 let app = NSApplication::sharedApplication(nil);
457 app.activateIgnoringOtherApps_(ignoring_other_apps.to_objc());
458 }
459 }
460
461 fn hide(&self) {
462 unsafe {
463 let app = NSApplication::sharedApplication(nil);
464 let _: () = msg_send![app, hide: nil];
465 }
466 }
467
468 fn hide_other_apps(&self) {
469 unsafe {
470 let app = NSApplication::sharedApplication(nil);
471 let _: () = msg_send![app, hideOtherApplications: nil];
472 }
473 }
474
475 fn unhide_other_apps(&self) {
476 unsafe {
477 let app = NSApplication::sharedApplication(nil);
478 let _: () = msg_send![app, unhideAllApplications: nil];
479 }
480 }
481
482 // fn add_status_item(&self, _handle: AnyWindowHandle) -> Box<dyn platform::Window> {
483 // Box::new(StatusItem::add(self.fonts()))
484 // }
485
486 fn displays(&self) -> Vec<Rc<dyn PlatformDisplay>> {
487 MacDisplay::all()
488 .map(|screen| Rc::new(screen) as Rc<_>)
489 .collect()
490 }
491
492 fn display(&self, id: DisplayId) -> Option<Rc<dyn PlatformDisplay>> {
493 MacDisplay::find_by_id(id).map(|screen| Rc::new(screen) as Rc<_>)
494 }
495
496 fn active_window(&self) -> Option<AnyWindowHandle> {
497 MacWindow::active_window()
498 }
499
500 fn open_window(
501 &self,
502 handle: AnyWindowHandle,
503 options: WindowOptions,
504 draw: Box<dyn FnMut() -> Result<Scene>>,
505 ) -> Box<dyn PlatformWindow> {
506 Box::new(MacWindow::open(
507 handle,
508 options,
509 draw,
510 self.foreground_executor(),
511 ))
512 }
513
514 fn set_display_link_output_callback(
515 &self,
516 display_id: DisplayId,
517 callback: Box<dyn FnMut(&VideoTimestamp, &VideoTimestamp) + Send>,
518 ) {
519 self.0
520 .lock()
521 .display_linker
522 .set_output_callback(display_id, callback);
523 }
524
525 fn start_display_link(&self, display_id: DisplayId) {
526 self.0.lock().display_linker.start(display_id);
527 }
528
529 fn stop_display_link(&self, display_id: DisplayId) {
530 self.0.lock().display_linker.stop(display_id);
531 }
532
533 fn open_url(&self, url: &str) {
534 unsafe {
535 let url = NSURL::alloc(nil)
536 .initWithString_(ns_string(url))
537 .autorelease();
538 let workspace: id = msg_send![class!(NSWorkspace), sharedWorkspace];
539 msg_send![workspace, openURL: url]
540 }
541 }
542
543 fn on_open_urls(&self, callback: Box<dyn FnMut(Vec<String>)>) {
544 self.0.lock().open_urls = Some(callback);
545 }
546
547 fn prompt_for_paths(
548 &self,
549 options: PathPromptOptions,
550 ) -> oneshot::Receiver<Option<Vec<PathBuf>>> {
551 unsafe {
552 let panel = NSOpenPanel::openPanel(nil);
553 panel.setCanChooseDirectories_(options.directories.to_objc());
554 panel.setCanChooseFiles_(options.files.to_objc());
555 panel.setAllowsMultipleSelection_(options.multiple.to_objc());
556 panel.setResolvesAliases_(false.to_objc());
557 let (done_tx, done_rx) = oneshot::channel();
558 let done_tx = Cell::new(Some(done_tx));
559 let block = ConcreteBlock::new(move |response: NSModalResponse| {
560 let result = if response == NSModalResponse::NSModalResponseOk {
561 let mut result = Vec::new();
562 let urls = panel.URLs();
563 for i in 0..urls.count() {
564 let url = urls.objectAtIndex(i);
565 if url.isFileURL() == YES {
566 if let Ok(path) = ns_url_to_path(url) {
567 result.push(path)
568 }
569 }
570 }
571 Some(result)
572 } else {
573 None
574 };
575
576 if let Some(done_tx) = done_tx.take() {
577 let _ = done_tx.send(result);
578 }
579 });
580 let block = block.copy();
581 let _: () = msg_send![panel, beginWithCompletionHandler: block];
582 done_rx
583 }
584 }
585
586 fn prompt_for_new_path(&self, directory: &Path) -> oneshot::Receiver<Option<PathBuf>> {
587 unsafe {
588 let panel = NSSavePanel::savePanel(nil);
589 let path = ns_string(directory.to_string_lossy().as_ref());
590 let url = NSURL::fileURLWithPath_isDirectory_(nil, path, true.to_objc());
591 panel.setDirectoryURL(url);
592
593 let (done_tx, done_rx) = oneshot::channel();
594 let done_tx = Cell::new(Some(done_tx));
595 let block = ConcreteBlock::new(move |response: NSModalResponse| {
596 let mut result = None;
597 if response == NSModalResponse::NSModalResponseOk {
598 let url = panel.URL();
599 if url.isFileURL() == YES {
600 result = ns_url_to_path(panel.URL()).ok()
601 }
602 }
603
604 if let Some(done_tx) = done_tx.take() {
605 let _ = done_tx.send(result);
606 }
607 });
608 let block = block.copy();
609 let _: () = msg_send![panel, beginWithCompletionHandler: block];
610 done_rx
611 }
612 }
613
614 fn reveal_path(&self, path: &Path) {
615 unsafe {
616 let path = path.to_path_buf();
617 self.0
618 .lock()
619 .background_executor
620 .spawn(async move {
621 let full_path = ns_string(path.to_str().unwrap_or(""));
622 let root_full_path = ns_string("");
623 let workspace: id = msg_send![class!(NSWorkspace), sharedWorkspace];
624 let _: BOOL = msg_send![
625 workspace,
626 selectFile: full_path
627 inFileViewerRootedAtPath: root_full_path
628 ];
629 })
630 .detach();
631 }
632 }
633
634 fn on_become_active(&self, callback: Box<dyn FnMut()>) {
635 self.0.lock().become_active = Some(callback);
636 }
637
638 fn on_resign_active(&self, callback: Box<dyn FnMut()>) {
639 self.0.lock().resign_active = Some(callback);
640 }
641
642 fn on_quit(&self, callback: Box<dyn FnMut()>) {
643 self.0.lock().quit = Some(callback);
644 }
645
646 fn on_reopen(&self, callback: Box<dyn FnMut()>) {
647 self.0.lock().reopen = Some(callback);
648 }
649
650 fn on_event(&self, callback: Box<dyn FnMut(InputEvent) -> bool>) {
651 self.0.lock().event = Some(callback);
652 }
653
654 fn on_app_menu_action(&self, callback: Box<dyn FnMut(&dyn Action)>) {
655 self.0.lock().menu_command = Some(callback);
656 }
657
658 fn on_will_open_app_menu(&self, callback: Box<dyn FnMut()>) {
659 self.0.lock().will_open_menu = Some(callback);
660 }
661
662 fn on_validate_app_menu_command(&self, callback: Box<dyn FnMut(&dyn Action) -> bool>) {
663 self.0.lock().validate_menu_command = Some(callback);
664 }
665
666 fn os_name(&self) -> &'static str {
667 "macOS"
668 }
669
670 fn double_click_interval(&self) -> Duration {
671 unsafe {
672 let double_click_interval: f64 = msg_send![class!(NSEvent), doubleClickInterval];
673 Duration::from_secs_f64(double_click_interval)
674 }
675 }
676
677 fn os_version(&self) -> Result<SemanticVersion> {
678 unsafe {
679 let process_info = NSProcessInfo::processInfo(nil);
680 let version = process_info.operatingSystemVersion();
681 Ok(SemanticVersion {
682 major: version.majorVersion as usize,
683 minor: version.minorVersion as usize,
684 patch: version.patchVersion as usize,
685 })
686 }
687 }
688
689 fn app_version(&self) -> Result<SemanticVersion> {
690 unsafe {
691 let bundle: id = NSBundle::mainBundle();
692 if bundle.is_null() {
693 Err(anyhow!("app is not running inside a bundle"))
694 } else {
695 let version: id = msg_send![bundle, objectForInfoDictionaryKey: ns_string("CFBundleShortVersionString")];
696 let len = msg_send![version, lengthOfBytesUsingEncoding: NSUTF8StringEncoding];
697 let bytes = version.UTF8String() as *const u8;
698 let version = str::from_utf8(slice::from_raw_parts(bytes, len)).unwrap();
699 version.parse()
700 }
701 }
702 }
703
704 fn app_path(&self) -> Result<PathBuf> {
705 unsafe {
706 let bundle: id = NSBundle::mainBundle();
707 if bundle.is_null() {
708 Err(anyhow!("app is not running inside a bundle"))
709 } else {
710 Ok(path_from_objc(msg_send![bundle, bundlePath]))
711 }
712 }
713 }
714
715 fn set_menus(&self, menus: Vec<Menu>, keymap: &Keymap) {
716 unsafe {
717 let app: id = msg_send![APP_CLASS, sharedApplication];
718 let mut state = self.0.lock();
719 let actions = &mut state.menu_actions;
720 app.setMainMenu_(self.create_menu_bar(menus, app.delegate(), actions, keymap));
721 }
722 }
723
724 fn local_timezone(&self) -> UtcOffset {
725 unsafe {
726 let local_timezone: id = msg_send![class!(NSTimeZone), localTimeZone];
727 let seconds_from_gmt: NSInteger = msg_send![local_timezone, secondsFromGMT];
728 UtcOffset::from_whole_seconds(seconds_from_gmt.try_into().unwrap()).unwrap()
729 }
730 }
731
732 fn path_for_auxiliary_executable(&self, name: &str) -> Result<PathBuf> {
733 unsafe {
734 let bundle: id = NSBundle::mainBundle();
735 if bundle.is_null() {
736 Err(anyhow!("app is not running inside a bundle"))
737 } else {
738 let name = ns_string(name);
739 let url: id = msg_send![bundle, URLForAuxiliaryExecutable: name];
740 if url.is_null() {
741 Err(anyhow!("resource not found"))
742 } else {
743 ns_url_to_path(url)
744 }
745 }
746 }
747 }
748
749 /// Match cursor style to one of the styles available
750 /// in macOS's [NSCursor](https://developer.apple.com/documentation/appkit/nscursor).
751 fn set_cursor_style(&self, style: CursorStyle) {
752 unsafe {
753 let new_cursor: id = match style {
754 CursorStyle::Arrow => msg_send![class!(NSCursor), arrowCursor],
755 CursorStyle::IBeam => msg_send![class!(NSCursor), IBeamCursor],
756 CursorStyle::Crosshair => msg_send![class!(NSCursor), crosshairCursor],
757 CursorStyle::ClosedHand => msg_send![class!(NSCursor), closedHandCursor],
758 CursorStyle::OpenHand => msg_send![class!(NSCursor), openHandCursor],
759 CursorStyle::PointingHand => msg_send![class!(NSCursor), pointingHandCursor],
760 CursorStyle::ResizeLeft => msg_send![class!(NSCursor), resizeLeftCursor],
761 CursorStyle::ResizeRight => msg_send![class!(NSCursor), resizeRightCursor],
762 CursorStyle::ResizeLeftRight => msg_send![class!(NSCursor), resizeLeftRightCursor],
763 CursorStyle::ResizeUp => msg_send![class!(NSCursor), resizeUpCursor],
764 CursorStyle::ResizeDown => msg_send![class!(NSCursor), resizeDownCursor],
765 CursorStyle::ResizeUpDown => msg_send![class!(NSCursor), resizeUpDownCursor],
766 CursorStyle::DisappearingItem => {
767 msg_send![class!(NSCursor), disappearingItemCursor]
768 }
769 CursorStyle::IBeamCursorForVerticalLayout => {
770 msg_send![class!(NSCursor), IBeamCursorForVerticalLayout]
771 }
772 CursorStyle::OperationNotAllowed => {
773 msg_send![class!(NSCursor), operationNotAllowedCursor]
774 }
775 CursorStyle::DragLink => msg_send![class!(NSCursor), dragLinkCursor],
776 CursorStyle::DragCopy => msg_send![class!(NSCursor), dragCopyCursor],
777 CursorStyle::ContextualMenu => msg_send![class!(NSCursor), contextualMenuCursor],
778 };
779
780 let old_cursor: id = msg_send![class!(NSCursor), currentCursor];
781 if new_cursor != old_cursor {
782 let _: () = msg_send![new_cursor, set];
783 }
784 }
785 }
786
787 fn should_auto_hide_scrollbars(&self) -> bool {
788 #[allow(non_upper_case_globals)]
789 const NSScrollerStyleOverlay: NSInteger = 1;
790
791 unsafe {
792 let style: NSInteger = msg_send![class!(NSScroller), preferredScrollerStyle];
793 style == NSScrollerStyleOverlay
794 }
795 }
796
797 fn write_to_clipboard(&self, item: ClipboardItem) {
798 let state = self.0.lock();
799 unsafe {
800 state.pasteboard.clearContents();
801
802 let text_bytes = NSData::dataWithBytes_length_(
803 nil,
804 item.text.as_ptr() as *const c_void,
805 item.text.len() as u64,
806 );
807 state
808 .pasteboard
809 .setData_forType(text_bytes, NSPasteboardTypeString);
810
811 if let Some(metadata) = item.metadata.as_ref() {
812 let hash_bytes = ClipboardItem::text_hash(&item.text).to_be_bytes();
813 let hash_bytes = NSData::dataWithBytes_length_(
814 nil,
815 hash_bytes.as_ptr() as *const c_void,
816 hash_bytes.len() as u64,
817 );
818 state
819 .pasteboard
820 .setData_forType(hash_bytes, state.text_hash_pasteboard_type);
821
822 let metadata_bytes = NSData::dataWithBytes_length_(
823 nil,
824 metadata.as_ptr() as *const c_void,
825 metadata.len() as u64,
826 );
827 state
828 .pasteboard
829 .setData_forType(metadata_bytes, state.metadata_pasteboard_type);
830 }
831 }
832 }
833
834 fn read_from_clipboard(&self) -> Option<ClipboardItem> {
835 let state = self.0.lock();
836 unsafe {
837 if let Some(text_bytes) =
838 self.read_from_pasteboard(state.pasteboard, NSPasteboardTypeString)
839 {
840 let text = String::from_utf8_lossy(text_bytes).to_string();
841 let hash_bytes = self
842 .read_from_pasteboard(state.pasteboard, state.text_hash_pasteboard_type)
843 .and_then(|bytes| bytes.try_into().ok())
844 .map(u64::from_be_bytes);
845 let metadata_bytes = self
846 .read_from_pasteboard(state.pasteboard, state.metadata_pasteboard_type)
847 .and_then(|bytes| String::from_utf8(bytes.to_vec()).ok());
848
849 if let Some((hash, metadata)) = hash_bytes.zip(metadata_bytes) {
850 if hash == ClipboardItem::text_hash(&text) {
851 Some(ClipboardItem {
852 text,
853 metadata: Some(metadata),
854 })
855 } else {
856 Some(ClipboardItem {
857 text,
858 metadata: None,
859 })
860 }
861 } else {
862 Some(ClipboardItem {
863 text,
864 metadata: None,
865 })
866 }
867 } else {
868 None
869 }
870 }
871 }
872
873 fn write_credentials(&self, url: &str, username: &str, password: &[u8]) -> Result<()> {
874 let url = CFString::from(url);
875 let username = CFString::from(username);
876 let password = CFData::from_buffer(password);
877
878 unsafe {
879 use security::*;
880
881 // First, check if there are already credentials for the given server. If so, then
882 // update the username and password.
883 let mut verb = "updating";
884 let mut query_attrs = CFMutableDictionary::with_capacity(2);
885 query_attrs.set(kSecClass as *const _, kSecClassInternetPassword as *const _);
886 query_attrs.set(kSecAttrServer as *const _, url.as_CFTypeRef());
887
888 let mut attrs = CFMutableDictionary::with_capacity(4);
889 attrs.set(kSecClass as *const _, kSecClassInternetPassword as *const _);
890 attrs.set(kSecAttrServer as *const _, url.as_CFTypeRef());
891 attrs.set(kSecAttrAccount as *const _, username.as_CFTypeRef());
892 attrs.set(kSecValueData as *const _, password.as_CFTypeRef());
893
894 let mut status = SecItemUpdate(
895 query_attrs.as_concrete_TypeRef(),
896 attrs.as_concrete_TypeRef(),
897 );
898
899 // If there were no existing credentials for the given server, then create them.
900 if status == errSecItemNotFound {
901 verb = "creating";
902 status = SecItemAdd(attrs.as_concrete_TypeRef(), ptr::null_mut());
903 }
904
905 if status != errSecSuccess {
906 return Err(anyhow!("{} password failed: {}", verb, status));
907 }
908 }
909 Ok(())
910 }
911
912 fn read_credentials(&self, url: &str) -> Result<Option<(String, Vec<u8>)>> {
913 let url = CFString::from(url);
914 let cf_true = CFBoolean::true_value().as_CFTypeRef();
915
916 unsafe {
917 use security::*;
918
919 // Find any credentials for the given server URL.
920 let mut attrs = CFMutableDictionary::with_capacity(5);
921 attrs.set(kSecClass as *const _, kSecClassInternetPassword as *const _);
922 attrs.set(kSecAttrServer as *const _, url.as_CFTypeRef());
923 attrs.set(kSecReturnAttributes as *const _, cf_true);
924 attrs.set(kSecReturnData as *const _, cf_true);
925
926 let mut result = CFTypeRef::from(ptr::null());
927 let status = SecItemCopyMatching(attrs.as_concrete_TypeRef(), &mut result);
928 match status {
929 security::errSecSuccess => {}
930 security::errSecItemNotFound | security::errSecUserCanceled => return Ok(None),
931 _ => return Err(anyhow!("reading password failed: {}", status)),
932 }
933
934 let result = CFType::wrap_under_create_rule(result)
935 .downcast::<CFDictionary>()
936 .ok_or_else(|| anyhow!("keychain item was not a dictionary"))?;
937 let username = result
938 .find(kSecAttrAccount as *const _)
939 .ok_or_else(|| anyhow!("account was missing from keychain item"))?;
940 let username = CFType::wrap_under_get_rule(*username)
941 .downcast::<CFString>()
942 .ok_or_else(|| anyhow!("account was not a string"))?;
943 let password = result
944 .find(kSecValueData as *const _)
945 .ok_or_else(|| anyhow!("password was missing from keychain item"))?;
946 let password = CFType::wrap_under_get_rule(*password)
947 .downcast::<CFData>()
948 .ok_or_else(|| anyhow!("password was not a string"))?;
949
950 Ok(Some((username.to_string(), password.bytes().to_vec())))
951 }
952 }
953
954 fn delete_credentials(&self, url: &str) -> Result<()> {
955 let url = CFString::from(url);
956
957 unsafe {
958 use security::*;
959
960 let mut query_attrs = CFMutableDictionary::with_capacity(2);
961 query_attrs.set(kSecClass as *const _, kSecClassInternetPassword as *const _);
962 query_attrs.set(kSecAttrServer as *const _, url.as_CFTypeRef());
963
964 let status = SecItemDelete(query_attrs.as_concrete_TypeRef());
965
966 if status != errSecSuccess {
967 return Err(anyhow!("delete password failed: {}", status));
968 }
969 }
970 Ok(())
971 }
972}
973
974unsafe fn path_from_objc(path: id) -> PathBuf {
975 let len = msg_send![path, lengthOfBytesUsingEncoding: NSUTF8StringEncoding];
976 let bytes = path.UTF8String() as *const u8;
977 let path = str::from_utf8(slice::from_raw_parts(bytes, len)).unwrap();
978 PathBuf::from(path)
979}
980
981unsafe fn get_mac_platform(object: &mut Object) -> &MacPlatform {
982 let platform_ptr: *mut c_void = *object.get_ivar(MAC_PLATFORM_IVAR);
983 assert!(!platform_ptr.is_null());
984 &*(platform_ptr as *const MacPlatform)
985}
986
987extern "C" fn send_event(this: &mut Object, _sel: Sel, native_event: id) {
988 unsafe {
989 if let Some(event) = InputEvent::from_native(native_event, None) {
990 let platform = get_mac_platform(this);
991 if let Some(callback) = platform.0.lock().event.as_mut() {
992 if !callback(event) {
993 return;
994 }
995 }
996 }
997 msg_send![super(this, class!(NSApplication)), sendEvent: native_event]
998 }
999}
1000
1001extern "C" fn did_finish_launching(this: &mut Object, _: Sel, _: id) {
1002 unsafe {
1003 let app: id = msg_send![APP_CLASS, sharedApplication];
1004 app.setActivationPolicy_(NSApplicationActivationPolicyRegular);
1005
1006 let platform = get_mac_platform(this);
1007 let callback = platform.0.lock().finish_launching.take();
1008 if let Some(callback) = callback {
1009 callback();
1010 }
1011 }
1012}
1013
1014extern "C" fn should_handle_reopen(this: &mut Object, _: Sel, _: id, has_open_windows: bool) {
1015 if !has_open_windows {
1016 let platform = unsafe { get_mac_platform(this) };
1017 if let Some(callback) = platform.0.lock().reopen.as_mut() {
1018 callback();
1019 }
1020 }
1021}
1022
1023extern "C" fn did_become_active(this: &mut Object, _: Sel, _: id) {
1024 let platform = unsafe { get_mac_platform(this) };
1025 if let Some(callback) = platform.0.lock().become_active.as_mut() {
1026 callback();
1027 }
1028}
1029
1030extern "C" fn did_resign_active(this: &mut Object, _: Sel, _: id) {
1031 let platform = unsafe { get_mac_platform(this) };
1032 if let Some(callback) = platform.0.lock().resign_active.as_mut() {
1033 callback();
1034 }
1035}
1036
1037extern "C" fn will_terminate(this: &mut Object, _: Sel, _: id) {
1038 let platform = unsafe { get_mac_platform(this) };
1039 if let Some(callback) = platform.0.lock().quit.as_mut() {
1040 callback();
1041 }
1042}
1043
1044extern "C" fn open_urls(this: &mut Object, _: Sel, _: id, urls: id) {
1045 let urls = unsafe {
1046 (0..urls.count())
1047 .filter_map(|i| {
1048 let url = urls.objectAtIndex(i);
1049 match CStr::from_ptr(url.absoluteString().UTF8String() as *mut c_char).to_str() {
1050 Ok(string) => Some(string.to_string()),
1051 Err(err) => {
1052 log::error!("error converting path to string: {}", err);
1053 None
1054 }
1055 }
1056 })
1057 .collect::<Vec<_>>()
1058 };
1059 let platform = unsafe { get_mac_platform(this) };
1060 if let Some(callback) = platform.0.lock().open_urls.as_mut() {
1061 callback(urls);
1062 }
1063}
1064
1065extern "C" fn handle_menu_item(this: &mut Object, _: Sel, item: id) {
1066 unsafe {
1067 let platform = get_mac_platform(this);
1068 let mut platform = platform.0.lock();
1069 if let Some(mut callback) = platform.menu_command.take() {
1070 let tag: NSInteger = msg_send![item, tag];
1071 let index = tag as usize;
1072 if let Some(action) = platform.menu_actions.get(index) {
1073 callback(action.as_ref());
1074 }
1075 platform.menu_command = Some(callback);
1076 }
1077 }
1078}
1079
1080extern "C" fn validate_menu_item(this: &mut Object, _: Sel, item: id) -> bool {
1081 unsafe {
1082 let mut result = false;
1083 let platform = get_mac_platform(this);
1084 let mut platform = platform.0.lock();
1085 if let Some(mut callback) = platform.validate_menu_command.take() {
1086 let tag: NSInteger = msg_send![item, tag];
1087 let index = tag as usize;
1088 if let Some(action) = platform.menu_actions.get(index) {
1089 result = callback(action.as_ref());
1090 }
1091 platform.validate_menu_command = Some(callback);
1092 }
1093 result
1094 }
1095}
1096
1097extern "C" fn menu_will_open(this: &mut Object, _: Sel, _: id) {
1098 unsafe {
1099 let platform = get_mac_platform(this);
1100 let mut platform = platform.0.lock();
1101 if let Some(mut callback) = platform.will_open_menu.take() {
1102 callback();
1103 platform.will_open_menu = Some(callback);
1104 }
1105 }
1106}
1107
1108unsafe fn ns_string(string: &str) -> id {
1109 NSString::alloc(nil).init_str(string).autorelease()
1110}
1111
1112unsafe fn ns_url_to_path(url: id) -> Result<PathBuf> {
1113 let path: *mut c_char = msg_send![url, fileSystemRepresentation];
1114 if path.is_null() {
1115 Err(anyhow!(
1116 "url is not a file path: {}",
1117 CStr::from_ptr(url.absoluteString().UTF8String()).to_string_lossy()
1118 ))
1119 } else {
1120 Ok(PathBuf::from(OsStr::from_bytes(
1121 CStr::from_ptr(path).to_bytes(),
1122 )))
1123 }
1124}
1125
1126mod security {
1127 #![allow(non_upper_case_globals)]
1128 use super::*;
1129
1130 #[link(name = "Security", kind = "framework")]
1131 extern "C" {
1132 pub static kSecClass: CFStringRef;
1133 pub static kSecClassInternetPassword: CFStringRef;
1134 pub static kSecAttrServer: CFStringRef;
1135 pub static kSecAttrAccount: CFStringRef;
1136 pub static kSecValueData: CFStringRef;
1137 pub static kSecReturnAttributes: CFStringRef;
1138 pub static kSecReturnData: CFStringRef;
1139
1140 pub fn SecItemAdd(attributes: CFDictionaryRef, result: *mut CFTypeRef) -> OSStatus;
1141 pub fn SecItemUpdate(query: CFDictionaryRef, attributes: CFDictionaryRef) -> OSStatus;
1142 pub fn SecItemDelete(query: CFDictionaryRef) -> OSStatus;
1143 pub fn SecItemCopyMatching(query: CFDictionaryRef, result: *mut CFTypeRef) -> OSStatus;
1144 }
1145
1146 pub const errSecSuccess: OSStatus = 0;
1147 pub const errSecUserCanceled: OSStatus = -128;
1148 pub const errSecItemNotFound: OSStatus = -25300;
1149}
1150
1151#[cfg(test)]
1152mod tests {
1153 use crate::ClipboardItem;
1154
1155 use super::*;
1156
1157 #[test]
1158 fn test_clipboard() {
1159 let platform = build_platform();
1160 assert_eq!(platform.read_from_clipboard(), None);
1161
1162 let item = ClipboardItem::new("1".to_string());
1163 platform.write_to_clipboard(item.clone());
1164 assert_eq!(platform.read_from_clipboard(), Some(item));
1165
1166 let item = ClipboardItem::new("2".to_string()).with_metadata(vec![3, 4]);
1167 platform.write_to_clipboard(item.clone());
1168 assert_eq!(platform.read_from_clipboard(), Some(item));
1169
1170 let text_from_other_app = "text from other app";
1171 unsafe {
1172 let bytes = NSData::dataWithBytes_length_(
1173 nil,
1174 text_from_other_app.as_ptr() as *const c_void,
1175 text_from_other_app.len() as u64,
1176 );
1177 platform
1178 .0
1179 .lock()
1180 .pasteboard
1181 .setData_forType(bytes, NSPasteboardTypeString);
1182 }
1183 assert_eq!(
1184 platform.read_from_clipboard(),
1185 Some(ClipboardItem::new(text_from_other_app.to_string()))
1186 );
1187 }
1188
1189 fn build_platform() -> MacPlatform {
1190 let platform = MacPlatform::new();
1191 platform.0.lock().pasteboard = unsafe { NSPasteboard::pasteboardWithUniqueName(nil) };
1192 platform
1193 }
1194}