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