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