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