window.rs

  1use crate::{
  2    executor,
  3    geometry::{
  4        rect::RectF,
  5        vector::{vec2f, Vector2F},
  6    },
  7    keymap::Keystroke,
  8    platform::{self, Event, WindowBounds, WindowContext},
  9    KeyDownEvent, ModifiersChangedEvent, MouseButton, MouseEvent, MouseMovedEvent, Scene,
 10};
 11use block::ConcreteBlock;
 12use cocoa::{
 13    appkit::{
 14        CGPoint, NSApplication, NSBackingStoreBuffered, NSScreen, NSView, NSViewHeightSizable,
 15        NSViewWidthSizable, NSWindow, NSWindowButton, NSWindowStyleMask,
 16    },
 17    base::{id, nil},
 18    foundation::{NSAutoreleasePool, NSInteger, NSSize, NSString},
 19    quartzcore::AutoresizingMask,
 20};
 21use core_graphics::display::CGRect;
 22use ctor::ctor;
 23use foreign_types::ForeignType as _;
 24use objc::{
 25    class,
 26    declare::ClassDecl,
 27    msg_send,
 28    runtime::{Class, Object, Protocol, Sel, BOOL, NO, YES},
 29    sel, sel_impl,
 30};
 31use postage::oneshot;
 32use smol::Timer;
 33use std::{
 34    any::Any,
 35    cell::{Cell, RefCell},
 36    convert::TryInto,
 37    ffi::c_void,
 38    mem, ptr,
 39    rc::{Rc, Weak},
 40    sync::Arc,
 41    time::Duration,
 42};
 43
 44use super::{geometry::RectFExt, renderer::Renderer};
 45
 46const WINDOW_STATE_IVAR: &'static str = "windowState";
 47
 48static mut WINDOW_CLASS: *const Class = ptr::null();
 49static mut VIEW_CLASS: *const Class = ptr::null();
 50
 51#[allow(non_upper_case_globals)]
 52const NSViewLayerContentsRedrawDuringViewResize: NSInteger = 2;
 53
 54#[ctor]
 55unsafe fn build_classes() {
 56    WINDOW_CLASS = {
 57        let mut decl = ClassDecl::new("GPUIWindow", class!(NSWindow)).unwrap();
 58        decl.add_ivar::<*mut c_void>(WINDOW_STATE_IVAR);
 59        decl.add_method(sel!(dealloc), dealloc_window as extern "C" fn(&Object, Sel));
 60        decl.add_method(
 61            sel!(canBecomeMainWindow),
 62            yes as extern "C" fn(&Object, Sel) -> BOOL,
 63        );
 64        decl.add_method(
 65            sel!(canBecomeKeyWindow),
 66            yes as extern "C" fn(&Object, Sel) -> BOOL,
 67        );
 68        decl.add_method(
 69            sel!(sendEvent:),
 70            send_event as extern "C" fn(&Object, Sel, id),
 71        );
 72        decl.add_method(
 73            sel!(windowDidResize:),
 74            window_did_resize as extern "C" fn(&Object, Sel, id),
 75        );
 76        decl.add_method(
 77            sel!(windowDidBecomeKey:),
 78            window_did_change_key_status as extern "C" fn(&Object, Sel, id),
 79        );
 80        decl.add_method(
 81            sel!(windowDidResignKey:),
 82            window_did_change_key_status as extern "C" fn(&Object, Sel, id),
 83        );
 84        decl.add_method(
 85            sel!(windowShouldClose:),
 86            window_should_close as extern "C" fn(&Object, Sel, id) -> BOOL,
 87        );
 88        decl.add_method(sel!(close), close_window as extern "C" fn(&Object, Sel));
 89        decl.register()
 90    };
 91
 92    VIEW_CLASS = {
 93        let mut decl = ClassDecl::new("GPUIView", class!(NSView)).unwrap();
 94        decl.add_ivar::<*mut c_void>(WINDOW_STATE_IVAR);
 95
 96        decl.add_method(sel!(dealloc), dealloc_view as extern "C" fn(&Object, Sel));
 97
 98        decl.add_method(
 99            sel!(performKeyEquivalent:),
100            handle_key_equivalent as extern "C" fn(&Object, Sel, id) -> BOOL,
101        );
102        decl.add_method(
103            sel!(mouseDown:),
104            handle_view_event as extern "C" fn(&Object, Sel, id),
105        );
106        decl.add_method(
107            sel!(mouseUp:),
108            handle_view_event as extern "C" fn(&Object, Sel, id),
109        );
110        decl.add_method(
111            sel!(rightMouseDown:),
112            handle_view_event as extern "C" fn(&Object, Sel, id),
113        );
114        decl.add_method(
115            sel!(rightMouseUp:),
116            handle_view_event as extern "C" fn(&Object, Sel, id),
117        );
118        decl.add_method(
119            sel!(otherMouseDown:),
120            handle_view_event as extern "C" fn(&Object, Sel, id),
121        );
122        decl.add_method(
123            sel!(otherMouseUp:),
124            handle_view_event as extern "C" fn(&Object, Sel, id),
125        );
126        decl.add_method(
127            sel!(mouseMoved:),
128            handle_view_event as extern "C" fn(&Object, Sel, id),
129        );
130        decl.add_method(
131            sel!(mouseDragged:),
132            handle_view_event as extern "C" fn(&Object, Sel, id),
133        );
134        decl.add_method(
135            sel!(scrollWheel:),
136            handle_view_event as extern "C" fn(&Object, Sel, id),
137        );
138        decl.add_method(
139            sel!(flagsChanged:),
140            handle_view_event as extern "C" fn(&Object, Sel, id),
141        );
142        decl.add_method(
143            sel!(cancelOperation:),
144            cancel_operation as extern "C" fn(&Object, Sel, id),
145        );
146
147        decl.add_method(
148            sel!(makeBackingLayer),
149            make_backing_layer as extern "C" fn(&Object, Sel) -> id,
150        );
151
152        decl.add_protocol(Protocol::get("CALayerDelegate").unwrap());
153        decl.add_method(
154            sel!(viewDidChangeBackingProperties),
155            view_did_change_backing_properties as extern "C" fn(&Object, Sel),
156        );
157        decl.add_method(
158            sel!(setFrameSize:),
159            set_frame_size as extern "C" fn(&Object, Sel, NSSize),
160        );
161        decl.add_method(
162            sel!(displayLayer:),
163            display_layer as extern "C" fn(&Object, Sel, id),
164        );
165
166        decl.register()
167    };
168}
169
170pub struct Window(Rc<RefCell<WindowState>>);
171
172struct WindowState {
173    id: usize,
174    native_window: id,
175    event_callback: Option<Box<dyn FnMut(Event) -> bool>>,
176    activate_callback: Option<Box<dyn FnMut(bool)>>,
177    resize_callback: Option<Box<dyn FnMut()>>,
178    should_close_callback: Option<Box<dyn FnMut() -> bool>>,
179    close_callback: Option<Box<dyn FnOnce()>>,
180    synthetic_drag_counter: usize,
181    executor: Rc<executor::Foreground>,
182    scene_to_render: Option<Scene>,
183    renderer: Renderer,
184    command_queue: metal::CommandQueue,
185    last_fresh_keydown: Option<(Keystroke, Option<String>)>,
186    layer: id,
187    traffic_light_position: Option<Vector2F>,
188    previous_modifiers_changed_event: Option<Event>,
189}
190
191impl Window {
192    pub fn open(
193        id: usize,
194        options: platform::WindowOptions,
195        executor: Rc<executor::Foreground>,
196        fonts: Arc<dyn platform::FontSystem>,
197    ) -> Self {
198        const PIXEL_FORMAT: metal::MTLPixelFormat = metal::MTLPixelFormat::BGRA8Unorm;
199
200        unsafe {
201            let pool = NSAutoreleasePool::new(nil);
202
203            let frame = match options.bounds {
204                WindowBounds::Maximized => RectF::new(Default::default(), vec2f(1024., 768.)),
205                WindowBounds::Fixed(rect) => rect,
206            }
207            .to_ns_rect();
208            let mut style_mask = NSWindowStyleMask::NSClosableWindowMask
209                | NSWindowStyleMask::NSMiniaturizableWindowMask
210                | NSWindowStyleMask::NSResizableWindowMask
211                | NSWindowStyleMask::NSTitledWindowMask;
212
213            if options.titlebar_appears_transparent {
214                style_mask |= NSWindowStyleMask::NSFullSizeContentViewWindowMask;
215            }
216
217            let native_window: id = msg_send![WINDOW_CLASS, alloc];
218            let native_window = native_window.initWithContentRect_styleMask_backing_defer_(
219                frame,
220                style_mask,
221                NSBackingStoreBuffered,
222                NO,
223            );
224            assert!(!native_window.is_null());
225
226            if matches!(options.bounds, WindowBounds::Maximized) {
227                let screen = native_window.screen();
228                native_window.setFrame_display_(screen.visibleFrame(), YES);
229            }
230
231            let device =
232                metal::Device::system_default().expect("could not find default metal device");
233
234            let layer: id = msg_send![class!(CAMetalLayer), layer];
235            let _: () = msg_send![layer, setDevice: device.as_ptr()];
236            let _: () = msg_send![layer, setPixelFormat: PIXEL_FORMAT];
237            let _: () = msg_send![layer, setAllowsNextDrawableTimeout: NO];
238            let _: () = msg_send![layer, setNeedsDisplayOnBoundsChange: YES];
239            let _: () = msg_send![layer, setPresentsWithTransaction: YES];
240            let _: () = msg_send![
241                layer,
242                setAutoresizingMask: AutoresizingMask::WIDTH_SIZABLE
243                    | AutoresizingMask::HEIGHT_SIZABLE
244            ];
245
246            let native_view: id = msg_send![VIEW_CLASS, alloc];
247            let native_view = NSView::init(native_view);
248            assert!(!native_view.is_null());
249
250            let window = Self(Rc::new(RefCell::new(WindowState {
251                id,
252                native_window,
253                event_callback: None,
254                resize_callback: None,
255                should_close_callback: None,
256                close_callback: None,
257                activate_callback: None,
258                synthetic_drag_counter: 0,
259                executor,
260                scene_to_render: Default::default(),
261                renderer: Renderer::new(
262                    device.clone(),
263                    PIXEL_FORMAT,
264                    get_scale_factor(native_window),
265                    fonts,
266                ),
267                command_queue: device.new_command_queue(),
268                last_fresh_keydown: None,
269                layer,
270                traffic_light_position: options.traffic_light_position,
271                previous_modifiers_changed_event: None,
272            })));
273
274            (*native_window).set_ivar(
275                WINDOW_STATE_IVAR,
276                Rc::into_raw(window.0.clone()) as *const c_void,
277            );
278            native_window.setDelegate_(native_window);
279            (*native_view).set_ivar(
280                WINDOW_STATE_IVAR,
281                Rc::into_raw(window.0.clone()) as *const c_void,
282            );
283
284            if let Some(title) = options.title.as_ref() {
285                native_window.setTitle_(NSString::alloc(nil).init_str(title));
286            }
287            if options.titlebar_appears_transparent {
288                native_window.setTitlebarAppearsTransparent_(YES);
289            }
290            native_window.setAcceptsMouseMovedEvents_(YES);
291
292            native_view.setAutoresizingMask_(NSViewWidthSizable | NSViewHeightSizable);
293            native_view.setWantsBestResolutionOpenGLSurface_(YES);
294
295            // From winit crate: On Mojave, views automatically become layer-backed shortly after
296            // being added to a native_window. Changing the layer-backedness of a view breaks the
297            // association between the view and its associated OpenGL context. To work around this,
298            // on we explicitly make the view layer-backed up front so that AppKit doesn't do it
299            // itself and break the association with its context.
300            native_view.setWantsLayer(YES);
301            let _: () = msg_send![
302                native_view,
303                setLayerContentsRedrawPolicy: NSViewLayerContentsRedrawDuringViewResize
304            ];
305
306            native_window.setContentView_(native_view.autorelease());
307            native_window.makeFirstResponder_(native_view);
308
309            native_window.center();
310            native_window.makeKeyAndOrderFront_(nil);
311
312            window.0.borrow().move_traffic_light();
313            pool.drain();
314
315            window
316        }
317    }
318
319    pub fn key_window_id() -> Option<usize> {
320        unsafe {
321            let app = NSApplication::sharedApplication(nil);
322            let key_window: id = msg_send![app, keyWindow];
323            if msg_send![key_window, isKindOfClass: WINDOW_CLASS] {
324                let id = get_window_state(&*key_window).borrow().id;
325                Some(id)
326            } else {
327                None
328            }
329        }
330    }
331}
332
333impl Drop for Window {
334    fn drop(&mut self) {
335        unsafe {
336            self.0.as_ref().borrow().native_window.close();
337        }
338    }
339}
340
341impl platform::Window for Window {
342    fn as_any_mut(&mut self) -> &mut dyn Any {
343        self
344    }
345
346    fn on_event(&mut self, callback: Box<dyn FnMut(Event) -> bool>) {
347        self.0.as_ref().borrow_mut().event_callback = Some(callback);
348    }
349
350    fn on_resize(&mut self, callback: Box<dyn FnMut()>) {
351        self.0.as_ref().borrow_mut().resize_callback = Some(callback);
352    }
353
354    fn on_should_close(&mut self, callback: Box<dyn FnMut() -> bool>) {
355        self.0.as_ref().borrow_mut().should_close_callback = Some(callback);
356    }
357
358    fn on_close(&mut self, callback: Box<dyn FnOnce()>) {
359        self.0.as_ref().borrow_mut().close_callback = Some(callback);
360    }
361
362    fn on_active_status_change(&mut self, callback: Box<dyn FnMut(bool)>) {
363        self.0.as_ref().borrow_mut().activate_callback = Some(callback);
364    }
365
366    fn prompt(
367        &self,
368        level: platform::PromptLevel,
369        msg: &str,
370        answers: &[&str],
371    ) -> oneshot::Receiver<usize> {
372        unsafe {
373            let alert: id = msg_send![class!(NSAlert), alloc];
374            let alert: id = msg_send![alert, init];
375            let alert_style = match level {
376                platform::PromptLevel::Info => 1,
377                platform::PromptLevel::Warning => 0,
378                platform::PromptLevel::Critical => 2,
379            };
380            let _: () = msg_send![alert, setAlertStyle: alert_style];
381            let _: () = msg_send![alert, setMessageText: ns_string(msg)];
382            for (ix, answer) in answers.into_iter().enumerate() {
383                let button: id = msg_send![alert, addButtonWithTitle: ns_string(answer)];
384                let _: () = msg_send![button, setTag: ix as NSInteger];
385            }
386            let (done_tx, done_rx) = oneshot::channel();
387            let done_tx = Cell::new(Some(done_tx));
388            let block = ConcreteBlock::new(move |answer: NSInteger| {
389                if let Some(mut done_tx) = done_tx.take() {
390                    let _ = postage::sink::Sink::try_send(&mut done_tx, answer.try_into().unwrap());
391                }
392            });
393            let block = block.copy();
394            let native_window = self.0.borrow().native_window;
395            self.0
396                .borrow()
397                .executor
398                .spawn(async move {
399                    let _: () = msg_send![
400                        alert,
401                        beginSheetModalForWindow: native_window
402                        completionHandler: block
403                    ];
404                })
405                .detach();
406
407            done_rx
408        }
409    }
410
411    fn activate(&self) {
412        let window = self.0.borrow().native_window;
413        self.0
414            .borrow()
415            .executor
416            .spawn(async move {
417                unsafe {
418                    let _: () = msg_send![window, makeKeyAndOrderFront: nil];
419                }
420            })
421            .detach();
422    }
423
424    fn set_title(&mut self, title: &str) {
425        unsafe {
426            let app = NSApplication::sharedApplication(nil);
427            let window = self.0.borrow().native_window;
428            let title = ns_string(title);
429            msg_send![app, changeWindowsItem:window title:title filename:false]
430        }
431    }
432
433    fn set_edited(&mut self, edited: bool) {
434        unsafe {
435            let window = self.0.borrow().native_window;
436            msg_send![window, setDocumentEdited: edited as BOOL]
437        }
438
439        // Changing the document edited state resets the traffic light position,
440        // so we have to move it again.
441        self.0.borrow().move_traffic_light();
442    }
443}
444
445impl platform::WindowContext for Window {
446    fn size(&self) -> Vector2F {
447        self.0.as_ref().borrow().size()
448    }
449
450    fn scale_factor(&self) -> f32 {
451        self.0.as_ref().borrow().scale_factor()
452    }
453
454    fn present_scene(&mut self, scene: Scene) {
455        self.0.as_ref().borrow_mut().present_scene(scene);
456    }
457
458    fn titlebar_height(&self) -> f32 {
459        self.0.as_ref().borrow().titlebar_height()
460    }
461}
462
463impl WindowState {
464    fn move_traffic_light(&self) {
465        if let Some(traffic_light_position) = self.traffic_light_position {
466            let titlebar_height = self.titlebar_height();
467
468            unsafe {
469                let close_button: id = msg_send![
470                    self.native_window,
471                    standardWindowButton: NSWindowButton::NSWindowCloseButton
472                ];
473                let min_button: id = msg_send![
474                    self.native_window,
475                    standardWindowButton: NSWindowButton::NSWindowMiniaturizeButton
476                ];
477                let zoom_button: id = msg_send![
478                    self.native_window,
479                    standardWindowButton: NSWindowButton::NSWindowZoomButton
480                ];
481
482                let mut close_button_frame: CGRect = msg_send![close_button, frame];
483                let mut min_button_frame: CGRect = msg_send![min_button, frame];
484                let mut zoom_button_frame: CGRect = msg_send![zoom_button, frame];
485                let mut origin = vec2f(
486                    traffic_light_position.x(),
487                    titlebar_height
488                        - traffic_light_position.y()
489                        - close_button_frame.size.height as f32,
490                );
491                let button_spacing =
492                    (min_button_frame.origin.x - close_button_frame.origin.x) as f32;
493
494                close_button_frame.origin = CGPoint::new(origin.x() as f64, origin.y() as f64);
495                let _: () = msg_send![close_button, setFrame: close_button_frame];
496                origin.set_x(origin.x() + button_spacing);
497
498                min_button_frame.origin = CGPoint::new(origin.x() as f64, origin.y() as f64);
499                let _: () = msg_send![min_button, setFrame: min_button_frame];
500                origin.set_x(origin.x() + button_spacing);
501
502                zoom_button_frame.origin = CGPoint::new(origin.x() as f64, origin.y() as f64);
503                let _: () = msg_send![zoom_button, setFrame: zoom_button_frame];
504            }
505        }
506    }
507}
508
509impl platform::WindowContext for WindowState {
510    fn size(&self) -> Vector2F {
511        let NSSize { width, height, .. } =
512            unsafe { NSView::frame(self.native_window.contentView()) }.size;
513        vec2f(width as f32, height as f32)
514    }
515
516    fn scale_factor(&self) -> f32 {
517        get_scale_factor(self.native_window)
518    }
519
520    fn titlebar_height(&self) -> f32 {
521        unsafe {
522            let frame = NSWindow::frame(self.native_window);
523            let content_layout_rect: CGRect = msg_send![self.native_window, contentLayoutRect];
524            (frame.size.height - content_layout_rect.size.height) as f32
525        }
526    }
527
528    fn present_scene(&mut self, scene: Scene) {
529        self.scene_to_render = Some(scene);
530        unsafe {
531            let _: () = msg_send![self.native_window.contentView(), setNeedsDisplay: YES];
532        }
533    }
534}
535
536fn get_scale_factor(native_window: id) -> f32 {
537    unsafe {
538        let screen: id = msg_send![native_window, screen];
539        NSScreen::backingScaleFactor(screen) as f32
540    }
541}
542
543unsafe fn get_window_state(object: &Object) -> Rc<RefCell<WindowState>> {
544    let raw: *mut c_void = *object.get_ivar(WINDOW_STATE_IVAR);
545    let rc1 = Rc::from_raw(raw as *mut RefCell<WindowState>);
546    let rc2 = rc1.clone();
547    mem::forget(rc1);
548    rc2
549}
550
551unsafe fn drop_window_state(object: &Object) {
552    let raw: *mut c_void = *object.get_ivar(WINDOW_STATE_IVAR);
553    Rc::from_raw(raw as *mut RefCell<WindowState>);
554}
555
556extern "C" fn yes(_: &Object, _: Sel) -> BOOL {
557    YES
558}
559
560extern "C" fn dealloc_window(this: &Object, _: Sel) {
561    unsafe {
562        drop_window_state(this);
563        let () = msg_send![super(this, class!(NSWindow)), dealloc];
564    }
565}
566
567extern "C" fn dealloc_view(this: &Object, _: Sel) {
568    unsafe {
569        drop_window_state(this);
570        let () = msg_send![super(this, class!(NSView)), dealloc];
571    }
572}
573
574extern "C" fn handle_key_equivalent(this: &Object, _: Sel, native_event: id) -> BOOL {
575    let window_state = unsafe { get_window_state(this) };
576    let mut window_state_borrow = window_state.as_ref().borrow_mut();
577
578    let event = unsafe { Event::from_native(native_event, Some(window_state_borrow.size().y())) };
579    if let Some(event) = event {
580        match &event {
581            Event::KeyDown(KeyDownEvent {
582                keystroke,
583                input,
584                is_held,
585            }) => {
586                let keydown = (keystroke.clone(), input.clone());
587                // Ignore events from held-down keys after some of the initially-pressed keys
588                // were released.
589                if *is_held {
590                    if window_state_borrow.last_fresh_keydown.as_ref() != Some(&keydown) {
591                        return YES;
592                    }
593                } else {
594                    window_state_borrow.last_fresh_keydown = Some(keydown);
595                }
596            }
597            _ => return NO,
598        }
599
600        if let Some(mut callback) = window_state_borrow.event_callback.take() {
601            drop(window_state_borrow);
602            let handled = callback(event);
603            window_state.borrow_mut().event_callback = Some(callback);
604            handled as BOOL
605        } else {
606            NO
607        }
608    } else {
609        NO
610    }
611}
612
613extern "C" fn handle_view_event(this: &Object, _: Sel, native_event: id) {
614    let window_state = unsafe { get_window_state(this) };
615    let weak_window_state = Rc::downgrade(&window_state);
616    let mut window_state_borrow = window_state.as_ref().borrow_mut();
617
618    let event = unsafe { Event::from_native(native_event, Some(window_state_borrow.size().y())) };
619
620    if let Some(event) = event {
621        match &event {
622            Event::MouseMoved(
623                event @ MouseMovedEvent {
624                    pressed_button: Some(_),
625                    ..
626                },
627            ) => {
628                window_state_borrow.synthetic_drag_counter += 1;
629                window_state_borrow
630                    .executor
631                    .spawn(synthetic_drag(
632                        weak_window_state,
633                        window_state_borrow.synthetic_drag_counter,
634                        *event,
635                    ))
636                    .detach();
637            }
638            Event::MouseUp(MouseEvent {
639                button: MouseButton::Left,
640                ..
641            }) => {
642                window_state_borrow.synthetic_drag_counter += 1;
643            }
644            Event::ModifiersChanged(ModifiersChangedEvent {
645                ctrl,
646                alt,
647                shift,
648                cmd,
649            }) => {
650                // Only raise modifiers changed event when they have actually changed
651                if let Some(Event::ModifiersChanged(ModifiersChangedEvent {
652                    ctrl: prev_ctrl,
653                    alt: prev_alt,
654                    shift: prev_shift,
655                    cmd: prev_cmd,
656                })) = &window_state_borrow.previous_modifiers_changed_event
657                {
658                    if prev_ctrl == ctrl
659                        && prev_alt == alt
660                        && prev_shift == shift
661                        && prev_cmd == cmd
662                    {
663                        return;
664                    }
665                }
666
667                window_state_borrow.previous_modifiers_changed_event = Some(event.clone());
668            }
669            _ => {}
670        }
671
672        if let Some(mut callback) = window_state_borrow.event_callback.take() {
673            drop(window_state_borrow);
674            callback(event);
675            window_state.borrow_mut().event_callback = Some(callback);
676        }
677    }
678}
679
680// Allows us to receive `cmd-.` (the shortcut for closing a dialog)
681// https://bugs.eclipse.org/bugs/show_bug.cgi?id=300620#c6
682extern "C" fn cancel_operation(this: &Object, _sel: Sel, _sender: id) {
683    let window_state = unsafe { get_window_state(this) };
684    let mut window_state_borrow = window_state.as_ref().borrow_mut();
685
686    let chars = ".".to_string();
687    let keystroke = Keystroke {
688        cmd: true,
689        ctrl: false,
690        alt: false,
691        shift: false,
692        key: chars.clone(),
693    };
694    let event = Event::KeyDown(KeyDownEvent {
695        keystroke: keystroke.clone(),
696        input: Some(chars.clone()),
697        is_held: false,
698    });
699
700    window_state_borrow.last_fresh_keydown = Some((keystroke, Some(chars)));
701    if let Some(mut callback) = window_state_borrow.event_callback.take() {
702        drop(window_state_borrow);
703        callback(event);
704        window_state.borrow_mut().event_callback = Some(callback);
705    }
706}
707
708extern "C" fn send_event(this: &Object, _: Sel, native_event: id) {
709    unsafe {
710        let () = msg_send![super(this, class!(NSWindow)), sendEvent: native_event];
711    }
712}
713
714extern "C" fn window_did_resize(this: &Object, _: Sel, _: id) {
715    let window_state = unsafe { get_window_state(this) };
716    window_state.as_ref().borrow().move_traffic_light();
717}
718
719extern "C" fn window_did_change_key_status(this: &Object, selector: Sel, _: id) {
720    let is_active = if selector == sel!(windowDidBecomeKey:) {
721        true
722    } else if selector == sel!(windowDidResignKey:) {
723        false
724    } else {
725        unreachable!();
726    };
727
728    let window_state = unsafe { get_window_state(this) };
729    let executor = window_state.as_ref().borrow().executor.clone();
730    executor
731        .spawn(async move {
732            let mut window_state_borrow = window_state.as_ref().borrow_mut();
733            if let Some(mut callback) = window_state_borrow.activate_callback.take() {
734                drop(window_state_borrow);
735                callback(is_active);
736                window_state.borrow_mut().activate_callback = Some(callback);
737            };
738        })
739        .detach();
740}
741
742extern "C" fn window_should_close(this: &Object, _: Sel, _: id) -> BOOL {
743    let window_state = unsafe { get_window_state(this) };
744    let mut window_state_borrow = window_state.as_ref().borrow_mut();
745    if let Some(mut callback) = window_state_borrow.should_close_callback.take() {
746        drop(window_state_borrow);
747        let should_close = callback();
748        window_state.borrow_mut().should_close_callback = Some(callback);
749        should_close as BOOL
750    } else {
751        YES
752    }
753}
754
755extern "C" fn close_window(this: &Object, _: Sel) {
756    unsafe {
757        let close_callback = {
758            let window_state = get_window_state(this);
759            window_state
760                .as_ref()
761                .try_borrow_mut()
762                .ok()
763                .and_then(|mut window_state| window_state.close_callback.take())
764        };
765
766        if let Some(callback) = close_callback {
767            callback();
768        }
769
770        let () = msg_send![super(this, class!(NSWindow)), close];
771    }
772}
773
774extern "C" fn make_backing_layer(this: &Object, _: Sel) -> id {
775    let window_state = unsafe { get_window_state(this) };
776    let window_state = window_state.as_ref().borrow();
777    window_state.layer
778}
779
780extern "C" fn view_did_change_backing_properties(this: &Object, _: Sel) {
781    let window_state = unsafe { get_window_state(this) };
782    let mut window_state_borrow = window_state.as_ref().borrow_mut();
783
784    unsafe {
785        let scale_factor = window_state_borrow.scale_factor() as f64;
786        let size = window_state_borrow.size();
787        let drawable_size: NSSize = NSSize {
788            width: size.x() as f64 * scale_factor,
789            height: size.y() as f64 * scale_factor,
790        };
791
792        let _: () = msg_send![window_state_borrow.layer, setContentsScale: scale_factor];
793        let _: () = msg_send![window_state_borrow.layer, setDrawableSize: drawable_size];
794    }
795
796    if let Some(mut callback) = window_state_borrow.resize_callback.take() {
797        drop(window_state_borrow);
798        callback();
799        window_state.as_ref().borrow_mut().resize_callback = Some(callback);
800    };
801}
802
803extern "C" fn set_frame_size(this: &Object, _: Sel, size: NSSize) {
804    let window_state = unsafe { get_window_state(this) };
805    let window_state_borrow = window_state.as_ref().borrow();
806
807    if window_state_borrow.size() == vec2f(size.width as f32, size.height as f32) {
808        return;
809    }
810
811    unsafe {
812        let _: () = msg_send![super(this, class!(NSView)), setFrameSize: size];
813    }
814
815    let scale_factor = window_state_borrow.scale_factor() as f64;
816    let drawable_size: NSSize = NSSize {
817        width: size.width * scale_factor,
818        height: size.height * scale_factor,
819    };
820
821    unsafe {
822        let _: () = msg_send![window_state_borrow.layer, setDrawableSize: drawable_size];
823    }
824
825    drop(window_state_borrow);
826    let mut window_state_borrow = window_state.borrow_mut();
827    if let Some(mut callback) = window_state_borrow.resize_callback.take() {
828        drop(window_state_borrow);
829        callback();
830        window_state.borrow_mut().resize_callback = Some(callback);
831    };
832}
833
834extern "C" fn display_layer(this: &Object, _: Sel, _: id) {
835    unsafe {
836        let window_state = get_window_state(this);
837        let mut window_state = window_state.as_ref().borrow_mut();
838
839        if let Some(scene) = window_state.scene_to_render.take() {
840            let drawable: &metal::MetalDrawableRef = msg_send![window_state.layer, nextDrawable];
841            let command_queue = window_state.command_queue.clone();
842            let command_buffer = command_queue.new_command_buffer();
843
844            let size = window_state.size();
845            let scale_factor = window_state.scale_factor();
846
847            window_state.renderer.render(
848                &scene,
849                size * scale_factor,
850                command_buffer,
851                drawable.texture(),
852            );
853
854            command_buffer.commit();
855            command_buffer.wait_until_completed();
856            drawable.present();
857        };
858    }
859}
860
861async fn synthetic_drag(
862    window_state: Weak<RefCell<WindowState>>,
863    drag_id: usize,
864    event: MouseMovedEvent,
865) {
866    loop {
867        Timer::after(Duration::from_millis(16)).await;
868        if let Some(window_state) = window_state.upgrade() {
869            let mut window_state_borrow = window_state.borrow_mut();
870            if window_state_borrow.synthetic_drag_counter == drag_id {
871                if let Some(mut callback) = window_state_borrow.event_callback.take() {
872                    drop(window_state_borrow);
873                    callback(Event::MouseMoved(event));
874                    window_state.borrow_mut().event_callback = Some(callback);
875                }
876            } else {
877                break;
878            }
879        }
880    }
881}
882
883unsafe fn ns_string(string: &str) -> id {
884    NSString::alloc(nil).init_str(string).autorelease()
885}