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