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