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