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
  77#[allow(non_upper_case_globals)]
  78type NSDragOperation = NSUInteger;
  79#[allow(non_upper_case_globals)]
  80const NSDragOperationNone: NSDragOperation = 0;
  81#[allow(non_upper_case_globals)]
  82const NSDragOperationCopy: NSDragOperation = 1;
  83
  84#[ctor]
  85unsafe fn build_classes() {
  86    ::util::gpui2_loaded();
  87
  88    WINDOW_CLASS = build_window_class("GPUI2Window", class!(NSWindow));
  89    PANEL_CLASS = build_window_class("GPUI2Panel", class!(NSPanel));
  90    VIEW_CLASS = {
  91        let mut decl = ClassDecl::new("GPUI2View", 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 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    decl.add_method(sel!(close), close_window as extern "C" fn(&Object, Sel));
 276
 277    decl.add_method(
 278        sel!(draggingEntered:),
 279        dragging_entered as extern "C" fn(&Object, Sel, id) -> NSDragOperation,
 280    );
 281    decl.add_method(
 282        sel!(draggingUpdated:),
 283        dragging_updated as extern "C" fn(&Object, Sel, id) -> NSDragOperation,
 284    );
 285    decl.add_method(
 286        sel!(draggingExited:),
 287        dragging_exited as extern "C" fn(&Object, Sel, id),
 288    );
 289    decl.add_method(
 290        sel!(performDragOperation:),
 291        perform_drag_operation as extern "C" fn(&Object, Sel, id) -> BOOL,
 292    );
 293    decl.add_method(
 294        sel!(concludeDragOperation:),
 295        conclude_drag_operation as extern "C" fn(&Object, Sel, id),
 296    );
 297
 298    decl.register()
 299}
 300
 301///Used to track what the IME does when we send it a keystroke.
 302///This is only used to handle the case where the IME mysteriously
 303///swallows certain keys.
 304///
 305///Basically a direct copy of the approach that WezTerm uses in:
 306///github.com/wez/wezterm : d5755f3e : window/src/os/macos/window.rs
 307enum ImeState {
 308    Continue,
 309    Acted,
 310    None,
 311}
 312
 313struct InsertText {
 314    replacement_range: Option<Range<usize>>,
 315    text: String,
 316}
 317
 318struct MacWindowState {
 319    handle: AnyWindowHandle,
 320    executor: ForegroundExecutor,
 321    native_window: id,
 322    renderer: MetalRenderer,
 323    draw: Option<DrawWindow>,
 324    kind: WindowKind,
 325    event_callback: Option<Box<dyn FnMut(InputEvent) -> bool>>,
 326    activate_callback: Option<Box<dyn FnMut(bool)>>,
 327    resize_callback: Option<Box<dyn FnMut(Size<Pixels>, f32)>>,
 328    fullscreen_callback: Option<Box<dyn FnMut(bool)>>,
 329    moved_callback: Option<Box<dyn FnMut()>>,
 330    should_close_callback: Option<Box<dyn FnMut() -> bool>>,
 331    close_callback: Option<Box<dyn FnOnce()>>,
 332    appearance_changed_callback: Option<Box<dyn FnMut()>>,
 333    input_handler: Option<Box<dyn PlatformInputHandler>>,
 334    pending_key_down: Option<(KeyDownEvent, Option<InsertText>)>,
 335    last_key_equivalent: Option<KeyDownEvent>,
 336    synthetic_drag_counter: usize,
 337    last_fresh_keydown: Option<Keystroke>,
 338    traffic_light_position: Option<Point<Pixels>>,
 339    previous_modifiers_changed_event: Option<InputEvent>,
 340    // State tracking what the IME did after the last request
 341    ime_state: ImeState,
 342    // Retains the last IME Text
 343    ime_text: Option<String>,
 344}
 345
 346impl MacWindowState {
 347    fn move_traffic_light(&self) {
 348        if let Some(traffic_light_position) = self.traffic_light_position {
 349            let titlebar_height = self.titlebar_height();
 350
 351            unsafe {
 352                let close_button: id = msg_send![
 353                    self.native_window,
 354                    standardWindowButton: NSWindowButton::NSWindowCloseButton
 355                ];
 356                let min_button: id = msg_send![
 357                    self.native_window,
 358                    standardWindowButton: NSWindowButton::NSWindowMiniaturizeButton
 359                ];
 360                let zoom_button: id = msg_send![
 361                    self.native_window,
 362                    standardWindowButton: NSWindowButton::NSWindowZoomButton
 363                ];
 364
 365                let mut close_button_frame: CGRect = msg_send![close_button, frame];
 366                let mut min_button_frame: CGRect = msg_send![min_button, frame];
 367                let mut zoom_button_frame: CGRect = msg_send![zoom_button, frame];
 368                let mut origin = point(
 369                    traffic_light_position.x,
 370                    titlebar_height
 371                        - traffic_light_position.y
 372                        - px(close_button_frame.size.height as f32),
 373                );
 374                let button_spacing =
 375                    px((min_button_frame.origin.x - close_button_frame.origin.x) as f32);
 376
 377                close_button_frame.origin = CGPoint::new(origin.x.into(), origin.y.into());
 378                let _: () = msg_send![close_button, setFrame: close_button_frame];
 379                origin.x += button_spacing;
 380
 381                min_button_frame.origin = CGPoint::new(origin.x.into(), origin.y.into());
 382                let _: () = msg_send![min_button, setFrame: min_button_frame];
 383                origin.x += button_spacing;
 384
 385                zoom_button_frame.origin = CGPoint::new(origin.x.into(), origin.y.into());
 386                let _: () = msg_send![zoom_button, setFrame: zoom_button_frame];
 387                origin.x += button_spacing;
 388            }
 389        }
 390    }
 391
 392    fn is_fullscreen(&self) -> bool {
 393        unsafe {
 394            let style_mask = self.native_window.styleMask();
 395            style_mask.contains(NSWindowStyleMask::NSFullScreenWindowMask)
 396        }
 397    }
 398
 399    fn bounds(&self) -> WindowBounds {
 400        unsafe {
 401            if self.is_fullscreen() {
 402                return WindowBounds::Fullscreen;
 403            }
 404
 405            let frame = self.frame();
 406            let screen_size = self.native_window.screen().visibleFrame().into();
 407            if frame.size == screen_size {
 408                WindowBounds::Maximized
 409            } else {
 410                WindowBounds::Fixed(frame)
 411            }
 412        }
 413    }
 414
 415    fn frame(&self) -> Bounds<GlobalPixels> {
 416        unsafe {
 417            let frame = NSWindow::frame(self.native_window);
 418            display_bounds_from_native(mem::transmute::<NSRect, CGRect>(frame))
 419        }
 420    }
 421
 422    fn content_size(&self) -> Size<Pixels> {
 423        let NSSize { width, height, .. } =
 424            unsafe { NSView::frame(self.native_window.contentView()) }.size;
 425        size(px(width as f32), px(height as f32))
 426    }
 427
 428    fn scale_factor(&self) -> f32 {
 429        get_scale_factor(self.native_window)
 430    }
 431
 432    fn titlebar_height(&self) -> Pixels {
 433        unsafe {
 434            let frame = NSWindow::frame(self.native_window);
 435            let content_layout_rect: CGRect = msg_send![self.native_window, contentLayoutRect];
 436            px((frame.size.height - content_layout_rect.size.height) as f32)
 437        }
 438    }
 439
 440    fn to_screen_ns_point(&self, point: Point<Pixels>) -> NSPoint {
 441        unsafe {
 442            let point = NSPoint::new(
 443                point.x.into(),
 444                (self.content_size().height - point.y).into(),
 445            );
 446            msg_send![self.native_window, convertPointToScreen: point]
 447        }
 448    }
 449}
 450
 451unsafe impl Send for MacWindowState {}
 452
 453pub struct MacWindow(Arc<Mutex<MacWindowState>>);
 454
 455impl MacWindow {
 456    pub fn open(
 457        handle: AnyWindowHandle,
 458        options: WindowOptions,
 459        draw: DrawWindow,
 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(|display_id| MacDisplay::all().find(|display| display.id() == display_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 screen = native_window.screen();
 523            match options.bounds {
 524                WindowBounds::Fullscreen => {
 525                    native_window.toggleFullScreen_(nil);
 526                }
 527                WindowBounds::Maximized => {
 528                    native_window.setFrame_display_(screen.visibleFrame(), YES);
 529                }
 530                WindowBounds::Fixed(bounds) => {
 531                    let display_bounds = display.bounds();
 532                    let frame = if bounds.intersects(&display_bounds) {
 533                        display_bounds_to_native(bounds)
 534                    } else {
 535                        display_bounds_to_native(display_bounds)
 536                    };
 537                    native_window.setFrame_display_(mem::transmute::<CGRect, NSRect>(frame), YES);
 538                }
 539            }
 540
 541            let native_view: id = msg_send![VIEW_CLASS, alloc];
 542            let native_view = NSView::init(native_view);
 543
 544            assert!(!native_view.is_null());
 545
 546            let window = Self(Arc::new(Mutex::new(MacWindowState {
 547                handle,
 548                executor,
 549                native_window,
 550                renderer: MetalRenderer::new(true),
 551                draw: Some(draw),
 552                kind: options.kind,
 553                event_callback: None,
 554                activate_callback: None,
 555                resize_callback: None,
 556                fullscreen_callback: None,
 557                moved_callback: None,
 558                should_close_callback: None,
 559                close_callback: None,
 560                appearance_changed_callback: None,
 561                input_handler: None,
 562                pending_key_down: None,
 563                last_key_equivalent: None,
 564                synthetic_drag_counter: 0,
 565                last_fresh_keydown: None,
 566                traffic_light_position: options
 567                    .titlebar
 568                    .as_ref()
 569                    .and_then(|titlebar| titlebar.traffic_light_position),
 570                previous_modifiers_changed_event: None,
 571                ime_state: ImeState::None,
 572                ime_text: None,
 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                    // todo!() this panic()s when you click the red close button
 690                    // unless should_close returns false.
 691                    // (luckliy in zed it always returns false)
 692                    window.close();
 693                }
 694            })
 695            .detach();
 696    }
 697}
 698
 699impl PlatformWindow for MacWindow {
 700    fn bounds(&self) -> WindowBounds {
 701        self.0.as_ref().lock().bounds()
 702    }
 703
 704    fn content_size(&self) -> Size<Pixels> {
 705        self.0.as_ref().lock().content_size().into()
 706    }
 707
 708    fn scale_factor(&self) -> f32 {
 709        self.0.as_ref().lock().scale_factor()
 710    }
 711
 712    fn titlebar_height(&self) -> Pixels {
 713        self.0.as_ref().lock().titlebar_height()
 714    }
 715
 716    fn appearance(&self) -> WindowAppearance {
 717        unsafe {
 718            let appearance: id = msg_send![self.0.lock().native_window, effectiveAppearance];
 719            WindowAppearance::from_native(appearance)
 720        }
 721    }
 722
 723    fn display(&self) -> Rc<dyn PlatformDisplay> {
 724        unsafe {
 725            let screen = self.0.lock().native_window.screen();
 726            let device_description: id = msg_send![screen, deviceDescription];
 727            let screen_number: id = NSDictionary::valueForKey_(
 728                device_description,
 729                NSString::alloc(nil).init_str("NSScreenNumber"),
 730            );
 731
 732            let screen_number: u32 = msg_send![screen_number, unsignedIntValue];
 733
 734            Rc::new(MacDisplay(screen_number))
 735        }
 736    }
 737
 738    fn mouse_position(&self) -> Point<Pixels> {
 739        let position = unsafe {
 740            self.0
 741                .lock()
 742                .native_window
 743                .mouseLocationOutsideOfEventStream()
 744        };
 745        convert_mouse_position(position, self.content_size().height)
 746    }
 747
 748    fn modifiers(&self) -> Modifiers {
 749        unsafe {
 750            let modifiers: NSEventModifierFlags = msg_send![class!(NSEvent), modifierFlags];
 751
 752            let control = modifiers.contains(NSEventModifierFlags::NSControlKeyMask);
 753            let alt = modifiers.contains(NSEventModifierFlags::NSAlternateKeyMask);
 754            let shift = modifiers.contains(NSEventModifierFlags::NSShiftKeyMask);
 755            let command = modifiers.contains(NSEventModifierFlags::NSCommandKeyMask);
 756            let function = modifiers.contains(NSEventModifierFlags::NSFunctionKeyMask);
 757
 758            Modifiers {
 759                control,
 760                alt,
 761                shift,
 762                command,
 763                function,
 764            }
 765        }
 766    }
 767
 768    fn as_any_mut(&mut self) -> &mut dyn Any {
 769        self
 770    }
 771
 772    fn set_input_handler(&mut self, input_handler: Box<dyn PlatformInputHandler>) {
 773        self.0.as_ref().lock().input_handler = Some(input_handler);
 774    }
 775
 776    fn clear_input_handler(&mut self) {
 777        self.0.as_ref().lock().input_handler = None;
 778    }
 779
 780    fn prompt(&self, level: PromptLevel, msg: &str, answers: &[&str]) -> oneshot::Receiver<usize> {
 781        // macOs applies overrides to modal window buttons after they are added.
 782        // Two most important for this logic are:
 783        // * Buttons with "Cancel" title will be displayed as the last buttons in the modal
 784        // * Last button added to the modal via `addButtonWithTitle` stays focused
 785        // * Focused buttons react on "space"/" " keypresses
 786        // * Usage of `keyEquivalent`, `makeFirstResponder` or `setInitialFirstResponder` does not change the focus
 787        //
 788        // See also https://developer.apple.com/documentation/appkit/nsalert/1524532-addbuttonwithtitle#discussion
 789        // ```
 790        // By default, the first button has a key equivalent of Return,
 791        // any button with a title of “Cancel” has a key equivalent of Escape,
 792        // 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).
 793        // ```
 794        //
 795        // To avoid situations when the last element added is "Cancel" and it gets the focus
 796        // (hence stealing both ESC and Space shortcuts), we find and add one non-Cancel button
 797        // last, so it gets focus and a Space shortcut.
 798        // This way, "Save this file? Yes/No/Cancel"-ish modals will get all three buttons mapped with a key.
 799        let latest_non_cancel_label = answers
 800            .iter()
 801            .enumerate()
 802            .rev()
 803            .find(|(_, &label)| label != "Cancel")
 804            .filter(|&(label_index, _)| label_index > 0);
 805
 806        unsafe {
 807            let alert: id = msg_send![class!(NSAlert), alloc];
 808            let alert: id = msg_send![alert, init];
 809            let alert_style = match level {
 810                PromptLevel::Info => 1,
 811                PromptLevel::Warning => 0,
 812                PromptLevel::Critical => 2,
 813            };
 814            let _: () = msg_send![alert, setAlertStyle: alert_style];
 815            let _: () = msg_send![alert, setMessageText: ns_string(msg)];
 816
 817            for (ix, answer) in answers
 818                .iter()
 819                .enumerate()
 820                .filter(|&(ix, _)| Some(ix) != latest_non_cancel_label.map(|(ix, _)| ix))
 821            {
 822                let button: id = msg_send![alert, addButtonWithTitle: ns_string(answer)];
 823                let _: () = msg_send![button, setTag: ix as NSInteger];
 824            }
 825            if let Some((ix, answer)) = latest_non_cancel_label {
 826                let button: id = msg_send![alert, addButtonWithTitle: ns_string(answer)];
 827                let _: () = msg_send![button, setTag: ix as NSInteger];
 828            }
 829
 830            let (done_tx, done_rx) = oneshot::channel();
 831            let done_tx = Cell::new(Some(done_tx));
 832            let block = ConcreteBlock::new(move |answer: NSInteger| {
 833                if let Some(done_tx) = done_tx.take() {
 834                    let _ = done_tx.send(answer.try_into().unwrap());
 835                }
 836            });
 837            let block = block.copy();
 838            let native_window = self.0.lock().native_window;
 839            let executor = self.0.lock().executor.clone();
 840            executor
 841                .spawn(async move {
 842                    let _: () = msg_send![
 843                        alert,
 844                        beginSheetModalForWindow: native_window
 845                        completionHandler: block
 846                    ];
 847                })
 848                .detach();
 849
 850            done_rx
 851        }
 852    }
 853
 854    fn activate(&self) {
 855        let window = self.0.lock().native_window;
 856        let executor = self.0.lock().executor.clone();
 857        executor
 858            .spawn(async move {
 859                unsafe {
 860                    let _: () = msg_send![window, makeKeyAndOrderFront: nil];
 861                }
 862            })
 863            .detach();
 864    }
 865
 866    fn set_title(&mut self, title: &str) {
 867        unsafe {
 868            let app = NSApplication::sharedApplication(nil);
 869            let window = self.0.lock().native_window;
 870            let title = ns_string(title);
 871            let _: () = msg_send![app, changeWindowsItem:window title:title filename:false];
 872            let _: () = msg_send![window, setTitle: title];
 873            self.0.lock().move_traffic_light();
 874        }
 875    }
 876
 877    fn set_edited(&mut self, edited: bool) {
 878        unsafe {
 879            let window = self.0.lock().native_window;
 880            msg_send![window, setDocumentEdited: edited as BOOL]
 881        }
 882
 883        // Changing the document edited state resets the traffic light position,
 884        // so we have to move it again.
 885        self.0.lock().move_traffic_light();
 886    }
 887
 888    fn show_character_palette(&self) {
 889        let this = self.0.lock();
 890        let window = this.native_window;
 891        this.executor
 892            .spawn(async move {
 893                unsafe {
 894                    let app = NSApplication::sharedApplication(nil);
 895                    let _: () = msg_send![app, orderFrontCharacterPalette: window];
 896                }
 897            })
 898            .detach();
 899    }
 900
 901    fn minimize(&self) {
 902        let window = self.0.lock().native_window;
 903        unsafe {
 904            window.miniaturize_(nil);
 905        }
 906    }
 907
 908    fn zoom(&self) {
 909        let this = self.0.lock();
 910        let window = this.native_window;
 911        this.executor
 912            .spawn(async move {
 913                unsafe {
 914                    window.zoom_(nil);
 915                }
 916            })
 917            .detach();
 918    }
 919
 920    fn toggle_full_screen(&self) {
 921        let this = self.0.lock();
 922        let window = this.native_window;
 923        this.executor
 924            .spawn(async move {
 925                unsafe {
 926                    window.toggleFullScreen_(nil);
 927                }
 928            })
 929            .detach();
 930    }
 931
 932    fn on_input(&self, callback: Box<dyn FnMut(InputEvent) -> bool>) {
 933        self.0.as_ref().lock().event_callback = Some(callback);
 934    }
 935
 936    fn on_active_status_change(&self, callback: Box<dyn FnMut(bool)>) {
 937        self.0.as_ref().lock().activate_callback = Some(callback);
 938    }
 939
 940    fn on_resize(&self, callback: Box<dyn FnMut(Size<Pixels>, f32)>) {
 941        self.0.as_ref().lock().resize_callback = Some(callback);
 942    }
 943
 944    fn on_fullscreen(&self, callback: Box<dyn FnMut(bool)>) {
 945        self.0.as_ref().lock().fullscreen_callback = Some(callback);
 946    }
 947
 948    fn on_moved(&self, callback: Box<dyn FnMut()>) {
 949        self.0.as_ref().lock().moved_callback = Some(callback);
 950    }
 951
 952    fn on_should_close(&self, callback: Box<dyn FnMut() -> bool>) {
 953        self.0.as_ref().lock().should_close_callback = Some(callback);
 954    }
 955
 956    fn on_close(&self, callback: Box<dyn FnOnce()>) {
 957        self.0.as_ref().lock().close_callback = Some(callback);
 958    }
 959
 960    fn on_appearance_changed(&self, callback: Box<dyn FnMut()>) {
 961        self.0.lock().appearance_changed_callback = Some(callback);
 962    }
 963
 964    fn is_topmost_for_position(&self, position: Point<Pixels>) -> bool {
 965        let self_borrow = self.0.lock();
 966        let self_handle = self_borrow.handle;
 967
 968        unsafe {
 969            let app = NSApplication::sharedApplication(nil);
 970
 971            // Convert back to screen coordinates
 972            let screen_point = self_borrow.to_screen_ns_point(position);
 973
 974            let window_number: NSInteger = msg_send![class!(NSWindow), windowNumberAtPoint:screen_point belowWindowWithWindowNumber:0];
 975            let top_most_window: id = msg_send![app, windowWithWindowNumber: window_number];
 976
 977            let is_panel: BOOL = msg_send![top_most_window, isKindOfClass: PANEL_CLASS];
 978            let is_window: BOOL = msg_send![top_most_window, isKindOfClass: WINDOW_CLASS];
 979            if is_panel == YES || is_window == YES {
 980                let topmost_window = get_window_state(&*top_most_window).lock().handle;
 981                topmost_window == self_handle
 982            } else {
 983                // Someone else's window is on top
 984                false
 985            }
 986        }
 987    }
 988
 989    fn invalidate(&self) {
 990        let this = self.0.lock();
 991        unsafe {
 992            let _: () = msg_send![this.native_window.contentView(), setNeedsDisplay: YES];
 993        }
 994    }
 995
 996    fn sprite_atlas(&self) -> Arc<dyn PlatformAtlas> {
 997        self.0.lock().renderer.sprite_atlas().clone()
 998    }
 999}
1000
1001fn get_scale_factor(native_window: id) -> f32 {
1002    unsafe {
1003        let screen: id = msg_send![native_window, screen];
1004        NSScreen::backingScaleFactor(screen) as f32
1005    }
1006}
1007
1008unsafe fn get_window_state(object: &Object) -> Arc<Mutex<MacWindowState>> {
1009    let raw: *mut c_void = *object.get_ivar(WINDOW_STATE_IVAR);
1010    let rc1 = Arc::from_raw(raw as *mut Mutex<MacWindowState>);
1011    let rc2 = rc1.clone();
1012    mem::forget(rc1);
1013    rc2
1014}
1015
1016unsafe fn drop_window_state(object: &Object) {
1017    let raw: *mut c_void = *object.get_ivar(WINDOW_STATE_IVAR);
1018    Rc::from_raw(raw as *mut RefCell<MacWindowState>);
1019}
1020
1021extern "C" fn yes(_: &Object, _: Sel) -> BOOL {
1022    YES
1023}
1024
1025extern "C" fn dealloc_window(this: &Object, _: Sel) {
1026    unsafe {
1027        drop_window_state(this);
1028        let _: () = msg_send![super(this, class!(NSWindow)), dealloc];
1029    }
1030}
1031
1032extern "C" fn dealloc_view(this: &Object, _: Sel) {
1033    unsafe {
1034        drop_window_state(this);
1035        let _: () = msg_send![super(this, class!(NSView)), dealloc];
1036    }
1037}
1038
1039extern "C" fn handle_key_equivalent(this: &Object, _: Sel, native_event: id) -> BOOL {
1040    handle_key_event(this, native_event, true)
1041}
1042
1043extern "C" fn handle_key_down(this: &Object, _: Sel, native_event: id) {
1044    handle_key_event(this, native_event, false);
1045}
1046
1047extern "C" fn handle_key_event(this: &Object, native_event: id, key_equivalent: bool) -> BOOL {
1048    let window_state = unsafe { get_window_state(this) };
1049    let mut lock = window_state.as_ref().lock();
1050
1051    let window_height = lock.content_size().height;
1052    let event = unsafe { InputEvent::from_native(native_event, Some(window_height)) };
1053
1054    if let Some(InputEvent::KeyDown(event)) = event {
1055        // For certain keystrokes, macOS will first dispatch a "key equivalent" event.
1056        // If that event isn't handled, it will then dispatch a "key down" event. GPUI
1057        // makes no distinction between these two types of events, so we need to ignore
1058        // the "key down" event if we've already just processed its "key equivalent" version.
1059        if key_equivalent {
1060            lock.last_key_equivalent = Some(event.clone());
1061        } else if lock.last_key_equivalent.take().as_ref() == Some(&event) {
1062            return NO;
1063        }
1064
1065        let keydown = event.keystroke.clone();
1066        let fn_modifier = keydown.modifiers.function;
1067        // Ignore events from held-down keys after some of the initially-pressed keys
1068        // were released.
1069        if event.is_held {
1070            if lock.last_fresh_keydown.as_ref() != Some(&keydown) {
1071                return YES;
1072            }
1073        } else {
1074            lock.last_fresh_keydown = Some(keydown);
1075        }
1076        lock.pending_key_down = Some((event, None));
1077        drop(lock);
1078
1079        // Send the event to the input context for IME handling, unless the `fn` modifier is
1080        // being pressed.
1081        if !fn_modifier {
1082            unsafe {
1083                let input_context: id = msg_send![this, inputContext];
1084                let _: BOOL = msg_send![input_context, handleEvent: native_event];
1085            }
1086        }
1087
1088        let mut handled = false;
1089        let mut lock = window_state.lock();
1090        let ime_text = lock.ime_text.clone();
1091        if let Some((event, insert_text)) = lock.pending_key_down.take() {
1092            let is_held = event.is_held;
1093            if let Some(mut callback) = lock.event_callback.take() {
1094                drop(lock);
1095
1096                let is_composing =
1097                    with_input_handler(this, |input_handler| input_handler.marked_text_range())
1098                        .flatten()
1099                        .is_some();
1100                if !is_composing {
1101                    // if the IME has changed the key, we'll first emit an event with the character
1102                    // generated by the IME system; then fallback to the keystroke if that is not
1103                    // handled.
1104                    // cases that we have working:
1105                    // - " on a brazillian layout by typing <quote><space>
1106                    // - ctrl-` on a brazillian layout by typing <ctrl-`>
1107                    // - $ on a czech QWERTY layout by typing <alt-4>
1108                    // - 4 on a czech QWERTY layout by typing <shift-4>
1109                    // - ctrl-4 on a czech QWERTY layout by typing <ctrl-alt-4> (or <ctrl-shift-4>)
1110                    if ime_text.is_some() && ime_text.as_ref() != Some(&event.keystroke.key) {
1111                        let event_with_ime_text = KeyDownEvent {
1112                            is_held: false,
1113                            keystroke: Keystroke {
1114                                // we match ctrl because some use-cases need it.
1115                                // we don't match alt because it's often used to generate the optional character
1116                                // we don't match shift because we're not here with letters (usually)
1117                                // we don't match cmd/fn because they don't seem to use IME
1118                                modifiers: Default::default(),
1119                                key: ime_text.clone().unwrap(),
1120                                ime_key: None, // todo!("handle IME key")
1121                            },
1122                        };
1123                        handled = callback(InputEvent::KeyDown(event_with_ime_text));
1124                    }
1125                    if !handled {
1126                        // empty key happens when you type a deadkey in input composition.
1127                        // (e.g. on a brazillian keyboard typing quote is a deadkey)
1128                        if !event.keystroke.key.is_empty() {
1129                            handled = callback(InputEvent::KeyDown(event));
1130                        }
1131                    }
1132                }
1133
1134                if !handled {
1135                    if let Some(insert) = insert_text {
1136                        handled = true;
1137                        with_input_handler(this, |input_handler| {
1138                            input_handler
1139                                .replace_text_in_range(insert.replacement_range, &insert.text)
1140                        });
1141                    } else if !is_composing && is_held {
1142                        if let Some(last_insert_text) = ime_text {
1143                            //MacOS IME is a bit funky, and even when you've told it there's nothing to
1144                            //inter it will still swallow certain keys (e.g. 'f', 'j') and not others
1145                            //(e.g. 'n'). This is a problem for certain kinds of views, like the terminal
1146                            with_input_handler(this, |input_handler| {
1147                                if input_handler.selected_text_range().is_none() {
1148                                    handled = true;
1149                                    input_handler.replace_text_in_range(None, &last_insert_text)
1150                                }
1151                            });
1152                        }
1153                    }
1154                }
1155
1156                window_state.lock().event_callback = Some(callback);
1157            }
1158        } else {
1159            handled = true;
1160        }
1161
1162        handled as BOOL
1163    } else {
1164        NO
1165    }
1166}
1167
1168extern "C" fn handle_view_event(this: &Object, _: Sel, native_event: id) {
1169    let window_state = unsafe { get_window_state(this) };
1170    let weak_window_state = Arc::downgrade(&window_state);
1171    let mut lock = window_state.as_ref().lock();
1172    let is_active = unsafe { lock.native_window.isKeyWindow() == YES };
1173
1174    let window_height = lock.content_size().height;
1175    let event = unsafe { InputEvent::from_native(native_event, Some(window_height)) };
1176
1177    if let Some(mut event) = event {
1178        match &mut event {
1179            InputEvent::MouseDown(
1180                event @ MouseDownEvent {
1181                    button: MouseButton::Left,
1182                    modifiers: Modifiers { control: true, .. },
1183                    ..
1184                },
1185            ) => {
1186                // On mac, a ctrl-left click should be handled as a right click.
1187                *event = MouseDownEvent {
1188                    button: MouseButton::Right,
1189                    modifiers: Modifiers {
1190                        control: false,
1191                        ..event.modifiers
1192                    },
1193                    click_count: 1,
1194                    ..*event
1195                };
1196            }
1197
1198            // Because we map a ctrl-left_down to a right_down -> right_up let's ignore
1199            // the ctrl-left_up to avoid having a mismatch in button down/up events if the
1200            // user is still holding ctrl when releasing the left mouse button
1201            InputEvent::MouseUp(
1202                event @ MouseUpEvent {
1203                    button: MouseButton::Left,
1204                    modifiers: Modifiers { control: true, .. },
1205                    ..
1206                },
1207            ) => {
1208                *event = MouseUpEvent {
1209                    button: MouseButton::Right,
1210                    modifiers: Modifiers {
1211                        control: false,
1212                        ..event.modifiers
1213                    },
1214                    click_count: 1,
1215                    ..*event
1216                };
1217            }
1218
1219            _ => {}
1220        };
1221
1222        match &event {
1223            InputEvent::MouseMove(
1224                event @ MouseMoveEvent {
1225                    pressed_button: Some(_),
1226                    ..
1227                },
1228            ) => {
1229                lock.synthetic_drag_counter += 1;
1230                let executor = lock.executor.clone();
1231                executor
1232                    .spawn(synthetic_drag(
1233                        weak_window_state,
1234                        lock.synthetic_drag_counter,
1235                        event.clone(),
1236                    ))
1237                    .detach();
1238            }
1239
1240            InputEvent::MouseMove(_) if !(is_active || lock.kind == WindowKind::PopUp) => return,
1241
1242            InputEvent::MouseUp(MouseUpEvent { .. }) => {
1243                lock.synthetic_drag_counter += 1;
1244            }
1245
1246            InputEvent::ModifiersChanged(ModifiersChangedEvent { modifiers }) => {
1247                // Only raise modifiers changed event when they have actually changed
1248                if let Some(InputEvent::ModifiersChanged(ModifiersChangedEvent {
1249                    modifiers: prev_modifiers,
1250                })) = &lock.previous_modifiers_changed_event
1251                {
1252                    if prev_modifiers == modifiers {
1253                        return;
1254                    }
1255                }
1256
1257                lock.previous_modifiers_changed_event = Some(event.clone());
1258            }
1259
1260            _ => {}
1261        }
1262
1263        if let Some(mut callback) = lock.event_callback.take() {
1264            drop(lock);
1265            callback(event);
1266            window_state.lock().event_callback = Some(callback);
1267        }
1268    }
1269}
1270
1271// Allows us to receive `cmd-.` (the shortcut for closing a dialog)
1272// https://bugs.eclipse.org/bugs/show_bug.cgi?id=300620#c6
1273extern "C" fn cancel_operation(this: &Object, _sel: Sel, _sender: id) {
1274    let window_state = unsafe { get_window_state(this) };
1275    let mut lock = window_state.as_ref().lock();
1276
1277    let keystroke = Keystroke {
1278        modifiers: Default::default(),
1279        key: ".".into(),
1280        ime_key: None,
1281    };
1282    let event = InputEvent::KeyDown(KeyDownEvent {
1283        keystroke: keystroke.clone(),
1284        is_held: false,
1285    });
1286
1287    lock.last_fresh_keydown = Some(keystroke);
1288    if let Some(mut callback) = lock.event_callback.take() {
1289        drop(lock);
1290        callback(event);
1291        window_state.lock().event_callback = Some(callback);
1292    }
1293}
1294
1295extern "C" fn window_did_resize(this: &Object, _: Sel, _: id) {
1296    let window_state = unsafe { get_window_state(this) };
1297    window_state.as_ref().lock().move_traffic_light();
1298}
1299
1300extern "C" fn window_will_enter_fullscreen(this: &Object, _: Sel, _: id) {
1301    window_fullscreen_changed(this, true);
1302}
1303
1304extern "C" fn window_will_exit_fullscreen(this: &Object, _: Sel, _: id) {
1305    window_fullscreen_changed(this, false);
1306}
1307
1308fn window_fullscreen_changed(this: &Object, is_fullscreen: bool) {
1309    let window_state = unsafe { get_window_state(this) };
1310    let mut lock = window_state.as_ref().lock();
1311    if let Some(mut callback) = lock.fullscreen_callback.take() {
1312        drop(lock);
1313        callback(is_fullscreen);
1314        window_state.lock().fullscreen_callback = Some(callback);
1315    }
1316}
1317
1318extern "C" fn window_did_move(this: &Object, _: Sel, _: id) {
1319    let window_state = unsafe { get_window_state(this) };
1320    let mut lock = window_state.as_ref().lock();
1321    if let Some(mut callback) = lock.moved_callback.take() {
1322        drop(lock);
1323        callback();
1324        window_state.lock().moved_callback = Some(callback);
1325    }
1326}
1327
1328extern "C" fn window_did_change_key_status(this: &Object, selector: Sel, _: id) {
1329    let window_state = unsafe { get_window_state(this) };
1330    let lock = window_state.lock();
1331    let is_active = unsafe { lock.native_window.isKeyWindow() == YES };
1332
1333    // When opening a pop-up while the application isn't active, Cocoa sends a spurious
1334    // `windowDidBecomeKey` message to the previous key window even though that window
1335    // isn't actually key. This causes a bug if the application is later activated while
1336    // the pop-up is still open, making it impossible to activate the previous key window
1337    // even if the pop-up gets closed. The only way to activate it again is to de-activate
1338    // the app and re-activate it, which is a pretty bad UX.
1339    // The following code detects the spurious event and invokes `resignKeyWindow`:
1340    // in theory, we're not supposed to invoke this method manually but it balances out
1341    // the spurious `becomeKeyWindow` event and helps us work around that bug.
1342    if selector == sel!(windowDidBecomeKey:) {
1343        if !is_active {
1344            unsafe {
1345                let _: () = msg_send![lock.native_window, resignKeyWindow];
1346                return;
1347            }
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            window_state.lock().pending_key_down = Some(pending_key_down);
1572        }
1573    }
1574}
1575
1576extern "C" fn set_marked_text(
1577    this: &Object,
1578    _: Sel,
1579    text: id,
1580    selected_range: NSRange,
1581    replacement_range: NSRange,
1582) {
1583    unsafe {
1584        let window_state = get_window_state(this);
1585        window_state.lock().pending_key_down.take();
1586
1587        let is_attributed_string: BOOL =
1588            msg_send![text, isKindOfClass: [class!(NSAttributedString)]];
1589        let text: id = if is_attributed_string == YES {
1590            msg_send![text, string]
1591        } else {
1592            text
1593        };
1594        let selected_range = selected_range.to_range();
1595        let replacement_range = replacement_range.to_range();
1596        let text = CStr::from_ptr(text.UTF8String() as *mut c_char)
1597            .to_str()
1598            .unwrap();
1599
1600        window_state.lock().ime_state = ImeState::Acted;
1601        window_state.lock().ime_text = Some(text.to_string());
1602
1603        with_input_handler(this, |input_handler| {
1604            input_handler.replace_and_mark_text_in_range(replacement_range, text, selected_range);
1605        });
1606    }
1607}
1608
1609extern "C" fn unmark_text(this: &Object, _: Sel) {
1610    unsafe {
1611        let state = get_window_state(this);
1612        let mut borrow = state.lock();
1613        borrow.ime_state = ImeState::Acted;
1614        borrow.ime_text.take();
1615    }
1616
1617    with_input_handler(this, |input_handler| input_handler.unmark_text());
1618}
1619
1620extern "C" fn attributed_substring_for_proposed_range(
1621    this: &Object,
1622    _: Sel,
1623    range: NSRange,
1624    _actual_range: *mut c_void,
1625) -> id {
1626    with_input_handler(this, |input_handler| {
1627        let range = range.to_range()?;
1628        if range.is_empty() {
1629            return None;
1630        }
1631
1632        let selected_text = input_handler.text_for_range(range)?;
1633        unsafe {
1634            let string: id = msg_send![class!(NSAttributedString), alloc];
1635            let string: id = msg_send![string, initWithString: ns_string(&selected_text)];
1636            Some(string)
1637        }
1638    })
1639    .flatten()
1640    .unwrap_or(nil)
1641}
1642
1643extern "C" fn do_command_by_selector(this: &Object, _: Sel, _: Sel) {
1644    unsafe {
1645        let state = get_window_state(this);
1646        let mut borrow = state.lock();
1647        borrow.ime_state = ImeState::Continue;
1648        borrow.ime_text.take();
1649    }
1650}
1651
1652extern "C" fn view_did_change_effective_appearance(this: &Object, _: Sel) {
1653    unsafe {
1654        let state = get_window_state(this);
1655        let mut lock = state.as_ref().lock();
1656        if let Some(mut callback) = lock.appearance_changed_callback.take() {
1657            drop(lock);
1658            callback();
1659            state.lock().appearance_changed_callback = Some(callback);
1660        }
1661    }
1662}
1663
1664extern "C" fn accepts_first_mouse(this: &Object, _: Sel, _: id) -> BOOL {
1665    unsafe {
1666        let state = get_window_state(this);
1667        let lock = state.as_ref().lock();
1668        return if lock.kind == WindowKind::PopUp {
1669            YES
1670        } else {
1671            NO
1672        };
1673    }
1674}
1675
1676extern "C" fn dragging_entered(this: &Object, _: Sel, dragging_info: id) -> NSDragOperation {
1677    let window_state = unsafe { get_window_state(this) };
1678    if send_new_event(&window_state, {
1679        let position = drag_event_position(&window_state, dragging_info);
1680        let paths = external_paths_from_event(dragging_info);
1681        InputEvent::FileDrop(FileDropEvent::Entered {
1682            position,
1683            files: paths,
1684        })
1685    }) {
1686        NSDragOperationCopy
1687    } else {
1688        NSDragOperationNone
1689    }
1690}
1691
1692extern "C" fn dragging_updated(this: &Object, _: Sel, dragging_info: id) -> NSDragOperation {
1693    let window_state = unsafe { get_window_state(this) };
1694    let position = drag_event_position(&window_state, dragging_info);
1695    if send_new_event(
1696        &window_state,
1697        InputEvent::FileDrop(FileDropEvent::Pending { position }),
1698    ) {
1699        NSDragOperationCopy
1700    } else {
1701        NSDragOperationNone
1702    }
1703}
1704
1705extern "C" fn dragging_exited(this: &Object, _: Sel, _: id) {
1706    let window_state = unsafe { get_window_state(this) };
1707    send_new_event(&window_state, InputEvent::FileDrop(FileDropEvent::Exited));
1708}
1709
1710extern "C" fn perform_drag_operation(this: &Object, _: Sel, dragging_info: id) -> BOOL {
1711    let window_state = unsafe { get_window_state(this) };
1712    let position = drag_event_position(&window_state, dragging_info);
1713    if send_new_event(
1714        &window_state,
1715        InputEvent::FileDrop(FileDropEvent::Submit { position }),
1716    ) {
1717        YES
1718    } else {
1719        NO
1720    }
1721}
1722
1723fn external_paths_from_event(dragging_info: *mut Object) -> ExternalPaths {
1724    let mut paths = SmallVec::new();
1725    let pasteboard: id = unsafe { msg_send![dragging_info, draggingPasteboard] };
1726    let filenames = unsafe { NSPasteboard::propertyListForType(pasteboard, NSFilenamesPboardType) };
1727    for file in unsafe { filenames.iter() } {
1728        let path = unsafe {
1729            let f = NSString::UTF8String(file);
1730            CStr::from_ptr(f).to_string_lossy().into_owned()
1731        };
1732        paths.push(PathBuf::from(path))
1733    }
1734    ExternalPaths(paths)
1735}
1736
1737extern "C" fn conclude_drag_operation(this: &Object, _: Sel, _: id) {
1738    let window_state = unsafe { get_window_state(this) };
1739    send_new_event(&window_state, InputEvent::FileDrop(FileDropEvent::Exited));
1740}
1741
1742async fn synthetic_drag(
1743    window_state: Weak<Mutex<MacWindowState>>,
1744    drag_id: usize,
1745    event: MouseMoveEvent,
1746) {
1747    loop {
1748        Timer::after(Duration::from_millis(16)).await;
1749        if let Some(window_state) = window_state.upgrade() {
1750            let mut lock = window_state.lock();
1751            if lock.synthetic_drag_counter == drag_id {
1752                if let Some(mut callback) = lock.event_callback.take() {
1753                    drop(lock);
1754                    callback(InputEvent::MouseMove(event.clone()));
1755                    window_state.lock().event_callback = Some(callback);
1756                }
1757            } else {
1758                break;
1759            }
1760        }
1761    }
1762}
1763
1764fn send_new_event(window_state_lock: &Mutex<MacWindowState>, e: InputEvent) -> bool {
1765    let window_state = window_state_lock.lock().event_callback.take();
1766    if let Some(mut callback) = window_state {
1767        callback(e);
1768        window_state_lock.lock().event_callback = Some(callback);
1769        true
1770    } else {
1771        false
1772    }
1773}
1774
1775fn drag_event_position(window_state: &Mutex<MacWindowState>, dragging_info: id) -> Point<Pixels> {
1776    let drag_location: NSPoint = unsafe { msg_send![dragging_info, draggingLocation] };
1777    convert_mouse_position(drag_location, window_state.lock().content_size().height)
1778}
1779
1780fn with_input_handler<F, R>(window: &Object, f: F) -> Option<R>
1781where
1782    F: FnOnce(&mut dyn PlatformInputHandler) -> R,
1783{
1784    let window_state = unsafe { get_window_state(window) };
1785    let mut lock = window_state.as_ref().lock();
1786    if let Some(mut input_handler) = lock.input_handler.take() {
1787        drop(lock);
1788        let result = f(input_handler.as_mut());
1789        window_state.lock().input_handler = Some(input_handler);
1790        Some(result)
1791    } else {
1792        None
1793    }
1794}