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 = NSString::alloc(nil).init_str(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 = NSString::alloc(nil).init_str("NSGlobalDomain");
912 let key = NSString::alloc(nil).init_str("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 = NSString::alloc(nil).init_str(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 = NSDictionary::valueForKey_(
1067 device_description,
1068 NSString::alloc(nil).init_str("NSScreenNumber"),
1069 );
1070
1071 let screen_number: u32 = msg_send![screen_number, unsignedIntValue];
1072
1073 Some(Rc::new(MacDisplay(screen_number)))
1074 }
1075 }
1076
1077 fn mouse_position(&self) -> Point<Pixels> {
1078 let position = unsafe {
1079 self.0
1080 .lock()
1081 .native_window
1082 .mouseLocationOutsideOfEventStream()
1083 };
1084 convert_mouse_position(position, self.content_size().height)
1085 }
1086
1087 fn modifiers(&self) -> Modifiers {
1088 unsafe {
1089 let modifiers: NSEventModifierFlags = msg_send![class!(NSEvent), modifierFlags];
1090
1091 let control = modifiers.contains(NSEventModifierFlags::NSControlKeyMask);
1092 let alt = modifiers.contains(NSEventModifierFlags::NSAlternateKeyMask);
1093 let shift = modifiers.contains(NSEventModifierFlags::NSShiftKeyMask);
1094 let command = modifiers.contains(NSEventModifierFlags::NSCommandKeyMask);
1095 let function = modifiers.contains(NSEventModifierFlags::NSFunctionKeyMask);
1096
1097 Modifiers {
1098 control,
1099 alt,
1100 shift,
1101 platform: command,
1102 function,
1103 }
1104 }
1105 }
1106
1107 fn capslock(&self) -> Capslock {
1108 unsafe {
1109 let modifiers: NSEventModifierFlags = msg_send![class!(NSEvent), modifierFlags];
1110
1111 Capslock {
1112 on: modifiers.contains(NSEventModifierFlags::NSAlphaShiftKeyMask),
1113 }
1114 }
1115 }
1116
1117 fn set_input_handler(&mut self, input_handler: PlatformInputHandler) {
1118 self.0.as_ref().lock().input_handler = Some(input_handler);
1119 }
1120
1121 fn take_input_handler(&mut self) -> Option<PlatformInputHandler> {
1122 self.0.as_ref().lock().input_handler.take()
1123 }
1124
1125 fn prompt(
1126 &self,
1127 level: PromptLevel,
1128 msg: &str,
1129 detail: Option<&str>,
1130 answers: &[PromptButton],
1131 ) -> Option<oneshot::Receiver<usize>> {
1132 // macOs applies overrides to modal window buttons after they are added.
1133 // Two most important for this logic are:
1134 // * Buttons with "Cancel" title will be displayed as the last buttons in the modal
1135 // * Last button added to the modal via `addButtonWithTitle` stays focused
1136 // * Focused buttons react on "space"/" " keypresses
1137 // * Usage of `keyEquivalent`, `makeFirstResponder` or `setInitialFirstResponder` does not change the focus
1138 //
1139 // See also https://developer.apple.com/documentation/appkit/nsalert/1524532-addbuttonwithtitle#discussion
1140 // ```
1141 // By default, the first button has a key equivalent of Return,
1142 // any button with a title of “Cancel” has a key equivalent of Escape,
1143 // 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).
1144 // ```
1145 //
1146 // To avoid situations when the last element added is "Cancel" and it gets the focus
1147 // (hence stealing both ESC and Space shortcuts), we find and add one non-Cancel button
1148 // last, so it gets focus and a Space shortcut.
1149 // This way, "Save this file? Yes/No/Cancel"-ish modals will get all three buttons mapped with a key.
1150 let latest_non_cancel_label = answers
1151 .iter()
1152 .enumerate()
1153 .rev()
1154 .find(|(_, label)| !label.is_cancel())
1155 .filter(|&(label_index, _)| label_index > 0);
1156
1157 unsafe {
1158 let alert: id = msg_send![class!(NSAlert), alloc];
1159 let alert: id = msg_send![alert, init];
1160 let alert_style = match level {
1161 PromptLevel::Info => 1,
1162 PromptLevel::Warning => 0,
1163 PromptLevel::Critical => 2,
1164 };
1165 let _: () = msg_send![alert, setAlertStyle: alert_style];
1166 let _: () = msg_send![alert, setMessageText: ns_string(msg)];
1167 if let Some(detail) = detail {
1168 let _: () = msg_send![alert, setInformativeText: ns_string(detail)];
1169 }
1170
1171 for (ix, answer) in answers
1172 .iter()
1173 .enumerate()
1174 .filter(|&(ix, _)| Some(ix) != latest_non_cancel_label.map(|(ix, _)| ix))
1175 {
1176 let button: id = msg_send![alert, addButtonWithTitle: ns_string(answer.label())];
1177 let _: () = msg_send![button, setTag: ix as NSInteger];
1178
1179 if answer.is_cancel() {
1180 // Bind Escape Key to Cancel Button
1181 if let Some(key) = std::char::from_u32(super::events::ESCAPE_KEY as u32) {
1182 let _: () =
1183 msg_send![button, setKeyEquivalent: ns_string(&key.to_string())];
1184 }
1185 }
1186 }
1187 if let Some((ix, answer)) = latest_non_cancel_label {
1188 let button: id = msg_send![alert, addButtonWithTitle: ns_string(answer.label())];
1189 let _: () = msg_send![button, setTag: ix as NSInteger];
1190 }
1191
1192 let (done_tx, done_rx) = oneshot::channel();
1193 let done_tx = Cell::new(Some(done_tx));
1194 let block = ConcreteBlock::new(move |answer: NSInteger| {
1195 if let Some(done_tx) = done_tx.take() {
1196 let _ = done_tx.send(answer.try_into().unwrap());
1197 }
1198 });
1199 let block = block.copy();
1200 let native_window = self.0.lock().native_window;
1201 let executor = self.0.lock().executor.clone();
1202 executor
1203 .spawn(async move {
1204 let _: () = msg_send![
1205 alert,
1206 beginSheetModalForWindow: native_window
1207 completionHandler: block
1208 ];
1209 })
1210 .detach();
1211
1212 Some(done_rx)
1213 }
1214 }
1215
1216 fn activate(&self) {
1217 let window = self.0.lock().native_window;
1218 let executor = self.0.lock().executor.clone();
1219 executor
1220 .spawn(async move {
1221 unsafe {
1222 let _: () = msg_send![window, makeKeyAndOrderFront: nil];
1223 }
1224 })
1225 .detach();
1226 }
1227
1228 fn is_active(&self) -> bool {
1229 unsafe { self.0.lock().native_window.isKeyWindow() == YES }
1230 }
1231
1232 // is_hovered is unused on macOS. See Window::is_window_hovered.
1233 fn is_hovered(&self) -> bool {
1234 false
1235 }
1236
1237 fn set_title(&mut self, title: &str) {
1238 unsafe {
1239 let app = NSApplication::sharedApplication(nil);
1240 let window = self.0.lock().native_window;
1241 let title = ns_string(title);
1242 let _: () = msg_send![app, changeWindowsItem:window title:title filename:false];
1243 let _: () = msg_send![window, setTitle: title];
1244 self.0.lock().move_traffic_light();
1245 }
1246 }
1247
1248 fn get_title(&self) -> String {
1249 unsafe {
1250 let title: id = msg_send![self.0.lock().native_window, title];
1251 if title.is_null() {
1252 "".to_string()
1253 } else {
1254 title.to_str().to_string()
1255 }
1256 }
1257 }
1258
1259 fn set_app_id(&mut self, _app_id: &str) {}
1260
1261 fn set_background_appearance(&self, background_appearance: WindowBackgroundAppearance) {
1262 let mut this = self.0.as_ref().lock();
1263
1264 let opaque = background_appearance == WindowBackgroundAppearance::Opaque;
1265 this.renderer.update_transparency(!opaque);
1266
1267 unsafe {
1268 this.native_window.setOpaque_(opaque as BOOL);
1269 let background_color = if opaque {
1270 NSColor::colorWithSRGBRed_green_blue_alpha_(nil, 0f64, 0f64, 0f64, 1f64)
1271 } else {
1272 // Not using `+[NSColor clearColor]` to avoid broken shadow.
1273 NSColor::colorWithSRGBRed_green_blue_alpha_(nil, 0f64, 0f64, 0f64, 0.0001)
1274 };
1275 this.native_window.setBackgroundColor_(background_color);
1276
1277 if NSAppKitVersionNumber < NSAppKitVersionNumber12_0 {
1278 // Whether `-[NSVisualEffectView respondsToSelector:@selector(_updateProxyLayer)]`.
1279 // On macOS Catalina/Big Sur `NSVisualEffectView` doesn’t own concrete sublayers
1280 // but uses a `CAProxyLayer`. Use the legacy WindowServer API.
1281 let blur_radius = if background_appearance == WindowBackgroundAppearance::Blurred {
1282 80
1283 } else {
1284 0
1285 };
1286
1287 let window_number = this.native_window.windowNumber();
1288 CGSSetWindowBackgroundBlurRadius(CGSMainConnectionID(), window_number, blur_radius);
1289 } else {
1290 // On newer macOS `NSVisualEffectView` manages the effect layer directly. Using it
1291 // could have a better performance (it downsamples the backdrop) and more control
1292 // over the effect layer.
1293 if background_appearance != WindowBackgroundAppearance::Blurred {
1294 if let Some(blur_view) = this.blurred_view {
1295 NSView::removeFromSuperview(blur_view);
1296 this.blurred_view = None;
1297 }
1298 } else if this.blurred_view.is_none() {
1299 let content_view = this.native_window.contentView();
1300 let frame = NSView::bounds(content_view);
1301 let mut blur_view: id = msg_send![BLURRED_VIEW_CLASS, alloc];
1302 blur_view = NSView::initWithFrame_(blur_view, frame);
1303 blur_view.setAutoresizingMask_(NSViewWidthSizable | NSViewHeightSizable);
1304
1305 let _: () = msg_send![
1306 content_view,
1307 addSubview: blur_view
1308 positioned: NSWindowOrderingMode::NSWindowBelow
1309 relativeTo: nil
1310 ];
1311 this.blurred_view = Some(blur_view.autorelease());
1312 }
1313 }
1314 }
1315 }
1316
1317 fn set_edited(&mut self, edited: bool) {
1318 unsafe {
1319 let window = self.0.lock().native_window;
1320 msg_send![window, setDocumentEdited: edited as BOOL]
1321 }
1322
1323 // Changing the document edited state resets the traffic light position,
1324 // so we have to move it again.
1325 self.0.lock().move_traffic_light();
1326 }
1327
1328 fn show_character_palette(&self) {
1329 let this = self.0.lock();
1330 let window = this.native_window;
1331 this.executor
1332 .spawn(async move {
1333 unsafe {
1334 let app = NSApplication::sharedApplication(nil);
1335 let _: () = msg_send![app, orderFrontCharacterPalette: window];
1336 }
1337 })
1338 .detach();
1339 }
1340
1341 fn minimize(&self) {
1342 let window = self.0.lock().native_window;
1343 unsafe {
1344 window.miniaturize_(nil);
1345 }
1346 }
1347
1348 fn zoom(&self) {
1349 let this = self.0.lock();
1350 let window = this.native_window;
1351 this.executor
1352 .spawn(async move {
1353 unsafe {
1354 window.zoom_(nil);
1355 }
1356 })
1357 .detach();
1358 }
1359
1360 fn toggle_fullscreen(&self) {
1361 let this = self.0.lock();
1362 let window = this.native_window;
1363 this.executor
1364 .spawn(async move {
1365 unsafe {
1366 window.toggleFullScreen_(nil);
1367 }
1368 })
1369 .detach();
1370 }
1371
1372 fn is_fullscreen(&self) -> bool {
1373 let this = self.0.lock();
1374 let window = this.native_window;
1375
1376 unsafe {
1377 window
1378 .styleMask()
1379 .contains(NSWindowStyleMask::NSFullScreenWindowMask)
1380 }
1381 }
1382
1383 fn on_request_frame(&self, callback: Box<dyn FnMut(RequestFrameOptions)>) {
1384 self.0.as_ref().lock().request_frame_callback = Some(callback);
1385 }
1386
1387 fn on_input(&self, callback: Box<dyn FnMut(PlatformInput) -> crate::DispatchEventResult>) {
1388 self.0.as_ref().lock().event_callback = Some(callback);
1389 }
1390
1391 fn on_active_status_change(&self, callback: Box<dyn FnMut(bool)>) {
1392 self.0.as_ref().lock().activate_callback = Some(callback);
1393 }
1394
1395 fn on_hover_status_change(&self, _: Box<dyn FnMut(bool)>) {}
1396
1397 fn on_resize(&self, callback: Box<dyn FnMut(Size<Pixels>, f32)>) {
1398 self.0.as_ref().lock().resize_callback = Some(callback);
1399 }
1400
1401 fn on_moved(&self, callback: Box<dyn FnMut()>) {
1402 self.0.as_ref().lock().moved_callback = Some(callback);
1403 }
1404
1405 fn on_should_close(&self, callback: Box<dyn FnMut() -> bool>) {
1406 self.0.as_ref().lock().should_close_callback = Some(callback);
1407 }
1408
1409 fn on_close(&self, callback: Box<dyn FnOnce()>) {
1410 self.0.as_ref().lock().close_callback = Some(callback);
1411 }
1412
1413 fn on_hit_test_window_control(&self, _callback: Box<dyn FnMut() -> Option<WindowControlArea>>) {
1414 }
1415
1416 fn on_appearance_changed(&self, callback: Box<dyn FnMut()>) {
1417 self.0.lock().appearance_changed_callback = Some(callback);
1418 }
1419
1420 fn tabbed_windows(&self) -> Option<Vec<SystemWindowTab>> {
1421 unsafe {
1422 let windows: id = msg_send![self.0.lock().native_window, tabbedWindows];
1423 if windows.is_null() {
1424 return None;
1425 }
1426
1427 let count: NSUInteger = msg_send![windows, count];
1428 let mut result = Vec::new();
1429 for i in 0..count {
1430 let window: id = msg_send![windows, objectAtIndex:i];
1431 if msg_send![window, isKindOfClass: WINDOW_CLASS] {
1432 let handle = get_window_state(&*window).lock().handle;
1433 let title: id = msg_send![window, title];
1434 let title = SharedString::from(title.to_str().to_string());
1435
1436 result.push(SystemWindowTab::new(title, handle));
1437 }
1438 }
1439
1440 Some(result)
1441 }
1442 }
1443
1444 fn tab_bar_visible(&self) -> bool {
1445 unsafe {
1446 let tab_group: id = msg_send![self.0.lock().native_window, tabGroup];
1447 if tab_group.is_null() {
1448 false
1449 } else {
1450 let tab_bar_visible: BOOL = msg_send![tab_group, isTabBarVisible];
1451 tab_bar_visible == YES
1452 }
1453 }
1454 }
1455
1456 fn on_move_tab_to_new_window(&self, callback: Box<dyn FnMut()>) {
1457 self.0.as_ref().lock().move_tab_to_new_window_callback = Some(callback);
1458 }
1459
1460 fn on_merge_all_windows(&self, callback: Box<dyn FnMut()>) {
1461 self.0.as_ref().lock().merge_all_windows_callback = Some(callback);
1462 }
1463
1464 fn on_select_next_tab(&self, callback: Box<dyn FnMut()>) {
1465 self.0.as_ref().lock().select_next_tab_callback = Some(callback);
1466 }
1467
1468 fn on_select_previous_tab(&self, callback: Box<dyn FnMut()>) {
1469 self.0.as_ref().lock().select_previous_tab_callback = Some(callback);
1470 }
1471
1472 fn on_toggle_tab_bar(&self, callback: Box<dyn FnMut()>) {
1473 self.0.as_ref().lock().toggle_tab_bar_callback = Some(callback);
1474 }
1475
1476 fn draw(&self, scene: &crate::Scene) {
1477 let mut this = self.0.lock();
1478 this.renderer.draw(scene);
1479 }
1480
1481 fn sprite_atlas(&self) -> Arc<dyn PlatformAtlas> {
1482 self.0.lock().renderer.sprite_atlas().clone()
1483 }
1484
1485 fn gpu_specs(&self) -> Option<crate::GpuSpecs> {
1486 None
1487 }
1488
1489 fn update_ime_position(&self, _bounds: Bounds<Pixels>) {
1490 let executor = self.0.lock().executor.clone();
1491 executor
1492 .spawn(async move {
1493 unsafe {
1494 let input_context: id =
1495 msg_send![class!(NSTextInputContext), currentInputContext];
1496 if input_context.is_null() {
1497 return;
1498 }
1499 let _: () = msg_send![input_context, invalidateCharacterCoordinates];
1500 }
1501 })
1502 .detach()
1503 }
1504
1505 fn titlebar_double_click(&self) {
1506 let this = self.0.lock();
1507 let window = this.native_window;
1508 this.executor
1509 .spawn(async move {
1510 unsafe {
1511 let defaults: id = NSUserDefaults::standardUserDefaults();
1512 let domain = NSString::alloc(nil).init_str("NSGlobalDomain");
1513 let key = NSString::alloc(nil).init_str("AppleActionOnDoubleClick");
1514
1515 let dict: id = msg_send![defaults, persistentDomainForName: domain];
1516 let action: id = if !dict.is_null() {
1517 msg_send![dict, objectForKey: key]
1518 } else {
1519 nil
1520 };
1521
1522 let action_str = if !action.is_null() {
1523 CStr::from_ptr(NSString::UTF8String(action)).to_string_lossy()
1524 } else {
1525 "".into()
1526 };
1527
1528 match action_str.as_ref() {
1529 "None" => {
1530 // "Do Nothing" selected, so do no action
1531 }
1532 "Minimize" => {
1533 window.miniaturize_(nil);
1534 }
1535 "Maximize" => {
1536 window.zoom_(nil);
1537 }
1538 "Fill" => {
1539 // There is no documented API for "Fill" action, so we'll just zoom the window
1540 window.zoom_(nil);
1541 }
1542 _ => {
1543 window.zoom_(nil);
1544 }
1545 }
1546 }
1547 })
1548 .detach();
1549 }
1550
1551 fn start_window_move(&self) {
1552 let this = self.0.lock();
1553 let window = this.native_window;
1554
1555 unsafe {
1556 let app = NSApplication::sharedApplication(nil);
1557 let mut event: id = msg_send![app, currentEvent];
1558 let _: () = msg_send![window, performWindowDragWithEvent: event];
1559 }
1560 }
1561}
1562
1563impl rwh::HasWindowHandle for MacWindow {
1564 fn window_handle(&self) -> Result<rwh::WindowHandle<'_>, rwh::HandleError> {
1565 // SAFETY: The AppKitWindowHandle is a wrapper around a pointer to an NSView
1566 unsafe {
1567 Ok(rwh::WindowHandle::borrow_raw(rwh::RawWindowHandle::AppKit(
1568 rwh::AppKitWindowHandle::new(self.0.lock().native_view.cast()),
1569 )))
1570 }
1571 }
1572}
1573
1574impl rwh::HasDisplayHandle for MacWindow {
1575 fn display_handle(&self) -> Result<rwh::DisplayHandle<'_>, rwh::HandleError> {
1576 // SAFETY: This is a no-op on macOS
1577 unsafe {
1578 Ok(rwh::DisplayHandle::borrow_raw(
1579 rwh::AppKitDisplayHandle::new().into(),
1580 ))
1581 }
1582 }
1583}
1584
1585fn get_scale_factor(native_window: id) -> f32 {
1586 let factor = unsafe {
1587 let screen: id = msg_send![native_window, screen];
1588 if screen.is_null() {
1589 return 2.0;
1590 }
1591 NSScreen::backingScaleFactor(screen) as f32
1592 };
1593
1594 // We are not certain what triggers this, but it seems that sometimes
1595 // this method would return 0 (https://github.com/zed-industries/zed/issues/6412)
1596 // It seems most likely that this would happen if the window has no screen
1597 // (if it is off-screen), though we'd expect to see viewDidChangeBackingProperties before
1598 // it was rendered for real.
1599 // Regardless, attempt to avoid the issue here.
1600 if factor == 0.0 { 2. } else { factor }
1601}
1602
1603unsafe fn get_window_state(object: &Object) -> Arc<Mutex<MacWindowState>> {
1604 unsafe {
1605 let raw: *mut c_void = *object.get_ivar(WINDOW_STATE_IVAR);
1606 let rc1 = Arc::from_raw(raw as *mut Mutex<MacWindowState>);
1607 let rc2 = rc1.clone();
1608 mem::forget(rc1);
1609 rc2
1610 }
1611}
1612
1613unsafe fn drop_window_state(object: &Object) {
1614 unsafe {
1615 let raw: *mut c_void = *object.get_ivar(WINDOW_STATE_IVAR);
1616 Arc::from_raw(raw as *mut Mutex<MacWindowState>);
1617 }
1618}
1619
1620extern "C" fn yes(_: &Object, _: Sel) -> BOOL {
1621 YES
1622}
1623
1624extern "C" fn dealloc_window(this: &Object, _: Sel) {
1625 unsafe {
1626 drop_window_state(this);
1627 let _: () = msg_send![super(this, class!(NSWindow)), dealloc];
1628 }
1629}
1630
1631extern "C" fn dealloc_view(this: &Object, _: Sel) {
1632 unsafe {
1633 drop_window_state(this);
1634 let _: () = msg_send![super(this, class!(NSView)), dealloc];
1635 }
1636}
1637
1638extern "C" fn handle_key_equivalent(this: &Object, _: Sel, native_event: id) -> BOOL {
1639 handle_key_event(this, native_event, true)
1640}
1641
1642extern "C" fn handle_key_down(this: &Object, _: Sel, native_event: id) {
1643 handle_key_event(this, native_event, false);
1644}
1645
1646extern "C" fn handle_key_up(this: &Object, _: Sel, native_event: id) {
1647 handle_key_event(this, native_event, false);
1648}
1649
1650// Things to test if you're modifying this method:
1651// U.S. layout:
1652// - The IME consumes characters like 'j' and 'k', which makes paging through `less` in
1653// the terminal behave incorrectly by default. This behavior should be patched by our
1654// IME integration
1655// - `alt-t` should open the tasks menu
1656// - In vim mode, this keybinding should work:
1657// ```
1658// {
1659// "context": "Editor && vim_mode == insert",
1660// "bindings": {"j j": "vim::NormalBefore"}
1661// }
1662// ```
1663// and typing 'j k' in insert mode with this keybinding should insert the two characters
1664// Brazilian layout:
1665// - `" space` should create an unmarked quote
1666// - `" backspace` should delete the marked quote
1667// - `" "`should create an unmarked quote and a second marked quote
1668// - `" up` should insert a quote, unmark it, and move up one line
1669// - `" cmd-down` should insert a quote, unmark it, and move to the end of the file
1670// - `cmd-ctrl-space` and clicking on an emoji should type it
1671// Czech (QWERTY) layout:
1672// - in vim mode `option-4` should go to end of line (same as $)
1673// Japanese (Romaji) layout:
1674// - type `a i left down up enter enter` should create an unmarked text "愛"
1675extern "C" fn handle_key_event(this: &Object, native_event: id, key_equivalent: bool) -> BOOL {
1676 let window_state = unsafe { get_window_state(this) };
1677 let mut lock = window_state.as_ref().lock();
1678
1679 let window_height = lock.content_size().height;
1680 let event = unsafe { PlatformInput::from_native(native_event, Some(window_height)) };
1681
1682 let Some(event) = event else {
1683 return NO;
1684 };
1685
1686 let run_callback = |event: PlatformInput| -> BOOL {
1687 let mut callback = window_state.as_ref().lock().event_callback.take();
1688 let handled: BOOL = if let Some(callback) = callback.as_mut() {
1689 !callback(event).propagate as BOOL
1690 } else {
1691 NO
1692 };
1693 window_state.as_ref().lock().event_callback = callback;
1694 handled
1695 };
1696
1697 match event {
1698 PlatformInput::KeyDown(mut key_down_event) => {
1699 // For certain keystrokes, macOS will first dispatch a "key equivalent" event.
1700 // If that event isn't handled, it will then dispatch a "key down" event. GPUI
1701 // makes no distinction between these two types of events, so we need to ignore
1702 // the "key down" event if we've already just processed its "key equivalent" version.
1703 if key_equivalent {
1704 lock.last_key_equivalent = Some(key_down_event.clone());
1705 } else if lock.last_key_equivalent.take().as_ref() == Some(&key_down_event) {
1706 return NO;
1707 }
1708
1709 drop(lock);
1710
1711 let is_composing =
1712 with_input_handler(this, |input_handler| input_handler.marked_text_range())
1713 .flatten()
1714 .is_some();
1715
1716 // If we're composing, send the key to the input handler first;
1717 // otherwise we only send to the input handler if we don't have a matching binding.
1718 // The input handler may call `do_command_by_selector` if it doesn't know how to handle
1719 // a key. If it does so, it will return YES so we won't send the key twice.
1720 // We also do this for non-printing keys (like arrow keys and escape) as the IME menu
1721 // may need them even if there is no marked text;
1722 // however we skip keys with control or the input handler adds control-characters to the buffer.
1723 // and keys with function, as the input handler swallows them.
1724 if is_composing
1725 || (key_down_event.keystroke.key_char.is_none()
1726 && !key_down_event.keystroke.modifiers.control
1727 && !key_down_event.keystroke.modifiers.function)
1728 {
1729 {
1730 let mut lock = window_state.as_ref().lock();
1731 lock.keystroke_for_do_command = Some(key_down_event.keystroke.clone());
1732 lock.do_command_handled.take();
1733 drop(lock);
1734 }
1735
1736 let handled: BOOL = unsafe {
1737 let input_context: id = msg_send![this, inputContext];
1738 msg_send![input_context, handleEvent: native_event]
1739 };
1740 window_state.as_ref().lock().keystroke_for_do_command.take();
1741 if let Some(handled) = window_state.as_ref().lock().do_command_handled.take() {
1742 return handled as BOOL;
1743 } else if handled == YES {
1744 return YES;
1745 }
1746
1747 let handled = run_callback(PlatformInput::KeyDown(key_down_event));
1748 return handled;
1749 }
1750
1751 let handled = run_callback(PlatformInput::KeyDown(key_down_event.clone()));
1752 if handled == YES {
1753 return YES;
1754 }
1755
1756 if key_down_event.is_held
1757 && let Some(key_char) = key_down_event.keystroke.key_char.as_ref()
1758 {
1759 let handled = with_input_handler(this, |input_handler| {
1760 if !input_handler.apple_press_and_hold_enabled() {
1761 input_handler.replace_text_in_range(None, key_char);
1762 return YES;
1763 }
1764 NO
1765 });
1766 if handled == Some(YES) {
1767 return YES;
1768 }
1769 }
1770
1771 // Don't send key equivalents to the input handler if there are key modifiers other
1772 // than Function key, or macOS shortcuts like cmd-` will stop working.
1773 if key_equivalent && key_down_event.keystroke.modifiers != Modifiers::function() {
1774 return NO;
1775 }
1776
1777 unsafe {
1778 let input_context: id = msg_send![this, inputContext];
1779 msg_send![input_context, handleEvent: native_event]
1780 }
1781 }
1782
1783 PlatformInput::KeyUp(_) => {
1784 drop(lock);
1785 run_callback(event)
1786 }
1787
1788 _ => NO,
1789 }
1790}
1791
1792extern "C" fn handle_view_event(this: &Object, _: Sel, native_event: id) {
1793 let window_state = unsafe { get_window_state(this) };
1794 let weak_window_state = Arc::downgrade(&window_state);
1795 let mut lock = window_state.as_ref().lock();
1796 let window_height = lock.content_size().height;
1797 let event = unsafe { PlatformInput::from_native(native_event, Some(window_height)) };
1798
1799 if let Some(mut event) = event {
1800 match &mut event {
1801 PlatformInput::MouseDown(
1802 event @ MouseDownEvent {
1803 button: MouseButton::Left,
1804 modifiers: Modifiers { control: true, .. },
1805 ..
1806 },
1807 ) => {
1808 // On mac, a ctrl-left click should be handled as a right click.
1809 *event = MouseDownEvent {
1810 button: MouseButton::Right,
1811 modifiers: Modifiers {
1812 control: false,
1813 ..event.modifiers
1814 },
1815 click_count: 1,
1816 ..*event
1817 };
1818 }
1819
1820 // Handles focusing click.
1821 PlatformInput::MouseDown(
1822 event @ MouseDownEvent {
1823 button: MouseButton::Left,
1824 ..
1825 },
1826 ) if (lock.first_mouse) => {
1827 *event = MouseDownEvent {
1828 first_mouse: true,
1829 ..*event
1830 };
1831 lock.first_mouse = false;
1832 }
1833
1834 // Because we map a ctrl-left_down to a right_down -> right_up let's ignore
1835 // the ctrl-left_up to avoid having a mismatch in button down/up events if the
1836 // user is still holding ctrl when releasing the left mouse button
1837 PlatformInput::MouseUp(
1838 event @ MouseUpEvent {
1839 button: MouseButton::Left,
1840 modifiers: Modifiers { control: true, .. },
1841 ..
1842 },
1843 ) => {
1844 *event = MouseUpEvent {
1845 button: MouseButton::Right,
1846 modifiers: Modifiers {
1847 control: false,
1848 ..event.modifiers
1849 },
1850 click_count: 1,
1851 ..*event
1852 };
1853 }
1854
1855 _ => {}
1856 };
1857
1858 match &event {
1859 PlatformInput::MouseDown(_) => {
1860 drop(lock);
1861 unsafe {
1862 let input_context: id = msg_send![this, inputContext];
1863 msg_send![input_context, handleEvent: native_event]
1864 }
1865 lock = window_state.as_ref().lock();
1866 }
1867 PlatformInput::MouseMove(
1868 event @ MouseMoveEvent {
1869 pressed_button: Some(_),
1870 ..
1871 },
1872 ) => {
1873 // Synthetic drag is used for selecting long buffer contents while buffer is being scrolled.
1874 // External file drag and drop is able to emit its own synthetic mouse events which will conflict
1875 // with these ones.
1876 if !lock.external_files_dragged {
1877 lock.synthetic_drag_counter += 1;
1878 let executor = lock.executor.clone();
1879 executor
1880 .spawn(synthetic_drag(
1881 weak_window_state,
1882 lock.synthetic_drag_counter,
1883 event.clone(),
1884 ))
1885 .detach();
1886 }
1887 }
1888
1889 PlatformInput::MouseUp(MouseUpEvent { .. }) => {
1890 lock.synthetic_drag_counter += 1;
1891 }
1892
1893 PlatformInput::ModifiersChanged(ModifiersChangedEvent {
1894 modifiers,
1895 capslock,
1896 }) => {
1897 // Only raise modifiers changed event when they have actually changed
1898 if let Some(PlatformInput::ModifiersChanged(ModifiersChangedEvent {
1899 modifiers: prev_modifiers,
1900 capslock: prev_capslock,
1901 })) = &lock.previous_modifiers_changed_event
1902 && prev_modifiers == modifiers
1903 && prev_capslock == capslock
1904 {
1905 return;
1906 }
1907
1908 lock.previous_modifiers_changed_event = Some(event.clone());
1909 }
1910
1911 _ => {}
1912 }
1913
1914 if let Some(mut callback) = lock.event_callback.take() {
1915 drop(lock);
1916 callback(event);
1917 window_state.lock().event_callback = Some(callback);
1918 }
1919 }
1920}
1921
1922extern "C" fn window_did_change_occlusion_state(this: &Object, _: Sel, _: id) {
1923 let window_state = unsafe { get_window_state(this) };
1924 let lock = &mut *window_state.lock();
1925 unsafe {
1926 if lock
1927 .native_window
1928 .occlusionState()
1929 .contains(NSWindowOcclusionState::NSWindowOcclusionStateVisible)
1930 {
1931 lock.move_traffic_light();
1932 lock.start_display_link();
1933 } else {
1934 lock.stop_display_link();
1935 }
1936 }
1937}
1938
1939extern "C" fn window_did_resize(this: &Object, _: Sel, _: id) {
1940 let window_state = unsafe { get_window_state(this) };
1941 window_state.as_ref().lock().move_traffic_light();
1942}
1943
1944extern "C" fn window_will_enter_fullscreen(this: &Object, _: Sel, _: id) {
1945 let window_state = unsafe { get_window_state(this) };
1946 let mut lock = window_state.as_ref().lock();
1947 lock.fullscreen_restore_bounds = lock.bounds();
1948
1949 let min_version = NSOperatingSystemVersion::new(15, 3, 0);
1950
1951 if is_macos_version_at_least(min_version) {
1952 unsafe {
1953 lock.native_window.setTitlebarAppearsTransparent_(NO);
1954 }
1955 }
1956}
1957
1958extern "C" fn window_will_exit_fullscreen(this: &Object, _: Sel, _: id) {
1959 let window_state = unsafe { get_window_state(this) };
1960 let mut lock = window_state.as_ref().lock();
1961
1962 let min_version = NSOperatingSystemVersion::new(15, 3, 0);
1963
1964 if is_macos_version_at_least(min_version) && lock.transparent_titlebar {
1965 unsafe {
1966 lock.native_window.setTitlebarAppearsTransparent_(YES);
1967 }
1968 }
1969}
1970
1971pub(crate) fn is_macos_version_at_least(version: NSOperatingSystemVersion) -> bool {
1972 unsafe { NSProcessInfo::processInfo(nil).isOperatingSystemAtLeastVersion(version) }
1973}
1974
1975extern "C" fn window_did_move(this: &Object, _: Sel, _: id) {
1976 let window_state = unsafe { get_window_state(this) };
1977 let mut lock = window_state.as_ref().lock();
1978 if let Some(mut callback) = lock.moved_callback.take() {
1979 drop(lock);
1980 callback();
1981 window_state.lock().moved_callback = Some(callback);
1982 }
1983}
1984
1985// Update the window scale factor and drawable size, and call the resize callback if any.
1986fn update_window_scale_factor(window_state: &Arc<Mutex<MacWindowState>>) {
1987 let mut lock = window_state.as_ref().lock();
1988 let scale_factor = lock.scale_factor();
1989 let size = lock.content_size();
1990 let drawable_size = size.to_device_pixels(scale_factor);
1991 unsafe {
1992 let _: () = msg_send![
1993 lock.renderer.layer(),
1994 setContentsScale: scale_factor as f64
1995 ];
1996 }
1997
1998 lock.renderer.update_drawable_size(drawable_size);
1999
2000 if let Some(mut callback) = lock.resize_callback.take() {
2001 let content_size = lock.content_size();
2002 let scale_factor = lock.scale_factor();
2003 drop(lock);
2004 callback(content_size, scale_factor);
2005 window_state.as_ref().lock().resize_callback = Some(callback);
2006 };
2007}
2008
2009extern "C" fn window_did_change_screen(this: &Object, _: Sel, _: id) {
2010 let window_state = unsafe { get_window_state(this) };
2011 let mut lock = window_state.as_ref().lock();
2012 lock.start_display_link();
2013 drop(lock);
2014 update_window_scale_factor(&window_state);
2015}
2016
2017extern "C" fn window_did_change_key_status(this: &Object, selector: Sel, _: id) {
2018 let window_state = unsafe { get_window_state(this) };
2019 let mut lock = window_state.lock();
2020 let is_active = unsafe { lock.native_window.isKeyWindow() == YES };
2021
2022 // When opening a pop-up while the application isn't active, Cocoa sends a spurious
2023 // `windowDidBecomeKey` message to the previous key window even though that window
2024 // isn't actually key. This causes a bug if the application is later activated while
2025 // the pop-up is still open, making it impossible to activate the previous key window
2026 // even if the pop-up gets closed. The only way to activate it again is to de-activate
2027 // the app and re-activate it, which is a pretty bad UX.
2028 // The following code detects the spurious event and invokes `resignKeyWindow`:
2029 // in theory, we're not supposed to invoke this method manually but it balances out
2030 // the spurious `becomeKeyWindow` event and helps us work around that bug.
2031 if selector == sel!(windowDidBecomeKey:) && !is_active {
2032 unsafe {
2033 let _: () = msg_send![lock.native_window, resignKeyWindow];
2034 return;
2035 }
2036 }
2037
2038 let executor = lock.executor.clone();
2039 drop(lock);
2040
2041 // When a window becomes active, trigger an immediate synchronous frame request to prevent
2042 // tab flicker when switching between windows in native tabs mode.
2043 //
2044 // This is only done on subsequent activations (not the first) to ensure the initial focus
2045 // path is properly established. Without this guard, the focus state would remain unset until
2046 // the first mouse click, causing keybindings to be non-functional.
2047 if selector == sel!(windowDidBecomeKey:) && is_active {
2048 let window_state = unsafe { get_window_state(this) };
2049 let mut lock = window_state.lock();
2050
2051 if lock.activated_least_once {
2052 if let Some(mut callback) = lock.request_frame_callback.take() {
2053 #[cfg(not(feature = "macos-blade"))]
2054 lock.renderer.set_presents_with_transaction(true);
2055 lock.stop_display_link();
2056 drop(lock);
2057 callback(Default::default());
2058
2059 let mut lock = window_state.lock();
2060 lock.request_frame_callback = Some(callback);
2061 #[cfg(not(feature = "macos-blade"))]
2062 lock.renderer.set_presents_with_transaction(false);
2063 lock.start_display_link();
2064 }
2065 } else {
2066 lock.activated_least_once = true;
2067 }
2068 }
2069
2070 executor
2071 .spawn(async move {
2072 let mut lock = window_state.as_ref().lock();
2073 if is_active {
2074 lock.move_traffic_light();
2075 }
2076
2077 if let Some(mut callback) = lock.activate_callback.take() {
2078 drop(lock);
2079 callback(is_active);
2080 window_state.lock().activate_callback = Some(callback);
2081 };
2082 })
2083 .detach();
2084}
2085
2086extern "C" fn window_should_close(this: &Object, _: Sel, _: id) -> BOOL {
2087 let window_state = unsafe { get_window_state(this) };
2088 let mut lock = window_state.as_ref().lock();
2089 if let Some(mut callback) = lock.should_close_callback.take() {
2090 drop(lock);
2091 let should_close = callback();
2092 window_state.lock().should_close_callback = Some(callback);
2093 should_close as BOOL
2094 } else {
2095 YES
2096 }
2097}
2098
2099extern "C" fn close_window(this: &Object, _: Sel) {
2100 unsafe {
2101 let close_callback = {
2102 let window_state = get_window_state(this);
2103 let mut lock = window_state.as_ref().lock();
2104 lock.close_callback.take()
2105 };
2106
2107 if let Some(callback) = close_callback {
2108 callback();
2109 }
2110
2111 let _: () = msg_send![super(this, class!(NSWindow)), close];
2112 }
2113}
2114
2115extern "C" fn make_backing_layer(this: &Object, _: Sel) -> id {
2116 let window_state = unsafe { get_window_state(this) };
2117 let window_state = window_state.as_ref().lock();
2118 window_state.renderer.layer_ptr() as id
2119}
2120
2121extern "C" fn view_did_change_backing_properties(this: &Object, _: Sel) {
2122 let window_state = unsafe { get_window_state(this) };
2123 update_window_scale_factor(&window_state);
2124}
2125
2126extern "C" fn set_frame_size(this: &Object, _: Sel, size: NSSize) {
2127 let window_state = unsafe { get_window_state(this) };
2128 let mut lock = window_state.as_ref().lock();
2129
2130 let new_size = Size::<Pixels>::from(size);
2131 let old_size = unsafe {
2132 let old_frame: NSRect = msg_send![this, frame];
2133 Size::<Pixels>::from(old_frame.size)
2134 };
2135
2136 if old_size == new_size {
2137 return;
2138 }
2139
2140 unsafe {
2141 let _: () = msg_send![super(this, class!(NSView)), setFrameSize: size];
2142 }
2143
2144 let scale_factor = lock.scale_factor();
2145 let drawable_size = new_size.to_device_pixels(scale_factor);
2146 lock.renderer.update_drawable_size(drawable_size);
2147
2148 if let Some(mut callback) = lock.resize_callback.take() {
2149 let content_size = lock.content_size();
2150 let scale_factor = lock.scale_factor();
2151 drop(lock);
2152 callback(content_size, scale_factor);
2153 window_state.lock().resize_callback = Some(callback);
2154 };
2155}
2156
2157extern "C" fn display_layer(this: &Object, _: Sel, _: id) {
2158 let window_state = unsafe { get_window_state(this) };
2159 let mut lock = window_state.lock();
2160 if let Some(mut callback) = lock.request_frame_callback.take() {
2161 #[cfg(not(feature = "macos-blade"))]
2162 lock.renderer.set_presents_with_transaction(true);
2163 lock.stop_display_link();
2164 drop(lock);
2165 callback(Default::default());
2166
2167 let mut lock = window_state.lock();
2168 lock.request_frame_callback = Some(callback);
2169 #[cfg(not(feature = "macos-blade"))]
2170 lock.renderer.set_presents_with_transaction(false);
2171 lock.start_display_link();
2172 }
2173}
2174
2175unsafe extern "C" fn step(view: *mut c_void) {
2176 let view = view as id;
2177 let window_state = unsafe { get_window_state(&*view) };
2178 let mut lock = window_state.lock();
2179
2180 if let Some(mut callback) = lock.request_frame_callback.take() {
2181 drop(lock);
2182 callback(Default::default());
2183 window_state.lock().request_frame_callback = Some(callback);
2184 }
2185}
2186
2187extern "C" fn valid_attributes_for_marked_text(_: &Object, _: Sel) -> id {
2188 unsafe { msg_send![class!(NSArray), array] }
2189}
2190
2191extern "C" fn has_marked_text(this: &Object, _: Sel) -> BOOL {
2192 let has_marked_text_result =
2193 with_input_handler(this, |input_handler| input_handler.marked_text_range()).flatten();
2194
2195 has_marked_text_result.is_some() as BOOL
2196}
2197
2198extern "C" fn marked_range(this: &Object, _: Sel) -> NSRange {
2199 let marked_range_result =
2200 with_input_handler(this, |input_handler| input_handler.marked_text_range()).flatten();
2201
2202 marked_range_result.map_or(NSRange::invalid(), |range| range.into())
2203}
2204
2205extern "C" fn selected_range(this: &Object, _: Sel) -> NSRange {
2206 let selected_range_result = with_input_handler(this, |input_handler| {
2207 input_handler.selected_text_range(false)
2208 })
2209 .flatten();
2210
2211 selected_range_result.map_or(NSRange::invalid(), |selection| selection.range.into())
2212}
2213
2214extern "C" fn first_rect_for_character_range(
2215 this: &Object,
2216 _: Sel,
2217 range: NSRange,
2218 _: id,
2219) -> NSRect {
2220 let frame = get_frame(this);
2221 with_input_handler(this, |input_handler| {
2222 input_handler.bounds_for_range(range.to_range()?)
2223 })
2224 .flatten()
2225 .map_or(
2226 NSRect::new(NSPoint::new(0., 0.), NSSize::new(0., 0.)),
2227 |bounds| {
2228 NSRect::new(
2229 NSPoint::new(
2230 frame.origin.x + bounds.origin.x.0 as f64,
2231 frame.origin.y + frame.size.height
2232 - bounds.origin.y.0 as f64
2233 - bounds.size.height.0 as f64,
2234 ),
2235 NSSize::new(bounds.size.width.0 as f64, bounds.size.height.0 as f64),
2236 )
2237 },
2238 )
2239}
2240
2241fn get_frame(this: &Object) -> NSRect {
2242 unsafe {
2243 let state = get_window_state(this);
2244 let lock = state.lock();
2245 let mut frame = NSWindow::frame(lock.native_window);
2246 let content_layout_rect: CGRect = msg_send![lock.native_window, contentLayoutRect];
2247 let style_mask: NSWindowStyleMask = msg_send![lock.native_window, styleMask];
2248 if !style_mask.contains(NSWindowStyleMask::NSFullSizeContentViewWindowMask) {
2249 frame.origin.y -= frame.size.height - content_layout_rect.size.height;
2250 }
2251 frame
2252 }
2253}
2254
2255extern "C" fn insert_text(this: &Object, _: Sel, text: id, replacement_range: NSRange) {
2256 unsafe {
2257 let is_attributed_string: BOOL =
2258 msg_send![text, isKindOfClass: [class!(NSAttributedString)]];
2259 let text: id = if is_attributed_string == YES {
2260 msg_send![text, string]
2261 } else {
2262 text
2263 };
2264
2265 let text = text.to_str();
2266 let replacement_range = replacement_range.to_range();
2267 with_input_handler(this, |input_handler| {
2268 input_handler.replace_text_in_range(replacement_range, text)
2269 });
2270 }
2271}
2272
2273extern "C" fn set_marked_text(
2274 this: &Object,
2275 _: Sel,
2276 text: id,
2277 selected_range: NSRange,
2278 replacement_range: NSRange,
2279) {
2280 unsafe {
2281 let is_attributed_string: BOOL =
2282 msg_send![text, isKindOfClass: [class!(NSAttributedString)]];
2283 let text: id = if is_attributed_string == YES {
2284 msg_send![text, string]
2285 } else {
2286 text
2287 };
2288 let selected_range = selected_range.to_range();
2289 let replacement_range = replacement_range.to_range();
2290 let text = text.to_str();
2291 with_input_handler(this, |input_handler| {
2292 input_handler.replace_and_mark_text_in_range(replacement_range, text, selected_range)
2293 });
2294 }
2295}
2296extern "C" fn unmark_text(this: &Object, _: Sel) {
2297 with_input_handler(this, |input_handler| input_handler.unmark_text());
2298}
2299
2300extern "C" fn attributed_substring_for_proposed_range(
2301 this: &Object,
2302 _: Sel,
2303 range: NSRange,
2304 actual_range: *mut c_void,
2305) -> id {
2306 with_input_handler(this, |input_handler| {
2307 let range = range.to_range()?;
2308 if range.is_empty() {
2309 return None;
2310 }
2311 let mut adjusted: Option<Range<usize>> = None;
2312
2313 let selected_text = input_handler.text_for_range(range.clone(), &mut adjusted)?;
2314 if let Some(adjusted) = adjusted
2315 && adjusted != range
2316 {
2317 unsafe { (actual_range as *mut NSRange).write(NSRange::from(adjusted)) };
2318 }
2319 unsafe {
2320 let string: id = msg_send![class!(NSAttributedString), alloc];
2321 let string: id = msg_send![string, initWithString: ns_string(&selected_text)];
2322 Some(string)
2323 }
2324 })
2325 .flatten()
2326 .unwrap_or(nil)
2327}
2328
2329// We ignore which selector it asks us to do because the user may have
2330// bound the shortcut to something else.
2331extern "C" fn do_command_by_selector(this: &Object, _: Sel, _: Sel) {
2332 let state = unsafe { get_window_state(this) };
2333 let mut lock = state.as_ref().lock();
2334 let keystroke = lock.keystroke_for_do_command.take();
2335 let mut event_callback = lock.event_callback.take();
2336 drop(lock);
2337
2338 if let Some((keystroke, mut callback)) = keystroke.zip(event_callback.as_mut()) {
2339 let handled = (callback)(PlatformInput::KeyDown(KeyDownEvent {
2340 keystroke,
2341 is_held: false,
2342 prefer_character_input: false,
2343 }));
2344 state.as_ref().lock().do_command_handled = Some(!handled.propagate);
2345 }
2346
2347 state.as_ref().lock().event_callback = event_callback;
2348}
2349
2350extern "C" fn view_did_change_effective_appearance(this: &Object, _: Sel) {
2351 unsafe {
2352 let state = get_window_state(this);
2353 let mut lock = state.as_ref().lock();
2354 if let Some(mut callback) = lock.appearance_changed_callback.take() {
2355 drop(lock);
2356 callback();
2357 state.lock().appearance_changed_callback = Some(callback);
2358 }
2359 }
2360}
2361
2362extern "C" fn accepts_first_mouse(this: &Object, _: Sel, _: id) -> BOOL {
2363 let window_state = unsafe { get_window_state(this) };
2364 let mut lock = window_state.as_ref().lock();
2365 lock.first_mouse = true;
2366 YES
2367}
2368
2369extern "C" fn character_index_for_point(this: &Object, _: Sel, position: NSPoint) -> u64 {
2370 let position = screen_point_to_gpui_point(this, position);
2371 with_input_handler(this, |input_handler| {
2372 input_handler.character_index_for_point(position)
2373 })
2374 .flatten()
2375 .map(|index| index as u64)
2376 .unwrap_or(NSNotFound as u64)
2377}
2378
2379fn screen_point_to_gpui_point(this: &Object, position: NSPoint) -> Point<Pixels> {
2380 let frame = get_frame(this);
2381 let window_x = position.x - frame.origin.x;
2382 let window_y = frame.size.height - (position.y - frame.origin.y);
2383
2384 point(px(window_x as f32), px(window_y as f32))
2385}
2386
2387extern "C" fn dragging_entered(this: &Object, _: Sel, dragging_info: id) -> NSDragOperation {
2388 let window_state = unsafe { get_window_state(this) };
2389 let position = drag_event_position(&window_state, dragging_info);
2390 let paths = external_paths_from_event(dragging_info);
2391 if let Some(event) =
2392 paths.map(|paths| PlatformInput::FileDrop(FileDropEvent::Entered { position, paths }))
2393 && send_new_event(&window_state, event)
2394 {
2395 window_state.lock().external_files_dragged = true;
2396 return NSDragOperationCopy;
2397 }
2398 NSDragOperationNone
2399}
2400
2401extern "C" fn dragging_updated(this: &Object, _: Sel, dragging_info: id) -> NSDragOperation {
2402 let window_state = unsafe { get_window_state(this) };
2403 let position = drag_event_position(&window_state, dragging_info);
2404 if send_new_event(
2405 &window_state,
2406 PlatformInput::FileDrop(FileDropEvent::Pending { position }),
2407 ) {
2408 NSDragOperationCopy
2409 } else {
2410 NSDragOperationNone
2411 }
2412}
2413
2414extern "C" fn dragging_exited(this: &Object, _: Sel, _: id) {
2415 let window_state = unsafe { get_window_state(this) };
2416 send_new_event(
2417 &window_state,
2418 PlatformInput::FileDrop(FileDropEvent::Exited),
2419 );
2420 window_state.lock().external_files_dragged = false;
2421}
2422
2423extern "C" fn perform_drag_operation(this: &Object, _: Sel, dragging_info: id) -> BOOL {
2424 let window_state = unsafe { get_window_state(this) };
2425 let position = drag_event_position(&window_state, dragging_info);
2426 send_new_event(
2427 &window_state,
2428 PlatformInput::FileDrop(FileDropEvent::Submit { position }),
2429 )
2430 .to_objc()
2431}
2432
2433fn external_paths_from_event(dragging_info: *mut Object) -> Option<ExternalPaths> {
2434 let mut paths = SmallVec::new();
2435 let pasteboard: id = unsafe { msg_send![dragging_info, draggingPasteboard] };
2436 let filenames = unsafe { NSPasteboard::propertyListForType(pasteboard, NSFilenamesPboardType) };
2437 if filenames == nil {
2438 return None;
2439 }
2440 for file in unsafe { filenames.iter() } {
2441 let path = unsafe {
2442 let f = NSString::UTF8String(file);
2443 CStr::from_ptr(f).to_string_lossy().into_owned()
2444 };
2445 paths.push(PathBuf::from(path))
2446 }
2447 Some(ExternalPaths(paths))
2448}
2449
2450extern "C" fn conclude_drag_operation(this: &Object, _: Sel, _: id) {
2451 let window_state = unsafe { get_window_state(this) };
2452 send_new_event(
2453 &window_state,
2454 PlatformInput::FileDrop(FileDropEvent::Exited),
2455 );
2456}
2457
2458async fn synthetic_drag(
2459 window_state: Weak<Mutex<MacWindowState>>,
2460 drag_id: usize,
2461 event: MouseMoveEvent,
2462) {
2463 loop {
2464 Timer::after(Duration::from_millis(16)).await;
2465 if let Some(window_state) = window_state.upgrade() {
2466 let mut lock = window_state.lock();
2467 if lock.synthetic_drag_counter == drag_id {
2468 if let Some(mut callback) = lock.event_callback.take() {
2469 drop(lock);
2470 callback(PlatformInput::MouseMove(event.clone()));
2471 window_state.lock().event_callback = Some(callback);
2472 }
2473 } else {
2474 break;
2475 }
2476 }
2477 }
2478}
2479
2480fn send_new_event(window_state_lock: &Mutex<MacWindowState>, e: PlatformInput) -> bool {
2481 let window_state = window_state_lock.lock().event_callback.take();
2482 if let Some(mut callback) = window_state {
2483 callback(e);
2484 window_state_lock.lock().event_callback = Some(callback);
2485 true
2486 } else {
2487 false
2488 }
2489}
2490
2491fn drag_event_position(window_state: &Mutex<MacWindowState>, dragging_info: id) -> Point<Pixels> {
2492 let drag_location: NSPoint = unsafe { msg_send![dragging_info, draggingLocation] };
2493 convert_mouse_position(drag_location, window_state.lock().content_size().height)
2494}
2495
2496fn with_input_handler<F, R>(window: &Object, f: F) -> Option<R>
2497where
2498 F: FnOnce(&mut PlatformInputHandler) -> R,
2499{
2500 let window_state = unsafe { get_window_state(window) };
2501 let mut lock = window_state.as_ref().lock();
2502 if let Some(mut input_handler) = lock.input_handler.take() {
2503 drop(lock);
2504 let result = f(&mut input_handler);
2505 window_state.lock().input_handler = Some(input_handler);
2506 Some(result)
2507 } else {
2508 None
2509 }
2510}
2511
2512unsafe fn display_id_for_screen(screen: id) -> CGDirectDisplayID {
2513 unsafe {
2514 let device_description = NSScreen::deviceDescription(screen);
2515 let screen_number_key: id = NSString::alloc(nil).init_str("NSScreenNumber");
2516 let screen_number = device_description.objectForKey_(screen_number_key);
2517 let screen_number: NSUInteger = msg_send![screen_number, unsignedIntegerValue];
2518 screen_number as CGDirectDisplayID
2519 }
2520}
2521
2522extern "C" fn blurred_view_init_with_frame(this: &Object, _: Sel, frame: NSRect) -> id {
2523 unsafe {
2524 let view = msg_send![super(this, class!(NSVisualEffectView)), initWithFrame: frame];
2525 // Use a colorless semantic material. The default value `AppearanceBased`, though not
2526 // manually set, is deprecated.
2527 NSVisualEffectView::setMaterial_(view, NSVisualEffectMaterial::Selection);
2528 NSVisualEffectView::setState_(view, NSVisualEffectState::Active);
2529 view
2530 }
2531}
2532
2533extern "C" fn blurred_view_update_layer(this: &Object, _: Sel) {
2534 unsafe {
2535 let _: () = msg_send![super(this, class!(NSVisualEffectView)), updateLayer];
2536 let layer: id = msg_send![this, layer];
2537 if !layer.is_null() {
2538 remove_layer_background(layer);
2539 }
2540 }
2541}
2542
2543unsafe fn remove_layer_background(layer: id) {
2544 unsafe {
2545 let _: () = msg_send![layer, setBackgroundColor:nil];
2546
2547 let class_name: id = msg_send![layer, className];
2548 if class_name.isEqualToString("CAChameleonLayer") {
2549 // Remove the desktop tinting effect.
2550 let _: () = msg_send![layer, setHidden: YES];
2551 return;
2552 }
2553
2554 let filters: id = msg_send![layer, filters];
2555 if !filters.is_null() {
2556 // Remove the increased saturation.
2557 // The effect of a `CAFilter` or `CIFilter` is determined by its name, and the
2558 // `description` reflects its name and some parameters. Currently `NSVisualEffectView`
2559 // uses a `CAFilter` named "colorSaturate". If one day they switch to `CIFilter`, the
2560 // `description` will still contain "Saturat" ("... inputSaturation = ...").
2561 let test_string: id = NSString::alloc(nil).init_str("Saturat").autorelease();
2562 let count = NSArray::count(filters);
2563 for i in 0..count {
2564 let description: id = msg_send![filters.objectAtIndex(i), description];
2565 let hit: BOOL = msg_send![description, containsString: test_string];
2566 if hit == NO {
2567 continue;
2568 }
2569
2570 let all_indices = NSRange {
2571 location: 0,
2572 length: count,
2573 };
2574 let indices: id = msg_send![class!(NSMutableIndexSet), indexSet];
2575 let _: () = msg_send![indices, addIndexesInRange: all_indices];
2576 let _: () = msg_send![indices, removeIndex:i];
2577 let filtered: id = msg_send![filters, objectsAtIndexes: indices];
2578 let _: () = msg_send![layer, setFilters: filtered];
2579 break;
2580 }
2581 }
2582
2583 let sublayers: id = msg_send![layer, sublayers];
2584 if !sublayers.is_null() {
2585 let count = NSArray::count(sublayers);
2586 for i in 0..count {
2587 let sublayer = sublayers.objectAtIndex(i);
2588 remove_layer_background(sublayer);
2589 }
2590 }
2591 }
2592}
2593
2594extern "C" fn add_titlebar_accessory_view_controller(this: &Object, _: Sel, view_controller: id) {
2595 unsafe {
2596 let _: () = msg_send![super(this, class!(NSWindow)), addTitlebarAccessoryViewController: view_controller];
2597
2598 // Hide the native tab bar and set its height to 0, since we render our own.
2599 let accessory_view: id = msg_send![view_controller, view];
2600 let _: () = msg_send![accessory_view, setHidden: YES];
2601 let mut frame: NSRect = msg_send![accessory_view, frame];
2602 frame.size.height = 0.0;
2603 let _: () = msg_send![accessory_view, setFrame: frame];
2604 }
2605}
2606
2607extern "C" fn move_tab_to_new_window(this: &Object, _: Sel, _: id) {
2608 unsafe {
2609 let _: () = msg_send![super(this, class!(NSWindow)), moveTabToNewWindow:nil];
2610
2611 let window_state = get_window_state(this);
2612 let mut lock = window_state.as_ref().lock();
2613 if let Some(mut callback) = lock.move_tab_to_new_window_callback.take() {
2614 drop(lock);
2615 callback();
2616 window_state.lock().move_tab_to_new_window_callback = Some(callback);
2617 }
2618 }
2619}
2620
2621extern "C" fn merge_all_windows(this: &Object, _: Sel, _: id) {
2622 unsafe {
2623 let _: () = msg_send![super(this, class!(NSWindow)), mergeAllWindows:nil];
2624
2625 let window_state = get_window_state(this);
2626 let mut lock = window_state.as_ref().lock();
2627 if let Some(mut callback) = lock.merge_all_windows_callback.take() {
2628 drop(lock);
2629 callback();
2630 window_state.lock().merge_all_windows_callback = Some(callback);
2631 }
2632 }
2633}
2634
2635extern "C" fn select_next_tab(this: &Object, _sel: Sel, _id: id) {
2636 let window_state = unsafe { get_window_state(this) };
2637 let mut lock = window_state.as_ref().lock();
2638 if let Some(mut callback) = lock.select_next_tab_callback.take() {
2639 drop(lock);
2640 callback();
2641 window_state.lock().select_next_tab_callback = Some(callback);
2642 }
2643}
2644
2645extern "C" fn select_previous_tab(this: &Object, _sel: Sel, _id: id) {
2646 let window_state = unsafe { get_window_state(this) };
2647 let mut lock = window_state.as_ref().lock();
2648 if let Some(mut callback) = lock.select_previous_tab_callback.take() {
2649 drop(lock);
2650 callback();
2651 window_state.lock().select_previous_tab_callback = Some(callback);
2652 }
2653}
2654
2655extern "C" fn toggle_tab_bar(this: &Object, _sel: Sel, _id: id) {
2656 unsafe {
2657 let _: () = msg_send![super(this, class!(NSWindow)), toggleTabBar:nil];
2658
2659 let window_state = get_window_state(this);
2660 let mut lock = window_state.as_ref().lock();
2661 lock.move_traffic_light();
2662
2663 if let Some(mut callback) = lock.toggle_tab_bar_callback.take() {
2664 drop(lock);
2665 callback();
2666 window_state.lock().toggle_tab_bar_callback = Some(callback);
2667 }
2668 }
2669}