window.rs

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