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