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