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 parking_lot::Mutex;
  53use raw_window_handle as rwh;
  54use smallvec::SmallVec;
  55use std::{
  56    cell::Cell,
  57    ffi::{CStr, c_void},
  58    mem,
  59    ops::Range,
  60    path::PathBuf,
  61    ptr::{self, NonNull},
  62    rc::Rc,
  63    sync::{
  64        Arc, Weak,
  65        atomic::{AtomicBool, Ordering},
  66    },
  67    time::Duration,
  68};
  69use util::ResultExt;
  70
  71const WINDOW_STATE_IVAR: &str = "windowState";
  72
  73static mut WINDOW_CLASS: *const Class = ptr::null();
  74static mut PANEL_CLASS: *const Class = ptr::null();
  75static mut VIEW_CLASS: *const Class = ptr::null();
  76static mut BLURRED_VIEW_CLASS: *const Class = ptr::null();
  77
  78#[allow(non_upper_case_globals)]
  79const NSWindowStyleMaskNonactivatingPanel: NSWindowStyleMask =
  80    NSWindowStyleMask::from_bits_retain(1 << 7);
  81// WindowLevel const value ref: https://docs.rs/core-graphics2/0.4.1/src/core_graphics2/window_level.rs.html
  82#[allow(non_upper_case_globals)]
  83const NSNormalWindowLevel: NSInteger = 0;
  84#[allow(non_upper_case_globals)]
  85const NSFloatingWindowLevel: NSInteger = 3;
  86#[allow(non_upper_case_globals)]
  87const NSPopUpWindowLevel: NSInteger = 101;
  88#[allow(non_upper_case_globals)]
  89const NSTrackingMouseEnteredAndExited: NSUInteger = 0x01;
  90#[allow(non_upper_case_globals)]
  91const NSTrackingMouseMoved: NSUInteger = 0x02;
  92#[allow(non_upper_case_globals)]
  93const NSTrackingActiveAlways: NSUInteger = 0x80;
  94#[allow(non_upper_case_globals)]
  95const NSTrackingInVisibleRect: NSUInteger = 0x200;
  96#[allow(non_upper_case_globals)]
  97const NSWindowAnimationBehaviorUtilityWindow: NSInteger = 4;
  98#[allow(non_upper_case_globals)]
  99const NSViewLayerContentsRedrawDuringViewResize: NSInteger = 2;
 100// https://developer.apple.com/documentation/appkit/nsdragoperation
 101type NSDragOperation = NSUInteger;
 102#[allow(non_upper_case_globals)]
 103const NSDragOperationNone: NSDragOperation = 0;
 104#[allow(non_upper_case_globals)]
 105const NSDragOperationCopy: NSDragOperation = 1;
 106#[derive(PartialEq)]
 107pub enum UserTabbingPreference {
 108    Never,
 109    Always,
 110    InFullScreen,
 111}
 112
 113#[link(name = "CoreGraphics", kind = "framework")]
 114unsafe extern "C" {
 115    // Widely used private APIs; Apple uses them for their Terminal.app.
 116    fn CGSMainConnectionID() -> id;
 117    fn CGSSetWindowBackgroundBlurRadius(
 118        connection_id: id,
 119        window_id: NSInteger,
 120        radius: i64,
 121    ) -> i32;
 122}
 123
 124#[ctor]
 125unsafe fn build_classes() {
 126    unsafe {
 127        WINDOW_CLASS = build_window_class("GPUIWindow", class!(NSWindow));
 128        PANEL_CLASS = build_window_class("GPUIPanel", class!(NSPanel));
 129        VIEW_CLASS = {
 130            let mut decl = ClassDecl::new("GPUIView", class!(NSView)).unwrap();
 131            decl.add_ivar::<*mut c_void>(WINDOW_STATE_IVAR);
 132            unsafe {
 133                decl.add_method(sel!(dealloc), dealloc_view as extern "C" fn(&Object, Sel));
 134
 135                decl.add_method(
 136                    sel!(performKeyEquivalent:),
 137                    handle_key_equivalent as extern "C" fn(&Object, Sel, id) -> BOOL,
 138                );
 139                decl.add_method(
 140                    sel!(keyDown:),
 141                    handle_key_down as extern "C" fn(&Object, Sel, id),
 142                );
 143                decl.add_method(
 144                    sel!(keyUp:),
 145                    handle_key_up as extern "C" fn(&Object, Sel, id),
 146                );
 147                decl.add_method(
 148                    sel!(mouseDown:),
 149                    handle_view_event as extern "C" fn(&Object, Sel, id),
 150                );
 151                decl.add_method(
 152                    sel!(mouseUp:),
 153                    handle_view_event as extern "C" fn(&Object, Sel, id),
 154                );
 155                decl.add_method(
 156                    sel!(rightMouseDown:),
 157                    handle_view_event as extern "C" fn(&Object, Sel, id),
 158                );
 159                decl.add_method(
 160                    sel!(rightMouseUp:),
 161                    handle_view_event as extern "C" fn(&Object, Sel, id),
 162                );
 163                decl.add_method(
 164                    sel!(otherMouseDown:),
 165                    handle_view_event as extern "C" fn(&Object, Sel, id),
 166                );
 167                decl.add_method(
 168                    sel!(otherMouseUp:),
 169                    handle_view_event as extern "C" fn(&Object, Sel, id),
 170                );
 171                decl.add_method(
 172                    sel!(mouseMoved:),
 173                    handle_view_event as extern "C" fn(&Object, Sel, id),
 174                );
 175                decl.add_method(
 176                    sel!(pressureChangeWithEvent:),
 177                    handle_view_event as extern "C" fn(&Object, Sel, id),
 178                );
 179                decl.add_method(
 180                    sel!(mouseExited:),
 181                    handle_view_event as extern "C" fn(&Object, Sel, id),
 182                );
 183                decl.add_method(
 184                    sel!(magnifyWithEvent:),
 185                    handle_view_event as extern "C" fn(&Object, Sel, id),
 186                );
 187                decl.add_method(
 188                    sel!(mouseDragged:),
 189                    handle_view_event as extern "C" fn(&Object, Sel, id),
 190                );
 191                decl.add_method(
 192                    sel!(rightMouseDragged:),
 193                    handle_view_event as extern "C" fn(&Object, Sel, id),
 194                );
 195                decl.add_method(
 196                    sel!(otherMouseDragged:),
 197                    handle_view_event as extern "C" fn(&Object, Sel, id),
 198                );
 199                decl.add_method(
 200                    sel!(scrollWheel:),
 201                    handle_view_event as extern "C" fn(&Object, Sel, id),
 202                );
 203                decl.add_method(
 204                    sel!(swipeWithEvent:),
 205                    handle_view_event as extern "C" fn(&Object, Sel, id),
 206                );
 207                decl.add_method(
 208                    sel!(flagsChanged:),
 209                    handle_view_event as extern "C" fn(&Object, Sel, id),
 210                );
 211
 212                decl.add_method(
 213                    sel!(makeBackingLayer),
 214                    make_backing_layer as extern "C" fn(&Object, Sel) -> id,
 215                );
 216
 217                decl.add_protocol(Protocol::get("CALayerDelegate").unwrap());
 218                decl.add_method(
 219                    sel!(viewDidChangeBackingProperties),
 220                    view_did_change_backing_properties as extern "C" fn(&Object, Sel),
 221                );
 222                decl.add_method(
 223                    sel!(setFrameSize:),
 224                    set_frame_size as extern "C" fn(&Object, Sel, NSSize),
 225                );
 226                decl.add_method(
 227                    sel!(displayLayer:),
 228                    display_layer as extern "C" fn(&Object, Sel, id),
 229                );
 230
 231                decl.add_protocol(Protocol::get("NSTextInputClient").unwrap());
 232                decl.add_method(
 233                    sel!(validAttributesForMarkedText),
 234                    valid_attributes_for_marked_text as extern "C" fn(&Object, Sel) -> id,
 235                );
 236                decl.add_method(
 237                    sel!(hasMarkedText),
 238                    has_marked_text as extern "C" fn(&Object, Sel) -> BOOL,
 239                );
 240                decl.add_method(
 241                    sel!(markedRange),
 242                    marked_range as extern "C" fn(&Object, Sel) -> NSRange,
 243                );
 244                decl.add_method(
 245                    sel!(selectedRange),
 246                    selected_range as extern "C" fn(&Object, Sel) -> NSRange,
 247                );
 248                decl.add_method(
 249                    sel!(firstRectForCharacterRange:actualRange:),
 250                    first_rect_for_character_range
 251                        as extern "C" fn(&Object, Sel, NSRange, id) -> NSRect,
 252                );
 253                decl.add_method(
 254                    sel!(insertText:replacementRange:),
 255                    insert_text as extern "C" fn(&Object, Sel, id, NSRange),
 256                );
 257                decl.add_method(
 258                    sel!(setMarkedText:selectedRange:replacementRange:),
 259                    set_marked_text as extern "C" fn(&Object, Sel, id, NSRange, NSRange),
 260                );
 261                decl.add_method(sel!(unmarkText), unmark_text as extern "C" fn(&Object, Sel));
 262                decl.add_method(
 263                    sel!(attributedSubstringForProposedRange:actualRange:),
 264                    attributed_substring_for_proposed_range
 265                        as extern "C" fn(&Object, Sel, NSRange, *mut c_void) -> id,
 266                );
 267                decl.add_method(
 268                    sel!(viewDidChangeEffectiveAppearance),
 269                    view_did_change_effective_appearance as extern "C" fn(&Object, Sel),
 270                );
 271
 272                // Suppress beep on keystrokes with modifier keys.
 273                decl.add_method(
 274                    sel!(doCommandBySelector:),
 275                    do_command_by_selector as extern "C" fn(&Object, Sel, Sel),
 276                );
 277
 278                decl.add_method(
 279                    sel!(acceptsFirstMouse:),
 280                    accepts_first_mouse as extern "C" fn(&Object, Sel, id) -> BOOL,
 281                );
 282
 283                decl.add_method(
 284                    sel!(characterIndexForPoint:),
 285                    character_index_for_point as extern "C" fn(&Object, Sel, NSPoint) -> u64,
 286                );
 287            }
 288            decl.register()
 289        };
 290        BLURRED_VIEW_CLASS = {
 291            let mut decl = ClassDecl::new("BlurredView", class!(NSVisualEffectView)).unwrap();
 292            unsafe {
 293                decl.add_method(
 294                    sel!(initWithFrame:),
 295                    blurred_view_init_with_frame as extern "C" fn(&Object, Sel, NSRect) -> id,
 296                );
 297                decl.add_method(
 298                    sel!(updateLayer),
 299                    blurred_view_update_layer as extern "C" fn(&Object, Sel),
 300                );
 301                decl.register()
 302            }
 303        };
 304    }
 305}
 306
 307pub(crate) fn convert_mouse_position(position: NSPoint, window_height: Pixels) -> Point<Pixels> {
 308    point(
 309        px(position.x as f32),
 310        // macOS screen coordinates are relative to bottom left
 311        window_height - px(position.y as f32),
 312    )
 313}
 314
 315unsafe fn build_window_class(name: &'static str, superclass: &Class) -> *const Class {
 316    unsafe {
 317        let mut decl = ClassDecl::new(name, superclass).unwrap();
 318        decl.add_ivar::<*mut c_void>(WINDOW_STATE_IVAR);
 319        decl.add_method(sel!(dealloc), dealloc_window as extern "C" fn(&Object, Sel));
 320
 321        decl.add_method(
 322            sel!(canBecomeMainWindow),
 323            yes as extern "C" fn(&Object, Sel) -> BOOL,
 324        );
 325        decl.add_method(
 326            sel!(canBecomeKeyWindow),
 327            yes as extern "C" fn(&Object, Sel) -> BOOL,
 328        );
 329        decl.add_method(
 330            sel!(windowDidResize:),
 331            window_did_resize as extern "C" fn(&Object, Sel, id),
 332        );
 333        decl.add_method(
 334            sel!(windowDidChangeOcclusionState:),
 335            window_did_change_occlusion_state as extern "C" fn(&Object, Sel, id),
 336        );
 337        decl.add_method(
 338            sel!(windowWillEnterFullScreen:),
 339            window_will_enter_fullscreen as extern "C" fn(&Object, Sel, id),
 340        );
 341        decl.add_method(
 342            sel!(windowWillExitFullScreen:),
 343            window_will_exit_fullscreen as extern "C" fn(&Object, Sel, id),
 344        );
 345        decl.add_method(
 346            sel!(windowDidMove:),
 347            window_did_move as extern "C" fn(&Object, Sel, id),
 348        );
 349        decl.add_method(
 350            sel!(windowDidChangeScreen:),
 351            window_did_change_screen as extern "C" fn(&Object, Sel, id),
 352        );
 353        decl.add_method(
 354            sel!(windowDidBecomeKey:),
 355            window_did_change_key_status as extern "C" fn(&Object, Sel, id),
 356        );
 357        decl.add_method(
 358            sel!(windowDidResignKey:),
 359            window_did_change_key_status as extern "C" fn(&Object, Sel, id),
 360        );
 361        decl.add_method(
 362            sel!(windowShouldClose:),
 363            window_should_close as extern "C" fn(&Object, Sel, id) -> BOOL,
 364        );
 365
 366        decl.add_method(sel!(close), close_window as extern "C" fn(&Object, Sel));
 367
 368        decl.add_method(
 369            sel!(draggingEntered:),
 370            dragging_entered as extern "C" fn(&Object, Sel, id) -> NSDragOperation,
 371        );
 372        decl.add_method(
 373            sel!(draggingUpdated:),
 374            dragging_updated as extern "C" fn(&Object, Sel, id) -> NSDragOperation,
 375        );
 376        decl.add_method(
 377            sel!(draggingExited:),
 378            dragging_exited as extern "C" fn(&Object, Sel, id),
 379        );
 380        decl.add_method(
 381            sel!(performDragOperation:),
 382            perform_drag_operation as extern "C" fn(&Object, Sel, id) -> BOOL,
 383        );
 384        decl.add_method(
 385            sel!(concludeDragOperation:),
 386            conclude_drag_operation as extern "C" fn(&Object, Sel, id),
 387        );
 388
 389        decl.add_method(
 390            sel!(addTitlebarAccessoryViewController:),
 391            add_titlebar_accessory_view_controller as extern "C" fn(&Object, Sel, id),
 392        );
 393
 394        decl.add_method(
 395            sel!(moveTabToNewWindow:),
 396            move_tab_to_new_window as extern "C" fn(&Object, Sel, id),
 397        );
 398
 399        decl.add_method(
 400            sel!(mergeAllWindows:),
 401            merge_all_windows as extern "C" fn(&Object, Sel, id),
 402        );
 403
 404        decl.add_method(
 405            sel!(selectNextTab:),
 406            select_next_tab as extern "C" fn(&Object, Sel, id),
 407        );
 408
 409        decl.add_method(
 410            sel!(selectPreviousTab:),
 411            select_previous_tab as extern "C" fn(&Object, Sel, id),
 412        );
 413
 414        decl.add_method(
 415            sel!(toggleTabBar:),
 416            toggle_tab_bar as extern "C" fn(&Object, Sel, id),
 417        );
 418
 419        decl.register()
 420    }
 421}
 422
 423struct MacWindowState {
 424    handle: AnyWindowHandle,
 425    foreground_executor: ForegroundExecutor,
 426    background_executor: BackgroundExecutor,
 427    native_window: id,
 428    native_view: NonNull<Object>,
 429    blurred_view: Option<id>,
 430    background_appearance: WindowBackgroundAppearance,
 431    display_link: Option<DisplayLink>,
 432    renderer: renderer::Renderer,
 433    request_frame_callback: Option<Box<dyn FnMut(RequestFrameOptions)>>,
 434    event_callback: Option<Box<dyn FnMut(PlatformInput) -> gpui::DispatchEventResult>>,
 435    activate_callback: Option<Box<dyn FnMut(bool)>>,
 436    resize_callback: Option<Box<dyn FnMut(Size<Pixels>, f32)>>,
 437    moved_callback: Option<Box<dyn FnMut()>>,
 438    should_close_callback: Option<Box<dyn FnMut() -> bool>>,
 439    close_callback: Option<Box<dyn FnOnce()>>,
 440    appearance_changed_callback: Option<Box<dyn FnMut()>>,
 441    input_handler: Option<PlatformInputHandler>,
 442    last_key_equivalent: Option<KeyDownEvent>,
 443    synthetic_drag_counter: usize,
 444    traffic_light_position: Option<Point<Pixels>>,
 445    transparent_titlebar: bool,
 446    previous_modifiers_changed_event: Option<PlatformInput>,
 447    keystroke_for_do_command: Option<Keystroke>,
 448    do_command_handled: Option<bool>,
 449    external_files_dragged: bool,
 450    // Whether the next left-mouse click is also the focusing click.
 451    first_mouse: bool,
 452    fullscreen_restore_bounds: Bounds<Pixels>,
 453    move_tab_to_new_window_callback: Option<Box<dyn FnMut()>>,
 454    merge_all_windows_callback: Option<Box<dyn FnMut()>>,
 455    select_next_tab_callback: Option<Box<dyn FnMut()>>,
 456    select_previous_tab_callback: Option<Box<dyn FnMut()>>,
 457    toggle_tab_bar_callback: Option<Box<dyn FnMut()>>,
 458    activated_least_once: bool,
 459    closed: Arc<AtomicBool>,
 460    // The parent window if this window is a sheet (Dialog kind)
 461    sheet_parent: Option<id>,
 462}
 463
 464impl MacWindowState {
 465    fn move_traffic_light(&self) {
 466        if let Some(traffic_light_position) = self.traffic_light_position {
 467            if self.is_fullscreen() {
 468                // Moving traffic lights while fullscreen doesn't work,
 469                // see https://github.com/zed-industries/zed/issues/4712
 470                return;
 471            }
 472
 473            let titlebar_height = self.titlebar_height();
 474
 475            unsafe {
 476                let close_button: id = msg_send![
 477                    self.native_window,
 478                    standardWindowButton: NSWindowButton::NSWindowCloseButton
 479                ];
 480                let min_button: id = msg_send![
 481                    self.native_window,
 482                    standardWindowButton: NSWindowButton::NSWindowMiniaturizeButton
 483                ];
 484                let zoom_button: id = msg_send![
 485                    self.native_window,
 486                    standardWindowButton: NSWindowButton::NSWindowZoomButton
 487                ];
 488
 489                let mut close_button_frame: CGRect = msg_send![close_button, frame];
 490                let mut min_button_frame: CGRect = msg_send![min_button, frame];
 491                let mut zoom_button_frame: CGRect = msg_send![zoom_button, frame];
 492                let mut origin = point(
 493                    traffic_light_position.x,
 494                    titlebar_height
 495                        - traffic_light_position.y
 496                        - px(close_button_frame.size.height as f32),
 497                );
 498                let button_spacing =
 499                    px((min_button_frame.origin.x - close_button_frame.origin.x) as f32);
 500
 501                close_button_frame.origin = CGPoint::new(origin.x.into(), origin.y.into());
 502                let _: () = msg_send![close_button, setFrame: close_button_frame];
 503                origin.x += button_spacing;
 504
 505                min_button_frame.origin = CGPoint::new(origin.x.into(), origin.y.into());
 506                let _: () = msg_send![min_button, setFrame: min_button_frame];
 507                origin.x += button_spacing;
 508
 509                zoom_button_frame.origin = CGPoint::new(origin.x.into(), origin.y.into());
 510                let _: () = msg_send![zoom_button, setFrame: zoom_button_frame];
 511                origin.x += button_spacing;
 512            }
 513        }
 514    }
 515
 516    fn start_display_link(&mut self) {
 517        self.stop_display_link();
 518        unsafe {
 519            if !self
 520                .native_window
 521                .occlusionState()
 522                .contains(NSWindowOcclusionState::NSWindowOcclusionStateVisible)
 523            {
 524                return;
 525            }
 526        }
 527        let display_id = unsafe { display_id_for_screen(self.native_window.screen()) };
 528        if let Some(mut display_link) =
 529            DisplayLink::new(display_id, self.native_view.as_ptr() as *mut c_void, step).log_err()
 530        {
 531            display_link.start().log_err();
 532            self.display_link = Some(display_link);
 533        }
 534    }
 535
 536    fn stop_display_link(&mut self) {
 537        self.display_link = None;
 538    }
 539
 540    fn is_maximized(&self) -> bool {
 541        fn rect_to_size(rect: NSRect) -> Size<Pixels> {
 542            let NSSize { width, height } = rect.size;
 543            size(width.into(), height.into())
 544        }
 545
 546        unsafe {
 547            let bounds = self.bounds();
 548            let screen_size = rect_to_size(self.native_window.screen().visibleFrame());
 549            bounds.size == screen_size
 550        }
 551    }
 552
 553    fn is_fullscreen(&self) -> bool {
 554        unsafe {
 555            let style_mask = self.native_window.styleMask();
 556            style_mask.contains(NSWindowStyleMask::NSFullScreenWindowMask)
 557        }
 558    }
 559
 560    fn bounds(&self) -> Bounds<Pixels> {
 561        let mut window_frame = unsafe { NSWindow::frame(self.native_window) };
 562        let screen = unsafe { NSWindow::screen(self.native_window) };
 563        if screen == nil {
 564            return Bounds::new(point(px(0.), px(0.)), gpui::DEFAULT_WINDOW_SIZE);
 565        }
 566        let screen_frame = unsafe { NSScreen::frame(screen) };
 567
 568        // Flip the y coordinate to be top-left origin
 569        window_frame.origin.y =
 570            screen_frame.size.height - window_frame.origin.y - window_frame.size.height;
 571
 572        Bounds::new(
 573            point(
 574                px((window_frame.origin.x - screen_frame.origin.x) as f32),
 575                px((window_frame.origin.y + screen_frame.origin.y) as f32),
 576            ),
 577            size(
 578                px(window_frame.size.width as f32),
 579                px(window_frame.size.height as f32),
 580            ),
 581        )
 582    }
 583
 584    fn content_size(&self) -> Size<Pixels> {
 585        let NSSize { width, height, .. } =
 586            unsafe { NSView::frame(self.native_window.contentView()) }.size;
 587        size(px(width as f32), px(height as f32))
 588    }
 589
 590    fn scale_factor(&self) -> f32 {
 591        get_scale_factor(self.native_window)
 592    }
 593
 594    fn titlebar_height(&self) -> Pixels {
 595        unsafe {
 596            let frame = NSWindow::frame(self.native_window);
 597            let content_layout_rect: CGRect = msg_send![self.native_window, contentLayoutRect];
 598            px((frame.size.height - content_layout_rect.size.height) as f32)
 599        }
 600    }
 601
 602    fn window_bounds(&self) -> WindowBounds {
 603        if self.is_fullscreen() {
 604            WindowBounds::Fullscreen(self.fullscreen_restore_bounds)
 605        } else {
 606            WindowBounds::Windowed(self.bounds())
 607        }
 608    }
 609}
 610
 611unsafe impl Send for MacWindowState {}
 612
 613pub(crate) struct MacWindow(Arc<Mutex<MacWindowState>>);
 614
 615impl MacWindow {
 616    pub fn open(
 617        handle: AnyWindowHandle,
 618        WindowParams {
 619            bounds,
 620            titlebar,
 621            kind,
 622            is_movable,
 623            is_resizable,
 624            is_minimizable,
 625            focus,
 626            show,
 627            display_id,
 628            window_min_size,
 629            tabbing_identifier,
 630        }: WindowParams,
 631        foreground_executor: ForegroundExecutor,
 632        background_executor: BackgroundExecutor,
 633        renderer_context: renderer::Context,
 634    ) -> Self {
 635        unsafe {
 636            let pool = NSAutoreleasePool::new(nil);
 637
 638            let allows_automatic_window_tabbing = tabbing_identifier.is_some();
 639            if allows_automatic_window_tabbing {
 640                let () = msg_send![class!(NSWindow), setAllowsAutomaticWindowTabbing: YES];
 641            } else {
 642                let () = msg_send![class!(NSWindow), setAllowsAutomaticWindowTabbing: NO];
 643            }
 644
 645            let mut style_mask;
 646            if let Some(titlebar) = titlebar.as_ref() {
 647                style_mask =
 648                    NSWindowStyleMask::NSClosableWindowMask | NSWindowStyleMask::NSTitledWindowMask;
 649
 650                if is_resizable {
 651                    style_mask |= NSWindowStyleMask::NSResizableWindowMask;
 652                }
 653
 654                if is_minimizable {
 655                    style_mask |= NSWindowStyleMask::NSMiniaturizableWindowMask;
 656                }
 657
 658                if titlebar.appears_transparent {
 659                    style_mask |= NSWindowStyleMask::NSFullSizeContentViewWindowMask;
 660                }
 661            } else {
 662                style_mask = NSWindowStyleMask::NSTitledWindowMask
 663                    | NSWindowStyleMask::NSFullSizeContentViewWindowMask;
 664            }
 665
 666            let native_window: id = match kind {
 667                WindowKind::Normal => {
 668                    msg_send![WINDOW_CLASS, alloc]
 669                }
 670                WindowKind::PopUp => {
 671                    style_mask |= NSWindowStyleMaskNonactivatingPanel;
 672                    msg_send![PANEL_CLASS, alloc]
 673                }
 674                WindowKind::Floating | WindowKind::Dialog => {
 675                    msg_send![PANEL_CLASS, alloc]
 676                }
 677            };
 678
 679            let display = display_id
 680                .and_then(MacDisplay::find_by_id)
 681                .unwrap_or_else(MacDisplay::primary);
 682
 683            let mut target_screen = nil;
 684            let mut screen_frame = None;
 685
 686            let screens = NSScreen::screens(nil);
 687            let count: u64 = cocoa::foundation::NSArray::count(screens);
 688            for i in 0..count {
 689                let screen = cocoa::foundation::NSArray::objectAtIndex(screens, i);
 690                let frame = NSScreen::frame(screen);
 691                let display_id = display_id_for_screen(screen);
 692                if display_id == display.0 {
 693                    screen_frame = Some(frame);
 694                    target_screen = screen;
 695                }
 696            }
 697
 698            let screen_frame = screen_frame.unwrap_or_else(|| {
 699                let screen = NSScreen::mainScreen(nil);
 700                target_screen = screen;
 701                NSScreen::frame(screen)
 702            });
 703
 704            let window_rect = NSRect::new(
 705                NSPoint::new(
 706                    screen_frame.origin.x + bounds.origin.x.as_f32() as f64,
 707                    screen_frame.origin.y
 708                        + (display.bounds().size.height - bounds.origin.y).as_f32() as f64,
 709                ),
 710                NSSize::new(
 711                    bounds.size.width.as_f32() as f64,
 712                    bounds.size.height.as_f32() as f64,
 713                ),
 714            );
 715
 716            let native_window = native_window.initWithContentRect_styleMask_backing_defer_screen_(
 717                window_rect,
 718                style_mask,
 719                NSBackingStoreBuffered,
 720                NO,
 721                target_screen,
 722            );
 723            assert!(!native_window.is_null());
 724            let () = msg_send![
 725                native_window,
 726                registerForDraggedTypes:
 727                    NSArray::arrayWithObject(nil, NSFilenamesPboardType)
 728            ];
 729            let () = msg_send![
 730                native_window,
 731                setReleasedWhenClosed: NO
 732            ];
 733
 734            let content_view = native_window.contentView();
 735            let native_view: id = msg_send![VIEW_CLASS, alloc];
 736            let native_view = NSView::initWithFrame_(native_view, NSView::bounds(content_view));
 737            assert!(!native_view.is_null());
 738
 739            let mut window = Self(Arc::new(Mutex::new(MacWindowState {
 740                handle,
 741                foreground_executor,
 742                background_executor,
 743                native_window,
 744                native_view: NonNull::new_unchecked(native_view),
 745                blurred_view: None,
 746                background_appearance: WindowBackgroundAppearance::Opaque,
 747                display_link: None,
 748                renderer: renderer::new_renderer(
 749                    renderer_context,
 750                    native_window as *mut _,
 751                    native_view as *mut _,
 752                    bounds.size.map(|pixels| pixels.as_f32()),
 753                    false,
 754                ),
 755                request_frame_callback: None,
 756                event_callback: None,
 757                activate_callback: None,
 758                resize_callback: None,
 759                moved_callback: None,
 760                should_close_callback: None,
 761                close_callback: None,
 762                appearance_changed_callback: None,
 763                input_handler: None,
 764                last_key_equivalent: None,
 765                synthetic_drag_counter: 0,
 766                traffic_light_position: titlebar
 767                    .as_ref()
 768                    .and_then(|titlebar| titlebar.traffic_light_position),
 769                transparent_titlebar: titlebar
 770                    .as_ref()
 771                    .is_none_or(|titlebar| titlebar.appears_transparent),
 772                previous_modifiers_changed_event: None,
 773                keystroke_for_do_command: None,
 774                do_command_handled: None,
 775                external_files_dragged: false,
 776                first_mouse: false,
 777                fullscreen_restore_bounds: Bounds::default(),
 778                move_tab_to_new_window_callback: None,
 779                merge_all_windows_callback: None,
 780                select_next_tab_callback: None,
 781                select_previous_tab_callback: None,
 782                toggle_tab_bar_callback: None,
 783                activated_least_once: false,
 784                closed: Arc::new(AtomicBool::new(false)),
 785                sheet_parent: None,
 786            })));
 787
 788            (*native_window).set_ivar(
 789                WINDOW_STATE_IVAR,
 790                Arc::into_raw(window.0.clone()) as *const c_void,
 791            );
 792            native_window.setDelegate_(native_window);
 793            (*native_view).set_ivar(
 794                WINDOW_STATE_IVAR,
 795                Arc::into_raw(window.0.clone()) as *const c_void,
 796            );
 797
 798            if let Some(title) = titlebar
 799                .as_ref()
 800                .and_then(|t| t.title.as_ref().map(AsRef::as_ref))
 801            {
 802                window.set_title(title);
 803            }
 804
 805            native_window.setMovable_(is_movable as BOOL);
 806
 807            if let Some(window_min_size) = window_min_size {
 808                native_window.setContentMinSize_(NSSize {
 809                    width: window_min_size.width.to_f64(),
 810                    height: window_min_size.height.to_f64(),
 811                });
 812            }
 813
 814            if titlebar.is_none_or(|titlebar| titlebar.appears_transparent) {
 815                native_window.setTitlebarAppearsTransparent_(YES);
 816                native_window.setTitleVisibility_(NSWindowTitleVisibility::NSWindowTitleHidden);
 817            }
 818
 819            native_view.setAutoresizingMask_(NSViewWidthSizable | NSViewHeightSizable);
 820            native_view.setWantsBestResolutionOpenGLSurface_(YES);
 821
 822            // From winit crate: On Mojave, views automatically become layer-backed shortly after
 823            // being added to a native_window. Changing the layer-backedness of a view breaks the
 824            // association between the view and its associated OpenGL context. To work around this,
 825            // on we explicitly make the view layer-backed up front so that AppKit doesn't do it
 826            // itself and break the association with its context.
 827            native_view.setWantsLayer(YES);
 828            let _: () = msg_send![
 829            native_view,
 830            setLayerContentsRedrawPolicy: NSViewLayerContentsRedrawDuringViewResize
 831            ];
 832
 833            content_view.addSubview_(native_view.autorelease());
 834            native_window.makeFirstResponder_(native_view);
 835
 836            let app: id = NSApplication::sharedApplication(nil);
 837            let main_window: id = msg_send![app, mainWindow];
 838            let mut sheet_parent = None;
 839
 840            match kind {
 841                WindowKind::Normal | WindowKind::Floating => {
 842                    if kind == WindowKind::Floating {
 843                        // Let the window float keep above normal windows.
 844                        native_window.setLevel_(NSFloatingWindowLevel);
 845                    } else {
 846                        native_window.setLevel_(NSNormalWindowLevel);
 847                    }
 848                    native_window.setAcceptsMouseMovedEvents_(YES);
 849
 850                    if let Some(tabbing_identifier) = tabbing_identifier {
 851                        let tabbing_id = ns_string(tabbing_identifier.as_str());
 852                        let _: () = msg_send![native_window, setTabbingIdentifier: tabbing_id];
 853                    } else {
 854                        let _: () = msg_send![native_window, setTabbingIdentifier:nil];
 855                    }
 856                }
 857                WindowKind::PopUp => {
 858                    // Use a tracking area to allow receiving MouseMoved events even when
 859                    // the window or application aren't active, which is often the case
 860                    // e.g. for notification windows.
 861                    let tracking_area: id = msg_send![class!(NSTrackingArea), alloc];
 862                    let _: () = msg_send![
 863                        tracking_area,
 864                        initWithRect: NSRect::new(NSPoint::new(0., 0.), NSSize::new(0., 0.))
 865                        options: NSTrackingMouseEnteredAndExited | NSTrackingMouseMoved | NSTrackingActiveAlways | NSTrackingInVisibleRect
 866                        owner: native_view
 867                        userInfo: nil
 868                    ];
 869                    let _: () =
 870                        msg_send![native_view, addTrackingArea: tracking_area.autorelease()];
 871
 872                    native_window.setLevel_(NSPopUpWindowLevel);
 873                    let _: () = msg_send![
 874                        native_window,
 875                        setAnimationBehavior: NSWindowAnimationBehaviorUtilityWindow
 876                    ];
 877                    native_window.setCollectionBehavior_(
 878                        NSWindowCollectionBehavior::NSWindowCollectionBehaviorCanJoinAllSpaces |
 879                        NSWindowCollectionBehavior::NSWindowCollectionBehaviorFullScreenAuxiliary
 880                    );
 881                }
 882                WindowKind::Dialog => {
 883                    if !main_window.is_null() {
 884                        let parent = {
 885                            let active_sheet: id = msg_send![main_window, attachedSheet];
 886                            if active_sheet.is_null() {
 887                                main_window
 888                            } else {
 889                                active_sheet
 890                            }
 891                        };
 892                        let _: () =
 893                            msg_send![parent, beginSheet: native_window completionHandler: nil];
 894                        sheet_parent = Some(parent);
 895                    }
 896                }
 897            }
 898
 899            if allows_automatic_window_tabbing
 900                && !main_window.is_null()
 901                && main_window != native_window
 902            {
 903                let main_window_is_fullscreen = main_window
 904                    .styleMask()
 905                    .contains(NSWindowStyleMask::NSFullScreenWindowMask);
 906                let user_tabbing_preference = Self::get_user_tabbing_preference()
 907                    .unwrap_or(UserTabbingPreference::InFullScreen);
 908                let should_add_as_tab = user_tabbing_preference == UserTabbingPreference::Always
 909                    || user_tabbing_preference == UserTabbingPreference::InFullScreen
 910                        && main_window_is_fullscreen;
 911
 912                if should_add_as_tab {
 913                    let main_window_can_tab: BOOL =
 914                        msg_send![main_window, respondsToSelector: sel!(addTabbedWindow:ordered:)];
 915                    let main_window_visible: BOOL = msg_send![main_window, isVisible];
 916
 917                    if main_window_can_tab == YES && main_window_visible == YES {
 918                        let _: () = msg_send![main_window, addTabbedWindow: native_window ordered: NSWindowOrderingMode::NSWindowAbove];
 919
 920                        // Ensure the window is visible immediately after adding the tab, since the tab bar is updated with a new entry at this point.
 921                        // Note: Calling orderFront here can break fullscreen mode (makes fullscreen windows exit fullscreen), so only do this if the main window is not fullscreen.
 922                        if !main_window_is_fullscreen {
 923                            let _: () = msg_send![native_window, orderFront: nil];
 924                        }
 925                    }
 926                }
 927            }
 928
 929            if focus && show {
 930                native_window.makeKeyAndOrderFront_(nil);
 931            } else if show {
 932                native_window.orderFront_(nil);
 933            }
 934
 935            // Set the initial position of the window to the specified origin.
 936            // Although we already specified the position using `initWithContentRect_styleMask_backing_defer_screen_`,
 937            // the window position might be incorrect if the main screen (the screen that contains the window that has focus)
 938            //  is different from the primary screen.
 939            NSWindow::setFrameTopLeftPoint_(native_window, window_rect.origin);
 940            {
 941                let mut window_state = window.0.lock();
 942                window_state.move_traffic_light();
 943                window_state.sheet_parent = sheet_parent;
 944            }
 945
 946            pool.drain();
 947
 948            window
 949        }
 950    }
 951
 952    pub fn active_window() -> Option<AnyWindowHandle> {
 953        unsafe {
 954            let app = NSApplication::sharedApplication(nil);
 955            let main_window: id = msg_send![app, mainWindow];
 956            if main_window.is_null() {
 957                return None;
 958            }
 959
 960            if msg_send![main_window, isKindOfClass: WINDOW_CLASS] {
 961                let handle = get_window_state(&*main_window).lock().handle;
 962                Some(handle)
 963            } else {
 964                None
 965            }
 966        }
 967    }
 968
 969    pub fn ordered_windows() -> Vec<AnyWindowHandle> {
 970        unsafe {
 971            let app = NSApplication::sharedApplication(nil);
 972            let windows: id = msg_send![app, orderedWindows];
 973            let count: NSUInteger = msg_send![windows, count];
 974
 975            let mut window_handles = Vec::new();
 976            for i in 0..count {
 977                let window: id = msg_send![windows, objectAtIndex:i];
 978                if msg_send![window, isKindOfClass: WINDOW_CLASS] {
 979                    let handle = get_window_state(&*window).lock().handle;
 980                    window_handles.push(handle);
 981                }
 982            }
 983
 984            window_handles
 985        }
 986    }
 987
 988    pub fn get_user_tabbing_preference() -> Option<UserTabbingPreference> {
 989        unsafe {
 990            let defaults: id = NSUserDefaults::standardUserDefaults();
 991            let domain = ns_string("NSGlobalDomain");
 992            let key = ns_string("AppleWindowTabbingMode");
 993
 994            let dict: id = msg_send![defaults, persistentDomainForName: domain];
 995            let value: id = if !dict.is_null() {
 996                msg_send![dict, objectForKey: key]
 997            } else {
 998                nil
 999            };
1000
1001            let value_str = if !value.is_null() {
1002                CStr::from_ptr(NSString::UTF8String(value)).to_string_lossy()
1003            } else {
1004                "".into()
1005            };
1006
1007            match value_str.as_ref() {
1008                "manual" => Some(UserTabbingPreference::Never),
1009                "always" => Some(UserTabbingPreference::Always),
1010                _ => Some(UserTabbingPreference::InFullScreen),
1011            }
1012        }
1013    }
1014}
1015
1016impl Drop for MacWindow {
1017    fn drop(&mut self) {
1018        let mut this = self.0.lock();
1019        this.renderer.destroy();
1020        let window = this.native_window;
1021        let sheet_parent = this.sheet_parent.take();
1022        this.display_link.take();
1023        unsafe {
1024            this.native_window.setDelegate_(nil);
1025        }
1026        this.input_handler.take();
1027        this.foreground_executor
1028            .spawn(async move {
1029                unsafe {
1030                    if let Some(parent) = sheet_parent {
1031                        let _: () = msg_send![parent, endSheet: window];
1032                    }
1033                    window.close();
1034                    window.autorelease();
1035                }
1036            })
1037            .detach();
1038    }
1039}
1040
1041/// Calls `f` if the window is not closed.
1042///
1043/// This should be used when spawning foreground tasks interacting with the
1044/// window, as some messages will end hard faulting if dispatched to no longer
1045/// valid window handles.
1046fn if_window_not_closed(closed: Arc<AtomicBool>, f: impl FnOnce()) {
1047    if !closed.load(Ordering::Acquire) {
1048        f();
1049    }
1050}
1051
1052impl PlatformWindow for MacWindow {
1053    fn bounds(&self) -> Bounds<Pixels> {
1054        self.0.as_ref().lock().bounds()
1055    }
1056
1057    fn window_bounds(&self) -> WindowBounds {
1058        self.0.as_ref().lock().window_bounds()
1059    }
1060
1061    fn is_maximized(&self) -> bool {
1062        self.0.as_ref().lock().is_maximized()
1063    }
1064
1065    fn content_size(&self) -> Size<Pixels> {
1066        self.0.as_ref().lock().content_size()
1067    }
1068
1069    fn resize(&mut self, size: Size<Pixels>) {
1070        let this = self.0.lock();
1071        let window = this.native_window;
1072        let closed = this.closed.clone();
1073        this.foreground_executor
1074            .spawn(async move {
1075                if_window_not_closed(closed, || unsafe {
1076                    window.setContentSize_(NSSize {
1077                        width: size.width.as_f32() as f64,
1078                        height: size.height.as_f32() as f64,
1079                    });
1080                })
1081            })
1082            .detach();
1083    }
1084
1085    fn merge_all_windows(&self) {
1086        let native_window = self.0.lock().native_window;
1087        extern "C" fn merge_windows_async(context: *mut std::ffi::c_void) {
1088            unsafe {
1089                let native_window = context as id;
1090                let _: () = msg_send![native_window, mergeAllWindows:nil];
1091            }
1092        }
1093
1094        unsafe {
1095            DispatchQueue::main()
1096                .exec_async_f(native_window as *mut std::ffi::c_void, merge_windows_async);
1097        }
1098    }
1099
1100    fn move_tab_to_new_window(&self) {
1101        let native_window = self.0.lock().native_window;
1102        extern "C" fn move_tab_async(context: *mut std::ffi::c_void) {
1103            unsafe {
1104                let native_window = context as id;
1105                let _: () = msg_send![native_window, moveTabToNewWindow:nil];
1106                let _: () = msg_send![native_window, makeKeyAndOrderFront: nil];
1107            }
1108        }
1109
1110        unsafe {
1111            DispatchQueue::main()
1112                .exec_async_f(native_window as *mut std::ffi::c_void, move_tab_async);
1113        }
1114    }
1115
1116    fn toggle_window_tab_overview(&self) {
1117        let native_window = self.0.lock().native_window;
1118        unsafe {
1119            let _: () = msg_send![native_window, toggleTabOverview:nil];
1120        }
1121    }
1122
1123    fn set_tabbing_identifier(&self, tabbing_identifier: Option<String>) {
1124        let native_window = self.0.lock().native_window;
1125        unsafe {
1126            let allows_automatic_window_tabbing = tabbing_identifier.is_some();
1127            if allows_automatic_window_tabbing {
1128                let () = msg_send![class!(NSWindow), setAllowsAutomaticWindowTabbing: YES];
1129            } else {
1130                let () = msg_send![class!(NSWindow), setAllowsAutomaticWindowTabbing: NO];
1131            }
1132
1133            if let Some(tabbing_identifier) = tabbing_identifier {
1134                let tabbing_id = ns_string(tabbing_identifier.as_str());
1135                let _: () = msg_send![native_window, setTabbingIdentifier: tabbing_id];
1136            } else {
1137                let _: () = msg_send![native_window, setTabbingIdentifier:nil];
1138            }
1139        }
1140    }
1141
1142    fn scale_factor(&self) -> f32 {
1143        self.0.as_ref().lock().scale_factor()
1144    }
1145
1146    fn appearance(&self) -> WindowAppearance {
1147        unsafe {
1148            let appearance: id = msg_send![self.0.lock().native_window, effectiveAppearance];
1149            crate::window_appearance::window_appearance_from_native(appearance)
1150        }
1151    }
1152
1153    fn display(&self) -> Option<Rc<dyn PlatformDisplay>> {
1154        unsafe {
1155            let screen = self.0.lock().native_window.screen();
1156            if screen.is_null() {
1157                return None;
1158            }
1159            let device_description: id = msg_send![screen, deviceDescription];
1160            let screen_number: id =
1161                NSDictionary::valueForKey_(device_description, ns_string("NSScreenNumber"));
1162
1163            let screen_number: u32 = msg_send![screen_number, unsignedIntValue];
1164
1165            Some(Rc::new(MacDisplay(screen_number)))
1166        }
1167    }
1168
1169    fn mouse_position(&self) -> Point<Pixels> {
1170        let position = unsafe {
1171            self.0
1172                .lock()
1173                .native_window
1174                .mouseLocationOutsideOfEventStream()
1175        };
1176        convert_mouse_position(position, self.content_size().height)
1177    }
1178
1179    fn modifiers(&self) -> Modifiers {
1180        unsafe {
1181            let modifiers: NSEventModifierFlags = msg_send![class!(NSEvent), modifierFlags];
1182
1183            let control = modifiers.contains(NSEventModifierFlags::NSControlKeyMask);
1184            let alt = modifiers.contains(NSEventModifierFlags::NSAlternateKeyMask);
1185            let shift = modifiers.contains(NSEventModifierFlags::NSShiftKeyMask);
1186            let command = modifiers.contains(NSEventModifierFlags::NSCommandKeyMask);
1187            let function = modifiers.contains(NSEventModifierFlags::NSFunctionKeyMask);
1188
1189            Modifiers {
1190                control,
1191                alt,
1192                shift,
1193                platform: command,
1194                function,
1195            }
1196        }
1197    }
1198
1199    fn capslock(&self) -> Capslock {
1200        unsafe {
1201            let modifiers: NSEventModifierFlags = msg_send![class!(NSEvent), modifierFlags];
1202
1203            Capslock {
1204                on: modifiers.contains(NSEventModifierFlags::NSAlphaShiftKeyMask),
1205            }
1206        }
1207    }
1208
1209    fn set_input_handler(&mut self, input_handler: PlatformInputHandler) {
1210        self.0.as_ref().lock().input_handler = Some(input_handler);
1211    }
1212
1213    fn take_input_handler(&mut self) -> Option<PlatformInputHandler> {
1214        self.0.as_ref().lock().input_handler.take()
1215    }
1216
1217    fn prompt(
1218        &self,
1219        level: PromptLevel,
1220        msg: &str,
1221        detail: Option<&str>,
1222        answers: &[PromptButton],
1223    ) -> Option<oneshot::Receiver<usize>> {
1224        // macOs applies overrides to modal window buttons after they are added.
1225        // Two most important for this logic are:
1226        // * Buttons with "Cancel" title will be displayed as the last buttons in the modal
1227        // * Last button added to the modal via `addButtonWithTitle` stays focused
1228        // * Focused buttons react on "space"/" " keypresses
1229        // * Usage of `keyEquivalent`, `makeFirstResponder` or `setInitialFirstResponder` does not change the focus
1230        //
1231        // See also https://developer.apple.com/documentation/appkit/nsalert/1524532-addbuttonwithtitle#discussion
1232        // ```
1233        // By default, the first button has a key equivalent of Return,
1234        // any button with a title of “Cancel” has a key equivalent of Escape,
1235        // 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).
1236        // ```
1237        //
1238        // To avoid situations when the last element added is "Cancel" and it gets the focus
1239        // (hence stealing both ESC and Space shortcuts), we find and add one non-Cancel button
1240        // last, so it gets focus and a Space shortcut.
1241        // This way, "Save this file? Yes/No/Cancel"-ish modals will get all three buttons mapped with a key.
1242        let latest_non_cancel_label = answers
1243            .iter()
1244            .enumerate()
1245            .rev()
1246            .find(|(_, label)| !label.is_cancel())
1247            .filter(|&(label_index, _)| label_index > 0);
1248
1249        unsafe {
1250            let alert: id = msg_send![class!(NSAlert), alloc];
1251            let alert: id = msg_send![alert, init];
1252            let alert_style = match level {
1253                PromptLevel::Info => 1,
1254                PromptLevel::Warning => 0,
1255                PromptLevel::Critical => 2,
1256            };
1257            let _: () = msg_send![alert, setAlertStyle: alert_style];
1258            let _: () = msg_send![alert, setMessageText: ns_string(msg)];
1259            if let Some(detail) = detail {
1260                let _: () = msg_send![alert, setInformativeText: ns_string(detail)];
1261            }
1262
1263            for (ix, answer) in answers
1264                .iter()
1265                .enumerate()
1266                .filter(|&(ix, _)| Some(ix) != latest_non_cancel_label.map(|(ix, _)| ix))
1267            {
1268                let button: id = msg_send![alert, addButtonWithTitle: ns_string(answer.label())];
1269                let _: () = msg_send![button, setTag: ix as NSInteger];
1270
1271                if answer.is_cancel() {
1272                    // Bind Escape Key to Cancel Button
1273                    if let Some(key) = std::char::from_u32(crate::events::ESCAPE_KEY as u32) {
1274                        let _: () =
1275                            msg_send![button, setKeyEquivalent: ns_string(&key.to_string())];
1276                    }
1277                }
1278            }
1279            if let Some((ix, answer)) = latest_non_cancel_label {
1280                let button: id = msg_send![alert, addButtonWithTitle: ns_string(answer.label())];
1281                let _: () = msg_send![button, setTag: ix as NSInteger];
1282            }
1283
1284            let (done_tx, done_rx) = oneshot::channel();
1285            let done_tx = Cell::new(Some(done_tx));
1286            let block = ConcreteBlock::new(move |answer: NSInteger| {
1287                let _: () = msg_send![alert, release];
1288                if let Some(done_tx) = done_tx.take() {
1289                    let _ = done_tx.send(answer.try_into().unwrap());
1290                }
1291            });
1292            let block = block.copy();
1293            let lock = self.0.lock();
1294            let native_window = lock.native_window;
1295            let closed = lock.closed.clone();
1296            let executor = lock.foreground_executor.clone();
1297            executor
1298                .spawn(async move {
1299                    if !closed.load(Ordering::Acquire) {
1300                        let _: () = msg_send![
1301                            alert,
1302                            beginSheetModalForWindow: native_window
1303                            completionHandler: block
1304                        ];
1305                    } else {
1306                        let _: () = msg_send![alert, release];
1307                    }
1308                })
1309                .detach();
1310
1311            Some(done_rx)
1312        }
1313    }
1314
1315    fn activate(&self) {
1316        let lock = self.0.lock();
1317        let window = lock.native_window;
1318        let closed = lock.closed.clone();
1319        let executor = lock.foreground_executor.clone();
1320        executor
1321            .spawn(async move {
1322                if !closed.load(Ordering::Acquire) {
1323                    unsafe {
1324                        let _: () = msg_send![window, makeKeyAndOrderFront: nil];
1325                    }
1326                }
1327            })
1328            .detach();
1329    }
1330
1331    fn is_active(&self) -> bool {
1332        unsafe { self.0.lock().native_window.isKeyWindow() == YES }
1333    }
1334
1335    // is_hovered is unused on macOS. See Window::is_window_hovered.
1336    fn is_hovered(&self) -> bool {
1337        false
1338    }
1339
1340    fn set_title(&mut self, title: &str) {
1341        unsafe {
1342            let app = NSApplication::sharedApplication(nil);
1343            let window = self.0.lock().native_window;
1344            let title = ns_string(title);
1345            let _: () = msg_send![app, changeWindowsItem:window title:title filename:false];
1346            let _: () = msg_send![window, setTitle: title];
1347            self.0.lock().move_traffic_light();
1348        }
1349    }
1350
1351    fn get_title(&self) -> String {
1352        unsafe {
1353            let title: id = msg_send![self.0.lock().native_window, title];
1354            if title.is_null() {
1355                "".to_string()
1356            } else {
1357                title.to_str().to_string()
1358            }
1359        }
1360    }
1361
1362    fn set_app_id(&mut self, _app_id: &str) {}
1363
1364    fn set_background_appearance(&self, background_appearance: WindowBackgroundAppearance) {
1365        let mut this = self.0.as_ref().lock();
1366        this.background_appearance = background_appearance;
1367
1368        let opaque = background_appearance == WindowBackgroundAppearance::Opaque;
1369        this.renderer.update_transparency(!opaque);
1370
1371        unsafe {
1372            this.native_window.setOpaque_(opaque as BOOL);
1373            let background_color = if opaque {
1374                NSColor::colorWithSRGBRed_green_blue_alpha_(nil, 0f64, 0f64, 0f64, 1f64)
1375            } else {
1376                // Not using `+[NSColor clearColor]` to avoid broken shadow.
1377                NSColor::colorWithSRGBRed_green_blue_alpha_(nil, 0f64, 0f64, 0f64, 0.0001)
1378            };
1379            this.native_window.setBackgroundColor_(background_color);
1380
1381            if NSAppKitVersionNumber < NSAppKitVersionNumber12_0 {
1382                // Whether `-[NSVisualEffectView respondsToSelector:@selector(_updateProxyLayer)]`.
1383                // On macOS Catalina/Big Sur `NSVisualEffectView` doesn’t own concrete sublayers
1384                // but uses a `CAProxyLayer`. Use the legacy WindowServer API.
1385                let blur_radius = if background_appearance == WindowBackgroundAppearance::Blurred {
1386                    80
1387                } else {
1388                    0
1389                };
1390
1391                let window_number = this.native_window.windowNumber();
1392                CGSSetWindowBackgroundBlurRadius(CGSMainConnectionID(), window_number, blur_radius);
1393            } else {
1394                // On newer macOS `NSVisualEffectView` manages the effect layer directly. Using it
1395                // could have a better performance (it downsamples the backdrop) and more control
1396                // over the effect layer.
1397                if background_appearance != WindowBackgroundAppearance::Blurred {
1398                    if let Some(blur_view) = this.blurred_view {
1399                        NSView::removeFromSuperview(blur_view);
1400                        this.blurred_view = None;
1401                    }
1402                } else if this.blurred_view.is_none() {
1403                    let content_view = this.native_window.contentView();
1404                    let frame = NSView::bounds(content_view);
1405                    let mut blur_view: id = msg_send![BLURRED_VIEW_CLASS, alloc];
1406                    blur_view = NSView::initWithFrame_(blur_view, frame);
1407                    blur_view.setAutoresizingMask_(NSViewWidthSizable | NSViewHeightSizable);
1408
1409                    let _: () = msg_send![
1410                        content_view,
1411                        addSubview: blur_view
1412                        positioned: NSWindowOrderingMode::NSWindowBelow
1413                        relativeTo: nil
1414                    ];
1415                    this.blurred_view = Some(blur_view.autorelease());
1416                }
1417            }
1418        }
1419    }
1420
1421    fn background_appearance(&self) -> WindowBackgroundAppearance {
1422        self.0.as_ref().lock().background_appearance
1423    }
1424
1425    fn is_subpixel_rendering_supported(&self) -> bool {
1426        false
1427    }
1428
1429    fn set_edited(&mut self, edited: bool) {
1430        unsafe {
1431            let window = self.0.lock().native_window;
1432            msg_send![window, setDocumentEdited: edited as BOOL]
1433        }
1434
1435        // Changing the document edited state resets the traffic light position,
1436        // so we have to move it again.
1437        self.0.lock().move_traffic_light();
1438    }
1439
1440    fn show_character_palette(&self) {
1441        let this = self.0.lock();
1442        let window = this.native_window;
1443        this.foreground_executor
1444            .spawn(async move {
1445                unsafe {
1446                    let app = NSApplication::sharedApplication(nil);
1447                    let _: () = msg_send![app, orderFrontCharacterPalette: window];
1448                }
1449            })
1450            .detach();
1451    }
1452
1453    fn minimize(&self) {
1454        let window = self.0.lock().native_window;
1455        unsafe {
1456            window.miniaturize_(nil);
1457        }
1458    }
1459
1460    fn zoom(&self) {
1461        let this = self.0.lock();
1462        let window = this.native_window;
1463        let closed = this.closed.clone();
1464        this.foreground_executor
1465            .spawn(async move {
1466                if_window_not_closed(closed, || unsafe {
1467                    window.zoom_(nil);
1468                })
1469            })
1470            .detach();
1471    }
1472
1473    fn toggle_fullscreen(&self) {
1474        let this = self.0.lock();
1475        let window = this.native_window;
1476        let closed = this.closed.clone();
1477        this.foreground_executor
1478            .spawn(async move {
1479                if_window_not_closed(closed, || unsafe {
1480                    window.toggleFullScreen_(nil);
1481                })
1482            })
1483            .detach();
1484    }
1485
1486    fn is_fullscreen(&self) -> bool {
1487        let this = self.0.lock();
1488        let window = this.native_window;
1489
1490        unsafe {
1491            window
1492                .styleMask()
1493                .contains(NSWindowStyleMask::NSFullScreenWindowMask)
1494        }
1495    }
1496
1497    fn on_request_frame(&self, callback: Box<dyn FnMut(RequestFrameOptions)>) {
1498        self.0.as_ref().lock().request_frame_callback = Some(callback);
1499    }
1500
1501    fn on_input(&self, callback: Box<dyn FnMut(PlatformInput) -> gpui::DispatchEventResult>) {
1502        self.0.as_ref().lock().event_callback = Some(callback);
1503    }
1504
1505    fn on_active_status_change(&self, callback: Box<dyn FnMut(bool)>) {
1506        self.0.as_ref().lock().activate_callback = Some(callback);
1507    }
1508
1509    fn on_hover_status_change(&self, _: Box<dyn FnMut(bool)>) {}
1510
1511    fn on_resize(&self, callback: Box<dyn FnMut(Size<Pixels>, f32)>) {
1512        self.0.as_ref().lock().resize_callback = Some(callback);
1513    }
1514
1515    fn on_moved(&self, callback: Box<dyn FnMut()>) {
1516        self.0.as_ref().lock().moved_callback = Some(callback);
1517    }
1518
1519    fn on_should_close(&self, callback: Box<dyn FnMut() -> bool>) {
1520        self.0.as_ref().lock().should_close_callback = Some(callback);
1521    }
1522
1523    fn on_close(&self, callback: Box<dyn FnOnce()>) {
1524        self.0.as_ref().lock().close_callback = Some(callback);
1525    }
1526
1527    fn on_hit_test_window_control(&self, _callback: Box<dyn FnMut() -> Option<WindowControlArea>>) {
1528    }
1529
1530    fn on_appearance_changed(&self, callback: Box<dyn FnMut()>) {
1531        self.0.lock().appearance_changed_callback = Some(callback);
1532    }
1533
1534    fn tabbed_windows(&self) -> Option<Vec<SystemWindowTab>> {
1535        unsafe {
1536            let windows: id = msg_send![self.0.lock().native_window, tabbedWindows];
1537            if windows.is_null() {
1538                return None;
1539            }
1540
1541            let count: NSUInteger = msg_send![windows, count];
1542            let mut result = Vec::new();
1543            for i in 0..count {
1544                let window: id = msg_send![windows, objectAtIndex:i];
1545                if msg_send![window, isKindOfClass: WINDOW_CLASS] {
1546                    let handle = get_window_state(&*window).lock().handle;
1547                    let title: id = msg_send![window, title];
1548                    let title = SharedString::from(title.to_str().to_string());
1549
1550                    result.push(SystemWindowTab::new(title, handle));
1551                }
1552            }
1553
1554            Some(result)
1555        }
1556    }
1557
1558    fn tab_bar_visible(&self) -> bool {
1559        unsafe {
1560            let tab_group: id = msg_send![self.0.lock().native_window, tabGroup];
1561            if tab_group.is_null() {
1562                false
1563            } else {
1564                let tab_bar_visible: BOOL = msg_send![tab_group, isTabBarVisible];
1565                tab_bar_visible == YES
1566            }
1567        }
1568    }
1569
1570    fn on_move_tab_to_new_window(&self, callback: Box<dyn FnMut()>) {
1571        self.0.as_ref().lock().move_tab_to_new_window_callback = Some(callback);
1572    }
1573
1574    fn on_merge_all_windows(&self, callback: Box<dyn FnMut()>) {
1575        self.0.as_ref().lock().merge_all_windows_callback = Some(callback);
1576    }
1577
1578    fn on_select_next_tab(&self, callback: Box<dyn FnMut()>) {
1579        self.0.as_ref().lock().select_next_tab_callback = Some(callback);
1580    }
1581
1582    fn on_select_previous_tab(&self, callback: Box<dyn FnMut()>) {
1583        self.0.as_ref().lock().select_previous_tab_callback = Some(callback);
1584    }
1585
1586    fn on_toggle_tab_bar(&self, callback: Box<dyn FnMut()>) {
1587        self.0.as_ref().lock().toggle_tab_bar_callback = Some(callback);
1588    }
1589
1590    fn draw(&self, scene: &gpui::Scene) {
1591        let mut this = self.0.lock();
1592        this.renderer.draw(scene);
1593    }
1594
1595    fn sprite_atlas(&self) -> Arc<dyn PlatformAtlas> {
1596        self.0.lock().renderer.sprite_atlas().clone()
1597    }
1598
1599    fn gpu_specs(&self) -> Option<gpui::GpuSpecs> {
1600        None
1601    }
1602
1603    fn update_ime_position(&self, _bounds: Bounds<Pixels>) {
1604        let executor = self.0.lock().foreground_executor.clone();
1605        executor
1606            .spawn(async move {
1607                unsafe {
1608                    let input_context: id =
1609                        msg_send![class!(NSTextInputContext), currentInputContext];
1610                    if input_context.is_null() {
1611                        return;
1612                    }
1613                    let _: () = msg_send![input_context, invalidateCharacterCoordinates];
1614                }
1615            })
1616            .detach()
1617    }
1618
1619    fn titlebar_double_click(&self) {
1620        let this = self.0.lock();
1621        let window = this.native_window;
1622        let closed = this.closed.clone();
1623        this.foreground_executor
1624            .spawn(async move {
1625                if_window_not_closed(closed, || {
1626                    unsafe {
1627                        let defaults: id = NSUserDefaults::standardUserDefaults();
1628                        let domain = ns_string("NSGlobalDomain");
1629                        let key = ns_string("AppleActionOnDoubleClick");
1630
1631                        let dict: id = msg_send![defaults, persistentDomainForName: domain];
1632                        let action: id = if !dict.is_null() {
1633                            msg_send![dict, objectForKey: key]
1634                        } else {
1635                            nil
1636                        };
1637
1638                        let action_str = if !action.is_null() {
1639                            CStr::from_ptr(NSString::UTF8String(action)).to_string_lossy()
1640                        } else {
1641                            "".into()
1642                        };
1643
1644                        match action_str.as_ref() {
1645                            "None" => {
1646                                // "Do Nothing" selected, so do no action
1647                            }
1648                            "Minimize" => {
1649                                window.miniaturize_(nil);
1650                            }
1651                            "Maximize" => {
1652                                window.zoom_(nil);
1653                            }
1654                            "Fill" => {
1655                                // There is no documented API for "Fill" action, so we'll just zoom the window
1656                                window.zoom_(nil);
1657                            }
1658                            _ => {
1659                                window.zoom_(nil);
1660                            }
1661                        }
1662                    }
1663                })
1664            })
1665            .detach();
1666    }
1667
1668    fn start_window_move(&self) {
1669        let this = self.0.lock();
1670        let window = this.native_window;
1671
1672        unsafe {
1673            let app = NSApplication::sharedApplication(nil);
1674            let event: id = msg_send![app, currentEvent];
1675            let _: () = msg_send![window, performWindowDragWithEvent: event];
1676        }
1677    }
1678
1679    #[cfg(any(test, feature = "test-support"))]
1680    fn render_to_image(&self, scene: &gpui::Scene) -> Result<RgbaImage> {
1681        let mut this = self.0.lock();
1682        this.renderer.render_to_image(scene)
1683    }
1684}
1685
1686impl rwh::HasWindowHandle for MacWindow {
1687    fn window_handle(&self) -> Result<rwh::WindowHandle<'_>, rwh::HandleError> {
1688        // SAFETY: The AppKitWindowHandle is a wrapper around a pointer to an NSView
1689        unsafe {
1690            Ok(rwh::WindowHandle::borrow_raw(rwh::RawWindowHandle::AppKit(
1691                rwh::AppKitWindowHandle::new(self.0.lock().native_view.cast()),
1692            )))
1693        }
1694    }
1695}
1696
1697impl rwh::HasDisplayHandle for MacWindow {
1698    fn display_handle(&self) -> Result<rwh::DisplayHandle<'_>, rwh::HandleError> {
1699        // SAFETY: This is a no-op on macOS
1700        unsafe {
1701            Ok(rwh::DisplayHandle::borrow_raw(
1702                rwh::AppKitDisplayHandle::new().into(),
1703            ))
1704        }
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}