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