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