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