window.rs

   1use super::{BoolExt, MacDisplay, NSRange, NSStringExt, ns_string, renderer};
   2use crate::{
   3    AnyWindowHandle, Bounds, DisplayLink, ExternalPaths, FileDropEvent, ForegroundExecutor,
   4    KeyDownEvent, Keystroke, Modifiers, ModifiersChangedEvent, MouseButton, MouseDownEvent,
   5    MouseMoveEvent, MouseUpEvent, Pixels, PlatformAtlas, PlatformDisplay, PlatformInput,
   6    PlatformWindow, Point, PromptLevel, RequestFrameOptions, ScaledPixels, Size, Timer,
   7    WindowAppearance, WindowBackgroundAppearance, WindowBounds, WindowKind, WindowParams,
   8    platform::PlatformInputHandler, point, px, size,
   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        NSOperatingSystemVersion, NSPoint, NSProcessInfo, 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::{BOOL, Class, NO, Object, Protocol, Sel, 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::{CStr, c_void},
  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 main_window.is_null() {
 748                return None;
 749            }
 750
 751            if msg_send![main_window, isKindOfClass: WINDOW_CLASS] {
 752                let handle = get_window_state(&*main_window).lock().handle;
 753                Some(handle)
 754            } else {
 755                None
 756            }
 757        }
 758    }
 759
 760    pub fn ordered_windows() -> Vec<AnyWindowHandle> {
 761        unsafe {
 762            let app = NSApplication::sharedApplication(nil);
 763            let windows: id = msg_send![app, orderedWindows];
 764            let count: NSUInteger = msg_send![windows, count];
 765
 766            let mut window_handles = Vec::new();
 767            for i in 0..count {
 768                let window: id = msg_send![windows, objectAtIndex:i];
 769                if msg_send![window, isKindOfClass: WINDOW_CLASS] {
 770                    let handle = get_window_state(&*window).lock().handle;
 771                    window_handles.push(handle);
 772                }
 773            }
 774
 775            window_handles
 776        }
 777    }
 778}
 779
 780impl Drop for MacWindow {
 781    fn drop(&mut self) {
 782        let mut this = self.0.lock();
 783        this.renderer.destroy();
 784        let window = this.native_window;
 785        this.display_link.take();
 786        unsafe {
 787            this.native_window.setDelegate_(nil);
 788        }
 789        this.input_handler.take();
 790        this.executor
 791            .spawn(async move {
 792                unsafe {
 793                    window.close();
 794                    window.autorelease();
 795                }
 796            })
 797            .detach();
 798    }
 799}
 800
 801impl PlatformWindow for MacWindow {
 802    fn bounds(&self) -> Bounds<Pixels> {
 803        self.0.as_ref().lock().bounds()
 804    }
 805
 806    fn window_bounds(&self) -> WindowBounds {
 807        self.0.as_ref().lock().window_bounds()
 808    }
 809
 810    fn is_maximized(&self) -> bool {
 811        self.0.as_ref().lock().is_maximized()
 812    }
 813
 814    fn content_size(&self) -> Size<Pixels> {
 815        self.0.as_ref().lock().content_size()
 816    }
 817
 818    fn resize(&mut self, size: Size<Pixels>) {
 819        let this = self.0.lock();
 820        let window = this.native_window;
 821        this.executor
 822            .spawn(async move {
 823                unsafe {
 824                    window.setContentSize_(NSSize {
 825                        width: size.width.0 as f64,
 826                        height: size.height.0 as f64,
 827                    });
 828                }
 829            })
 830            .detach();
 831    }
 832
 833    fn scale_factor(&self) -> f32 {
 834        self.0.as_ref().lock().scale_factor()
 835    }
 836
 837    fn appearance(&self) -> WindowAppearance {
 838        unsafe {
 839            let appearance: id = msg_send![self.0.lock().native_window, effectiveAppearance];
 840            WindowAppearance::from_native(appearance)
 841        }
 842    }
 843
 844    fn display(&self) -> Option<Rc<dyn PlatformDisplay>> {
 845        unsafe {
 846            let screen = self.0.lock().native_window.screen();
 847            if screen.is_null() {
 848                return None;
 849            }
 850            let device_description: id = msg_send![screen, deviceDescription];
 851            let screen_number: id = NSDictionary::valueForKey_(
 852                device_description,
 853                NSString::alloc(nil).init_str("NSScreenNumber"),
 854            );
 855
 856            let screen_number: u32 = msg_send![screen_number, unsignedIntValue];
 857
 858            Some(Rc::new(MacDisplay(screen_number)))
 859        }
 860    }
 861
 862    fn mouse_position(&self) -> Point<Pixels> {
 863        let position = unsafe {
 864            self.0
 865                .lock()
 866                .native_window
 867                .mouseLocationOutsideOfEventStream()
 868        };
 869        convert_mouse_position(position, self.content_size().height)
 870    }
 871
 872    fn modifiers(&self) -> Modifiers {
 873        unsafe {
 874            let modifiers: NSEventModifierFlags = msg_send![class!(NSEvent), modifierFlags];
 875
 876            let control = modifiers.contains(NSEventModifierFlags::NSControlKeyMask);
 877            let alt = modifiers.contains(NSEventModifierFlags::NSAlternateKeyMask);
 878            let shift = modifiers.contains(NSEventModifierFlags::NSShiftKeyMask);
 879            let command = modifiers.contains(NSEventModifierFlags::NSCommandKeyMask);
 880            let function = modifiers.contains(NSEventModifierFlags::NSFunctionKeyMask);
 881
 882            Modifiers {
 883                control,
 884                alt,
 885                shift,
 886                platform: command,
 887                function,
 888            }
 889        }
 890    }
 891
 892    fn set_input_handler(&mut self, input_handler: PlatformInputHandler) {
 893        self.0.as_ref().lock().input_handler = Some(input_handler);
 894    }
 895
 896    fn take_input_handler(&mut self) -> Option<PlatformInputHandler> {
 897        self.0.as_ref().lock().input_handler.take()
 898    }
 899
 900    fn prompt(
 901        &self,
 902        level: PromptLevel,
 903        msg: &str,
 904        detail: Option<&str>,
 905        answers: &[&str],
 906    ) -> Option<oneshot::Receiver<usize>> {
 907        // macOs applies overrides to modal window buttons after they are added.
 908        // Two most important for this logic are:
 909        // * Buttons with "Cancel" title will be displayed as the last buttons in the modal
 910        // * Last button added to the modal via `addButtonWithTitle` stays focused
 911        // * Focused buttons react on "space"/" " keypresses
 912        // * Usage of `keyEquivalent`, `makeFirstResponder` or `setInitialFirstResponder` does not change the focus
 913        //
 914        // See also https://developer.apple.com/documentation/appkit/nsalert/1524532-addbuttonwithtitle#discussion
 915        // ```
 916        // By default, the first button has a key equivalent of Return,
 917        // any button with a title of “Cancel” has a key equivalent of Escape,
 918        // 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).
 919        // ```
 920        //
 921        // To avoid situations when the last element added is "Cancel" and it gets the focus
 922        // (hence stealing both ESC and Space shortcuts), we find and add one non-Cancel button
 923        // last, so it gets focus and a Space shortcut.
 924        // This way, "Save this file? Yes/No/Cancel"-ish modals will get all three buttons mapped with a key.
 925        let latest_non_cancel_label = answers
 926            .iter()
 927            .enumerate()
 928            .rev()
 929            .find(|(_, label)| **label != "Cancel")
 930            .filter(|&(label_index, _)| label_index > 0);
 931
 932        unsafe {
 933            let alert: id = msg_send![class!(NSAlert), alloc];
 934            let alert: id = msg_send![alert, init];
 935            let alert_style = match level {
 936                PromptLevel::Info => 1,
 937                PromptLevel::Warning => 0,
 938                PromptLevel::Critical => 2,
 939            };
 940            let _: () = msg_send![alert, setAlertStyle: alert_style];
 941            let _: () = msg_send![alert, setMessageText: ns_string(msg)];
 942            if let Some(detail) = detail {
 943                let _: () = msg_send![alert, setInformativeText: ns_string(detail)];
 944            }
 945
 946            for (ix, answer) in answers
 947                .iter()
 948                .enumerate()
 949                .filter(|&(ix, _)| Some(ix) != latest_non_cancel_label.map(|(ix, _)| ix))
 950            {
 951                let button: id = msg_send![alert, addButtonWithTitle: ns_string(answer)];
 952                let _: () = msg_send![button, setTag: ix as NSInteger];
 953            }
 954            if let Some((ix, answer)) = latest_non_cancel_label {
 955                let button: id = msg_send![alert, addButtonWithTitle: ns_string(answer)];
 956                let _: () = msg_send![button, setTag: ix as NSInteger];
 957            }
 958
 959            let (done_tx, done_rx) = oneshot::channel();
 960            let done_tx = Cell::new(Some(done_tx));
 961            let block = ConcreteBlock::new(move |answer: NSInteger| {
 962                if let Some(done_tx) = done_tx.take() {
 963                    let _ = done_tx.send(answer.try_into().unwrap());
 964                }
 965            });
 966            let block = block.copy();
 967            let native_window = self.0.lock().native_window;
 968            let executor = self.0.lock().executor.clone();
 969            executor
 970                .spawn(async move {
 971                    let _: () = msg_send![
 972                        alert,
 973                        beginSheetModalForWindow: native_window
 974                        completionHandler: block
 975                    ];
 976                })
 977                .detach();
 978
 979            Some(done_rx)
 980        }
 981    }
 982
 983    fn activate(&self) {
 984        let window = self.0.lock().native_window;
 985        let executor = self.0.lock().executor.clone();
 986        executor
 987            .spawn(async move {
 988                unsafe {
 989                    let _: () = msg_send![window, makeKeyAndOrderFront: nil];
 990                }
 991            })
 992            .detach();
 993    }
 994
 995    fn is_active(&self) -> bool {
 996        unsafe { self.0.lock().native_window.isKeyWindow() == YES }
 997    }
 998
 999    // is_hovered is unused on macOS. See Window::is_window_hovered.
1000    fn is_hovered(&self) -> bool {
1001        false
1002    }
1003
1004    fn set_title(&mut self, title: &str) {
1005        unsafe {
1006            let app = NSApplication::sharedApplication(nil);
1007            let window = self.0.lock().native_window;
1008            let title = ns_string(title);
1009            let _: () = msg_send![app, changeWindowsItem:window title:title filename:false];
1010            let _: () = msg_send![window, setTitle: title];
1011            self.0.lock().move_traffic_light();
1012        }
1013    }
1014
1015    fn set_app_id(&mut self, _app_id: &str) {}
1016
1017    fn set_background_appearance(&self, background_appearance: WindowBackgroundAppearance) {
1018        let mut this = self.0.as_ref().lock();
1019        this.renderer
1020            .update_transparency(background_appearance != WindowBackgroundAppearance::Opaque);
1021
1022        let blur_radius = if background_appearance == WindowBackgroundAppearance::Blurred {
1023            80
1024        } else {
1025            0
1026        };
1027        let opaque = (background_appearance == WindowBackgroundAppearance::Opaque).to_objc();
1028
1029        unsafe {
1030            this.native_window.setOpaque_(opaque);
1031            // Shadows for transparent windows cause artifacts and performance issues
1032            this.native_window.setHasShadow_(opaque);
1033            let clear_color = if opaque == YES {
1034                NSColor::colorWithSRGBRed_green_blue_alpha_(nil, 0f64, 0f64, 0f64, 1f64)
1035            } else {
1036                NSColor::clearColor(nil)
1037            };
1038            this.native_window.setBackgroundColor_(clear_color);
1039            let window_number = this.native_window.windowNumber();
1040            CGSSetWindowBackgroundBlurRadius(CGSMainConnectionID(), window_number, blur_radius);
1041        }
1042    }
1043
1044    fn set_edited(&mut self, edited: bool) {
1045        unsafe {
1046            let window = self.0.lock().native_window;
1047            msg_send![window, setDocumentEdited: edited as BOOL]
1048        }
1049
1050        // Changing the document edited state resets the traffic light position,
1051        // so we have to move it again.
1052        self.0.lock().move_traffic_light();
1053    }
1054
1055    fn show_character_palette(&self) {
1056        let this = self.0.lock();
1057        let window = this.native_window;
1058        this.executor
1059            .spawn(async move {
1060                unsafe {
1061                    let app = NSApplication::sharedApplication(nil);
1062                    let _: () = msg_send![app, orderFrontCharacterPalette: window];
1063                }
1064            })
1065            .detach();
1066    }
1067
1068    fn minimize(&self) {
1069        let window = self.0.lock().native_window;
1070        unsafe {
1071            window.miniaturize_(nil);
1072        }
1073    }
1074
1075    fn zoom(&self) {
1076        let this = self.0.lock();
1077        let window = this.native_window;
1078        this.executor
1079            .spawn(async move {
1080                unsafe {
1081                    window.zoom_(nil);
1082                }
1083            })
1084            .detach();
1085    }
1086
1087    fn toggle_fullscreen(&self) {
1088        let this = self.0.lock();
1089        let window = this.native_window;
1090        this.executor
1091            .spawn(async move {
1092                unsafe {
1093                    window.toggleFullScreen_(nil);
1094                }
1095            })
1096            .detach();
1097    }
1098
1099    fn is_fullscreen(&self) -> bool {
1100        let this = self.0.lock();
1101        let window = this.native_window;
1102
1103        unsafe {
1104            window
1105                .styleMask()
1106                .contains(NSWindowStyleMask::NSFullScreenWindowMask)
1107        }
1108    }
1109
1110    fn on_request_frame(&self, callback: Box<dyn FnMut(RequestFrameOptions)>) {
1111        self.0.as_ref().lock().request_frame_callback = Some(callback);
1112    }
1113
1114    fn on_input(&self, callback: Box<dyn FnMut(PlatformInput) -> crate::DispatchEventResult>) {
1115        self.0.as_ref().lock().event_callback = Some(callback);
1116    }
1117
1118    fn on_active_status_change(&self, callback: Box<dyn FnMut(bool)>) {
1119        self.0.as_ref().lock().activate_callback = Some(callback);
1120    }
1121
1122    fn on_hover_status_change(&self, _: Box<dyn FnMut(bool)>) {}
1123
1124    fn on_resize(&self, callback: Box<dyn FnMut(Size<Pixels>, f32)>) {
1125        self.0.as_ref().lock().resize_callback = Some(callback);
1126    }
1127
1128    fn on_moved(&self, callback: Box<dyn FnMut()>) {
1129        self.0.as_ref().lock().moved_callback = Some(callback);
1130    }
1131
1132    fn on_should_close(&self, callback: Box<dyn FnMut() -> bool>) {
1133        self.0.as_ref().lock().should_close_callback = Some(callback);
1134    }
1135
1136    fn on_close(&self, callback: Box<dyn FnOnce()>) {
1137        self.0.as_ref().lock().close_callback = Some(callback);
1138    }
1139
1140    fn on_appearance_changed(&self, callback: Box<dyn FnMut()>) {
1141        self.0.lock().appearance_changed_callback = Some(callback);
1142    }
1143
1144    fn draw(&self, scene: &crate::Scene) {
1145        let mut this = self.0.lock();
1146        this.renderer.draw(scene);
1147    }
1148
1149    fn sprite_atlas(&self) -> Arc<dyn PlatformAtlas> {
1150        self.0.lock().renderer.sprite_atlas().clone()
1151    }
1152
1153    fn gpu_specs(&self) -> Option<crate::GpuSpecs> {
1154        None
1155    }
1156
1157    fn update_ime_position(&self, _bounds: Bounds<ScaledPixels>) {
1158        let executor = self.0.lock().executor.clone();
1159        executor
1160            .spawn(async move {
1161                unsafe {
1162                    let input_context: id =
1163                        msg_send![class!(NSTextInputContext), currentInputContext];
1164                    if input_context.is_null() {
1165                        return;
1166                    }
1167                    let _: () = msg_send![input_context, invalidateCharacterCoordinates];
1168                }
1169            })
1170            .detach()
1171    }
1172}
1173
1174impl rwh::HasWindowHandle for MacWindow {
1175    fn window_handle(&self) -> Result<rwh::WindowHandle<'_>, rwh::HandleError> {
1176        // SAFETY: The AppKitWindowHandle is a wrapper around a pointer to an NSView
1177        unsafe {
1178            Ok(rwh::WindowHandle::borrow_raw(rwh::RawWindowHandle::AppKit(
1179                rwh::AppKitWindowHandle::new(self.0.lock().native_view.cast()),
1180            )))
1181        }
1182    }
1183}
1184
1185impl rwh::HasDisplayHandle for MacWindow {
1186    fn display_handle(&self) -> Result<rwh::DisplayHandle<'_>, rwh::HandleError> {
1187        // SAFETY: This is a no-op on macOS
1188        unsafe {
1189            Ok(rwh::DisplayHandle::borrow_raw(
1190                rwh::AppKitDisplayHandle::new().into(),
1191            ))
1192        }
1193    }
1194}
1195
1196fn get_scale_factor(native_window: id) -> f32 {
1197    let factor = unsafe {
1198        let screen: id = msg_send![native_window, screen];
1199        if screen.is_null() {
1200            return 1.0;
1201        }
1202        NSScreen::backingScaleFactor(screen) as f32
1203    };
1204
1205    // We are not certain what triggers this, but it seems that sometimes
1206    // this method would return 0 (https://github.com/zed-industries/zed/issues/6412)
1207    // It seems most likely that this would happen if the window has no screen
1208    // (if it is off-screen), though we'd expect to see viewDidChangeBackingProperties before
1209    // it was rendered for real.
1210    // Regardless, attempt to avoid the issue here.
1211    if factor == 0.0 { 2. } else { factor }
1212}
1213
1214unsafe fn get_window_state(object: &Object) -> Arc<Mutex<MacWindowState>> {
1215    unsafe {
1216        let raw: *mut c_void = *object.get_ivar(WINDOW_STATE_IVAR);
1217        let rc1 = Arc::from_raw(raw as *mut Mutex<MacWindowState>);
1218        let rc2 = rc1.clone();
1219        mem::forget(rc1);
1220        rc2
1221    }
1222}
1223
1224unsafe fn drop_window_state(object: &Object) {
1225    unsafe {
1226        let raw: *mut c_void = *object.get_ivar(WINDOW_STATE_IVAR);
1227        Arc::from_raw(raw as *mut Mutex<MacWindowState>);
1228    }
1229}
1230
1231extern "C" fn yes(_: &Object, _: Sel) -> BOOL {
1232    YES
1233}
1234
1235extern "C" fn dealloc_window(this: &Object, _: Sel) {
1236    unsafe {
1237        drop_window_state(this);
1238        let _: () = msg_send![super(this, class!(NSWindow)), dealloc];
1239    }
1240}
1241
1242extern "C" fn dealloc_view(this: &Object, _: Sel) {
1243    unsafe {
1244        drop_window_state(this);
1245        let _: () = msg_send![super(this, class!(NSView)), dealloc];
1246    }
1247}
1248
1249extern "C" fn handle_key_equivalent(this: &Object, _: Sel, native_event: id) -> BOOL {
1250    handle_key_event(this, native_event, true)
1251}
1252
1253extern "C" fn handle_key_down(this: &Object, _: Sel, native_event: id) {
1254    handle_key_event(this, native_event, false);
1255}
1256
1257extern "C" fn handle_key_up(this: &Object, _: Sel, native_event: id) {
1258    handle_key_event(this, native_event, false);
1259}
1260
1261// Things to test if you're modifying this method:
1262//  U.S. layout:
1263//   - The IME consumes characters like 'j' and 'k', which makes paging through `less` in
1264//     the terminal behave incorrectly by default. This behavior should be patched by our
1265//     IME integration
1266//   - `alt-t` should open the tasks menu
1267//   - In vim mode, this keybinding should work:
1268//     ```
1269//        {
1270//          "context": "Editor && vim_mode == insert",
1271//          "bindings": {"j j": "vim::NormalBefore"}
1272//        }
1273//     ```
1274//     and typing 'j k' in insert mode with this keybinding should insert the two characters
1275//  Brazilian layout:
1276//   - `" space` should create an unmarked quote
1277//   - `" backspace` should delete the marked quote
1278//   - `" "`should create an unmarked quote and a second marked quote
1279//   - `" up` should insert a quote, unmark it, and move up one line
1280//   - `" cmd-down` should insert a quote, unmark it, and move to the end of the file
1281//   - `cmd-ctrl-space` and clicking on an emoji should type it
1282//  Czech (QWERTY) layout:
1283//   - in vim mode `option-4`  should go to end of line (same as $)
1284//  Japanese (Romaji) layout:
1285//   - type `a i left down up enter enter` should create an unmarked text "愛"
1286extern "C" fn handle_key_event(this: &Object, native_event: id, key_equivalent: bool) -> BOOL {
1287    let window_state = unsafe { get_window_state(this) };
1288    let mut lock = window_state.as_ref().lock();
1289
1290    let window_height = lock.content_size().height;
1291    let event = unsafe { PlatformInput::from_native(native_event, Some(window_height)) };
1292
1293    let Some(event) = event else {
1294        return NO;
1295    };
1296
1297    let run_callback = |event: PlatformInput| -> BOOL {
1298        let mut callback = window_state.as_ref().lock().event_callback.take();
1299        let handled: BOOL = if let Some(callback) = callback.as_mut() {
1300            !callback(event).propagate as BOOL
1301        } else {
1302            NO
1303        };
1304        window_state.as_ref().lock().event_callback = callback;
1305        handled
1306    };
1307
1308    match event {
1309        PlatformInput::KeyDown(mut key_down_event) => {
1310            // For certain keystrokes, macOS will first dispatch a "key equivalent" event.
1311            // If that event isn't handled, it will then dispatch a "key down" event. GPUI
1312            // makes no distinction between these two types of events, so we need to ignore
1313            // the "key down" event if we've already just processed its "key equivalent" version.
1314            if key_equivalent {
1315                lock.last_key_equivalent = Some(key_down_event.clone());
1316            } else if lock.last_key_equivalent.take().as_ref() == Some(&key_down_event) {
1317                return NO;
1318            }
1319
1320            drop(lock);
1321
1322            let is_composing =
1323                with_input_handler(this, |input_handler| input_handler.marked_text_range())
1324                    .flatten()
1325                    .is_some();
1326
1327            // If we're composing, send the key to the input handler first;
1328            // otherwise we only send to the input handler if we don't have a matching binding.
1329            // The input handler may call `do_command_by_selector` if it doesn't know how to handle
1330            // a key. If it does so, it will return YES so we won't send the key twice.
1331            // We also do this for non-printing keys (like arrow keys and escape) as the IME menu
1332            // may need them even if there is no marked text;
1333            // however we skip keys with control or the input handler adds control-characters to the buffer.
1334            // and keys with function, as the input handler swallows them.
1335            if is_composing
1336                || (key_down_event.keystroke.key_char.is_none()
1337                    && !key_down_event.keystroke.modifiers.control
1338                    && !key_down_event.keystroke.modifiers.function)
1339            {
1340                {
1341                    let mut lock = window_state.as_ref().lock();
1342                    lock.keystroke_for_do_command = Some(key_down_event.keystroke.clone());
1343                    lock.do_command_handled.take();
1344                    drop(lock);
1345                }
1346
1347                let handled: BOOL = unsafe {
1348                    let input_context: id = msg_send![this, inputContext];
1349                    msg_send![input_context, handleEvent: native_event]
1350                };
1351                window_state.as_ref().lock().keystroke_for_do_command.take();
1352                if let Some(handled) = window_state.as_ref().lock().do_command_handled.take() {
1353                    return handled as BOOL;
1354                } else if handled == YES {
1355                    return YES;
1356                }
1357
1358                let handled = run_callback(PlatformInput::KeyDown(key_down_event));
1359                return handled;
1360            }
1361
1362            let handled = run_callback(PlatformInput::KeyDown(key_down_event.clone()));
1363            if handled == YES {
1364                return YES;
1365            }
1366
1367            if key_down_event.is_held {
1368                if let Some(key_char) = key_down_event.keystroke.key_char.as_ref() {
1369                    let handled = with_input_handler(&this, |input_handler| {
1370                        if !input_handler.apple_press_and_hold_enabled() {
1371                            input_handler.replace_text_in_range(None, &key_char);
1372                            return YES;
1373                        }
1374                        NO
1375                    });
1376                    if handled == Some(YES) {
1377                        return YES;
1378                    }
1379                }
1380            }
1381
1382            // Don't send key equivalents to the input handler,
1383            // or macOS shortcuts like cmd-` will stop working.
1384            if key_equivalent {
1385                return NO;
1386            }
1387
1388            unsafe {
1389                let input_context: id = msg_send![this, inputContext];
1390                msg_send![input_context, handleEvent: native_event]
1391            }
1392        }
1393
1394        PlatformInput::KeyUp(_) => {
1395            drop(lock);
1396            run_callback(event)
1397        }
1398
1399        _ => NO,
1400    }
1401}
1402
1403extern "C" fn handle_view_event(this: &Object, _: Sel, native_event: id) {
1404    let window_state = unsafe { get_window_state(this) };
1405    let weak_window_state = Arc::downgrade(&window_state);
1406    let mut lock = window_state.as_ref().lock();
1407    let window_height = lock.content_size().height;
1408    let event = unsafe { PlatformInput::from_native(native_event, Some(window_height)) };
1409
1410    if let Some(mut event) = event {
1411        match &mut event {
1412            PlatformInput::MouseDown(
1413                event @ MouseDownEvent {
1414                    button: MouseButton::Left,
1415                    modifiers: Modifiers { control: true, .. },
1416                    ..
1417                },
1418            ) => {
1419                // On mac, a ctrl-left click should be handled as a right click.
1420                *event = MouseDownEvent {
1421                    button: MouseButton::Right,
1422                    modifiers: Modifiers {
1423                        control: false,
1424                        ..event.modifiers
1425                    },
1426                    click_count: 1,
1427                    ..*event
1428                };
1429            }
1430
1431            // Handles focusing click.
1432            PlatformInput::MouseDown(
1433                event @ MouseDownEvent {
1434                    button: MouseButton::Left,
1435                    ..
1436                },
1437            ) if (lock.first_mouse) => {
1438                *event = MouseDownEvent {
1439                    first_mouse: true,
1440                    ..*event
1441                };
1442                lock.first_mouse = false;
1443            }
1444
1445            // Because we map a ctrl-left_down to a right_down -> right_up let's ignore
1446            // the ctrl-left_up to avoid having a mismatch in button down/up events if the
1447            // user is still holding ctrl when releasing the left mouse button
1448            PlatformInput::MouseUp(
1449                event @ MouseUpEvent {
1450                    button: MouseButton::Left,
1451                    modifiers: Modifiers { control: true, .. },
1452                    ..
1453                },
1454            ) => {
1455                *event = MouseUpEvent {
1456                    button: MouseButton::Right,
1457                    modifiers: Modifiers {
1458                        control: false,
1459                        ..event.modifiers
1460                    },
1461                    click_count: 1,
1462                    ..*event
1463                };
1464            }
1465
1466            _ => {}
1467        };
1468
1469        match &event {
1470            PlatformInput::MouseDown(_) => {
1471                drop(lock);
1472                unsafe {
1473                    let input_context: id = msg_send![this, inputContext];
1474                    msg_send![input_context, handleEvent: native_event]
1475                }
1476                lock = window_state.as_ref().lock();
1477            }
1478            PlatformInput::MouseMove(
1479                event @ MouseMoveEvent {
1480                    pressed_button: Some(_),
1481                    ..
1482                },
1483            ) => {
1484                // Synthetic drag is used for selecting long buffer contents while buffer is being scrolled.
1485                // External file drag and drop is able to emit its own synthetic mouse events which will conflict
1486                // with these ones.
1487                if !lock.external_files_dragged {
1488                    lock.synthetic_drag_counter += 1;
1489                    let executor = lock.executor.clone();
1490                    executor
1491                        .spawn(synthetic_drag(
1492                            weak_window_state,
1493                            lock.synthetic_drag_counter,
1494                            event.clone(),
1495                        ))
1496                        .detach();
1497                }
1498            }
1499
1500            PlatformInput::MouseUp(MouseUpEvent { .. }) => {
1501                lock.synthetic_drag_counter += 1;
1502            }
1503
1504            PlatformInput::ModifiersChanged(ModifiersChangedEvent { modifiers }) => {
1505                // Only raise modifiers changed event when they have actually changed
1506                if let Some(PlatformInput::ModifiersChanged(ModifiersChangedEvent {
1507                    modifiers: prev_modifiers,
1508                })) = &lock.previous_modifiers_changed_event
1509                {
1510                    if prev_modifiers == modifiers {
1511                        return;
1512                    }
1513                }
1514
1515                lock.previous_modifiers_changed_event = Some(event.clone());
1516            }
1517
1518            _ => {}
1519        }
1520
1521        if let Some(mut callback) = lock.event_callback.take() {
1522            drop(lock);
1523            callback(event);
1524            window_state.lock().event_callback = Some(callback);
1525        }
1526    }
1527}
1528
1529extern "C" fn window_did_change_occlusion_state(this: &Object, _: Sel, _: id) {
1530    let window_state = unsafe { get_window_state(this) };
1531    let lock = &mut *window_state.lock();
1532    unsafe {
1533        if lock
1534            .native_window
1535            .occlusionState()
1536            .contains(NSWindowOcclusionState::NSWindowOcclusionStateVisible)
1537        {
1538            lock.start_display_link();
1539        } else {
1540            lock.stop_display_link();
1541        }
1542    }
1543}
1544
1545extern "C" fn window_did_resize(this: &Object, _: Sel, _: id) {
1546    let window_state = unsafe { get_window_state(this) };
1547    window_state.as_ref().lock().move_traffic_light();
1548}
1549
1550extern "C" fn window_will_enter_fullscreen(this: &Object, _: Sel, _: id) {
1551    let window_state = unsafe { get_window_state(this) };
1552    let mut lock = window_state.as_ref().lock();
1553    lock.fullscreen_restore_bounds = lock.bounds();
1554
1555    let min_version = NSOperatingSystemVersion::new(15, 3, 0);
1556
1557    if is_macos_version_at_least(min_version) {
1558        unsafe {
1559            lock.native_window.setTitlebarAppearsTransparent_(NO);
1560        }
1561    }
1562}
1563
1564extern "C" fn window_will_exit_fullscreen(this: &Object, _: Sel, _: id) {
1565    let window_state = unsafe { get_window_state(this) };
1566    let mut lock = window_state.as_ref().lock();
1567
1568    let min_version = NSOperatingSystemVersion::new(15, 3, 0);
1569
1570    if is_macos_version_at_least(min_version) && lock.transparent_titlebar {
1571        unsafe {
1572            lock.native_window.setTitlebarAppearsTransparent_(YES);
1573        }
1574    }
1575}
1576
1577pub(crate) fn is_macos_version_at_least(version: NSOperatingSystemVersion) -> bool {
1578    unsafe { NSProcessInfo::processInfo(nil).isOperatingSystemAtLeastVersion(version) }
1579}
1580
1581extern "C" fn window_did_move(this: &Object, _: Sel, _: id) {
1582    let window_state = unsafe { get_window_state(this) };
1583    let mut lock = window_state.as_ref().lock();
1584    if let Some(mut callback) = lock.moved_callback.take() {
1585        drop(lock);
1586        callback();
1587        window_state.lock().moved_callback = Some(callback);
1588    }
1589}
1590
1591extern "C" fn window_did_change_screen(this: &Object, _: Sel, _: id) {
1592    let window_state = unsafe { get_window_state(this) };
1593    let mut lock = window_state.as_ref().lock();
1594    lock.start_display_link();
1595}
1596
1597extern "C" fn window_did_change_key_status(this: &Object, selector: Sel, _: id) {
1598    let window_state = unsafe { get_window_state(this) };
1599    let lock = window_state.lock();
1600    let is_active = unsafe { lock.native_window.isKeyWindow() == YES };
1601
1602    // When opening a pop-up while the application isn't active, Cocoa sends a spurious
1603    // `windowDidBecomeKey` message to the previous key window even though that window
1604    // isn't actually key. This causes a bug if the application is later activated while
1605    // the pop-up is still open, making it impossible to activate the previous key window
1606    // even if the pop-up gets closed. The only way to activate it again is to de-activate
1607    // the app and re-activate it, which is a pretty bad UX.
1608    // The following code detects the spurious event and invokes `resignKeyWindow`:
1609    // in theory, we're not supposed to invoke this method manually but it balances out
1610    // the spurious `becomeKeyWindow` event and helps us work around that bug.
1611    if selector == sel!(windowDidBecomeKey:) && !is_active {
1612        unsafe {
1613            let _: () = msg_send![lock.native_window, resignKeyWindow];
1614            return;
1615        }
1616    }
1617
1618    let executor = lock.executor.clone();
1619    drop(lock);
1620    executor
1621        .spawn(async move {
1622            let mut lock = window_state.as_ref().lock();
1623            if let Some(mut callback) = lock.activate_callback.take() {
1624                drop(lock);
1625                callback(is_active);
1626                window_state.lock().activate_callback = Some(callback);
1627            };
1628        })
1629        .detach();
1630}
1631
1632extern "C" fn window_should_close(this: &Object, _: Sel, _: id) -> BOOL {
1633    let window_state = unsafe { get_window_state(this) };
1634    let mut lock = window_state.as_ref().lock();
1635    if let Some(mut callback) = lock.should_close_callback.take() {
1636        drop(lock);
1637        let should_close = callback();
1638        window_state.lock().should_close_callback = Some(callback);
1639        should_close as BOOL
1640    } else {
1641        YES
1642    }
1643}
1644
1645extern "C" fn close_window(this: &Object, _: Sel) {
1646    unsafe {
1647        let close_callback = {
1648            let window_state = get_window_state(this);
1649            let mut lock = window_state.as_ref().lock();
1650            lock.close_callback.take()
1651        };
1652
1653        if let Some(callback) = close_callback {
1654            callback();
1655        }
1656
1657        let _: () = msg_send![super(this, class!(NSWindow)), close];
1658    }
1659}
1660
1661extern "C" fn make_backing_layer(this: &Object, _: Sel) -> id {
1662    let window_state = unsafe { get_window_state(this) };
1663    let window_state = window_state.as_ref().lock();
1664    window_state.renderer.layer_ptr() as id
1665}
1666
1667extern "C" fn view_did_change_backing_properties(this: &Object, _: Sel) {
1668    let window_state = unsafe { get_window_state(this) };
1669    let mut lock = window_state.as_ref().lock();
1670
1671    let scale_factor = lock.scale_factor();
1672    let size = lock.content_size();
1673    let drawable_size = size.to_device_pixels(scale_factor);
1674    unsafe {
1675        let _: () = msg_send![
1676            lock.renderer.layer(),
1677            setContentsScale: scale_factor as f64
1678        ];
1679    }
1680
1681    lock.renderer.update_drawable_size(drawable_size);
1682
1683    if let Some(mut callback) = lock.resize_callback.take() {
1684        let content_size = lock.content_size();
1685        let scale_factor = lock.scale_factor();
1686        drop(lock);
1687        callback(content_size, scale_factor);
1688        window_state.as_ref().lock().resize_callback = Some(callback);
1689    };
1690}
1691
1692extern "C" fn set_frame_size(this: &Object, _: Sel, size: NSSize) {
1693    let window_state = unsafe { get_window_state(this) };
1694    let mut lock = window_state.as_ref().lock();
1695
1696    let new_size = Size::<Pixels>::from(size);
1697    if lock.content_size() == new_size {
1698        return;
1699    }
1700
1701    unsafe {
1702        let _: () = msg_send![super(this, class!(NSView)), setFrameSize: size];
1703    }
1704
1705    let scale_factor = lock.scale_factor();
1706    let drawable_size = new_size.to_device_pixels(scale_factor);
1707    lock.renderer.update_drawable_size(drawable_size);
1708
1709    if let Some(mut callback) = lock.resize_callback.take() {
1710        let content_size = lock.content_size();
1711        let scale_factor = lock.scale_factor();
1712        drop(lock);
1713        callback(content_size, scale_factor);
1714        window_state.lock().resize_callback = Some(callback);
1715    };
1716}
1717
1718extern "C" fn display_layer(this: &Object, _: Sel, _: id) {
1719    let window_state = unsafe { get_window_state(this) };
1720    let mut lock = window_state.lock();
1721    if let Some(mut callback) = lock.request_frame_callback.take() {
1722        #[cfg(not(feature = "macos-blade"))]
1723        lock.renderer.set_presents_with_transaction(true);
1724        lock.stop_display_link();
1725        drop(lock);
1726        callback(Default::default());
1727
1728        let mut lock = window_state.lock();
1729        lock.request_frame_callback = Some(callback);
1730        #[cfg(not(feature = "macos-blade"))]
1731        lock.renderer.set_presents_with_transaction(false);
1732        lock.start_display_link();
1733    }
1734}
1735
1736unsafe extern "C" fn step(view: *mut c_void) {
1737    let view = view as id;
1738    let window_state = unsafe { get_window_state(&*view) };
1739    let mut lock = window_state.lock();
1740
1741    if let Some(mut callback) = lock.request_frame_callback.take() {
1742        drop(lock);
1743        callback(Default::default());
1744        window_state.lock().request_frame_callback = Some(callback);
1745    }
1746}
1747
1748extern "C" fn valid_attributes_for_marked_text(_: &Object, _: Sel) -> id {
1749    unsafe { msg_send![class!(NSArray), array] }
1750}
1751
1752extern "C" fn has_marked_text(this: &Object, _: Sel) -> BOOL {
1753    let has_marked_text_result =
1754        with_input_handler(this, |input_handler| input_handler.marked_text_range()).flatten();
1755
1756    has_marked_text_result.is_some() as BOOL
1757}
1758
1759extern "C" fn marked_range(this: &Object, _: Sel) -> NSRange {
1760    let marked_range_result =
1761        with_input_handler(this, |input_handler| input_handler.marked_text_range()).flatten();
1762
1763    marked_range_result.map_or(NSRange::invalid(), |range| range.into())
1764}
1765
1766extern "C" fn selected_range(this: &Object, _: Sel) -> NSRange {
1767    let selected_range_result = with_input_handler(this, |input_handler| {
1768        input_handler.selected_text_range(false)
1769    })
1770    .flatten();
1771
1772    selected_range_result.map_or(NSRange::invalid(), |selection| selection.range.into())
1773}
1774
1775extern "C" fn first_rect_for_character_range(
1776    this: &Object,
1777    _: Sel,
1778    range: NSRange,
1779    _: id,
1780) -> NSRect {
1781    let frame = get_frame(this);
1782    with_input_handler(this, |input_handler| {
1783        input_handler.bounds_for_range(range.to_range()?)
1784    })
1785    .flatten()
1786    .map_or(
1787        NSRect::new(NSPoint::new(0., 0.), NSSize::new(0., 0.)),
1788        |bounds| {
1789            NSRect::new(
1790                NSPoint::new(
1791                    frame.origin.x + bounds.origin.x.0 as f64,
1792                    frame.origin.y + frame.size.height
1793                        - bounds.origin.y.0 as f64
1794                        - bounds.size.height.0 as f64,
1795                ),
1796                NSSize::new(bounds.size.width.0 as f64, bounds.size.height.0 as f64),
1797            )
1798        },
1799    )
1800}
1801
1802fn get_frame(this: &Object) -> NSRect {
1803    unsafe {
1804        let state = get_window_state(this);
1805        let lock = state.lock();
1806        let mut frame = NSWindow::frame(lock.native_window);
1807        let content_layout_rect: CGRect = msg_send![lock.native_window, contentLayoutRect];
1808        let style_mask: NSWindowStyleMask = msg_send![lock.native_window, styleMask];
1809        if !style_mask.contains(NSWindowStyleMask::NSFullSizeContentViewWindowMask) {
1810            frame.origin.y -= frame.size.height - content_layout_rect.size.height;
1811        }
1812        frame
1813    }
1814}
1815
1816extern "C" fn insert_text(this: &Object, _: Sel, text: id, replacement_range: NSRange) {
1817    unsafe {
1818        let is_attributed_string: BOOL =
1819            msg_send![text, isKindOfClass: [class!(NSAttributedString)]];
1820        let text: id = if is_attributed_string == YES {
1821            msg_send![text, string]
1822        } else {
1823            text
1824        };
1825
1826        let text = text.to_str();
1827        let replacement_range = replacement_range.to_range();
1828        with_input_handler(this, |input_handler| {
1829            input_handler.replace_text_in_range(replacement_range, &text)
1830        });
1831    }
1832}
1833
1834extern "C" fn set_marked_text(
1835    this: &Object,
1836    _: Sel,
1837    text: id,
1838    selected_range: NSRange,
1839    replacement_range: NSRange,
1840) {
1841    unsafe {
1842        let is_attributed_string: BOOL =
1843            msg_send![text, isKindOfClass: [class!(NSAttributedString)]];
1844        let text: id = if is_attributed_string == YES {
1845            msg_send![text, string]
1846        } else {
1847            text
1848        };
1849        let selected_range = selected_range.to_range();
1850        let replacement_range = replacement_range.to_range();
1851        let text = text.to_str();
1852        with_input_handler(this, |input_handler| {
1853            input_handler.replace_and_mark_text_in_range(replacement_range, &text, selected_range)
1854        });
1855    }
1856}
1857extern "C" fn unmark_text(this: &Object, _: Sel) {
1858    with_input_handler(this, |input_handler| input_handler.unmark_text());
1859}
1860
1861extern "C" fn attributed_substring_for_proposed_range(
1862    this: &Object,
1863    _: Sel,
1864    range: NSRange,
1865    actual_range: *mut c_void,
1866) -> id {
1867    with_input_handler(this, |input_handler| {
1868        let range = range.to_range()?;
1869        if range.is_empty() {
1870            return None;
1871        }
1872        let mut adjusted: Option<Range<usize>> = None;
1873
1874        let selected_text = input_handler.text_for_range(range.clone(), &mut adjusted)?;
1875        if let Some(adjusted) = adjusted {
1876            if adjusted != range {
1877                unsafe { (actual_range as *mut NSRange).write(NSRange::from(adjusted)) };
1878            }
1879        }
1880        unsafe {
1881            let string: id = msg_send![class!(NSAttributedString), alloc];
1882            let string: id = msg_send![string, initWithString: ns_string(&selected_text)];
1883            Some(string)
1884        }
1885    })
1886    .flatten()
1887    .unwrap_or(nil)
1888}
1889
1890// We ignore which selector it asks us to do because the user may have
1891// bound the shortcut to something else.
1892extern "C" fn do_command_by_selector(this: &Object, _: Sel, _: Sel) {
1893    let state = unsafe { get_window_state(this) };
1894    let mut lock = state.as_ref().lock();
1895    let keystroke = lock.keystroke_for_do_command.take();
1896    let mut event_callback = lock.event_callback.take();
1897    drop(lock);
1898
1899    if let Some((keystroke, mut callback)) = keystroke.zip(event_callback.as_mut()) {
1900        let handled = (callback)(PlatformInput::KeyDown(KeyDownEvent {
1901            keystroke,
1902            is_held: false,
1903        }));
1904        state.as_ref().lock().do_command_handled = Some(!handled.propagate);
1905    }
1906
1907    state.as_ref().lock().event_callback = event_callback;
1908}
1909
1910extern "C" fn view_did_change_effective_appearance(this: &Object, _: Sel) {
1911    unsafe {
1912        let state = get_window_state(this);
1913        let mut lock = state.as_ref().lock();
1914        if let Some(mut callback) = lock.appearance_changed_callback.take() {
1915            drop(lock);
1916            callback();
1917            state.lock().appearance_changed_callback = Some(callback);
1918        }
1919    }
1920}
1921
1922extern "C" fn accepts_first_mouse(this: &Object, _: Sel, _: id) -> BOOL {
1923    let window_state = unsafe { get_window_state(this) };
1924    let mut lock = window_state.as_ref().lock();
1925    lock.first_mouse = true;
1926    YES
1927}
1928
1929extern "C" fn character_index_for_point(this: &Object, _: Sel, position: NSPoint) -> u64 {
1930    let position = screen_point_to_gpui_point(this, position);
1931    with_input_handler(this, |input_handler| {
1932        input_handler.character_index_for_point(position)
1933    })
1934    .flatten()
1935    .map(|index| index as u64)
1936    .unwrap_or(NSNotFound as u64)
1937}
1938
1939fn screen_point_to_gpui_point(this: &Object, position: NSPoint) -> Point<Pixels> {
1940    let frame = get_frame(this);
1941    let window_x = position.x - frame.origin.x;
1942    let window_y = frame.size.height - (position.y - frame.origin.y);
1943    let position = point(px(window_x as f32), px(window_y as f32));
1944    position
1945}
1946
1947extern "C" fn dragging_entered(this: &Object, _: Sel, dragging_info: id) -> NSDragOperation {
1948    let window_state = unsafe { get_window_state(this) };
1949    let position = drag_event_position(&window_state, dragging_info);
1950    let paths = external_paths_from_event(dragging_info);
1951    if let Some(event) =
1952        paths.map(|paths| PlatformInput::FileDrop(FileDropEvent::Entered { position, paths }))
1953    {
1954        if send_new_event(&window_state, event) {
1955            window_state.lock().external_files_dragged = true;
1956            return NSDragOperationCopy;
1957        }
1958    }
1959    NSDragOperationNone
1960}
1961
1962extern "C" fn dragging_updated(this: &Object, _: Sel, dragging_info: id) -> NSDragOperation {
1963    let window_state = unsafe { get_window_state(this) };
1964    let position = drag_event_position(&window_state, dragging_info);
1965    if send_new_event(
1966        &window_state,
1967        PlatformInput::FileDrop(FileDropEvent::Pending { position }),
1968    ) {
1969        NSDragOperationCopy
1970    } else {
1971        NSDragOperationNone
1972    }
1973}
1974
1975extern "C" fn dragging_exited(this: &Object, _: Sel, _: id) {
1976    let window_state = unsafe { get_window_state(this) };
1977    send_new_event(
1978        &window_state,
1979        PlatformInput::FileDrop(FileDropEvent::Exited),
1980    );
1981    window_state.lock().external_files_dragged = false;
1982}
1983
1984extern "C" fn perform_drag_operation(this: &Object, _: Sel, dragging_info: id) -> BOOL {
1985    let window_state = unsafe { get_window_state(this) };
1986    let position = drag_event_position(&window_state, dragging_info);
1987    send_new_event(
1988        &window_state,
1989        PlatformInput::FileDrop(FileDropEvent::Submit { position }),
1990    )
1991    .to_objc()
1992}
1993
1994fn external_paths_from_event(dragging_info: *mut Object) -> Option<ExternalPaths> {
1995    let mut paths = SmallVec::new();
1996    let pasteboard: id = unsafe { msg_send![dragging_info, draggingPasteboard] };
1997    let filenames = unsafe { NSPasteboard::propertyListForType(pasteboard, NSFilenamesPboardType) };
1998    if filenames == nil {
1999        return None;
2000    }
2001    for file in unsafe { filenames.iter() } {
2002        let path = unsafe {
2003            let f = NSString::UTF8String(file);
2004            CStr::from_ptr(f).to_string_lossy().into_owned()
2005        };
2006        paths.push(PathBuf::from(path))
2007    }
2008    Some(ExternalPaths(paths))
2009}
2010
2011extern "C" fn conclude_drag_operation(this: &Object, _: Sel, _: id) {
2012    let window_state = unsafe { get_window_state(this) };
2013    send_new_event(
2014        &window_state,
2015        PlatformInput::FileDrop(FileDropEvent::Exited),
2016    );
2017}
2018
2019async fn synthetic_drag(
2020    window_state: Weak<Mutex<MacWindowState>>,
2021    drag_id: usize,
2022    event: MouseMoveEvent,
2023) {
2024    loop {
2025        Timer::after(Duration::from_millis(16)).await;
2026        if let Some(window_state) = window_state.upgrade() {
2027            let mut lock = window_state.lock();
2028            if lock.synthetic_drag_counter == drag_id {
2029                if let Some(mut callback) = lock.event_callback.take() {
2030                    drop(lock);
2031                    callback(PlatformInput::MouseMove(event.clone()));
2032                    window_state.lock().event_callback = Some(callback);
2033                }
2034            } else {
2035                break;
2036            }
2037        }
2038    }
2039}
2040
2041fn send_new_event(window_state_lock: &Mutex<MacWindowState>, e: PlatformInput) -> bool {
2042    let window_state = window_state_lock.lock().event_callback.take();
2043    if let Some(mut callback) = window_state {
2044        callback(e);
2045        window_state_lock.lock().event_callback = Some(callback);
2046        true
2047    } else {
2048        false
2049    }
2050}
2051
2052fn drag_event_position(window_state: &Mutex<MacWindowState>, dragging_info: id) -> Point<Pixels> {
2053    let drag_location: NSPoint = unsafe { msg_send![dragging_info, draggingLocation] };
2054    convert_mouse_position(drag_location, window_state.lock().content_size().height)
2055}
2056
2057fn with_input_handler<F, R>(window: &Object, f: F) -> Option<R>
2058where
2059    F: FnOnce(&mut PlatformInputHandler) -> R,
2060{
2061    let window_state = unsafe { get_window_state(window) };
2062    let mut lock = window_state.as_ref().lock();
2063    if let Some(mut input_handler) = lock.input_handler.take() {
2064        drop(lock);
2065        let result = f(&mut input_handler);
2066        window_state.lock().input_handler = Some(input_handler);
2067        Some(result)
2068    } else {
2069        None
2070    }
2071}
2072
2073unsafe fn display_id_for_screen(screen: id) -> CGDirectDisplayID {
2074    unsafe {
2075        let device_description = NSScreen::deviceDescription(screen);
2076        let screen_number_key: id = NSString::alloc(nil).init_str("NSScreenNumber");
2077        let screen_number = device_description.objectForKey_(screen_number_key);
2078        let screen_number: NSUInteger = msg_send![screen_number, unsignedIntegerValue];
2079        screen_number as CGDirectDisplayID
2080    }
2081}