window.rs

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