window.rs

   1use super::{ns_string, renderer, MacDisplay, NSRange};
   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, 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    os::raw::c_char,
  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!(windowWillExitFullScreen:),
 268        window_will_exit_fullscreen as extern "C" fn(&Object, Sel, id),
 269    );
 270    decl.add_method(
 271        sel!(windowDidMove:),
 272        window_did_move as extern "C" fn(&Object, Sel, id),
 273    );
 274    decl.add_method(
 275        sel!(windowDidChangeScreen:),
 276        window_did_change_screen as extern "C" fn(&Object, Sel, id),
 277    );
 278    decl.add_method(
 279        sel!(windowDidBecomeKey:),
 280        window_did_change_key_status as extern "C" fn(&Object, Sel, id),
 281    );
 282    decl.add_method(
 283        sel!(windowDidResignKey:),
 284        window_did_change_key_status as extern "C" fn(&Object, Sel, id),
 285    );
 286    decl.add_method(
 287        sel!(windowShouldClose:),
 288        window_should_close as extern "C" fn(&Object, Sel, id) -> BOOL,
 289    );
 290
 291    decl.add_method(sel!(close), close_window as extern "C" fn(&Object, Sel));
 292
 293    decl.add_method(
 294        sel!(draggingEntered:),
 295        dragging_entered as extern "C" fn(&Object, Sel, id) -> NSDragOperation,
 296    );
 297    decl.add_method(
 298        sel!(draggingUpdated:),
 299        dragging_updated as extern "C" fn(&Object, Sel, id) -> NSDragOperation,
 300    );
 301    decl.add_method(
 302        sel!(draggingExited:),
 303        dragging_exited as extern "C" fn(&Object, Sel, id),
 304    );
 305    decl.add_method(
 306        sel!(performDragOperation:),
 307        perform_drag_operation as extern "C" fn(&Object, Sel, id) -> BOOL,
 308    );
 309    decl.add_method(
 310        sel!(concludeDragOperation:),
 311        conclude_drag_operation as extern "C" fn(&Object, Sel, id),
 312    );
 313    decl.add_method(
 314        sel!(windowDidMiniaturize:),
 315        window_did_miniaturize as extern "C" fn(&Object, Sel, id),
 316    );
 317    decl.add_method(
 318        sel!(windowDidDeminiaturize:),
 319        window_did_deminiaturize as extern "C" fn(&Object, Sel, id),
 320    );
 321
 322    decl.register()
 323}
 324
 325#[allow(clippy::enum_variant_names)]
 326enum ImeInput {
 327    InsertText(String, Option<Range<usize>>),
 328    SetMarkedText(String, Option<Range<usize>>, Option<Range<usize>>),
 329    UnmarkText,
 330}
 331
 332struct MacWindowState {
 333    handle: AnyWindowHandle,
 334    executor: ForegroundExecutor,
 335    native_window: id,
 336    native_view: NonNull<Object>,
 337    display_link: Option<DisplayLink>,
 338    renderer: renderer::Renderer,
 339    request_frame_callback: Option<Box<dyn FnMut()>>,
 340    event_callback: Option<Box<dyn FnMut(PlatformInput) -> crate::DispatchEventResult>>,
 341    activate_callback: Option<Box<dyn FnMut(bool)>>,
 342    resize_callback: Option<Box<dyn FnMut(Size<Pixels>, f32)>>,
 343    fullscreen_callback: Option<Box<dyn FnMut(bool)>>,
 344    moved_callback: Option<Box<dyn FnMut()>>,
 345    should_close_callback: Option<Box<dyn FnMut() -> bool>>,
 346    close_callback: Option<Box<dyn FnOnce()>>,
 347    appearance_changed_callback: Option<Box<dyn FnMut()>>,
 348    input_handler: Option<PlatformInputHandler>,
 349    last_key_equivalent: Option<KeyDownEvent>,
 350    synthetic_drag_counter: usize,
 351    last_fresh_keydown: Option<Keystroke>,
 352    traffic_light_position: Option<Point<Pixels>>,
 353    previous_modifiers_changed_event: Option<PlatformInput>,
 354    // State tracking what the IME did after the last request
 355    input_during_keydown: Option<SmallVec<[ImeInput; 1]>>,
 356    previous_keydown_inserted_text: Option<String>,
 357    external_files_dragged: bool,
 358    // Whether the next left-mouse click is also the focusing click.
 359    first_mouse: bool,
 360    minimized: bool,
 361}
 362
 363impl MacWindowState {
 364    fn move_traffic_light(&self) {
 365        if let Some(traffic_light_position) = self.traffic_light_position {
 366            if self.is_fullscreen() {
 367                // Moving traffic lights while fullscreen doesn't work,
 368                // see https://github.com/zed-industries/zed/issues/4712
 369                return;
 370            }
 371
 372            let titlebar_height = self.titlebar_height();
 373
 374            unsafe {
 375                let close_button: id = msg_send![
 376                    self.native_window,
 377                    standardWindowButton: NSWindowButton::NSWindowCloseButton
 378                ];
 379                let min_button: id = msg_send![
 380                    self.native_window,
 381                    standardWindowButton: NSWindowButton::NSWindowMiniaturizeButton
 382                ];
 383                let zoom_button: id = msg_send![
 384                    self.native_window,
 385                    standardWindowButton: NSWindowButton::NSWindowZoomButton
 386                ];
 387
 388                let mut close_button_frame: CGRect = msg_send![close_button, frame];
 389                let mut min_button_frame: CGRect = msg_send![min_button, frame];
 390                let mut zoom_button_frame: CGRect = msg_send![zoom_button, frame];
 391                let mut origin = point(
 392                    traffic_light_position.x,
 393                    titlebar_height
 394                        - traffic_light_position.y
 395                        - px(close_button_frame.size.height as f32),
 396                );
 397                let button_spacing =
 398                    px((min_button_frame.origin.x - close_button_frame.origin.x) as f32);
 399
 400                close_button_frame.origin = CGPoint::new(origin.x.into(), origin.y.into());
 401                let _: () = msg_send![close_button, setFrame: close_button_frame];
 402                origin.x += button_spacing;
 403
 404                min_button_frame.origin = CGPoint::new(origin.x.into(), origin.y.into());
 405                let _: () = msg_send![min_button, setFrame: min_button_frame];
 406                origin.x += button_spacing;
 407
 408                zoom_button_frame.origin = CGPoint::new(origin.x.into(), origin.y.into());
 409                let _: () = msg_send![zoom_button, setFrame: zoom_button_frame];
 410                origin.x += button_spacing;
 411            }
 412        }
 413    }
 414
 415    fn start_display_link(&mut self) {
 416        self.stop_display_link();
 417        unsafe {
 418            if !self
 419                .native_window
 420                .occlusionState()
 421                .contains(NSWindowOcclusionState::NSWindowOcclusionStateVisible)
 422            {
 423                return;
 424            }
 425        }
 426        let display_id = unsafe { display_id_for_screen(self.native_window.screen()) };
 427        if let Some(mut display_link) =
 428            DisplayLink::new(display_id, self.native_view.as_ptr() as *mut c_void, step).log_err()
 429        {
 430            display_link.start().log_err();
 431            self.display_link = Some(display_link);
 432        }
 433    }
 434
 435    fn stop_display_link(&mut self) {
 436        self.display_link = None;
 437    }
 438
 439    fn is_maximized(&self) -> bool {
 440        unsafe {
 441            let bounds = self.bounds();
 442            let screen_size = self.native_window.screen().visibleFrame().into();
 443            bounds.size == screen_size
 444        }
 445    }
 446
 447    fn is_minimized(&self) -> bool {
 448        self.minimized
 449    }
 450
 451    fn is_fullscreen(&self) -> bool {
 452        unsafe {
 453            let style_mask = self.native_window.styleMask();
 454            style_mask.contains(NSWindowStyleMask::NSFullScreenWindowMask)
 455        }
 456    }
 457
 458    fn bounds(&self) -> Bounds<DevicePixels> {
 459        let mut window_frame = unsafe { NSWindow::frame(self.native_window) };
 460        let screen_frame = unsafe {
 461            let screen = NSWindow::screen(self.native_window);
 462            NSScreen::frame(screen)
 463        };
 464
 465        // Flip the y coordinate to be top-left origin
 466        window_frame.origin.y =
 467            screen_frame.size.height - window_frame.origin.y - window_frame.size.height;
 468
 469        let bounds = Bounds::new(
 470            point(
 471                ((window_frame.origin.x - screen_frame.origin.x) as i32).into(),
 472                ((window_frame.origin.y - screen_frame.origin.y) as i32).into(),
 473            ),
 474            size(
 475                (window_frame.size.width as i32).into(),
 476                (window_frame.size.height as i32).into(),
 477            ),
 478        );
 479        bounds
 480    }
 481
 482    fn content_size(&self) -> Size<Pixels> {
 483        let NSSize { width, height, .. } =
 484            unsafe { NSView::frame(self.native_window.contentView()) }.size;
 485        size(px(width as f32), px(height as f32))
 486    }
 487
 488    fn scale_factor(&self) -> f32 {
 489        get_scale_factor(self.native_window)
 490    }
 491
 492    fn update_drawable_size(&mut self, drawable_size: NSSize) {
 493        self.renderer.update_drawable_size(Size {
 494            width: drawable_size.width,
 495            height: drawable_size.height,
 496        })
 497    }
 498
 499    fn titlebar_height(&self) -> Pixels {
 500        unsafe {
 501            let frame = NSWindow::frame(self.native_window);
 502            let content_layout_rect: CGRect = msg_send![self.native_window, contentLayoutRect];
 503            px((frame.size.height - content_layout_rect.size.height) as f32)
 504        }
 505    }
 506}
 507
 508unsafe impl Send for MacWindowState {}
 509
 510pub(crate) struct MacWindow(Arc<Mutex<MacWindowState>>);
 511
 512impl MacWindow {
 513    pub fn open(
 514        handle: AnyWindowHandle,
 515        WindowParams {
 516            window_background,
 517            bounds,
 518            titlebar,
 519            kind,
 520            is_movable,
 521            focus,
 522            show,
 523            display_id,
 524        }: WindowParams,
 525        executor: ForegroundExecutor,
 526        renderer_context: renderer::Context,
 527    ) -> Self {
 528        unsafe {
 529            let pool = NSAutoreleasePool::new(nil);
 530
 531            let mut style_mask;
 532            if let Some(titlebar) = titlebar.as_ref() {
 533                style_mask = NSWindowStyleMask::NSClosableWindowMask
 534                    | NSWindowStyleMask::NSMiniaturizableWindowMask
 535                    | NSWindowStyleMask::NSResizableWindowMask
 536                    | NSWindowStyleMask::NSTitledWindowMask;
 537
 538                if titlebar.appears_transparent {
 539                    style_mask |= NSWindowStyleMask::NSFullSizeContentViewWindowMask;
 540                }
 541            } else {
 542                style_mask = NSWindowStyleMask::NSTitledWindowMask
 543                    | NSWindowStyleMask::NSFullSizeContentViewWindowMask;
 544            }
 545
 546            let native_window: id = match kind {
 547                WindowKind::Normal => msg_send![WINDOW_CLASS, alloc],
 548                WindowKind::PopUp => {
 549                    style_mask |= NSWindowStyleMaskNonactivatingPanel;
 550                    msg_send![PANEL_CLASS, alloc]
 551                }
 552            };
 553
 554            let display = display_id
 555                .and_then(MacDisplay::find_by_id)
 556                .unwrap_or_else(|| MacDisplay::primary());
 557
 558            let mut target_screen = nil;
 559            let mut screen_frame = None;
 560
 561            let screens = NSScreen::screens(nil);
 562            let count: u64 = cocoa::foundation::NSArray::count(screens);
 563            for i in 0..count {
 564                let screen = cocoa::foundation::NSArray::objectAtIndex(screens, i);
 565                let frame = NSScreen::visibleFrame(screen);
 566                let display_id = display_id_for_screen(screen);
 567                if display_id == display.0 {
 568                    screen_frame = Some(frame);
 569                    target_screen = screen;
 570                }
 571            }
 572
 573            let screen_frame = screen_frame.unwrap_or_else(|| {
 574                let screen = NSScreen::mainScreen(nil);
 575                target_screen = screen;
 576                NSScreen::visibleFrame(screen)
 577            });
 578
 579            let window_rect = NSRect::new(
 580                NSPoint::new(
 581                    screen_frame.origin.x + bounds.origin.x.0 as f64,
 582                    screen_frame.origin.y
 583                        + (display.bounds().size.height - bounds.origin.y).0 as f64,
 584                ),
 585                NSSize::new(bounds.size.width.0 as f64, bounds.size.height.0 as f64),
 586            );
 587
 588            let native_window = native_window.initWithContentRect_styleMask_backing_defer_screen_(
 589                window_rect,
 590                style_mask,
 591                NSBackingStoreBuffered,
 592                NO,
 593                target_screen,
 594            );
 595            assert!(!native_window.is_null());
 596            let () = msg_send![
 597                native_window,
 598                registerForDraggedTypes:
 599                    NSArray::arrayWithObject(nil, NSFilenamesPboardType)
 600            ];
 601            let () = msg_send![
 602                native_window,
 603                setReleasedWhenClosed: NO
 604            ];
 605
 606            let native_view: id = msg_send![VIEW_CLASS, alloc];
 607            let native_view = NSView::init(native_view);
 608            assert!(!native_view.is_null());
 609
 610            let window_size = {
 611                let scale = get_scale_factor(native_window);
 612                size(
 613                    bounds.size.width.0 as f32 * scale,
 614                    bounds.size.height.0 as f32 * scale,
 615                )
 616            };
 617
 618            let mut window = Self(Arc::new(Mutex::new(MacWindowState {
 619                handle,
 620                executor,
 621                native_window,
 622                native_view: NonNull::new_unchecked(native_view),
 623                display_link: None,
 624                renderer: renderer::new_renderer(
 625                    renderer_context,
 626                    native_window as *mut _,
 627                    native_view as *mut _,
 628                    window_size,
 629                ),
 630                request_frame_callback: None,
 631                event_callback: None,
 632                activate_callback: None,
 633                resize_callback: None,
 634                fullscreen_callback: None,
 635                moved_callback: None,
 636                should_close_callback: None,
 637                close_callback: None,
 638                appearance_changed_callback: None,
 639                input_handler: None,
 640                last_key_equivalent: None,
 641                synthetic_drag_counter: 0,
 642                last_fresh_keydown: None,
 643                traffic_light_position: titlebar
 644                    .as_ref()
 645                    .and_then(|titlebar| titlebar.traffic_light_position),
 646                previous_modifiers_changed_event: None,
 647                input_during_keydown: None,
 648                previous_keydown_inserted_text: None,
 649                external_files_dragged: false,
 650                first_mouse: false,
 651                minimized: false,
 652            })));
 653
 654            (*native_window).set_ivar(
 655                WINDOW_STATE_IVAR,
 656                Arc::into_raw(window.0.clone()) as *const c_void,
 657            );
 658            native_window.setDelegate_(native_window);
 659            (*native_view).set_ivar(
 660                WINDOW_STATE_IVAR,
 661                Arc::into_raw(window.0.clone()) as *const c_void,
 662            );
 663
 664            if let Some(title) = titlebar
 665                .as_ref()
 666                .and_then(|t| t.title.as_ref().map(AsRef::as_ref))
 667            {
 668                native_window.setTitle_(NSString::alloc(nil).init_str(title));
 669            }
 670
 671            native_window.setMovable_(is_movable as BOOL);
 672
 673            if titlebar.map_or(true, |titlebar| titlebar.appears_transparent) {
 674                native_window.setTitlebarAppearsTransparent_(YES);
 675                native_window.setTitleVisibility_(NSWindowTitleVisibility::NSWindowTitleHidden);
 676            }
 677
 678            native_view.setAutoresizingMask_(NSViewWidthSizable | NSViewHeightSizable);
 679            native_view.setWantsBestResolutionOpenGLSurface_(YES);
 680
 681            // From winit crate: On Mojave, views automatically become layer-backed shortly after
 682            // being added to a native_window. Changing the layer-backedness of a view breaks the
 683            // association between the view and its associated OpenGL context. To work around this,
 684            // on we explicitly make the view layer-backed up front so that AppKit doesn't do it
 685            // itself and break the association with its context.
 686            native_view.setWantsLayer(YES);
 687            let _: () = msg_send![
 688                native_view,
 689                setLayerContentsRedrawPolicy: NSViewLayerContentsRedrawDuringViewResize
 690            ];
 691
 692            native_window.setContentView_(native_view.autorelease());
 693            native_window.makeFirstResponder_(native_view);
 694
 695            window.set_background_appearance(window_background);
 696
 697            match kind {
 698                WindowKind::Normal => {
 699                    native_window.setLevel_(NSNormalWindowLevel);
 700                    native_window.setAcceptsMouseMovedEvents_(YES);
 701                }
 702                WindowKind::PopUp => {
 703                    // Use a tracking area to allow receiving MouseMoved events even when
 704                    // the window or application aren't active, which is often the case
 705                    // e.g. for notification windows.
 706                    let tracking_area: id = msg_send![class!(NSTrackingArea), alloc];
 707                    let _: () = msg_send![
 708                        tracking_area,
 709                        initWithRect: NSRect::new(NSPoint::new(0., 0.), NSSize::new(0., 0.))
 710                        options: NSTrackingMouseEnteredAndExited | NSTrackingMouseMoved | NSTrackingActiveAlways | NSTrackingInVisibleRect
 711                        owner: native_view
 712                        userInfo: nil
 713                    ];
 714                    let _: () =
 715                        msg_send![native_view, addTrackingArea: tracking_area.autorelease()];
 716
 717                    native_window.setLevel_(NSPopUpWindowLevel);
 718                    let _: () = msg_send![
 719                        native_window,
 720                        setAnimationBehavior: NSWindowAnimationBehaviorUtilityWindow
 721                    ];
 722                    native_window.setCollectionBehavior_(
 723                        NSWindowCollectionBehavior::NSWindowCollectionBehaviorCanJoinAllSpaces |
 724                        NSWindowCollectionBehavior::NSWindowCollectionBehaviorFullScreenAuxiliary
 725                    );
 726                }
 727            }
 728
 729            if focus {
 730                native_window.makeKeyAndOrderFront_(nil);
 731            } else if show {
 732                native_window.orderFront_(nil);
 733            }
 734
 735            // Set the initial position of the window to the specified origin.
 736            // Although we already specified the position using `initWithContentRect_styleMask_backing_defer_screen_`,
 737            // the window position might be incorrect if the main screen (the screen that contains the window that has focus)
 738            //  is different from the primary screen.
 739            NSWindow::setFrameTopLeftPoint_(native_window, window_rect.origin);
 740            window.0.lock().move_traffic_light();
 741
 742            pool.drain();
 743
 744            window
 745        }
 746    }
 747
 748    pub fn active_window() -> Option<AnyWindowHandle> {
 749        unsafe {
 750            let app = NSApplication::sharedApplication(nil);
 751            let main_window: id = msg_send![app, mainWindow];
 752            if msg_send![main_window, isKindOfClass: WINDOW_CLASS] {
 753                let handle = get_window_state(&*main_window).lock().handle;
 754                Some(handle)
 755            } else {
 756                None
 757            }
 758        }
 759    }
 760}
 761
 762impl Drop for MacWindow {
 763    fn drop(&mut self) {
 764        let mut this = self.0.lock();
 765        this.renderer.destroy();
 766        let window = this.native_window;
 767        this.display_link.take();
 768        unsafe {
 769            this.native_window.setDelegate_(nil);
 770        }
 771        this.executor
 772            .spawn(async move {
 773                unsafe {
 774                    window.close();
 775                    window.autorelease();
 776                }
 777            })
 778            .detach();
 779    }
 780}
 781
 782impl PlatformWindow for MacWindow {
 783    fn bounds(&self) -> Bounds<DevicePixels> {
 784        self.0.as_ref().lock().bounds()
 785    }
 786
 787    fn is_maximized(&self) -> bool {
 788        self.0.as_ref().lock().is_maximized()
 789    }
 790
 791    fn is_minimized(&self) -> bool {
 792        self.0.as_ref().lock().is_minimized()
 793    }
 794
 795    fn content_size(&self) -> Size<Pixels> {
 796        self.0.as_ref().lock().content_size()
 797    }
 798
 799    fn scale_factor(&self) -> f32 {
 800        self.0.as_ref().lock().scale_factor()
 801    }
 802
 803    fn appearance(&self) -> WindowAppearance {
 804        unsafe {
 805            let appearance: id = msg_send![self.0.lock().native_window, effectiveAppearance];
 806            WindowAppearance::from_native(appearance)
 807        }
 808    }
 809
 810    fn display(&self) -> Rc<dyn PlatformDisplay> {
 811        unsafe {
 812            let screen = self.0.lock().native_window.screen();
 813            let device_description: id = msg_send![screen, deviceDescription];
 814            let screen_number: id = NSDictionary::valueForKey_(
 815                device_description,
 816                NSString::alloc(nil).init_str("NSScreenNumber"),
 817            );
 818
 819            let screen_number: u32 = msg_send![screen_number, unsignedIntValue];
 820
 821            Rc::new(MacDisplay(screen_number))
 822        }
 823    }
 824
 825    fn mouse_position(&self) -> Point<Pixels> {
 826        let position = unsafe {
 827            self.0
 828                .lock()
 829                .native_window
 830                .mouseLocationOutsideOfEventStream()
 831        };
 832        convert_mouse_position(position, self.content_size().height)
 833    }
 834
 835    fn modifiers(&self) -> Modifiers {
 836        unsafe {
 837            let modifiers: NSEventModifierFlags = msg_send![class!(NSEvent), modifierFlags];
 838
 839            let control = modifiers.contains(NSEventModifierFlags::NSControlKeyMask);
 840            let alt = modifiers.contains(NSEventModifierFlags::NSAlternateKeyMask);
 841            let shift = modifiers.contains(NSEventModifierFlags::NSShiftKeyMask);
 842            let command = modifiers.contains(NSEventModifierFlags::NSCommandKeyMask);
 843            let function = modifiers.contains(NSEventModifierFlags::NSFunctionKeyMask);
 844
 845            Modifiers {
 846                control,
 847                alt,
 848                shift,
 849                platform: command,
 850                function,
 851            }
 852        }
 853    }
 854
 855    fn set_input_handler(&mut self, input_handler: PlatformInputHandler) {
 856        self.0.as_ref().lock().input_handler = Some(input_handler);
 857    }
 858
 859    fn take_input_handler(&mut self) -> Option<PlatformInputHandler> {
 860        self.0.as_ref().lock().input_handler.take()
 861    }
 862
 863    fn prompt(
 864        &self,
 865        level: PromptLevel,
 866        msg: &str,
 867        detail: Option<&str>,
 868        answers: &[&str],
 869    ) -> Option<oneshot::Receiver<usize>> {
 870        // macOs applies overrides to modal window buttons after they are added.
 871        // Two most important for this logic are:
 872        // * Buttons with "Cancel" title will be displayed as the last buttons in the modal
 873        // * Last button added to the modal via `addButtonWithTitle` stays focused
 874        // * Focused buttons react on "space"/" " keypresses
 875        // * Usage of `keyEquivalent`, `makeFirstResponder` or `setInitialFirstResponder` does not change the focus
 876        //
 877        // See also https://developer.apple.com/documentation/appkit/nsalert/1524532-addbuttonwithtitle#discussion
 878        // ```
 879        // By default, the first button has a key equivalent of Return,
 880        // any button with a title of “Cancel” has a key equivalent of Escape,
 881        // and any button with the title “Don’t Save” has a key equivalent of Command-D (but only if it’s not the first button).
 882        // ```
 883        //
 884        // To avoid situations when the last element added is "Cancel" and it gets the focus
 885        // (hence stealing both ESC and Space shortcuts), we find and add one non-Cancel button
 886        // last, so it gets focus and a Space shortcut.
 887        // This way, "Save this file? Yes/No/Cancel"-ish modals will get all three buttons mapped with a key.
 888        let latest_non_cancel_label = answers
 889            .iter()
 890            .enumerate()
 891            .rev()
 892            .find(|(_, &label)| label != "Cancel")
 893            .filter(|&(label_index, _)| label_index > 0);
 894
 895        unsafe {
 896            let alert: id = msg_send![class!(NSAlert), alloc];
 897            let alert: id = msg_send![alert, init];
 898            let alert_style = match level {
 899                PromptLevel::Info => 1,
 900                PromptLevel::Warning => 0,
 901                PromptLevel::Critical | PromptLevel::Destructive => 2,
 902            };
 903            let _: () = msg_send![alert, setAlertStyle: alert_style];
 904            let _: () = msg_send![alert, setMessageText: ns_string(msg)];
 905            if let Some(detail) = detail {
 906                let _: () = msg_send![alert, setInformativeText: ns_string(detail)];
 907            }
 908
 909            for (ix, answer) in answers
 910                .iter()
 911                .enumerate()
 912                .filter(|&(ix, _)| Some(ix) != latest_non_cancel_label.map(|(ix, _)| ix))
 913            {
 914                let button: id = msg_send![alert, addButtonWithTitle: ns_string(answer)];
 915                let _: () = msg_send![button, setTag: ix as NSInteger];
 916                if level == PromptLevel::Destructive && answer != &"Cancel" {
 917                    let _: () = msg_send![button, setHasDestructiveAction: YES];
 918                }
 919            }
 920            if let Some((ix, answer)) = latest_non_cancel_label {
 921                let button: id = msg_send![alert, addButtonWithTitle: ns_string(answer)];
 922                let _: () = msg_send![button, setTag: ix as NSInteger];
 923                if level == PromptLevel::Destructive {
 924                    let _: () = msg_send![button, setHasDestructiveAction: YES];
 925                }
 926            }
 927
 928            let (done_tx, done_rx) = oneshot::channel();
 929            let done_tx = Cell::new(Some(done_tx));
 930            let block = ConcreteBlock::new(move |answer: NSInteger| {
 931                if let Some(done_tx) = done_tx.take() {
 932                    let _ = done_tx.send(answer.try_into().unwrap());
 933                }
 934            });
 935            let block = block.copy();
 936            let native_window = self.0.lock().native_window;
 937            let executor = self.0.lock().executor.clone();
 938            executor
 939                .spawn(async move {
 940                    let _: () = msg_send![
 941                        alert,
 942                        beginSheetModalForWindow: native_window
 943                        completionHandler: block
 944                    ];
 945                })
 946                .detach();
 947
 948            Some(done_rx)
 949        }
 950    }
 951
 952    fn activate(&self) {
 953        let window = self.0.lock().native_window;
 954        let executor = self.0.lock().executor.clone();
 955        executor
 956            .spawn(async move {
 957                unsafe {
 958                    let _: () = msg_send![window, makeKeyAndOrderFront: nil];
 959                }
 960            })
 961            .detach();
 962    }
 963
 964    fn is_active(&self) -> bool {
 965        unsafe { self.0.lock().native_window.isKeyWindow() == YES }
 966    }
 967
 968    fn set_title(&mut self, title: &str) {
 969        unsafe {
 970            let app = NSApplication::sharedApplication(nil);
 971            let window = self.0.lock().native_window;
 972            let title = ns_string(title);
 973            let _: () = msg_send![app, changeWindowsItem:window title:title filename:false];
 974            let _: () = msg_send![window, setTitle: title];
 975            self.0.lock().move_traffic_light();
 976        }
 977    }
 978
 979    fn set_app_id(&mut self, _app_id: &str) {}
 980
 981    fn set_background_appearance(&mut self, background_appearance: WindowBackgroundAppearance) {
 982        let this = self.0.as_ref().lock();
 983        let blur_radius = if background_appearance == WindowBackgroundAppearance::Blurred {
 984            80
 985        } else {
 986            0
 987        };
 988        let opaque = if background_appearance == WindowBackgroundAppearance::Opaque {
 989            YES
 990        } else {
 991            NO
 992        };
 993        unsafe {
 994            this.native_window.setOpaque_(opaque);
 995            // Shadows for transparent windows cause artifacts and performance issues
 996            this.native_window.setHasShadow_(opaque);
 997            let clear_color = if opaque == YES {
 998                NSColor::colorWithSRGBRed_green_blue_alpha_(nil, 0f64, 0f64, 0f64, 1f64)
 999            } else {
1000                NSColor::clearColor(nil)
1001            };
1002            this.native_window.setBackgroundColor_(clear_color);
1003            let window_number = this.native_window.windowNumber();
1004            CGSSetWindowBackgroundBlurRadius(CGSMainConnectionID(), window_number, blur_radius);
1005        }
1006    }
1007
1008    fn set_edited(&mut self, edited: bool) {
1009        unsafe {
1010            let window = self.0.lock().native_window;
1011            msg_send![window, setDocumentEdited: edited as BOOL]
1012        }
1013
1014        // Changing the document edited state resets the traffic light position,
1015        // so we have to move it again.
1016        self.0.lock().move_traffic_light();
1017    }
1018
1019    fn show_character_palette(&self) {
1020        let this = self.0.lock();
1021        let window = this.native_window;
1022        this.executor
1023            .spawn(async move {
1024                unsafe {
1025                    let app = NSApplication::sharedApplication(nil);
1026                    let _: () = msg_send![app, orderFrontCharacterPalette: window];
1027                }
1028            })
1029            .detach();
1030    }
1031
1032    fn minimize(&self) {
1033        let window = self.0.lock().native_window;
1034        unsafe {
1035            window.miniaturize_(nil);
1036        }
1037    }
1038
1039    fn zoom(&self) {
1040        let this = self.0.lock();
1041        let window = this.native_window;
1042        this.executor
1043            .spawn(async move {
1044                unsafe {
1045                    window.zoom_(nil);
1046                }
1047            })
1048            .detach();
1049    }
1050
1051    fn toggle_fullscreen(&self) {
1052        let this = self.0.lock();
1053        let window = this.native_window;
1054        this.executor
1055            .spawn(async move {
1056                unsafe {
1057                    window.toggleFullScreen_(nil);
1058                }
1059            })
1060            .detach();
1061    }
1062
1063    fn is_fullscreen(&self) -> bool {
1064        let this = self.0.lock();
1065        let window = this.native_window;
1066
1067        unsafe {
1068            window
1069                .styleMask()
1070                .contains(NSWindowStyleMask::NSFullScreenWindowMask)
1071        }
1072    }
1073
1074    fn on_request_frame(&self, callback: Box<dyn FnMut()>) {
1075        self.0.as_ref().lock().request_frame_callback = Some(callback);
1076    }
1077
1078    fn on_input(&self, callback: Box<dyn FnMut(PlatformInput) -> crate::DispatchEventResult>) {
1079        self.0.as_ref().lock().event_callback = Some(callback);
1080    }
1081
1082    fn on_active_status_change(&self, callback: Box<dyn FnMut(bool)>) {
1083        self.0.as_ref().lock().activate_callback = Some(callback);
1084    }
1085
1086    fn on_resize(&self, callback: Box<dyn FnMut(Size<Pixels>, f32)>) {
1087        self.0.as_ref().lock().resize_callback = Some(callback);
1088    }
1089
1090    fn on_moved(&self, callback: Box<dyn FnMut()>) {
1091        self.0.as_ref().lock().moved_callback = Some(callback);
1092    }
1093
1094    fn on_should_close(&self, callback: Box<dyn FnMut() -> bool>) {
1095        self.0.as_ref().lock().should_close_callback = Some(callback);
1096    }
1097
1098    fn on_close(&self, callback: Box<dyn FnOnce()>) {
1099        self.0.as_ref().lock().close_callback = Some(callback);
1100    }
1101
1102    fn on_appearance_changed(&self, callback: Box<dyn FnMut()>) {
1103        self.0.lock().appearance_changed_callback = Some(callback);
1104    }
1105
1106    fn draw(&self, scene: &crate::Scene) {
1107        let mut this = self.0.lock();
1108        this.renderer.draw(scene);
1109    }
1110
1111    fn sprite_atlas(&self) -> Arc<dyn PlatformAtlas> {
1112        self.0.lock().renderer.sprite_atlas().clone()
1113    }
1114}
1115
1116impl rwh::HasWindowHandle for MacWindow {
1117    fn window_handle(&self) -> Result<rwh::WindowHandle<'_>, rwh::HandleError> {
1118        // SAFETY: The AppKitWindowHandle is a wrapper around a pointer to an NSView
1119        unsafe {
1120            Ok(rwh::WindowHandle::borrow_raw(rwh::RawWindowHandle::AppKit(
1121                rwh::AppKitWindowHandle::new(self.0.lock().native_view.cast()),
1122            )))
1123        }
1124    }
1125}
1126
1127impl rwh::HasDisplayHandle for MacWindow {
1128    fn display_handle(&self) -> Result<rwh::DisplayHandle<'_>, rwh::HandleError> {
1129        // SAFETY: This is a no-op on macOS
1130        unsafe {
1131            Ok(rwh::DisplayHandle::borrow_raw(
1132                rwh::AppKitDisplayHandle::new().into(),
1133            ))
1134        }
1135    }
1136}
1137
1138fn get_scale_factor(native_window: id) -> f32 {
1139    let factor = unsafe {
1140        let screen: id = msg_send![native_window, screen];
1141        NSScreen::backingScaleFactor(screen) as f32
1142    };
1143
1144    // We are not certain what triggers this, but it seems that sometimes
1145    // this method would return 0 (https://github.com/zed-industries/zed/issues/6412)
1146    // It seems most likely that this would happen if the window has no screen
1147    // (if it is off-screen), though we'd expect to see viewDidChangeBackingProperties before
1148    // it was rendered for real.
1149    // Regardless, attempt to avoid the issue here.
1150    if factor == 0.0 {
1151        2.
1152    } else {
1153        factor
1154    }
1155}
1156
1157unsafe fn get_window_state(object: &Object) -> Arc<Mutex<MacWindowState>> {
1158    let raw: *mut c_void = *object.get_ivar(WINDOW_STATE_IVAR);
1159    let rc1 = Arc::from_raw(raw as *mut Mutex<MacWindowState>);
1160    let rc2 = rc1.clone();
1161    mem::forget(rc1);
1162    rc2
1163}
1164
1165unsafe fn drop_window_state(object: &Object) {
1166    let raw: *mut c_void = *object.get_ivar(WINDOW_STATE_IVAR);
1167    Arc::from_raw(raw as *mut Mutex<MacWindowState>);
1168}
1169
1170extern "C" fn yes(_: &Object, _: Sel) -> BOOL {
1171    YES
1172}
1173
1174extern "C" fn dealloc_window(this: &Object, _: Sel) {
1175    unsafe {
1176        drop_window_state(this);
1177        let _: () = msg_send![super(this, class!(NSWindow)), dealloc];
1178    }
1179}
1180
1181extern "C" fn dealloc_view(this: &Object, _: Sel) {
1182    unsafe {
1183        drop_window_state(this);
1184        let _: () = msg_send![super(this, class!(NSView)), dealloc];
1185    }
1186}
1187
1188extern "C" fn handle_key_equivalent(this: &Object, _: Sel, native_event: id) -> BOOL {
1189    handle_key_event(this, native_event, true)
1190}
1191
1192extern "C" fn handle_key_down(this: &Object, _: Sel, native_event: id) {
1193    handle_key_event(this, native_event, false);
1194}
1195
1196// Things to test if you're modifying this method:
1197//  Brazilian layout:
1198//   - `" space` should type a quote
1199//   - `" backspace` should delete the marked quote
1200//   - `" up` should type the quote, unmark it, and move up one line
1201//   - `" cmd-down` should not leave a marked quote behind (it maybe should dispatch the key though?)
1202//   - `cmd-ctrl-space` and clicking on an emoji should type it
1203//  Czech (QWERTY) layout:
1204//   - in vim mode `option-4`  should go to end of line (same as $)
1205extern "C" fn handle_key_event(this: &Object, native_event: id, key_equivalent: bool) -> BOOL {
1206    let window_state = unsafe { get_window_state(this) };
1207    let mut lock = window_state.as_ref().lock();
1208
1209    let window_height = lock.content_size().height;
1210    let event = unsafe { PlatformInput::from_native(native_event, Some(window_height)) };
1211
1212    if let Some(PlatformInput::KeyDown(mut event)) = event {
1213        // For certain keystrokes, macOS will first dispatch a "key equivalent" event.
1214        // If that event isn't handled, it will then dispatch a "key down" event. GPUI
1215        // makes no distinction between these two types of events, so we need to ignore
1216        // the "key down" event if we've already just processed its "key equivalent" version.
1217        if key_equivalent {
1218            lock.last_key_equivalent = Some(event.clone());
1219        } else if lock.last_key_equivalent.take().as_ref() == Some(&event) {
1220            return NO;
1221        }
1222
1223        let keydown = event.keystroke.clone();
1224        let fn_modifier = keydown.modifiers.function;
1225        // Ignore events from held-down keys after some of the initially-pressed keys
1226        // were released.
1227        if event.is_held {
1228            if lock.last_fresh_keydown.as_ref() != Some(&keydown) {
1229                return YES;
1230            }
1231        } else {
1232            lock.last_fresh_keydown = Some(keydown.clone());
1233        }
1234        lock.input_during_keydown = Some(SmallVec::new());
1235        drop(lock);
1236
1237        // Send the event to the input context for IME handling, unless the `fn` modifier is
1238        // being pressed.
1239        // this will call back into `insert_text`, etc.
1240        if !fn_modifier {
1241            unsafe {
1242                let input_context: id = msg_send![this, inputContext];
1243                let _: BOOL = msg_send![input_context, handleEvent: native_event];
1244            }
1245        }
1246
1247        let mut handled = false;
1248        let mut lock = window_state.lock();
1249        let previous_keydown_inserted_text = lock.previous_keydown_inserted_text.take();
1250        let mut input_during_keydown = lock.input_during_keydown.take().unwrap();
1251        let mut callback = lock.event_callback.take();
1252        drop(lock);
1253
1254        let last_ime = input_during_keydown.pop();
1255        // on a brazilian keyboard typing `"` and then hitting `up` will cause two IME
1256        // events, one to unmark the quote, and one to send the up arrow.
1257        for ime in input_during_keydown {
1258            send_to_input_handler(this, ime);
1259        }
1260
1261        let is_composing =
1262            with_input_handler(this, |input_handler| input_handler.marked_text_range())
1263                .flatten()
1264                .is_some();
1265
1266        if let Some(ime) = last_ime {
1267            if let ImeInput::InsertText(text, _) = &ime {
1268                if !is_composing {
1269                    window_state.lock().previous_keydown_inserted_text = Some(text.clone());
1270                    if let Some(callback) = callback.as_mut() {
1271                        event.keystroke.ime_key = Some(text.clone());
1272                        handled = !callback(PlatformInput::KeyDown(event)).propagate;
1273                    }
1274                }
1275            }
1276
1277            if !handled {
1278                handled = true;
1279                send_to_input_handler(this, ime);
1280            }
1281        } else if !is_composing {
1282            let is_held = event.is_held;
1283
1284            if let Some(callback) = callback.as_mut() {
1285                handled = !callback(PlatformInput::KeyDown(event)).propagate;
1286            }
1287
1288            if !handled && is_held {
1289                if let Some(text) = previous_keydown_inserted_text {
1290                    // MacOS IME is a bit funky, and even when you've told it there's nothing to
1291                    // enter it will still swallow certain keys (e.g. 'f', 'j') and not others
1292                    // (e.g. 'n'). This is a problem for certain kinds of views, like the terminal.
1293                    with_input_handler(this, |input_handler| {
1294                        if input_handler.selected_text_range().is_none() {
1295                            handled = true;
1296                            input_handler.replace_text_in_range(None, &text)
1297                        }
1298                    });
1299                    window_state.lock().previous_keydown_inserted_text = Some(text);
1300                }
1301            }
1302        }
1303
1304        window_state.lock().event_callback = callback;
1305
1306        handled as BOOL
1307    } else {
1308        NO
1309    }
1310}
1311
1312extern "C" fn handle_view_event(this: &Object, _: Sel, native_event: id) {
1313    let window_state = unsafe { get_window_state(this) };
1314    let weak_window_state = Arc::downgrade(&window_state);
1315    let mut lock = window_state.as_ref().lock();
1316    let window_height = lock.content_size().height;
1317    let event = unsafe { PlatformInput::from_native(native_event, Some(window_height)) };
1318
1319    if let Some(mut event) = event {
1320        match &mut event {
1321            PlatformInput::MouseDown(
1322                event @ MouseDownEvent {
1323                    button: MouseButton::Left,
1324                    modifiers: Modifiers { control: true, .. },
1325                    ..
1326                },
1327            ) => {
1328                // On mac, a ctrl-left click should be handled as a right click.
1329                *event = MouseDownEvent {
1330                    button: MouseButton::Right,
1331                    modifiers: Modifiers {
1332                        control: false,
1333                        ..event.modifiers
1334                    },
1335                    click_count: 1,
1336                    ..*event
1337                };
1338            }
1339
1340            // Handles focusing click.
1341            PlatformInput::MouseDown(
1342                event @ MouseDownEvent {
1343                    button: MouseButton::Left,
1344                    ..
1345                },
1346            ) if (lock.first_mouse) => {
1347                *event = MouseDownEvent {
1348                    first_mouse: true,
1349                    ..*event
1350                };
1351                lock.first_mouse = false;
1352            }
1353
1354            // Because we map a ctrl-left_down to a right_down -> right_up let's ignore
1355            // the ctrl-left_up to avoid having a mismatch in button down/up events if the
1356            // user is still holding ctrl when releasing the left mouse button
1357            PlatformInput::MouseUp(
1358                event @ MouseUpEvent {
1359                    button: MouseButton::Left,
1360                    modifiers: Modifiers { control: true, .. },
1361                    ..
1362                },
1363            ) => {
1364                *event = MouseUpEvent {
1365                    button: MouseButton::Right,
1366                    modifiers: Modifiers {
1367                        control: false,
1368                        ..event.modifiers
1369                    },
1370                    click_count: 1,
1371                    ..*event
1372                };
1373            }
1374
1375            _ => {}
1376        };
1377
1378        match &event {
1379            PlatformInput::MouseMove(
1380                event @ MouseMoveEvent {
1381                    pressed_button: Some(_),
1382                    ..
1383                },
1384            ) => {
1385                // Synthetic drag is used for selecting long buffer contents while buffer is being scrolled.
1386                // External file drag and drop is able to emit its own synthetic mouse events which will conflict
1387                // with these ones.
1388                if !lock.external_files_dragged {
1389                    lock.synthetic_drag_counter += 1;
1390                    let executor = lock.executor.clone();
1391                    executor
1392                        .spawn(synthetic_drag(
1393                            weak_window_state,
1394                            lock.synthetic_drag_counter,
1395                            event.clone(),
1396                        ))
1397                        .detach();
1398                }
1399            }
1400
1401            PlatformInput::MouseUp(MouseUpEvent { .. }) => {
1402                lock.synthetic_drag_counter += 1;
1403            }
1404
1405            PlatformInput::ModifiersChanged(ModifiersChangedEvent { modifiers }) => {
1406                // Only raise modifiers changed event when they have actually changed
1407                if let Some(PlatformInput::ModifiersChanged(ModifiersChangedEvent {
1408                    modifiers: prev_modifiers,
1409                })) = &lock.previous_modifiers_changed_event
1410                {
1411                    if prev_modifiers == modifiers {
1412                        return;
1413                    }
1414                }
1415
1416                lock.previous_modifiers_changed_event = Some(event.clone());
1417            }
1418
1419            _ => {}
1420        }
1421
1422        if let Some(mut callback) = lock.event_callback.take() {
1423            drop(lock);
1424            callback(event);
1425            window_state.lock().event_callback = Some(callback);
1426        }
1427    }
1428}
1429
1430// Allows us to receive `cmd-.` (the shortcut for closing a dialog)
1431// https://bugs.eclipse.org/bugs/show_bug.cgi?id=300620#c6
1432extern "C" fn cancel_operation(this: &Object, _sel: Sel, _sender: id) {
1433    let window_state = unsafe { get_window_state(this) };
1434    let mut lock = window_state.as_ref().lock();
1435
1436    let keystroke = Keystroke {
1437        modifiers: Default::default(),
1438        key: ".".into(),
1439        ime_key: None,
1440    };
1441    let event = PlatformInput::KeyDown(KeyDownEvent {
1442        keystroke: keystroke.clone(),
1443        is_held: false,
1444    });
1445
1446    lock.last_fresh_keydown = Some(keystroke);
1447    if let Some(mut callback) = lock.event_callback.take() {
1448        drop(lock);
1449        callback(event);
1450        window_state.lock().event_callback = Some(callback);
1451    }
1452}
1453
1454extern "C" fn window_did_change_occlusion_state(this: &Object, _: Sel, _: id) {
1455    let window_state = unsafe { get_window_state(this) };
1456    let lock = &mut *window_state.lock();
1457    unsafe {
1458        if lock
1459            .native_window
1460            .occlusionState()
1461            .contains(NSWindowOcclusionState::NSWindowOcclusionStateVisible)
1462        {
1463            lock.start_display_link();
1464        } else {
1465            lock.stop_display_link();
1466        }
1467    }
1468}
1469
1470extern "C" fn window_did_resize(this: &Object, _: Sel, _: id) {
1471    let window_state = unsafe { get_window_state(this) };
1472    window_state.as_ref().lock().move_traffic_light();
1473}
1474
1475extern "C" fn window_will_enter_fullscreen(this: &Object, _: Sel, _: id) {
1476    window_fullscreen_changed(this, true);
1477}
1478
1479extern "C" fn window_will_exit_fullscreen(this: &Object, _: Sel, _: id) {
1480    window_fullscreen_changed(this, false);
1481}
1482
1483fn window_fullscreen_changed(this: &Object, is_fullscreen: bool) {
1484    let window_state = unsafe { get_window_state(this) };
1485    let mut lock = window_state.as_ref().lock();
1486    if let Some(mut callback) = lock.fullscreen_callback.take() {
1487        drop(lock);
1488        callback(is_fullscreen);
1489        window_state.lock().fullscreen_callback = Some(callback);
1490    }
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    with_input_handler(this, |input_handler| input_handler.marked_text_range())
1674        .flatten()
1675        .is_some() as BOOL
1676}
1677
1678extern "C" fn marked_range(this: &Object, _: Sel) -> NSRange {
1679    with_input_handler(this, |input_handler| input_handler.marked_text_range())
1680        .flatten()
1681        .map_or(NSRange::invalid(), |range| range.into())
1682}
1683
1684extern "C" fn selected_range(this: &Object, _: Sel) -> NSRange {
1685    with_input_handler(this, |input_handler| input_handler.selected_text_range())
1686        .flatten()
1687        .map_or(NSRange::invalid(), |range| range.into())
1688}
1689
1690extern "C" fn first_rect_for_character_range(
1691    this: &Object,
1692    _: Sel,
1693    range: NSRange,
1694    _: id,
1695) -> NSRect {
1696    let frame = unsafe {
1697        let window = get_window_state(this).lock().native_window;
1698        NSView::frame(window)
1699    };
1700    with_input_handler(this, |input_handler| {
1701        input_handler.bounds_for_range(range.to_range()?)
1702    })
1703    .flatten()
1704    .map_or(
1705        NSRect::new(NSPoint::new(0., 0.), NSSize::new(0., 0.)),
1706        |bounds| {
1707            NSRect::new(
1708                NSPoint::new(
1709                    frame.origin.x + bounds.origin.x.0 as f64,
1710                    frame.origin.y + frame.size.height
1711                        - bounds.origin.y.0 as f64
1712                        - bounds.size.height.0 as f64,
1713                ),
1714                NSSize::new(bounds.size.width.0 as f64, bounds.size.height.0 as f64),
1715            )
1716        },
1717    )
1718}
1719
1720extern "C" fn insert_text(this: &Object, _: Sel, text: id, replacement_range: NSRange) {
1721    unsafe {
1722        let is_attributed_string: BOOL =
1723            msg_send![text, isKindOfClass: [class!(NSAttributedString)]];
1724        let text: id = if is_attributed_string == YES {
1725            msg_send![text, string]
1726        } else {
1727            text
1728        };
1729        let text = CStr::from_ptr(text.UTF8String() as *mut c_char)
1730            .to_str()
1731            .unwrap();
1732        let replacement_range = replacement_range.to_range();
1733        send_to_input_handler(
1734            this,
1735            ImeInput::InsertText(text.to_string(), replacement_range),
1736        );
1737    }
1738}
1739
1740extern "C" fn set_marked_text(
1741    this: &Object,
1742    _: Sel,
1743    text: id,
1744    selected_range: NSRange,
1745    replacement_range: NSRange,
1746) {
1747    unsafe {
1748        let is_attributed_string: BOOL =
1749            msg_send![text, isKindOfClass: [class!(NSAttributedString)]];
1750        let text: id = if is_attributed_string == YES {
1751            msg_send![text, string]
1752        } else {
1753            text
1754        };
1755        let selected_range = selected_range.to_range();
1756        let replacement_range = replacement_range.to_range();
1757        let text = CStr::from_ptr(text.UTF8String() as *mut c_char)
1758            .to_str()
1759            .unwrap();
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)?;
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
1890extern "C" fn window_did_miniaturize(this: &Object, _: Sel, _: id) {
1891    let window_state = unsafe { get_window_state(this) };
1892
1893    window_state.lock().minimized = true;
1894}
1895
1896extern "C" fn window_did_deminiaturize(this: &Object, _: Sel, _: id) {
1897    let window_state = unsafe { get_window_state(this) };
1898
1899    window_state.lock().minimized = false;
1900}
1901
1902async fn synthetic_drag(
1903    window_state: Weak<Mutex<MacWindowState>>,
1904    drag_id: usize,
1905    event: MouseMoveEvent,
1906) {
1907    loop {
1908        Timer::after(Duration::from_millis(16)).await;
1909        if let Some(window_state) = window_state.upgrade() {
1910            let mut lock = window_state.lock();
1911            if lock.synthetic_drag_counter == drag_id {
1912                if let Some(mut callback) = lock.event_callback.take() {
1913                    drop(lock);
1914                    callback(PlatformInput::MouseMove(event.clone()));
1915                    window_state.lock().event_callback = Some(callback);
1916                }
1917            } else {
1918                break;
1919            }
1920        }
1921    }
1922}
1923
1924fn send_new_event(window_state_lock: &Mutex<MacWindowState>, e: PlatformInput) -> bool {
1925    let window_state = window_state_lock.lock().event_callback.take();
1926    if let Some(mut callback) = window_state {
1927        callback(e);
1928        window_state_lock.lock().event_callback = Some(callback);
1929        true
1930    } else {
1931        false
1932    }
1933}
1934
1935fn drag_event_position(window_state: &Mutex<MacWindowState>, dragging_info: id) -> Point<Pixels> {
1936    let drag_location: NSPoint = unsafe { msg_send![dragging_info, draggingLocation] };
1937    convert_mouse_position(drag_location, window_state.lock().content_size().height)
1938}
1939
1940fn with_input_handler<F, R>(window: &Object, f: F) -> Option<R>
1941where
1942    F: FnOnce(&mut PlatformInputHandler) -> R,
1943{
1944    let window_state = unsafe { get_window_state(window) };
1945    let mut lock = window_state.as_ref().lock();
1946    if let Some(mut input_handler) = lock.input_handler.take() {
1947        drop(lock);
1948        let result = f(&mut input_handler);
1949        window_state.lock().input_handler = Some(input_handler);
1950        Some(result)
1951    } else {
1952        None
1953    }
1954}
1955
1956fn send_to_input_handler(window: &Object, ime: ImeInput) {
1957    unsafe {
1958        let window_state = get_window_state(window);
1959        let mut lock = window_state.lock();
1960        if let Some(ime_input) = lock.input_during_keydown.as_mut() {
1961            ime_input.push(ime);
1962            return;
1963        }
1964        if let Some(mut input_handler) = lock.input_handler.take() {
1965            drop(lock);
1966            match ime {
1967                ImeInput::InsertText(text, range) => {
1968                    input_handler.replace_text_in_range(range, &text)
1969                }
1970                ImeInput::SetMarkedText(text, range, marked_range) => {
1971                    input_handler.replace_and_mark_text_in_range(range, &text, marked_range)
1972                }
1973                ImeInput::UnmarkText => input_handler.unmark_text(),
1974            }
1975            window_state.lock().input_handler = Some(input_handler);
1976        }
1977    }
1978}
1979
1980unsafe fn display_id_for_screen(screen: id) -> CGDirectDisplayID {
1981    let device_description = NSScreen::deviceDescription(screen);
1982    let screen_number_key: id = NSString::alloc(nil).init_str("NSScreenNumber");
1983    let screen_number = device_description.objectForKey_(screen_number_key);
1984    let screen_number: NSUInteger = msg_send![screen_number, unsignedIntegerValue];
1985    screen_number as CGDirectDisplayID
1986}