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                let _: () = msg_send![alert, release];
1202                if let Some(done_tx) = done_tx.take() {
1203                    let _ = done_tx.send(answer.try_into().unwrap());
1204                }
1205            });
1206            let block = block.copy();
1207            let native_window = self.0.lock().native_window;
1208            let executor = self.0.lock().executor.clone();
1209            executor
1210                .spawn(async move {
1211                    let _: () = msg_send![
1212                        alert,
1213                        beginSheetModalForWindow: native_window
1214                        completionHandler: block
1215                    ];
1216                })
1217                .detach();
1218
1219            Some(done_rx)
1220        }
1221    }
1222
1223    fn activate(&self) {
1224        let window = self.0.lock().native_window;
1225        let executor = self.0.lock().executor.clone();
1226        executor
1227            .spawn(async move {
1228                unsafe {
1229                    let _: () = msg_send![window, makeKeyAndOrderFront: nil];
1230                }
1231            })
1232            .detach();
1233    }
1234
1235    fn is_active(&self) -> bool {
1236        unsafe { self.0.lock().native_window.isKeyWindow() == YES }
1237    }
1238
1239    // is_hovered is unused on macOS. See Window::is_window_hovered.
1240    fn is_hovered(&self) -> bool {
1241        false
1242    }
1243
1244    fn set_title(&mut self, title: &str) {
1245        unsafe {
1246            let app = NSApplication::sharedApplication(nil);
1247            let window = self.0.lock().native_window;
1248            let title = ns_string(title);
1249            let _: () = msg_send![app, changeWindowsItem:window title:title filename:false];
1250            let _: () = msg_send![window, setTitle: title];
1251            self.0.lock().move_traffic_light();
1252        }
1253    }
1254
1255    fn get_title(&self) -> String {
1256        unsafe {
1257            let title: id = msg_send![self.0.lock().native_window, title];
1258            if title.is_null() {
1259                "".to_string()
1260            } else {
1261                title.to_str().to_string()
1262            }
1263        }
1264    }
1265
1266    fn set_app_id(&mut self, _app_id: &str) {}
1267
1268    fn set_background_appearance(&self, background_appearance: WindowBackgroundAppearance) {
1269        let mut this = self.0.as_ref().lock();
1270
1271        let opaque = background_appearance == WindowBackgroundAppearance::Opaque;
1272        this.renderer.update_transparency(!opaque);
1273
1274        unsafe {
1275            this.native_window.setOpaque_(opaque as BOOL);
1276            let background_color = if opaque {
1277                NSColor::colorWithSRGBRed_green_blue_alpha_(nil, 0f64, 0f64, 0f64, 1f64)
1278            } else {
1279                // Not using `+[NSColor clearColor]` to avoid broken shadow.
1280                NSColor::colorWithSRGBRed_green_blue_alpha_(nil, 0f64, 0f64, 0f64, 0.0001)
1281            };
1282            this.native_window.setBackgroundColor_(background_color);
1283
1284            if NSAppKitVersionNumber < NSAppKitVersionNumber12_0 {
1285                // Whether `-[NSVisualEffectView respondsToSelector:@selector(_updateProxyLayer)]`.
1286                // On macOS Catalina/Big Sur `NSVisualEffectView` doesn’t own concrete sublayers
1287                // but uses a `CAProxyLayer`. Use the legacy WindowServer API.
1288                let blur_radius = if background_appearance == WindowBackgroundAppearance::Blurred {
1289                    80
1290                } else {
1291                    0
1292                };
1293
1294                let window_number = this.native_window.windowNumber();
1295                CGSSetWindowBackgroundBlurRadius(CGSMainConnectionID(), window_number, blur_radius);
1296            } else {
1297                // On newer macOS `NSVisualEffectView` manages the effect layer directly. Using it
1298                // could have a better performance (it downsamples the backdrop) and more control
1299                // over the effect layer.
1300                if background_appearance != WindowBackgroundAppearance::Blurred {
1301                    if let Some(blur_view) = this.blurred_view {
1302                        NSView::removeFromSuperview(blur_view);
1303                        this.blurred_view = None;
1304                    }
1305                } else if this.blurred_view.is_none() {
1306                    let content_view = this.native_window.contentView();
1307                    let frame = NSView::bounds(content_view);
1308                    let mut blur_view: id = msg_send![BLURRED_VIEW_CLASS, alloc];
1309                    blur_view = NSView::initWithFrame_(blur_view, frame);
1310                    blur_view.setAutoresizingMask_(NSViewWidthSizable | NSViewHeightSizable);
1311
1312                    let _: () = msg_send![
1313                        content_view,
1314                        addSubview: blur_view
1315                        positioned: NSWindowOrderingMode::NSWindowBelow
1316                        relativeTo: nil
1317                    ];
1318                    this.blurred_view = Some(blur_view.autorelease());
1319                }
1320            }
1321        }
1322    }
1323
1324    fn set_edited(&mut self, edited: bool) {
1325        unsafe {
1326            let window = self.0.lock().native_window;
1327            msg_send![window, setDocumentEdited: edited as BOOL]
1328        }
1329
1330        // Changing the document edited state resets the traffic light position,
1331        // so we have to move it again.
1332        self.0.lock().move_traffic_light();
1333    }
1334
1335    fn show_character_palette(&self) {
1336        let this = self.0.lock();
1337        let window = this.native_window;
1338        this.executor
1339            .spawn(async move {
1340                unsafe {
1341                    let app = NSApplication::sharedApplication(nil);
1342                    let _: () = msg_send![app, orderFrontCharacterPalette: window];
1343                }
1344            })
1345            .detach();
1346    }
1347
1348    fn minimize(&self) {
1349        let window = self.0.lock().native_window;
1350        unsafe {
1351            window.miniaturize_(nil);
1352        }
1353    }
1354
1355    fn zoom(&self) {
1356        let this = self.0.lock();
1357        let window = this.native_window;
1358        this.executor
1359            .spawn(async move {
1360                unsafe {
1361                    window.zoom_(nil);
1362                }
1363            })
1364            .detach();
1365    }
1366
1367    fn toggle_fullscreen(&self) {
1368        let this = self.0.lock();
1369        let window = this.native_window;
1370        this.executor
1371            .spawn(async move {
1372                unsafe {
1373                    window.toggleFullScreen_(nil);
1374                }
1375            })
1376            .detach();
1377    }
1378
1379    fn is_fullscreen(&self) -> bool {
1380        let this = self.0.lock();
1381        let window = this.native_window;
1382
1383        unsafe {
1384            window
1385                .styleMask()
1386                .contains(NSWindowStyleMask::NSFullScreenWindowMask)
1387        }
1388    }
1389
1390    fn on_request_frame(&self, callback: Box<dyn FnMut(RequestFrameOptions)>) {
1391        self.0.as_ref().lock().request_frame_callback = Some(callback);
1392    }
1393
1394    fn on_input(&self, callback: Box<dyn FnMut(PlatformInput) -> crate::DispatchEventResult>) {
1395        self.0.as_ref().lock().event_callback = Some(callback);
1396    }
1397
1398    fn on_active_status_change(&self, callback: Box<dyn FnMut(bool)>) {
1399        self.0.as_ref().lock().activate_callback = Some(callback);
1400    }
1401
1402    fn on_hover_status_change(&self, _: Box<dyn FnMut(bool)>) {}
1403
1404    fn on_resize(&self, callback: Box<dyn FnMut(Size<Pixels>, f32)>) {
1405        self.0.as_ref().lock().resize_callback = Some(callback);
1406    }
1407
1408    fn on_moved(&self, callback: Box<dyn FnMut()>) {
1409        self.0.as_ref().lock().moved_callback = Some(callback);
1410    }
1411
1412    fn on_should_close(&self, callback: Box<dyn FnMut() -> bool>) {
1413        self.0.as_ref().lock().should_close_callback = Some(callback);
1414    }
1415
1416    fn on_close(&self, callback: Box<dyn FnOnce()>) {
1417        self.0.as_ref().lock().close_callback = Some(callback);
1418    }
1419
1420    fn on_hit_test_window_control(&self, _callback: Box<dyn FnMut() -> Option<WindowControlArea>>) {
1421    }
1422
1423    fn on_appearance_changed(&self, callback: Box<dyn FnMut()>) {
1424        self.0.lock().appearance_changed_callback = Some(callback);
1425    }
1426
1427    fn tabbed_windows(&self) -> Option<Vec<SystemWindowTab>> {
1428        unsafe {
1429            let windows: id = msg_send![self.0.lock().native_window, tabbedWindows];
1430            if windows.is_null() {
1431                return None;
1432            }
1433
1434            let count: NSUInteger = msg_send![windows, count];
1435            let mut result = Vec::new();
1436            for i in 0..count {
1437                let window: id = msg_send![windows, objectAtIndex:i];
1438                if msg_send![window, isKindOfClass: WINDOW_CLASS] {
1439                    let handle = get_window_state(&*window).lock().handle;
1440                    let title: id = msg_send![window, title];
1441                    let title = SharedString::from(title.to_str().to_string());
1442
1443                    result.push(SystemWindowTab::new(title, handle));
1444                }
1445            }
1446
1447            Some(result)
1448        }
1449    }
1450
1451    fn tab_bar_visible(&self) -> bool {
1452        unsafe {
1453            let tab_group: id = msg_send![self.0.lock().native_window, tabGroup];
1454            if tab_group.is_null() {
1455                false
1456            } else {
1457                let tab_bar_visible: BOOL = msg_send![tab_group, isTabBarVisible];
1458                tab_bar_visible == YES
1459            }
1460        }
1461    }
1462
1463    fn on_move_tab_to_new_window(&self, callback: Box<dyn FnMut()>) {
1464        self.0.as_ref().lock().move_tab_to_new_window_callback = Some(callback);
1465    }
1466
1467    fn on_merge_all_windows(&self, callback: Box<dyn FnMut()>) {
1468        self.0.as_ref().lock().merge_all_windows_callback = Some(callback);
1469    }
1470
1471    fn on_select_next_tab(&self, callback: Box<dyn FnMut()>) {
1472        self.0.as_ref().lock().select_next_tab_callback = Some(callback);
1473    }
1474
1475    fn on_select_previous_tab(&self, callback: Box<dyn FnMut()>) {
1476        self.0.as_ref().lock().select_previous_tab_callback = Some(callback);
1477    }
1478
1479    fn on_toggle_tab_bar(&self, callback: Box<dyn FnMut()>) {
1480        self.0.as_ref().lock().toggle_tab_bar_callback = Some(callback);
1481    }
1482
1483    fn draw(&self, scene: &crate::Scene) {
1484        let mut this = self.0.lock();
1485        this.renderer.draw(scene);
1486    }
1487
1488    fn sprite_atlas(&self) -> Arc<dyn PlatformAtlas> {
1489        self.0.lock().renderer.sprite_atlas().clone()
1490    }
1491
1492    fn gpu_specs(&self) -> Option<crate::GpuSpecs> {
1493        None
1494    }
1495
1496    fn update_ime_position(&self, _bounds: Bounds<Pixels>) {
1497        let executor = self.0.lock().executor.clone();
1498        executor
1499            .spawn(async move {
1500                unsafe {
1501                    let input_context: id =
1502                        msg_send![class!(NSTextInputContext), currentInputContext];
1503                    if input_context.is_null() {
1504                        return;
1505                    }
1506                    let _: () = msg_send![input_context, invalidateCharacterCoordinates];
1507                }
1508            })
1509            .detach()
1510    }
1511
1512    fn titlebar_double_click(&self) {
1513        let this = self.0.lock();
1514        let window = this.native_window;
1515        this.executor
1516            .spawn(async move {
1517                unsafe {
1518                    let defaults: id = NSUserDefaults::standardUserDefaults();
1519                    let domain = ns_string("NSGlobalDomain");
1520                    let key = ns_string("AppleActionOnDoubleClick");
1521
1522                    let dict: id = msg_send![defaults, persistentDomainForName: domain];
1523                    let action: id = if !dict.is_null() {
1524                        msg_send![dict, objectForKey: key]
1525                    } else {
1526                        nil
1527                    };
1528
1529                    let action_str = if !action.is_null() {
1530                        CStr::from_ptr(NSString::UTF8String(action)).to_string_lossy()
1531                    } else {
1532                        "".into()
1533                    };
1534
1535                    match action_str.as_ref() {
1536                        "None" => {
1537                            // "Do Nothing" selected, so do no action
1538                        }
1539                        "Minimize" => {
1540                            window.miniaturize_(nil);
1541                        }
1542                        "Maximize" => {
1543                            window.zoom_(nil);
1544                        }
1545                        "Fill" => {
1546                            // There is no documented API for "Fill" action, so we'll just zoom the window
1547                            window.zoom_(nil);
1548                        }
1549                        _ => {
1550                            window.zoom_(nil);
1551                        }
1552                    }
1553                }
1554            })
1555            .detach();
1556    }
1557
1558    fn start_window_move(&self) {
1559        let this = self.0.lock();
1560        let window = this.native_window;
1561
1562        unsafe {
1563            let app = NSApplication::sharedApplication(nil);
1564            let mut event: id = msg_send![app, currentEvent];
1565            let _: () = msg_send![window, performWindowDragWithEvent: event];
1566        }
1567    }
1568
1569    #[cfg(any(test, feature = "test-support"))]
1570    fn native_window_id(&self) -> Option<u32> {
1571        Some(self.window_number())
1572    }
1573}
1574
1575impl rwh::HasWindowHandle for MacWindow {
1576    fn window_handle(&self) -> Result<rwh::WindowHandle<'_>, rwh::HandleError> {
1577        // SAFETY: The AppKitWindowHandle is a wrapper around a pointer to an NSView
1578        unsafe {
1579            Ok(rwh::WindowHandle::borrow_raw(rwh::RawWindowHandle::AppKit(
1580                rwh::AppKitWindowHandle::new(self.0.lock().native_view.cast()),
1581            )))
1582        }
1583    }
1584}
1585
1586impl rwh::HasDisplayHandle for MacWindow {
1587    fn display_handle(&self) -> Result<rwh::DisplayHandle<'_>, rwh::HandleError> {
1588        // SAFETY: This is a no-op on macOS
1589        unsafe {
1590            Ok(rwh::DisplayHandle::borrow_raw(
1591                rwh::AppKitDisplayHandle::new().into(),
1592            ))
1593        }
1594    }
1595}
1596
1597fn get_scale_factor(native_window: id) -> f32 {
1598    let factor = unsafe {
1599        let screen: id = msg_send![native_window, screen];
1600        if screen.is_null() {
1601            return 2.0;
1602        }
1603        NSScreen::backingScaleFactor(screen) as f32
1604    };
1605
1606    // We are not certain what triggers this, but it seems that sometimes
1607    // this method would return 0 (https://github.com/zed-industries/zed/issues/6412)
1608    // It seems most likely that this would happen if the window has no screen
1609    // (if it is off-screen), though we'd expect to see viewDidChangeBackingProperties before
1610    // it was rendered for real.
1611    // Regardless, attempt to avoid the issue here.
1612    if factor == 0.0 { 2. } else { factor }
1613}
1614
1615unsafe fn get_window_state(object: &Object) -> Arc<Mutex<MacWindowState>> {
1616    unsafe {
1617        let raw: *mut c_void = *object.get_ivar(WINDOW_STATE_IVAR);
1618        let rc1 = Arc::from_raw(raw as *mut Mutex<MacWindowState>);
1619        let rc2 = rc1.clone();
1620        mem::forget(rc1);
1621        rc2
1622    }
1623}
1624
1625unsafe fn drop_window_state(object: &Object) {
1626    unsafe {
1627        let raw: *mut c_void = *object.get_ivar(WINDOW_STATE_IVAR);
1628        Arc::from_raw(raw as *mut Mutex<MacWindowState>);
1629    }
1630}
1631
1632extern "C" fn yes(_: &Object, _: Sel) -> BOOL {
1633    YES
1634}
1635
1636extern "C" fn dealloc_window(this: &Object, _: Sel) {
1637    unsafe {
1638        drop_window_state(this);
1639        let _: () = msg_send![super(this, class!(NSWindow)), dealloc];
1640    }
1641}
1642
1643extern "C" fn dealloc_view(this: &Object, _: Sel) {
1644    unsafe {
1645        drop_window_state(this);
1646        let _: () = msg_send![super(this, class!(NSView)), dealloc];
1647    }
1648}
1649
1650extern "C" fn handle_key_equivalent(this: &Object, _: Sel, native_event: id) -> BOOL {
1651    handle_key_event(this, native_event, true)
1652}
1653
1654extern "C" fn handle_key_down(this: &Object, _: Sel, native_event: id) {
1655    handle_key_event(this, native_event, false);
1656}
1657
1658extern "C" fn handle_key_up(this: &Object, _: Sel, native_event: id) {
1659    handle_key_event(this, native_event, false);
1660}
1661
1662// Things to test if you're modifying this method:
1663//  U.S. layout:
1664//   - The IME consumes characters like 'j' and 'k', which makes paging through `less` in
1665//     the terminal behave incorrectly by default. This behavior should be patched by our
1666//     IME integration
1667//   - `alt-t` should open the tasks menu
1668//   - In vim mode, this keybinding should work:
1669//     ```
1670//        {
1671//          "context": "Editor && vim_mode == insert",
1672//          "bindings": {"j j": "vim::NormalBefore"}
1673//        }
1674//     ```
1675//     and typing 'j k' in insert mode with this keybinding should insert the two characters
1676//  Brazilian layout:
1677//   - `" space` should create an unmarked quote
1678//   - `" backspace` should delete the marked quote
1679//   - `" "`should create an unmarked quote and a second marked quote
1680//   - `" up` should insert a quote, unmark it, and move up one line
1681//   - `" cmd-down` should insert a quote, unmark it, and move to the end of the file
1682//   - `cmd-ctrl-space` and clicking on an emoji should type it
1683//  Czech (QWERTY) layout:
1684//   - in vim mode `option-4`  should go to end of line (same as $)
1685//  Japanese (Romaji) layout:
1686//   - type `a i left down up enter enter` should create an unmarked text "愛"
1687extern "C" fn handle_key_event(this: &Object, native_event: id, key_equivalent: bool) -> BOOL {
1688    let window_state = unsafe { get_window_state(this) };
1689    let mut lock = window_state.as_ref().lock();
1690
1691    let window_height = lock.content_size().height;
1692    let event = unsafe { PlatformInput::from_native(native_event, Some(window_height)) };
1693
1694    let Some(event) = event else {
1695        return NO;
1696    };
1697
1698    let run_callback = |event: PlatformInput| -> BOOL {
1699        let mut callback = window_state.as_ref().lock().event_callback.take();
1700        let handled: BOOL = if let Some(callback) = callback.as_mut() {
1701            !callback(event).propagate as BOOL
1702        } else {
1703            NO
1704        };
1705        window_state.as_ref().lock().event_callback = callback;
1706        handled
1707    };
1708
1709    match event {
1710        PlatformInput::KeyDown(mut key_down_event) => {
1711            // For certain keystrokes, macOS will first dispatch a "key equivalent" event.
1712            // If that event isn't handled, it will then dispatch a "key down" event. GPUI
1713            // makes no distinction between these two types of events, so we need to ignore
1714            // the "key down" event if we've already just processed its "key equivalent" version.
1715            if key_equivalent {
1716                lock.last_key_equivalent = Some(key_down_event.clone());
1717            } else if lock.last_key_equivalent.take().as_ref() == Some(&key_down_event) {
1718                return NO;
1719            }
1720
1721            drop(lock);
1722
1723            let is_composing =
1724                with_input_handler(this, |input_handler| input_handler.marked_text_range())
1725                    .flatten()
1726                    .is_some();
1727
1728            // If we're composing, send the key to the input handler first;
1729            // otherwise we only send to the input handler if we don't have a matching binding.
1730            // The input handler may call `do_command_by_selector` if it doesn't know how to handle
1731            // a key. If it does so, it will return YES so we won't send the key twice.
1732            // We also do this for non-printing keys (like arrow keys and escape) as the IME menu
1733            // may need them even if there is no marked text;
1734            // however we skip keys with control or the input handler adds control-characters to the buffer.
1735            // and keys with function, as the input handler swallows them.
1736            if is_composing
1737                || (key_down_event.keystroke.key_char.is_none()
1738                    && !key_down_event.keystroke.modifiers.control
1739                    && !key_down_event.keystroke.modifiers.function)
1740            {
1741                {
1742                    let mut lock = window_state.as_ref().lock();
1743                    lock.keystroke_for_do_command = Some(key_down_event.keystroke.clone());
1744                    lock.do_command_handled.take();
1745                    drop(lock);
1746                }
1747
1748                let handled: BOOL = unsafe {
1749                    let input_context: id = msg_send![this, inputContext];
1750                    msg_send![input_context, handleEvent: native_event]
1751                };
1752                window_state.as_ref().lock().keystroke_for_do_command.take();
1753                if let Some(handled) = window_state.as_ref().lock().do_command_handled.take() {
1754                    return handled as BOOL;
1755                } else if handled == YES {
1756                    return YES;
1757                }
1758
1759                let handled = run_callback(PlatformInput::KeyDown(key_down_event));
1760                return handled;
1761            }
1762
1763            let handled = run_callback(PlatformInput::KeyDown(key_down_event.clone()));
1764            if handled == YES {
1765                return YES;
1766            }
1767
1768            if key_down_event.is_held
1769                && let Some(key_char) = key_down_event.keystroke.key_char.as_ref()
1770            {
1771                let handled = with_input_handler(this, |input_handler| {
1772                    if !input_handler.apple_press_and_hold_enabled() {
1773                        input_handler.replace_text_in_range(None, key_char);
1774                        return YES;
1775                    }
1776                    NO
1777                });
1778                if handled == Some(YES) {
1779                    return YES;
1780                }
1781            }
1782
1783            // Don't send key equivalents to the input handler if there are key modifiers other
1784            // than Function key, or macOS shortcuts like cmd-` will stop working.
1785            if key_equivalent && key_down_event.keystroke.modifiers != Modifiers::function() {
1786                return NO;
1787            }
1788
1789            unsafe {
1790                let input_context: id = msg_send![this, inputContext];
1791                msg_send![input_context, handleEvent: native_event]
1792            }
1793        }
1794
1795        PlatformInput::KeyUp(_) => {
1796            drop(lock);
1797            run_callback(event)
1798        }
1799
1800        _ => NO,
1801    }
1802}
1803
1804extern "C" fn handle_view_event(this: &Object, _: Sel, native_event: id) {
1805    let window_state = unsafe { get_window_state(this) };
1806    let weak_window_state = Arc::downgrade(&window_state);
1807    let mut lock = window_state.as_ref().lock();
1808    let window_height = lock.content_size().height;
1809    let event = unsafe { PlatformInput::from_native(native_event, Some(window_height)) };
1810
1811    if let Some(mut event) = event {
1812        match &mut event {
1813            PlatformInput::MouseDown(
1814                event @ MouseDownEvent {
1815                    button: MouseButton::Left,
1816                    modifiers: Modifiers { control: true, .. },
1817                    ..
1818                },
1819            ) => {
1820                // On mac, a ctrl-left click should be handled as a right click.
1821                *event = MouseDownEvent {
1822                    button: MouseButton::Right,
1823                    modifiers: Modifiers {
1824                        control: false,
1825                        ..event.modifiers
1826                    },
1827                    click_count: 1,
1828                    ..*event
1829                };
1830            }
1831
1832            // Handles focusing click.
1833            PlatformInput::MouseDown(
1834                event @ MouseDownEvent {
1835                    button: MouseButton::Left,
1836                    ..
1837                },
1838            ) if (lock.first_mouse) => {
1839                *event = MouseDownEvent {
1840                    first_mouse: true,
1841                    ..*event
1842                };
1843                lock.first_mouse = false;
1844            }
1845
1846            // Because we map a ctrl-left_down to a right_down -> right_up let's ignore
1847            // the ctrl-left_up to avoid having a mismatch in button down/up events if the
1848            // user is still holding ctrl when releasing the left mouse button
1849            PlatformInput::MouseUp(
1850                event @ MouseUpEvent {
1851                    button: MouseButton::Left,
1852                    modifiers: Modifiers { control: true, .. },
1853                    ..
1854                },
1855            ) => {
1856                *event = MouseUpEvent {
1857                    button: MouseButton::Right,
1858                    modifiers: Modifiers {
1859                        control: false,
1860                        ..event.modifiers
1861                    },
1862                    click_count: 1,
1863                    ..*event
1864                };
1865            }
1866
1867            _ => {}
1868        };
1869
1870        match &event {
1871            PlatformInput::MouseDown(_) => {
1872                drop(lock);
1873                unsafe {
1874                    let input_context: id = msg_send![this, inputContext];
1875                    msg_send![input_context, handleEvent: native_event]
1876                }
1877                lock = window_state.as_ref().lock();
1878            }
1879            PlatformInput::MouseMove(
1880                event @ MouseMoveEvent {
1881                    pressed_button: Some(_),
1882                    ..
1883                },
1884            ) => {
1885                // Synthetic drag is used for selecting long buffer contents while buffer is being scrolled.
1886                // External file drag and drop is able to emit its own synthetic mouse events which will conflict
1887                // with these ones.
1888                if !lock.external_files_dragged {
1889                    lock.synthetic_drag_counter += 1;
1890                    let executor = lock.executor.clone();
1891                    executor
1892                        .spawn(synthetic_drag(
1893                            weak_window_state,
1894                            lock.synthetic_drag_counter,
1895                            event.clone(),
1896                        ))
1897                        .detach();
1898                }
1899            }
1900
1901            PlatformInput::MouseUp(MouseUpEvent { .. }) => {
1902                lock.synthetic_drag_counter += 1;
1903            }
1904
1905            PlatformInput::ModifiersChanged(ModifiersChangedEvent {
1906                modifiers,
1907                capslock,
1908            }) => {
1909                // Only raise modifiers changed event when they have actually changed
1910                if let Some(PlatformInput::ModifiersChanged(ModifiersChangedEvent {
1911                    modifiers: prev_modifiers,
1912                    capslock: prev_capslock,
1913                })) = &lock.previous_modifiers_changed_event
1914                    && prev_modifiers == modifiers
1915                    && prev_capslock == capslock
1916                {
1917                    return;
1918                }
1919
1920                lock.previous_modifiers_changed_event = Some(event.clone());
1921            }
1922
1923            _ => {}
1924        }
1925
1926        if let Some(mut callback) = lock.event_callback.take() {
1927            drop(lock);
1928            callback(event);
1929            window_state.lock().event_callback = Some(callback);
1930        }
1931    }
1932}
1933
1934extern "C" fn window_did_change_occlusion_state(this: &Object, _: Sel, _: id) {
1935    let window_state = unsafe { get_window_state(this) };
1936    let lock = &mut *window_state.lock();
1937    unsafe {
1938        if lock
1939            .native_window
1940            .occlusionState()
1941            .contains(NSWindowOcclusionState::NSWindowOcclusionStateVisible)
1942        {
1943            lock.move_traffic_light();
1944            lock.start_display_link();
1945        } else {
1946            lock.stop_display_link();
1947        }
1948    }
1949}
1950
1951extern "C" fn window_did_resize(this: &Object, _: Sel, _: id) {
1952    let window_state = unsafe { get_window_state(this) };
1953    window_state.as_ref().lock().move_traffic_light();
1954}
1955
1956extern "C" fn window_will_enter_fullscreen(this: &Object, _: Sel, _: id) {
1957    let window_state = unsafe { get_window_state(this) };
1958    let mut lock = window_state.as_ref().lock();
1959    lock.fullscreen_restore_bounds = lock.bounds();
1960
1961    let min_version = NSOperatingSystemVersion::new(15, 3, 0);
1962
1963    if is_macos_version_at_least(min_version) {
1964        unsafe {
1965            lock.native_window.setTitlebarAppearsTransparent_(NO);
1966        }
1967    }
1968}
1969
1970extern "C" fn window_will_exit_fullscreen(this: &Object, _: Sel, _: id) {
1971    let window_state = unsafe { get_window_state(this) };
1972    let mut lock = window_state.as_ref().lock();
1973
1974    let min_version = NSOperatingSystemVersion::new(15, 3, 0);
1975
1976    if is_macos_version_at_least(min_version) && lock.transparent_titlebar {
1977        unsafe {
1978            lock.native_window.setTitlebarAppearsTransparent_(YES);
1979        }
1980    }
1981}
1982
1983pub(crate) fn is_macos_version_at_least(version: NSOperatingSystemVersion) -> bool {
1984    unsafe { NSProcessInfo::processInfo(nil).isOperatingSystemAtLeastVersion(version) }
1985}
1986
1987extern "C" fn window_did_move(this: &Object, _: Sel, _: id) {
1988    let window_state = unsafe { get_window_state(this) };
1989    let mut lock = window_state.as_ref().lock();
1990    if let Some(mut callback) = lock.moved_callback.take() {
1991        drop(lock);
1992        callback();
1993        window_state.lock().moved_callback = Some(callback);
1994    }
1995}
1996
1997// Update the window scale factor and drawable size, and call the resize callback if any.
1998fn update_window_scale_factor(window_state: &Arc<Mutex<MacWindowState>>) {
1999    let mut lock = window_state.as_ref().lock();
2000    let scale_factor = lock.scale_factor();
2001    let size = lock.content_size();
2002    let drawable_size = size.to_device_pixels(scale_factor);
2003    unsafe {
2004        let _: () = msg_send![
2005            lock.renderer.layer(),
2006            setContentsScale: scale_factor as f64
2007        ];
2008    }
2009
2010    lock.renderer.update_drawable_size(drawable_size);
2011
2012    if let Some(mut callback) = lock.resize_callback.take() {
2013        let content_size = lock.content_size();
2014        let scale_factor = lock.scale_factor();
2015        drop(lock);
2016        callback(content_size, scale_factor);
2017        window_state.as_ref().lock().resize_callback = Some(callback);
2018    };
2019}
2020
2021extern "C" fn window_did_change_screen(this: &Object, _: Sel, _: id) {
2022    let window_state = unsafe { get_window_state(this) };
2023    let mut lock = window_state.as_ref().lock();
2024    lock.start_display_link();
2025    drop(lock);
2026    update_window_scale_factor(&window_state);
2027}
2028
2029extern "C" fn window_did_change_key_status(this: &Object, selector: Sel, _: id) {
2030    let window_state = unsafe { get_window_state(this) };
2031    let mut lock = window_state.lock();
2032    let is_active = unsafe { lock.native_window.isKeyWindow() == YES };
2033
2034    // When opening a pop-up while the application isn't active, Cocoa sends a spurious
2035    // `windowDidBecomeKey` message to the previous key window even though that window
2036    // isn't actually key. This causes a bug if the application is later activated while
2037    // the pop-up is still open, making it impossible to activate the previous key window
2038    // even if the pop-up gets closed. The only way to activate it again is to de-activate
2039    // the app and re-activate it, which is a pretty bad UX.
2040    // The following code detects the spurious event and invokes `resignKeyWindow`:
2041    // in theory, we're not supposed to invoke this method manually but it balances out
2042    // the spurious `becomeKeyWindow` event and helps us work around that bug.
2043    if selector == sel!(windowDidBecomeKey:) && !is_active {
2044        unsafe {
2045            let _: () = msg_send![lock.native_window, resignKeyWindow];
2046            return;
2047        }
2048    }
2049
2050    let executor = lock.executor.clone();
2051    drop(lock);
2052
2053    // When a window becomes active, trigger an immediate synchronous frame request to prevent
2054    // tab flicker when switching between windows in native tabs mode.
2055    //
2056    // This is only done on subsequent activations (not the first) to ensure the initial focus
2057    // path is properly established. Without this guard, the focus state would remain unset until
2058    // the first mouse click, causing keybindings to be non-functional.
2059    if selector == sel!(windowDidBecomeKey:) && is_active {
2060        let window_state = unsafe { get_window_state(this) };
2061        let mut lock = window_state.lock();
2062
2063        if lock.activated_least_once {
2064            if let Some(mut callback) = lock.request_frame_callback.take() {
2065                #[cfg(not(feature = "macos-blade"))]
2066                lock.renderer.set_presents_with_transaction(true);
2067                lock.stop_display_link();
2068                drop(lock);
2069                callback(Default::default());
2070
2071                let mut lock = window_state.lock();
2072                lock.request_frame_callback = Some(callback);
2073                #[cfg(not(feature = "macos-blade"))]
2074                lock.renderer.set_presents_with_transaction(false);
2075                lock.start_display_link();
2076            }
2077        } else {
2078            lock.activated_least_once = true;
2079        }
2080    }
2081
2082    executor
2083        .spawn(async move {
2084            let mut lock = window_state.as_ref().lock();
2085            if is_active {
2086                lock.move_traffic_light();
2087            }
2088
2089            if let Some(mut callback) = lock.activate_callback.take() {
2090                drop(lock);
2091                callback(is_active);
2092                window_state.lock().activate_callback = Some(callback);
2093            };
2094        })
2095        .detach();
2096}
2097
2098extern "C" fn window_should_close(this: &Object, _: Sel, _: id) -> BOOL {
2099    let window_state = unsafe { get_window_state(this) };
2100    let mut lock = window_state.as_ref().lock();
2101    if let Some(mut callback) = lock.should_close_callback.take() {
2102        drop(lock);
2103        let should_close = callback();
2104        window_state.lock().should_close_callback = Some(callback);
2105        should_close as BOOL
2106    } else {
2107        YES
2108    }
2109}
2110
2111extern "C" fn close_window(this: &Object, _: Sel) {
2112    unsafe {
2113        let close_callback = {
2114            let window_state = get_window_state(this);
2115            let mut lock = window_state.as_ref().lock();
2116            lock.close_callback.take()
2117        };
2118
2119        if let Some(callback) = close_callback {
2120            callback();
2121        }
2122
2123        let _: () = msg_send![super(this, class!(NSWindow)), close];
2124    }
2125}
2126
2127extern "C" fn make_backing_layer(this: &Object, _: Sel) -> id {
2128    let window_state = unsafe { get_window_state(this) };
2129    let window_state = window_state.as_ref().lock();
2130    window_state.renderer.layer_ptr() as id
2131}
2132
2133extern "C" fn view_did_change_backing_properties(this: &Object, _: Sel) {
2134    let window_state = unsafe { get_window_state(this) };
2135    update_window_scale_factor(&window_state);
2136}
2137
2138extern "C" fn set_frame_size(this: &Object, _: Sel, size: NSSize) {
2139    let window_state = unsafe { get_window_state(this) };
2140    let mut lock = window_state.as_ref().lock();
2141
2142    let new_size = Size::<Pixels>::from(size);
2143    let old_size = unsafe {
2144        let old_frame: NSRect = msg_send![this, frame];
2145        Size::<Pixels>::from(old_frame.size)
2146    };
2147
2148    if old_size == new_size {
2149        return;
2150    }
2151
2152    unsafe {
2153        let _: () = msg_send![super(this, class!(NSView)), setFrameSize: size];
2154    }
2155
2156    let scale_factor = lock.scale_factor();
2157    let drawable_size = new_size.to_device_pixels(scale_factor);
2158    lock.renderer.update_drawable_size(drawable_size);
2159
2160    if let Some(mut callback) = lock.resize_callback.take() {
2161        let content_size = lock.content_size();
2162        let scale_factor = lock.scale_factor();
2163        drop(lock);
2164        callback(content_size, scale_factor);
2165        window_state.lock().resize_callback = Some(callback);
2166    };
2167}
2168
2169extern "C" fn display_layer(this: &Object, _: Sel, _: id) {
2170    let window_state = unsafe { get_window_state(this) };
2171    let mut lock = window_state.lock();
2172    if let Some(mut callback) = lock.request_frame_callback.take() {
2173        #[cfg(not(feature = "macos-blade"))]
2174        lock.renderer.set_presents_with_transaction(true);
2175        lock.stop_display_link();
2176        drop(lock);
2177        callback(Default::default());
2178
2179        let mut lock = window_state.lock();
2180        lock.request_frame_callback = Some(callback);
2181        #[cfg(not(feature = "macos-blade"))]
2182        lock.renderer.set_presents_with_transaction(false);
2183        lock.start_display_link();
2184    }
2185}
2186
2187unsafe extern "C" fn step(view: *mut c_void) {
2188    let view = view as id;
2189    let window_state = unsafe { get_window_state(&*view) };
2190    let mut lock = window_state.lock();
2191
2192    if let Some(mut callback) = lock.request_frame_callback.take() {
2193        drop(lock);
2194        callback(Default::default());
2195        window_state.lock().request_frame_callback = Some(callback);
2196    }
2197}
2198
2199extern "C" fn valid_attributes_for_marked_text(_: &Object, _: Sel) -> id {
2200    unsafe { msg_send![class!(NSArray), array] }
2201}
2202
2203extern "C" fn has_marked_text(this: &Object, _: Sel) -> BOOL {
2204    let has_marked_text_result =
2205        with_input_handler(this, |input_handler| input_handler.marked_text_range()).flatten();
2206
2207    has_marked_text_result.is_some() as BOOL
2208}
2209
2210extern "C" fn marked_range(this: &Object, _: Sel) -> NSRange {
2211    let marked_range_result =
2212        with_input_handler(this, |input_handler| input_handler.marked_text_range()).flatten();
2213
2214    marked_range_result.map_or(NSRange::invalid(), |range| range.into())
2215}
2216
2217extern "C" fn selected_range(this: &Object, _: Sel) -> NSRange {
2218    let selected_range_result = with_input_handler(this, |input_handler| {
2219        input_handler.selected_text_range(false)
2220    })
2221    .flatten();
2222
2223    selected_range_result.map_or(NSRange::invalid(), |selection| selection.range.into())
2224}
2225
2226extern "C" fn first_rect_for_character_range(
2227    this: &Object,
2228    _: Sel,
2229    range: NSRange,
2230    _: id,
2231) -> NSRect {
2232    let frame = get_frame(this);
2233    with_input_handler(this, |input_handler| {
2234        input_handler.bounds_for_range(range.to_range()?)
2235    })
2236    .flatten()
2237    .map_or(
2238        NSRect::new(NSPoint::new(0., 0.), NSSize::new(0., 0.)),
2239        |bounds| {
2240            NSRect::new(
2241                NSPoint::new(
2242                    frame.origin.x + bounds.origin.x.0 as f64,
2243                    frame.origin.y + frame.size.height
2244                        - bounds.origin.y.0 as f64
2245                        - bounds.size.height.0 as f64,
2246                ),
2247                NSSize::new(bounds.size.width.0 as f64, bounds.size.height.0 as f64),
2248            )
2249        },
2250    )
2251}
2252
2253fn get_frame(this: &Object) -> NSRect {
2254    unsafe {
2255        let state = get_window_state(this);
2256        let lock = state.lock();
2257        let mut frame = NSWindow::frame(lock.native_window);
2258        let content_layout_rect: CGRect = msg_send![lock.native_window, contentLayoutRect];
2259        let style_mask: NSWindowStyleMask = msg_send![lock.native_window, styleMask];
2260        if !style_mask.contains(NSWindowStyleMask::NSFullSizeContentViewWindowMask) {
2261            frame.origin.y -= frame.size.height - content_layout_rect.size.height;
2262        }
2263        frame
2264    }
2265}
2266
2267extern "C" fn insert_text(this: &Object, _: Sel, text: id, replacement_range: NSRange) {
2268    unsafe {
2269        let is_attributed_string: BOOL =
2270            msg_send![text, isKindOfClass: [class!(NSAttributedString)]];
2271        let text: id = if is_attributed_string == YES {
2272            msg_send![text, string]
2273        } else {
2274            text
2275        };
2276
2277        let text = text.to_str();
2278        let replacement_range = replacement_range.to_range();
2279        with_input_handler(this, |input_handler| {
2280            input_handler.replace_text_in_range(replacement_range, text)
2281        });
2282    }
2283}
2284
2285extern "C" fn set_marked_text(
2286    this: &Object,
2287    _: Sel,
2288    text: id,
2289    selected_range: NSRange,
2290    replacement_range: NSRange,
2291) {
2292    unsafe {
2293        let is_attributed_string: BOOL =
2294            msg_send![text, isKindOfClass: [class!(NSAttributedString)]];
2295        let text: id = if is_attributed_string == YES {
2296            msg_send![text, string]
2297        } else {
2298            text
2299        };
2300        let selected_range = selected_range.to_range();
2301        let replacement_range = replacement_range.to_range();
2302        let text = text.to_str();
2303        with_input_handler(this, |input_handler| {
2304            input_handler.replace_and_mark_text_in_range(replacement_range, text, selected_range)
2305        });
2306    }
2307}
2308extern "C" fn unmark_text(this: &Object, _: Sel) {
2309    with_input_handler(this, |input_handler| input_handler.unmark_text());
2310}
2311
2312extern "C" fn attributed_substring_for_proposed_range(
2313    this: &Object,
2314    _: Sel,
2315    range: NSRange,
2316    actual_range: *mut c_void,
2317) -> id {
2318    with_input_handler(this, |input_handler| {
2319        let range = range.to_range()?;
2320        if range.is_empty() {
2321            return None;
2322        }
2323        let mut adjusted: Option<Range<usize>> = None;
2324
2325        let selected_text = input_handler.text_for_range(range.clone(), &mut adjusted)?;
2326        if let Some(adjusted) = adjusted
2327            && adjusted != range
2328        {
2329            unsafe { (actual_range as *mut NSRange).write(NSRange::from(adjusted)) };
2330        }
2331        unsafe {
2332            let string: id = msg_send![class!(NSAttributedString), alloc];
2333            let string: id = msg_send![string, initWithString: ns_string(&selected_text)];
2334            Some(string)
2335        }
2336    })
2337    .flatten()
2338    .unwrap_or(nil)
2339}
2340
2341// We ignore which selector it asks us to do because the user may have
2342// bound the shortcut to something else.
2343extern "C" fn do_command_by_selector(this: &Object, _: Sel, _: Sel) {
2344    let state = unsafe { get_window_state(this) };
2345    let mut lock = state.as_ref().lock();
2346    let keystroke = lock.keystroke_for_do_command.take();
2347    let mut event_callback = lock.event_callback.take();
2348    drop(lock);
2349
2350    if let Some((keystroke, mut callback)) = keystroke.zip(event_callback.as_mut()) {
2351        let handled = (callback)(PlatformInput::KeyDown(KeyDownEvent {
2352            keystroke,
2353            is_held: false,
2354            prefer_character_input: false,
2355        }));
2356        state.as_ref().lock().do_command_handled = Some(!handled.propagate);
2357    }
2358
2359    state.as_ref().lock().event_callback = event_callback;
2360}
2361
2362extern "C" fn view_did_change_effective_appearance(this: &Object, _: Sel) {
2363    unsafe {
2364        let state = get_window_state(this);
2365        let mut lock = state.as_ref().lock();
2366        if let Some(mut callback) = lock.appearance_changed_callback.take() {
2367            drop(lock);
2368            callback();
2369            state.lock().appearance_changed_callback = Some(callback);
2370        }
2371    }
2372}
2373
2374extern "C" fn accepts_first_mouse(this: &Object, _: Sel, _: id) -> BOOL {
2375    let window_state = unsafe { get_window_state(this) };
2376    let mut lock = window_state.as_ref().lock();
2377    lock.first_mouse = true;
2378    YES
2379}
2380
2381extern "C" fn character_index_for_point(this: &Object, _: Sel, position: NSPoint) -> u64 {
2382    let position = screen_point_to_gpui_point(this, position);
2383    with_input_handler(this, |input_handler| {
2384        input_handler.character_index_for_point(position)
2385    })
2386    .flatten()
2387    .map(|index| index as u64)
2388    .unwrap_or(NSNotFound as u64)
2389}
2390
2391fn screen_point_to_gpui_point(this: &Object, position: NSPoint) -> Point<Pixels> {
2392    let frame = get_frame(this);
2393    let window_x = position.x - frame.origin.x;
2394    let window_y = frame.size.height - (position.y - frame.origin.y);
2395
2396    point(px(window_x as f32), px(window_y as f32))
2397}
2398
2399extern "C" fn dragging_entered(this: &Object, _: Sel, dragging_info: id) -> NSDragOperation {
2400    let window_state = unsafe { get_window_state(this) };
2401    let position = drag_event_position(&window_state, dragging_info);
2402    let paths = external_paths_from_event(dragging_info);
2403    if let Some(event) =
2404        paths.map(|paths| PlatformInput::FileDrop(FileDropEvent::Entered { position, paths }))
2405        && send_new_event(&window_state, event)
2406    {
2407        window_state.lock().external_files_dragged = true;
2408        return NSDragOperationCopy;
2409    }
2410    NSDragOperationNone
2411}
2412
2413extern "C" fn dragging_updated(this: &Object, _: Sel, dragging_info: id) -> NSDragOperation {
2414    let window_state = unsafe { get_window_state(this) };
2415    let position = drag_event_position(&window_state, dragging_info);
2416    if send_new_event(
2417        &window_state,
2418        PlatformInput::FileDrop(FileDropEvent::Pending { position }),
2419    ) {
2420        NSDragOperationCopy
2421    } else {
2422        NSDragOperationNone
2423    }
2424}
2425
2426extern "C" fn dragging_exited(this: &Object, _: Sel, _: id) {
2427    let window_state = unsafe { get_window_state(this) };
2428    send_new_event(
2429        &window_state,
2430        PlatformInput::FileDrop(FileDropEvent::Exited),
2431    );
2432    window_state.lock().external_files_dragged = false;
2433}
2434
2435extern "C" fn perform_drag_operation(this: &Object, _: Sel, dragging_info: id) -> BOOL {
2436    let window_state = unsafe { get_window_state(this) };
2437    let position = drag_event_position(&window_state, dragging_info);
2438    send_new_event(
2439        &window_state,
2440        PlatformInput::FileDrop(FileDropEvent::Submit { position }),
2441    )
2442    .to_objc()
2443}
2444
2445fn external_paths_from_event(dragging_info: *mut Object) -> Option<ExternalPaths> {
2446    let mut paths = SmallVec::new();
2447    let pasteboard: id = unsafe { msg_send![dragging_info, draggingPasteboard] };
2448    let filenames = unsafe { NSPasteboard::propertyListForType(pasteboard, NSFilenamesPboardType) };
2449    if filenames == nil {
2450        return None;
2451    }
2452    for file in unsafe { filenames.iter() } {
2453        let path = unsafe {
2454            let f = NSString::UTF8String(file);
2455            CStr::from_ptr(f).to_string_lossy().into_owned()
2456        };
2457        paths.push(PathBuf::from(path))
2458    }
2459    Some(ExternalPaths(paths))
2460}
2461
2462extern "C" fn conclude_drag_operation(this: &Object, _: Sel, _: id) {
2463    let window_state = unsafe { get_window_state(this) };
2464    send_new_event(
2465        &window_state,
2466        PlatformInput::FileDrop(FileDropEvent::Exited),
2467    );
2468}
2469
2470async fn synthetic_drag(
2471    window_state: Weak<Mutex<MacWindowState>>,
2472    drag_id: usize,
2473    event: MouseMoveEvent,
2474) {
2475    loop {
2476        Timer::after(Duration::from_millis(16)).await;
2477        if let Some(window_state) = window_state.upgrade() {
2478            let mut lock = window_state.lock();
2479            if lock.synthetic_drag_counter == drag_id {
2480                if let Some(mut callback) = lock.event_callback.take() {
2481                    drop(lock);
2482                    callback(PlatformInput::MouseMove(event.clone()));
2483                    window_state.lock().event_callback = Some(callback);
2484                }
2485            } else {
2486                break;
2487            }
2488        }
2489    }
2490}
2491
2492fn send_new_event(window_state_lock: &Mutex<MacWindowState>, e: PlatformInput) -> bool {
2493    let window_state = window_state_lock.lock().event_callback.take();
2494    if let Some(mut callback) = window_state {
2495        callback(e);
2496        window_state_lock.lock().event_callback = Some(callback);
2497        true
2498    } else {
2499        false
2500    }
2501}
2502
2503fn drag_event_position(window_state: &Mutex<MacWindowState>, dragging_info: id) -> Point<Pixels> {
2504    let drag_location: NSPoint = unsafe { msg_send![dragging_info, draggingLocation] };
2505    convert_mouse_position(drag_location, window_state.lock().content_size().height)
2506}
2507
2508fn with_input_handler<F, R>(window: &Object, f: F) -> Option<R>
2509where
2510    F: FnOnce(&mut PlatformInputHandler) -> R,
2511{
2512    let window_state = unsafe { get_window_state(window) };
2513    let mut lock = window_state.as_ref().lock();
2514    if let Some(mut input_handler) = lock.input_handler.take() {
2515        drop(lock);
2516        let result = f(&mut input_handler);
2517        window_state.lock().input_handler = Some(input_handler);
2518        Some(result)
2519    } else {
2520        None
2521    }
2522}
2523
2524unsafe fn display_id_for_screen(screen: id) -> CGDirectDisplayID {
2525    unsafe {
2526        let device_description = NSScreen::deviceDescription(screen);
2527        let screen_number_key: id = ns_string("NSScreenNumber");
2528        let screen_number = device_description.objectForKey_(screen_number_key);
2529        let screen_number: NSUInteger = msg_send![screen_number, unsignedIntegerValue];
2530        screen_number as CGDirectDisplayID
2531    }
2532}
2533
2534extern "C" fn blurred_view_init_with_frame(this: &Object, _: Sel, frame: NSRect) -> id {
2535    unsafe {
2536        let view = msg_send![super(this, class!(NSVisualEffectView)), initWithFrame: frame];
2537        // Use a colorless semantic material. The default value `AppearanceBased`, though not
2538        // manually set, is deprecated.
2539        NSVisualEffectView::setMaterial_(view, NSVisualEffectMaterial::Selection);
2540        NSVisualEffectView::setState_(view, NSVisualEffectState::Active);
2541        view
2542    }
2543}
2544
2545extern "C" fn blurred_view_update_layer(this: &Object, _: Sel) {
2546    unsafe {
2547        let _: () = msg_send![super(this, class!(NSVisualEffectView)), updateLayer];
2548        let layer: id = msg_send![this, layer];
2549        if !layer.is_null() {
2550            remove_layer_background(layer);
2551        }
2552    }
2553}
2554
2555unsafe fn remove_layer_background(layer: id) {
2556    unsafe {
2557        let _: () = msg_send![layer, setBackgroundColor:nil];
2558
2559        let class_name: id = msg_send![layer, className];
2560        if class_name.isEqualToString("CAChameleonLayer") {
2561            // Remove the desktop tinting effect.
2562            let _: () = msg_send![layer, setHidden: YES];
2563            return;
2564        }
2565
2566        let filters: id = msg_send![layer, filters];
2567        if !filters.is_null() {
2568            // Remove the increased saturation.
2569            // The effect of a `CAFilter` or `CIFilter` is determined by its name, and the
2570            // `description` reflects its name and some parameters. Currently `NSVisualEffectView`
2571            // uses a `CAFilter` named "colorSaturate". If one day they switch to `CIFilter`, the
2572            // `description` will still contain "Saturat" ("... inputSaturation = ...").
2573            let test_string: id = ns_string("Saturat");
2574            let count = NSArray::count(filters);
2575            for i in 0..count {
2576                let description: id = msg_send![filters.objectAtIndex(i), description];
2577                let hit: BOOL = msg_send![description, containsString: test_string];
2578                if hit == NO {
2579                    continue;
2580                }
2581
2582                let all_indices = NSRange {
2583                    location: 0,
2584                    length: count,
2585                };
2586                let indices: id = msg_send![class!(NSMutableIndexSet), indexSet];
2587                let _: () = msg_send![indices, addIndexesInRange: all_indices];
2588                let _: () = msg_send![indices, removeIndex:i];
2589                let filtered: id = msg_send![filters, objectsAtIndexes: indices];
2590                let _: () = msg_send![layer, setFilters: filtered];
2591                break;
2592            }
2593        }
2594
2595        let sublayers: id = msg_send![layer, sublayers];
2596        if !sublayers.is_null() {
2597            let count = NSArray::count(sublayers);
2598            for i in 0..count {
2599                let sublayer = sublayers.objectAtIndex(i);
2600                remove_layer_background(sublayer);
2601            }
2602        }
2603    }
2604}
2605
2606extern "C" fn add_titlebar_accessory_view_controller(this: &Object, _: Sel, view_controller: id) {
2607    unsafe {
2608        let _: () = msg_send![super(this, class!(NSWindow)), addTitlebarAccessoryViewController: view_controller];
2609
2610        // Hide the native tab bar and set its height to 0, since we render our own.
2611        let accessory_view: id = msg_send![view_controller, view];
2612        let _: () = msg_send![accessory_view, setHidden: YES];
2613        let mut frame: NSRect = msg_send![accessory_view, frame];
2614        frame.size.height = 0.0;
2615        let _: () = msg_send![accessory_view, setFrame: frame];
2616    }
2617}
2618
2619extern "C" fn move_tab_to_new_window(this: &Object, _: Sel, _: id) {
2620    unsafe {
2621        let _: () = msg_send![super(this, class!(NSWindow)), moveTabToNewWindow:nil];
2622
2623        let window_state = get_window_state(this);
2624        let mut lock = window_state.as_ref().lock();
2625        if let Some(mut callback) = lock.move_tab_to_new_window_callback.take() {
2626            drop(lock);
2627            callback();
2628            window_state.lock().move_tab_to_new_window_callback = Some(callback);
2629        }
2630    }
2631}
2632
2633extern "C" fn merge_all_windows(this: &Object, _: Sel, _: id) {
2634    unsafe {
2635        let _: () = msg_send![super(this, class!(NSWindow)), mergeAllWindows:nil];
2636
2637        let window_state = get_window_state(this);
2638        let mut lock = window_state.as_ref().lock();
2639        if let Some(mut callback) = lock.merge_all_windows_callback.take() {
2640            drop(lock);
2641            callback();
2642            window_state.lock().merge_all_windows_callback = Some(callback);
2643        }
2644    }
2645}
2646
2647extern "C" fn select_next_tab(this: &Object, _sel: Sel, _id: id) {
2648    let window_state = unsafe { get_window_state(this) };
2649    let mut lock = window_state.as_ref().lock();
2650    if let Some(mut callback) = lock.select_next_tab_callback.take() {
2651        drop(lock);
2652        callback();
2653        window_state.lock().select_next_tab_callback = Some(callback);
2654    }
2655}
2656
2657extern "C" fn select_previous_tab(this: &Object, _sel: Sel, _id: id) {
2658    let window_state = unsafe { get_window_state(this) };
2659    let mut lock = window_state.as_ref().lock();
2660    if let Some(mut callback) = lock.select_previous_tab_callback.take() {
2661        drop(lock);
2662        callback();
2663        window_state.lock().select_previous_tab_callback = Some(callback);
2664    }
2665}
2666
2667extern "C" fn toggle_tab_bar(this: &Object, _sel: Sel, _id: id) {
2668    unsafe {
2669        let _: () = msg_send![super(this, class!(NSWindow)), toggleTabBar:nil];
2670
2671        let window_state = get_window_state(this);
2672        let mut lock = window_state.as_ref().lock();
2673        lock.move_traffic_light();
2674
2675        if let Some(mut callback) = lock.toggle_tab_bar_callback.take() {
2676            drop(lock);
2677            callback();
2678            window_state.lock().toggle_tab_bar_callback = Some(callback);
2679        }
2680    }
2681}