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