window.rs

   1use crate::{
   2    executor,
   3    geometry::{
   4        rect::RectF,
   5        vector::{vec2f, Vector2F},
   6    },
   7    keymap_matcher::Keystroke,
   8    mac::platform::NSViewLayerContentsRedrawDuringViewResize,
   9    platform::{
  10        self,
  11        mac::{geometry::RectFExt, renderer::Renderer, screen::Screen},
  12        Event, WindowBounds,
  13    },
  14    InputHandler, KeyDownEvent, ModifiersChangedEvent, MouseButton, MouseButtonEvent,
  15    MouseMovedEvent, Scene, WindowKind,
  16};
  17use block::ConcreteBlock;
  18use cocoa::{
  19    appkit::{
  20        CGPoint, NSApplication, NSBackingStoreBuffered, NSScreen, NSView, NSViewHeightSizable,
  21        NSViewWidthSizable, NSWindow, NSWindowButton, NSWindowCollectionBehavior,
  22        NSWindowStyleMask, NSWindowTitleVisibility,
  23    },
  24    base::{id, nil},
  25    foundation::{NSAutoreleasePool, NSInteger, NSPoint, NSRect, NSSize, NSString, NSUInteger},
  26};
  27use core_graphics::display::CGRect;
  28use ctor::ctor;
  29use foreign_types::ForeignTypeRef;
  30use objc::{
  31    class,
  32    declare::ClassDecl,
  33    msg_send,
  34    runtime::{Class, Object, Protocol, Sel, BOOL, NO, YES},
  35    sel, sel_impl,
  36};
  37use postage::oneshot;
  38use smol::Timer;
  39use std::{
  40    any::Any,
  41    cell::{Cell, RefCell},
  42    convert::TryInto,
  43    ffi::{c_void, CStr},
  44    mem,
  45    ops::Range,
  46    os::raw::c_char,
  47    ptr,
  48    rc::{Rc, Weak},
  49    sync::Arc,
  50    time::Duration,
  51};
  52
  53use super::{
  54    geometry::{NSRectExt, Vector2FExt},
  55    ns_string, NSRange,
  56};
  57
  58const WINDOW_STATE_IVAR: &str = "windowState";
  59
  60static mut WINDOW_CLASS: *const Class = ptr::null();
  61static mut PANEL_CLASS: *const Class = ptr::null();
  62static mut VIEW_CLASS: *const Class = ptr::null();
  63
  64#[allow(non_upper_case_globals)]
  65const NSWindowStyleMaskNonactivatingPanel: NSWindowStyleMask =
  66    unsafe { NSWindowStyleMask::from_bits_unchecked(1 << 7) };
  67#[allow(non_upper_case_globals)]
  68const NSNormalWindowLevel: NSInteger = 0;
  69#[allow(non_upper_case_globals)]
  70const NSPopUpWindowLevel: NSInteger = 101;
  71#[allow(non_upper_case_globals)]
  72const NSTrackingMouseEnteredAndExited: NSUInteger = 0x01;
  73#[allow(non_upper_case_globals)]
  74const NSTrackingMouseMoved: NSUInteger = 0x02;
  75#[allow(non_upper_case_globals)]
  76const NSTrackingActiveAlways: NSUInteger = 0x80;
  77#[allow(non_upper_case_globals)]
  78const NSTrackingInVisibleRect: NSUInteger = 0x200;
  79#[allow(non_upper_case_globals)]
  80const NSWindowAnimationBehaviorUtilityWindow: NSInteger = 4;
  81
  82#[ctor]
  83unsafe fn build_classes() {
  84    WINDOW_CLASS = build_window_class("GPUIWindow", class!(NSWindow));
  85    PANEL_CLASS = build_window_class("GPUIPanel", class!(NSPanel));
  86    VIEW_CLASS = {
  87        let mut decl = ClassDecl::new("GPUIView", class!(NSView)).unwrap();
  88        decl.add_ivar::<*mut c_void>(WINDOW_STATE_IVAR);
  89
  90        decl.add_method(sel!(dealloc), dealloc_view as extern "C" fn(&Object, Sel));
  91
  92        decl.add_method(
  93            sel!(performKeyEquivalent:),
  94            handle_key_equivalent as extern "C" fn(&Object, Sel, id) -> BOOL,
  95        );
  96        decl.add_method(
  97            sel!(keyDown:),
  98            handle_key_down as extern "C" fn(&Object, Sel, id),
  99        );
 100        decl.add_method(
 101            sel!(mouseDown:),
 102            handle_view_event as extern "C" fn(&Object, Sel, id),
 103        );
 104        decl.add_method(
 105            sel!(mouseUp:),
 106            handle_view_event as extern "C" fn(&Object, Sel, id),
 107        );
 108        decl.add_method(
 109            sel!(rightMouseDown:),
 110            handle_view_event as extern "C" fn(&Object, Sel, id),
 111        );
 112        decl.add_method(
 113            sel!(rightMouseUp:),
 114            handle_view_event as extern "C" fn(&Object, Sel, id),
 115        );
 116        decl.add_method(
 117            sel!(otherMouseDown:),
 118            handle_view_event as extern "C" fn(&Object, Sel, id),
 119        );
 120        decl.add_method(
 121            sel!(otherMouseUp:),
 122            handle_view_event as extern "C" fn(&Object, Sel, id),
 123        );
 124        decl.add_method(
 125            sel!(mouseMoved:),
 126            handle_view_event as extern "C" fn(&Object, Sel, id),
 127        );
 128        decl.add_method(
 129            sel!(mouseExited:),
 130            handle_view_event as extern "C" fn(&Object, Sel, id),
 131        );
 132        decl.add_method(
 133            sel!(mouseDragged:),
 134            handle_view_event as extern "C" fn(&Object, Sel, id),
 135        );
 136        decl.add_method(
 137            sel!(scrollWheel:),
 138            handle_view_event as extern "C" fn(&Object, Sel, id),
 139        );
 140        decl.add_method(
 141            sel!(flagsChanged:),
 142            handle_view_event as extern "C" fn(&Object, Sel, id),
 143        );
 144        decl.add_method(
 145            sel!(cancelOperation:),
 146            cancel_operation as extern "C" fn(&Object, Sel, id),
 147        );
 148
 149        decl.add_method(
 150            sel!(makeBackingLayer),
 151            make_backing_layer as extern "C" fn(&Object, Sel) -> id,
 152        );
 153
 154        decl.add_protocol(Protocol::get("CALayerDelegate").unwrap());
 155        decl.add_method(
 156            sel!(viewDidChangeBackingProperties),
 157            view_did_change_backing_properties as extern "C" fn(&Object, Sel),
 158        );
 159        decl.add_method(
 160            sel!(setFrameSize:),
 161            set_frame_size as extern "C" fn(&Object, Sel, NSSize),
 162        );
 163        decl.add_method(
 164            sel!(displayLayer:),
 165            display_layer as extern "C" fn(&Object, Sel, id),
 166        );
 167
 168        decl.add_protocol(Protocol::get("NSTextInputClient").unwrap());
 169        decl.add_method(
 170            sel!(validAttributesForMarkedText),
 171            valid_attributes_for_marked_text as extern "C" fn(&Object, Sel) -> id,
 172        );
 173        decl.add_method(
 174            sel!(hasMarkedText),
 175            has_marked_text as extern "C" fn(&Object, Sel) -> BOOL,
 176        );
 177        decl.add_method(
 178            sel!(markedRange),
 179            marked_range as extern "C" fn(&Object, Sel) -> NSRange,
 180        );
 181        decl.add_method(
 182            sel!(selectedRange),
 183            selected_range as extern "C" fn(&Object, Sel) -> NSRange,
 184        );
 185        decl.add_method(
 186            sel!(firstRectForCharacterRange:actualRange:),
 187            first_rect_for_character_range as extern "C" fn(&Object, Sel, NSRange, id) -> NSRect,
 188        );
 189        decl.add_method(
 190            sel!(insertText:replacementRange:),
 191            insert_text as extern "C" fn(&Object, Sel, id, NSRange),
 192        );
 193        decl.add_method(
 194            sel!(setMarkedText:selectedRange:replacementRange:),
 195            set_marked_text as extern "C" fn(&Object, Sel, id, NSRange, NSRange),
 196        );
 197        decl.add_method(sel!(unmarkText), unmark_text as extern "C" fn(&Object, Sel));
 198        decl.add_method(
 199            sel!(attributedSubstringForProposedRange:actualRange:),
 200            attributed_substring_for_proposed_range
 201                as extern "C" fn(&Object, Sel, NSRange, *mut c_void) -> id,
 202        );
 203        decl.add_method(
 204            sel!(viewDidChangeEffectiveAppearance),
 205            view_did_change_effective_appearance as extern "C" fn(&Object, Sel),
 206        );
 207
 208        // Suppress beep on keystrokes with modifier keys.
 209        decl.add_method(
 210            sel!(doCommandBySelector:),
 211            do_command_by_selector as extern "C" fn(&Object, Sel, Sel),
 212        );
 213
 214        decl.add_method(
 215            sel!(acceptsFirstMouse:),
 216            accepts_first_mouse as extern "C" fn(&Object, Sel, id) -> BOOL,
 217        );
 218
 219        decl.register()
 220    };
 221}
 222
 223unsafe fn build_window_class(name: &'static str, superclass: &Class) -> *const Class {
 224    let mut decl = ClassDecl::new(name, superclass).unwrap();
 225    decl.add_ivar::<*mut c_void>(WINDOW_STATE_IVAR);
 226    decl.add_method(sel!(dealloc), dealloc_window as extern "C" fn(&Object, Sel));
 227    decl.add_method(
 228        sel!(canBecomeMainWindow),
 229        yes as extern "C" fn(&Object, Sel) -> BOOL,
 230    );
 231    decl.add_method(
 232        sel!(canBecomeKeyWindow),
 233        yes as extern "C" fn(&Object, Sel) -> BOOL,
 234    );
 235    decl.add_method(
 236        sel!(sendEvent:),
 237        send_event as extern "C" fn(&Object, Sel, id),
 238    );
 239    decl.add_method(
 240        sel!(windowDidResize:),
 241        window_did_resize as extern "C" fn(&Object, Sel, id),
 242    );
 243    decl.add_method(
 244        sel!(windowWillEnterFullScreen:),
 245        window_will_enter_fullscreen as extern "C" fn(&Object, Sel, id),
 246    );
 247    decl.add_method(
 248        sel!(windowWillExitFullScreen:),
 249        window_will_exit_fullscreen as extern "C" fn(&Object, Sel, id),
 250    );
 251    decl.add_method(
 252        sel!(windowDidMove:),
 253        window_did_move as extern "C" fn(&Object, Sel, id),
 254    );
 255    decl.add_method(
 256        sel!(windowDidBecomeKey:),
 257        window_did_change_key_status as extern "C" fn(&Object, Sel, id),
 258    );
 259    decl.add_method(
 260        sel!(windowDidResignKey:),
 261        window_did_change_key_status as extern "C" fn(&Object, Sel, id),
 262    );
 263    decl.add_method(
 264        sel!(windowShouldClose:),
 265        window_should_close as extern "C" fn(&Object, Sel, id) -> BOOL,
 266    );
 267    decl.add_method(sel!(close), close_window as extern "C" fn(&Object, Sel));
 268    decl.register()
 269}
 270
 271///Used to track what the IME does when we send it a keystroke.
 272///This is only used to handle the case where the IME mysteriously
 273///swallows certain keys.
 274///
 275///Basically a direct copy of the approach that WezTerm uses in:
 276///github.com/wez/wezterm : d5755f3e : window/src/os/macos/window.rs
 277enum ImeState {
 278    Continue,
 279    Acted,
 280    None,
 281}
 282
 283struct InsertText {
 284    replacement_range: Option<Range<usize>>,
 285    text: String,
 286}
 287
 288struct WindowState {
 289    id: usize,
 290    native_window: id,
 291    kind: WindowKind,
 292    event_callback: Option<Box<dyn FnMut(Event) -> bool>>,
 293    activate_callback: Option<Box<dyn FnMut(bool)>>,
 294    resize_callback: Option<Box<dyn FnMut()>>,
 295    fullscreen_callback: Option<Box<dyn FnMut(bool)>>,
 296    moved_callback: Option<Box<dyn FnMut()>>,
 297    should_close_callback: Option<Box<dyn FnMut() -> bool>>,
 298    close_callback: Option<Box<dyn FnOnce()>>,
 299    appearance_changed_callback: Option<Box<dyn FnMut()>>,
 300    input_handler: Option<Box<dyn InputHandler>>,
 301    pending_key_down: Option<(KeyDownEvent, Option<InsertText>)>,
 302    performed_key_equivalent: bool,
 303    synthetic_drag_counter: usize,
 304    executor: Rc<executor::Foreground>,
 305    scene_to_render: Option<Scene>,
 306    renderer: Renderer,
 307    last_fresh_keydown: Option<Keystroke>,
 308    traffic_light_position: Option<Vector2F>,
 309    previous_modifiers_changed_event: Option<Event>,
 310    //State tracking what the IME did after the last request
 311    ime_state: ImeState,
 312    //Retains the last IME Text
 313    ime_text: Option<String>,
 314}
 315
 316impl WindowState {
 317    fn move_traffic_light(&self) {
 318        if let Some(traffic_light_position) = self.traffic_light_position {
 319            let titlebar_height = self.titlebar_height();
 320
 321            unsafe {
 322                let close_button: id = msg_send![
 323                    self.native_window,
 324                    standardWindowButton: NSWindowButton::NSWindowCloseButton
 325                ];
 326                let min_button: id = msg_send![
 327                    self.native_window,
 328                    standardWindowButton: NSWindowButton::NSWindowMiniaturizeButton
 329                ];
 330                let zoom_button: id = msg_send![
 331                    self.native_window,
 332                    standardWindowButton: NSWindowButton::NSWindowZoomButton
 333                ];
 334
 335                let mut close_button_frame: CGRect = msg_send![close_button, frame];
 336                let mut min_button_frame: CGRect = msg_send![min_button, frame];
 337                let mut zoom_button_frame: CGRect = msg_send![zoom_button, frame];
 338                let mut origin = vec2f(
 339                    traffic_light_position.x(),
 340                    titlebar_height
 341                        - traffic_light_position.y()
 342                        - close_button_frame.size.height as f32,
 343                );
 344                let button_spacing =
 345                    (min_button_frame.origin.x - close_button_frame.origin.x) as f32;
 346
 347                close_button_frame.origin = CGPoint::new(origin.x() as f64, origin.y() as f64);
 348                let _: () = msg_send![close_button, setFrame: close_button_frame];
 349                origin.set_x(origin.x() + button_spacing);
 350
 351                min_button_frame.origin = CGPoint::new(origin.x() as f64, origin.y() as f64);
 352                let _: () = msg_send![min_button, setFrame: min_button_frame];
 353                origin.set_x(origin.x() + button_spacing);
 354
 355                zoom_button_frame.origin = CGPoint::new(origin.x() as f64, origin.y() as f64);
 356                let _: () = msg_send![zoom_button, setFrame: zoom_button_frame];
 357            }
 358        }
 359    }
 360
 361    fn is_fullscreen(&self) -> bool {
 362        unsafe {
 363            let style_mask = self.native_window.styleMask();
 364            style_mask.contains(NSWindowStyleMask::NSFullScreenWindowMask)
 365        }
 366    }
 367
 368    fn bounds(&self) -> WindowBounds {
 369        unsafe {
 370            if self.is_fullscreen() {
 371                return WindowBounds::Fullscreen;
 372            }
 373
 374            let window_frame = self.frame();
 375            if window_frame == self.native_window.screen().visibleFrame().to_rectf() {
 376                WindowBounds::Maximized
 377            } else {
 378                WindowBounds::Fixed(window_frame)
 379            }
 380        }
 381    }
 382
 383    // Returns the window bounds in window coordinates
 384    fn frame(&self) -> RectF {
 385        unsafe {
 386            let ns_frame = NSWindow::frame(self.native_window);
 387            ns_frame.to_rectf()
 388        }
 389    }
 390
 391    fn content_size(&self) -> Vector2F {
 392        let NSSize { width, height, .. } =
 393            unsafe { NSView::frame(self.native_window.contentView()) }.size;
 394        vec2f(width as f32, height as f32)
 395    }
 396
 397    fn scale_factor(&self) -> f32 {
 398        get_scale_factor(self.native_window)
 399    }
 400
 401    fn titlebar_height(&self) -> f32 {
 402        unsafe {
 403            let frame = NSWindow::frame(self.native_window);
 404            let content_layout_rect: CGRect = msg_send![self.native_window, contentLayoutRect];
 405            (frame.size.height - content_layout_rect.size.height) as f32
 406        }
 407    }
 408
 409    fn present_scene(&mut self, scene: Scene) {
 410        self.scene_to_render = Some(scene);
 411        unsafe {
 412            let _: () = msg_send![self.native_window.contentView(), setNeedsDisplay: YES];
 413        }
 414    }
 415}
 416
 417pub struct Window(Rc<RefCell<WindowState>>);
 418
 419impl Window {
 420    pub fn open(
 421        id: usize,
 422        options: platform::WindowOptions,
 423        executor: Rc<executor::Foreground>,
 424        fonts: Arc<dyn platform::FontSystem>,
 425    ) -> Self {
 426        unsafe {
 427            let pool = NSAutoreleasePool::new(nil);
 428
 429            let mut style_mask;
 430            if let Some(titlebar) = options.titlebar.as_ref() {
 431                style_mask = NSWindowStyleMask::NSClosableWindowMask
 432                    | NSWindowStyleMask::NSMiniaturizableWindowMask
 433                    | NSWindowStyleMask::NSResizableWindowMask
 434                    | NSWindowStyleMask::NSTitledWindowMask;
 435
 436                if titlebar.appears_transparent {
 437                    style_mask |= NSWindowStyleMask::NSFullSizeContentViewWindowMask;
 438                }
 439            } else {
 440                style_mask = NSWindowStyleMask::NSTitledWindowMask
 441                    | NSWindowStyleMask::NSFullSizeContentViewWindowMask;
 442            }
 443
 444            let native_window: id = match options.kind {
 445                WindowKind::Normal => msg_send![WINDOW_CLASS, alloc],
 446                WindowKind::PopUp => {
 447                    style_mask |= NSWindowStyleMaskNonactivatingPanel;
 448                    msg_send![PANEL_CLASS, alloc]
 449                }
 450            };
 451            let native_window = native_window.initWithContentRect_styleMask_backing_defer_screen_(
 452                NSRect::new(NSPoint::new(0., 0.), NSSize::new(1024., 768.)),
 453                style_mask,
 454                NSBackingStoreBuffered,
 455                NO,
 456                options
 457                    .screen
 458                    .and_then(|screen| {
 459                        Some(screen.as_any().downcast_ref::<Screen>()?.native_screen)
 460                    })
 461                    .unwrap_or(nil),
 462            );
 463            assert!(!native_window.is_null());
 464
 465            let screen = native_window.screen();
 466            match options.bounds {
 467                WindowBounds::Fullscreen => {
 468                    native_window.toggleFullScreen_(nil);
 469                }
 470                WindowBounds::Maximized => {
 471                    native_window.setFrame_display_(screen.visibleFrame(), YES);
 472                }
 473                WindowBounds::Fixed(rect) => {
 474                    let screen_frame = screen.visibleFrame();
 475                    let ns_rect = rect.to_ns_rect();
 476                    if ns_rect.intersects(screen_frame) {
 477                        native_window.setFrame_display_(ns_rect, YES);
 478                    } else {
 479                        native_window.setFrame_display_(screen_frame, YES);
 480                    }
 481                }
 482            }
 483
 484            let native_view: id = msg_send![VIEW_CLASS, alloc];
 485            let native_view = NSView::init(native_view);
 486
 487            assert!(!native_view.is_null());
 488
 489            let window = Self(Rc::new(RefCell::new(WindowState {
 490                id,
 491                native_window,
 492                kind: options.kind,
 493                event_callback: None,
 494                resize_callback: None,
 495                should_close_callback: None,
 496                close_callback: None,
 497                activate_callback: None,
 498                fullscreen_callback: None,
 499                moved_callback: None,
 500                appearance_changed_callback: None,
 501                input_handler: None,
 502                pending_key_down: None,
 503                performed_key_equivalent: false,
 504                synthetic_drag_counter: 0,
 505                executor,
 506                scene_to_render: Default::default(),
 507                renderer: Renderer::new(true, fonts),
 508                last_fresh_keydown: None,
 509                traffic_light_position: options
 510                    .titlebar
 511                    .as_ref()
 512                    .and_then(|titlebar| titlebar.traffic_light_position),
 513                previous_modifiers_changed_event: None,
 514                ime_state: ImeState::None,
 515                ime_text: None,
 516            })));
 517
 518            (*native_window).set_ivar(
 519                WINDOW_STATE_IVAR,
 520                Rc::into_raw(window.0.clone()) as *const c_void,
 521            );
 522            native_window.setDelegate_(native_window);
 523            (*native_view).set_ivar(
 524                WINDOW_STATE_IVAR,
 525                Rc::into_raw(window.0.clone()) as *const c_void,
 526            );
 527
 528            if let Some(title) = options.titlebar.as_ref().and_then(|t| t.title) {
 529                native_window.setTitle_(NSString::alloc(nil).init_str(title));
 530            }
 531
 532            native_window.setMovable_(options.is_movable as BOOL);
 533
 534            if options
 535                .titlebar
 536                .map_or(true, |titlebar| titlebar.appears_transparent)
 537            {
 538                native_window.setTitlebarAppearsTransparent_(YES);
 539                native_window.setTitleVisibility_(NSWindowTitleVisibility::NSWindowTitleHidden);
 540            }
 541
 542            native_view.setAutoresizingMask_(NSViewWidthSizable | NSViewHeightSizable);
 543            native_view.setWantsBestResolutionOpenGLSurface_(YES);
 544
 545            // From winit crate: On Mojave, views automatically become layer-backed shortly after
 546            // being added to a native_window. Changing the layer-backedness of a view breaks the
 547            // association between the view and its associated OpenGL context. To work around this,
 548            // on we explicitly make the view layer-backed up front so that AppKit doesn't do it
 549            // itself and break the association with its context.
 550            native_view.setWantsLayer(YES);
 551            let _: () = msg_send![
 552                native_view,
 553                setLayerContentsRedrawPolicy: NSViewLayerContentsRedrawDuringViewResize
 554            ];
 555
 556            native_window.setContentView_(native_view.autorelease());
 557            native_window.makeFirstResponder_(native_view);
 558
 559            if options.center {
 560                native_window.center();
 561            }
 562
 563            match options.kind {
 564                WindowKind::Normal => {
 565                    native_window.setLevel_(NSNormalWindowLevel);
 566                    native_window.setAcceptsMouseMovedEvents_(YES);
 567                }
 568                WindowKind::PopUp => {
 569                    // Use a tracking area to allow receiving MouseMoved events even when
 570                    // the window or application aren't active, which is often the case
 571                    // e.g. for notification windows.
 572                    let tracking_area: id = msg_send![class!(NSTrackingArea), alloc];
 573                    let _: () = msg_send![
 574                        tracking_area,
 575                        initWithRect: NSRect::new(NSPoint::new(0., 0.), NSSize::new(0., 0.))
 576                        options: NSTrackingMouseEnteredAndExited | NSTrackingMouseMoved | NSTrackingActiveAlways | NSTrackingInVisibleRect
 577                        owner: native_view
 578                        userInfo: nil
 579                    ];
 580                    let _: () =
 581                        msg_send![native_view, addTrackingArea: tracking_area.autorelease()];
 582
 583                    native_window.setLevel_(NSPopUpWindowLevel);
 584                    let _: () = msg_send![
 585                        native_window,
 586                        setAnimationBehavior: NSWindowAnimationBehaviorUtilityWindow
 587                    ];
 588                    native_window.setCollectionBehavior_(
 589                        NSWindowCollectionBehavior::NSWindowCollectionBehaviorCanJoinAllSpaces |
 590                        NSWindowCollectionBehavior::NSWindowCollectionBehaviorFullScreenAuxiliary
 591                    );
 592                }
 593            }
 594            if options.focus {
 595                native_window.makeKeyAndOrderFront_(nil);
 596            } else {
 597                native_window.orderFront_(nil);
 598            }
 599
 600            window.0.borrow().move_traffic_light();
 601            pool.drain();
 602
 603            window
 604        }
 605    }
 606
 607    pub fn main_window_id() -> Option<usize> {
 608        unsafe {
 609            let app = NSApplication::sharedApplication(nil);
 610            let main_window: id = msg_send![app, mainWindow];
 611            if msg_send![main_window, isKindOfClass: WINDOW_CLASS] {
 612                let id = get_window_state(&*main_window).borrow().id;
 613                Some(id)
 614            } else {
 615                None
 616            }
 617        }
 618    }
 619}
 620
 621impl Drop for Window {
 622    fn drop(&mut self) {
 623        let this = self.0.borrow();
 624        let window = this.native_window;
 625        this.executor
 626            .spawn(async move {
 627                unsafe {
 628                    window.close();
 629                }
 630            })
 631            .detach();
 632    }
 633}
 634
 635impl platform::Window for Window {
 636    fn bounds(&self) -> WindowBounds {
 637        self.0.as_ref().borrow().bounds()
 638    }
 639
 640    fn content_size(&self) -> Vector2F {
 641        self.0.as_ref().borrow().content_size()
 642    }
 643
 644    fn scale_factor(&self) -> f32 {
 645        self.0.as_ref().borrow().scale_factor()
 646    }
 647
 648    fn titlebar_height(&self) -> f32 {
 649        self.0.as_ref().borrow().titlebar_height()
 650    }
 651
 652    fn appearance(&self) -> crate::Appearance {
 653        unsafe {
 654            let appearance: id = msg_send![self.0.borrow().native_window, effectiveAppearance];
 655            crate::Appearance::from_native(appearance)
 656        }
 657    }
 658
 659    fn screen(&self) -> Rc<dyn crate::Screen> {
 660        unsafe {
 661            Rc::new(Screen {
 662                native_screen: self.0.as_ref().borrow().native_window.screen(),
 663            })
 664        }
 665    }
 666
 667    fn as_any_mut(&mut self) -> &mut dyn Any {
 668        self
 669    }
 670
 671    fn set_input_handler(&mut self, input_handler: Box<dyn InputHandler>) {
 672        self.0.as_ref().borrow_mut().input_handler = Some(input_handler);
 673    }
 674
 675    fn prompt(
 676        &self,
 677        level: platform::PromptLevel,
 678        msg: &str,
 679        answers: &[&str],
 680    ) -> oneshot::Receiver<usize> {
 681        unsafe {
 682            let alert: id = msg_send![class!(NSAlert), alloc];
 683            let alert: id = msg_send![alert, init];
 684            let alert_style = match level {
 685                platform::PromptLevel::Info => 1,
 686                platform::PromptLevel::Warning => 0,
 687                platform::PromptLevel::Critical => 2,
 688            };
 689            let _: () = msg_send![alert, setAlertStyle: alert_style];
 690            let _: () = msg_send![alert, setMessageText: ns_string(msg)];
 691            for (ix, answer) in answers.iter().enumerate() {
 692                let button: id = msg_send![alert, addButtonWithTitle: ns_string(answer)];
 693                let _: () = msg_send![button, setTag: ix as NSInteger];
 694            }
 695            let (done_tx, done_rx) = oneshot::channel();
 696            let done_tx = Cell::new(Some(done_tx));
 697            let block = ConcreteBlock::new(move |answer: NSInteger| {
 698                if let Some(mut done_tx) = done_tx.take() {
 699                    let _ = postage::sink::Sink::try_send(&mut done_tx, answer.try_into().unwrap());
 700                }
 701            });
 702            let block = block.copy();
 703            let native_window = self.0.borrow().native_window;
 704            self.0
 705                .borrow()
 706                .executor
 707                .spawn(async move {
 708                    let _: () = msg_send![
 709                        alert,
 710                        beginSheetModalForWindow: native_window
 711                        completionHandler: block
 712                    ];
 713                })
 714                .detach();
 715
 716            done_rx
 717        }
 718    }
 719
 720    fn activate(&self) {
 721        let window = self.0.borrow().native_window;
 722        self.0
 723            .borrow()
 724            .executor
 725            .spawn(async move {
 726                unsafe {
 727                    let _: () = msg_send![window, makeKeyAndOrderFront: nil];
 728                }
 729            })
 730            .detach();
 731    }
 732
 733    fn set_title(&mut self, title: &str) {
 734        unsafe {
 735            let app = NSApplication::sharedApplication(nil);
 736            let window = self.0.borrow().native_window;
 737            let title = ns_string(title);
 738            let _: () = msg_send![app, changeWindowsItem:window title:title filename:false];
 739            let _: () = msg_send![window, setTitle: title];
 740            self.0.borrow().move_traffic_light();
 741        }
 742    }
 743
 744    fn set_edited(&mut self, edited: bool) {
 745        unsafe {
 746            let window = self.0.borrow().native_window;
 747            msg_send![window, setDocumentEdited: edited as BOOL]
 748        }
 749
 750        // Changing the document edited state resets the traffic light position,
 751        // so we have to move it again.
 752        self.0.borrow().move_traffic_light();
 753    }
 754
 755    fn show_character_palette(&self) {
 756        unsafe {
 757            let app = NSApplication::sharedApplication(nil);
 758            let window = self.0.borrow().native_window;
 759            let _: () = msg_send![app, orderFrontCharacterPalette: window];
 760        }
 761    }
 762
 763    fn minimize(&self) {
 764        let window = self.0.borrow().native_window;
 765        unsafe {
 766            window.miniaturize_(nil);
 767        }
 768    }
 769
 770    fn zoom(&self) {
 771        let this = self.0.borrow();
 772        let window = this.native_window;
 773        this.executor
 774            .spawn(async move {
 775                unsafe {
 776                    window.zoom_(nil);
 777                }
 778            })
 779            .detach();
 780    }
 781
 782    fn present_scene(&mut self, scene: Scene) {
 783        self.0.as_ref().borrow_mut().present_scene(scene);
 784    }
 785
 786    fn toggle_full_screen(&self) {
 787        let this = self.0.borrow();
 788        let window = this.native_window;
 789        this.executor
 790            .spawn(async move {
 791                unsafe {
 792                    window.toggleFullScreen_(nil);
 793                }
 794            })
 795            .detach();
 796    }
 797
 798    fn on_event(&mut self, callback: Box<dyn FnMut(Event) -> bool>) {
 799        self.0.as_ref().borrow_mut().event_callback = Some(callback);
 800    }
 801
 802    fn on_active_status_change(&mut self, callback: Box<dyn FnMut(bool)>) {
 803        self.0.as_ref().borrow_mut().activate_callback = Some(callback);
 804    }
 805
 806    fn on_resize(&mut self, callback: Box<dyn FnMut()>) {
 807        self.0.as_ref().borrow_mut().resize_callback = Some(callback);
 808    }
 809
 810    fn on_fullscreen(&mut self, callback: Box<dyn FnMut(bool)>) {
 811        self.0.as_ref().borrow_mut().fullscreen_callback = Some(callback);
 812    }
 813
 814    fn on_moved(&mut self, callback: Box<dyn FnMut()>) {
 815        self.0.as_ref().borrow_mut().moved_callback = Some(callback);
 816    }
 817
 818    fn on_should_close(&mut self, callback: Box<dyn FnMut() -> bool>) {
 819        self.0.as_ref().borrow_mut().should_close_callback = Some(callback);
 820    }
 821
 822    fn on_close(&mut self, callback: Box<dyn FnOnce()>) {
 823        self.0.as_ref().borrow_mut().close_callback = Some(callback);
 824    }
 825
 826    fn on_appearance_changed(&mut self, callback: Box<dyn FnMut()>) {
 827        self.0.borrow_mut().appearance_changed_callback = Some(callback);
 828    }
 829
 830    fn is_topmost_for_position(&self, position: Vector2F) -> bool {
 831        let self_borrow = self.0.borrow();
 832        let self_id = self_borrow.id;
 833
 834        unsafe {
 835            let app = NSApplication::sharedApplication(nil);
 836
 837            // Convert back to screen coordinates
 838            let screen_point = position.to_screen_ns_point(
 839                self_borrow.native_window,
 840                self_borrow.content_size().y() as f64,
 841            );
 842
 843            let window_number: NSInteger = msg_send![class!(NSWindow), windowNumberAtPoint:screen_point belowWindowWithWindowNumber:0];
 844            let top_most_window: id = msg_send![app, windowWithWindowNumber: window_number];
 845
 846            let is_panel: BOOL = msg_send![top_most_window, isKindOfClass: PANEL_CLASS];
 847            let is_window: BOOL = msg_send![top_most_window, isKindOfClass: WINDOW_CLASS];
 848            if is_panel == YES || is_window == YES {
 849                let topmost_window_id = get_window_state(&*top_most_window).borrow().id;
 850                topmost_window_id == self_id
 851            } else {
 852                // Someone else's window is on top
 853                false
 854            }
 855        }
 856    }
 857}
 858
 859fn get_scale_factor(native_window: id) -> f32 {
 860    unsafe {
 861        let screen: id = msg_send![native_window, screen];
 862        NSScreen::backingScaleFactor(screen) as f32
 863    }
 864}
 865
 866unsafe fn get_window_state(object: &Object) -> Rc<RefCell<WindowState>> {
 867    let raw: *mut c_void = *object.get_ivar(WINDOW_STATE_IVAR);
 868    let rc1 = Rc::from_raw(raw as *mut RefCell<WindowState>);
 869    let rc2 = rc1.clone();
 870    mem::forget(rc1);
 871    rc2
 872}
 873
 874unsafe fn drop_window_state(object: &Object) {
 875    let raw: *mut c_void = *object.get_ivar(WINDOW_STATE_IVAR);
 876    Rc::from_raw(raw as *mut RefCell<WindowState>);
 877}
 878
 879extern "C" fn yes(_: &Object, _: Sel) -> BOOL {
 880    YES
 881}
 882
 883extern "C" fn dealloc_window(this: &Object, _: Sel) {
 884    unsafe {
 885        drop_window_state(this);
 886        let _: () = msg_send![super(this, class!(NSWindow)), dealloc];
 887    }
 888}
 889
 890extern "C" fn dealloc_view(this: &Object, _: Sel) {
 891    unsafe {
 892        drop_window_state(this);
 893        let _: () = msg_send![super(this, class!(NSView)), dealloc];
 894    }
 895}
 896
 897extern "C" fn handle_key_equivalent(this: &Object, _: Sel, native_event: id) -> BOOL {
 898    handle_key_event(this, native_event, true)
 899}
 900
 901extern "C" fn handle_key_down(this: &Object, _: Sel, native_event: id) {
 902    handle_key_event(this, native_event, false);
 903}
 904
 905extern "C" fn handle_key_event(this: &Object, native_event: id, key_equivalent: bool) -> BOOL {
 906    let window_state = unsafe { get_window_state(this) };
 907    let mut window_state_borrow = window_state.as_ref().borrow_mut();
 908
 909    let window_height = window_state_borrow.content_size().y();
 910    let event = unsafe { Event::from_native(native_event, Some(window_height)) };
 911
 912    if let Some(event) = event {
 913        if key_equivalent {
 914            window_state_borrow.performed_key_equivalent = true;
 915        } else if window_state_borrow.performed_key_equivalent {
 916            return NO;
 917        }
 918
 919        let function_is_held;
 920        window_state_borrow.pending_key_down = match event {
 921            Event::KeyDown(event) => {
 922                let keydown = event.keystroke.clone();
 923                // Ignore events from held-down keys after some of the initially-pressed keys
 924                // were released.
 925                if event.is_held {
 926                    if window_state_borrow.last_fresh_keydown.as_ref() != Some(&keydown) {
 927                        return YES;
 928                    }
 929                } else {
 930                    window_state_borrow.last_fresh_keydown = Some(keydown);
 931                }
 932                function_is_held = event.keystroke.function;
 933                Some((event, None))
 934            }
 935
 936            _ => return NO,
 937        };
 938
 939        drop(window_state_borrow);
 940
 941        if !function_is_held {
 942            unsafe {
 943                let input_context: id = msg_send![this, inputContext];
 944                let _: BOOL = msg_send![input_context, handleEvent: native_event];
 945            }
 946        }
 947
 948        let mut handled = false;
 949        let mut window_state_borrow = window_state.borrow_mut();
 950        let ime_text = window_state_borrow.ime_text.clone();
 951        if let Some((event, insert_text)) = window_state_borrow.pending_key_down.take() {
 952            let is_held = event.is_held;
 953            if let Some(mut callback) = window_state_borrow.event_callback.take() {
 954                drop(window_state_borrow);
 955
 956                let is_composing =
 957                    with_input_handler(this, |input_handler| input_handler.marked_text_range())
 958                        .flatten()
 959                        .is_some();
 960                if !is_composing {
 961                    handled = callback(Event::KeyDown(event));
 962                }
 963
 964                if !handled {
 965                    if let Some(insert) = insert_text {
 966                        handled = true;
 967                        with_input_handler(this, |input_handler| {
 968                            input_handler
 969                                .replace_text_in_range(insert.replacement_range, &insert.text)
 970                        });
 971                    } else if !is_composing && is_held {
 972                        if let Some(last_insert_text) = ime_text {
 973                            //MacOS IME is a bit funky, and even when you've told it there's nothing to
 974                            //inter it will still swallow certain keys (e.g. 'f', 'j') and not others
 975                            //(e.g. 'n'). This is a problem for certain kinds of views, like the terminal
 976                            with_input_handler(this, |input_handler| {
 977                                if input_handler.selected_text_range().is_none() {
 978                                    handled = true;
 979                                    input_handler.replace_text_in_range(None, &last_insert_text)
 980                                }
 981                            });
 982                        }
 983                    }
 984                }
 985
 986                window_state.borrow_mut().event_callback = Some(callback);
 987            }
 988        } else {
 989            handled = true;
 990        }
 991
 992        handled as BOOL
 993    } else {
 994        NO
 995    }
 996}
 997
 998extern "C" fn handle_view_event(this: &Object, _: Sel, native_event: id) {
 999    let window_state = unsafe { get_window_state(this) };
1000    let weak_window_state = Rc::downgrade(&window_state);
1001    let mut window_state_borrow = window_state.as_ref().borrow_mut();
1002    let is_active = unsafe { window_state_borrow.native_window.isKeyWindow() == YES };
1003
1004    let window_height = window_state_borrow.content_size().y();
1005    let event = unsafe { Event::from_native(native_event, Some(window_height)) };
1006    if let Some(event) = event {
1007        match &event {
1008            Event::MouseMoved(
1009                event @ MouseMovedEvent {
1010                    pressed_button: Some(_),
1011                    ..
1012                },
1013            ) => {
1014                window_state_borrow.synthetic_drag_counter += 1;
1015                window_state_borrow
1016                    .executor
1017                    .spawn(synthetic_drag(
1018                        weak_window_state,
1019                        window_state_borrow.synthetic_drag_counter,
1020                        *event,
1021                    ))
1022                    .detach();
1023            }
1024
1025            Event::MouseMoved(_)
1026                if !(is_active || window_state_borrow.kind == WindowKind::PopUp) =>
1027            {
1028                return
1029            }
1030
1031            Event::MouseUp(MouseButtonEvent {
1032                button: MouseButton::Left,
1033                ..
1034            }) => {
1035                window_state_borrow.synthetic_drag_counter += 1;
1036            }
1037
1038            Event::ModifiersChanged(ModifiersChangedEvent { modifiers }) => {
1039                // Only raise modifiers changed event when they have actually changed
1040                if let Some(Event::ModifiersChanged(ModifiersChangedEvent {
1041                    modifiers: prev_modifiers,
1042                })) = &window_state_borrow.previous_modifiers_changed_event
1043                {
1044                    if prev_modifiers == modifiers {
1045                        return;
1046                    }
1047                }
1048
1049                window_state_borrow.previous_modifiers_changed_event = Some(event.clone());
1050            }
1051
1052            _ => {}
1053        }
1054
1055        if let Some(mut callback) = window_state_borrow.event_callback.take() {
1056            drop(window_state_borrow);
1057            callback(event);
1058            window_state.borrow_mut().event_callback = Some(callback);
1059        }
1060    }
1061}
1062
1063// Allows us to receive `cmd-.` (the shortcut for closing a dialog)
1064// https://bugs.eclipse.org/bugs/show_bug.cgi?id=300620#c6
1065extern "C" fn cancel_operation(this: &Object, _sel: Sel, _sender: id) {
1066    let window_state = unsafe { get_window_state(this) };
1067    let mut window_state_borrow = window_state.as_ref().borrow_mut();
1068
1069    let keystroke = Keystroke {
1070        cmd: true,
1071        ctrl: false,
1072        alt: false,
1073        shift: false,
1074        function: false,
1075        key: ".".into(),
1076    };
1077    let event = Event::KeyDown(KeyDownEvent {
1078        keystroke: keystroke.clone(),
1079        is_held: false,
1080    });
1081
1082    window_state_borrow.last_fresh_keydown = Some(keystroke);
1083    if let Some(mut callback) = window_state_borrow.event_callback.take() {
1084        drop(window_state_borrow);
1085        callback(event);
1086        window_state.borrow_mut().event_callback = Some(callback);
1087    }
1088}
1089
1090extern "C" fn send_event(this: &Object, _: Sel, native_event: id) {
1091    unsafe {
1092        let _: () = msg_send![super(this, class!(NSWindow)), sendEvent: native_event];
1093        get_window_state(this).borrow_mut().performed_key_equivalent = false;
1094    }
1095}
1096
1097extern "C" fn window_did_resize(this: &Object, _: Sel, _: id) {
1098    let window_state = unsafe { get_window_state(this) };
1099    window_state.as_ref().borrow().move_traffic_light();
1100}
1101
1102extern "C" fn window_will_enter_fullscreen(this: &Object, _: Sel, _: id) {
1103    window_fullscreen_changed(this, true);
1104}
1105
1106extern "C" fn window_will_exit_fullscreen(this: &Object, _: Sel, _: id) {
1107    window_fullscreen_changed(this, false);
1108}
1109
1110fn window_fullscreen_changed(this: &Object, is_fullscreen: bool) {
1111    let window_state = unsafe { get_window_state(this) };
1112    let mut window_state_borrow = window_state.as_ref().borrow_mut();
1113    if let Some(mut callback) = window_state_borrow.fullscreen_callback.take() {
1114        drop(window_state_borrow);
1115        callback(is_fullscreen);
1116        window_state.borrow_mut().fullscreen_callback = Some(callback);
1117    }
1118}
1119
1120extern "C" fn window_did_move(this: &Object, _: Sel, _: id) {
1121    let window_state = unsafe { get_window_state(this) };
1122    let mut window_state_borrow = window_state.as_ref().borrow_mut();
1123    if let Some(mut callback) = window_state_borrow.moved_callback.take() {
1124        drop(window_state_borrow);
1125        callback();
1126        window_state.borrow_mut().moved_callback = Some(callback);
1127    }
1128}
1129
1130extern "C" fn window_did_change_key_status(this: &Object, selector: Sel, _: id) {
1131    let window_state = unsafe { get_window_state(this) };
1132    let window_state_borrow = window_state.borrow();
1133    let is_active = unsafe { window_state_borrow.native_window.isKeyWindow() == YES };
1134
1135    // When opening a pop-up while the application isn't active, Cocoa sends a spurious
1136    // `windowDidBecomeKey` message to the previous key window even though that window
1137    // isn't actually key. This causes a bug if the application is later activated while
1138    // the pop-up is still open, making it impossible to activate the previous key window
1139    // even if the pop-up gets closed. The only way to activate it again is to de-activate
1140    // the app and re-activate it, which is a pretty bad UX.
1141    // The following code detects the spurious event and invokes `resignKeyWindow`:
1142    // in theory, we're not supposed to invoke this method manually but it balances out
1143    // the spurious `becomeKeyWindow` event and helps us work around that bug.
1144    if selector == sel!(windowDidBecomeKey:) {
1145        if !is_active {
1146            unsafe {
1147                let _: () = msg_send![window_state_borrow.native_window, resignKeyWindow];
1148                return;
1149            }
1150        }
1151    }
1152
1153    let executor = window_state_borrow.executor.clone();
1154    drop(window_state_borrow);
1155    executor
1156        .spawn(async move {
1157            let mut window_state_borrow = window_state.as_ref().borrow_mut();
1158            if let Some(mut callback) = window_state_borrow.activate_callback.take() {
1159                drop(window_state_borrow);
1160                callback(is_active);
1161                window_state.borrow_mut().activate_callback = Some(callback);
1162            };
1163        })
1164        .detach();
1165}
1166
1167extern "C" fn window_should_close(this: &Object, _: Sel, _: id) -> BOOL {
1168    let window_state = unsafe { get_window_state(this) };
1169    let mut window_state_borrow = window_state.as_ref().borrow_mut();
1170    if let Some(mut callback) = window_state_borrow.should_close_callback.take() {
1171        drop(window_state_borrow);
1172        let should_close = callback();
1173        window_state.borrow_mut().should_close_callback = Some(callback);
1174        should_close as BOOL
1175    } else {
1176        YES
1177    }
1178}
1179
1180extern "C" fn close_window(this: &Object, _: Sel) {
1181    unsafe {
1182        let close_callback = {
1183            let window_state = get_window_state(this);
1184            window_state
1185                .as_ref()
1186                .try_borrow_mut()
1187                .ok()
1188                .and_then(|mut window_state| window_state.close_callback.take())
1189        };
1190
1191        if let Some(callback) = close_callback {
1192            callback();
1193        }
1194
1195        let _: () = msg_send![super(this, class!(NSWindow)), close];
1196    }
1197}
1198
1199extern "C" fn make_backing_layer(this: &Object, _: Sel) -> id {
1200    let window_state = unsafe { get_window_state(this) };
1201    let window_state = window_state.as_ref().borrow();
1202    window_state.renderer.layer().as_ptr() as id
1203}
1204
1205extern "C" fn view_did_change_backing_properties(this: &Object, _: Sel) {
1206    let window_state = unsafe { get_window_state(this) };
1207    let mut window_state_borrow = window_state.as_ref().borrow_mut();
1208
1209    unsafe {
1210        let scale_factor = window_state_borrow.scale_factor() as f64;
1211        let size = window_state_borrow.content_size();
1212        let drawable_size: NSSize = NSSize {
1213            width: size.x() as f64 * scale_factor,
1214            height: size.y() as f64 * scale_factor,
1215        };
1216
1217        let _: () = msg_send![
1218            window_state_borrow.renderer.layer(),
1219            setContentsScale: scale_factor
1220        ];
1221        let _: () = msg_send![
1222            window_state_borrow.renderer.layer(),
1223            setDrawableSize: drawable_size
1224        ];
1225    }
1226
1227    if let Some(mut callback) = window_state_borrow.resize_callback.take() {
1228        drop(window_state_borrow);
1229        callback();
1230        window_state.as_ref().borrow_mut().resize_callback = Some(callback);
1231    };
1232}
1233
1234extern "C" fn set_frame_size(this: &Object, _: Sel, size: NSSize) {
1235    let window_state = unsafe { get_window_state(this) };
1236    let window_state_borrow = window_state.as_ref().borrow();
1237
1238    if window_state_borrow.content_size() == vec2f(size.width as f32, size.height as f32) {
1239        return;
1240    }
1241
1242    unsafe {
1243        let _: () = msg_send![super(this, class!(NSView)), setFrameSize: size];
1244    }
1245
1246    let scale_factor = window_state_borrow.scale_factor() as f64;
1247    let drawable_size: NSSize = NSSize {
1248        width: size.width * scale_factor,
1249        height: size.height * scale_factor,
1250    };
1251
1252    unsafe {
1253        let _: () = msg_send![
1254            window_state_borrow.renderer.layer(),
1255            setDrawableSize: drawable_size
1256        ];
1257    }
1258
1259    drop(window_state_borrow);
1260    let mut window_state_borrow = window_state.borrow_mut();
1261    if let Some(mut callback) = window_state_borrow.resize_callback.take() {
1262        drop(window_state_borrow);
1263        callback();
1264        window_state.borrow_mut().resize_callback = Some(callback);
1265    };
1266}
1267
1268extern "C" fn display_layer(this: &Object, _: Sel, _: id) {
1269    unsafe {
1270        let window_state = get_window_state(this);
1271        let mut window_state = window_state.as_ref().borrow_mut();
1272        if let Some(scene) = window_state.scene_to_render.take() {
1273            window_state.renderer.render(&scene);
1274        };
1275    }
1276}
1277
1278extern "C" fn valid_attributes_for_marked_text(_: &Object, _: Sel) -> id {
1279    unsafe { msg_send![class!(NSArray), array] }
1280}
1281
1282extern "C" fn has_marked_text(this: &Object, _: Sel) -> BOOL {
1283    with_input_handler(this, |input_handler| input_handler.marked_text_range())
1284        .flatten()
1285        .is_some() as BOOL
1286}
1287
1288extern "C" fn marked_range(this: &Object, _: Sel) -> NSRange {
1289    with_input_handler(this, |input_handler| input_handler.marked_text_range())
1290        .flatten()
1291        .map_or(NSRange::invalid(), |range| range.into())
1292}
1293
1294extern "C" fn selected_range(this: &Object, _: Sel) -> NSRange {
1295    with_input_handler(this, |input_handler| input_handler.selected_text_range())
1296        .flatten()
1297        .map_or(NSRange::invalid(), |range| range.into())
1298}
1299
1300extern "C" fn first_rect_for_character_range(
1301    this: &Object,
1302    _: Sel,
1303    range: NSRange,
1304    _: id,
1305) -> NSRect {
1306    let frame = unsafe {
1307        let window = get_window_state(this).borrow().native_window;
1308        NSView::frame(window)
1309    };
1310    with_input_handler(this, |input_handler| {
1311        input_handler.rect_for_range(range.to_range()?)
1312    })
1313    .flatten()
1314    .map_or(
1315        NSRect::new(NSPoint::new(0., 0.), NSSize::new(0., 0.)),
1316        |rect| {
1317            NSRect::new(
1318                NSPoint::new(
1319                    frame.origin.x + rect.origin_x() as f64,
1320                    frame.origin.y + frame.size.height - rect.origin_y() as f64,
1321                ),
1322                NSSize::new(rect.width() as f64, rect.height() as f64),
1323            )
1324        },
1325    )
1326}
1327
1328extern "C" fn insert_text(this: &Object, _: Sel, text: id, replacement_range: NSRange) {
1329    unsafe {
1330        let window_state = get_window_state(this);
1331        let mut window_state_borrow = window_state.borrow_mut();
1332        let pending_key_down = window_state_borrow.pending_key_down.take();
1333        drop(window_state_borrow);
1334
1335        let is_attributed_string: BOOL =
1336            msg_send![text, isKindOfClass: [class!(NSAttributedString)]];
1337        let text: id = if is_attributed_string == YES {
1338            msg_send![text, string]
1339        } else {
1340            text
1341        };
1342        let text = CStr::from_ptr(text.UTF8String() as *mut c_char)
1343            .to_str()
1344            .unwrap();
1345        let replacement_range = replacement_range.to_range();
1346
1347        window_state.borrow_mut().ime_text = Some(text.to_string());
1348        window_state.borrow_mut().ime_state = ImeState::Acted;
1349
1350        let is_composing =
1351            with_input_handler(this, |input_handler| input_handler.marked_text_range())
1352                .flatten()
1353                .is_some();
1354
1355        if is_composing || text.chars().count() > 1 || pending_key_down.is_none() {
1356            with_input_handler(this, |input_handler| {
1357                input_handler.replace_text_in_range(replacement_range, text)
1358            });
1359        } else {
1360            let mut pending_key_down = pending_key_down.unwrap();
1361            pending_key_down.1 = Some(InsertText {
1362                replacement_range,
1363                text: text.to_string(),
1364            });
1365            window_state.borrow_mut().pending_key_down = Some(pending_key_down);
1366        }
1367    }
1368}
1369
1370extern "C" fn set_marked_text(
1371    this: &Object,
1372    _: Sel,
1373    text: id,
1374    selected_range: NSRange,
1375    replacement_range: NSRange,
1376) {
1377    unsafe {
1378        let window_state = get_window_state(this);
1379        window_state.borrow_mut().pending_key_down.take();
1380
1381        let is_attributed_string: BOOL =
1382            msg_send![text, isKindOfClass: [class!(NSAttributedString)]];
1383        let text: id = if is_attributed_string == YES {
1384            msg_send![text, string]
1385        } else {
1386            text
1387        };
1388        let selected_range = selected_range.to_range();
1389        let replacement_range = replacement_range.to_range();
1390        let text = CStr::from_ptr(text.UTF8String() as *mut c_char)
1391            .to_str()
1392            .unwrap();
1393
1394        window_state.borrow_mut().ime_state = ImeState::Acted;
1395        window_state.borrow_mut().ime_text = Some(text.to_string());
1396
1397        with_input_handler(this, |input_handler| {
1398            input_handler.replace_and_mark_text_in_range(replacement_range, text, selected_range);
1399        });
1400    }
1401}
1402
1403extern "C" fn unmark_text(this: &Object, _: Sel) {
1404    unsafe {
1405        let state = get_window_state(this);
1406        let mut borrow = state.borrow_mut();
1407        borrow.ime_state = ImeState::Acted;
1408        borrow.ime_text.take();
1409    }
1410
1411    with_input_handler(this, |input_handler| input_handler.unmark_text());
1412}
1413
1414extern "C" fn attributed_substring_for_proposed_range(
1415    this: &Object,
1416    _: Sel,
1417    range: NSRange,
1418    _actual_range: *mut c_void,
1419) -> id {
1420    with_input_handler(this, |input_handler| {
1421        let range = range.to_range()?;
1422        if range.is_empty() {
1423            return None;
1424        }
1425
1426        let selected_text = input_handler.text_for_range(range)?;
1427        unsafe {
1428            let string: id = msg_send![class!(NSAttributedString), alloc];
1429            let string: id = msg_send![string, initWithString: ns_string(&selected_text)];
1430            Some(string)
1431        }
1432    })
1433    .flatten()
1434    .unwrap_or(nil)
1435}
1436
1437extern "C" fn do_command_by_selector(this: &Object, _: Sel, _: Sel) {
1438    unsafe {
1439        let state = get_window_state(this);
1440        let mut borrow = state.borrow_mut();
1441        borrow.ime_state = ImeState::Continue;
1442        borrow.ime_text.take();
1443    }
1444}
1445
1446extern "C" fn view_did_change_effective_appearance(this: &Object, _: Sel) {
1447    unsafe {
1448        let state = get_window_state(this);
1449        let mut state_borrow = state.as_ref().borrow_mut();
1450        if let Some(mut callback) = state_borrow.appearance_changed_callback.take() {
1451            drop(state_borrow);
1452            callback();
1453            state.borrow_mut().appearance_changed_callback = Some(callback);
1454        }
1455    }
1456}
1457
1458extern "C" fn accepts_first_mouse(this: &Object, _: Sel, _: id) -> BOOL {
1459    unsafe {
1460        let state = get_window_state(this);
1461        let state_borrow = state.as_ref().borrow();
1462        return if state_borrow.kind == WindowKind::PopUp {
1463            YES
1464        } else {
1465            NO
1466        };
1467    }
1468}
1469
1470async fn synthetic_drag(
1471    window_state: Weak<RefCell<WindowState>>,
1472    drag_id: usize,
1473    event: MouseMovedEvent,
1474) {
1475    loop {
1476        Timer::after(Duration::from_millis(16)).await;
1477        if let Some(window_state) = window_state.upgrade() {
1478            let mut window_state_borrow = window_state.borrow_mut();
1479            if window_state_borrow.synthetic_drag_counter == drag_id {
1480                if let Some(mut callback) = window_state_borrow.event_callback.take() {
1481                    drop(window_state_borrow);
1482                    callback(Event::MouseMoved(event));
1483                    window_state.borrow_mut().event_callback = Some(callback);
1484                }
1485            } else {
1486                break;
1487            }
1488        }
1489    }
1490}
1491
1492fn with_input_handler<F, R>(window: &Object, f: F) -> Option<R>
1493where
1494    F: FnOnce(&mut dyn InputHandler) -> R,
1495{
1496    let window_state = unsafe { get_window_state(window) };
1497    let mut window_state_borrow = window_state.as_ref().borrow_mut();
1498    if let Some(mut input_handler) = window_state_borrow.input_handler.take() {
1499        drop(window_state_borrow);
1500        let result = f(input_handler.as_mut());
1501        window_state.borrow_mut().input_handler = Some(input_handler);
1502        Some(result)
1503    } else {
1504        None
1505    }
1506}