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