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