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