window.rs

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