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(
 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            let _: () = msg_send![
396                alert,
397                beginSheetModalForWindow: native_window
398                completionHandler: block
399            ];
400            done_rx
401        }
402    }
403
404    fn activate(&self) {
405        unsafe { msg_send![self.0.borrow().native_window, makeKeyAndOrderFront: nil] }
406    }
407
408    fn set_title(&mut self, title: &str) {
409        unsafe {
410            let app = NSApplication::sharedApplication(nil);
411            let window = self.0.borrow().native_window;
412            let title = ns_string(title);
413            msg_send![app, changeWindowsItem:window title:title filename:false]
414        }
415    }
416
417    fn set_edited(&mut self, edited: bool) {
418        unsafe {
419            let window = self.0.borrow().native_window;
420            msg_send![window, setDocumentEdited: edited as BOOL]
421        }
422
423        // Changing the document edited state resets the traffic light position,
424        // so we have to move it again.
425        self.0.borrow().move_traffic_light();
426    }
427}
428
429impl platform::WindowContext for Window {
430    fn size(&self) -> Vector2F {
431        self.0.as_ref().borrow().size()
432    }
433
434    fn scale_factor(&self) -> f32 {
435        self.0.as_ref().borrow().scale_factor()
436    }
437
438    fn present_scene(&mut self, scene: Scene) {
439        self.0.as_ref().borrow_mut().present_scene(scene);
440    }
441
442    fn titlebar_height(&self) -> f32 {
443        self.0.as_ref().borrow().titlebar_height()
444    }
445}
446
447impl WindowState {
448    fn move_traffic_light(&self) {
449        if let Some(traffic_light_position) = self.traffic_light_position {
450            let titlebar_height = self.titlebar_height();
451
452            unsafe {
453                let close_button: id = msg_send![
454                    self.native_window,
455                    standardWindowButton: NSWindowButton::NSWindowCloseButton
456                ];
457                let min_button: id = msg_send![
458                    self.native_window,
459                    standardWindowButton: NSWindowButton::NSWindowMiniaturizeButton
460                ];
461                let zoom_button: id = msg_send![
462                    self.native_window,
463                    standardWindowButton: NSWindowButton::NSWindowZoomButton
464                ];
465
466                let mut close_button_frame: CGRect = msg_send![close_button, frame];
467                let mut min_button_frame: CGRect = msg_send![min_button, frame];
468                let mut zoom_button_frame: CGRect = msg_send![zoom_button, frame];
469                let mut origin = vec2f(
470                    traffic_light_position.x(),
471                    titlebar_height
472                        - traffic_light_position.y()
473                        - close_button_frame.size.height as f32,
474                );
475                let button_spacing =
476                    (min_button_frame.origin.x - close_button_frame.origin.x) as f32;
477
478                close_button_frame.origin = CGPoint::new(origin.x() as f64, origin.y() as f64);
479                let _: () = msg_send![close_button, setFrame: close_button_frame];
480                origin.set_x(origin.x() + button_spacing);
481
482                min_button_frame.origin = CGPoint::new(origin.x() as f64, origin.y() as f64);
483                let _: () = msg_send![min_button, setFrame: min_button_frame];
484                origin.set_x(origin.x() + button_spacing);
485
486                zoom_button_frame.origin = CGPoint::new(origin.x() as f64, origin.y() as f64);
487                let _: () = msg_send![zoom_button, setFrame: zoom_button_frame];
488            }
489        }
490    }
491}
492
493impl platform::WindowContext for WindowState {
494    fn size(&self) -> Vector2F {
495        let NSSize { width, height, .. } =
496            unsafe { NSView::frame(self.native_window.contentView()) }.size;
497        vec2f(width as f32, height as f32)
498    }
499
500    fn scale_factor(&self) -> f32 {
501        get_scale_factor(self.native_window)
502    }
503
504    fn titlebar_height(&self) -> f32 {
505        unsafe {
506            let frame = NSWindow::frame(self.native_window);
507            let content_layout_rect: CGRect = msg_send![self.native_window, contentLayoutRect];
508            (frame.size.height - content_layout_rect.size.height) as f32
509        }
510    }
511
512    fn present_scene(&mut self, scene: Scene) {
513        self.scene_to_render = Some(scene);
514        unsafe {
515            let _: () = msg_send![self.native_window.contentView(), setNeedsDisplay: YES];
516        }
517    }
518}
519
520fn get_scale_factor(native_window: id) -> f32 {
521    unsafe {
522        let screen: id = msg_send![native_window, screen];
523        NSScreen::backingScaleFactor(screen) as f32
524    }
525}
526
527unsafe fn get_window_state(object: &Object) -> Rc<RefCell<WindowState>> {
528    let raw: *mut c_void = *object.get_ivar(WINDOW_STATE_IVAR);
529    let rc1 = Rc::from_raw(raw as *mut RefCell<WindowState>);
530    let rc2 = rc1.clone();
531    mem::forget(rc1);
532    rc2
533}
534
535unsafe fn drop_window_state(object: &Object) {
536    let raw: *mut c_void = *object.get_ivar(WINDOW_STATE_IVAR);
537    Rc::from_raw(raw as *mut RefCell<WindowState>);
538}
539
540extern "C" fn yes(_: &Object, _: Sel) -> BOOL {
541    YES
542}
543
544extern "C" fn dealloc_window(this: &Object, _: Sel) {
545    unsafe {
546        drop_window_state(this);
547        let () = msg_send![super(this, class!(NSWindow)), dealloc];
548    }
549}
550
551extern "C" fn dealloc_view(this: &Object, _: Sel) {
552    unsafe {
553        drop_window_state(this);
554        let () = msg_send![super(this, class!(NSView)), dealloc];
555    }
556}
557
558extern "C" fn handle_key_equivalent(this: &Object, _: Sel, native_event: id) -> BOOL {
559    let window_state = unsafe { get_window_state(this) };
560    let mut window_state_borrow = window_state.as_ref().borrow_mut();
561
562    let event = unsafe { Event::from_native(native_event, Some(window_state_borrow.size().y())) };
563    if let Some(event) = event {
564        match &event {
565            Event::KeyDown {
566                keystroke,
567                input,
568                is_held,
569            } => {
570                let keydown = (keystroke.clone(), input.clone());
571                // Ignore events from held-down keys after some of the initially-pressed keys
572                // were released.
573                if *is_held {
574                    if window_state_borrow.last_fresh_keydown.as_ref() != Some(&keydown) {
575                        return YES;
576                    }
577                } else {
578                    window_state_borrow.last_fresh_keydown = Some(keydown);
579                }
580            }
581            _ => return NO,
582        }
583
584        if let Some(mut callback) = window_state_borrow.event_callback.take() {
585            drop(window_state_borrow);
586            let handled = callback(event);
587            window_state.borrow_mut().event_callback = Some(callback);
588            handled as BOOL
589        } else {
590            NO
591        }
592    } else {
593        NO
594    }
595}
596
597extern "C" fn handle_view_event(this: &Object, _: Sel, native_event: id) {
598    let window_state = unsafe { get_window_state(this) };
599    let weak_window_state = Rc::downgrade(&window_state);
600    let mut window_state_borrow = window_state.as_ref().borrow_mut();
601
602    let event = unsafe { Event::from_native(native_event, Some(window_state_borrow.size().y())) };
603
604    if let Some(event) = event {
605        match &event {
606            Event::LeftMouseDragged { position, .. } => {
607                window_state_borrow.synthetic_drag_counter += 1;
608                window_state_borrow
609                    .executor
610                    .spawn(synthetic_drag(
611                        weak_window_state,
612                        window_state_borrow.synthetic_drag_counter,
613                        *position,
614                    ))
615                    .detach();
616            }
617            Event::LeftMouseUp { .. } => {
618                window_state_borrow.synthetic_drag_counter += 1;
619            }
620            Event::ModifiersChanged {
621                ctrl,
622                alt,
623                shift,
624                cmd,
625            } => {
626                // Only raise modifiers changed event when they have actually changed
627                if let Some(Event::ModifiersChanged {
628                    ctrl: prev_ctrl,
629                    alt: prev_alt,
630                    shift: prev_shift,
631                    cmd: prev_cmd,
632                }) = &window_state_borrow.previous_modifiers_changed_event
633                {
634                    if prev_ctrl == ctrl
635                        && prev_alt == alt
636                        && prev_shift == shift
637                        && prev_cmd == cmd
638                    {
639                        return;
640                    }
641                }
642
643                window_state_borrow.previous_modifiers_changed_event = Some(event.clone());
644            }
645            _ => {}
646        }
647
648        if let Some(mut callback) = window_state_borrow.event_callback.take() {
649            drop(window_state_borrow);
650            callback(event);
651            window_state.borrow_mut().event_callback = Some(callback);
652        }
653    }
654}
655
656// Allows us to receive `cmd-.` (the shortcut for closing a dialog)
657// https://bugs.eclipse.org/bugs/show_bug.cgi?id=300620#c6
658extern "C" fn cancel_operation(this: &Object, _sel: Sel, _sender: id) {
659    let window_state = unsafe { get_window_state(this) };
660    let mut window_state_borrow = window_state.as_ref().borrow_mut();
661
662    let chars = ".".to_string();
663    let keystroke = Keystroke {
664        cmd: true,
665        ctrl: false,
666        alt: false,
667        shift: false,
668        key: chars.clone(),
669    };
670    let event = Event::KeyDown {
671        keystroke: keystroke.clone(),
672        input: Some(chars.clone()),
673        is_held: false,
674    };
675
676    window_state_borrow.last_fresh_keydown = Some((keystroke, Some(chars)));
677    if let Some(mut callback) = window_state_borrow.event_callback.take() {
678        drop(window_state_borrow);
679        callback(event);
680        window_state.borrow_mut().event_callback = Some(callback);
681    }
682}
683
684extern "C" fn send_event(this: &Object, _: Sel, native_event: id) {
685    unsafe {
686        let () = msg_send![super(this, class!(NSWindow)), sendEvent: native_event];
687    }
688}
689
690extern "C" fn window_did_resize(this: &Object, _: Sel, _: id) {
691    let window_state = unsafe { get_window_state(this) };
692    window_state.as_ref().borrow().move_traffic_light();
693}
694
695extern "C" fn window_did_change_key_status(this: &Object, selector: Sel, _: id) {
696    let is_active = if selector == sel!(windowDidBecomeKey:) {
697        true
698    } else if selector == sel!(windowDidResignKey:) {
699        false
700    } else {
701        unreachable!();
702    };
703
704    let window_state = unsafe { get_window_state(this) };
705    let executor = window_state.as_ref().borrow().executor.clone();
706    executor
707        .spawn(async move {
708            let mut window_state_borrow = window_state.as_ref().borrow_mut();
709            if let Some(mut callback) = window_state_borrow.activate_callback.take() {
710                drop(window_state_borrow);
711                callback(is_active);
712                window_state.borrow_mut().activate_callback = Some(callback);
713            };
714        })
715        .detach();
716}
717
718extern "C" fn window_should_close(this: &Object, _: Sel, _: id) -> BOOL {
719    let window_state = unsafe { get_window_state(this) };
720    let mut window_state_borrow = window_state.as_ref().borrow_mut();
721    if let Some(mut callback) = window_state_borrow.should_close_callback.take() {
722        drop(window_state_borrow);
723        let should_close = callback();
724        window_state.borrow_mut().should_close_callback = Some(callback);
725        should_close as BOOL
726    } else {
727        YES
728    }
729}
730
731extern "C" fn close_window(this: &Object, _: Sel) {
732    unsafe {
733        let close_callback = {
734            let window_state = get_window_state(this);
735            window_state
736                .as_ref()
737                .try_borrow_mut()
738                .ok()
739                .and_then(|mut window_state| window_state.close_callback.take())
740        };
741
742        if let Some(callback) = close_callback {
743            callback();
744        }
745
746        let () = msg_send![super(this, class!(NSWindow)), close];
747    }
748}
749
750extern "C" fn make_backing_layer(this: &Object, _: Sel) -> id {
751    let window_state = unsafe { get_window_state(this) };
752    let window_state = window_state.as_ref().borrow();
753    window_state.layer
754}
755
756extern "C" fn view_did_change_backing_properties(this: &Object, _: Sel) {
757    let window_state = unsafe { get_window_state(this) };
758    let mut window_state_borrow = window_state.as_ref().borrow_mut();
759
760    unsafe {
761        let scale_factor = window_state_borrow.scale_factor() as f64;
762        let size = window_state_borrow.size();
763        let drawable_size: NSSize = NSSize {
764            width: size.x() as f64 * scale_factor,
765            height: size.y() as f64 * scale_factor,
766        };
767
768        let _: () = msg_send![window_state_borrow.layer, setContentsScale: scale_factor];
769        let _: () = msg_send![window_state_borrow.layer, setDrawableSize: drawable_size];
770    }
771
772    if let Some(mut callback) = window_state_borrow.resize_callback.take() {
773        drop(window_state_borrow);
774        callback();
775        window_state.as_ref().borrow_mut().resize_callback = Some(callback);
776    };
777}
778
779extern "C" fn set_frame_size(this: &Object, _: Sel, size: NSSize) {
780    let window_state = unsafe { get_window_state(this) };
781    let mut window_state_borrow = window_state.as_ref().borrow_mut();
782
783    if window_state_borrow.size() == vec2f(size.width as f32, size.height as f32) {
784        return;
785    }
786
787    unsafe {
788        let _: () = msg_send![super(this, class!(NSView)), setFrameSize: size];
789    }
790
791    let scale_factor = window_state_borrow.scale_factor() as f64;
792    let drawable_size: NSSize = NSSize {
793        width: size.width * scale_factor,
794        height: size.height * scale_factor,
795    };
796
797    unsafe {
798        let _: () = msg_send![window_state_borrow.layer, setDrawableSize: drawable_size];
799    }
800
801    if let Some(mut callback) = window_state_borrow.resize_callback.take() {
802        drop(window_state_borrow);
803        callback();
804        window_state.borrow_mut().resize_callback = Some(callback);
805    };
806}
807
808extern "C" fn display_layer(this: &Object, _: Sel, _: id) {
809    unsafe {
810        let window_state = get_window_state(this);
811        let mut window_state = window_state.as_ref().borrow_mut();
812
813        if let Some(scene) = window_state.scene_to_render.take() {
814            let drawable: &metal::MetalDrawableRef = msg_send![window_state.layer, nextDrawable];
815            let command_queue = window_state.command_queue.clone();
816            let command_buffer = command_queue.new_command_buffer();
817
818            let size = window_state.size();
819            let scale_factor = window_state.scale_factor();
820
821            window_state.renderer.render(
822                &scene,
823                size * scale_factor,
824                command_buffer,
825                drawable.texture(),
826            );
827
828            command_buffer.commit();
829            command_buffer.wait_until_completed();
830            drawable.present();
831        };
832    }
833}
834
835async fn synthetic_drag(
836    window_state: Weak<RefCell<WindowState>>,
837    drag_id: usize,
838    position: Vector2F,
839) {
840    loop {
841        Timer::after(Duration::from_millis(16)).await;
842        if let Some(window_state) = window_state.upgrade() {
843            let mut window_state_borrow = window_state.borrow_mut();
844            if window_state_borrow.synthetic_drag_counter == drag_id {
845                if let Some(mut callback) = window_state_borrow.event_callback.take() {
846                    drop(window_state_borrow);
847                    callback(Event::LeftMouseDragged {
848                        // TODO: Make sure empty modifiers is correct for this
849                        position,
850                        shift: false,
851                        ctrl: false,
852                        alt: false,
853                        cmd: false,
854                    });
855                    window_state.borrow_mut().event_callback = Some(callback);
856                }
857            } else {
858                break;
859            }
860        }
861    }
862}
863
864unsafe fn ns_string(string: &str) -> id {
865    NSString::alloc(nil).init_str(string).autorelease()
866}