window.rs

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