window.rs

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