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        if !this.native_window_was_closed {
 742            unsafe {
 743                this.native_window.setDelegate_(nil);
 744            }
 745
 746            this.executor
 747                .spawn(async move {
 748                    unsafe {
 749                        window.close();
 750                    }
 751                })
 752                .detach();
 753        }
 754    }
 755}
 756
 757impl PlatformWindow for MacWindow {
 758    fn bounds(&self) -> WindowBounds {
 759        self.0.as_ref().lock().bounds()
 760    }
 761
 762    fn content_size(&self) -> Size<Pixels> {
 763        self.0.as_ref().lock().content_size()
 764    }
 765
 766    fn scale_factor(&self) -> f32 {
 767        self.0.as_ref().lock().scale_factor()
 768    }
 769
 770    fn titlebar_height(&self) -> Pixels {
 771        self.0.as_ref().lock().titlebar_height()
 772    }
 773
 774    fn appearance(&self) -> WindowAppearance {
 775        unsafe {
 776            let appearance: id = msg_send![self.0.lock().native_window, effectiveAppearance];
 777            WindowAppearance::from_native(appearance)
 778        }
 779    }
 780
 781    fn display(&self) -> Rc<dyn PlatformDisplay> {
 782        unsafe {
 783            let screen = self.0.lock().native_window.screen();
 784            let device_description: id = msg_send![screen, deviceDescription];
 785            let screen_number: id = NSDictionary::valueForKey_(
 786                device_description,
 787                NSString::alloc(nil).init_str("NSScreenNumber"),
 788            );
 789
 790            let screen_number: u32 = msg_send![screen_number, unsignedIntValue];
 791
 792            Rc::new(MacDisplay(screen_number))
 793        }
 794    }
 795
 796    fn mouse_position(&self) -> Point<Pixels> {
 797        let position = unsafe {
 798            self.0
 799                .lock()
 800                .native_window
 801                .mouseLocationOutsideOfEventStream()
 802        };
 803        convert_mouse_position(position, self.content_size().height)
 804    }
 805
 806    fn modifiers(&self) -> Modifiers {
 807        unsafe {
 808            let modifiers: NSEventModifierFlags = msg_send![class!(NSEvent), modifierFlags];
 809
 810            let control = modifiers.contains(NSEventModifierFlags::NSControlKeyMask);
 811            let alt = modifiers.contains(NSEventModifierFlags::NSAlternateKeyMask);
 812            let shift = modifiers.contains(NSEventModifierFlags::NSShiftKeyMask);
 813            let command = modifiers.contains(NSEventModifierFlags::NSCommandKeyMask);
 814            let function = modifiers.contains(NSEventModifierFlags::NSFunctionKeyMask);
 815
 816            Modifiers {
 817                control,
 818                alt,
 819                shift,
 820                command,
 821                function,
 822            }
 823        }
 824    }
 825
 826    fn as_any_mut(&mut self) -> &mut dyn Any {
 827        self
 828    }
 829
 830    fn set_input_handler(&mut self, input_handler: PlatformInputHandler) {
 831        self.0.as_ref().lock().input_handler = Some(input_handler);
 832    }
 833
 834    fn take_input_handler(&mut self) -> Option<PlatformInputHandler> {
 835        self.0.as_ref().lock().input_handler.take()
 836    }
 837
 838    fn prompt(
 839        &self,
 840        level: PromptLevel,
 841        msg: &str,
 842        detail: Option<&str>,
 843        answers: &[&str],
 844    ) -> oneshot::Receiver<usize> {
 845        // macOs applies overrides to modal window buttons after they are added.
 846        // Two most important for this logic are:
 847        // * Buttons with "Cancel" title will be displayed as the last buttons in the modal
 848        // * Last button added to the modal via `addButtonWithTitle` stays focused
 849        // * Focused buttons react on "space"/" " keypresses
 850        // * Usage of `keyEquivalent`, `makeFirstResponder` or `setInitialFirstResponder` does not change the focus
 851        //
 852        // See also https://developer.apple.com/documentation/appkit/nsalert/1524532-addbuttonwithtitle#discussion
 853        // ```
 854        // By default, the first button has a key equivalent of Return,
 855        // any button with a title of “Cancel” has a key equivalent of Escape,
 856        // 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).
 857        // ```
 858        //
 859        // To avoid situations when the last element added is "Cancel" and it gets the focus
 860        // (hence stealing both ESC and Space shortcuts), we find and add one non-Cancel button
 861        // last, so it gets focus and a Space shortcut.
 862        // This way, "Save this file? Yes/No/Cancel"-ish modals will get all three buttons mapped with a key.
 863        let latest_non_cancel_label = answers
 864            .iter()
 865            .enumerate()
 866            .rev()
 867            .find(|(_, &label)| label != "Cancel")
 868            .filter(|&(label_index, _)| label_index > 0);
 869
 870        unsafe {
 871            let alert: id = msg_send![class!(NSAlert), alloc];
 872            let alert: id = msg_send![alert, init];
 873            let alert_style = match level {
 874                PromptLevel::Info => 1,
 875                PromptLevel::Warning => 0,
 876                PromptLevel::Critical => 2,
 877            };
 878            let _: () = msg_send![alert, setAlertStyle: alert_style];
 879            let _: () = msg_send![alert, setMessageText: ns_string(msg)];
 880            if let Some(detail) = detail {
 881                let _: () = msg_send![alert, setInformativeText: ns_string(detail)];
 882            }
 883
 884            for (ix, answer) in answers
 885                .iter()
 886                .enumerate()
 887                .filter(|&(ix, _)| Some(ix) != latest_non_cancel_label.map(|(ix, _)| ix))
 888            {
 889                let button: id = msg_send![alert, addButtonWithTitle: ns_string(answer)];
 890                let _: () = msg_send![button, setTag: ix as NSInteger];
 891            }
 892            if let Some((ix, answer)) = latest_non_cancel_label {
 893                let button: id = msg_send![alert, addButtonWithTitle: ns_string(answer)];
 894                let _: () = msg_send![button, setTag: ix as NSInteger];
 895            }
 896
 897            let (done_tx, done_rx) = oneshot::channel();
 898            let done_tx = Cell::new(Some(done_tx));
 899            let block = ConcreteBlock::new(move |answer: NSInteger| {
 900                if let Some(done_tx) = done_tx.take() {
 901                    let _ = done_tx.send(answer.try_into().unwrap());
 902                }
 903            });
 904            let block = block.copy();
 905            let native_window = self.0.lock().native_window;
 906            let executor = self.0.lock().executor.clone();
 907            executor
 908                .spawn(async move {
 909                    let _: () = msg_send![
 910                        alert,
 911                        beginSheetModalForWindow: native_window
 912                        completionHandler: block
 913                    ];
 914                })
 915                .detach();
 916
 917            done_rx
 918        }
 919    }
 920
 921    fn activate(&self) {
 922        let window = self.0.lock().native_window;
 923        let executor = self.0.lock().executor.clone();
 924        executor
 925            .spawn(async move {
 926                unsafe {
 927                    let _: () = msg_send![window, makeKeyAndOrderFront: nil];
 928                }
 929            })
 930            .detach();
 931    }
 932
 933    fn set_title(&mut self, title: &str) {
 934        unsafe {
 935            let app = NSApplication::sharedApplication(nil);
 936            let window = self.0.lock().native_window;
 937            let title = ns_string(title);
 938            let _: () = msg_send![app, changeWindowsItem:window title:title filename:false];
 939            let _: () = msg_send![window, setTitle: title];
 940            self.0.lock().move_traffic_light();
 941        }
 942    }
 943
 944    fn set_edited(&mut self, edited: bool) {
 945        unsafe {
 946            let window = self.0.lock().native_window;
 947            msg_send![window, setDocumentEdited: edited as BOOL]
 948        }
 949
 950        // Changing the document edited state resets the traffic light position,
 951        // so we have to move it again.
 952        self.0.lock().move_traffic_light();
 953    }
 954
 955    fn show_character_palette(&self) {
 956        let this = self.0.lock();
 957        let window = this.native_window;
 958        this.executor
 959            .spawn(async move {
 960                unsafe {
 961                    let app = NSApplication::sharedApplication(nil);
 962                    let _: () = msg_send![app, orderFrontCharacterPalette: window];
 963                }
 964            })
 965            .detach();
 966    }
 967
 968    fn minimize(&self) {
 969        let window = self.0.lock().native_window;
 970        unsafe {
 971            window.miniaturize_(nil);
 972        }
 973    }
 974
 975    fn zoom(&self) {
 976        let this = self.0.lock();
 977        let window = this.native_window;
 978        this.executor
 979            .spawn(async move {
 980                unsafe {
 981                    window.zoom_(nil);
 982                }
 983            })
 984            .detach();
 985    }
 986
 987    fn toggle_full_screen(&self) {
 988        let this = self.0.lock();
 989        let window = this.native_window;
 990        this.executor
 991            .spawn(async move {
 992                unsafe {
 993                    window.toggleFullScreen_(nil);
 994                }
 995            })
 996            .detach();
 997    }
 998
 999    fn on_request_frame(&self, callback: Box<dyn FnMut()>) {
1000        self.0.as_ref().lock().request_frame_callback = Some(callback);
1001    }
1002
1003    fn on_input(&self, callback: Box<dyn FnMut(PlatformInput) -> bool>) {
1004        self.0.as_ref().lock().event_callback = Some(callback);
1005    }
1006
1007    fn on_active_status_change(&self, callback: Box<dyn FnMut(bool)>) {
1008        self.0.as_ref().lock().activate_callback = Some(callback);
1009    }
1010
1011    fn on_resize(&self, callback: Box<dyn FnMut(Size<Pixels>, f32)>) {
1012        self.0.as_ref().lock().resize_callback = Some(callback);
1013    }
1014
1015    fn on_fullscreen(&self, callback: Box<dyn FnMut(bool)>) {
1016        self.0.as_ref().lock().fullscreen_callback = Some(callback);
1017    }
1018
1019    fn on_moved(&self, callback: Box<dyn FnMut()>) {
1020        self.0.as_ref().lock().moved_callback = Some(callback);
1021    }
1022
1023    fn on_should_close(&self, callback: Box<dyn FnMut() -> bool>) {
1024        self.0.as_ref().lock().should_close_callback = Some(callback);
1025    }
1026
1027    fn on_close(&self, callback: Box<dyn FnOnce()>) {
1028        self.0.as_ref().lock().close_callback = Some(callback);
1029    }
1030
1031    fn on_appearance_changed(&self, callback: Box<dyn FnMut()>) {
1032        self.0.lock().appearance_changed_callback = Some(callback);
1033    }
1034
1035    fn is_topmost_for_position(&self, position: Point<Pixels>) -> bool {
1036        let self_borrow = self.0.lock();
1037        let self_handle = self_borrow.handle;
1038
1039        unsafe {
1040            let app = NSApplication::sharedApplication(nil);
1041
1042            // Convert back to screen coordinates
1043            let screen_point = self_borrow.to_screen_ns_point(position);
1044
1045            let window_number: NSInteger = msg_send![class!(NSWindow), windowNumberAtPoint:screen_point belowWindowWithWindowNumber:0];
1046            let top_most_window: id = msg_send![app, windowWithWindowNumber: window_number];
1047
1048            let is_panel: BOOL = msg_send![top_most_window, isKindOfClass: PANEL_CLASS];
1049            let is_window: BOOL = msg_send![top_most_window, isKindOfClass: WINDOW_CLASS];
1050            if is_panel == YES || is_window == YES {
1051                let topmost_window = get_window_state(&*top_most_window).lock().handle;
1052                topmost_window == self_handle
1053            } else {
1054                // Someone else's window is on top
1055                false
1056            }
1057        }
1058    }
1059
1060    fn draw(&self, scene: &crate::Scene) {
1061        let mut this = self.0.lock();
1062        this.renderer.draw(scene);
1063    }
1064
1065    fn sprite_atlas(&self) -> Arc<dyn PlatformAtlas> {
1066        self.0.lock().renderer.sprite_atlas().clone()
1067    }
1068}
1069
1070impl HasWindowHandle for MacWindow {
1071    fn window_handle(
1072        &self,
1073    ) -> Result<raw_window_handle::WindowHandle<'_>, raw_window_handle::HandleError> {
1074        // SAFETY: The AppKitWindowHandle is a wrapper around a pointer to an NSView
1075        unsafe {
1076            Ok(WindowHandle::borrow_raw(RawWindowHandle::AppKit(
1077                AppKitWindowHandle::new(self.0.lock().native_view.cast()),
1078            )))
1079        }
1080    }
1081}
1082
1083impl HasDisplayHandle for MacWindow {
1084    fn display_handle(
1085        &self,
1086    ) -> Result<raw_window_handle::DisplayHandle<'_>, raw_window_handle::HandleError> {
1087        // SAFETY: This is a no-op on macOS
1088        unsafe { Ok(DisplayHandle::borrow_raw(AppKitDisplayHandle::new().into())) }
1089    }
1090}
1091
1092fn get_scale_factor(native_window: id) -> f32 {
1093    let factor = unsafe {
1094        let screen: id = msg_send![native_window, screen];
1095        NSScreen::backingScaleFactor(screen) as f32
1096    };
1097
1098    // We are not certain what triggers this, but it seems that sometimes
1099    // this method would return 0 (https://github.com/zed-industries/zed/issues/6412)
1100    // It seems most likely that this would happen if the window has no screen
1101    // (if it is off-screen), though we'd expect to see viewDidChangeBackingProperties before
1102    // it was rendered for real.
1103    // Regardless, attempt to avoid the issue here.
1104    if factor == 0.0 {
1105        2.
1106    } else {
1107        factor
1108    }
1109}
1110
1111unsafe fn get_window_state(object: &Object) -> Arc<Mutex<MacWindowState>> {
1112    let raw: *mut c_void = *object.get_ivar(WINDOW_STATE_IVAR);
1113    let rc1 = Arc::from_raw(raw as *mut Mutex<MacWindowState>);
1114    let rc2 = rc1.clone();
1115    mem::forget(rc1);
1116    rc2
1117}
1118
1119unsafe fn drop_window_state(object: &Object) {
1120    let raw: *mut c_void = *object.get_ivar(WINDOW_STATE_IVAR);
1121    Arc::from_raw(raw as *mut Mutex<MacWindowState>);
1122}
1123
1124extern "C" fn yes(_: &Object, _: Sel) -> BOOL {
1125    YES
1126}
1127
1128extern "C" fn dealloc_window(this: &Object, _: Sel) {
1129    unsafe {
1130        drop_window_state(this);
1131        let _: () = msg_send![super(this, class!(NSWindow)), dealloc];
1132    }
1133}
1134
1135extern "C" fn dealloc_view(this: &Object, _: Sel) {
1136    unsafe {
1137        drop_window_state(this);
1138        let _: () = msg_send![super(this, class!(NSView)), dealloc];
1139    }
1140}
1141
1142extern "C" fn handle_key_equivalent(this: &Object, _: Sel, native_event: id) -> BOOL {
1143    handle_key_event(this, native_event, true)
1144}
1145
1146extern "C" fn handle_key_down(this: &Object, _: Sel, native_event: id) {
1147    handle_key_event(this, native_event, false);
1148}
1149
1150// Things to test if you're modifying this method:
1151//  Brazilian layout:
1152//   - `" space` should type a quote
1153//   - `" backspace` should delete the marked quote
1154//   - `" up` should type the quote, unmark it, and move up one line
1155//   - `" cmd-down` should not leave a marked quote behind (it maybe should dispatch the key though?)
1156//   - `cmd-ctrl-space` and clicking on an emoji should type it
1157//  Czech (QWERTY) layout:
1158//   - in vim mode `option-4`  should go to end of line (same as $)
1159extern "C" fn handle_key_event(this: &Object, native_event: id, key_equivalent: bool) -> BOOL {
1160    let window_state = unsafe { get_window_state(this) };
1161    let mut lock = window_state.as_ref().lock();
1162
1163    let window_height = lock.content_size().height;
1164    let event = unsafe { PlatformInput::from_native(native_event, Some(window_height)) };
1165
1166    if let Some(PlatformInput::KeyDown(mut event)) = event {
1167        // For certain keystrokes, macOS will first dispatch a "key equivalent" event.
1168        // If that event isn't handled, it will then dispatch a "key down" event. GPUI
1169        // makes no distinction between these two types of events, so we need to ignore
1170        // the "key down" event if we've already just processed its "key equivalent" version.
1171        if key_equivalent {
1172            lock.last_key_equivalent = Some(event.clone());
1173        } else if lock.last_key_equivalent.take().as_ref() == Some(&event) {
1174            return NO;
1175        }
1176
1177        let keydown = event.keystroke.clone();
1178        let fn_modifier = keydown.modifiers.function;
1179        // Ignore events from held-down keys after some of the initially-pressed keys
1180        // were released.
1181        if event.is_held {
1182            if lock.last_fresh_keydown.as_ref() != Some(&keydown) {
1183                return YES;
1184            }
1185        } else {
1186            lock.last_fresh_keydown = Some(keydown.clone());
1187        }
1188        lock.input_during_keydown = Some(SmallVec::new());
1189        drop(lock);
1190
1191        // Send the event to the input context for IME handling, unless the `fn` modifier is
1192        // being pressed.
1193        // this will call back into `insert_text`, etc.
1194        if !fn_modifier {
1195            unsafe {
1196                let input_context: id = msg_send![this, inputContext];
1197                let _: BOOL = msg_send![input_context, handleEvent: native_event];
1198            }
1199        }
1200
1201        let mut handled = false;
1202        let mut lock = window_state.lock();
1203        let previous_keydown_inserted_text = lock.previous_keydown_inserted_text.take();
1204        let mut input_during_keydown = lock.input_during_keydown.take().unwrap();
1205        let mut callback = lock.event_callback.take();
1206        drop(lock);
1207
1208        let last_ime = input_during_keydown.pop();
1209        // on a brazilian keyboard typing `"` and then hitting `up` will cause two IME
1210        // events, one to unmark the quote, and one to send the up arrow.
1211        for ime in input_during_keydown {
1212            send_to_input_handler(this, ime);
1213        }
1214
1215        let is_composing =
1216            with_input_handler(this, |input_handler| input_handler.marked_text_range())
1217                .flatten()
1218                .is_some();
1219
1220        if let Some(ime) = last_ime {
1221            if let ImeInput::InsertText(text, _) = &ime {
1222                if !is_composing {
1223                    window_state.lock().previous_keydown_inserted_text = Some(text.clone());
1224                    if let Some(callback) = callback.as_mut() {
1225                        event.keystroke.ime_key = Some(text.clone());
1226                        handled = callback(PlatformInput::KeyDown(event));
1227                    }
1228                }
1229            }
1230
1231            if !handled {
1232                handled = true;
1233                send_to_input_handler(this, ime);
1234            }
1235        } else if !is_composing {
1236            let is_held = event.is_held;
1237
1238            if let Some(callback) = callback.as_mut() {
1239                handled = callback(PlatformInput::KeyDown(event));
1240            }
1241
1242            if !handled && is_held {
1243                if let Some(text) = previous_keydown_inserted_text {
1244                    // MacOS IME is a bit funky, and even when you've told it there's nothing to
1245                    // enter it will still swallow certain keys (e.g. 'f', 'j') and not others
1246                    // (e.g. 'n'). This is a problem for certain kinds of views, like the terminal.
1247                    with_input_handler(this, |input_handler| {
1248                        if input_handler.selected_text_range().is_none() {
1249                            handled = true;
1250                            input_handler.replace_text_in_range(None, &text)
1251                        }
1252                    });
1253                    window_state.lock().previous_keydown_inserted_text = Some(text);
1254                }
1255            }
1256        }
1257
1258        window_state.lock().event_callback = callback;
1259
1260        handled as BOOL
1261    } else {
1262        NO
1263    }
1264}
1265
1266extern "C" fn handle_view_event(this: &Object, _: Sel, native_event: id) {
1267    let window_state = unsafe { get_window_state(this) };
1268    let weak_window_state = Arc::downgrade(&window_state);
1269    let mut lock = window_state.as_ref().lock();
1270    let is_active = unsafe { lock.native_window.isKeyWindow() == YES };
1271
1272    let window_height = lock.content_size().height;
1273    let event = unsafe { PlatformInput::from_native(native_event, Some(window_height)) };
1274
1275    if let Some(mut event) = event {
1276        match &mut event {
1277            PlatformInput::MouseDown(
1278                event @ MouseDownEvent {
1279                    button: MouseButton::Left,
1280                    modifiers: Modifiers { control: true, .. },
1281                    ..
1282                },
1283            ) => {
1284                // On mac, a ctrl-left click should be handled as a right click.
1285                *event = MouseDownEvent {
1286                    button: MouseButton::Right,
1287                    modifiers: Modifiers {
1288                        control: false,
1289                        ..event.modifiers
1290                    },
1291                    click_count: 1,
1292                    ..*event
1293                };
1294            }
1295
1296            // Because we map a ctrl-left_down to a right_down -> right_up let's ignore
1297            // the ctrl-left_up to avoid having a mismatch in button down/up events if the
1298            // user is still holding ctrl when releasing the left mouse button
1299            PlatformInput::MouseUp(
1300                event @ MouseUpEvent {
1301                    button: MouseButton::Left,
1302                    modifiers: Modifiers { control: true, .. },
1303                    ..
1304                },
1305            ) => {
1306                *event = MouseUpEvent {
1307                    button: MouseButton::Right,
1308                    modifiers: Modifiers {
1309                        control: false,
1310                        ..event.modifiers
1311                    },
1312                    click_count: 1,
1313                    ..*event
1314                };
1315            }
1316
1317            _ => {}
1318        };
1319
1320        match &event {
1321            PlatformInput::MouseMove(
1322                event @ MouseMoveEvent {
1323                    pressed_button: Some(_),
1324                    ..
1325                },
1326            ) => {
1327                // Synthetic drag is used for selecting long buffer contents while buffer is being scrolled.
1328                // External file drag and drop is able to emit its own synthetic mouse events which will conflict
1329                // with these ones.
1330                if !lock.external_files_dragged {
1331                    lock.synthetic_drag_counter += 1;
1332                    let executor = lock.executor.clone();
1333                    executor
1334                        .spawn(synthetic_drag(
1335                            weak_window_state,
1336                            lock.synthetic_drag_counter,
1337                            event.clone(),
1338                        ))
1339                        .detach();
1340                }
1341            }
1342
1343            PlatformInput::MouseMove(_) if !(is_active || lock.kind == WindowKind::PopUp) => return,
1344
1345            PlatformInput::MouseUp(MouseUpEvent { .. }) => {
1346                lock.synthetic_drag_counter += 1;
1347            }
1348
1349            PlatformInput::ModifiersChanged(ModifiersChangedEvent { modifiers }) => {
1350                // Only raise modifiers changed event when they have actually changed
1351                if let Some(PlatformInput::ModifiersChanged(ModifiersChangedEvent {
1352                    modifiers: prev_modifiers,
1353                })) = &lock.previous_modifiers_changed_event
1354                {
1355                    if prev_modifiers == modifiers {
1356                        return;
1357                    }
1358                }
1359
1360                lock.previous_modifiers_changed_event = Some(event.clone());
1361            }
1362
1363            _ => {}
1364        }
1365
1366        if let Some(mut callback) = lock.event_callback.take() {
1367            drop(lock);
1368            callback(event);
1369            window_state.lock().event_callback = Some(callback);
1370        }
1371    }
1372}
1373
1374// Allows us to receive `cmd-.` (the shortcut for closing a dialog)
1375// https://bugs.eclipse.org/bugs/show_bug.cgi?id=300620#c6
1376extern "C" fn cancel_operation(this: &Object, _sel: Sel, _sender: id) {
1377    let window_state = unsafe { get_window_state(this) };
1378    let mut lock = window_state.as_ref().lock();
1379
1380    let keystroke = Keystroke {
1381        modifiers: Default::default(),
1382        key: ".".into(),
1383        ime_key: None,
1384    };
1385    let event = PlatformInput::KeyDown(KeyDownEvent {
1386        keystroke: keystroke.clone(),
1387        is_held: false,
1388    });
1389
1390    lock.last_fresh_keydown = Some(keystroke);
1391    if let Some(mut callback) = lock.event_callback.take() {
1392        drop(lock);
1393        callback(event);
1394        window_state.lock().event_callback = Some(callback);
1395    }
1396}
1397
1398extern "C" fn window_did_change_occlusion_state(this: &Object, _: Sel, _: id) {
1399    let window_state = unsafe { get_window_state(this) };
1400    let lock = &mut *window_state.lock();
1401    unsafe {
1402        if lock
1403            .native_window
1404            .occlusionState()
1405            .contains(NSWindowOcclusionState::NSWindowOcclusionStateVisible)
1406        {
1407            lock.start_display_link();
1408        } else {
1409            lock.stop_display_link();
1410        }
1411    }
1412}
1413
1414extern "C" fn window_did_resize(this: &Object, _: Sel, _: id) {
1415    let window_state = unsafe { get_window_state(this) };
1416    window_state.as_ref().lock().move_traffic_light();
1417}
1418
1419extern "C" fn window_will_enter_fullscreen(this: &Object, _: Sel, _: id) {
1420    window_fullscreen_changed(this, true);
1421}
1422
1423extern "C" fn window_will_exit_fullscreen(this: &Object, _: Sel, _: id) {
1424    window_fullscreen_changed(this, false);
1425}
1426
1427fn window_fullscreen_changed(this: &Object, is_fullscreen: bool) {
1428    let window_state = unsafe { get_window_state(this) };
1429    let mut lock = window_state.as_ref().lock();
1430    if let Some(mut callback) = lock.fullscreen_callback.take() {
1431        drop(lock);
1432        callback(is_fullscreen);
1433        window_state.lock().fullscreen_callback = Some(callback);
1434    }
1435}
1436
1437extern "C" fn window_did_move(this: &Object, _: Sel, _: id) {
1438    let window_state = unsafe { get_window_state(this) };
1439    let mut lock = window_state.as_ref().lock();
1440    if let Some(mut callback) = lock.moved_callback.take() {
1441        drop(lock);
1442        callback();
1443        window_state.lock().moved_callback = Some(callback);
1444    }
1445}
1446
1447extern "C" fn window_did_change_screen(this: &Object, _: Sel, _: id) {
1448    let window_state = unsafe { get_window_state(this) };
1449    let mut lock = window_state.as_ref().lock();
1450    lock.start_display_link();
1451}
1452
1453extern "C" fn window_did_change_key_status(this: &Object, selector: Sel, _: id) {
1454    let window_state = unsafe { get_window_state(this) };
1455    let lock = window_state.lock();
1456    let is_active = unsafe { lock.native_window.isKeyWindow() == YES };
1457
1458    // When opening a pop-up while the application isn't active, Cocoa sends a spurious
1459    // `windowDidBecomeKey` message to the previous key window even though that window
1460    // isn't actually key. This causes a bug if the application is later activated while
1461    // the pop-up is still open, making it impossible to activate the previous key window
1462    // even if the pop-up gets closed. The only way to activate it again is to de-activate
1463    // the app and re-activate it, which is a pretty bad UX.
1464    // The following code detects the spurious event and invokes `resignKeyWindow`:
1465    // in theory, we're not supposed to invoke this method manually but it balances out
1466    // the spurious `becomeKeyWindow` event and helps us work around that bug.
1467    if selector == sel!(windowDidBecomeKey:) && !is_active {
1468        unsafe {
1469            let _: () = msg_send![lock.native_window, resignKeyWindow];
1470            return;
1471        }
1472    }
1473
1474    let executor = lock.executor.clone();
1475    drop(lock);
1476    executor
1477        .spawn(async move {
1478            let mut lock = window_state.as_ref().lock();
1479            if let Some(mut callback) = lock.activate_callback.take() {
1480                drop(lock);
1481                callback(is_active);
1482                window_state.lock().activate_callback = Some(callback);
1483            };
1484        })
1485        .detach();
1486}
1487
1488extern "C" fn window_should_close(this: &Object, _: Sel, _: id) -> BOOL {
1489    let window_state = unsafe { get_window_state(this) };
1490    let mut lock = window_state.as_ref().lock();
1491    if let Some(mut callback) = lock.should_close_callback.take() {
1492        drop(lock);
1493        let should_close = callback();
1494        window_state.lock().should_close_callback = Some(callback);
1495        should_close as BOOL
1496    } else {
1497        YES
1498    }
1499}
1500
1501extern "C" fn close_window(this: &Object, _: Sel) {
1502    unsafe {
1503        let close_callback = {
1504            let window_state = get_window_state(this);
1505            let mut lock = window_state.as_ref().lock();
1506            lock.native_window_was_closed = true;
1507            lock.close_callback.take()
1508        };
1509
1510        if let Some(callback) = close_callback {
1511            callback();
1512        }
1513
1514        let _: () = msg_send![super(this, class!(NSWindow)), close];
1515    }
1516}
1517
1518extern "C" fn make_backing_layer(this: &Object, _: Sel) -> id {
1519    let window_state = unsafe { get_window_state(this) };
1520    let window_state = window_state.as_ref().lock();
1521    window_state.renderer.layer_ptr() as id
1522}
1523
1524extern "C" fn view_did_change_backing_properties(this: &Object, _: Sel) {
1525    let window_state = unsafe { get_window_state(this) };
1526    let mut lock = window_state.as_ref().lock();
1527
1528    let scale_factor = lock.scale_factor() as f64;
1529    let size = lock.content_size();
1530    let drawable_size: NSSize = NSSize {
1531        width: f64::from(size.width) * scale_factor,
1532        height: f64::from(size.height) * scale_factor,
1533    };
1534    unsafe {
1535        let _: () = msg_send![
1536            lock.renderer.layer(),
1537            setContentsScale: scale_factor
1538        ];
1539    }
1540
1541    lock.update_drawable_size(drawable_size);
1542
1543    if let Some(mut callback) = lock.resize_callback.take() {
1544        let content_size = lock.content_size();
1545        let scale_factor = lock.scale_factor();
1546        drop(lock);
1547        callback(content_size, scale_factor);
1548        window_state.as_ref().lock().resize_callback = Some(callback);
1549    };
1550}
1551
1552extern "C" fn set_frame_size(this: &Object, _: Sel, size: NSSize) {
1553    let window_state = unsafe { get_window_state(this) };
1554    let mut lock = window_state.as_ref().lock();
1555
1556    if lock.content_size() == size.into() {
1557        return;
1558    }
1559
1560    unsafe {
1561        let _: () = msg_send![super(this, class!(NSView)), setFrameSize: size];
1562    }
1563
1564    let scale_factor = lock.scale_factor() as f64;
1565    let drawable_size: NSSize = NSSize {
1566        width: size.width * scale_factor,
1567        height: size.height * scale_factor,
1568    };
1569
1570    lock.update_drawable_size(drawable_size);
1571
1572    drop(lock);
1573    let mut lock = window_state.lock();
1574    if let Some(mut callback) = lock.resize_callback.take() {
1575        let content_size = lock.content_size();
1576        let scale_factor = lock.scale_factor();
1577        drop(lock);
1578        callback(content_size, scale_factor);
1579        window_state.lock().resize_callback = Some(callback);
1580    };
1581}
1582
1583extern "C" fn display_layer(this: &Object, _: Sel, _: id) {
1584    let window_state = unsafe { get_window_state(this) };
1585    let mut lock = window_state.lock();
1586    if let Some(mut callback) = lock.request_frame_callback.take() {
1587        #[cfg(not(feature = "macos-blade"))]
1588        lock.renderer.set_presents_with_transaction(true);
1589        lock.stop_display_link();
1590        drop(lock);
1591        callback();
1592
1593        let mut lock = window_state.lock();
1594        lock.request_frame_callback = Some(callback);
1595        #[cfg(not(feature = "macos-blade"))]
1596        lock.renderer.set_presents_with_transaction(false);
1597        lock.start_display_link();
1598    }
1599}
1600
1601unsafe extern "C" fn step(view: *mut c_void) {
1602    let view = view as id;
1603    let window_state = unsafe { get_window_state(&*view) };
1604    let mut lock = window_state.lock();
1605
1606    if let Some(mut callback) = lock.request_frame_callback.take() {
1607        drop(lock);
1608        callback();
1609        window_state.lock().request_frame_callback = Some(callback);
1610    }
1611}
1612
1613extern "C" fn valid_attributes_for_marked_text(_: &Object, _: Sel) -> id {
1614    unsafe { msg_send![class!(NSArray), array] }
1615}
1616
1617extern "C" fn has_marked_text(this: &Object, _: Sel) -> BOOL {
1618    with_input_handler(this, |input_handler| input_handler.marked_text_range())
1619        .flatten()
1620        .is_some() as BOOL
1621}
1622
1623extern "C" fn marked_range(this: &Object, _: Sel) -> NSRange {
1624    with_input_handler(this, |input_handler| input_handler.marked_text_range())
1625        .flatten()
1626        .map_or(NSRange::invalid(), |range| range.into())
1627}
1628
1629extern "C" fn selected_range(this: &Object, _: Sel) -> NSRange {
1630    with_input_handler(this, |input_handler| input_handler.selected_text_range())
1631        .flatten()
1632        .map_or(NSRange::invalid(), |range| range.into())
1633}
1634
1635extern "C" fn first_rect_for_character_range(
1636    this: &Object,
1637    _: Sel,
1638    range: NSRange,
1639    _: id,
1640) -> NSRect {
1641    let frame = unsafe {
1642        let window = get_window_state(this).lock().native_window;
1643        NSView::frame(window)
1644    };
1645    with_input_handler(this, |input_handler| {
1646        input_handler.bounds_for_range(range.to_range()?)
1647    })
1648    .flatten()
1649    .map_or(
1650        NSRect::new(NSPoint::new(0., 0.), NSSize::new(0., 0.)),
1651        |bounds| {
1652            NSRect::new(
1653                NSPoint::new(
1654                    frame.origin.x + bounds.origin.x.0 as f64,
1655                    frame.origin.y + frame.size.height
1656                        - bounds.origin.y.0 as f64
1657                        - bounds.size.height.0 as f64,
1658                ),
1659                NSSize::new(bounds.size.width.0 as f64, bounds.size.height.0 as f64),
1660            )
1661        },
1662    )
1663}
1664
1665extern "C" fn insert_text(this: &Object, _: Sel, text: id, replacement_range: NSRange) {
1666    unsafe {
1667        let is_attributed_string: BOOL =
1668            msg_send![text, isKindOfClass: [class!(NSAttributedString)]];
1669        let text: id = if is_attributed_string == YES {
1670            msg_send![text, string]
1671        } else {
1672            text
1673        };
1674        let text = CStr::from_ptr(text.UTF8String() as *mut c_char)
1675            .to_str()
1676            .unwrap();
1677        let replacement_range = replacement_range.to_range();
1678        send_to_input_handler(
1679            this,
1680            ImeInput::InsertText(text.to_string(), replacement_range),
1681        );
1682    }
1683}
1684
1685extern "C" fn set_marked_text(
1686    this: &Object,
1687    _: Sel,
1688    text: id,
1689    selected_range: NSRange,
1690    replacement_range: NSRange,
1691) {
1692    unsafe {
1693        let is_attributed_string: BOOL =
1694            msg_send![text, isKindOfClass: [class!(NSAttributedString)]];
1695        let text: id = if is_attributed_string == YES {
1696            msg_send![text, string]
1697        } else {
1698            text
1699        };
1700        let selected_range = selected_range.to_range();
1701        let replacement_range = replacement_range.to_range();
1702        let text = CStr::from_ptr(text.UTF8String() as *mut c_char)
1703            .to_str()
1704            .unwrap();
1705
1706        send_to_input_handler(
1707            this,
1708            ImeInput::SetMarkedText(text.to_string(), replacement_range, selected_range),
1709        );
1710    }
1711}
1712extern "C" fn unmark_text(this: &Object, _: Sel) {
1713    send_to_input_handler(this, ImeInput::UnmarkText);
1714}
1715
1716extern "C" fn attributed_substring_for_proposed_range(
1717    this: &Object,
1718    _: Sel,
1719    range: NSRange,
1720    _actual_range: *mut c_void,
1721) -> id {
1722    with_input_handler(this, |input_handler| {
1723        let range = range.to_range()?;
1724        if range.is_empty() {
1725            return None;
1726        }
1727
1728        let selected_text = input_handler.text_for_range(range)?;
1729        unsafe {
1730            let string: id = msg_send![class!(NSAttributedString), alloc];
1731            let string: id = msg_send![string, initWithString: ns_string(&selected_text)];
1732            Some(string)
1733        }
1734    })
1735    .flatten()
1736    .unwrap_or(nil)
1737}
1738
1739extern "C" fn do_command_by_selector(_: &Object, _: Sel, _: Sel) {}
1740
1741extern "C" fn view_did_change_effective_appearance(this: &Object, _: Sel) {
1742    unsafe {
1743        let state = get_window_state(this);
1744        let mut lock = state.as_ref().lock();
1745        if let Some(mut callback) = lock.appearance_changed_callback.take() {
1746            drop(lock);
1747            callback();
1748            state.lock().appearance_changed_callback = Some(callback);
1749        }
1750    }
1751}
1752
1753extern "C" fn accepts_first_mouse(this: &Object, _: Sel, _: id) -> BOOL {
1754    unsafe {
1755        let state = get_window_state(this);
1756        let lock = state.as_ref().lock();
1757        if lock.kind == WindowKind::PopUp {
1758            YES
1759        } else {
1760            NO
1761        }
1762    }
1763}
1764
1765extern "C" fn dragging_entered(this: &Object, _: Sel, dragging_info: id) -> NSDragOperation {
1766    let window_state = unsafe { get_window_state(this) };
1767    if send_new_event(&window_state, {
1768        let position = drag_event_position(&window_state, dragging_info);
1769        let paths = external_paths_from_event(dragging_info);
1770        PlatformInput::FileDrop(FileDropEvent::Entered { position, paths })
1771    }) {
1772        window_state.lock().external_files_dragged = true;
1773        NSDragOperationCopy
1774    } else {
1775        NSDragOperationNone
1776    }
1777}
1778
1779extern "C" fn dragging_updated(this: &Object, _: Sel, dragging_info: id) -> NSDragOperation {
1780    let window_state = unsafe { get_window_state(this) };
1781    let position = drag_event_position(&window_state, dragging_info);
1782    if send_new_event(
1783        &window_state,
1784        PlatformInput::FileDrop(FileDropEvent::Pending { position }),
1785    ) {
1786        NSDragOperationCopy
1787    } else {
1788        NSDragOperationNone
1789    }
1790}
1791
1792extern "C" fn dragging_exited(this: &Object, _: Sel, _: id) {
1793    let window_state = unsafe { get_window_state(this) };
1794    send_new_event(
1795        &window_state,
1796        PlatformInput::FileDrop(FileDropEvent::Exited),
1797    );
1798    window_state.lock().external_files_dragged = false;
1799}
1800
1801extern "C" fn perform_drag_operation(this: &Object, _: Sel, dragging_info: id) -> BOOL {
1802    let window_state = unsafe { get_window_state(this) };
1803    let position = drag_event_position(&window_state, dragging_info);
1804    if send_new_event(
1805        &window_state,
1806        PlatformInput::FileDrop(FileDropEvent::Submit { position }),
1807    ) {
1808        YES
1809    } else {
1810        NO
1811    }
1812}
1813
1814fn external_paths_from_event(dragging_info: *mut Object) -> ExternalPaths {
1815    let mut paths = SmallVec::new();
1816    let pasteboard: id = unsafe { msg_send![dragging_info, draggingPasteboard] };
1817    let filenames = unsafe { NSPasteboard::propertyListForType(pasteboard, NSFilenamesPboardType) };
1818    for file in unsafe { filenames.iter() } {
1819        let path = unsafe {
1820            let f = NSString::UTF8String(file);
1821            CStr::from_ptr(f).to_string_lossy().into_owned()
1822        };
1823        paths.push(PathBuf::from(path))
1824    }
1825    ExternalPaths(paths)
1826}
1827
1828extern "C" fn conclude_drag_operation(this: &Object, _: Sel, _: id) {
1829    let window_state = unsafe { get_window_state(this) };
1830    send_new_event(
1831        &window_state,
1832        PlatformInput::FileDrop(FileDropEvent::Exited),
1833    );
1834}
1835
1836async fn synthetic_drag(
1837    window_state: Weak<Mutex<MacWindowState>>,
1838    drag_id: usize,
1839    event: MouseMoveEvent,
1840) {
1841    loop {
1842        Timer::after(Duration::from_millis(16)).await;
1843        if let Some(window_state) = window_state.upgrade() {
1844            let mut lock = window_state.lock();
1845            if lock.synthetic_drag_counter == drag_id {
1846                if let Some(mut callback) = lock.event_callback.take() {
1847                    drop(lock);
1848                    callback(PlatformInput::MouseMove(event.clone()));
1849                    window_state.lock().event_callback = Some(callback);
1850                }
1851            } else {
1852                break;
1853            }
1854        }
1855    }
1856}
1857
1858fn send_new_event(window_state_lock: &Mutex<MacWindowState>, e: PlatformInput) -> bool {
1859    let window_state = window_state_lock.lock().event_callback.take();
1860    if let Some(mut callback) = window_state {
1861        callback(e);
1862        window_state_lock.lock().event_callback = Some(callback);
1863        true
1864    } else {
1865        false
1866    }
1867}
1868
1869fn drag_event_position(window_state: &Mutex<MacWindowState>, dragging_info: id) -> Point<Pixels> {
1870    let drag_location: NSPoint = unsafe { msg_send![dragging_info, draggingLocation] };
1871    convert_mouse_position(drag_location, window_state.lock().content_size().height)
1872}
1873
1874fn with_input_handler<F, R>(window: &Object, f: F) -> Option<R>
1875where
1876    F: FnOnce(&mut PlatformInputHandler) -> R,
1877{
1878    let window_state = unsafe { get_window_state(window) };
1879    let mut lock = window_state.as_ref().lock();
1880    if let Some(mut input_handler) = lock.input_handler.take() {
1881        drop(lock);
1882        let result = f(&mut input_handler);
1883        window_state.lock().input_handler = Some(input_handler);
1884        Some(result)
1885    } else {
1886        None
1887    }
1888}
1889
1890fn send_to_input_handler(window: &Object, ime: ImeInput) {
1891    unsafe {
1892        let window_state = get_window_state(window);
1893        let mut lock = window_state.lock();
1894        if let Some(ime_input) = lock.input_during_keydown.as_mut() {
1895            ime_input.push(ime);
1896            return;
1897        }
1898        if let Some(mut input_handler) = lock.input_handler.take() {
1899            drop(lock);
1900            match ime {
1901                ImeInput::InsertText(text, range) => {
1902                    input_handler.replace_text_in_range(range, &text)
1903                }
1904                ImeInput::SetMarkedText(text, range, marked_range) => {
1905                    input_handler.replace_and_mark_text_in_range(range, &text, marked_range)
1906                }
1907                ImeInput::UnmarkText => input_handler.unmark_text(),
1908            }
1909            window_state.lock().input_handler = Some(input_handler);
1910        }
1911    }
1912}
1913
1914unsafe fn display_id_for_screen(screen: id) -> CGDirectDisplayID {
1915    let device_description = NSScreen::deviceDescription(screen);
1916    let screen_number_key: id = NSString::alloc(nil).init_str("NSScreenNumber");
1917    let screen_number = device_description.objectForKey_(screen_number_key);
1918    let screen_number: NSUInteger = msg_send![screen_number, unsignedIntegerValue];
1919    screen_number as CGDirectDisplayID
1920}