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        Ok(rwh::DisplayHandle::appkit())
1705    }
1706}
1707
1708fn get_scale_factor(native_window: id) -> f32 {
1709    let factor = unsafe {
1710        let screen: id = msg_send![native_window, screen];
1711        if screen.is_null() {
1712            return 2.0;
1713        }
1714        NSScreen::backingScaleFactor(screen) as f32
1715    };
1716
1717    // We are not certain what triggers this, but it seems that sometimes
1718    // this method would return 0 (https://github.com/zed-industries/zed/issues/6412)
1719    // It seems most likely that this would happen if the window has no screen
1720    // (if it is off-screen), though we'd expect to see viewDidChangeBackingProperties before
1721    // it was rendered for real.
1722    // Regardless, attempt to avoid the issue here.
1723    if factor == 0.0 { 2. } else { factor }
1724}
1725
1726unsafe fn get_window_state(object: &Object) -> Arc<Mutex<MacWindowState>> {
1727    unsafe {
1728        let raw: *mut c_void = *object.get_ivar(WINDOW_STATE_IVAR);
1729        let rc1 = Arc::from_raw(raw as *mut Mutex<MacWindowState>);
1730        let rc2 = rc1.clone();
1731        mem::forget(rc1);
1732        rc2
1733    }
1734}
1735
1736unsafe fn drop_window_state(object: &Object) {
1737    unsafe {
1738        let raw: *mut c_void = *object.get_ivar(WINDOW_STATE_IVAR);
1739        Arc::from_raw(raw as *mut Mutex<MacWindowState>);
1740    }
1741}
1742
1743extern "C" fn yes(_: &Object, _: Sel) -> BOOL {
1744    YES
1745}
1746
1747extern "C" fn dealloc_window(this: &Object, _: Sel) {
1748    unsafe {
1749        drop_window_state(this);
1750        let _: () = msg_send![super(this, class!(NSWindow)), dealloc];
1751    }
1752}
1753
1754extern "C" fn dealloc_view(this: &Object, _: Sel) {
1755    unsafe {
1756        drop_window_state(this);
1757        let _: () = msg_send![super(this, class!(NSView)), dealloc];
1758    }
1759}
1760
1761extern "C" fn handle_key_equivalent(this: &Object, _: Sel, native_event: id) -> BOOL {
1762    handle_key_event(this, native_event, true)
1763}
1764
1765extern "C" fn handle_key_down(this: &Object, _: Sel, native_event: id) {
1766    handle_key_event(this, native_event, false);
1767}
1768
1769extern "C" fn handle_key_up(this: &Object, _: Sel, native_event: id) {
1770    handle_key_event(this, native_event, false);
1771}
1772
1773// Things to test if you're modifying this method:
1774//  U.S. layout:
1775//   - The IME consumes characters like 'j' and 'k', which makes paging through `less` in
1776//     the terminal behave incorrectly by default. This behavior should be patched by our
1777//     IME integration
1778//   - `alt-t` should open the tasks menu
1779//   - In vim mode, this keybinding should work:
1780//     ```
1781//        {
1782//          "context": "Editor && vim_mode == insert",
1783//          "bindings": {"j j": "vim::NormalBefore"}
1784//        }
1785//     ```
1786//     and typing 'j k' in insert mode with this keybinding should insert the two characters
1787//  Brazilian layout:
1788//   - `" space` should create an unmarked quote
1789//   - `" backspace` should delete the marked quote
1790//   - `" "`should create an unmarked quote and a second marked quote
1791//   - `" up` should insert a quote, unmark it, and move up one line
1792//   - `" cmd-down` should insert a quote, unmark it, and move to the end of the file
1793//   - `cmd-ctrl-space` and clicking on an emoji should type it
1794//  Czech (QWERTY) layout:
1795//   - in vim mode `option-4`  should go to end of line (same as $)
1796//  Japanese (Romaji) layout:
1797//   - type `a i left down up enter enter` should create an unmarked text "愛"
1798//   - In vim mode with `jj` bound to `vim::NormalBefore` in insert mode, typing 'j i' with
1799//     Japanese IME should produce "じ" (ji), not "jい"
1800
1801/// Returns true if the current keyboard input source is a composition-based IME
1802/// (e.g. Japanese Hiragana, Korean, Chinese Pinyin) that produces non-ASCII output.
1803///
1804/// This checks two properties:
1805/// 1. The source type is `kTISTypeKeyboardInputMode` (an IME input mode, not a plain
1806///    keyboard layout). This excludes non-ASCII layouts like Armenian and Ukrainian
1807///    that map keys directly without composition.
1808/// 2. The source is not ASCII-capable, which excludes modes like Japanese Romaji that
1809///    produce ASCII characters and should allow multi-stroke keybindings like `jj`.
1810unsafe fn is_ime_input_source_active() -> bool {
1811    unsafe {
1812        let source = TISCopyCurrentKeyboardInputSource();
1813        if source.is_null() {
1814            return false;
1815        }
1816
1817        let source_type =
1818            TISGetInputSourceProperty(source, kTISPropertyInputSourceType as *const c_void);
1819        let is_input_mode = !source_type.is_null()
1820            && CFEqual(
1821                source_type as CFTypeRef,
1822                kTISTypeKeyboardInputMode as CFTypeRef,
1823            ) != 0;
1824
1825        let is_ascii = TISGetInputSourceProperty(
1826            source,
1827            kTISPropertyInputSourceIsASCIICapable as *const c_void,
1828        );
1829        let is_ascii_capable = !is_ascii.is_null() && CFBooleanGetValue(is_ascii as CFBooleanRef);
1830
1831        CFRelease(source as CFTypeRef);
1832
1833        is_input_mode && !is_ascii_capable
1834    }
1835}
1836
1837extern "C" fn handle_key_event(this: &Object, native_event: id, key_equivalent: bool) -> BOOL {
1838    let window_state = unsafe { get_window_state(this) };
1839    let mut lock = window_state.as_ref().lock();
1840
1841    let window_height = lock.content_size().height;
1842    let event = unsafe { platform_input_from_native(native_event, Some(window_height)) };
1843
1844    let Some(event) = event else {
1845        return NO;
1846    };
1847
1848    let run_callback = |event: PlatformInput| -> BOOL {
1849        let mut callback = window_state.as_ref().lock().event_callback.take();
1850        let handled: BOOL = if let Some(callback) = callback.as_mut() {
1851            !callback(event).propagate as BOOL
1852        } else {
1853            NO
1854        };
1855        window_state.as_ref().lock().event_callback = callback;
1856        handled
1857    };
1858
1859    match event {
1860        PlatformInput::KeyDown(key_down_event) => {
1861            // For certain keystrokes, macOS will first dispatch a "key equivalent" event.
1862            // If that event isn't handled, it will then dispatch a "key down" event. GPUI
1863            // makes no distinction between these two types of events, so we need to ignore
1864            // the "key down" event if we've already just processed its "key equivalent" version.
1865            if key_equivalent {
1866                lock.last_key_equivalent = Some(key_down_event.clone());
1867            } else if lock.last_key_equivalent.take().as_ref() == Some(&key_down_event) {
1868                return NO;
1869            }
1870
1871            drop(lock);
1872
1873            let is_composing =
1874                with_input_handler(this, |input_handler| input_handler.marked_text_range())
1875                    .flatten()
1876                    .is_some();
1877
1878            // If we're composing, send the key to the input handler first;
1879            // otherwise we only send to the input handler if we don't have a matching binding.
1880            // The input handler may call `do_command_by_selector` if it doesn't know how to handle
1881            // a key. If it does so, it will return YES so we won't send the key twice.
1882            // We also do this for non-printing keys (like arrow keys and escape) as the IME menu
1883            // may need them even if there is no marked text;
1884            // however we skip keys with control or the input handler adds control-characters to the buffer.
1885            // and keys with function, as the input handler swallows them.
1886            // and keys with platform (Cmd), so that Cmd+key events (e.g. Cmd+`) are not
1887            // consumed by the IME on non-QWERTY / dead-key layouts.
1888            // We also send printable keys to the IME first when an IME input source (e.g. Japanese,
1889            // Korean, Chinese) is active and the input handler accepts text input. This prevents
1890            // multi-stroke keybindings like `jj` from intercepting keys that the IME should compose
1891            // (e.g. typing 'ji' should produce 'じ', not 'jい'). If the IME doesn't handle the key,
1892            // it calls `doCommandBySelector:` which routes it back to keybinding matching.
1893            let is_ime_printable_key = !is_composing
1894                && key_down_event
1895                    .keystroke
1896                    .key_char
1897                    .as_ref()
1898                    .is_some_and(|key_char| key_char.chars().all(|c| !c.is_control()))
1899                && !key_down_event.keystroke.modifiers.control
1900                && !key_down_event.keystroke.modifiers.function
1901                && !key_down_event.keystroke.modifiers.platform
1902                && unsafe { is_ime_input_source_active() }
1903                && with_input_handler(this, |input_handler| {
1904                    input_handler.query_prefers_ime_for_printable_keys()
1905                })
1906                .unwrap_or(false);
1907
1908            if is_composing
1909                || is_ime_printable_key
1910                || (key_down_event.keystroke.key_char.is_none()
1911                    && !key_down_event.keystroke.modifiers.control
1912                    && !key_down_event.keystroke.modifiers.function
1913                    && !key_down_event.keystroke.modifiers.platform)
1914            {
1915                {
1916                    let mut lock = window_state.as_ref().lock();
1917                    lock.keystroke_for_do_command = Some(key_down_event.keystroke.clone());
1918                    lock.do_command_handled.take();
1919                    drop(lock);
1920                }
1921
1922                let handled: BOOL = unsafe {
1923                    let input_context: id = msg_send![this, inputContext];
1924                    msg_send![input_context, handleEvent: native_event]
1925                };
1926                window_state.as_ref().lock().keystroke_for_do_command.take();
1927                if let Some(handled) = window_state.as_ref().lock().do_command_handled.take() {
1928                    return handled as BOOL;
1929                } else if handled == YES {
1930                    return YES;
1931                }
1932
1933                let handled = run_callback(PlatformInput::KeyDown(key_down_event));
1934                return handled;
1935            }
1936
1937            let handled = run_callback(PlatformInput::KeyDown(key_down_event.clone()));
1938            if handled == YES {
1939                return YES;
1940            }
1941
1942            if key_down_event.is_held
1943                && let Some(key_char) = key_down_event.keystroke.key_char.as_ref()
1944            {
1945                let handled = with_input_handler(this, |input_handler| {
1946                    if !input_handler.apple_press_and_hold_enabled() {
1947                        input_handler.replace_text_in_range(None, key_char);
1948                        return YES;
1949                    }
1950                    NO
1951                });
1952                if handled == Some(YES) {
1953                    return YES;
1954                }
1955            }
1956
1957            // Don't send key equivalents to the input handler if there are key modifiers other
1958            // than Function key, or macOS shortcuts like cmd-` will stop working.
1959            if key_equivalent && key_down_event.keystroke.modifiers != Modifiers::function() {
1960                return NO;
1961            }
1962
1963            unsafe {
1964                let input_context: id = msg_send![this, inputContext];
1965                msg_send![input_context, handleEvent: native_event]
1966            }
1967        }
1968
1969        PlatformInput::KeyUp(_) => {
1970            drop(lock);
1971            run_callback(event)
1972        }
1973
1974        _ => NO,
1975    }
1976}
1977
1978extern "C" fn handle_view_event(this: &Object, _: Sel, native_event: id) {
1979    let window_state = unsafe { get_window_state(this) };
1980    let weak_window_state = Arc::downgrade(&window_state);
1981    let mut lock = window_state.as_ref().lock();
1982    let window_height = lock.content_size().height;
1983    let event = unsafe { platform_input_from_native(native_event, Some(window_height)) };
1984
1985    if let Some(mut event) = event {
1986        match &mut event {
1987            PlatformInput::MouseDown(
1988                event @ MouseDownEvent {
1989                    button: MouseButton::Left,
1990                    modifiers: Modifiers { control: true, .. },
1991                    ..
1992                },
1993            ) => {
1994                // On mac, a ctrl-left click should be handled as a right click.
1995                *event = MouseDownEvent {
1996                    button: MouseButton::Right,
1997                    modifiers: Modifiers {
1998                        control: false,
1999                        ..event.modifiers
2000                    },
2001                    click_count: 1,
2002                    ..*event
2003                };
2004            }
2005
2006            // Handles focusing click.
2007            PlatformInput::MouseDown(
2008                event @ MouseDownEvent {
2009                    button: MouseButton::Left,
2010                    ..
2011                },
2012            ) if (lock.first_mouse) => {
2013                *event = MouseDownEvent {
2014                    first_mouse: true,
2015                    ..*event
2016                };
2017                lock.first_mouse = false;
2018            }
2019
2020            // Because we map a ctrl-left_down to a right_down -> right_up let's ignore
2021            // the ctrl-left_up to avoid having a mismatch in button down/up events if the
2022            // user is still holding ctrl when releasing the left mouse button
2023            PlatformInput::MouseUp(
2024                event @ MouseUpEvent {
2025                    button: MouseButton::Left,
2026                    modifiers: Modifiers { control: true, .. },
2027                    ..
2028                },
2029            ) => {
2030                *event = MouseUpEvent {
2031                    button: MouseButton::Right,
2032                    modifiers: Modifiers {
2033                        control: false,
2034                        ..event.modifiers
2035                    },
2036                    click_count: 1,
2037                    ..*event
2038                };
2039            }
2040
2041            _ => {}
2042        };
2043
2044        match &event {
2045            PlatformInput::MouseDown(_) => {
2046                drop(lock);
2047                unsafe {
2048                    let input_context: id = msg_send![this, inputContext];
2049                    msg_send![input_context, handleEvent: native_event]
2050                }
2051                lock = window_state.as_ref().lock();
2052            }
2053            PlatformInput::MouseMove(
2054                event @ MouseMoveEvent {
2055                    pressed_button: Some(_),
2056                    ..
2057                },
2058            ) => {
2059                // Synthetic drag is used for selecting long buffer contents while buffer is being scrolled.
2060                // External file drag and drop is able to emit its own synthetic mouse events which will conflict
2061                // with these ones.
2062                if !lock.external_files_dragged {
2063                    lock.synthetic_drag_counter += 1;
2064                    let executor = lock.foreground_executor.clone();
2065                    executor
2066                        .spawn(synthetic_drag(
2067                            weak_window_state,
2068                            lock.synthetic_drag_counter,
2069                            event.clone(),
2070                            lock.background_executor.clone(),
2071                        ))
2072                        .detach();
2073                }
2074            }
2075
2076            PlatformInput::MouseUp(MouseUpEvent { .. }) => {
2077                lock.synthetic_drag_counter += 1;
2078            }
2079
2080            PlatformInput::ModifiersChanged(ModifiersChangedEvent {
2081                modifiers,
2082                capslock,
2083            }) => {
2084                // Only raise modifiers changed event when they have actually changed
2085                if let Some(PlatformInput::ModifiersChanged(ModifiersChangedEvent {
2086                    modifiers: prev_modifiers,
2087                    capslock: prev_capslock,
2088                })) = &lock.previous_modifiers_changed_event
2089                    && prev_modifiers == modifiers
2090                    && prev_capslock == capslock
2091                {
2092                    return;
2093                }
2094
2095                lock.previous_modifiers_changed_event = Some(event.clone());
2096            }
2097
2098            _ => {}
2099        }
2100
2101        if let Some(mut callback) = lock.event_callback.take() {
2102            drop(lock);
2103            callback(event);
2104            window_state.lock().event_callback = Some(callback);
2105        }
2106    }
2107}
2108
2109extern "C" fn window_did_change_occlusion_state(this: &Object, _: Sel, _: id) {
2110    let window_state = unsafe { get_window_state(this) };
2111    let lock = &mut *window_state.lock();
2112    unsafe {
2113        if lock
2114            .native_window
2115            .occlusionState()
2116            .contains(NSWindowOcclusionState::NSWindowOcclusionStateVisible)
2117        {
2118            lock.move_traffic_light();
2119            lock.start_display_link();
2120        } else {
2121            lock.stop_display_link();
2122        }
2123    }
2124}
2125
2126extern "C" fn window_did_resize(this: &Object, _: Sel, _: id) {
2127    let window_state = unsafe { get_window_state(this) };
2128    window_state.as_ref().lock().move_traffic_light();
2129}
2130
2131extern "C" fn window_will_enter_fullscreen(this: &Object, _: Sel, _: id) {
2132    let window_state = unsafe { get_window_state(this) };
2133    let mut lock = window_state.as_ref().lock();
2134    lock.fullscreen_restore_bounds = lock.bounds();
2135
2136    let min_version = NSOperatingSystemVersion::new(15, 3, 0);
2137
2138    if is_macos_version_at_least(min_version) {
2139        unsafe {
2140            lock.native_window.setTitlebarAppearsTransparent_(NO);
2141        }
2142    }
2143}
2144
2145extern "C" fn window_will_exit_fullscreen(this: &Object, _: Sel, _: id) {
2146    let window_state = unsafe { get_window_state(this) };
2147    let lock = window_state.as_ref().lock();
2148
2149    let min_version = NSOperatingSystemVersion::new(15, 3, 0);
2150
2151    if is_macos_version_at_least(min_version) && lock.transparent_titlebar {
2152        unsafe {
2153            lock.native_window.setTitlebarAppearsTransparent_(YES);
2154        }
2155    }
2156}
2157
2158pub(crate) fn is_macos_version_at_least(version: NSOperatingSystemVersion) -> bool {
2159    unsafe { NSProcessInfo::processInfo(nil).isOperatingSystemAtLeastVersion(version) }
2160}
2161
2162extern "C" fn window_did_move(this: &Object, _: Sel, _: id) {
2163    let window_state = unsafe { get_window_state(this) };
2164    let mut lock = window_state.as_ref().lock();
2165    if let Some(mut callback) = lock.moved_callback.take() {
2166        drop(lock);
2167        callback();
2168        window_state.lock().moved_callback = Some(callback);
2169    }
2170}
2171
2172// Update the window scale factor and drawable size, and call the resize callback if any.
2173fn update_window_scale_factor(window_state: &Arc<Mutex<MacWindowState>>) {
2174    let mut lock = window_state.as_ref().lock();
2175    let scale_factor = lock.scale_factor();
2176    let size = lock.content_size();
2177    let drawable_size = size.to_device_pixels(scale_factor);
2178    if let Some(layer) = lock.renderer.layer() {
2179        unsafe {
2180            let _: () = msg_send![
2181                layer,
2182                setContentsScale: scale_factor as f64
2183            ];
2184        }
2185    }
2186
2187    lock.renderer.update_drawable_size(drawable_size);
2188
2189    if let Some(mut callback) = lock.resize_callback.take() {
2190        let content_size = lock.content_size();
2191        let scale_factor = lock.scale_factor();
2192        drop(lock);
2193        callback(content_size, scale_factor);
2194        window_state.as_ref().lock().resize_callback = Some(callback);
2195    };
2196}
2197
2198extern "C" fn window_did_change_screen(this: &Object, _: Sel, _: id) {
2199    let window_state = unsafe { get_window_state(this) };
2200    let mut lock = window_state.as_ref().lock();
2201    lock.start_display_link();
2202    drop(lock);
2203    update_window_scale_factor(&window_state);
2204}
2205
2206extern "C" fn window_did_change_key_status(this: &Object, selector: Sel, _: id) {
2207    let window_state = unsafe { get_window_state(this) };
2208    let lock = window_state.lock();
2209    let is_active = unsafe { lock.native_window.isKeyWindow() == YES };
2210
2211    // When opening a pop-up while the application isn't active, Cocoa sends a spurious
2212    // `windowDidBecomeKey` message to the previous key window even though that window
2213    // isn't actually key. This causes a bug if the application is later activated while
2214    // the pop-up is still open, making it impossible to activate the previous key window
2215    // even if the pop-up gets closed. The only way to activate it again is to de-activate
2216    // the app and re-activate it, which is a pretty bad UX.
2217    // The following code detects the spurious event and invokes `resignKeyWindow`:
2218    // in theory, we're not supposed to invoke this method manually but it balances out
2219    // the spurious `becomeKeyWindow` event and helps us work around that bug.
2220    if selector == sel!(windowDidBecomeKey:) && !is_active {
2221        let native_window = lock.native_window;
2222        drop(lock);
2223        unsafe {
2224            let _: () = msg_send![native_window, resignKeyWindow];
2225        }
2226        return;
2227    }
2228
2229    let executor = lock.foreground_executor.clone();
2230    drop(lock);
2231
2232    // When a window becomes active, trigger an immediate synchronous frame request to prevent
2233    // tab flicker when switching between windows in native tabs mode.
2234    //
2235    // This is only done on subsequent activations (not the first) to ensure the initial focus
2236    // path is properly established. Without this guard, the focus state would remain unset until
2237    // the first mouse click, causing keybindings to be non-functional.
2238    if selector == sel!(windowDidBecomeKey:) && is_active {
2239        let window_state = unsafe { get_window_state(this) };
2240        let mut lock = window_state.lock();
2241
2242        if lock.activated_least_once {
2243            if let Some(mut callback) = lock.request_frame_callback.take() {
2244                lock.renderer.set_presents_with_transaction(true);
2245                lock.stop_display_link();
2246                drop(lock);
2247                callback(Default::default());
2248
2249                let mut lock = window_state.lock();
2250                lock.request_frame_callback = Some(callback);
2251                lock.renderer.set_presents_with_transaction(false);
2252                lock.start_display_link();
2253            }
2254        } else {
2255            lock.activated_least_once = true;
2256        }
2257    }
2258
2259    executor
2260        .spawn(async move {
2261            let mut lock = window_state.as_ref().lock();
2262            if is_active {
2263                lock.move_traffic_light();
2264            }
2265
2266            if let Some(mut callback) = lock.activate_callback.take() {
2267                drop(lock);
2268                callback(is_active);
2269                window_state.lock().activate_callback = Some(callback);
2270            };
2271        })
2272        .detach();
2273}
2274
2275extern "C" fn window_should_close(this: &Object, _: Sel, _: id) -> BOOL {
2276    let window_state = unsafe { get_window_state(this) };
2277    let mut lock = window_state.as_ref().lock();
2278    if let Some(mut callback) = lock.should_close_callback.take() {
2279        drop(lock);
2280        let should_close = callback();
2281        window_state.lock().should_close_callback = Some(callback);
2282        should_close as BOOL
2283    } else {
2284        YES
2285    }
2286}
2287
2288extern "C" fn close_window(this: &Object, _: Sel) {
2289    unsafe {
2290        let close_callback = {
2291            let window_state = get_window_state(this);
2292            let mut lock = window_state.as_ref().lock();
2293            lock.closed.store(true, Ordering::Release);
2294            lock.close_callback.take()
2295        };
2296
2297        if let Some(callback) = close_callback {
2298            callback();
2299        }
2300
2301        let _: () = msg_send![super(this, class!(NSWindow)), close];
2302    }
2303}
2304
2305extern "C" fn make_backing_layer(this: &Object, _: Sel) -> id {
2306    let window_state = unsafe { get_window_state(this) };
2307    let window_state = window_state.as_ref().lock();
2308    window_state.renderer.layer_ptr() as id
2309}
2310
2311extern "C" fn view_did_change_backing_properties(this: &Object, _: Sel) {
2312    let window_state = unsafe { get_window_state(this) };
2313    update_window_scale_factor(&window_state);
2314}
2315
2316extern "C" fn set_frame_size(this: &Object, _: Sel, size: NSSize) {
2317    fn convert(value: NSSize) -> Size<Pixels> {
2318        Size {
2319            width: px(value.width as f32),
2320            height: px(value.height as f32),
2321        }
2322    }
2323
2324    let window_state = unsafe { get_window_state(this) };
2325    let mut lock = window_state.as_ref().lock();
2326
2327    let new_size = convert(size);
2328    let old_size = unsafe {
2329        let old_frame: NSRect = msg_send![this, frame];
2330        convert(old_frame.size)
2331    };
2332
2333    if old_size == new_size {
2334        return;
2335    }
2336
2337    unsafe {
2338        let _: () = msg_send![super(this, class!(NSView)), setFrameSize: size];
2339    }
2340
2341    let scale_factor = lock.scale_factor();
2342    let drawable_size = new_size.to_device_pixels(scale_factor);
2343    lock.renderer.update_drawable_size(drawable_size);
2344
2345    if let Some(mut callback) = lock.resize_callback.take() {
2346        let content_size = lock.content_size();
2347        let scale_factor = lock.scale_factor();
2348        drop(lock);
2349        callback(content_size, scale_factor);
2350        window_state.lock().resize_callback = Some(callback);
2351    };
2352}
2353
2354extern "C" fn display_layer(this: &Object, _: Sel, _: id) {
2355    let window_state = unsafe { get_window_state(this) };
2356    let mut lock = window_state.lock();
2357    if let Some(mut callback) = lock.request_frame_callback.take() {
2358        lock.renderer.set_presents_with_transaction(true);
2359        lock.stop_display_link();
2360        drop(lock);
2361        callback(Default::default());
2362
2363        let mut lock = window_state.lock();
2364        lock.request_frame_callback = Some(callback);
2365        lock.renderer.set_presents_with_transaction(false);
2366        lock.start_display_link();
2367    }
2368}
2369
2370extern "C" fn step(view: *mut c_void) {
2371    let view = view as id;
2372    let window_state = unsafe { get_window_state(&*view) };
2373    let mut lock = window_state.lock();
2374
2375    if let Some(mut callback) = lock.request_frame_callback.take() {
2376        drop(lock);
2377        callback(Default::default());
2378        window_state.lock().request_frame_callback = Some(callback);
2379    }
2380}
2381
2382extern "C" fn valid_attributes_for_marked_text(_: &Object, _: Sel) -> id {
2383    unsafe { msg_send![class!(NSArray), array] }
2384}
2385
2386extern "C" fn has_marked_text(this: &Object, _: Sel) -> BOOL {
2387    let has_marked_text_result =
2388        with_input_handler(this, |input_handler| input_handler.marked_text_range()).flatten();
2389
2390    has_marked_text_result.is_some() as BOOL
2391}
2392
2393extern "C" fn marked_range(this: &Object, _: Sel) -> NSRange {
2394    let marked_range_result =
2395        with_input_handler(this, |input_handler| input_handler.marked_text_range()).flatten();
2396
2397    marked_range_result.map_or(NSRange::invalid(), |range| range.into())
2398}
2399
2400extern "C" fn selected_range(this: &Object, _: Sel) -> NSRange {
2401    let selected_range_result = with_input_handler(this, |input_handler| {
2402        input_handler.selected_text_range(false)
2403    })
2404    .flatten();
2405
2406    selected_range_result.map_or(NSRange::invalid(), |selection| selection.range.into())
2407}
2408
2409extern "C" fn first_rect_for_character_range(
2410    this: &Object,
2411    _: Sel,
2412    range: NSRange,
2413    _: id,
2414) -> NSRect {
2415    let frame = get_frame(this);
2416    with_input_handler(this, |input_handler| {
2417        input_handler.bounds_for_range(range.to_range()?)
2418    })
2419    .flatten()
2420    .map_or(
2421        NSRect::new(NSPoint::new(0., 0.), NSSize::new(0., 0.)),
2422        |bounds| {
2423            NSRect::new(
2424                NSPoint::new(
2425                    frame.origin.x + bounds.origin.x.as_f32() as f64,
2426                    frame.origin.y + frame.size.height
2427                        - bounds.origin.y.as_f32() as f64
2428                        - bounds.size.height.as_f32() as f64,
2429                ),
2430                NSSize::new(
2431                    bounds.size.width.as_f32() as f64,
2432                    bounds.size.height.as_f32() as f64,
2433                ),
2434            )
2435        },
2436    )
2437}
2438
2439fn get_frame(this: &Object) -> NSRect {
2440    unsafe {
2441        let state = get_window_state(this);
2442        let lock = state.lock();
2443        let mut frame = NSWindow::frame(lock.native_window);
2444        let content_layout_rect: CGRect = msg_send![lock.native_window, contentLayoutRect];
2445        let style_mask: NSWindowStyleMask = msg_send![lock.native_window, styleMask];
2446        if !style_mask.contains(NSWindowStyleMask::NSFullSizeContentViewWindowMask) {
2447            frame.origin.y -= frame.size.height - content_layout_rect.size.height;
2448        }
2449        frame
2450    }
2451}
2452
2453extern "C" fn insert_text(this: &Object, _: Sel, text: id, replacement_range: NSRange) {
2454    unsafe {
2455        let is_attributed_string: BOOL =
2456            msg_send![text, isKindOfClass: [class!(NSAttributedString)]];
2457        let text: id = if is_attributed_string == YES {
2458            msg_send![text, string]
2459        } else {
2460            text
2461        };
2462
2463        let text = text.to_str();
2464        let replacement_range = replacement_range.to_range();
2465        with_input_handler(this, |input_handler| {
2466            input_handler.replace_text_in_range(replacement_range, text)
2467        });
2468    }
2469}
2470
2471extern "C" fn set_marked_text(
2472    this: &Object,
2473    _: Sel,
2474    text: id,
2475    selected_range: NSRange,
2476    replacement_range: NSRange,
2477) {
2478    unsafe {
2479        let is_attributed_string: BOOL =
2480            msg_send![text, isKindOfClass: [class!(NSAttributedString)]];
2481        let text: id = if is_attributed_string == YES {
2482            msg_send![text, string]
2483        } else {
2484            text
2485        };
2486        let selected_range = selected_range.to_range();
2487        let replacement_range = replacement_range.to_range();
2488        let text = text.to_str();
2489        with_input_handler(this, |input_handler| {
2490            input_handler.replace_and_mark_text_in_range(replacement_range, text, selected_range)
2491        });
2492    }
2493}
2494extern "C" fn unmark_text(this: &Object, _: Sel) {
2495    with_input_handler(this, |input_handler| input_handler.unmark_text());
2496}
2497
2498extern "C" fn attributed_substring_for_proposed_range(
2499    this: &Object,
2500    _: Sel,
2501    range: NSRange,
2502    actual_range: *mut c_void,
2503) -> id {
2504    with_input_handler(this, |input_handler| {
2505        let range = range.to_range()?;
2506        if range.is_empty() {
2507            return None;
2508        }
2509        let mut adjusted: Option<Range<usize>> = None;
2510
2511        let selected_text = input_handler.text_for_range(range.clone(), &mut adjusted)?;
2512        if let Some(adjusted) = adjusted
2513            && adjusted != range
2514        {
2515            unsafe { (actual_range as *mut NSRange).write(NSRange::from(adjusted)) };
2516        }
2517        unsafe {
2518            let string: id = msg_send![class!(NSAttributedString), alloc];
2519            let string: id = msg_send![string, initWithString: ns_string(&selected_text)];
2520            Some(string)
2521        }
2522    })
2523    .flatten()
2524    .unwrap_or(nil)
2525}
2526
2527// We ignore which selector it asks us to do because the user may have
2528// bound the shortcut to something else.
2529extern "C" fn do_command_by_selector(this: &Object, _: Sel, _: Sel) {
2530    let state = unsafe { get_window_state(this) };
2531    let mut lock = state.as_ref().lock();
2532    let keystroke = lock.keystroke_for_do_command.take();
2533    let mut event_callback = lock.event_callback.take();
2534    drop(lock);
2535
2536    if let Some((keystroke, callback)) = keystroke.zip(event_callback.as_mut()) {
2537        let handled = (callback)(PlatformInput::KeyDown(KeyDownEvent {
2538            keystroke,
2539            is_held: false,
2540            prefer_character_input: false,
2541        }));
2542        state.as_ref().lock().do_command_handled = Some(!handled.propagate);
2543    }
2544
2545    state.as_ref().lock().event_callback = event_callback;
2546}
2547
2548extern "C" fn view_did_change_effective_appearance(this: &Object, _: Sel) {
2549    unsafe {
2550        let state = get_window_state(this);
2551        let mut lock = state.as_ref().lock();
2552        if let Some(mut callback) = lock.appearance_changed_callback.take() {
2553            drop(lock);
2554            callback();
2555            state.lock().appearance_changed_callback = Some(callback);
2556        }
2557    }
2558}
2559
2560extern "C" fn accepts_first_mouse(this: &Object, _: Sel, _: id) -> BOOL {
2561    let window_state = unsafe { get_window_state(this) };
2562    let mut lock = window_state.as_ref().lock();
2563    lock.first_mouse = true;
2564    YES
2565}
2566
2567extern "C" fn character_index_for_point(this: &Object, _: Sel, position: NSPoint) -> u64 {
2568    let position = screen_point_to_gpui_point(this, position);
2569    with_input_handler(this, |input_handler| {
2570        input_handler.character_index_for_point(position)
2571    })
2572    .flatten()
2573    .map(|index| index as u64)
2574    .unwrap_or(NSNotFound as u64)
2575}
2576
2577fn screen_point_to_gpui_point(this: &Object, position: NSPoint) -> Point<Pixels> {
2578    let frame = get_frame(this);
2579    let window_x = position.x - frame.origin.x;
2580    let window_y = frame.size.height - (position.y - frame.origin.y);
2581
2582    point(px(window_x as f32), px(window_y as f32))
2583}
2584
2585extern "C" fn dragging_entered(this: &Object, _: Sel, dragging_info: id) -> NSDragOperation {
2586    let window_state = unsafe { get_window_state(this) };
2587    let position = drag_event_position(&window_state, dragging_info);
2588    let paths = external_paths_from_event(dragging_info);
2589    if let Some(event) = paths.map(|paths| FileDropEvent::Entered { position, paths })
2590        && send_file_drop_event(window_state, event)
2591    {
2592        return NSDragOperationCopy;
2593    }
2594    NSDragOperationNone
2595}
2596
2597extern "C" fn dragging_updated(this: &Object, _: Sel, dragging_info: id) -> NSDragOperation {
2598    let window_state = unsafe { get_window_state(this) };
2599    let position = drag_event_position(&window_state, dragging_info);
2600    if send_file_drop_event(window_state, FileDropEvent::Pending { position }) {
2601        NSDragOperationCopy
2602    } else {
2603        NSDragOperationNone
2604    }
2605}
2606
2607extern "C" fn dragging_exited(this: &Object, _: Sel, _: id) {
2608    let window_state = unsafe { get_window_state(this) };
2609    send_file_drop_event(window_state, FileDropEvent::Exited);
2610}
2611
2612extern "C" fn perform_drag_operation(this: &Object, _: Sel, dragging_info: id) -> BOOL {
2613    let window_state = unsafe { get_window_state(this) };
2614    let position = drag_event_position(&window_state, dragging_info);
2615    send_file_drop_event(window_state, FileDropEvent::Submit { position }).to_objc()
2616}
2617
2618fn external_paths_from_event(dragging_info: *mut Object) -> Option<ExternalPaths> {
2619    let mut paths = SmallVec::new();
2620    let pasteboard: id = unsafe { msg_send![dragging_info, draggingPasteboard] };
2621    let filenames = unsafe { NSPasteboard::propertyListForType(pasteboard, NSFilenamesPboardType) };
2622    if filenames == nil {
2623        return None;
2624    }
2625    for file in unsafe { filenames.iter() } {
2626        let path = unsafe {
2627            let f = NSString::UTF8String(file);
2628            CStr::from_ptr(f).to_string_lossy().into_owned()
2629        };
2630        paths.push(PathBuf::from(path))
2631    }
2632    Some(ExternalPaths(paths))
2633}
2634
2635extern "C" fn conclude_drag_operation(this: &Object, _: Sel, _: id) {
2636    let window_state = unsafe { get_window_state(this) };
2637    send_file_drop_event(window_state, FileDropEvent::Exited);
2638}
2639
2640async fn synthetic_drag(
2641    window_state: Weak<Mutex<MacWindowState>>,
2642    drag_id: usize,
2643    event: MouseMoveEvent,
2644    executor: BackgroundExecutor,
2645) {
2646    loop {
2647        executor.timer(Duration::from_millis(16)).await;
2648        if let Some(window_state) = window_state.upgrade() {
2649            let mut lock = window_state.lock();
2650            if lock.synthetic_drag_counter == drag_id {
2651                if let Some(mut callback) = lock.event_callback.take() {
2652                    drop(lock);
2653                    callback(PlatformInput::MouseMove(event.clone()));
2654                    window_state.lock().event_callback = Some(callback);
2655                }
2656            } else {
2657                break;
2658            }
2659        }
2660    }
2661}
2662
2663/// Sends the specified FileDropEvent using `PlatformInput::FileDrop` to the window
2664/// state and updates the window state according to the event passed.
2665fn send_file_drop_event(
2666    window_state: Arc<Mutex<MacWindowState>>,
2667    file_drop_event: FileDropEvent,
2668) -> bool {
2669    let external_files_dragged = match file_drop_event {
2670        FileDropEvent::Entered { .. } => Some(true),
2671        FileDropEvent::Exited => Some(false),
2672        _ => None,
2673    };
2674
2675    let mut lock = window_state.lock();
2676    if let Some(mut callback) = lock.event_callback.take() {
2677        drop(lock);
2678        callback(PlatformInput::FileDrop(file_drop_event));
2679        let mut lock = window_state.lock();
2680        lock.event_callback = Some(callback);
2681        if let Some(external_files_dragged) = external_files_dragged {
2682            lock.external_files_dragged = external_files_dragged;
2683        }
2684        true
2685    } else {
2686        false
2687    }
2688}
2689
2690fn drag_event_position(window_state: &Mutex<MacWindowState>, dragging_info: id) -> Point<Pixels> {
2691    let drag_location: NSPoint = unsafe { msg_send![dragging_info, draggingLocation] };
2692    convert_mouse_position(drag_location, window_state.lock().content_size().height)
2693}
2694
2695fn with_input_handler<F, R>(window: &Object, f: F) -> Option<R>
2696where
2697    F: FnOnce(&mut PlatformInputHandler) -> R,
2698{
2699    let window_state = unsafe { get_window_state(window) };
2700    let mut lock = window_state.as_ref().lock();
2701    if let Some(mut input_handler) = lock.input_handler.take() {
2702        drop(lock);
2703        let result = f(&mut input_handler);
2704        window_state.lock().input_handler = Some(input_handler);
2705        Some(result)
2706    } else {
2707        None
2708    }
2709}
2710
2711unsafe fn display_id_for_screen(screen: id) -> CGDirectDisplayID {
2712    unsafe {
2713        let device_description = NSScreen::deviceDescription(screen);
2714        let screen_number_key: id = ns_string("NSScreenNumber");
2715        let screen_number = device_description.objectForKey_(screen_number_key);
2716        let screen_number: NSUInteger = msg_send![screen_number, unsignedIntegerValue];
2717        screen_number as CGDirectDisplayID
2718    }
2719}
2720
2721extern "C" fn blurred_view_init_with_frame(this: &Object, _: Sel, frame: NSRect) -> id {
2722    unsafe {
2723        let view = msg_send![super(this, class!(NSVisualEffectView)), initWithFrame: frame];
2724        // Use a colorless semantic material. The default value `AppearanceBased`, though not
2725        // manually set, is deprecated.
2726        NSVisualEffectView::setMaterial_(view, NSVisualEffectMaterial::Selection);
2727        NSVisualEffectView::setState_(view, NSVisualEffectState::Active);
2728        view
2729    }
2730}
2731
2732extern "C" fn blurred_view_update_layer(this: &Object, _: Sel) {
2733    unsafe {
2734        let _: () = msg_send![super(this, class!(NSVisualEffectView)), updateLayer];
2735        let layer: id = msg_send![this, layer];
2736        if !layer.is_null() {
2737            remove_layer_background(layer);
2738        }
2739    }
2740}
2741
2742unsafe fn remove_layer_background(layer: id) {
2743    unsafe {
2744        let _: () = msg_send![layer, setBackgroundColor:nil];
2745
2746        let class_name: id = msg_send![layer, className];
2747        if class_name.isEqualToString("CAChameleonLayer") {
2748            // Remove the desktop tinting effect.
2749            let _: () = msg_send![layer, setHidden: YES];
2750            return;
2751        }
2752
2753        let filters: id = msg_send![layer, filters];
2754        if !filters.is_null() {
2755            // Remove the increased saturation.
2756            // The effect of a `CAFilter` or `CIFilter` is determined by its name, and the
2757            // `description` reflects its name and some parameters. Currently `NSVisualEffectView`
2758            // uses a `CAFilter` named "colorSaturate". If one day they switch to `CIFilter`, the
2759            // `description` will still contain "Saturat" ("... inputSaturation = ...").
2760            let test_string: id = ns_string("Saturat");
2761            let count = NSArray::count(filters);
2762            for i in 0..count {
2763                let description: id = msg_send![filters.objectAtIndex(i), description];
2764                let hit: BOOL = msg_send![description, containsString: test_string];
2765                if hit == NO {
2766                    continue;
2767                }
2768
2769                let all_indices = NSRange {
2770                    location: 0,
2771                    length: count,
2772                };
2773                let indices: id = msg_send![class!(NSMutableIndexSet), indexSet];
2774                let _: () = msg_send![indices, addIndexesInRange: all_indices];
2775                let _: () = msg_send![indices, removeIndex:i];
2776                let filtered: id = msg_send![filters, objectsAtIndexes: indices];
2777                let _: () = msg_send![layer, setFilters: filtered];
2778                break;
2779            }
2780        }
2781
2782        let sublayers: id = msg_send![layer, sublayers];
2783        if !sublayers.is_null() {
2784            let count = NSArray::count(sublayers);
2785            for i in 0..count {
2786                let sublayer = sublayers.objectAtIndex(i);
2787                remove_layer_background(sublayer);
2788            }
2789        }
2790    }
2791}
2792
2793extern "C" fn add_titlebar_accessory_view_controller(this: &Object, _: Sel, view_controller: id) {
2794    unsafe {
2795        let _: () = msg_send![super(this, class!(NSWindow)), addTitlebarAccessoryViewController: view_controller];
2796
2797        // Hide the native tab bar and set its height to 0, since we render our own.
2798        let accessory_view: id = msg_send![view_controller, view];
2799        let _: () = msg_send![accessory_view, setHidden: YES];
2800        let mut frame: NSRect = msg_send![accessory_view, frame];
2801        frame.size.height = 0.0;
2802        let _: () = msg_send![accessory_view, setFrame: frame];
2803    }
2804}
2805
2806extern "C" fn move_tab_to_new_window(this: &Object, _: Sel, _: id) {
2807    unsafe {
2808        let _: () = msg_send![super(this, class!(NSWindow)), moveTabToNewWindow:nil];
2809
2810        let window_state = get_window_state(this);
2811        let mut lock = window_state.as_ref().lock();
2812        if let Some(mut callback) = lock.move_tab_to_new_window_callback.take() {
2813            drop(lock);
2814            callback();
2815            window_state.lock().move_tab_to_new_window_callback = Some(callback);
2816        }
2817    }
2818}
2819
2820extern "C" fn merge_all_windows(this: &Object, _: Sel, _: id) {
2821    unsafe {
2822        let _: () = msg_send![super(this, class!(NSWindow)), mergeAllWindows:nil];
2823
2824        let window_state = get_window_state(this);
2825        let mut lock = window_state.as_ref().lock();
2826        if let Some(mut callback) = lock.merge_all_windows_callback.take() {
2827            drop(lock);
2828            callback();
2829            window_state.lock().merge_all_windows_callback = Some(callback);
2830        }
2831    }
2832}
2833
2834extern "C" fn select_next_tab(this: &Object, _sel: Sel, _id: id) {
2835    let window_state = unsafe { get_window_state(this) };
2836    let mut lock = window_state.as_ref().lock();
2837    if let Some(mut callback) = lock.select_next_tab_callback.take() {
2838        drop(lock);
2839        callback();
2840        window_state.lock().select_next_tab_callback = Some(callback);
2841    }
2842}
2843
2844extern "C" fn select_previous_tab(this: &Object, _sel: Sel, _id: id) {
2845    let window_state = unsafe { get_window_state(this) };
2846    let mut lock = window_state.as_ref().lock();
2847    if let Some(mut callback) = lock.select_previous_tab_callback.take() {
2848        drop(lock);
2849        callback();
2850        window_state.lock().select_previous_tab_callback = Some(callback);
2851    }
2852}
2853
2854extern "C" fn toggle_tab_bar(this: &Object, _sel: Sel, _id: id) {
2855    unsafe {
2856        let _: () = msg_send![super(this, class!(NSWindow)), toggleTabBar:nil];
2857
2858        let window_state = get_window_state(this);
2859        let mut lock = window_state.as_ref().lock();
2860        lock.move_traffic_light();
2861
2862        if let Some(mut callback) = lock.toggle_tab_bar_callback.take() {
2863            drop(lock);
2864            callback();
2865            window_state.lock().toggle_tab_bar_callback = Some(callback);
2866        }
2867    }
2868}