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("--")
 862                    .arg(path)
 863                    .spawn()
 864                    .context("invoking open command")
 865                    .log_err()
 866                {
 867                    child.status().await.log_err();
 868                }
 869            })
 870            .detach();
 871    }
 872
 873    fn on_quit(&self, callback: Box<dyn FnMut()>) {
 874        self.0.lock().quit = Some(callback);
 875    }
 876
 877    fn on_reopen(&self, callback: Box<dyn FnMut()>) {
 878        self.0.lock().reopen = Some(callback);
 879    }
 880
 881    fn on_keyboard_layout_change(&self, callback: Box<dyn FnMut()>) {
 882        self.0.lock().on_keyboard_layout_change = Some(callback);
 883    }
 884
 885    fn on_app_menu_action(&self, callback: Box<dyn FnMut(&dyn Action)>) {
 886        self.0.lock().menu_command = Some(callback);
 887    }
 888
 889    fn on_will_open_app_menu(&self, callback: Box<dyn FnMut()>) {
 890        self.0.lock().will_open_menu = Some(callback);
 891    }
 892
 893    fn on_validate_app_menu_command(&self, callback: Box<dyn FnMut(&dyn Action) -> bool>) {
 894        self.0.lock().validate_menu_command = Some(callback);
 895    }
 896
 897    fn on_thermal_state_change(&self, callback: Box<dyn FnMut()>) {
 898        self.0.lock().on_thermal_state_change = Some(callback);
 899    }
 900
 901    fn thermal_state(&self) -> ThermalState {
 902        unsafe {
 903            let process_info: id = msg_send![class!(NSProcessInfo), processInfo];
 904            let state: NSInteger = msg_send![process_info, thermalState];
 905            match state {
 906                0 => ThermalState::Nominal,
 907                1 => ThermalState::Fair,
 908                2 => ThermalState::Serious,
 909                3 => ThermalState::Critical,
 910                _ => ThermalState::Nominal,
 911            }
 912        }
 913    }
 914
 915    fn keyboard_layout(&self) -> Box<dyn PlatformKeyboardLayout> {
 916        Box::new(MacKeyboardLayout::new())
 917    }
 918
 919    fn keyboard_mapper(&self) -> Rc<dyn PlatformKeyboardMapper> {
 920        self.0.lock().keyboard_mapper.clone()
 921    }
 922
 923    fn app_path(&self) -> Result<PathBuf> {
 924        unsafe {
 925            let bundle: id = NSBundle::mainBundle();
 926            anyhow::ensure!(!bundle.is_null(), "app is not running inside a bundle");
 927            Ok(path_from_objc(msg_send![bundle, bundlePath]))
 928        }
 929    }
 930
 931    fn set_menus(&self, menus: Vec<Menu>, keymap: &Keymap) {
 932        unsafe {
 933            let app: id = msg_send![APP_CLASS, sharedApplication];
 934            let mut state = self.0.lock();
 935            let actions = &mut state.menu_actions;
 936            let menu = self.create_menu_bar(&menus, NSWindow::delegate(app), actions, keymap);
 937            drop(state);
 938            app.setMainMenu_(menu);
 939        }
 940        self.0.lock().menus = Some(menus.into_iter().map(|menu| menu.owned()).collect());
 941    }
 942
 943    fn get_menus(&self) -> Option<Vec<OwnedMenu>> {
 944        self.0.lock().menus.clone()
 945    }
 946
 947    fn set_dock_menu(&self, menu: Vec<MenuItem>, keymap: &Keymap) {
 948        unsafe {
 949            let app: id = msg_send![APP_CLASS, sharedApplication];
 950            let mut state = self.0.lock();
 951            let actions = &mut state.menu_actions;
 952            let new = self.create_dock_menu(menu, NSWindow::delegate(app), actions, keymap);
 953            if let Some(old) = state.dock_menu.replace(new) {
 954                CFRelease(old as _)
 955            }
 956        }
 957    }
 958
 959    fn add_recent_document(&self, path: &Path) {
 960        if let Some(path_str) = path.to_str() {
 961            unsafe {
 962                let document_controller: id =
 963                    msg_send![class!(NSDocumentController), sharedDocumentController];
 964                let url: id = NSURL::fileURLWithPath_(nil, ns_string(path_str));
 965                let _: () = msg_send![document_controller, noteNewRecentDocumentURL:url];
 966            }
 967        }
 968    }
 969
 970    fn path_for_auxiliary_executable(&self, name: &str) -> Result<PathBuf> {
 971        unsafe {
 972            let bundle: id = NSBundle::mainBundle();
 973            anyhow::ensure!(!bundle.is_null(), "app is not running inside a bundle");
 974            let name = ns_string(name);
 975            let url: id = msg_send![bundle, URLForAuxiliaryExecutable: name];
 976            anyhow::ensure!(!url.is_null(), "resource not found");
 977            ns_url_to_path(url)
 978        }
 979    }
 980
 981    /// Match cursor style to one of the styles available
 982    /// in macOS's [NSCursor](https://developer.apple.com/documentation/appkit/nscursor).
 983    fn set_cursor_style(&self, style: CursorStyle) {
 984        unsafe {
 985            if style == CursorStyle::None {
 986                let _: () = msg_send![class!(NSCursor), setHiddenUntilMouseMoves:YES];
 987                return;
 988            }
 989
 990            let new_cursor: id = match style {
 991                CursorStyle::Arrow => msg_send![class!(NSCursor), arrowCursor],
 992                CursorStyle::IBeam => msg_send![class!(NSCursor), IBeamCursor],
 993                CursorStyle::Crosshair => msg_send![class!(NSCursor), crosshairCursor],
 994                CursorStyle::ClosedHand => msg_send![class!(NSCursor), closedHandCursor],
 995                CursorStyle::OpenHand => msg_send![class!(NSCursor), openHandCursor],
 996                CursorStyle::PointingHand => msg_send![class!(NSCursor), pointingHandCursor],
 997                CursorStyle::ResizeLeftRight => msg_send![class!(NSCursor), resizeLeftRightCursor],
 998                CursorStyle::ResizeUpDown => msg_send![class!(NSCursor), resizeUpDownCursor],
 999                CursorStyle::ResizeLeft => msg_send![class!(NSCursor), resizeLeftCursor],
1000                CursorStyle::ResizeRight => msg_send![class!(NSCursor), resizeRightCursor],
1001                CursorStyle::ResizeColumn => msg_send![class!(NSCursor), resizeLeftRightCursor],
1002                CursorStyle::ResizeRow => msg_send![class!(NSCursor), resizeUpDownCursor],
1003                CursorStyle::ResizeUp => msg_send![class!(NSCursor), resizeUpCursor],
1004                CursorStyle::ResizeDown => msg_send![class!(NSCursor), resizeDownCursor],
1005
1006                // Undocumented, private class methods:
1007                // https://stackoverflow.com/questions/27242353/cocoa-predefined-resize-mouse-cursor
1008                CursorStyle::ResizeUpLeftDownRight => {
1009                    msg_send![class!(NSCursor), _windowResizeNorthWestSouthEastCursor]
1010                }
1011                CursorStyle::ResizeUpRightDownLeft => {
1012                    msg_send![class!(NSCursor), _windowResizeNorthEastSouthWestCursor]
1013                }
1014
1015                CursorStyle::IBeamCursorForVerticalLayout => {
1016                    msg_send![class!(NSCursor), IBeamCursorForVerticalLayout]
1017                }
1018                CursorStyle::OperationNotAllowed => {
1019                    msg_send![class!(NSCursor), operationNotAllowedCursor]
1020                }
1021                CursorStyle::DragLink => msg_send![class!(NSCursor), dragLinkCursor],
1022                CursorStyle::DragCopy => msg_send![class!(NSCursor), dragCopyCursor],
1023                CursorStyle::ContextualMenu => msg_send![class!(NSCursor), contextualMenuCursor],
1024                CursorStyle::None => unreachable!(),
1025            };
1026
1027            let old_cursor: id = msg_send![class!(NSCursor), currentCursor];
1028            if new_cursor != old_cursor {
1029                let _: () = msg_send![new_cursor, set];
1030            }
1031        }
1032    }
1033
1034    fn should_auto_hide_scrollbars(&self) -> bool {
1035        #[allow(non_upper_case_globals)]
1036        const NSScrollerStyleOverlay: NSInteger = 1;
1037
1038        unsafe {
1039            let style: NSInteger = msg_send![class!(NSScroller), preferredScrollerStyle];
1040            style == NSScrollerStyleOverlay
1041        }
1042    }
1043
1044    fn read_from_clipboard(&self) -> Option<ClipboardItem> {
1045        let state = self.0.lock();
1046        state.general_pasteboard.read()
1047    }
1048
1049    fn write_to_clipboard(&self, item: ClipboardItem) {
1050        let state = self.0.lock();
1051        state.general_pasteboard.write(item);
1052    }
1053
1054    fn read_from_find_pasteboard(&self) -> Option<ClipboardItem> {
1055        let state = self.0.lock();
1056        state.find_pasteboard.read()
1057    }
1058
1059    fn write_to_find_pasteboard(&self, item: ClipboardItem) {
1060        let state = self.0.lock();
1061        state.find_pasteboard.write(item);
1062    }
1063
1064    fn write_credentials(&self, url: &str, username: &str, password: &[u8]) -> Task<Result<()>> {
1065        let url = url.to_string();
1066        let username = username.to_string();
1067        let password = password.to_vec();
1068        self.background_executor().spawn(async move {
1069            unsafe {
1070                use security::*;
1071
1072                let url = CFString::from(url.as_str());
1073                let username = CFString::from(username.as_str());
1074                let password = CFData::from_buffer(&password);
1075
1076                // First, check if there are already credentials for the given server. If so, then
1077                // update the username and password.
1078                let mut verb = "updating";
1079                let mut query_attrs = CFMutableDictionary::with_capacity(2);
1080                query_attrs.set(kSecClass as *const _, kSecClassInternetPassword as *const _);
1081                query_attrs.set(kSecAttrServer as *const _, url.as_CFTypeRef());
1082
1083                let mut attrs = CFMutableDictionary::with_capacity(4);
1084                attrs.set(kSecClass as *const _, kSecClassInternetPassword as *const _);
1085                attrs.set(kSecAttrServer as *const _, url.as_CFTypeRef());
1086                attrs.set(kSecAttrAccount as *const _, username.as_CFTypeRef());
1087                attrs.set(kSecValueData as *const _, password.as_CFTypeRef());
1088
1089                let mut status = SecItemUpdate(
1090                    query_attrs.as_concrete_TypeRef(),
1091                    attrs.as_concrete_TypeRef(),
1092                );
1093
1094                // If there were no existing credentials for the given server, then create them.
1095                if status == errSecItemNotFound {
1096                    verb = "creating";
1097                    status = SecItemAdd(attrs.as_concrete_TypeRef(), ptr::null_mut());
1098                }
1099                anyhow::ensure!(status == errSecSuccess, "{verb} password failed: {status}");
1100            }
1101            Ok(())
1102        })
1103    }
1104
1105    fn read_credentials(&self, url: &str) -> Task<Result<Option<(String, Vec<u8>)>>> {
1106        let url = url.to_string();
1107        self.background_executor().spawn(async move {
1108            let url = CFString::from(url.as_str());
1109            let cf_true = CFBoolean::true_value().as_CFTypeRef();
1110
1111            unsafe {
1112                use security::*;
1113
1114                // Find any credentials for the given server URL.
1115                let mut attrs = CFMutableDictionary::with_capacity(5);
1116                attrs.set(kSecClass as *const _, kSecClassInternetPassword as *const _);
1117                attrs.set(kSecAttrServer as *const _, url.as_CFTypeRef());
1118                attrs.set(kSecReturnAttributes as *const _, cf_true);
1119                attrs.set(kSecReturnData as *const _, cf_true);
1120
1121                let mut result = CFTypeRef::from(ptr::null());
1122                let status = SecItemCopyMatching(attrs.as_concrete_TypeRef(), &mut result);
1123                match status {
1124                    security::errSecSuccess => {}
1125                    security::errSecItemNotFound | security::errSecUserCanceled => return Ok(None),
1126                    _ => anyhow::bail!("reading password failed: {status}"),
1127                }
1128
1129                let result = CFType::wrap_under_create_rule(result)
1130                    .downcast::<CFDictionary>()
1131                    .context("keychain item was not a dictionary")?;
1132                let username = result
1133                    .find(kSecAttrAccount as *const _)
1134                    .context("account was missing from keychain item")?;
1135                let username = CFType::wrap_under_get_rule(*username)
1136                    .downcast::<CFString>()
1137                    .context("account was not a string")?;
1138                let password = result
1139                    .find(kSecValueData as *const _)
1140                    .context("password was missing from keychain item")?;
1141                let password = CFType::wrap_under_get_rule(*password)
1142                    .downcast::<CFData>()
1143                    .context("password was not a string")?;
1144
1145                Ok(Some((username.to_string(), password.bytes().to_vec())))
1146            }
1147        })
1148    }
1149
1150    fn delete_credentials(&self, url: &str) -> Task<Result<()>> {
1151        let url = url.to_string();
1152
1153        self.background_executor().spawn(async move {
1154            unsafe {
1155                use security::*;
1156
1157                let url = CFString::from(url.as_str());
1158                let mut query_attrs = CFMutableDictionary::with_capacity(2);
1159                query_attrs.set(kSecClass as *const _, kSecClassInternetPassword as *const _);
1160                query_attrs.set(kSecAttrServer as *const _, url.as_CFTypeRef());
1161
1162                let status = SecItemDelete(query_attrs.as_concrete_TypeRef());
1163                anyhow::ensure!(status == errSecSuccess, "delete password failed: {status}");
1164            }
1165            Ok(())
1166        })
1167    }
1168}
1169
1170unsafe fn path_from_objc(path: id) -> PathBuf {
1171    let len = msg_send![path, lengthOfBytesUsingEncoding: NSUTF8StringEncoding];
1172    let bytes = unsafe { path.UTF8String() as *const u8 };
1173    let path = str::from_utf8(unsafe { slice::from_raw_parts(bytes, len) }).unwrap();
1174    PathBuf::from(path)
1175}
1176
1177unsafe fn get_mac_platform(object: &mut Object) -> &MacPlatform {
1178    unsafe {
1179        let platform_ptr: *mut c_void = *object.get_ivar(MAC_PLATFORM_IVAR);
1180        assert!(!platform_ptr.is_null());
1181        &*(platform_ptr as *const MacPlatform)
1182    }
1183}
1184
1185extern "C" fn will_finish_launching(this: &mut Object, _: Sel, _: id) {
1186    unsafe {
1187        let user_defaults: id = msg_send![class!(NSUserDefaults), standardUserDefaults];
1188
1189        // The autofill heuristic controller causes slowdown and high CPU usage.
1190        // We don't know exactly why. This disables the full heuristic controller.
1191        //
1192        // Adapted from: https://github.com/ghostty-org/ghostty/pull/8625
1193        let name = ns_string("NSAutoFillHeuristicControllerEnabled");
1194        let existing_value: id = msg_send![user_defaults, objectForKey: name];
1195        if existing_value == nil {
1196            let false_value: id = msg_send![class!(NSNumber), numberWithBool:false];
1197            let _: () = msg_send![user_defaults, setObject: false_value forKey: name];
1198        }
1199
1200        // Register kAEGetURL Apple Event handler so that URL open requests are
1201        // delivered synchronously before applicationDidFinishLaunching:, replacing
1202        // application:openURLs: which has non-deterministic timing.
1203        let event_manager: id = msg_send![class!(NSAppleEventManager), sharedAppleEventManager];
1204        let _: () = msg_send![event_manager,
1205            setEventHandler: this as id
1206            andSelector: sel!(handleGetURLEvent:withReplyEvent:)
1207            forEventClass: INTERNET_EVENT_CLASS
1208            andEventID: AE_GET_URL
1209        ];
1210    }
1211}
1212
1213extern "C" fn did_finish_launching(this: &mut Object, _: Sel, _: id) {
1214    unsafe {
1215        let app: id = msg_send![APP_CLASS, sharedApplication];
1216        app.setActivationPolicy_(NSApplicationActivationPolicyRegular);
1217
1218        let notification_center: *mut Object =
1219            msg_send![class!(NSNotificationCenter), defaultCenter];
1220        let name = ns_string("NSTextInputContextKeyboardSelectionDidChangeNotification");
1221        let _: () = msg_send![notification_center, addObserver: this as id
1222            selector: sel!(onKeyboardLayoutChange:)
1223            name: name
1224            object: nil
1225        ];
1226
1227        let thermal_name = ns_string("NSProcessInfoThermalStateDidChangeNotification");
1228        let process_info: id = msg_send![class!(NSProcessInfo), processInfo];
1229        let _: () = msg_send![notification_center, addObserver: this as id
1230            selector: sel!(onThermalStateChange:)
1231            name: thermal_name
1232            object: process_info
1233        ];
1234
1235        let platform = get_mac_platform(this);
1236        let callback = platform.0.lock().finish_launching.take();
1237        if let Some(callback) = callback {
1238            callback();
1239        }
1240    }
1241}
1242
1243extern "C" fn should_handle_reopen(this: &mut Object, _: Sel, _: id, has_open_windows: bool) {
1244    if !has_open_windows {
1245        let platform = unsafe { get_mac_platform(this) };
1246        let mut lock = platform.0.lock();
1247        if let Some(mut callback) = lock.reopen.take() {
1248            drop(lock);
1249            callback();
1250            platform.0.lock().reopen.get_or_insert(callback);
1251        }
1252    }
1253}
1254
1255extern "C" fn will_terminate(this: &mut Object, _: Sel, _: id) {
1256    let platform = unsafe { get_mac_platform(this) };
1257    let mut lock = platform.0.lock();
1258    if let Some(mut callback) = lock.quit.take() {
1259        drop(lock);
1260        callback();
1261        platform.0.lock().quit.get_or_insert(callback);
1262    }
1263}
1264
1265extern "C" fn on_keyboard_layout_change(this: &mut Object, _: Sel, _: id) {
1266    let platform = unsafe { get_mac_platform(this) };
1267    let mut lock = platform.0.lock();
1268    let keyboard_layout = MacKeyboardLayout::new();
1269    lock.keyboard_mapper = Rc::new(MacKeyboardMapper::new(keyboard_layout.id()));
1270    if let Some(mut callback) = lock.on_keyboard_layout_change.take() {
1271        drop(lock);
1272        callback();
1273        platform
1274            .0
1275            .lock()
1276            .on_keyboard_layout_change
1277            .get_or_insert(callback);
1278    }
1279}
1280
1281extern "C" fn on_thermal_state_change(this: &mut Object, _: Sel, _: id) {
1282    // Defer to the next run loop iteration to avoid re-entrant borrows of the App RefCell,
1283    // as NSNotificationCenter delivers this notification synchronously and it may fire while
1284    // the App is already borrowed (same pattern as quit() above).
1285    let platform = unsafe { get_mac_platform(this) };
1286    let platform_ptr = platform as *const MacPlatform as *mut c_void;
1287    unsafe {
1288        DispatchQueue::main().exec_async_f(platform_ptr, on_thermal_state_change);
1289    }
1290
1291    extern "C" fn on_thermal_state_change(context: *mut c_void) {
1292        let platform = unsafe { &*(context as *const MacPlatform) };
1293        let mut lock = platform.0.lock();
1294        if let Some(mut callback) = lock.on_thermal_state_change.take() {
1295            drop(lock);
1296            callback();
1297            platform
1298                .0
1299                .lock()
1300                .on_thermal_state_change
1301                .get_or_insert(callback);
1302        }
1303    }
1304}
1305
1306extern "C" fn handle_get_url_event(this: &mut Object, _: Sel, event: id, _reply: id) {
1307    unsafe {
1308        let descriptor: id = msg_send![event, paramDescriptorForKeyword: DIRECT_OBJECT_KEY];
1309        if descriptor == nil {
1310            return;
1311        }
1312        let url_string: id = msg_send![descriptor, stringValue];
1313        if url_string == nil {
1314            return;
1315        }
1316        let utf8_ptr = url_string.UTF8String() as *mut c_char;
1317        if utf8_ptr.is_null() {
1318            return;
1319        }
1320        let url_str = CStr::from_ptr(utf8_ptr);
1321        match url_str.to_str() {
1322            Ok(string) => {
1323                let urls = vec![string.to_string()];
1324                let platform = get_mac_platform(this);
1325                let mut lock = platform.0.lock();
1326                if let Some(mut callback) = lock.open_urls.take() {
1327                    drop(lock);
1328                    callback(urls);
1329                    platform.0.lock().open_urls.get_or_insert(callback);
1330                }
1331            }
1332            Err(err) => {
1333                log::error!("error converting URL to string: {}", err);
1334            }
1335        }
1336    }
1337}
1338
1339extern "C" fn handle_menu_item(this: &mut Object, _: Sel, item: id) {
1340    unsafe {
1341        let platform = get_mac_platform(this);
1342        let mut lock = platform.0.lock();
1343        if let Some(mut callback) = lock.menu_command.take() {
1344            let tag: NSInteger = msg_send![item, tag];
1345            let index = tag as usize;
1346            if let Some(action) = lock.menu_actions.get(index) {
1347                let action = action.boxed_clone();
1348                drop(lock);
1349                callback(&*action);
1350            }
1351            platform.0.lock().menu_command.get_or_insert(callback);
1352        }
1353    }
1354}
1355
1356extern "C" fn validate_menu_item(this: &mut Object, _: Sel, item: id) -> bool {
1357    unsafe {
1358        let mut result = false;
1359        let platform = get_mac_platform(this);
1360        let mut lock = platform.0.lock();
1361        if let Some(mut callback) = lock.validate_menu_command.take() {
1362            let tag: NSInteger = msg_send![item, tag];
1363            let index = tag as usize;
1364            if let Some(action) = lock.menu_actions.get(index) {
1365                let action = action.boxed_clone();
1366                drop(lock);
1367                result = callback(action.as_ref());
1368            }
1369            platform
1370                .0
1371                .lock()
1372                .validate_menu_command
1373                .get_or_insert(callback);
1374        }
1375        result
1376    }
1377}
1378
1379extern "C" fn menu_will_open(this: &mut Object, _: Sel, _: id) {
1380    unsafe {
1381        let platform = get_mac_platform(this);
1382        let mut lock = platform.0.lock();
1383        if let Some(mut callback) = lock.will_open_menu.take() {
1384            drop(lock);
1385            callback();
1386            platform.0.lock().will_open_menu.get_or_insert(callback);
1387        }
1388    }
1389}
1390
1391extern "C" fn handle_dock_menu(this: &mut Object, _: Sel, _: id) -> id {
1392    unsafe {
1393        let platform = get_mac_platform(this);
1394        let state = platform.0.lock();
1395        if let Some(id) = state.dock_menu {
1396            id
1397        } else {
1398            nil
1399        }
1400    }
1401}
1402
1403unsafe fn ns_url_to_path(url: id) -> Result<PathBuf> {
1404    let path: *mut c_char = msg_send![url, fileSystemRepresentation];
1405    anyhow::ensure!(!path.is_null(), "url is not a file path: {}", unsafe {
1406        CStr::from_ptr(url.absoluteString().UTF8String()).to_string_lossy()
1407    });
1408    Ok(PathBuf::from(OsStr::from_bytes(unsafe {
1409        CStr::from_ptr(path).to_bytes()
1410    })))
1411}
1412
1413#[link(name = "Carbon", kind = "framework")]
1414unsafe extern "C" {
1415    pub(super) fn TISCopyCurrentKeyboardLayoutInputSource() -> *mut Object;
1416    pub(super) fn TISCopyCurrentKeyboardInputSource() -> *mut Object;
1417    pub(super) fn TISGetInputSourceProperty(
1418        inputSource: *mut Object,
1419        propertyKey: *const c_void,
1420    ) -> *mut Object;
1421
1422    pub(super) fn UCKeyTranslate(
1423        keyLayoutPtr: *const ::std::os::raw::c_void,
1424        virtualKeyCode: u16,
1425        keyAction: u16,
1426        modifierKeyState: u32,
1427        keyboardType: u32,
1428        keyTranslateOptions: u32,
1429        deadKeyState: *mut u32,
1430        maxStringLength: usize,
1431        actualStringLength: *mut usize,
1432        unicodeString: *mut u16,
1433    ) -> u32;
1434    pub(super) fn LMGetKbdType() -> u16;
1435    pub(super) static kTISPropertyUnicodeKeyLayoutData: CFStringRef;
1436    pub(super) static kTISPropertyInputSourceID: CFStringRef;
1437    pub(super) static kTISPropertyLocalizedName: CFStringRef;
1438    pub(super) static kTISPropertyInputSourceIsASCIICapable: CFStringRef;
1439    pub(super) static kTISPropertyInputSourceType: CFStringRef;
1440    pub(super) static kTISTypeKeyboardInputMode: CFStringRef;
1441}
1442
1443mod security {
1444    #![allow(non_upper_case_globals)]
1445    use super::*;
1446
1447    #[link(name = "Security", kind = "framework")]
1448    unsafe extern "C" {
1449        pub static kSecClass: CFStringRef;
1450        pub static kSecClassInternetPassword: CFStringRef;
1451        pub static kSecAttrServer: CFStringRef;
1452        pub static kSecAttrAccount: CFStringRef;
1453        pub static kSecValueData: CFStringRef;
1454        pub static kSecReturnAttributes: CFStringRef;
1455        pub static kSecReturnData: CFStringRef;
1456
1457        pub fn SecItemAdd(attributes: CFDictionaryRef, result: *mut CFTypeRef) -> OSStatus;
1458        pub fn SecItemUpdate(query: CFDictionaryRef, attributes: CFDictionaryRef) -> OSStatus;
1459        pub fn SecItemDelete(query: CFDictionaryRef) -> OSStatus;
1460        pub fn SecItemCopyMatching(query: CFDictionaryRef, result: *mut CFTypeRef) -> OSStatus;
1461    }
1462
1463    pub const errSecSuccess: OSStatus = 0;
1464    pub const errSecUserCanceled: OSStatus = -128;
1465    pub const errSecItemNotFound: OSStatus = -25300;
1466}