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