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