window.rs

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