window.rs

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