window.rs

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