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