1use crate::{
2 BoolExt, DisplayLink, MacDisplay, NSRange, NSStringExt, events::platform_input_from_native,
3 ns_string, renderer,
4};
5#[cfg(any(test, feature = "test-support"))]
6use anyhow::Result;
7use block::ConcreteBlock;
8use cocoa::{
9 appkit::{
10 NSAppKitVersionNumber, NSAppKitVersionNumber12_0, NSApplication, NSBackingStoreBuffered,
11 NSColor, NSEvent, NSEventModifierFlags, NSFilenamesPboardType, NSPasteboard, NSScreen,
12 NSView, NSViewHeightSizable, NSViewWidthSizable, NSVisualEffectMaterial,
13 NSVisualEffectState, NSVisualEffectView, NSWindow, NSWindowButton,
14 NSWindowCollectionBehavior, NSWindowOcclusionState, NSWindowOrderingMode,
15 NSWindowStyleMask, NSWindowTitleVisibility,
16 },
17 base::{id, nil},
18 foundation::{
19 NSArray, NSAutoreleasePool, NSDictionary, NSFastEnumeration, NSInteger, NSNotFound,
20 NSOperatingSystemVersion, NSPoint, NSProcessInfo, NSRect, NSSize, NSString, NSUInteger,
21 NSUserDefaults,
22 },
23};
24use dispatch2::DispatchQueue;
25use gpui::{
26 AnyWindowHandle, BackgroundExecutor, Bounds, Capslock, ExternalPaths, FileDropEvent,
27 ForegroundExecutor, KeyDownEvent, Keystroke, Modifiers, ModifiersChangedEvent, MouseButton,
28 MouseDownEvent, MouseMoveEvent, MouseUpEvent, Pixels, PlatformAtlas, PlatformDisplay,
29 PlatformInput, PlatformInputHandler, PlatformWindow, Point, PromptButton, PromptLevel,
30 RequestFrameOptions, SharedString, Size, SystemWindowTab, WindowAppearance,
31 WindowBackgroundAppearance, WindowBounds, WindowControlArea, WindowKind, WindowParams, point,
32 px, size,
33};
34#[cfg(any(test, feature = "test-support"))]
35use image::RgbaImage;
36
37use core_graphics::display::{CGDirectDisplayID, CGPoint, CGRect};
38use ctor::ctor;
39use futures::channel::oneshot;
40use objc::{
41 class,
42 declare::ClassDecl,
43 msg_send,
44 runtime::{BOOL, Class, NO, Object, Protocol, Sel, YES},
45 sel, sel_impl,
46};
47use parking_lot::Mutex;
48use raw_window_handle as rwh;
49use smallvec::SmallVec;
50use std::{
51 cell::Cell,
52 ffi::{CStr, c_void},
53 mem,
54 ops::Range,
55 path::PathBuf,
56 ptr::{self, NonNull},
57 rc::Rc,
58 sync::{
59 Arc, Weak,
60 atomic::{AtomicBool, Ordering},
61 },
62 time::Duration,
63};
64use util::ResultExt;
65
66const WINDOW_STATE_IVAR: &str = "windowState";
67
68static mut WINDOW_CLASS: *const Class = ptr::null();
69static mut PANEL_CLASS: *const Class = ptr::null();
70static mut VIEW_CLASS: *const Class = ptr::null();
71static mut BLURRED_VIEW_CLASS: *const Class = ptr::null();
72
73#[allow(non_upper_case_globals)]
74const NSWindowStyleMaskNonactivatingPanel: NSWindowStyleMask =
75 NSWindowStyleMask::from_bits_retain(1 << 7);
76// WindowLevel const value ref: https://docs.rs/core-graphics2/0.4.1/src/core_graphics2/window_level.rs.html
77#[allow(non_upper_case_globals)]
78const NSNormalWindowLevel: NSInteger = 0;
79#[allow(non_upper_case_globals)]
80const NSFloatingWindowLevel: NSInteger = 3;
81#[allow(non_upper_case_globals)]
82const NSPopUpWindowLevel: NSInteger = 101;
83#[allow(non_upper_case_globals)]
84const NSTrackingMouseEnteredAndExited: NSUInteger = 0x01;
85#[allow(non_upper_case_globals)]
86const NSTrackingMouseMoved: NSUInteger = 0x02;
87#[allow(non_upper_case_globals)]
88const NSTrackingActiveAlways: NSUInteger = 0x80;
89#[allow(non_upper_case_globals)]
90const NSTrackingInVisibleRect: NSUInteger = 0x200;
91#[allow(non_upper_case_globals)]
92const NSWindowAnimationBehaviorUtilityWindow: NSInteger = 4;
93#[allow(non_upper_case_globals)]
94const NSViewLayerContentsRedrawDuringViewResize: NSInteger = 2;
95// https://developer.apple.com/documentation/appkit/nsdragoperation
96type NSDragOperation = NSUInteger;
97#[allow(non_upper_case_globals)]
98const NSDragOperationNone: NSDragOperation = 0;
99#[allow(non_upper_case_globals)]
100const NSDragOperationCopy: NSDragOperation = 1;
101#[derive(PartialEq)]
102pub enum UserTabbingPreference {
103 Never,
104 Always,
105 InFullScreen,
106}
107
108#[link(name = "CoreGraphics", kind = "framework")]
109unsafe extern "C" {
110 // Widely used private APIs; Apple uses them for their Terminal.app.
111 fn CGSMainConnectionID() -> id;
112 fn CGSSetWindowBackgroundBlurRadius(
113 connection_id: id,
114 window_id: NSInteger,
115 radius: i64,
116 ) -> i32;
117}
118
119#[ctor]
120unsafe fn build_classes() {
121 unsafe {
122 WINDOW_CLASS = build_window_class("GPUIWindow", class!(NSWindow));
123 PANEL_CLASS = build_window_class("GPUIPanel", class!(NSPanel));
124 VIEW_CLASS = {
125 let mut decl = ClassDecl::new("GPUIView", class!(NSView)).unwrap();
126 decl.add_ivar::<*mut c_void>(WINDOW_STATE_IVAR);
127 unsafe {
128 decl.add_method(sel!(dealloc), dealloc_view as extern "C" fn(&Object, Sel));
129
130 decl.add_method(
131 sel!(performKeyEquivalent:),
132 handle_key_equivalent as extern "C" fn(&Object, Sel, id) -> BOOL,
133 );
134 decl.add_method(
135 sel!(keyDown:),
136 handle_key_down as extern "C" fn(&Object, Sel, id),
137 );
138 decl.add_method(
139 sel!(keyUp:),
140 handle_key_up as extern "C" fn(&Object, Sel, id),
141 );
142 decl.add_method(
143 sel!(mouseDown:),
144 handle_view_event as extern "C" fn(&Object, Sel, id),
145 );
146 decl.add_method(
147 sel!(mouseUp:),
148 handle_view_event as extern "C" fn(&Object, Sel, id),
149 );
150 decl.add_method(
151 sel!(rightMouseDown:),
152 handle_view_event as extern "C" fn(&Object, Sel, id),
153 );
154 decl.add_method(
155 sel!(rightMouseUp:),
156 handle_view_event as extern "C" fn(&Object, Sel, id),
157 );
158 decl.add_method(
159 sel!(otherMouseDown:),
160 handle_view_event as extern "C" fn(&Object, Sel, id),
161 );
162 decl.add_method(
163 sel!(otherMouseUp:),
164 handle_view_event as extern "C" fn(&Object, Sel, id),
165 );
166 decl.add_method(
167 sel!(mouseMoved:),
168 handle_view_event as extern "C" fn(&Object, Sel, id),
169 );
170 decl.add_method(
171 sel!(pressureChangeWithEvent:),
172 handle_view_event as extern "C" fn(&Object, Sel, id),
173 );
174 decl.add_method(
175 sel!(mouseExited:),
176 handle_view_event as extern "C" fn(&Object, Sel, id),
177 );
178 decl.add_method(
179 sel!(magnifyWithEvent:),
180 handle_view_event as extern "C" fn(&Object, Sel, id),
181 );
182 decl.add_method(
183 sel!(mouseDragged:),
184 handle_view_event as extern "C" fn(&Object, Sel, id),
185 );
186 decl.add_method(
187 sel!(scrollWheel:),
188 handle_view_event as extern "C" fn(&Object, Sel, id),
189 );
190 decl.add_method(
191 sel!(swipeWithEvent:),
192 handle_view_event as extern "C" fn(&Object, Sel, id),
193 );
194 decl.add_method(
195 sel!(flagsChanged:),
196 handle_view_event as extern "C" fn(&Object, Sel, id),
197 );
198
199 decl.add_method(
200 sel!(makeBackingLayer),
201 make_backing_layer as extern "C" fn(&Object, Sel) -> id,
202 );
203
204 decl.add_protocol(Protocol::get("CALayerDelegate").unwrap());
205 decl.add_method(
206 sel!(viewDidChangeBackingProperties),
207 view_did_change_backing_properties as extern "C" fn(&Object, Sel),
208 );
209 decl.add_method(
210 sel!(setFrameSize:),
211 set_frame_size as extern "C" fn(&Object, Sel, NSSize),
212 );
213 decl.add_method(
214 sel!(displayLayer:),
215 display_layer as extern "C" fn(&Object, Sel, id),
216 );
217
218 decl.add_protocol(Protocol::get("NSTextInputClient").unwrap());
219 decl.add_method(
220 sel!(validAttributesForMarkedText),
221 valid_attributes_for_marked_text as extern "C" fn(&Object, Sel) -> id,
222 );
223 decl.add_method(
224 sel!(hasMarkedText),
225 has_marked_text as extern "C" fn(&Object, Sel) -> BOOL,
226 );
227 decl.add_method(
228 sel!(markedRange),
229 marked_range as extern "C" fn(&Object, Sel) -> NSRange,
230 );
231 decl.add_method(
232 sel!(selectedRange),
233 selected_range as extern "C" fn(&Object, Sel) -> NSRange,
234 );
235 decl.add_method(
236 sel!(firstRectForCharacterRange:actualRange:),
237 first_rect_for_character_range
238 as extern "C" fn(&Object, Sel, NSRange, id) -> NSRect,
239 );
240 decl.add_method(
241 sel!(insertText:replacementRange:),
242 insert_text as extern "C" fn(&Object, Sel, id, NSRange),
243 );
244 decl.add_method(
245 sel!(setMarkedText:selectedRange:replacementRange:),
246 set_marked_text as extern "C" fn(&Object, Sel, id, NSRange, NSRange),
247 );
248 decl.add_method(sel!(unmarkText), unmark_text as extern "C" fn(&Object, Sel));
249 decl.add_method(
250 sel!(attributedSubstringForProposedRange:actualRange:),
251 attributed_substring_for_proposed_range
252 as extern "C" fn(&Object, Sel, NSRange, *mut c_void) -> id,
253 );
254 decl.add_method(
255 sel!(viewDidChangeEffectiveAppearance),
256 view_did_change_effective_appearance as extern "C" fn(&Object, Sel),
257 );
258
259 // Suppress beep on keystrokes with modifier keys.
260 decl.add_method(
261 sel!(doCommandBySelector:),
262 do_command_by_selector as extern "C" fn(&Object, Sel, Sel),
263 );
264
265 decl.add_method(
266 sel!(acceptsFirstMouse:),
267 accepts_first_mouse as extern "C" fn(&Object, Sel, id) -> BOOL,
268 );
269
270 decl.add_method(
271 sel!(characterIndexForPoint:),
272 character_index_for_point as extern "C" fn(&Object, Sel, NSPoint) -> u64,
273 );
274 }
275 decl.register()
276 };
277 BLURRED_VIEW_CLASS = {
278 let mut decl = ClassDecl::new("BlurredView", class!(NSVisualEffectView)).unwrap();
279 unsafe {
280 decl.add_method(
281 sel!(initWithFrame:),
282 blurred_view_init_with_frame as extern "C" fn(&Object, Sel, NSRect) -> id,
283 );
284 decl.add_method(
285 sel!(updateLayer),
286 blurred_view_update_layer as extern "C" fn(&Object, Sel),
287 );
288 decl.register()
289 }
290 };
291 }
292}
293
294pub(crate) fn convert_mouse_position(position: NSPoint, window_height: Pixels) -> Point<Pixels> {
295 point(
296 px(position.x as f32),
297 // macOS screen coordinates are relative to bottom left
298 window_height - px(position.y as f32),
299 )
300}
301
302unsafe fn build_window_class(name: &'static str, superclass: &Class) -> *const Class {
303 unsafe {
304 let mut decl = ClassDecl::new(name, superclass).unwrap();
305 decl.add_ivar::<*mut c_void>(WINDOW_STATE_IVAR);
306 decl.add_method(sel!(dealloc), dealloc_window as extern "C" fn(&Object, Sel));
307
308 decl.add_method(
309 sel!(canBecomeMainWindow),
310 yes as extern "C" fn(&Object, Sel) -> BOOL,
311 );
312 decl.add_method(
313 sel!(canBecomeKeyWindow),
314 yes as extern "C" fn(&Object, Sel) -> BOOL,
315 );
316 decl.add_method(
317 sel!(windowDidResize:),
318 window_did_resize as extern "C" fn(&Object, Sel, id),
319 );
320 decl.add_method(
321 sel!(windowDidChangeOcclusionState:),
322 window_did_change_occlusion_state as extern "C" fn(&Object, Sel, id),
323 );
324 decl.add_method(
325 sel!(windowWillEnterFullScreen:),
326 window_will_enter_fullscreen as extern "C" fn(&Object, Sel, id),
327 );
328 decl.add_method(
329 sel!(windowWillExitFullScreen:),
330 window_will_exit_fullscreen as extern "C" fn(&Object, Sel, id),
331 );
332 decl.add_method(
333 sel!(windowDidMove:),
334 window_did_move as extern "C" fn(&Object, Sel, id),
335 );
336 decl.add_method(
337 sel!(windowDidChangeScreen:),
338 window_did_change_screen as extern "C" fn(&Object, Sel, id),
339 );
340 decl.add_method(
341 sel!(windowDidBecomeKey:),
342 window_did_change_key_status as extern "C" fn(&Object, Sel, id),
343 );
344 decl.add_method(
345 sel!(windowDidResignKey:),
346 window_did_change_key_status as extern "C" fn(&Object, Sel, id),
347 );
348 decl.add_method(
349 sel!(windowShouldClose:),
350 window_should_close as extern "C" fn(&Object, Sel, id) -> BOOL,
351 );
352
353 decl.add_method(sel!(close), close_window as extern "C" fn(&Object, Sel));
354
355 decl.add_method(
356 sel!(draggingEntered:),
357 dragging_entered as extern "C" fn(&Object, Sel, id) -> NSDragOperation,
358 );
359 decl.add_method(
360 sel!(draggingUpdated:),
361 dragging_updated as extern "C" fn(&Object, Sel, id) -> NSDragOperation,
362 );
363 decl.add_method(
364 sel!(draggingExited:),
365 dragging_exited as extern "C" fn(&Object, Sel, id),
366 );
367 decl.add_method(
368 sel!(performDragOperation:),
369 perform_drag_operation as extern "C" fn(&Object, Sel, id) -> BOOL,
370 );
371 decl.add_method(
372 sel!(concludeDragOperation:),
373 conclude_drag_operation as extern "C" fn(&Object, Sel, id),
374 );
375
376 decl.add_method(
377 sel!(addTitlebarAccessoryViewController:),
378 add_titlebar_accessory_view_controller as extern "C" fn(&Object, Sel, id),
379 );
380
381 decl.add_method(
382 sel!(moveTabToNewWindow:),
383 move_tab_to_new_window as extern "C" fn(&Object, Sel, id),
384 );
385
386 decl.add_method(
387 sel!(mergeAllWindows:),
388 merge_all_windows as extern "C" fn(&Object, Sel, id),
389 );
390
391 decl.add_method(
392 sel!(selectNextTab:),
393 select_next_tab as extern "C" fn(&Object, Sel, id),
394 );
395
396 decl.add_method(
397 sel!(selectPreviousTab:),
398 select_previous_tab as extern "C" fn(&Object, Sel, id),
399 );
400
401 decl.add_method(
402 sel!(toggleTabBar:),
403 toggle_tab_bar as extern "C" fn(&Object, Sel, id),
404 );
405
406 decl.register()
407 }
408}
409
410struct MacWindowState {
411 handle: AnyWindowHandle,
412 foreground_executor: ForegroundExecutor,
413 background_executor: BackgroundExecutor,
414 native_window: id,
415 native_view: NonNull<Object>,
416 blurred_view: Option<id>,
417 background_appearance: WindowBackgroundAppearance,
418 display_link: Option<DisplayLink>,
419 renderer: renderer::Renderer,
420 request_frame_callback: Option<Box<dyn FnMut(RequestFrameOptions)>>,
421 event_callback: Option<Box<dyn FnMut(PlatformInput) -> gpui::DispatchEventResult>>,
422 activate_callback: Option<Box<dyn FnMut(bool)>>,
423 resize_callback: Option<Box<dyn FnMut(Size<Pixels>, f32)>>,
424 moved_callback: Option<Box<dyn FnMut()>>,
425 should_close_callback: Option<Box<dyn FnMut() -> bool>>,
426 close_callback: Option<Box<dyn FnOnce()>>,
427 appearance_changed_callback: Option<Box<dyn FnMut()>>,
428 input_handler: Option<PlatformInputHandler>,
429 last_key_equivalent: Option<KeyDownEvent>,
430 synthetic_drag_counter: usize,
431 traffic_light_position: Option<Point<Pixels>>,
432 transparent_titlebar: bool,
433 previous_modifiers_changed_event: Option<PlatformInput>,
434 keystroke_for_do_command: Option<Keystroke>,
435 do_command_handled: Option<bool>,
436 external_files_dragged: bool,
437 // Whether the next left-mouse click is also the focusing click.
438 first_mouse: bool,
439 fullscreen_restore_bounds: Bounds<Pixels>,
440 move_tab_to_new_window_callback: Option<Box<dyn FnMut()>>,
441 merge_all_windows_callback: Option<Box<dyn FnMut()>>,
442 select_next_tab_callback: Option<Box<dyn FnMut()>>,
443 select_previous_tab_callback: Option<Box<dyn FnMut()>>,
444 toggle_tab_bar_callback: Option<Box<dyn FnMut()>>,
445 activated_least_once: bool,
446 closed: Arc<AtomicBool>,
447 // The parent window if this window is a sheet (Dialog kind)
448 sheet_parent: Option<id>,
449}
450
451impl MacWindowState {
452 fn move_traffic_light(&self) {
453 if let Some(traffic_light_position) = self.traffic_light_position {
454 if self.is_fullscreen() {
455 // Moving traffic lights while fullscreen doesn't work,
456 // see https://github.com/zed-industries/zed/issues/4712
457 return;
458 }
459
460 let titlebar_height = self.titlebar_height();
461
462 unsafe {
463 let close_button: id = msg_send![
464 self.native_window,
465 standardWindowButton: NSWindowButton::NSWindowCloseButton
466 ];
467 let min_button: id = msg_send![
468 self.native_window,
469 standardWindowButton: NSWindowButton::NSWindowMiniaturizeButton
470 ];
471 let zoom_button: id = msg_send![
472 self.native_window,
473 standardWindowButton: NSWindowButton::NSWindowZoomButton
474 ];
475
476 let mut close_button_frame: CGRect = msg_send![close_button, frame];
477 let mut min_button_frame: CGRect = msg_send![min_button, frame];
478 let mut zoom_button_frame: CGRect = msg_send![zoom_button, frame];
479 let mut origin = point(
480 traffic_light_position.x,
481 titlebar_height
482 - traffic_light_position.y
483 - px(close_button_frame.size.height as f32),
484 );
485 let button_spacing =
486 px((min_button_frame.origin.x - close_button_frame.origin.x) as f32);
487
488 close_button_frame.origin = CGPoint::new(origin.x.into(), origin.y.into());
489 let _: () = msg_send![close_button, setFrame: close_button_frame];
490 origin.x += button_spacing;
491
492 min_button_frame.origin = CGPoint::new(origin.x.into(), origin.y.into());
493 let _: () = msg_send![min_button, setFrame: min_button_frame];
494 origin.x += button_spacing;
495
496 zoom_button_frame.origin = CGPoint::new(origin.x.into(), origin.y.into());
497 let _: () = msg_send![zoom_button, setFrame: zoom_button_frame];
498 origin.x += button_spacing;
499 }
500 }
501 }
502
503 fn start_display_link(&mut self) {
504 self.stop_display_link();
505 unsafe {
506 if !self
507 .native_window
508 .occlusionState()
509 .contains(NSWindowOcclusionState::NSWindowOcclusionStateVisible)
510 {
511 return;
512 }
513 }
514 let display_id = unsafe { display_id_for_screen(self.native_window.screen()) };
515 if let Some(mut display_link) =
516 DisplayLink::new(display_id, self.native_view.as_ptr() as *mut c_void, step).log_err()
517 {
518 display_link.start().log_err();
519 self.display_link = Some(display_link);
520 }
521 }
522
523 fn stop_display_link(&mut self) {
524 self.display_link = None;
525 }
526
527 fn is_maximized(&self) -> bool {
528 fn rect_to_size(rect: NSRect) -> Size<Pixels> {
529 let NSSize { width, height } = rect.size;
530 size(width.into(), height.into())
531 }
532
533 unsafe {
534 let bounds = self.bounds();
535 let screen_size = rect_to_size(self.native_window.screen().visibleFrame());
536 bounds.size == screen_size
537 }
538 }
539
540 fn is_fullscreen(&self) -> bool {
541 unsafe {
542 let style_mask = self.native_window.styleMask();
543 style_mask.contains(NSWindowStyleMask::NSFullScreenWindowMask)
544 }
545 }
546
547 fn bounds(&self) -> Bounds<Pixels> {
548 let mut window_frame = unsafe { NSWindow::frame(self.native_window) };
549 let screen = unsafe { NSWindow::screen(self.native_window) };
550 if screen == nil {
551 return Bounds::new(point(px(0.), px(0.)), gpui::DEFAULT_WINDOW_SIZE);
552 }
553 let screen_frame = unsafe { NSScreen::frame(screen) };
554
555 // Flip the y coordinate to be top-left origin
556 window_frame.origin.y =
557 screen_frame.size.height - window_frame.origin.y - window_frame.size.height;
558
559 Bounds::new(
560 point(
561 px((window_frame.origin.x - screen_frame.origin.x) as f32),
562 px((window_frame.origin.y + screen_frame.origin.y) as f32),
563 ),
564 size(
565 px(window_frame.size.width as f32),
566 px(window_frame.size.height as f32),
567 ),
568 )
569 }
570
571 fn content_size(&self) -> Size<Pixels> {
572 let NSSize { width, height, .. } =
573 unsafe { NSView::frame(self.native_window.contentView()) }.size;
574 size(px(width as f32), px(height as f32))
575 }
576
577 fn scale_factor(&self) -> f32 {
578 get_scale_factor(self.native_window)
579 }
580
581 fn titlebar_height(&self) -> Pixels {
582 unsafe {
583 let frame = NSWindow::frame(self.native_window);
584 let content_layout_rect: CGRect = msg_send![self.native_window, contentLayoutRect];
585 px((frame.size.height - content_layout_rect.size.height) as f32)
586 }
587 }
588
589 fn window_bounds(&self) -> WindowBounds {
590 if self.is_fullscreen() {
591 WindowBounds::Fullscreen(self.fullscreen_restore_bounds)
592 } else {
593 WindowBounds::Windowed(self.bounds())
594 }
595 }
596}
597
598unsafe impl Send for MacWindowState {}
599
600pub(crate) struct MacWindow(Arc<Mutex<MacWindowState>>);
601
602impl MacWindow {
603 pub fn open(
604 handle: AnyWindowHandle,
605 WindowParams {
606 bounds,
607 titlebar,
608 kind,
609 is_movable,
610 is_resizable,
611 is_minimizable,
612 focus,
613 show,
614 display_id,
615 window_min_size,
616 tabbing_identifier,
617 }: WindowParams,
618 foreground_executor: ForegroundExecutor,
619 background_executor: BackgroundExecutor,
620 renderer_context: renderer::Context,
621 ) -> Self {
622 unsafe {
623 let pool = NSAutoreleasePool::new(nil);
624
625 let allows_automatic_window_tabbing = tabbing_identifier.is_some();
626 if allows_automatic_window_tabbing {
627 let () = msg_send![class!(NSWindow), setAllowsAutomaticWindowTabbing: YES];
628 } else {
629 let () = msg_send![class!(NSWindow), setAllowsAutomaticWindowTabbing: NO];
630 }
631
632 let mut style_mask;
633 if let Some(titlebar) = titlebar.as_ref() {
634 style_mask =
635 NSWindowStyleMask::NSClosableWindowMask | NSWindowStyleMask::NSTitledWindowMask;
636
637 if is_resizable {
638 style_mask |= NSWindowStyleMask::NSResizableWindowMask;
639 }
640
641 if is_minimizable {
642 style_mask |= NSWindowStyleMask::NSMiniaturizableWindowMask;
643 }
644
645 if titlebar.appears_transparent {
646 style_mask |= NSWindowStyleMask::NSFullSizeContentViewWindowMask;
647 }
648 } else {
649 style_mask = NSWindowStyleMask::NSTitledWindowMask
650 | NSWindowStyleMask::NSFullSizeContentViewWindowMask;
651 }
652
653 let native_window: id = match kind {
654 WindowKind::Normal => {
655 msg_send![WINDOW_CLASS, alloc]
656 }
657 WindowKind::PopUp => {
658 style_mask |= NSWindowStyleMaskNonactivatingPanel;
659 msg_send![PANEL_CLASS, alloc]
660 }
661 WindowKind::Floating | WindowKind::Dialog => {
662 msg_send![PANEL_CLASS, alloc]
663 }
664 };
665
666 let display = display_id
667 .and_then(MacDisplay::find_by_id)
668 .unwrap_or_else(MacDisplay::primary);
669
670 let mut target_screen = nil;
671 let mut screen_frame = None;
672
673 let screens = NSScreen::screens(nil);
674 let count: u64 = cocoa::foundation::NSArray::count(screens);
675 for i in 0..count {
676 let screen = cocoa::foundation::NSArray::objectAtIndex(screens, i);
677 let frame = NSScreen::frame(screen);
678 let display_id = display_id_for_screen(screen);
679 if display_id == display.0 {
680 screen_frame = Some(frame);
681 target_screen = screen;
682 }
683 }
684
685 let screen_frame = screen_frame.unwrap_or_else(|| {
686 let screen = NSScreen::mainScreen(nil);
687 target_screen = screen;
688 NSScreen::frame(screen)
689 });
690
691 let window_rect = NSRect::new(
692 NSPoint::new(
693 screen_frame.origin.x + bounds.origin.x.as_f32() as f64,
694 screen_frame.origin.y
695 + (display.bounds().size.height - bounds.origin.y).as_f32() as f64,
696 ),
697 NSSize::new(
698 bounds.size.width.as_f32() as f64,
699 bounds.size.height.as_f32() as f64,
700 ),
701 );
702
703 let native_window = native_window.initWithContentRect_styleMask_backing_defer_screen_(
704 window_rect,
705 style_mask,
706 NSBackingStoreBuffered,
707 NO,
708 target_screen,
709 );
710 assert!(!native_window.is_null());
711 let () = msg_send![
712 native_window,
713 registerForDraggedTypes:
714 NSArray::arrayWithObject(nil, NSFilenamesPboardType)
715 ];
716 let () = msg_send![
717 native_window,
718 setReleasedWhenClosed: NO
719 ];
720
721 let content_view = native_window.contentView();
722 let native_view: id = msg_send![VIEW_CLASS, alloc];
723 let native_view = NSView::initWithFrame_(native_view, NSView::bounds(content_view));
724 assert!(!native_view.is_null());
725
726 let mut window = Self(Arc::new(Mutex::new(MacWindowState {
727 handle,
728 foreground_executor,
729 background_executor,
730 native_window,
731 native_view: NonNull::new_unchecked(native_view),
732 blurred_view: None,
733 background_appearance: WindowBackgroundAppearance::Opaque,
734 display_link: None,
735 renderer: renderer::new_renderer(
736 renderer_context,
737 native_window as *mut _,
738 native_view as *mut _,
739 bounds.size.map(|pixels| pixels.as_f32()),
740 false,
741 ),
742 request_frame_callback: None,
743 event_callback: None,
744 activate_callback: None,
745 resize_callback: None,
746 moved_callback: None,
747 should_close_callback: None,
748 close_callback: None,
749 appearance_changed_callback: None,
750 input_handler: None,
751 last_key_equivalent: None,
752 synthetic_drag_counter: 0,
753 traffic_light_position: titlebar
754 .as_ref()
755 .and_then(|titlebar| titlebar.traffic_light_position),
756 transparent_titlebar: titlebar
757 .as_ref()
758 .is_none_or(|titlebar| titlebar.appears_transparent),
759 previous_modifiers_changed_event: None,
760 keystroke_for_do_command: None,
761 do_command_handled: None,
762 external_files_dragged: false,
763 first_mouse: false,
764 fullscreen_restore_bounds: Bounds::default(),
765 move_tab_to_new_window_callback: None,
766 merge_all_windows_callback: None,
767 select_next_tab_callback: None,
768 select_previous_tab_callback: None,
769 toggle_tab_bar_callback: None,
770 activated_least_once: false,
771 closed: Arc::new(AtomicBool::new(false)),
772 sheet_parent: None,
773 })));
774
775 (*native_window).set_ivar(
776 WINDOW_STATE_IVAR,
777 Arc::into_raw(window.0.clone()) as *const c_void,
778 );
779 native_window.setDelegate_(native_window);
780 (*native_view).set_ivar(
781 WINDOW_STATE_IVAR,
782 Arc::into_raw(window.0.clone()) as *const c_void,
783 );
784
785 if let Some(title) = titlebar
786 .as_ref()
787 .and_then(|t| t.title.as_ref().map(AsRef::as_ref))
788 {
789 window.set_title(title);
790 }
791
792 native_window.setMovable_(is_movable as BOOL);
793
794 if let Some(window_min_size) = window_min_size {
795 native_window.setContentMinSize_(NSSize {
796 width: window_min_size.width.to_f64(),
797 height: window_min_size.height.to_f64(),
798 });
799 }
800
801 if titlebar.is_none_or(|titlebar| titlebar.appears_transparent) {
802 native_window.setTitlebarAppearsTransparent_(YES);
803 native_window.setTitleVisibility_(NSWindowTitleVisibility::NSWindowTitleHidden);
804 }
805
806 native_view.setAutoresizingMask_(NSViewWidthSizable | NSViewHeightSizable);
807 native_view.setWantsBestResolutionOpenGLSurface_(YES);
808
809 // From winit crate: On Mojave, views automatically become layer-backed shortly after
810 // being added to a native_window. Changing the layer-backedness of a view breaks the
811 // association between the view and its associated OpenGL context. To work around this,
812 // on we explicitly make the view layer-backed up front so that AppKit doesn't do it
813 // itself and break the association with its context.
814 native_view.setWantsLayer(YES);
815 let _: () = msg_send![
816 native_view,
817 setLayerContentsRedrawPolicy: NSViewLayerContentsRedrawDuringViewResize
818 ];
819
820 content_view.addSubview_(native_view.autorelease());
821 native_window.makeFirstResponder_(native_view);
822
823 let app: id = NSApplication::sharedApplication(nil);
824 let main_window: id = msg_send![app, mainWindow];
825 let mut sheet_parent = None;
826
827 match kind {
828 WindowKind::Normal | WindowKind::Floating => {
829 if kind == WindowKind::Floating {
830 // Let the window float keep above normal windows.
831 native_window.setLevel_(NSFloatingWindowLevel);
832 } else {
833 native_window.setLevel_(NSNormalWindowLevel);
834 }
835 native_window.setAcceptsMouseMovedEvents_(YES);
836
837 if let Some(tabbing_identifier) = tabbing_identifier {
838 let tabbing_id = ns_string(tabbing_identifier.as_str());
839 let _: () = msg_send![native_window, setTabbingIdentifier: tabbing_id];
840 } else {
841 let _: () = msg_send![native_window, setTabbingIdentifier:nil];
842 }
843 }
844 WindowKind::PopUp => {
845 // Use a tracking area to allow receiving MouseMoved events even when
846 // the window or application aren't active, which is often the case
847 // e.g. for notification windows.
848 let tracking_area: id = msg_send![class!(NSTrackingArea), alloc];
849 let _: () = msg_send![
850 tracking_area,
851 initWithRect: NSRect::new(NSPoint::new(0., 0.), NSSize::new(0., 0.))
852 options: NSTrackingMouseEnteredAndExited | NSTrackingMouseMoved | NSTrackingActiveAlways | NSTrackingInVisibleRect
853 owner: native_view
854 userInfo: nil
855 ];
856 let _: () =
857 msg_send![native_view, addTrackingArea: tracking_area.autorelease()];
858
859 native_window.setLevel_(NSPopUpWindowLevel);
860 let _: () = msg_send![
861 native_window,
862 setAnimationBehavior: NSWindowAnimationBehaviorUtilityWindow
863 ];
864 native_window.setCollectionBehavior_(
865 NSWindowCollectionBehavior::NSWindowCollectionBehaviorCanJoinAllSpaces |
866 NSWindowCollectionBehavior::NSWindowCollectionBehaviorFullScreenAuxiliary
867 );
868 }
869 WindowKind::Dialog => {
870 if !main_window.is_null() {
871 let parent = {
872 let active_sheet: id = msg_send![main_window, attachedSheet];
873 if active_sheet.is_null() {
874 main_window
875 } else {
876 active_sheet
877 }
878 };
879 let _: () =
880 msg_send![parent, beginSheet: native_window completionHandler: nil];
881 sheet_parent = Some(parent);
882 }
883 }
884 }
885
886 if allows_automatic_window_tabbing
887 && !main_window.is_null()
888 && main_window != native_window
889 {
890 let main_window_is_fullscreen = main_window
891 .styleMask()
892 .contains(NSWindowStyleMask::NSFullScreenWindowMask);
893 let user_tabbing_preference = Self::get_user_tabbing_preference()
894 .unwrap_or(UserTabbingPreference::InFullScreen);
895 let should_add_as_tab = user_tabbing_preference == UserTabbingPreference::Always
896 || user_tabbing_preference == UserTabbingPreference::InFullScreen
897 && main_window_is_fullscreen;
898
899 if should_add_as_tab {
900 let main_window_can_tab: BOOL =
901 msg_send![main_window, respondsToSelector: sel!(addTabbedWindow:ordered:)];
902 let main_window_visible: BOOL = msg_send![main_window, isVisible];
903
904 if main_window_can_tab == YES && main_window_visible == YES {
905 let _: () = msg_send![main_window, addTabbedWindow: native_window ordered: NSWindowOrderingMode::NSWindowAbove];
906
907 // Ensure the window is visible immediately after adding the tab, since the tab bar is updated with a new entry at this point.
908 // Note: Calling orderFront here can break fullscreen mode (makes fullscreen windows exit fullscreen), so only do this if the main window is not fullscreen.
909 if !main_window_is_fullscreen {
910 let _: () = msg_send![native_window, orderFront: nil];
911 }
912 }
913 }
914 }
915
916 if focus && show {
917 native_window.makeKeyAndOrderFront_(nil);
918 } else if show {
919 native_window.orderFront_(nil);
920 }
921
922 // Set the initial position of the window to the specified origin.
923 // Although we already specified the position using `initWithContentRect_styleMask_backing_defer_screen_`,
924 // the window position might be incorrect if the main screen (the screen that contains the window that has focus)
925 // is different from the primary screen.
926 NSWindow::setFrameTopLeftPoint_(native_window, window_rect.origin);
927 {
928 let mut window_state = window.0.lock();
929 window_state.move_traffic_light();
930 window_state.sheet_parent = sheet_parent;
931 }
932
933 pool.drain();
934
935 window
936 }
937 }
938
939 pub fn active_window() -> Option<AnyWindowHandle> {
940 unsafe {
941 let app = NSApplication::sharedApplication(nil);
942 let main_window: id = msg_send![app, mainWindow];
943 if main_window.is_null() {
944 return None;
945 }
946
947 if msg_send![main_window, isKindOfClass: WINDOW_CLASS] {
948 let handle = get_window_state(&*main_window).lock().handle;
949 Some(handle)
950 } else {
951 None
952 }
953 }
954 }
955
956 pub fn ordered_windows() -> Vec<AnyWindowHandle> {
957 unsafe {
958 let app = NSApplication::sharedApplication(nil);
959 let windows: id = msg_send![app, orderedWindows];
960 let count: NSUInteger = msg_send![windows, count];
961
962 let mut window_handles = Vec::new();
963 for i in 0..count {
964 let window: id = msg_send![windows, objectAtIndex:i];
965 if msg_send![window, isKindOfClass: WINDOW_CLASS] {
966 let handle = get_window_state(&*window).lock().handle;
967 window_handles.push(handle);
968 }
969 }
970
971 window_handles
972 }
973 }
974
975 pub fn get_user_tabbing_preference() -> Option<UserTabbingPreference> {
976 unsafe {
977 let defaults: id = NSUserDefaults::standardUserDefaults();
978 let domain = ns_string("NSGlobalDomain");
979 let key = ns_string("AppleWindowTabbingMode");
980
981 let dict: id = msg_send![defaults, persistentDomainForName: domain];
982 let value: id = if !dict.is_null() {
983 msg_send![dict, objectForKey: key]
984 } else {
985 nil
986 };
987
988 let value_str = if !value.is_null() {
989 CStr::from_ptr(NSString::UTF8String(value)).to_string_lossy()
990 } else {
991 "".into()
992 };
993
994 match value_str.as_ref() {
995 "manual" => Some(UserTabbingPreference::Never),
996 "always" => Some(UserTabbingPreference::Always),
997 _ => Some(UserTabbingPreference::InFullScreen),
998 }
999 }
1000 }
1001}
1002
1003impl Drop for MacWindow {
1004 fn drop(&mut self) {
1005 let mut this = self.0.lock();
1006 this.renderer.destroy();
1007 let window = this.native_window;
1008 let sheet_parent = this.sheet_parent.take();
1009 this.display_link.take();
1010 unsafe {
1011 this.native_window.setDelegate_(nil);
1012 }
1013 this.input_handler.take();
1014 this.foreground_executor
1015 .spawn(async move {
1016 unsafe {
1017 if let Some(parent) = sheet_parent {
1018 let _: () = msg_send![parent, endSheet: window];
1019 }
1020 window.close();
1021 window.autorelease();
1022 }
1023 })
1024 .detach();
1025 }
1026}
1027
1028/// Calls `f` if the window is not closed.
1029///
1030/// This should be used when spawning foreground tasks interacting with the
1031/// window, as some messages will end hard faulting if dispatched to no longer
1032/// valid window handles.
1033fn if_window_not_closed(closed: Arc<AtomicBool>, f: impl FnOnce()) {
1034 if !closed.load(Ordering::Acquire) {
1035 f();
1036 }
1037}
1038
1039impl PlatformWindow for MacWindow {
1040 fn bounds(&self) -> Bounds<Pixels> {
1041 self.0.as_ref().lock().bounds()
1042 }
1043
1044 fn window_bounds(&self) -> WindowBounds {
1045 self.0.as_ref().lock().window_bounds()
1046 }
1047
1048 fn is_maximized(&self) -> bool {
1049 self.0.as_ref().lock().is_maximized()
1050 }
1051
1052 fn content_size(&self) -> Size<Pixels> {
1053 self.0.as_ref().lock().content_size()
1054 }
1055
1056 fn resize(&mut self, size: Size<Pixels>) {
1057 let this = self.0.lock();
1058 let window = this.native_window;
1059 let closed = this.closed.clone();
1060 this.foreground_executor
1061 .spawn(async move {
1062 if_window_not_closed(closed, || unsafe {
1063 window.setContentSize_(NSSize {
1064 width: size.width.as_f32() as f64,
1065 height: size.height.as_f32() as f64,
1066 });
1067 })
1068 })
1069 .detach();
1070 }
1071
1072 fn merge_all_windows(&self) {
1073 let native_window = self.0.lock().native_window;
1074 extern "C" fn merge_windows_async(context: *mut std::ffi::c_void) {
1075 unsafe {
1076 let native_window = context as id;
1077 let _: () = msg_send![native_window, mergeAllWindows:nil];
1078 }
1079 }
1080
1081 unsafe {
1082 DispatchQueue::main()
1083 .exec_async_f(native_window as *mut std::ffi::c_void, merge_windows_async);
1084 }
1085 }
1086
1087 fn move_tab_to_new_window(&self) {
1088 let native_window = self.0.lock().native_window;
1089 extern "C" fn move_tab_async(context: *mut std::ffi::c_void) {
1090 unsafe {
1091 let native_window = context as id;
1092 let _: () = msg_send![native_window, moveTabToNewWindow:nil];
1093 let _: () = msg_send![native_window, makeKeyAndOrderFront: nil];
1094 }
1095 }
1096
1097 unsafe {
1098 DispatchQueue::main()
1099 .exec_async_f(native_window as *mut std::ffi::c_void, move_tab_async);
1100 }
1101 }
1102
1103 fn toggle_window_tab_overview(&self) {
1104 let native_window = self.0.lock().native_window;
1105 unsafe {
1106 let _: () = msg_send![native_window, toggleTabOverview:nil];
1107 }
1108 }
1109
1110 fn set_tabbing_identifier(&self, tabbing_identifier: Option<String>) {
1111 let native_window = self.0.lock().native_window;
1112 unsafe {
1113 let allows_automatic_window_tabbing = tabbing_identifier.is_some();
1114 if allows_automatic_window_tabbing {
1115 let () = msg_send![class!(NSWindow), setAllowsAutomaticWindowTabbing: YES];
1116 } else {
1117 let () = msg_send![class!(NSWindow), setAllowsAutomaticWindowTabbing: NO];
1118 }
1119
1120 if let Some(tabbing_identifier) = tabbing_identifier {
1121 let tabbing_id = ns_string(tabbing_identifier.as_str());
1122 let _: () = msg_send![native_window, setTabbingIdentifier: tabbing_id];
1123 } else {
1124 let _: () = msg_send![native_window, setTabbingIdentifier:nil];
1125 }
1126 }
1127 }
1128
1129 fn scale_factor(&self) -> f32 {
1130 self.0.as_ref().lock().scale_factor()
1131 }
1132
1133 fn appearance(&self) -> WindowAppearance {
1134 unsafe {
1135 let appearance: id = msg_send![self.0.lock().native_window, effectiveAppearance];
1136 crate::window_appearance::window_appearance_from_native(appearance)
1137 }
1138 }
1139
1140 fn display(&self) -> Option<Rc<dyn PlatformDisplay>> {
1141 unsafe {
1142 let screen = self.0.lock().native_window.screen();
1143 if screen.is_null() {
1144 return None;
1145 }
1146 let device_description: id = msg_send![screen, deviceDescription];
1147 let screen_number: id =
1148 NSDictionary::valueForKey_(device_description, ns_string("NSScreenNumber"));
1149
1150 let screen_number: u32 = msg_send![screen_number, unsignedIntValue];
1151
1152 Some(Rc::new(MacDisplay(screen_number)))
1153 }
1154 }
1155
1156 fn mouse_position(&self) -> Point<Pixels> {
1157 let position = unsafe {
1158 self.0
1159 .lock()
1160 .native_window
1161 .mouseLocationOutsideOfEventStream()
1162 };
1163 convert_mouse_position(position, self.content_size().height)
1164 }
1165
1166 fn modifiers(&self) -> Modifiers {
1167 unsafe {
1168 let modifiers: NSEventModifierFlags = msg_send![class!(NSEvent), modifierFlags];
1169
1170 let control = modifiers.contains(NSEventModifierFlags::NSControlKeyMask);
1171 let alt = modifiers.contains(NSEventModifierFlags::NSAlternateKeyMask);
1172 let shift = modifiers.contains(NSEventModifierFlags::NSShiftKeyMask);
1173 let command = modifiers.contains(NSEventModifierFlags::NSCommandKeyMask);
1174 let function = modifiers.contains(NSEventModifierFlags::NSFunctionKeyMask);
1175
1176 Modifiers {
1177 control,
1178 alt,
1179 shift,
1180 platform: command,
1181 function,
1182 }
1183 }
1184 }
1185
1186 fn capslock(&self) -> Capslock {
1187 unsafe {
1188 let modifiers: NSEventModifierFlags = msg_send![class!(NSEvent), modifierFlags];
1189
1190 Capslock {
1191 on: modifiers.contains(NSEventModifierFlags::NSAlphaShiftKeyMask),
1192 }
1193 }
1194 }
1195
1196 fn set_input_handler(&mut self, input_handler: PlatformInputHandler) {
1197 self.0.as_ref().lock().input_handler = Some(input_handler);
1198 }
1199
1200 fn take_input_handler(&mut self) -> Option<PlatformInputHandler> {
1201 self.0.as_ref().lock().input_handler.take()
1202 }
1203
1204 fn prompt(
1205 &self,
1206 level: PromptLevel,
1207 msg: &str,
1208 detail: Option<&str>,
1209 answers: &[PromptButton],
1210 ) -> Option<oneshot::Receiver<usize>> {
1211 // macOs applies overrides to modal window buttons after they are added.
1212 // Two most important for this logic are:
1213 // * Buttons with "Cancel" title will be displayed as the last buttons in the modal
1214 // * Last button added to the modal via `addButtonWithTitle` stays focused
1215 // * Focused buttons react on "space"/" " keypresses
1216 // * Usage of `keyEquivalent`, `makeFirstResponder` or `setInitialFirstResponder` does not change the focus
1217 //
1218 // See also https://developer.apple.com/documentation/appkit/nsalert/1524532-addbuttonwithtitle#discussion
1219 // ```
1220 // By default, the first button has a key equivalent of Return,
1221 // any button with a title of “Cancel” has a key equivalent of Escape,
1222 // 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).
1223 // ```
1224 //
1225 // To avoid situations when the last element added is "Cancel" and it gets the focus
1226 // (hence stealing both ESC and Space shortcuts), we find and add one non-Cancel button
1227 // last, so it gets focus and a Space shortcut.
1228 // This way, "Save this file? Yes/No/Cancel"-ish modals will get all three buttons mapped with a key.
1229 let latest_non_cancel_label = answers
1230 .iter()
1231 .enumerate()
1232 .rev()
1233 .find(|(_, label)| !label.is_cancel())
1234 .filter(|&(label_index, _)| label_index > 0);
1235
1236 unsafe {
1237 let alert: id = msg_send![class!(NSAlert), alloc];
1238 let alert: id = msg_send![alert, init];
1239 let alert_style = match level {
1240 PromptLevel::Info => 1,
1241 PromptLevel::Warning => 0,
1242 PromptLevel::Critical => 2,
1243 };
1244 let _: () = msg_send![alert, setAlertStyle: alert_style];
1245 let _: () = msg_send![alert, setMessageText: ns_string(msg)];
1246 if let Some(detail) = detail {
1247 let _: () = msg_send![alert, setInformativeText: ns_string(detail)];
1248 }
1249
1250 for (ix, answer) in answers
1251 .iter()
1252 .enumerate()
1253 .filter(|&(ix, _)| Some(ix) != latest_non_cancel_label.map(|(ix, _)| ix))
1254 {
1255 let button: id = msg_send![alert, addButtonWithTitle: ns_string(answer.label())];
1256 let _: () = msg_send![button, setTag: ix as NSInteger];
1257
1258 if answer.is_cancel() {
1259 // Bind Escape Key to Cancel Button
1260 if let Some(key) = std::char::from_u32(crate::events::ESCAPE_KEY as u32) {
1261 let _: () =
1262 msg_send![button, setKeyEquivalent: ns_string(&key.to_string())];
1263 }
1264 }
1265 }
1266 if let Some((ix, answer)) = latest_non_cancel_label {
1267 let button: id = msg_send![alert, addButtonWithTitle: ns_string(answer.label())];
1268 let _: () = msg_send![button, setTag: ix as NSInteger];
1269 }
1270
1271 let (done_tx, done_rx) = oneshot::channel();
1272 let done_tx = Cell::new(Some(done_tx));
1273 let block = ConcreteBlock::new(move |answer: NSInteger| {
1274 let _: () = msg_send![alert, release];
1275 if let Some(done_tx) = done_tx.take() {
1276 let _ = done_tx.send(answer.try_into().unwrap());
1277 }
1278 });
1279 let block = block.copy();
1280 let lock = self.0.lock();
1281 let native_window = lock.native_window;
1282 let closed = lock.closed.clone();
1283 let executor = lock.foreground_executor.clone();
1284 executor
1285 .spawn(async move {
1286 if !closed.load(Ordering::Acquire) {
1287 let _: () = msg_send![
1288 alert,
1289 beginSheetModalForWindow: native_window
1290 completionHandler: block
1291 ];
1292 } else {
1293 let _: () = msg_send![alert, release];
1294 }
1295 })
1296 .detach();
1297
1298 Some(done_rx)
1299 }
1300 }
1301
1302 fn activate(&self) {
1303 let lock = self.0.lock();
1304 let window = lock.native_window;
1305 let closed = lock.closed.clone();
1306 let executor = lock.foreground_executor.clone();
1307 executor
1308 .spawn(async move {
1309 if !closed.load(Ordering::Acquire) {
1310 unsafe {
1311 let _: () = msg_send![window, makeKeyAndOrderFront: nil];
1312 }
1313 }
1314 })
1315 .detach();
1316 }
1317
1318 fn is_active(&self) -> bool {
1319 unsafe { self.0.lock().native_window.isKeyWindow() == YES }
1320 }
1321
1322 // is_hovered is unused on macOS. See Window::is_window_hovered.
1323 fn is_hovered(&self) -> bool {
1324 false
1325 }
1326
1327 fn set_title(&mut self, title: &str) {
1328 unsafe {
1329 let app = NSApplication::sharedApplication(nil);
1330 let window = self.0.lock().native_window;
1331 let title = ns_string(title);
1332 let _: () = msg_send![app, changeWindowsItem:window title:title filename:false];
1333 let _: () = msg_send![window, setTitle: title];
1334 self.0.lock().move_traffic_light();
1335 }
1336 }
1337
1338 fn get_title(&self) -> String {
1339 unsafe {
1340 let title: id = msg_send![self.0.lock().native_window, title];
1341 if title.is_null() {
1342 "".to_string()
1343 } else {
1344 title.to_str().to_string()
1345 }
1346 }
1347 }
1348
1349 fn set_app_id(&mut self, _app_id: &str) {}
1350
1351 fn set_background_appearance(&self, background_appearance: WindowBackgroundAppearance) {
1352 let mut this = self.0.as_ref().lock();
1353 this.background_appearance = background_appearance;
1354
1355 let opaque = background_appearance == WindowBackgroundAppearance::Opaque;
1356 this.renderer.update_transparency(!opaque);
1357
1358 unsafe {
1359 this.native_window.setOpaque_(opaque as BOOL);
1360 let background_color = if opaque {
1361 NSColor::colorWithSRGBRed_green_blue_alpha_(nil, 0f64, 0f64, 0f64, 1f64)
1362 } else {
1363 // Not using `+[NSColor clearColor]` to avoid broken shadow.
1364 NSColor::colorWithSRGBRed_green_blue_alpha_(nil, 0f64, 0f64, 0f64, 0.0001)
1365 };
1366 this.native_window.setBackgroundColor_(background_color);
1367
1368 if NSAppKitVersionNumber < NSAppKitVersionNumber12_0 {
1369 // Whether `-[NSVisualEffectView respondsToSelector:@selector(_updateProxyLayer)]`.
1370 // On macOS Catalina/Big Sur `NSVisualEffectView` doesn’t own concrete sublayers
1371 // but uses a `CAProxyLayer`. Use the legacy WindowServer API.
1372 let blur_radius = if background_appearance == WindowBackgroundAppearance::Blurred {
1373 80
1374 } else {
1375 0
1376 };
1377
1378 let window_number = this.native_window.windowNumber();
1379 CGSSetWindowBackgroundBlurRadius(CGSMainConnectionID(), window_number, blur_radius);
1380 } else {
1381 // On newer macOS `NSVisualEffectView` manages the effect layer directly. Using it
1382 // could have a better performance (it downsamples the backdrop) and more control
1383 // over the effect layer.
1384 if background_appearance != WindowBackgroundAppearance::Blurred {
1385 if let Some(blur_view) = this.blurred_view {
1386 NSView::removeFromSuperview(blur_view);
1387 this.blurred_view = None;
1388 }
1389 } else if this.blurred_view.is_none() {
1390 let content_view = this.native_window.contentView();
1391 let frame = NSView::bounds(content_view);
1392 let mut blur_view: id = msg_send![BLURRED_VIEW_CLASS, alloc];
1393 blur_view = NSView::initWithFrame_(blur_view, frame);
1394 blur_view.setAutoresizingMask_(NSViewWidthSizable | NSViewHeightSizable);
1395
1396 let _: () = msg_send![
1397 content_view,
1398 addSubview: blur_view
1399 positioned: NSWindowOrderingMode::NSWindowBelow
1400 relativeTo: nil
1401 ];
1402 this.blurred_view = Some(blur_view.autorelease());
1403 }
1404 }
1405 }
1406 }
1407
1408 fn background_appearance(&self) -> WindowBackgroundAppearance {
1409 self.0.as_ref().lock().background_appearance
1410 }
1411
1412 fn is_subpixel_rendering_supported(&self) -> bool {
1413 false
1414 }
1415
1416 fn set_edited(&mut self, edited: bool) {
1417 unsafe {
1418 let window = self.0.lock().native_window;
1419 msg_send![window, setDocumentEdited: edited as BOOL]
1420 }
1421
1422 // Changing the document edited state resets the traffic light position,
1423 // so we have to move it again.
1424 self.0.lock().move_traffic_light();
1425 }
1426
1427 fn show_character_palette(&self) {
1428 let this = self.0.lock();
1429 let window = this.native_window;
1430 this.foreground_executor
1431 .spawn(async move {
1432 unsafe {
1433 let app = NSApplication::sharedApplication(nil);
1434 let _: () = msg_send![app, orderFrontCharacterPalette: window];
1435 }
1436 })
1437 .detach();
1438 }
1439
1440 fn minimize(&self) {
1441 let window = self.0.lock().native_window;
1442 unsafe {
1443 window.miniaturize_(nil);
1444 }
1445 }
1446
1447 fn zoom(&self) {
1448 let this = self.0.lock();
1449 let window = this.native_window;
1450 let closed = this.closed.clone();
1451 this.foreground_executor
1452 .spawn(async move {
1453 if_window_not_closed(closed, || unsafe {
1454 window.zoom_(nil);
1455 })
1456 })
1457 .detach();
1458 }
1459
1460 fn toggle_fullscreen(&self) {
1461 let this = self.0.lock();
1462 let window = this.native_window;
1463 let closed = this.closed.clone();
1464 this.foreground_executor
1465 .spawn(async move {
1466 if_window_not_closed(closed, || unsafe {
1467 window.toggleFullScreen_(nil);
1468 })
1469 })
1470 .detach();
1471 }
1472
1473 fn is_fullscreen(&self) -> bool {
1474 let this = self.0.lock();
1475 let window = this.native_window;
1476
1477 unsafe {
1478 window
1479 .styleMask()
1480 .contains(NSWindowStyleMask::NSFullScreenWindowMask)
1481 }
1482 }
1483
1484 fn on_request_frame(&self, callback: Box<dyn FnMut(RequestFrameOptions)>) {
1485 self.0.as_ref().lock().request_frame_callback = Some(callback);
1486 }
1487
1488 fn on_input(&self, callback: Box<dyn FnMut(PlatformInput) -> gpui::DispatchEventResult>) {
1489 self.0.as_ref().lock().event_callback = Some(callback);
1490 }
1491
1492 fn on_active_status_change(&self, callback: Box<dyn FnMut(bool)>) {
1493 self.0.as_ref().lock().activate_callback = Some(callback);
1494 }
1495
1496 fn on_hover_status_change(&self, _: Box<dyn FnMut(bool)>) {}
1497
1498 fn on_resize(&self, callback: Box<dyn FnMut(Size<Pixels>, f32)>) {
1499 self.0.as_ref().lock().resize_callback = Some(callback);
1500 }
1501
1502 fn on_moved(&self, callback: Box<dyn FnMut()>) {
1503 self.0.as_ref().lock().moved_callback = Some(callback);
1504 }
1505
1506 fn on_should_close(&self, callback: Box<dyn FnMut() -> bool>) {
1507 self.0.as_ref().lock().should_close_callback = Some(callback);
1508 }
1509
1510 fn on_close(&self, callback: Box<dyn FnOnce()>) {
1511 self.0.as_ref().lock().close_callback = Some(callback);
1512 }
1513
1514 fn on_hit_test_window_control(&self, _callback: Box<dyn FnMut() -> Option<WindowControlArea>>) {
1515 }
1516
1517 fn on_appearance_changed(&self, callback: Box<dyn FnMut()>) {
1518 self.0.lock().appearance_changed_callback = Some(callback);
1519 }
1520
1521 fn tabbed_windows(&self) -> Option<Vec<SystemWindowTab>> {
1522 unsafe {
1523 let windows: id = msg_send![self.0.lock().native_window, tabbedWindows];
1524 if windows.is_null() {
1525 return None;
1526 }
1527
1528 let count: NSUInteger = msg_send![windows, count];
1529 let mut result = Vec::new();
1530 for i in 0..count {
1531 let window: id = msg_send![windows, objectAtIndex:i];
1532 if msg_send![window, isKindOfClass: WINDOW_CLASS] {
1533 let handle = get_window_state(&*window).lock().handle;
1534 let title: id = msg_send![window, title];
1535 let title = SharedString::from(title.to_str().to_string());
1536
1537 result.push(SystemWindowTab::new(title, handle));
1538 }
1539 }
1540
1541 Some(result)
1542 }
1543 }
1544
1545 fn tab_bar_visible(&self) -> bool {
1546 unsafe {
1547 let tab_group: id = msg_send![self.0.lock().native_window, tabGroup];
1548 if tab_group.is_null() {
1549 false
1550 } else {
1551 let tab_bar_visible: BOOL = msg_send![tab_group, isTabBarVisible];
1552 tab_bar_visible == YES
1553 }
1554 }
1555 }
1556
1557 fn on_move_tab_to_new_window(&self, callback: Box<dyn FnMut()>) {
1558 self.0.as_ref().lock().move_tab_to_new_window_callback = Some(callback);
1559 }
1560
1561 fn on_merge_all_windows(&self, callback: Box<dyn FnMut()>) {
1562 self.0.as_ref().lock().merge_all_windows_callback = Some(callback);
1563 }
1564
1565 fn on_select_next_tab(&self, callback: Box<dyn FnMut()>) {
1566 self.0.as_ref().lock().select_next_tab_callback = Some(callback);
1567 }
1568
1569 fn on_select_previous_tab(&self, callback: Box<dyn FnMut()>) {
1570 self.0.as_ref().lock().select_previous_tab_callback = Some(callback);
1571 }
1572
1573 fn on_toggle_tab_bar(&self, callback: Box<dyn FnMut()>) {
1574 self.0.as_ref().lock().toggle_tab_bar_callback = Some(callback);
1575 }
1576
1577 fn draw(&self, scene: &gpui::Scene) {
1578 let mut this = self.0.lock();
1579 this.renderer.draw(scene);
1580 }
1581
1582 fn sprite_atlas(&self) -> Arc<dyn PlatformAtlas> {
1583 self.0.lock().renderer.sprite_atlas().clone()
1584 }
1585
1586 fn gpu_specs(&self) -> Option<gpui::GpuSpecs> {
1587 None
1588 }
1589
1590 fn update_ime_position(&self, _bounds: Bounds<Pixels>) {
1591 let executor = self.0.lock().foreground_executor.clone();
1592 executor
1593 .spawn(async move {
1594 unsafe {
1595 let input_context: id =
1596 msg_send![class!(NSTextInputContext), currentInputContext];
1597 if input_context.is_null() {
1598 return;
1599 }
1600 let _: () = msg_send![input_context, invalidateCharacterCoordinates];
1601 }
1602 })
1603 .detach()
1604 }
1605
1606 fn titlebar_double_click(&self) {
1607 let this = self.0.lock();
1608 let window = this.native_window;
1609 let closed = this.closed.clone();
1610 this.foreground_executor
1611 .spawn(async move {
1612 if_window_not_closed(closed, || {
1613 unsafe {
1614 let defaults: id = NSUserDefaults::standardUserDefaults();
1615 let domain = ns_string("NSGlobalDomain");
1616 let key = ns_string("AppleActionOnDoubleClick");
1617
1618 let dict: id = msg_send![defaults, persistentDomainForName: domain];
1619 let action: id = if !dict.is_null() {
1620 msg_send![dict, objectForKey: key]
1621 } else {
1622 nil
1623 };
1624
1625 let action_str = if !action.is_null() {
1626 CStr::from_ptr(NSString::UTF8String(action)).to_string_lossy()
1627 } else {
1628 "".into()
1629 };
1630
1631 match action_str.as_ref() {
1632 "None" => {
1633 // "Do Nothing" selected, so do no action
1634 }
1635 "Minimize" => {
1636 window.miniaturize_(nil);
1637 }
1638 "Maximize" => {
1639 window.zoom_(nil);
1640 }
1641 "Fill" => {
1642 // There is no documented API for "Fill" action, so we'll just zoom the window
1643 window.zoom_(nil);
1644 }
1645 _ => {
1646 window.zoom_(nil);
1647 }
1648 }
1649 }
1650 })
1651 })
1652 .detach();
1653 }
1654
1655 fn start_window_move(&self) {
1656 let this = self.0.lock();
1657 let window = this.native_window;
1658
1659 unsafe {
1660 let app = NSApplication::sharedApplication(nil);
1661 let event: id = msg_send![app, currentEvent];
1662 let _: () = msg_send![window, performWindowDragWithEvent: event];
1663 }
1664 }
1665
1666 #[cfg(any(test, feature = "test-support"))]
1667 fn render_to_image(&self, scene: &gpui::Scene) -> Result<RgbaImage> {
1668 let mut this = self.0.lock();
1669 this.renderer.render_to_image(scene)
1670 }
1671}
1672
1673impl rwh::HasWindowHandle for MacWindow {
1674 fn window_handle(&self) -> Result<rwh::WindowHandle<'_>, rwh::HandleError> {
1675 // SAFETY: The AppKitWindowHandle is a wrapper around a pointer to an NSView
1676 unsafe {
1677 Ok(rwh::WindowHandle::borrow_raw(rwh::RawWindowHandle::AppKit(
1678 rwh::AppKitWindowHandle::new(self.0.lock().native_view.cast()),
1679 )))
1680 }
1681 }
1682}
1683
1684impl rwh::HasDisplayHandle for MacWindow {
1685 fn display_handle(&self) -> Result<rwh::DisplayHandle<'_>, rwh::HandleError> {
1686 // SAFETY: This is a no-op on macOS
1687 unsafe {
1688 Ok(rwh::DisplayHandle::borrow_raw(
1689 rwh::AppKitDisplayHandle::new().into(),
1690 ))
1691 }
1692 }
1693}
1694
1695fn get_scale_factor(native_window: id) -> f32 {
1696 let factor = unsafe {
1697 let screen: id = msg_send![native_window, screen];
1698 if screen.is_null() {
1699 return 2.0;
1700 }
1701 NSScreen::backingScaleFactor(screen) as f32
1702 };
1703
1704 // We are not certain what triggers this, but it seems that sometimes
1705 // this method would return 0 (https://github.com/zed-industries/zed/issues/6412)
1706 // It seems most likely that this would happen if the window has no screen
1707 // (if it is off-screen), though we'd expect to see viewDidChangeBackingProperties before
1708 // it was rendered for real.
1709 // Regardless, attempt to avoid the issue here.
1710 if factor == 0.0 { 2. } else { factor }
1711}
1712
1713unsafe fn get_window_state(object: &Object) -> Arc<Mutex<MacWindowState>> {
1714 unsafe {
1715 let raw: *mut c_void = *object.get_ivar(WINDOW_STATE_IVAR);
1716 let rc1 = Arc::from_raw(raw as *mut Mutex<MacWindowState>);
1717 let rc2 = rc1.clone();
1718 mem::forget(rc1);
1719 rc2
1720 }
1721}
1722
1723unsafe fn drop_window_state(object: &Object) {
1724 unsafe {
1725 let raw: *mut c_void = *object.get_ivar(WINDOW_STATE_IVAR);
1726 Arc::from_raw(raw as *mut Mutex<MacWindowState>);
1727 }
1728}
1729
1730extern "C" fn yes(_: &Object, _: Sel) -> BOOL {
1731 YES
1732}
1733
1734extern "C" fn dealloc_window(this: &Object, _: Sel) {
1735 unsafe {
1736 drop_window_state(this);
1737 let _: () = msg_send![super(this, class!(NSWindow)), dealloc];
1738 }
1739}
1740
1741extern "C" fn dealloc_view(this: &Object, _: Sel) {
1742 unsafe {
1743 drop_window_state(this);
1744 let _: () = msg_send![super(this, class!(NSView)), dealloc];
1745 }
1746}
1747
1748extern "C" fn handle_key_equivalent(this: &Object, _: Sel, native_event: id) -> BOOL {
1749 handle_key_event(this, native_event, true)
1750}
1751
1752extern "C" fn handle_key_down(this: &Object, _: Sel, native_event: id) {
1753 handle_key_event(this, native_event, false);
1754}
1755
1756extern "C" fn handle_key_up(this: &Object, _: Sel, native_event: id) {
1757 handle_key_event(this, native_event, false);
1758}
1759
1760// Things to test if you're modifying this method:
1761// U.S. layout:
1762// - The IME consumes characters like 'j' and 'k', which makes paging through `less` in
1763// the terminal behave incorrectly by default. This behavior should be patched by our
1764// IME integration
1765// - `alt-t` should open the tasks menu
1766// - In vim mode, this keybinding should work:
1767// ```
1768// {
1769// "context": "Editor && vim_mode == insert",
1770// "bindings": {"j j": "vim::NormalBefore"}
1771// }
1772// ```
1773// and typing 'j k' in insert mode with this keybinding should insert the two characters
1774// Brazilian layout:
1775// - `" space` should create an unmarked quote
1776// - `" backspace` should delete the marked quote
1777// - `" "`should create an unmarked quote and a second marked quote
1778// - `" up` should insert a quote, unmark it, and move up one line
1779// - `" cmd-down` should insert a quote, unmark it, and move to the end of the file
1780// - `cmd-ctrl-space` and clicking on an emoji should type it
1781// Czech (QWERTY) layout:
1782// - in vim mode `option-4` should go to end of line (same as $)
1783// Japanese (Romaji) layout:
1784// - type `a i left down up enter enter` should create an unmarked text "愛"
1785extern "C" fn handle_key_event(this: &Object, native_event: id, key_equivalent: bool) -> BOOL {
1786 let window_state = unsafe { get_window_state(this) };
1787 let mut lock = window_state.as_ref().lock();
1788
1789 let window_height = lock.content_size().height;
1790 let event = unsafe { platform_input_from_native(native_event, Some(window_height)) };
1791
1792 let Some(event) = event else {
1793 return NO;
1794 };
1795
1796 let run_callback = |event: PlatformInput| -> BOOL {
1797 let mut callback = window_state.as_ref().lock().event_callback.take();
1798 let handled: BOOL = if let Some(callback) = callback.as_mut() {
1799 !callback(event).propagate as BOOL
1800 } else {
1801 NO
1802 };
1803 window_state.as_ref().lock().event_callback = callback;
1804 handled
1805 };
1806
1807 match event {
1808 PlatformInput::KeyDown(key_down_event) => {
1809 // For certain keystrokes, macOS will first dispatch a "key equivalent" event.
1810 // If that event isn't handled, it will then dispatch a "key down" event. GPUI
1811 // makes no distinction between these two types of events, so we need to ignore
1812 // the "key down" event if we've already just processed its "key equivalent" version.
1813 if key_equivalent {
1814 lock.last_key_equivalent = Some(key_down_event.clone());
1815 } else if lock.last_key_equivalent.take().as_ref() == Some(&key_down_event) {
1816 return NO;
1817 }
1818
1819 drop(lock);
1820
1821 let is_composing =
1822 with_input_handler(this, |input_handler| input_handler.marked_text_range())
1823 .flatten()
1824 .is_some();
1825
1826 // If we're composing, send the key to the input handler first;
1827 // otherwise we only send to the input handler if we don't have a matching binding.
1828 // The input handler may call `do_command_by_selector` if it doesn't know how to handle
1829 // a key. If it does so, it will return YES so we won't send the key twice.
1830 // We also do this for non-printing keys (like arrow keys and escape) as the IME menu
1831 // may need them even if there is no marked text;
1832 // however we skip keys with control or the input handler adds control-characters to the buffer.
1833 // and keys with function, as the input handler swallows them.
1834 // and keys with platform (Cmd), so that Cmd+key events (e.g. Cmd+`) are not
1835 // consumed by the IME on non-QWERTY / dead-key layouts.
1836 if is_composing
1837 || (key_down_event.keystroke.key_char.is_none()
1838 && !key_down_event.keystroke.modifiers.control
1839 && !key_down_event.keystroke.modifiers.function
1840 && !key_down_event.keystroke.modifiers.platform)
1841 {
1842 {
1843 let mut lock = window_state.as_ref().lock();
1844 lock.keystroke_for_do_command = Some(key_down_event.keystroke.clone());
1845 lock.do_command_handled.take();
1846 drop(lock);
1847 }
1848
1849 let handled: BOOL = unsafe {
1850 let input_context: id = msg_send![this, inputContext];
1851 msg_send![input_context, handleEvent: native_event]
1852 };
1853 window_state.as_ref().lock().keystroke_for_do_command.take();
1854 if let Some(handled) = window_state.as_ref().lock().do_command_handled.take() {
1855 return handled as BOOL;
1856 } else if handled == YES {
1857 return YES;
1858 }
1859
1860 let handled = run_callback(PlatformInput::KeyDown(key_down_event));
1861 return handled;
1862 }
1863
1864 let handled = run_callback(PlatformInput::KeyDown(key_down_event.clone()));
1865 if handled == YES {
1866 return YES;
1867 }
1868
1869 if key_down_event.is_held
1870 && let Some(key_char) = key_down_event.keystroke.key_char.as_ref()
1871 {
1872 let handled = with_input_handler(this, |input_handler| {
1873 if !input_handler.apple_press_and_hold_enabled() {
1874 input_handler.replace_text_in_range(None, key_char);
1875 return YES;
1876 }
1877 NO
1878 });
1879 if handled == Some(YES) {
1880 return YES;
1881 }
1882 }
1883
1884 // Don't send key equivalents to the input handler if there are key modifiers other
1885 // than Function key, or macOS shortcuts like cmd-` will stop working.
1886 if key_equivalent && key_down_event.keystroke.modifiers != Modifiers::function() {
1887 return NO;
1888 }
1889
1890 unsafe {
1891 let input_context: id = msg_send![this, inputContext];
1892 msg_send![input_context, handleEvent: native_event]
1893 }
1894 }
1895
1896 PlatformInput::KeyUp(_) => {
1897 drop(lock);
1898 run_callback(event)
1899 }
1900
1901 _ => NO,
1902 }
1903}
1904
1905extern "C" fn handle_view_event(this: &Object, _: Sel, native_event: id) {
1906 let window_state = unsafe { get_window_state(this) };
1907 let weak_window_state = Arc::downgrade(&window_state);
1908 let mut lock = window_state.as_ref().lock();
1909 let window_height = lock.content_size().height;
1910 let event = unsafe { platform_input_from_native(native_event, Some(window_height)) };
1911
1912 if let Some(mut event) = event {
1913 match &mut event {
1914 PlatformInput::MouseDown(
1915 event @ MouseDownEvent {
1916 button: MouseButton::Left,
1917 modifiers: Modifiers { control: true, .. },
1918 ..
1919 },
1920 ) => {
1921 // On mac, a ctrl-left click should be handled as a right click.
1922 *event = MouseDownEvent {
1923 button: MouseButton::Right,
1924 modifiers: Modifiers {
1925 control: false,
1926 ..event.modifiers
1927 },
1928 click_count: 1,
1929 ..*event
1930 };
1931 }
1932
1933 // Handles focusing click.
1934 PlatformInput::MouseDown(
1935 event @ MouseDownEvent {
1936 button: MouseButton::Left,
1937 ..
1938 },
1939 ) if (lock.first_mouse) => {
1940 *event = MouseDownEvent {
1941 first_mouse: true,
1942 ..*event
1943 };
1944 lock.first_mouse = false;
1945 }
1946
1947 // Because we map a ctrl-left_down to a right_down -> right_up let's ignore
1948 // the ctrl-left_up to avoid having a mismatch in button down/up events if the
1949 // user is still holding ctrl when releasing the left mouse button
1950 PlatformInput::MouseUp(
1951 event @ MouseUpEvent {
1952 button: MouseButton::Left,
1953 modifiers: Modifiers { control: true, .. },
1954 ..
1955 },
1956 ) => {
1957 *event = MouseUpEvent {
1958 button: MouseButton::Right,
1959 modifiers: Modifiers {
1960 control: false,
1961 ..event.modifiers
1962 },
1963 click_count: 1,
1964 ..*event
1965 };
1966 }
1967
1968 _ => {}
1969 };
1970
1971 match &event {
1972 PlatformInput::MouseDown(_) => {
1973 drop(lock);
1974 unsafe {
1975 let input_context: id = msg_send![this, inputContext];
1976 msg_send![input_context, handleEvent: native_event]
1977 }
1978 lock = window_state.as_ref().lock();
1979 }
1980 PlatformInput::MouseMove(
1981 event @ MouseMoveEvent {
1982 pressed_button: Some(_),
1983 ..
1984 },
1985 ) => {
1986 // Synthetic drag is used for selecting long buffer contents while buffer is being scrolled.
1987 // External file drag and drop is able to emit its own synthetic mouse events which will conflict
1988 // with these ones.
1989 if !lock.external_files_dragged {
1990 lock.synthetic_drag_counter += 1;
1991 let executor = lock.foreground_executor.clone();
1992 executor
1993 .spawn(synthetic_drag(
1994 weak_window_state,
1995 lock.synthetic_drag_counter,
1996 event.clone(),
1997 lock.background_executor.clone(),
1998 ))
1999 .detach();
2000 }
2001 }
2002
2003 PlatformInput::MouseUp(MouseUpEvent { .. }) => {
2004 lock.synthetic_drag_counter += 1;
2005 }
2006
2007 PlatformInput::ModifiersChanged(ModifiersChangedEvent {
2008 modifiers,
2009 capslock,
2010 }) => {
2011 // Only raise modifiers changed event when they have actually changed
2012 if let Some(PlatformInput::ModifiersChanged(ModifiersChangedEvent {
2013 modifiers: prev_modifiers,
2014 capslock: prev_capslock,
2015 })) = &lock.previous_modifiers_changed_event
2016 && prev_modifiers == modifiers
2017 && prev_capslock == capslock
2018 {
2019 return;
2020 }
2021
2022 lock.previous_modifiers_changed_event = Some(event.clone());
2023 }
2024
2025 _ => {}
2026 }
2027
2028 if let Some(mut callback) = lock.event_callback.take() {
2029 drop(lock);
2030 callback(event);
2031 window_state.lock().event_callback = Some(callback);
2032 }
2033 }
2034}
2035
2036extern "C" fn window_did_change_occlusion_state(this: &Object, _: Sel, _: id) {
2037 let window_state = unsafe { get_window_state(this) };
2038 let lock = &mut *window_state.lock();
2039 unsafe {
2040 if lock
2041 .native_window
2042 .occlusionState()
2043 .contains(NSWindowOcclusionState::NSWindowOcclusionStateVisible)
2044 {
2045 lock.move_traffic_light();
2046 lock.start_display_link();
2047 } else {
2048 lock.stop_display_link();
2049 }
2050 }
2051}
2052
2053extern "C" fn window_did_resize(this: &Object, _: Sel, _: id) {
2054 let window_state = unsafe { get_window_state(this) };
2055 window_state.as_ref().lock().move_traffic_light();
2056}
2057
2058extern "C" fn window_will_enter_fullscreen(this: &Object, _: Sel, _: id) {
2059 let window_state = unsafe { get_window_state(this) };
2060 let mut lock = window_state.as_ref().lock();
2061 lock.fullscreen_restore_bounds = lock.bounds();
2062
2063 let min_version = NSOperatingSystemVersion::new(15, 3, 0);
2064
2065 if is_macos_version_at_least(min_version) {
2066 unsafe {
2067 lock.native_window.setTitlebarAppearsTransparent_(NO);
2068 }
2069 }
2070}
2071
2072extern "C" fn window_will_exit_fullscreen(this: &Object, _: Sel, _: id) {
2073 let window_state = unsafe { get_window_state(this) };
2074 let lock = window_state.as_ref().lock();
2075
2076 let min_version = NSOperatingSystemVersion::new(15, 3, 0);
2077
2078 if is_macos_version_at_least(min_version) && lock.transparent_titlebar {
2079 unsafe {
2080 lock.native_window.setTitlebarAppearsTransparent_(YES);
2081 }
2082 }
2083}
2084
2085pub(crate) fn is_macos_version_at_least(version: NSOperatingSystemVersion) -> bool {
2086 unsafe { NSProcessInfo::processInfo(nil).isOperatingSystemAtLeastVersion(version) }
2087}
2088
2089extern "C" fn window_did_move(this: &Object, _: Sel, _: id) {
2090 let window_state = unsafe { get_window_state(this) };
2091 let mut lock = window_state.as_ref().lock();
2092 if let Some(mut callback) = lock.moved_callback.take() {
2093 drop(lock);
2094 callback();
2095 window_state.lock().moved_callback = Some(callback);
2096 }
2097}
2098
2099// Update the window scale factor and drawable size, and call the resize callback if any.
2100fn update_window_scale_factor(window_state: &Arc<Mutex<MacWindowState>>) {
2101 let mut lock = window_state.as_ref().lock();
2102 let scale_factor = lock.scale_factor();
2103 let size = lock.content_size();
2104 let drawable_size = size.to_device_pixels(scale_factor);
2105 if let Some(layer) = lock.renderer.layer() {
2106 unsafe {
2107 let _: () = msg_send![
2108 layer,
2109 setContentsScale: scale_factor as f64
2110 ];
2111 }
2112 }
2113
2114 lock.renderer.update_drawable_size(drawable_size);
2115
2116 if let Some(mut callback) = lock.resize_callback.take() {
2117 let content_size = lock.content_size();
2118 let scale_factor = lock.scale_factor();
2119 drop(lock);
2120 callback(content_size, scale_factor);
2121 window_state.as_ref().lock().resize_callback = Some(callback);
2122 };
2123}
2124
2125extern "C" fn window_did_change_screen(this: &Object, _: Sel, _: id) {
2126 let window_state = unsafe { get_window_state(this) };
2127 let mut lock = window_state.as_ref().lock();
2128 lock.start_display_link();
2129 drop(lock);
2130 update_window_scale_factor(&window_state);
2131}
2132
2133extern "C" fn window_did_change_key_status(this: &Object, selector: Sel, _: id) {
2134 let window_state = unsafe { get_window_state(this) };
2135 let lock = window_state.lock();
2136 let is_active = unsafe { lock.native_window.isKeyWindow() == YES };
2137
2138 // When opening a pop-up while the application isn't active, Cocoa sends a spurious
2139 // `windowDidBecomeKey` message to the previous key window even though that window
2140 // isn't actually key. This causes a bug if the application is later activated while
2141 // the pop-up is still open, making it impossible to activate the previous key window
2142 // even if the pop-up gets closed. The only way to activate it again is to de-activate
2143 // the app and re-activate it, which is a pretty bad UX.
2144 // The following code detects the spurious event and invokes `resignKeyWindow`:
2145 // in theory, we're not supposed to invoke this method manually but it balances out
2146 // the spurious `becomeKeyWindow` event and helps us work around that bug.
2147 if selector == sel!(windowDidBecomeKey:) && !is_active {
2148 let native_window = lock.native_window;
2149 drop(lock);
2150 unsafe {
2151 let _: () = msg_send![native_window, resignKeyWindow];
2152 }
2153 return;
2154 }
2155
2156 let executor = lock.foreground_executor.clone();
2157 drop(lock);
2158
2159 // When a window becomes active, trigger an immediate synchronous frame request to prevent
2160 // tab flicker when switching between windows in native tabs mode.
2161 //
2162 // This is only done on subsequent activations (not the first) to ensure the initial focus
2163 // path is properly established. Without this guard, the focus state would remain unset until
2164 // the first mouse click, causing keybindings to be non-functional.
2165 if selector == sel!(windowDidBecomeKey:) && is_active {
2166 let window_state = unsafe { get_window_state(this) };
2167 let mut lock = window_state.lock();
2168
2169 if lock.activated_least_once {
2170 if let Some(mut callback) = lock.request_frame_callback.take() {
2171 lock.renderer.set_presents_with_transaction(true);
2172 lock.stop_display_link();
2173 drop(lock);
2174 callback(Default::default());
2175
2176 let mut lock = window_state.lock();
2177 lock.request_frame_callback = Some(callback);
2178 lock.renderer.set_presents_with_transaction(false);
2179 lock.start_display_link();
2180 }
2181 } else {
2182 lock.activated_least_once = true;
2183 }
2184 }
2185
2186 executor
2187 .spawn(async move {
2188 let mut lock = window_state.as_ref().lock();
2189 if is_active {
2190 lock.move_traffic_light();
2191 }
2192
2193 if let Some(mut callback) = lock.activate_callback.take() {
2194 drop(lock);
2195 callback(is_active);
2196 window_state.lock().activate_callback = Some(callback);
2197 };
2198 })
2199 .detach();
2200}
2201
2202extern "C" fn window_should_close(this: &Object, _: Sel, _: id) -> BOOL {
2203 let window_state = unsafe { get_window_state(this) };
2204 let mut lock = window_state.as_ref().lock();
2205 if let Some(mut callback) = lock.should_close_callback.take() {
2206 drop(lock);
2207 let should_close = callback();
2208 window_state.lock().should_close_callback = Some(callback);
2209 should_close as BOOL
2210 } else {
2211 YES
2212 }
2213}
2214
2215extern "C" fn close_window(this: &Object, _: Sel) {
2216 unsafe {
2217 let close_callback = {
2218 let window_state = get_window_state(this);
2219 let mut lock = window_state.as_ref().lock();
2220 lock.closed.store(true, Ordering::Release);
2221 lock.close_callback.take()
2222 };
2223
2224 if let Some(callback) = close_callback {
2225 callback();
2226 }
2227
2228 let _: () = msg_send![super(this, class!(NSWindow)), close];
2229 }
2230}
2231
2232extern "C" fn make_backing_layer(this: &Object, _: Sel) -> id {
2233 let window_state = unsafe { get_window_state(this) };
2234 let window_state = window_state.as_ref().lock();
2235 window_state.renderer.layer_ptr() as id
2236}
2237
2238extern "C" fn view_did_change_backing_properties(this: &Object, _: Sel) {
2239 let window_state = unsafe { get_window_state(this) };
2240 update_window_scale_factor(&window_state);
2241}
2242
2243extern "C" fn set_frame_size(this: &Object, _: Sel, size: NSSize) {
2244 fn convert(value: NSSize) -> Size<Pixels> {
2245 Size {
2246 width: px(value.width as f32),
2247 height: px(value.height as f32),
2248 }
2249 }
2250
2251 let window_state = unsafe { get_window_state(this) };
2252 let mut lock = window_state.as_ref().lock();
2253
2254 let new_size = convert(size);
2255 let old_size = unsafe {
2256 let old_frame: NSRect = msg_send![this, frame];
2257 convert(old_frame.size)
2258 };
2259
2260 if old_size == new_size {
2261 return;
2262 }
2263
2264 unsafe {
2265 let _: () = msg_send![super(this, class!(NSView)), setFrameSize: size];
2266 }
2267
2268 let scale_factor = lock.scale_factor();
2269 let drawable_size = new_size.to_device_pixels(scale_factor);
2270 lock.renderer.update_drawable_size(drawable_size);
2271
2272 if let Some(mut callback) = lock.resize_callback.take() {
2273 let content_size = lock.content_size();
2274 let scale_factor = lock.scale_factor();
2275 drop(lock);
2276 callback(content_size, scale_factor);
2277 window_state.lock().resize_callback = Some(callback);
2278 };
2279}
2280
2281extern "C" fn display_layer(this: &Object, _: Sel, _: id) {
2282 let window_state = unsafe { get_window_state(this) };
2283 let mut lock = window_state.lock();
2284 if let Some(mut callback) = lock.request_frame_callback.take() {
2285 lock.renderer.set_presents_with_transaction(true);
2286 lock.stop_display_link();
2287 drop(lock);
2288 callback(Default::default());
2289
2290 let mut lock = window_state.lock();
2291 lock.request_frame_callback = Some(callback);
2292 lock.renderer.set_presents_with_transaction(false);
2293 lock.start_display_link();
2294 }
2295}
2296
2297extern "C" fn step(view: *mut c_void) {
2298 let view = view as id;
2299 let window_state = unsafe { get_window_state(&*view) };
2300 let mut lock = window_state.lock();
2301
2302 if let Some(mut callback) = lock.request_frame_callback.take() {
2303 drop(lock);
2304 callback(Default::default());
2305 window_state.lock().request_frame_callback = Some(callback);
2306 }
2307}
2308
2309extern "C" fn valid_attributes_for_marked_text(_: &Object, _: Sel) -> id {
2310 unsafe { msg_send![class!(NSArray), array] }
2311}
2312
2313extern "C" fn has_marked_text(this: &Object, _: Sel) -> BOOL {
2314 let has_marked_text_result =
2315 with_input_handler(this, |input_handler| input_handler.marked_text_range()).flatten();
2316
2317 has_marked_text_result.is_some() as BOOL
2318}
2319
2320extern "C" fn marked_range(this: &Object, _: Sel) -> NSRange {
2321 let marked_range_result =
2322 with_input_handler(this, |input_handler| input_handler.marked_text_range()).flatten();
2323
2324 marked_range_result.map_or(NSRange::invalid(), |range| range.into())
2325}
2326
2327extern "C" fn selected_range(this: &Object, _: Sel) -> NSRange {
2328 let selected_range_result = with_input_handler(this, |input_handler| {
2329 input_handler.selected_text_range(false)
2330 })
2331 .flatten();
2332
2333 selected_range_result.map_or(NSRange::invalid(), |selection| selection.range.into())
2334}
2335
2336extern "C" fn first_rect_for_character_range(
2337 this: &Object,
2338 _: Sel,
2339 range: NSRange,
2340 _: id,
2341) -> NSRect {
2342 let frame = get_frame(this);
2343 with_input_handler(this, |input_handler| {
2344 input_handler.bounds_for_range(range.to_range()?)
2345 })
2346 .flatten()
2347 .map_or(
2348 NSRect::new(NSPoint::new(0., 0.), NSSize::new(0., 0.)),
2349 |bounds| {
2350 NSRect::new(
2351 NSPoint::new(
2352 frame.origin.x + bounds.origin.x.as_f32() as f64,
2353 frame.origin.y + frame.size.height
2354 - bounds.origin.y.as_f32() as f64
2355 - bounds.size.height.as_f32() as f64,
2356 ),
2357 NSSize::new(
2358 bounds.size.width.as_f32() as f64,
2359 bounds.size.height.as_f32() as f64,
2360 ),
2361 )
2362 },
2363 )
2364}
2365
2366fn get_frame(this: &Object) -> NSRect {
2367 unsafe {
2368 let state = get_window_state(this);
2369 let lock = state.lock();
2370 let mut frame = NSWindow::frame(lock.native_window);
2371 let content_layout_rect: CGRect = msg_send![lock.native_window, contentLayoutRect];
2372 let style_mask: NSWindowStyleMask = msg_send![lock.native_window, styleMask];
2373 if !style_mask.contains(NSWindowStyleMask::NSFullSizeContentViewWindowMask) {
2374 frame.origin.y -= frame.size.height - content_layout_rect.size.height;
2375 }
2376 frame
2377 }
2378}
2379
2380extern "C" fn insert_text(this: &Object, _: Sel, text: id, replacement_range: NSRange) {
2381 unsafe {
2382 let is_attributed_string: BOOL =
2383 msg_send![text, isKindOfClass: [class!(NSAttributedString)]];
2384 let text: id = if is_attributed_string == YES {
2385 msg_send![text, string]
2386 } else {
2387 text
2388 };
2389
2390 let text = text.to_str();
2391 let replacement_range = replacement_range.to_range();
2392 with_input_handler(this, |input_handler| {
2393 input_handler.replace_text_in_range(replacement_range, text)
2394 });
2395 }
2396}
2397
2398extern "C" fn set_marked_text(
2399 this: &Object,
2400 _: Sel,
2401 text: id,
2402 selected_range: NSRange,
2403 replacement_range: NSRange,
2404) {
2405 unsafe {
2406 let is_attributed_string: BOOL =
2407 msg_send![text, isKindOfClass: [class!(NSAttributedString)]];
2408 let text: id = if is_attributed_string == YES {
2409 msg_send![text, string]
2410 } else {
2411 text
2412 };
2413 let selected_range = selected_range.to_range();
2414 let replacement_range = replacement_range.to_range();
2415 let text = text.to_str();
2416 with_input_handler(this, |input_handler| {
2417 input_handler.replace_and_mark_text_in_range(replacement_range, text, selected_range)
2418 });
2419 }
2420}
2421extern "C" fn unmark_text(this: &Object, _: Sel) {
2422 with_input_handler(this, |input_handler| input_handler.unmark_text());
2423}
2424
2425extern "C" fn attributed_substring_for_proposed_range(
2426 this: &Object,
2427 _: Sel,
2428 range: NSRange,
2429 actual_range: *mut c_void,
2430) -> id {
2431 with_input_handler(this, |input_handler| {
2432 let range = range.to_range()?;
2433 if range.is_empty() {
2434 return None;
2435 }
2436 let mut adjusted: Option<Range<usize>> = None;
2437
2438 let selected_text = input_handler.text_for_range(range.clone(), &mut adjusted)?;
2439 if let Some(adjusted) = adjusted
2440 && adjusted != range
2441 {
2442 unsafe { (actual_range as *mut NSRange).write(NSRange::from(adjusted)) };
2443 }
2444 unsafe {
2445 let string: id = msg_send![class!(NSAttributedString), alloc];
2446 let string: id = msg_send![string, initWithString: ns_string(&selected_text)];
2447 Some(string)
2448 }
2449 })
2450 .flatten()
2451 .unwrap_or(nil)
2452}
2453
2454// We ignore which selector it asks us to do because the user may have
2455// bound the shortcut to something else.
2456extern "C" fn do_command_by_selector(this: &Object, _: Sel, _: Sel) {
2457 let state = unsafe { get_window_state(this) };
2458 let mut lock = state.as_ref().lock();
2459 let keystroke = lock.keystroke_for_do_command.take();
2460 let mut event_callback = lock.event_callback.take();
2461 drop(lock);
2462
2463 if let Some((keystroke, callback)) = keystroke.zip(event_callback.as_mut()) {
2464 let handled = (callback)(PlatformInput::KeyDown(KeyDownEvent {
2465 keystroke,
2466 is_held: false,
2467 prefer_character_input: false,
2468 }));
2469 state.as_ref().lock().do_command_handled = Some(!handled.propagate);
2470 }
2471
2472 state.as_ref().lock().event_callback = event_callback;
2473}
2474
2475extern "C" fn view_did_change_effective_appearance(this: &Object, _: Sel) {
2476 unsafe {
2477 let state = get_window_state(this);
2478 let mut lock = state.as_ref().lock();
2479 if let Some(mut callback) = lock.appearance_changed_callback.take() {
2480 drop(lock);
2481 callback();
2482 state.lock().appearance_changed_callback = Some(callback);
2483 }
2484 }
2485}
2486
2487extern "C" fn accepts_first_mouse(this: &Object, _: Sel, _: id) -> BOOL {
2488 let window_state = unsafe { get_window_state(this) };
2489 let mut lock = window_state.as_ref().lock();
2490 lock.first_mouse = true;
2491 YES
2492}
2493
2494extern "C" fn character_index_for_point(this: &Object, _: Sel, position: NSPoint) -> u64 {
2495 let position = screen_point_to_gpui_point(this, position);
2496 with_input_handler(this, |input_handler| {
2497 input_handler.character_index_for_point(position)
2498 })
2499 .flatten()
2500 .map(|index| index as u64)
2501 .unwrap_or(NSNotFound as u64)
2502}
2503
2504fn screen_point_to_gpui_point(this: &Object, position: NSPoint) -> Point<Pixels> {
2505 let frame = get_frame(this);
2506 let window_x = position.x - frame.origin.x;
2507 let window_y = frame.size.height - (position.y - frame.origin.y);
2508
2509 point(px(window_x as f32), px(window_y as f32))
2510}
2511
2512extern "C" fn dragging_entered(this: &Object, _: Sel, dragging_info: id) -> NSDragOperation {
2513 let window_state = unsafe { get_window_state(this) };
2514 let position = drag_event_position(&window_state, dragging_info);
2515 let paths = external_paths_from_event(dragging_info);
2516 if let Some(event) = paths.map(|paths| FileDropEvent::Entered { position, paths })
2517 && send_file_drop_event(window_state, event)
2518 {
2519 return NSDragOperationCopy;
2520 }
2521 NSDragOperationNone
2522}
2523
2524extern "C" fn dragging_updated(this: &Object, _: Sel, dragging_info: id) -> NSDragOperation {
2525 let window_state = unsafe { get_window_state(this) };
2526 let position = drag_event_position(&window_state, dragging_info);
2527 if send_file_drop_event(window_state, FileDropEvent::Pending { position }) {
2528 NSDragOperationCopy
2529 } else {
2530 NSDragOperationNone
2531 }
2532}
2533
2534extern "C" fn dragging_exited(this: &Object, _: Sel, _: id) {
2535 let window_state = unsafe { get_window_state(this) };
2536 send_file_drop_event(window_state, FileDropEvent::Exited);
2537}
2538
2539extern "C" fn perform_drag_operation(this: &Object, _: Sel, dragging_info: id) -> BOOL {
2540 let window_state = unsafe { get_window_state(this) };
2541 let position = drag_event_position(&window_state, dragging_info);
2542 send_file_drop_event(window_state, FileDropEvent::Submit { position }).to_objc()
2543}
2544
2545fn external_paths_from_event(dragging_info: *mut Object) -> Option<ExternalPaths> {
2546 let mut paths = SmallVec::new();
2547 let pasteboard: id = unsafe { msg_send![dragging_info, draggingPasteboard] };
2548 let filenames = unsafe { NSPasteboard::propertyListForType(pasteboard, NSFilenamesPboardType) };
2549 if filenames == nil {
2550 return None;
2551 }
2552 for file in unsafe { filenames.iter() } {
2553 let path = unsafe {
2554 let f = NSString::UTF8String(file);
2555 CStr::from_ptr(f).to_string_lossy().into_owned()
2556 };
2557 paths.push(PathBuf::from(path))
2558 }
2559 Some(ExternalPaths(paths))
2560}
2561
2562extern "C" fn conclude_drag_operation(this: &Object, _: Sel, _: id) {
2563 let window_state = unsafe { get_window_state(this) };
2564 send_file_drop_event(window_state, FileDropEvent::Exited);
2565}
2566
2567async fn synthetic_drag(
2568 window_state: Weak<Mutex<MacWindowState>>,
2569 drag_id: usize,
2570 event: MouseMoveEvent,
2571 executor: BackgroundExecutor,
2572) {
2573 loop {
2574 executor.timer(Duration::from_millis(16)).await;
2575 if let Some(window_state) = window_state.upgrade() {
2576 let mut lock = window_state.lock();
2577 if lock.synthetic_drag_counter == drag_id {
2578 if let Some(mut callback) = lock.event_callback.take() {
2579 drop(lock);
2580 callback(PlatformInput::MouseMove(event.clone()));
2581 window_state.lock().event_callback = Some(callback);
2582 }
2583 } else {
2584 break;
2585 }
2586 }
2587 }
2588}
2589
2590/// Sends the specified FileDropEvent using `PlatformInput::FileDrop` to the window
2591/// state and updates the window state according to the event passed.
2592fn send_file_drop_event(
2593 window_state: Arc<Mutex<MacWindowState>>,
2594 file_drop_event: FileDropEvent,
2595) -> bool {
2596 let external_files_dragged = match file_drop_event {
2597 FileDropEvent::Entered { .. } => Some(true),
2598 FileDropEvent::Exited => Some(false),
2599 _ => None,
2600 };
2601
2602 let mut lock = window_state.lock();
2603 if let Some(mut callback) = lock.event_callback.take() {
2604 drop(lock);
2605 callback(PlatformInput::FileDrop(file_drop_event));
2606 let mut lock = window_state.lock();
2607 lock.event_callback = Some(callback);
2608 if let Some(external_files_dragged) = external_files_dragged {
2609 lock.external_files_dragged = external_files_dragged;
2610 }
2611 true
2612 } else {
2613 false
2614 }
2615}
2616
2617fn drag_event_position(window_state: &Mutex<MacWindowState>, dragging_info: id) -> Point<Pixels> {
2618 let drag_location: NSPoint = unsafe { msg_send![dragging_info, draggingLocation] };
2619 convert_mouse_position(drag_location, window_state.lock().content_size().height)
2620}
2621
2622fn with_input_handler<F, R>(window: &Object, f: F) -> Option<R>
2623where
2624 F: FnOnce(&mut PlatformInputHandler) -> R,
2625{
2626 let window_state = unsafe { get_window_state(window) };
2627 let mut lock = window_state.as_ref().lock();
2628 if let Some(mut input_handler) = lock.input_handler.take() {
2629 drop(lock);
2630 let result = f(&mut input_handler);
2631 window_state.lock().input_handler = Some(input_handler);
2632 Some(result)
2633 } else {
2634 None
2635 }
2636}
2637
2638unsafe fn display_id_for_screen(screen: id) -> CGDirectDisplayID {
2639 unsafe {
2640 let device_description = NSScreen::deviceDescription(screen);
2641 let screen_number_key: id = ns_string("NSScreenNumber");
2642 let screen_number = device_description.objectForKey_(screen_number_key);
2643 let screen_number: NSUInteger = msg_send![screen_number, unsignedIntegerValue];
2644 screen_number as CGDirectDisplayID
2645 }
2646}
2647
2648extern "C" fn blurred_view_init_with_frame(this: &Object, _: Sel, frame: NSRect) -> id {
2649 unsafe {
2650 let view = msg_send![super(this, class!(NSVisualEffectView)), initWithFrame: frame];
2651 // Use a colorless semantic material. The default value `AppearanceBased`, though not
2652 // manually set, is deprecated.
2653 NSVisualEffectView::setMaterial_(view, NSVisualEffectMaterial::Selection);
2654 NSVisualEffectView::setState_(view, NSVisualEffectState::Active);
2655 view
2656 }
2657}
2658
2659extern "C" fn blurred_view_update_layer(this: &Object, _: Sel) {
2660 unsafe {
2661 let _: () = msg_send![super(this, class!(NSVisualEffectView)), updateLayer];
2662 let layer: id = msg_send![this, layer];
2663 if !layer.is_null() {
2664 remove_layer_background(layer);
2665 }
2666 }
2667}
2668
2669unsafe fn remove_layer_background(layer: id) {
2670 unsafe {
2671 let _: () = msg_send![layer, setBackgroundColor:nil];
2672
2673 let class_name: id = msg_send![layer, className];
2674 if class_name.isEqualToString("CAChameleonLayer") {
2675 // Remove the desktop tinting effect.
2676 let _: () = msg_send![layer, setHidden: YES];
2677 return;
2678 }
2679
2680 let filters: id = msg_send![layer, filters];
2681 if !filters.is_null() {
2682 // Remove the increased saturation.
2683 // The effect of a `CAFilter` or `CIFilter` is determined by its name, and the
2684 // `description` reflects its name and some parameters. Currently `NSVisualEffectView`
2685 // uses a `CAFilter` named "colorSaturate". If one day they switch to `CIFilter`, the
2686 // `description` will still contain "Saturat" ("... inputSaturation = ...").
2687 let test_string: id = ns_string("Saturat");
2688 let count = NSArray::count(filters);
2689 for i in 0..count {
2690 let description: id = msg_send![filters.objectAtIndex(i), description];
2691 let hit: BOOL = msg_send![description, containsString: test_string];
2692 if hit == NO {
2693 continue;
2694 }
2695
2696 let all_indices = NSRange {
2697 location: 0,
2698 length: count,
2699 };
2700 let indices: id = msg_send![class!(NSMutableIndexSet), indexSet];
2701 let _: () = msg_send![indices, addIndexesInRange: all_indices];
2702 let _: () = msg_send![indices, removeIndex:i];
2703 let filtered: id = msg_send![filters, objectsAtIndexes: indices];
2704 let _: () = msg_send![layer, setFilters: filtered];
2705 break;
2706 }
2707 }
2708
2709 let sublayers: id = msg_send![layer, sublayers];
2710 if !sublayers.is_null() {
2711 let count = NSArray::count(sublayers);
2712 for i in 0..count {
2713 let sublayer = sublayers.objectAtIndex(i);
2714 remove_layer_background(sublayer);
2715 }
2716 }
2717 }
2718}
2719
2720extern "C" fn add_titlebar_accessory_view_controller(this: &Object, _: Sel, view_controller: id) {
2721 unsafe {
2722 let _: () = msg_send![super(this, class!(NSWindow)), addTitlebarAccessoryViewController: view_controller];
2723
2724 // Hide the native tab bar and set its height to 0, since we render our own.
2725 let accessory_view: id = msg_send![view_controller, view];
2726 let _: () = msg_send![accessory_view, setHidden: YES];
2727 let mut frame: NSRect = msg_send![accessory_view, frame];
2728 frame.size.height = 0.0;
2729 let _: () = msg_send![accessory_view, setFrame: frame];
2730 }
2731}
2732
2733extern "C" fn move_tab_to_new_window(this: &Object, _: Sel, _: id) {
2734 unsafe {
2735 let _: () = msg_send![super(this, class!(NSWindow)), moveTabToNewWindow:nil];
2736
2737 let window_state = get_window_state(this);
2738 let mut lock = window_state.as_ref().lock();
2739 if let Some(mut callback) = lock.move_tab_to_new_window_callback.take() {
2740 drop(lock);
2741 callback();
2742 window_state.lock().move_tab_to_new_window_callback = Some(callback);
2743 }
2744 }
2745}
2746
2747extern "C" fn merge_all_windows(this: &Object, _: Sel, _: id) {
2748 unsafe {
2749 let _: () = msg_send![super(this, class!(NSWindow)), mergeAllWindows:nil];
2750
2751 let window_state = get_window_state(this);
2752 let mut lock = window_state.as_ref().lock();
2753 if let Some(mut callback) = lock.merge_all_windows_callback.take() {
2754 drop(lock);
2755 callback();
2756 window_state.lock().merge_all_windows_callback = Some(callback);
2757 }
2758 }
2759}
2760
2761extern "C" fn select_next_tab(this: &Object, _sel: Sel, _id: id) {
2762 let window_state = unsafe { get_window_state(this) };
2763 let mut lock = window_state.as_ref().lock();
2764 if let Some(mut callback) = lock.select_next_tab_callback.take() {
2765 drop(lock);
2766 callback();
2767 window_state.lock().select_next_tab_callback = Some(callback);
2768 }
2769}
2770
2771extern "C" fn select_previous_tab(this: &Object, _sel: Sel, _id: id) {
2772 let window_state = unsafe { get_window_state(this) };
2773 let mut lock = window_state.as_ref().lock();
2774 if let Some(mut callback) = lock.select_previous_tab_callback.take() {
2775 drop(lock);
2776 callback();
2777 window_state.lock().select_previous_tab_callback = Some(callback);
2778 }
2779}
2780
2781extern "C" fn toggle_tab_bar(this: &Object, _sel: Sel, _id: id) {
2782 unsafe {
2783 let _: () = msg_send![super(this, class!(NSWindow)), toggleTabBar:nil];
2784
2785 let window_state = get_window_state(this);
2786 let mut lock = window_state.as_ref().lock();
2787 lock.move_traffic_light();
2788
2789 if let Some(mut callback) = lock.toggle_tab_bar_callback.take() {
2790 drop(lock);
2791 callback();
2792 window_state.lock().toggle_tab_bar_callback = Some(callback);
2793 }
2794 }
2795}