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