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