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