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