window.rs

   1use super::{ns_string, renderer, MacDisplay, NSRange, NSStringExt};
   2use crate::{
   3    platform::PlatformInputHandler, point, px, size, AnyWindowHandle, Bounds, DisplayLink,
   4    ExternalPaths, FileDropEvent, ForegroundExecutor, KeyDownEvent, Keystroke, Modifiers,
   5    ModifiersChangedEvent, MouseButton, MouseDownEvent, MouseMoveEvent, MouseUpEvent, Pixels,
   6    PlatformAtlas, PlatformDisplay, PlatformInput, PlatformWindow, Point, PromptLevel,
   7    RequestFrameOptions, ScaledPixels, Size, Timer, WindowAppearance, WindowBackgroundAppearance,
   8    WindowBounds, WindowKind, WindowParams,
   9};
  10use block::ConcreteBlock;
  11use cocoa::{
  12    appkit::{
  13        NSApplication, NSBackingStoreBuffered, NSColor, NSEvent, NSEventModifierFlags,
  14        NSFilenamesPboardType, NSPasteboard, NSScreen, NSView, NSViewHeightSizable,
  15        NSViewWidthSizable, NSWindow, NSWindowButton, NSWindowCollectionBehavior,
  16        NSWindowOcclusionState, NSWindowStyleMask, NSWindowTitleVisibility,
  17    },
  18    base::{id, nil},
  19    foundation::{
  20        NSArray, NSAutoreleasePool, NSDictionary, NSFastEnumeration, NSInteger, NSPoint, NSRect,
  21        NSSize, NSString, NSUInteger,
  22    },
  23};
  24use core_graphics::display::{CGDirectDisplayID, CGPoint, CGRect};
  25use ctor::ctor;
  26use futures::channel::oneshot;
  27use objc::{
  28    class,
  29    declare::ClassDecl,
  30    msg_send,
  31    runtime::{Class, Object, Protocol, Sel, BOOL, NO, YES},
  32    sel, sel_impl,
  33};
  34use parking_lot::Mutex;
  35use raw_window_handle as rwh;
  36use smallvec::SmallVec;
  37use std::{
  38    cell::Cell,
  39    ffi::{c_void, CStr},
  40    mem,
  41    path::PathBuf,
  42    ptr::{self, NonNull},
  43    rc::Rc,
  44    sync::{Arc, Weak},
  45    time::Duration,
  46};
  47use util::ResultExt;
  48
  49const WINDOW_STATE_IVAR: &str = "windowState";
  50
  51static mut WINDOW_CLASS: *const Class = ptr::null();
  52static mut PANEL_CLASS: *const Class = ptr::null();
  53static mut VIEW_CLASS: *const Class = ptr::null();
  54
  55#[allow(non_upper_case_globals)]
  56const NSWindowStyleMaskNonactivatingPanel: NSWindowStyleMask =
  57    NSWindowStyleMask::from_bits_retain(1 << 7);
  58#[allow(non_upper_case_globals)]
  59const NSNormalWindowLevel: NSInteger = 0;
  60#[allow(non_upper_case_globals)]
  61const NSPopUpWindowLevel: NSInteger = 101;
  62#[allow(non_upper_case_globals)]
  63const NSTrackingMouseEnteredAndExited: NSUInteger = 0x01;
  64#[allow(non_upper_case_globals)]
  65const NSTrackingMouseMoved: NSUInteger = 0x02;
  66#[allow(non_upper_case_globals)]
  67const NSTrackingActiveAlways: NSUInteger = 0x80;
  68#[allow(non_upper_case_globals)]
  69const NSTrackingInVisibleRect: NSUInteger = 0x200;
  70#[allow(non_upper_case_globals)]
  71const NSWindowAnimationBehaviorUtilityWindow: NSInteger = 4;
  72#[allow(non_upper_case_globals)]
  73const NSViewLayerContentsRedrawDuringViewResize: NSInteger = 2;
  74// https://developer.apple.com/documentation/appkit/nsdragoperation
  75type NSDragOperation = NSUInteger;
  76#[allow(non_upper_case_globals)]
  77const NSDragOperationNone: NSDragOperation = 0;
  78#[allow(non_upper_case_globals)]
  79const NSDragOperationCopy: NSDragOperation = 1;
  80
  81#[link(name = "CoreGraphics", kind = "framework")]
  82extern "C" {
  83    // Widely used private APIs; Apple uses them for their Terminal.app.
  84    fn CGSMainConnectionID() -> id;
  85    fn CGSSetWindowBackgroundBlurRadius(
  86        connection_id: id,
  87        window_id: NSInteger,
  88        radius: i64,
  89    ) -> i32;
  90}
  91
  92#[ctor]
  93unsafe fn build_classes() {
  94    WINDOW_CLASS = build_window_class("GPUIWindow", class!(NSWindow));
  95    PANEL_CLASS = build_window_class("GPUIPanel", class!(NSPanel));
  96    VIEW_CLASS = {
  97        let mut decl = ClassDecl::new("GPUIView", class!(NSView)).unwrap();
  98        decl.add_ivar::<*mut c_void>(WINDOW_STATE_IVAR);
  99
 100        decl.add_method(sel!(dealloc), dealloc_view as extern "C" fn(&Object, Sel));
 101
 102        decl.add_method(
 103            sel!(performKeyEquivalent:),
 104            handle_key_equivalent as extern "C" fn(&Object, Sel, id) -> BOOL,
 105        );
 106        decl.add_method(
 107            sel!(keyDown:),
 108            handle_key_down as extern "C" fn(&Object, Sel, id),
 109        );
 110        decl.add_method(
 111            sel!(mouseDown:),
 112            handle_view_event as extern "C" fn(&Object, Sel, id),
 113        );
 114        decl.add_method(
 115            sel!(mouseUp:),
 116            handle_view_event as extern "C" fn(&Object, Sel, id),
 117        );
 118        decl.add_method(
 119            sel!(rightMouseDown:),
 120            handle_view_event as extern "C" fn(&Object, Sel, id),
 121        );
 122        decl.add_method(
 123            sel!(rightMouseUp:),
 124            handle_view_event as extern "C" fn(&Object, Sel, id),
 125        );
 126        decl.add_method(
 127            sel!(otherMouseDown:),
 128            handle_view_event as extern "C" fn(&Object, Sel, id),
 129        );
 130        decl.add_method(
 131            sel!(otherMouseUp:),
 132            handle_view_event as extern "C" fn(&Object, Sel, id),
 133        );
 134        decl.add_method(
 135            sel!(mouseMoved:),
 136            handle_view_event as extern "C" fn(&Object, Sel, id),
 137        );
 138        decl.add_method(
 139            sel!(mouseExited:),
 140            handle_view_event as extern "C" fn(&Object, Sel, id),
 141        );
 142        decl.add_method(
 143            sel!(mouseDragged:),
 144            handle_view_event as extern "C" fn(&Object, Sel, id),
 145        );
 146        decl.add_method(
 147            sel!(scrollWheel:),
 148            handle_view_event as extern "C" fn(&Object, Sel, id),
 149        );
 150        decl.add_method(
 151            sel!(flagsChanged:),
 152            handle_view_event as extern "C" fn(&Object, Sel, id),
 153        );
 154        decl.add_method(
 155            sel!(cancelOperation:),
 156            cancel_operation as extern "C" fn(&Object, Sel, id),
 157        );
 158
 159        decl.add_method(
 160            sel!(makeBackingLayer),
 161            make_backing_layer as extern "C" fn(&Object, Sel) -> id,
 162        );
 163
 164        decl.add_protocol(Protocol::get("CALayerDelegate").unwrap());
 165        decl.add_method(
 166            sel!(viewDidChangeBackingProperties),
 167            view_did_change_backing_properties as extern "C" fn(&Object, Sel),
 168        );
 169        decl.add_method(
 170            sel!(setFrameSize:),
 171            set_frame_size as extern "C" fn(&Object, Sel, NSSize),
 172        );
 173        decl.add_method(
 174            sel!(displayLayer:),
 175            display_layer as extern "C" fn(&Object, Sel, id),
 176        );
 177
 178        decl.add_protocol(Protocol::get("NSTextInputClient").unwrap());
 179        decl.add_method(
 180            sel!(validAttributesForMarkedText),
 181            valid_attributes_for_marked_text as extern "C" fn(&Object, Sel) -> id,
 182        );
 183        decl.add_method(
 184            sel!(hasMarkedText),
 185            has_marked_text as extern "C" fn(&Object, Sel) -> BOOL,
 186        );
 187        decl.add_method(
 188            sel!(markedRange),
 189            marked_range as extern "C" fn(&Object, Sel) -> NSRange,
 190        );
 191        decl.add_method(
 192            sel!(selectedRange),
 193            selected_range as extern "C" fn(&Object, Sel) -> NSRange,
 194        );
 195        decl.add_method(
 196            sel!(firstRectForCharacterRange:actualRange:),
 197            first_rect_for_character_range as extern "C" fn(&Object, Sel, NSRange, id) -> NSRect,
 198        );
 199        decl.add_method(
 200            sel!(insertText:replacementRange:),
 201            insert_text as extern "C" fn(&Object, Sel, id, NSRange),
 202        );
 203        decl.add_method(
 204            sel!(setMarkedText:selectedRange:replacementRange:),
 205            set_marked_text as extern "C" fn(&Object, Sel, id, NSRange, NSRange),
 206        );
 207        decl.add_method(sel!(unmarkText), unmark_text as extern "C" fn(&Object, Sel));
 208        decl.add_method(
 209            sel!(attributedSubstringForProposedRange:actualRange:),
 210            attributed_substring_for_proposed_range
 211                as extern "C" fn(&Object, Sel, NSRange, *mut c_void) -> id,
 212        );
 213        decl.add_method(
 214            sel!(viewDidChangeEffectiveAppearance),
 215            view_did_change_effective_appearance as extern "C" fn(&Object, Sel),
 216        );
 217
 218        // Suppress beep on keystrokes with modifier keys.
 219        decl.add_method(
 220            sel!(doCommandBySelector:),
 221            do_command_by_selector as extern "C" fn(&Object, Sel, Sel),
 222        );
 223
 224        decl.add_method(
 225            sel!(acceptsFirstMouse:),
 226            accepts_first_mouse as extern "C" fn(&Object, Sel, id) -> BOOL,
 227        );
 228
 229        decl.register()
 230    };
 231}
 232
 233pub(crate) fn convert_mouse_position(position: NSPoint, window_height: Pixels) -> Point<Pixels> {
 234    point(
 235        px(position.x as f32),
 236        // macOS screen coordinates are relative to bottom left
 237        window_height - px(position.y as f32),
 238    )
 239}
 240
 241unsafe fn build_window_class(name: &'static str, superclass: &Class) -> *const Class {
 242    let mut decl = ClassDecl::new(name, superclass).unwrap();
 243    decl.add_ivar::<*mut c_void>(WINDOW_STATE_IVAR);
 244    decl.add_method(sel!(dealloc), dealloc_window as extern "C" fn(&Object, Sel));
 245    decl.add_method(
 246        sel!(canBecomeMainWindow),
 247        yes as extern "C" fn(&Object, Sel) -> BOOL,
 248    );
 249    decl.add_method(
 250        sel!(canBecomeKeyWindow),
 251        yes as extern "C" fn(&Object, Sel) -> BOOL,
 252    );
 253    decl.add_method(
 254        sel!(windowDidResize:),
 255        window_did_resize as extern "C" fn(&Object, Sel, id),
 256    );
 257    decl.add_method(
 258        sel!(windowDidChangeOcclusionState:),
 259        window_did_change_occlusion_state as extern "C" fn(&Object, Sel, id),
 260    );
 261    decl.add_method(
 262        sel!(windowWillEnterFullScreen:),
 263        window_will_enter_fullscreen as extern "C" fn(&Object, Sel, id),
 264    );
 265    decl.add_method(
 266        sel!(windowDidMove:),
 267        window_did_move as extern "C" fn(&Object, Sel, id),
 268    );
 269    decl.add_method(
 270        sel!(windowDidChangeScreen:),
 271        window_did_change_screen as extern "C" fn(&Object, Sel, id),
 272    );
 273    decl.add_method(
 274        sel!(windowDidBecomeKey:),
 275        window_did_change_key_status as extern "C" fn(&Object, Sel, id),
 276    );
 277    decl.add_method(
 278        sel!(windowDidResignKey:),
 279        window_did_change_key_status as extern "C" fn(&Object, Sel, id),
 280    );
 281    decl.add_method(
 282        sel!(windowShouldClose:),
 283        window_should_close as extern "C" fn(&Object, Sel, id) -> BOOL,
 284    );
 285
 286    decl.add_method(sel!(close), close_window as extern "C" fn(&Object, Sel));
 287
 288    decl.add_method(
 289        sel!(draggingEntered:),
 290        dragging_entered as extern "C" fn(&Object, Sel, id) -> NSDragOperation,
 291    );
 292    decl.add_method(
 293        sel!(draggingUpdated:),
 294        dragging_updated as extern "C" fn(&Object, Sel, id) -> NSDragOperation,
 295    );
 296    decl.add_method(
 297        sel!(draggingExited:),
 298        dragging_exited as extern "C" fn(&Object, Sel, id),
 299    );
 300    decl.add_method(
 301        sel!(performDragOperation:),
 302        perform_drag_operation as extern "C" fn(&Object, Sel, id) -> BOOL,
 303    );
 304    decl.add_method(
 305        sel!(concludeDragOperation:),
 306        conclude_drag_operation as extern "C" fn(&Object, Sel, id),
 307    );
 308
 309    decl.register()
 310}
 311
 312struct MacWindowState {
 313    handle: AnyWindowHandle,
 314    executor: ForegroundExecutor,
 315    native_window: id,
 316    native_view: NonNull<Object>,
 317    display_link: Option<DisplayLink>,
 318    renderer: renderer::Renderer,
 319    request_frame_callback: Option<Box<dyn FnMut(RequestFrameOptions)>>,
 320    event_callback: Option<Box<dyn FnMut(PlatformInput) -> crate::DispatchEventResult>>,
 321    activate_callback: Option<Box<dyn FnMut(bool)>>,
 322    resize_callback: Option<Box<dyn FnMut(Size<Pixels>, f32)>>,
 323    moved_callback: Option<Box<dyn FnMut()>>,
 324    should_close_callback: Option<Box<dyn FnMut() -> bool>>,
 325    close_callback: Option<Box<dyn FnOnce()>>,
 326    appearance_changed_callback: Option<Box<dyn FnMut()>>,
 327    input_handler: Option<PlatformInputHandler>,
 328    last_key_equivalent: Option<KeyDownEvent>,
 329    synthetic_drag_counter: usize,
 330    traffic_light_position: Option<Point<Pixels>>,
 331    previous_modifiers_changed_event: Option<PlatformInput>,
 332    keystroke_for_do_command: Option<Keystroke>,
 333    external_files_dragged: bool,
 334    // Whether the next left-mouse click is also the focusing click.
 335    first_mouse: bool,
 336    fullscreen_restore_bounds: Bounds<Pixels>,
 337}
 338
 339impl MacWindowState {
 340    fn move_traffic_light(&self) {
 341        if let Some(traffic_light_position) = self.traffic_light_position {
 342            if self.is_fullscreen() {
 343                // Moving traffic lights while fullscreen doesn't work,
 344                // see https://github.com/zed-industries/zed/issues/4712
 345                return;
 346            }
 347
 348            let titlebar_height = self.titlebar_height();
 349
 350            unsafe {
 351                let close_button: id = msg_send![
 352                    self.native_window,
 353                    standardWindowButton: NSWindowButton::NSWindowCloseButton
 354                ];
 355                let min_button: id = msg_send![
 356                    self.native_window,
 357                    standardWindowButton: NSWindowButton::NSWindowMiniaturizeButton
 358                ];
 359                let zoom_button: id = msg_send![
 360                    self.native_window,
 361                    standardWindowButton: NSWindowButton::NSWindowZoomButton
 362                ];
 363
 364                let mut close_button_frame: CGRect = msg_send![close_button, frame];
 365                let mut min_button_frame: CGRect = msg_send![min_button, frame];
 366                let mut zoom_button_frame: CGRect = msg_send![zoom_button, frame];
 367                let mut origin = point(
 368                    traffic_light_position.x,
 369                    titlebar_height
 370                        - traffic_light_position.y
 371                        - px(close_button_frame.size.height as f32),
 372                );
 373                let button_spacing =
 374                    px((min_button_frame.origin.x - close_button_frame.origin.x) as f32);
 375
 376                close_button_frame.origin = CGPoint::new(origin.x.into(), origin.y.into());
 377                let _: () = msg_send![close_button, setFrame: close_button_frame];
 378                origin.x += button_spacing;
 379
 380                min_button_frame.origin = CGPoint::new(origin.x.into(), origin.y.into());
 381                let _: () = msg_send![min_button, setFrame: min_button_frame];
 382                origin.x += button_spacing;
 383
 384                zoom_button_frame.origin = CGPoint::new(origin.x.into(), origin.y.into());
 385                let _: () = msg_send![zoom_button, setFrame: zoom_button_frame];
 386                origin.x += button_spacing;
 387            }
 388        }
 389    }
 390
 391    fn start_display_link(&mut self) {
 392        self.stop_display_link();
 393        unsafe {
 394            if !self
 395                .native_window
 396                .occlusionState()
 397                .contains(NSWindowOcclusionState::NSWindowOcclusionStateVisible)
 398            {
 399                return;
 400            }
 401        }
 402        let display_id = unsafe { display_id_for_screen(self.native_window.screen()) };
 403        if let Some(mut display_link) =
 404            DisplayLink::new(display_id, self.native_view.as_ptr() as *mut c_void, step).log_err()
 405        {
 406            display_link.start().log_err();
 407            self.display_link = Some(display_link);
 408        }
 409    }
 410
 411    fn stop_display_link(&mut self) {
 412        self.display_link = None;
 413    }
 414
 415    fn is_maximized(&self) -> bool {
 416        unsafe {
 417            let bounds = self.bounds();
 418            let screen_size = self.native_window.screen().visibleFrame().into();
 419            bounds.size == screen_size
 420        }
 421    }
 422
 423    fn is_fullscreen(&self) -> bool {
 424        unsafe {
 425            let style_mask = self.native_window.styleMask();
 426            style_mask.contains(NSWindowStyleMask::NSFullScreenWindowMask)
 427        }
 428    }
 429
 430    fn bounds(&self) -> Bounds<Pixels> {
 431        let mut window_frame = unsafe { NSWindow::frame(self.native_window) };
 432        let screen_frame = unsafe {
 433            let screen = NSWindow::screen(self.native_window);
 434            NSScreen::frame(screen)
 435        };
 436
 437        // Flip the y coordinate to be top-left origin
 438        window_frame.origin.y =
 439            screen_frame.size.height - window_frame.origin.y - window_frame.size.height;
 440
 441        Bounds::new(
 442            point(
 443                px((window_frame.origin.x - screen_frame.origin.x) as f32),
 444                px((window_frame.origin.y + screen_frame.origin.y) as f32),
 445            ),
 446            size(
 447                px(window_frame.size.width as f32),
 448                px(window_frame.size.height as f32),
 449            ),
 450        )
 451    }
 452
 453    fn content_size(&self) -> Size<Pixels> {
 454        let NSSize { width, height, .. } =
 455            unsafe { NSView::frame(self.native_window.contentView()) }.size;
 456        size(px(width as f32), px(height as f32))
 457    }
 458
 459    fn scale_factor(&self) -> f32 {
 460        get_scale_factor(self.native_window)
 461    }
 462
 463    fn titlebar_height(&self) -> Pixels {
 464        unsafe {
 465            let frame = NSWindow::frame(self.native_window);
 466            let content_layout_rect: CGRect = msg_send![self.native_window, contentLayoutRect];
 467            px((frame.size.height - content_layout_rect.size.height) as f32)
 468        }
 469    }
 470
 471    fn window_bounds(&self) -> WindowBounds {
 472        if self.is_fullscreen() {
 473            WindowBounds::Fullscreen(self.fullscreen_restore_bounds)
 474        } else {
 475            WindowBounds::Windowed(self.bounds())
 476        }
 477    }
 478}
 479
 480unsafe impl Send for MacWindowState {}
 481
 482pub(crate) struct MacWindow(Arc<Mutex<MacWindowState>>);
 483
 484impl MacWindow {
 485    pub fn open(
 486        handle: AnyWindowHandle,
 487        WindowParams {
 488            bounds,
 489            titlebar,
 490            kind,
 491            is_movable,
 492            focus,
 493            show,
 494            display_id,
 495            window_min_size,
 496        }: WindowParams,
 497        executor: ForegroundExecutor,
 498        renderer_context: renderer::Context,
 499    ) -> Self {
 500        unsafe {
 501            let pool = NSAutoreleasePool::new(nil);
 502
 503            let mut style_mask;
 504            if let Some(titlebar) = titlebar.as_ref() {
 505                style_mask = NSWindowStyleMask::NSClosableWindowMask
 506                    | NSWindowStyleMask::NSMiniaturizableWindowMask
 507                    | NSWindowStyleMask::NSResizableWindowMask
 508                    | NSWindowStyleMask::NSTitledWindowMask;
 509
 510                if titlebar.appears_transparent {
 511                    style_mask |= NSWindowStyleMask::NSFullSizeContentViewWindowMask;
 512                }
 513            } else {
 514                style_mask = NSWindowStyleMask::NSTitledWindowMask
 515                    | NSWindowStyleMask::NSFullSizeContentViewWindowMask;
 516            }
 517
 518            let native_window: id = match kind {
 519                WindowKind::Normal => msg_send![WINDOW_CLASS, alloc],
 520                WindowKind::PopUp => {
 521                    style_mask |= NSWindowStyleMaskNonactivatingPanel;
 522                    msg_send![PANEL_CLASS, alloc]
 523                }
 524            };
 525
 526            let display = display_id
 527                .and_then(MacDisplay::find_by_id)
 528                .unwrap_or_else(MacDisplay::primary);
 529
 530            let mut target_screen = nil;
 531            let mut screen_frame = None;
 532
 533            let screens = NSScreen::screens(nil);
 534            let count: u64 = cocoa::foundation::NSArray::count(screens);
 535            for i in 0..count {
 536                let screen = cocoa::foundation::NSArray::objectAtIndex(screens, i);
 537                let frame = NSScreen::frame(screen);
 538                let display_id = display_id_for_screen(screen);
 539                if display_id == display.0 {
 540                    screen_frame = Some(frame);
 541                    target_screen = screen;
 542                }
 543            }
 544
 545            let screen_frame = screen_frame.unwrap_or_else(|| {
 546                let screen = NSScreen::mainScreen(nil);
 547                target_screen = screen;
 548                NSScreen::frame(screen)
 549            });
 550
 551            let window_rect = NSRect::new(
 552                NSPoint::new(
 553                    screen_frame.origin.x + bounds.origin.x.0 as f64,
 554                    screen_frame.origin.y
 555                        + (display.bounds().size.height - bounds.origin.y).0 as f64,
 556                ),
 557                NSSize::new(bounds.size.width.0 as f64, bounds.size.height.0 as f64),
 558            );
 559
 560            let native_window = native_window.initWithContentRect_styleMask_backing_defer_screen_(
 561                window_rect,
 562                style_mask,
 563                NSBackingStoreBuffered,
 564                NO,
 565                target_screen,
 566            );
 567            assert!(!native_window.is_null());
 568            let () = msg_send![
 569                native_window,
 570                registerForDraggedTypes:
 571                    NSArray::arrayWithObject(nil, NSFilenamesPboardType)
 572            ];
 573            let () = msg_send![
 574                native_window,
 575                setReleasedWhenClosed: NO
 576            ];
 577
 578            let native_view: id = msg_send![VIEW_CLASS, alloc];
 579            let native_view = NSView::init(native_view);
 580            assert!(!native_view.is_null());
 581
 582            let mut window = Self(Arc::new(Mutex::new(MacWindowState {
 583                handle,
 584                executor,
 585                native_window,
 586                native_view: NonNull::new_unchecked(native_view),
 587                display_link: None,
 588                renderer: renderer::new_renderer(
 589                    renderer_context,
 590                    native_window as *mut _,
 591                    native_view as *mut _,
 592                    bounds.size.map(|pixels| pixels.0),
 593                    false,
 594                ),
 595                request_frame_callback: None,
 596                event_callback: None,
 597                activate_callback: None,
 598                resize_callback: None,
 599                moved_callback: None,
 600                should_close_callback: None,
 601                close_callback: None,
 602                appearance_changed_callback: None,
 603                input_handler: None,
 604                last_key_equivalent: None,
 605                synthetic_drag_counter: 0,
 606                traffic_light_position: titlebar
 607                    .as_ref()
 608                    .and_then(|titlebar| titlebar.traffic_light_position),
 609                previous_modifiers_changed_event: None,
 610                keystroke_for_do_command: None,
 611                external_files_dragged: false,
 612                first_mouse: false,
 613                fullscreen_restore_bounds: Bounds::default(),
 614            })));
 615
 616            (*native_window).set_ivar(
 617                WINDOW_STATE_IVAR,
 618                Arc::into_raw(window.0.clone()) as *const c_void,
 619            );
 620            native_window.setDelegate_(native_window);
 621            (*native_view).set_ivar(
 622                WINDOW_STATE_IVAR,
 623                Arc::into_raw(window.0.clone()) as *const c_void,
 624            );
 625
 626            if let Some(title) = titlebar
 627                .as_ref()
 628                .and_then(|t| t.title.as_ref().map(AsRef::as_ref))
 629            {
 630                window.set_title(title);
 631            }
 632
 633            native_window.setMovable_(is_movable as BOOL);
 634
 635            if let Some(window_min_size) = window_min_size {
 636                native_window.setContentMinSize_(NSSize {
 637                    width: window_min_size.width.to_f64(),
 638                    height: window_min_size.height.to_f64(),
 639                });
 640            }
 641
 642            if titlebar.map_or(true, |titlebar| titlebar.appears_transparent) {
 643                native_window.setTitlebarAppearsTransparent_(YES);
 644                native_window.setTitleVisibility_(NSWindowTitleVisibility::NSWindowTitleHidden);
 645            }
 646
 647            native_view.setAutoresizingMask_(NSViewWidthSizable | NSViewHeightSizable);
 648            native_view.setWantsBestResolutionOpenGLSurface_(YES);
 649
 650            // From winit crate: On Mojave, views automatically become layer-backed shortly after
 651            // being added to a native_window. Changing the layer-backedness of a view breaks the
 652            // association between the view and its associated OpenGL context. To work around this,
 653            // on we explicitly make the view layer-backed up front so that AppKit doesn't do it
 654            // itself and break the association with its context.
 655            native_view.setWantsLayer(YES);
 656            let _: () = msg_send![
 657                native_view,
 658                setLayerContentsRedrawPolicy: NSViewLayerContentsRedrawDuringViewResize
 659            ];
 660
 661            native_window.setContentView_(native_view.autorelease());
 662            native_window.makeFirstResponder_(native_view);
 663
 664            match kind {
 665                WindowKind::Normal => {
 666                    native_window.setLevel_(NSNormalWindowLevel);
 667                    native_window.setAcceptsMouseMovedEvents_(YES);
 668                }
 669                WindowKind::PopUp => {
 670                    // Use a tracking area to allow receiving MouseMoved events even when
 671                    // the window or application aren't active, which is often the case
 672                    // e.g. for notification windows.
 673                    let tracking_area: id = msg_send![class!(NSTrackingArea), alloc];
 674                    let _: () = msg_send![
 675                        tracking_area,
 676                        initWithRect: NSRect::new(NSPoint::new(0., 0.), NSSize::new(0., 0.))
 677                        options: NSTrackingMouseEnteredAndExited | NSTrackingMouseMoved | NSTrackingActiveAlways | NSTrackingInVisibleRect
 678                        owner: native_view
 679                        userInfo: nil
 680                    ];
 681                    let _: () =
 682                        msg_send![native_view, addTrackingArea: tracking_area.autorelease()];
 683
 684                    native_window.setLevel_(NSPopUpWindowLevel);
 685                    let _: () = msg_send![
 686                        native_window,
 687                        setAnimationBehavior: NSWindowAnimationBehaviorUtilityWindow
 688                    ];
 689                    native_window.setCollectionBehavior_(
 690                        NSWindowCollectionBehavior::NSWindowCollectionBehaviorCanJoinAllSpaces |
 691                        NSWindowCollectionBehavior::NSWindowCollectionBehaviorFullScreenAuxiliary
 692                    );
 693                }
 694            }
 695
 696            if focus && show {
 697                native_window.makeKeyAndOrderFront_(nil);
 698            } else if show {
 699                native_window.orderFront_(nil);
 700            }
 701
 702            // Set the initial position of the window to the specified origin.
 703            // Although we already specified the position using `initWithContentRect_styleMask_backing_defer_screen_`,
 704            // the window position might be incorrect if the main screen (the screen that contains the window that has focus)
 705            //  is different from the primary screen.
 706            NSWindow::setFrameTopLeftPoint_(native_window, window_rect.origin);
 707            window.0.lock().move_traffic_light();
 708
 709            pool.drain();
 710
 711            window
 712        }
 713    }
 714
 715    pub fn active_window() -> Option<AnyWindowHandle> {
 716        unsafe {
 717            let app = NSApplication::sharedApplication(nil);
 718            let main_window: id = msg_send![app, mainWindow];
 719            if msg_send![main_window, isKindOfClass: WINDOW_CLASS] {
 720                let handle = get_window_state(&*main_window).lock().handle;
 721                Some(handle)
 722            } else {
 723                None
 724            }
 725        }
 726    }
 727
 728    pub fn ordered_windows() -> Vec<AnyWindowHandle> {
 729        unsafe {
 730            let app = NSApplication::sharedApplication(nil);
 731            let windows: id = msg_send![app, orderedWindows];
 732            let count: NSUInteger = msg_send![windows, count];
 733
 734            let mut window_handles = Vec::new();
 735            for i in 0..count {
 736                let window: id = msg_send![windows, objectAtIndex:i];
 737                if msg_send![window, isKindOfClass: WINDOW_CLASS] {
 738                    let handle = get_window_state(&*window).lock().handle;
 739                    window_handles.push(handle);
 740                }
 741            }
 742
 743            window_handles
 744        }
 745    }
 746}
 747
 748impl Drop for MacWindow {
 749    fn drop(&mut self) {
 750        let mut this = self.0.lock();
 751        this.renderer.destroy();
 752        let window = this.native_window;
 753        this.display_link.take();
 754        unsafe {
 755            this.native_window.setDelegate_(nil);
 756        }
 757        this.input_handler.take();
 758        this.executor
 759            .spawn(async move {
 760                unsafe {
 761                    window.close();
 762                    window.autorelease();
 763                }
 764            })
 765            .detach();
 766    }
 767}
 768
 769impl PlatformWindow for MacWindow {
 770    fn bounds(&self) -> Bounds<Pixels> {
 771        self.0.as_ref().lock().bounds()
 772    }
 773
 774    fn window_bounds(&self) -> WindowBounds {
 775        self.0.as_ref().lock().window_bounds()
 776    }
 777
 778    fn is_maximized(&self) -> bool {
 779        self.0.as_ref().lock().is_maximized()
 780    }
 781
 782    fn content_size(&self) -> Size<Pixels> {
 783        self.0.as_ref().lock().content_size()
 784    }
 785
 786    fn scale_factor(&self) -> f32 {
 787        self.0.as_ref().lock().scale_factor()
 788    }
 789
 790    fn appearance(&self) -> WindowAppearance {
 791        unsafe {
 792            let appearance: id = msg_send![self.0.lock().native_window, effectiveAppearance];
 793            WindowAppearance::from_native(appearance)
 794        }
 795    }
 796
 797    fn display(&self) -> Option<Rc<dyn PlatformDisplay>> {
 798        unsafe {
 799            let screen = self.0.lock().native_window.screen();
 800            let device_description: id = msg_send![screen, deviceDescription];
 801            let screen_number: id = NSDictionary::valueForKey_(
 802                device_description,
 803                NSString::alloc(nil).init_str("NSScreenNumber"),
 804            );
 805
 806            let screen_number: u32 = msg_send![screen_number, unsignedIntValue];
 807
 808            Some(Rc::new(MacDisplay(screen_number)))
 809        }
 810    }
 811
 812    fn mouse_position(&self) -> Point<Pixels> {
 813        let position = unsafe {
 814            self.0
 815                .lock()
 816                .native_window
 817                .mouseLocationOutsideOfEventStream()
 818        };
 819        convert_mouse_position(position, self.content_size().height)
 820    }
 821
 822    fn modifiers(&self) -> Modifiers {
 823        unsafe {
 824            let modifiers: NSEventModifierFlags = msg_send![class!(NSEvent), modifierFlags];
 825
 826            let control = modifiers.contains(NSEventModifierFlags::NSControlKeyMask);
 827            let alt = modifiers.contains(NSEventModifierFlags::NSAlternateKeyMask);
 828            let shift = modifiers.contains(NSEventModifierFlags::NSShiftKeyMask);
 829            let command = modifiers.contains(NSEventModifierFlags::NSCommandKeyMask);
 830            let function = modifiers.contains(NSEventModifierFlags::NSFunctionKeyMask);
 831
 832            Modifiers {
 833                control,
 834                alt,
 835                shift,
 836                platform: command,
 837                function,
 838            }
 839        }
 840    }
 841
 842    fn set_input_handler(&mut self, input_handler: PlatformInputHandler) {
 843        self.0.as_ref().lock().input_handler = Some(input_handler);
 844    }
 845
 846    fn take_input_handler(&mut self) -> Option<PlatformInputHandler> {
 847        self.0.as_ref().lock().input_handler.take()
 848    }
 849
 850    fn prompt(
 851        &self,
 852        level: PromptLevel,
 853        msg: &str,
 854        detail: Option<&str>,
 855        answers: &[&str],
 856    ) -> Option<oneshot::Receiver<usize>> {
 857        // macOs applies overrides to modal window buttons after they are added.
 858        // Two most important for this logic are:
 859        // * Buttons with "Cancel" title will be displayed as the last buttons in the modal
 860        // * Last button added to the modal via `addButtonWithTitle` stays focused
 861        // * Focused buttons react on "space"/" " keypresses
 862        // * Usage of `keyEquivalent`, `makeFirstResponder` or `setInitialFirstResponder` does not change the focus
 863        //
 864        // See also https://developer.apple.com/documentation/appkit/nsalert/1524532-addbuttonwithtitle#discussion
 865        // ```
 866        // By default, the first button has a key equivalent of Return,
 867        // any button with a title of “Cancel” has a key equivalent of Escape,
 868        // 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).
 869        // ```
 870        //
 871        // To avoid situations when the last element added is "Cancel" and it gets the focus
 872        // (hence stealing both ESC and Space shortcuts), we find and add one non-Cancel button
 873        // last, so it gets focus and a Space shortcut.
 874        // This way, "Save this file? Yes/No/Cancel"-ish modals will get all three buttons mapped with a key.
 875        let latest_non_cancel_label = answers
 876            .iter()
 877            .enumerate()
 878            .rev()
 879            .find(|(_, &label)| label != "Cancel")
 880            .filter(|&(label_index, _)| label_index > 0);
 881
 882        unsafe {
 883            let alert: id = msg_send![class!(NSAlert), alloc];
 884            let alert: id = msg_send![alert, init];
 885            let alert_style = match level {
 886                PromptLevel::Info => 1,
 887                PromptLevel::Warning => 0,
 888                PromptLevel::Critical => 2,
 889            };
 890            let _: () = msg_send![alert, setAlertStyle: alert_style];
 891            let _: () = msg_send![alert, setMessageText: ns_string(msg)];
 892            if let Some(detail) = detail {
 893                let _: () = msg_send![alert, setInformativeText: ns_string(detail)];
 894            }
 895
 896            for (ix, answer) in answers
 897                .iter()
 898                .enumerate()
 899                .filter(|&(ix, _)| Some(ix) != latest_non_cancel_label.map(|(ix, _)| ix))
 900            {
 901                let button: id = msg_send![alert, addButtonWithTitle: ns_string(answer)];
 902                let _: () = msg_send![button, setTag: ix as NSInteger];
 903            }
 904            if let Some((ix, answer)) = latest_non_cancel_label {
 905                let button: id = msg_send![alert, addButtonWithTitle: ns_string(answer)];
 906                let _: () = msg_send![button, setTag: ix as NSInteger];
 907            }
 908
 909            let (done_tx, done_rx) = oneshot::channel();
 910            let done_tx = Cell::new(Some(done_tx));
 911            let block = ConcreteBlock::new(move |answer: NSInteger| {
 912                if let Some(done_tx) = done_tx.take() {
 913                    let _ = done_tx.send(answer.try_into().unwrap());
 914                }
 915            });
 916            let block = block.copy();
 917            let native_window = self.0.lock().native_window;
 918            let executor = self.0.lock().executor.clone();
 919            executor
 920                .spawn(async move {
 921                    let _: () = msg_send![
 922                        alert,
 923                        beginSheetModalForWindow: native_window
 924                        completionHandler: block
 925                    ];
 926                })
 927                .detach();
 928
 929            Some(done_rx)
 930        }
 931    }
 932
 933    fn activate(&self) {
 934        let window = self.0.lock().native_window;
 935        let executor = self.0.lock().executor.clone();
 936        executor
 937            .spawn(async move {
 938                unsafe {
 939                    let _: () = msg_send![window, makeKeyAndOrderFront: nil];
 940                }
 941            })
 942            .detach();
 943    }
 944
 945    fn is_active(&self) -> bool {
 946        unsafe { self.0.lock().native_window.isKeyWindow() == YES }
 947    }
 948
 949    // is_hovered is unused on macOS. See WindowContext::is_window_hovered.
 950    fn is_hovered(&self) -> bool {
 951        false
 952    }
 953
 954    fn set_title(&mut self, title: &str) {
 955        unsafe {
 956            let app = NSApplication::sharedApplication(nil);
 957            let window = self.0.lock().native_window;
 958            let title = ns_string(title);
 959            let _: () = msg_send![app, changeWindowsItem:window title:title filename:false];
 960            let _: () = msg_send![window, setTitle: title];
 961            self.0.lock().move_traffic_light();
 962        }
 963    }
 964
 965    fn set_app_id(&mut self, _app_id: &str) {}
 966
 967    fn set_background_appearance(&self, background_appearance: WindowBackgroundAppearance) {
 968        let mut this = self.0.as_ref().lock();
 969        this.renderer
 970            .update_transparency(background_appearance != WindowBackgroundAppearance::Opaque);
 971
 972        let blur_radius = if background_appearance == WindowBackgroundAppearance::Blurred {
 973            80
 974        } else {
 975            0
 976        };
 977        let opaque = if background_appearance == WindowBackgroundAppearance::Opaque {
 978            YES
 979        } else {
 980            NO
 981        };
 982        unsafe {
 983            this.native_window.setOpaque_(opaque);
 984            // Shadows for transparent windows cause artifacts and performance issues
 985            this.native_window.setHasShadow_(opaque);
 986            let clear_color = if opaque == YES {
 987                NSColor::colorWithSRGBRed_green_blue_alpha_(nil, 0f64, 0f64, 0f64, 1f64)
 988            } else {
 989                NSColor::clearColor(nil)
 990            };
 991            this.native_window.setBackgroundColor_(clear_color);
 992            let window_number = this.native_window.windowNumber();
 993            CGSSetWindowBackgroundBlurRadius(CGSMainConnectionID(), window_number, blur_radius);
 994        }
 995    }
 996
 997    fn set_edited(&mut self, edited: bool) {
 998        unsafe {
 999            let window = self.0.lock().native_window;
1000            msg_send![window, setDocumentEdited: edited as BOOL]
1001        }
1002
1003        // Changing the document edited state resets the traffic light position,
1004        // so we have to move it again.
1005        self.0.lock().move_traffic_light();
1006    }
1007
1008    fn show_character_palette(&self) {
1009        let this = self.0.lock();
1010        let window = this.native_window;
1011        this.executor
1012            .spawn(async move {
1013                unsafe {
1014                    let app = NSApplication::sharedApplication(nil);
1015                    let _: () = msg_send![app, orderFrontCharacterPalette: window];
1016                }
1017            })
1018            .detach();
1019    }
1020
1021    fn minimize(&self) {
1022        let window = self.0.lock().native_window;
1023        unsafe {
1024            window.miniaturize_(nil);
1025        }
1026    }
1027
1028    fn zoom(&self) {
1029        let this = self.0.lock();
1030        let window = this.native_window;
1031        this.executor
1032            .spawn(async move {
1033                unsafe {
1034                    window.zoom_(nil);
1035                }
1036            })
1037            .detach();
1038    }
1039
1040    fn toggle_fullscreen(&self) {
1041        let this = self.0.lock();
1042        let window = this.native_window;
1043        this.executor
1044            .spawn(async move {
1045                unsafe {
1046                    window.toggleFullScreen_(nil);
1047                }
1048            })
1049            .detach();
1050    }
1051
1052    fn is_fullscreen(&self) -> bool {
1053        let this = self.0.lock();
1054        let window = this.native_window;
1055
1056        unsafe {
1057            window
1058                .styleMask()
1059                .contains(NSWindowStyleMask::NSFullScreenWindowMask)
1060        }
1061    }
1062
1063    fn on_request_frame(&self, callback: Box<dyn FnMut(RequestFrameOptions)>) {
1064        self.0.as_ref().lock().request_frame_callback = Some(callback);
1065    }
1066
1067    fn on_input(&self, callback: Box<dyn FnMut(PlatformInput) -> crate::DispatchEventResult>) {
1068        self.0.as_ref().lock().event_callback = Some(callback);
1069    }
1070
1071    fn on_active_status_change(&self, callback: Box<dyn FnMut(bool)>) {
1072        self.0.as_ref().lock().activate_callback = Some(callback);
1073    }
1074
1075    fn on_hover_status_change(&self, _: Box<dyn FnMut(bool)>) {}
1076
1077    fn on_resize(&self, callback: Box<dyn FnMut(Size<Pixels>, f32)>) {
1078        self.0.as_ref().lock().resize_callback = Some(callback);
1079    }
1080
1081    fn on_moved(&self, callback: Box<dyn FnMut()>) {
1082        self.0.as_ref().lock().moved_callback = Some(callback);
1083    }
1084
1085    fn on_should_close(&self, callback: Box<dyn FnMut() -> bool>) {
1086        self.0.as_ref().lock().should_close_callback = Some(callback);
1087    }
1088
1089    fn on_close(&self, callback: Box<dyn FnOnce()>) {
1090        self.0.as_ref().lock().close_callback = Some(callback);
1091    }
1092
1093    fn on_appearance_changed(&self, callback: Box<dyn FnMut()>) {
1094        self.0.lock().appearance_changed_callback = Some(callback);
1095    }
1096
1097    fn draw(&self, scene: &crate::Scene) {
1098        let mut this = self.0.lock();
1099        this.renderer.draw(scene);
1100    }
1101
1102    fn sprite_atlas(&self) -> Arc<dyn PlatformAtlas> {
1103        self.0.lock().renderer.sprite_atlas().clone()
1104    }
1105
1106    fn gpu_specs(&self) -> Option<crate::GPUSpecs> {
1107        None
1108    }
1109
1110    fn update_ime_position(&self, _bounds: Bounds<ScaledPixels>) {
1111        unsafe {
1112            let input_context: id = msg_send![class!(NSTextInputContext), currentInputContext];
1113            let _: () = msg_send![input_context, invalidateCharacterCoordinates];
1114        }
1115    }
1116}
1117
1118impl rwh::HasWindowHandle for MacWindow {
1119    fn window_handle(&self) -> Result<rwh::WindowHandle<'_>, rwh::HandleError> {
1120        // SAFETY: The AppKitWindowHandle is a wrapper around a pointer to an NSView
1121        unsafe {
1122            Ok(rwh::WindowHandle::borrow_raw(rwh::RawWindowHandle::AppKit(
1123                rwh::AppKitWindowHandle::new(self.0.lock().native_view.cast()),
1124            )))
1125        }
1126    }
1127}
1128
1129impl rwh::HasDisplayHandle for MacWindow {
1130    fn display_handle(&self) -> Result<rwh::DisplayHandle<'_>, rwh::HandleError> {
1131        // SAFETY: This is a no-op on macOS
1132        unsafe {
1133            Ok(rwh::DisplayHandle::borrow_raw(
1134                rwh::AppKitDisplayHandle::new().into(),
1135            ))
1136        }
1137    }
1138}
1139
1140fn get_scale_factor(native_window: id) -> f32 {
1141    let factor = unsafe {
1142        let screen: id = msg_send![native_window, screen];
1143        NSScreen::backingScaleFactor(screen) as f32
1144    };
1145
1146    // We are not certain what triggers this, but it seems that sometimes
1147    // this method would return 0 (https://github.com/zed-industries/zed/issues/6412)
1148    // It seems most likely that this would happen if the window has no screen
1149    // (if it is off-screen), though we'd expect to see viewDidChangeBackingProperties before
1150    // it was rendered for real.
1151    // Regardless, attempt to avoid the issue here.
1152    if factor == 0.0 {
1153        2.
1154    } else {
1155        factor
1156    }
1157}
1158
1159unsafe fn get_window_state(object: &Object) -> Arc<Mutex<MacWindowState>> {
1160    let raw: *mut c_void = *object.get_ivar(WINDOW_STATE_IVAR);
1161    let rc1 = Arc::from_raw(raw as *mut Mutex<MacWindowState>);
1162    let rc2 = rc1.clone();
1163    mem::forget(rc1);
1164    rc2
1165}
1166
1167unsafe fn drop_window_state(object: &Object) {
1168    let raw: *mut c_void = *object.get_ivar(WINDOW_STATE_IVAR);
1169    Arc::from_raw(raw as *mut Mutex<MacWindowState>);
1170}
1171
1172extern "C" fn yes(_: &Object, _: Sel) -> BOOL {
1173    YES
1174}
1175
1176extern "C" fn dealloc_window(this: &Object, _: Sel) {
1177    unsafe {
1178        drop_window_state(this);
1179        let _: () = msg_send![super(this, class!(NSWindow)), dealloc];
1180    }
1181}
1182
1183extern "C" fn dealloc_view(this: &Object, _: Sel) {
1184    unsafe {
1185        drop_window_state(this);
1186        let _: () = msg_send![super(this, class!(NSView)), dealloc];
1187    }
1188}
1189
1190extern "C" fn handle_key_equivalent(this: &Object, _: Sel, native_event: id) -> BOOL {
1191    handle_key_event(this, native_event, true)
1192}
1193
1194extern "C" fn handle_key_down(this: &Object, _: Sel, native_event: id) {
1195    handle_key_event(this, native_event, false);
1196}
1197
1198// Things to test if you're modifying this method:
1199//  U.S. layout:
1200//   - The IME consumes characters like 'j' and 'k', which makes paging through `less` in
1201//     the terminal behave incorrectly by default. This behavior should be patched by our
1202//     IME integration
1203//   - `alt-t` should open the tasks menu
1204//   - In vim mode, this keybinding should work:
1205//     ```
1206//        {
1207//          "context": "Editor && vim_mode == insert",
1208//          "bindings": {"j j": "vim::NormalBefore"}
1209//        }
1210//     ```
1211//     and typing 'j k' in insert mode with this keybinding should insert the two characters
1212//  Brazilian layout:
1213//   - `" space` should create an unmarked quote
1214//   - `" backspace` should delete the marked quote
1215//   - `" "`should create an unmarked quote and a second marked quote
1216//   - `" up` should insert a quote, unmark it, and move up one line
1217//   - `" cmd-down` should insert a quote, unmark it, and move to the end of the file
1218//   - `cmd-ctrl-space` and clicking on an emoji should type it
1219//  Czech (QWERTY) layout:
1220//   - in vim mode `option-4`  should go to end of line (same as $)
1221//  Japanese (Romaji) layout:
1222//   - type `a i left down up enter enter` should create an unmarked text "愛"
1223extern "C" fn handle_key_event(this: &Object, native_event: id, key_equivalent: bool) -> BOOL {
1224    let window_state = unsafe { get_window_state(this) };
1225    let mut lock = window_state.as_ref().lock();
1226
1227    let window_height = lock.content_size().height;
1228    let event = unsafe { PlatformInput::from_native(native_event, Some(window_height)) };
1229
1230    let Some(PlatformInput::KeyDown(mut event)) = event else {
1231        return NO;
1232    };
1233    // For certain keystrokes, macOS will first dispatch a "key equivalent" event.
1234    // If that event isn't handled, it will then dispatch a "key down" event. GPUI
1235    // makes no distinction between these two types of events, so we need to ignore
1236    // the "key down" event if we've already just processed its "key equivalent" version.
1237    if key_equivalent {
1238        lock.last_key_equivalent = Some(event.clone());
1239    } else if lock.last_key_equivalent.take().as_ref() == Some(&event) {
1240        return NO;
1241    }
1242
1243    drop(lock);
1244
1245    let is_composing = with_input_handler(this, |input_handler| input_handler.marked_text_range())
1246        .flatten()
1247        .is_some();
1248
1249    // If we're composing, send the key to the input handler first;
1250    // otherwise we only send to the input handler if we don't have a matching binding.
1251    // The input handler may call `do_command_by_selector` if it doesn't know how to handle
1252    // a key. If it does so, it will return YES so we won't send the key twice.
1253    if is_composing || event.keystroke.key.is_empty() {
1254        window_state.as_ref().lock().keystroke_for_do_command = Some(event.keystroke.clone());
1255        let handled: BOOL = unsafe {
1256            let input_context: id = msg_send![this, inputContext];
1257            msg_send![input_context, handleEvent: native_event]
1258        };
1259        window_state.as_ref().lock().keystroke_for_do_command.take();
1260        if handled == YES {
1261            return YES;
1262        }
1263
1264        let mut callback = window_state.as_ref().lock().event_callback.take();
1265        let handled: BOOL = if let Some(callback) = callback.as_mut() {
1266            !callback(PlatformInput::KeyDown(event)).propagate as BOOL
1267        } else {
1268            NO
1269        };
1270        window_state.as_ref().lock().event_callback = callback;
1271        return handled as BOOL;
1272    }
1273
1274    let mut callback = window_state.as_ref().lock().event_callback.take();
1275    let handled = if let Some(callback) = callback.as_mut() {
1276        !callback(PlatformInput::KeyDown(event.clone())).propagate as BOOL
1277    } else {
1278        NO
1279    };
1280    window_state.as_ref().lock().event_callback = callback;
1281    if handled == YES {
1282        return YES;
1283    }
1284
1285    if event.is_held {
1286        let handled = with_input_handler(&this, |input_handler| {
1287            if !input_handler.apple_press_and_hold_enabled() {
1288                input_handler.replace_text_in_range(
1289                    None,
1290                    &event.keystroke.ime_key.unwrap_or(event.keystroke.key),
1291                );
1292                return YES;
1293            }
1294            NO
1295        });
1296        if handled == Some(YES) {
1297            return YES;
1298        }
1299    }
1300
1301    unsafe {
1302        let input_context: id = msg_send![this, inputContext];
1303        msg_send![input_context, handleEvent: native_event]
1304    }
1305}
1306
1307extern "C" fn handle_view_event(this: &Object, _: Sel, native_event: id) {
1308    let window_state = unsafe { get_window_state(this) };
1309    let weak_window_state = Arc::downgrade(&window_state);
1310    let mut lock = window_state.as_ref().lock();
1311    let window_height = lock.content_size().height;
1312    let event = unsafe { PlatformInput::from_native(native_event, Some(window_height)) };
1313
1314    if let Some(mut event) = event {
1315        match &mut event {
1316            PlatformInput::MouseDown(
1317                event @ MouseDownEvent {
1318                    button: MouseButton::Left,
1319                    modifiers: Modifiers { control: true, .. },
1320                    ..
1321                },
1322            ) => {
1323                // On mac, a ctrl-left click should be handled as a right click.
1324                *event = MouseDownEvent {
1325                    button: MouseButton::Right,
1326                    modifiers: Modifiers {
1327                        control: false,
1328                        ..event.modifiers
1329                    },
1330                    click_count: 1,
1331                    ..*event
1332                };
1333            }
1334
1335            // Handles focusing click.
1336            PlatformInput::MouseDown(
1337                event @ MouseDownEvent {
1338                    button: MouseButton::Left,
1339                    ..
1340                },
1341            ) if (lock.first_mouse) => {
1342                *event = MouseDownEvent {
1343                    first_mouse: true,
1344                    ..*event
1345                };
1346                lock.first_mouse = false;
1347            }
1348
1349            // Because we map a ctrl-left_down to a right_down -> right_up let's ignore
1350            // the ctrl-left_up to avoid having a mismatch in button down/up events if the
1351            // user is still holding ctrl when releasing the left mouse button
1352            PlatformInput::MouseUp(
1353                event @ MouseUpEvent {
1354                    button: MouseButton::Left,
1355                    modifiers: Modifiers { control: true, .. },
1356                    ..
1357                },
1358            ) => {
1359                *event = MouseUpEvent {
1360                    button: MouseButton::Right,
1361                    modifiers: Modifiers {
1362                        control: false,
1363                        ..event.modifiers
1364                    },
1365                    click_count: 1,
1366                    ..*event
1367                };
1368            }
1369
1370            _ => {}
1371        };
1372
1373        match &event {
1374            PlatformInput::MouseMove(
1375                event @ MouseMoveEvent {
1376                    pressed_button: Some(_),
1377                    ..
1378                },
1379            ) => {
1380                // Synthetic drag is used for selecting long buffer contents while buffer is being scrolled.
1381                // External file drag and drop is able to emit its own synthetic mouse events which will conflict
1382                // with these ones.
1383                if !lock.external_files_dragged {
1384                    lock.synthetic_drag_counter += 1;
1385                    let executor = lock.executor.clone();
1386                    executor
1387                        .spawn(synthetic_drag(
1388                            weak_window_state,
1389                            lock.synthetic_drag_counter,
1390                            event.clone(),
1391                        ))
1392                        .detach();
1393                }
1394            }
1395
1396            PlatformInput::MouseUp(MouseUpEvent { .. }) => {
1397                lock.synthetic_drag_counter += 1;
1398            }
1399
1400            PlatformInput::ModifiersChanged(ModifiersChangedEvent { modifiers }) => {
1401                // Only raise modifiers changed event when they have actually changed
1402                if let Some(PlatformInput::ModifiersChanged(ModifiersChangedEvent {
1403                    modifiers: prev_modifiers,
1404                })) = &lock.previous_modifiers_changed_event
1405                {
1406                    if prev_modifiers == modifiers {
1407                        return;
1408                    }
1409                }
1410
1411                lock.previous_modifiers_changed_event = Some(event.clone());
1412            }
1413
1414            _ => {}
1415        }
1416
1417        if let Some(mut callback) = lock.event_callback.take() {
1418            drop(lock);
1419            callback(event);
1420            window_state.lock().event_callback = Some(callback);
1421        }
1422    }
1423}
1424
1425// Allows us to receive `cmd-.` (the shortcut for closing a dialog)
1426// https://bugs.eclipse.org/bugs/show_bug.cgi?id=300620#c6
1427extern "C" fn cancel_operation(this: &Object, _sel: Sel, _sender: id) {
1428    let window_state = unsafe { get_window_state(this) };
1429    let mut lock = window_state.as_ref().lock();
1430
1431    let keystroke = Keystroke {
1432        modifiers: Default::default(),
1433        key: ".".into(),
1434        ime_key: None,
1435    };
1436    let event = PlatformInput::KeyDown(KeyDownEvent {
1437        keystroke: keystroke.clone(),
1438        is_held: false,
1439    });
1440
1441    if let Some(mut callback) = lock.event_callback.take() {
1442        drop(lock);
1443        callback(event);
1444        window_state.lock().event_callback = Some(callback);
1445    }
1446}
1447
1448extern "C" fn window_did_change_occlusion_state(this: &Object, _: Sel, _: id) {
1449    let window_state = unsafe { get_window_state(this) };
1450    let lock = &mut *window_state.lock();
1451    unsafe {
1452        if lock
1453            .native_window
1454            .occlusionState()
1455            .contains(NSWindowOcclusionState::NSWindowOcclusionStateVisible)
1456        {
1457            lock.start_display_link();
1458        } else {
1459            lock.stop_display_link();
1460        }
1461    }
1462}
1463
1464extern "C" fn window_did_resize(this: &Object, _: Sel, _: id) {
1465    let window_state = unsafe { get_window_state(this) };
1466    window_state.as_ref().lock().move_traffic_light();
1467}
1468
1469extern "C" fn window_will_enter_fullscreen(this: &Object, _: Sel, _: id) {
1470    let window_state = unsafe { get_window_state(this) };
1471    let mut lock = window_state.as_ref().lock();
1472    lock.fullscreen_restore_bounds = lock.bounds();
1473}
1474
1475extern "C" fn window_did_move(this: &Object, _: Sel, _: id) {
1476    let window_state = unsafe { get_window_state(this) };
1477    let mut lock = window_state.as_ref().lock();
1478    if let Some(mut callback) = lock.moved_callback.take() {
1479        drop(lock);
1480        callback();
1481        window_state.lock().moved_callback = Some(callback);
1482    }
1483}
1484
1485extern "C" fn window_did_change_screen(this: &Object, _: Sel, _: id) {
1486    let window_state = unsafe { get_window_state(this) };
1487    let mut lock = window_state.as_ref().lock();
1488    lock.start_display_link();
1489}
1490
1491extern "C" fn window_did_change_key_status(this: &Object, selector: Sel, _: id) {
1492    let window_state = unsafe { get_window_state(this) };
1493    let lock = window_state.lock();
1494    let is_active = unsafe { lock.native_window.isKeyWindow() == YES };
1495
1496    // When opening a pop-up while the application isn't active, Cocoa sends a spurious
1497    // `windowDidBecomeKey` message to the previous key window even though that window
1498    // isn't actually key. This causes a bug if the application is later activated while
1499    // the pop-up is still open, making it impossible to activate the previous key window
1500    // even if the pop-up gets closed. The only way to activate it again is to de-activate
1501    // the app and re-activate it, which is a pretty bad UX.
1502    // The following code detects the spurious event and invokes `resignKeyWindow`:
1503    // in theory, we're not supposed to invoke this method manually but it balances out
1504    // the spurious `becomeKeyWindow` event and helps us work around that bug.
1505    if selector == sel!(windowDidBecomeKey:) && !is_active {
1506        unsafe {
1507            let _: () = msg_send![lock.native_window, resignKeyWindow];
1508            return;
1509        }
1510    }
1511
1512    let executor = lock.executor.clone();
1513    drop(lock);
1514    executor
1515        .spawn(async move {
1516            let mut lock = window_state.as_ref().lock();
1517            if let Some(mut callback) = lock.activate_callback.take() {
1518                drop(lock);
1519                callback(is_active);
1520                window_state.lock().activate_callback = Some(callback);
1521            };
1522        })
1523        .detach();
1524}
1525
1526extern "C" fn window_should_close(this: &Object, _: Sel, _: id) -> BOOL {
1527    let window_state = unsafe { get_window_state(this) };
1528    let mut lock = window_state.as_ref().lock();
1529    if let Some(mut callback) = lock.should_close_callback.take() {
1530        drop(lock);
1531        let should_close = callback();
1532        window_state.lock().should_close_callback = Some(callback);
1533        should_close as BOOL
1534    } else {
1535        YES
1536    }
1537}
1538
1539extern "C" fn close_window(this: &Object, _: Sel) {
1540    unsafe {
1541        let close_callback = {
1542            let window_state = get_window_state(this);
1543            let mut lock = window_state.as_ref().lock();
1544            lock.close_callback.take()
1545        };
1546
1547        if let Some(callback) = close_callback {
1548            callback();
1549        }
1550
1551        let _: () = msg_send![super(this, class!(NSWindow)), close];
1552    }
1553}
1554
1555extern "C" fn make_backing_layer(this: &Object, _: Sel) -> id {
1556    let window_state = unsafe { get_window_state(this) };
1557    let window_state = window_state.as_ref().lock();
1558    window_state.renderer.layer_ptr() as id
1559}
1560
1561extern "C" fn view_did_change_backing_properties(this: &Object, _: Sel) {
1562    let window_state = unsafe { get_window_state(this) };
1563    let mut lock = window_state.as_ref().lock();
1564
1565    let scale_factor = lock.scale_factor();
1566    let size = lock.content_size();
1567    let drawable_size = size.to_device_pixels(scale_factor);
1568    unsafe {
1569        let _: () = msg_send![
1570            lock.renderer.layer(),
1571            setContentsScale: scale_factor as f64
1572        ];
1573    }
1574
1575    lock.renderer.update_drawable_size(drawable_size);
1576
1577    if let Some(mut callback) = lock.resize_callback.take() {
1578        let content_size = lock.content_size();
1579        let scale_factor = lock.scale_factor();
1580        drop(lock);
1581        callback(content_size, scale_factor);
1582        window_state.as_ref().lock().resize_callback = Some(callback);
1583    };
1584}
1585
1586extern "C" fn set_frame_size(this: &Object, _: Sel, size: NSSize) {
1587    let window_state = unsafe { get_window_state(this) };
1588    let mut lock = window_state.as_ref().lock();
1589
1590    let new_size = Size::<Pixels>::from(size);
1591    if lock.content_size() == new_size {
1592        return;
1593    }
1594
1595    unsafe {
1596        let _: () = msg_send![super(this, class!(NSView)), setFrameSize: size];
1597    }
1598
1599    let scale_factor = lock.scale_factor();
1600    let drawable_size = new_size.to_device_pixels(scale_factor);
1601    lock.renderer.update_drawable_size(drawable_size);
1602
1603    if let Some(mut callback) = lock.resize_callback.take() {
1604        let content_size = lock.content_size();
1605        let scale_factor = lock.scale_factor();
1606        drop(lock);
1607        callback(content_size, scale_factor);
1608        window_state.lock().resize_callback = Some(callback);
1609    };
1610}
1611
1612extern "C" fn display_layer(this: &Object, _: Sel, _: id) {
1613    let window_state = unsafe { get_window_state(this) };
1614    let mut lock = window_state.lock();
1615    if let Some(mut callback) = lock.request_frame_callback.take() {
1616        #[cfg(not(feature = "macos-blade"))]
1617        lock.renderer.set_presents_with_transaction(true);
1618        lock.stop_display_link();
1619        drop(lock);
1620        callback(Default::default());
1621
1622        let mut lock = window_state.lock();
1623        lock.request_frame_callback = Some(callback);
1624        #[cfg(not(feature = "macos-blade"))]
1625        lock.renderer.set_presents_with_transaction(false);
1626        lock.start_display_link();
1627    }
1628}
1629
1630unsafe extern "C" fn step(view: *mut c_void) {
1631    let view = view as id;
1632    let window_state = unsafe { get_window_state(&*view) };
1633    let mut lock = window_state.lock();
1634
1635    if let Some(mut callback) = lock.request_frame_callback.take() {
1636        drop(lock);
1637        callback(Default::default());
1638        window_state.lock().request_frame_callback = Some(callback);
1639    }
1640}
1641
1642extern "C" fn valid_attributes_for_marked_text(_: &Object, _: Sel) -> id {
1643    unsafe { msg_send![class!(NSArray), array] }
1644}
1645
1646extern "C" fn has_marked_text(this: &Object, _: Sel) -> BOOL {
1647    let has_marked_text_result =
1648        with_input_handler(this, |input_handler| input_handler.marked_text_range()).flatten();
1649
1650    has_marked_text_result.is_some() as BOOL
1651}
1652
1653extern "C" fn marked_range(this: &Object, _: Sel) -> NSRange {
1654    let marked_range_result =
1655        with_input_handler(this, |input_handler| input_handler.marked_text_range()).flatten();
1656
1657    marked_range_result.map_or(NSRange::invalid(), |range| range.into())
1658}
1659
1660extern "C" fn selected_range(this: &Object, _: Sel) -> NSRange {
1661    let selected_range_result = with_input_handler(this, |input_handler| {
1662        input_handler.selected_text_range(false)
1663    })
1664    .flatten();
1665
1666    selected_range_result.map_or(NSRange::invalid(), |selection| selection.range.into())
1667}
1668
1669extern "C" fn first_rect_for_character_range(
1670    this: &Object,
1671    _: Sel,
1672    range: NSRange,
1673    _: id,
1674) -> NSRect {
1675    let frame: NSRect = unsafe {
1676        let state = get_window_state(this);
1677        let lock = state.lock();
1678        let mut frame = NSWindow::frame(lock.native_window);
1679        let content_layout_rect: CGRect = msg_send![lock.native_window, contentLayoutRect];
1680        frame.origin.y -= frame.size.height - content_layout_rect.size.height;
1681        frame
1682    };
1683    with_input_handler(this, |input_handler| {
1684        input_handler.bounds_for_range(range.to_range()?)
1685    })
1686    .flatten()
1687    .map_or(
1688        NSRect::new(NSPoint::new(0., 0.), NSSize::new(0., 0.)),
1689        |bounds| {
1690            NSRect::new(
1691                NSPoint::new(
1692                    frame.origin.x + bounds.origin.x.0 as f64,
1693                    frame.origin.y + frame.size.height
1694                        - bounds.origin.y.0 as f64
1695                        - bounds.size.height.0 as f64,
1696                ),
1697                NSSize::new(bounds.size.width.0 as f64, bounds.size.height.0 as f64),
1698            )
1699        },
1700    )
1701}
1702
1703extern "C" fn insert_text(this: &Object, _: Sel, text: id, replacement_range: NSRange) {
1704    unsafe {
1705        let is_attributed_string: BOOL =
1706            msg_send![text, isKindOfClass: [class!(NSAttributedString)]];
1707        let text: id = if is_attributed_string == YES {
1708            msg_send![text, string]
1709        } else {
1710            text
1711        };
1712
1713        let text = text.to_str();
1714        let replacement_range = replacement_range.to_range();
1715        with_input_handler(this, |input_handler| {
1716            input_handler.replace_text_in_range(replacement_range, &text)
1717        });
1718    }
1719}
1720
1721extern "C" fn set_marked_text(
1722    this: &Object,
1723    _: Sel,
1724    text: id,
1725    selected_range: NSRange,
1726    replacement_range: NSRange,
1727) {
1728    unsafe {
1729        let is_attributed_string: BOOL =
1730            msg_send![text, isKindOfClass: [class!(NSAttributedString)]];
1731        let text: id = if is_attributed_string == YES {
1732            msg_send![text, string]
1733        } else {
1734            text
1735        };
1736        let selected_range = selected_range.to_range();
1737        let replacement_range = replacement_range.to_range();
1738        let text = text.to_str();
1739        with_input_handler(this, |input_handler| {
1740            input_handler.replace_and_mark_text_in_range(replacement_range, &text, selected_range)
1741        });
1742    }
1743}
1744extern "C" fn unmark_text(this: &Object, _: Sel) {
1745    with_input_handler(this, |input_handler| input_handler.unmark_text());
1746}
1747
1748extern "C" fn attributed_substring_for_proposed_range(
1749    this: &Object,
1750    _: Sel,
1751    range: NSRange,
1752    _actual_range: *mut c_void,
1753) -> id {
1754    with_input_handler(this, |input_handler| {
1755        let range = range.to_range()?;
1756        if range.is_empty() {
1757            return None;
1758        }
1759
1760        let selected_text = input_handler.text_for_range(range.clone())?;
1761        unsafe {
1762            let string: id = msg_send![class!(NSAttributedString), alloc];
1763            let string: id = msg_send![string, initWithString: ns_string(&selected_text)];
1764            Some(string)
1765        }
1766    })
1767    .flatten()
1768    .unwrap_or(nil)
1769}
1770
1771// We ignore which selector it asks us to do because the user may have
1772// bound the shortcut to something else.
1773extern "C" fn do_command_by_selector(this: &Object, _: Sel, _: Sel) {
1774    let state = unsafe { get_window_state(this) };
1775    let mut lock = state.as_ref().lock();
1776    let keystroke = lock.keystroke_for_do_command.take();
1777    let mut event_callback = lock.event_callback.take();
1778    drop(lock);
1779
1780    if let Some((keystroke, mut callback)) = keystroke.zip(event_callback.as_mut()) {
1781        (callback)(PlatformInput::KeyDown(KeyDownEvent {
1782            keystroke,
1783            is_held: false,
1784        }));
1785    }
1786
1787    state.as_ref().lock().event_callback = event_callback;
1788}
1789
1790extern "C" fn view_did_change_effective_appearance(this: &Object, _: Sel) {
1791    unsafe {
1792        let state = get_window_state(this);
1793        let mut lock = state.as_ref().lock();
1794        if let Some(mut callback) = lock.appearance_changed_callback.take() {
1795            drop(lock);
1796            callback();
1797            state.lock().appearance_changed_callback = Some(callback);
1798        }
1799    }
1800}
1801
1802extern "C" fn accepts_first_mouse(this: &Object, _: Sel, _: id) -> BOOL {
1803    let window_state = unsafe { get_window_state(this) };
1804    let mut lock = window_state.as_ref().lock();
1805    lock.first_mouse = true;
1806    YES
1807}
1808
1809extern "C" fn dragging_entered(this: &Object, _: Sel, dragging_info: id) -> NSDragOperation {
1810    let window_state = unsafe { get_window_state(this) };
1811    let position = drag_event_position(&window_state, dragging_info);
1812    let paths = external_paths_from_event(dragging_info);
1813    if let Some(event) =
1814        paths.map(|paths| PlatformInput::FileDrop(FileDropEvent::Entered { position, paths }))
1815    {
1816        if send_new_event(&window_state, event) {
1817            window_state.lock().external_files_dragged = true;
1818            return NSDragOperationCopy;
1819        }
1820    }
1821    NSDragOperationNone
1822}
1823
1824extern "C" fn dragging_updated(this: &Object, _: Sel, dragging_info: id) -> NSDragOperation {
1825    let window_state = unsafe { get_window_state(this) };
1826    let position = drag_event_position(&window_state, dragging_info);
1827    if send_new_event(
1828        &window_state,
1829        PlatformInput::FileDrop(FileDropEvent::Pending { position }),
1830    ) {
1831        NSDragOperationCopy
1832    } else {
1833        NSDragOperationNone
1834    }
1835}
1836
1837extern "C" fn dragging_exited(this: &Object, _: Sel, _: id) {
1838    let window_state = unsafe { get_window_state(this) };
1839    send_new_event(
1840        &window_state,
1841        PlatformInput::FileDrop(FileDropEvent::Exited),
1842    );
1843    window_state.lock().external_files_dragged = false;
1844}
1845
1846extern "C" fn perform_drag_operation(this: &Object, _: Sel, dragging_info: id) -> BOOL {
1847    let window_state = unsafe { get_window_state(this) };
1848    let position = drag_event_position(&window_state, dragging_info);
1849    if send_new_event(
1850        &window_state,
1851        PlatformInput::FileDrop(FileDropEvent::Submit { position }),
1852    ) {
1853        YES
1854    } else {
1855        NO
1856    }
1857}
1858
1859fn external_paths_from_event(dragging_info: *mut Object) -> Option<ExternalPaths> {
1860    let mut paths = SmallVec::new();
1861    let pasteboard: id = unsafe { msg_send![dragging_info, draggingPasteboard] };
1862    let filenames = unsafe { NSPasteboard::propertyListForType(pasteboard, NSFilenamesPboardType) };
1863    if filenames == nil {
1864        return None;
1865    }
1866    for file in unsafe { filenames.iter() } {
1867        let path = unsafe {
1868            let f = NSString::UTF8String(file);
1869            CStr::from_ptr(f).to_string_lossy().into_owned()
1870        };
1871        paths.push(PathBuf::from(path))
1872    }
1873    Some(ExternalPaths(paths))
1874}
1875
1876extern "C" fn conclude_drag_operation(this: &Object, _: Sel, _: id) {
1877    let window_state = unsafe { get_window_state(this) };
1878    send_new_event(
1879        &window_state,
1880        PlatformInput::FileDrop(FileDropEvent::Exited),
1881    );
1882}
1883
1884async fn synthetic_drag(
1885    window_state: Weak<Mutex<MacWindowState>>,
1886    drag_id: usize,
1887    event: MouseMoveEvent,
1888) {
1889    loop {
1890        Timer::after(Duration::from_millis(16)).await;
1891        if let Some(window_state) = window_state.upgrade() {
1892            let mut lock = window_state.lock();
1893            if lock.synthetic_drag_counter == drag_id {
1894                if let Some(mut callback) = lock.event_callback.take() {
1895                    drop(lock);
1896                    callback(PlatformInput::MouseMove(event.clone()));
1897                    window_state.lock().event_callback = Some(callback);
1898                }
1899            } else {
1900                break;
1901            }
1902        }
1903    }
1904}
1905
1906fn send_new_event(window_state_lock: &Mutex<MacWindowState>, e: PlatformInput) -> bool {
1907    let window_state = window_state_lock.lock().event_callback.take();
1908    if let Some(mut callback) = window_state {
1909        callback(e);
1910        window_state_lock.lock().event_callback = Some(callback);
1911        true
1912    } else {
1913        false
1914    }
1915}
1916
1917fn drag_event_position(window_state: &Mutex<MacWindowState>, dragging_info: id) -> Point<Pixels> {
1918    let drag_location: NSPoint = unsafe { msg_send![dragging_info, draggingLocation] };
1919    convert_mouse_position(drag_location, window_state.lock().content_size().height)
1920}
1921
1922fn with_input_handler<F, R>(window: &Object, f: F) -> Option<R>
1923where
1924    F: FnOnce(&mut PlatformInputHandler) -> R,
1925{
1926    let window_state = unsafe { get_window_state(window) };
1927    let mut lock = window_state.as_ref().lock();
1928    if let Some(mut input_handler) = lock.input_handler.take() {
1929        drop(lock);
1930        let result = f(&mut input_handler);
1931        window_state.lock().input_handler = Some(input_handler);
1932        Some(result)
1933    } else {
1934        None
1935    }
1936}
1937
1938unsafe fn display_id_for_screen(screen: id) -> CGDirectDisplayID {
1939    let device_description = NSScreen::deviceDescription(screen);
1940    let screen_number_key: id = NSString::alloc(nil).init_str("NSScreenNumber");
1941    let screen_number = device_description.objectForKey_(screen_number_key);
1942    let screen_number: NSUInteger = msg_send![screen_number, unsignedIntegerValue];
1943    screen_number as CGDirectDisplayID
1944}