window.rs

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