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