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