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, ExternalPaths,
   4    FileDropEvent, ForegroundExecutor, GlobalPixels, KeyDownEvent, Keystroke, Modifiers,
   5    ModifiersChangedEvent, MouseButton, MouseDownEvent, MouseMoveEvent, MouseUpEvent, Pixels,
   6    PlatformAtlas, PlatformDisplay, PlatformInput, 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};
  49
  50const WINDOW_STATE_IVAR: &str = "windowState";
  51
  52static mut WINDOW_CLASS: *const Class = ptr::null();
  53static mut PANEL_CLASS: *const Class = ptr::null();
  54static mut VIEW_CLASS: *const Class = ptr::null();
  55
  56#[allow(non_upper_case_globals)]
  57const NSWindowStyleMaskNonactivatingPanel: NSWindowStyleMask =
  58    unsafe { NSWindowStyleMask::from_bits_unchecked(1 << 7) };
  59#[allow(non_upper_case_globals)]
  60const NSNormalWindowLevel: NSInteger = 0;
  61#[allow(non_upper_case_globals)]
  62const NSPopUpWindowLevel: NSInteger = 101;
  63#[allow(non_upper_case_globals)]
  64const NSTrackingMouseEnteredAndExited: NSUInteger = 0x01;
  65#[allow(non_upper_case_globals)]
  66const NSTrackingMouseMoved: NSUInteger = 0x02;
  67#[allow(non_upper_case_globals)]
  68const NSTrackingActiveAlways: NSUInteger = 0x80;
  69#[allow(non_upper_case_globals)]
  70const NSTrackingInVisibleRect: NSUInteger = 0x200;
  71#[allow(non_upper_case_globals)]
  72const NSWindowAnimationBehaviorUtilityWindow: NSInteger = 4;
  73#[allow(non_upper_case_globals)]
  74const NSViewLayerContentsRedrawDuringViewResize: NSInteger = 2;
  75// https://developer.apple.com/documentation/appkit/nsdragoperation
  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    WINDOW_CLASS = build_window_class("GPUIWindow", class!(NSWindow));
  85    PANEL_CLASS = build_window_class("GPUIPanel", class!(NSPanel));
  86    VIEW_CLASS = {
  87        let mut decl = ClassDecl::new("GPUIView", class!(NSView)).unwrap();
  88        decl.add_ivar::<*mut c_void>(WINDOW_STATE_IVAR);
  89
  90        decl.add_method(sel!(dealloc), dealloc_view as extern "C" fn(&Object, Sel));
  91
  92        decl.add_method(
  93            sel!(performKeyEquivalent:),
  94            handle_key_equivalent as extern "C" fn(&Object, Sel, id) -> BOOL,
  95        );
  96        decl.add_method(
  97            sel!(keyDown:),
  98            handle_key_down as extern "C" fn(&Object, Sel, id),
  99        );
 100        decl.add_method(
 101            sel!(mouseDown:),
 102            handle_view_event as extern "C" fn(&Object, Sel, id),
 103        );
 104        decl.add_method(
 105            sel!(mouseUp:),
 106            handle_view_event as extern "C" fn(&Object, Sel, id),
 107        );
 108        decl.add_method(
 109            sel!(rightMouseDown:),
 110            handle_view_event as extern "C" fn(&Object, Sel, id),
 111        );
 112        decl.add_method(
 113            sel!(rightMouseUp:),
 114            handle_view_event as extern "C" fn(&Object, Sel, id),
 115        );
 116        decl.add_method(
 117            sel!(otherMouseDown:),
 118            handle_view_event as extern "C" fn(&Object, Sel, id),
 119        );
 120        decl.add_method(
 121            sel!(otherMouseUp:),
 122            handle_view_event as extern "C" fn(&Object, Sel, id),
 123        );
 124        decl.add_method(
 125            sel!(mouseMoved:),
 126            handle_view_event as extern "C" fn(&Object, Sel, id),
 127        );
 128        decl.add_method(
 129            sel!(mouseExited:),
 130            handle_view_event as extern "C" fn(&Object, Sel, id),
 131        );
 132        decl.add_method(
 133            sel!(mouseDragged:),
 134            handle_view_event as extern "C" fn(&Object, Sel, id),
 135        );
 136        decl.add_method(
 137            sel!(scrollWheel:),
 138            handle_view_event as extern "C" fn(&Object, Sel, id),
 139        );
 140        decl.add_method(
 141            sel!(flagsChanged:),
 142            handle_view_event as extern "C" fn(&Object, Sel, id),
 143        );
 144        decl.add_method(
 145            sel!(cancelOperation:),
 146            cancel_operation as extern "C" fn(&Object, Sel, id),
 147        );
 148
 149        decl.add_method(
 150            sel!(makeBackingLayer),
 151            make_backing_layer as extern "C" fn(&Object, Sel) -> id,
 152        );
 153
 154        decl.add_protocol(Protocol::get("CALayerDelegate").unwrap());
 155        decl.add_method(
 156            sel!(viewDidChangeBackingProperties),
 157            view_did_change_backing_properties as extern "C" fn(&Object, Sel),
 158        );
 159        decl.add_method(
 160            sel!(setFrameSize:),
 161            set_frame_size as extern "C" fn(&Object, Sel, NSSize),
 162        );
 163        decl.add_method(
 164            sel!(displayLayer:),
 165            display_layer as extern "C" fn(&Object, Sel, id),
 166        );
 167
 168        decl.add_protocol(Protocol::get("NSTextInputClient").unwrap());
 169        decl.add_method(
 170            sel!(validAttributesForMarkedText),
 171            valid_attributes_for_marked_text as extern "C" fn(&Object, Sel) -> id,
 172        );
 173        decl.add_method(
 174            sel!(hasMarkedText),
 175            has_marked_text as extern "C" fn(&Object, Sel) -> BOOL,
 176        );
 177        decl.add_method(
 178            sel!(markedRange),
 179            marked_range as extern "C" fn(&Object, Sel) -> NSRange,
 180        );
 181        decl.add_method(
 182            sel!(selectedRange),
 183            selected_range as extern "C" fn(&Object, Sel) -> NSRange,
 184        );
 185        decl.add_method(
 186            sel!(firstRectForCharacterRange:actualRange:),
 187            first_rect_for_character_range as extern "C" fn(&Object, Sel, NSRange, id) -> NSRect,
 188        );
 189        decl.add_method(
 190            sel!(insertText:replacementRange:),
 191            insert_text as extern "C" fn(&Object, Sel, id, NSRange),
 192        );
 193        decl.add_method(
 194            sel!(setMarkedText:selectedRange:replacementRange:),
 195            set_marked_text as extern "C" fn(&Object, Sel, id, NSRange, NSRange),
 196        );
 197        decl.add_method(sel!(unmarkText), unmark_text as extern "C" fn(&Object, Sel));
 198        decl.add_method(
 199            sel!(attributedSubstringForProposedRange:actualRange:),
 200            attributed_substring_for_proposed_range
 201                as extern "C" fn(&Object, Sel, NSRange, *mut c_void) -> id,
 202        );
 203        decl.add_method(
 204            sel!(viewDidChangeEffectiveAppearance),
 205            view_did_change_effective_appearance as extern "C" fn(&Object, Sel),
 206        );
 207
 208        // Suppress beep on keystrokes with modifier keys.
 209        decl.add_method(
 210            sel!(doCommandBySelector:),
 211            do_command_by_selector as extern "C" fn(&Object, Sel, Sel),
 212        );
 213
 214        decl.add_method(
 215            sel!(acceptsFirstMouse:),
 216            accepts_first_mouse as extern "C" fn(&Object, Sel, id) -> BOOL,
 217        );
 218
 219        decl.register()
 220    };
 221}
 222
 223pub fn convert_mouse_position(position: NSPoint, window_height: Pixels) -> Point<Pixels> {
 224    point(
 225        px(position.x as f32),
 226        // MacOS screen coordinates are relative to bottom left
 227        window_height - px(position.y as f32),
 228    )
 229}
 230
 231unsafe fn build_window_class(name: &'static str, superclass: &Class) -> *const Class {
 232    let mut decl = ClassDecl::new(name, superclass).unwrap();
 233    decl.add_ivar::<*mut c_void>(WINDOW_STATE_IVAR);
 234    decl.add_method(sel!(dealloc), dealloc_window as extern "C" fn(&Object, Sel));
 235    decl.add_method(
 236        sel!(canBecomeMainWindow),
 237        yes as extern "C" fn(&Object, Sel) -> BOOL,
 238    );
 239    decl.add_method(
 240        sel!(canBecomeKeyWindow),
 241        yes as extern "C" fn(&Object, Sel) -> BOOL,
 242    );
 243    decl.add_method(
 244        sel!(windowDidResize:),
 245        window_did_resize as extern "C" fn(&Object, Sel, id),
 246    );
 247    decl.add_method(
 248        sel!(windowWillEnterFullScreen:),
 249        window_will_enter_fullscreen as extern "C" fn(&Object, Sel, id),
 250    );
 251    decl.add_method(
 252        sel!(windowWillExitFullScreen:),
 253        window_will_exit_fullscreen as extern "C" fn(&Object, Sel, id),
 254    );
 255    decl.add_method(
 256        sel!(windowDidMove:),
 257        window_did_move as extern "C" fn(&Object, Sel, id),
 258    );
 259    decl.add_method(
 260        sel!(windowDidBecomeKey:),
 261        window_did_change_key_status as extern "C" fn(&Object, Sel, id),
 262    );
 263    decl.add_method(
 264        sel!(windowDidResignKey:),
 265        window_did_change_key_status as extern "C" fn(&Object, Sel, id),
 266    );
 267    decl.add_method(
 268        sel!(windowShouldClose:),
 269        window_should_close as extern "C" fn(&Object, Sel, id) -> BOOL,
 270    );
 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    kind: WindowKind,
 321    request_frame_callback: Option<Box<dyn FnMut()>>,
 322    event_callback: Option<Box<dyn FnMut(PlatformInput) -> 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<PlatformInput>,
 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    external_files_dragged: bool,
 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(
 455        handle: AnyWindowHandle,
 456        options: WindowOptions,
 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(MacDisplay::find_by_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 native_view: id = msg_send![VIEW_CLASS, alloc];
 520            let native_view = NSView::init(native_view);
 521
 522            assert!(!native_view.is_null());
 523
 524            let window = Self(Arc::new(Mutex::new(MacWindowState {
 525                handle,
 526                executor,
 527                native_window,
 528                renderer: MetalRenderer::new(true),
 529                kind: options.kind,
 530                request_frame_callback: None,
 531                event_callback: None,
 532                activate_callback: None,
 533                resize_callback: None,
 534                fullscreen_callback: None,
 535                moved_callback: None,
 536                should_close_callback: None,
 537                close_callback: None,
 538                appearance_changed_callback: None,
 539                input_handler: None,
 540                pending_key_down: None,
 541                last_key_equivalent: None,
 542                synthetic_drag_counter: 0,
 543                last_fresh_keydown: None,
 544                traffic_light_position: options
 545                    .titlebar
 546                    .as_ref()
 547                    .and_then(|titlebar| titlebar.traffic_light_position),
 548                previous_modifiers_changed_event: None,
 549                ime_state: ImeState::None,
 550                ime_text: None,
 551                external_files_dragged: false,
 552            })));
 553
 554            (*native_window).set_ivar(
 555                WINDOW_STATE_IVAR,
 556                Arc::into_raw(window.0.clone()) as *const c_void,
 557            );
 558            native_window.setDelegate_(native_window);
 559            (*native_view).set_ivar(
 560                WINDOW_STATE_IVAR,
 561                Arc::into_raw(window.0.clone()) as *const c_void,
 562            );
 563
 564            if let Some(title) = options
 565                .titlebar
 566                .as_ref()
 567                .and_then(|t| t.title.as_ref().map(AsRef::as_ref))
 568            {
 569                native_window.setTitle_(NSString::alloc(nil).init_str(title));
 570            }
 571
 572            native_window.setMovable_(options.is_movable as BOOL);
 573
 574            if options
 575                .titlebar
 576                .map_or(true, |titlebar| titlebar.appears_transparent)
 577            {
 578                native_window.setTitlebarAppearsTransparent_(YES);
 579                native_window.setTitleVisibility_(NSWindowTitleVisibility::NSWindowTitleHidden);
 580            }
 581
 582            native_view.setAutoresizingMask_(NSViewWidthSizable | NSViewHeightSizable);
 583            native_view.setWantsBestResolutionOpenGLSurface_(YES);
 584
 585            // From winit crate: On Mojave, views automatically become layer-backed shortly after
 586            // being added to a native_window. Changing the layer-backedness of a view breaks the
 587            // association between the view and its associated OpenGL context. To work around this,
 588            // on we explicitly make the view layer-backed up front so that AppKit doesn't do it
 589            // itself and break the association with its context.
 590            native_view.setWantsLayer(YES);
 591            let _: () = msg_send![
 592                native_view,
 593                setLayerContentsRedrawPolicy: NSViewLayerContentsRedrawDuringViewResize
 594            ];
 595
 596            native_window.setContentView_(native_view.autorelease());
 597            native_window.makeFirstResponder_(native_view);
 598
 599            if options.center {
 600                native_window.center();
 601            }
 602
 603            match options.kind {
 604                WindowKind::Normal => {
 605                    native_window.setLevel_(NSNormalWindowLevel);
 606                    native_window.setAcceptsMouseMovedEvents_(YES);
 607                }
 608                WindowKind::PopUp => {
 609                    // Use a tracking area to allow receiving MouseMoved events even when
 610                    // the window or application aren't active, which is often the case
 611                    // e.g. for notification windows.
 612                    let tracking_area: id = msg_send![class!(NSTrackingArea), alloc];
 613                    let _: () = msg_send![
 614                        tracking_area,
 615                        initWithRect: NSRect::new(NSPoint::new(0., 0.), NSSize::new(0., 0.))
 616                        options: NSTrackingMouseEnteredAndExited | NSTrackingMouseMoved | NSTrackingActiveAlways | NSTrackingInVisibleRect
 617                        owner: native_view
 618                        userInfo: nil
 619                    ];
 620                    let _: () =
 621                        msg_send![native_view, addTrackingArea: tracking_area.autorelease()];
 622
 623                    native_window.setLevel_(NSPopUpWindowLevel);
 624                    let _: () = msg_send![
 625                        native_window,
 626                        setAnimationBehavior: NSWindowAnimationBehaviorUtilityWindow
 627                    ];
 628                    native_window.setCollectionBehavior_(
 629                        NSWindowCollectionBehavior::NSWindowCollectionBehaviorCanJoinAllSpaces |
 630                        NSWindowCollectionBehavior::NSWindowCollectionBehaviorFullScreenAuxiliary
 631                    );
 632                }
 633            }
 634            if options.focus {
 635                native_window.makeKeyAndOrderFront_(nil);
 636            } else if options.show {
 637                native_window.orderFront_(nil);
 638            }
 639
 640            let screen = native_window.screen();
 641            match options.bounds {
 642                WindowBounds::Fullscreen => {
 643                    // We need to toggle full screen asynchronously as doing so may
 644                    // call back into the platform handlers.
 645                    window.toggle_full_screen()
 646                }
 647                WindowBounds::Maximized => {
 648                    native_window.setFrame_display_(screen.visibleFrame(), YES);
 649                }
 650                WindowBounds::Fixed(bounds) => {
 651                    let display_bounds = display.bounds();
 652                    let frame = if bounds.intersects(&display_bounds) {
 653                        display_bounds_to_native(bounds)
 654                    } else {
 655                        display_bounds_to_native(display_bounds)
 656                    };
 657                    native_window.setFrame_display_(mem::transmute::<CGRect, NSRect>(frame), YES);
 658                }
 659            }
 660
 661            window.0.lock().move_traffic_light();
 662            pool.drain();
 663
 664            window
 665        }
 666    }
 667
 668    pub fn active_window() -> Option<AnyWindowHandle> {
 669        unsafe {
 670            let app = NSApplication::sharedApplication(nil);
 671            let main_window: id = msg_send![app, mainWindow];
 672            if msg_send![main_window, isKindOfClass: WINDOW_CLASS] {
 673                let handle = get_window_state(&*main_window).lock().handle;
 674                Some(handle)
 675            } else {
 676                None
 677            }
 678        }
 679    }
 680}
 681
 682impl Drop for MacWindow {
 683    fn drop(&mut self) {
 684        let this = self.0.lock();
 685        let window = this.native_window;
 686        this.executor
 687            .spawn(async move {
 688                unsafe {
 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 take_input_handler(&mut self) -> Option<Box<dyn PlatformInputHandler>> {
 774        self.0.as_ref().lock().input_handler.take()
 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_request_frame(&self, callback: Box<dyn FnMut()>) {
 930        self.0.as_ref().lock().request_frame_callback = Some(callback);
 931    }
 932
 933    fn on_input(&self, callback: Box<dyn FnMut(PlatformInput) -> bool>) {
 934        self.0.as_ref().lock().event_callback = Some(callback);
 935    }
 936
 937    fn on_active_status_change(&self, callback: Box<dyn FnMut(bool)>) {
 938        self.0.as_ref().lock().activate_callback = Some(callback);
 939    }
 940
 941    fn on_resize(&self, callback: Box<dyn FnMut(Size<Pixels>, f32)>) {
 942        self.0.as_ref().lock().resize_callback = Some(callback);
 943    }
 944
 945    fn on_fullscreen(&self, callback: Box<dyn FnMut(bool)>) {
 946        self.0.as_ref().lock().fullscreen_callback = Some(callback);
 947    }
 948
 949    fn on_moved(&self, callback: Box<dyn FnMut()>) {
 950        self.0.as_ref().lock().moved_callback = Some(callback);
 951    }
 952
 953    fn on_should_close(&self, callback: Box<dyn FnMut() -> bool>) {
 954        self.0.as_ref().lock().should_close_callback = Some(callback);
 955    }
 956
 957    fn on_close(&self, callback: Box<dyn FnOnce()>) {
 958        self.0.as_ref().lock().close_callback = Some(callback);
 959    }
 960
 961    fn on_appearance_changed(&self, callback: Box<dyn FnMut()>) {
 962        self.0.lock().appearance_changed_callback = Some(callback);
 963    }
 964
 965    fn is_topmost_for_position(&self, position: Point<Pixels>) -> bool {
 966        let self_borrow = self.0.lock();
 967        let self_handle = self_borrow.handle;
 968
 969        unsafe {
 970            let app = NSApplication::sharedApplication(nil);
 971
 972            // Convert back to screen coordinates
 973            let screen_point = self_borrow.to_screen_ns_point(position);
 974
 975            let window_number: NSInteger = msg_send![class!(NSWindow), windowNumberAtPoint:screen_point belowWindowWithWindowNumber:0];
 976            let top_most_window: id = msg_send![app, windowWithWindowNumber: window_number];
 977
 978            let is_panel: BOOL = msg_send![top_most_window, isKindOfClass: PANEL_CLASS];
 979            let is_window: BOOL = msg_send![top_most_window, isKindOfClass: WINDOW_CLASS];
 980            if is_panel == YES || is_window == YES {
 981                let topmost_window = get_window_state(&*top_most_window).lock().handle;
 982                topmost_window == self_handle
 983            } else {
 984                // Someone else's window is on top
 985                false
 986            }
 987        }
 988    }
 989
 990    fn invalidate(&self) {
 991        let this = self.0.lock();
 992        unsafe {
 993            let _: () = msg_send![this.native_window.contentView(), setNeedsDisplay: YES];
 994        }
 995    }
 996
 997    fn draw(&self, scene: &crate::Scene) {
 998        let mut this = self.0.lock();
 999        this.renderer.draw(scene);
1000    }
1001
1002    fn sprite_atlas(&self) -> Arc<dyn PlatformAtlas> {
1003        self.0.lock().renderer.sprite_atlas().clone()
1004    }
1005}
1006
1007fn get_scale_factor(native_window: id) -> f32 {
1008    unsafe {
1009        let screen: id = msg_send![native_window, screen];
1010        NSScreen::backingScaleFactor(screen) as f32
1011    }
1012}
1013
1014unsafe fn get_window_state(object: &Object) -> Arc<Mutex<MacWindowState>> {
1015    let raw: *mut c_void = *object.get_ivar(WINDOW_STATE_IVAR);
1016    let rc1 = Arc::from_raw(raw as *mut Mutex<MacWindowState>);
1017    let rc2 = rc1.clone();
1018    mem::forget(rc1);
1019    rc2
1020}
1021
1022unsafe fn drop_window_state(object: &Object) {
1023    let raw: *mut c_void = *object.get_ivar(WINDOW_STATE_IVAR);
1024    Rc::from_raw(raw as *mut RefCell<MacWindowState>);
1025}
1026
1027extern "C" fn yes(_: &Object, _: Sel) -> BOOL {
1028    YES
1029}
1030
1031extern "C" fn dealloc_window(this: &Object, _: Sel) {
1032    unsafe {
1033        drop_window_state(this);
1034        let _: () = msg_send![super(this, class!(NSWindow)), dealloc];
1035    }
1036}
1037
1038extern "C" fn dealloc_view(this: &Object, _: Sel) {
1039    unsafe {
1040        drop_window_state(this);
1041        let _: () = msg_send![super(this, class!(NSView)), dealloc];
1042    }
1043}
1044
1045extern "C" fn handle_key_equivalent(this: &Object, _: Sel, native_event: id) -> BOOL {
1046    handle_key_event(this, native_event, true)
1047}
1048
1049extern "C" fn handle_key_down(this: &Object, _: Sel, native_event: id) {
1050    handle_key_event(this, native_event, false);
1051}
1052
1053extern "C" fn handle_key_event(this: &Object, native_event: id, key_equivalent: bool) -> BOOL {
1054    let window_state = unsafe { get_window_state(this) };
1055    let mut lock = window_state.as_ref().lock();
1056
1057    let window_height = lock.content_size().height;
1058    let event = unsafe { PlatformInput::from_native(native_event, Some(window_height)) };
1059
1060    if let Some(PlatformInput::KeyDown(event)) = event {
1061        // For certain keystrokes, macOS will first dispatch a "key equivalent" event.
1062        // If that event isn't handled, it will then dispatch a "key down" event. GPUI
1063        // makes no distinction between these two types of events, so we need to ignore
1064        // the "key down" event if we've already just processed its "key equivalent" version.
1065        if key_equivalent {
1066            lock.last_key_equivalent = Some(event.clone());
1067        } else if lock.last_key_equivalent.take().as_ref() == Some(&event) {
1068            return NO;
1069        }
1070
1071        let keydown = event.keystroke.clone();
1072        let fn_modifier = keydown.modifiers.function;
1073        // Ignore events from held-down keys after some of the initially-pressed keys
1074        // were released.
1075        if event.is_held {
1076            if lock.last_fresh_keydown.as_ref() != Some(&keydown) {
1077                return YES;
1078            }
1079        } else {
1080            lock.last_fresh_keydown = Some(keydown);
1081        }
1082        lock.pending_key_down = Some((event, None));
1083        drop(lock);
1084
1085        // Send the event to the input context for IME handling, unless the `fn` modifier is
1086        // being pressed.
1087        if !fn_modifier {
1088            unsafe {
1089                let input_context: id = msg_send![this, inputContext];
1090                let _: BOOL = msg_send![input_context, handleEvent: native_event];
1091            }
1092        }
1093
1094        let mut handled = false;
1095        let mut lock = window_state.lock();
1096        let ime_text = lock.ime_text.clone();
1097        if let Some((event, insert_text)) = lock.pending_key_down.take() {
1098            let is_held = event.is_held;
1099            if let Some(mut callback) = lock.event_callback.take() {
1100                drop(lock);
1101
1102                let is_composing =
1103                    with_input_handler(this, |input_handler| input_handler.marked_text_range())
1104                        .flatten()
1105                        .is_some();
1106                if !is_composing {
1107                    handled = callback(PlatformInput::KeyDown(event));
1108                }
1109
1110                if !handled {
1111                    if let Some(insert) = insert_text {
1112                        handled = true;
1113                        with_input_handler(this, |input_handler| {
1114                            input_handler
1115                                .replace_text_in_range(insert.replacement_range, &insert.text)
1116                        });
1117                    } else if !is_composing && is_held {
1118                        if let Some(last_insert_text) = ime_text {
1119                            //MacOS IME is a bit funky, and even when you've told it there's nothing to
1120                            //inter it will still swallow certain keys (e.g. 'f', 'j') and not others
1121                            //(e.g. 'n'). This is a problem for certain kinds of views, like the terminal
1122                            with_input_handler(this, |input_handler| {
1123                                if input_handler.selected_text_range().is_none() {
1124                                    handled = true;
1125                                    input_handler.replace_text_in_range(None, &last_insert_text)
1126                                }
1127                            });
1128                        }
1129                    }
1130                }
1131
1132                window_state.lock().event_callback = Some(callback);
1133            }
1134        } else {
1135            handled = true;
1136        }
1137
1138        handled as BOOL
1139    } else {
1140        NO
1141    }
1142}
1143
1144extern "C" fn handle_view_event(this: &Object, _: Sel, native_event: id) {
1145    let window_state = unsafe { get_window_state(this) };
1146    let weak_window_state = Arc::downgrade(&window_state);
1147    let mut lock = window_state.as_ref().lock();
1148    let is_active = unsafe { lock.native_window.isKeyWindow() == YES };
1149
1150    let window_height = lock.content_size().height;
1151    let event = unsafe { PlatformInput::from_native(native_event, Some(window_height)) };
1152
1153    if let Some(mut event) = event {
1154        match &mut event {
1155            PlatformInput::MouseDown(
1156                event @ MouseDownEvent {
1157                    button: MouseButton::Left,
1158                    modifiers: Modifiers { control: true, .. },
1159                    ..
1160                },
1161            ) => {
1162                // On mac, a ctrl-left click should be handled as a right click.
1163                *event = MouseDownEvent {
1164                    button: MouseButton::Right,
1165                    modifiers: Modifiers {
1166                        control: false,
1167                        ..event.modifiers
1168                    },
1169                    click_count: 1,
1170                    ..*event
1171                };
1172            }
1173
1174            // Because we map a ctrl-left_down to a right_down -> right_up let's ignore
1175            // the ctrl-left_up to avoid having a mismatch in button down/up events if the
1176            // user is still holding ctrl when releasing the left mouse button
1177            PlatformInput::MouseUp(
1178                event @ MouseUpEvent {
1179                    button: MouseButton::Left,
1180                    modifiers: Modifiers { control: true, .. },
1181                    ..
1182                },
1183            ) => {
1184                *event = MouseUpEvent {
1185                    button: MouseButton::Right,
1186                    modifiers: Modifiers {
1187                        control: false,
1188                        ..event.modifiers
1189                    },
1190                    click_count: 1,
1191                    ..*event
1192                };
1193            }
1194
1195            _ => {}
1196        };
1197
1198        match &event {
1199            PlatformInput::MouseMove(
1200                event @ MouseMoveEvent {
1201                    pressed_button: Some(_),
1202                    ..
1203                },
1204            ) => {
1205                // Synthetic drag is used for selecting long buffer contents while buffer is being scrolled.
1206                // External file drag and drop is able to emit its own synthetic mouse events which will conflict
1207                // with these ones.
1208                if !lock.external_files_dragged {
1209                    lock.synthetic_drag_counter += 1;
1210                    let executor = lock.executor.clone();
1211                    executor
1212                        .spawn(synthetic_drag(
1213                            weak_window_state,
1214                            lock.synthetic_drag_counter,
1215                            event.clone(),
1216                        ))
1217                        .detach();
1218                }
1219            }
1220
1221            PlatformInput::MouseMove(_) if !(is_active || lock.kind == WindowKind::PopUp) => return,
1222
1223            PlatformInput::MouseUp(MouseUpEvent { .. }) => {
1224                lock.synthetic_drag_counter += 1;
1225            }
1226
1227            PlatformInput::ModifiersChanged(ModifiersChangedEvent { modifiers }) => {
1228                // Only raise modifiers changed event when they have actually changed
1229                if let Some(PlatformInput::ModifiersChanged(ModifiersChangedEvent {
1230                    modifiers: prev_modifiers,
1231                })) = &lock.previous_modifiers_changed_event
1232                {
1233                    if prev_modifiers == modifiers {
1234                        return;
1235                    }
1236                }
1237
1238                lock.previous_modifiers_changed_event = Some(event.clone());
1239            }
1240
1241            _ => {}
1242        }
1243
1244        if let Some(mut callback) = lock.event_callback.take() {
1245            drop(lock);
1246            callback(event);
1247            window_state.lock().event_callback = Some(callback);
1248        }
1249    }
1250}
1251
1252// Allows us to receive `cmd-.` (the shortcut for closing a dialog)
1253// https://bugs.eclipse.org/bugs/show_bug.cgi?id=300620#c6
1254extern "C" fn cancel_operation(this: &Object, _sel: Sel, _sender: id) {
1255    let window_state = unsafe { get_window_state(this) };
1256    let mut lock = window_state.as_ref().lock();
1257
1258    let keystroke = Keystroke {
1259        modifiers: Default::default(),
1260        key: ".".into(),
1261        ime_key: None,
1262    };
1263    let event = PlatformInput::KeyDown(KeyDownEvent {
1264        keystroke: keystroke.clone(),
1265        is_held: false,
1266    });
1267
1268    lock.last_fresh_keydown = Some(keystroke);
1269    if let Some(mut callback) = lock.event_callback.take() {
1270        drop(lock);
1271        callback(event);
1272        window_state.lock().event_callback = Some(callback);
1273    }
1274}
1275
1276extern "C" fn window_did_resize(this: &Object, _: Sel, _: id) {
1277    let window_state = unsafe { get_window_state(this) };
1278    window_state.as_ref().lock().move_traffic_light();
1279}
1280
1281extern "C" fn window_will_enter_fullscreen(this: &Object, _: Sel, _: id) {
1282    window_fullscreen_changed(this, true);
1283}
1284
1285extern "C" fn window_will_exit_fullscreen(this: &Object, _: Sel, _: id) {
1286    window_fullscreen_changed(this, false);
1287}
1288
1289fn window_fullscreen_changed(this: &Object, is_fullscreen: bool) {
1290    let window_state = unsafe { get_window_state(this) };
1291    let mut lock = window_state.as_ref().lock();
1292    if let Some(mut callback) = lock.fullscreen_callback.take() {
1293        drop(lock);
1294        callback(is_fullscreen);
1295        window_state.lock().fullscreen_callback = Some(callback);
1296    }
1297}
1298
1299extern "C" fn window_did_move(this: &Object, _: Sel, _: id) {
1300    let window_state = unsafe { get_window_state(this) };
1301    let mut lock = window_state.as_ref().lock();
1302    if let Some(mut callback) = lock.moved_callback.take() {
1303        drop(lock);
1304        callback();
1305        window_state.lock().moved_callback = Some(callback);
1306    }
1307}
1308
1309extern "C" fn window_did_change_key_status(this: &Object, selector: Sel, _: id) {
1310    let window_state = unsafe { get_window_state(this) };
1311    let lock = window_state.lock();
1312    let is_active = unsafe { lock.native_window.isKeyWindow() == YES };
1313
1314    // When opening a pop-up while the application isn't active, Cocoa sends a spurious
1315    // `windowDidBecomeKey` message to the previous key window even though that window
1316    // isn't actually key. This causes a bug if the application is later activated while
1317    // the pop-up is still open, making it impossible to activate the previous key window
1318    // even if the pop-up gets closed. The only way to activate it again is to de-activate
1319    // the app and re-activate it, which is a pretty bad UX.
1320    // The following code detects the spurious event and invokes `resignKeyWindow`:
1321    // in theory, we're not supposed to invoke this method manually but it balances out
1322    // the spurious `becomeKeyWindow` event and helps us work around that bug.
1323    if selector == sel!(windowDidBecomeKey:) && !is_active {
1324        unsafe {
1325            let _: () = msg_send![lock.native_window, resignKeyWindow];
1326            return;
1327        }
1328    }
1329
1330    let executor = lock.executor.clone();
1331    drop(lock);
1332    executor
1333        .spawn(async move {
1334            let mut lock = window_state.as_ref().lock();
1335            if let Some(mut callback) = lock.activate_callback.take() {
1336                drop(lock);
1337                callback(is_active);
1338                window_state.lock().activate_callback = Some(callback);
1339            };
1340        })
1341        .detach();
1342}
1343
1344extern "C" fn window_should_close(this: &Object, _: Sel, _: id) -> BOOL {
1345    let window_state = unsafe { get_window_state(this) };
1346    let mut lock = window_state.as_ref().lock();
1347    if let Some(mut callback) = lock.should_close_callback.take() {
1348        drop(lock);
1349        let should_close = callback();
1350        window_state.lock().should_close_callback = Some(callback);
1351        should_close as BOOL
1352    } else {
1353        YES
1354    }
1355}
1356
1357extern "C" fn close_window(this: &Object, _: Sel) {
1358    unsafe {
1359        let close_callback = {
1360            let window_state = get_window_state(this);
1361            window_state
1362                .as_ref()
1363                .try_lock()
1364                .and_then(|mut window_state| window_state.close_callback.take())
1365        };
1366
1367        if let Some(callback) = close_callback {
1368            callback();
1369        }
1370
1371        let _: () = msg_send![super(this, class!(NSWindow)), close];
1372    }
1373}
1374
1375extern "C" fn make_backing_layer(this: &Object, _: Sel) -> id {
1376    let window_state = unsafe { get_window_state(this) };
1377    let window_state = window_state.as_ref().lock();
1378    window_state.renderer.layer().as_ptr() as id
1379}
1380
1381extern "C" fn view_did_change_backing_properties(this: &Object, _: Sel) {
1382    let window_state = unsafe { get_window_state(this) };
1383    let mut lock = window_state.as_ref().lock();
1384
1385    unsafe {
1386        let scale_factor = lock.scale_factor() as f64;
1387        let size = lock.content_size();
1388        let drawable_size: NSSize = NSSize {
1389            width: f64::from(size.width) * scale_factor,
1390            height: f64::from(size.height) * scale_factor,
1391        };
1392
1393        let _: () = msg_send![
1394            lock.renderer.layer(),
1395            setContentsScale: scale_factor
1396        ];
1397        let _: () = msg_send![
1398            lock.renderer.layer(),
1399            setDrawableSize: drawable_size
1400        ];
1401    }
1402
1403    if let Some(mut callback) = lock.resize_callback.take() {
1404        let content_size = lock.content_size();
1405        let scale_factor = lock.scale_factor();
1406        drop(lock);
1407        callback(content_size, scale_factor);
1408        window_state.as_ref().lock().resize_callback = Some(callback);
1409    };
1410}
1411
1412extern "C" fn set_frame_size(this: &Object, _: Sel, size: NSSize) {
1413    let window_state = unsafe { get_window_state(this) };
1414    let lock = window_state.as_ref().lock();
1415
1416    if lock.content_size() == size.into() {
1417        return;
1418    }
1419
1420    unsafe {
1421        let _: () = msg_send![super(this, class!(NSView)), setFrameSize: size];
1422    }
1423
1424    let scale_factor = lock.scale_factor() as f64;
1425    let drawable_size: NSSize = NSSize {
1426        width: size.width * scale_factor,
1427        height: size.height * scale_factor,
1428    };
1429
1430    unsafe {
1431        let _: () = msg_send![
1432            lock.renderer.layer(),
1433            setDrawableSize: drawable_size
1434        ];
1435    }
1436
1437    drop(lock);
1438    let mut lock = window_state.lock();
1439    if let Some(mut callback) = lock.resize_callback.take() {
1440        let content_size = lock.content_size();
1441        let scale_factor = lock.scale_factor();
1442        drop(lock);
1443        callback(content_size, scale_factor);
1444        window_state.lock().resize_callback = Some(callback);
1445    };
1446}
1447
1448extern "C" fn display_layer(this: &Object, _: Sel, _: id) {
1449    let window_state = unsafe { get_window_state(this) };
1450    let mut lock = window_state.lock();
1451    if let Some(mut callback) = lock.request_frame_callback.take() {
1452        drop(lock);
1453        callback();
1454        window_state.lock().request_frame_callback = Some(callback);
1455    }
1456}
1457
1458extern "C" fn valid_attributes_for_marked_text(_: &Object, _: Sel) -> id {
1459    unsafe { msg_send![class!(NSArray), array] }
1460}
1461
1462extern "C" fn has_marked_text(this: &Object, _: Sel) -> BOOL {
1463    with_input_handler(this, |input_handler| input_handler.marked_text_range())
1464        .flatten()
1465        .is_some() as BOOL
1466}
1467
1468extern "C" fn marked_range(this: &Object, _: Sel) -> NSRange {
1469    with_input_handler(this, |input_handler| input_handler.marked_text_range())
1470        .flatten()
1471        .map_or(NSRange::invalid(), |range| range.into())
1472}
1473
1474extern "C" fn selected_range(this: &Object, _: Sel) -> NSRange {
1475    with_input_handler(this, |input_handler| input_handler.selected_text_range())
1476        .flatten()
1477        .map_or(NSRange::invalid(), |range| range.into())
1478}
1479
1480extern "C" fn first_rect_for_character_range(
1481    this: &Object,
1482    _: Sel,
1483    range: NSRange,
1484    _: id,
1485) -> NSRect {
1486    let frame = unsafe {
1487        let window = get_window_state(this).lock().native_window;
1488        NSView::frame(window)
1489    };
1490    with_input_handler(this, |input_handler| {
1491        input_handler.bounds_for_range(range.to_range()?)
1492    })
1493    .flatten()
1494    .map_or(
1495        NSRect::new(NSPoint::new(0., 0.), NSSize::new(0., 0.)),
1496        |bounds| {
1497            NSRect::new(
1498                NSPoint::new(
1499                    frame.origin.x + bounds.origin.x.0 as f64,
1500                    frame.origin.y + frame.size.height
1501                        - bounds.origin.y.0 as f64
1502                        - bounds.size.height.0 as f64,
1503                ),
1504                NSSize::new(bounds.size.width.0 as f64, bounds.size.height.0 as f64),
1505            )
1506        },
1507    )
1508}
1509
1510extern "C" fn insert_text(this: &Object, _: Sel, text: id, replacement_range: NSRange) {
1511    unsafe {
1512        let window_state = get_window_state(this);
1513        let mut lock = window_state.lock();
1514        let pending_key_down = lock.pending_key_down.take();
1515        drop(lock);
1516
1517        let is_attributed_string: BOOL =
1518            msg_send![text, isKindOfClass: [class!(NSAttributedString)]];
1519        let text: id = if is_attributed_string == YES {
1520            msg_send![text, string]
1521        } else {
1522            text
1523        };
1524        let text = CStr::from_ptr(text.UTF8String() as *mut c_char)
1525            .to_str()
1526            .unwrap();
1527        let replacement_range = replacement_range.to_range();
1528
1529        window_state.lock().ime_text = Some(text.to_string());
1530        window_state.lock().ime_state = ImeState::Acted;
1531
1532        let is_composing =
1533            with_input_handler(this, |input_handler| input_handler.marked_text_range())
1534                .flatten()
1535                .is_some();
1536
1537        if is_composing || text.chars().count() > 1 || pending_key_down.is_none() {
1538            with_input_handler(this, |input_handler| {
1539                input_handler.replace_text_in_range(replacement_range, text)
1540            });
1541        } else {
1542            let mut pending_key_down = pending_key_down.unwrap();
1543            pending_key_down.1 = Some(InsertText {
1544                replacement_range,
1545                text: text.to_string(),
1546            });
1547            if text.to_string().to_ascii_lowercase() != pending_key_down.0.keystroke.key {
1548                pending_key_down.0.keystroke.ime_key = Some(text.to_string());
1549            }
1550            window_state.lock().pending_key_down = Some(pending_key_down);
1551        }
1552    }
1553}
1554
1555extern "C" fn set_marked_text(
1556    this: &Object,
1557    _: Sel,
1558    text: id,
1559    selected_range: NSRange,
1560    replacement_range: NSRange,
1561) {
1562    unsafe {
1563        let window_state = get_window_state(this);
1564        window_state.lock().pending_key_down.take();
1565
1566        let is_attributed_string: BOOL =
1567            msg_send![text, isKindOfClass: [class!(NSAttributedString)]];
1568        let text: id = if is_attributed_string == YES {
1569            msg_send![text, string]
1570        } else {
1571            text
1572        };
1573        let selected_range = selected_range.to_range();
1574        let replacement_range = replacement_range.to_range();
1575        let text = CStr::from_ptr(text.UTF8String() as *mut c_char)
1576            .to_str()
1577            .unwrap();
1578
1579        window_state.lock().ime_state = ImeState::Acted;
1580        window_state.lock().ime_text = Some(text.to_string());
1581
1582        with_input_handler(this, |input_handler| {
1583            input_handler.replace_and_mark_text_in_range(replacement_range, text, selected_range);
1584        });
1585    }
1586}
1587
1588extern "C" fn unmark_text(this: &Object, _: Sel) {
1589    unsafe {
1590        let state = get_window_state(this);
1591        let mut borrow = state.lock();
1592        borrow.ime_state = ImeState::Acted;
1593        borrow.ime_text.take();
1594    }
1595
1596    with_input_handler(this, |input_handler| input_handler.unmark_text());
1597}
1598
1599extern "C" fn attributed_substring_for_proposed_range(
1600    this: &Object,
1601    _: Sel,
1602    range: NSRange,
1603    _actual_range: *mut c_void,
1604) -> id {
1605    with_input_handler(this, |input_handler| {
1606        let range = range.to_range()?;
1607        if range.is_empty() {
1608            return None;
1609        }
1610
1611        let selected_text = input_handler.text_for_range(range)?;
1612        unsafe {
1613            let string: id = msg_send![class!(NSAttributedString), alloc];
1614            let string: id = msg_send![string, initWithString: ns_string(&selected_text)];
1615            Some(string)
1616        }
1617    })
1618    .flatten()
1619    .unwrap_or(nil)
1620}
1621
1622extern "C" fn do_command_by_selector(this: &Object, _: Sel, _: Sel) {
1623    unsafe {
1624        let state = get_window_state(this);
1625        let mut borrow = state.lock();
1626        borrow.ime_state = ImeState::Continue;
1627        borrow.ime_text.take();
1628    }
1629}
1630
1631extern "C" fn view_did_change_effective_appearance(this: &Object, _: Sel) {
1632    unsafe {
1633        let state = get_window_state(this);
1634        let mut lock = state.as_ref().lock();
1635        if let Some(mut callback) = lock.appearance_changed_callback.take() {
1636            drop(lock);
1637            callback();
1638            state.lock().appearance_changed_callback = Some(callback);
1639        }
1640    }
1641}
1642
1643extern "C" fn accepts_first_mouse(this: &Object, _: Sel, _: id) -> BOOL {
1644    unsafe {
1645        let state = get_window_state(this);
1646        let lock = state.as_ref().lock();
1647        if lock.kind == WindowKind::PopUp {
1648            YES
1649        } else {
1650            NO
1651        }
1652    }
1653}
1654
1655extern "C" fn dragging_entered(this: &Object, _: Sel, dragging_info: id) -> NSDragOperation {
1656    let window_state = unsafe { get_window_state(this) };
1657    if send_new_event(&window_state, {
1658        let position = drag_event_position(&window_state, dragging_info);
1659        let paths = external_paths_from_event(dragging_info);
1660        PlatformInput::FileDrop(FileDropEvent::Entered { position, paths })
1661    }) {
1662        window_state.lock().external_files_dragged = true;
1663        NSDragOperationCopy
1664    } else {
1665        NSDragOperationNone
1666    }
1667}
1668
1669extern "C" fn dragging_updated(this: &Object, _: Sel, dragging_info: id) -> NSDragOperation {
1670    let window_state = unsafe { get_window_state(this) };
1671    let position = drag_event_position(&window_state, dragging_info);
1672    if send_new_event(
1673        &window_state,
1674        PlatformInput::FileDrop(FileDropEvent::Pending { position }),
1675    ) {
1676        NSDragOperationCopy
1677    } else {
1678        NSDragOperationNone
1679    }
1680}
1681
1682extern "C" fn dragging_exited(this: &Object, _: Sel, _: id) {
1683    let window_state = unsafe { get_window_state(this) };
1684    send_new_event(
1685        &window_state,
1686        PlatformInput::FileDrop(FileDropEvent::Exited),
1687    );
1688    window_state.lock().external_files_dragged = false;
1689}
1690
1691extern "C" fn perform_drag_operation(this: &Object, _: Sel, dragging_info: id) -> BOOL {
1692    let window_state = unsafe { get_window_state(this) };
1693    let position = drag_event_position(&window_state, dragging_info);
1694    if send_new_event(
1695        &window_state,
1696        PlatformInput::FileDrop(FileDropEvent::Submit { position }),
1697    ) {
1698        YES
1699    } else {
1700        NO
1701    }
1702}
1703
1704fn external_paths_from_event(dragging_info: *mut Object) -> ExternalPaths {
1705    let mut paths = SmallVec::new();
1706    let pasteboard: id = unsafe { msg_send![dragging_info, draggingPasteboard] };
1707    let filenames = unsafe { NSPasteboard::propertyListForType(pasteboard, NSFilenamesPboardType) };
1708    for file in unsafe { filenames.iter() } {
1709        let path = unsafe {
1710            let f = NSString::UTF8String(file);
1711            CStr::from_ptr(f).to_string_lossy().into_owned()
1712        };
1713        paths.push(PathBuf::from(path))
1714    }
1715    ExternalPaths(paths)
1716}
1717
1718extern "C" fn conclude_drag_operation(this: &Object, _: Sel, _: id) {
1719    let window_state = unsafe { get_window_state(this) };
1720    send_new_event(
1721        &window_state,
1722        PlatformInput::FileDrop(FileDropEvent::Exited),
1723    );
1724}
1725
1726async fn synthetic_drag(
1727    window_state: Weak<Mutex<MacWindowState>>,
1728    drag_id: usize,
1729    event: MouseMoveEvent,
1730) {
1731    loop {
1732        Timer::after(Duration::from_millis(16)).await;
1733        if let Some(window_state) = window_state.upgrade() {
1734            let mut lock = window_state.lock();
1735            if lock.synthetic_drag_counter == drag_id {
1736                if let Some(mut callback) = lock.event_callback.take() {
1737                    drop(lock);
1738                    callback(PlatformInput::MouseMove(event.clone()));
1739                    window_state.lock().event_callback = Some(callback);
1740                }
1741            } else {
1742                break;
1743            }
1744        }
1745    }
1746}
1747
1748fn send_new_event(window_state_lock: &Mutex<MacWindowState>, e: PlatformInput) -> bool {
1749    let window_state = window_state_lock.lock().event_callback.take();
1750    if let Some(mut callback) = window_state {
1751        callback(e);
1752        window_state_lock.lock().event_callback = Some(callback);
1753        true
1754    } else {
1755        false
1756    }
1757}
1758
1759fn drag_event_position(window_state: &Mutex<MacWindowState>, dragging_info: id) -> Point<Pixels> {
1760    let drag_location: NSPoint = unsafe { msg_send![dragging_info, draggingLocation] };
1761    convert_mouse_position(drag_location, window_state.lock().content_size().height)
1762}
1763
1764fn with_input_handler<F, R>(window: &Object, f: F) -> Option<R>
1765where
1766    F: FnOnce(&mut dyn PlatformInputHandler) -> R,
1767{
1768    let window_state = unsafe { get_window_state(window) };
1769    let mut lock = window_state.as_ref().lock();
1770    if let Some(mut input_handler) = lock.input_handler.take() {
1771        drop(lock);
1772        let result = f(input_handler.as_mut());
1773        window_state.lock().input_handler = Some(input_handler);
1774        Some(result)
1775    } else {
1776        None
1777    }
1778}