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