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