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