window.rs

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