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