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