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