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!(swipeWithEvent:),
153 handle_view_event as extern "C" fn(&Object, Sel, id),
154 );
155 decl.add_method(
156 sel!(flagsChanged:),
157 handle_view_event as extern "C" fn(&Object, Sel, id),
158 );
159
160 decl.add_method(
161 sel!(makeBackingLayer),
162 make_backing_layer as extern "C" fn(&Object, Sel) -> id,
163 );
164
165 decl.add_protocol(Protocol::get("CALayerDelegate").unwrap());
166 decl.add_method(
167 sel!(viewDidChangeBackingProperties),
168 view_did_change_backing_properties as extern "C" fn(&Object, Sel),
169 );
170 decl.add_method(
171 sel!(setFrameSize:),
172 set_frame_size as extern "C" fn(&Object, Sel, NSSize),
173 );
174 decl.add_method(
175 sel!(displayLayer:),
176 display_layer as extern "C" fn(&Object, Sel, id),
177 );
178
179 decl.add_protocol(Protocol::get("NSTextInputClient").unwrap());
180 decl.add_method(
181 sel!(validAttributesForMarkedText),
182 valid_attributes_for_marked_text as extern "C" fn(&Object, Sel) -> id,
183 );
184 decl.add_method(
185 sel!(hasMarkedText),
186 has_marked_text as extern "C" fn(&Object, Sel) -> BOOL,
187 );
188 decl.add_method(
189 sel!(markedRange),
190 marked_range as extern "C" fn(&Object, Sel) -> NSRange,
191 );
192 decl.add_method(
193 sel!(selectedRange),
194 selected_range as extern "C" fn(&Object, Sel) -> NSRange,
195 );
196 decl.add_method(
197 sel!(firstRectForCharacterRange:actualRange:),
198 first_rect_for_character_range as extern "C" fn(&Object, Sel, NSRange, id) -> NSRect,
199 );
200 decl.add_method(
201 sel!(insertText:replacementRange:),
202 insert_text as extern "C" fn(&Object, Sel, id, NSRange),
203 );
204 decl.add_method(
205 sel!(setMarkedText:selectedRange:replacementRange:),
206 set_marked_text as extern "C" fn(&Object, Sel, id, NSRange, NSRange),
207 );
208 decl.add_method(sel!(unmarkText), unmark_text as extern "C" fn(&Object, Sel));
209 decl.add_method(
210 sel!(attributedSubstringForProposedRange:actualRange:),
211 attributed_substring_for_proposed_range
212 as extern "C" fn(&Object, Sel, NSRange, *mut c_void) -> id,
213 );
214 decl.add_method(
215 sel!(viewDidChangeEffectiveAppearance),
216 view_did_change_effective_appearance as extern "C" fn(&Object, Sel),
217 );
218
219 // Suppress beep on keystrokes with modifier keys.
220 decl.add_method(
221 sel!(doCommandBySelector:),
222 do_command_by_selector as extern "C" fn(&Object, Sel, Sel),
223 );
224
225 decl.add_method(
226 sel!(acceptsFirstMouse:),
227 accepts_first_mouse as extern "C" fn(&Object, Sel, id) -> BOOL,
228 );
229
230 decl.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 Window::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 // and keys with function, as the input handler swallows them.
1266 if is_composing
1267 || (event.keystroke.key_char.is_none()
1268 && !event.keystroke.modifiers.control
1269 && !event.keystroke.modifiers.function)
1270 {
1271 {
1272 let mut lock = window_state.as_ref().lock();
1273 lock.keystroke_for_do_command = Some(event.keystroke.clone());
1274 lock.do_command_handled.take();
1275 drop(lock);
1276 }
1277
1278 let handled: BOOL = unsafe {
1279 let input_context: id = msg_send![this, inputContext];
1280 msg_send![input_context, handleEvent: native_event]
1281 };
1282 window_state.as_ref().lock().keystroke_for_do_command.take();
1283 if let Some(handled) = window_state.as_ref().lock().do_command_handled.take() {
1284 return handled as BOOL;
1285 } else if handled == YES {
1286 return YES;
1287 }
1288
1289 let mut callback = window_state.as_ref().lock().event_callback.take();
1290 let handled: BOOL = if let Some(callback) = callback.as_mut() {
1291 !callback(PlatformInput::KeyDown(event)).propagate as BOOL
1292 } else {
1293 NO
1294 };
1295 window_state.as_ref().lock().event_callback = callback;
1296 return handled as BOOL;
1297 }
1298
1299 let mut callback = window_state.as_ref().lock().event_callback.take();
1300 let handled = if let Some(callback) = callback.as_mut() {
1301 !callback(PlatformInput::KeyDown(event.clone())).propagate as BOOL
1302 } else {
1303 NO
1304 };
1305 window_state.as_ref().lock().event_callback = callback;
1306 if handled == YES {
1307 return YES;
1308 }
1309
1310 if event.is_held {
1311 if let Some(key_char) = event.keystroke.key_char.as_ref() {
1312 let handled = with_input_handler(&this, |input_handler| {
1313 if !input_handler.apple_press_and_hold_enabled() {
1314 input_handler.replace_text_in_range(None, &key_char);
1315 return YES;
1316 }
1317 NO
1318 });
1319 if handled == Some(YES) {
1320 return YES;
1321 }
1322 }
1323 }
1324
1325 // Don't send key equivalents to the input handler,
1326 // or macOS shortcuts like cmd-` will stop working.
1327 if key_equivalent {
1328 return NO;
1329 }
1330
1331 unsafe {
1332 let input_context: id = msg_send![this, inputContext];
1333 msg_send![input_context, handleEvent: native_event]
1334 }
1335}
1336
1337extern "C" fn handle_view_event(this: &Object, _: Sel, native_event: id) {
1338 let window_state = unsafe { get_window_state(this) };
1339 let weak_window_state = Arc::downgrade(&window_state);
1340 let mut lock = window_state.as_ref().lock();
1341 let window_height = lock.content_size().height;
1342 let event = unsafe { PlatformInput::from_native(native_event, Some(window_height)) };
1343
1344 if let Some(mut event) = event {
1345 match &mut event {
1346 PlatformInput::MouseDown(
1347 event @ MouseDownEvent {
1348 button: MouseButton::Left,
1349 modifiers: Modifiers { control: true, .. },
1350 ..
1351 },
1352 ) => {
1353 // On mac, a ctrl-left click should be handled as a right click.
1354 *event = MouseDownEvent {
1355 button: MouseButton::Right,
1356 modifiers: Modifiers {
1357 control: false,
1358 ..event.modifiers
1359 },
1360 click_count: 1,
1361 ..*event
1362 };
1363 }
1364
1365 // Handles focusing click.
1366 PlatformInput::MouseDown(
1367 event @ MouseDownEvent {
1368 button: MouseButton::Left,
1369 ..
1370 },
1371 ) if (lock.first_mouse) => {
1372 *event = MouseDownEvent {
1373 first_mouse: true,
1374 ..*event
1375 };
1376 lock.first_mouse = false;
1377 }
1378
1379 // Because we map a ctrl-left_down to a right_down -> right_up let's ignore
1380 // the ctrl-left_up to avoid having a mismatch in button down/up events if the
1381 // user is still holding ctrl when releasing the left mouse button
1382 PlatformInput::MouseUp(
1383 event @ MouseUpEvent {
1384 button: MouseButton::Left,
1385 modifiers: Modifiers { control: true, .. },
1386 ..
1387 },
1388 ) => {
1389 *event = MouseUpEvent {
1390 button: MouseButton::Right,
1391 modifiers: Modifiers {
1392 control: false,
1393 ..event.modifiers
1394 },
1395 click_count: 1,
1396 ..*event
1397 };
1398 }
1399
1400 _ => {}
1401 };
1402
1403 match &event {
1404 PlatformInput::MouseDown(_) => {
1405 drop(lock);
1406 unsafe {
1407 let input_context: id = msg_send![this, inputContext];
1408 msg_send![input_context, handleEvent: native_event]
1409 }
1410 lock = window_state.as_ref().lock();
1411 }
1412 PlatformInput::MouseMove(
1413 event @ MouseMoveEvent {
1414 pressed_button: Some(_),
1415 ..
1416 },
1417 ) => {
1418 // Synthetic drag is used for selecting long buffer contents while buffer is being scrolled.
1419 // External file drag and drop is able to emit its own synthetic mouse events which will conflict
1420 // with these ones.
1421 if !lock.external_files_dragged {
1422 lock.synthetic_drag_counter += 1;
1423 let executor = lock.executor.clone();
1424 executor
1425 .spawn(synthetic_drag(
1426 weak_window_state,
1427 lock.synthetic_drag_counter,
1428 event.clone(),
1429 ))
1430 .detach();
1431 }
1432 }
1433
1434 PlatformInput::MouseUp(MouseUpEvent { .. }) => {
1435 lock.synthetic_drag_counter += 1;
1436 }
1437
1438 PlatformInput::ModifiersChanged(ModifiersChangedEvent { modifiers }) => {
1439 // Only raise modifiers changed event when they have actually changed
1440 if let Some(PlatformInput::ModifiersChanged(ModifiersChangedEvent {
1441 modifiers: prev_modifiers,
1442 })) = &lock.previous_modifiers_changed_event
1443 {
1444 if prev_modifiers == modifiers {
1445 return;
1446 }
1447 }
1448
1449 lock.previous_modifiers_changed_event = Some(event.clone());
1450 }
1451
1452 _ => {}
1453 }
1454
1455 if let Some(mut callback) = lock.event_callback.take() {
1456 drop(lock);
1457 callback(event);
1458 window_state.lock().event_callback = Some(callback);
1459 }
1460 }
1461}
1462
1463extern "C" fn window_did_change_occlusion_state(this: &Object, _: Sel, _: id) {
1464 let window_state = unsafe { get_window_state(this) };
1465 let lock = &mut *window_state.lock();
1466 unsafe {
1467 if lock
1468 .native_window
1469 .occlusionState()
1470 .contains(NSWindowOcclusionState::NSWindowOcclusionStateVisible)
1471 {
1472 lock.start_display_link();
1473 } else {
1474 lock.stop_display_link();
1475 }
1476 }
1477}
1478
1479extern "C" fn window_did_resize(this: &Object, _: Sel, _: id) {
1480 let window_state = unsafe { get_window_state(this) };
1481 window_state.as_ref().lock().move_traffic_light();
1482}
1483
1484extern "C" fn window_will_enter_fullscreen(this: &Object, _: Sel, _: id) {
1485 let window_state = unsafe { get_window_state(this) };
1486 let mut lock = window_state.as_ref().lock();
1487 lock.fullscreen_restore_bounds = lock.bounds();
1488}
1489
1490extern "C" fn window_did_move(this: &Object, _: Sel, _: id) {
1491 let window_state = unsafe { get_window_state(this) };
1492 let mut lock = window_state.as_ref().lock();
1493 if let Some(mut callback) = lock.moved_callback.take() {
1494 drop(lock);
1495 callback();
1496 window_state.lock().moved_callback = Some(callback);
1497 }
1498}
1499
1500extern "C" fn window_did_change_screen(this: &Object, _: Sel, _: id) {
1501 let window_state = unsafe { get_window_state(this) };
1502 let mut lock = window_state.as_ref().lock();
1503 lock.start_display_link();
1504}
1505
1506extern "C" fn window_did_change_key_status(this: &Object, selector: Sel, _: id) {
1507 let window_state = unsafe { get_window_state(this) };
1508 let lock = window_state.lock();
1509 let is_active = unsafe { lock.native_window.isKeyWindow() == YES };
1510
1511 // When opening a pop-up while the application isn't active, Cocoa sends a spurious
1512 // `windowDidBecomeKey` message to the previous key window even though that window
1513 // isn't actually key. This causes a bug if the application is later activated while
1514 // the pop-up is still open, making it impossible to activate the previous key window
1515 // even if the pop-up gets closed. The only way to activate it again is to de-activate
1516 // the app and re-activate it, which is a pretty bad UX.
1517 // The following code detects the spurious event and invokes `resignKeyWindow`:
1518 // in theory, we're not supposed to invoke this method manually but it balances out
1519 // the spurious `becomeKeyWindow` event and helps us work around that bug.
1520 if selector == sel!(windowDidBecomeKey:) && !is_active {
1521 unsafe {
1522 let _: () = msg_send![lock.native_window, resignKeyWindow];
1523 return;
1524 }
1525 }
1526
1527 let executor = lock.executor.clone();
1528 drop(lock);
1529 executor
1530 .spawn(async move {
1531 let mut lock = window_state.as_ref().lock();
1532 if let Some(mut callback) = lock.activate_callback.take() {
1533 drop(lock);
1534 callback(is_active);
1535 window_state.lock().activate_callback = Some(callback);
1536 };
1537 })
1538 .detach();
1539}
1540
1541extern "C" fn window_should_close(this: &Object, _: Sel, _: id) -> BOOL {
1542 let window_state = unsafe { get_window_state(this) };
1543 let mut lock = window_state.as_ref().lock();
1544 if let Some(mut callback) = lock.should_close_callback.take() {
1545 drop(lock);
1546 let should_close = callback();
1547 window_state.lock().should_close_callback = Some(callback);
1548 should_close as BOOL
1549 } else {
1550 YES
1551 }
1552}
1553
1554extern "C" fn close_window(this: &Object, _: Sel) {
1555 unsafe {
1556 let close_callback = {
1557 let window_state = get_window_state(this);
1558 let mut lock = window_state.as_ref().lock();
1559 lock.close_callback.take()
1560 };
1561
1562 if let Some(callback) = close_callback {
1563 callback();
1564 }
1565
1566 let _: () = msg_send![super(this, class!(NSWindow)), close];
1567 }
1568}
1569
1570extern "C" fn make_backing_layer(this: &Object, _: Sel) -> id {
1571 let window_state = unsafe { get_window_state(this) };
1572 let window_state = window_state.as_ref().lock();
1573 window_state.renderer.layer_ptr() as id
1574}
1575
1576extern "C" fn view_did_change_backing_properties(this: &Object, _: Sel) {
1577 let window_state = unsafe { get_window_state(this) };
1578 let mut lock = window_state.as_ref().lock();
1579
1580 let scale_factor = lock.scale_factor();
1581 let size = lock.content_size();
1582 let drawable_size = size.to_device_pixels(scale_factor);
1583 unsafe {
1584 let _: () = msg_send![
1585 lock.renderer.layer(),
1586 setContentsScale: scale_factor as f64
1587 ];
1588 }
1589
1590 lock.renderer.update_drawable_size(drawable_size);
1591
1592 if let Some(mut callback) = lock.resize_callback.take() {
1593 let content_size = lock.content_size();
1594 let scale_factor = lock.scale_factor();
1595 drop(lock);
1596 callback(content_size, scale_factor);
1597 window_state.as_ref().lock().resize_callback = Some(callback);
1598 };
1599}
1600
1601extern "C" fn set_frame_size(this: &Object, _: Sel, size: NSSize) {
1602 let window_state = unsafe { get_window_state(this) };
1603 let mut lock = window_state.as_ref().lock();
1604
1605 let new_size = Size::<Pixels>::from(size);
1606 if lock.content_size() == new_size {
1607 return;
1608 }
1609
1610 unsafe {
1611 let _: () = msg_send![super(this, class!(NSView)), setFrameSize: size];
1612 }
1613
1614 let scale_factor = lock.scale_factor();
1615 let drawable_size = new_size.to_device_pixels(scale_factor);
1616 lock.renderer.update_drawable_size(drawable_size);
1617
1618 if let Some(mut callback) = lock.resize_callback.take() {
1619 let content_size = lock.content_size();
1620 let scale_factor = lock.scale_factor();
1621 drop(lock);
1622 callback(content_size, scale_factor);
1623 window_state.lock().resize_callback = Some(callback);
1624 };
1625}
1626
1627extern "C" fn display_layer(this: &Object, _: Sel, _: id) {
1628 let window_state = unsafe { get_window_state(this) };
1629 let mut lock = window_state.lock();
1630 if let Some(mut callback) = lock.request_frame_callback.take() {
1631 #[cfg(not(feature = "macos-blade"))]
1632 lock.renderer.set_presents_with_transaction(true);
1633 lock.stop_display_link();
1634 drop(lock);
1635 callback(Default::default());
1636
1637 let mut lock = window_state.lock();
1638 lock.request_frame_callback = Some(callback);
1639 #[cfg(not(feature = "macos-blade"))]
1640 lock.renderer.set_presents_with_transaction(false);
1641 lock.start_display_link();
1642 }
1643}
1644
1645unsafe extern "C" fn step(view: *mut c_void) {
1646 let view = view as id;
1647 let window_state = unsafe { get_window_state(&*view) };
1648 let mut lock = window_state.lock();
1649
1650 if let Some(mut callback) = lock.request_frame_callback.take() {
1651 drop(lock);
1652 callback(Default::default());
1653 window_state.lock().request_frame_callback = Some(callback);
1654 }
1655}
1656
1657extern "C" fn valid_attributes_for_marked_text(_: &Object, _: Sel) -> id {
1658 unsafe { msg_send![class!(NSArray), array] }
1659}
1660
1661extern "C" fn has_marked_text(this: &Object, _: Sel) -> BOOL {
1662 let has_marked_text_result =
1663 with_input_handler(this, |input_handler| input_handler.marked_text_range()).flatten();
1664
1665 has_marked_text_result.is_some() as BOOL
1666}
1667
1668extern "C" fn marked_range(this: &Object, _: Sel) -> NSRange {
1669 let marked_range_result =
1670 with_input_handler(this, |input_handler| input_handler.marked_text_range()).flatten();
1671
1672 marked_range_result.map_or(NSRange::invalid(), |range| range.into())
1673}
1674
1675extern "C" fn selected_range(this: &Object, _: Sel) -> NSRange {
1676 let selected_range_result = with_input_handler(this, |input_handler| {
1677 input_handler.selected_text_range(false)
1678 })
1679 .flatten();
1680
1681 selected_range_result.map_or(NSRange::invalid(), |selection| selection.range.into())
1682}
1683
1684extern "C" fn first_rect_for_character_range(
1685 this: &Object,
1686 _: Sel,
1687 range: NSRange,
1688 _: id,
1689) -> NSRect {
1690 let frame: NSRect = unsafe {
1691 let state = get_window_state(this);
1692 let lock = state.lock();
1693 let mut frame = NSWindow::frame(lock.native_window);
1694 let content_layout_rect: CGRect = msg_send![lock.native_window, contentLayoutRect];
1695 let style_mask: NSWindowStyleMask = msg_send![lock.native_window, styleMask];
1696 if !style_mask.contains(NSWindowStyleMask::NSFullSizeContentViewWindowMask) {
1697 frame.origin.y -= frame.size.height - content_layout_rect.size.height;
1698 }
1699 frame
1700 };
1701 with_input_handler(this, |input_handler| {
1702 input_handler.bounds_for_range(range.to_range()?)
1703 })
1704 .flatten()
1705 .map_or(
1706 NSRect::new(NSPoint::new(0., 0.), NSSize::new(0., 0.)),
1707 |bounds| {
1708 NSRect::new(
1709 NSPoint::new(
1710 frame.origin.x + bounds.origin.x.0 as f64,
1711 frame.origin.y + frame.size.height
1712 - bounds.origin.y.0 as f64
1713 - bounds.size.height.0 as f64,
1714 ),
1715 NSSize::new(bounds.size.width.0 as f64, bounds.size.height.0 as f64),
1716 )
1717 },
1718 )
1719}
1720
1721extern "C" fn insert_text(this: &Object, _: Sel, text: id, replacement_range: NSRange) {
1722 unsafe {
1723 let is_attributed_string: BOOL =
1724 msg_send![text, isKindOfClass: [class!(NSAttributedString)]];
1725 let text: id = if is_attributed_string == YES {
1726 msg_send![text, string]
1727 } else {
1728 text
1729 };
1730
1731 let text = text.to_str();
1732 let replacement_range = replacement_range.to_range();
1733 with_input_handler(this, |input_handler| {
1734 input_handler.replace_text_in_range(replacement_range, &text)
1735 });
1736 }
1737}
1738
1739extern "C" fn set_marked_text(
1740 this: &Object,
1741 _: Sel,
1742 text: id,
1743 selected_range: NSRange,
1744 replacement_range: NSRange,
1745) {
1746 unsafe {
1747 let is_attributed_string: BOOL =
1748 msg_send![text, isKindOfClass: [class!(NSAttributedString)]];
1749 let text: id = if is_attributed_string == YES {
1750 msg_send![text, string]
1751 } else {
1752 text
1753 };
1754 let selected_range = selected_range.to_range();
1755 let replacement_range = replacement_range.to_range();
1756 let text = text.to_str();
1757 with_input_handler(this, |input_handler| {
1758 input_handler.replace_and_mark_text_in_range(replacement_range, &text, selected_range)
1759 });
1760 }
1761}
1762extern "C" fn unmark_text(this: &Object, _: Sel) {
1763 with_input_handler(this, |input_handler| input_handler.unmark_text());
1764}
1765
1766extern "C" fn attributed_substring_for_proposed_range(
1767 this: &Object,
1768 _: Sel,
1769 range: NSRange,
1770 actual_range: *mut c_void,
1771) -> id {
1772 with_input_handler(this, |input_handler| {
1773 let range = range.to_range()?;
1774 if range.is_empty() {
1775 return None;
1776 }
1777 let mut adjusted: Option<Range<usize>> = None;
1778
1779 let selected_text = input_handler.text_for_range(range.clone(), &mut adjusted)?;
1780 if let Some(adjusted) = adjusted {
1781 if adjusted != range {
1782 unsafe { (actual_range as *mut NSRange).write(NSRange::from(adjusted)) };
1783 }
1784 }
1785 unsafe {
1786 let string: id = msg_send![class!(NSAttributedString), alloc];
1787 let string: id = msg_send![string, initWithString: ns_string(&selected_text)];
1788 Some(string)
1789 }
1790 })
1791 .flatten()
1792 .unwrap_or(nil)
1793}
1794
1795// We ignore which selector it asks us to do because the user may have
1796// bound the shortcut to something else.
1797extern "C" fn do_command_by_selector(this: &Object, _: Sel, _: Sel) {
1798 let state = unsafe { get_window_state(this) };
1799 let mut lock = state.as_ref().lock();
1800 let keystroke = lock.keystroke_for_do_command.take();
1801 let mut event_callback = lock.event_callback.take();
1802 drop(lock);
1803
1804 if let Some((keystroke, mut callback)) = keystroke.zip(event_callback.as_mut()) {
1805 let handled = (callback)(PlatformInput::KeyDown(KeyDownEvent {
1806 keystroke,
1807 is_held: false,
1808 }));
1809 state.as_ref().lock().do_command_handled = Some(!handled.propagate);
1810 }
1811
1812 state.as_ref().lock().event_callback = event_callback;
1813}
1814
1815extern "C" fn view_did_change_effective_appearance(this: &Object, _: Sel) {
1816 unsafe {
1817 let state = get_window_state(this);
1818 let mut lock = state.as_ref().lock();
1819 if let Some(mut callback) = lock.appearance_changed_callback.take() {
1820 drop(lock);
1821 callback();
1822 state.lock().appearance_changed_callback = Some(callback);
1823 }
1824 }
1825}
1826
1827extern "C" fn accepts_first_mouse(this: &Object, _: Sel, _: id) -> BOOL {
1828 let window_state = unsafe { get_window_state(this) };
1829 let mut lock = window_state.as_ref().lock();
1830 lock.first_mouse = true;
1831 YES
1832}
1833
1834extern "C" fn dragging_entered(this: &Object, _: Sel, dragging_info: id) -> NSDragOperation {
1835 let window_state = unsafe { get_window_state(this) };
1836 let position = drag_event_position(&window_state, dragging_info);
1837 let paths = external_paths_from_event(dragging_info);
1838 if let Some(event) =
1839 paths.map(|paths| PlatformInput::FileDrop(FileDropEvent::Entered { position, paths }))
1840 {
1841 if send_new_event(&window_state, event) {
1842 window_state.lock().external_files_dragged = true;
1843 return NSDragOperationCopy;
1844 }
1845 }
1846 NSDragOperationNone
1847}
1848
1849extern "C" fn dragging_updated(this: &Object, _: Sel, dragging_info: id) -> NSDragOperation {
1850 let window_state = unsafe { get_window_state(this) };
1851 let position = drag_event_position(&window_state, dragging_info);
1852 if send_new_event(
1853 &window_state,
1854 PlatformInput::FileDrop(FileDropEvent::Pending { position }),
1855 ) {
1856 NSDragOperationCopy
1857 } else {
1858 NSDragOperationNone
1859 }
1860}
1861
1862extern "C" fn dragging_exited(this: &Object, _: Sel, _: id) {
1863 let window_state = unsafe { get_window_state(this) };
1864 send_new_event(
1865 &window_state,
1866 PlatformInput::FileDrop(FileDropEvent::Exited),
1867 );
1868 window_state.lock().external_files_dragged = false;
1869}
1870
1871extern "C" fn perform_drag_operation(this: &Object, _: Sel, dragging_info: id) -> BOOL {
1872 let window_state = unsafe { get_window_state(this) };
1873 let position = drag_event_position(&window_state, dragging_info);
1874 if send_new_event(
1875 &window_state,
1876 PlatformInput::FileDrop(FileDropEvent::Submit { position }),
1877 ) {
1878 YES
1879 } else {
1880 NO
1881 }
1882}
1883
1884fn external_paths_from_event(dragging_info: *mut Object) -> Option<ExternalPaths> {
1885 let mut paths = SmallVec::new();
1886 let pasteboard: id = unsafe { msg_send![dragging_info, draggingPasteboard] };
1887 let filenames = unsafe { NSPasteboard::propertyListForType(pasteboard, NSFilenamesPboardType) };
1888 if filenames == nil {
1889 return None;
1890 }
1891 for file in unsafe { filenames.iter() } {
1892 let path = unsafe {
1893 let f = NSString::UTF8String(file);
1894 CStr::from_ptr(f).to_string_lossy().into_owned()
1895 };
1896 paths.push(PathBuf::from(path))
1897 }
1898 Some(ExternalPaths(paths))
1899}
1900
1901extern "C" fn conclude_drag_operation(this: &Object, _: Sel, _: id) {
1902 let window_state = unsafe { get_window_state(this) };
1903 send_new_event(
1904 &window_state,
1905 PlatformInput::FileDrop(FileDropEvent::Exited),
1906 );
1907}
1908
1909async fn synthetic_drag(
1910 window_state: Weak<Mutex<MacWindowState>>,
1911 drag_id: usize,
1912 event: MouseMoveEvent,
1913) {
1914 loop {
1915 Timer::after(Duration::from_millis(16)).await;
1916 if let Some(window_state) = window_state.upgrade() {
1917 let mut lock = window_state.lock();
1918 if lock.synthetic_drag_counter == drag_id {
1919 if let Some(mut callback) = lock.event_callback.take() {
1920 drop(lock);
1921 callback(PlatformInput::MouseMove(event.clone()));
1922 window_state.lock().event_callback = Some(callback);
1923 }
1924 } else {
1925 break;
1926 }
1927 }
1928 }
1929}
1930
1931fn send_new_event(window_state_lock: &Mutex<MacWindowState>, e: PlatformInput) -> bool {
1932 let window_state = window_state_lock.lock().event_callback.take();
1933 if let Some(mut callback) = window_state {
1934 callback(e);
1935 window_state_lock.lock().event_callback = Some(callback);
1936 true
1937 } else {
1938 false
1939 }
1940}
1941
1942fn drag_event_position(window_state: &Mutex<MacWindowState>, dragging_info: id) -> Point<Pixels> {
1943 let drag_location: NSPoint = unsafe { msg_send![dragging_info, draggingLocation] };
1944 convert_mouse_position(drag_location, window_state.lock().content_size().height)
1945}
1946
1947fn with_input_handler<F, R>(window: &Object, f: F) -> Option<R>
1948where
1949 F: FnOnce(&mut PlatformInputHandler) -> R,
1950{
1951 let window_state = unsafe { get_window_state(window) };
1952 let mut lock = window_state.as_ref().lock();
1953 if let Some(mut input_handler) = lock.input_handler.take() {
1954 drop(lock);
1955 let result = f(&mut input_handler);
1956 window_state.lock().input_handler = Some(input_handler);
1957 Some(result)
1958 } else {
1959 None
1960 }
1961}
1962
1963unsafe fn display_id_for_screen(screen: id) -> CGDirectDisplayID {
1964 let device_description = NSScreen::deviceDescription(screen);
1965 let screen_number_key: id = NSString::alloc(nil).init_str("NSScreenNumber");
1966 let screen_number = device_description.objectForKey_(screen_number_key);
1967 let screen_number: NSUInteger = msg_send![screen_number, unsignedIntegerValue];
1968 screen_number as CGDirectDisplayID
1969}