platform.rs

   1use crate::{
   2    BoolExt, MacDispatcher, MacDisplay, MacKeyboardLayout, MacKeyboardMapper, MacWindow,
   3    events::key_to_native, ns_string, pasteboard::Pasteboard, renderer,
   4};
   5use anyhow::{Context as _, anyhow};
   6use block::ConcreteBlock;
   7use cocoa::{
   8    appkit::{
   9        NSApplication, NSApplicationActivationPolicy::NSApplicationActivationPolicyRegular,
  10        NSEventModifierFlags, NSMenu, NSMenuItem, NSModalResponse, NSOpenPanel, NSSavePanel,
  11        NSVisualEffectState, NSVisualEffectView, NSWindow,
  12    },
  13    base::{BOOL, NO, YES, id, nil, selector},
  14    foundation::{
  15        NSArray, NSAutoreleasePool, NSBundle, NSInteger, NSProcessInfo, NSString, NSUInteger, NSURL,
  16    },
  17};
  18use core_foundation::{
  19    base::{CFRelease, CFType, CFTypeRef, OSStatus, TCFType},
  20    boolean::CFBoolean,
  21    data::CFData,
  22    dictionary::{CFDictionary, CFDictionaryRef, CFMutableDictionary},
  23    runloop::CFRunLoopRun,
  24    string::{CFString, CFStringRef},
  25};
  26use ctor::ctor;
  27use dispatch2::DispatchQueue;
  28use futures::channel::oneshot;
  29use gpui::{
  30    Action, AnyWindowHandle, BackgroundExecutor, ClipboardItem, CursorStyle, ForegroundExecutor,
  31    KeyContext, Keymap, Menu, MenuItem, OsMenu, OwnedMenu, PathPromptOptions, Platform,
  32    PlatformDisplay, PlatformKeyboardLayout, PlatformKeyboardMapper, PlatformTextSystem,
  33    PlatformWindow, Result, SystemMenuType, Task, ThermalState, WindowAppearance, WindowParams,
  34};
  35use itertools::Itertools;
  36use objc::{
  37    class,
  38    declare::ClassDecl,
  39    msg_send,
  40    runtime::{Class, Object, Sel},
  41    sel, sel_impl,
  42};
  43use parking_lot::Mutex;
  44use ptr::null_mut;
  45use semver::Version;
  46use std::{
  47    cell::Cell,
  48    ffi::{CStr, OsStr, c_void},
  49    os::{raw::c_char, unix::ffi::OsStrExt},
  50    path::{Path, PathBuf},
  51    ptr,
  52    rc::Rc,
  53    slice, str,
  54    sync::{Arc, OnceLock},
  55};
  56use util::{
  57    ResultExt,
  58    command::{new_command, new_std_command},
  59};
  60
  61#[allow(non_upper_case_globals)]
  62const NSUTF8StringEncoding: NSUInteger = 4;
  63
  64const MAC_PLATFORM_IVAR: &str = "platform";
  65static mut APP_CLASS: *const Class = ptr::null();
  66static mut APP_DELEGATE_CLASS: *const Class = ptr::null();
  67
  68#[ctor]
  69unsafe fn build_classes() {
  70    unsafe {
  71        APP_CLASS = {
  72            let mut decl = ClassDecl::new("GPUIApplication", class!(NSApplication)).unwrap();
  73            decl.add_ivar::<*mut c_void>(MAC_PLATFORM_IVAR);
  74            decl.register()
  75        }
  76    };
  77    unsafe {
  78        APP_DELEGATE_CLASS = unsafe {
  79            let mut decl = ClassDecl::new("GPUIApplicationDelegate", class!(NSResponder)).unwrap();
  80            decl.add_ivar::<*mut c_void>(MAC_PLATFORM_IVAR);
  81            decl.add_method(
  82                sel!(applicationWillFinishLaunching:),
  83                will_finish_launching as extern "C" fn(&mut Object, Sel, id),
  84            );
  85            decl.add_method(
  86                sel!(applicationDidFinishLaunching:),
  87                did_finish_launching as extern "C" fn(&mut Object, Sel, id),
  88            );
  89            decl.add_method(
  90                sel!(applicationShouldHandleReopen:hasVisibleWindows:),
  91                should_handle_reopen as extern "C" fn(&mut Object, Sel, id, bool),
  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!(applicationDockMenu:),
 136                handle_dock_menu as extern "C" fn(&mut Object, Sel, id) -> id,
 137            );
 138            decl.add_method(
 139                sel!(application:openURLs:),
 140                open_urls as extern "C" fn(&mut Object, Sel, id, id),
 141            );
 142
 143            decl.add_method(
 144                sel!(onKeyboardLayoutChange:),
 145                on_keyboard_layout_change as extern "C" fn(&mut Object, Sel, id),
 146            );
 147
 148            decl.add_method(
 149                sel!(onThermalStateChange:),
 150                on_thermal_state_change as extern "C" fn(&mut Object, Sel, id),
 151            );
 152
 153            decl.register()
 154        }
 155    }
 156}
 157
 158pub struct MacPlatform(Mutex<MacPlatformState>);
 159
 160pub(crate) struct MacPlatformState {
 161    background_executor: BackgroundExecutor,
 162    foreground_executor: ForegroundExecutor,
 163    text_system: Arc<dyn PlatformTextSystem>,
 164    renderer_context: renderer::Context,
 165    headless: bool,
 166    general_pasteboard: Pasteboard,
 167    find_pasteboard: Pasteboard,
 168    reopen: Option<Box<dyn FnMut()>>,
 169    on_keyboard_layout_change: Option<Box<dyn FnMut()>>,
 170    on_thermal_state_change: Option<Box<dyn FnMut()>>,
 171    quit: Option<Box<dyn FnMut()>>,
 172    menu_command: Option<Box<dyn FnMut(&dyn Action)>>,
 173    validate_menu_command: Option<Box<dyn FnMut(&dyn Action) -> bool>>,
 174    will_open_menu: Option<Box<dyn FnMut()>>,
 175    menu_actions: Vec<Box<dyn Action>>,
 176    open_urls: Option<Box<dyn FnMut(Vec<String>)>>,
 177    finish_launching: Option<Box<dyn FnOnce()>>,
 178    dock_menu: Option<id>,
 179    menus: Option<Vec<OwnedMenu>>,
 180    keyboard_mapper: Rc<MacKeyboardMapper>,
 181}
 182
 183impl MacPlatform {
 184    pub fn new(headless: bool) -> Self {
 185        let dispatcher = Arc::new(MacDispatcher::new());
 186
 187        #[cfg(feature = "font-kit")]
 188        let text_system = Arc::new(crate::MacTextSystem::new());
 189
 190        #[cfg(not(feature = "font-kit"))]
 191        let text_system = Arc::new(gpui::NoopTextSystem::new());
 192
 193        let keyboard_layout = MacKeyboardLayout::new();
 194        let keyboard_mapper = Rc::new(MacKeyboardMapper::new(keyboard_layout.id()));
 195
 196        Self(Mutex::new(MacPlatformState {
 197            headless,
 198            text_system,
 199            background_executor: BackgroundExecutor::new(dispatcher.clone()),
 200            foreground_executor: ForegroundExecutor::new(dispatcher),
 201            renderer_context: renderer::Context::default(),
 202            general_pasteboard: Pasteboard::general(),
 203            find_pasteboard: Pasteboard::find(),
 204            reopen: None,
 205            quit: None,
 206            menu_command: None,
 207            validate_menu_command: None,
 208            will_open_menu: None,
 209            menu_actions: Default::default(),
 210            open_urls: None,
 211            finish_launching: None,
 212            dock_menu: None,
 213            on_keyboard_layout_change: None,
 214            on_thermal_state_change: None,
 215            menus: None,
 216            keyboard_mapper,
 217        }))
 218    }
 219
 220    unsafe fn create_menu_bar(
 221        &self,
 222        menus: &Vec<Menu>,
 223        delegate: id,
 224        actions: &mut Vec<Box<dyn Action>>,
 225        keymap: &Keymap,
 226    ) -> id {
 227        unsafe {
 228            let application_menu = NSMenu::new(nil).autorelease();
 229            application_menu.setDelegate_(delegate);
 230
 231            for menu_config in menus {
 232                let menu = NSMenu::new(nil).autorelease();
 233                let menu_title = ns_string(&menu_config.name);
 234                menu.setTitle_(menu_title);
 235                menu.setDelegate_(delegate);
 236
 237                for item_config in &menu_config.items {
 238                    menu.addItem_(Self::create_menu_item(
 239                        item_config,
 240                        delegate,
 241                        actions,
 242                        keymap,
 243                    ));
 244                }
 245
 246                let menu_item = NSMenuItem::new(nil).autorelease();
 247                menu_item.setTitle_(menu_title);
 248                menu_item.setSubmenu_(menu);
 249                application_menu.addItem_(menu_item);
 250
 251                if menu_config.name == "Window" {
 252                    let app: id = msg_send![APP_CLASS, sharedApplication];
 253                    app.setWindowsMenu_(menu);
 254                }
 255            }
 256
 257            application_menu
 258        }
 259    }
 260
 261    unsafe fn create_dock_menu(
 262        &self,
 263        menu_items: Vec<MenuItem>,
 264        delegate: id,
 265        actions: &mut Vec<Box<dyn Action>>,
 266        keymap: &Keymap,
 267    ) -> id {
 268        unsafe {
 269            let dock_menu = NSMenu::new(nil);
 270            dock_menu.setDelegate_(delegate);
 271            for item_config in menu_items {
 272                dock_menu.addItem_(Self::create_menu_item(
 273                    &item_config,
 274                    delegate,
 275                    actions,
 276                    keymap,
 277                ));
 278            }
 279
 280            dock_menu
 281        }
 282    }
 283
 284    unsafe fn create_menu_item(
 285        item: &MenuItem,
 286        delegate: id,
 287        actions: &mut Vec<Box<dyn Action>>,
 288        keymap: &Keymap,
 289    ) -> id {
 290        static DEFAULT_CONTEXT: OnceLock<Vec<KeyContext>> = OnceLock::new();
 291
 292        unsafe {
 293            match item {
 294                MenuItem::Separator => NSMenuItem::separatorItem(nil),
 295                MenuItem::Action {
 296                    name,
 297                    action,
 298                    os_action,
 299                    checked,
 300                } => {
 301                    // Note that this is intentionally using earlier bindings, whereas typically
 302                    // later ones take display precedence. See the discussion on
 303                    // https://github.com/zed-industries/zed/issues/23621
 304                    let keystrokes = keymap
 305                        .bindings_for_action(action.as_ref())
 306                        .find_or_first(|binding| {
 307                            binding.predicate().is_none_or(|predicate| {
 308                                predicate.eval(DEFAULT_CONTEXT.get_or_init(|| {
 309                                    let mut workspace_context = KeyContext::new_with_defaults();
 310                                    workspace_context.add("Workspace");
 311                                    let mut pane_context = KeyContext::new_with_defaults();
 312                                    pane_context.add("Pane");
 313                                    let mut editor_context = KeyContext::new_with_defaults();
 314                                    editor_context.add("Editor");
 315
 316                                    pane_context.extend(&editor_context);
 317                                    workspace_context.extend(&pane_context);
 318                                    vec![workspace_context]
 319                                }))
 320                            })
 321                        })
 322                        .map(|binding| binding.keystrokes());
 323
 324                    let selector = match os_action {
 325                        Some(gpui::OsAction::Cut) => selector("cut:"),
 326                        Some(gpui::OsAction::Copy) => selector("copy:"),
 327                        Some(gpui::OsAction::Paste) => selector("paste:"),
 328                        Some(gpui::OsAction::SelectAll) => selector("selectAll:"),
 329                        // "undo:" and "redo:" are always disabled in our case, as
 330                        // we don't have a NSTextView/NSTextField to enable them on.
 331                        Some(gpui::OsAction::Undo) => selector("handleGPUIMenuItem:"),
 332                        Some(gpui::OsAction::Redo) => selector("handleGPUIMenuItem:"),
 333                        None => selector("handleGPUIMenuItem:"),
 334                    };
 335
 336                    let item;
 337                    if let Some(keystrokes) = keystrokes {
 338                        if keystrokes.len() == 1 {
 339                            let keystroke = &keystrokes[0];
 340                            let mut mask = NSEventModifierFlags::empty();
 341                            for (modifier, flag) in &[
 342                                (
 343                                    keystroke.modifiers().platform,
 344                                    NSEventModifierFlags::NSCommandKeyMask,
 345                                ),
 346                                (
 347                                    keystroke.modifiers().control,
 348                                    NSEventModifierFlags::NSControlKeyMask,
 349                                ),
 350                                (
 351                                    keystroke.modifiers().alt,
 352                                    NSEventModifierFlags::NSAlternateKeyMask,
 353                                ),
 354                                (
 355                                    keystroke.modifiers().shift,
 356                                    NSEventModifierFlags::NSShiftKeyMask,
 357                                ),
 358                            ] {
 359                                if *modifier {
 360                                    mask |= *flag;
 361                                }
 362                            }
 363
 364                            item = NSMenuItem::alloc(nil)
 365                                .initWithTitle_action_keyEquivalent_(
 366                                    ns_string(name),
 367                                    selector,
 368                                    ns_string(key_to_native(keystroke.key()).as_ref()),
 369                                )
 370                                .autorelease();
 371                            if Self::os_version() >= Version::new(12, 0, 0) {
 372                                let _: () = msg_send![item, setAllowsAutomaticKeyEquivalentLocalization: NO];
 373                            }
 374                            item.setKeyEquivalentModifierMask_(mask);
 375                        } else {
 376                            item = NSMenuItem::alloc(nil)
 377                                .initWithTitle_action_keyEquivalent_(
 378                                    ns_string(name),
 379                                    selector,
 380                                    ns_string(""),
 381                                )
 382                                .autorelease();
 383                        }
 384                    } else {
 385                        item = NSMenuItem::alloc(nil)
 386                            .initWithTitle_action_keyEquivalent_(
 387                                ns_string(name),
 388                                selector,
 389                                ns_string(""),
 390                            )
 391                            .autorelease();
 392                    }
 393
 394                    if *checked {
 395                        item.setState_(NSVisualEffectState::Active);
 396                    }
 397
 398                    let tag = actions.len() as NSInteger;
 399                    let _: () = msg_send![item, setTag: tag];
 400                    actions.push(action.boxed_clone());
 401                    item
 402                }
 403                MenuItem::Submenu(Menu { name, items }) => {
 404                    let item = NSMenuItem::new(nil).autorelease();
 405                    let submenu = NSMenu::new(nil).autorelease();
 406                    submenu.setDelegate_(delegate);
 407                    for item in items {
 408                        submenu.addItem_(Self::create_menu_item(item, delegate, actions, keymap));
 409                    }
 410                    item.setSubmenu_(submenu);
 411                    item.setTitle_(ns_string(name));
 412                    item
 413                }
 414                MenuItem::SystemMenu(OsMenu { name, menu_type }) => {
 415                    let item = NSMenuItem::new(nil).autorelease();
 416                    let submenu = NSMenu::new(nil).autorelease();
 417                    submenu.setDelegate_(delegate);
 418                    item.setSubmenu_(submenu);
 419                    item.setTitle_(ns_string(name));
 420
 421                    match menu_type {
 422                        SystemMenuType::Services => {
 423                            let app: id = msg_send![APP_CLASS, sharedApplication];
 424                            app.setServicesMenu_(item);
 425                        }
 426                    }
 427
 428                    item
 429                }
 430            }
 431        }
 432    }
 433
 434    fn os_version() -> Version {
 435        let version = unsafe {
 436            let process_info = NSProcessInfo::processInfo(nil);
 437            process_info.operatingSystemVersion()
 438        };
 439        Version::new(
 440            version.majorVersion,
 441            version.minorVersion,
 442            version.patchVersion,
 443        )
 444    }
 445}
 446
 447impl Platform for MacPlatform {
 448    fn background_executor(&self) -> BackgroundExecutor {
 449        self.0.lock().background_executor.clone()
 450    }
 451
 452    fn foreground_executor(&self) -> gpui::ForegroundExecutor {
 453        self.0.lock().foreground_executor.clone()
 454    }
 455
 456    fn text_system(&self) -> Arc<dyn PlatformTextSystem> {
 457        self.0.lock().text_system.clone()
 458    }
 459
 460    fn run(&self, on_finish_launching: Box<dyn FnOnce()>) {
 461        let mut state = self.0.lock();
 462        if state.headless {
 463            drop(state);
 464            on_finish_launching();
 465            unsafe { CFRunLoopRun() };
 466        } else {
 467            state.finish_launching = Some(on_finish_launching);
 468            drop(state);
 469        }
 470
 471        unsafe {
 472            let app: id = msg_send![APP_CLASS, sharedApplication];
 473            let app_delegate: id = msg_send![APP_DELEGATE_CLASS, new];
 474            app.setDelegate_(app_delegate);
 475
 476            let self_ptr = self as *const Self as *const c_void;
 477            (*app).set_ivar(MAC_PLATFORM_IVAR, self_ptr);
 478            (*app_delegate).set_ivar(MAC_PLATFORM_IVAR, self_ptr);
 479
 480            let pool = NSAutoreleasePool::new(nil);
 481            app.run();
 482            pool.drain();
 483
 484            (*app).set_ivar(MAC_PLATFORM_IVAR, null_mut::<c_void>());
 485            (*NSWindow::delegate(app)).set_ivar(MAC_PLATFORM_IVAR, null_mut::<c_void>());
 486        }
 487    }
 488
 489    fn quit(&self) {
 490        // Quitting the app causes us to close windows, which invokes `Window::on_close` callbacks
 491        // synchronously before this method terminates. If we call `Platform::quit` while holding a
 492        // borrow of the app state (which most of the time we will do), we will end up
 493        // double-borrowing the app state in the `on_close` callbacks for our open windows. To solve
 494        // this, we make quitting the application asynchronous so that we aren't holding borrows to
 495        // the app state on the stack when we actually terminate the app.
 496
 497        unsafe {
 498            DispatchQueue::main().exec_async_f(ptr::null_mut(), quit);
 499        }
 500
 501        extern "C" fn quit(_: *mut c_void) {
 502            unsafe {
 503                let app = NSApplication::sharedApplication(nil);
 504                let _: () = msg_send![app, terminate: nil];
 505            }
 506        }
 507    }
 508
 509    fn restart(&self, _binary_path: Option<PathBuf>) {
 510        use std::os::unix::process::CommandExt as _;
 511
 512        let app_pid = std::process::id().to_string();
 513        let app_path = self
 514            .app_path()
 515            .ok()
 516            // When the app is not bundled, `app_path` returns the
 517            // directory containing the executable. Disregard this
 518            // and get the path to the executable itself.
 519            .and_then(|path| (path.extension()?.to_str()? == "app").then_some(path))
 520            .unwrap_or_else(|| std::env::current_exe().unwrap());
 521
 522        // Wait until this process has exited and then re-open this path.
 523        let script = r#"
 524            while kill -0 $0 2> /dev/null; do
 525                sleep 0.1
 526            done
 527            open "$1"
 528        "#;
 529
 530        #[allow(
 531            clippy::disallowed_methods,
 532            reason = "We are restarting ourselves, using std command thus is fine"
 533        )]
 534        let restart_process = new_std_command("/bin/bash")
 535            .arg("-c")
 536            .arg(script)
 537            .arg(app_pid)
 538            .arg(app_path)
 539            .process_group(0)
 540            .spawn();
 541
 542        match restart_process {
 543            Ok(_) => self.quit(),
 544            Err(e) => log::error!("failed to spawn restart script: {:?}", e),
 545        }
 546    }
 547
 548    fn activate(&self, ignoring_other_apps: bool) {
 549        unsafe {
 550            let app = NSApplication::sharedApplication(nil);
 551            app.activateIgnoringOtherApps_(ignoring_other_apps.to_objc());
 552        }
 553    }
 554
 555    fn hide(&self) {
 556        unsafe {
 557            let app = NSApplication::sharedApplication(nil);
 558            let _: () = msg_send![app, hide: nil];
 559        }
 560    }
 561
 562    fn hide_other_apps(&self) {
 563        unsafe {
 564            let app = NSApplication::sharedApplication(nil);
 565            let _: () = msg_send![app, hideOtherApplications: nil];
 566        }
 567    }
 568
 569    fn unhide_other_apps(&self) {
 570        unsafe {
 571            let app = NSApplication::sharedApplication(nil);
 572            let _: () = msg_send![app, unhideAllApplications: nil];
 573        }
 574    }
 575
 576    fn primary_display(&self) -> Option<Rc<dyn PlatformDisplay>> {
 577        Some(Rc::new(MacDisplay::primary()))
 578    }
 579
 580    fn displays(&self) -> Vec<Rc<dyn PlatformDisplay>> {
 581        MacDisplay::all()
 582            .map(|screen| Rc::new(screen) as Rc<_>)
 583            .collect()
 584    }
 585
 586    #[cfg(feature = "screen-capture")]
 587    fn is_screen_capture_supported(&self) -> bool {
 588        let min_version = cocoa::foundation::NSOperatingSystemVersion::new(12, 3, 0);
 589        crate::is_macos_version_at_least(min_version)
 590    }
 591
 592    #[cfg(feature = "screen-capture")]
 593    fn screen_capture_sources(
 594        &self,
 595    ) -> oneshot::Receiver<Result<Vec<Rc<dyn gpui::ScreenCaptureSource>>>> {
 596        crate::screen_capture::get_sources()
 597    }
 598
 599    fn active_window(&self) -> Option<AnyWindowHandle> {
 600        MacWindow::active_window()
 601    }
 602
 603    // Returns the windows ordered front-to-back, meaning that the active
 604    // window is the first one in the returned vec.
 605    fn window_stack(&self) -> Option<Vec<AnyWindowHandle>> {
 606        Some(MacWindow::ordered_windows())
 607    }
 608
 609    fn open_window(
 610        &self,
 611        handle: AnyWindowHandle,
 612        options: WindowParams,
 613    ) -> Result<Box<dyn PlatformWindow>> {
 614        let renderer_context = self.0.lock().renderer_context.clone();
 615        Ok(Box::new(MacWindow::open(
 616            handle,
 617            options,
 618            self.foreground_executor(),
 619            self.background_executor(),
 620            renderer_context,
 621        )))
 622    }
 623
 624    fn window_appearance(&self) -> WindowAppearance {
 625        unsafe {
 626            let app = NSApplication::sharedApplication(nil);
 627            let appearance: id = msg_send![app, effectiveAppearance];
 628            crate::window_appearance::window_appearance_from_native(appearance)
 629        }
 630    }
 631
 632    fn open_url(&self, url: &str) {
 633        unsafe {
 634            let ns_url = NSURL::alloc(nil).initWithString_(ns_string(url));
 635            if ns_url.is_null() {
 636                log::error!("Failed to create NSURL from string: {}", url);
 637                return;
 638            }
 639            let url = ns_url.autorelease();
 640            let workspace: id = msg_send![class!(NSWorkspace), sharedWorkspace];
 641            msg_send![workspace, openURL: url]
 642        }
 643    }
 644
 645    fn register_url_scheme(&self, scheme: &str) -> Task<anyhow::Result<()>> {
 646        // API only available post Monterey
 647        // https://developer.apple.com/documentation/appkit/nsworkspace/3753004-setdefaultapplicationaturl
 648        let (done_tx, done_rx) = oneshot::channel();
 649        if Self::os_version() < Version::new(12, 0, 0) {
 650            return Task::ready(Err(anyhow!(
 651                "macOS 12.0 or later is required to register URL schemes"
 652            )));
 653        }
 654
 655        let bundle_id = unsafe {
 656            let bundle: id = msg_send![class!(NSBundle), mainBundle];
 657            let bundle_id: id = msg_send![bundle, bundleIdentifier];
 658            if bundle_id == nil {
 659                return Task::ready(Err(anyhow!("Can only register URL scheme in bundled apps")));
 660            }
 661            bundle_id
 662        };
 663
 664        unsafe {
 665            let workspace: id = msg_send![class!(NSWorkspace), sharedWorkspace];
 666            let scheme: id = ns_string(scheme);
 667            let app: id = msg_send![workspace, URLForApplicationWithBundleIdentifier: bundle_id];
 668            if app == nil {
 669                return Task::ready(Err(anyhow!(
 670                    "Cannot register URL scheme until app is installed"
 671                )));
 672            }
 673            let done_tx = Cell::new(Some(done_tx));
 674            let block = ConcreteBlock::new(move |error: id| {
 675                let result = if error == nil {
 676                    Ok(())
 677                } else {
 678                    let msg: id = msg_send![error, localizedDescription];
 679                    Err(anyhow!("Failed to register: {msg:?}"))
 680                };
 681
 682                if let Some(done_tx) = done_tx.take() {
 683                    let _ = done_tx.send(result);
 684                }
 685            });
 686            let block = block.copy();
 687            let _: () = msg_send![workspace, setDefaultApplicationAtURL: app toOpenURLsWithScheme: scheme completionHandler: block];
 688        }
 689
 690        self.background_executor()
 691            .spawn(async { done_rx.await.map_err(|e| anyhow!(e))? })
 692    }
 693
 694    fn on_open_urls(&self, callback: Box<dyn FnMut(Vec<String>)>) {
 695        self.0.lock().open_urls = Some(callback);
 696    }
 697
 698    fn prompt_for_paths(
 699        &self,
 700        options: PathPromptOptions,
 701    ) -> oneshot::Receiver<Result<Option<Vec<PathBuf>>>> {
 702        let (done_tx, done_rx) = oneshot::channel();
 703        self.foreground_executor()
 704            .spawn(async move {
 705                unsafe {
 706                    let panel = NSOpenPanel::openPanel(nil);
 707                    panel.setCanChooseDirectories_(options.directories.to_objc());
 708                    panel.setCanChooseFiles_(options.files.to_objc());
 709                    panel.setAllowsMultipleSelection_(options.multiple.to_objc());
 710
 711                    panel.setCanCreateDirectories(true.to_objc());
 712                    panel.setResolvesAliases_(false.to_objc());
 713                    let done_tx = Cell::new(Some(done_tx));
 714                    let block = ConcreteBlock::new(move |response: NSModalResponse| {
 715                        let result = if response == NSModalResponse::NSModalResponseOk {
 716                            let mut result = Vec::new();
 717                            let urls = panel.URLs();
 718                            for i in 0..urls.count() {
 719                                let url = urls.objectAtIndex(i);
 720                                if url.isFileURL() == YES
 721                                    && let Ok(path) = ns_url_to_path(url)
 722                                {
 723                                    result.push(path)
 724                                }
 725                            }
 726                            Some(result)
 727                        } else {
 728                            None
 729                        };
 730
 731                        if let Some(done_tx) = done_tx.take() {
 732                            let _ = done_tx.send(Ok(result));
 733                        }
 734                    });
 735                    let block = block.copy();
 736
 737                    if let Some(prompt) = options.prompt {
 738                        let _: () = msg_send![panel, setPrompt: ns_string(&prompt)];
 739                    }
 740
 741                    let _: () = msg_send![panel, beginWithCompletionHandler: block];
 742                }
 743            })
 744            .detach();
 745        done_rx
 746    }
 747
 748    fn prompt_for_new_path(
 749        &self,
 750        directory: &Path,
 751        suggested_name: Option<&str>,
 752    ) -> oneshot::Receiver<Result<Option<PathBuf>>> {
 753        let directory = directory.to_owned();
 754        let suggested_name = suggested_name.map(|s| s.to_owned());
 755        let (done_tx, done_rx) = oneshot::channel();
 756        self.foreground_executor()
 757            .spawn(async move {
 758                unsafe {
 759                    let panel = NSSavePanel::savePanel(nil);
 760                    let path = ns_string(directory.to_string_lossy().as_ref());
 761                    let url = NSURL::fileURLWithPath_isDirectory_(nil, path, true.to_objc());
 762                    panel.setDirectoryURL(url);
 763
 764                    if let Some(suggested_name) = suggested_name {
 765                        let name_string = ns_string(&suggested_name);
 766                        let _: () = msg_send![panel, setNameFieldStringValue: name_string];
 767                    }
 768
 769                    let done_tx = Cell::new(Some(done_tx));
 770                    let block = ConcreteBlock::new(move |response: NSModalResponse| {
 771                        let mut result = None;
 772                        if response == NSModalResponse::NSModalResponseOk {
 773                            let url = panel.URL();
 774                            if url.isFileURL() == YES {
 775                                result = ns_url_to_path(panel.URL()).ok().map(|mut result| {
 776                                    let Some(filename) = result.file_name() else {
 777                                        return result;
 778                                    };
 779                                    let chunks = filename
 780                                        .as_bytes()
 781                                        .split(|&b| b == b'.')
 782                                        .collect::<Vec<_>>();
 783
 784                                    // https://github.com/zed-industries/zed/issues/16969
 785                                    // Workaround a bug in macOS Sequoia that adds an extra file-extension
 786                                    // sometimes. e.g. `a.sql` becomes `a.sql.s` or `a.txtx` becomes `a.txtx.txt`
 787                                    //
 788                                    // This is conditional on OS version because I'd like to get rid of it, so that
 789                                    // you can manually create a file called `a.sql.s`. That said it seems better
 790                                    // to break that use-case than breaking `a.sql`.
 791                                    if chunks.len() == 3
 792                                        && chunks[1].starts_with(chunks[2])
 793                                        && Self::os_version() >= Version::new(15, 0, 0)
 794                                    {
 795                                        let new_filename = OsStr::from_bytes(
 796                                            &filename.as_bytes()
 797                                                [..chunks[0].len() + 1 + chunks[1].len()],
 798                                        )
 799                                        .to_owned();
 800                                        result.set_file_name(&new_filename);
 801                                    }
 802                                    result
 803                                })
 804                            }
 805                        }
 806
 807                        if let Some(done_tx) = done_tx.take() {
 808                            let _ = done_tx.send(Ok(result));
 809                        }
 810                    });
 811                    let block = block.copy();
 812                    let _: () = msg_send![panel, beginWithCompletionHandler: block];
 813                }
 814            })
 815            .detach();
 816
 817        done_rx
 818    }
 819
 820    fn can_select_mixed_files_and_dirs(&self) -> bool {
 821        true
 822    }
 823
 824    fn reveal_path(&self, path: &Path) {
 825        unsafe {
 826            let path = path.to_path_buf();
 827            self.0
 828                .lock()
 829                .background_executor
 830                .spawn(async move {
 831                    let full_path = ns_string(path.to_str().unwrap_or(""));
 832                    let root_full_path = ns_string("");
 833                    let workspace: id = msg_send![class!(NSWorkspace), sharedWorkspace];
 834                    let _: BOOL = msg_send![
 835                        workspace,
 836                        selectFile: full_path
 837                        inFileViewerRootedAtPath: root_full_path
 838                    ];
 839                })
 840                .detach();
 841        }
 842    }
 843
 844    fn open_with_system(&self, path: &Path) {
 845        let path = path.to_owned();
 846        self.0
 847            .lock()
 848            .background_executor
 849            .spawn(async move {
 850                if let Some(mut child) = new_command("open")
 851                    .arg(path)
 852                    .spawn()
 853                    .context("invoking open command")
 854                    .log_err()
 855                {
 856                    child.status().await.log_err();
 857                }
 858            })
 859            .detach();
 860    }
 861
 862    fn on_quit(&self, callback: Box<dyn FnMut()>) {
 863        self.0.lock().quit = Some(callback);
 864    }
 865
 866    fn on_reopen(&self, callback: Box<dyn FnMut()>) {
 867        self.0.lock().reopen = Some(callback);
 868    }
 869
 870    fn on_keyboard_layout_change(&self, callback: Box<dyn FnMut()>) {
 871        self.0.lock().on_keyboard_layout_change = Some(callback);
 872    }
 873
 874    fn on_app_menu_action(&self, callback: Box<dyn FnMut(&dyn Action)>) {
 875        self.0.lock().menu_command = Some(callback);
 876    }
 877
 878    fn on_will_open_app_menu(&self, callback: Box<dyn FnMut()>) {
 879        self.0.lock().will_open_menu = Some(callback);
 880    }
 881
 882    fn on_validate_app_menu_command(&self, callback: Box<dyn FnMut(&dyn Action) -> bool>) {
 883        self.0.lock().validate_menu_command = Some(callback);
 884    }
 885
 886    fn on_thermal_state_change(&self, callback: Box<dyn FnMut()>) {
 887        self.0.lock().on_thermal_state_change = Some(callback);
 888    }
 889
 890    fn thermal_state(&self) -> ThermalState {
 891        unsafe {
 892            let process_info: id = msg_send![class!(NSProcessInfo), processInfo];
 893            let state: NSInteger = msg_send![process_info, thermalState];
 894            match state {
 895                0 => ThermalState::Nominal,
 896                1 => ThermalState::Fair,
 897                2 => ThermalState::Serious,
 898                3 => ThermalState::Critical,
 899                _ => ThermalState::Nominal,
 900            }
 901        }
 902    }
 903
 904    fn keyboard_layout(&self) -> Box<dyn PlatformKeyboardLayout> {
 905        Box::new(MacKeyboardLayout::new())
 906    }
 907
 908    fn keyboard_mapper(&self) -> Rc<dyn PlatformKeyboardMapper> {
 909        self.0.lock().keyboard_mapper.clone()
 910    }
 911
 912    fn app_path(&self) -> Result<PathBuf> {
 913        unsafe {
 914            let bundle: id = NSBundle::mainBundle();
 915            anyhow::ensure!(!bundle.is_null(), "app is not running inside a bundle");
 916            Ok(path_from_objc(msg_send![bundle, bundlePath]))
 917        }
 918    }
 919
 920    fn set_menus(&self, menus: Vec<Menu>, keymap: &Keymap) {
 921        unsafe {
 922            let app: id = msg_send![APP_CLASS, sharedApplication];
 923            let mut state = self.0.lock();
 924            let actions = &mut state.menu_actions;
 925            let menu = self.create_menu_bar(&menus, NSWindow::delegate(app), actions, keymap);
 926            drop(state);
 927            app.setMainMenu_(menu);
 928        }
 929        self.0.lock().menus = Some(menus.into_iter().map(|menu| menu.owned()).collect());
 930    }
 931
 932    fn get_menus(&self) -> Option<Vec<OwnedMenu>> {
 933        self.0.lock().menus.clone()
 934    }
 935
 936    fn set_dock_menu(&self, menu: Vec<MenuItem>, keymap: &Keymap) {
 937        unsafe {
 938            let app: id = msg_send![APP_CLASS, sharedApplication];
 939            let mut state = self.0.lock();
 940            let actions = &mut state.menu_actions;
 941            let new = self.create_dock_menu(menu, NSWindow::delegate(app), actions, keymap);
 942            if let Some(old) = state.dock_menu.replace(new) {
 943                CFRelease(old as _)
 944            }
 945        }
 946    }
 947
 948    fn add_recent_document(&self, path: &Path) {
 949        if let Some(path_str) = path.to_str() {
 950            unsafe {
 951                let document_controller: id =
 952                    msg_send![class!(NSDocumentController), sharedDocumentController];
 953                let url: id = NSURL::fileURLWithPath_(nil, ns_string(path_str));
 954                let _: () = msg_send![document_controller, noteNewRecentDocumentURL:url];
 955            }
 956        }
 957    }
 958
 959    fn path_for_auxiliary_executable(&self, name: &str) -> Result<PathBuf> {
 960        unsafe {
 961            let bundle: id = NSBundle::mainBundle();
 962            anyhow::ensure!(!bundle.is_null(), "app is not running inside a bundle");
 963            let name = ns_string(name);
 964            let url: id = msg_send![bundle, URLForAuxiliaryExecutable: name];
 965            anyhow::ensure!(!url.is_null(), "resource not found");
 966            ns_url_to_path(url)
 967        }
 968    }
 969
 970    /// Match cursor style to one of the styles available
 971    /// in macOS's [NSCursor](https://developer.apple.com/documentation/appkit/nscursor).
 972    fn set_cursor_style(&self, style: CursorStyle) {
 973        unsafe {
 974            if style == CursorStyle::None {
 975                let _: () = msg_send![class!(NSCursor), setHiddenUntilMouseMoves:YES];
 976                return;
 977            }
 978
 979            let new_cursor: id = match style {
 980                CursorStyle::Arrow => msg_send![class!(NSCursor), arrowCursor],
 981                CursorStyle::IBeam => msg_send![class!(NSCursor), IBeamCursor],
 982                CursorStyle::Crosshair => msg_send![class!(NSCursor), crosshairCursor],
 983                CursorStyle::ClosedHand => msg_send![class!(NSCursor), closedHandCursor],
 984                CursorStyle::OpenHand => msg_send![class!(NSCursor), openHandCursor],
 985                CursorStyle::PointingHand => msg_send![class!(NSCursor), pointingHandCursor],
 986                CursorStyle::ResizeLeftRight => msg_send![class!(NSCursor), resizeLeftRightCursor],
 987                CursorStyle::ResizeUpDown => msg_send![class!(NSCursor), resizeUpDownCursor],
 988                CursorStyle::ResizeLeft => msg_send![class!(NSCursor), resizeLeftCursor],
 989                CursorStyle::ResizeRight => msg_send![class!(NSCursor), resizeRightCursor],
 990                CursorStyle::ResizeColumn => msg_send![class!(NSCursor), resizeLeftRightCursor],
 991                CursorStyle::ResizeRow => msg_send![class!(NSCursor), resizeUpDownCursor],
 992                CursorStyle::ResizeUp => msg_send![class!(NSCursor), resizeUpCursor],
 993                CursorStyle::ResizeDown => msg_send![class!(NSCursor), resizeDownCursor],
 994
 995                // Undocumented, private class methods:
 996                // https://stackoverflow.com/questions/27242353/cocoa-predefined-resize-mouse-cursor
 997                CursorStyle::ResizeUpLeftDownRight => {
 998                    msg_send![class!(NSCursor), _windowResizeNorthWestSouthEastCursor]
 999                }
1000                CursorStyle::ResizeUpRightDownLeft => {
1001                    msg_send![class!(NSCursor), _windowResizeNorthEastSouthWestCursor]
1002                }
1003
1004                CursorStyle::IBeamCursorForVerticalLayout => {
1005                    msg_send![class!(NSCursor), IBeamCursorForVerticalLayout]
1006                }
1007                CursorStyle::OperationNotAllowed => {
1008                    msg_send![class!(NSCursor), operationNotAllowedCursor]
1009                }
1010                CursorStyle::DragLink => msg_send![class!(NSCursor), dragLinkCursor],
1011                CursorStyle::DragCopy => msg_send![class!(NSCursor), dragCopyCursor],
1012                CursorStyle::ContextualMenu => msg_send![class!(NSCursor), contextualMenuCursor],
1013                CursorStyle::None => unreachable!(),
1014            };
1015
1016            let old_cursor: id = msg_send![class!(NSCursor), currentCursor];
1017            if new_cursor != old_cursor {
1018                let _: () = msg_send![new_cursor, set];
1019            }
1020        }
1021    }
1022
1023    fn should_auto_hide_scrollbars(&self) -> bool {
1024        #[allow(non_upper_case_globals)]
1025        const NSScrollerStyleOverlay: NSInteger = 1;
1026
1027        unsafe {
1028            let style: NSInteger = msg_send![class!(NSScroller), preferredScrollerStyle];
1029            style == NSScrollerStyleOverlay
1030        }
1031    }
1032
1033    fn read_from_clipboard(&self) -> Option<ClipboardItem> {
1034        let state = self.0.lock();
1035        state.general_pasteboard.read()
1036    }
1037
1038    fn write_to_clipboard(&self, item: ClipboardItem) {
1039        let state = self.0.lock();
1040        state.general_pasteboard.write(item);
1041    }
1042
1043    fn read_from_find_pasteboard(&self) -> Option<ClipboardItem> {
1044        let state = self.0.lock();
1045        state.find_pasteboard.read()
1046    }
1047
1048    fn write_to_find_pasteboard(&self, item: ClipboardItem) {
1049        let state = self.0.lock();
1050        state.find_pasteboard.write(item);
1051    }
1052
1053    fn write_credentials(&self, url: &str, username: &str, password: &[u8]) -> Task<Result<()>> {
1054        let url = url.to_string();
1055        let username = username.to_string();
1056        let password = password.to_vec();
1057        self.background_executor().spawn(async move {
1058            unsafe {
1059                use security::*;
1060
1061                let url = CFString::from(url.as_str());
1062                let username = CFString::from(username.as_str());
1063                let password = CFData::from_buffer(&password);
1064
1065                // First, check if there are already credentials for the given server. If so, then
1066                // update the username and password.
1067                let mut verb = "updating";
1068                let mut query_attrs = CFMutableDictionary::with_capacity(2);
1069                query_attrs.set(kSecClass as *const _, kSecClassInternetPassword as *const _);
1070                query_attrs.set(kSecAttrServer as *const _, url.as_CFTypeRef());
1071
1072                let mut attrs = CFMutableDictionary::with_capacity(4);
1073                attrs.set(kSecClass as *const _, kSecClassInternetPassword as *const _);
1074                attrs.set(kSecAttrServer as *const _, url.as_CFTypeRef());
1075                attrs.set(kSecAttrAccount as *const _, username.as_CFTypeRef());
1076                attrs.set(kSecValueData as *const _, password.as_CFTypeRef());
1077
1078                let mut status = SecItemUpdate(
1079                    query_attrs.as_concrete_TypeRef(),
1080                    attrs.as_concrete_TypeRef(),
1081                );
1082
1083                // If there were no existing credentials for the given server, then create them.
1084                if status == errSecItemNotFound {
1085                    verb = "creating";
1086                    status = SecItemAdd(attrs.as_concrete_TypeRef(), ptr::null_mut());
1087                }
1088                anyhow::ensure!(status == errSecSuccess, "{verb} password failed: {status}");
1089            }
1090            Ok(())
1091        })
1092    }
1093
1094    fn read_credentials(&self, url: &str) -> Task<Result<Option<(String, Vec<u8>)>>> {
1095        let url = url.to_string();
1096        self.background_executor().spawn(async move {
1097            let url = CFString::from(url.as_str());
1098            let cf_true = CFBoolean::true_value().as_CFTypeRef();
1099
1100            unsafe {
1101                use security::*;
1102
1103                // Find any credentials for the given server URL.
1104                let mut attrs = CFMutableDictionary::with_capacity(5);
1105                attrs.set(kSecClass as *const _, kSecClassInternetPassword as *const _);
1106                attrs.set(kSecAttrServer as *const _, url.as_CFTypeRef());
1107                attrs.set(kSecReturnAttributes as *const _, cf_true);
1108                attrs.set(kSecReturnData as *const _, cf_true);
1109
1110                let mut result = CFTypeRef::from(ptr::null());
1111                let status = SecItemCopyMatching(attrs.as_concrete_TypeRef(), &mut result);
1112                match status {
1113                    security::errSecSuccess => {}
1114                    security::errSecItemNotFound | security::errSecUserCanceled => return Ok(None),
1115                    _ => anyhow::bail!("reading password failed: {status}"),
1116                }
1117
1118                let result = CFType::wrap_under_create_rule(result)
1119                    .downcast::<CFDictionary>()
1120                    .context("keychain item was not a dictionary")?;
1121                let username = result
1122                    .find(kSecAttrAccount as *const _)
1123                    .context("account was missing from keychain item")?;
1124                let username = CFType::wrap_under_get_rule(*username)
1125                    .downcast::<CFString>()
1126                    .context("account was not a string")?;
1127                let password = result
1128                    .find(kSecValueData as *const _)
1129                    .context("password was missing from keychain item")?;
1130                let password = CFType::wrap_under_get_rule(*password)
1131                    .downcast::<CFData>()
1132                    .context("password was not a string")?;
1133
1134                Ok(Some((username.to_string(), password.bytes().to_vec())))
1135            }
1136        })
1137    }
1138
1139    fn delete_credentials(&self, url: &str) -> Task<Result<()>> {
1140        let url = url.to_string();
1141
1142        self.background_executor().spawn(async move {
1143            unsafe {
1144                use security::*;
1145
1146                let url = CFString::from(url.as_str());
1147                let mut query_attrs = CFMutableDictionary::with_capacity(2);
1148                query_attrs.set(kSecClass as *const _, kSecClassInternetPassword as *const _);
1149                query_attrs.set(kSecAttrServer as *const _, url.as_CFTypeRef());
1150
1151                let status = SecItemDelete(query_attrs.as_concrete_TypeRef());
1152                anyhow::ensure!(status == errSecSuccess, "delete password failed: {status}");
1153            }
1154            Ok(())
1155        })
1156    }
1157}
1158
1159unsafe fn path_from_objc(path: id) -> PathBuf {
1160    let len = msg_send![path, lengthOfBytesUsingEncoding: NSUTF8StringEncoding];
1161    let bytes = unsafe { path.UTF8String() as *const u8 };
1162    let path = str::from_utf8(unsafe { slice::from_raw_parts(bytes, len) }).unwrap();
1163    PathBuf::from(path)
1164}
1165
1166unsafe fn get_mac_platform(object: &mut Object) -> &MacPlatform {
1167    unsafe {
1168        let platform_ptr: *mut c_void = *object.get_ivar(MAC_PLATFORM_IVAR);
1169        assert!(!platform_ptr.is_null());
1170        &*(platform_ptr as *const MacPlatform)
1171    }
1172}
1173
1174extern "C" fn will_finish_launching(_this: &mut Object, _: Sel, _: id) {
1175    unsafe {
1176        let user_defaults: id = msg_send![class!(NSUserDefaults), standardUserDefaults];
1177
1178        // The autofill heuristic controller causes slowdown and high CPU usage.
1179        // We don't know exactly why. This disables the full heuristic controller.
1180        //
1181        // Adapted from: https://github.com/ghostty-org/ghostty/pull/8625
1182        let name = ns_string("NSAutoFillHeuristicControllerEnabled");
1183        let existing_value: id = msg_send![user_defaults, objectForKey: name];
1184        if existing_value == nil {
1185            let false_value: id = msg_send![class!(NSNumber), numberWithBool:false];
1186            let _: () = msg_send![user_defaults, setObject: false_value forKey: name];
1187        }
1188    }
1189}
1190
1191extern "C" fn did_finish_launching(this: &mut Object, _: Sel, _: id) {
1192    unsafe {
1193        let app: id = msg_send![APP_CLASS, sharedApplication];
1194        app.setActivationPolicy_(NSApplicationActivationPolicyRegular);
1195
1196        let notification_center: *mut Object =
1197            msg_send![class!(NSNotificationCenter), defaultCenter];
1198        let name = ns_string("NSTextInputContextKeyboardSelectionDidChangeNotification");
1199        let _: () = msg_send![notification_center, addObserver: this as id
1200            selector: sel!(onKeyboardLayoutChange:)
1201            name: name
1202            object: nil
1203        ];
1204
1205        let thermal_name = ns_string("NSProcessInfoThermalStateDidChangeNotification");
1206        let process_info: id = msg_send![class!(NSProcessInfo), processInfo];
1207        let _: () = msg_send![notification_center, addObserver: this as id
1208            selector: sel!(onThermalStateChange:)
1209            name: thermal_name
1210            object: process_info
1211        ];
1212
1213        let platform = get_mac_platform(this);
1214        let callback = platform.0.lock().finish_launching.take();
1215        if let Some(callback) = callback {
1216            callback();
1217        }
1218    }
1219}
1220
1221extern "C" fn should_handle_reopen(this: &mut Object, _: Sel, _: id, has_open_windows: bool) {
1222    if !has_open_windows {
1223        let platform = unsafe { get_mac_platform(this) };
1224        let mut lock = platform.0.lock();
1225        if let Some(mut callback) = lock.reopen.take() {
1226            drop(lock);
1227            callback();
1228            platform.0.lock().reopen.get_or_insert(callback);
1229        }
1230    }
1231}
1232
1233extern "C" fn will_terminate(this: &mut Object, _: Sel, _: id) {
1234    let platform = unsafe { get_mac_platform(this) };
1235    let mut lock = platform.0.lock();
1236    if let Some(mut callback) = lock.quit.take() {
1237        drop(lock);
1238        callback();
1239        platform.0.lock().quit.get_or_insert(callback);
1240    }
1241}
1242
1243extern "C" fn on_keyboard_layout_change(this: &mut Object, _: Sel, _: id) {
1244    let platform = unsafe { get_mac_platform(this) };
1245    let mut lock = platform.0.lock();
1246    let keyboard_layout = MacKeyboardLayout::new();
1247    lock.keyboard_mapper = Rc::new(MacKeyboardMapper::new(keyboard_layout.id()));
1248    if let Some(mut callback) = lock.on_keyboard_layout_change.take() {
1249        drop(lock);
1250        callback();
1251        platform
1252            .0
1253            .lock()
1254            .on_keyboard_layout_change
1255            .get_or_insert(callback);
1256    }
1257}
1258
1259extern "C" fn on_thermal_state_change(this: &mut Object, _: Sel, _: id) {
1260    // Defer to the next run loop iteration to avoid re-entrant borrows of the App RefCell,
1261    // as NSNotificationCenter delivers this notification synchronously and it may fire while
1262    // the App is already borrowed (same pattern as quit() above).
1263    let platform = unsafe { get_mac_platform(this) };
1264    let platform_ptr = platform as *const MacPlatform as *mut c_void;
1265    unsafe {
1266        DispatchQueue::main().exec_async_f(platform_ptr, on_thermal_state_change);
1267    }
1268
1269    extern "C" fn on_thermal_state_change(context: *mut c_void) {
1270        let platform = unsafe { &*(context as *const MacPlatform) };
1271        let mut lock = platform.0.lock();
1272        if let Some(mut callback) = lock.on_thermal_state_change.take() {
1273            drop(lock);
1274            callback();
1275            platform
1276                .0
1277                .lock()
1278                .on_thermal_state_change
1279                .get_or_insert(callback);
1280        }
1281    }
1282}
1283
1284extern "C" fn open_urls(this: &mut Object, _: Sel, _: id, urls: id) {
1285    let urls = unsafe {
1286        (0..urls.count())
1287            .filter_map(|i| {
1288                let url = urls.objectAtIndex(i);
1289                match CStr::from_ptr(url.absoluteString().UTF8String() as *mut c_char).to_str() {
1290                    Ok(string) => Some(string.to_string()),
1291                    Err(err) => {
1292                        log::error!("error converting path to string: {}", err);
1293                        None
1294                    }
1295                }
1296            })
1297            .collect::<Vec<_>>()
1298    };
1299    let platform = unsafe { get_mac_platform(this) };
1300    let mut lock = platform.0.lock();
1301    if let Some(mut callback) = lock.open_urls.take() {
1302        drop(lock);
1303        callback(urls);
1304        platform.0.lock().open_urls.get_or_insert(callback);
1305    }
1306}
1307
1308extern "C" fn handle_menu_item(this: &mut Object, _: Sel, item: id) {
1309    unsafe {
1310        let platform = get_mac_platform(this);
1311        let mut lock = platform.0.lock();
1312        if let Some(mut callback) = lock.menu_command.take() {
1313            let tag: NSInteger = msg_send![item, tag];
1314            let index = tag as usize;
1315            if let Some(action) = lock.menu_actions.get(index) {
1316                let action = action.boxed_clone();
1317                drop(lock);
1318                callback(&*action);
1319            }
1320            platform.0.lock().menu_command.get_or_insert(callback);
1321        }
1322    }
1323}
1324
1325extern "C" fn validate_menu_item(this: &mut Object, _: Sel, item: id) -> bool {
1326    unsafe {
1327        let mut result = false;
1328        let platform = get_mac_platform(this);
1329        let mut lock = platform.0.lock();
1330        if let Some(mut callback) = lock.validate_menu_command.take() {
1331            let tag: NSInteger = msg_send![item, tag];
1332            let index = tag as usize;
1333            if let Some(action) = lock.menu_actions.get(index) {
1334                let action = action.boxed_clone();
1335                drop(lock);
1336                result = callback(action.as_ref());
1337            }
1338            platform
1339                .0
1340                .lock()
1341                .validate_menu_command
1342                .get_or_insert(callback);
1343        }
1344        result
1345    }
1346}
1347
1348extern "C" fn menu_will_open(this: &mut Object, _: Sel, _: id) {
1349    unsafe {
1350        let platform = get_mac_platform(this);
1351        let mut lock = platform.0.lock();
1352        if let Some(mut callback) = lock.will_open_menu.take() {
1353            drop(lock);
1354            callback();
1355            platform.0.lock().will_open_menu.get_or_insert(callback);
1356        }
1357    }
1358}
1359
1360extern "C" fn handle_dock_menu(this: &mut Object, _: Sel, _: id) -> id {
1361    unsafe {
1362        let platform = get_mac_platform(this);
1363        let state = platform.0.lock();
1364        if let Some(id) = state.dock_menu {
1365            id
1366        } else {
1367            nil
1368        }
1369    }
1370}
1371
1372unsafe fn ns_url_to_path(url: id) -> Result<PathBuf> {
1373    let path: *mut c_char = msg_send![url, fileSystemRepresentation];
1374    anyhow::ensure!(!path.is_null(), "url is not a file path: {}", unsafe {
1375        CStr::from_ptr(url.absoluteString().UTF8String()).to_string_lossy()
1376    });
1377    Ok(PathBuf::from(OsStr::from_bytes(unsafe {
1378        CStr::from_ptr(path).to_bytes()
1379    })))
1380}
1381
1382#[link(name = "Carbon", kind = "framework")]
1383unsafe extern "C" {
1384    pub(super) fn TISCopyCurrentKeyboardLayoutInputSource() -> *mut Object;
1385    pub(super) fn TISGetInputSourceProperty(
1386        inputSource: *mut Object,
1387        propertyKey: *const c_void,
1388    ) -> *mut Object;
1389
1390    pub(super) fn UCKeyTranslate(
1391        keyLayoutPtr: *const ::std::os::raw::c_void,
1392        virtualKeyCode: u16,
1393        keyAction: u16,
1394        modifierKeyState: u32,
1395        keyboardType: u32,
1396        keyTranslateOptions: u32,
1397        deadKeyState: *mut u32,
1398        maxStringLength: usize,
1399        actualStringLength: *mut usize,
1400        unicodeString: *mut u16,
1401    ) -> u32;
1402    pub(super) fn LMGetKbdType() -> u16;
1403    pub(super) static kTISPropertyUnicodeKeyLayoutData: CFStringRef;
1404    pub(super) static kTISPropertyInputSourceID: CFStringRef;
1405    pub(super) static kTISPropertyLocalizedName: CFStringRef;
1406}
1407
1408mod security {
1409    #![allow(non_upper_case_globals)]
1410    use super::*;
1411
1412    #[link(name = "Security", kind = "framework")]
1413    unsafe extern "C" {
1414        pub static kSecClass: CFStringRef;
1415        pub static kSecClassInternetPassword: CFStringRef;
1416        pub static kSecAttrServer: CFStringRef;
1417        pub static kSecAttrAccount: CFStringRef;
1418        pub static kSecValueData: CFStringRef;
1419        pub static kSecReturnAttributes: CFStringRef;
1420        pub static kSecReturnData: CFStringRef;
1421
1422        pub fn SecItemAdd(attributes: CFDictionaryRef, result: *mut CFTypeRef) -> OSStatus;
1423        pub fn SecItemUpdate(query: CFDictionaryRef, attributes: CFDictionaryRef) -> OSStatus;
1424        pub fn SecItemDelete(query: CFDictionaryRef) -> OSStatus;
1425        pub fn SecItemCopyMatching(query: CFDictionaryRef, result: *mut CFTypeRef) -> OSStatus;
1426    }
1427
1428    pub const errSecSuccess: OSStatus = 0;
1429    pub const errSecUserCanceled: OSStatus = -128;
1430    pub const errSecItemNotFound: OSStatus = -25300;
1431}