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