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