platform.rs

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