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