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