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