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    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    last_ime_inputs: Option<SmallVec<[(String, Option<Range<usize>>); 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<Pixels>,
 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<Pixels> {
 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                px((window_frame.origin.x - screen_frame.origin.x) as f32),
 455                px((window_frame.origin.y - screen_frame.origin.y) as f32),
 456            ),
 457            size(
 458                px(window_frame.size.width as f32),
 459                px(window_frame.size.height as f32),
 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 titlebar_height(&self) -> Pixels {
 476        unsafe {
 477            let frame = NSWindow::frame(self.native_window);
 478            let content_layout_rect: CGRect = msg_send![self.native_window, contentLayoutRect];
 479            px((frame.size.height - content_layout_rect.size.height) as f32)
 480        }
 481    }
 482
 483    fn window_bounds(&self) -> WindowBounds {
 484        if self.is_fullscreen() {
 485            WindowBounds::Fullscreen(self.fullscreen_restore_bounds)
 486        } else {
 487            WindowBounds::Windowed(self.bounds())
 488        }
 489    }
 490}
 491
 492unsafe impl Send for MacWindowState {}
 493
 494pub(crate) struct MacWindow(Arc<Mutex<MacWindowState>>);
 495
 496impl MacWindow {
 497    pub fn open(
 498        handle: AnyWindowHandle,
 499        WindowParams {
 500            window_background,
 501            bounds,
 502            titlebar,
 503            kind,
 504            is_movable,
 505            focus,
 506            show,
 507            display_id,
 508        }: WindowParams,
 509        executor: ForegroundExecutor,
 510        renderer_context: renderer::Context,
 511    ) -> Self {
 512        unsafe {
 513            let pool = NSAutoreleasePool::new(nil);
 514
 515            let mut style_mask;
 516            if let Some(titlebar) = titlebar.as_ref() {
 517                style_mask = NSWindowStyleMask::NSClosableWindowMask
 518                    | NSWindowStyleMask::NSMiniaturizableWindowMask
 519                    | NSWindowStyleMask::NSResizableWindowMask
 520                    | NSWindowStyleMask::NSTitledWindowMask;
 521
 522                if titlebar.appears_transparent {
 523                    style_mask |= NSWindowStyleMask::NSFullSizeContentViewWindowMask;
 524                }
 525            } else {
 526                style_mask = NSWindowStyleMask::NSTitledWindowMask
 527                    | NSWindowStyleMask::NSFullSizeContentViewWindowMask;
 528            }
 529
 530            let native_window: id = match kind {
 531                WindowKind::Normal => msg_send![WINDOW_CLASS, alloc],
 532                WindowKind::PopUp => {
 533                    style_mask |= NSWindowStyleMaskNonactivatingPanel;
 534                    msg_send![PANEL_CLASS, alloc]
 535                }
 536            };
 537
 538            let display = display_id
 539                .and_then(MacDisplay::find_by_id)
 540                .unwrap_or_else(|| MacDisplay::primary());
 541
 542            let mut target_screen = nil;
 543            let mut screen_frame = None;
 544
 545            let screens = NSScreen::screens(nil);
 546            let count: u64 = cocoa::foundation::NSArray::count(screens);
 547            for i in 0..count {
 548                let screen = cocoa::foundation::NSArray::objectAtIndex(screens, i);
 549                let frame = NSScreen::visibleFrame(screen);
 550                let display_id = display_id_for_screen(screen);
 551                if display_id == display.0 {
 552                    screen_frame = Some(frame);
 553                    target_screen = screen;
 554                }
 555            }
 556
 557            let screen_frame = screen_frame.unwrap_or_else(|| {
 558                let screen = NSScreen::mainScreen(nil);
 559                target_screen = screen;
 560                NSScreen::visibleFrame(screen)
 561            });
 562
 563            let window_rect = NSRect::new(
 564                NSPoint::new(
 565                    screen_frame.origin.x + bounds.origin.x.0 as f64,
 566                    screen_frame.origin.y
 567                        + (display.bounds().size.height - bounds.origin.y).0 as f64,
 568                ),
 569                NSSize::new(bounds.size.width.0 as f64, bounds.size.height.0 as f64),
 570            );
 571
 572            let native_window = native_window.initWithContentRect_styleMask_backing_defer_screen_(
 573                window_rect,
 574                style_mask,
 575                NSBackingStoreBuffered,
 576                NO,
 577                target_screen,
 578            );
 579            assert!(!native_window.is_null());
 580            let () = msg_send![
 581                native_window,
 582                registerForDraggedTypes:
 583                    NSArray::arrayWithObject(nil, NSFilenamesPboardType)
 584            ];
 585            let () = msg_send![
 586                native_window,
 587                setReleasedWhenClosed: NO
 588            ];
 589
 590            let native_view: id = msg_send![VIEW_CLASS, alloc];
 591            let native_view = NSView::init(native_view);
 592            assert!(!native_view.is_null());
 593
 594            let mut window = Self(Arc::new(Mutex::new(MacWindowState {
 595                handle,
 596                executor,
 597                native_window,
 598                native_view: NonNull::new_unchecked(native_view),
 599                display_link: None,
 600                renderer: renderer::new_renderer(
 601                    renderer_context,
 602                    native_window as *mut _,
 603                    native_view as *mut _,
 604                    bounds.size.map(|pixels| pixels.0),
 605                    window_background != WindowBackgroundAppearance::Opaque,
 606                ),
 607                request_frame_callback: None,
 608                event_callback: None,
 609                activate_callback: None,
 610                resize_callback: None,
 611                moved_callback: None,
 612                should_close_callback: None,
 613                close_callback: None,
 614                appearance_changed_callback: None,
 615                input_handler: None,
 616                last_key_equivalent: None,
 617                synthetic_drag_counter: 0,
 618                last_fresh_keydown: None,
 619                traffic_light_position: titlebar
 620                    .as_ref()
 621                    .and_then(|titlebar| titlebar.traffic_light_position),
 622                previous_modifiers_changed_event: None,
 623                last_ime_inputs: None,
 624                previous_keydown_inserted_text: None,
 625                external_files_dragged: false,
 626                first_mouse: false,
 627                fullscreen_restore_bounds: Bounds::default(),
 628            })));
 629
 630            (*native_window).set_ivar(
 631                WINDOW_STATE_IVAR,
 632                Arc::into_raw(window.0.clone()) as *const c_void,
 633            );
 634            native_window.setDelegate_(native_window);
 635            (*native_view).set_ivar(
 636                WINDOW_STATE_IVAR,
 637                Arc::into_raw(window.0.clone()) as *const c_void,
 638            );
 639
 640            if let Some(title) = titlebar
 641                .as_ref()
 642                .and_then(|t| t.title.as_ref().map(AsRef::as_ref))
 643            {
 644                window.set_title(title);
 645            }
 646
 647            native_window.setMovable_(is_movable as BOOL);
 648
 649            if titlebar.map_or(true, |titlebar| titlebar.appears_transparent) {
 650                native_window.setTitlebarAppearsTransparent_(YES);
 651                native_window.setTitleVisibility_(NSWindowTitleVisibility::NSWindowTitleHidden);
 652            }
 653
 654            native_view.setAutoresizingMask_(NSViewWidthSizable | NSViewHeightSizable);
 655            native_view.setWantsBestResolutionOpenGLSurface_(YES);
 656
 657            // From winit crate: On Mojave, views automatically become layer-backed shortly after
 658            // being added to a native_window. Changing the layer-backedness of a view breaks the
 659            // association between the view and its associated OpenGL context. To work around this,
 660            // on we explicitly make the view layer-backed up front so that AppKit doesn't do it
 661            // itself and break the association with its context.
 662            native_view.setWantsLayer(YES);
 663            let _: () = msg_send![
 664                native_view,
 665                setLayerContentsRedrawPolicy: NSViewLayerContentsRedrawDuringViewResize
 666            ];
 667
 668            native_window.setContentView_(native_view.autorelease());
 669            native_window.makeFirstResponder_(native_view);
 670
 671            window.set_background_appearance(window_background);
 672
 673            match kind {
 674                WindowKind::Normal => {
 675                    native_window.setLevel_(NSNormalWindowLevel);
 676                    native_window.setAcceptsMouseMovedEvents_(YES);
 677                }
 678                WindowKind::PopUp => {
 679                    // Use a tracking area to allow receiving MouseMoved events even when
 680                    // the window or application aren't active, which is often the case
 681                    // e.g. for notification windows.
 682                    let tracking_area: id = msg_send![class!(NSTrackingArea), alloc];
 683                    let _: () = msg_send![
 684                        tracking_area,
 685                        initWithRect: NSRect::new(NSPoint::new(0., 0.), NSSize::new(0., 0.))
 686                        options: NSTrackingMouseEnteredAndExited | NSTrackingMouseMoved | NSTrackingActiveAlways | NSTrackingInVisibleRect
 687                        owner: native_view
 688                        userInfo: nil
 689                    ];
 690                    let _: () =
 691                        msg_send![native_view, addTrackingArea: tracking_area.autorelease()];
 692
 693                    native_window.setLevel_(NSPopUpWindowLevel);
 694                    let _: () = msg_send![
 695                        native_window,
 696                        setAnimationBehavior: NSWindowAnimationBehaviorUtilityWindow
 697                    ];
 698                    native_window.setCollectionBehavior_(
 699                        NSWindowCollectionBehavior::NSWindowCollectionBehaviorCanJoinAllSpaces |
 700                        NSWindowCollectionBehavior::NSWindowCollectionBehaviorFullScreenAuxiliary
 701                    );
 702                }
 703            }
 704
 705            if focus {
 706                native_window.makeKeyAndOrderFront_(nil);
 707            } else if show {
 708                native_window.orderFront_(nil);
 709            }
 710
 711            // Set the initial position of the window to the specified origin.
 712            // Although we already specified the position using `initWithContentRect_styleMask_backing_defer_screen_`,
 713            // the window position might be incorrect if the main screen (the screen that contains the window that has focus)
 714            //  is different from the primary screen.
 715            NSWindow::setFrameTopLeftPoint_(native_window, window_rect.origin);
 716            window.0.lock().move_traffic_light();
 717
 718            pool.drain();
 719
 720            window
 721        }
 722    }
 723
 724    pub fn active_window() -> Option<AnyWindowHandle> {
 725        unsafe {
 726            let app = NSApplication::sharedApplication(nil);
 727            let main_window: id = msg_send![app, mainWindow];
 728            if msg_send![main_window, isKindOfClass: WINDOW_CLASS] {
 729                let handle = get_window_state(&*main_window).lock().handle;
 730                Some(handle)
 731            } else {
 732                None
 733            }
 734        }
 735    }
 736}
 737
 738impl Drop for MacWindow {
 739    fn drop(&mut self) {
 740        let mut this = self.0.lock();
 741        this.renderer.destroy();
 742        let window = this.native_window;
 743        this.display_link.take();
 744        unsafe {
 745            this.native_window.setDelegate_(nil);
 746        }
 747        this.executor
 748            .spawn(async move {
 749                unsafe {
 750                    window.close();
 751                    window.autorelease();
 752                }
 753            })
 754            .detach();
 755    }
 756}
 757
 758impl PlatformWindow for MacWindow {
 759    fn bounds(&self) -> Bounds<Pixels> {
 760        self.0.as_ref().lock().bounds()
 761    }
 762
 763    fn window_bounds(&self) -> WindowBounds {
 764        self.0.as_ref().lock().window_bounds()
 765    }
 766
 767    fn is_maximized(&self) -> bool {
 768        self.0.as_ref().lock().is_maximized()
 769    }
 770
 771    fn content_size(&self) -> Size<Pixels> {
 772        self.0.as_ref().lock().content_size()
 773    }
 774
 775    fn scale_factor(&self) -> f32 {
 776        self.0.as_ref().lock().scale_factor()
 777    }
 778
 779    fn appearance(&self) -> WindowAppearance {
 780        unsafe {
 781            let appearance: id = msg_send![self.0.lock().native_window, effectiveAppearance];
 782            WindowAppearance::from_native(appearance)
 783        }
 784    }
 785
 786    fn display(&self) -> Option<Rc<dyn PlatformDisplay>> {
 787        unsafe {
 788            let screen = self.0.lock().native_window.screen();
 789            let device_description: id = msg_send![screen, deviceDescription];
 790            let screen_number: id = NSDictionary::valueForKey_(
 791                device_description,
 792                NSString::alloc(nil).init_str("NSScreenNumber"),
 793            );
 794
 795            let screen_number: u32 = msg_send![screen_number, unsignedIntValue];
 796
 797            Some(Rc::new(MacDisplay(screen_number)))
 798        }
 799    }
 800
 801    fn mouse_position(&self) -> Point<Pixels> {
 802        let position = unsafe {
 803            self.0
 804                .lock()
 805                .native_window
 806                .mouseLocationOutsideOfEventStream()
 807        };
 808        convert_mouse_position(position, self.content_size().height)
 809    }
 810
 811    fn modifiers(&self) -> Modifiers {
 812        unsafe {
 813            let modifiers: NSEventModifierFlags = msg_send![class!(NSEvent), modifierFlags];
 814
 815            let control = modifiers.contains(NSEventModifierFlags::NSControlKeyMask);
 816            let alt = modifiers.contains(NSEventModifierFlags::NSAlternateKeyMask);
 817            let shift = modifiers.contains(NSEventModifierFlags::NSShiftKeyMask);
 818            let command = modifiers.contains(NSEventModifierFlags::NSCommandKeyMask);
 819            let function = modifiers.contains(NSEventModifierFlags::NSFunctionKeyMask);
 820
 821            Modifiers {
 822                control,
 823                alt,
 824                shift,
 825                platform: command,
 826                function,
 827            }
 828        }
 829    }
 830
 831    fn set_input_handler(&mut self, input_handler: PlatformInputHandler) {
 832        self.0.as_ref().lock().input_handler = Some(input_handler);
 833    }
 834
 835    fn take_input_handler(&mut self) -> Option<PlatformInputHandler> {
 836        self.0.as_ref().lock().input_handler.take()
 837    }
 838
 839    fn prompt(
 840        &self,
 841        level: PromptLevel,
 842        msg: &str,
 843        detail: Option<&str>,
 844        answers: &[&str],
 845    ) -> Option<oneshot::Receiver<usize>> {
 846        // macOs applies overrides to modal window buttons after they are added.
 847        // Two most important for this logic are:
 848        // * Buttons with "Cancel" title will be displayed as the last buttons in the modal
 849        // * Last button added to the modal via `addButtonWithTitle` stays focused
 850        // * Focused buttons react on "space"/" " keypresses
 851        // * Usage of `keyEquivalent`, `makeFirstResponder` or `setInitialFirstResponder` does not change the focus
 852        //
 853        // See also https://developer.apple.com/documentation/appkit/nsalert/1524532-addbuttonwithtitle#discussion
 854        // ```
 855        // By default, the first button has a key equivalent of Return,
 856        // any button with a title of “Cancel” has a key equivalent of Escape,
 857        // 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).
 858        // ```
 859        //
 860        // To avoid situations when the last element added is "Cancel" and it gets the focus
 861        // (hence stealing both ESC and Space shortcuts), we find and add one non-Cancel button
 862        // last, so it gets focus and a Space shortcut.
 863        // This way, "Save this file? Yes/No/Cancel"-ish modals will get all three buttons mapped with a key.
 864        let latest_non_cancel_label = answers
 865            .iter()
 866            .enumerate()
 867            .rev()
 868            .find(|(_, &label)| label != "Cancel")
 869            .filter(|&(label_index, _)| label_index > 0);
 870
 871        unsafe {
 872            let alert: id = msg_send![class!(NSAlert), alloc];
 873            let alert: id = msg_send![alert, init];
 874            let alert_style = match level {
 875                PromptLevel::Info => 1,
 876                PromptLevel::Warning => 0,
 877                PromptLevel::Critical => 2,
 878            };
 879            let _: () = msg_send![alert, setAlertStyle: alert_style];
 880            let _: () = msg_send![alert, setMessageText: ns_string(msg)];
 881            if let Some(detail) = detail {
 882                let _: () = msg_send![alert, setInformativeText: ns_string(detail)];
 883            }
 884
 885            for (ix, answer) in answers
 886                .iter()
 887                .enumerate()
 888                .filter(|&(ix, _)| Some(ix) != latest_non_cancel_label.map(|(ix, _)| ix))
 889            {
 890                let button: id = msg_send![alert, addButtonWithTitle: ns_string(answer)];
 891                let _: () = msg_send![button, setTag: ix as NSInteger];
 892            }
 893            if let Some((ix, answer)) = latest_non_cancel_label {
 894                let button: id = msg_send![alert, addButtonWithTitle: ns_string(answer)];
 895                let _: () = msg_send![button, setTag: ix as NSInteger];
 896            }
 897
 898            let (done_tx, done_rx) = oneshot::channel();
 899            let done_tx = Cell::new(Some(done_tx));
 900            let block = ConcreteBlock::new(move |answer: NSInteger| {
 901                if let Some(done_tx) = done_tx.take() {
 902                    let _ = done_tx.send(answer.try_into().unwrap());
 903                }
 904            });
 905            let block = block.copy();
 906            let native_window = self.0.lock().native_window;
 907            let executor = self.0.lock().executor.clone();
 908            executor
 909                .spawn(async move {
 910                    let _: () = msg_send![
 911                        alert,
 912                        beginSheetModalForWindow: native_window
 913                        completionHandler: block
 914                    ];
 915                })
 916                .detach();
 917
 918            Some(done_rx)
 919        }
 920    }
 921
 922    fn activate(&self) {
 923        let window = self.0.lock().native_window;
 924        let executor = self.0.lock().executor.clone();
 925        executor
 926            .spawn(async move {
 927                unsafe {
 928                    let _: () = msg_send![window, makeKeyAndOrderFront: nil];
 929                }
 930            })
 931            .detach();
 932    }
 933
 934    fn is_active(&self) -> bool {
 935        unsafe { self.0.lock().native_window.isKeyWindow() == YES }
 936    }
 937
 938    fn set_title(&mut self, title: &str) {
 939        unsafe {
 940            let app = NSApplication::sharedApplication(nil);
 941            let window = self.0.lock().native_window;
 942            let title = ns_string(title);
 943            let _: () = msg_send![app, changeWindowsItem:window title:title filename:false];
 944            let _: () = msg_send![window, setTitle: title];
 945            self.0.lock().move_traffic_light();
 946        }
 947    }
 948
 949    fn set_app_id(&mut self, _app_id: &str) {}
 950
 951    fn set_background_appearance(&mut self, background_appearance: WindowBackgroundAppearance) {
 952        let mut this = self.0.as_ref().lock();
 953        this.renderer
 954            .update_transparency(background_appearance != WindowBackgroundAppearance::Opaque);
 955
 956        let blur_radius = if background_appearance == WindowBackgroundAppearance::Blurred {
 957            80
 958        } else {
 959            0
 960        };
 961        let opaque = if background_appearance == WindowBackgroundAppearance::Opaque {
 962            YES
 963        } else {
 964            NO
 965        };
 966        unsafe {
 967            this.native_window.setOpaque_(opaque);
 968            // Shadows for transparent windows cause artifacts and performance issues
 969            this.native_window.setHasShadow_(opaque);
 970            let clear_color = if opaque == YES {
 971                NSColor::colorWithSRGBRed_green_blue_alpha_(nil, 0f64, 0f64, 0f64, 1f64)
 972            } else {
 973                NSColor::clearColor(nil)
 974            };
 975            this.native_window.setBackgroundColor_(clear_color);
 976            let window_number = this.native_window.windowNumber();
 977            CGSSetWindowBackgroundBlurRadius(CGSMainConnectionID(), window_number, blur_radius);
 978        }
 979    }
 980
 981    fn set_edited(&mut self, edited: bool) {
 982        unsafe {
 983            let window = self.0.lock().native_window;
 984            msg_send![window, setDocumentEdited: edited as BOOL]
 985        }
 986
 987        // Changing the document edited state resets the traffic light position,
 988        // so we have to move it again.
 989        self.0.lock().move_traffic_light();
 990    }
 991
 992    fn show_character_palette(&self) {
 993        let this = self.0.lock();
 994        let window = this.native_window;
 995        this.executor
 996            .spawn(async move {
 997                unsafe {
 998                    let app = NSApplication::sharedApplication(nil);
 999                    let _: () = msg_send![app, orderFrontCharacterPalette: window];
1000                }
1001            })
1002            .detach();
1003    }
1004
1005    fn minimize(&self) {
1006        let window = self.0.lock().native_window;
1007        unsafe {
1008            window.miniaturize_(nil);
1009        }
1010    }
1011
1012    fn zoom(&self) {
1013        let this = self.0.lock();
1014        let window = this.native_window;
1015        this.executor
1016            .spawn(async move {
1017                unsafe {
1018                    window.zoom_(nil);
1019                }
1020            })
1021            .detach();
1022    }
1023
1024    fn toggle_fullscreen(&self) {
1025        let this = self.0.lock();
1026        let window = this.native_window;
1027        this.executor
1028            .spawn(async move {
1029                unsafe {
1030                    window.toggleFullScreen_(nil);
1031                }
1032            })
1033            .detach();
1034    }
1035
1036    fn is_fullscreen(&self) -> bool {
1037        let this = self.0.lock();
1038        let window = this.native_window;
1039
1040        unsafe {
1041            window
1042                .styleMask()
1043                .contains(NSWindowStyleMask::NSFullScreenWindowMask)
1044        }
1045    }
1046
1047    fn on_request_frame(&self, callback: Box<dyn FnMut()>) {
1048        self.0.as_ref().lock().request_frame_callback = Some(callback);
1049    }
1050
1051    fn on_input(&self, callback: Box<dyn FnMut(PlatformInput) -> crate::DispatchEventResult>) {
1052        self.0.as_ref().lock().event_callback = Some(callback);
1053    }
1054
1055    fn on_active_status_change(&self, callback: Box<dyn FnMut(bool)>) {
1056        self.0.as_ref().lock().activate_callback = Some(callback);
1057    }
1058
1059    fn on_resize(&self, callback: Box<dyn FnMut(Size<Pixels>, f32)>) {
1060        self.0.as_ref().lock().resize_callback = Some(callback);
1061    }
1062
1063    fn on_moved(&self, callback: Box<dyn FnMut()>) {
1064        self.0.as_ref().lock().moved_callback = Some(callback);
1065    }
1066
1067    fn on_should_close(&self, callback: Box<dyn FnMut() -> bool>) {
1068        self.0.as_ref().lock().should_close_callback = Some(callback);
1069    }
1070
1071    fn on_close(&self, callback: Box<dyn FnOnce()>) {
1072        self.0.as_ref().lock().close_callback = Some(callback);
1073    }
1074
1075    fn on_appearance_changed(&self, callback: Box<dyn FnMut()>) {
1076        self.0.lock().appearance_changed_callback = Some(callback);
1077    }
1078
1079    fn draw(&self, scene: &crate::Scene) {
1080        let mut this = self.0.lock();
1081        this.renderer.draw(scene);
1082    }
1083
1084    fn sprite_atlas(&self) -> Arc<dyn PlatformAtlas> {
1085        self.0.lock().renderer.sprite_atlas().clone()
1086    }
1087
1088    fn show_window_menu(&self, _position: Point<Pixels>) {}
1089
1090    fn start_system_move(&self) {}
1091
1092    fn should_render_window_controls(&self) -> bool {
1093        false
1094    }
1095}
1096
1097impl rwh::HasWindowHandle for MacWindow {
1098    fn window_handle(&self) -> Result<rwh::WindowHandle<'_>, rwh::HandleError> {
1099        // SAFETY: The AppKitWindowHandle is a wrapper around a pointer to an NSView
1100        unsafe {
1101            Ok(rwh::WindowHandle::borrow_raw(rwh::RawWindowHandle::AppKit(
1102                rwh::AppKitWindowHandle::new(self.0.lock().native_view.cast()),
1103            )))
1104        }
1105    }
1106}
1107
1108impl rwh::HasDisplayHandle for MacWindow {
1109    fn display_handle(&self) -> Result<rwh::DisplayHandle<'_>, rwh::HandleError> {
1110        // SAFETY: This is a no-op on macOS
1111        unsafe {
1112            Ok(rwh::DisplayHandle::borrow_raw(
1113                rwh::AppKitDisplayHandle::new().into(),
1114            ))
1115        }
1116    }
1117}
1118
1119fn get_scale_factor(native_window: id) -> f32 {
1120    let factor = unsafe {
1121        let screen: id = msg_send![native_window, screen];
1122        NSScreen::backingScaleFactor(screen) as f32
1123    };
1124
1125    // We are not certain what triggers this, but it seems that sometimes
1126    // this method would return 0 (https://github.com/zed-industries/zed/issues/6412)
1127    // It seems most likely that this would happen if the window has no screen
1128    // (if it is off-screen), though we'd expect to see viewDidChangeBackingProperties before
1129    // it was rendered for real.
1130    // Regardless, attempt to avoid the issue here.
1131    if factor == 0.0 {
1132        2.
1133    } else {
1134        factor
1135    }
1136}
1137
1138unsafe fn get_window_state(object: &Object) -> Arc<Mutex<MacWindowState>> {
1139    let raw: *mut c_void = *object.get_ivar(WINDOW_STATE_IVAR);
1140    let rc1 = Arc::from_raw(raw as *mut Mutex<MacWindowState>);
1141    let rc2 = rc1.clone();
1142    mem::forget(rc1);
1143    rc2
1144}
1145
1146unsafe fn drop_window_state(object: &Object) {
1147    let raw: *mut c_void = *object.get_ivar(WINDOW_STATE_IVAR);
1148    Arc::from_raw(raw as *mut Mutex<MacWindowState>);
1149}
1150
1151extern "C" fn yes(_: &Object, _: Sel) -> BOOL {
1152    YES
1153}
1154
1155extern "C" fn dealloc_window(this: &Object, _: Sel) {
1156    unsafe {
1157        drop_window_state(this);
1158        let _: () = msg_send![super(this, class!(NSWindow)), dealloc];
1159    }
1160}
1161
1162extern "C" fn dealloc_view(this: &Object, _: Sel) {
1163    unsafe {
1164        drop_window_state(this);
1165        let _: () = msg_send![super(this, class!(NSView)), dealloc];
1166    }
1167}
1168
1169extern "C" fn handle_key_equivalent(this: &Object, _: Sel, native_event: id) -> BOOL {
1170    handle_key_event(this, native_event, true)
1171}
1172
1173extern "C" fn handle_key_down(this: &Object, _: Sel, native_event: id) {
1174    handle_key_event(this, native_event, false);
1175}
1176
1177// Things to test if you're modifying this method:
1178//  U.S. layout:
1179//   - The IME consumes characters like 'j' and 'k', which makes paging through `less` in
1180//     the terminal behave incorrectly by default. This behavior should be patched by our
1181//     IME integration
1182//   - `alt-t` should open the tasks menu
1183//   - In vim mode, this keybinding should work:
1184//     ```
1185//        {
1186//          "context": "Editor && vim_mode == insert",
1187//          "bindings": {"j j": "vim::NormalBefore"}
1188//        }
1189//     ```
1190//     and typing 'j k' in insert mode with this keybinding should insert the two characters
1191//  Brazilian layout:
1192//   - `" space` should create an unmarked quote
1193//   - `" backspace` should delete the marked quote
1194//   - `" up` should insert a quote, unmark it, and move up one line
1195//   - `" cmd-down` should insert a quote, unmark it, and move to the end of the file
1196//      - NOTE: The current implementation does not move the selection to the end of the file
1197//   - `cmd-ctrl-space` and clicking on an emoji should type it
1198//  Czech (QWERTY) layout:
1199//   - in vim mode `option-4`  should go to end of line (same as $)
1200//  Japanese (Romaji) layout:
1201//   - type `a i left down up enter enter` should create an unmarked text "愛"
1202extern "C" fn handle_key_event(this: &Object, native_event: id, key_equivalent: bool) -> BOOL {
1203    let window_state = unsafe { get_window_state(this) };
1204    let mut lock = window_state.as_ref().lock();
1205
1206    let window_height = lock.content_size().height;
1207    let event = unsafe { PlatformInput::from_native(native_event, Some(window_height)) };
1208
1209    if let Some(PlatformInput::KeyDown(mut event)) = event {
1210        // For certain keystrokes, macOS will first dispatch a "key equivalent" event.
1211        // If that event isn't handled, it will then dispatch a "key down" event. GPUI
1212        // makes no distinction between these two types of events, so we need to ignore
1213        // the "key down" event if we've already just processed its "key equivalent" version.
1214        if key_equivalent {
1215            lock.last_key_equivalent = Some(event.clone());
1216        } else if lock.last_key_equivalent.take().as_ref() == Some(&event) {
1217            return NO;
1218        }
1219
1220        let keydown = event.keystroke.clone();
1221        let fn_modifier = keydown.modifiers.function;
1222        // Ignore events from held-down keys after some of the initially-pressed keys
1223        // were released.
1224        if event.is_held {
1225            if lock.last_fresh_keydown.as_ref() != Some(&keydown) {
1226                return YES;
1227            }
1228        } else {
1229            lock.last_fresh_keydown = Some(keydown.clone());
1230        }
1231        lock.last_ime_inputs = Some(Default::default());
1232        drop(lock);
1233
1234        // Send the event to the input context for IME handling, unless the `fn` modifier is
1235        // being pressed.
1236        // this will call back into `insert_text`, etc.
1237        if !fn_modifier {
1238            unsafe {
1239                let input_context: id = msg_send![this, inputContext];
1240                let _: BOOL = msg_send![input_context, handleEvent: native_event];
1241            }
1242        }
1243
1244        let mut handled = false;
1245        let mut lock = window_state.lock();
1246        let previous_keydown_inserted_text = lock.previous_keydown_inserted_text.take();
1247        let mut last_inserts = lock.last_ime_inputs.take().unwrap();
1248
1249        let mut callback = lock.event_callback.take();
1250        drop(lock);
1251
1252        let last_insert = last_inserts.pop();
1253        // on a brazilian keyboard typing `"` and then hitting `up` will cause two IME
1254        // events, one to unmark the quote, and one to send the up arrow.
1255        for (text, range) in last_inserts {
1256            send_to_input_handler(this, ImeInput::InsertText(text, range));
1257        }
1258
1259        let is_composing =
1260            with_input_handler(this, |input_handler| input_handler.marked_text_range())
1261                .flatten()
1262                .is_some();
1263
1264        if let Some((text, range)) = last_insert {
1265            if !is_composing {
1266                window_state.lock().previous_keydown_inserted_text = Some(text.clone());
1267                if let Some(callback) = callback.as_mut() {
1268                    event.keystroke.ime_key = Some(text.clone());
1269                    handled = !callback(PlatformInput::KeyDown(event)).propagate;
1270                }
1271            }
1272
1273            if !handled {
1274                handled = true;
1275                send_to_input_handler(this, ImeInput::InsertText(text, range));
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();
1568    let size = lock.content_size();
1569    let drawable_size = size.to_device_pixels(scale_factor);
1570    unsafe {
1571        let _: () = msg_send![
1572            lock.renderer.layer(),
1573            setContentsScale: scale_factor as f64
1574        ];
1575    }
1576
1577    lock.renderer.update_drawable_size(drawable_size);
1578
1579    if let Some(mut callback) = lock.resize_callback.take() {
1580        let content_size = lock.content_size();
1581        let scale_factor = lock.scale_factor();
1582        drop(lock);
1583        callback(content_size, scale_factor);
1584        window_state.as_ref().lock().resize_callback = Some(callback);
1585    };
1586}
1587
1588extern "C" fn set_frame_size(this: &Object, _: Sel, size: NSSize) {
1589    let window_state = unsafe { get_window_state(this) };
1590    let mut lock = window_state.as_ref().lock();
1591
1592    let new_size = Size::<Pixels>::from(size);
1593    if lock.content_size() == new_size {
1594        return;
1595    }
1596
1597    unsafe {
1598        let _: () = msg_send![super(this, class!(NSView)), setFrameSize: size];
1599    }
1600
1601    let scale_factor = lock.scale_factor();
1602    let drawable_size = new_size.to_device_pixels(scale_factor);
1603    lock.renderer.update_drawable_size(drawable_size);
1604
1605    if let Some(mut callback) = lock.resize_callback.take() {
1606        let content_size = lock.content_size();
1607        let scale_factor = lock.scale_factor();
1608        drop(lock);
1609        callback(content_size, scale_factor);
1610        window_state.lock().resize_callback = Some(callback);
1611    };
1612}
1613
1614extern "C" fn display_layer(this: &Object, _: Sel, _: id) {
1615    let window_state = unsafe { get_window_state(this) };
1616    let mut lock = window_state.lock();
1617    if let Some(mut callback) = lock.request_frame_callback.take() {
1618        #[cfg(not(feature = "macos-blade"))]
1619        lock.renderer.set_presents_with_transaction(true);
1620        lock.stop_display_link();
1621        drop(lock);
1622        callback();
1623
1624        let mut lock = window_state.lock();
1625        lock.request_frame_callback = Some(callback);
1626        #[cfg(not(feature = "macos-blade"))]
1627        lock.renderer.set_presents_with_transaction(false);
1628        lock.start_display_link();
1629    }
1630}
1631
1632unsafe extern "C" fn step(view: *mut c_void) {
1633    let view = view as id;
1634    let window_state = unsafe { get_window_state(&*view) };
1635    let mut lock = window_state.lock();
1636
1637    if let Some(mut callback) = lock.request_frame_callback.take() {
1638        drop(lock);
1639        callback();
1640        window_state.lock().request_frame_callback = Some(callback);
1641    }
1642}
1643
1644extern "C" fn valid_attributes_for_marked_text(_: &Object, _: Sel) -> id {
1645    unsafe { msg_send![class!(NSArray), array] }
1646}
1647
1648extern "C" fn has_marked_text(this: &Object, _: Sel) -> BOOL {
1649    let has_marked_text_result =
1650        with_input_handler(this, |input_handler| input_handler.marked_text_range()).flatten();
1651
1652    has_marked_text_result.is_some() as BOOL
1653}
1654
1655extern "C" fn marked_range(this: &Object, _: Sel) -> NSRange {
1656    let marked_range_result =
1657        with_input_handler(this, |input_handler| input_handler.marked_text_range()).flatten();
1658
1659    marked_range_result.map_or(NSRange::invalid(), |range| range.into())
1660}
1661
1662extern "C" fn selected_range(this: &Object, _: Sel) -> NSRange {
1663    let selected_range_result =
1664        with_input_handler(this, |input_handler| input_handler.selected_text_range()).flatten();
1665
1666    selected_range_result.map_or(NSRange::invalid(), |range| range.into())
1667}
1668
1669extern "C" fn first_rect_for_character_range(
1670    this: &Object,
1671    _: Sel,
1672    range: NSRange,
1673    _: id,
1674) -> NSRect {
1675    let frame = unsafe {
1676        let window = get_window_state(this).lock().native_window;
1677        NSView::frame(window)
1678    };
1679    with_input_handler(this, |input_handler| {
1680        input_handler.bounds_for_range(range.to_range()?)
1681    })
1682    .flatten()
1683    .map_or(
1684        NSRect::new(NSPoint::new(0., 0.), NSSize::new(0., 0.)),
1685        |bounds| {
1686            NSRect::new(
1687                NSPoint::new(
1688                    frame.origin.x + bounds.origin.x.0 as f64,
1689                    frame.origin.y + frame.size.height
1690                        - bounds.origin.y.0 as f64
1691                        - bounds.size.height.0 as f64,
1692                ),
1693                NSSize::new(bounds.size.width.0 as f64, bounds.size.height.0 as f64),
1694            )
1695        },
1696    )
1697}
1698
1699extern "C" fn insert_text(this: &Object, _: Sel, text: id, replacement_range: NSRange) {
1700    unsafe {
1701        let is_attributed_string: BOOL =
1702            msg_send![text, isKindOfClass: [class!(NSAttributedString)]];
1703        let text: id = if is_attributed_string == YES {
1704            msg_send![text, string]
1705        } else {
1706            text
1707        };
1708
1709        let text = text.to_str();
1710        let replacement_range = replacement_range.to_range();
1711        send_to_input_handler(
1712            this,
1713            ImeInput::InsertText(text.to_string(), replacement_range),
1714        );
1715    }
1716}
1717
1718extern "C" fn set_marked_text(
1719    this: &Object,
1720    _: Sel,
1721    text: id,
1722    selected_range: NSRange,
1723    replacement_range: NSRange,
1724) {
1725    unsafe {
1726        let is_attributed_string: BOOL =
1727            msg_send![text, isKindOfClass: [class!(NSAttributedString)]];
1728        let text: id = if is_attributed_string == YES {
1729            msg_send![text, string]
1730        } else {
1731            text
1732        };
1733        let selected_range = selected_range.to_range();
1734        let replacement_range = replacement_range.to_range();
1735        let text = text.to_str();
1736
1737        send_to_input_handler(
1738            this,
1739            ImeInput::SetMarkedText(text.to_string(), replacement_range, selected_range),
1740        );
1741    }
1742}
1743extern "C" fn unmark_text(this: &Object, _: Sel) {
1744    send_to_input_handler(this, ImeInput::UnmarkText);
1745}
1746
1747extern "C" fn attributed_substring_for_proposed_range(
1748    this: &Object,
1749    _: Sel,
1750    range: NSRange,
1751    _actual_range: *mut c_void,
1752) -> id {
1753    with_input_handler(this, |input_handler| {
1754        let range = range.to_range()?;
1755        if range.is_empty() {
1756            return None;
1757        }
1758
1759        let selected_text = input_handler.text_for_range(range.clone())?;
1760        unsafe {
1761            let string: id = msg_send![class!(NSAttributedString), alloc];
1762            let string: id = msg_send![string, initWithString: ns_string(&selected_text)];
1763            Some(string)
1764        }
1765    })
1766    .flatten()
1767    .unwrap_or(nil)
1768}
1769
1770extern "C" fn do_command_by_selector(_: &Object, _: Sel, _: Sel) {}
1771
1772extern "C" fn view_did_change_effective_appearance(this: &Object, _: Sel) {
1773    unsafe {
1774        let state = get_window_state(this);
1775        let mut lock = state.as_ref().lock();
1776        if let Some(mut callback) = lock.appearance_changed_callback.take() {
1777            drop(lock);
1778            callback();
1779            state.lock().appearance_changed_callback = Some(callback);
1780        }
1781    }
1782}
1783
1784extern "C" fn accepts_first_mouse(this: &Object, _: Sel, _: id) -> BOOL {
1785    let window_state = unsafe { get_window_state(this) };
1786    let mut lock = window_state.as_ref().lock();
1787    lock.first_mouse = true;
1788    YES
1789}
1790
1791extern "C" fn dragging_entered(this: &Object, _: Sel, dragging_info: id) -> NSDragOperation {
1792    let window_state = unsafe { get_window_state(this) };
1793    let position = drag_event_position(&window_state, dragging_info);
1794    let paths = external_paths_from_event(dragging_info);
1795    if let Some(event) =
1796        paths.map(|paths| PlatformInput::FileDrop(FileDropEvent::Entered { position, paths }))
1797    {
1798        if send_new_event(&window_state, event) {
1799            window_state.lock().external_files_dragged = true;
1800            return NSDragOperationCopy;
1801        }
1802    }
1803    NSDragOperationNone
1804}
1805
1806extern "C" fn dragging_updated(this: &Object, _: Sel, dragging_info: id) -> NSDragOperation {
1807    let window_state = unsafe { get_window_state(this) };
1808    let position = drag_event_position(&window_state, dragging_info);
1809    if send_new_event(
1810        &window_state,
1811        PlatformInput::FileDrop(FileDropEvent::Pending { position }),
1812    ) {
1813        NSDragOperationCopy
1814    } else {
1815        NSDragOperationNone
1816    }
1817}
1818
1819extern "C" fn dragging_exited(this: &Object, _: Sel, _: id) {
1820    let window_state = unsafe { get_window_state(this) };
1821    send_new_event(
1822        &window_state,
1823        PlatformInput::FileDrop(FileDropEvent::Exited),
1824    );
1825    window_state.lock().external_files_dragged = false;
1826}
1827
1828extern "C" fn perform_drag_operation(this: &Object, _: Sel, dragging_info: id) -> BOOL {
1829    let window_state = unsafe { get_window_state(this) };
1830    let position = drag_event_position(&window_state, dragging_info);
1831    if send_new_event(
1832        &window_state,
1833        PlatformInput::FileDrop(FileDropEvent::Submit { position }),
1834    ) {
1835        YES
1836    } else {
1837        NO
1838    }
1839}
1840
1841fn external_paths_from_event(dragging_info: *mut Object) -> Option<ExternalPaths> {
1842    let mut paths = SmallVec::new();
1843    let pasteboard: id = unsafe { msg_send![dragging_info, draggingPasteboard] };
1844    let filenames = unsafe { NSPasteboard::propertyListForType(pasteboard, NSFilenamesPboardType) };
1845    if filenames == nil {
1846        return None;
1847    }
1848    for file in unsafe { filenames.iter() } {
1849        let path = unsafe {
1850            let f = NSString::UTF8String(file);
1851            CStr::from_ptr(f).to_string_lossy().into_owned()
1852        };
1853        paths.push(PathBuf::from(path))
1854    }
1855    Some(ExternalPaths(paths))
1856}
1857
1858extern "C" fn conclude_drag_operation(this: &Object, _: Sel, _: id) {
1859    let window_state = unsafe { get_window_state(this) };
1860    send_new_event(
1861        &window_state,
1862        PlatformInput::FileDrop(FileDropEvent::Exited),
1863    );
1864}
1865
1866async fn synthetic_drag(
1867    window_state: Weak<Mutex<MacWindowState>>,
1868    drag_id: usize,
1869    event: MouseMoveEvent,
1870) {
1871    loop {
1872        Timer::after(Duration::from_millis(16)).await;
1873        if let Some(window_state) = window_state.upgrade() {
1874            let mut lock = window_state.lock();
1875            if lock.synthetic_drag_counter == drag_id {
1876                if let Some(mut callback) = lock.event_callback.take() {
1877                    drop(lock);
1878                    callback(PlatformInput::MouseMove(event.clone()));
1879                    window_state.lock().event_callback = Some(callback);
1880                }
1881            } else {
1882                break;
1883            }
1884        }
1885    }
1886}
1887
1888fn send_new_event(window_state_lock: &Mutex<MacWindowState>, e: PlatformInput) -> bool {
1889    let window_state = window_state_lock.lock().event_callback.take();
1890    if let Some(mut callback) = window_state {
1891        callback(e);
1892        window_state_lock.lock().event_callback = Some(callback);
1893        true
1894    } else {
1895        false
1896    }
1897}
1898
1899fn drag_event_position(window_state: &Mutex<MacWindowState>, dragging_info: id) -> Point<Pixels> {
1900    let drag_location: NSPoint = unsafe { msg_send![dragging_info, draggingLocation] };
1901    convert_mouse_position(drag_location, window_state.lock().content_size().height)
1902}
1903
1904fn with_input_handler<F, R>(window: &Object, f: F) -> Option<R>
1905where
1906    F: FnOnce(&mut PlatformInputHandler) -> R,
1907{
1908    let window_state = unsafe { get_window_state(window) };
1909    let mut lock = window_state.as_ref().lock();
1910    if let Some(mut input_handler) = lock.input_handler.take() {
1911        drop(lock);
1912        let result = f(&mut input_handler);
1913        window_state.lock().input_handler = Some(input_handler);
1914        Some(result)
1915    } else {
1916        None
1917    }
1918}
1919
1920fn send_to_input_handler(window: &Object, ime: ImeInput) {
1921    unsafe {
1922        let window_state = get_window_state(window);
1923        let mut lock = window_state.lock();
1924
1925        if let Some(mut input_handler) = lock.input_handler.take() {
1926            match ime.clone() {
1927                ImeInput::InsertText(text, range) => {
1928                    if let Some(ime_input) = lock.last_ime_inputs.as_mut() {
1929                        ime_input.push((text, range));
1930                        lock.input_handler = Some(input_handler);
1931                        return;
1932                    }
1933                    drop(lock);
1934                    input_handler.replace_text_in_range(range, &text)
1935                }
1936                ImeInput::SetMarkedText(text, range, marked_range) => {
1937                    drop(lock);
1938                    input_handler.replace_and_mark_text_in_range(range, &text, marked_range)
1939                }
1940                ImeInput::UnmarkText => {
1941                    drop(lock);
1942                    input_handler.unmark_text()
1943                }
1944            }
1945            window_state.lock().input_handler = Some(input_handler);
1946        }
1947    }
1948}
1949
1950unsafe fn display_id_for_screen(screen: id) -> CGDirectDisplayID {
1951    let device_description = NSScreen::deviceDescription(screen);
1952    let screen_number_key: id = NSString::alloc(nil).init_str("NSScreenNumber");
1953    let screen_number = device_description.objectForKey_(screen_number_key);
1954    let screen_number: NSUInteger = msg_send![screen_number, unsignedIntegerValue];
1955    screen_number as CGDirectDisplayID
1956}