window.rs

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