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