window.rs

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