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