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