1use super::{ns_string, renderer, MacDisplay, NSRange};
2use crate::{
3 platform::PlatformInputHandler, point, px, size, AnyWindowHandle, Bounds, DevicePixels,
4 DisplayLink, ExternalPaths, FileDropEvent, ForegroundExecutor, KeyDownEvent, Keystroke,
5 Modifiers, ModifiersChangedEvent, MouseButton, MouseDownEvent, MouseMoveEvent, MouseUpEvent,
6 Pixels, PlatformAtlas, PlatformDisplay, PlatformInput, PlatformWindow, Point, PromptLevel,
7 Size, Timer, WindowAppearance, WindowBackgroundAppearance, WindowKind, WindowParams,
8};
9use block::ConcreteBlock;
10use cocoa::{
11 appkit::{
12 CGPoint, NSApplication, NSBackingStoreBuffered, NSColor, NSEvent, NSEventModifierFlags,
13 NSFilenamesPboardType, NSPasteboard, NSScreen, NSView, NSViewHeightSizable,
14 NSViewWidthSizable, NSWindow, NSWindowButton, NSWindowCollectionBehavior,
15 NSWindowOcclusionState, NSWindowStyleMask, NSWindowTitleVisibility,
16 },
17 base::{id, nil},
18 foundation::{
19 NSArray, NSAutoreleasePool, NSDictionary, NSFastEnumeration, NSInteger, NSPoint, NSRect,
20 NSSize, NSString, NSUInteger,
21 },
22};
23use core_graphics::display::{CGDirectDisplayID, CGRect};
24use ctor::ctor;
25use futures::channel::oneshot;
26use objc::{
27 class,
28 declare::ClassDecl,
29 msg_send,
30 runtime::{Class, Object, Protocol, Sel, BOOL, NO, YES},
31 sel, sel_impl,
32};
33use parking_lot::Mutex;
34use raw_window_handle as rwh;
35use smallvec::SmallVec;
36use std::{
37 any::Any,
38 cell::Cell,
39 ffi::{c_void, CStr},
40 mem,
41 ops::Range,
42 os::raw::c_char,
43 path::PathBuf,
44 ptr::{self, NonNull},
45 rc::Rc,
46 sync::{Arc, Weak},
47 time::Duration,
48};
49use util::ResultExt;
50
51const WINDOW_STATE_IVAR: &str = "windowState";
52
53static mut WINDOW_CLASS: *const Class = ptr::null();
54static mut PANEL_CLASS: *const Class = ptr::null();
55static mut VIEW_CLASS: *const Class = ptr::null();
56
57#[allow(non_upper_case_globals)]
58const NSWindowStyleMaskNonactivatingPanel: NSWindowStyleMask =
59 unsafe { NSWindowStyleMask::from_bits_unchecked(1 << 7) };
60#[allow(non_upper_case_globals)]
61const NSNormalWindowLevel: NSInteger = 0;
62#[allow(non_upper_case_globals)]
63const NSPopUpWindowLevel: NSInteger = 101;
64#[allow(non_upper_case_globals)]
65const NSTrackingMouseEnteredAndExited: NSUInteger = 0x01;
66#[allow(non_upper_case_globals)]
67const NSTrackingMouseMoved: NSUInteger = 0x02;
68#[allow(non_upper_case_globals)]
69const NSTrackingActiveAlways: NSUInteger = 0x80;
70#[allow(non_upper_case_globals)]
71const NSTrackingInVisibleRect: NSUInteger = 0x200;
72#[allow(non_upper_case_globals)]
73const NSWindowAnimationBehaviorUtilityWindow: NSInteger = 4;
74#[allow(non_upper_case_globals)]
75const NSViewLayerContentsRedrawDuringViewResize: NSInteger = 2;
76// https://developer.apple.com/documentation/appkit/nsdragoperation
77type NSDragOperation = NSUInteger;
78#[allow(non_upper_case_globals)]
79const NSDragOperationNone: NSDragOperation = 0;
80#[allow(non_upper_case_globals)]
81const NSDragOperationCopy: NSDragOperation = 1;
82
83#[link(name = "CoreGraphics", kind = "framework")]
84extern "C" {
85 // Widely used private APIs; Apple uses them for their Terminal.app.
86 fn CGSMainConnectionID() -> id;
87 fn CGSSetWindowBackgroundBlurRadius(
88 connection_id: id,
89 window_id: NSInteger,
90 radius: i64,
91 ) -> i32;
92}
93
94#[ctor]
95unsafe fn build_classes() {
96 WINDOW_CLASS = build_window_class("GPUIWindow", class!(NSWindow));
97 PANEL_CLASS = build_window_class("GPUIPanel", class!(NSPanel));
98 VIEW_CLASS = {
99 let mut decl = ClassDecl::new("GPUIView", class!(NSView)).unwrap();
100 decl.add_ivar::<*mut c_void>(WINDOW_STATE_IVAR);
101
102 decl.add_method(sel!(dealloc), dealloc_view as extern "C" fn(&Object, Sel));
103
104 decl.add_method(
105 sel!(performKeyEquivalent:),
106 handle_key_equivalent as extern "C" fn(&Object, Sel, id) -> BOOL,
107 );
108 decl.add_method(
109 sel!(keyDown:),
110 handle_key_down as extern "C" fn(&Object, Sel, id),
111 );
112 decl.add_method(
113 sel!(mouseDown:),
114 handle_view_event as extern "C" fn(&Object, Sel, id),
115 );
116 decl.add_method(
117 sel!(mouseUp:),
118 handle_view_event as extern "C" fn(&Object, Sel, id),
119 );
120 decl.add_method(
121 sel!(rightMouseDown:),
122 handle_view_event as extern "C" fn(&Object, Sel, id),
123 );
124 decl.add_method(
125 sel!(rightMouseUp:),
126 handle_view_event as extern "C" fn(&Object, Sel, id),
127 );
128 decl.add_method(
129 sel!(otherMouseDown:),
130 handle_view_event as extern "C" fn(&Object, Sel, id),
131 );
132 decl.add_method(
133 sel!(otherMouseUp:),
134 handle_view_event as extern "C" fn(&Object, Sel, id),
135 );
136 decl.add_method(
137 sel!(mouseMoved:),
138 handle_view_event as extern "C" fn(&Object, Sel, id),
139 );
140 decl.add_method(
141 sel!(mouseExited:),
142 handle_view_event as extern "C" fn(&Object, Sel, id),
143 );
144 decl.add_method(
145 sel!(mouseDragged:),
146 handle_view_event as extern "C" fn(&Object, Sel, id),
147 );
148 decl.add_method(
149 sel!(scrollWheel:),
150 handle_view_event as extern "C" fn(&Object, Sel, id),
151 );
152 decl.add_method(
153 sel!(flagsChanged:),
154 handle_view_event as extern "C" fn(&Object, Sel, id),
155 );
156 decl.add_method(
157 sel!(cancelOperation:),
158 cancel_operation as extern "C" fn(&Object, Sel, id),
159 );
160
161 decl.add_method(
162 sel!(makeBackingLayer),
163 make_backing_layer as extern "C" fn(&Object, Sel) -> id,
164 );
165
166 decl.add_protocol(Protocol::get("CALayerDelegate").unwrap());
167 decl.add_method(
168 sel!(viewDidChangeBackingProperties),
169 view_did_change_backing_properties as extern "C" fn(&Object, Sel),
170 );
171 decl.add_method(
172 sel!(setFrameSize:),
173 set_frame_size as extern "C" fn(&Object, Sel, NSSize),
174 );
175 decl.add_method(
176 sel!(displayLayer:),
177 display_layer as extern "C" fn(&Object, Sel, id),
178 );
179
180 decl.add_protocol(Protocol::get("NSTextInputClient").unwrap());
181 decl.add_method(
182 sel!(validAttributesForMarkedText),
183 valid_attributes_for_marked_text as extern "C" fn(&Object, Sel) -> id,
184 );
185 decl.add_method(
186 sel!(hasMarkedText),
187 has_marked_text as extern "C" fn(&Object, Sel) -> BOOL,
188 );
189 decl.add_method(
190 sel!(markedRange),
191 marked_range as extern "C" fn(&Object, Sel) -> NSRange,
192 );
193 decl.add_method(
194 sel!(selectedRange),
195 selected_range as extern "C" fn(&Object, Sel) -> NSRange,
196 );
197 decl.add_method(
198 sel!(firstRectForCharacterRange:actualRange:),
199 first_rect_for_character_range as extern "C" fn(&Object, Sel, NSRange, id) -> NSRect,
200 );
201 decl.add_method(
202 sel!(insertText:replacementRange:),
203 insert_text as extern "C" fn(&Object, Sel, id, NSRange),
204 );
205 decl.add_method(
206 sel!(setMarkedText:selectedRange:replacementRange:),
207 set_marked_text as extern "C" fn(&Object, Sel, id, NSRange, NSRange),
208 );
209 decl.add_method(sel!(unmarkText), unmark_text as extern "C" fn(&Object, Sel));
210 decl.add_method(
211 sel!(attributedSubstringForProposedRange:actualRange:),
212 attributed_substring_for_proposed_range
213 as extern "C" fn(&Object, Sel, NSRange, *mut c_void) -> id,
214 );
215 decl.add_method(
216 sel!(viewDidChangeEffectiveAppearance),
217 view_did_change_effective_appearance as extern "C" fn(&Object, Sel),
218 );
219
220 // Suppress beep on keystrokes with modifier keys.
221 decl.add_method(
222 sel!(doCommandBySelector:),
223 do_command_by_selector as extern "C" fn(&Object, Sel, Sel),
224 );
225
226 decl.add_method(
227 sel!(acceptsFirstMouse:),
228 accepts_first_mouse as extern "C" fn(&Object, Sel, id) -> BOOL,
229 );
230
231 decl.register()
232 };
233}
234
235pub(crate) fn convert_mouse_position(position: NSPoint, window_height: Pixels) -> Point<Pixels> {
236 point(
237 px(position.x as f32),
238 // MacOS screen coordinates are relative to bottom left
239 window_height - px(position.y as f32),
240 )
241}
242
243unsafe fn build_window_class(name: &'static str, superclass: &Class) -> *const Class {
244 let mut decl = ClassDecl::new(name, superclass).unwrap();
245 decl.add_ivar::<*mut c_void>(WINDOW_STATE_IVAR);
246 decl.add_method(sel!(dealloc), dealloc_window as extern "C" fn(&Object, Sel));
247 decl.add_method(
248 sel!(canBecomeMainWindow),
249 yes as extern "C" fn(&Object, Sel) -> BOOL,
250 );
251 decl.add_method(
252 sel!(canBecomeKeyWindow),
253 yes as extern "C" fn(&Object, Sel) -> BOOL,
254 );
255 decl.add_method(
256 sel!(windowDidResize:),
257 window_did_resize as extern "C" fn(&Object, Sel, id),
258 );
259 decl.add_method(
260 sel!(windowDidChangeOcclusionState:),
261 window_did_change_occlusion_state as extern "C" fn(&Object, Sel, id),
262 );
263 decl.add_method(
264 sel!(windowWillEnterFullScreen:),
265 window_will_enter_fullscreen as extern "C" fn(&Object, Sel, id),
266 );
267 decl.add_method(
268 sel!(windowWillExitFullScreen:),
269 window_will_exit_fullscreen as extern "C" fn(&Object, Sel, id),
270 );
271 decl.add_method(
272 sel!(windowDidMove:),
273 window_did_move as extern "C" fn(&Object, Sel, id),
274 );
275 decl.add_method(
276 sel!(windowDidChangeScreen:),
277 window_did_change_screen as extern "C" fn(&Object, Sel, id),
278 );
279 decl.add_method(
280 sel!(windowDidBecomeKey:),
281 window_did_change_key_status as extern "C" fn(&Object, Sel, id),
282 );
283 decl.add_method(
284 sel!(windowDidResignKey:),
285 window_did_change_key_status as extern "C" fn(&Object, Sel, id),
286 );
287 decl.add_method(
288 sel!(windowShouldClose:),
289 window_should_close as extern "C" fn(&Object, Sel, id) -> BOOL,
290 );
291
292 decl.add_method(sel!(close), close_window as extern "C" fn(&Object, Sel));
293
294 decl.add_method(
295 sel!(draggingEntered:),
296 dragging_entered as extern "C" fn(&Object, Sel, id) -> NSDragOperation,
297 );
298 decl.add_method(
299 sel!(draggingUpdated:),
300 dragging_updated as extern "C" fn(&Object, Sel, id) -> NSDragOperation,
301 );
302 decl.add_method(
303 sel!(draggingExited:),
304 dragging_exited as extern "C" fn(&Object, Sel, id),
305 );
306 decl.add_method(
307 sel!(performDragOperation:),
308 perform_drag_operation as extern "C" fn(&Object, Sel, id) -> BOOL,
309 );
310 decl.add_method(
311 sel!(concludeDragOperation:),
312 conclude_drag_operation as extern "C" fn(&Object, Sel, id),
313 );
314 decl.add_method(
315 sel!(windowDidMiniaturize:),
316 window_did_miniaturize as extern "C" fn(&Object, Sel, id),
317 );
318 decl.add_method(
319 sel!(windowDidDeminiaturize:),
320 window_did_deminiaturize as extern "C" fn(&Object, Sel, id),
321 );
322
323 decl.register()
324}
325
326#[allow(clippy::enum_variant_names)]
327enum ImeInput {
328 InsertText(String, Option<Range<usize>>),
329 SetMarkedText(String, Option<Range<usize>>, Option<Range<usize>>),
330 UnmarkText,
331}
332
333struct MacWindowState {
334 handle: AnyWindowHandle,
335 executor: ForegroundExecutor,
336 native_window: id,
337 native_view: NonNull<Object>,
338 display_link: Option<DisplayLink>,
339 renderer: renderer::Renderer,
340 request_frame_callback: Option<Box<dyn FnMut()>>,
341 event_callback: Option<Box<dyn FnMut(PlatformInput) -> crate::DispatchEventResult>>,
342 activate_callback: Option<Box<dyn FnMut(bool)>>,
343 resize_callback: Option<Box<dyn FnMut(Size<Pixels>, f32)>>,
344 fullscreen_callback: Option<Box<dyn FnMut(bool)>>,
345 moved_callback: Option<Box<dyn FnMut()>>,
346 should_close_callback: Option<Box<dyn FnMut() -> bool>>,
347 close_callback: Option<Box<dyn FnOnce()>>,
348 appearance_changed_callback: Option<Box<dyn FnMut()>>,
349 input_handler: Option<PlatformInputHandler>,
350 last_key_equivalent: Option<KeyDownEvent>,
351 synthetic_drag_counter: usize,
352 last_fresh_keydown: Option<Keystroke>,
353 traffic_light_position: Option<Point<Pixels>>,
354 previous_modifiers_changed_event: Option<PlatformInput>,
355 // State tracking what the IME did after the last request
356 input_during_keydown: Option<SmallVec<[ImeInput; 1]>>,
357 previous_keydown_inserted_text: Option<String>,
358 external_files_dragged: bool,
359 // Whether the next left-mouse click is also the focusing click.
360 first_mouse: bool,
361 minimized: bool,
362}
363
364impl MacWindowState {
365 fn move_traffic_light(&self) {
366 if let Some(traffic_light_position) = self.traffic_light_position {
367 if self.is_fullscreen() {
368 // Moving traffic lights while fullscreen doesn't work,
369 // see https://github.com/zed-industries/zed/issues/4712
370 return;
371 }
372
373 let titlebar_height = self.titlebar_height();
374
375 unsafe {
376 let close_button: id = msg_send![
377 self.native_window,
378 standardWindowButton: NSWindowButton::NSWindowCloseButton
379 ];
380 let min_button: id = msg_send![
381 self.native_window,
382 standardWindowButton: NSWindowButton::NSWindowMiniaturizeButton
383 ];
384 let zoom_button: id = msg_send![
385 self.native_window,
386 standardWindowButton: NSWindowButton::NSWindowZoomButton
387 ];
388
389 let mut close_button_frame: CGRect = msg_send![close_button, frame];
390 let mut min_button_frame: CGRect = msg_send![min_button, frame];
391 let mut zoom_button_frame: CGRect = msg_send![zoom_button, frame];
392 let mut origin = point(
393 traffic_light_position.x,
394 titlebar_height
395 - traffic_light_position.y
396 - px(close_button_frame.size.height as f32),
397 );
398 let button_spacing =
399 px((min_button_frame.origin.x - close_button_frame.origin.x) as f32);
400
401 close_button_frame.origin = CGPoint::new(origin.x.into(), origin.y.into());
402 let _: () = msg_send![close_button, setFrame: close_button_frame];
403 origin.x += button_spacing;
404
405 min_button_frame.origin = CGPoint::new(origin.x.into(), origin.y.into());
406 let _: () = msg_send![min_button, setFrame: min_button_frame];
407 origin.x += button_spacing;
408
409 zoom_button_frame.origin = CGPoint::new(origin.x.into(), origin.y.into());
410 let _: () = msg_send![zoom_button, setFrame: zoom_button_frame];
411 origin.x += button_spacing;
412 }
413 }
414 }
415
416 fn start_display_link(&mut self) {
417 self.stop_display_link();
418 let display_id = unsafe { display_id_for_screen(self.native_window.screen()) };
419 if let Some(mut display_link) =
420 DisplayLink::new(display_id, self.native_view.as_ptr() as *mut c_void, step).log_err()
421 {
422 display_link.start().log_err();
423 self.display_link = Some(display_link);
424 }
425 }
426
427 fn stop_display_link(&mut self) {
428 self.display_link = None;
429 }
430
431 fn is_maximized(&self) -> bool {
432 unsafe {
433 let bounds = self.bounds();
434 let screen_size = self.native_window.screen().visibleFrame().into();
435 bounds.size == screen_size
436 }
437 }
438
439 fn is_minimized(&self) -> bool {
440 self.minimized
441 }
442
443 fn is_fullscreen(&self) -> bool {
444 unsafe {
445 let style_mask = self.native_window.styleMask();
446 style_mask.contains(NSWindowStyleMask::NSFullScreenWindowMask)
447 }
448 }
449
450 fn bounds(&self) -> Bounds<DevicePixels> {
451 let mut window_frame = unsafe { NSWindow::frame(self.native_window) };
452 let screen_frame = unsafe {
453 let screen = NSWindow::screen(self.native_window);
454 NSScreen::frame(screen)
455 };
456
457 // Flip the y coordinate to be top-left origin
458 window_frame.origin.y =
459 screen_frame.size.height - window_frame.origin.y - window_frame.size.height;
460
461 let bounds = Bounds::new(
462 point(
463 ((window_frame.origin.x - screen_frame.origin.x) as i32).into(),
464 ((window_frame.origin.y - screen_frame.origin.y) as i32).into(),
465 ),
466 size(
467 (window_frame.size.width as i32).into(),
468 (window_frame.size.height as i32).into(),
469 ),
470 );
471 bounds
472 }
473
474 fn content_size(&self) -> Size<Pixels> {
475 let NSSize { width, height, .. } =
476 unsafe { NSView::frame(self.native_window.contentView()) }.size;
477 size(px(width as f32), px(height as f32))
478 }
479
480 fn scale_factor(&self) -> f32 {
481 get_scale_factor(self.native_window)
482 }
483
484 fn update_drawable_size(&mut self, drawable_size: NSSize) {
485 self.renderer.update_drawable_size(Size {
486 width: drawable_size.width,
487 height: drawable_size.height,
488 })
489 }
490
491 fn titlebar_height(&self) -> Pixels {
492 unsafe {
493 let frame = NSWindow::frame(self.native_window);
494 let content_layout_rect: CGRect = msg_send![self.native_window, contentLayoutRect];
495 px((frame.size.height - content_layout_rect.size.height) as f32)
496 }
497 }
498
499 fn to_screen_ns_point(&self, point: Point<Pixels>) -> NSPoint {
500 unsafe {
501 let point = NSPoint::new(
502 point.x.into(),
503 (self.content_size().height - point.y).into(),
504 );
505 msg_send![self.native_window, convertPointToScreen: point]
506 }
507 }
508}
509
510unsafe impl Send for MacWindowState {}
511
512pub(crate) struct MacWindow(Arc<Mutex<MacWindowState>>);
513
514impl MacWindow {
515 pub fn open(
516 handle: AnyWindowHandle,
517 WindowParams {
518 window_background,
519 bounds,
520 titlebar,
521 kind,
522 is_movable,
523 focus,
524 show,
525 display_id,
526 }: WindowParams,
527 executor: ForegroundExecutor,
528 renderer_context: renderer::Context,
529 ) -> Self {
530 unsafe {
531 let pool = NSAutoreleasePool::new(nil);
532
533 let mut style_mask;
534 if let Some(titlebar) = titlebar.as_ref() {
535 style_mask = NSWindowStyleMask::NSClosableWindowMask
536 | NSWindowStyleMask::NSMiniaturizableWindowMask
537 | NSWindowStyleMask::NSResizableWindowMask
538 | NSWindowStyleMask::NSTitledWindowMask;
539
540 if titlebar.appears_transparent {
541 style_mask |= NSWindowStyleMask::NSFullSizeContentViewWindowMask;
542 }
543 } else {
544 style_mask = NSWindowStyleMask::NSTitledWindowMask
545 | NSWindowStyleMask::NSFullSizeContentViewWindowMask;
546 }
547
548 let native_window: id = match kind {
549 WindowKind::Normal => msg_send![WINDOW_CLASS, alloc],
550 WindowKind::PopUp => {
551 style_mask |= NSWindowStyleMaskNonactivatingPanel;
552 msg_send![PANEL_CLASS, alloc]
553 }
554 };
555
556 let display = display_id
557 .and_then(MacDisplay::find_by_id)
558 .unwrap_or_else(|| MacDisplay::primary());
559
560 let mut target_screen = nil;
561 let mut screen_frame = None;
562
563 let screens = NSScreen::screens(nil);
564 let count: u64 = cocoa::foundation::NSArray::count(screens);
565 for i in 0..count {
566 let screen = cocoa::foundation::NSArray::objectAtIndex(screens, i);
567 let frame = NSScreen::visibleFrame(screen);
568 let display_id = display_id_for_screen(screen);
569 if display_id == display.0 {
570 screen_frame = Some(frame);
571 target_screen = screen;
572 }
573 }
574
575 let screen_frame = screen_frame.unwrap_or_else(|| {
576 let screen = NSScreen::mainScreen(nil);
577 target_screen = screen;
578 NSScreen::visibleFrame(screen)
579 });
580
581 let window_rect = NSRect::new(
582 NSPoint::new(
583 screen_frame.origin.x + bounds.origin.x.0 as f64,
584 screen_frame.origin.y
585 + (display.bounds().size.height - bounds.origin.y).0 as f64,
586 ),
587 NSSize::new(bounds.size.width.0 as f64, bounds.size.height.0 as f64),
588 );
589
590 let native_window = native_window.initWithContentRect_styleMask_backing_defer_screen_(
591 window_rect,
592 style_mask,
593 NSBackingStoreBuffered,
594 NO,
595 target_screen,
596 );
597 assert!(!native_window.is_null());
598 let () = msg_send![
599 native_window,
600 registerForDraggedTypes:
601 NSArray::arrayWithObject(nil, NSFilenamesPboardType)
602 ];
603 let () = msg_send![
604 native_window,
605 setReleasedWhenClosed: NO
606 ];
607
608 let native_view: id = msg_send![VIEW_CLASS, alloc];
609 let native_view = NSView::init(native_view);
610 assert!(!native_view.is_null());
611
612 let window_size = {
613 let scale = get_scale_factor(native_window);
614 size(
615 bounds.size.width.0 as f32 * scale,
616 bounds.size.height.0 as f32 * scale,
617 )
618 };
619
620 let mut window = Self(Arc::new(Mutex::new(MacWindowState {
621 handle,
622 executor,
623 native_window,
624 native_view: NonNull::new_unchecked(native_view),
625 display_link: None,
626 renderer: renderer::new_renderer(
627 renderer_context,
628 native_window as *mut _,
629 native_view as *mut _,
630 window_size,
631 ),
632 request_frame_callback: None,
633 event_callback: None,
634 activate_callback: None,
635 resize_callback: None,
636 fullscreen_callback: None,
637 moved_callback: None,
638 should_close_callback: None,
639 close_callback: None,
640 appearance_changed_callback: None,
641 input_handler: None,
642 last_key_equivalent: None,
643 synthetic_drag_counter: 0,
644 last_fresh_keydown: None,
645 traffic_light_position: titlebar
646 .as_ref()
647 .and_then(|titlebar| titlebar.traffic_light_position),
648 previous_modifiers_changed_event: None,
649 input_during_keydown: None,
650 previous_keydown_inserted_text: None,
651 external_files_dragged: false,
652 first_mouse: false,
653 minimized: false,
654 })));
655
656 (*native_window).set_ivar(
657 WINDOW_STATE_IVAR,
658 Arc::into_raw(window.0.clone()) as *const c_void,
659 );
660 native_window.setDelegate_(native_window);
661 (*native_view).set_ivar(
662 WINDOW_STATE_IVAR,
663 Arc::into_raw(window.0.clone()) as *const c_void,
664 );
665
666 if let Some(title) = titlebar
667 .as_ref()
668 .and_then(|t| t.title.as_ref().map(AsRef::as_ref))
669 {
670 native_window.setTitle_(NSString::alloc(nil).init_str(title));
671 }
672
673 native_window.setMovable_(is_movable as BOOL);
674
675 if titlebar.map_or(true, |titlebar| titlebar.appears_transparent) {
676 native_window.setTitlebarAppearsTransparent_(YES);
677 native_window.setTitleVisibility_(NSWindowTitleVisibility::NSWindowTitleHidden);
678 }
679
680 native_view.setAutoresizingMask_(NSViewWidthSizable | NSViewHeightSizable);
681 native_view.setWantsBestResolutionOpenGLSurface_(YES);
682
683 // From winit crate: On Mojave, views automatically become layer-backed shortly after
684 // being added to a native_window. Changing the layer-backedness of a view breaks the
685 // association between the view and its associated OpenGL context. To work around this,
686 // on we explicitly make the view layer-backed up front so that AppKit doesn't do it
687 // itself and break the association with its context.
688 native_view.setWantsLayer(YES);
689 let _: () = msg_send![
690 native_view,
691 setLayerContentsRedrawPolicy: NSViewLayerContentsRedrawDuringViewResize
692 ];
693
694 native_window.setContentView_(native_view.autorelease());
695 native_window.makeFirstResponder_(native_view);
696
697 window.set_background_appearance(window_background);
698
699 match kind {
700 WindowKind::Normal => {
701 native_window.setLevel_(NSNormalWindowLevel);
702 native_window.setAcceptsMouseMovedEvents_(YES);
703 }
704 WindowKind::PopUp => {
705 // Use a tracking area to allow receiving MouseMoved events even when
706 // the window or application aren't active, which is often the case
707 // e.g. for notification windows.
708 let tracking_area: id = msg_send![class!(NSTrackingArea), alloc];
709 let _: () = msg_send![
710 tracking_area,
711 initWithRect: NSRect::new(NSPoint::new(0., 0.), NSSize::new(0., 0.))
712 options: NSTrackingMouseEnteredAndExited | NSTrackingMouseMoved | NSTrackingActiveAlways | NSTrackingInVisibleRect
713 owner: native_view
714 userInfo: nil
715 ];
716 let _: () =
717 msg_send![native_view, addTrackingArea: tracking_area.autorelease()];
718
719 native_window.setLevel_(NSPopUpWindowLevel);
720 let _: () = msg_send![
721 native_window,
722 setAnimationBehavior: NSWindowAnimationBehaviorUtilityWindow
723 ];
724 native_window.setCollectionBehavior_(
725 NSWindowCollectionBehavior::NSWindowCollectionBehaviorCanJoinAllSpaces |
726 NSWindowCollectionBehavior::NSWindowCollectionBehaviorFullScreenAuxiliary
727 );
728 }
729 }
730
731 if focus {
732 native_window.makeKeyAndOrderFront_(nil);
733 } else if show {
734 native_window.orderFront_(nil);
735 }
736
737 // Set the initial position of the window to the specified origin.
738 // Although we already specified the position using `initWithContentRect_styleMask_backing_defer_screen_`,
739 // the window position might be incorrect if the main screen (the screen that contains the window that has focus)
740 // is different from the primary screen.
741 NSWindow::setFrameTopLeftPoint_(native_window, window_rect.origin);
742 window.0.lock().move_traffic_light();
743
744 pool.drain();
745
746 window
747 }
748 }
749
750 pub fn active_window() -> Option<AnyWindowHandle> {
751 unsafe {
752 let app = NSApplication::sharedApplication(nil);
753 let main_window: id = msg_send![app, mainWindow];
754 if msg_send![main_window, isKindOfClass: WINDOW_CLASS] {
755 let handle = get_window_state(&*main_window).lock().handle;
756 Some(handle)
757 } else {
758 None
759 }
760 }
761 }
762}
763
764impl Drop for MacWindow {
765 fn drop(&mut self) {
766 let mut this = self.0.lock();
767 this.renderer.destroy();
768 let window = this.native_window;
769 this.display_link.take();
770 unsafe {
771 this.native_window.setDelegate_(nil);
772 }
773 this.executor
774 .spawn(async move {
775 unsafe {
776 window.close();
777 window.autorelease();
778 }
779 })
780 .detach();
781 }
782}
783
784impl PlatformWindow for MacWindow {
785 fn bounds(&self) -> Bounds<DevicePixels> {
786 self.0.as_ref().lock().bounds()
787 }
788
789 fn is_maximized(&self) -> bool {
790 self.0.as_ref().lock().is_maximized()
791 }
792
793 fn is_minimized(&self) -> bool {
794 self.0.as_ref().lock().is_minimized()
795 }
796
797 fn content_size(&self) -> Size<Pixels> {
798 self.0.as_ref().lock().content_size()
799 }
800
801 fn scale_factor(&self) -> f32 {
802 self.0.as_ref().lock().scale_factor()
803 }
804
805 fn appearance(&self) -> WindowAppearance {
806 unsafe {
807 let appearance: id = msg_send![self.0.lock().native_window, effectiveAppearance];
808 WindowAppearance::from_native(appearance)
809 }
810 }
811
812 fn display(&self) -> Rc<dyn PlatformDisplay> {
813 unsafe {
814 let screen = self.0.lock().native_window.screen();
815 let device_description: id = msg_send![screen, deviceDescription];
816 let screen_number: id = NSDictionary::valueForKey_(
817 device_description,
818 NSString::alloc(nil).init_str("NSScreenNumber"),
819 );
820
821 let screen_number: u32 = msg_send![screen_number, unsignedIntValue];
822
823 Rc::new(MacDisplay(screen_number))
824 }
825 }
826
827 fn mouse_position(&self) -> Point<Pixels> {
828 let position = unsafe {
829 self.0
830 .lock()
831 .native_window
832 .mouseLocationOutsideOfEventStream()
833 };
834 convert_mouse_position(position, self.content_size().height)
835 }
836
837 fn modifiers(&self) -> Modifiers {
838 unsafe {
839 let modifiers: NSEventModifierFlags = msg_send![class!(NSEvent), modifierFlags];
840
841 let control = modifiers.contains(NSEventModifierFlags::NSControlKeyMask);
842 let alt = modifiers.contains(NSEventModifierFlags::NSAlternateKeyMask);
843 let shift = modifiers.contains(NSEventModifierFlags::NSShiftKeyMask);
844 let command = modifiers.contains(NSEventModifierFlags::NSCommandKeyMask);
845 let function = modifiers.contains(NSEventModifierFlags::NSFunctionKeyMask);
846
847 Modifiers {
848 control,
849 alt,
850 shift,
851 platform: command,
852 function,
853 }
854 }
855 }
856
857 fn as_any_mut(&mut self) -> &mut dyn Any {
858 self
859 }
860
861 fn set_input_handler(&mut self, input_handler: PlatformInputHandler) {
862 self.0.as_ref().lock().input_handler = Some(input_handler);
863 }
864
865 fn take_input_handler(&mut self) -> Option<PlatformInputHandler> {
866 self.0.as_ref().lock().input_handler.take()
867 }
868
869 fn prompt(
870 &self,
871 level: PromptLevel,
872 msg: &str,
873 detail: Option<&str>,
874 answers: &[&str],
875 ) -> Option<oneshot::Receiver<usize>> {
876 // macOs applies overrides to modal window buttons after they are added.
877 // Two most important for this logic are:
878 // * Buttons with "Cancel" title will be displayed as the last buttons in the modal
879 // * Last button added to the modal via `addButtonWithTitle` stays focused
880 // * Focused buttons react on "space"/" " keypresses
881 // * Usage of `keyEquivalent`, `makeFirstResponder` or `setInitialFirstResponder` does not change the focus
882 //
883 // See also https://developer.apple.com/documentation/appkit/nsalert/1524532-addbuttonwithtitle#discussion
884 // ```
885 // By default, the first button has a key equivalent of Return,
886 // any button with a title of “Cancel” has a key equivalent of Escape,
887 // and any button with the title “Don’t Save” has a key equivalent of Command-D (but only if it’s not the first button).
888 // ```
889 //
890 // To avoid situations when the last element added is "Cancel" and it gets the focus
891 // (hence stealing both ESC and Space shortcuts), we find and add one non-Cancel button
892 // last, so it gets focus and a Space shortcut.
893 // This way, "Save this file? Yes/No/Cancel"-ish modals will get all three buttons mapped with a key.
894 let latest_non_cancel_label = answers
895 .iter()
896 .enumerate()
897 .rev()
898 .find(|(_, &label)| label != "Cancel")
899 .filter(|&(label_index, _)| label_index > 0);
900
901 unsafe {
902 let alert: id = msg_send![class!(NSAlert), alloc];
903 let alert: id = msg_send![alert, init];
904 let alert_style = match level {
905 PromptLevel::Info => 1,
906 PromptLevel::Warning => 0,
907 PromptLevel::Critical | PromptLevel::Destructive => 2,
908 };
909 let _: () = msg_send![alert, setAlertStyle: alert_style];
910 let _: () = msg_send![alert, setMessageText: ns_string(msg)];
911 if let Some(detail) = detail {
912 let _: () = msg_send![alert, setInformativeText: ns_string(detail)];
913 }
914
915 for (ix, answer) in answers
916 .iter()
917 .enumerate()
918 .filter(|&(ix, _)| Some(ix) != latest_non_cancel_label.map(|(ix, _)| ix))
919 {
920 let button: id = msg_send![alert, addButtonWithTitle: ns_string(answer)];
921 let _: () = msg_send![button, setTag: ix as NSInteger];
922 if level == PromptLevel::Destructive && answer != &"Cancel" {
923 let _: () = msg_send![button, setHasDestructiveAction: YES];
924 }
925 }
926 if let Some((ix, answer)) = latest_non_cancel_label {
927 let button: id = msg_send![alert, addButtonWithTitle: ns_string(answer)];
928 let _: () = msg_send![button, setTag: ix as NSInteger];
929 if level == PromptLevel::Destructive {
930 let _: () = msg_send![button, setHasDestructiveAction: YES];
931 }
932 }
933
934 let (done_tx, done_rx) = oneshot::channel();
935 let done_tx = Cell::new(Some(done_tx));
936 let block = ConcreteBlock::new(move |answer: NSInteger| {
937 if let Some(done_tx) = done_tx.take() {
938 let _ = done_tx.send(answer.try_into().unwrap());
939 }
940 });
941 let block = block.copy();
942 let native_window = self.0.lock().native_window;
943 let executor = self.0.lock().executor.clone();
944 executor
945 .spawn(async move {
946 let _: () = msg_send![
947 alert,
948 beginSheetModalForWindow: native_window
949 completionHandler: block
950 ];
951 })
952 .detach();
953
954 Some(done_rx)
955 }
956 }
957
958 fn activate(&self) {
959 let window = self.0.lock().native_window;
960 let executor = self.0.lock().executor.clone();
961 executor
962 .spawn(async move {
963 unsafe {
964 let _: () = msg_send![window, makeKeyAndOrderFront: nil];
965 }
966 })
967 .detach();
968 }
969
970 fn is_active(&self) -> bool {
971 unsafe { self.0.lock().native_window.isKeyWindow() == YES }
972 }
973
974 fn set_title(&mut self, title: &str) {
975 unsafe {
976 let app = NSApplication::sharedApplication(nil);
977 let window = self.0.lock().native_window;
978 let title = ns_string(title);
979 let _: () = msg_send![app, changeWindowsItem:window title:title filename:false];
980 let _: () = msg_send![window, setTitle: title];
981 self.0.lock().move_traffic_light();
982 }
983 }
984
985 fn set_app_id(&mut self, _app_id: &str) {}
986
987 fn set_background_appearance(&mut self, background_appearance: WindowBackgroundAppearance) {
988 let this = self.0.as_ref().lock();
989 let blur_radius = if background_appearance == WindowBackgroundAppearance::Blurred {
990 80
991 } else {
992 0
993 };
994 let opaque = if background_appearance == WindowBackgroundAppearance::Opaque {
995 YES
996 } else {
997 NO
998 };
999 unsafe {
1000 this.native_window.setOpaque_(opaque);
1001 // Shadows for transparent windows cause artifacts and performance issues
1002 this.native_window.setHasShadow_(opaque);
1003 let clear_color = if opaque == YES {
1004 NSColor::colorWithSRGBRed_green_blue_alpha_(nil, 0f64, 0f64, 0f64, 1f64)
1005 } else {
1006 NSColor::clearColor(nil)
1007 };
1008 this.native_window.setBackgroundColor_(clear_color);
1009 let window_number = this.native_window.windowNumber();
1010 CGSSetWindowBackgroundBlurRadius(CGSMainConnectionID(), window_number, blur_radius);
1011 }
1012 }
1013
1014 fn set_edited(&mut self, edited: bool) {
1015 unsafe {
1016 let window = self.0.lock().native_window;
1017 msg_send![window, setDocumentEdited: edited as BOOL]
1018 }
1019
1020 // Changing the document edited state resets the traffic light position,
1021 // so we have to move it again.
1022 self.0.lock().move_traffic_light();
1023 }
1024
1025 fn show_character_palette(&self) {
1026 let this = self.0.lock();
1027 let window = this.native_window;
1028 this.executor
1029 .spawn(async move {
1030 unsafe {
1031 let app = NSApplication::sharedApplication(nil);
1032 let _: () = msg_send![app, orderFrontCharacterPalette: window];
1033 }
1034 })
1035 .detach();
1036 }
1037
1038 fn minimize(&self) {
1039 let window = self.0.lock().native_window;
1040 unsafe {
1041 window.miniaturize_(nil);
1042 }
1043 }
1044
1045 fn zoom(&self) {
1046 let this = self.0.lock();
1047 let window = this.native_window;
1048 this.executor
1049 .spawn(async move {
1050 unsafe {
1051 window.zoom_(nil);
1052 }
1053 })
1054 .detach();
1055 }
1056
1057 fn toggle_fullscreen(&self) {
1058 let this = self.0.lock();
1059 let window = this.native_window;
1060 this.executor
1061 .spawn(async move {
1062 unsafe {
1063 window.toggleFullScreen_(nil);
1064 }
1065 })
1066 .detach();
1067 }
1068
1069 fn is_fullscreen(&self) -> bool {
1070 let this = self.0.lock();
1071 let window = this.native_window;
1072
1073 unsafe {
1074 window
1075 .styleMask()
1076 .contains(NSWindowStyleMask::NSFullScreenWindowMask)
1077 }
1078 }
1079
1080 fn on_request_frame(&self, callback: Box<dyn FnMut()>) {
1081 self.0.as_ref().lock().request_frame_callback = Some(callback);
1082 }
1083
1084 fn on_input(&self, callback: Box<dyn FnMut(PlatformInput) -> crate::DispatchEventResult>) {
1085 self.0.as_ref().lock().event_callback = Some(callback);
1086 }
1087
1088 fn on_active_status_change(&self, callback: Box<dyn FnMut(bool)>) {
1089 self.0.as_ref().lock().activate_callback = Some(callback);
1090 }
1091
1092 fn on_resize(&self, callback: Box<dyn FnMut(Size<Pixels>, f32)>) {
1093 self.0.as_ref().lock().resize_callback = Some(callback);
1094 }
1095
1096 fn on_fullscreen(&self, callback: Box<dyn FnMut(bool)>) {
1097 self.0.as_ref().lock().fullscreen_callback = Some(callback);
1098 }
1099
1100 fn on_moved(&self, callback: Box<dyn FnMut()>) {
1101 self.0.as_ref().lock().moved_callback = Some(callback);
1102 }
1103
1104 fn on_should_close(&self, callback: Box<dyn FnMut() -> bool>) {
1105 self.0.as_ref().lock().should_close_callback = Some(callback);
1106 }
1107
1108 fn on_close(&self, callback: Box<dyn FnOnce()>) {
1109 self.0.as_ref().lock().close_callback = Some(callback);
1110 }
1111
1112 fn on_appearance_changed(&self, callback: Box<dyn FnMut()>) {
1113 self.0.lock().appearance_changed_callback = Some(callback);
1114 }
1115
1116 fn is_topmost_for_position(&self, position: Point<Pixels>) -> bool {
1117 let self_borrow = self.0.lock();
1118 let self_handle = self_borrow.handle;
1119
1120 unsafe {
1121 let app = NSApplication::sharedApplication(nil);
1122
1123 // Convert back to screen coordinates
1124 let screen_point = self_borrow.to_screen_ns_point(position);
1125
1126 let window_number: NSInteger = msg_send![class!(NSWindow), windowNumberAtPoint:screen_point belowWindowWithWindowNumber:0];
1127 let top_most_window: id = msg_send![app, windowWithWindowNumber: window_number];
1128
1129 let is_panel: BOOL = msg_send![top_most_window, isKindOfClass: PANEL_CLASS];
1130 let is_window: BOOL = msg_send![top_most_window, isKindOfClass: WINDOW_CLASS];
1131 if is_panel == YES || is_window == YES {
1132 let topmost_window = get_window_state(&*top_most_window).lock().handle;
1133 topmost_window == self_handle
1134 } else {
1135 // Someone else's window is on top
1136 false
1137 }
1138 }
1139 }
1140
1141 fn draw(&self, scene: &crate::Scene) {
1142 let mut this = self.0.lock();
1143 this.renderer.draw(scene);
1144 }
1145
1146 fn sprite_atlas(&self) -> Arc<dyn PlatformAtlas> {
1147 self.0.lock().renderer.sprite_atlas().clone()
1148 }
1149}
1150
1151impl rwh::HasWindowHandle for MacWindow {
1152 fn window_handle(&self) -> Result<rwh::WindowHandle<'_>, rwh::HandleError> {
1153 // SAFETY: The AppKitWindowHandle is a wrapper around a pointer to an NSView
1154 unsafe {
1155 Ok(rwh::WindowHandle::borrow_raw(rwh::RawWindowHandle::AppKit(
1156 rwh::AppKitWindowHandle::new(self.0.lock().native_view.cast()),
1157 )))
1158 }
1159 }
1160}
1161
1162impl rwh::HasDisplayHandle for MacWindow {
1163 fn display_handle(&self) -> Result<rwh::DisplayHandle<'_>, rwh::HandleError> {
1164 // SAFETY: This is a no-op on macOS
1165 unsafe {
1166 Ok(rwh::DisplayHandle::borrow_raw(
1167 rwh::AppKitDisplayHandle::new().into(),
1168 ))
1169 }
1170 }
1171}
1172
1173fn get_scale_factor(native_window: id) -> f32 {
1174 let factor = unsafe {
1175 let screen: id = msg_send![native_window, screen];
1176 NSScreen::backingScaleFactor(screen) as f32
1177 };
1178
1179 // We are not certain what triggers this, but it seems that sometimes
1180 // this method would return 0 (https://github.com/zed-industries/zed/issues/6412)
1181 // It seems most likely that this would happen if the window has no screen
1182 // (if it is off-screen), though we'd expect to see viewDidChangeBackingProperties before
1183 // it was rendered for real.
1184 // Regardless, attempt to avoid the issue here.
1185 if factor == 0.0 {
1186 2.
1187 } else {
1188 factor
1189 }
1190}
1191
1192unsafe fn get_window_state(object: &Object) -> Arc<Mutex<MacWindowState>> {
1193 let raw: *mut c_void = *object.get_ivar(WINDOW_STATE_IVAR);
1194 let rc1 = Arc::from_raw(raw as *mut Mutex<MacWindowState>);
1195 let rc2 = rc1.clone();
1196 mem::forget(rc1);
1197 rc2
1198}
1199
1200unsafe fn drop_window_state(object: &Object) {
1201 let raw: *mut c_void = *object.get_ivar(WINDOW_STATE_IVAR);
1202 Arc::from_raw(raw as *mut Mutex<MacWindowState>);
1203}
1204
1205extern "C" fn yes(_: &Object, _: Sel) -> BOOL {
1206 YES
1207}
1208
1209extern "C" fn dealloc_window(this: &Object, _: Sel) {
1210 unsafe {
1211 drop_window_state(this);
1212 let _: () = msg_send![super(this, class!(NSWindow)), dealloc];
1213 }
1214}
1215
1216extern "C" fn dealloc_view(this: &Object, _: Sel) {
1217 unsafe {
1218 drop_window_state(this);
1219 let _: () = msg_send![super(this, class!(NSView)), dealloc];
1220 }
1221}
1222
1223extern "C" fn handle_key_equivalent(this: &Object, _: Sel, native_event: id) -> BOOL {
1224 handle_key_event(this, native_event, true)
1225}
1226
1227extern "C" fn handle_key_down(this: &Object, _: Sel, native_event: id) {
1228 handle_key_event(this, native_event, false);
1229}
1230
1231// Things to test if you're modifying this method:
1232// Brazilian layout:
1233// - `" space` should type a quote
1234// - `" backspace` should delete the marked quote
1235// - `" up` should type the quote, unmark it, and move up one line
1236// - `" cmd-down` should not leave a marked quote behind (it maybe should dispatch the key though?)
1237// - `cmd-ctrl-space` and clicking on an emoji should type it
1238// Czech (QWERTY) layout:
1239// - in vim mode `option-4` should go to end of line (same as $)
1240extern "C" fn handle_key_event(this: &Object, native_event: id, key_equivalent: bool) -> BOOL {
1241 let window_state = unsafe { get_window_state(this) };
1242 let mut lock = window_state.as_ref().lock();
1243
1244 let window_height = lock.content_size().height;
1245 let event = unsafe { PlatformInput::from_native(native_event, Some(window_height)) };
1246
1247 if let Some(PlatformInput::KeyDown(mut event)) = event {
1248 // For certain keystrokes, macOS will first dispatch a "key equivalent" event.
1249 // If that event isn't handled, it will then dispatch a "key down" event. GPUI
1250 // makes no distinction between these two types of events, so we need to ignore
1251 // the "key down" event if we've already just processed its "key equivalent" version.
1252 if key_equivalent {
1253 lock.last_key_equivalent = Some(event.clone());
1254 } else if lock.last_key_equivalent.take().as_ref() == Some(&event) {
1255 return NO;
1256 }
1257
1258 let keydown = event.keystroke.clone();
1259 let fn_modifier = keydown.modifiers.function;
1260 // Ignore events from held-down keys after some of the initially-pressed keys
1261 // were released.
1262 if event.is_held {
1263 if lock.last_fresh_keydown.as_ref() != Some(&keydown) {
1264 return YES;
1265 }
1266 } else {
1267 lock.last_fresh_keydown = Some(keydown.clone());
1268 }
1269 lock.input_during_keydown = Some(SmallVec::new());
1270 drop(lock);
1271
1272 // Send the event to the input context for IME handling, unless the `fn` modifier is
1273 // being pressed.
1274 // this will call back into `insert_text`, etc.
1275 if !fn_modifier {
1276 unsafe {
1277 let input_context: id = msg_send![this, inputContext];
1278 let _: BOOL = msg_send![input_context, handleEvent: native_event];
1279 }
1280 }
1281
1282 let mut handled = false;
1283 let mut lock = window_state.lock();
1284 let previous_keydown_inserted_text = lock.previous_keydown_inserted_text.take();
1285 let mut input_during_keydown = lock.input_during_keydown.take().unwrap();
1286 let mut callback = lock.event_callback.take();
1287 drop(lock);
1288
1289 let last_ime = input_during_keydown.pop();
1290 // on a brazilian keyboard typing `"` and then hitting `up` will cause two IME
1291 // events, one to unmark the quote, and one to send the up arrow.
1292 for ime in input_during_keydown {
1293 send_to_input_handler(this, ime);
1294 }
1295
1296 let is_composing =
1297 with_input_handler(this, |input_handler| input_handler.marked_text_range())
1298 .flatten()
1299 .is_some();
1300
1301 if let Some(ime) = last_ime {
1302 if let ImeInput::InsertText(text, _) = &ime {
1303 if !is_composing {
1304 window_state.lock().previous_keydown_inserted_text = Some(text.clone());
1305 if let Some(callback) = callback.as_mut() {
1306 event.keystroke.ime_key = Some(text.clone());
1307 handled = !callback(PlatformInput::KeyDown(event)).propagate;
1308 }
1309 }
1310 }
1311
1312 if !handled {
1313 handled = true;
1314 send_to_input_handler(this, ime);
1315 }
1316 } else if !is_composing {
1317 let is_held = event.is_held;
1318
1319 if let Some(callback) = callback.as_mut() {
1320 handled = !callback(PlatformInput::KeyDown(event)).propagate;
1321 }
1322
1323 if !handled && is_held {
1324 if let Some(text) = previous_keydown_inserted_text {
1325 // MacOS IME is a bit funky, and even when you've told it there's nothing to
1326 // enter it will still swallow certain keys (e.g. 'f', 'j') and not others
1327 // (e.g. 'n'). This is a problem for certain kinds of views, like the terminal.
1328 with_input_handler(this, |input_handler| {
1329 if input_handler.selected_text_range().is_none() {
1330 handled = true;
1331 input_handler.replace_text_in_range(None, &text)
1332 }
1333 });
1334 window_state.lock().previous_keydown_inserted_text = Some(text);
1335 }
1336 }
1337 }
1338
1339 window_state.lock().event_callback = callback;
1340
1341 handled as BOOL
1342 } else {
1343 NO
1344 }
1345}
1346
1347extern "C" fn handle_view_event(this: &Object, _: Sel, native_event: id) {
1348 let window_state = unsafe { get_window_state(this) };
1349 let weak_window_state = Arc::downgrade(&window_state);
1350 let mut lock = window_state.as_ref().lock();
1351 let window_height = lock.content_size().height;
1352 let event = unsafe { PlatformInput::from_native(native_event, Some(window_height)) };
1353
1354 if let Some(mut event) = event {
1355 match &mut event {
1356 PlatformInput::MouseDown(
1357 event @ MouseDownEvent {
1358 button: MouseButton::Left,
1359 modifiers: Modifiers { control: true, .. },
1360 ..
1361 },
1362 ) => {
1363 // On mac, a ctrl-left click should be handled as a right click.
1364 *event = MouseDownEvent {
1365 button: MouseButton::Right,
1366 modifiers: Modifiers {
1367 control: false,
1368 ..event.modifiers
1369 },
1370 click_count: 1,
1371 ..*event
1372 };
1373 }
1374
1375 // Handles focusing click.
1376 PlatformInput::MouseDown(
1377 event @ MouseDownEvent {
1378 button: MouseButton::Left,
1379 ..
1380 },
1381 ) if (lock.first_mouse) => {
1382 *event = MouseDownEvent {
1383 first_mouse: true,
1384 ..*event
1385 };
1386 lock.first_mouse = false;
1387 }
1388
1389 // Because we map a ctrl-left_down to a right_down -> right_up let's ignore
1390 // the ctrl-left_up to avoid having a mismatch in button down/up events if the
1391 // user is still holding ctrl when releasing the left mouse button
1392 PlatformInput::MouseUp(
1393 event @ MouseUpEvent {
1394 button: MouseButton::Left,
1395 modifiers: Modifiers { control: true, .. },
1396 ..
1397 },
1398 ) => {
1399 *event = MouseUpEvent {
1400 button: MouseButton::Right,
1401 modifiers: Modifiers {
1402 control: false,
1403 ..event.modifiers
1404 },
1405 click_count: 1,
1406 ..*event
1407 };
1408 }
1409
1410 _ => {}
1411 };
1412
1413 match &event {
1414 PlatformInput::MouseMove(
1415 event @ MouseMoveEvent {
1416 pressed_button: Some(_),
1417 ..
1418 },
1419 ) => {
1420 // Synthetic drag is used for selecting long buffer contents while buffer is being scrolled.
1421 // External file drag and drop is able to emit its own synthetic mouse events which will conflict
1422 // with these ones.
1423 if !lock.external_files_dragged {
1424 lock.synthetic_drag_counter += 1;
1425 let executor = lock.executor.clone();
1426 executor
1427 .spawn(synthetic_drag(
1428 weak_window_state,
1429 lock.synthetic_drag_counter,
1430 event.clone(),
1431 ))
1432 .detach();
1433 }
1434 }
1435
1436 PlatformInput::MouseUp(MouseUpEvent { .. }) => {
1437 lock.synthetic_drag_counter += 1;
1438 }
1439
1440 PlatformInput::ModifiersChanged(ModifiersChangedEvent { modifiers }) => {
1441 // Only raise modifiers changed event when they have actually changed
1442 if let Some(PlatformInput::ModifiersChanged(ModifiersChangedEvent {
1443 modifiers: prev_modifiers,
1444 })) = &lock.previous_modifiers_changed_event
1445 {
1446 if prev_modifiers == modifiers {
1447 return;
1448 }
1449 }
1450
1451 lock.previous_modifiers_changed_event = Some(event.clone());
1452 }
1453
1454 _ => {}
1455 }
1456
1457 if let Some(mut callback) = lock.event_callback.take() {
1458 drop(lock);
1459 callback(event);
1460 window_state.lock().event_callback = Some(callback);
1461 }
1462 }
1463}
1464
1465// Allows us to receive `cmd-.` (the shortcut for closing a dialog)
1466// https://bugs.eclipse.org/bugs/show_bug.cgi?id=300620#c6
1467extern "C" fn cancel_operation(this: &Object, _sel: Sel, _sender: id) {
1468 let window_state = unsafe { get_window_state(this) };
1469 let mut lock = window_state.as_ref().lock();
1470
1471 let keystroke = Keystroke {
1472 modifiers: Default::default(),
1473 key: ".".into(),
1474 ime_key: None,
1475 };
1476 let event = PlatformInput::KeyDown(KeyDownEvent {
1477 keystroke: keystroke.clone(),
1478 is_held: false,
1479 });
1480
1481 lock.last_fresh_keydown = Some(keystroke);
1482 if let Some(mut callback) = lock.event_callback.take() {
1483 drop(lock);
1484 callback(event);
1485 window_state.lock().event_callback = Some(callback);
1486 }
1487}
1488
1489extern "C" fn window_did_change_occlusion_state(this: &Object, _: Sel, _: id) {
1490 let window_state = unsafe { get_window_state(this) };
1491 let lock = &mut *window_state.lock();
1492 unsafe {
1493 if lock
1494 .native_window
1495 .occlusionState()
1496 .contains(NSWindowOcclusionState::NSWindowOcclusionStateVisible)
1497 {
1498 lock.start_display_link();
1499 } else {
1500 lock.stop_display_link();
1501 }
1502 }
1503}
1504
1505extern "C" fn window_did_resize(this: &Object, _: Sel, _: id) {
1506 let window_state = unsafe { get_window_state(this) };
1507 window_state.as_ref().lock().move_traffic_light();
1508}
1509
1510extern "C" fn window_will_enter_fullscreen(this: &Object, _: Sel, _: id) {
1511 window_fullscreen_changed(this, true);
1512}
1513
1514extern "C" fn window_will_exit_fullscreen(this: &Object, _: Sel, _: id) {
1515 window_fullscreen_changed(this, false);
1516}
1517
1518fn window_fullscreen_changed(this: &Object, is_fullscreen: bool) {
1519 let window_state = unsafe { get_window_state(this) };
1520 let mut lock = window_state.as_ref().lock();
1521 if let Some(mut callback) = lock.fullscreen_callback.take() {
1522 drop(lock);
1523 callback(is_fullscreen);
1524 window_state.lock().fullscreen_callback = Some(callback);
1525 }
1526}
1527
1528extern "C" fn window_did_move(this: &Object, _: Sel, _: id) {
1529 let window_state = unsafe { get_window_state(this) };
1530 let mut lock = window_state.as_ref().lock();
1531 if let Some(mut callback) = lock.moved_callback.take() {
1532 drop(lock);
1533 callback();
1534 window_state.lock().moved_callback = Some(callback);
1535 }
1536}
1537
1538extern "C" fn window_did_change_screen(this: &Object, _: Sel, _: id) {
1539 let window_state = unsafe { get_window_state(this) };
1540 let mut lock = window_state.as_ref().lock();
1541 lock.start_display_link();
1542}
1543
1544extern "C" fn window_did_change_key_status(this: &Object, selector: Sel, _: id) {
1545 let window_state = unsafe { get_window_state(this) };
1546 let lock = window_state.lock();
1547 let is_active = unsafe { lock.native_window.isKeyWindow() == YES };
1548
1549 // When opening a pop-up while the application isn't active, Cocoa sends a spurious
1550 // `windowDidBecomeKey` message to the previous key window even though that window
1551 // isn't actually key. This causes a bug if the application is later activated while
1552 // the pop-up is still open, making it impossible to activate the previous key window
1553 // even if the pop-up gets closed. The only way to activate it again is to de-activate
1554 // the app and re-activate it, which is a pretty bad UX.
1555 // The following code detects the spurious event and invokes `resignKeyWindow`:
1556 // in theory, we're not supposed to invoke this method manually but it balances out
1557 // the spurious `becomeKeyWindow` event and helps us work around that bug.
1558 if selector == sel!(windowDidBecomeKey:) && !is_active {
1559 unsafe {
1560 let _: () = msg_send![lock.native_window, resignKeyWindow];
1561 return;
1562 }
1563 }
1564
1565 let executor = lock.executor.clone();
1566 drop(lock);
1567 executor
1568 .spawn(async move {
1569 let mut lock = window_state.as_ref().lock();
1570 if let Some(mut callback) = lock.activate_callback.take() {
1571 drop(lock);
1572 callback(is_active);
1573 window_state.lock().activate_callback = Some(callback);
1574 };
1575 })
1576 .detach();
1577}
1578
1579extern "C" fn window_should_close(this: &Object, _: Sel, _: id) -> BOOL {
1580 let window_state = unsafe { get_window_state(this) };
1581 let mut lock = window_state.as_ref().lock();
1582 if let Some(mut callback) = lock.should_close_callback.take() {
1583 drop(lock);
1584 let should_close = callback();
1585 window_state.lock().should_close_callback = Some(callback);
1586 should_close as BOOL
1587 } else {
1588 YES
1589 }
1590}
1591
1592extern "C" fn close_window(this: &Object, _: Sel) {
1593 unsafe {
1594 let close_callback = {
1595 let window_state = get_window_state(this);
1596 let mut lock = window_state.as_ref().lock();
1597 lock.close_callback.take()
1598 };
1599
1600 if let Some(callback) = close_callback {
1601 callback();
1602 }
1603
1604 let _: () = msg_send![super(this, class!(NSWindow)), close];
1605 }
1606}
1607
1608extern "C" fn make_backing_layer(this: &Object, _: Sel) -> id {
1609 let window_state = unsafe { get_window_state(this) };
1610 let window_state = window_state.as_ref().lock();
1611 window_state.renderer.layer_ptr() as id
1612}
1613
1614extern "C" fn view_did_change_backing_properties(this: &Object, _: Sel) {
1615 let window_state = unsafe { get_window_state(this) };
1616 let mut lock = window_state.as_ref().lock();
1617
1618 let scale_factor = lock.scale_factor() as f64;
1619 let size = lock.content_size();
1620 let drawable_size: NSSize = NSSize {
1621 width: f64::from(size.width) * scale_factor,
1622 height: f64::from(size.height) * scale_factor,
1623 };
1624 unsafe {
1625 let _: () = msg_send![
1626 lock.renderer.layer(),
1627 setContentsScale: scale_factor
1628 ];
1629 }
1630
1631 lock.update_drawable_size(drawable_size);
1632
1633 if let Some(mut callback) = lock.resize_callback.take() {
1634 let content_size = lock.content_size();
1635 let scale_factor = lock.scale_factor();
1636 drop(lock);
1637 callback(content_size, scale_factor);
1638 window_state.as_ref().lock().resize_callback = Some(callback);
1639 };
1640}
1641
1642extern "C" fn set_frame_size(this: &Object, _: Sel, size: NSSize) {
1643 let window_state = unsafe { get_window_state(this) };
1644 let mut lock = window_state.as_ref().lock();
1645
1646 if lock.content_size() == size.into() {
1647 return;
1648 }
1649
1650 unsafe {
1651 let _: () = msg_send![super(this, class!(NSView)), setFrameSize: size];
1652 }
1653
1654 let scale_factor = lock.scale_factor() as f64;
1655 let drawable_size: NSSize = NSSize {
1656 width: size.width * scale_factor,
1657 height: size.height * scale_factor,
1658 };
1659
1660 lock.update_drawable_size(drawable_size);
1661
1662 drop(lock);
1663 let mut lock = window_state.lock();
1664 if let Some(mut callback) = lock.resize_callback.take() {
1665 let content_size = lock.content_size();
1666 let scale_factor = lock.scale_factor();
1667 drop(lock);
1668 callback(content_size, scale_factor);
1669 window_state.lock().resize_callback = Some(callback);
1670 };
1671}
1672
1673extern "C" fn display_layer(this: &Object, _: Sel, _: id) {
1674 let window_state = unsafe { get_window_state(this) };
1675 let mut lock = window_state.lock();
1676 if let Some(mut callback) = lock.request_frame_callback.take() {
1677 #[cfg(not(feature = "macos-blade"))]
1678 lock.renderer.set_presents_with_transaction(true);
1679 lock.stop_display_link();
1680 drop(lock);
1681 callback();
1682
1683 let mut lock = window_state.lock();
1684 lock.request_frame_callback = Some(callback);
1685 #[cfg(not(feature = "macos-blade"))]
1686 lock.renderer.set_presents_with_transaction(false);
1687 lock.start_display_link();
1688 }
1689}
1690
1691unsafe extern "C" fn step(view: *mut c_void) {
1692 let view = view as id;
1693 let window_state = unsafe { get_window_state(&*view) };
1694 let mut lock = window_state.lock();
1695
1696 if let Some(mut callback) = lock.request_frame_callback.take() {
1697 drop(lock);
1698 callback();
1699 window_state.lock().request_frame_callback = Some(callback);
1700 }
1701}
1702
1703extern "C" fn valid_attributes_for_marked_text(_: &Object, _: Sel) -> id {
1704 unsafe { msg_send![class!(NSArray), array] }
1705}
1706
1707extern "C" fn has_marked_text(this: &Object, _: Sel) -> BOOL {
1708 with_input_handler(this, |input_handler| input_handler.marked_text_range())
1709 .flatten()
1710 .is_some() as BOOL
1711}
1712
1713extern "C" fn marked_range(this: &Object, _: Sel) -> NSRange {
1714 with_input_handler(this, |input_handler| input_handler.marked_text_range())
1715 .flatten()
1716 .map_or(NSRange::invalid(), |range| range.into())
1717}
1718
1719extern "C" fn selected_range(this: &Object, _: Sel) -> NSRange {
1720 with_input_handler(this, |input_handler| input_handler.selected_text_range())
1721 .flatten()
1722 .map_or(NSRange::invalid(), |range| range.into())
1723}
1724
1725extern "C" fn first_rect_for_character_range(
1726 this: &Object,
1727 _: Sel,
1728 range: NSRange,
1729 _: id,
1730) -> NSRect {
1731 let frame = unsafe {
1732 let window = get_window_state(this).lock().native_window;
1733 NSView::frame(window)
1734 };
1735 with_input_handler(this, |input_handler| {
1736 input_handler.bounds_for_range(range.to_range()?)
1737 })
1738 .flatten()
1739 .map_or(
1740 NSRect::new(NSPoint::new(0., 0.), NSSize::new(0., 0.)),
1741 |bounds| {
1742 NSRect::new(
1743 NSPoint::new(
1744 frame.origin.x + bounds.origin.x.0 as f64,
1745 frame.origin.y + frame.size.height
1746 - bounds.origin.y.0 as f64
1747 - bounds.size.height.0 as f64,
1748 ),
1749 NSSize::new(bounds.size.width.0 as f64, bounds.size.height.0 as f64),
1750 )
1751 },
1752 )
1753}
1754
1755extern "C" fn insert_text(this: &Object, _: Sel, text: id, replacement_range: NSRange) {
1756 unsafe {
1757 let is_attributed_string: BOOL =
1758 msg_send![text, isKindOfClass: [class!(NSAttributedString)]];
1759 let text: id = if is_attributed_string == YES {
1760 msg_send![text, string]
1761 } else {
1762 text
1763 };
1764 let text = CStr::from_ptr(text.UTF8String() as *mut c_char)
1765 .to_str()
1766 .unwrap();
1767 let replacement_range = replacement_range.to_range();
1768 send_to_input_handler(
1769 this,
1770 ImeInput::InsertText(text.to_string(), replacement_range),
1771 );
1772 }
1773}
1774
1775extern "C" fn set_marked_text(
1776 this: &Object,
1777 _: Sel,
1778 text: id,
1779 selected_range: NSRange,
1780 replacement_range: NSRange,
1781) {
1782 unsafe {
1783 let is_attributed_string: BOOL =
1784 msg_send![text, isKindOfClass: [class!(NSAttributedString)]];
1785 let text: id = if is_attributed_string == YES {
1786 msg_send![text, string]
1787 } else {
1788 text
1789 };
1790 let selected_range = selected_range.to_range();
1791 let replacement_range = replacement_range.to_range();
1792 let text = CStr::from_ptr(text.UTF8String() as *mut c_char)
1793 .to_str()
1794 .unwrap();
1795
1796 send_to_input_handler(
1797 this,
1798 ImeInput::SetMarkedText(text.to_string(), replacement_range, selected_range),
1799 );
1800 }
1801}
1802extern "C" fn unmark_text(this: &Object, _: Sel) {
1803 send_to_input_handler(this, ImeInput::UnmarkText);
1804}
1805
1806extern "C" fn attributed_substring_for_proposed_range(
1807 this: &Object,
1808 _: Sel,
1809 range: NSRange,
1810 _actual_range: *mut c_void,
1811) -> id {
1812 with_input_handler(this, |input_handler| {
1813 let range = range.to_range()?;
1814 if range.is_empty() {
1815 return None;
1816 }
1817
1818 let selected_text = input_handler.text_for_range(range)?;
1819 unsafe {
1820 let string: id = msg_send![class!(NSAttributedString), alloc];
1821 let string: id = msg_send![string, initWithString: ns_string(&selected_text)];
1822 Some(string)
1823 }
1824 })
1825 .flatten()
1826 .unwrap_or(nil)
1827}
1828
1829extern "C" fn do_command_by_selector(_: &Object, _: Sel, _: Sel) {}
1830
1831extern "C" fn view_did_change_effective_appearance(this: &Object, _: Sel) {
1832 unsafe {
1833 let state = get_window_state(this);
1834 let mut lock = state.as_ref().lock();
1835 if let Some(mut callback) = lock.appearance_changed_callback.take() {
1836 drop(lock);
1837 callback();
1838 state.lock().appearance_changed_callback = Some(callback);
1839 }
1840 }
1841}
1842
1843extern "C" fn accepts_first_mouse(this: &Object, _: Sel, _: id) -> BOOL {
1844 let window_state = unsafe { get_window_state(this) };
1845 let mut lock = window_state.as_ref().lock();
1846 lock.first_mouse = true;
1847 YES
1848}
1849
1850extern "C" fn dragging_entered(this: &Object, _: Sel, dragging_info: id) -> NSDragOperation {
1851 let window_state = unsafe { get_window_state(this) };
1852 let position = drag_event_position(&window_state, dragging_info);
1853 let paths = external_paths_from_event(dragging_info);
1854 if let Some(event) =
1855 paths.map(|paths| PlatformInput::FileDrop(FileDropEvent::Entered { position, paths }))
1856 {
1857 if send_new_event(&window_state, event) {
1858 window_state.lock().external_files_dragged = true;
1859 return NSDragOperationCopy;
1860 }
1861 }
1862 NSDragOperationNone
1863}
1864
1865extern "C" fn dragging_updated(this: &Object, _: Sel, dragging_info: id) -> NSDragOperation {
1866 let window_state = unsafe { get_window_state(this) };
1867 let position = drag_event_position(&window_state, dragging_info);
1868 if send_new_event(
1869 &window_state,
1870 PlatformInput::FileDrop(FileDropEvent::Pending { position }),
1871 ) {
1872 NSDragOperationCopy
1873 } else {
1874 NSDragOperationNone
1875 }
1876}
1877
1878extern "C" fn dragging_exited(this: &Object, _: Sel, _: id) {
1879 let window_state = unsafe { get_window_state(this) };
1880 send_new_event(
1881 &window_state,
1882 PlatformInput::FileDrop(FileDropEvent::Exited),
1883 );
1884 window_state.lock().external_files_dragged = false;
1885}
1886
1887extern "C" fn perform_drag_operation(this: &Object, _: Sel, dragging_info: id) -> BOOL {
1888 let window_state = unsafe { get_window_state(this) };
1889 let position = drag_event_position(&window_state, dragging_info);
1890 if send_new_event(
1891 &window_state,
1892 PlatformInput::FileDrop(FileDropEvent::Submit { position }),
1893 ) {
1894 YES
1895 } else {
1896 NO
1897 }
1898}
1899
1900fn external_paths_from_event(dragging_info: *mut Object) -> Option<ExternalPaths> {
1901 let mut paths = SmallVec::new();
1902 let pasteboard: id = unsafe { msg_send![dragging_info, draggingPasteboard] };
1903 let filenames = unsafe { NSPasteboard::propertyListForType(pasteboard, NSFilenamesPboardType) };
1904 if filenames == nil {
1905 return None;
1906 }
1907 for file in unsafe { filenames.iter() } {
1908 let path = unsafe {
1909 let f = NSString::UTF8String(file);
1910 CStr::from_ptr(f).to_string_lossy().into_owned()
1911 };
1912 paths.push(PathBuf::from(path))
1913 }
1914 Some(ExternalPaths(paths))
1915}
1916
1917extern "C" fn conclude_drag_operation(this: &Object, _: Sel, _: id) {
1918 let window_state = unsafe { get_window_state(this) };
1919 send_new_event(
1920 &window_state,
1921 PlatformInput::FileDrop(FileDropEvent::Exited),
1922 );
1923}
1924
1925extern "C" fn window_did_miniaturize(this: &Object, _: Sel, _: id) {
1926 let window_state = unsafe { get_window_state(this) };
1927
1928 window_state.lock().minimized = true;
1929}
1930
1931extern "C" fn window_did_deminiaturize(this: &Object, _: Sel, _: id) {
1932 let window_state = unsafe { get_window_state(this) };
1933
1934 window_state.lock().minimized = false;
1935}
1936
1937async fn synthetic_drag(
1938 window_state: Weak<Mutex<MacWindowState>>,
1939 drag_id: usize,
1940 event: MouseMoveEvent,
1941) {
1942 loop {
1943 Timer::after(Duration::from_millis(16)).await;
1944 if let Some(window_state) = window_state.upgrade() {
1945 let mut lock = window_state.lock();
1946 if lock.synthetic_drag_counter == drag_id {
1947 if let Some(mut callback) = lock.event_callback.take() {
1948 drop(lock);
1949 callback(PlatformInput::MouseMove(event.clone()));
1950 window_state.lock().event_callback = Some(callback);
1951 }
1952 } else {
1953 break;
1954 }
1955 }
1956 }
1957}
1958
1959fn send_new_event(window_state_lock: &Mutex<MacWindowState>, e: PlatformInput) -> bool {
1960 let window_state = window_state_lock.lock().event_callback.take();
1961 if let Some(mut callback) = window_state {
1962 callback(e);
1963 window_state_lock.lock().event_callback = Some(callback);
1964 true
1965 } else {
1966 false
1967 }
1968}
1969
1970fn drag_event_position(window_state: &Mutex<MacWindowState>, dragging_info: id) -> Point<Pixels> {
1971 let drag_location: NSPoint = unsafe { msg_send![dragging_info, draggingLocation] };
1972 convert_mouse_position(drag_location, window_state.lock().content_size().height)
1973}
1974
1975fn with_input_handler<F, R>(window: &Object, f: F) -> Option<R>
1976where
1977 F: FnOnce(&mut PlatformInputHandler) -> R,
1978{
1979 let window_state = unsafe { get_window_state(window) };
1980 let mut lock = window_state.as_ref().lock();
1981 if let Some(mut input_handler) = lock.input_handler.take() {
1982 drop(lock);
1983 let result = f(&mut input_handler);
1984 window_state.lock().input_handler = Some(input_handler);
1985 Some(result)
1986 } else {
1987 None
1988 }
1989}
1990
1991fn send_to_input_handler(window: &Object, ime: ImeInput) {
1992 unsafe {
1993 let window_state = get_window_state(window);
1994 let mut lock = window_state.lock();
1995 if let Some(ime_input) = lock.input_during_keydown.as_mut() {
1996 ime_input.push(ime);
1997 return;
1998 }
1999 if let Some(mut input_handler) = lock.input_handler.take() {
2000 drop(lock);
2001 match ime {
2002 ImeInput::InsertText(text, range) => {
2003 input_handler.replace_text_in_range(range, &text)
2004 }
2005 ImeInput::SetMarkedText(text, range, marked_range) => {
2006 input_handler.replace_and_mark_text_in_range(range, &text, marked_range)
2007 }
2008 ImeInput::UnmarkText => input_handler.unmark_text(),
2009 }
2010 window_state.lock().input_handler = Some(input_handler);
2011 }
2012 }
2013}
2014
2015unsafe fn display_id_for_screen(screen: id) -> CGDirectDisplayID {
2016 let device_description = NSScreen::deviceDescription(screen);
2017 let screen_number_key: id = NSString::alloc(nil).init_str("NSScreenNumber");
2018 let screen_number = device_description.objectForKey_(screen_number_key);
2019 let screen_number: NSUInteger = msg_send![screen_number, unsignedIntegerValue];
2020 screen_number as CGDirectDisplayID
2021}