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