1use super::{BoolExt as _, Dispatcher, FontSystem, Window};
2use crate::{
3 executor,
4 keymap::Keystroke,
5 platform::{self, CursorStyle},
6 Action, ClipboardItem, Event, Menu, MenuItem,
7};
8use anyhow::{anyhow, Result};
9use block::ConcreteBlock;
10use cocoa::{
11 appkit::{
12 NSApplication, NSApplicationActivationPolicy::NSApplicationActivationPolicyRegular,
13 NSEventModifierFlags, NSMenu, NSMenuItem, NSModalResponse, NSOpenPanel, NSPasteboard,
14 NSPasteboardTypeString, NSSavePanel, NSWindow,
15 },
16 base::{id, nil, selector, YES},
17 foundation::{
18 NSArray, NSAutoreleasePool, NSBundle, NSData, NSInteger, NSString, 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 objc::{
30 class,
31 declare::ClassDecl,
32 msg_send,
33 runtime::{Class, Object, Sel},
34 sel, sel_impl,
35};
36use postage::oneshot;
37use ptr::null_mut;
38use std::{
39 cell::{Cell, RefCell},
40 convert::TryInto,
41 ffi::{c_void, CStr, OsStr},
42 os::{raw::c_char, unix::ffi::OsStrExt},
43 path::{Path, PathBuf},
44 ptr,
45 rc::Rc,
46 slice, str,
47 sync::Arc,
48};
49use time::UtcOffset;
50
51#[allow(non_upper_case_globals)]
52const NSUTF8StringEncoding: NSUInteger = 4;
53
54const MAC_PLATFORM_IVAR: &'static str = "platform";
55static mut APP_CLASS: *const Class = ptr::null();
56static mut APP_DELEGATE_CLASS: *const Class = ptr::null();
57
58#[ctor]
59unsafe fn build_classes() {
60 APP_CLASS = {
61 let mut decl = ClassDecl::new("GPUIApplication", class!(NSApplication)).unwrap();
62 decl.add_ivar::<*mut c_void>(MAC_PLATFORM_IVAR);
63 decl.add_method(
64 sel!(sendEvent:),
65 send_event as extern "C" fn(&mut Object, Sel, id),
66 );
67 decl.register()
68 };
69
70 APP_DELEGATE_CLASS = {
71 let mut decl = ClassDecl::new("GPUIApplicationDelegate", class!(NSResponder)).unwrap();
72 decl.add_ivar::<*mut c_void>(MAC_PLATFORM_IVAR);
73 decl.add_method(
74 sel!(applicationDidFinishLaunching:),
75 did_finish_launching as extern "C" fn(&mut Object, Sel, id),
76 );
77 decl.add_method(
78 sel!(applicationDidBecomeActive:),
79 did_become_active as extern "C" fn(&mut Object, Sel, id),
80 );
81 decl.add_method(
82 sel!(applicationDidResignActive:),
83 did_resign_active as extern "C" fn(&mut Object, Sel, id),
84 );
85 decl.add_method(
86 sel!(applicationWillTerminate:),
87 will_terminate as extern "C" fn(&mut Object, Sel, id),
88 );
89 decl.add_method(
90 sel!(handleGPUIMenuItem:),
91 handle_menu_item as extern "C" fn(&mut Object, Sel, id),
92 );
93 decl.add_method(
94 sel!(application:openURLs:),
95 open_urls as extern "C" fn(&mut Object, Sel, id, id),
96 );
97 decl.register()
98 }
99}
100
101#[derive(Default)]
102pub struct MacForegroundPlatform(RefCell<MacForegroundPlatformState>);
103
104#[derive(Default)]
105pub struct MacForegroundPlatformState {
106 become_active: Option<Box<dyn FnMut()>>,
107 resign_active: Option<Box<dyn FnMut()>>,
108 quit: Option<Box<dyn FnMut()>>,
109 event: Option<Box<dyn FnMut(crate::Event) -> bool>>,
110 menu_command: Option<Box<dyn FnMut(&dyn Action)>>,
111 open_urls: Option<Box<dyn FnMut(Vec<String>)>>,
112 finish_launching: Option<Box<dyn FnOnce() -> ()>>,
113 menu_actions: Vec<Box<dyn Action>>,
114}
115
116impl MacForegroundPlatform {
117 unsafe fn create_menu_bar(&self, menus: Vec<Menu>) -> id {
118 let menu_bar = NSMenu::new(nil).autorelease();
119 let mut state = self.0.borrow_mut();
120
121 state.menu_actions.clear();
122
123 for menu_config in menus {
124 let menu_bar_item = NSMenuItem::new(nil).autorelease();
125 let menu = NSMenu::new(nil).autorelease();
126 let menu_name = menu_config.name;
127
128 menu.setTitle_(ns_string(menu_name));
129
130 for item_config in menu_config.items {
131 let item;
132
133 match item_config {
134 MenuItem::Separator => {
135 item = NSMenuItem::separatorItem(nil);
136 }
137 MenuItem::Action {
138 name,
139 keystroke,
140 action,
141 } => {
142 if let Some(keystroke) = keystroke {
143 let keystroke = Keystroke::parse(keystroke).unwrap_or_else(|err| {
144 panic!(
145 "Invalid keystroke for menu item {}:{} - {:?}",
146 menu_name, name, err
147 )
148 });
149
150 let mut mask = NSEventModifierFlags::empty();
151 for (modifier, flag) in &[
152 (keystroke.cmd, NSEventModifierFlags::NSCommandKeyMask),
153 (keystroke.ctrl, NSEventModifierFlags::NSControlKeyMask),
154 (keystroke.alt, NSEventModifierFlags::NSAlternateKeyMask),
155 ] {
156 if *modifier {
157 mask |= *flag;
158 }
159 }
160
161 item = NSMenuItem::alloc(nil)
162 .initWithTitle_action_keyEquivalent_(
163 ns_string(name),
164 selector("handleGPUIMenuItem:"),
165 ns_string(&keystroke.key),
166 )
167 .autorelease();
168 item.setKeyEquivalentModifierMask_(mask);
169 } else {
170 item = NSMenuItem::alloc(nil)
171 .initWithTitle_action_keyEquivalent_(
172 ns_string(name),
173 selector("handleGPUIMenuItem:"),
174 ns_string(""),
175 )
176 .autorelease();
177 }
178
179 let tag = state.menu_actions.len() as NSInteger;
180 let _: () = msg_send![item, setTag: tag];
181 state.menu_actions.push(action);
182 }
183 }
184
185 menu.addItem_(item);
186 }
187
188 menu_bar_item.setSubmenu_(menu);
189 menu_bar.addItem_(menu_bar_item);
190 }
191
192 menu_bar
193 }
194}
195
196impl platform::ForegroundPlatform for MacForegroundPlatform {
197 fn on_become_active(&self, callback: Box<dyn FnMut()>) {
198 self.0.borrow_mut().become_active = Some(callback);
199 }
200
201 fn on_resign_active(&self, callback: Box<dyn FnMut()>) {
202 self.0.borrow_mut().resign_active = Some(callback);
203 }
204
205 fn on_quit(&self, callback: Box<dyn FnMut()>) {
206 self.0.borrow_mut().quit = Some(callback);
207 }
208
209 fn on_event(&self, callback: Box<dyn FnMut(crate::Event) -> bool>) {
210 self.0.borrow_mut().event = Some(callback);
211 }
212
213 fn on_open_urls(&self, callback: Box<dyn FnMut(Vec<String>)>) {
214 self.0.borrow_mut().open_urls = Some(callback);
215 }
216
217 fn run(&self, on_finish_launching: Box<dyn FnOnce() -> ()>) {
218 self.0.borrow_mut().finish_launching = Some(on_finish_launching);
219
220 unsafe {
221 let app: id = msg_send![APP_CLASS, sharedApplication];
222 let app_delegate: id = msg_send![APP_DELEGATE_CLASS, new];
223 app.setDelegate_(app_delegate);
224
225 let self_ptr = self as *const Self as *const c_void;
226 (*app).set_ivar(MAC_PLATFORM_IVAR, self_ptr);
227 (*app_delegate).set_ivar(MAC_PLATFORM_IVAR, self_ptr);
228
229 let pool = NSAutoreleasePool::new(nil);
230 app.run();
231 pool.drain();
232
233 (*app).set_ivar(MAC_PLATFORM_IVAR, null_mut::<c_void>());
234 (*app.delegate()).set_ivar(MAC_PLATFORM_IVAR, null_mut::<c_void>());
235 }
236 }
237
238 fn on_menu_command(&self, callback: Box<dyn FnMut(&dyn Action)>) {
239 self.0.borrow_mut().menu_command = Some(callback);
240 }
241
242 fn set_menus(&self, menus: Vec<Menu>) {
243 unsafe {
244 let app: id = msg_send![APP_CLASS, sharedApplication];
245 app.setMainMenu_(self.create_menu_bar(menus));
246 }
247 }
248
249 fn prompt_for_paths(
250 &self,
251 options: platform::PathPromptOptions,
252 ) -> oneshot::Receiver<Option<Vec<PathBuf>>> {
253 unsafe {
254 let panel = NSOpenPanel::openPanel(nil);
255 panel.setCanChooseDirectories_(options.directories.to_objc());
256 panel.setCanChooseFiles_(options.files.to_objc());
257 panel.setAllowsMultipleSelection_(options.multiple.to_objc());
258 panel.setResolvesAliases_(false.to_objc());
259 let (done_tx, done_rx) = oneshot::channel();
260 let done_tx = Cell::new(Some(done_tx));
261 let block = ConcreteBlock::new(move |response: NSModalResponse| {
262 let result = if response == NSModalResponse::NSModalResponseOk {
263 let mut result = Vec::new();
264 let urls = panel.URLs();
265 for i in 0..urls.count() {
266 let url = urls.objectAtIndex(i);
267 if url.isFileURL() == YES {
268 if let Ok(path) = ns_url_to_path(url) {
269 result.push(path)
270 }
271 }
272 }
273 Some(result)
274 } else {
275 None
276 };
277
278 if let Some(mut done_tx) = done_tx.take() {
279 let _ = postage::sink::Sink::try_send(&mut done_tx, result);
280 }
281 });
282 let block = block.copy();
283 let _: () = msg_send![panel, beginWithCompletionHandler: block];
284 done_rx
285 }
286 }
287
288 fn prompt_for_new_path(&self, directory: &Path) -> oneshot::Receiver<Option<PathBuf>> {
289 unsafe {
290 let panel = NSSavePanel::savePanel(nil);
291 let path = ns_string(directory.to_string_lossy().as_ref());
292 let url = NSURL::fileURLWithPath_isDirectory_(nil, path, true.to_objc());
293 panel.setDirectoryURL(url);
294
295 let (done_tx, done_rx) = oneshot::channel();
296 let done_tx = Cell::new(Some(done_tx));
297 let block = ConcreteBlock::new(move |response: NSModalResponse| {
298 let mut result = None;
299 if response == NSModalResponse::NSModalResponseOk {
300 let url = panel.URL();
301 if url.isFileURL() == YES {
302 result = ns_url_to_path(panel.URL()).ok()
303 }
304 }
305
306 if let Some(mut done_tx) = done_tx.take() {
307 let _ = postage::sink::Sink::try_send(&mut done_tx, result);
308 }
309 });
310 let block = block.copy();
311 let _: () = msg_send![panel, beginWithCompletionHandler: block];
312 done_rx
313 }
314 }
315}
316
317pub struct MacPlatform {
318 dispatcher: Arc<Dispatcher>,
319 fonts: Arc<FontSystem>,
320 pasteboard: id,
321 text_hash_pasteboard_type: id,
322 metadata_pasteboard_type: id,
323}
324
325impl MacPlatform {
326 pub fn new() -> Self {
327 Self {
328 dispatcher: Arc::new(Dispatcher),
329 fonts: Arc::new(FontSystem::new()),
330 pasteboard: unsafe { NSPasteboard::generalPasteboard(nil) },
331 text_hash_pasteboard_type: unsafe { ns_string("zed-text-hash") },
332 metadata_pasteboard_type: unsafe { ns_string("zed-metadata") },
333 }
334 }
335
336 unsafe fn read_from_pasteboard(&self, kind: id) -> Option<&[u8]> {
337 let data = self.pasteboard.dataForType(kind);
338 if data == nil {
339 None
340 } else {
341 Some(slice::from_raw_parts(
342 data.bytes() as *mut u8,
343 data.length() as usize,
344 ))
345 }
346 }
347}
348
349unsafe impl Send for MacPlatform {}
350unsafe impl Sync for MacPlatform {}
351
352impl platform::Platform for MacPlatform {
353 fn dispatcher(&self) -> Arc<dyn platform::Dispatcher> {
354 self.dispatcher.clone()
355 }
356
357 fn activate(&self, ignoring_other_apps: bool) {
358 unsafe {
359 let app = NSApplication::sharedApplication(nil);
360 app.activateIgnoringOtherApps_(ignoring_other_apps.to_objc());
361 }
362 }
363
364 fn open_window(
365 &self,
366 id: usize,
367 options: platform::WindowOptions,
368 executor: Rc<executor::Foreground>,
369 ) -> Box<dyn platform::Window> {
370 Box::new(Window::open(id, options, executor, self.fonts()))
371 }
372
373 fn key_window_id(&self) -> Option<usize> {
374 Window::key_window_id()
375 }
376
377 fn fonts(&self) -> Arc<dyn platform::FontSystem> {
378 self.fonts.clone()
379 }
380
381 fn quit(&self) {
382 // Quitting the app causes us to close windows, which invokes `Window::on_close` callbacks
383 // synchronously before this method terminates. If we call `Platform::quit` while holding a
384 // borrow of the app state (which most of the time we will do), we will end up
385 // double-borrowing the app state in the `on_close` callbacks for our open windows. To solve
386 // this, we make quitting the application asynchronous so that we aren't holding borrows to
387 // the app state on the stack when we actually terminate the app.
388
389 use super::dispatcher::{dispatch_async_f, dispatch_get_main_queue};
390
391 unsafe {
392 dispatch_async_f(dispatch_get_main_queue(), ptr::null_mut(), Some(quit));
393 }
394
395 unsafe extern "C" fn quit(_: *mut c_void) {
396 let app = NSApplication::sharedApplication(nil);
397 let _: () = msg_send![app, terminate: nil];
398 }
399 }
400
401 fn write_to_clipboard(&self, item: ClipboardItem) {
402 unsafe {
403 self.pasteboard.clearContents();
404
405 let text_bytes = NSData::dataWithBytes_length_(
406 nil,
407 item.text.as_ptr() as *const c_void,
408 item.text.len() as u64,
409 );
410 self.pasteboard
411 .setData_forType(text_bytes, NSPasteboardTypeString);
412
413 if let Some(metadata) = item.metadata.as_ref() {
414 let hash_bytes = ClipboardItem::text_hash(&item.text).to_be_bytes();
415 let hash_bytes = NSData::dataWithBytes_length_(
416 nil,
417 hash_bytes.as_ptr() as *const c_void,
418 hash_bytes.len() as u64,
419 );
420 self.pasteboard
421 .setData_forType(hash_bytes, self.text_hash_pasteboard_type);
422
423 let metadata_bytes = NSData::dataWithBytes_length_(
424 nil,
425 metadata.as_ptr() as *const c_void,
426 metadata.len() as u64,
427 );
428 self.pasteboard
429 .setData_forType(metadata_bytes, self.metadata_pasteboard_type);
430 }
431 }
432 }
433
434 fn read_from_clipboard(&self) -> Option<ClipboardItem> {
435 unsafe {
436 if let Some(text_bytes) = self.read_from_pasteboard(NSPasteboardTypeString) {
437 let text = String::from_utf8_lossy(&text_bytes).to_string();
438 let hash_bytes = self
439 .read_from_pasteboard(self.text_hash_pasteboard_type)
440 .and_then(|bytes| bytes.try_into().ok())
441 .map(u64::from_be_bytes);
442 let metadata_bytes = self
443 .read_from_pasteboard(self.metadata_pasteboard_type)
444 .and_then(|bytes| String::from_utf8(bytes.to_vec()).ok());
445
446 if let Some((hash, metadata)) = hash_bytes.zip(metadata_bytes) {
447 if hash == ClipboardItem::text_hash(&text) {
448 Some(ClipboardItem {
449 text,
450 metadata: Some(metadata),
451 })
452 } else {
453 Some(ClipboardItem {
454 text,
455 metadata: None,
456 })
457 }
458 } else {
459 Some(ClipboardItem {
460 text,
461 metadata: None,
462 })
463 }
464 } else {
465 None
466 }
467 }
468 }
469
470 fn open_url(&self, url: &str) {
471 unsafe {
472 let url = NSURL::alloc(nil)
473 .initWithString_(ns_string(url))
474 .autorelease();
475 let workspace: id = msg_send![class!(NSWorkspace), sharedWorkspace];
476 msg_send![workspace, openURL: url]
477 }
478 }
479
480 fn write_credentials(&self, url: &str, username: &str, password: &[u8]) -> Result<()> {
481 let url = CFString::from(url);
482 let username = CFString::from(username);
483 let password = CFData::from_buffer(password);
484
485 unsafe {
486 use security::*;
487
488 // First, check if there are already credentials for the given server. If so, then
489 // update the username and password.
490 let mut verb = "updating";
491 let mut query_attrs = CFMutableDictionary::with_capacity(2);
492 query_attrs.set(kSecClass as *const _, kSecClassInternetPassword as *const _);
493 query_attrs.set(kSecAttrServer as *const _, url.as_CFTypeRef());
494
495 let mut attrs = CFMutableDictionary::with_capacity(4);
496 attrs.set(kSecClass as *const _, kSecClassInternetPassword as *const _);
497 attrs.set(kSecAttrServer as *const _, url.as_CFTypeRef());
498 attrs.set(kSecAttrAccount as *const _, username.as_CFTypeRef());
499 attrs.set(kSecValueData as *const _, password.as_CFTypeRef());
500
501 let mut status = SecItemUpdate(
502 query_attrs.as_concrete_TypeRef(),
503 attrs.as_concrete_TypeRef(),
504 );
505
506 // If there were no existing credentials for the given server, then create them.
507 if status == errSecItemNotFound {
508 verb = "creating";
509 status = SecItemAdd(attrs.as_concrete_TypeRef(), ptr::null_mut());
510 }
511
512 if status != errSecSuccess {
513 return Err(anyhow!("{} password failed: {}", verb, status));
514 }
515 }
516 Ok(())
517 }
518
519 fn read_credentials(&self, url: &str) -> Result<Option<(String, Vec<u8>)>> {
520 let url = CFString::from(url);
521 let cf_true = CFBoolean::true_value().as_CFTypeRef();
522
523 unsafe {
524 use security::*;
525
526 // Find any credentials for the given server URL.
527 let mut attrs = CFMutableDictionary::with_capacity(5);
528 attrs.set(kSecClass as *const _, kSecClassInternetPassword as *const _);
529 attrs.set(kSecAttrServer as *const _, url.as_CFTypeRef());
530 attrs.set(kSecReturnAttributes as *const _, cf_true);
531 attrs.set(kSecReturnData as *const _, cf_true);
532
533 let mut result = CFTypeRef::from(ptr::null_mut());
534 let status = SecItemCopyMatching(attrs.as_concrete_TypeRef(), &mut result);
535 match status {
536 security::errSecSuccess => {}
537 security::errSecItemNotFound | security::errSecUserCanceled => return Ok(None),
538 _ => return Err(anyhow!("reading password failed: {}", status)),
539 }
540
541 let result = CFType::wrap_under_create_rule(result)
542 .downcast::<CFDictionary>()
543 .ok_or_else(|| anyhow!("keychain item was not a dictionary"))?;
544 let username = result
545 .find(kSecAttrAccount as *const _)
546 .ok_or_else(|| anyhow!("account was missing from keychain item"))?;
547 let username = CFType::wrap_under_get_rule(*username)
548 .downcast::<CFString>()
549 .ok_or_else(|| anyhow!("account was not a string"))?;
550 let password = result
551 .find(kSecValueData as *const _)
552 .ok_or_else(|| anyhow!("password was missing from keychain item"))?;
553 let password = CFType::wrap_under_get_rule(*password)
554 .downcast::<CFData>()
555 .ok_or_else(|| anyhow!("password was not a string"))?;
556
557 Ok(Some((username.to_string(), password.bytes().to_vec())))
558 }
559 }
560
561 fn delete_credentials(&self, url: &str) -> Result<()> {
562 let url = CFString::from(url);
563
564 unsafe {
565 use security::*;
566
567 let mut query_attrs = CFMutableDictionary::with_capacity(2);
568 query_attrs.set(kSecClass as *const _, kSecClassInternetPassword as *const _);
569 query_attrs.set(kSecAttrServer as *const _, url.as_CFTypeRef());
570
571 let status = SecItemDelete(query_attrs.as_concrete_TypeRef());
572
573 if status != errSecSuccess {
574 return Err(anyhow!("delete password failed: {}", status));
575 }
576 }
577 Ok(())
578 }
579
580 fn set_cursor_style(&self, style: CursorStyle) {
581 unsafe {
582 let cursor: id = match style {
583 CursorStyle::Arrow => msg_send![class!(NSCursor), arrowCursor],
584 CursorStyle::ResizeLeftRight => msg_send![class!(NSCursor), resizeLeftRightCursor],
585 CursorStyle::PointingHand => msg_send![class!(NSCursor), pointingHandCursor],
586 };
587 let _: () = msg_send![cursor, set];
588 }
589 }
590
591 fn local_timezone(&self) -> UtcOffset {
592 unsafe {
593 let local_timezone: id = msg_send![class!(NSTimeZone), localTimeZone];
594 let seconds_from_gmt: NSInteger = msg_send![local_timezone, secondsFromGMT];
595 UtcOffset::from_whole_seconds(seconds_from_gmt.try_into().unwrap()).unwrap()
596 }
597 }
598
599 fn path_for_auxiliary_executable(&self, name: &str) -> Result<PathBuf> {
600 unsafe {
601 let bundle: id = NSBundle::mainBundle();
602 if bundle.is_null() {
603 Err(anyhow!("app is not running inside a bundle"))
604 } else {
605 let name = ns_string(name);
606 let url: id = msg_send![bundle, URLForAuxiliaryExecutable: name];
607 if url.is_null() {
608 Err(anyhow!("resource not found"))
609 } else {
610 ns_url_to_path(url)
611 }
612 }
613 }
614 }
615
616 fn app_path(&self) -> Result<PathBuf> {
617 unsafe {
618 let bundle: id = NSBundle::mainBundle();
619 if bundle.is_null() {
620 Err(anyhow!("app is not running inside a bundle"))
621 } else {
622 Ok(path_from_objc(msg_send![bundle, bundlePath]))
623 }
624 }
625 }
626
627 fn app_version(&self) -> Result<platform::AppVersion> {
628 unsafe {
629 let bundle: id = NSBundle::mainBundle();
630 if bundle.is_null() {
631 Err(anyhow!("app is not running inside a bundle"))
632 } else {
633 let version: id = msg_send![bundle, objectForInfoDictionaryKey: ns_string("CFBundleShortVersionString")];
634 let len = msg_send![version, lengthOfBytesUsingEncoding: NSUTF8StringEncoding];
635 let bytes = version.UTF8String() as *const u8;
636 let version = str::from_utf8(slice::from_raw_parts(bytes, len)).unwrap();
637 version.parse()
638 }
639 }
640 }
641}
642
643unsafe fn path_from_objc(path: id) -> PathBuf {
644 let len = msg_send![path, lengthOfBytesUsingEncoding: NSUTF8StringEncoding];
645 let bytes = path.UTF8String() as *const u8;
646 let path = str::from_utf8(slice::from_raw_parts(bytes, len)).unwrap();
647 PathBuf::from(path)
648}
649
650unsafe fn get_foreground_platform(object: &mut Object) -> &MacForegroundPlatform {
651 let platform_ptr: *mut c_void = *object.get_ivar(MAC_PLATFORM_IVAR);
652 assert!(!platform_ptr.is_null());
653 &*(platform_ptr as *const MacForegroundPlatform)
654}
655
656extern "C" fn send_event(this: &mut Object, _sel: Sel, native_event: id) {
657 unsafe {
658 if let Some(event) = Event::from_native(native_event, None) {
659 let platform = get_foreground_platform(this);
660 if let Some(callback) = platform.0.borrow_mut().event.as_mut() {
661 if callback(event) {
662 return;
663 }
664 }
665 }
666
667 msg_send![super(this, class!(NSApplication)), sendEvent: native_event]
668 }
669}
670
671extern "C" fn did_finish_launching(this: &mut Object, _: Sel, _: id) {
672 unsafe {
673 let app: id = msg_send![APP_CLASS, sharedApplication];
674 app.setActivationPolicy_(NSApplicationActivationPolicyRegular);
675
676 let platform = get_foreground_platform(this);
677 let callback = platform.0.borrow_mut().finish_launching.take();
678 if let Some(callback) = callback {
679 callback();
680 }
681 }
682}
683
684extern "C" fn did_become_active(this: &mut Object, _: Sel, _: id) {
685 let platform = unsafe { get_foreground_platform(this) };
686 if let Some(callback) = platform.0.borrow_mut().become_active.as_mut() {
687 callback();
688 }
689}
690
691extern "C" fn did_resign_active(this: &mut Object, _: Sel, _: id) {
692 let platform = unsafe { get_foreground_platform(this) };
693 if let Some(callback) = platform.0.borrow_mut().resign_active.as_mut() {
694 callback();
695 }
696}
697
698extern "C" fn will_terminate(this: &mut Object, _: Sel, _: id) {
699 let platform = unsafe { get_foreground_platform(this) };
700 if let Some(callback) = platform.0.borrow_mut().quit.as_mut() {
701 callback();
702 }
703}
704
705extern "C" fn open_urls(this: &mut Object, _: Sel, _: id, urls: id) {
706 let urls = unsafe {
707 (0..urls.count())
708 .into_iter()
709 .filter_map(|i| {
710 let path = urls.objectAtIndex(i);
711 match CStr::from_ptr(path.absoluteString().UTF8String() as *mut c_char).to_str() {
712 Ok(string) => Some(string.to_string()),
713 Err(err) => {
714 log::error!("error converting path to string: {}", err);
715 None
716 }
717 }
718 })
719 .collect::<Vec<_>>()
720 };
721 let platform = unsafe { get_foreground_platform(this) };
722 if let Some(callback) = platform.0.borrow_mut().open_urls.as_mut() {
723 callback(urls);
724 }
725}
726
727extern "C" fn handle_menu_item(this: &mut Object, _: Sel, item: id) {
728 unsafe {
729 let platform = get_foreground_platform(this);
730 let mut platform = platform.0.borrow_mut();
731 if let Some(mut callback) = platform.menu_command.take() {
732 let tag: NSInteger = msg_send![item, tag];
733 let index = tag as usize;
734 if let Some(action) = platform.menu_actions.get(index) {
735 callback(action.as_ref());
736 }
737 platform.menu_command = Some(callback);
738 }
739 }
740}
741
742unsafe fn ns_string(string: &str) -> id {
743 NSString::alloc(nil).init_str(string).autorelease()
744}
745
746unsafe fn ns_url_to_path(url: id) -> Result<PathBuf> {
747 let path: *mut c_char = msg_send![url, fileSystemRepresentation];
748 if path.is_null() {
749 Err(anyhow!(
750 "url is not a file path: {}",
751 CStr::from_ptr(url.absoluteString().UTF8String()).to_string_lossy()
752 ))
753 } else {
754 Ok(PathBuf::from(OsStr::from_bytes(
755 CStr::from_ptr(path).to_bytes(),
756 )))
757 }
758}
759
760mod security {
761 #![allow(non_upper_case_globals)]
762 use super::*;
763
764 #[link(name = "Security", kind = "framework")]
765 extern "C" {
766 pub static kSecClass: CFStringRef;
767 pub static kSecClassInternetPassword: CFStringRef;
768 pub static kSecAttrServer: CFStringRef;
769 pub static kSecAttrAccount: CFStringRef;
770 pub static kSecValueData: CFStringRef;
771 pub static kSecReturnAttributes: CFStringRef;
772 pub static kSecReturnData: CFStringRef;
773
774 pub fn SecItemAdd(attributes: CFDictionaryRef, result: *mut CFTypeRef) -> OSStatus;
775 pub fn SecItemUpdate(query: CFDictionaryRef, attributes: CFDictionaryRef) -> OSStatus;
776 pub fn SecItemDelete(query: CFDictionaryRef) -> OSStatus;
777 pub fn SecItemCopyMatching(query: CFDictionaryRef, result: *mut CFTypeRef) -> OSStatus;
778 }
779
780 pub const errSecSuccess: OSStatus = 0;
781 pub const errSecUserCanceled: OSStatus = -128;
782 pub const errSecItemNotFound: OSStatus = -25300;
783}
784
785#[cfg(test)]
786mod tests {
787 use crate::platform::Platform;
788
789 use super::*;
790
791 #[test]
792 fn test_clipboard() {
793 let platform = build_platform();
794 assert_eq!(platform.read_from_clipboard(), None);
795
796 let item = ClipboardItem::new("1".to_string());
797 platform.write_to_clipboard(item.clone());
798 assert_eq!(platform.read_from_clipboard(), Some(item));
799
800 let item = ClipboardItem::new("2".to_string()).with_metadata(vec![3, 4]);
801 platform.write_to_clipboard(item.clone());
802 assert_eq!(platform.read_from_clipboard(), Some(item));
803
804 let text_from_other_app = "text from other app";
805 unsafe {
806 let bytes = NSData::dataWithBytes_length_(
807 nil,
808 text_from_other_app.as_ptr() as *const c_void,
809 text_from_other_app.len() as u64,
810 );
811 platform
812 .pasteboard
813 .setData_forType(bytes, NSPasteboardTypeString);
814 }
815 assert_eq!(
816 platform.read_from_clipboard(),
817 Some(ClipboardItem::new(text_from_other_app.to_string()))
818 );
819 }
820
821 fn build_platform() -> MacPlatform {
822 let mut platform = MacPlatform::new();
823 platform.pasteboard = unsafe { NSPasteboard::pasteboardWithUniqueName(nil) };
824 platform
825 }
826}