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, ModifiersChangedEvent, MouseButton, MouseButtonEvent,
  14        MouseMovedEvent, Scene, WindowBounds, WindowKind,
  15    },
  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            let screen_frame = self.native_window.screen().visibleFrame().to_rectf();
 376            if window_frame.size() == screen_frame.size() {
 377                WindowBounds::Maximized
 378            } else {
 379                WindowBounds::Fixed(window_frame)
 380            }
 381        }
 382    }
 383
 384    // Returns the window bounds in window coordinates
 385    fn frame(&self) -> RectF {
 386        unsafe {
 387            let screen_frame = self.native_window.screen().visibleFrame();
 388            let window_frame = NSWindow::frame(self.native_window);
 389            RectF::new(
 390                vec2f(
 391                    window_frame.origin.x as f32,
 392                    (screen_frame.size.height - window_frame.origin.y - window_frame.size.height)
 393                        as f32,
 394                ),
 395                vec2f(
 396                    window_frame.size.width as f32,
 397                    window_frame.size.height as f32,
 398                ),
 399            )
 400        }
 401    }
 402
 403    fn content_size(&self) -> Vector2F {
 404        let NSSize { width, height, .. } =
 405            unsafe { NSView::frame(self.native_window.contentView()) }.size;
 406        vec2f(width as f32, height as f32)
 407    }
 408
 409    fn scale_factor(&self) -> f32 {
 410        get_scale_factor(self.native_window)
 411    }
 412
 413    fn titlebar_height(&self) -> f32 {
 414        unsafe {
 415            let frame = NSWindow::frame(self.native_window);
 416            let content_layout_rect: CGRect = msg_send![self.native_window, contentLayoutRect];
 417            (frame.size.height - content_layout_rect.size.height) as f32
 418        }
 419    }
 420
 421    fn present_scene(&mut self, scene: Scene) {
 422        self.scene_to_render = Some(scene);
 423        unsafe {
 424            let _: () = msg_send![self.native_window.contentView(), setNeedsDisplay: YES];
 425        }
 426    }
 427}
 428
 429pub struct Window(Rc<RefCell<WindowState>>);
 430
 431impl Window {
 432    pub fn open(
 433        id: usize,
 434        options: platform::WindowOptions,
 435        executor: Rc<executor::Foreground>,
 436        fonts: Arc<dyn platform::FontSystem>,
 437    ) -> Self {
 438        unsafe {
 439            let pool = NSAutoreleasePool::new(nil);
 440
 441            let mut style_mask;
 442            if let Some(titlebar) = options.titlebar.as_ref() {
 443                style_mask = NSWindowStyleMask::NSClosableWindowMask
 444                    | NSWindowStyleMask::NSMiniaturizableWindowMask
 445                    | NSWindowStyleMask::NSResizableWindowMask
 446                    | NSWindowStyleMask::NSTitledWindowMask;
 447
 448                if titlebar.appears_transparent {
 449                    style_mask |= NSWindowStyleMask::NSFullSizeContentViewWindowMask;
 450                }
 451            } else {
 452                style_mask = NSWindowStyleMask::NSTitledWindowMask
 453                    | NSWindowStyleMask::NSFullSizeContentViewWindowMask;
 454            }
 455
 456            let native_window: id = match options.kind {
 457                WindowKind::Normal => msg_send![WINDOW_CLASS, alloc],
 458                WindowKind::PopUp => {
 459                    style_mask |= NSWindowStyleMaskNonactivatingPanel;
 460                    msg_send![PANEL_CLASS, alloc]
 461                }
 462            };
 463            let native_window = native_window.initWithContentRect_styleMask_backing_defer_screen_(
 464                NSRect::new(NSPoint::new(0., 0.), NSSize::new(1024., 768.)),
 465                style_mask,
 466                NSBackingStoreBuffered,
 467                NO,
 468                options
 469                    .screen
 470                    .and_then(|screen| {
 471                        Some(screen.as_any().downcast_ref::<Screen>()?.native_screen)
 472                    })
 473                    .unwrap_or(nil),
 474            );
 475            assert!(!native_window.is_null());
 476
 477            let screen = native_window.screen();
 478            match options.bounds {
 479                WindowBounds::Fullscreen => {
 480                    native_window.toggleFullScreen_(nil);
 481                }
 482                WindowBounds::Maximized => {
 483                    native_window.setFrame_display_(screen.visibleFrame(), YES);
 484                }
 485                WindowBounds::Fixed(rect) => {
 486                    let screen_frame = screen.visibleFrame();
 487                    let ns_rect = NSRect::new(
 488                        NSPoint::new(
 489                            rect.origin_x() as f64,
 490                            screen_frame.size.height
 491                                - rect.origin_y() as f64
 492                                - rect.height() as f64,
 493                        ),
 494                        NSSize::new(rect.width() as f64, rect.height() as f64),
 495                    );
 496
 497                    if ns_rect.intersects(screen_frame) {
 498                        native_window.setFrame_display_(ns_rect, YES);
 499                    } else {
 500                        native_window.setFrame_display_(screen_frame, YES);
 501                    }
 502                }
 503            }
 504
 505            let native_view: id = msg_send![VIEW_CLASS, alloc];
 506            let native_view = NSView::init(native_view);
 507
 508            assert!(!native_view.is_null());
 509
 510            let window = Self(Rc::new(RefCell::new(WindowState {
 511                id,
 512                native_window,
 513                kind: options.kind,
 514                event_callback: None,
 515                resize_callback: None,
 516                should_close_callback: None,
 517                close_callback: None,
 518                activate_callback: None,
 519                fullscreen_callback: None,
 520                moved_callback: None,
 521                appearance_changed_callback: None,
 522                input_handler: None,
 523                pending_key_down: None,
 524                performed_key_equivalent: false,
 525                synthetic_drag_counter: 0,
 526                executor,
 527                scene_to_render: Default::default(),
 528                renderer: Renderer::new(true, fonts),
 529                last_fresh_keydown: None,
 530                traffic_light_position: options
 531                    .titlebar
 532                    .as_ref()
 533                    .and_then(|titlebar| titlebar.traffic_light_position),
 534                previous_modifiers_changed_event: None,
 535                ime_state: ImeState::None,
 536                ime_text: None,
 537            })));
 538
 539            (*native_window).set_ivar(
 540                WINDOW_STATE_IVAR,
 541                Rc::into_raw(window.0.clone()) as *const c_void,
 542            );
 543            native_window.setDelegate_(native_window);
 544            (*native_view).set_ivar(
 545                WINDOW_STATE_IVAR,
 546                Rc::into_raw(window.0.clone()) as *const c_void,
 547            );
 548
 549            if let Some(title) = options.titlebar.as_ref().and_then(|t| t.title) {
 550                native_window.setTitle_(NSString::alloc(nil).init_str(title));
 551            }
 552
 553            native_window.setMovable_(options.is_movable as BOOL);
 554
 555            if options
 556                .titlebar
 557                .map_or(true, |titlebar| titlebar.appears_transparent)
 558            {
 559                native_window.setTitlebarAppearsTransparent_(YES);
 560                native_window.setTitleVisibility_(NSWindowTitleVisibility::NSWindowTitleHidden);
 561            }
 562
 563            native_view.setAutoresizingMask_(NSViewWidthSizable | NSViewHeightSizable);
 564            native_view.setWantsBestResolutionOpenGLSurface_(YES);
 565
 566            // From winit crate: On Mojave, views automatically become layer-backed shortly after
 567            // being added to a native_window. Changing the layer-backedness of a view breaks the
 568            // association between the view and its associated OpenGL context. To work around this,
 569            // on we explicitly make the view layer-backed up front so that AppKit doesn't do it
 570            // itself and break the association with its context.
 571            native_view.setWantsLayer(YES);
 572            let _: () = msg_send![
 573                native_view,
 574                setLayerContentsRedrawPolicy: NSViewLayerContentsRedrawDuringViewResize
 575            ];
 576
 577            native_window.setContentView_(native_view.autorelease());
 578            native_window.makeFirstResponder_(native_view);
 579
 580            if options.center {
 581                native_window.center();
 582            }
 583
 584            match options.kind {
 585                WindowKind::Normal => {
 586                    native_window.setLevel_(NSNormalWindowLevel);
 587                    native_window.setAcceptsMouseMovedEvents_(YES);
 588                }
 589                WindowKind::PopUp => {
 590                    // Use a tracking area to allow receiving MouseMoved events even when
 591                    // the window or application aren't active, which is often the case
 592                    // e.g. for notification windows.
 593                    let tracking_area: id = msg_send![class!(NSTrackingArea), alloc];
 594                    let _: () = msg_send![
 595                        tracking_area,
 596                        initWithRect: NSRect::new(NSPoint::new(0., 0.), NSSize::new(0., 0.))
 597                        options: NSTrackingMouseEnteredAndExited | NSTrackingMouseMoved | NSTrackingActiveAlways | NSTrackingInVisibleRect
 598                        owner: native_view
 599                        userInfo: nil
 600                    ];
 601                    let _: () =
 602                        msg_send![native_view, addTrackingArea: tracking_area.autorelease()];
 603
 604                    native_window.setLevel_(NSPopUpWindowLevel);
 605                    let _: () = msg_send![
 606                        native_window,
 607                        setAnimationBehavior: NSWindowAnimationBehaviorUtilityWindow
 608                    ];
 609                    native_window.setCollectionBehavior_(
 610                        NSWindowCollectionBehavior::NSWindowCollectionBehaviorCanJoinAllSpaces |
 611                        NSWindowCollectionBehavior::NSWindowCollectionBehaviorFullScreenAuxiliary
 612                    );
 613                }
 614            }
 615            if options.focus {
 616                native_window.makeKeyAndOrderFront_(nil);
 617            } else if options.show {
 618                native_window.orderFront_(nil);
 619            }
 620
 621            window.0.borrow().move_traffic_light();
 622            pool.drain();
 623
 624            window
 625        }
 626    }
 627
 628    pub fn main_window_id() -> Option<usize> {
 629        unsafe {
 630            let app = NSApplication::sharedApplication(nil);
 631            let main_window: id = msg_send![app, mainWindow];
 632            if msg_send![main_window, isKindOfClass: WINDOW_CLASS] {
 633                let id = get_window_state(&*main_window).borrow().id;
 634                Some(id)
 635            } else {
 636                None
 637            }
 638        }
 639    }
 640}
 641
 642impl Drop for Window {
 643    fn drop(&mut self) {
 644        let this = self.0.borrow();
 645        let window = this.native_window;
 646        this.executor
 647            .spawn(async move {
 648                unsafe {
 649                    window.close();
 650                }
 651            })
 652            .detach();
 653    }
 654}
 655
 656impl platform::Window for Window {
 657    fn bounds(&self) -> WindowBounds {
 658        self.0.as_ref().borrow().bounds()
 659    }
 660
 661    fn content_size(&self) -> Vector2F {
 662        self.0.as_ref().borrow().content_size()
 663    }
 664
 665    fn scale_factor(&self) -> f32 {
 666        self.0.as_ref().borrow().scale_factor()
 667    }
 668
 669    fn titlebar_height(&self) -> f32 {
 670        self.0.as_ref().borrow().titlebar_height()
 671    }
 672
 673    fn appearance(&self) -> platform::Appearance {
 674        unsafe {
 675            let appearance: id = msg_send![self.0.borrow().native_window, effectiveAppearance];
 676            platform::Appearance::from_native(appearance)
 677        }
 678    }
 679
 680    fn screen(&self) -> Rc<dyn platform::Screen> {
 681        unsafe {
 682            Rc::new(Screen {
 683                native_screen: self.0.as_ref().borrow().native_window.screen(),
 684            })
 685        }
 686    }
 687
 688    fn as_any_mut(&mut self) -> &mut dyn Any {
 689        self
 690    }
 691
 692    fn set_input_handler(&mut self, input_handler: Box<dyn InputHandler>) {
 693        self.0.as_ref().borrow_mut().input_handler = Some(input_handler);
 694    }
 695
 696    fn prompt(
 697        &self,
 698        level: platform::PromptLevel,
 699        msg: &str,
 700        answers: &[&str],
 701    ) -> oneshot::Receiver<usize> {
 702        // macOs applies overrides to modal window buttons after they are added.
 703        // Two most important for this logic are:
 704        // * Buttons with "Cancel" title will be displayed as the last buttons in the modal
 705        // * Last button added to the modal via `addButtonWithTitle` stays focused
 706        // * Focused buttons react on "space"/" " keypresses
 707        // * Usage of `keyEquivalent`, `makeFirstResponder` or `setInitialFirstResponder` does not change the focus
 708        //
 709        // See also https://developer.apple.com/documentation/appkit/nsalert/1524532-addbuttonwithtitle#discussion
 710        // ```
 711        // By default, the first button has a key equivalent of Return,
 712        // any button with a title of “Cancel” has a key equivalent of Escape,
 713        // 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).
 714        // ```
 715        //
 716        // To avoid situations when the last element added is "Cancel" and it gets the focus
 717        // (hence stealing both ESC and Space shortcuts), we find and add one non-Cancel button
 718        // last, so it gets focus and a Space shortcut.
 719        // This way, "Save this file? Yes/No/Cancel"-ish modals will get all three buttons mapped with a key.
 720        let latest_non_cancel_label = answers
 721            .iter()
 722            .enumerate()
 723            .rev()
 724            .find(|(_, &label)| label != "Cancel")
 725            .filter(|&(label_index, _)| label_index > 0);
 726
 727        unsafe {
 728            let alert: id = msg_send![class!(NSAlert), alloc];
 729            let alert: id = msg_send![alert, init];
 730            let alert_style = match level {
 731                platform::PromptLevel::Info => 1,
 732                platform::PromptLevel::Warning => 0,
 733                platform::PromptLevel::Critical => 2,
 734            };
 735            let _: () = msg_send![alert, setAlertStyle: alert_style];
 736            let _: () = msg_send![alert, setMessageText: ns_string(msg)];
 737
 738            for (ix, answer) in answers
 739                .iter()
 740                .enumerate()
 741                .filter(|&(ix, _)| Some(ix) != latest_non_cancel_label.map(|(ix, _)| ix))
 742            {
 743                let button: id = msg_send![alert, addButtonWithTitle: ns_string(answer)];
 744                let _: () = msg_send![button, setTag: ix as NSInteger];
 745            }
 746            if let Some((ix, answer)) = latest_non_cancel_label {
 747                let button: id = msg_send![alert, addButtonWithTitle: ns_string(answer)];
 748                let _: () = msg_send![button, setTag: ix as NSInteger];
 749            }
 750
 751            let (done_tx, done_rx) = oneshot::channel();
 752            let done_tx = Cell::new(Some(done_tx));
 753            let block = ConcreteBlock::new(move |answer: NSInteger| {
 754                if let Some(mut done_tx) = done_tx.take() {
 755                    let _ = postage::sink::Sink::try_send(&mut done_tx, answer.try_into().unwrap());
 756                }
 757            });
 758            let block = block.copy();
 759            let native_window = self.0.borrow().native_window;
 760            self.0
 761                .borrow()
 762                .executor
 763                .spawn(async move {
 764                    let _: () = msg_send![
 765                        alert,
 766                        beginSheetModalForWindow: native_window
 767                        completionHandler: block
 768                    ];
 769                })
 770                .detach();
 771
 772            done_rx
 773        }
 774    }
 775
 776    fn activate(&self) {
 777        let window = self.0.borrow().native_window;
 778        self.0
 779            .borrow()
 780            .executor
 781            .spawn(async move {
 782                unsafe {
 783                    let _: () = msg_send![window, makeKeyAndOrderFront: nil];
 784                }
 785            })
 786            .detach();
 787    }
 788
 789    fn set_title(&mut self, title: &str) {
 790        unsafe {
 791            let app = NSApplication::sharedApplication(nil);
 792            let window = self.0.borrow().native_window;
 793            let title = ns_string(title);
 794            let _: () = msg_send![app, changeWindowsItem:window title:title filename:false];
 795            let _: () = msg_send![window, setTitle: title];
 796            self.0.borrow().move_traffic_light();
 797        }
 798    }
 799
 800    fn set_edited(&mut self, edited: bool) {
 801        unsafe {
 802            let window = self.0.borrow().native_window;
 803            msg_send![window, setDocumentEdited: edited as BOOL]
 804        }
 805
 806        // Changing the document edited state resets the traffic light position,
 807        // so we have to move it again.
 808        self.0.borrow().move_traffic_light();
 809    }
 810
 811    fn show_character_palette(&self) {
 812        unsafe {
 813            let app = NSApplication::sharedApplication(nil);
 814            let window = self.0.borrow().native_window;
 815            let _: () = msg_send![app, orderFrontCharacterPalette: window];
 816        }
 817    }
 818
 819    fn minimize(&self) {
 820        let window = self.0.borrow().native_window;
 821        unsafe {
 822            window.miniaturize_(nil);
 823        }
 824    }
 825
 826    fn zoom(&self) {
 827        let this = self.0.borrow();
 828        let window = this.native_window;
 829        this.executor
 830            .spawn(async move {
 831                unsafe {
 832                    window.zoom_(nil);
 833                }
 834            })
 835            .detach();
 836    }
 837
 838    fn present_scene(&mut self, scene: Scene) {
 839        self.0.as_ref().borrow_mut().present_scene(scene);
 840    }
 841
 842    fn toggle_full_screen(&self) {
 843        let this = self.0.borrow();
 844        let window = this.native_window;
 845        this.executor
 846            .spawn(async move {
 847                unsafe {
 848                    window.toggleFullScreen_(nil);
 849                }
 850            })
 851            .detach();
 852    }
 853
 854    fn on_event(&mut self, callback: Box<dyn FnMut(Event) -> bool>) {
 855        self.0.as_ref().borrow_mut().event_callback = Some(callback);
 856    }
 857
 858    fn on_active_status_change(&mut self, callback: Box<dyn FnMut(bool)>) {
 859        self.0.as_ref().borrow_mut().activate_callback = Some(callback);
 860    }
 861
 862    fn on_resize(&mut self, callback: Box<dyn FnMut()>) {
 863        self.0.as_ref().borrow_mut().resize_callback = Some(callback);
 864    }
 865
 866    fn on_fullscreen(&mut self, callback: Box<dyn FnMut(bool)>) {
 867        self.0.as_ref().borrow_mut().fullscreen_callback = Some(callback);
 868    }
 869
 870    fn on_moved(&mut self, callback: Box<dyn FnMut()>) {
 871        self.0.as_ref().borrow_mut().moved_callback = Some(callback);
 872    }
 873
 874    fn on_should_close(&mut self, callback: Box<dyn FnMut() -> bool>) {
 875        self.0.as_ref().borrow_mut().should_close_callback = Some(callback);
 876    }
 877
 878    fn on_close(&mut self, callback: Box<dyn FnOnce()>) {
 879        self.0.as_ref().borrow_mut().close_callback = Some(callback);
 880    }
 881
 882    fn on_appearance_changed(&mut self, callback: Box<dyn FnMut()>) {
 883        self.0.borrow_mut().appearance_changed_callback = Some(callback);
 884    }
 885
 886    fn is_topmost_for_position(&self, position: Vector2F) -> bool {
 887        let self_borrow = self.0.borrow();
 888        let self_id = self_borrow.id;
 889
 890        unsafe {
 891            let app = NSApplication::sharedApplication(nil);
 892
 893            // Convert back to screen coordinates
 894            let screen_point = position.to_screen_ns_point(
 895                self_borrow.native_window,
 896                self_borrow.content_size().y() as f64,
 897            );
 898
 899            let window_number: NSInteger = msg_send![class!(NSWindow), windowNumberAtPoint:screen_point belowWindowWithWindowNumber:0];
 900            let top_most_window: id = msg_send![app, windowWithWindowNumber: window_number];
 901
 902            let is_panel: BOOL = msg_send![top_most_window, isKindOfClass: PANEL_CLASS];
 903            let is_window: BOOL = msg_send![top_most_window, isKindOfClass: WINDOW_CLASS];
 904            if is_panel == YES || is_window == YES {
 905                let topmost_window_id = get_window_state(&*top_most_window).borrow().id;
 906                topmost_window_id == self_id
 907            } else {
 908                // Someone else's window is on top
 909                false
 910            }
 911        }
 912    }
 913}
 914
 915fn get_scale_factor(native_window: id) -> f32 {
 916    unsafe {
 917        let screen: id = msg_send![native_window, screen];
 918        NSScreen::backingScaleFactor(screen) as f32
 919    }
 920}
 921
 922unsafe fn get_window_state(object: &Object) -> Rc<RefCell<WindowState>> {
 923    let raw: *mut c_void = *object.get_ivar(WINDOW_STATE_IVAR);
 924    let rc1 = Rc::from_raw(raw as *mut RefCell<WindowState>);
 925    let rc2 = rc1.clone();
 926    mem::forget(rc1);
 927    rc2
 928}
 929
 930unsafe fn drop_window_state(object: &Object) {
 931    let raw: *mut c_void = *object.get_ivar(WINDOW_STATE_IVAR);
 932    Rc::from_raw(raw as *mut RefCell<WindowState>);
 933}
 934
 935extern "C" fn yes(_: &Object, _: Sel) -> BOOL {
 936    YES
 937}
 938
 939extern "C" fn dealloc_window(this: &Object, _: Sel) {
 940    unsafe {
 941        drop_window_state(this);
 942        let _: () = msg_send![super(this, class!(NSWindow)), dealloc];
 943    }
 944}
 945
 946extern "C" fn dealloc_view(this: &Object, _: Sel) {
 947    unsafe {
 948        drop_window_state(this);
 949        let _: () = msg_send![super(this, class!(NSView)), dealloc];
 950    }
 951}
 952
 953extern "C" fn handle_key_equivalent(this: &Object, _: Sel, native_event: id) -> BOOL {
 954    handle_key_event(this, native_event, true)
 955}
 956
 957extern "C" fn handle_key_down(this: &Object, _: Sel, native_event: id) {
 958    handle_key_event(this, native_event, false);
 959}
 960
 961extern "C" fn handle_key_event(this: &Object, native_event: id, key_equivalent: bool) -> BOOL {
 962    let window_state = unsafe { get_window_state(this) };
 963    let mut window_state_borrow = window_state.as_ref().borrow_mut();
 964
 965    let window_height = window_state_borrow.content_size().y();
 966    let event = unsafe { Event::from_native(native_event, Some(window_height)) };
 967
 968    if let Some(event) = event {
 969        if key_equivalent {
 970            window_state_borrow.performed_key_equivalent = true;
 971        } else if window_state_borrow.performed_key_equivalent {
 972            return NO;
 973        }
 974
 975        let function_is_held;
 976        window_state_borrow.pending_key_down = match event {
 977            Event::KeyDown(event) => {
 978                let keydown = event.keystroke.clone();
 979                // Ignore events from held-down keys after some of the initially-pressed keys
 980                // were released.
 981                if event.is_held {
 982                    if window_state_borrow.last_fresh_keydown.as_ref() != Some(&keydown) {
 983                        return YES;
 984                    }
 985                } else {
 986                    window_state_borrow.last_fresh_keydown = Some(keydown);
 987                }
 988                function_is_held = event.keystroke.function;
 989                Some((event, None))
 990            }
 991
 992            _ => return NO,
 993        };
 994
 995        drop(window_state_borrow);
 996
 997        if !function_is_held {
 998            unsafe {
 999                let input_context: id = msg_send![this, inputContext];
1000                let _: BOOL = msg_send![input_context, handleEvent: native_event];
1001            }
1002        }
1003
1004        let mut handled = false;
1005        let mut window_state_borrow = window_state.borrow_mut();
1006        let ime_text = window_state_borrow.ime_text.clone();
1007        if let Some((event, insert_text)) = window_state_borrow.pending_key_down.take() {
1008            let is_held = event.is_held;
1009            if let Some(mut callback) = window_state_borrow.event_callback.take() {
1010                drop(window_state_borrow);
1011
1012                let is_composing =
1013                    with_input_handler(this, |input_handler| input_handler.marked_text_range())
1014                        .flatten()
1015                        .is_some();
1016                if !is_composing {
1017                    handled = callback(Event::KeyDown(event));
1018                }
1019
1020                if !handled {
1021                    if let Some(insert) = insert_text {
1022                        handled = true;
1023                        with_input_handler(this, |input_handler| {
1024                            input_handler
1025                                .replace_text_in_range(insert.replacement_range, &insert.text)
1026                        });
1027                    } else if !is_composing && is_held {
1028                        if let Some(last_insert_text) = ime_text {
1029                            //MacOS IME is a bit funky, and even when you've told it there's nothing to
1030                            //inter it will still swallow certain keys (e.g. 'f', 'j') and not others
1031                            //(e.g. 'n'). This is a problem for certain kinds of views, like the terminal
1032                            with_input_handler(this, |input_handler| {
1033                                if input_handler.selected_text_range().is_none() {
1034                                    handled = true;
1035                                    input_handler.replace_text_in_range(None, &last_insert_text)
1036                                }
1037                            });
1038                        }
1039                    }
1040                }
1041
1042                window_state.borrow_mut().event_callback = Some(callback);
1043            }
1044        } else {
1045            handled = true;
1046        }
1047
1048        handled as BOOL
1049    } else {
1050        NO
1051    }
1052}
1053
1054extern "C" fn handle_view_event(this: &Object, _: Sel, native_event: id) {
1055    let window_state = unsafe { get_window_state(this) };
1056    let weak_window_state = Rc::downgrade(&window_state);
1057    let mut window_state_borrow = window_state.as_ref().borrow_mut();
1058    let is_active = unsafe { window_state_borrow.native_window.isKeyWindow() == YES };
1059
1060    let window_height = window_state_borrow.content_size().y();
1061    let event = unsafe { Event::from_native(native_event, Some(window_height)) };
1062    if let Some(event) = event {
1063        match &event {
1064            Event::MouseMoved(
1065                event @ MouseMovedEvent {
1066                    pressed_button: Some(_),
1067                    ..
1068                },
1069            ) => {
1070                window_state_borrow.synthetic_drag_counter += 1;
1071                window_state_borrow
1072                    .executor
1073                    .spawn(synthetic_drag(
1074                        weak_window_state,
1075                        window_state_borrow.synthetic_drag_counter,
1076                        *event,
1077                    ))
1078                    .detach();
1079            }
1080
1081            Event::MouseMoved(_)
1082                if !(is_active || window_state_borrow.kind == WindowKind::PopUp) =>
1083            {
1084                return
1085            }
1086
1087            Event::MouseUp(MouseButtonEvent {
1088                button: MouseButton::Left,
1089                ..
1090            }) => {
1091                window_state_borrow.synthetic_drag_counter += 1;
1092            }
1093
1094            Event::ModifiersChanged(ModifiersChangedEvent { modifiers }) => {
1095                // Only raise modifiers changed event when they have actually changed
1096                if let Some(Event::ModifiersChanged(ModifiersChangedEvent {
1097                    modifiers: prev_modifiers,
1098                })) = &window_state_borrow.previous_modifiers_changed_event
1099                {
1100                    if prev_modifiers == modifiers {
1101                        return;
1102                    }
1103                }
1104
1105                window_state_borrow.previous_modifiers_changed_event = Some(event.clone());
1106            }
1107
1108            _ => {}
1109        }
1110
1111        if let Some(mut callback) = window_state_borrow.event_callback.take() {
1112            drop(window_state_borrow);
1113            callback(event);
1114            window_state.borrow_mut().event_callback = Some(callback);
1115        }
1116    }
1117}
1118
1119// Allows us to receive `cmd-.` (the shortcut for closing a dialog)
1120// https://bugs.eclipse.org/bugs/show_bug.cgi?id=300620#c6
1121extern "C" fn cancel_operation(this: &Object, _sel: Sel, _sender: id) {
1122    let window_state = unsafe { get_window_state(this) };
1123    let mut window_state_borrow = window_state.as_ref().borrow_mut();
1124
1125    let keystroke = Keystroke {
1126        cmd: true,
1127        ctrl: false,
1128        alt: false,
1129        shift: false,
1130        function: false,
1131        key: ".".into(),
1132    };
1133    let event = Event::KeyDown(KeyDownEvent {
1134        keystroke: keystroke.clone(),
1135        is_held: false,
1136    });
1137
1138    window_state_borrow.last_fresh_keydown = Some(keystroke);
1139    if let Some(mut callback) = window_state_borrow.event_callback.take() {
1140        drop(window_state_borrow);
1141        callback(event);
1142        window_state.borrow_mut().event_callback = Some(callback);
1143    }
1144}
1145
1146extern "C" fn send_event(this: &Object, _: Sel, native_event: id) {
1147    unsafe {
1148        let _: () = msg_send![super(this, class!(NSWindow)), sendEvent: native_event];
1149        get_window_state(this).borrow_mut().performed_key_equivalent = false;
1150    }
1151}
1152
1153extern "C" fn window_did_resize(this: &Object, _: Sel, _: id) {
1154    let window_state = unsafe { get_window_state(this) };
1155    window_state.as_ref().borrow().move_traffic_light();
1156}
1157
1158extern "C" fn window_will_enter_fullscreen(this: &Object, _: Sel, _: id) {
1159    window_fullscreen_changed(this, true);
1160}
1161
1162extern "C" fn window_will_exit_fullscreen(this: &Object, _: Sel, _: id) {
1163    window_fullscreen_changed(this, false);
1164}
1165
1166fn window_fullscreen_changed(this: &Object, is_fullscreen: bool) {
1167    let window_state = unsafe { get_window_state(this) };
1168    let mut window_state_borrow = window_state.as_ref().borrow_mut();
1169    if let Some(mut callback) = window_state_borrow.fullscreen_callback.take() {
1170        drop(window_state_borrow);
1171        callback(is_fullscreen);
1172        window_state.borrow_mut().fullscreen_callback = Some(callback);
1173    }
1174}
1175
1176extern "C" fn window_did_move(this: &Object, _: Sel, _: id) {
1177    let window_state = unsafe { get_window_state(this) };
1178    let mut window_state_borrow = window_state.as_ref().borrow_mut();
1179    if let Some(mut callback) = window_state_borrow.moved_callback.take() {
1180        drop(window_state_borrow);
1181        callback();
1182        window_state.borrow_mut().moved_callback = Some(callback);
1183    }
1184}
1185
1186extern "C" fn window_did_change_key_status(this: &Object, selector: Sel, _: id) {
1187    let window_state = unsafe { get_window_state(this) };
1188    let window_state_borrow = window_state.borrow();
1189    let is_active = unsafe { window_state_borrow.native_window.isKeyWindow() == YES };
1190
1191    // When opening a pop-up while the application isn't active, Cocoa sends a spurious
1192    // `windowDidBecomeKey` message to the previous key window even though that window
1193    // isn't actually key. This causes a bug if the application is later activated while
1194    // the pop-up is still open, making it impossible to activate the previous key window
1195    // even if the pop-up gets closed. The only way to activate it again is to de-activate
1196    // the app and re-activate it, which is a pretty bad UX.
1197    // The following code detects the spurious event and invokes `resignKeyWindow`:
1198    // in theory, we're not supposed to invoke this method manually but it balances out
1199    // the spurious `becomeKeyWindow` event and helps us work around that bug.
1200    if selector == sel!(windowDidBecomeKey:) {
1201        if !is_active {
1202            unsafe {
1203                let _: () = msg_send![window_state_borrow.native_window, resignKeyWindow];
1204                return;
1205            }
1206        }
1207    }
1208
1209    let executor = window_state_borrow.executor.clone();
1210    drop(window_state_borrow);
1211    executor
1212        .spawn(async move {
1213            let mut window_state_borrow = window_state.as_ref().borrow_mut();
1214            if let Some(mut callback) = window_state_borrow.activate_callback.take() {
1215                drop(window_state_borrow);
1216                callback(is_active);
1217                window_state.borrow_mut().activate_callback = Some(callback);
1218            };
1219        })
1220        .detach();
1221}
1222
1223extern "C" fn window_should_close(this: &Object, _: Sel, _: id) -> BOOL {
1224    let window_state = unsafe { get_window_state(this) };
1225    let mut window_state_borrow = window_state.as_ref().borrow_mut();
1226    if let Some(mut callback) = window_state_borrow.should_close_callback.take() {
1227        drop(window_state_borrow);
1228        let should_close = callback();
1229        window_state.borrow_mut().should_close_callback = Some(callback);
1230        should_close as BOOL
1231    } else {
1232        YES
1233    }
1234}
1235
1236extern "C" fn close_window(this: &Object, _: Sel) {
1237    unsafe {
1238        let close_callback = {
1239            let window_state = get_window_state(this);
1240            window_state
1241                .as_ref()
1242                .try_borrow_mut()
1243                .ok()
1244                .and_then(|mut window_state| window_state.close_callback.take())
1245        };
1246
1247        if let Some(callback) = close_callback {
1248            callback();
1249        }
1250
1251        let _: () = msg_send![super(this, class!(NSWindow)), close];
1252    }
1253}
1254
1255extern "C" fn make_backing_layer(this: &Object, _: Sel) -> id {
1256    let window_state = unsafe { get_window_state(this) };
1257    let window_state = window_state.as_ref().borrow();
1258    window_state.renderer.layer().as_ptr() as id
1259}
1260
1261extern "C" fn view_did_change_backing_properties(this: &Object, _: Sel) {
1262    let window_state = unsafe { get_window_state(this) };
1263    let mut window_state_borrow = window_state.as_ref().borrow_mut();
1264
1265    unsafe {
1266        let scale_factor = window_state_borrow.scale_factor() as f64;
1267        let size = window_state_borrow.content_size();
1268        let drawable_size: NSSize = NSSize {
1269            width: size.x() as f64 * scale_factor,
1270            height: size.y() as f64 * scale_factor,
1271        };
1272
1273        let _: () = msg_send![
1274            window_state_borrow.renderer.layer(),
1275            setContentsScale: scale_factor
1276        ];
1277        let _: () = msg_send![
1278            window_state_borrow.renderer.layer(),
1279            setDrawableSize: drawable_size
1280        ];
1281    }
1282
1283    if let Some(mut callback) = window_state_borrow.resize_callback.take() {
1284        drop(window_state_borrow);
1285        callback();
1286        window_state.as_ref().borrow_mut().resize_callback = Some(callback);
1287    };
1288}
1289
1290extern "C" fn set_frame_size(this: &Object, _: Sel, size: NSSize) {
1291    let window_state = unsafe { get_window_state(this) };
1292    let window_state_borrow = window_state.as_ref().borrow();
1293
1294    if window_state_borrow.content_size() == vec2f(size.width as f32, size.height as f32) {
1295        return;
1296    }
1297
1298    unsafe {
1299        let _: () = msg_send![super(this, class!(NSView)), setFrameSize: size];
1300    }
1301
1302    let scale_factor = window_state_borrow.scale_factor() as f64;
1303    let drawable_size: NSSize = NSSize {
1304        width: size.width * scale_factor,
1305        height: size.height * scale_factor,
1306    };
1307
1308    unsafe {
1309        let _: () = msg_send![
1310            window_state_borrow.renderer.layer(),
1311            setDrawableSize: drawable_size
1312        ];
1313    }
1314
1315    drop(window_state_borrow);
1316    let mut window_state_borrow = window_state.borrow_mut();
1317    if let Some(mut callback) = window_state_borrow.resize_callback.take() {
1318        drop(window_state_borrow);
1319        callback();
1320        window_state.borrow_mut().resize_callback = Some(callback);
1321    };
1322}
1323
1324extern "C" fn display_layer(this: &Object, _: Sel, _: id) {
1325    unsafe {
1326        let window_state = get_window_state(this);
1327        let mut window_state = window_state.as_ref().borrow_mut();
1328        if let Some(scene) = window_state.scene_to_render.take() {
1329            window_state.renderer.render(&scene);
1330        };
1331    }
1332}
1333
1334extern "C" fn valid_attributes_for_marked_text(_: &Object, _: Sel) -> id {
1335    unsafe { msg_send![class!(NSArray), array] }
1336}
1337
1338extern "C" fn has_marked_text(this: &Object, _: Sel) -> BOOL {
1339    with_input_handler(this, |input_handler| input_handler.marked_text_range())
1340        .flatten()
1341        .is_some() as BOOL
1342}
1343
1344extern "C" fn marked_range(this: &Object, _: Sel) -> NSRange {
1345    with_input_handler(this, |input_handler| input_handler.marked_text_range())
1346        .flatten()
1347        .map_or(NSRange::invalid(), |range| range.into())
1348}
1349
1350extern "C" fn selected_range(this: &Object, _: Sel) -> NSRange {
1351    with_input_handler(this, |input_handler| input_handler.selected_text_range())
1352        .flatten()
1353        .map_or(NSRange::invalid(), |range| range.into())
1354}
1355
1356extern "C" fn first_rect_for_character_range(
1357    this: &Object,
1358    _: Sel,
1359    range: NSRange,
1360    _: id,
1361) -> NSRect {
1362    let frame = unsafe {
1363        let window = get_window_state(this).borrow().native_window;
1364        NSView::frame(window)
1365    };
1366    with_input_handler(this, |input_handler| {
1367        input_handler.rect_for_range(range.to_range()?)
1368    })
1369    .flatten()
1370    .map_or(
1371        NSRect::new(NSPoint::new(0., 0.), NSSize::new(0., 0.)),
1372        |rect| {
1373            NSRect::new(
1374                NSPoint::new(
1375                    frame.origin.x + rect.origin_x() as f64,
1376                    frame.origin.y + frame.size.height - rect.origin_y() as f64,
1377                ),
1378                NSSize::new(rect.width() as f64, rect.height() as f64),
1379            )
1380        },
1381    )
1382}
1383
1384extern "C" fn insert_text(this: &Object, _: Sel, text: id, replacement_range: NSRange) {
1385    unsafe {
1386        let window_state = get_window_state(this);
1387        let mut window_state_borrow = window_state.borrow_mut();
1388        let pending_key_down = window_state_borrow.pending_key_down.take();
1389        drop(window_state_borrow);
1390
1391        let is_attributed_string: BOOL =
1392            msg_send![text, isKindOfClass: [class!(NSAttributedString)]];
1393        let text: id = if is_attributed_string == YES {
1394            msg_send![text, string]
1395        } else {
1396            text
1397        };
1398        let text = CStr::from_ptr(text.UTF8String() as *mut c_char)
1399            .to_str()
1400            .unwrap();
1401        let replacement_range = replacement_range.to_range();
1402
1403        window_state.borrow_mut().ime_text = Some(text.to_string());
1404        window_state.borrow_mut().ime_state = ImeState::Acted;
1405
1406        let is_composing =
1407            with_input_handler(this, |input_handler| input_handler.marked_text_range())
1408                .flatten()
1409                .is_some();
1410
1411        if is_composing || text.chars().count() > 1 || pending_key_down.is_none() {
1412            with_input_handler(this, |input_handler| {
1413                input_handler.replace_text_in_range(replacement_range, text)
1414            });
1415        } else {
1416            let mut pending_key_down = pending_key_down.unwrap();
1417            pending_key_down.1 = Some(InsertText {
1418                replacement_range,
1419                text: text.to_string(),
1420            });
1421            window_state.borrow_mut().pending_key_down = Some(pending_key_down);
1422        }
1423    }
1424}
1425
1426extern "C" fn set_marked_text(
1427    this: &Object,
1428    _: Sel,
1429    text: id,
1430    selected_range: NSRange,
1431    replacement_range: NSRange,
1432) {
1433    unsafe {
1434        let window_state = get_window_state(this);
1435        window_state.borrow_mut().pending_key_down.take();
1436
1437        let is_attributed_string: BOOL =
1438            msg_send![text, isKindOfClass: [class!(NSAttributedString)]];
1439        let text: id = if is_attributed_string == YES {
1440            msg_send![text, string]
1441        } else {
1442            text
1443        };
1444        let selected_range = selected_range.to_range();
1445        let replacement_range = replacement_range.to_range();
1446        let text = CStr::from_ptr(text.UTF8String() as *mut c_char)
1447            .to_str()
1448            .unwrap();
1449
1450        window_state.borrow_mut().ime_state = ImeState::Acted;
1451        window_state.borrow_mut().ime_text = Some(text.to_string());
1452
1453        with_input_handler(this, |input_handler| {
1454            input_handler.replace_and_mark_text_in_range(replacement_range, text, selected_range);
1455        });
1456    }
1457}
1458
1459extern "C" fn unmark_text(this: &Object, _: Sel) {
1460    unsafe {
1461        let state = get_window_state(this);
1462        let mut borrow = state.borrow_mut();
1463        borrow.ime_state = ImeState::Acted;
1464        borrow.ime_text.take();
1465    }
1466
1467    with_input_handler(this, |input_handler| input_handler.unmark_text());
1468}
1469
1470extern "C" fn attributed_substring_for_proposed_range(
1471    this: &Object,
1472    _: Sel,
1473    range: NSRange,
1474    _actual_range: *mut c_void,
1475) -> id {
1476    with_input_handler(this, |input_handler| {
1477        let range = range.to_range()?;
1478        if range.is_empty() {
1479            return None;
1480        }
1481
1482        let selected_text = input_handler.text_for_range(range)?;
1483        unsafe {
1484            let string: id = msg_send![class!(NSAttributedString), alloc];
1485            let string: id = msg_send![string, initWithString: ns_string(&selected_text)];
1486            Some(string)
1487        }
1488    })
1489    .flatten()
1490    .unwrap_or(nil)
1491}
1492
1493extern "C" fn do_command_by_selector(this: &Object, _: Sel, _: Sel) {
1494    unsafe {
1495        let state = get_window_state(this);
1496        let mut borrow = state.borrow_mut();
1497        borrow.ime_state = ImeState::Continue;
1498        borrow.ime_text.take();
1499    }
1500}
1501
1502extern "C" fn view_did_change_effective_appearance(this: &Object, _: Sel) {
1503    unsafe {
1504        let state = get_window_state(this);
1505        let mut state_borrow = state.as_ref().borrow_mut();
1506        if let Some(mut callback) = state_borrow.appearance_changed_callback.take() {
1507            drop(state_borrow);
1508            callback();
1509            state.borrow_mut().appearance_changed_callback = Some(callback);
1510        }
1511    }
1512}
1513
1514extern "C" fn accepts_first_mouse(this: &Object, _: Sel, _: id) -> BOOL {
1515    unsafe {
1516        let state = get_window_state(this);
1517        let state_borrow = state.as_ref().borrow();
1518        return if state_borrow.kind == WindowKind::PopUp {
1519            YES
1520        } else {
1521            NO
1522        };
1523    }
1524}
1525
1526async fn synthetic_drag(
1527    window_state: Weak<RefCell<WindowState>>,
1528    drag_id: usize,
1529    event: MouseMovedEvent,
1530) {
1531    loop {
1532        Timer::after(Duration::from_millis(16)).await;
1533        if let Some(window_state) = window_state.upgrade() {
1534            let mut window_state_borrow = window_state.borrow_mut();
1535            if window_state_borrow.synthetic_drag_counter == drag_id {
1536                if let Some(mut callback) = window_state_borrow.event_callback.take() {
1537                    drop(window_state_borrow);
1538                    callback(Event::MouseMoved(event));
1539                    window_state.borrow_mut().event_callback = Some(callback);
1540                }
1541            } else {
1542                break;
1543            }
1544        }
1545    }
1546}
1547
1548fn with_input_handler<F, R>(window: &Object, f: F) -> Option<R>
1549where
1550    F: FnOnce(&mut dyn InputHandler) -> R,
1551{
1552    let window_state = unsafe { get_window_state(window) };
1553    let mut window_state_borrow = window_state.as_ref().borrow_mut();
1554    if let Some(mut input_handler) = window_state_borrow.input_handler.take() {
1555        drop(window_state_borrow);
1556        let result = f(input_handler.as_mut());
1557        window_state.borrow_mut().input_handler = Some(input_handler);
1558        Some(result)
1559    } else {
1560        None
1561    }
1562}