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_view: NonNull<Object>,
 341    display_link: Option<DisplayLink>,
 342    renderer: renderer::Renderer,
 343    request_frame_callback: Option<Box<dyn FnMut()>>,
 344    event_callback: Option<Box<dyn FnMut(PlatformInput) -> crate::DispatchEventResult>>,
 345    activate_callback: Option<Box<dyn FnMut(bool)>>,
 346    resize_callback: Option<Box<dyn FnMut(Size<Pixels>, f32)>>,
 347    fullscreen_callback: Option<Box<dyn FnMut(bool)>>,
 348    moved_callback: Option<Box<dyn FnMut()>>,
 349    should_close_callback: Option<Box<dyn FnMut() -> bool>>,
 350    close_callback: Option<Box<dyn FnOnce()>>,
 351    appearance_changed_callback: Option<Box<dyn FnMut()>>,
 352    input_handler: Option<PlatformInputHandler>,
 353    last_key_equivalent: Option<KeyDownEvent>,
 354    synthetic_drag_counter: usize,
 355    last_fresh_keydown: Option<Keystroke>,
 356    traffic_light_position: Option<Point<Pixels>>,
 357    previous_modifiers_changed_event: Option<PlatformInput>,
 358    // State tracking what the IME did after the last request
 359    input_during_keydown: Option<SmallVec<[ImeInput; 1]>>,
 360    previous_keydown_inserted_text: Option<String>,
 361    external_files_dragged: bool,
 362    // Whether the next left-mouse click is also the focusing click.
 363    first_mouse: bool,
 364    minimized: bool,
 365}
 366
 367impl MacWindowState {
 368    fn move_traffic_light(&self) {
 369        if let Some(traffic_light_position) = self.traffic_light_position {
 370            if self.is_fullscreen() {
 371                // Moving traffic lights while fullscreen doesn't work,
 372                // see https://github.com/zed-industries/zed/issues/4712
 373                return;
 374            }
 375
 376            let titlebar_height = self.titlebar_height();
 377
 378            unsafe {
 379                let close_button: id = msg_send![
 380                    self.native_window,
 381                    standardWindowButton: NSWindowButton::NSWindowCloseButton
 382                ];
 383                let min_button: id = msg_send![
 384                    self.native_window,
 385                    standardWindowButton: NSWindowButton::NSWindowMiniaturizeButton
 386                ];
 387                let zoom_button: id = msg_send![
 388                    self.native_window,
 389                    standardWindowButton: NSWindowButton::NSWindowZoomButton
 390                ];
 391
 392                let mut close_button_frame: CGRect = msg_send![close_button, frame];
 393                let mut min_button_frame: CGRect = msg_send![min_button, frame];
 394                let mut zoom_button_frame: CGRect = msg_send![zoom_button, frame];
 395                let mut origin = point(
 396                    traffic_light_position.x,
 397                    titlebar_height
 398                        - traffic_light_position.y
 399                        - px(close_button_frame.size.height as f32),
 400                );
 401                let button_spacing =
 402                    px((min_button_frame.origin.x - close_button_frame.origin.x) as f32);
 403
 404                close_button_frame.origin = CGPoint::new(origin.x.into(), origin.y.into());
 405                let _: () = msg_send![close_button, setFrame: close_button_frame];
 406                origin.x += button_spacing;
 407
 408                min_button_frame.origin = CGPoint::new(origin.x.into(), origin.y.into());
 409                let _: () = msg_send![min_button, setFrame: min_button_frame];
 410                origin.x += button_spacing;
 411
 412                zoom_button_frame.origin = CGPoint::new(origin.x.into(), origin.y.into());
 413                let _: () = msg_send![zoom_button, setFrame: zoom_button_frame];
 414                origin.x += button_spacing;
 415            }
 416        }
 417    }
 418
 419    fn start_display_link(&mut self) {
 420        self.stop_display_link();
 421        let display_id = unsafe { display_id_for_screen(self.native_window.screen()) };
 422        if let Some(mut display_link) =
 423            DisplayLink::new(display_id, self.native_view.as_ptr() as *mut c_void, step).log_err()
 424        {
 425            display_link.start().log_err();
 426            self.display_link = Some(display_link);
 427        }
 428    }
 429
 430    fn stop_display_link(&mut self) {
 431        self.display_link = None;
 432    }
 433
 434    fn is_maximized(&self) -> bool {
 435        unsafe {
 436            let bounds = self.bounds();
 437            let screen_size = self.native_window.screen().visibleFrame().into();
 438            bounds.size == screen_size
 439        }
 440    }
 441
 442    fn is_minimized(&self) -> bool {
 443        self.minimized
 444    }
 445
 446    fn is_fullscreen(&self) -> bool {
 447        unsafe {
 448            let style_mask = self.native_window.styleMask();
 449            style_mask.contains(NSWindowStyleMask::NSFullScreenWindowMask)
 450        }
 451    }
 452
 453    fn bounds(&self) -> Bounds<DevicePixels> {
 454        let mut window_frame = unsafe { NSWindow::frame(self.native_window) };
 455        let screen_frame = unsafe {
 456            let screen = NSWindow::screen(self.native_window);
 457            NSScreen::frame(screen)
 458        };
 459
 460        // Flip the y coordinate to be top-left origin
 461        window_frame.origin.y =
 462            screen_frame.size.height - window_frame.origin.y - window_frame.size.height;
 463
 464        let bounds = Bounds::new(
 465            point(
 466                ((window_frame.origin.x - screen_frame.origin.x) as i32).into(),
 467                ((window_frame.origin.y - screen_frame.origin.y) as i32).into(),
 468            ),
 469            size(
 470                (window_frame.size.width as i32).into(),
 471                (window_frame.size.height as i32).into(),
 472            ),
 473        );
 474        bounds
 475    }
 476
 477    fn content_size(&self) -> Size<Pixels> {
 478        let NSSize { width, height, .. } =
 479            unsafe { NSView::frame(self.native_window.contentView()) }.size;
 480        size(px(width as f32), px(height as f32))
 481    }
 482
 483    fn scale_factor(&self) -> f32 {
 484        get_scale_factor(self.native_window)
 485    }
 486
 487    fn update_drawable_size(&mut self, drawable_size: NSSize) {
 488        self.renderer.update_drawable_size(Size {
 489            width: drawable_size.width,
 490            height: drawable_size.height,
 491        })
 492    }
 493
 494    fn titlebar_height(&self) -> Pixels {
 495        unsafe {
 496            let frame = NSWindow::frame(self.native_window);
 497            let content_layout_rect: CGRect = msg_send![self.native_window, contentLayoutRect];
 498            px((frame.size.height - content_layout_rect.size.height) as f32)
 499        }
 500    }
 501
 502    fn to_screen_ns_point(&self, point: Point<Pixels>) -> NSPoint {
 503        unsafe {
 504            let point = NSPoint::new(
 505                point.x.into(),
 506                (self.content_size().height - point.y).into(),
 507            );
 508            msg_send![self.native_window, convertPointToScreen: point]
 509        }
 510    }
 511}
 512
 513unsafe impl Send for MacWindowState {}
 514
 515pub(crate) struct MacWindow(Arc<Mutex<MacWindowState>>);
 516
 517impl MacWindow {
 518    pub fn open(
 519        handle: AnyWindowHandle,
 520        WindowParams {
 521            window_background,
 522            bounds,
 523            titlebar,
 524            kind,
 525            is_movable,
 526            focus,
 527            show,
 528            display_id,
 529        }: WindowParams,
 530        executor: ForegroundExecutor,
 531        renderer_context: renderer::Context,
 532    ) -> Self {
 533        unsafe {
 534            let pool = NSAutoreleasePool::new(nil);
 535
 536            let mut style_mask;
 537            if let Some(titlebar) = titlebar.as_ref() {
 538                style_mask = NSWindowStyleMask::NSClosableWindowMask
 539                    | NSWindowStyleMask::NSMiniaturizableWindowMask
 540                    | NSWindowStyleMask::NSResizableWindowMask
 541                    | NSWindowStyleMask::NSTitledWindowMask;
 542
 543                if titlebar.appears_transparent {
 544                    style_mask |= NSWindowStyleMask::NSFullSizeContentViewWindowMask;
 545                }
 546            } else {
 547                style_mask = NSWindowStyleMask::NSTitledWindowMask
 548                    | NSWindowStyleMask::NSFullSizeContentViewWindowMask;
 549            }
 550
 551            let native_window: id = match kind {
 552                WindowKind::Normal => msg_send![WINDOW_CLASS, alloc],
 553                WindowKind::PopUp => {
 554                    style_mask |= NSWindowStyleMaskNonactivatingPanel;
 555                    msg_send![PANEL_CLASS, alloc]
 556                }
 557            };
 558
 559            let display = display_id
 560                .and_then(MacDisplay::find_by_id)
 561                .unwrap_or_else(|| MacDisplay::primary());
 562
 563            let mut target_screen = nil;
 564            let mut screen_frame = None;
 565
 566            let screens = NSScreen::screens(nil);
 567            let count: u64 = cocoa::foundation::NSArray::count(screens);
 568            for i in 0..count {
 569                let screen = cocoa::foundation::NSArray::objectAtIndex(screens, i);
 570                let frame = NSScreen::visibleFrame(screen);
 571                let display_id = display_id_for_screen(screen);
 572                if display_id == display.0 {
 573                    screen_frame = Some(frame);
 574                    target_screen = screen;
 575                }
 576            }
 577
 578            let screen_frame = screen_frame.unwrap_or_else(|| {
 579                let screen = NSScreen::mainScreen(nil);
 580                target_screen = screen;
 581                NSScreen::visibleFrame(screen)
 582            });
 583
 584            let window_rect = NSRect::new(
 585                NSPoint::new(
 586                    screen_frame.origin.x + bounds.origin.x.0 as f64,
 587                    screen_frame.origin.y
 588                        + (display.bounds().size.height - bounds.origin.y).0 as f64,
 589                ),
 590                NSSize::new(bounds.size.width.0 as f64, bounds.size.height.0 as f64),
 591            );
 592
 593            let native_window = native_window.initWithContentRect_styleMask_backing_defer_screen_(
 594                window_rect,
 595                style_mask,
 596                NSBackingStoreBuffered,
 597                NO,
 598                target_screen,
 599            );
 600            assert!(!native_window.is_null());
 601            let () = msg_send![
 602                native_window,
 603                registerForDraggedTypes:
 604                    NSArray::arrayWithObject(nil, NSFilenamesPboardType)
 605            ];
 606            let () = msg_send![
 607                native_window,
 608                setReleasedWhenClosed: NO
 609            ];
 610
 611            let native_view: id = msg_send![VIEW_CLASS, alloc];
 612            let native_view = NSView::init(native_view);
 613            assert!(!native_view.is_null());
 614
 615            let window_size = {
 616                let scale = get_scale_factor(native_window);
 617                size(
 618                    bounds.size.width.0 as f32 * scale,
 619                    bounds.size.height.0 as f32 * scale,
 620                )
 621            };
 622
 623            let mut window = Self(Arc::new(Mutex::new(MacWindowState {
 624                handle,
 625                executor,
 626                native_window,
 627                native_view: NonNull::new_unchecked(native_view),
 628                display_link: None,
 629                renderer: renderer::new_renderer(
 630                    renderer_context,
 631                    native_window as *mut _,
 632                    native_view as *mut _,
 633                    window_size,
 634                ),
 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        unsafe {
 774            this.native_window.setDelegate_(nil);
 775        }
 776        this.executor
 777            .spawn(async move {
 778                unsafe {
 779                    window.close();
 780                    window.autorelease();
 781                }
 782            })
 783            .detach();
 784    }
 785}
 786
 787impl PlatformWindow for MacWindow {
 788    fn bounds(&self) -> Bounds<DevicePixels> {
 789        self.0.as_ref().lock().bounds()
 790    }
 791
 792    fn is_maximized(&self) -> bool {
 793        self.0.as_ref().lock().is_maximized()
 794    }
 795
 796    fn is_minimized(&self) -> bool {
 797        self.0.as_ref().lock().is_minimized()
 798    }
 799
 800    fn content_size(&self) -> Size<Pixels> {
 801        self.0.as_ref().lock().content_size()
 802    }
 803
 804    fn scale_factor(&self) -> f32 {
 805        self.0.as_ref().lock().scale_factor()
 806    }
 807
 808    fn appearance(&self) -> WindowAppearance {
 809        unsafe {
 810            let appearance: id = msg_send![self.0.lock().native_window, effectiveAppearance];
 811            WindowAppearance::from_native(appearance)
 812        }
 813    }
 814
 815    fn display(&self) -> Rc<dyn PlatformDisplay> {
 816        unsafe {
 817            let screen = self.0.lock().native_window.screen();
 818            let device_description: id = msg_send![screen, deviceDescription];
 819            let screen_number: id = NSDictionary::valueForKey_(
 820                device_description,
 821                NSString::alloc(nil).init_str("NSScreenNumber"),
 822            );
 823
 824            let screen_number: u32 = msg_send![screen_number, unsignedIntValue];
 825
 826            Rc::new(MacDisplay(screen_number))
 827        }
 828    }
 829
 830    fn mouse_position(&self) -> Point<Pixels> {
 831        let position = unsafe {
 832            self.0
 833                .lock()
 834                .native_window
 835                .mouseLocationOutsideOfEventStream()
 836        };
 837        convert_mouse_position(position, self.content_size().height)
 838    }
 839
 840    fn modifiers(&self) -> Modifiers {
 841        unsafe {
 842            let modifiers: NSEventModifierFlags = msg_send![class!(NSEvent), modifierFlags];
 843
 844            let control = modifiers.contains(NSEventModifierFlags::NSControlKeyMask);
 845            let alt = modifiers.contains(NSEventModifierFlags::NSAlternateKeyMask);
 846            let shift = modifiers.contains(NSEventModifierFlags::NSShiftKeyMask);
 847            let command = modifiers.contains(NSEventModifierFlags::NSCommandKeyMask);
 848            let function = modifiers.contains(NSEventModifierFlags::NSFunctionKeyMask);
 849
 850            Modifiers {
 851                control,
 852                alt,
 853                shift,
 854                platform: command,
 855                function,
 856            }
 857        }
 858    }
 859
 860    fn as_any_mut(&mut self) -> &mut dyn Any {
 861        self
 862    }
 863
 864    fn set_input_handler(&mut self, input_handler: PlatformInputHandler) {
 865        self.0.as_ref().lock().input_handler = Some(input_handler);
 866    }
 867
 868    fn take_input_handler(&mut self) -> Option<PlatformInputHandler> {
 869        self.0.as_ref().lock().input_handler.take()
 870    }
 871
 872    fn prompt(
 873        &self,
 874        level: PromptLevel,
 875        msg: &str,
 876        detail: Option<&str>,
 877        answers: &[&str],
 878    ) -> Option<oneshot::Receiver<usize>> {
 879        // macOs applies overrides to modal window buttons after they are added.
 880        // Two most important for this logic are:
 881        // * Buttons with "Cancel" title will be displayed as the last buttons in the modal
 882        // * Last button added to the modal via `addButtonWithTitle` stays focused
 883        // * Focused buttons react on "space"/" " keypresses
 884        // * Usage of `keyEquivalent`, `makeFirstResponder` or `setInitialFirstResponder` does not change the focus
 885        //
 886        // See also https://developer.apple.com/documentation/appkit/nsalert/1524532-addbuttonwithtitle#discussion
 887        // ```
 888        // By default, the first button has a key equivalent of Return,
 889        // any button with a title of “Cancel” has a key equivalent of Escape,
 890        // 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).
 891        // ```
 892        //
 893        // To avoid situations when the last element added is "Cancel" and it gets the focus
 894        // (hence stealing both ESC and Space shortcuts), we find and add one non-Cancel button
 895        // last, so it gets focus and a Space shortcut.
 896        // This way, "Save this file? Yes/No/Cancel"-ish modals will get all three buttons mapped with a key.
 897        let latest_non_cancel_label = answers
 898            .iter()
 899            .enumerate()
 900            .rev()
 901            .find(|(_, &label)| label != "Cancel")
 902            .filter(|&(label_index, _)| label_index > 0);
 903
 904        unsafe {
 905            let alert: id = msg_send![class!(NSAlert), alloc];
 906            let alert: id = msg_send![alert, init];
 907            let alert_style = match level {
 908                PromptLevel::Info => 1,
 909                PromptLevel::Warning => 0,
 910                PromptLevel::Critical => 2,
 911            };
 912            let _: () = msg_send![alert, setAlertStyle: alert_style];
 913            let _: () = msg_send![alert, setMessageText: ns_string(msg)];
 914            if let Some(detail) = detail {
 915                let _: () = msg_send![alert, setInformativeText: ns_string(detail)];
 916            }
 917
 918            for (ix, answer) in answers
 919                .iter()
 920                .enumerate()
 921                .filter(|&(ix, _)| Some(ix) != latest_non_cancel_label.map(|(ix, _)| ix))
 922            {
 923                let button: id = msg_send![alert, addButtonWithTitle: ns_string(answer)];
 924                let _: () = msg_send![button, setTag: ix as NSInteger];
 925            }
 926            if let Some((ix, answer)) = latest_non_cancel_label {
 927                let button: id = msg_send![alert, addButtonWithTitle: ns_string(answer)];
 928                let _: () = msg_send![button, setTag: ix as NSInteger];
 929            }
 930
 931            let (done_tx, done_rx) = oneshot::channel();
 932            let done_tx = Cell::new(Some(done_tx));
 933            let block = ConcreteBlock::new(move |answer: NSInteger| {
 934                if let Some(done_tx) = done_tx.take() {
 935                    let _ = done_tx.send(answer.try_into().unwrap());
 936                }
 937            });
 938            let block = block.copy();
 939            let native_window = self.0.lock().native_window;
 940            let executor = self.0.lock().executor.clone();
 941            executor
 942                .spawn(async move {
 943                    let _: () = msg_send![
 944                        alert,
 945                        beginSheetModalForWindow: native_window
 946                        completionHandler: block
 947                    ];
 948                })
 949                .detach();
 950
 951            Some(done_rx)
 952        }
 953    }
 954
 955    fn activate(&self) {
 956        let window = self.0.lock().native_window;
 957        let executor = self.0.lock().executor.clone();
 958        executor
 959            .spawn(async move {
 960                unsafe {
 961                    let _: () = msg_send![window, makeKeyAndOrderFront: nil];
 962                }
 963            })
 964            .detach();
 965    }
 966
 967    fn is_active(&self) -> bool {
 968        unsafe { self.0.lock().native_window.isKeyWindow() == YES }
 969    }
 970
 971    fn set_title(&mut self, title: &str) {
 972        unsafe {
 973            let app = NSApplication::sharedApplication(nil);
 974            let window = self.0.lock().native_window;
 975            let title = ns_string(title);
 976            let _: () = msg_send![app, changeWindowsItem:window title:title filename:false];
 977            let _: () = msg_send![window, setTitle: title];
 978            self.0.lock().move_traffic_light();
 979        }
 980    }
 981
 982    fn set_background_appearance(&mut self, background_appearance: WindowBackgroundAppearance) {
 983        let this = self.0.as_ref().lock();
 984        let blur_radius = if background_appearance == WindowBackgroundAppearance::Blurred {
 985            80
 986        } else {
 987            0
 988        };
 989        let opaque = if background_appearance == WindowBackgroundAppearance::Opaque {
 990            YES
 991        } else {
 992            NO
 993        };
 994        unsafe {
 995            this.native_window.setOpaque_(opaque);
 996            let clear_color = if opaque == YES {
 997                NSColor::colorWithSRGBRed_green_blue_alpha_(nil, 0f64, 0f64, 0f64, 1f64)
 998            } else {
 999                NSColor::clearColor(nil)
1000            };
1001            this.native_window.setBackgroundColor_(clear_color);
1002            let window_number = this.native_window.windowNumber();
1003            CGSSetWindowBackgroundBlurRadius(CGSMainConnectionID(), window_number, blur_radius);
1004        }
1005    }
1006
1007    fn set_edited(&mut self, edited: bool) {
1008        unsafe {
1009            let window = self.0.lock().native_window;
1010            msg_send![window, setDocumentEdited: edited as BOOL]
1011        }
1012
1013        // Changing the document edited state resets the traffic light position,
1014        // so we have to move it again.
1015        self.0.lock().move_traffic_light();
1016    }
1017
1018    fn show_character_palette(&self) {
1019        let this = self.0.lock();
1020        let window = this.native_window;
1021        this.executor
1022            .spawn(async move {
1023                unsafe {
1024                    let app = NSApplication::sharedApplication(nil);
1025                    let _: () = msg_send![app, orderFrontCharacterPalette: window];
1026                }
1027            })
1028            .detach();
1029    }
1030
1031    fn minimize(&self) {
1032        let window = self.0.lock().native_window;
1033        unsafe {
1034            window.miniaturize_(nil);
1035        }
1036    }
1037
1038    fn zoom(&self) {
1039        let this = self.0.lock();
1040        let window = this.native_window;
1041        this.executor
1042            .spawn(async move {
1043                unsafe {
1044                    window.zoom_(nil);
1045                }
1046            })
1047            .detach();
1048    }
1049
1050    fn toggle_fullscreen(&self) {
1051        let this = self.0.lock();
1052        let window = this.native_window;
1053        this.executor
1054            .spawn(async move {
1055                unsafe {
1056                    window.toggleFullScreen_(nil);
1057                }
1058            })
1059            .detach();
1060    }
1061
1062    fn is_fullscreen(&self) -> bool {
1063        let this = self.0.lock();
1064        let window = this.native_window;
1065
1066        unsafe {
1067            window
1068                .styleMask()
1069                .contains(NSWindowStyleMask::NSFullScreenWindowMask)
1070        }
1071    }
1072
1073    fn on_request_frame(&self, callback: Box<dyn FnMut()>) {
1074        self.0.as_ref().lock().request_frame_callback = Some(callback);
1075    }
1076
1077    fn on_input(&self, callback: Box<dyn FnMut(PlatformInput) -> crate::DispatchEventResult>) {
1078        self.0.as_ref().lock().event_callback = Some(callback);
1079    }
1080
1081    fn on_active_status_change(&self, callback: Box<dyn FnMut(bool)>) {
1082        self.0.as_ref().lock().activate_callback = Some(callback);
1083    }
1084
1085    fn on_resize(&self, callback: Box<dyn FnMut(Size<Pixels>, f32)>) {
1086        self.0.as_ref().lock().resize_callback = Some(callback);
1087    }
1088
1089    fn on_fullscreen(&self, callback: Box<dyn FnMut(bool)>) {
1090        self.0.as_ref().lock().fullscreen_callback = Some(callback);
1091    }
1092
1093    fn on_moved(&self, callback: Box<dyn FnMut()>) {
1094        self.0.as_ref().lock().moved_callback = Some(callback);
1095    }
1096
1097    fn on_should_close(&self, callback: Box<dyn FnMut() -> bool>) {
1098        self.0.as_ref().lock().should_close_callback = Some(callback);
1099    }
1100
1101    fn on_close(&self, callback: Box<dyn FnOnce()>) {
1102        self.0.as_ref().lock().close_callback = Some(callback);
1103    }
1104
1105    fn on_appearance_changed(&self, callback: Box<dyn FnMut()>) {
1106        self.0.lock().appearance_changed_callback = Some(callback);
1107    }
1108
1109    fn is_topmost_for_position(&self, position: Point<Pixels>) -> bool {
1110        let self_borrow = self.0.lock();
1111        let self_handle = self_borrow.handle;
1112
1113        unsafe {
1114            let app = NSApplication::sharedApplication(nil);
1115
1116            // Convert back to screen coordinates
1117            let screen_point = self_borrow.to_screen_ns_point(position);
1118
1119            let window_number: NSInteger = msg_send![class!(NSWindow), windowNumberAtPoint:screen_point belowWindowWithWindowNumber:0];
1120            let top_most_window: id = msg_send![app, windowWithWindowNumber: window_number];
1121
1122            let is_panel: BOOL = msg_send![top_most_window, isKindOfClass: PANEL_CLASS];
1123            let is_window: BOOL = msg_send![top_most_window, isKindOfClass: WINDOW_CLASS];
1124            if is_panel == YES || is_window == YES {
1125                let topmost_window = get_window_state(&*top_most_window).lock().handle;
1126                topmost_window == self_handle
1127            } else {
1128                // Someone else's window is on top
1129                false
1130            }
1131        }
1132    }
1133
1134    fn draw(&self, scene: &crate::Scene) {
1135        let mut this = self.0.lock();
1136        this.renderer.draw(scene);
1137    }
1138
1139    fn sprite_atlas(&self) -> Arc<dyn PlatformAtlas> {
1140        self.0.lock().renderer.sprite_atlas().clone()
1141    }
1142}
1143
1144impl HasWindowHandle for MacWindow {
1145    fn window_handle(
1146        &self,
1147    ) -> Result<raw_window_handle::WindowHandle<'_>, raw_window_handle::HandleError> {
1148        // SAFETY: The AppKitWindowHandle is a wrapper around a pointer to an NSView
1149        unsafe {
1150            Ok(WindowHandle::borrow_raw(RawWindowHandle::AppKit(
1151                AppKitWindowHandle::new(self.0.lock().native_view.cast()),
1152            )))
1153        }
1154    }
1155}
1156
1157impl HasDisplayHandle for MacWindow {
1158    fn display_handle(
1159        &self,
1160    ) -> Result<raw_window_handle::DisplayHandle<'_>, raw_window_handle::HandleError> {
1161        // SAFETY: This is a no-op on macOS
1162        unsafe { Ok(DisplayHandle::borrow_raw(AppKitDisplayHandle::new().into())) }
1163    }
1164}
1165
1166fn get_scale_factor(native_window: id) -> f32 {
1167    let factor = unsafe {
1168        let screen: id = msg_send![native_window, screen];
1169        NSScreen::backingScaleFactor(screen) as f32
1170    };
1171
1172    // We are not certain what triggers this, but it seems that sometimes
1173    // this method would return 0 (https://github.com/zed-industries/zed/issues/6412)
1174    // It seems most likely that this would happen if the window has no screen
1175    // (if it is off-screen), though we'd expect to see viewDidChangeBackingProperties before
1176    // it was rendered for real.
1177    // Regardless, attempt to avoid the issue here.
1178    if factor == 0.0 {
1179        2.
1180    } else {
1181        factor
1182    }
1183}
1184
1185unsafe fn get_window_state(object: &Object) -> Arc<Mutex<MacWindowState>> {
1186    let raw: *mut c_void = *object.get_ivar(WINDOW_STATE_IVAR);
1187    let rc1 = Arc::from_raw(raw as *mut Mutex<MacWindowState>);
1188    let rc2 = rc1.clone();
1189    mem::forget(rc1);
1190    rc2
1191}
1192
1193unsafe fn drop_window_state(object: &Object) {
1194    let raw: *mut c_void = *object.get_ivar(WINDOW_STATE_IVAR);
1195    Arc::from_raw(raw as *mut Mutex<MacWindowState>);
1196}
1197
1198extern "C" fn yes(_: &Object, _: Sel) -> BOOL {
1199    YES
1200}
1201
1202extern "C" fn dealloc_window(this: &Object, _: Sel) {
1203    unsafe {
1204        drop_window_state(this);
1205        let _: () = msg_send![super(this, class!(NSWindow)), dealloc];
1206    }
1207}
1208
1209extern "C" fn dealloc_view(this: &Object, _: Sel) {
1210    unsafe {
1211        drop_window_state(this);
1212        let _: () = msg_send![super(this, class!(NSView)), dealloc];
1213    }
1214}
1215
1216extern "C" fn handle_key_equivalent(this: &Object, _: Sel, native_event: id) -> BOOL {
1217    handle_key_event(this, native_event, true)
1218}
1219
1220extern "C" fn handle_key_down(this: &Object, _: Sel, native_event: id) {
1221    handle_key_event(this, native_event, false);
1222}
1223
1224// Things to test if you're modifying this method:
1225//  Brazilian layout:
1226//   - `" space` should type a quote
1227//   - `" backspace` should delete the marked quote
1228//   - `" up` should type the quote, unmark it, and move up one line
1229//   - `" cmd-down` should not leave a marked quote behind (it maybe should dispatch the key though?)
1230//   - `cmd-ctrl-space` and clicking on an emoji should type it
1231//  Czech (QWERTY) layout:
1232//   - in vim mode `option-4`  should go to end of line (same as $)
1233extern "C" fn handle_key_event(this: &Object, native_event: id, key_equivalent: bool) -> BOOL {
1234    let window_state = unsafe { get_window_state(this) };
1235    let mut lock = window_state.as_ref().lock();
1236
1237    let window_height = lock.content_size().height;
1238    let event = unsafe { PlatformInput::from_native(native_event, Some(window_height)) };
1239
1240    if let Some(PlatformInput::KeyDown(mut event)) = event {
1241        // For certain keystrokes, macOS will first dispatch a "key equivalent" event.
1242        // If that event isn't handled, it will then dispatch a "key down" event. GPUI
1243        // makes no distinction between these two types of events, so we need to ignore
1244        // the "key down" event if we've already just processed its "key equivalent" version.
1245        if key_equivalent {
1246            lock.last_key_equivalent = Some(event.clone());
1247        } else if lock.last_key_equivalent.take().as_ref() == Some(&event) {
1248            return NO;
1249        }
1250
1251        let keydown = event.keystroke.clone();
1252        let fn_modifier = keydown.modifiers.function;
1253        // Ignore events from held-down keys after some of the initially-pressed keys
1254        // were released.
1255        if event.is_held {
1256            if lock.last_fresh_keydown.as_ref() != Some(&keydown) {
1257                return YES;
1258            }
1259        } else {
1260            lock.last_fresh_keydown = Some(keydown.clone());
1261        }
1262        lock.input_during_keydown = Some(SmallVec::new());
1263        drop(lock);
1264
1265        // Send the event to the input context for IME handling, unless the `fn` modifier is
1266        // being pressed.
1267        // this will call back into `insert_text`, etc.
1268        if !fn_modifier {
1269            unsafe {
1270                let input_context: id = msg_send![this, inputContext];
1271                let _: BOOL = msg_send![input_context, handleEvent: native_event];
1272            }
1273        }
1274
1275        let mut handled = false;
1276        let mut lock = window_state.lock();
1277        let previous_keydown_inserted_text = lock.previous_keydown_inserted_text.take();
1278        let mut input_during_keydown = lock.input_during_keydown.take().unwrap();
1279        let mut callback = lock.event_callback.take();
1280        drop(lock);
1281
1282        let last_ime = input_during_keydown.pop();
1283        // on a brazilian keyboard typing `"` and then hitting `up` will cause two IME
1284        // events, one to unmark the quote, and one to send the up arrow.
1285        for ime in input_during_keydown {
1286            send_to_input_handler(this, ime);
1287        }
1288
1289        let is_composing =
1290            with_input_handler(this, |input_handler| input_handler.marked_text_range())
1291                .flatten()
1292                .is_some();
1293
1294        if let Some(ime) = last_ime {
1295            if let ImeInput::InsertText(text, _) = &ime {
1296                if !is_composing {
1297                    window_state.lock().previous_keydown_inserted_text = Some(text.clone());
1298                    if let Some(callback) = callback.as_mut() {
1299                        event.keystroke.ime_key = Some(text.clone());
1300                        handled = !callback(PlatformInput::KeyDown(event)).propagate;
1301                    }
1302                }
1303            }
1304
1305            if !handled {
1306                handled = true;
1307                send_to_input_handler(this, ime);
1308            }
1309        } else if !is_composing {
1310            let is_held = event.is_held;
1311
1312            if let Some(callback) = callback.as_mut() {
1313                handled = !callback(PlatformInput::KeyDown(event)).propagate;
1314            }
1315
1316            if !handled && is_held {
1317                if let Some(text) = previous_keydown_inserted_text {
1318                    // MacOS IME is a bit funky, and even when you've told it there's nothing to
1319                    // enter it will still swallow certain keys (e.g. 'f', 'j') and not others
1320                    // (e.g. 'n'). This is a problem for certain kinds of views, like the terminal.
1321                    with_input_handler(this, |input_handler| {
1322                        if input_handler.selected_text_range().is_none() {
1323                            handled = true;
1324                            input_handler.replace_text_in_range(None, &text)
1325                        }
1326                    });
1327                    window_state.lock().previous_keydown_inserted_text = Some(text);
1328                }
1329            }
1330        }
1331
1332        window_state.lock().event_callback = callback;
1333
1334        handled as BOOL
1335    } else {
1336        NO
1337    }
1338}
1339
1340extern "C" fn handle_view_event(this: &Object, _: Sel, native_event: id) {
1341    let window_state = unsafe { get_window_state(this) };
1342    let weak_window_state = Arc::downgrade(&window_state);
1343    let mut lock = window_state.as_ref().lock();
1344    let window_height = lock.content_size().height;
1345    let event = unsafe { PlatformInput::from_native(native_event, Some(window_height)) };
1346
1347    if let Some(mut event) = event {
1348        match &mut event {
1349            PlatformInput::MouseDown(
1350                event @ MouseDownEvent {
1351                    button: MouseButton::Left,
1352                    modifiers: Modifiers { control: true, .. },
1353                    ..
1354                },
1355            ) => {
1356                // On mac, a ctrl-left click should be handled as a right click.
1357                *event = MouseDownEvent {
1358                    button: MouseButton::Right,
1359                    modifiers: Modifiers {
1360                        control: false,
1361                        ..event.modifiers
1362                    },
1363                    click_count: 1,
1364                    ..*event
1365                };
1366            }
1367
1368            // Handles focusing click.
1369            PlatformInput::MouseDown(
1370                event @ MouseDownEvent {
1371                    button: MouseButton::Left,
1372                    ..
1373                },
1374            ) if (lock.first_mouse) => {
1375                *event = MouseDownEvent {
1376                    first_mouse: true,
1377                    ..*event
1378                };
1379                lock.first_mouse = false;
1380            }
1381
1382            // Because we map a ctrl-left_down to a right_down -> right_up let's ignore
1383            // the ctrl-left_up to avoid having a mismatch in button down/up events if the
1384            // user is still holding ctrl when releasing the left mouse button
1385            PlatformInput::MouseUp(
1386                event @ MouseUpEvent {
1387                    button: MouseButton::Left,
1388                    modifiers: Modifiers { control: true, .. },
1389                    ..
1390                },
1391            ) => {
1392                *event = MouseUpEvent {
1393                    button: MouseButton::Right,
1394                    modifiers: Modifiers {
1395                        control: false,
1396                        ..event.modifiers
1397                    },
1398                    click_count: 1,
1399                    ..*event
1400                };
1401            }
1402
1403            _ => {}
1404        };
1405
1406        match &event {
1407            PlatformInput::MouseMove(
1408                event @ MouseMoveEvent {
1409                    pressed_button: Some(_),
1410                    ..
1411                },
1412            ) => {
1413                // Synthetic drag is used for selecting long buffer contents while buffer is being scrolled.
1414                // External file drag and drop is able to emit its own synthetic mouse events which will conflict
1415                // with these ones.
1416                if !lock.external_files_dragged {
1417                    lock.synthetic_drag_counter += 1;
1418                    let executor = lock.executor.clone();
1419                    executor
1420                        .spawn(synthetic_drag(
1421                            weak_window_state,
1422                            lock.synthetic_drag_counter,
1423                            event.clone(),
1424                        ))
1425                        .detach();
1426                }
1427            }
1428
1429            PlatformInput::MouseUp(MouseUpEvent { .. }) => {
1430                lock.synthetic_drag_counter += 1;
1431            }
1432
1433            PlatformInput::ModifiersChanged(ModifiersChangedEvent { modifiers }) => {
1434                // Only raise modifiers changed event when they have actually changed
1435                if let Some(PlatformInput::ModifiersChanged(ModifiersChangedEvent {
1436                    modifiers: prev_modifiers,
1437                })) = &lock.previous_modifiers_changed_event
1438                {
1439                    if prev_modifiers == modifiers {
1440                        return;
1441                    }
1442                }
1443
1444                lock.previous_modifiers_changed_event = Some(event.clone());
1445            }
1446
1447            _ => {}
1448        }
1449
1450        if let Some(mut callback) = lock.event_callback.take() {
1451            drop(lock);
1452            callback(event);
1453            window_state.lock().event_callback = Some(callback);
1454        }
1455    }
1456}
1457
1458// Allows us to receive `cmd-.` (the shortcut for closing a dialog)
1459// https://bugs.eclipse.org/bugs/show_bug.cgi?id=300620#c6
1460extern "C" fn cancel_operation(this: &Object, _sel: Sel, _sender: id) {
1461    let window_state = unsafe { get_window_state(this) };
1462    let mut lock = window_state.as_ref().lock();
1463
1464    let keystroke = Keystroke {
1465        modifiers: Default::default(),
1466        key: ".".into(),
1467        ime_key: None,
1468    };
1469    let event = PlatformInput::KeyDown(KeyDownEvent {
1470        keystroke: keystroke.clone(),
1471        is_held: false,
1472    });
1473
1474    lock.last_fresh_keydown = Some(keystroke);
1475    if let Some(mut callback) = lock.event_callback.take() {
1476        drop(lock);
1477        callback(event);
1478        window_state.lock().event_callback = Some(callback);
1479    }
1480}
1481
1482extern "C" fn window_did_change_occlusion_state(this: &Object, _: Sel, _: id) {
1483    let window_state = unsafe { get_window_state(this) };
1484    let lock = &mut *window_state.lock();
1485    unsafe {
1486        if lock
1487            .native_window
1488            .occlusionState()
1489            .contains(NSWindowOcclusionState::NSWindowOcclusionStateVisible)
1490        {
1491            lock.start_display_link();
1492        } else {
1493            lock.stop_display_link();
1494        }
1495    }
1496}
1497
1498extern "C" fn window_did_resize(this: &Object, _: Sel, _: id) {
1499    let window_state = unsafe { get_window_state(this) };
1500    window_state.as_ref().lock().move_traffic_light();
1501}
1502
1503extern "C" fn window_will_enter_fullscreen(this: &Object, _: Sel, _: id) {
1504    window_fullscreen_changed(this, true);
1505}
1506
1507extern "C" fn window_will_exit_fullscreen(this: &Object, _: Sel, _: id) {
1508    window_fullscreen_changed(this, false);
1509}
1510
1511fn window_fullscreen_changed(this: &Object, is_fullscreen: bool) {
1512    let window_state = unsafe { get_window_state(this) };
1513    let mut lock = window_state.as_ref().lock();
1514    if let Some(mut callback) = lock.fullscreen_callback.take() {
1515        drop(lock);
1516        callback(is_fullscreen);
1517        window_state.lock().fullscreen_callback = Some(callback);
1518    }
1519}
1520
1521extern "C" fn window_did_move(this: &Object, _: Sel, _: id) {
1522    let window_state = unsafe { get_window_state(this) };
1523    let mut lock = window_state.as_ref().lock();
1524    if let Some(mut callback) = lock.moved_callback.take() {
1525        drop(lock);
1526        callback();
1527        window_state.lock().moved_callback = Some(callback);
1528    }
1529}
1530
1531extern "C" fn window_did_change_screen(this: &Object, _: Sel, _: id) {
1532    let window_state = unsafe { get_window_state(this) };
1533    let mut lock = window_state.as_ref().lock();
1534    lock.start_display_link();
1535}
1536
1537extern "C" fn window_did_change_key_status(this: &Object, selector: Sel, _: id) {
1538    let window_state = unsafe { get_window_state(this) };
1539    let lock = window_state.lock();
1540    let is_active = unsafe { lock.native_window.isKeyWindow() == YES };
1541
1542    // When opening a pop-up while the application isn't active, Cocoa sends a spurious
1543    // `windowDidBecomeKey` message to the previous key window even though that window
1544    // isn't actually key. This causes a bug if the application is later activated while
1545    // the pop-up is still open, making it impossible to activate the previous key window
1546    // even if the pop-up gets closed. The only way to activate it again is to de-activate
1547    // the app and re-activate it, which is a pretty bad UX.
1548    // The following code detects the spurious event and invokes `resignKeyWindow`:
1549    // in theory, we're not supposed to invoke this method manually but it balances out
1550    // the spurious `becomeKeyWindow` event and helps us work around that bug.
1551    if selector == sel!(windowDidBecomeKey:) && !is_active {
1552        unsafe {
1553            let _: () = msg_send![lock.native_window, resignKeyWindow];
1554            return;
1555        }
1556    }
1557
1558    let executor = lock.executor.clone();
1559    drop(lock);
1560    executor
1561        .spawn(async move {
1562            let mut lock = window_state.as_ref().lock();
1563            if let Some(mut callback) = lock.activate_callback.take() {
1564                drop(lock);
1565                callback(is_active);
1566                window_state.lock().activate_callback = Some(callback);
1567            };
1568        })
1569        .detach();
1570}
1571
1572extern "C" fn window_should_close(this: &Object, _: Sel, _: id) -> BOOL {
1573    let window_state = unsafe { get_window_state(this) };
1574    let mut lock = window_state.as_ref().lock();
1575    if let Some(mut callback) = lock.should_close_callback.take() {
1576        drop(lock);
1577        let should_close = callback();
1578        window_state.lock().should_close_callback = Some(callback);
1579        should_close as BOOL
1580    } else {
1581        YES
1582    }
1583}
1584
1585extern "C" fn close_window(this: &Object, _: Sel) {
1586    unsafe {
1587        let close_callback = {
1588            let window_state = get_window_state(this);
1589            let mut lock = window_state.as_ref().lock();
1590            lock.close_callback.take()
1591        };
1592
1593        if let Some(callback) = close_callback {
1594            callback();
1595        }
1596
1597        let _: () = msg_send![super(this, class!(NSWindow)), close];
1598    }
1599}
1600
1601extern "C" fn make_backing_layer(this: &Object, _: Sel) -> id {
1602    let window_state = unsafe { get_window_state(this) };
1603    let window_state = window_state.as_ref().lock();
1604    window_state.renderer.layer_ptr() as id
1605}
1606
1607extern "C" fn view_did_change_backing_properties(this: &Object, _: Sel) {
1608    let window_state = unsafe { get_window_state(this) };
1609    let mut lock = window_state.as_ref().lock();
1610
1611    let scale_factor = lock.scale_factor() as f64;
1612    let size = lock.content_size();
1613    let drawable_size: NSSize = NSSize {
1614        width: f64::from(size.width) * scale_factor,
1615        height: f64::from(size.height) * scale_factor,
1616    };
1617    unsafe {
1618        let _: () = msg_send![
1619            lock.renderer.layer(),
1620            setContentsScale: scale_factor
1621        ];
1622    }
1623
1624    lock.update_drawable_size(drawable_size);
1625
1626    if let Some(mut callback) = lock.resize_callback.take() {
1627        let content_size = lock.content_size();
1628        let scale_factor = lock.scale_factor();
1629        drop(lock);
1630        callback(content_size, scale_factor);
1631        window_state.as_ref().lock().resize_callback = Some(callback);
1632    };
1633}
1634
1635extern "C" fn set_frame_size(this: &Object, _: Sel, size: NSSize) {
1636    let window_state = unsafe { get_window_state(this) };
1637    let mut lock = window_state.as_ref().lock();
1638
1639    if lock.content_size() == size.into() {
1640        return;
1641    }
1642
1643    unsafe {
1644        let _: () = msg_send![super(this, class!(NSView)), setFrameSize: size];
1645    }
1646
1647    let scale_factor = lock.scale_factor() as f64;
1648    let drawable_size: NSSize = NSSize {
1649        width: size.width * scale_factor,
1650        height: size.height * scale_factor,
1651    };
1652
1653    lock.update_drawable_size(drawable_size);
1654
1655    drop(lock);
1656    let mut lock = window_state.lock();
1657    if let Some(mut callback) = lock.resize_callback.take() {
1658        let content_size = lock.content_size();
1659        let scale_factor = lock.scale_factor();
1660        drop(lock);
1661        callback(content_size, scale_factor);
1662        window_state.lock().resize_callback = Some(callback);
1663    };
1664}
1665
1666extern "C" fn display_layer(this: &Object, _: Sel, _: id) {
1667    let window_state = unsafe { get_window_state(this) };
1668    let mut lock = window_state.lock();
1669    if let Some(mut callback) = lock.request_frame_callback.take() {
1670        #[cfg(not(feature = "macos-blade"))]
1671        lock.renderer.set_presents_with_transaction(true);
1672        lock.stop_display_link();
1673        drop(lock);
1674        callback();
1675
1676        let mut lock = window_state.lock();
1677        lock.request_frame_callback = Some(callback);
1678        #[cfg(not(feature = "macos-blade"))]
1679        lock.renderer.set_presents_with_transaction(false);
1680        lock.start_display_link();
1681    }
1682}
1683
1684unsafe extern "C" fn step(view: *mut c_void) {
1685    let view = view as id;
1686    let window_state = unsafe { get_window_state(&*view) };
1687    let mut lock = window_state.lock();
1688
1689    if let Some(mut callback) = lock.request_frame_callback.take() {
1690        drop(lock);
1691        callback();
1692        window_state.lock().request_frame_callback = Some(callback);
1693    }
1694}
1695
1696extern "C" fn valid_attributes_for_marked_text(_: &Object, _: Sel) -> id {
1697    unsafe { msg_send![class!(NSArray), array] }
1698}
1699
1700extern "C" fn has_marked_text(this: &Object, _: Sel) -> BOOL {
1701    with_input_handler(this, |input_handler| input_handler.marked_text_range())
1702        .flatten()
1703        .is_some() as BOOL
1704}
1705
1706extern "C" fn marked_range(this: &Object, _: Sel) -> NSRange {
1707    with_input_handler(this, |input_handler| input_handler.marked_text_range())
1708        .flatten()
1709        .map_or(NSRange::invalid(), |range| range.into())
1710}
1711
1712extern "C" fn selected_range(this: &Object, _: Sel) -> NSRange {
1713    with_input_handler(this, |input_handler| input_handler.selected_text_range())
1714        .flatten()
1715        .map_or(NSRange::invalid(), |range| range.into())
1716}
1717
1718extern "C" fn first_rect_for_character_range(
1719    this: &Object,
1720    _: Sel,
1721    range: NSRange,
1722    _: id,
1723) -> NSRect {
1724    let frame = unsafe {
1725        let window = get_window_state(this).lock().native_window;
1726        NSView::frame(window)
1727    };
1728    with_input_handler(this, |input_handler| {
1729        input_handler.bounds_for_range(range.to_range()?)
1730    })
1731    .flatten()
1732    .map_or(
1733        NSRect::new(NSPoint::new(0., 0.), NSSize::new(0., 0.)),
1734        |bounds| {
1735            NSRect::new(
1736                NSPoint::new(
1737                    frame.origin.x + bounds.origin.x.0 as f64,
1738                    frame.origin.y + frame.size.height
1739                        - bounds.origin.y.0 as f64
1740                        - bounds.size.height.0 as f64,
1741                ),
1742                NSSize::new(bounds.size.width.0 as f64, bounds.size.height.0 as f64),
1743            )
1744        },
1745    )
1746}
1747
1748extern "C" fn insert_text(this: &Object, _: Sel, text: id, replacement_range: NSRange) {
1749    unsafe {
1750        let is_attributed_string: BOOL =
1751            msg_send![text, isKindOfClass: [class!(NSAttributedString)]];
1752        let text: id = if is_attributed_string == YES {
1753            msg_send![text, string]
1754        } else {
1755            text
1756        };
1757        let text = CStr::from_ptr(text.UTF8String() as *mut c_char)
1758            .to_str()
1759            .unwrap();
1760        let replacement_range = replacement_range.to_range();
1761        send_to_input_handler(
1762            this,
1763            ImeInput::InsertText(text.to_string(), replacement_range),
1764        );
1765    }
1766}
1767
1768extern "C" fn set_marked_text(
1769    this: &Object,
1770    _: Sel,
1771    text: id,
1772    selected_range: NSRange,
1773    replacement_range: NSRange,
1774) {
1775    unsafe {
1776        let is_attributed_string: BOOL =
1777            msg_send![text, isKindOfClass: [class!(NSAttributedString)]];
1778        let text: id = if is_attributed_string == YES {
1779            msg_send![text, string]
1780        } else {
1781            text
1782        };
1783        let selected_range = selected_range.to_range();
1784        let replacement_range = replacement_range.to_range();
1785        let text = CStr::from_ptr(text.UTF8String() as *mut c_char)
1786            .to_str()
1787            .unwrap();
1788
1789        send_to_input_handler(
1790            this,
1791            ImeInput::SetMarkedText(text.to_string(), replacement_range, selected_range),
1792        );
1793    }
1794}
1795extern "C" fn unmark_text(this: &Object, _: Sel) {
1796    send_to_input_handler(this, ImeInput::UnmarkText);
1797}
1798
1799extern "C" fn attributed_substring_for_proposed_range(
1800    this: &Object,
1801    _: Sel,
1802    range: NSRange,
1803    _actual_range: *mut c_void,
1804) -> id {
1805    with_input_handler(this, |input_handler| {
1806        let range = range.to_range()?;
1807        if range.is_empty() {
1808            return None;
1809        }
1810
1811        let selected_text = input_handler.text_for_range(range)?;
1812        unsafe {
1813            let string: id = msg_send![class!(NSAttributedString), alloc];
1814            let string: id = msg_send![string, initWithString: ns_string(&selected_text)];
1815            Some(string)
1816        }
1817    })
1818    .flatten()
1819    .unwrap_or(nil)
1820}
1821
1822extern "C" fn do_command_by_selector(_: &Object, _: Sel, _: Sel) {}
1823
1824extern "C" fn view_did_change_effective_appearance(this: &Object, _: Sel) {
1825    unsafe {
1826        let state = get_window_state(this);
1827        let mut lock = state.as_ref().lock();
1828        if let Some(mut callback) = lock.appearance_changed_callback.take() {
1829            drop(lock);
1830            callback();
1831            state.lock().appearance_changed_callback = Some(callback);
1832        }
1833    }
1834}
1835
1836extern "C" fn accepts_first_mouse(this: &Object, _: Sel, _: id) -> BOOL {
1837    let window_state = unsafe { get_window_state(this) };
1838    let mut lock = window_state.as_ref().lock();
1839    lock.first_mouse = true;
1840    YES
1841}
1842
1843extern "C" fn dragging_entered(this: &Object, _: Sel, dragging_info: id) -> NSDragOperation {
1844    let window_state = unsafe { get_window_state(this) };
1845    let position = drag_event_position(&window_state, dragging_info);
1846    let paths = external_paths_from_event(dragging_info);
1847    if let Some(event) =
1848        paths.map(|paths| PlatformInput::FileDrop(FileDropEvent::Entered { position, paths }))
1849    {
1850        if send_new_event(&window_state, event) {
1851            window_state.lock().external_files_dragged = true;
1852            return NSDragOperationCopy;
1853        }
1854    }
1855    NSDragOperationNone
1856}
1857
1858extern "C" fn dragging_updated(this: &Object, _: Sel, dragging_info: id) -> NSDragOperation {
1859    let window_state = unsafe { get_window_state(this) };
1860    let position = drag_event_position(&window_state, dragging_info);
1861    if send_new_event(
1862        &window_state,
1863        PlatformInput::FileDrop(FileDropEvent::Pending { position }),
1864    ) {
1865        NSDragOperationCopy
1866    } else {
1867        NSDragOperationNone
1868    }
1869}
1870
1871extern "C" fn dragging_exited(this: &Object, _: Sel, _: id) {
1872    let window_state = unsafe { get_window_state(this) };
1873    send_new_event(
1874        &window_state,
1875        PlatformInput::FileDrop(FileDropEvent::Exited),
1876    );
1877    window_state.lock().external_files_dragged = false;
1878}
1879
1880extern "C" fn perform_drag_operation(this: &Object, _: Sel, dragging_info: id) -> BOOL {
1881    let window_state = unsafe { get_window_state(this) };
1882    let position = drag_event_position(&window_state, dragging_info);
1883    if send_new_event(
1884        &window_state,
1885        PlatformInput::FileDrop(FileDropEvent::Submit { position }),
1886    ) {
1887        YES
1888    } else {
1889        NO
1890    }
1891}
1892
1893fn external_paths_from_event(dragging_info: *mut Object) -> Option<ExternalPaths> {
1894    let mut paths = SmallVec::new();
1895    let pasteboard: id = unsafe { msg_send![dragging_info, draggingPasteboard] };
1896    let filenames = unsafe { NSPasteboard::propertyListForType(pasteboard, NSFilenamesPboardType) };
1897    if filenames == nil {
1898        return None;
1899    }
1900    for file in unsafe { filenames.iter() } {
1901        let path = unsafe {
1902            let f = NSString::UTF8String(file);
1903            CStr::from_ptr(f).to_string_lossy().into_owned()
1904        };
1905        paths.push(PathBuf::from(path))
1906    }
1907    Some(ExternalPaths(paths))
1908}
1909
1910extern "C" fn conclude_drag_operation(this: &Object, _: Sel, _: id) {
1911    let window_state = unsafe { get_window_state(this) };
1912    send_new_event(
1913        &window_state,
1914        PlatformInput::FileDrop(FileDropEvent::Exited),
1915    );
1916}
1917
1918extern "C" fn window_did_miniaturize(this: &Object, _: Sel, _: id) {
1919    let window_state = unsafe { get_window_state(this) };
1920
1921    window_state.lock().minimized = true;
1922}
1923
1924extern "C" fn window_did_deminiaturize(this: &Object, _: Sel, _: id) {
1925    let window_state = unsafe { get_window_state(this) };
1926
1927    window_state.lock().minimized = false;
1928}
1929
1930async fn synthetic_drag(
1931    window_state: Weak<Mutex<MacWindowState>>,
1932    drag_id: usize,
1933    event: MouseMoveEvent,
1934) {
1935    loop {
1936        Timer::after(Duration::from_millis(16)).await;
1937        if let Some(window_state) = window_state.upgrade() {
1938            let mut lock = window_state.lock();
1939            if lock.synthetic_drag_counter == drag_id {
1940                if let Some(mut callback) = lock.event_callback.take() {
1941                    drop(lock);
1942                    callback(PlatformInput::MouseMove(event.clone()));
1943                    window_state.lock().event_callback = Some(callback);
1944                }
1945            } else {
1946                break;
1947            }
1948        }
1949    }
1950}
1951
1952fn send_new_event(window_state_lock: &Mutex<MacWindowState>, e: PlatformInput) -> bool {
1953    let window_state = window_state_lock.lock().event_callback.take();
1954    if let Some(mut callback) = window_state {
1955        callback(e);
1956        window_state_lock.lock().event_callback = Some(callback);
1957        true
1958    } else {
1959        false
1960    }
1961}
1962
1963fn drag_event_position(window_state: &Mutex<MacWindowState>, dragging_info: id) -> Point<Pixels> {
1964    let drag_location: NSPoint = unsafe { msg_send![dragging_info, draggingLocation] };
1965    convert_mouse_position(drag_location, window_state.lock().content_size().height)
1966}
1967
1968fn with_input_handler<F, R>(window: &Object, f: F) -> Option<R>
1969where
1970    F: FnOnce(&mut PlatformInputHandler) -> R,
1971{
1972    let window_state = unsafe { get_window_state(window) };
1973    let mut lock = window_state.as_ref().lock();
1974    if let Some(mut input_handler) = lock.input_handler.take() {
1975        drop(lock);
1976        let result = f(&mut input_handler);
1977        window_state.lock().input_handler = Some(input_handler);
1978        Some(result)
1979    } else {
1980        None
1981    }
1982}
1983
1984fn send_to_input_handler(window: &Object, ime: ImeInput) {
1985    unsafe {
1986        let window_state = get_window_state(window);
1987        let mut lock = window_state.lock();
1988        if let Some(ime_input) = lock.input_during_keydown.as_mut() {
1989            ime_input.push(ime);
1990            return;
1991        }
1992        if let Some(mut input_handler) = lock.input_handler.take() {
1993            drop(lock);
1994            match ime {
1995                ImeInput::InsertText(text, range) => {
1996                    input_handler.replace_text_in_range(range, &text)
1997                }
1998                ImeInput::SetMarkedText(text, range, marked_range) => {
1999                    input_handler.replace_and_mark_text_in_range(range, &text, marked_range)
2000                }
2001                ImeInput::UnmarkText => input_handler.unmark_text(),
2002            }
2003            window_state.lock().input_handler = Some(input_handler);
2004        }
2005    }
2006}
2007
2008unsafe fn display_id_for_screen(screen: id) -> CGDirectDisplayID {
2009    let device_description = NSScreen::deviceDescription(screen);
2010    let screen_number_key: id = NSString::alloc(nil).init_str("NSScreenNumber");
2011    let screen_number = device_description.objectForKey_(screen_number_key);
2012    let screen_number: NSUInteger = msg_send![screen_number, unsignedIntegerValue];
2013    screen_number as CGDirectDisplayID
2014}