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("GPUIWindow", class!(NSWindow));
  89    PANEL_CLASS = build_window_class("GPUIPanel", class!(NSPanel));
  90    VIEW_CLASS = {
  91        let mut decl = ClassDecl::new("GPUIView", class!(NSView)).unwrap();
  92        decl.add_ivar::<*mut c_void>(WINDOW_STATE_IVAR);
  93
  94        decl.add_method(sel!(dealloc), dealloc_view as extern "C" fn(&Object, Sel));
  95
  96        decl.add_method(
  97            sel!(performKeyEquivalent:),
  98            handle_key_equivalent as extern "C" fn(&Object, Sel, id) -> BOOL,
  99        );
 100        decl.add_method(
 101            sel!(keyDown:),
 102            handle_key_down as extern "C" fn(&Object, Sel, id),
 103        );
 104        decl.add_method(
 105            sel!(mouseDown:),
 106            handle_view_event as extern "C" fn(&Object, Sel, id),
 107        );
 108        decl.add_method(
 109            sel!(mouseUp:),
 110            handle_view_event as extern "C" fn(&Object, Sel, id),
 111        );
 112        decl.add_method(
 113            sel!(rightMouseDown:),
 114            handle_view_event as extern "C" fn(&Object, Sel, id),
 115        );
 116        decl.add_method(
 117            sel!(rightMouseUp:),
 118            handle_view_event as extern "C" fn(&Object, Sel, id),
 119        );
 120        decl.add_method(
 121            sel!(otherMouseDown:),
 122            handle_view_event as extern "C" fn(&Object, Sel, id),
 123        );
 124        decl.add_method(
 125            sel!(otherMouseUp:),
 126            handle_view_event as extern "C" fn(&Object, Sel, id),
 127        );
 128        decl.add_method(
 129            sel!(mouseMoved:),
 130            handle_view_event as extern "C" fn(&Object, Sel, id),
 131        );
 132        decl.add_method(
 133            sel!(mouseExited:),
 134            handle_view_event as extern "C" fn(&Object, Sel, id),
 135        );
 136        decl.add_method(
 137            sel!(mouseDragged:),
 138            handle_view_event as extern "C" fn(&Object, Sel, id),
 139        );
 140        decl.add_method(
 141            sel!(scrollWheel:),
 142            handle_view_event as extern "C" fn(&Object, Sel, id),
 143        );
 144        decl.add_method(
 145            sel!(flagsChanged:),
 146            handle_view_event as extern "C" fn(&Object, Sel, id),
 147        );
 148        decl.add_method(
 149            sel!(cancelOperation:),
 150            cancel_operation as extern "C" fn(&Object, Sel, id),
 151        );
 152
 153        decl.add_method(
 154            sel!(makeBackingLayer),
 155            make_backing_layer as extern "C" fn(&Object, Sel) -> id,
 156        );
 157
 158        decl.add_protocol(Protocol::get("CALayerDelegate").unwrap());
 159        decl.add_method(
 160            sel!(viewDidChangeBackingProperties),
 161            view_did_change_backing_properties as extern "C" fn(&Object, Sel),
 162        );
 163        decl.add_method(
 164            sel!(setFrameSize:),
 165            set_frame_size as extern "C" fn(&Object, Sel, NSSize),
 166        );
 167        decl.add_method(
 168            sel!(displayLayer:),
 169            display_layer as extern "C" fn(&Object, Sel, id),
 170        );
 171
 172        decl.add_protocol(Protocol::get("NSTextInputClient").unwrap());
 173        decl.add_method(
 174            sel!(validAttributesForMarkedText),
 175            valid_attributes_for_marked_text as extern "C" fn(&Object, Sel) -> id,
 176        );
 177        decl.add_method(
 178            sel!(hasMarkedText),
 179            has_marked_text as extern "C" fn(&Object, Sel) -> BOOL,
 180        );
 181        decl.add_method(
 182            sel!(markedRange),
 183            marked_range as extern "C" fn(&Object, Sel) -> NSRange,
 184        );
 185        decl.add_method(
 186            sel!(selectedRange),
 187            selected_range as extern "C" fn(&Object, Sel) -> NSRange,
 188        );
 189        decl.add_method(
 190            sel!(firstRectForCharacterRange:actualRange:),
 191            first_rect_for_character_range as extern "C" fn(&Object, Sel, NSRange, id) -> NSRect,
 192        );
 193        decl.add_method(
 194            sel!(insertText:replacementRange:),
 195            insert_text as extern "C" fn(&Object, Sel, id, NSRange),
 196        );
 197        decl.add_method(
 198            sel!(setMarkedText:selectedRange:replacementRange:),
 199            set_marked_text as extern "C" fn(&Object, Sel, id, NSRange, NSRange),
 200        );
 201        decl.add_method(sel!(unmarkText), unmark_text as extern "C" fn(&Object, Sel));
 202        decl.add_method(
 203            sel!(attributedSubstringForProposedRange:actualRange:),
 204            attributed_substring_for_proposed_range
 205                as extern "C" fn(&Object, Sel, NSRange, *mut c_void) -> id,
 206        );
 207        decl.add_method(
 208            sel!(viewDidChangeEffectiveAppearance),
 209            view_did_change_effective_appearance as extern "C" fn(&Object, Sel),
 210        );
 211
 212        // Suppress beep on keystrokes with modifier keys.
 213        decl.add_method(
 214            sel!(doCommandBySelector:),
 215            do_command_by_selector as extern "C" fn(&Object, Sel, Sel),
 216        );
 217
 218        decl.add_method(
 219            sel!(acceptsFirstMouse:),
 220            accepts_first_mouse as extern "C" fn(&Object, Sel, id) -> BOOL,
 221        );
 222
 223        decl.register()
 224    };
 225}
 226
 227pub 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        unsafe {
 890            let app = NSApplication::sharedApplication(nil);
 891            let window = self.0.lock().native_window;
 892            let _: () = msg_send![app, orderFrontCharacterPalette: window];
 893        }
 894    }
 895
 896    fn minimize(&self) {
 897        let window = self.0.lock().native_window;
 898        unsafe {
 899            window.miniaturize_(nil);
 900        }
 901    }
 902
 903    fn zoom(&self) {
 904        let this = self.0.lock();
 905        let window = this.native_window;
 906        this.executor
 907            .spawn(async move {
 908                unsafe {
 909                    window.zoom_(nil);
 910                }
 911            })
 912            .detach();
 913    }
 914
 915    fn toggle_full_screen(&self) {
 916        let this = self.0.lock();
 917        let window = this.native_window;
 918        this.executor
 919            .spawn(async move {
 920                unsafe {
 921                    window.toggleFullScreen_(nil);
 922                }
 923            })
 924            .detach();
 925    }
 926
 927    fn on_input(&self, callback: Box<dyn FnMut(InputEvent) -> bool>) {
 928        self.0.as_ref().lock().event_callback = Some(callback);
 929    }
 930
 931    fn on_active_status_change(&self, callback: Box<dyn FnMut(bool)>) {
 932        self.0.as_ref().lock().activate_callback = Some(callback);
 933    }
 934
 935    fn on_resize(&self, callback: Box<dyn FnMut(Size<Pixels>, f32)>) {
 936        self.0.as_ref().lock().resize_callback = Some(callback);
 937    }
 938
 939    fn on_fullscreen(&self, callback: Box<dyn FnMut(bool)>) {
 940        self.0.as_ref().lock().fullscreen_callback = Some(callback);
 941    }
 942
 943    fn on_moved(&self, callback: Box<dyn FnMut()>) {
 944        self.0.as_ref().lock().moved_callback = Some(callback);
 945    }
 946
 947    fn on_should_close(&self, callback: Box<dyn FnMut() -> bool>) {
 948        self.0.as_ref().lock().should_close_callback = Some(callback);
 949    }
 950
 951    fn on_close(&self, callback: Box<dyn FnOnce()>) {
 952        self.0.as_ref().lock().close_callback = Some(callback);
 953    }
 954
 955    fn on_appearance_changed(&self, callback: Box<dyn FnMut()>) {
 956        self.0.lock().appearance_changed_callback = Some(callback);
 957    }
 958
 959    fn is_topmost_for_position(&self, position: Point<Pixels>) -> bool {
 960        let self_borrow = self.0.lock();
 961        let self_handle = self_borrow.handle;
 962
 963        unsafe {
 964            let app = NSApplication::sharedApplication(nil);
 965
 966            // Convert back to screen coordinates
 967            let screen_point = self_borrow.to_screen_ns_point(position);
 968
 969            let window_number: NSInteger = msg_send![class!(NSWindow), windowNumberAtPoint:screen_point belowWindowWithWindowNumber:0];
 970            let top_most_window: id = msg_send![app, windowWithWindowNumber: window_number];
 971
 972            let is_panel: BOOL = msg_send![top_most_window, isKindOfClass: PANEL_CLASS];
 973            let is_window: BOOL = msg_send![top_most_window, isKindOfClass: WINDOW_CLASS];
 974            if is_panel == YES || is_window == YES {
 975                let topmost_window = get_window_state(&*top_most_window).lock().handle;
 976                topmost_window == self_handle
 977            } else {
 978                // Someone else's window is on top
 979                false
 980            }
 981        }
 982    }
 983
 984    fn invalidate(&self) {
 985        let this = self.0.lock();
 986        unsafe {
 987            let _: () = msg_send![this.native_window.contentView(), setNeedsDisplay: YES];
 988        }
 989    }
 990
 991    fn sprite_atlas(&self) -> Arc<dyn PlatformAtlas> {
 992        self.0.lock().renderer.sprite_atlas().clone()
 993    }
 994}
 995
 996fn get_scale_factor(native_window: id) -> f32 {
 997    unsafe {
 998        let screen: id = msg_send![native_window, screen];
 999        NSScreen::backingScaleFactor(screen) as f32
1000    }
1001}
1002
1003unsafe fn get_window_state(object: &Object) -> Arc<Mutex<MacWindowState>> {
1004    let raw: *mut c_void = *object.get_ivar(WINDOW_STATE_IVAR);
1005    let rc1 = Arc::from_raw(raw as *mut Mutex<MacWindowState>);
1006    let rc2 = rc1.clone();
1007    mem::forget(rc1);
1008    rc2
1009}
1010
1011unsafe fn drop_window_state(object: &Object) {
1012    let raw: *mut c_void = *object.get_ivar(WINDOW_STATE_IVAR);
1013    Rc::from_raw(raw as *mut RefCell<MacWindowState>);
1014}
1015
1016extern "C" fn yes(_: &Object, _: Sel) -> BOOL {
1017    YES
1018}
1019
1020extern "C" fn dealloc_window(this: &Object, _: Sel) {
1021    unsafe {
1022        drop_window_state(this);
1023        let _: () = msg_send![super(this, class!(NSWindow)), dealloc];
1024    }
1025}
1026
1027extern "C" fn dealloc_view(this: &Object, _: Sel) {
1028    unsafe {
1029        drop_window_state(this);
1030        let _: () = msg_send![super(this, class!(NSView)), dealloc];
1031    }
1032}
1033
1034extern "C" fn handle_key_equivalent(this: &Object, _: Sel, native_event: id) -> BOOL {
1035    handle_key_event(this, native_event, true)
1036}
1037
1038extern "C" fn handle_key_down(this: &Object, _: Sel, native_event: id) {
1039    handle_key_event(this, native_event, false);
1040}
1041
1042extern "C" fn handle_key_event(this: &Object, native_event: id, key_equivalent: bool) -> BOOL {
1043    let window_state = unsafe { get_window_state(this) };
1044    let mut lock = window_state.as_ref().lock();
1045
1046    let window_height = lock.content_size().height;
1047    let event = unsafe { InputEvent::from_native(native_event, Some(window_height)) };
1048
1049    if let Some(InputEvent::KeyDown(event)) = event {
1050        // For certain keystrokes, macOS will first dispatch a "key equivalent" event.
1051        // If that event isn't handled, it will then dispatch a "key down" event. GPUI
1052        // makes no distinction between these two types of events, so we need to ignore
1053        // the "key down" event if we've already just processed its "key equivalent" version.
1054        if key_equivalent {
1055            lock.last_key_equivalent = Some(event.clone());
1056        } else if lock.last_key_equivalent.take().as_ref() == Some(&event) {
1057            return NO;
1058        }
1059
1060        let keydown = event.keystroke.clone();
1061        let fn_modifier = keydown.modifiers.function;
1062        // Ignore events from held-down keys after some of the initially-pressed keys
1063        // were released.
1064        if event.is_held {
1065            if lock.last_fresh_keydown.as_ref() != Some(&keydown) {
1066                return YES;
1067            }
1068        } else {
1069            lock.last_fresh_keydown = Some(keydown);
1070        }
1071        lock.pending_key_down = Some((event, None));
1072        drop(lock);
1073
1074        // Send the event to the input context for IME handling, unless the `fn` modifier is
1075        // being pressed.
1076        if !fn_modifier {
1077            unsafe {
1078                let input_context: id = msg_send![this, inputContext];
1079                let _: BOOL = msg_send![input_context, handleEvent: native_event];
1080            }
1081        }
1082
1083        let mut handled = false;
1084        let mut lock = window_state.lock();
1085        let ime_text = lock.ime_text.clone();
1086        if let Some((event, insert_text)) = lock.pending_key_down.take() {
1087            let is_held = event.is_held;
1088            if let Some(mut callback) = lock.event_callback.take() {
1089                drop(lock);
1090
1091                let is_composing =
1092                    with_input_handler(this, |input_handler| input_handler.marked_text_range())
1093                        .flatten()
1094                        .is_some();
1095                if !is_composing {
1096                    // if the IME has changed the key, we'll first emit an event with the character
1097                    // generated by the IME system; then fallback to the keystroke if that is not
1098                    // handled.
1099                    // cases that we have working:
1100                    // - " on a brazillian layout by typing <quote><space>
1101                    // - ctrl-` on a brazillian layout by typing <ctrl-`>
1102                    // - $ on a czech QWERTY layout by typing <alt-4>
1103                    // - 4 on a czech QWERTY layout by typing <shift-4>
1104                    // - ctrl-4 on a czech QWERTY layout by typing <ctrl-alt-4> (or <ctrl-shift-4>)
1105                    if ime_text.is_some() && ime_text.as_ref() != Some(&event.keystroke.key) {
1106                        let event_with_ime_text = KeyDownEvent {
1107                            is_held: false,
1108                            keystroke: Keystroke {
1109                                // we match ctrl because some use-cases need it.
1110                                // we don't match alt because it's often used to generate the optional character
1111                                // we don't match shift because we're not here with letters (usually)
1112                                // we don't match cmd/fn because they don't seem to use IME
1113                                modifiers: Default::default(),
1114                                key: ime_text.clone().unwrap(),
1115                                ime_key: None, // todo!("handle IME key")
1116                            },
1117                        };
1118                        handled = callback(InputEvent::KeyDown(event_with_ime_text));
1119                    }
1120                    if !handled {
1121                        // empty key happens when you type a deadkey in input composition.
1122                        // (e.g. on a brazillian keyboard typing quote is a deadkey)
1123                        if !event.keystroke.key.is_empty() {
1124                            handled = callback(InputEvent::KeyDown(event));
1125                        }
1126                    }
1127                }
1128
1129                if !handled {
1130                    if let Some(insert) = insert_text {
1131                        handled = true;
1132                        with_input_handler(this, |input_handler| {
1133                            input_handler
1134                                .replace_text_in_range(insert.replacement_range, &insert.text)
1135                        });
1136                    } else if !is_composing && is_held {
1137                        if let Some(last_insert_text) = ime_text {
1138                            //MacOS IME is a bit funky, and even when you've told it there's nothing to
1139                            //inter it will still swallow certain keys (e.g. 'f', 'j') and not others
1140                            //(e.g. 'n'). This is a problem for certain kinds of views, like the terminal
1141                            with_input_handler(this, |input_handler| {
1142                                if input_handler.selected_text_range().is_none() {
1143                                    handled = true;
1144                                    input_handler.replace_text_in_range(None, &last_insert_text)
1145                                }
1146                            });
1147                        }
1148                    }
1149                }
1150
1151                window_state.lock().event_callback = Some(callback);
1152            }
1153        } else {
1154            handled = true;
1155        }
1156
1157        handled as BOOL
1158    } else {
1159        NO
1160    }
1161}
1162
1163extern "C" fn handle_view_event(this: &Object, _: Sel, native_event: id) {
1164    let window_state = unsafe { get_window_state(this) };
1165    let weak_window_state = Arc::downgrade(&window_state);
1166    let mut lock = window_state.as_ref().lock();
1167    let is_active = unsafe { lock.native_window.isKeyWindow() == YES };
1168
1169    let window_height = lock.content_size().height;
1170    let event = unsafe { InputEvent::from_native(native_event, Some(window_height)) };
1171
1172    if let Some(mut event) = event {
1173        match &mut event {
1174            InputEvent::MouseDown(
1175                event @ MouseDownEvent {
1176                    button: MouseButton::Left,
1177                    modifiers: Modifiers { control: true, .. },
1178                    ..
1179                },
1180            ) => {
1181                // On mac, a ctrl-left click should be handled as a right click.
1182                *event = MouseDownEvent {
1183                    button: MouseButton::Right,
1184                    modifiers: Modifiers {
1185                        control: false,
1186                        ..event.modifiers
1187                    },
1188                    click_count: 1,
1189                    ..*event
1190                };
1191            }
1192
1193            // Because we map a ctrl-left_down to a right_down -> right_up let's ignore
1194            // the ctrl-left_up to avoid having a mismatch in button down/up events if the
1195            // user is still holding ctrl when releasing the left mouse button
1196            InputEvent::MouseUp(
1197                event @ MouseUpEvent {
1198                    button: MouseButton::Left,
1199                    modifiers: Modifiers { control: true, .. },
1200                    ..
1201                },
1202            ) => {
1203                *event = MouseUpEvent {
1204                    button: MouseButton::Right,
1205                    modifiers: Modifiers {
1206                        control: false,
1207                        ..event.modifiers
1208                    },
1209                    click_count: 1,
1210                    ..*event
1211                };
1212            }
1213
1214            _ => {}
1215        };
1216
1217        match &event {
1218            InputEvent::MouseMove(
1219                event @ MouseMoveEvent {
1220                    pressed_button: Some(_),
1221                    ..
1222                },
1223            ) => {
1224                lock.synthetic_drag_counter += 1;
1225                let executor = lock.executor.clone();
1226                executor
1227                    .spawn(synthetic_drag(
1228                        weak_window_state,
1229                        lock.synthetic_drag_counter,
1230                        event.clone(),
1231                    ))
1232                    .detach();
1233            }
1234
1235            InputEvent::MouseMove(_) if !(is_active || lock.kind == WindowKind::PopUp) => return,
1236
1237            InputEvent::MouseUp(MouseUpEvent { .. }) => {
1238                lock.synthetic_drag_counter += 1;
1239            }
1240
1241            InputEvent::ModifiersChanged(ModifiersChangedEvent { modifiers }) => {
1242                // Only raise modifiers changed event when they have actually changed
1243                if let Some(InputEvent::ModifiersChanged(ModifiersChangedEvent {
1244                    modifiers: prev_modifiers,
1245                })) = &lock.previous_modifiers_changed_event
1246                {
1247                    if prev_modifiers == modifiers {
1248                        return;
1249                    }
1250                }
1251
1252                lock.previous_modifiers_changed_event = Some(event.clone());
1253            }
1254
1255            _ => {}
1256        }
1257
1258        if let Some(mut callback) = lock.event_callback.take() {
1259            drop(lock);
1260            callback(event);
1261            window_state.lock().event_callback = Some(callback);
1262        }
1263    }
1264}
1265
1266// Allows us to receive `cmd-.` (the shortcut for closing a dialog)
1267// https://bugs.eclipse.org/bugs/show_bug.cgi?id=300620#c6
1268extern "C" fn cancel_operation(this: &Object, _sel: Sel, _sender: id) {
1269    let window_state = unsafe { get_window_state(this) };
1270    let mut lock = window_state.as_ref().lock();
1271
1272    let keystroke = Keystroke {
1273        modifiers: Default::default(),
1274        key: ".".into(),
1275        ime_key: None,
1276    };
1277    let event = InputEvent::KeyDown(KeyDownEvent {
1278        keystroke: keystroke.clone(),
1279        is_held: false,
1280    });
1281
1282    lock.last_fresh_keydown = Some(keystroke);
1283    if let Some(mut callback) = lock.event_callback.take() {
1284        drop(lock);
1285        callback(event);
1286        window_state.lock().event_callback = Some(callback);
1287    }
1288}
1289
1290extern "C" fn window_did_resize(this: &Object, _: Sel, _: id) {
1291    let window_state = unsafe { get_window_state(this) };
1292    window_state.as_ref().lock().move_traffic_light();
1293}
1294
1295extern "C" fn window_will_enter_fullscreen(this: &Object, _: Sel, _: id) {
1296    window_fullscreen_changed(this, true);
1297}
1298
1299extern "C" fn window_will_exit_fullscreen(this: &Object, _: Sel, _: id) {
1300    window_fullscreen_changed(this, false);
1301}
1302
1303fn window_fullscreen_changed(this: &Object, is_fullscreen: bool) {
1304    let window_state = unsafe { get_window_state(this) };
1305    let mut lock = window_state.as_ref().lock();
1306    if let Some(mut callback) = lock.fullscreen_callback.take() {
1307        drop(lock);
1308        callback(is_fullscreen);
1309        window_state.lock().fullscreen_callback = Some(callback);
1310    }
1311}
1312
1313extern "C" fn window_did_move(this: &Object, _: Sel, _: id) {
1314    let window_state = unsafe { get_window_state(this) };
1315    let mut lock = window_state.as_ref().lock();
1316    if let Some(mut callback) = lock.moved_callback.take() {
1317        drop(lock);
1318        callback();
1319        window_state.lock().moved_callback = Some(callback);
1320    }
1321}
1322
1323extern "C" fn window_did_change_key_status(this: &Object, selector: Sel, _: id) {
1324    let window_state = unsafe { get_window_state(this) };
1325    let lock = window_state.lock();
1326    let is_active = unsafe { lock.native_window.isKeyWindow() == YES };
1327
1328    // When opening a pop-up while the application isn't active, Cocoa sends a spurious
1329    // `windowDidBecomeKey` message to the previous key window even though that window
1330    // isn't actually key. This causes a bug if the application is later activated while
1331    // the pop-up is still open, making it impossible to activate the previous key window
1332    // even if the pop-up gets closed. The only way to activate it again is to de-activate
1333    // the app and re-activate it, which is a pretty bad UX.
1334    // The following code detects the spurious event and invokes `resignKeyWindow`:
1335    // in theory, we're not supposed to invoke this method manually but it balances out
1336    // the spurious `becomeKeyWindow` event and helps us work around that bug.
1337    if selector == sel!(windowDidBecomeKey:) {
1338        if !is_active {
1339            unsafe {
1340                let _: () = msg_send![lock.native_window, resignKeyWindow];
1341                return;
1342            }
1343        }
1344    }
1345
1346    let executor = lock.executor.clone();
1347    drop(lock);
1348    executor
1349        .spawn(async move {
1350            let mut lock = window_state.as_ref().lock();
1351            if let Some(mut callback) = lock.activate_callback.take() {
1352                drop(lock);
1353                callback(is_active);
1354                window_state.lock().activate_callback = Some(callback);
1355            };
1356        })
1357        .detach();
1358}
1359
1360extern "C" fn window_should_close(this: &Object, _: Sel, _: id) -> BOOL {
1361    let window_state = unsafe { get_window_state(this) };
1362    let mut lock = window_state.as_ref().lock();
1363    if let Some(mut callback) = lock.should_close_callback.take() {
1364        drop(lock);
1365        let should_close = callback();
1366        window_state.lock().should_close_callback = Some(callback);
1367        should_close as BOOL
1368    } else {
1369        YES
1370    }
1371}
1372
1373extern "C" fn close_window(this: &Object, _: Sel) {
1374    unsafe {
1375        let close_callback = {
1376            let window_state = get_window_state(this);
1377            window_state
1378                .as_ref()
1379                .try_lock()
1380                .and_then(|mut window_state| window_state.close_callback.take())
1381        };
1382
1383        if let Some(callback) = close_callback {
1384            callback();
1385        }
1386
1387        let _: () = msg_send![super(this, class!(NSWindow)), close];
1388    }
1389}
1390
1391extern "C" fn make_backing_layer(this: &Object, _: Sel) -> id {
1392    let window_state = unsafe { get_window_state(this) };
1393    let window_state = window_state.as_ref().lock();
1394    window_state.renderer.layer().as_ptr() as id
1395}
1396
1397extern "C" fn view_did_change_backing_properties(this: &Object, _: Sel) {
1398    let window_state = unsafe { get_window_state(this) };
1399    let mut lock = window_state.as_ref().lock();
1400
1401    unsafe {
1402        let scale_factor = lock.scale_factor() as f64;
1403        let size = lock.content_size();
1404        let drawable_size: NSSize = NSSize {
1405            width: f64::from(size.width) * scale_factor,
1406            height: f64::from(size.height) * scale_factor,
1407        };
1408
1409        let _: () = msg_send![
1410            lock.renderer.layer(),
1411            setContentsScale: scale_factor
1412        ];
1413        let _: () = msg_send![
1414            lock.renderer.layer(),
1415            setDrawableSize: drawable_size
1416        ];
1417    }
1418
1419    if let Some(mut callback) = lock.resize_callback.take() {
1420        let content_size = lock.content_size();
1421        let scale_factor = lock.scale_factor();
1422        drop(lock);
1423        callback(content_size, scale_factor);
1424        window_state.as_ref().lock().resize_callback = Some(callback);
1425    };
1426}
1427
1428extern "C" fn set_frame_size(this: &Object, _: Sel, size: NSSize) {
1429    let window_state = unsafe { get_window_state(this) };
1430    let lock = window_state.as_ref().lock();
1431
1432    if lock.content_size() == size.into() {
1433        return;
1434    }
1435
1436    unsafe {
1437        let _: () = msg_send![super(this, class!(NSView)), setFrameSize: size];
1438    }
1439
1440    let scale_factor = lock.scale_factor() as f64;
1441    let drawable_size: NSSize = NSSize {
1442        width: size.width * scale_factor,
1443        height: size.height * scale_factor,
1444    };
1445
1446    unsafe {
1447        let _: () = msg_send![
1448            lock.renderer.layer(),
1449            setDrawableSize: drawable_size
1450        ];
1451    }
1452
1453    drop(lock);
1454    let mut lock = window_state.lock();
1455    if let Some(mut callback) = lock.resize_callback.take() {
1456        let content_size = lock.content_size();
1457        let scale_factor = lock.scale_factor();
1458        drop(lock);
1459        callback(content_size, scale_factor);
1460        window_state.lock().resize_callback = Some(callback);
1461    };
1462}
1463
1464extern "C" fn display_layer(this: &Object, _: Sel, _: id) {
1465    unsafe {
1466        let window_state = get_window_state(this);
1467        let mut draw = window_state.lock().draw.take().unwrap();
1468        let scene = draw().log_err();
1469        let mut window_state = window_state.lock();
1470        window_state.draw = Some(draw);
1471        if let Some(scene) = scene {
1472            window_state.renderer.draw(&scene);
1473        }
1474    }
1475}
1476
1477extern "C" fn valid_attributes_for_marked_text(_: &Object, _: Sel) -> id {
1478    unsafe { msg_send![class!(NSArray), array] }
1479}
1480
1481extern "C" fn has_marked_text(this: &Object, _: Sel) -> BOOL {
1482    with_input_handler(this, |input_handler| input_handler.marked_text_range())
1483        .flatten()
1484        .is_some() as BOOL
1485}
1486
1487extern "C" fn marked_range(this: &Object, _: Sel) -> NSRange {
1488    with_input_handler(this, |input_handler| input_handler.marked_text_range())
1489        .flatten()
1490        .map_or(NSRange::invalid(), |range| range.into())
1491}
1492
1493extern "C" fn selected_range(this: &Object, _: Sel) -> NSRange {
1494    with_input_handler(this, |input_handler| input_handler.selected_text_range())
1495        .flatten()
1496        .map_or(NSRange::invalid(), |range| range.into())
1497}
1498
1499extern "C" fn first_rect_for_character_range(
1500    this: &Object,
1501    _: Sel,
1502    range: NSRange,
1503    _: id,
1504) -> NSRect {
1505    let frame = unsafe {
1506        let window = get_window_state(this).lock().native_window;
1507        NSView::frame(window)
1508    };
1509    with_input_handler(this, |input_handler| {
1510        input_handler.bounds_for_range(range.to_range()?)
1511    })
1512    .flatten()
1513    .map_or(
1514        NSRect::new(NSPoint::new(0., 0.), NSSize::new(0., 0.)),
1515        |bounds| {
1516            NSRect::new(
1517                NSPoint::new(
1518                    frame.origin.x + bounds.origin.x.0 as f64,
1519                    frame.origin.y + frame.size.height
1520                        - bounds.origin.y.0 as f64
1521                        - bounds.size.height.0 as f64,
1522                ),
1523                NSSize::new(bounds.size.width.0 as f64, bounds.size.height.0 as f64),
1524            )
1525        },
1526    )
1527}
1528
1529extern "C" fn insert_text(this: &Object, _: Sel, text: id, replacement_range: NSRange) {
1530    unsafe {
1531        let window_state = get_window_state(this);
1532        let mut lock = window_state.lock();
1533        let pending_key_down = lock.pending_key_down.take();
1534        drop(lock);
1535
1536        let is_attributed_string: BOOL =
1537            msg_send![text, isKindOfClass: [class!(NSAttributedString)]];
1538        let text: id = if is_attributed_string == YES {
1539            msg_send![text, string]
1540        } else {
1541            text
1542        };
1543        let text = CStr::from_ptr(text.UTF8String() as *mut c_char)
1544            .to_str()
1545            .unwrap();
1546        let replacement_range = replacement_range.to_range();
1547
1548        window_state.lock().ime_text = Some(text.to_string());
1549        window_state.lock().ime_state = ImeState::Acted;
1550
1551        let is_composing =
1552            with_input_handler(this, |input_handler| input_handler.marked_text_range())
1553                .flatten()
1554                .is_some();
1555
1556        if is_composing || text.chars().count() > 1 || pending_key_down.is_none() {
1557            with_input_handler(this, |input_handler| {
1558                input_handler.replace_text_in_range(replacement_range, text)
1559            });
1560        } else {
1561            let mut pending_key_down = pending_key_down.unwrap();
1562            pending_key_down.1 = Some(InsertText {
1563                replacement_range,
1564                text: text.to_string(),
1565            });
1566            window_state.lock().pending_key_down = Some(pending_key_down);
1567        }
1568    }
1569}
1570
1571extern "C" fn set_marked_text(
1572    this: &Object,
1573    _: Sel,
1574    text: id,
1575    selected_range: NSRange,
1576    replacement_range: NSRange,
1577) {
1578    unsafe {
1579        let window_state = get_window_state(this);
1580        window_state.lock().pending_key_down.take();
1581
1582        let is_attributed_string: BOOL =
1583            msg_send![text, isKindOfClass: [class!(NSAttributedString)]];
1584        let text: id = if is_attributed_string == YES {
1585            msg_send![text, string]
1586        } else {
1587            text
1588        };
1589        let selected_range = selected_range.to_range();
1590        let replacement_range = replacement_range.to_range();
1591        let text = CStr::from_ptr(text.UTF8String() as *mut c_char)
1592            .to_str()
1593            .unwrap();
1594
1595        window_state.lock().ime_state = ImeState::Acted;
1596        window_state.lock().ime_text = Some(text.to_string());
1597
1598        with_input_handler(this, |input_handler| {
1599            input_handler.replace_and_mark_text_in_range(replacement_range, text, selected_range);
1600        });
1601    }
1602}
1603
1604extern "C" fn unmark_text(this: &Object, _: Sel) {
1605    unsafe {
1606        let state = get_window_state(this);
1607        let mut borrow = state.lock();
1608        borrow.ime_state = ImeState::Acted;
1609        borrow.ime_text.take();
1610    }
1611
1612    with_input_handler(this, |input_handler| input_handler.unmark_text());
1613}
1614
1615extern "C" fn attributed_substring_for_proposed_range(
1616    this: &Object,
1617    _: Sel,
1618    range: NSRange,
1619    _actual_range: *mut c_void,
1620) -> id {
1621    with_input_handler(this, |input_handler| {
1622        let range = range.to_range()?;
1623        if range.is_empty() {
1624            return None;
1625        }
1626
1627        let selected_text = input_handler.text_for_range(range)?;
1628        unsafe {
1629            let string: id = msg_send![class!(NSAttributedString), alloc];
1630            let string: id = msg_send![string, initWithString: ns_string(&selected_text)];
1631            Some(string)
1632        }
1633    })
1634    .flatten()
1635    .unwrap_or(nil)
1636}
1637
1638extern "C" fn do_command_by_selector(this: &Object, _: Sel, _: Sel) {
1639    unsafe {
1640        let state = get_window_state(this);
1641        let mut borrow = state.lock();
1642        borrow.ime_state = ImeState::Continue;
1643        borrow.ime_text.take();
1644    }
1645}
1646
1647extern "C" fn view_did_change_effective_appearance(this: &Object, _: Sel) {
1648    unsafe {
1649        let state = get_window_state(this);
1650        let mut lock = state.as_ref().lock();
1651        if let Some(mut callback) = lock.appearance_changed_callback.take() {
1652            drop(lock);
1653            callback();
1654            state.lock().appearance_changed_callback = Some(callback);
1655        }
1656    }
1657}
1658
1659extern "C" fn accepts_first_mouse(this: &Object, _: Sel, _: id) -> BOOL {
1660    unsafe {
1661        let state = get_window_state(this);
1662        let lock = state.as_ref().lock();
1663        return if lock.kind == WindowKind::PopUp {
1664            YES
1665        } else {
1666            NO
1667        };
1668    }
1669}
1670
1671extern "C" fn dragging_entered(this: &Object, _: Sel, dragging_info: id) -> NSDragOperation {
1672    let window_state = unsafe { get_window_state(this) };
1673    if send_new_event(&window_state, {
1674        let position = drag_event_position(&window_state, dragging_info);
1675        let paths = external_paths_from_event(dragging_info);
1676        InputEvent::FileDrop(FileDropEvent::Entered {
1677            position,
1678            files: paths,
1679        })
1680    }) {
1681        NSDragOperationCopy
1682    } else {
1683        NSDragOperationNone
1684    }
1685}
1686
1687extern "C" fn dragging_updated(this: &Object, _: Sel, dragging_info: id) -> NSDragOperation {
1688    let window_state = unsafe { get_window_state(this) };
1689    let position = drag_event_position(&window_state, dragging_info);
1690    if send_new_event(
1691        &window_state,
1692        InputEvent::FileDrop(FileDropEvent::Pending { position }),
1693    ) {
1694        NSDragOperationCopy
1695    } else {
1696        NSDragOperationNone
1697    }
1698}
1699
1700extern "C" fn dragging_exited(this: &Object, _: Sel, _: id) {
1701    let window_state = unsafe { get_window_state(this) };
1702    send_new_event(&window_state, InputEvent::FileDrop(FileDropEvent::Exited));
1703}
1704
1705extern "C" fn perform_drag_operation(this: &Object, _: Sel, dragging_info: id) -> BOOL {
1706    let window_state = unsafe { get_window_state(this) };
1707    let position = drag_event_position(&window_state, dragging_info);
1708    if send_new_event(
1709        &window_state,
1710        InputEvent::FileDrop(FileDropEvent::Submit { position }),
1711    ) {
1712        YES
1713    } else {
1714        NO
1715    }
1716}
1717
1718fn external_paths_from_event(dragging_info: *mut Object) -> ExternalPaths {
1719    let mut paths = SmallVec::new();
1720    let pasteboard: id = unsafe { msg_send![dragging_info, draggingPasteboard] };
1721    let filenames = unsafe { NSPasteboard::propertyListForType(pasteboard, NSFilenamesPboardType) };
1722    for file in unsafe { filenames.iter() } {
1723        let path = unsafe {
1724            let f = NSString::UTF8String(file);
1725            CStr::from_ptr(f).to_string_lossy().into_owned()
1726        };
1727        paths.push(PathBuf::from(path))
1728    }
1729    ExternalPaths(paths)
1730}
1731
1732extern "C" fn conclude_drag_operation(this: &Object, _: Sel, _: id) {
1733    let window_state = unsafe { get_window_state(this) };
1734    send_new_event(&window_state, InputEvent::FileDrop(FileDropEvent::Exited));
1735}
1736
1737async fn synthetic_drag(
1738    window_state: Weak<Mutex<MacWindowState>>,
1739    drag_id: usize,
1740    event: MouseMoveEvent,
1741) {
1742    loop {
1743        Timer::after(Duration::from_millis(16)).await;
1744        if let Some(window_state) = window_state.upgrade() {
1745            let mut lock = window_state.lock();
1746            if lock.synthetic_drag_counter == drag_id {
1747                if let Some(mut callback) = lock.event_callback.take() {
1748                    drop(lock);
1749                    callback(InputEvent::MouseMove(event.clone()));
1750                    window_state.lock().event_callback = Some(callback);
1751                }
1752            } else {
1753                break;
1754            }
1755        }
1756    }
1757}
1758
1759fn send_new_event(window_state_lock: &Mutex<MacWindowState>, e: InputEvent) -> bool {
1760    let window_state = window_state_lock.lock().event_callback.take();
1761    if let Some(mut callback) = window_state {
1762        callback(e);
1763        window_state_lock.lock().event_callback = Some(callback);
1764        true
1765    } else {
1766        false
1767    }
1768}
1769
1770fn drag_event_position(window_state: &Mutex<MacWindowState>, dragging_info: id) -> Point<Pixels> {
1771    let drag_location: NSPoint = unsafe { msg_send![dragging_info, draggingLocation] };
1772    convert_mouse_position(drag_location, window_state.lock().content_size().height)
1773}
1774
1775fn with_input_handler<F, R>(window: &Object, f: F) -> Option<R>
1776where
1777    F: FnOnce(&mut dyn PlatformInputHandler) -> R,
1778{
1779    let window_state = unsafe { get_window_state(window) };
1780    let mut lock = window_state.as_ref().lock();
1781    if let Some(mut input_handler) = lock.input_handler.take() {
1782        drop(lock);
1783        let result = f(input_handler.as_mut());
1784        window_state.lock().input_handler = Some(input_handler);
1785        Some(result)
1786    } else {
1787        None
1788    }
1789}