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