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!(keyDown:),
 96            handle_view_event as extern "C" fn(&Object, Sel, id),
 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)>>,
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)>) {
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
402impl platform::WindowContext for Window {
403    fn size(&self) -> Vector2F {
404        self.0.as_ref().borrow().size()
405    }
406
407    fn scale_factor(&self) -> f32 {
408        self.0.as_ref().borrow().scale_factor()
409    }
410
411    fn present_scene(&mut self, scene: Scene) {
412        self.0.as_ref().borrow_mut().present_scene(scene);
413    }
414
415    fn titlebar_height(&self) -> f32 {
416        self.0.as_ref().borrow().titlebar_height()
417    }
418}
419
420impl WindowState {
421    fn move_traffic_light(&self) {
422        if let Some(traffic_light_position) = self.traffic_light_position {
423            let titlebar_height = self.titlebar_height();
424
425            unsafe {
426                let close_button: id = msg_send![
427                    self.native_window,
428                    standardWindowButton: NSWindowButton::NSWindowCloseButton
429                ];
430                let min_button: id = msg_send![
431                    self.native_window,
432                    standardWindowButton: NSWindowButton::NSWindowMiniaturizeButton
433                ];
434                let zoom_button: id = msg_send![
435                    self.native_window,
436                    standardWindowButton: NSWindowButton::NSWindowZoomButton
437                ];
438
439                let mut close_button_frame: CGRect = msg_send![close_button, frame];
440                let mut min_button_frame: CGRect = msg_send![min_button, frame];
441                let mut zoom_button_frame: CGRect = msg_send![zoom_button, frame];
442                let mut origin = vec2f(
443                    traffic_light_position.x(),
444                    titlebar_height
445                        - traffic_light_position.y()
446                        - close_button_frame.size.height as f32,
447                );
448                let button_spacing =
449                    (min_button_frame.origin.x - close_button_frame.origin.x) as f32;
450
451                close_button_frame.origin = CGPoint::new(origin.x() as f64, origin.y() as f64);
452                let _: () = msg_send![close_button, setFrame: close_button_frame];
453                origin.set_x(origin.x() + button_spacing);
454
455                min_button_frame.origin = CGPoint::new(origin.x() as f64, origin.y() as f64);
456                let _: () = msg_send![min_button, setFrame: min_button_frame];
457                origin.set_x(origin.x() + button_spacing);
458
459                zoom_button_frame.origin = CGPoint::new(origin.x() as f64, origin.y() as f64);
460                let _: () = msg_send![zoom_button, setFrame: zoom_button_frame];
461            }
462        }
463    }
464}
465
466impl platform::WindowContext for WindowState {
467    fn size(&self) -> Vector2F {
468        let NSSize { width, height, .. } =
469            unsafe { NSView::frame(self.native_window.contentView()) }.size;
470        vec2f(width as f32, height as f32)
471    }
472
473    fn scale_factor(&self) -> f32 {
474        get_scale_factor(self.native_window)
475    }
476
477    fn titlebar_height(&self) -> f32 {
478        unsafe {
479            let frame = NSWindow::frame(self.native_window);
480            let content_layout_rect: CGRect = msg_send![self.native_window, contentLayoutRect];
481            (frame.size.height - content_layout_rect.size.height) as f32
482        }
483    }
484
485    fn present_scene(&mut self, scene: Scene) {
486        self.scene_to_render = Some(scene);
487        unsafe {
488            let _: () = msg_send![self.native_window.contentView(), setNeedsDisplay: YES];
489        }
490    }
491}
492
493fn get_scale_factor(native_window: id) -> f32 {
494    unsafe {
495        let screen: id = msg_send![native_window, screen];
496        NSScreen::backingScaleFactor(screen) as f32
497    }
498}
499
500unsafe fn get_window_state(object: &Object) -> Rc<RefCell<WindowState>> {
501    let raw: *mut c_void = *object.get_ivar(WINDOW_STATE_IVAR);
502    let rc1 = Rc::from_raw(raw as *mut RefCell<WindowState>);
503    let rc2 = rc1.clone();
504    mem::forget(rc1);
505    rc2
506}
507
508unsafe fn drop_window_state(object: &Object) {
509    let raw: *mut c_void = *object.get_ivar(WINDOW_STATE_IVAR);
510    Rc::from_raw(raw as *mut RefCell<WindowState>);
511}
512
513extern "C" fn yes(_: &Object, _: Sel) -> BOOL {
514    YES
515}
516
517extern "C" fn dealloc_window(this: &Object, _: Sel) {
518    unsafe {
519        drop_window_state(this);
520        let () = msg_send![super(this, class!(NSWindow)), dealloc];
521    }
522}
523
524extern "C" fn dealloc_view(this: &Object, _: Sel) {
525    unsafe {
526        drop_window_state(this);
527        let () = msg_send![super(this, class!(NSView)), dealloc];
528    }
529}
530
531extern "C" fn handle_view_event(this: &Object, _: Sel, native_event: id) {
532    let window_state = unsafe { get_window_state(this) };
533    let weak_window_state = Rc::downgrade(&window_state);
534    let mut window_state_borrow = window_state.as_ref().borrow_mut();
535
536    let event = unsafe { Event::from_native(native_event, Some(window_state_borrow.size().y())) };
537
538    if let Some(event) = event {
539        match &event {
540            Event::LeftMouseDragged { position } => {
541                window_state_borrow.synthetic_drag_counter += 1;
542                window_state_borrow
543                    .executor
544                    .spawn(synthetic_drag(
545                        weak_window_state,
546                        window_state_borrow.synthetic_drag_counter,
547                        *position,
548                    ))
549                    .detach();
550            }
551            Event::LeftMouseUp { .. } => {
552                window_state_borrow.synthetic_drag_counter += 1;
553            }
554
555            // Ignore events from held-down keys after some of the initially-pressed keys
556            // were released.
557            Event::KeyDown {
558                input,
559                keystroke,
560                is_held,
561            } => {
562                let keydown = (keystroke.clone(), input.clone());
563                if *is_held {
564                    if window_state_borrow.last_fresh_keydown.as_ref() != Some(&keydown) {
565                        return;
566                    }
567                } else {
568                    window_state_borrow.last_fresh_keydown = Some(keydown);
569                }
570            }
571
572            _ => {}
573        }
574
575        if let Some(mut callback) = window_state_borrow.event_callback.take() {
576            drop(window_state_borrow);
577            callback(event);
578            window_state.borrow_mut().event_callback = Some(callback);
579        }
580    }
581}
582
583// Allows us to receive `cmd-.` (the shortcut for closing a dialog)
584// https://bugs.eclipse.org/bugs/show_bug.cgi?id=300620#c6
585extern "C" fn cancel_operation(this: &Object, _sel: Sel, _sender: id) {
586    let window_state = unsafe { get_window_state(this) };
587    let mut window_state_borrow = window_state.as_ref().borrow_mut();
588
589    let chars = ".".to_string();
590    let keystroke = Keystroke {
591        cmd: true,
592        ctrl: false,
593        alt: false,
594        shift: false,
595        key: chars.clone(),
596    };
597    let event = Event::KeyDown {
598        keystroke: keystroke.clone(),
599        input: Some(chars.clone()),
600        is_held: false,
601    };
602
603    window_state_borrow.last_fresh_keydown = Some((keystroke, Some(chars)));
604    if let Some(mut callback) = window_state_borrow.event_callback.take() {
605        drop(window_state_borrow);
606        callback(event);
607        window_state.borrow_mut().event_callback = Some(callback);
608    }
609}
610
611extern "C" fn send_event(this: &Object, _: Sel, native_event: id) {
612    unsafe {
613        let () = msg_send![super(this, class!(NSWindow)), sendEvent: native_event];
614    }
615}
616
617extern "C" fn window_did_resize(this: &Object, _: Sel, _: id) {
618    let window_state = unsafe { get_window_state(this) };
619    window_state.as_ref().borrow().move_traffic_light();
620}
621
622extern "C" fn window_did_change_key_status(this: &Object, selector: Sel, _: id) {
623    let is_active = if selector == sel!(windowDidBecomeKey:) {
624        true
625    } else if selector == sel!(windowDidResignKey:) {
626        false
627    } else {
628        unreachable!();
629    };
630
631    let window_state = unsafe { get_window_state(this) };
632    let executor = window_state.as_ref().borrow().executor.clone();
633    executor
634        .spawn(async move {
635            let mut window_state_borrow = window_state.as_ref().borrow_mut();
636            if let Some(mut callback) = window_state_borrow.activate_callback.take() {
637                drop(window_state_borrow);
638                callback(is_active);
639                window_state.borrow_mut().activate_callback = Some(callback);
640            };
641        })
642        .detach();
643}
644
645extern "C" fn close_window(this: &Object, _: Sel) {
646    unsafe {
647        let close_callback = {
648            let window_state = get_window_state(this);
649            window_state
650                .as_ref()
651                .try_borrow_mut()
652                .ok()
653                .and_then(|mut window_state| window_state.close_callback.take())
654        };
655
656        if let Some(callback) = close_callback {
657            callback();
658        }
659
660        let () = msg_send![super(this, class!(NSWindow)), close];
661    }
662}
663
664extern "C" fn make_backing_layer(this: &Object, _: Sel) -> id {
665    let window_state = unsafe { get_window_state(this) };
666    let window_state = window_state.as_ref().borrow();
667    window_state.layer
668}
669
670extern "C" fn view_did_change_backing_properties(this: &Object, _: Sel) {
671    let window_state = unsafe { get_window_state(this) };
672    let mut window_state_borrow = window_state.as_ref().borrow_mut();
673
674    unsafe {
675        let _: () = msg_send![window_state_borrow.layer, setContentsScale: window_state_borrow.scale_factor() as f64];
676    }
677
678    if let Some(mut callback) = window_state_borrow.resize_callback.take() {
679        drop(window_state_borrow);
680        callback();
681        window_state.as_ref().borrow_mut().resize_callback = Some(callback);
682    };
683}
684
685extern "C" fn set_frame_size(this: &Object, _: Sel, size: NSSize) {
686    let window_state = unsafe { get_window_state(this) };
687    let mut window_state_borrow = window_state.as_ref().borrow_mut();
688
689    if window_state_borrow.size() == vec2f(size.width as f32, size.height as f32) {
690        return;
691    }
692
693    unsafe {
694        let _: () = msg_send![super(this, class!(NSView)), setFrameSize: size];
695    }
696
697    let scale_factor = window_state_borrow.scale_factor() as f64;
698    let drawable_size: NSSize = NSSize {
699        width: size.width * scale_factor,
700        height: size.height * scale_factor,
701    };
702
703    unsafe {
704        let _: () = msg_send![window_state_borrow.layer, setDrawableSize: drawable_size];
705    }
706
707    if let Some(mut callback) = window_state_borrow.resize_callback.take() {
708        drop(window_state_borrow);
709        callback();
710        window_state.borrow_mut().resize_callback = Some(callback);
711    };
712}
713
714extern "C" fn display_layer(this: &Object, _: Sel, _: id) {
715    unsafe {
716        let window_state = get_window_state(this);
717        let mut window_state = window_state.as_ref().borrow_mut();
718
719        if let Some(scene) = window_state.scene_to_render.take() {
720            let drawable: &metal::MetalDrawableRef = msg_send![window_state.layer, nextDrawable];
721            let command_queue = window_state.command_queue.clone();
722            let command_buffer = command_queue.new_command_buffer();
723
724            let size = window_state.size();
725            let scale_factor = window_state.scale_factor();
726
727            window_state.renderer.render(
728                &scene,
729                size * scale_factor,
730                command_buffer,
731                drawable.texture(),
732            );
733
734            command_buffer.commit();
735            command_buffer.wait_until_completed();
736            drawable.present();
737        };
738    }
739}
740
741async fn synthetic_drag(
742    window_state: Weak<RefCell<WindowState>>,
743    drag_id: usize,
744    position: Vector2F,
745) {
746    loop {
747        Timer::after(Duration::from_millis(16)).await;
748        if let Some(window_state) = window_state.upgrade() {
749            let mut window_state_borrow = window_state.borrow_mut();
750            if window_state_borrow.synthetic_drag_counter == drag_id {
751                if let Some(mut callback) = window_state_borrow.event_callback.take() {
752                    drop(window_state_borrow);
753                    callback(Event::LeftMouseDragged { position });
754                    window_state.borrow_mut().event_callback = Some(callback);
755                }
756            } else {
757                break;
758            }
759        }
760    }
761}
762
763unsafe fn ns_string(string: &str) -> id {
764    NSString::alloc(nil).init_str(string).autorelease()
765}