window.rs

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