window.rs

   1use crate::{
   2    BoolExt, DisplayLink, MacDisplay, NSRange, NSStringExt, TISCopyCurrentKeyboardInputSource,
   3    TISGetInputSourceProperty, events::platform_input_from_native,
   4    kTISPropertyInputSourceIsASCIICapable, kTISPropertyInputSourceType, kTISTypeKeyboardInputMode,
   5    ns_string, renderer,
   6};
   7#[cfg(any(test, feature = "test-support"))]
   8use anyhow::Result;
   9use block::ConcreteBlock;
  10use cocoa::{
  11    appkit::{
  12        NSAppKitVersionNumber, NSAppKitVersionNumber12_0, NSApplication, NSBackingStoreBuffered,
  13        NSColor, NSEvent, NSEventModifierFlags, NSFilenamesPboardType, NSPasteboard, NSScreen,
  14        NSView, NSViewHeightSizable, NSViewWidthSizable, NSVisualEffectMaterial,
  15        NSVisualEffectState, NSVisualEffectView, NSWindow, NSWindowButton,
  16        NSWindowCollectionBehavior, NSWindowOcclusionState, NSWindowOrderingMode,
  17        NSWindowStyleMask, NSWindowTitleVisibility,
  18    },
  19    base::{id, nil},
  20    foundation::{
  21        NSArray, NSAutoreleasePool, NSDictionary, NSFastEnumeration, NSInteger, NSNotFound,
  22        NSOperatingSystemVersion, NSPoint, NSProcessInfo, NSRect, NSSize, NSString, NSUInteger,
  23        NSUserDefaults,
  24    },
  25};
  26use dispatch2::DispatchQueue;
  27use gpui::{
  28    AnyWindowHandle, BackgroundExecutor, Bounds, Capslock, ExternalPaths, FileDropEvent,
  29    ForegroundExecutor, KeyDownEvent, Keystroke, Modifiers, ModifiersChangedEvent, MouseButton,
  30    MouseDownEvent, MouseMoveEvent, MouseUpEvent, Pixels, PlatformAtlas, PlatformDisplay,
  31    PlatformInput, PlatformInputHandler, PlatformWindow, Point, PromptButton, PromptLevel,
  32    RequestFrameOptions, SharedString, Size, SystemWindowTab, WindowAppearance,
  33    WindowBackgroundAppearance, WindowBounds, WindowControlArea, WindowKind, WindowParams, point,
  34    px, size,
  35};
  36#[cfg(any(test, feature = "test-support"))]
  37use image::RgbaImage;
  38
  39use core_foundation::base::{CFRelease, CFTypeRef};
  40use core_foundation_sys::base::CFEqual;
  41use core_foundation_sys::number::{CFBooleanGetValue, CFBooleanRef};
  42use core_graphics::display::{CGDirectDisplayID, CGPoint, CGRect};
  43use ctor::ctor;
  44use futures::channel::oneshot;
  45use objc::{
  46    class,
  47    declare::ClassDecl,
  48    msg_send,
  49    runtime::{BOOL, Class, NO, Object, Protocol, Sel, YES},
  50    sel, sel_impl,
  51};
  52use objc2_app_kit::NSBeep;
  53use parking_lot::Mutex;
  54use raw_window_handle as rwh;
  55use smallvec::SmallVec;
  56use std::{
  57    cell::Cell,
  58    ffi::{CStr, c_void},
  59    mem,
  60    ops::Range,
  61    path::PathBuf,
  62    ptr::{self, NonNull},
  63    rc::Rc,
  64    sync::{
  65        Arc, Weak,
  66        atomic::{AtomicBool, Ordering},
  67    },
  68    time::Duration,
  69};
  70use util::ResultExt;
  71
  72const WINDOW_STATE_IVAR: &str = "windowState";
  73
  74static mut WINDOW_CLASS: *const Class = ptr::null();
  75static mut PANEL_CLASS: *const Class = ptr::null();
  76static mut VIEW_CLASS: *const Class = ptr::null();
  77static mut BLURRED_VIEW_CLASS: *const Class = ptr::null();
  78
  79#[allow(non_upper_case_globals)]
  80const NSWindowStyleMaskNonactivatingPanel: NSWindowStyleMask =
  81    NSWindowStyleMask::from_bits_retain(1 << 7);
  82// WindowLevel const value ref: https://docs.rs/core-graphics2/0.4.1/src/core_graphics2/window_level.rs.html
  83#[allow(non_upper_case_globals)]
  84const NSNormalWindowLevel: NSInteger = 0;
  85#[allow(non_upper_case_globals)]
  86const NSFloatingWindowLevel: NSInteger = 3;
  87#[allow(non_upper_case_globals)]
  88const NSPopUpWindowLevel: NSInteger = 101;
  89#[allow(non_upper_case_globals)]
  90const NSTrackingMouseEnteredAndExited: NSUInteger = 0x01;
  91#[allow(non_upper_case_globals)]
  92const NSTrackingMouseMoved: NSUInteger = 0x02;
  93#[allow(non_upper_case_globals)]
  94const NSTrackingActiveAlways: NSUInteger = 0x80;
  95#[allow(non_upper_case_globals)]
  96const NSTrackingInVisibleRect: NSUInteger = 0x200;
  97#[allow(non_upper_case_globals)]
  98const NSWindowAnimationBehaviorUtilityWindow: NSInteger = 4;
  99#[allow(non_upper_case_globals)]
 100const NSViewLayerContentsRedrawDuringViewResize: NSInteger = 2;
 101// https://developer.apple.com/documentation/appkit/nsdragoperation
 102type NSDragOperation = NSUInteger;
 103#[allow(non_upper_case_globals)]
 104const NSDragOperationNone: NSDragOperation = 0;
 105#[allow(non_upper_case_globals)]
 106const NSDragOperationCopy: NSDragOperation = 1;
 107#[derive(PartialEq)]
 108pub enum UserTabbingPreference {
 109    Never,
 110    Always,
 111    InFullScreen,
 112}
 113
 114#[link(name = "CoreGraphics", kind = "framework")]
 115unsafe extern "C" {
 116    // Widely used private APIs; Apple uses them for their Terminal.app.
 117    fn CGSMainConnectionID() -> id;
 118    fn CGSSetWindowBackgroundBlurRadius(
 119        connection_id: id,
 120        window_id: NSInteger,
 121        radius: i64,
 122    ) -> i32;
 123}
 124
 125#[ctor]
 126unsafe fn build_classes() {
 127    unsafe {
 128        WINDOW_CLASS = build_window_class("GPUIWindow", class!(NSWindow));
 129        PANEL_CLASS = build_window_class("GPUIPanel", class!(NSPanel));
 130        VIEW_CLASS = {
 131            let mut decl = ClassDecl::new("GPUIView", class!(NSView)).unwrap();
 132            decl.add_ivar::<*mut c_void>(WINDOW_STATE_IVAR);
 133            unsafe {
 134                decl.add_method(sel!(dealloc), dealloc_view as extern "C" fn(&Object, Sel));
 135
 136                decl.add_method(
 137                    sel!(performKeyEquivalent:),
 138                    handle_key_equivalent as extern "C" fn(&Object, Sel, id) -> BOOL,
 139                );
 140                decl.add_method(
 141                    sel!(keyDown:),
 142                    handle_key_down as extern "C" fn(&Object, Sel, id),
 143                );
 144                decl.add_method(
 145                    sel!(keyUp:),
 146                    handle_key_up as extern "C" fn(&Object, Sel, id),
 147                );
 148                decl.add_method(
 149                    sel!(mouseDown:),
 150                    handle_view_event as extern "C" fn(&Object, Sel, id),
 151                );
 152                decl.add_method(
 153                    sel!(mouseUp:),
 154                    handle_view_event as extern "C" fn(&Object, Sel, id),
 155                );
 156                decl.add_method(
 157                    sel!(rightMouseDown:),
 158                    handle_view_event as extern "C" fn(&Object, Sel, id),
 159                );
 160                decl.add_method(
 161                    sel!(rightMouseUp:),
 162                    handle_view_event as extern "C" fn(&Object, Sel, id),
 163                );
 164                decl.add_method(
 165                    sel!(otherMouseDown:),
 166                    handle_view_event as extern "C" fn(&Object, Sel, id),
 167                );
 168                decl.add_method(
 169                    sel!(otherMouseUp:),
 170                    handle_view_event as extern "C" fn(&Object, Sel, id),
 171                );
 172                decl.add_method(
 173                    sel!(mouseMoved:),
 174                    handle_view_event as extern "C" fn(&Object, Sel, id),
 175                );
 176                decl.add_method(
 177                    sel!(pressureChangeWithEvent:),
 178                    handle_view_event as extern "C" fn(&Object, Sel, id),
 179                );
 180                decl.add_method(
 181                    sel!(mouseExited:),
 182                    handle_view_event as extern "C" fn(&Object, Sel, id),
 183                );
 184                decl.add_method(
 185                    sel!(magnifyWithEvent:),
 186                    handle_view_event as extern "C" fn(&Object, Sel, id),
 187                );
 188                decl.add_method(
 189                    sel!(mouseDragged:),
 190                    handle_view_event as extern "C" fn(&Object, Sel, id),
 191                );
 192                decl.add_method(
 193                    sel!(rightMouseDragged:),
 194                    handle_view_event as extern "C" fn(&Object, Sel, id),
 195                );
 196                decl.add_method(
 197                    sel!(otherMouseDragged:),
 198                    handle_view_event as extern "C" fn(&Object, Sel, id),
 199                );
 200                decl.add_method(
 201                    sel!(scrollWheel:),
 202                    handle_view_event as extern "C" fn(&Object, Sel, id),
 203                );
 204                decl.add_method(
 205                    sel!(swipeWithEvent:),
 206                    handle_view_event as extern "C" fn(&Object, Sel, id),
 207                );
 208                decl.add_method(
 209                    sel!(flagsChanged:),
 210                    handle_view_event as extern "C" fn(&Object, Sel, id),
 211                );
 212
 213                decl.add_method(
 214                    sel!(makeBackingLayer),
 215                    make_backing_layer as extern "C" fn(&Object, Sel) -> id,
 216                );
 217
 218                decl.add_protocol(Protocol::get("CALayerDelegate").unwrap());
 219                decl.add_method(
 220                    sel!(viewDidChangeBackingProperties),
 221                    view_did_change_backing_properties as extern "C" fn(&Object, Sel),
 222                );
 223                decl.add_method(
 224                    sel!(setFrameSize:),
 225                    set_frame_size as extern "C" fn(&Object, Sel, NSSize),
 226                );
 227                decl.add_method(
 228                    sel!(displayLayer:),
 229                    display_layer as extern "C" fn(&Object, Sel, id),
 230                );
 231
 232                decl.add_protocol(Protocol::get("NSTextInputClient").unwrap());
 233                decl.add_method(
 234                    sel!(validAttributesForMarkedText),
 235                    valid_attributes_for_marked_text as extern "C" fn(&Object, Sel) -> id,
 236                );
 237                decl.add_method(
 238                    sel!(hasMarkedText),
 239                    has_marked_text as extern "C" fn(&Object, Sel) -> BOOL,
 240                );
 241                decl.add_method(
 242                    sel!(markedRange),
 243                    marked_range as extern "C" fn(&Object, Sel) -> NSRange,
 244                );
 245                decl.add_method(
 246                    sel!(selectedRange),
 247                    selected_range as extern "C" fn(&Object, Sel) -> NSRange,
 248                );
 249                decl.add_method(
 250                    sel!(firstRectForCharacterRange:actualRange:),
 251                    first_rect_for_character_range
 252                        as extern "C" fn(&Object, Sel, NSRange, id) -> NSRect,
 253                );
 254                decl.add_method(
 255                    sel!(insertText:replacementRange:),
 256                    insert_text as extern "C" fn(&Object, Sel, id, NSRange),
 257                );
 258                decl.add_method(
 259                    sel!(setMarkedText:selectedRange:replacementRange:),
 260                    set_marked_text as extern "C" fn(&Object, Sel, id, NSRange, NSRange),
 261                );
 262                decl.add_method(sel!(unmarkText), unmark_text as extern "C" fn(&Object, Sel));
 263                decl.add_method(
 264                    sel!(attributedSubstringForProposedRange:actualRange:),
 265                    attributed_substring_for_proposed_range
 266                        as extern "C" fn(&Object, Sel, NSRange, *mut c_void) -> id,
 267                );
 268                decl.add_method(
 269                    sel!(viewDidChangeEffectiveAppearance),
 270                    view_did_change_effective_appearance as extern "C" fn(&Object, Sel),
 271                );
 272
 273                // Suppress beep on keystrokes with modifier keys.
 274                decl.add_method(
 275                    sel!(doCommandBySelector:),
 276                    do_command_by_selector as extern "C" fn(&Object, Sel, Sel),
 277                );
 278
 279                decl.add_method(
 280                    sel!(acceptsFirstMouse:),
 281                    accepts_first_mouse as extern "C" fn(&Object, Sel, id) -> BOOL,
 282                );
 283
 284                decl.add_method(
 285                    sel!(characterIndexForPoint:),
 286                    character_index_for_point as extern "C" fn(&Object, Sel, NSPoint) -> u64,
 287                );
 288            }
 289            decl.register()
 290        };
 291        BLURRED_VIEW_CLASS = {
 292            let mut decl = ClassDecl::new("BlurredView", class!(NSVisualEffectView)).unwrap();
 293            unsafe {
 294                decl.add_method(
 295                    sel!(initWithFrame:),
 296                    blurred_view_init_with_frame as extern "C" fn(&Object, Sel, NSRect) -> id,
 297                );
 298                decl.add_method(
 299                    sel!(updateLayer),
 300                    blurred_view_update_layer as extern "C" fn(&Object, Sel),
 301                );
 302                decl.register()
 303            }
 304        };
 305    }
 306}
 307
 308pub(crate) fn convert_mouse_position(position: NSPoint, window_height: Pixels) -> Point<Pixels> {
 309    point(
 310        px(position.x as f32),
 311        // macOS screen coordinates are relative to bottom left
 312        window_height - px(position.y as f32),
 313    )
 314}
 315
 316unsafe fn build_window_class(name: &'static str, superclass: &Class) -> *const Class {
 317    unsafe {
 318        let mut decl = ClassDecl::new(name, superclass).unwrap();
 319        decl.add_ivar::<*mut c_void>(WINDOW_STATE_IVAR);
 320        decl.add_method(sel!(dealloc), dealloc_window as extern "C" fn(&Object, Sel));
 321
 322        decl.add_method(
 323            sel!(canBecomeMainWindow),
 324            yes as extern "C" fn(&Object, Sel) -> BOOL,
 325        );
 326        decl.add_method(
 327            sel!(canBecomeKeyWindow),
 328            yes as extern "C" fn(&Object, Sel) -> BOOL,
 329        );
 330        decl.add_method(
 331            sel!(windowDidResize:),
 332            window_did_resize as extern "C" fn(&Object, Sel, id),
 333        );
 334        decl.add_method(
 335            sel!(windowDidChangeOcclusionState:),
 336            window_did_change_occlusion_state as extern "C" fn(&Object, Sel, id),
 337        );
 338        decl.add_method(
 339            sel!(windowWillEnterFullScreen:),
 340            window_will_enter_fullscreen as extern "C" fn(&Object, Sel, id),
 341        );
 342        decl.add_method(
 343            sel!(windowWillExitFullScreen:),
 344            window_will_exit_fullscreen as extern "C" fn(&Object, Sel, id),
 345        );
 346        decl.add_method(
 347            sel!(windowDidMove:),
 348            window_did_move as extern "C" fn(&Object, Sel, id),
 349        );
 350        decl.add_method(
 351            sel!(windowDidChangeScreen:),
 352            window_did_change_screen as extern "C" fn(&Object, Sel, id),
 353        );
 354        decl.add_method(
 355            sel!(windowDidBecomeKey:),
 356            window_did_change_key_status as extern "C" fn(&Object, Sel, id),
 357        );
 358        decl.add_method(
 359            sel!(windowDidResignKey:),
 360            window_did_change_key_status as extern "C" fn(&Object, Sel, id),
 361        );
 362        decl.add_method(
 363            sel!(windowShouldClose:),
 364            window_should_close as extern "C" fn(&Object, Sel, id) -> BOOL,
 365        );
 366
 367        decl.add_method(sel!(close), close_window as extern "C" fn(&Object, Sel));
 368
 369        decl.add_method(
 370            sel!(draggingEntered:),
 371            dragging_entered as extern "C" fn(&Object, Sel, id) -> NSDragOperation,
 372        );
 373        decl.add_method(
 374            sel!(draggingUpdated:),
 375            dragging_updated as extern "C" fn(&Object, Sel, id) -> NSDragOperation,
 376        );
 377        decl.add_method(
 378            sel!(draggingExited:),
 379            dragging_exited as extern "C" fn(&Object, Sel, id),
 380        );
 381        decl.add_method(
 382            sel!(performDragOperation:),
 383            perform_drag_operation as extern "C" fn(&Object, Sel, id) -> BOOL,
 384        );
 385        decl.add_method(
 386            sel!(concludeDragOperation:),
 387            conclude_drag_operation as extern "C" fn(&Object, Sel, id),
 388        );
 389
 390        decl.add_method(
 391            sel!(addTitlebarAccessoryViewController:),
 392            add_titlebar_accessory_view_controller as extern "C" fn(&Object, Sel, id),
 393        );
 394
 395        decl.add_method(
 396            sel!(moveTabToNewWindow:),
 397            move_tab_to_new_window as extern "C" fn(&Object, Sel, id),
 398        );
 399
 400        decl.add_method(
 401            sel!(mergeAllWindows:),
 402            merge_all_windows as extern "C" fn(&Object, Sel, id),
 403        );
 404
 405        decl.add_method(
 406            sel!(selectNextTab:),
 407            select_next_tab as extern "C" fn(&Object, Sel, id),
 408        );
 409
 410        decl.add_method(
 411            sel!(selectPreviousTab:),
 412            select_previous_tab as extern "C" fn(&Object, Sel, id),
 413        );
 414
 415        decl.add_method(
 416            sel!(toggleTabBar:),
 417            toggle_tab_bar as extern "C" fn(&Object, Sel, id),
 418        );
 419
 420        decl.register()
 421    }
 422}
 423
 424struct MacWindowState {
 425    handle: AnyWindowHandle,
 426    foreground_executor: ForegroundExecutor,
 427    background_executor: BackgroundExecutor,
 428    native_window: id,
 429    native_view: NonNull<Object>,
 430    blurred_view: Option<id>,
 431    background_appearance: WindowBackgroundAppearance,
 432    display_link: Option<DisplayLink>,
 433    renderer: renderer::Renderer,
 434    request_frame_callback: Option<Box<dyn FnMut(RequestFrameOptions)>>,
 435    event_callback: Option<Box<dyn FnMut(PlatformInput) -> gpui::DispatchEventResult>>,
 436    activate_callback: Option<Box<dyn FnMut(bool)>>,
 437    resize_callback: Option<Box<dyn FnMut(Size<Pixels>, f32)>>,
 438    moved_callback: Option<Box<dyn FnMut()>>,
 439    should_close_callback: Option<Box<dyn FnMut() -> bool>>,
 440    close_callback: Option<Box<dyn FnOnce()>>,
 441    appearance_changed_callback: Option<Box<dyn FnMut()>>,
 442    input_handler: Option<PlatformInputHandler>,
 443    last_key_equivalent: Option<KeyDownEvent>,
 444    synthetic_drag_counter: usize,
 445    traffic_light_position: Option<Point<Pixels>>,
 446    transparent_titlebar: bool,
 447    previous_modifiers_changed_event: Option<PlatformInput>,
 448    keystroke_for_do_command: Option<Keystroke>,
 449    do_command_handled: Option<bool>,
 450    external_files_dragged: bool,
 451    // Whether the next left-mouse click is also the focusing click.
 452    first_mouse: bool,
 453    fullscreen_restore_bounds: Bounds<Pixels>,
 454    move_tab_to_new_window_callback: Option<Box<dyn FnMut()>>,
 455    merge_all_windows_callback: Option<Box<dyn FnMut()>>,
 456    select_next_tab_callback: Option<Box<dyn FnMut()>>,
 457    select_previous_tab_callback: Option<Box<dyn FnMut()>>,
 458    toggle_tab_bar_callback: Option<Box<dyn FnMut()>>,
 459    activated_least_once: bool,
 460    closed: Arc<AtomicBool>,
 461    // The parent window if this window is a sheet (Dialog kind)
 462    sheet_parent: Option<id>,
 463}
 464
 465impl MacWindowState {
 466    fn move_traffic_light(&self) {
 467        if let Some(traffic_light_position) = self.traffic_light_position {
 468            if self.is_fullscreen() {
 469                // Moving traffic lights while fullscreen doesn't work,
 470                // see https://github.com/zed-industries/zed/issues/4712
 471                return;
 472            }
 473
 474            let titlebar_height = self.titlebar_height();
 475
 476            unsafe {
 477                let close_button: id = msg_send![
 478                    self.native_window,
 479                    standardWindowButton: NSWindowButton::NSWindowCloseButton
 480                ];
 481                let min_button: id = msg_send![
 482                    self.native_window,
 483                    standardWindowButton: NSWindowButton::NSWindowMiniaturizeButton
 484                ];
 485                let zoom_button: id = msg_send![
 486                    self.native_window,
 487                    standardWindowButton: NSWindowButton::NSWindowZoomButton
 488                ];
 489
 490                let mut close_button_frame: CGRect = msg_send![close_button, frame];
 491                let mut min_button_frame: CGRect = msg_send![min_button, frame];
 492                let mut zoom_button_frame: CGRect = msg_send![zoom_button, frame];
 493                let mut origin = point(
 494                    traffic_light_position.x,
 495                    titlebar_height
 496                        - traffic_light_position.y
 497                        - px(close_button_frame.size.height as f32),
 498                );
 499                let button_spacing =
 500                    px((min_button_frame.origin.x - close_button_frame.origin.x) as f32);
 501
 502                close_button_frame.origin = CGPoint::new(origin.x.into(), origin.y.into());
 503                let _: () = msg_send![close_button, setFrame: close_button_frame];
 504                origin.x += button_spacing;
 505
 506                min_button_frame.origin = CGPoint::new(origin.x.into(), origin.y.into());
 507                let _: () = msg_send![min_button, setFrame: min_button_frame];
 508                origin.x += button_spacing;
 509
 510                zoom_button_frame.origin = CGPoint::new(origin.x.into(), origin.y.into());
 511                let _: () = msg_send![zoom_button, setFrame: zoom_button_frame];
 512                origin.x += button_spacing;
 513            }
 514        }
 515    }
 516
 517    fn start_display_link(&mut self) {
 518        self.stop_display_link();
 519        unsafe {
 520            if !self
 521                .native_window
 522                .occlusionState()
 523                .contains(NSWindowOcclusionState::NSWindowOcclusionStateVisible)
 524            {
 525                return;
 526            }
 527        }
 528        let display_id = unsafe { display_id_for_screen(self.native_window.screen()) };
 529        if let Some(mut display_link) =
 530            DisplayLink::new(display_id, self.native_view.as_ptr() as *mut c_void, step).log_err()
 531        {
 532            display_link.start().log_err();
 533            self.display_link = Some(display_link);
 534        }
 535    }
 536
 537    fn stop_display_link(&mut self) {
 538        self.display_link = None;
 539    }
 540
 541    fn is_maximized(&self) -> bool {
 542        fn rect_to_size(rect: NSRect) -> Size<Pixels> {
 543            let NSSize { width, height } = rect.size;
 544            size(width.into(), height.into())
 545        }
 546
 547        unsafe {
 548            let bounds = self.bounds();
 549            let screen_size = rect_to_size(self.native_window.screen().visibleFrame());
 550            bounds.size == screen_size
 551        }
 552    }
 553
 554    fn is_fullscreen(&self) -> bool {
 555        unsafe {
 556            let style_mask = self.native_window.styleMask();
 557            style_mask.contains(NSWindowStyleMask::NSFullScreenWindowMask)
 558        }
 559    }
 560
 561    fn bounds(&self) -> Bounds<Pixels> {
 562        let mut window_frame = unsafe { NSWindow::frame(self.native_window) };
 563        let screen = unsafe { NSWindow::screen(self.native_window) };
 564        if screen == nil {
 565            return Bounds::new(point(px(0.), px(0.)), gpui::DEFAULT_WINDOW_SIZE);
 566        }
 567        let screen_frame = unsafe { NSScreen::frame(screen) };
 568
 569        // Flip the y coordinate to be top-left origin
 570        window_frame.origin.y =
 571            screen_frame.size.height - window_frame.origin.y - window_frame.size.height;
 572
 573        Bounds::new(
 574            point(
 575                px((window_frame.origin.x - screen_frame.origin.x) as f32),
 576                px((window_frame.origin.y + screen_frame.origin.y) as f32),
 577            ),
 578            size(
 579                px(window_frame.size.width as f32),
 580                px(window_frame.size.height as f32),
 581            ),
 582        )
 583    }
 584
 585    fn content_size(&self) -> Size<Pixels> {
 586        let NSSize { width, height, .. } =
 587            unsafe { NSView::frame(self.native_window.contentView()) }.size;
 588        size(px(width as f32), px(height as f32))
 589    }
 590
 591    fn scale_factor(&self) -> f32 {
 592        get_scale_factor(self.native_window)
 593    }
 594
 595    fn titlebar_height(&self) -> Pixels {
 596        unsafe {
 597            let frame = NSWindow::frame(self.native_window);
 598            let content_layout_rect: CGRect = msg_send![self.native_window, contentLayoutRect];
 599            px((frame.size.height - content_layout_rect.size.height) as f32)
 600        }
 601    }
 602
 603    fn window_bounds(&self) -> WindowBounds {
 604        if self.is_fullscreen() {
 605            WindowBounds::Fullscreen(self.fullscreen_restore_bounds)
 606        } else {
 607            WindowBounds::Windowed(self.bounds())
 608        }
 609    }
 610}
 611
 612unsafe impl Send for MacWindowState {}
 613
 614pub(crate) struct MacWindow(Arc<Mutex<MacWindowState>>);
 615
 616impl MacWindow {
 617    pub fn open(
 618        handle: AnyWindowHandle,
 619        WindowParams {
 620            bounds,
 621            titlebar,
 622            kind,
 623            is_movable,
 624            is_resizable,
 625            is_minimizable,
 626            focus,
 627            show,
 628            display_id,
 629            window_min_size,
 630            tabbing_identifier,
 631        }: WindowParams,
 632        foreground_executor: ForegroundExecutor,
 633        background_executor: BackgroundExecutor,
 634        renderer_context: renderer::Context,
 635    ) -> Self {
 636        unsafe {
 637            let pool = NSAutoreleasePool::new(nil);
 638
 639            let allows_automatic_window_tabbing = tabbing_identifier.is_some();
 640            if allows_automatic_window_tabbing {
 641                let () = msg_send![class!(NSWindow), setAllowsAutomaticWindowTabbing: YES];
 642            } else {
 643                let () = msg_send![class!(NSWindow), setAllowsAutomaticWindowTabbing: NO];
 644            }
 645
 646            let mut style_mask;
 647            if let Some(titlebar) = titlebar.as_ref() {
 648                style_mask =
 649                    NSWindowStyleMask::NSClosableWindowMask | NSWindowStyleMask::NSTitledWindowMask;
 650
 651                if is_resizable {
 652                    style_mask |= NSWindowStyleMask::NSResizableWindowMask;
 653                }
 654
 655                if is_minimizable {
 656                    style_mask |= NSWindowStyleMask::NSMiniaturizableWindowMask;
 657                }
 658
 659                if titlebar.appears_transparent {
 660                    style_mask |= NSWindowStyleMask::NSFullSizeContentViewWindowMask;
 661                }
 662            } else {
 663                style_mask = NSWindowStyleMask::NSTitledWindowMask
 664                    | NSWindowStyleMask::NSFullSizeContentViewWindowMask;
 665            }
 666
 667            let native_window: id = match kind {
 668                WindowKind::Normal => {
 669                    msg_send![WINDOW_CLASS, alloc]
 670                }
 671                WindowKind::PopUp => {
 672                    style_mask |= NSWindowStyleMaskNonactivatingPanel;
 673                    msg_send![PANEL_CLASS, alloc]
 674                }
 675                WindowKind::Floating | WindowKind::Dialog => {
 676                    msg_send![PANEL_CLASS, alloc]
 677                }
 678            };
 679
 680            let display = display_id
 681                .and_then(MacDisplay::find_by_id)
 682                .unwrap_or_else(MacDisplay::primary);
 683
 684            let mut target_screen = nil;
 685            let mut screen_frame = None;
 686
 687            let screens = NSScreen::screens(nil);
 688            let count: u64 = cocoa::foundation::NSArray::count(screens);
 689            for i in 0..count {
 690                let screen = cocoa::foundation::NSArray::objectAtIndex(screens, i);
 691                let frame = NSScreen::frame(screen);
 692                let display_id = display_id_for_screen(screen);
 693                if display_id == display.0 {
 694                    screen_frame = Some(frame);
 695                    target_screen = screen;
 696                }
 697            }
 698
 699            let screen_frame = screen_frame.unwrap_or_else(|| {
 700                let screen = NSScreen::mainScreen(nil);
 701                target_screen = screen;
 702                NSScreen::frame(screen)
 703            });
 704
 705            let window_rect = NSRect::new(
 706                NSPoint::new(
 707                    screen_frame.origin.x + bounds.origin.x.as_f32() as f64,
 708                    screen_frame.origin.y
 709                        + (display.bounds().size.height - bounds.origin.y).as_f32() as f64,
 710                ),
 711                NSSize::new(
 712                    bounds.size.width.as_f32() as f64,
 713                    bounds.size.height.as_f32() as f64,
 714                ),
 715            );
 716
 717            let native_window = native_window.initWithContentRect_styleMask_backing_defer_screen_(
 718                window_rect,
 719                style_mask,
 720                NSBackingStoreBuffered,
 721                NO,
 722                target_screen,
 723            );
 724            assert!(!native_window.is_null());
 725            let () = msg_send![
 726                native_window,
 727                registerForDraggedTypes:
 728                    NSArray::arrayWithObject(nil, NSFilenamesPboardType)
 729            ];
 730            let () = msg_send![
 731                native_window,
 732                setReleasedWhenClosed: NO
 733            ];
 734
 735            let content_view = native_window.contentView();
 736            let native_view: id = msg_send![VIEW_CLASS, alloc];
 737            let native_view = NSView::initWithFrame_(native_view, NSView::bounds(content_view));
 738            assert!(!native_view.is_null());
 739
 740            let mut window = Self(Arc::new(Mutex::new(MacWindowState {
 741                handle,
 742                foreground_executor,
 743                background_executor,
 744                native_window,
 745                native_view: NonNull::new_unchecked(native_view),
 746                blurred_view: None,
 747                background_appearance: WindowBackgroundAppearance::Opaque,
 748                display_link: None,
 749                renderer: renderer::new_renderer(
 750                    renderer_context,
 751                    native_window as *mut _,
 752                    native_view as *mut _,
 753                    bounds.size.map(|pixels| pixels.as_f32()),
 754                    false,
 755                ),
 756                request_frame_callback: None,
 757                event_callback: None,
 758                activate_callback: None,
 759                resize_callback: None,
 760                moved_callback: None,
 761                should_close_callback: None,
 762                close_callback: None,
 763                appearance_changed_callback: None,
 764                input_handler: None,
 765                last_key_equivalent: None,
 766                synthetic_drag_counter: 0,
 767                traffic_light_position: titlebar
 768                    .as_ref()
 769                    .and_then(|titlebar| titlebar.traffic_light_position),
 770                transparent_titlebar: titlebar
 771                    .as_ref()
 772                    .is_none_or(|titlebar| titlebar.appears_transparent),
 773                previous_modifiers_changed_event: None,
 774                keystroke_for_do_command: None,
 775                do_command_handled: None,
 776                external_files_dragged: false,
 777                first_mouse: false,
 778                fullscreen_restore_bounds: Bounds::default(),
 779                move_tab_to_new_window_callback: None,
 780                merge_all_windows_callback: None,
 781                select_next_tab_callback: None,
 782                select_previous_tab_callback: None,
 783                toggle_tab_bar_callback: None,
 784                activated_least_once: false,
 785                closed: Arc::new(AtomicBool::new(false)),
 786                sheet_parent: None,
 787            })));
 788
 789            (*native_window).set_ivar(
 790                WINDOW_STATE_IVAR,
 791                Arc::into_raw(window.0.clone()) as *const c_void,
 792            );
 793            native_window.setDelegate_(native_window);
 794            (*native_view).set_ivar(
 795                WINDOW_STATE_IVAR,
 796                Arc::into_raw(window.0.clone()) as *const c_void,
 797            );
 798
 799            if let Some(title) = titlebar
 800                .as_ref()
 801                .and_then(|t| t.title.as_ref().map(AsRef::as_ref))
 802            {
 803                window.set_title(title);
 804            }
 805
 806            native_window.setMovable_(is_movable as BOOL);
 807
 808            if let Some(window_min_size) = window_min_size {
 809                native_window.setContentMinSize_(NSSize {
 810                    width: window_min_size.width.to_f64(),
 811                    height: window_min_size.height.to_f64(),
 812                });
 813            }
 814
 815            if titlebar.is_none_or(|titlebar| titlebar.appears_transparent) {
 816                native_window.setTitlebarAppearsTransparent_(YES);
 817                native_window.setTitleVisibility_(NSWindowTitleVisibility::NSWindowTitleHidden);
 818            }
 819
 820            native_view.setAutoresizingMask_(NSViewWidthSizable | NSViewHeightSizable);
 821            native_view.setWantsBestResolutionOpenGLSurface_(YES);
 822
 823            // From winit crate: On Mojave, views automatically become layer-backed shortly after
 824            // being added to a native_window. Changing the layer-backedness of a view breaks the
 825            // association between the view and its associated OpenGL context. To work around this,
 826            // on we explicitly make the view layer-backed up front so that AppKit doesn't do it
 827            // itself and break the association with its context.
 828            native_view.setWantsLayer(YES);
 829            let _: () = msg_send![
 830            native_view,
 831            setLayerContentsRedrawPolicy: NSViewLayerContentsRedrawDuringViewResize
 832            ];
 833
 834            content_view.addSubview_(native_view.autorelease());
 835            native_window.makeFirstResponder_(native_view);
 836
 837            let app: id = NSApplication::sharedApplication(nil);
 838            let main_window: id = msg_send![app, mainWindow];
 839            let mut sheet_parent = None;
 840
 841            match kind {
 842                WindowKind::Normal | WindowKind::Floating => {
 843                    if kind == WindowKind::Floating {
 844                        // Let the window float keep above normal windows.
 845                        native_window.setLevel_(NSFloatingWindowLevel);
 846                    } else {
 847                        native_window.setLevel_(NSNormalWindowLevel);
 848                    }
 849                    native_window.setAcceptsMouseMovedEvents_(YES);
 850
 851                    if let Some(tabbing_identifier) = tabbing_identifier {
 852                        let tabbing_id = ns_string(tabbing_identifier.as_str());
 853                        let _: () = msg_send![native_window, setTabbingIdentifier: tabbing_id];
 854                    } else {
 855                        let _: () = msg_send![native_window, setTabbingIdentifier:nil];
 856                    }
 857                }
 858                WindowKind::PopUp => {
 859                    // Use a tracking area to allow receiving MouseMoved events even when
 860                    // the window or application aren't active, which is often the case
 861                    // e.g. for notification windows.
 862                    let tracking_area: id = msg_send![class!(NSTrackingArea), alloc];
 863                    let _: () = msg_send![
 864                        tracking_area,
 865                        initWithRect: NSRect::new(NSPoint::new(0., 0.), NSSize::new(0., 0.))
 866                        options: NSTrackingMouseEnteredAndExited | NSTrackingMouseMoved | NSTrackingActiveAlways | NSTrackingInVisibleRect
 867                        owner: native_view
 868                        userInfo: nil
 869                    ];
 870                    let _: () =
 871                        msg_send![native_view, addTrackingArea: tracking_area.autorelease()];
 872
 873                    native_window.setLevel_(NSPopUpWindowLevel);
 874                    let _: () = msg_send![
 875                        native_window,
 876                        setAnimationBehavior: NSWindowAnimationBehaviorUtilityWindow
 877                    ];
 878                    native_window.setCollectionBehavior_(
 879                        NSWindowCollectionBehavior::NSWindowCollectionBehaviorCanJoinAllSpaces |
 880                        NSWindowCollectionBehavior::NSWindowCollectionBehaviorFullScreenAuxiliary
 881                    );
 882                }
 883                WindowKind::Dialog => {
 884                    if !main_window.is_null() {
 885                        let parent = {
 886                            let active_sheet: id = msg_send![main_window, attachedSheet];
 887                            if active_sheet.is_null() {
 888                                main_window
 889                            } else {
 890                                active_sheet
 891                            }
 892                        };
 893                        let _: () =
 894                            msg_send![parent, beginSheet: native_window completionHandler: nil];
 895                        sheet_parent = Some(parent);
 896                    }
 897                }
 898            }
 899
 900            if allows_automatic_window_tabbing
 901                && !main_window.is_null()
 902                && main_window != native_window
 903            {
 904                let main_window_is_fullscreen = main_window
 905                    .styleMask()
 906                    .contains(NSWindowStyleMask::NSFullScreenWindowMask);
 907                let user_tabbing_preference = Self::get_user_tabbing_preference()
 908                    .unwrap_or(UserTabbingPreference::InFullScreen);
 909                let should_add_as_tab = user_tabbing_preference == UserTabbingPreference::Always
 910                    || user_tabbing_preference == UserTabbingPreference::InFullScreen
 911                        && main_window_is_fullscreen;
 912
 913                if should_add_as_tab {
 914                    let main_window_can_tab: BOOL =
 915                        msg_send![main_window, respondsToSelector: sel!(addTabbedWindow:ordered:)];
 916                    let main_window_visible: BOOL = msg_send![main_window, isVisible];
 917
 918                    if main_window_can_tab == YES && main_window_visible == YES {
 919                        let _: () = msg_send![main_window, addTabbedWindow: native_window ordered: NSWindowOrderingMode::NSWindowAbove];
 920
 921                        // Ensure the window is visible immediately after adding the tab, since the tab bar is updated with a new entry at this point.
 922                        // Note: Calling orderFront here can break fullscreen mode (makes fullscreen windows exit fullscreen), so only do this if the main window is not fullscreen.
 923                        if !main_window_is_fullscreen {
 924                            let _: () = msg_send![native_window, orderFront: nil];
 925                        }
 926                    }
 927                }
 928            }
 929
 930            if focus && show {
 931                native_window.makeKeyAndOrderFront_(nil);
 932            } else if show {
 933                native_window.orderFront_(nil);
 934            }
 935
 936            // Set the initial position of the window to the specified origin.
 937            // Although we already specified the position using `initWithContentRect_styleMask_backing_defer_screen_`,
 938            // the window position might be incorrect if the main screen (the screen that contains the window that has focus)
 939            //  is different from the primary screen.
 940            NSWindow::setFrameTopLeftPoint_(native_window, window_rect.origin);
 941            {
 942                let mut window_state = window.0.lock();
 943                window_state.move_traffic_light();
 944                window_state.sheet_parent = sheet_parent;
 945            }
 946
 947            pool.drain();
 948
 949            window
 950        }
 951    }
 952
 953    pub fn active_window() -> Option<AnyWindowHandle> {
 954        unsafe {
 955            let app = NSApplication::sharedApplication(nil);
 956            let main_window: id = msg_send![app, mainWindow];
 957            if main_window.is_null() {
 958                return None;
 959            }
 960
 961            if msg_send![main_window, isKindOfClass: WINDOW_CLASS] {
 962                let handle = get_window_state(&*main_window).lock().handle;
 963                Some(handle)
 964            } else {
 965                None
 966            }
 967        }
 968    }
 969
 970    pub fn ordered_windows() -> Vec<AnyWindowHandle> {
 971        unsafe {
 972            let app = NSApplication::sharedApplication(nil);
 973            let windows: id = msg_send![app, orderedWindows];
 974            let count: NSUInteger = msg_send![windows, count];
 975
 976            let mut window_handles = Vec::new();
 977            for i in 0..count {
 978                let window: id = msg_send![windows, objectAtIndex:i];
 979                if msg_send![window, isKindOfClass: WINDOW_CLASS] {
 980                    let handle = get_window_state(&*window).lock().handle;
 981                    window_handles.push(handle);
 982                }
 983            }
 984
 985            window_handles
 986        }
 987    }
 988
 989    pub fn get_user_tabbing_preference() -> Option<UserTabbingPreference> {
 990        unsafe {
 991            let defaults: id = NSUserDefaults::standardUserDefaults();
 992            let domain = ns_string("NSGlobalDomain");
 993            let key = ns_string("AppleWindowTabbingMode");
 994
 995            let dict: id = msg_send![defaults, persistentDomainForName: domain];
 996            let value: id = if !dict.is_null() {
 997                msg_send![dict, objectForKey: key]
 998            } else {
 999                nil
1000            };
1001
1002            let value_str = if !value.is_null() {
1003                CStr::from_ptr(NSString::UTF8String(value)).to_string_lossy()
1004            } else {
1005                "".into()
1006            };
1007
1008            match value_str.as_ref() {
1009                "manual" => Some(UserTabbingPreference::Never),
1010                "always" => Some(UserTabbingPreference::Always),
1011                _ => Some(UserTabbingPreference::InFullScreen),
1012            }
1013        }
1014    }
1015}
1016
1017impl Drop for MacWindow {
1018    fn drop(&mut self) {
1019        let mut this = self.0.lock();
1020        this.renderer.destroy();
1021        let window = this.native_window;
1022        let sheet_parent = this.sheet_parent.take();
1023        this.display_link.take();
1024        unsafe {
1025            this.native_window.setDelegate_(nil);
1026        }
1027        this.input_handler.take();
1028        this.foreground_executor
1029            .spawn(async move {
1030                unsafe {
1031                    if let Some(parent) = sheet_parent {
1032                        let _: () = msg_send![parent, endSheet: window];
1033                    }
1034                    window.close();
1035                    window.autorelease();
1036                }
1037            })
1038            .detach();
1039    }
1040}
1041
1042/// Calls `f` if the window is not closed.
1043///
1044/// This should be used when spawning foreground tasks interacting with the
1045/// window, as some messages will end hard faulting if dispatched to no longer
1046/// valid window handles.
1047fn if_window_not_closed(closed: Arc<AtomicBool>, f: impl FnOnce()) {
1048    if !closed.load(Ordering::Acquire) {
1049        f();
1050    }
1051}
1052
1053impl PlatformWindow for MacWindow {
1054    fn bounds(&self) -> Bounds<Pixels> {
1055        self.0.as_ref().lock().bounds()
1056    }
1057
1058    fn window_bounds(&self) -> WindowBounds {
1059        self.0.as_ref().lock().window_bounds()
1060    }
1061
1062    fn is_maximized(&self) -> bool {
1063        self.0.as_ref().lock().is_maximized()
1064    }
1065
1066    fn content_size(&self) -> Size<Pixels> {
1067        self.0.as_ref().lock().content_size()
1068    }
1069
1070    fn resize(&mut self, size: Size<Pixels>) {
1071        let this = self.0.lock();
1072        let window = this.native_window;
1073        let closed = this.closed.clone();
1074        this.foreground_executor
1075            .spawn(async move {
1076                if_window_not_closed(closed, || unsafe {
1077                    window.setContentSize_(NSSize {
1078                        width: size.width.as_f32() as f64,
1079                        height: size.height.as_f32() as f64,
1080                    });
1081                })
1082            })
1083            .detach();
1084    }
1085
1086    fn merge_all_windows(&self) {
1087        let native_window = self.0.lock().native_window;
1088        extern "C" fn merge_windows_async(context: *mut std::ffi::c_void) {
1089            unsafe {
1090                let native_window = context as id;
1091                let _: () = msg_send![native_window, mergeAllWindows:nil];
1092            }
1093        }
1094
1095        unsafe {
1096            DispatchQueue::main()
1097                .exec_async_f(native_window as *mut std::ffi::c_void, merge_windows_async);
1098        }
1099    }
1100
1101    fn move_tab_to_new_window(&self) {
1102        let native_window = self.0.lock().native_window;
1103        extern "C" fn move_tab_async(context: *mut std::ffi::c_void) {
1104            unsafe {
1105                let native_window = context as id;
1106                let _: () = msg_send![native_window, moveTabToNewWindow:nil];
1107                let _: () = msg_send![native_window, makeKeyAndOrderFront: nil];
1108            }
1109        }
1110
1111        unsafe {
1112            DispatchQueue::main()
1113                .exec_async_f(native_window as *mut std::ffi::c_void, move_tab_async);
1114        }
1115    }
1116
1117    fn toggle_window_tab_overview(&self) {
1118        let native_window = self.0.lock().native_window;
1119        unsafe {
1120            let _: () = msg_send![native_window, toggleTabOverview:nil];
1121        }
1122    }
1123
1124    fn set_tabbing_identifier(&self, tabbing_identifier: Option<String>) {
1125        let native_window = self.0.lock().native_window;
1126        unsafe {
1127            let allows_automatic_window_tabbing = tabbing_identifier.is_some();
1128            if allows_automatic_window_tabbing {
1129                let () = msg_send![class!(NSWindow), setAllowsAutomaticWindowTabbing: YES];
1130            } else {
1131                let () = msg_send![class!(NSWindow), setAllowsAutomaticWindowTabbing: NO];
1132            }
1133
1134            if let Some(tabbing_identifier) = tabbing_identifier {
1135                let tabbing_id = ns_string(tabbing_identifier.as_str());
1136                let _: () = msg_send![native_window, setTabbingIdentifier: tabbing_id];
1137            } else {
1138                let _: () = msg_send![native_window, setTabbingIdentifier:nil];
1139            }
1140        }
1141    }
1142
1143    fn scale_factor(&self) -> f32 {
1144        self.0.as_ref().lock().scale_factor()
1145    }
1146
1147    fn appearance(&self) -> WindowAppearance {
1148        unsafe {
1149            let appearance: id = msg_send![self.0.lock().native_window, effectiveAppearance];
1150            crate::window_appearance::window_appearance_from_native(appearance)
1151        }
1152    }
1153
1154    fn display(&self) -> Option<Rc<dyn PlatformDisplay>> {
1155        unsafe {
1156            let screen = self.0.lock().native_window.screen();
1157            if screen.is_null() {
1158                return None;
1159            }
1160            let device_description: id = msg_send![screen, deviceDescription];
1161            let screen_number: id =
1162                NSDictionary::valueForKey_(device_description, ns_string("NSScreenNumber"));
1163
1164            let screen_number: u32 = msg_send![screen_number, unsignedIntValue];
1165
1166            Some(Rc::new(MacDisplay(screen_number)))
1167        }
1168    }
1169
1170    fn mouse_position(&self) -> Point<Pixels> {
1171        let position = unsafe {
1172            self.0
1173                .lock()
1174                .native_window
1175                .mouseLocationOutsideOfEventStream()
1176        };
1177        convert_mouse_position(position, self.content_size().height)
1178    }
1179
1180    fn modifiers(&self) -> Modifiers {
1181        unsafe {
1182            let modifiers: NSEventModifierFlags = msg_send![class!(NSEvent), modifierFlags];
1183
1184            let control = modifiers.contains(NSEventModifierFlags::NSControlKeyMask);
1185            let alt = modifiers.contains(NSEventModifierFlags::NSAlternateKeyMask);
1186            let shift = modifiers.contains(NSEventModifierFlags::NSShiftKeyMask);
1187            let command = modifiers.contains(NSEventModifierFlags::NSCommandKeyMask);
1188            let function = modifiers.contains(NSEventModifierFlags::NSFunctionKeyMask);
1189
1190            Modifiers {
1191                control,
1192                alt,
1193                shift,
1194                platform: command,
1195                function,
1196            }
1197        }
1198    }
1199
1200    fn capslock(&self) -> Capslock {
1201        unsafe {
1202            let modifiers: NSEventModifierFlags = msg_send![class!(NSEvent), modifierFlags];
1203
1204            Capslock {
1205                on: modifiers.contains(NSEventModifierFlags::NSAlphaShiftKeyMask),
1206            }
1207        }
1208    }
1209
1210    fn set_input_handler(&mut self, input_handler: PlatformInputHandler) {
1211        self.0.as_ref().lock().input_handler = Some(input_handler);
1212    }
1213
1214    fn take_input_handler(&mut self) -> Option<PlatformInputHandler> {
1215        self.0.as_ref().lock().input_handler.take()
1216    }
1217
1218    fn prompt(
1219        &self,
1220        level: PromptLevel,
1221        msg: &str,
1222        detail: Option<&str>,
1223        answers: &[PromptButton],
1224    ) -> Option<oneshot::Receiver<usize>> {
1225        // macOs applies overrides to modal window buttons after they are added.
1226        // Two most important for this logic are:
1227        // * Buttons with "Cancel" title will be displayed as the last buttons in the modal
1228        // * Last button added to the modal via `addButtonWithTitle` stays focused
1229        // * Focused buttons react on "space"/" " keypresses
1230        // * Usage of `keyEquivalent`, `makeFirstResponder` or `setInitialFirstResponder` does not change the focus
1231        //
1232        // See also https://developer.apple.com/documentation/appkit/nsalert/1524532-addbuttonwithtitle#discussion
1233        // ```
1234        // By default, the first button has a key equivalent of Return,
1235        // any button with a title of “Cancel” has a key equivalent of Escape,
1236        // and any button with the title “Don’t Save” has a key equivalent of Command-D (but only if it’s not the first button).
1237        // ```
1238        //
1239        // To avoid situations when the last element added is "Cancel" and it gets the focus
1240        // (hence stealing both ESC and Space shortcuts), we find and add one non-Cancel button
1241        // last, so it gets focus and a Space shortcut.
1242        // This way, "Save this file? Yes/No/Cancel"-ish modals will get all three buttons mapped with a key.
1243        let latest_non_cancel_label = answers
1244            .iter()
1245            .enumerate()
1246            .rev()
1247            .find(|(_, label)| !label.is_cancel())
1248            .filter(|&(label_index, _)| label_index > 0);
1249
1250        unsafe {
1251            let alert: id = msg_send![class!(NSAlert), alloc];
1252            let alert: id = msg_send![alert, init];
1253            let alert_style = match level {
1254                PromptLevel::Info => 1,
1255                PromptLevel::Warning => 0,
1256                PromptLevel::Critical => 2,
1257            };
1258            let _: () = msg_send![alert, setAlertStyle: alert_style];
1259            let _: () = msg_send![alert, setMessageText: ns_string(msg)];
1260            if let Some(detail) = detail {
1261                let _: () = msg_send![alert, setInformativeText: ns_string(detail)];
1262            }
1263
1264            for (ix, answer) in answers
1265                .iter()
1266                .enumerate()
1267                .filter(|&(ix, _)| Some(ix) != latest_non_cancel_label.map(|(ix, _)| ix))
1268            {
1269                let button: id = msg_send![alert, addButtonWithTitle: ns_string(answer.label())];
1270                let _: () = msg_send![button, setTag: ix as NSInteger];
1271
1272                if answer.is_cancel() {
1273                    // Bind Escape Key to Cancel Button
1274                    if let Some(key) = std::char::from_u32(crate::events::ESCAPE_KEY as u32) {
1275                        let _: () =
1276                            msg_send![button, setKeyEquivalent: ns_string(&key.to_string())];
1277                    }
1278                }
1279            }
1280            if let Some((ix, answer)) = latest_non_cancel_label {
1281                let button: id = msg_send![alert, addButtonWithTitle: ns_string(answer.label())];
1282                let _: () = msg_send![button, setTag: ix as NSInteger];
1283            }
1284
1285            let (done_tx, done_rx) = oneshot::channel();
1286            let done_tx = Cell::new(Some(done_tx));
1287            let block = ConcreteBlock::new(move |answer: NSInteger| {
1288                let _: () = msg_send![alert, release];
1289                if let Some(done_tx) = done_tx.take() {
1290                    let _ = done_tx.send(answer.try_into().unwrap());
1291                }
1292            });
1293            let block = block.copy();
1294            let lock = self.0.lock();
1295            let native_window = lock.native_window;
1296            let closed = lock.closed.clone();
1297            let executor = lock.foreground_executor.clone();
1298            executor
1299                .spawn(async move {
1300                    if !closed.load(Ordering::Acquire) {
1301                        let _: () = msg_send![
1302                            alert,
1303                            beginSheetModalForWindow: native_window
1304                            completionHandler: block
1305                        ];
1306                    } else {
1307                        let _: () = msg_send![alert, release];
1308                    }
1309                })
1310                .detach();
1311
1312            Some(done_rx)
1313        }
1314    }
1315
1316    fn activate(&self) {
1317        let lock = self.0.lock();
1318        let window = lock.native_window;
1319        let closed = lock.closed.clone();
1320        let executor = lock.foreground_executor.clone();
1321        executor
1322            .spawn(async move {
1323                if !closed.load(Ordering::Acquire) {
1324                    unsafe {
1325                        let _: () = msg_send![window, makeKeyAndOrderFront: nil];
1326                    }
1327                }
1328            })
1329            .detach();
1330    }
1331
1332    fn is_active(&self) -> bool {
1333        unsafe { self.0.lock().native_window.isKeyWindow() == YES }
1334    }
1335
1336    // is_hovered is unused on macOS. See Window::is_window_hovered.
1337    fn is_hovered(&self) -> bool {
1338        false
1339    }
1340
1341    fn set_title(&mut self, title: &str) {
1342        unsafe {
1343            let app = NSApplication::sharedApplication(nil);
1344            let window = self.0.lock().native_window;
1345            let title = ns_string(title);
1346            let _: () = msg_send![app, changeWindowsItem:window title:title filename:false];
1347            let _: () = msg_send![window, setTitle: title];
1348            self.0.lock().move_traffic_light();
1349        }
1350    }
1351
1352    fn get_title(&self) -> String {
1353        unsafe {
1354            let title: id = msg_send![self.0.lock().native_window, title];
1355            if title.is_null() {
1356                "".to_string()
1357            } else {
1358                title.to_str().to_string()
1359            }
1360        }
1361    }
1362
1363    fn set_app_id(&mut self, _app_id: &str) {}
1364
1365    fn set_background_appearance(&self, background_appearance: WindowBackgroundAppearance) {
1366        let mut this = self.0.as_ref().lock();
1367        this.background_appearance = background_appearance;
1368
1369        let opaque = background_appearance == WindowBackgroundAppearance::Opaque;
1370        this.renderer.update_transparency(!opaque);
1371
1372        unsafe {
1373            this.native_window.setOpaque_(opaque as BOOL);
1374            let background_color = if opaque {
1375                NSColor::colorWithSRGBRed_green_blue_alpha_(nil, 0f64, 0f64, 0f64, 1f64)
1376            } else {
1377                // Not using `+[NSColor clearColor]` to avoid broken shadow.
1378                NSColor::colorWithSRGBRed_green_blue_alpha_(nil, 0f64, 0f64, 0f64, 0.0001)
1379            };
1380            this.native_window.setBackgroundColor_(background_color);
1381
1382            if NSAppKitVersionNumber < NSAppKitVersionNumber12_0 {
1383                // Whether `-[NSVisualEffectView respondsToSelector:@selector(_updateProxyLayer)]`.
1384                // On macOS Catalina/Big Sur `NSVisualEffectView` doesn’t own concrete sublayers
1385                // but uses a `CAProxyLayer`. Use the legacy WindowServer API.
1386                let blur_radius = if background_appearance == WindowBackgroundAppearance::Blurred {
1387                    80
1388                } else {
1389                    0
1390                };
1391
1392                let window_number = this.native_window.windowNumber();
1393                CGSSetWindowBackgroundBlurRadius(CGSMainConnectionID(), window_number, blur_radius);
1394            } else {
1395                // On newer macOS `NSVisualEffectView` manages the effect layer directly. Using it
1396                // could have a better performance (it downsamples the backdrop) and more control
1397                // over the effect layer.
1398                if background_appearance != WindowBackgroundAppearance::Blurred {
1399                    if let Some(blur_view) = this.blurred_view {
1400                        NSView::removeFromSuperview(blur_view);
1401                        this.blurred_view = None;
1402                    }
1403                } else if this.blurred_view.is_none() {
1404                    let content_view = this.native_window.contentView();
1405                    let frame = NSView::bounds(content_view);
1406                    let mut blur_view: id = msg_send![BLURRED_VIEW_CLASS, alloc];
1407                    blur_view = NSView::initWithFrame_(blur_view, frame);
1408                    blur_view.setAutoresizingMask_(NSViewWidthSizable | NSViewHeightSizable);
1409
1410                    let _: () = msg_send![
1411                        content_view,
1412                        addSubview: blur_view
1413                        positioned: NSWindowOrderingMode::NSWindowBelow
1414                        relativeTo: nil
1415                    ];
1416                    this.blurred_view = Some(blur_view.autorelease());
1417                }
1418            }
1419        }
1420    }
1421
1422    fn background_appearance(&self) -> WindowBackgroundAppearance {
1423        self.0.as_ref().lock().background_appearance
1424    }
1425
1426    fn is_subpixel_rendering_supported(&self) -> bool {
1427        false
1428    }
1429
1430    fn set_edited(&mut self, edited: bool) {
1431        unsafe {
1432            let window = self.0.lock().native_window;
1433            msg_send![window, setDocumentEdited: edited as BOOL]
1434        }
1435
1436        // Changing the document edited state resets the traffic light position,
1437        // so we have to move it again.
1438        self.0.lock().move_traffic_light();
1439    }
1440
1441    fn show_character_palette(&self) {
1442        let this = self.0.lock();
1443        let window = this.native_window;
1444        this.foreground_executor
1445            .spawn(async move {
1446                unsafe {
1447                    let app = NSApplication::sharedApplication(nil);
1448                    let _: () = msg_send![app, orderFrontCharacterPalette: window];
1449                }
1450            })
1451            .detach();
1452    }
1453
1454    fn minimize(&self) {
1455        let window = self.0.lock().native_window;
1456        unsafe {
1457            window.miniaturize_(nil);
1458        }
1459    }
1460
1461    fn zoom(&self) {
1462        let this = self.0.lock();
1463        let window = this.native_window;
1464        let closed = this.closed.clone();
1465        this.foreground_executor
1466            .spawn(async move {
1467                if_window_not_closed(closed, || unsafe {
1468                    window.zoom_(nil);
1469                })
1470            })
1471            .detach();
1472    }
1473
1474    fn toggle_fullscreen(&self) {
1475        let this = self.0.lock();
1476        let window = this.native_window;
1477        let closed = this.closed.clone();
1478        this.foreground_executor
1479            .spawn(async move {
1480                if_window_not_closed(closed, || unsafe {
1481                    window.toggleFullScreen_(nil);
1482                })
1483            })
1484            .detach();
1485    }
1486
1487    fn is_fullscreen(&self) -> bool {
1488        let this = self.0.lock();
1489        let window = this.native_window;
1490
1491        unsafe {
1492            window
1493                .styleMask()
1494                .contains(NSWindowStyleMask::NSFullScreenWindowMask)
1495        }
1496    }
1497
1498    fn on_request_frame(&self, callback: Box<dyn FnMut(RequestFrameOptions)>) {
1499        self.0.as_ref().lock().request_frame_callback = Some(callback);
1500    }
1501
1502    fn on_input(&self, callback: Box<dyn FnMut(PlatformInput) -> gpui::DispatchEventResult>) {
1503        self.0.as_ref().lock().event_callback = Some(callback);
1504    }
1505
1506    fn on_active_status_change(&self, callback: Box<dyn FnMut(bool)>) {
1507        self.0.as_ref().lock().activate_callback = Some(callback);
1508    }
1509
1510    fn on_hover_status_change(&self, _: Box<dyn FnMut(bool)>) {}
1511
1512    fn on_resize(&self, callback: Box<dyn FnMut(Size<Pixels>, f32)>) {
1513        self.0.as_ref().lock().resize_callback = Some(callback);
1514    }
1515
1516    fn on_moved(&self, callback: Box<dyn FnMut()>) {
1517        self.0.as_ref().lock().moved_callback = Some(callback);
1518    }
1519
1520    fn on_should_close(&self, callback: Box<dyn FnMut() -> bool>) {
1521        self.0.as_ref().lock().should_close_callback = Some(callback);
1522    }
1523
1524    fn on_close(&self, callback: Box<dyn FnOnce()>) {
1525        self.0.as_ref().lock().close_callback = Some(callback);
1526    }
1527
1528    fn on_hit_test_window_control(&self, _callback: Box<dyn FnMut() -> Option<WindowControlArea>>) {
1529    }
1530
1531    fn on_appearance_changed(&self, callback: Box<dyn FnMut()>) {
1532        self.0.lock().appearance_changed_callback = Some(callback);
1533    }
1534
1535    fn tabbed_windows(&self) -> Option<Vec<SystemWindowTab>> {
1536        unsafe {
1537            let windows: id = msg_send![self.0.lock().native_window, tabbedWindows];
1538            if windows.is_null() {
1539                return None;
1540            }
1541
1542            let count: NSUInteger = msg_send![windows, count];
1543            let mut result = Vec::new();
1544            for i in 0..count {
1545                let window: id = msg_send![windows, objectAtIndex:i];
1546                if msg_send![window, isKindOfClass: WINDOW_CLASS] {
1547                    let handle = get_window_state(&*window).lock().handle;
1548                    let title: id = msg_send![window, title];
1549                    let title = SharedString::from(title.to_str().to_string());
1550
1551                    result.push(SystemWindowTab::new(title, handle));
1552                }
1553            }
1554
1555            Some(result)
1556        }
1557    }
1558
1559    fn tab_bar_visible(&self) -> bool {
1560        unsafe {
1561            let tab_group: id = msg_send![self.0.lock().native_window, tabGroup];
1562            if tab_group.is_null() {
1563                false
1564            } else {
1565                let tab_bar_visible: BOOL = msg_send![tab_group, isTabBarVisible];
1566                tab_bar_visible == YES
1567            }
1568        }
1569    }
1570
1571    fn on_move_tab_to_new_window(&self, callback: Box<dyn FnMut()>) {
1572        self.0.as_ref().lock().move_tab_to_new_window_callback = Some(callback);
1573    }
1574
1575    fn on_merge_all_windows(&self, callback: Box<dyn FnMut()>) {
1576        self.0.as_ref().lock().merge_all_windows_callback = Some(callback);
1577    }
1578
1579    fn on_select_next_tab(&self, callback: Box<dyn FnMut()>) {
1580        self.0.as_ref().lock().select_next_tab_callback = Some(callback);
1581    }
1582
1583    fn on_select_previous_tab(&self, callback: Box<dyn FnMut()>) {
1584        self.0.as_ref().lock().select_previous_tab_callback = Some(callback);
1585    }
1586
1587    fn on_toggle_tab_bar(&self, callback: Box<dyn FnMut()>) {
1588        self.0.as_ref().lock().toggle_tab_bar_callback = Some(callback);
1589    }
1590
1591    fn draw(&self, scene: &gpui::Scene) {
1592        let mut this = self.0.lock();
1593        this.renderer.draw(scene);
1594    }
1595
1596    fn sprite_atlas(&self) -> Arc<dyn PlatformAtlas> {
1597        self.0.lock().renderer.sprite_atlas().clone()
1598    }
1599
1600    fn gpu_specs(&self) -> Option<gpui::GpuSpecs> {
1601        None
1602    }
1603
1604    fn update_ime_position(&self, _bounds: Bounds<Pixels>) {
1605        let executor = self.0.lock().foreground_executor.clone();
1606        executor
1607            .spawn(async move {
1608                unsafe {
1609                    let input_context: id =
1610                        msg_send![class!(NSTextInputContext), currentInputContext];
1611                    if input_context.is_null() {
1612                        return;
1613                    }
1614                    let _: () = msg_send![input_context, invalidateCharacterCoordinates];
1615                }
1616            })
1617            .detach()
1618    }
1619
1620    fn titlebar_double_click(&self) {
1621        let this = self.0.lock();
1622        let window = this.native_window;
1623        let closed = this.closed.clone();
1624        this.foreground_executor
1625            .spawn(async move {
1626                if_window_not_closed(closed, || {
1627                    unsafe {
1628                        let defaults: id = NSUserDefaults::standardUserDefaults();
1629                        let domain = ns_string("NSGlobalDomain");
1630                        let key = ns_string("AppleActionOnDoubleClick");
1631
1632                        let dict: id = msg_send![defaults, persistentDomainForName: domain];
1633                        let action: id = if !dict.is_null() {
1634                            msg_send![dict, objectForKey: key]
1635                        } else {
1636                            nil
1637                        };
1638
1639                        let action_str = if !action.is_null() {
1640                            CStr::from_ptr(NSString::UTF8String(action)).to_string_lossy()
1641                        } else {
1642                            "".into()
1643                        };
1644
1645                        match action_str.as_ref() {
1646                            "None" => {
1647                                // "Do Nothing" selected, so do no action
1648                            }
1649                            "Minimize" => {
1650                                window.miniaturize_(nil);
1651                            }
1652                            "Maximize" => {
1653                                window.zoom_(nil);
1654                            }
1655                            "Fill" => {
1656                                // There is no documented API for "Fill" action, so we'll just zoom the window
1657                                window.zoom_(nil);
1658                            }
1659                            _ => {
1660                                window.zoom_(nil);
1661                            }
1662                        }
1663                    }
1664                })
1665            })
1666            .detach();
1667    }
1668
1669    fn start_window_move(&self) {
1670        let this = self.0.lock();
1671        let window = this.native_window;
1672
1673        unsafe {
1674            let app = NSApplication::sharedApplication(nil);
1675            let event: id = msg_send![app, currentEvent];
1676            let _: () = msg_send![window, performWindowDragWithEvent: event];
1677        }
1678    }
1679
1680    fn play_system_bell(&self) {
1681        unsafe { NSBeep() }
1682    }
1683
1684    #[cfg(any(test, feature = "test-support"))]
1685    fn render_to_image(&self, scene: &gpui::Scene) -> Result<RgbaImage> {
1686        let mut this = self.0.lock();
1687        this.renderer.render_to_image(scene)
1688    }
1689}
1690
1691impl rwh::HasWindowHandle for MacWindow {
1692    fn window_handle(&self) -> Result<rwh::WindowHandle<'_>, rwh::HandleError> {
1693        // SAFETY: The AppKitWindowHandle is a wrapper around a pointer to an NSView
1694        unsafe {
1695            Ok(rwh::WindowHandle::borrow_raw(rwh::RawWindowHandle::AppKit(
1696                rwh::AppKitWindowHandle::new(self.0.lock().native_view.cast()),
1697            )))
1698        }
1699    }
1700}
1701
1702impl rwh::HasDisplayHandle for MacWindow {
1703    fn display_handle(&self) -> Result<rwh::DisplayHandle<'_>, rwh::HandleError> {
1704        // SAFETY: This is a no-op on macOS
1705        unsafe {
1706            Ok(rwh::DisplayHandle::borrow_raw(
1707                rwh::AppKitDisplayHandle::new().into(),
1708            ))
1709        }
1710    }
1711}
1712
1713fn get_scale_factor(native_window: id) -> f32 {
1714    let factor = unsafe {
1715        let screen: id = msg_send![native_window, screen];
1716        if screen.is_null() {
1717            return 2.0;
1718        }
1719        NSScreen::backingScaleFactor(screen) as f32
1720    };
1721
1722    // We are not certain what triggers this, but it seems that sometimes
1723    // this method would return 0 (https://github.com/zed-industries/zed/issues/6412)
1724    // It seems most likely that this would happen if the window has no screen
1725    // (if it is off-screen), though we'd expect to see viewDidChangeBackingProperties before
1726    // it was rendered for real.
1727    // Regardless, attempt to avoid the issue here.
1728    if factor == 0.0 { 2. } else { factor }
1729}
1730
1731unsafe fn get_window_state(object: &Object) -> Arc<Mutex<MacWindowState>> {
1732    unsafe {
1733        let raw: *mut c_void = *object.get_ivar(WINDOW_STATE_IVAR);
1734        let rc1 = Arc::from_raw(raw as *mut Mutex<MacWindowState>);
1735        let rc2 = rc1.clone();
1736        mem::forget(rc1);
1737        rc2
1738    }
1739}
1740
1741unsafe fn drop_window_state(object: &Object) {
1742    unsafe {
1743        let raw: *mut c_void = *object.get_ivar(WINDOW_STATE_IVAR);
1744        Arc::from_raw(raw as *mut Mutex<MacWindowState>);
1745    }
1746}
1747
1748extern "C" fn yes(_: &Object, _: Sel) -> BOOL {
1749    YES
1750}
1751
1752extern "C" fn dealloc_window(this: &Object, _: Sel) {
1753    unsafe {
1754        drop_window_state(this);
1755        let _: () = msg_send![super(this, class!(NSWindow)), dealloc];
1756    }
1757}
1758
1759extern "C" fn dealloc_view(this: &Object, _: Sel) {
1760    unsafe {
1761        drop_window_state(this);
1762        let _: () = msg_send![super(this, class!(NSView)), dealloc];
1763    }
1764}
1765
1766extern "C" fn handle_key_equivalent(this: &Object, _: Sel, native_event: id) -> BOOL {
1767    handle_key_event(this, native_event, true)
1768}
1769
1770extern "C" fn handle_key_down(this: &Object, _: Sel, native_event: id) {
1771    handle_key_event(this, native_event, false);
1772}
1773
1774extern "C" fn handle_key_up(this: &Object, _: Sel, native_event: id) {
1775    handle_key_event(this, native_event, false);
1776}
1777
1778// Things to test if you're modifying this method:
1779//  U.S. layout:
1780//   - The IME consumes characters like 'j' and 'k', which makes paging through `less` in
1781//     the terminal behave incorrectly by default. This behavior should be patched by our
1782//     IME integration
1783//   - `alt-t` should open the tasks menu
1784//   - In vim mode, this keybinding should work:
1785//     ```
1786//        {
1787//          "context": "Editor && vim_mode == insert",
1788//          "bindings": {"j j": "vim::NormalBefore"}
1789//        }
1790//     ```
1791//     and typing 'j k' in insert mode with this keybinding should insert the two characters
1792//  Brazilian layout:
1793//   - `" space` should create an unmarked quote
1794//   - `" backspace` should delete the marked quote
1795//   - `" "`should create an unmarked quote and a second marked quote
1796//   - `" up` should insert a quote, unmark it, and move up one line
1797//   - `" cmd-down` should insert a quote, unmark it, and move to the end of the file
1798//   - `cmd-ctrl-space` and clicking on an emoji should type it
1799//  Czech (QWERTY) layout:
1800//   - in vim mode `option-4`  should go to end of line (same as $)
1801//  Japanese (Romaji) layout:
1802//   - type `a i left down up enter enter` should create an unmarked text "愛"
1803//   - In vim mode with `jj` bound to `vim::NormalBefore` in insert mode, typing 'j i' with
1804//     Japanese IME should produce "じ" (ji), not "jい"
1805
1806/// Returns true if the current keyboard input source is a composition-based IME
1807/// (e.g. Japanese Hiragana, Korean, Chinese Pinyin) that produces non-ASCII output.
1808///
1809/// This checks two properties:
1810/// 1. The source type is `kTISTypeKeyboardInputMode` (an IME input mode, not a plain
1811///    keyboard layout). This excludes non-ASCII layouts like Armenian and Ukrainian
1812///    that map keys directly without composition.
1813/// 2. The source is not ASCII-capable, which excludes modes like Japanese Romaji that
1814///    produce ASCII characters and should allow multi-stroke keybindings like `jj`.
1815unsafe fn is_ime_input_source_active() -> bool {
1816    unsafe {
1817        let source = TISCopyCurrentKeyboardInputSource();
1818        if source.is_null() {
1819            return false;
1820        }
1821
1822        let source_type =
1823            TISGetInputSourceProperty(source, kTISPropertyInputSourceType as *const c_void);
1824        let is_input_mode = !source_type.is_null()
1825            && CFEqual(
1826                source_type as CFTypeRef,
1827                kTISTypeKeyboardInputMode as CFTypeRef,
1828            ) != 0;
1829
1830        let is_ascii = TISGetInputSourceProperty(
1831            source,
1832            kTISPropertyInputSourceIsASCIICapable as *const c_void,
1833        );
1834        let is_ascii_capable = !is_ascii.is_null() && CFBooleanGetValue(is_ascii as CFBooleanRef);
1835
1836        CFRelease(source as CFTypeRef);
1837
1838        is_input_mode && !is_ascii_capable
1839    }
1840}
1841
1842extern "C" fn handle_key_event(this: &Object, native_event: id, key_equivalent: bool) -> BOOL {
1843    let window_state = unsafe { get_window_state(this) };
1844    let mut lock = window_state.as_ref().lock();
1845
1846    let window_height = lock.content_size().height;
1847    let event = unsafe { platform_input_from_native(native_event, Some(window_height)) };
1848
1849    let Some(event) = event else {
1850        return NO;
1851    };
1852
1853    let run_callback = |event: PlatformInput| -> BOOL {
1854        let mut callback = window_state.as_ref().lock().event_callback.take();
1855        let handled: BOOL = if let Some(callback) = callback.as_mut() {
1856            !callback(event).propagate as BOOL
1857        } else {
1858            NO
1859        };
1860        window_state.as_ref().lock().event_callback = callback;
1861        handled
1862    };
1863
1864    match event {
1865        PlatformInput::KeyDown(key_down_event) => {
1866            // For certain keystrokes, macOS will first dispatch a "key equivalent" event.
1867            // If that event isn't handled, it will then dispatch a "key down" event. GPUI
1868            // makes no distinction between these two types of events, so we need to ignore
1869            // the "key down" event if we've already just processed its "key equivalent" version.
1870            if key_equivalent {
1871                lock.last_key_equivalent = Some(key_down_event.clone());
1872            } else if lock.last_key_equivalent.take().as_ref() == Some(&key_down_event) {
1873                return NO;
1874            }
1875
1876            drop(lock);
1877
1878            let is_composing =
1879                with_input_handler(this, |input_handler| input_handler.marked_text_range())
1880                    .flatten()
1881                    .is_some();
1882
1883            // If we're composing, send the key to the input handler first;
1884            // otherwise we only send to the input handler if we don't have a matching binding.
1885            // The input handler may call `do_command_by_selector` if it doesn't know how to handle
1886            // a key. If it does so, it will return YES so we won't send the key twice.
1887            // We also do this for non-printing keys (like arrow keys and escape) as the IME menu
1888            // may need them even if there is no marked text;
1889            // however we skip keys with control or the input handler adds control-characters to the buffer.
1890            // and keys with function, as the input handler swallows them.
1891            // and keys with platform (Cmd), so that Cmd+key events (e.g. Cmd+`) are not
1892            // consumed by the IME on non-QWERTY / dead-key layouts.
1893            // We also send printable keys to the IME first when an IME input source (e.g. Japanese,
1894            // Korean, Chinese) is active and the input handler accepts text input. This prevents
1895            // multi-stroke keybindings like `jj` from intercepting keys that the IME should compose
1896            // (e.g. typing 'ji' should produce 'じ', not 'jい'). If the IME doesn't handle the key,
1897            // it calls `doCommandBySelector:` which routes it back to keybinding matching.
1898            let is_ime_printable_key = !is_composing
1899                && key_down_event
1900                    .keystroke
1901                    .key_char
1902                    .as_ref()
1903                    .is_some_and(|key_char| key_char.chars().all(|c| !c.is_control()))
1904                && !key_down_event.keystroke.modifiers.control
1905                && !key_down_event.keystroke.modifiers.function
1906                && !key_down_event.keystroke.modifiers.platform
1907                && unsafe { is_ime_input_source_active() }
1908                && with_input_handler(this, |input_handler| {
1909                    input_handler.query_prefers_ime_for_printable_keys()
1910                })
1911                .unwrap_or(false);
1912
1913            if is_composing
1914                || is_ime_printable_key
1915                || (key_down_event.keystroke.key_char.is_none()
1916                    && !key_down_event.keystroke.modifiers.control
1917                    && !key_down_event.keystroke.modifiers.function
1918                    && !key_down_event.keystroke.modifiers.platform)
1919            {
1920                {
1921                    let mut lock = window_state.as_ref().lock();
1922                    lock.keystroke_for_do_command = Some(key_down_event.keystroke.clone());
1923                    lock.do_command_handled.take();
1924                    drop(lock);
1925                }
1926
1927                let handled: BOOL = unsafe {
1928                    let input_context: id = msg_send![this, inputContext];
1929                    msg_send![input_context, handleEvent: native_event]
1930                };
1931                window_state.as_ref().lock().keystroke_for_do_command.take();
1932                if let Some(handled) = window_state.as_ref().lock().do_command_handled.take() {
1933                    return handled as BOOL;
1934                } else if handled == YES {
1935                    return YES;
1936                }
1937
1938                let handled = run_callback(PlatformInput::KeyDown(key_down_event));
1939                return handled;
1940            }
1941
1942            let handled = run_callback(PlatformInput::KeyDown(key_down_event.clone()));
1943            if handled == YES {
1944                return YES;
1945            }
1946
1947            if key_down_event.is_held
1948                && let Some(key_char) = key_down_event.keystroke.key_char.as_ref()
1949            {
1950                let handled = with_input_handler(this, |input_handler| {
1951                    if !input_handler.apple_press_and_hold_enabled() {
1952                        input_handler.replace_text_in_range(None, key_char);
1953                        return YES;
1954                    }
1955                    NO
1956                });
1957                if handled == Some(YES) {
1958                    return YES;
1959                }
1960            }
1961
1962            // Don't send key equivalents to the input handler if there are key modifiers other
1963            // than Function key, or macOS shortcuts like cmd-` will stop working.
1964            if key_equivalent && key_down_event.keystroke.modifiers != Modifiers::function() {
1965                return NO;
1966            }
1967
1968            unsafe {
1969                let input_context: id = msg_send![this, inputContext];
1970                msg_send![input_context, handleEvent: native_event]
1971            }
1972        }
1973
1974        PlatformInput::KeyUp(_) => {
1975            drop(lock);
1976            run_callback(event)
1977        }
1978
1979        _ => NO,
1980    }
1981}
1982
1983extern "C" fn handle_view_event(this: &Object, _: Sel, native_event: id) {
1984    let window_state = unsafe { get_window_state(this) };
1985    let weak_window_state = Arc::downgrade(&window_state);
1986    let mut lock = window_state.as_ref().lock();
1987    let window_height = lock.content_size().height;
1988    let event = unsafe { platform_input_from_native(native_event, Some(window_height)) };
1989
1990    if let Some(mut event) = event {
1991        match &mut event {
1992            PlatformInput::MouseDown(
1993                event @ MouseDownEvent {
1994                    button: MouseButton::Left,
1995                    modifiers: Modifiers { control: true, .. },
1996                    ..
1997                },
1998            ) => {
1999                // On mac, a ctrl-left click should be handled as a right click.
2000                *event = MouseDownEvent {
2001                    button: MouseButton::Right,
2002                    modifiers: Modifiers {
2003                        control: false,
2004                        ..event.modifiers
2005                    },
2006                    click_count: 1,
2007                    ..*event
2008                };
2009            }
2010
2011            // Handles focusing click.
2012            PlatformInput::MouseDown(
2013                event @ MouseDownEvent {
2014                    button: MouseButton::Left,
2015                    ..
2016                },
2017            ) if (lock.first_mouse) => {
2018                *event = MouseDownEvent {
2019                    first_mouse: true,
2020                    ..*event
2021                };
2022                lock.first_mouse = false;
2023            }
2024
2025            // Because we map a ctrl-left_down to a right_down -> right_up let's ignore
2026            // the ctrl-left_up to avoid having a mismatch in button down/up events if the
2027            // user is still holding ctrl when releasing the left mouse button
2028            PlatformInput::MouseUp(
2029                event @ MouseUpEvent {
2030                    button: MouseButton::Left,
2031                    modifiers: Modifiers { control: true, .. },
2032                    ..
2033                },
2034            ) => {
2035                *event = MouseUpEvent {
2036                    button: MouseButton::Right,
2037                    modifiers: Modifiers {
2038                        control: false,
2039                        ..event.modifiers
2040                    },
2041                    click_count: 1,
2042                    ..*event
2043                };
2044            }
2045
2046            _ => {}
2047        };
2048
2049        match &event {
2050            PlatformInput::MouseDown(_) => {
2051                drop(lock);
2052                unsafe {
2053                    let input_context: id = msg_send![this, inputContext];
2054                    msg_send![input_context, handleEvent: native_event]
2055                }
2056                lock = window_state.as_ref().lock();
2057            }
2058            PlatformInput::MouseMove(
2059                event @ MouseMoveEvent {
2060                    pressed_button: Some(_),
2061                    ..
2062                },
2063            ) => {
2064                // Synthetic drag is used for selecting long buffer contents while buffer is being scrolled.
2065                // External file drag and drop is able to emit its own synthetic mouse events which will conflict
2066                // with these ones.
2067                if !lock.external_files_dragged {
2068                    lock.synthetic_drag_counter += 1;
2069                    let executor = lock.foreground_executor.clone();
2070                    executor
2071                        .spawn(synthetic_drag(
2072                            weak_window_state,
2073                            lock.synthetic_drag_counter,
2074                            event.clone(),
2075                            lock.background_executor.clone(),
2076                        ))
2077                        .detach();
2078                }
2079            }
2080
2081            PlatformInput::MouseUp(MouseUpEvent { .. }) => {
2082                lock.synthetic_drag_counter += 1;
2083            }
2084
2085            PlatformInput::ModifiersChanged(ModifiersChangedEvent {
2086                modifiers,
2087                capslock,
2088            }) => {
2089                // Only raise modifiers changed event when they have actually changed
2090                if let Some(PlatformInput::ModifiersChanged(ModifiersChangedEvent {
2091                    modifiers: prev_modifiers,
2092                    capslock: prev_capslock,
2093                })) = &lock.previous_modifiers_changed_event
2094                    && prev_modifiers == modifiers
2095                    && prev_capslock == capslock
2096                {
2097                    return;
2098                }
2099
2100                lock.previous_modifiers_changed_event = Some(event.clone());
2101            }
2102
2103            _ => {}
2104        }
2105
2106        if let Some(mut callback) = lock.event_callback.take() {
2107            drop(lock);
2108            callback(event);
2109            window_state.lock().event_callback = Some(callback);
2110        }
2111    }
2112}
2113
2114extern "C" fn window_did_change_occlusion_state(this: &Object, _: Sel, _: id) {
2115    let window_state = unsafe { get_window_state(this) };
2116    let lock = &mut *window_state.lock();
2117    unsafe {
2118        if lock
2119            .native_window
2120            .occlusionState()
2121            .contains(NSWindowOcclusionState::NSWindowOcclusionStateVisible)
2122        {
2123            lock.move_traffic_light();
2124            lock.start_display_link();
2125        } else {
2126            lock.stop_display_link();
2127        }
2128    }
2129}
2130
2131extern "C" fn window_did_resize(this: &Object, _: Sel, _: id) {
2132    let window_state = unsafe { get_window_state(this) };
2133    window_state.as_ref().lock().move_traffic_light();
2134}
2135
2136extern "C" fn window_will_enter_fullscreen(this: &Object, _: Sel, _: id) {
2137    let window_state = unsafe { get_window_state(this) };
2138    let mut lock = window_state.as_ref().lock();
2139    lock.fullscreen_restore_bounds = lock.bounds();
2140
2141    let min_version = NSOperatingSystemVersion::new(15, 3, 0);
2142
2143    if is_macos_version_at_least(min_version) {
2144        unsafe {
2145            lock.native_window.setTitlebarAppearsTransparent_(NO);
2146        }
2147    }
2148}
2149
2150extern "C" fn window_will_exit_fullscreen(this: &Object, _: Sel, _: id) {
2151    let window_state = unsafe { get_window_state(this) };
2152    let lock = window_state.as_ref().lock();
2153
2154    let min_version = NSOperatingSystemVersion::new(15, 3, 0);
2155
2156    if is_macos_version_at_least(min_version) && lock.transparent_titlebar {
2157        unsafe {
2158            lock.native_window.setTitlebarAppearsTransparent_(YES);
2159        }
2160    }
2161}
2162
2163pub(crate) fn is_macos_version_at_least(version: NSOperatingSystemVersion) -> bool {
2164    unsafe { NSProcessInfo::processInfo(nil).isOperatingSystemAtLeastVersion(version) }
2165}
2166
2167extern "C" fn window_did_move(this: &Object, _: Sel, _: id) {
2168    let window_state = unsafe { get_window_state(this) };
2169    let mut lock = window_state.as_ref().lock();
2170    if let Some(mut callback) = lock.moved_callback.take() {
2171        drop(lock);
2172        callback();
2173        window_state.lock().moved_callback = Some(callback);
2174    }
2175}
2176
2177// Update the window scale factor and drawable size, and call the resize callback if any.
2178fn update_window_scale_factor(window_state: &Arc<Mutex<MacWindowState>>) {
2179    let mut lock = window_state.as_ref().lock();
2180    let scale_factor = lock.scale_factor();
2181    let size = lock.content_size();
2182    let drawable_size = size.to_device_pixels(scale_factor);
2183    if let Some(layer) = lock.renderer.layer() {
2184        unsafe {
2185            let _: () = msg_send![
2186                layer,
2187                setContentsScale: scale_factor as f64
2188            ];
2189        }
2190    }
2191
2192    lock.renderer.update_drawable_size(drawable_size);
2193
2194    if let Some(mut callback) = lock.resize_callback.take() {
2195        let content_size = lock.content_size();
2196        let scale_factor = lock.scale_factor();
2197        drop(lock);
2198        callback(content_size, scale_factor);
2199        window_state.as_ref().lock().resize_callback = Some(callback);
2200    };
2201}
2202
2203extern "C" fn window_did_change_screen(this: &Object, _: Sel, _: id) {
2204    let window_state = unsafe { get_window_state(this) };
2205    let mut lock = window_state.as_ref().lock();
2206    lock.start_display_link();
2207    drop(lock);
2208    update_window_scale_factor(&window_state);
2209}
2210
2211extern "C" fn window_did_change_key_status(this: &Object, selector: Sel, _: id) {
2212    let window_state = unsafe { get_window_state(this) };
2213    let lock = window_state.lock();
2214    let is_active = unsafe { lock.native_window.isKeyWindow() == YES };
2215
2216    // When opening a pop-up while the application isn't active, Cocoa sends a spurious
2217    // `windowDidBecomeKey` message to the previous key window even though that window
2218    // isn't actually key. This causes a bug if the application is later activated while
2219    // the pop-up is still open, making it impossible to activate the previous key window
2220    // even if the pop-up gets closed. The only way to activate it again is to de-activate
2221    // the app and re-activate it, which is a pretty bad UX.
2222    // The following code detects the spurious event and invokes `resignKeyWindow`:
2223    // in theory, we're not supposed to invoke this method manually but it balances out
2224    // the spurious `becomeKeyWindow` event and helps us work around that bug.
2225    if selector == sel!(windowDidBecomeKey:) && !is_active {
2226        let native_window = lock.native_window;
2227        drop(lock);
2228        unsafe {
2229            let _: () = msg_send![native_window, resignKeyWindow];
2230        }
2231        return;
2232    }
2233
2234    let executor = lock.foreground_executor.clone();
2235    drop(lock);
2236
2237    // When a window becomes active, trigger an immediate synchronous frame request to prevent
2238    // tab flicker when switching between windows in native tabs mode.
2239    //
2240    // This is only done on subsequent activations (not the first) to ensure the initial focus
2241    // path is properly established. Without this guard, the focus state would remain unset until
2242    // the first mouse click, causing keybindings to be non-functional.
2243    if selector == sel!(windowDidBecomeKey:) && is_active {
2244        let window_state = unsafe { get_window_state(this) };
2245        let mut lock = window_state.lock();
2246
2247        if lock.activated_least_once {
2248            if let Some(mut callback) = lock.request_frame_callback.take() {
2249                lock.renderer.set_presents_with_transaction(true);
2250                lock.stop_display_link();
2251                drop(lock);
2252                callback(Default::default());
2253
2254                let mut lock = window_state.lock();
2255                lock.request_frame_callback = Some(callback);
2256                lock.renderer.set_presents_with_transaction(false);
2257                lock.start_display_link();
2258            }
2259        } else {
2260            lock.activated_least_once = true;
2261        }
2262    }
2263
2264    executor
2265        .spawn(async move {
2266            let mut lock = window_state.as_ref().lock();
2267            if is_active {
2268                lock.move_traffic_light();
2269            }
2270
2271            if let Some(mut callback) = lock.activate_callback.take() {
2272                drop(lock);
2273                callback(is_active);
2274                window_state.lock().activate_callback = Some(callback);
2275            };
2276        })
2277        .detach();
2278}
2279
2280extern "C" fn window_should_close(this: &Object, _: Sel, _: id) -> BOOL {
2281    let window_state = unsafe { get_window_state(this) };
2282    let mut lock = window_state.as_ref().lock();
2283    if let Some(mut callback) = lock.should_close_callback.take() {
2284        drop(lock);
2285        let should_close = callback();
2286        window_state.lock().should_close_callback = Some(callback);
2287        should_close as BOOL
2288    } else {
2289        YES
2290    }
2291}
2292
2293extern "C" fn close_window(this: &Object, _: Sel) {
2294    unsafe {
2295        let close_callback = {
2296            let window_state = get_window_state(this);
2297            let mut lock = window_state.as_ref().lock();
2298            lock.closed.store(true, Ordering::Release);
2299            lock.close_callback.take()
2300        };
2301
2302        if let Some(callback) = close_callback {
2303            callback();
2304        }
2305
2306        let _: () = msg_send![super(this, class!(NSWindow)), close];
2307    }
2308}
2309
2310extern "C" fn make_backing_layer(this: &Object, _: Sel) -> id {
2311    let window_state = unsafe { get_window_state(this) };
2312    let window_state = window_state.as_ref().lock();
2313    window_state.renderer.layer_ptr() as id
2314}
2315
2316extern "C" fn view_did_change_backing_properties(this: &Object, _: Sel) {
2317    let window_state = unsafe { get_window_state(this) };
2318    update_window_scale_factor(&window_state);
2319}
2320
2321extern "C" fn set_frame_size(this: &Object, _: Sel, size: NSSize) {
2322    fn convert(value: NSSize) -> Size<Pixels> {
2323        Size {
2324            width: px(value.width as f32),
2325            height: px(value.height as f32),
2326        }
2327    }
2328
2329    let window_state = unsafe { get_window_state(this) };
2330    let mut lock = window_state.as_ref().lock();
2331
2332    let new_size = convert(size);
2333    let old_size = unsafe {
2334        let old_frame: NSRect = msg_send![this, frame];
2335        convert(old_frame.size)
2336    };
2337
2338    if old_size == new_size {
2339        return;
2340    }
2341
2342    unsafe {
2343        let _: () = msg_send![super(this, class!(NSView)), setFrameSize: size];
2344    }
2345
2346    let scale_factor = lock.scale_factor();
2347    let drawable_size = new_size.to_device_pixels(scale_factor);
2348    lock.renderer.update_drawable_size(drawable_size);
2349
2350    if let Some(mut callback) = lock.resize_callback.take() {
2351        let content_size = lock.content_size();
2352        let scale_factor = lock.scale_factor();
2353        drop(lock);
2354        callback(content_size, scale_factor);
2355        window_state.lock().resize_callback = Some(callback);
2356    };
2357}
2358
2359extern "C" fn display_layer(this: &Object, _: Sel, _: id) {
2360    let window_state = unsafe { get_window_state(this) };
2361    let mut lock = window_state.lock();
2362    if let Some(mut callback) = lock.request_frame_callback.take() {
2363        lock.renderer.set_presents_with_transaction(true);
2364        lock.stop_display_link();
2365        drop(lock);
2366        callback(Default::default());
2367
2368        let mut lock = window_state.lock();
2369        lock.request_frame_callback = Some(callback);
2370        lock.renderer.set_presents_with_transaction(false);
2371        lock.start_display_link();
2372    }
2373}
2374
2375extern "C" fn step(view: *mut c_void) {
2376    let view = view as id;
2377    let window_state = unsafe { get_window_state(&*view) };
2378    let mut lock = window_state.lock();
2379
2380    if let Some(mut callback) = lock.request_frame_callback.take() {
2381        drop(lock);
2382        callback(Default::default());
2383        window_state.lock().request_frame_callback = Some(callback);
2384    }
2385}
2386
2387extern "C" fn valid_attributes_for_marked_text(_: &Object, _: Sel) -> id {
2388    unsafe { msg_send![class!(NSArray), array] }
2389}
2390
2391extern "C" fn has_marked_text(this: &Object, _: Sel) -> BOOL {
2392    let has_marked_text_result =
2393        with_input_handler(this, |input_handler| input_handler.marked_text_range()).flatten();
2394
2395    has_marked_text_result.is_some() as BOOL
2396}
2397
2398extern "C" fn marked_range(this: &Object, _: Sel) -> NSRange {
2399    let marked_range_result =
2400        with_input_handler(this, |input_handler| input_handler.marked_text_range()).flatten();
2401
2402    marked_range_result.map_or(NSRange::invalid(), |range| range.into())
2403}
2404
2405extern "C" fn selected_range(this: &Object, _: Sel) -> NSRange {
2406    let selected_range_result = with_input_handler(this, |input_handler| {
2407        input_handler.selected_text_range(false)
2408    })
2409    .flatten();
2410
2411    selected_range_result.map_or(NSRange::invalid(), |selection| selection.range.into())
2412}
2413
2414extern "C" fn first_rect_for_character_range(
2415    this: &Object,
2416    _: Sel,
2417    range: NSRange,
2418    _: id,
2419) -> NSRect {
2420    let frame = get_frame(this);
2421    with_input_handler(this, |input_handler| {
2422        input_handler.bounds_for_range(range.to_range()?)
2423    })
2424    .flatten()
2425    .map_or(
2426        NSRect::new(NSPoint::new(0., 0.), NSSize::new(0., 0.)),
2427        |bounds| {
2428            NSRect::new(
2429                NSPoint::new(
2430                    frame.origin.x + bounds.origin.x.as_f32() as f64,
2431                    frame.origin.y + frame.size.height
2432                        - bounds.origin.y.as_f32() as f64
2433                        - bounds.size.height.as_f32() as f64,
2434                ),
2435                NSSize::new(
2436                    bounds.size.width.as_f32() as f64,
2437                    bounds.size.height.as_f32() as f64,
2438                ),
2439            )
2440        },
2441    )
2442}
2443
2444fn get_frame(this: &Object) -> NSRect {
2445    unsafe {
2446        let state = get_window_state(this);
2447        let lock = state.lock();
2448        let mut frame = NSWindow::frame(lock.native_window);
2449        let content_layout_rect: CGRect = msg_send![lock.native_window, contentLayoutRect];
2450        let style_mask: NSWindowStyleMask = msg_send![lock.native_window, styleMask];
2451        if !style_mask.contains(NSWindowStyleMask::NSFullSizeContentViewWindowMask) {
2452            frame.origin.y -= frame.size.height - content_layout_rect.size.height;
2453        }
2454        frame
2455    }
2456}
2457
2458extern "C" fn insert_text(this: &Object, _: Sel, text: id, replacement_range: NSRange) {
2459    unsafe {
2460        let is_attributed_string: BOOL =
2461            msg_send![text, isKindOfClass: [class!(NSAttributedString)]];
2462        let text: id = if is_attributed_string == YES {
2463            msg_send![text, string]
2464        } else {
2465            text
2466        };
2467
2468        let text = text.to_str();
2469        let replacement_range = replacement_range.to_range();
2470        with_input_handler(this, |input_handler| {
2471            input_handler.replace_text_in_range(replacement_range, text)
2472        });
2473    }
2474}
2475
2476extern "C" fn set_marked_text(
2477    this: &Object,
2478    _: Sel,
2479    text: id,
2480    selected_range: NSRange,
2481    replacement_range: NSRange,
2482) {
2483    unsafe {
2484        let is_attributed_string: BOOL =
2485            msg_send![text, isKindOfClass: [class!(NSAttributedString)]];
2486        let text: id = if is_attributed_string == YES {
2487            msg_send![text, string]
2488        } else {
2489            text
2490        };
2491        let selected_range = selected_range.to_range();
2492        let replacement_range = replacement_range.to_range();
2493        let text = text.to_str();
2494        with_input_handler(this, |input_handler| {
2495            input_handler.replace_and_mark_text_in_range(replacement_range, text, selected_range)
2496        });
2497    }
2498}
2499extern "C" fn unmark_text(this: &Object, _: Sel) {
2500    with_input_handler(this, |input_handler| input_handler.unmark_text());
2501}
2502
2503extern "C" fn attributed_substring_for_proposed_range(
2504    this: &Object,
2505    _: Sel,
2506    range: NSRange,
2507    actual_range: *mut c_void,
2508) -> id {
2509    with_input_handler(this, |input_handler| {
2510        let range = range.to_range()?;
2511        if range.is_empty() {
2512            return None;
2513        }
2514        let mut adjusted: Option<Range<usize>> = None;
2515
2516        let selected_text = input_handler.text_for_range(range.clone(), &mut adjusted)?;
2517        if let Some(adjusted) = adjusted
2518            && adjusted != range
2519        {
2520            unsafe { (actual_range as *mut NSRange).write(NSRange::from(adjusted)) };
2521        }
2522        unsafe {
2523            let string: id = msg_send![class!(NSAttributedString), alloc];
2524            let string: id = msg_send![string, initWithString: ns_string(&selected_text)];
2525            Some(string)
2526        }
2527    })
2528    .flatten()
2529    .unwrap_or(nil)
2530}
2531
2532// We ignore which selector it asks us to do because the user may have
2533// bound the shortcut to something else.
2534extern "C" fn do_command_by_selector(this: &Object, _: Sel, _: Sel) {
2535    let state = unsafe { get_window_state(this) };
2536    let mut lock = state.as_ref().lock();
2537    let keystroke = lock.keystroke_for_do_command.take();
2538    let mut event_callback = lock.event_callback.take();
2539    drop(lock);
2540
2541    if let Some((keystroke, callback)) = keystroke.zip(event_callback.as_mut()) {
2542        let handled = (callback)(PlatformInput::KeyDown(KeyDownEvent {
2543            keystroke,
2544            is_held: false,
2545            prefer_character_input: false,
2546        }));
2547        state.as_ref().lock().do_command_handled = Some(!handled.propagate);
2548    }
2549
2550    state.as_ref().lock().event_callback = event_callback;
2551}
2552
2553extern "C" fn view_did_change_effective_appearance(this: &Object, _: Sel) {
2554    unsafe {
2555        let state = get_window_state(this);
2556        let mut lock = state.as_ref().lock();
2557        if let Some(mut callback) = lock.appearance_changed_callback.take() {
2558            drop(lock);
2559            callback();
2560            state.lock().appearance_changed_callback = Some(callback);
2561        }
2562    }
2563}
2564
2565extern "C" fn accepts_first_mouse(this: &Object, _: Sel, _: id) -> BOOL {
2566    let window_state = unsafe { get_window_state(this) };
2567    let mut lock = window_state.as_ref().lock();
2568    lock.first_mouse = true;
2569    YES
2570}
2571
2572extern "C" fn character_index_for_point(this: &Object, _: Sel, position: NSPoint) -> u64 {
2573    let position = screen_point_to_gpui_point(this, position);
2574    with_input_handler(this, |input_handler| {
2575        input_handler.character_index_for_point(position)
2576    })
2577    .flatten()
2578    .map(|index| index as u64)
2579    .unwrap_or(NSNotFound as u64)
2580}
2581
2582fn screen_point_to_gpui_point(this: &Object, position: NSPoint) -> Point<Pixels> {
2583    let frame = get_frame(this);
2584    let window_x = position.x - frame.origin.x;
2585    let window_y = frame.size.height - (position.y - frame.origin.y);
2586
2587    point(px(window_x as f32), px(window_y as f32))
2588}
2589
2590extern "C" fn dragging_entered(this: &Object, _: Sel, dragging_info: id) -> NSDragOperation {
2591    let window_state = unsafe { get_window_state(this) };
2592    let position = drag_event_position(&window_state, dragging_info);
2593    let paths = external_paths_from_event(dragging_info);
2594    if let Some(event) = paths.map(|paths| FileDropEvent::Entered { position, paths })
2595        && send_file_drop_event(window_state, event)
2596    {
2597        return NSDragOperationCopy;
2598    }
2599    NSDragOperationNone
2600}
2601
2602extern "C" fn dragging_updated(this: &Object, _: Sel, dragging_info: id) -> NSDragOperation {
2603    let window_state = unsafe { get_window_state(this) };
2604    let position = drag_event_position(&window_state, dragging_info);
2605    if send_file_drop_event(window_state, FileDropEvent::Pending { position }) {
2606        NSDragOperationCopy
2607    } else {
2608        NSDragOperationNone
2609    }
2610}
2611
2612extern "C" fn dragging_exited(this: &Object, _: Sel, _: id) {
2613    let window_state = unsafe { get_window_state(this) };
2614    send_file_drop_event(window_state, FileDropEvent::Exited);
2615}
2616
2617extern "C" fn perform_drag_operation(this: &Object, _: Sel, dragging_info: id) -> BOOL {
2618    let window_state = unsafe { get_window_state(this) };
2619    let position = drag_event_position(&window_state, dragging_info);
2620    send_file_drop_event(window_state, FileDropEvent::Submit { position }).to_objc()
2621}
2622
2623fn external_paths_from_event(dragging_info: *mut Object) -> Option<ExternalPaths> {
2624    let mut paths = SmallVec::new();
2625    let pasteboard: id = unsafe { msg_send![dragging_info, draggingPasteboard] };
2626    let filenames = unsafe { NSPasteboard::propertyListForType(pasteboard, NSFilenamesPboardType) };
2627    if filenames == nil {
2628        return None;
2629    }
2630    for file in unsafe { filenames.iter() } {
2631        let path = unsafe {
2632            let f = NSString::UTF8String(file);
2633            CStr::from_ptr(f).to_string_lossy().into_owned()
2634        };
2635        paths.push(PathBuf::from(path))
2636    }
2637    Some(ExternalPaths(paths))
2638}
2639
2640extern "C" fn conclude_drag_operation(this: &Object, _: Sel, _: id) {
2641    let window_state = unsafe { get_window_state(this) };
2642    send_file_drop_event(window_state, FileDropEvent::Exited);
2643}
2644
2645async fn synthetic_drag(
2646    window_state: Weak<Mutex<MacWindowState>>,
2647    drag_id: usize,
2648    event: MouseMoveEvent,
2649    executor: BackgroundExecutor,
2650) {
2651    loop {
2652        executor.timer(Duration::from_millis(16)).await;
2653        if let Some(window_state) = window_state.upgrade() {
2654            let mut lock = window_state.lock();
2655            if lock.synthetic_drag_counter == drag_id {
2656                if let Some(mut callback) = lock.event_callback.take() {
2657                    drop(lock);
2658                    callback(PlatformInput::MouseMove(event.clone()));
2659                    window_state.lock().event_callback = Some(callback);
2660                }
2661            } else {
2662                break;
2663            }
2664        }
2665    }
2666}
2667
2668/// Sends the specified FileDropEvent using `PlatformInput::FileDrop` to the window
2669/// state and updates the window state according to the event passed.
2670fn send_file_drop_event(
2671    window_state: Arc<Mutex<MacWindowState>>,
2672    file_drop_event: FileDropEvent,
2673) -> bool {
2674    let external_files_dragged = match file_drop_event {
2675        FileDropEvent::Entered { .. } => Some(true),
2676        FileDropEvent::Exited => Some(false),
2677        _ => None,
2678    };
2679
2680    let mut lock = window_state.lock();
2681    if let Some(mut callback) = lock.event_callback.take() {
2682        drop(lock);
2683        callback(PlatformInput::FileDrop(file_drop_event));
2684        let mut lock = window_state.lock();
2685        lock.event_callback = Some(callback);
2686        if let Some(external_files_dragged) = external_files_dragged {
2687            lock.external_files_dragged = external_files_dragged;
2688        }
2689        true
2690    } else {
2691        false
2692    }
2693}
2694
2695fn drag_event_position(window_state: &Mutex<MacWindowState>, dragging_info: id) -> Point<Pixels> {
2696    let drag_location: NSPoint = unsafe { msg_send![dragging_info, draggingLocation] };
2697    convert_mouse_position(drag_location, window_state.lock().content_size().height)
2698}
2699
2700fn with_input_handler<F, R>(window: &Object, f: F) -> Option<R>
2701where
2702    F: FnOnce(&mut PlatformInputHandler) -> R,
2703{
2704    let window_state = unsafe { get_window_state(window) };
2705    let mut lock = window_state.as_ref().lock();
2706    if let Some(mut input_handler) = lock.input_handler.take() {
2707        drop(lock);
2708        let result = f(&mut input_handler);
2709        window_state.lock().input_handler = Some(input_handler);
2710        Some(result)
2711    } else {
2712        None
2713    }
2714}
2715
2716unsafe fn display_id_for_screen(screen: id) -> CGDirectDisplayID {
2717    unsafe {
2718        let device_description = NSScreen::deviceDescription(screen);
2719        let screen_number_key: id = ns_string("NSScreenNumber");
2720        let screen_number = device_description.objectForKey_(screen_number_key);
2721        let screen_number: NSUInteger = msg_send![screen_number, unsignedIntegerValue];
2722        screen_number as CGDirectDisplayID
2723    }
2724}
2725
2726extern "C" fn blurred_view_init_with_frame(this: &Object, _: Sel, frame: NSRect) -> id {
2727    unsafe {
2728        let view = msg_send![super(this, class!(NSVisualEffectView)), initWithFrame: frame];
2729        // Use a colorless semantic material. The default value `AppearanceBased`, though not
2730        // manually set, is deprecated.
2731        NSVisualEffectView::setMaterial_(view, NSVisualEffectMaterial::Selection);
2732        NSVisualEffectView::setState_(view, NSVisualEffectState::Active);
2733        view
2734    }
2735}
2736
2737extern "C" fn blurred_view_update_layer(this: &Object, _: Sel) {
2738    unsafe {
2739        let _: () = msg_send![super(this, class!(NSVisualEffectView)), updateLayer];
2740        let layer: id = msg_send![this, layer];
2741        if !layer.is_null() {
2742            remove_layer_background(layer);
2743        }
2744    }
2745}
2746
2747unsafe fn remove_layer_background(layer: id) {
2748    unsafe {
2749        let _: () = msg_send![layer, setBackgroundColor:nil];
2750
2751        let class_name: id = msg_send![layer, className];
2752        if class_name.isEqualToString("CAChameleonLayer") {
2753            // Remove the desktop tinting effect.
2754            let _: () = msg_send![layer, setHidden: YES];
2755            return;
2756        }
2757
2758        let filters: id = msg_send![layer, filters];
2759        if !filters.is_null() {
2760            // Remove the increased saturation.
2761            // The effect of a `CAFilter` or `CIFilter` is determined by its name, and the
2762            // `description` reflects its name and some parameters. Currently `NSVisualEffectView`
2763            // uses a `CAFilter` named "colorSaturate". If one day they switch to `CIFilter`, the
2764            // `description` will still contain "Saturat" ("... inputSaturation = ...").
2765            let test_string: id = ns_string("Saturat");
2766            let count = NSArray::count(filters);
2767            for i in 0..count {
2768                let description: id = msg_send![filters.objectAtIndex(i), description];
2769                let hit: BOOL = msg_send![description, containsString: test_string];
2770                if hit == NO {
2771                    continue;
2772                }
2773
2774                let all_indices = NSRange {
2775                    location: 0,
2776                    length: count,
2777                };
2778                let indices: id = msg_send![class!(NSMutableIndexSet), indexSet];
2779                let _: () = msg_send![indices, addIndexesInRange: all_indices];
2780                let _: () = msg_send![indices, removeIndex:i];
2781                let filtered: id = msg_send![filters, objectsAtIndexes: indices];
2782                let _: () = msg_send![layer, setFilters: filtered];
2783                break;
2784            }
2785        }
2786
2787        let sublayers: id = msg_send![layer, sublayers];
2788        if !sublayers.is_null() {
2789            let count = NSArray::count(sublayers);
2790            for i in 0..count {
2791                let sublayer = sublayers.objectAtIndex(i);
2792                remove_layer_background(sublayer);
2793            }
2794        }
2795    }
2796}
2797
2798extern "C" fn add_titlebar_accessory_view_controller(this: &Object, _: Sel, view_controller: id) {
2799    unsafe {
2800        let _: () = msg_send![super(this, class!(NSWindow)), addTitlebarAccessoryViewController: view_controller];
2801
2802        // Hide the native tab bar and set its height to 0, since we render our own.
2803        let accessory_view: id = msg_send![view_controller, view];
2804        let _: () = msg_send![accessory_view, setHidden: YES];
2805        let mut frame: NSRect = msg_send![accessory_view, frame];
2806        frame.size.height = 0.0;
2807        let _: () = msg_send![accessory_view, setFrame: frame];
2808    }
2809}
2810
2811extern "C" fn move_tab_to_new_window(this: &Object, _: Sel, _: id) {
2812    unsafe {
2813        let _: () = msg_send![super(this, class!(NSWindow)), moveTabToNewWindow:nil];
2814
2815        let window_state = get_window_state(this);
2816        let mut lock = window_state.as_ref().lock();
2817        if let Some(mut callback) = lock.move_tab_to_new_window_callback.take() {
2818            drop(lock);
2819            callback();
2820            window_state.lock().move_tab_to_new_window_callback = Some(callback);
2821        }
2822    }
2823}
2824
2825extern "C" fn merge_all_windows(this: &Object, _: Sel, _: id) {
2826    unsafe {
2827        let _: () = msg_send![super(this, class!(NSWindow)), mergeAllWindows:nil];
2828
2829        let window_state = get_window_state(this);
2830        let mut lock = window_state.as_ref().lock();
2831        if let Some(mut callback) = lock.merge_all_windows_callback.take() {
2832            drop(lock);
2833            callback();
2834            window_state.lock().merge_all_windows_callback = Some(callback);
2835        }
2836    }
2837}
2838
2839extern "C" fn select_next_tab(this: &Object, _sel: Sel, _id: id) {
2840    let window_state = unsafe { get_window_state(this) };
2841    let mut lock = window_state.as_ref().lock();
2842    if let Some(mut callback) = lock.select_next_tab_callback.take() {
2843        drop(lock);
2844        callback();
2845        window_state.lock().select_next_tab_callback = Some(callback);
2846    }
2847}
2848
2849extern "C" fn select_previous_tab(this: &Object, _sel: Sel, _id: id) {
2850    let window_state = unsafe { get_window_state(this) };
2851    let mut lock = window_state.as_ref().lock();
2852    if let Some(mut callback) = lock.select_previous_tab_callback.take() {
2853        drop(lock);
2854        callback();
2855        window_state.lock().select_previous_tab_callback = Some(callback);
2856    }
2857}
2858
2859extern "C" fn toggle_tab_bar(this: &Object, _sel: Sel, _id: id) {
2860    unsafe {
2861        let _: () = msg_send![super(this, class!(NSWindow)), toggleTabBar:nil];
2862
2863        let window_state = get_window_state(this);
2864        let mut lock = window_state.as_ref().lock();
2865        lock.move_traffic_light();
2866
2867        if let Some(mut callback) = lock.toggle_tab_bar_callback.take() {
2868            drop(lock);
2869            callback();
2870            window_state.lock().toggle_tab_bar_callback = Some(callback);
2871        }
2872    }
2873}