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