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