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