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