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