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