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