window.rs

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