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