window.rs

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