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