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