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