window.rs

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