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