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, InputEvent, KeyDownEvent, Keystroke,
   5    Modifiers, ModifiersChangedEvent, MouseButton, MouseDownEvent, MouseMoveEvent, MouseUpEvent,
   6    Pixels, PlatformAtlas, PlatformDisplay, PlatformInputHandler, PlatformWindow, Point,
   7    PromptLevel, Scene, Size, Timer, WindowAppearance, WindowBounds, WindowKind, WindowOptions,
   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: ForegroundExecutor,
 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(
 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(|display_id| MacDisplay::all().find(|display| display.id() == display_id))
 488                .unwrap_or_else(|| MacDisplay::primary());
 489
 490            let mut target_screen = nil;
 491            let screens = NSScreen::screens(nil);
 492            let count: u64 = cocoa::foundation::NSArray::count(screens);
 493            for i in 0..count {
 494                let screen = cocoa::foundation::NSArray::objectAtIndex(screens, i);
 495                let device_description = NSScreen::deviceDescription(screen);
 496                let screen_number_key: id = NSString::alloc(nil).init_str("NSScreenNumber");
 497                let screen_number = device_description.objectForKey_(screen_number_key);
 498                let screen_number: NSUInteger = msg_send![screen_number, unsignedIntegerValue];
 499                if screen_number as u32 == display.id().0 {
 500                    target_screen = screen;
 501                    break;
 502                }
 503            }
 504
 505            let native_window = native_window.initWithContentRect_styleMask_backing_defer_screen_(
 506                NSRect::new(NSPoint::new(0., 0.), NSSize::new(1024., 768.)),
 507                style_mask,
 508                NSBackingStoreBuffered,
 509                NO,
 510                target_screen,
 511            );
 512            assert!(!native_window.is_null());
 513            let () = msg_send![
 514                native_window,
 515                registerForDraggedTypes:
 516                    NSArray::arrayWithObject(nil, NSFilenamesPboardType)
 517            ];
 518
 519            let screen = native_window.screen();
 520            match options.bounds {
 521                WindowBounds::Fullscreen => {
 522                    native_window.toggleFullScreen_(nil);
 523                }
 524                WindowBounds::Maximized => {
 525                    native_window.setFrame_display_(screen.visibleFrame(), YES);
 526                }
 527                WindowBounds::Fixed(bounds) => {
 528                    let display_bounds = display.bounds();
 529                    let frame = if bounds.intersects(&display_bounds) {
 530                        display_bounds_to_native(bounds)
 531                    } else {
 532                        display_bounds_to_native(display_bounds)
 533                    };
 534                    native_window.setFrame_display_(mem::transmute::<CGRect, NSRect>(frame), YES);
 535                }
 536            }
 537
 538            let native_view: id = msg_send![VIEW_CLASS, alloc];
 539            let native_view = NSView::init(native_view);
 540
 541            assert!(!native_view.is_null());
 542
 543            let window = Self(Arc::new(Mutex::new(MacWindowState {
 544                handle,
 545                executor,
 546                native_window,
 547                renderer: MetalRenderer::new(true),
 548                scene_to_render: None,
 549                kind: options.kind,
 550                event_callback: None,
 551                activate_callback: None,
 552                resize_callback: None,
 553                fullscreen_callback: None,
 554                moved_callback: None,
 555                should_close_callback: None,
 556                close_callback: None,
 557                appearance_changed_callback: None,
 558                input_handler: None,
 559                pending_key_down: None,
 560                last_key_equivalent: None,
 561                synthetic_drag_counter: 0,
 562                last_fresh_keydown: None,
 563                traffic_light_position: options
 564                    .titlebar
 565                    .as_ref()
 566                    .and_then(|titlebar| titlebar.traffic_light_position),
 567                previous_modifiers_changed_event: None,
 568                ime_state: ImeState::None,
 569                ime_text: None,
 570            })));
 571
 572            (*native_window).set_ivar(
 573                WINDOW_STATE_IVAR,
 574                Arc::into_raw(window.0.clone()) as *const c_void,
 575            );
 576            native_window.setDelegate_(native_window);
 577            (*native_view).set_ivar(
 578                WINDOW_STATE_IVAR,
 579                Arc::into_raw(window.0.clone()) as *const c_void,
 580            );
 581
 582            if let Some(title) = options
 583                .titlebar
 584                .as_ref()
 585                .and_then(|t| t.title.as_ref().map(AsRef::as_ref))
 586            {
 587                native_window.setTitle_(NSString::alloc(nil).init_str(title));
 588            }
 589
 590            native_window.setMovable_(options.is_movable as BOOL);
 591
 592            if options
 593                .titlebar
 594                .map_or(true, |titlebar| titlebar.appears_transparent)
 595            {
 596                native_window.setTitlebarAppearsTransparent_(YES);
 597                native_window.setTitleVisibility_(NSWindowTitleVisibility::NSWindowTitleHidden);
 598            }
 599
 600            native_view.setAutoresizingMask_(NSViewWidthSizable | NSViewHeightSizable);
 601            native_view.setWantsBestResolutionOpenGLSurface_(YES);
 602
 603            // From winit crate: On Mojave, views automatically become layer-backed shortly after
 604            // being added to a native_window. Changing the layer-backedness of a view breaks the
 605            // association between the view and its associated OpenGL context. To work around this,
 606            // on we explicitly make the view layer-backed up front so that AppKit doesn't do it
 607            // itself and break the association with its context.
 608            native_view.setWantsLayer(YES);
 609            let _: () = msg_send![
 610                native_view,
 611                setLayerContentsRedrawPolicy: NSViewLayerContentsRedrawDuringViewResize
 612            ];
 613
 614            native_window.setContentView_(native_view.autorelease());
 615            native_window.makeFirstResponder_(native_view);
 616
 617            if options.center {
 618                native_window.center();
 619            }
 620
 621            match options.kind {
 622                WindowKind::Normal => {
 623                    native_window.setLevel_(NSNormalWindowLevel);
 624                    native_window.setAcceptsMouseMovedEvents_(YES);
 625                }
 626                WindowKind::PopUp => {
 627                    // Use a tracking area to allow receiving MouseMoved events even when
 628                    // the window or application aren't active, which is often the case
 629                    // e.g. for notification windows.
 630                    let tracking_area: id = msg_send![class!(NSTrackingArea), alloc];
 631                    let _: () = msg_send![
 632                        tracking_area,
 633                        initWithRect: NSRect::new(NSPoint::new(0., 0.), NSSize::new(0., 0.))
 634                        options: NSTrackingMouseEnteredAndExited | NSTrackingMouseMoved | NSTrackingActiveAlways | NSTrackingInVisibleRect
 635                        owner: native_view
 636                        userInfo: nil
 637                    ];
 638                    let _: () =
 639                        msg_send![native_view, addTrackingArea: tracking_area.autorelease()];
 640
 641                    native_window.setLevel_(NSPopUpWindowLevel);
 642                    let _: () = msg_send![
 643                        native_window,
 644                        setAnimationBehavior: NSWindowAnimationBehaviorUtilityWindow
 645                    ];
 646                    native_window.setCollectionBehavior_(
 647                        NSWindowCollectionBehavior::NSWindowCollectionBehaviorCanJoinAllSpaces |
 648                        NSWindowCollectionBehavior::NSWindowCollectionBehaviorFullScreenAuxiliary
 649                    );
 650                }
 651            }
 652            if options.focus {
 653                native_window.makeKeyAndOrderFront_(nil);
 654            } else if options.show {
 655                native_window.orderFront_(nil);
 656            }
 657
 658            window.0.lock().move_traffic_light();
 659            pool.drain();
 660
 661            window
 662        }
 663    }
 664
 665    pub fn main_window() -> Option<AnyWindowHandle> {
 666        unsafe {
 667            let app = NSApplication::sharedApplication(nil);
 668            let main_window: id = msg_send![app, mainWindow];
 669            if msg_send![main_window, isKindOfClass: WINDOW_CLASS] {
 670                let handle = get_window_state(&*main_window).lock().handle;
 671                Some(handle)
 672            } else {
 673                None
 674            }
 675        }
 676    }
 677}
 678
 679impl Drop for MacWindow {
 680    fn drop(&mut self) {
 681        let this = self.0.lock();
 682        let window = this.native_window;
 683        this.executor
 684            .spawn(async move {
 685                unsafe {
 686                    window.close();
 687                }
 688            })
 689            .detach();
 690    }
 691}
 692
 693impl PlatformWindow for MacWindow {
 694    fn bounds(&self) -> WindowBounds {
 695        self.0.as_ref().lock().bounds()
 696    }
 697
 698    fn content_size(&self) -> Size<Pixels> {
 699        self.0.as_ref().lock().content_size().into()
 700    }
 701
 702    fn scale_factor(&self) -> f32 {
 703        self.0.as_ref().lock().scale_factor()
 704    }
 705
 706    fn titlebar_height(&self) -> Pixels {
 707        self.0.as_ref().lock().titlebar_height()
 708    }
 709
 710    fn appearance(&self) -> WindowAppearance {
 711        unsafe {
 712            let appearance: id = msg_send![self.0.lock().native_window, effectiveAppearance];
 713            WindowAppearance::from_native(appearance)
 714        }
 715    }
 716
 717    fn display(&self) -> Rc<dyn PlatformDisplay> {
 718        unsafe {
 719            let screen = self.0.lock().native_window.screen();
 720            let device_description: id = msg_send![screen, deviceDescription];
 721            let screen_number: id = NSDictionary::valueForKey_(
 722                device_description,
 723                NSString::alloc(nil).init_str("NSScreenNumber"),
 724            );
 725
 726            let screen_number: u32 = msg_send![screen_number, unsignedIntValue];
 727
 728            Rc::new(MacDisplay(screen_number))
 729        }
 730    }
 731
 732    fn mouse_position(&self) -> Point<Pixels> {
 733        let position = unsafe {
 734            self.0
 735                .lock()
 736                .native_window
 737                .mouseLocationOutsideOfEventStream()
 738        };
 739        convert_mouse_position(position, self.content_size().height)
 740    }
 741
 742    fn as_any_mut(&mut self) -> &mut dyn Any {
 743        self
 744    }
 745
 746    fn set_input_handler(&mut self, input_handler: Box<dyn PlatformInputHandler>) {
 747        self.0.as_ref().lock().input_handler = Some(input_handler);
 748    }
 749
 750    fn prompt(&self, level: PromptLevel, msg: &str, answers: &[&str]) -> oneshot::Receiver<usize> {
 751        // macOs applies overrides to modal window buttons after they are added.
 752        // Two most important for this logic are:
 753        // * Buttons with "Cancel" title will be displayed as the last buttons in the modal
 754        // * Last button added to the modal via `addButtonWithTitle` stays focused
 755        // * Focused buttons react on "space"/" " keypresses
 756        // * Usage of `keyEquivalent`, `makeFirstResponder` or `setInitialFirstResponder` does not change the focus
 757        //
 758        // See also https://developer.apple.com/documentation/appkit/nsalert/1524532-addbuttonwithtitle#discussion
 759        // ```
 760        // By default, the first button has a key equivalent of Return,
 761        // any button with a title of “Cancel” has a key equivalent of Escape,
 762        // 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).
 763        // ```
 764        //
 765        // To avoid situations when the last element added is "Cancel" and it gets the focus
 766        // (hence stealing both ESC and Space shortcuts), we find and add one non-Cancel button
 767        // last, so it gets focus and a Space shortcut.
 768        // This way, "Save this file? Yes/No/Cancel"-ish modals will get all three buttons mapped with a key.
 769        let latest_non_cancel_label = answers
 770            .iter()
 771            .enumerate()
 772            .rev()
 773            .find(|(_, &label)| label != "Cancel")
 774            .filter(|&(label_index, _)| label_index > 0);
 775
 776        unsafe {
 777            let alert: id = msg_send![class!(NSAlert), alloc];
 778            let alert: id = msg_send![alert, init];
 779            let alert_style = match level {
 780                PromptLevel::Info => 1,
 781                PromptLevel::Warning => 0,
 782                PromptLevel::Critical => 2,
 783            };
 784            let _: () = msg_send![alert, setAlertStyle: alert_style];
 785            let _: () = msg_send![alert, setMessageText: ns_string(msg)];
 786
 787            for (ix, answer) in answers
 788                .iter()
 789                .enumerate()
 790                .filter(|&(ix, _)| Some(ix) != latest_non_cancel_label.map(|(ix, _)| ix))
 791            {
 792                let button: id = msg_send![alert, addButtonWithTitle: ns_string(answer)];
 793                let _: () = msg_send![button, setTag: ix as NSInteger];
 794            }
 795            if let Some((ix, answer)) = latest_non_cancel_label {
 796                let button: id = msg_send![alert, addButtonWithTitle: ns_string(answer)];
 797                let _: () = msg_send![button, setTag: ix as NSInteger];
 798            }
 799
 800            let (done_tx, done_rx) = oneshot::channel();
 801            let done_tx = Cell::new(Some(done_tx));
 802            let block = ConcreteBlock::new(move |answer: NSInteger| {
 803                if let Some(done_tx) = done_tx.take() {
 804                    let _ = done_tx.send(answer.try_into().unwrap());
 805                }
 806            });
 807            let block = block.copy();
 808            let native_window = self.0.lock().native_window;
 809            let executor = self.0.lock().executor.clone();
 810            executor
 811                .spawn(async move {
 812                    let _: () = msg_send![
 813                        alert,
 814                        beginSheetModalForWindow: native_window
 815                        completionHandler: block
 816                    ];
 817                })
 818                .detach();
 819
 820            done_rx
 821        }
 822    }
 823
 824    fn activate(&self) {
 825        let window = self.0.lock().native_window;
 826        let executor = self.0.lock().executor.clone();
 827        executor
 828            .spawn(async move {
 829                unsafe {
 830                    let _: () = msg_send![window, makeKeyAndOrderFront: nil];
 831                }
 832            })
 833            .detach();
 834    }
 835
 836    fn set_title(&mut self, title: &str) {
 837        unsafe {
 838            let app = NSApplication::sharedApplication(nil);
 839            let window = self.0.lock().native_window;
 840            let title = ns_string(title);
 841            let _: () = msg_send![app, changeWindowsItem:window title:title filename:false];
 842            let _: () = msg_send![window, setTitle: title];
 843            self.0.lock().move_traffic_light();
 844        }
 845    }
 846
 847    fn set_edited(&mut self, edited: bool) {
 848        unsafe {
 849            let window = self.0.lock().native_window;
 850            msg_send![window, setDocumentEdited: edited as BOOL]
 851        }
 852
 853        // Changing the document edited state resets the traffic light position,
 854        // so we have to move it again.
 855        self.0.lock().move_traffic_light();
 856    }
 857
 858    fn show_character_palette(&self) {
 859        unsafe {
 860            let app = NSApplication::sharedApplication(nil);
 861            let window = self.0.lock().native_window;
 862            let _: () = msg_send![app, orderFrontCharacterPalette: window];
 863        }
 864    }
 865
 866    fn minimize(&self) {
 867        let window = self.0.lock().native_window;
 868        unsafe {
 869            window.miniaturize_(nil);
 870        }
 871    }
 872
 873    fn zoom(&self) {
 874        let this = self.0.lock();
 875        let window = this.native_window;
 876        this.executor
 877            .spawn(async move {
 878                unsafe {
 879                    window.zoom_(nil);
 880                }
 881            })
 882            .detach();
 883    }
 884
 885    fn toggle_full_screen(&self) {
 886        let this = self.0.lock();
 887        let window = this.native_window;
 888        this.executor
 889            .spawn(async move {
 890                unsafe {
 891                    window.toggleFullScreen_(nil);
 892                }
 893            })
 894            .detach();
 895    }
 896
 897    fn on_input(&self, callback: Box<dyn FnMut(InputEvent) -> bool>) {
 898        self.0.as_ref().lock().event_callback = Some(callback);
 899    }
 900
 901    fn on_active_status_change(&self, callback: Box<dyn FnMut(bool)>) {
 902        self.0.as_ref().lock().activate_callback = Some(callback);
 903    }
 904
 905    fn on_resize(&self, callback: Box<dyn FnMut(Size<Pixels>, f32)>) {
 906        self.0.as_ref().lock().resize_callback = Some(callback);
 907    }
 908
 909    fn on_fullscreen(&self, callback: Box<dyn FnMut(bool)>) {
 910        self.0.as_ref().lock().fullscreen_callback = Some(callback);
 911    }
 912
 913    fn on_moved(&self, callback: Box<dyn FnMut()>) {
 914        self.0.as_ref().lock().moved_callback = Some(callback);
 915    }
 916
 917    fn on_should_close(&self, callback: Box<dyn FnMut() -> bool>) {
 918        self.0.as_ref().lock().should_close_callback = Some(callback);
 919    }
 920
 921    fn on_close(&self, callback: Box<dyn FnOnce()>) {
 922        self.0.as_ref().lock().close_callback = Some(callback);
 923    }
 924
 925    fn on_appearance_changed(&self, callback: Box<dyn FnMut()>) {
 926        self.0.lock().appearance_changed_callback = Some(callback);
 927    }
 928
 929    fn is_topmost_for_position(&self, position: Point<Pixels>) -> bool {
 930        let self_borrow = self.0.lock();
 931        let self_handle = self_borrow.handle;
 932
 933        unsafe {
 934            let app = NSApplication::sharedApplication(nil);
 935
 936            // Convert back to screen coordinates
 937            let screen_point = self_borrow.to_screen_ns_point(position);
 938
 939            let window_number: NSInteger = msg_send![class!(NSWindow), windowNumberAtPoint:screen_point belowWindowWithWindowNumber:0];
 940            let top_most_window: id = msg_send![app, windowWithWindowNumber: window_number];
 941
 942            let is_panel: BOOL = msg_send![top_most_window, isKindOfClass: PANEL_CLASS];
 943            let is_window: BOOL = msg_send![top_most_window, isKindOfClass: WINDOW_CLASS];
 944            if is_panel == YES || is_window == YES {
 945                let topmost_window = get_window_state(&*top_most_window).lock().handle;
 946                topmost_window == self_handle
 947            } else {
 948                // Someone else's window is on top
 949                false
 950            }
 951        }
 952    }
 953
 954    fn draw(&self, scene: Scene) {
 955        let mut this = self.0.lock();
 956        this.scene_to_render = Some(scene);
 957        unsafe {
 958            let _: () = msg_send![this.native_window.contentView(), setNeedsDisplay: YES];
 959        }
 960    }
 961
 962    fn sprite_atlas(&self) -> Arc<dyn PlatformAtlas> {
 963        self.0.lock().renderer.sprite_atlas().clone()
 964    }
 965}
 966
 967fn get_scale_factor(native_window: id) -> f32 {
 968    unsafe {
 969        let screen: id = msg_send![native_window, screen];
 970        NSScreen::backingScaleFactor(screen) as f32
 971    }
 972}
 973
 974unsafe fn get_window_state(object: &Object) -> Arc<Mutex<MacWindowState>> {
 975    let raw: *mut c_void = *object.get_ivar(WINDOW_STATE_IVAR);
 976    let rc1 = Arc::from_raw(raw as *mut Mutex<MacWindowState>);
 977    let rc2 = rc1.clone();
 978    mem::forget(rc1);
 979    rc2
 980}
 981
 982unsafe fn drop_window_state(object: &Object) {
 983    let raw: *mut c_void = *object.get_ivar(WINDOW_STATE_IVAR);
 984    Rc::from_raw(raw as *mut RefCell<MacWindowState>);
 985}
 986
 987extern "C" fn yes(_: &Object, _: Sel) -> BOOL {
 988    YES
 989}
 990
 991extern "C" fn dealloc_window(this: &Object, _: Sel) {
 992    unsafe {
 993        drop_window_state(this);
 994        let _: () = msg_send![super(this, class!(NSWindow)), dealloc];
 995    }
 996}
 997
 998extern "C" fn dealloc_view(this: &Object, _: Sel) {
 999    unsafe {
1000        drop_window_state(this);
1001        let _: () = msg_send![super(this, class!(NSView)), dealloc];
1002    }
1003}
1004
1005extern "C" fn handle_key_equivalent(this: &Object, _: Sel, native_event: id) -> BOOL {
1006    handle_key_event(this, native_event, true)
1007}
1008
1009extern "C" fn handle_key_down(this: &Object, _: Sel, native_event: id) {
1010    handle_key_event(this, native_event, false);
1011}
1012
1013extern "C" fn handle_key_event(this: &Object, native_event: id, key_equivalent: bool) -> BOOL {
1014    let window_state = unsafe { get_window_state(this) };
1015    let mut lock = window_state.as_ref().lock();
1016
1017    let window_height = lock.content_size().height;
1018    let event = unsafe { InputEvent::from_native(native_event, Some(window_height)) };
1019
1020    if let Some(InputEvent::KeyDown(event)) = event {
1021        // For certain keystrokes, macOS will first dispatch a "key equivalent" event.
1022        // If that event isn't handled, it will then dispatch a "key down" event. GPUI
1023        // makes no distinction between these two types of events, so we need to ignore
1024        // the "key down" event if we've already just processed its "key equivalent" version.
1025        if key_equivalent {
1026            lock.last_key_equivalent = Some(event.clone());
1027        } else if lock.last_key_equivalent.take().as_ref() == Some(&event) {
1028            return NO;
1029        }
1030
1031        let keydown = event.keystroke.clone();
1032        let fn_modifier = keydown.modifiers.function;
1033        // Ignore events from held-down keys after some of the initially-pressed keys
1034        // were released.
1035        if event.is_held {
1036            if lock.last_fresh_keydown.as_ref() != Some(&keydown) {
1037                return YES;
1038            }
1039        } else {
1040            lock.last_fresh_keydown = Some(keydown);
1041        }
1042        lock.pending_key_down = Some((event, None));
1043        drop(lock);
1044
1045        // Send the event to the input context for IME handling, unless the `fn` modifier is
1046        // being pressed.
1047        if !fn_modifier {
1048            unsafe {
1049                let input_context: id = msg_send![this, inputContext];
1050                let _: BOOL = msg_send![input_context, handleEvent: native_event];
1051            }
1052        }
1053
1054        let mut handled = false;
1055        let mut lock = window_state.lock();
1056        let ime_text = lock.ime_text.clone();
1057        if let Some((event, insert_text)) = lock.pending_key_down.take() {
1058            let is_held = event.is_held;
1059            if let Some(mut callback) = lock.event_callback.take() {
1060                drop(lock);
1061
1062                let is_composing =
1063                    with_input_handler(this, |input_handler| input_handler.marked_text_range())
1064                        .flatten()
1065                        .is_some();
1066                if !is_composing {
1067                    // if the IME has changed the key, we'll first emit an event with the character
1068                    // generated by the IME system; then fallback to the keystroke if that is not
1069                    // handled.
1070                    // cases that we have working:
1071                    // - " on a brazillian layout by typing <quote><space>
1072                    // - ctrl-` on a brazillian layout by typing <ctrl-`>
1073                    // - $ on a czech QWERTY layout by typing <alt-4>
1074                    // - 4 on a czech QWERTY layout by typing <shift-4>
1075                    // - ctrl-4 on a czech QWERTY layout by typing <ctrl-alt-4> (or <ctrl-shift-4>)
1076                    if ime_text.is_some() && ime_text.as_ref() != Some(&event.keystroke.key) {
1077                        let event_with_ime_text = KeyDownEvent {
1078                            is_held: false,
1079                            keystroke: Keystroke {
1080                                // we match ctrl because some use-cases need it.
1081                                // we don't match alt because it's often used to generate the optional character
1082                                // we don't match shift because we're not here with letters (usually)
1083                                // we don't match cmd/fn because they don't seem to use IME
1084                                modifiers: Default::default(),
1085                                key: ime_text.clone().unwrap(),
1086                                ime_key: None, // todo!("handle IME key")
1087                            },
1088                        };
1089                        handled = callback(InputEvent::KeyDown(event_with_ime_text));
1090                    }
1091                    if !handled {
1092                        // empty key happens when you type a deadkey in input composition.
1093                        // (e.g. on a brazillian keyboard typing quote is a deadkey)
1094                        if !event.keystroke.key.is_empty() {
1095                            handled = callback(InputEvent::KeyDown(event));
1096                        }
1097                    }
1098                }
1099
1100                if !handled {
1101                    if let Some(insert) = insert_text {
1102                        handled = true;
1103                        with_input_handler(this, |input_handler| {
1104                            input_handler
1105                                .replace_text_in_range(insert.replacement_range, &insert.text)
1106                        });
1107                    } else if !is_composing && is_held {
1108                        if let Some(last_insert_text) = ime_text {
1109                            //MacOS IME is a bit funky, and even when you've told it there's nothing to
1110                            //inter it will still swallow certain keys (e.g. 'f', 'j') and not others
1111                            //(e.g. 'n'). This is a problem for certain kinds of views, like the terminal
1112                            with_input_handler(this, |input_handler| {
1113                                if input_handler.selected_text_range().is_none() {
1114                                    handled = true;
1115                                    input_handler.replace_text_in_range(None, &last_insert_text)
1116                                }
1117                            });
1118                        }
1119                    }
1120                }
1121
1122                window_state.lock().event_callback = Some(callback);
1123            }
1124        } else {
1125            handled = true;
1126        }
1127
1128        handled as BOOL
1129    } else {
1130        NO
1131    }
1132}
1133
1134extern "C" fn handle_view_event(this: &Object, _: Sel, native_event: id) {
1135    let window_state = unsafe { get_window_state(this) };
1136    let weak_window_state = Arc::downgrade(&window_state);
1137    let mut lock = window_state.as_ref().lock();
1138    let is_active = unsafe { lock.native_window.isKeyWindow() == YES };
1139
1140    let window_height = lock.content_size().height;
1141    let event = unsafe { InputEvent::from_native(native_event, Some(window_height)) };
1142
1143    if let Some(mut event) = event {
1144        let synthesized_second_event = match &mut event {
1145            InputEvent::MouseDown(
1146                event @ MouseDownEvent {
1147                    button: MouseButton::Left,
1148                    modifiers: Modifiers { control: true, .. },
1149                    ..
1150                },
1151            ) => {
1152                *event = MouseDownEvent {
1153                    button: MouseButton::Right,
1154                    modifiers: Modifiers {
1155                        control: false,
1156                        ..event.modifiers
1157                    },
1158                    click_count: 1,
1159                    ..*event
1160                };
1161
1162                Some(InputEvent::MouseDown(MouseDownEvent {
1163                    button: MouseButton::Right,
1164                    ..*event
1165                }))
1166            }
1167
1168            // Because we map a ctrl-left_down to a right_down -> right_up let's ignore
1169            // the ctrl-left_up to avoid having a mismatch in button down/up events if the
1170            // user is still holding ctrl when releasing the left mouse button
1171            InputEvent::MouseUp(MouseUpEvent {
1172                button: MouseButton::Left,
1173                modifiers: Modifiers { control: true, .. },
1174                ..
1175            }) => {
1176                lock.synthetic_drag_counter += 1;
1177                return;
1178            }
1179
1180            _ => None,
1181        };
1182
1183        match &event {
1184            InputEvent::MouseMove(
1185                event @ MouseMoveEvent {
1186                    pressed_button: Some(_),
1187                    ..
1188                },
1189            ) => {
1190                lock.synthetic_drag_counter += 1;
1191                let executor = lock.executor.clone();
1192                executor
1193                    .spawn(synthetic_drag(
1194                        weak_window_state,
1195                        lock.synthetic_drag_counter,
1196                        event.clone(),
1197                    ))
1198                    .detach();
1199            }
1200
1201            InputEvent::MouseMove(_) if !(is_active || lock.kind == WindowKind::PopUp) => return,
1202
1203            InputEvent::MouseUp(MouseUpEvent {
1204                button: MouseButton::Left,
1205                ..
1206            }) => {
1207                lock.synthetic_drag_counter += 1;
1208            }
1209
1210            InputEvent::ModifiersChanged(ModifiersChangedEvent { modifiers }) => {
1211                // Only raise modifiers changed event when they have actually changed
1212                if let Some(InputEvent::ModifiersChanged(ModifiersChangedEvent {
1213                    modifiers: prev_modifiers,
1214                })) = &lock.previous_modifiers_changed_event
1215                {
1216                    if prev_modifiers == modifiers {
1217                        return;
1218                    }
1219                }
1220
1221                lock.previous_modifiers_changed_event = Some(event.clone());
1222            }
1223
1224            _ => {}
1225        }
1226
1227        if let Some(mut callback) = lock.event_callback.take() {
1228            drop(lock);
1229            callback(event);
1230            if let Some(event) = synthesized_second_event {
1231                callback(event);
1232            }
1233            window_state.lock().event_callback = Some(callback);
1234        }
1235    }
1236}
1237
1238// Allows us to receive `cmd-.` (the shortcut for closing a dialog)
1239// https://bugs.eclipse.org/bugs/show_bug.cgi?id=300620#c6
1240extern "C" fn cancel_operation(this: &Object, _sel: Sel, _sender: id) {
1241    let window_state = unsafe { get_window_state(this) };
1242    let mut lock = window_state.as_ref().lock();
1243
1244    let keystroke = Keystroke {
1245        modifiers: Default::default(),
1246        key: ".".into(),
1247        ime_key: None,
1248    };
1249    let event = InputEvent::KeyDown(KeyDownEvent {
1250        keystroke: keystroke.clone(),
1251        is_held: false,
1252    });
1253
1254    lock.last_fresh_keydown = Some(keystroke);
1255    if let Some(mut callback) = lock.event_callback.take() {
1256        drop(lock);
1257        callback(event);
1258        window_state.lock().event_callback = Some(callback);
1259    }
1260}
1261
1262extern "C" fn window_did_resize(this: &Object, _: Sel, _: id) {
1263    let window_state = unsafe { get_window_state(this) };
1264    window_state.as_ref().lock().move_traffic_light();
1265}
1266
1267extern "C" fn window_will_enter_fullscreen(this: &Object, _: Sel, _: id) {
1268    window_fullscreen_changed(this, true);
1269}
1270
1271extern "C" fn window_will_exit_fullscreen(this: &Object, _: Sel, _: id) {
1272    window_fullscreen_changed(this, false);
1273}
1274
1275fn window_fullscreen_changed(this: &Object, is_fullscreen: bool) {
1276    let window_state = unsafe { get_window_state(this) };
1277    let mut lock = window_state.as_ref().lock();
1278    if let Some(mut callback) = lock.fullscreen_callback.take() {
1279        drop(lock);
1280        callback(is_fullscreen);
1281        window_state.lock().fullscreen_callback = Some(callback);
1282    }
1283}
1284
1285extern "C" fn window_did_move(this: &Object, _: Sel, _: id) {
1286    let window_state = unsafe { get_window_state(this) };
1287    let mut lock = window_state.as_ref().lock();
1288    if let Some(mut callback) = lock.moved_callback.take() {
1289        drop(lock);
1290        callback();
1291        window_state.lock().moved_callback = Some(callback);
1292    }
1293}
1294
1295extern "C" fn window_did_change_key_status(this: &Object, selector: Sel, _: id) {
1296    let window_state = unsafe { get_window_state(this) };
1297    let lock = window_state.lock();
1298    let is_active = unsafe { lock.native_window.isKeyWindow() == YES };
1299
1300    // When opening a pop-up while the application isn't active, Cocoa sends a spurious
1301    // `windowDidBecomeKey` message to the previous key window even though that window
1302    // isn't actually key. This causes a bug if the application is later activated while
1303    // the pop-up is still open, making it impossible to activate the previous key window
1304    // even if the pop-up gets closed. The only way to activate it again is to de-activate
1305    // the app and re-activate it, which is a pretty bad UX.
1306    // The following code detects the spurious event and invokes `resignKeyWindow`:
1307    // in theory, we're not supposed to invoke this method manually but it balances out
1308    // the spurious `becomeKeyWindow` event and helps us work around that bug.
1309    if selector == sel!(windowDidBecomeKey:) {
1310        if !is_active {
1311            unsafe {
1312                let _: () = msg_send![lock.native_window, resignKeyWindow];
1313                return;
1314            }
1315        }
1316    }
1317
1318    let executor = lock.executor.clone();
1319    drop(lock);
1320    executor
1321        .spawn(async move {
1322            let mut lock = window_state.as_ref().lock();
1323            if let Some(mut callback) = lock.activate_callback.take() {
1324                drop(lock);
1325                callback(is_active);
1326                window_state.lock().activate_callback = Some(callback);
1327            };
1328        })
1329        .detach();
1330}
1331
1332extern "C" fn window_should_close(this: &Object, _: Sel, _: id) -> BOOL {
1333    let window_state = unsafe { get_window_state(this) };
1334    let mut lock = window_state.as_ref().lock();
1335    if let Some(mut callback) = lock.should_close_callback.take() {
1336        drop(lock);
1337        let should_close = callback();
1338        window_state.lock().should_close_callback = Some(callback);
1339        should_close as BOOL
1340    } else {
1341        YES
1342    }
1343}
1344
1345extern "C" fn close_window(this: &Object, _: Sel) {
1346    unsafe {
1347        let close_callback = {
1348            let window_state = get_window_state(this);
1349            window_state
1350                .as_ref()
1351                .try_lock()
1352                .and_then(|mut window_state| window_state.close_callback.take())
1353        };
1354
1355        if let Some(callback) = close_callback {
1356            callback();
1357        }
1358
1359        let _: () = msg_send![super(this, class!(NSWindow)), close];
1360    }
1361}
1362
1363extern "C" fn make_backing_layer(this: &Object, _: Sel) -> id {
1364    let window_state = unsafe { get_window_state(this) };
1365    let window_state = window_state.as_ref().lock();
1366    window_state.renderer.layer().as_ptr() as id
1367}
1368
1369extern "C" fn view_did_change_backing_properties(this: &Object, _: Sel) {
1370    let window_state = unsafe { get_window_state(this) };
1371    let mut lock = window_state.as_ref().lock();
1372
1373    unsafe {
1374        let scale_factor = lock.scale_factor() as f64;
1375        let size = lock.content_size();
1376        let drawable_size: NSSize = NSSize {
1377            width: f64::from(size.width) * scale_factor,
1378            height: f64::from(size.height) * scale_factor,
1379        };
1380
1381        let _: () = msg_send![
1382            lock.renderer.layer(),
1383            setContentsScale: scale_factor
1384        ];
1385        let _: () = msg_send![
1386            lock.renderer.layer(),
1387            setDrawableSize: drawable_size
1388        ];
1389    }
1390
1391    if let Some(mut callback) = lock.resize_callback.take() {
1392        let content_size = lock.content_size();
1393        let scale_factor = lock.scale_factor();
1394        drop(lock);
1395        callback(content_size, scale_factor);
1396        window_state.as_ref().lock().resize_callback = Some(callback);
1397    };
1398}
1399
1400extern "C" fn set_frame_size(this: &Object, _: Sel, size: NSSize) {
1401    let window_state = unsafe { get_window_state(this) };
1402    let lock = window_state.as_ref().lock();
1403
1404    if lock.content_size() == size.into() {
1405        return;
1406    }
1407
1408    unsafe {
1409        let _: () = msg_send![super(this, class!(NSView)), setFrameSize: size];
1410    }
1411
1412    let scale_factor = lock.scale_factor() as f64;
1413    let drawable_size: NSSize = NSSize {
1414        width: size.width * scale_factor,
1415        height: size.height * scale_factor,
1416    };
1417
1418    unsafe {
1419        let _: () = msg_send![
1420            lock.renderer.layer(),
1421            setDrawableSize: drawable_size
1422        ];
1423    }
1424
1425    drop(lock);
1426    let mut lock = window_state.lock();
1427    if let Some(mut callback) = lock.resize_callback.take() {
1428        let content_size = lock.content_size();
1429        let scale_factor = lock.scale_factor();
1430        drop(lock);
1431        callback(content_size, scale_factor);
1432        window_state.lock().resize_callback = Some(callback);
1433    };
1434}
1435
1436extern "C" fn display_layer(this: &Object, _: Sel, _: id) {
1437    unsafe {
1438        let window_state = get_window_state(this);
1439        let mut window_state = window_state.as_ref().lock();
1440        if let Some(scene) = window_state.scene_to_render.take() {
1441            window_state.renderer.draw(&scene);
1442        }
1443    }
1444}
1445
1446extern "C" fn valid_attributes_for_marked_text(_: &Object, _: Sel) -> id {
1447    unsafe { msg_send![class!(NSArray), array] }
1448}
1449
1450extern "C" fn has_marked_text(this: &Object, _: Sel) -> BOOL {
1451    with_input_handler(this, |input_handler| input_handler.marked_text_range())
1452        .flatten()
1453        .is_some() as BOOL
1454}
1455
1456extern "C" fn marked_range(this: &Object, _: Sel) -> NSRange {
1457    with_input_handler(this, |input_handler| input_handler.marked_text_range())
1458        .flatten()
1459        .map_or(NSRange::invalid(), |range| range.into())
1460}
1461
1462extern "C" fn selected_range(this: &Object, _: Sel) -> NSRange {
1463    with_input_handler(this, |input_handler| input_handler.selected_text_range())
1464        .flatten()
1465        .map_or(NSRange::invalid(), |range| range.into())
1466}
1467
1468extern "C" fn first_rect_for_character_range(
1469    this: &Object,
1470    _: Sel,
1471    range: NSRange,
1472    _: id,
1473) -> NSRect {
1474    let frame = unsafe {
1475        let window = get_window_state(this).lock().native_window;
1476        NSView::frame(window)
1477    };
1478    with_input_handler(this, |input_handler| {
1479        input_handler.bounds_for_range(range.to_range()?)
1480    })
1481    .flatten()
1482    .map_or(
1483        NSRect::new(NSPoint::new(0., 0.), NSSize::new(0., 0.)),
1484        |bounds| {
1485            NSRect::new(
1486                NSPoint::new(
1487                    frame.origin.x + bounds.origin.x as f64,
1488                    frame.origin.y + frame.size.height - bounds.origin.y as f64,
1489                ),
1490                NSSize::new(bounds.size.width as f64, bounds.size.height as f64),
1491            )
1492        },
1493    )
1494}
1495
1496extern "C" fn insert_text(this: &Object, _: Sel, text: id, replacement_range: NSRange) {
1497    unsafe {
1498        let window_state = get_window_state(this);
1499        let mut lock = window_state.lock();
1500        let pending_key_down = lock.pending_key_down.take();
1501        drop(lock);
1502
1503        let is_attributed_string: BOOL =
1504            msg_send![text, isKindOfClass: [class!(NSAttributedString)]];
1505        let text: id = if is_attributed_string == YES {
1506            msg_send![text, string]
1507        } else {
1508            text
1509        };
1510        let text = CStr::from_ptr(text.UTF8String() as *mut c_char)
1511            .to_str()
1512            .unwrap();
1513        let replacement_range = replacement_range.to_range();
1514
1515        window_state.lock().ime_text = Some(text.to_string());
1516        window_state.lock().ime_state = ImeState::Acted;
1517
1518        let is_composing =
1519            with_input_handler(this, |input_handler| input_handler.marked_text_range())
1520                .flatten()
1521                .is_some();
1522
1523        if is_composing || text.chars().count() > 1 || pending_key_down.is_none() {
1524            with_input_handler(this, |input_handler| {
1525                input_handler.replace_text_in_range(replacement_range, text)
1526            });
1527        } else {
1528            let mut pending_key_down = pending_key_down.unwrap();
1529            pending_key_down.1 = Some(InsertText {
1530                replacement_range,
1531                text: text.to_string(),
1532            });
1533            window_state.lock().pending_key_down = Some(pending_key_down);
1534        }
1535    }
1536}
1537
1538extern "C" fn set_marked_text(
1539    this: &Object,
1540    _: Sel,
1541    text: id,
1542    selected_range: NSRange,
1543    replacement_range: NSRange,
1544) {
1545    unsafe {
1546        let window_state = get_window_state(this);
1547        window_state.lock().pending_key_down.take();
1548
1549        let is_attributed_string: BOOL =
1550            msg_send![text, isKindOfClass: [class!(NSAttributedString)]];
1551        let text: id = if is_attributed_string == YES {
1552            msg_send![text, string]
1553        } else {
1554            text
1555        };
1556        let selected_range = selected_range.to_range();
1557        let replacement_range = replacement_range.to_range();
1558        let text = CStr::from_ptr(text.UTF8String() as *mut c_char)
1559            .to_str()
1560            .unwrap();
1561
1562        window_state.lock().ime_state = ImeState::Acted;
1563        window_state.lock().ime_text = Some(text.to_string());
1564
1565        with_input_handler(this, |input_handler| {
1566            input_handler.replace_and_mark_text_in_range(replacement_range, text, selected_range);
1567        });
1568    }
1569}
1570
1571extern "C" fn unmark_text(this: &Object, _: Sel) {
1572    unsafe {
1573        let state = get_window_state(this);
1574        let mut borrow = state.lock();
1575        borrow.ime_state = ImeState::Acted;
1576        borrow.ime_text.take();
1577    }
1578
1579    with_input_handler(this, |input_handler| input_handler.unmark_text());
1580}
1581
1582extern "C" fn attributed_substring_for_proposed_range(
1583    this: &Object,
1584    _: Sel,
1585    range: NSRange,
1586    _actual_range: *mut c_void,
1587) -> id {
1588    with_input_handler(this, |input_handler| {
1589        let range = range.to_range()?;
1590        if range.is_empty() {
1591            return None;
1592        }
1593
1594        let selected_text = input_handler.text_for_range(range)?;
1595        unsafe {
1596            let string: id = msg_send![class!(NSAttributedString), alloc];
1597            let string: id = msg_send![string, initWithString: ns_string(&selected_text)];
1598            Some(string)
1599        }
1600    })
1601    .flatten()
1602    .unwrap_or(nil)
1603}
1604
1605extern "C" fn do_command_by_selector(this: &Object, _: Sel, _: Sel) {
1606    unsafe {
1607        let state = get_window_state(this);
1608        let mut borrow = state.lock();
1609        borrow.ime_state = ImeState::Continue;
1610        borrow.ime_text.take();
1611    }
1612}
1613
1614extern "C" fn view_did_change_effective_appearance(this: &Object, _: Sel) {
1615    unsafe {
1616        let state = get_window_state(this);
1617        let mut lock = state.as_ref().lock();
1618        if let Some(mut callback) = lock.appearance_changed_callback.take() {
1619            drop(lock);
1620            callback();
1621            state.lock().appearance_changed_callback = Some(callback);
1622        }
1623    }
1624}
1625
1626extern "C" fn accepts_first_mouse(this: &Object, _: Sel, _: id) -> BOOL {
1627    unsafe {
1628        let state = get_window_state(this);
1629        let lock = state.as_ref().lock();
1630        return if lock.kind == WindowKind::PopUp {
1631            YES
1632        } else {
1633            NO
1634        };
1635    }
1636}
1637
1638extern "C" fn dragging_entered(this: &Object, _: Sel, dragging_info: id) -> NSDragOperation {
1639    let window_state = unsafe { get_window_state(this) };
1640    if send_new_event(&window_state, {
1641        let position = drag_event_position(&window_state, dragging_info);
1642        let paths = external_paths_from_event(dragging_info);
1643        InputEvent::FileDrop(FileDropEvent::Entered {
1644            position,
1645            files: paths,
1646        })
1647    }) {
1648        NSDragOperationCopy
1649    } else {
1650        NSDragOperationNone
1651    }
1652}
1653
1654extern "C" fn dragging_updated(this: &Object, _: Sel, dragging_info: id) -> NSDragOperation {
1655    let window_state = unsafe { get_window_state(this) };
1656    let position = drag_event_position(&window_state, dragging_info);
1657    if send_new_event(
1658        &window_state,
1659        InputEvent::FileDrop(FileDropEvent::Pending { position }),
1660    ) {
1661        NSDragOperationCopy
1662    } else {
1663        NSDragOperationNone
1664    }
1665}
1666
1667extern "C" fn dragging_exited(this: &Object, _: Sel, _: id) {
1668    let window_state = unsafe { get_window_state(this) };
1669    send_new_event(&window_state, InputEvent::FileDrop(FileDropEvent::Exited));
1670}
1671
1672extern "C" fn perform_drag_operation(this: &Object, _: Sel, dragging_info: id) -> BOOL {
1673    let window_state = unsafe { get_window_state(this) };
1674    let position = drag_event_position(&window_state, dragging_info);
1675    if send_new_event(
1676        &window_state,
1677        InputEvent::FileDrop(FileDropEvent::Submit { position }),
1678    ) {
1679        YES
1680    } else {
1681        NO
1682    }
1683}
1684
1685fn external_paths_from_event(dragging_info: *mut Object) -> ExternalPaths {
1686    let mut paths = SmallVec::new();
1687    let pasteboard: id = unsafe { msg_send![dragging_info, draggingPasteboard] };
1688    let filenames = unsafe { NSPasteboard::propertyListForType(pasteboard, NSFilenamesPboardType) };
1689    for file in unsafe { filenames.iter() } {
1690        let path = unsafe {
1691            let f = NSString::UTF8String(file);
1692            CStr::from_ptr(f).to_string_lossy().into_owned()
1693        };
1694        paths.push(PathBuf::from(path))
1695    }
1696    ExternalPaths(paths)
1697}
1698
1699extern "C" fn conclude_drag_operation(this: &Object, _: Sel, _: id) {
1700    let window_state = unsafe { get_window_state(this) };
1701    send_new_event(&window_state, InputEvent::FileDrop(FileDropEvent::Exited));
1702}
1703
1704async fn synthetic_drag(
1705    window_state: Weak<Mutex<MacWindowState>>,
1706    drag_id: usize,
1707    event: MouseMoveEvent,
1708) {
1709    loop {
1710        Timer::after(Duration::from_millis(16)).await;
1711        if let Some(window_state) = window_state.upgrade() {
1712            let mut lock = window_state.lock();
1713            if lock.synthetic_drag_counter == drag_id {
1714                if let Some(mut callback) = lock.event_callback.take() {
1715                    drop(lock);
1716                    callback(InputEvent::MouseMove(event.clone()));
1717                    window_state.lock().event_callback = Some(callback);
1718                }
1719            } else {
1720                break;
1721            }
1722        }
1723    }
1724}
1725
1726fn send_new_event(window_state_lock: &Mutex<MacWindowState>, e: InputEvent) -> bool {
1727    let window_state = window_state_lock.lock().event_callback.take();
1728    if let Some(mut callback) = window_state {
1729        callback(e);
1730        window_state_lock.lock().event_callback = Some(callback);
1731        true
1732    } else {
1733        false
1734    }
1735}
1736
1737fn drag_event_position(window_state: &Mutex<MacWindowState>, dragging_info: id) -> Point<Pixels> {
1738    let drag_location: NSPoint = unsafe { msg_send![dragging_info, draggingLocation] };
1739    convert_mouse_position(drag_location, window_state.lock().content_size().height)
1740}
1741
1742fn with_input_handler<F, R>(window: &Object, f: F) -> Option<R>
1743where
1744    F: FnOnce(&mut dyn PlatformInputHandler) -> R,
1745{
1746    let window_state = unsafe { get_window_state(window) };
1747    let mut lock = window_state.as_ref().lock();
1748    if let Some(mut input_handler) = lock.input_handler.take() {
1749        drop(lock);
1750        let result = f(input_handler.as_mut());
1751        window_state.lock().input_handler = Some(input_handler);
1752        Some(result)
1753    } else {
1754        None
1755    }
1756}