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