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