window.rs

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