window.rs

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