window.rs

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