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