1 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* vim: set ts=2 et sw=2 tw=80: */
3 /* This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
7 #include "nsCocoaWindow.h"
9 #include "NativeKeyBindings.h"
10 #include "ScreenHelperCocoa.h"
11 #include "TextInputHandler.h"
12 #include "nsCocoaUtils.h"
13 #include "nsObjCExceptions.h"
15 #include "nsWidgetsCID.h"
16 #include "nsIRollupListener.h"
17 #include "nsChildView.h"
18 #include "nsWindowMap.h"
19 #include "nsAppShell.h"
20 #include "nsIAppShellService.h"
21 #include "nsIBaseWindow.h"
22 #include "nsIInterfaceRequestorUtils.h"
23 #include "nsIAppWindow.h"
24 #include "nsToolkit.h"
25 #include "nsPIDOMWindow.h"
26 #include "nsThreadUtils.h"
27 #include "nsMenuBarX.h"
28 #include "nsMenuUtilsX.h"
29 #include "nsStyleConsts.h"
30 #include "nsNativeThemeColors.h"
31 #include "nsNativeThemeCocoa.h"
32 #include "nsChildView.h"
33 #include "nsCocoaFeatures.h"
34 #include "nsIScreenManager.h"
35 #include "nsIWidgetListener.h"
36 #include "nsXULPopupManager.h"
37 #include "VibrancyManager.h"
38 #include "nsPresContext.h"
39 #include "nsDocShell.h"
41 #include "gfxPlatform.h"
44 #include "mozilla/AutoRestore.h"
45 #include "mozilla/BasicEvents.h"
46 #include "mozilla/dom/Document.h"
47 #include "mozilla/Maybe.h"
48 #include "mozilla/NativeKeyBindingsType.h"
49 #include "mozilla/Preferences.h"
50 #include "mozilla/PresShell.h"
51 #include "mozilla/ScopeExit.h"
52 #include "mozilla/StaticPrefs_gfx.h"
53 #include "mozilla/StaticPrefs_widget.h"
54 #include "mozilla/WritingModes.h"
55 #include "mozilla/layers/CompositorBridgeChild.h"
56 #include "mozilla/widget/Screen.h"
63 } // namespace mozilla
64 using namespace mozilla::layers;
65 using namespace mozilla::widget;
66 using namespace mozilla;
68 BOOL sTouchBarIsInitialized = NO;
70 // defined in nsMenuBarX.mm
71 extern NSMenu* sApplicationMenu; // Application menu shared by all menubars
73 // defined in nsChildView.mm
74 extern BOOL gSomeMenuBarPainted;
76 static uint32_t sModalWindowCount = 0;
80 typedef NSInteger CGSConnection;
81 typedef NSUInteger CGSSpaceID;
82 typedef NSInteger CGSWindow;
84 kCGSSpaceIncludesCurrent = 1 << 0,
85 kCGSSpaceIncludesOthers = 1 << 1,
86 kCGSSpaceIncludesUser = 1 << 2,
89 kCGSSpaceIncludesCurrent | kCGSSpaceIncludesOthers | kCGSSpaceIncludesUser
91 static NSString* const CGSSpaceIDKey = @"ManagedSpaceID";
92 static NSString* const CGSSpacesKey = @"Spaces";
93 extern CGSConnection _CGSDefaultConnection(void);
94 extern CGError CGSSetWindowTransform(CGSConnection cid, CGSWindow wid,
95 CGAffineTransform transform);
98 #define NS_APPSHELLSERVICE_CONTRACTID "@mozilla.org/appshell/appShellService;1"
100 static void RollUpPopups(nsIRollupListener::AllowAnimations aAllowAnimations =
101 nsIRollupListener::AllowAnimations::Yes) {
102 if (RefPtr pm = nsXULPopupManager::GetInstance()) {
103 pm->RollupTooltips();
106 nsIRollupListener* rollupListener = nsBaseWidget::GetActiveRollupListener();
107 if (!rollupListener) {
110 if (rollupListener->RollupNativeMenu()) {
113 nsCOMPtr<nsIWidget> rollupWidget = rollupListener->GetRollupWidget();
117 nsIRollupListener::RollupOptions options{
118 0, nsIRollupListener::FlushViews::Yes, nullptr, aAllowAnimations};
119 rollupListener->Rollup(options);
122 nsCocoaWindow::nsCocoaWindow()
124 mClosedRetainedWindow(nil),
126 mPopupContentView(nil),
127 mFullscreenTransitionAnimation(nil),
128 mShadowStyle(WindowShadow::None),
129 mBackingScaleFactor(0.0),
130 mAnimationType(nsIWidget::eGenericWindowAnimation),
131 mWindowMadeHere(false),
132 mSizeMode(nsSizeMode_Normal),
133 mInFullScreenMode(false),
134 mInNativeFullScreenMode(false),
135 mIgnoreOcclusionCount(0),
136 mHasStartedNativeFullscreen(false),
137 mWindowAnimationBehavior(NSWindowAnimationBehaviorDefault) {
138 // Disable automatic tabbing. We need to do this before we
139 // orderFront any of our windows.
140 NSWindow.allowsAutomaticWindowTabbing = NO;
143 void nsCocoaWindow::DestroyNativeWindow() {
144 NS_OBJC_BEGIN_TRY_IGNORE_BLOCK;
150 MOZ_ASSERT(mWindowMadeHere,
151 "We shouldn't be trying to destroy a window we didn't create.");
153 // Clear our class state that is keyed off of mWindow. It's our last
154 // chance! This ensures that other nsCocoaWindow instances are not waiting
155 // for us to finish a native transition that will have no listener once
156 // we clear our delegate.
157 EndOurNativeTransition();
159 // We are about to destroy mWindow. Before we do that, make sure that we
160 // hide the window using the Show() method, because it has several side
161 // effects that our parent and listeners might be expecting. If we don't
162 // do this now, then these side effects will never execute, though the
163 // window will definitely no longer be shown.
166 [mWindow removeTrackingArea];
168 [mWindow releaseJSObjects];
169 // We want to unhook the delegate here because we don't want events
170 // sent to it after this object has been destroyed.
171 mWindow.delegate = nil;
173 // Closing the window will also release it. Our second reference will
174 // keep it alive through our destructor. Release any reference we might
175 // have from an earlier call to DestroyNativeWindow, then create a new
177 [mClosedRetainedWindow autorelease];
178 mClosedRetainedWindow = [mWindow retain];
179 MOZ_ASSERT(mWindow.releasedWhenClosed);
183 [mDelegate autorelease];
185 NS_OBJC_END_TRY_IGNORE_BLOCK;
188 nsCocoaWindow::~nsCocoaWindow() {
189 NS_OBJC_BEGIN_TRY_IGNORE_BLOCK;
192 if (mWindow && mWindowMadeHere) {
193 CancelAllTransitions();
194 DestroyNativeWindow();
197 [mClosedRetainedWindow release];
199 NS_IF_RELEASE(mPopupContentView);
200 NS_OBJC_END_TRY_IGNORE_BLOCK;
203 // Find the screen that overlaps aRect the most,
204 // if none are found default to the mainScreen.
205 static NSScreen* FindTargetScreenForRect(const DesktopIntRect& aRect) {
206 NSScreen* targetScreen = [NSScreen mainScreen];
207 NSEnumerator* screenEnum = [[NSScreen screens] objectEnumerator];
208 int largestIntersectArea = 0;
209 while (NSScreen* screen = [screenEnum nextObject]) {
210 DesktopIntRect screenRect =
211 nsCocoaUtils::CocoaRectToGeckoRect([screen visibleFrame]);
212 screenRect = screenRect.Intersect(aRect);
213 int area = screenRect.width * screenRect.height;
214 if (area > largestIntersectArea) {
215 largestIntersectArea = area;
216 targetScreen = screen;
222 DesktopToLayoutDeviceScale ParentBackingScaleFactor(nsIWidget* aParent) {
224 return aParent->GetDesktopToDeviceScale();
226 return DesktopToLayoutDeviceScale(1.0);
229 // Returns the screen rectangle for the given widget.
230 // Child widgets are positioned relative to this rectangle.
231 // Exactly one of the arguments must be non-null.
232 static DesktopRect GetWidgetScreenRectForChildren(nsIWidget* aWidget) {
233 mozilla::DesktopToLayoutDeviceScale scale =
234 aWidget->GetDesktopToDeviceScale();
235 if (aWidget->GetWindowType() == WindowType::Child) {
236 return aWidget->GetScreenBounds() / scale;
238 return aWidget->GetClientBounds() / scale;
241 // aRect here is specified in desktop pixels
243 // For child windows aRect.{x,y} are offsets from the origin of the parent
244 // window and not an absolute position.
245 nsresult nsCocoaWindow::Create(nsIWidget* aParent, const DesktopIntRect& aRect,
246 widget::InitData* aInitData) {
247 NS_OBJC_BEGIN_TRY_BLOCK_RETURN;
249 // Because the hidden window is created outside of an event loop,
250 // we have to provide an autorelease pool (see bug 559075).
251 nsAutoreleasePool localPool;
253 // Set defaults which can be overriden from aInitData in BaseCreate
254 mWindowType = WindowType::TopLevel;
255 mBorderStyle = BorderStyle::Default;
257 // Ensure that the toolkit is created.
258 nsToolkit::GetToolkit();
260 Inherited::BaseCreate(aParent, aInitData);
262 mAlwaysOnTop = aInitData->mAlwaysOnTop;
263 mIsAlert = aInitData->mIsAlert;
265 // If we have a parent widget, the new widget will be offset from the
266 // parent widget by aRect.{x,y}. Otherwise, we'll use aRect for the
267 // new widget coordinates.
268 DesktopIntPoint parentOrigin;
270 // Do we have a parent widget?
272 DesktopRect parentDesktopRect = GetWidgetScreenRectForChildren(aParent);
273 parentOrigin = gfx::RoundedToInt(parentDesktopRect.TopLeft());
276 DesktopIntRect widgetRect = aRect + parentOrigin;
279 CreateNativeWindow(nsCocoaUtils::GeckoRectToCocoaRect(widgetRect),
280 mBorderStyle, false, aInitData->mIsPrivate);
281 NS_ENSURE_SUCCESS(rv, rv);
283 if (mWindowType == WindowType::Popup) {
284 // now we can convert widgetRect to device pixels for the window we created,
285 // as the child view expects a rect expressed in the dev pix of its parent
286 LayoutDeviceIntRect devRect =
287 RoundedToInt(aRect * GetDesktopToDeviceScale());
288 return CreatePopupContentView(devRect, aInitData);
291 mIsAnimationSuppressed = aInitData->mIsAnimationSuppressed;
295 NS_OBJC_END_TRY_BLOCK_RETURN(NS_ERROR_FAILURE);
298 nsresult nsCocoaWindow::Create(nsIWidget* aParent,
299 const LayoutDeviceIntRect& aRect,
300 widget::InitData* aInitData) {
301 DesktopIntRect desktopRect =
302 RoundedToInt(aRect / ParentBackingScaleFactor(aParent));
303 return Create(aParent, desktopRect, aInitData);
306 static unsigned int WindowMaskForBorderStyle(BorderStyle aBorderStyle) {
307 bool allOrDefault = (aBorderStyle == BorderStyle::All ||
308 aBorderStyle == BorderStyle::Default);
310 /* Apple's docs on NSWindow styles say that "a window's style mask should
311 * include NSWindowStyleMaskTitled if it includes any of the others [besides
312 * NSWindowStyleMaskBorderless]". This implies that a borderless window
313 * shouldn't have any other styles than NSWindowStyleMaskBorderless.
315 if (!allOrDefault && !(aBorderStyle & BorderStyle::Title)) {
316 if (aBorderStyle & BorderStyle::Minimize) {
317 /* It appears that at a minimum, borderless windows can be miniaturizable,
318 * effectively contradicting some of Apple's documentation referenced
319 * above. One such exception is the screen share indicator, see
322 return NSWindowStyleMaskBorderless | NSWindowStyleMaskMiniaturizable;
324 return NSWindowStyleMaskBorderless;
327 unsigned int mask = NSWindowStyleMaskTitled;
328 if (allOrDefault || aBorderStyle & BorderStyle::Close) {
329 mask |= NSWindowStyleMaskClosable;
331 if (allOrDefault || aBorderStyle & BorderStyle::Minimize) {
332 mask |= NSWindowStyleMaskMiniaturizable;
334 if (allOrDefault || aBorderStyle & BorderStyle::ResizeH) {
335 mask |= NSWindowStyleMaskResizable;
341 // If aRectIsFrameRect, aRect specifies the frame rect of the new window.
342 // Otherwise, aRect.x/y specify the position of the window's frame relative to
343 // the bottom of the menubar and aRect.width/height specify the size of the
345 nsresult nsCocoaWindow::CreateNativeWindow(const NSRect& aRect,
346 BorderStyle aBorderStyle,
347 bool aRectIsFrameRect,
348 bool aIsPrivateBrowsing) {
349 NS_OBJC_BEGIN_TRY_BLOCK_RETURN;
351 // We default to NSWindowStyleMaskBorderless, add features if needed.
352 unsigned int features = NSWindowStyleMaskBorderless;
354 // Configure the window we will create based on the window type.
355 switch (mWindowType) {
356 case WindowType::Invisible:
357 case WindowType::Child:
359 case WindowType::Popup:
360 if (aBorderStyle != BorderStyle::Default &&
361 mBorderStyle & BorderStyle::Title) {
362 features |= NSWindowStyleMaskTitled;
363 if (aBorderStyle & BorderStyle::Close) {
364 features |= NSWindowStyleMaskClosable;
368 case WindowType::TopLevel:
369 case WindowType::Dialog:
370 features = WindowMaskForBorderStyle(aBorderStyle);
373 NS_ERROR("Unhandled window type!");
374 return NS_ERROR_FAILURE;
379 if (aRectIsFrameRect) {
380 contentRect = [NSWindow contentRectForFrameRect:aRect styleMask:features];
383 * We pass a content area rect to initialize the native Cocoa window. The
384 * content rect we give is the same size as the size we're given by gecko.
385 * The origin we're given for non-popup windows is moved down by the height
386 * of the menu bar so that an origin of (0,100) from gecko puts the window
387 * 100 pixels below the top of the available desktop area. We also move the
388 * origin down by the height of a title bar if it exists. This is so the
389 * origin that gecko gives us for the top-left of the window turns out to
390 * be the top-left of the window we create. This is how it was done in
391 * Carbon. If it ought to be different we'll probably need to look at all
394 * Note: This means that if you put a secondary screen on top of your main
395 * screen and open a window in the top screen, it'll be incorrectly shifted
396 * down by the height of the menu bar. Same thing would happen in Carbon.
398 * Note: If you pass a rect with 0,0 for an origin, the window ends up in a
399 * weird place for some reason. This stops that without breaking popups.
401 // Compensate for difference between frame and content area height (e.g.
403 NSRect newWindowFrame = [NSWindow frameRectForContentRect:aRect
407 contentRect.origin.y -= (newWindowFrame.size.height - aRect.size.height);
409 if (mWindowType != WindowType::Popup) {
410 contentRect.origin.y -= NSApp.mainMenu.menuBarHeight;
414 // NSLog(@"Top-level window being created at Cocoa rect: %f, %f, %f, %f\n",
415 // rect.origin.x, rect.origin.y, rect.size.width, rect.size.height);
417 Class windowClass = [BaseWindow class];
418 if ((mWindowType == WindowType::TopLevel ||
419 mWindowType == WindowType::Dialog) &&
420 (features & NSWindowStyleMaskTitled)) {
421 // If we have a titlebar on a top-level window, we want to be able to
422 // control the titlebar color (for unified windows), so use the special
423 // ToolbarWindow class. Note that we need to check the window type because
424 // we mark sheets as having titlebars.
425 windowClass = [ToolbarWindow class];
426 } else if (mWindowType == WindowType::Popup) {
427 windowClass = [PopupWindow class];
428 // If we're a popup window we need to use the PopupWindow class.
429 } else if (features == NSWindowStyleMaskBorderless) {
430 // If we're a non-popup borderless window we need to use the
431 // BorderlessWindow class.
432 windowClass = [BorderlessWindow class];
436 mWindow = [[windowClass alloc] initWithContentRect:contentRect
438 backing:NSBackingStoreBuffered
441 // Make sure that window titles don't leak to disk in private browsing mode
442 // due to macOS' resume feature.
443 mWindow.restorable = !aIsPrivateBrowsing;
444 if (aIsPrivateBrowsing) {
445 [mWindow disableSnapshotRestoration];
448 // setup our notification delegate. Note that setDelegate: does NOT retain.
449 mDelegate = [[WindowDelegate alloc] initWithGeckoWindow:this];
450 mWindow.delegate = mDelegate;
452 // Make sure that the content rect we gave has been honored.
453 NSRect wantedFrame = [mWindow frameRectForChildViewRect:contentRect];
454 if (!NSEqualRects(mWindow.frame, wantedFrame)) {
455 // This can happen when the window is not on the primary screen.
456 [mWindow setFrame:wantedFrame display:NO];
460 if (mWindowType == WindowType::Invisible) {
461 mWindow.level = kCGDesktopWindowLevelKey;
464 if (mWindowType == WindowType::Popup) {
465 SetPopupWindowLevel();
466 mWindow.backgroundColor = NSColor.clearColor;
469 // When multiple spaces are in use and the browser is assigned to a
470 // particular space, override the "Assign To" space and display popups on
471 // the active space. Does not work with multiple displays. See
472 // NeedsRecreateToReshow() for multi-display with multi-space workaround.
473 mWindow.collectionBehavior = mWindow.collectionBehavior |
474 NSWindowCollectionBehaviorMoveToActiveSpace;
476 // Non-popup windows are always opaque.
477 mWindow.opaque = YES;
480 if (mAlwaysOnTop || mIsAlert) {
481 mWindow.level = NSFloatingWindowLevel;
482 mWindow.collectionBehavior =
483 mWindow.collectionBehavior | NSWindowCollectionBehaviorCanJoinAllSpaces;
485 mWindow.contentMinSize = NSMakeSize(60, 60);
486 [mWindow disableCursorRects];
488 // Make the window use CoreAnimation from the start, so that we don't
489 // switch from a non-CA window to a CA-window in the middle.
490 mWindow.contentView.wantsLayer = YES;
492 [mWindow createTrackingArea];
494 // Make sure the window starts out not draggable by the background.
495 // We will turn it on as necessary.
496 mWindow.movableByWindowBackground = NO;
498 [WindowDataMap.sharedWindowDataMap ensureDataForWindow:mWindow];
499 mWindowMadeHere = true;
503 NS_OBJC_END_TRY_BLOCK_RETURN(NS_ERROR_FAILURE);
506 nsresult nsCocoaWindow::CreatePopupContentView(const LayoutDeviceIntRect& aRect,
507 widget::InitData* aInitData) {
508 NS_OBJC_BEGIN_TRY_BLOCK_RETURN;
510 // We need to make our content view a ChildView.
511 mPopupContentView = new nsChildView();
512 if (!mPopupContentView) return NS_ERROR_FAILURE;
514 NS_ADDREF(mPopupContentView);
516 nsIWidget* thisAsWidget = static_cast<nsIWidget*>(this);
517 nsresult rv = mPopupContentView->Create(thisAsWidget, aRect, aInitData);
518 if (NS_WARN_IF(NS_FAILED(rv))) {
522 NSView* contentView = mWindow.contentView;
523 auto* childView = static_cast<ChildView*>(
524 mPopupContentView->GetNativeData(NS_NATIVE_WIDGET));
525 childView.frame = contentView.bounds;
526 childView.autoresizingMask = NSViewWidthSizable | NSViewHeightSizable;
527 [contentView addSubview:childView];
531 NS_OBJC_END_TRY_BLOCK_RETURN(NS_ERROR_FAILURE);
534 void nsCocoaWindow::Destroy() {
535 if (mOnDestroyCalled) {
538 mOnDestroyCalled = true;
540 // Deal with the possiblity that we're being destroyed while running modal.
545 // If we don't hide here we run into problems with panels, this is not ideal.
549 if (mPopupContentView) {
550 mPopupContentView->Destroy();
553 if (mFullscreenTransitionAnimation) {
554 [mFullscreenTransitionAnimation stopAnimation];
555 ReleaseFullscreenTransitionAnimation();
558 if (mInFullScreenMode && !mInNativeFullScreenMode) {
559 // Keep these calls balanced for emulated fullscreen.
560 nsCocoaUtils::HideOSChromeOnScreen(false);
563 // Destroy the native window here (and not wait for that to happen in our
564 // destructor). Otherwise this might not happen for several seconds because
565 // at least one object holding a reference to ourselves is usually waiting
566 // to be garbage-collected.
567 if (mWindow && mWindowMadeHere) {
568 CancelAllTransitions();
569 DestroyNativeWindow();
572 nsCOMPtr<nsIWidget> kungFuDeathGrip(this);
574 nsBaseWidget::OnDestroy();
575 nsBaseWidget::Destroy();
578 void* nsCocoaWindow::GetNativeData(uint32_t aDataType) {
579 NS_OBJC_BEGIN_TRY_BLOCK_RETURN;
581 void* retVal = nullptr;
584 // to emulate how windows works, we always have to return a NSView
585 // for NS_NATIVE_WIDGET
586 case NS_NATIVE_WIDGET:
587 retVal = mWindow.contentView;
590 case NS_NATIVE_WINDOW:
594 case NS_NATIVE_GRAPHIC:
595 // There isn't anything that makes sense to return here,
596 // and it doesn't matter so just return nullptr.
597 NS_ERROR("Requesting NS_NATIVE_GRAPHIC on a top-level window!");
599 case NS_RAW_NATIVE_IME_CONTEXT: {
600 retVal = GetPseudoIMEContext();
604 NSView* view = mWindow ? mWindow.contentView : nil;
606 retVal = view.inputContext;
608 // If inputContext isn't available on this window, return this window's
609 // pointer instead of nullptr since if this returns nullptr,
610 // IMEStateManager cannot manage composition with TextComposition
611 // instance. Although, this case shouldn't occur.
612 if (NS_WARN_IF(!retVal)) {
621 NS_OBJC_END_TRY_BLOCK_RETURN(nullptr);
624 bool nsCocoaWindow::IsVisible() const {
625 NS_OBJC_BEGIN_TRY_BLOCK_RETURN;
627 return mWindow && mWindow.isVisibleOrBeingShown;
629 NS_OBJC_END_TRY_BLOCK_RETURN(false);
632 void nsCocoaWindow::SetModal(bool aModal) {
633 NS_OBJC_BEGIN_TRY_IGNORE_BLOCK;
635 if (mModal == aModal) {
639 // Unlike many functions here, we explicitly *do not check* for the
640 // existence of mWindow. This is to ensure that calls to SetModal have
641 // no early exits and always update state. That way, if the calls are
642 // balanced, we get expected behavior even if the native window has
643 // been destroyed during the modal period. Within this function, all
644 // the calls to mWindow will resolve even if mWindow is nil (as is
645 // guaranteed by Objective-C). And since those calls are only concerned
646 // with changing mWindow appearance/level, it's fine for them to be
647 // no-ops if mWindow has already been destroyed.
649 // This is used during startup (outside the event loop) when creating
650 // the add-ons compatibility checking dialog and the profile manager UI;
651 // therefore, it needs to provide an autorelease pool to avoid cocoa
653 nsAutoreleasePool localPool;
660 MOZ_ASSERT(sModalWindowCount);
664 // When a window gets "set modal", make the window(s) that it appears over
665 // behave as they should. We can't rely on native methods to do this, for the
666 // following reason: The OS runs modal non-sheet windows in an event loop
667 // (using [NSApplication runModalForWindow:] or similar methods) that's
668 // incompatible with the modal event loop in AppWindow::ShowModal() (each of
669 // these event loops is "exclusive", and can't run at the same time as other
670 // (similar) event loops).
671 for (auto* ancestorWidget = mParent; ancestorWidget;
672 ancestorWidget = ancestorWidget->GetParent()) {
673 if (ancestorWidget->GetWindowType() == WindowType::Child) {
676 auto* ancestor = static_cast<nsCocoaWindow*>(ancestorWidget);
677 const bool changed = aModal ? ancestor->mNumModalDescendants++ == 0
678 : --ancestor->mNumModalDescendants == 0;
679 NS_ASSERTION(ancestor->mNumModalDescendants >= 0,
680 "Widget hierarchy changed while modal!");
681 if (!changed || ancestor->mWindowType == WindowType::Invisible) {
684 NSWindow* win = ancestor->GetCocoaWindow();
685 [[win standardWindowButton:NSWindowCloseButton] setEnabled:!aModal];
686 [[win standardWindowButton:NSWindowMiniaturizeButton] setEnabled:!aModal];
687 [[win standardWindowButton:NSWindowZoomButton] setEnabled:!aModal];
690 mWindow.level = NSModalPanelWindowLevel;
691 } else if (mWindowType == WindowType::Popup) {
692 SetPopupWindowLevel();
694 mWindow.level = NSNormalWindowLevel;
697 NS_OBJC_END_TRY_IGNORE_BLOCK;
700 bool nsCocoaWindow::IsRunningAppModal() { return [NSApp _isRunningAppModal]; }
702 // Hide or show this window
703 void nsCocoaWindow::Show(bool aState) {
704 NS_OBJC_BEGIN_TRY_IGNORE_BLOCK;
710 // Early exit if our current visibility state is already the requested
712 if (aState == mWindow.isVisibleOrBeingShown) {
716 [mWindow setBeingShown:aState];
717 if (aState && !mWasShown) {
721 NSWindow* nativeParentWindow =
722 mParent ? (NSWindow*)mParent->GetNativeData(NS_NATIVE_WINDOW) : nil;
724 if (aState && !mBounds.IsEmpty()) {
725 // If we had set the activationPolicy to accessory, then right now we won't
726 // have a dock icon. Make sure that we undo that and show a dock icon now
727 // that we're going to show a window.
728 if (NSApp.activationPolicy != NSApplicationActivationPolicyRegular) {
729 NSApp.activationPolicy = NSApplicationActivationPolicyRegular;
730 PR_SetEnv("MOZ_APP_NO_DOCK=");
733 // Don't try to show a popup when the parent isn't visible or is minimized.
734 if (mWindowType == WindowType::Popup && nativeParentWindow) {
735 if (!nativeParentWindow.isVisible || nativeParentWindow.isMiniaturized) {
740 if (mPopupContentView) {
741 // Ensure our content view is visible. We never need to hide it.
742 mPopupContentView->Show(true);
745 // We're about to show a window. If we are opening the new window while the
746 // user is in a fullscreen space, for example because the new window is
747 // opened from an existing fullscreen window, then macOS will open the new
748 // window in fullscreen, too. For some windows, this is not desirable. We
749 // want to prevent it for any popup, alert, or alwaysOnTop windows that
750 // aren't already in fullscreen. If the user already got the window into
751 // fullscreen somehow, that's fine, but we don't want the initial display to
753 bool savedValueForSupportsNativeFullscreen = GetSupportsNativeFullscreen();
754 if (!mInFullScreenMode &&
755 ((mWindowType == WindowType::Popup) || mAlwaysOnTop || mIsAlert)) {
756 SetSupportsNativeFullscreen(false);
759 if (mWindowType == WindowType::Popup) {
760 // For reasons that aren't yet clear, calls to [NSWindow orderFront:] or
761 // [NSWindow makeKeyAndOrderFront:] can sometimes trigger "Error (1000)
762 // creating CGSWindow", which in turn triggers an internal inconsistency
763 // NSException. These errors shouldn't be fatal. So we need to wrap
764 // calls to ...orderFront: in TRY blocks. See bmo bug 470864.
765 NS_OBJC_BEGIN_TRY_IGNORE_BLOCK;
766 [[mWindow contentView] setNeedsDisplay:YES];
767 if (!nativeParentWindow || mPopupLevel != PopupLevel::Parent) {
768 [mWindow orderFront:nil];
770 NS_OBJC_END_TRY_IGNORE_BLOCK;
771 // If our popup window is a non-native context menu, tell the OS (and
772 // other programs) that a menu has opened. This is how the OS knows to
773 // close other programs' context menus when ours open.
774 if ([mWindow isKindOfClass:[PopupWindow class]] &&
775 [(PopupWindow*)mWindow isContextMenu]) {
776 [NSDistributedNotificationCenter.defaultCenter
777 postNotificationName:
778 @"com.apple.HIToolbox.beginMenuTrackingNotification"
779 object:@"org.mozilla.gecko.PopupWindow"];
782 // If a parent window was supplied and this is a popup at the parent
783 // level, set its child window. This will cause the child window to
784 // appear above the parent and move when the parent does.
785 if (nativeParentWindow && mPopupLevel == PopupLevel::Parent) {
786 [nativeParentWindow addChildWindow:mWindow ordered:NSWindowAbove];
789 NS_OBJC_BEGIN_TRY_IGNORE_BLOCK;
790 if (mWindowType == WindowType::TopLevel &&
791 [mWindow respondsToSelector:@selector(setAnimationBehavior:)]) {
792 NSWindowAnimationBehavior behavior;
793 if (mIsAnimationSuppressed) {
794 behavior = NSWindowAnimationBehaviorNone;
796 switch (mAnimationType) {
797 case nsIWidget::eDocumentWindowAnimation:
798 behavior = NSWindowAnimationBehaviorDocumentWindow;
801 MOZ_FALLTHROUGH_ASSERT("unexpected mAnimationType value");
802 case nsIWidget::eGenericWindowAnimation:
803 behavior = NSWindowAnimationBehaviorDefault;
807 [mWindow setAnimationBehavior:behavior];
808 mWindowAnimationBehavior = behavior;
811 // We don't want alwaysontop / alert windows to pull focus when they're
812 // opened, as these tend to be for peripheral indicators and displays.
813 if (mAlwaysOnTop || mIsAlert) {
814 [mWindow orderFront:nil];
816 [mWindow makeKeyAndOrderFront:nil];
818 NS_OBJC_END_TRY_IGNORE_BLOCK;
820 SetSupportsNativeFullscreen(savedValueForSupportsNativeFullscreen);
822 // roll up any popups if a top-level window is going away
823 if (mWindowType == WindowType::TopLevel ||
824 mWindowType == WindowType::Dialog) {
828 // If the window is a popup window with a parent window we need to
829 // unhook it here before ordering it out. When you order out the child
830 // of a window it hides the parent window.
831 if (mWindowType == WindowType::Popup && nativeParentWindow) {
832 [nativeParentWindow removeChildWindow:mWindow];
835 [mWindow orderOut:nil];
836 // If our popup window is a non-native context menu, tell the OS (and
837 // other programs) that a menu has closed.
838 if ([mWindow isKindOfClass:[PopupWindow class]] &&
839 [(PopupWindow*)mWindow isContextMenu]) {
840 [NSDistributedNotificationCenter.defaultCenter
841 postNotificationName:
842 @"com.apple.HIToolbox.endMenuTrackingNotification"
843 object:@"org.mozilla.gecko.PopupWindow"];
847 [mWindow setBeingShown:NO];
849 NS_OBJC_END_TRY_IGNORE_BLOCK;
852 // Work around a problem where with multiple displays and multiple spaces
853 // enabled, where the browser is assigned to a single display or space, popup
854 // windows that are reshown after being hidden with [NSWindow orderOut] show on
855 // the assigned space even when opened from another display. Apply the
856 // workaround whenever more than one display is enabled.
857 bool nsCocoaWindow::NeedsRecreateToReshow() {
858 // Limit the workaround to popup windows because only they need to override
859 // the "Assign To" setting. i.e., to display where the parent window is.
860 return mWindowType == WindowType::Popup && mWasShown &&
861 NSScreen.screens.count > 1;
864 WindowRenderer* nsCocoaWindow::GetWindowRenderer() {
865 if (mPopupContentView) {
866 return mPopupContentView->GetWindowRenderer();
871 TransparencyMode nsCocoaWindow::GetTransparencyMode() {
872 NS_OBJC_BEGIN_TRY_BLOCK_RETURN;
874 return mWindow.isOpaque ? TransparencyMode::Opaque
875 : TransparencyMode::Transparent;
877 NS_OBJC_END_TRY_BLOCK_RETURN(TransparencyMode::Opaque);
880 // This is called from nsMenuPopupFrame when making a popup transparent.
881 void nsCocoaWindow::SetTransparencyMode(TransparencyMode aMode) {
882 NS_OBJC_BEGIN_TRY_IGNORE_BLOCK;
888 BOOL isTransparent = aMode == TransparencyMode::Transparent;
889 BOOL currentTransparency = !mWindow.isOpaque;
890 if (isTransparent == currentTransparency) {
893 mWindow.opaque = !isTransparent;
894 mWindow.backgroundColor =
895 isTransparent ? NSColor.clearColor : NSColor.whiteColor;
897 NS_OBJC_END_TRY_IGNORE_BLOCK;
900 void nsCocoaWindow::Enable(bool aState) {}
902 bool nsCocoaWindow::IsEnabled() const { return true; }
904 void nsCocoaWindow::ConstrainPosition(DesktopIntPoint& aPoint) {
905 NS_OBJC_BEGIN_TRY_IGNORE_BLOCK;
907 if (!mWindow || ![mWindow screen]) {
911 DesktopIntRect screenRect;
913 int32_t width, height;
915 NSRect frame = mWindow.frame;
917 // zero size rects confuse the screen manager
918 width = std::max<int32_t>(frame.size.width, 1);
919 height = std::max<int32_t>(frame.size.height, 1);
921 nsCOMPtr<nsIScreenManager> screenMgr =
922 do_GetService("@mozilla.org/gfx/screenmanager;1");
924 nsCOMPtr<nsIScreen> screen;
925 screenMgr->ScreenForRect(aPoint.x, aPoint.y, width, height,
926 getter_AddRefs(screen));
929 screenRect = screen->GetRectDisplayPix();
933 aPoint = ConstrainPositionToBounds(aPoint, {width, height}, screenRect);
935 NS_OBJC_END_TRY_IGNORE_BLOCK;
938 void nsCocoaWindow::SetSizeConstraints(const SizeConstraints& aConstraints) {
939 NS_OBJC_BEGIN_TRY_IGNORE_BLOCK;
941 // Popups can be smaller than (32, 32)
942 NSRect rect = (mWindowType == WindowType::Popup)
944 : NSMakeRect(0.0, 0.0, 32, 32);
945 rect = [mWindow frameRectForChildViewRect:rect];
947 SizeConstraints c = aConstraints;
949 if (c.mScale.scale == MOZ_WIDGET_INVALID_SCALE) {
950 c.mScale.scale = BackingScaleFactor();
953 c.mMinSize.width = std::max(
954 nsCocoaUtils::CocoaPointsToDevPixels(rect.size.width, c.mScale.scale),
956 c.mMinSize.height = std::max(
957 nsCocoaUtils::CocoaPointsToDevPixels(rect.size.height, c.mScale.scale),
961 nsCocoaUtils::DevPixelsToCocoaPoints(c.mMinSize.width, c.mScale.scale),
962 nsCocoaUtils::DevPixelsToCocoaPoints(c.mMinSize.height, c.mScale.scale)};
963 mWindow.minSize = minSize;
965 c.mMaxSize.width = std::max(
966 nsCocoaUtils::CocoaPointsToDevPixels(c.mMaxSize.width, c.mScale.scale),
968 c.mMaxSize.height = std::max(
969 nsCocoaUtils::CocoaPointsToDevPixels(c.mMaxSize.height, c.mScale.scale),
973 c.mMaxSize.width == NS_MAXSIZE ? FLT_MAX
974 : nsCocoaUtils::DevPixelsToCocoaPoints(
975 c.mMaxSize.width, c.mScale.scale),
976 c.mMaxSize.height == NS_MAXSIZE ? FLT_MAX
977 : nsCocoaUtils::DevPixelsToCocoaPoints(
978 c.mMaxSize.height, c.mScale.scale)};
979 mWindow.maxSize = maxSize;
980 nsBaseWidget::SetSizeConstraints(c);
982 NS_OBJC_END_TRY_IGNORE_BLOCK;
985 // Coordinates are desktop pixels
986 void nsCocoaWindow::Move(double aX, double aY) {
987 NS_OBJC_BEGIN_TRY_IGNORE_BLOCK;
993 // The point we have is in Gecko coordinates (origin top-left). Convert
994 // it to Cocoa ones (origin bottom-left).
996 static_cast<float>(aX),
997 static_cast<float>(nsCocoaUtils::FlippedScreenY(NSToIntRound(aY)))};
999 NSRect frame = mWindow.frame;
1000 if (frame.origin.x != coord.x ||
1001 frame.origin.y + frame.size.height != coord.y) {
1002 [mWindow setFrameTopLeftPoint:coord];
1005 NS_OBJC_END_TRY_IGNORE_BLOCK;
1008 void nsCocoaWindow::SetSizeMode(nsSizeMode aMode) {
1009 if (aMode == nsSizeMode_Normal) {
1010 QueueTransition(TransitionType::Windowed);
1011 } else if (aMode == nsSizeMode_Minimized) {
1012 QueueTransition(TransitionType::Miniaturize);
1013 } else if (aMode == nsSizeMode_Maximized) {
1014 QueueTransition(TransitionType::Zoom);
1015 } else if (aMode == nsSizeMode_Fullscreen) {
1016 MakeFullScreen(true);
1020 // The (work)space switching implementation below was inspired by Phoenix:
1021 // https://github.com/kasper/phoenix/tree/d6c877f62b30a060dff119d8416b0934f76af534
1024 // Runtime `CGSGetActiveSpace` library function feature detection.
1025 typedef CGSSpaceID (*CGSGetActiveSpaceFunc)(CGSConnection cid);
1026 static CGSGetActiveSpaceFunc GetCGSGetActiveSpaceFunc() {
1027 static CGSGetActiveSpaceFunc func = nullptr;
1028 static bool lookedUpFunc = false;
1029 if (!lookedUpFunc) {
1030 func = (CGSGetActiveSpaceFunc)dlsym(RTLD_DEFAULT, "CGSGetActiveSpace");
1031 lookedUpFunc = true;
1035 // Runtime `CGSCopyManagedDisplaySpaces` library function feature detection.
1036 typedef CFArrayRef (*CGSCopyManagedDisplaySpacesFunc)(CGSConnection cid);
1037 static CGSCopyManagedDisplaySpacesFunc GetCGSCopyManagedDisplaySpacesFunc() {
1038 static CGSCopyManagedDisplaySpacesFunc func = nullptr;
1039 static bool lookedUpFunc = false;
1040 if (!lookedUpFunc) {
1041 func = (CGSCopyManagedDisplaySpacesFunc)dlsym(
1042 RTLD_DEFAULT, "CGSCopyManagedDisplaySpaces");
1043 lookedUpFunc = true;
1047 // Runtime `CGSCopySpacesForWindows` library function feature detection.
1048 typedef CFArrayRef (*CGSCopySpacesForWindowsFunc)(CGSConnection cid,
1050 CFArrayRef windowIDs);
1051 static CGSCopySpacesForWindowsFunc GetCGSCopySpacesForWindowsFunc() {
1052 static CGSCopySpacesForWindowsFunc func = nullptr;
1053 static bool lookedUpFunc = false;
1054 if (!lookedUpFunc) {
1055 func = (CGSCopySpacesForWindowsFunc)dlsym(RTLD_DEFAULT,
1056 "CGSCopySpacesForWindows");
1057 lookedUpFunc = true;
1061 // Runtime `CGSAddWindowsToSpaces` library function feature detection.
1062 typedef void (*CGSAddWindowsToSpacesFunc)(CGSConnection cid,
1063 CFArrayRef windowIDs,
1064 CFArrayRef spaceIDs);
1065 static CGSAddWindowsToSpacesFunc GetCGSAddWindowsToSpacesFunc() {
1066 static CGSAddWindowsToSpacesFunc func = nullptr;
1067 static bool lookedUpFunc = false;
1068 if (!lookedUpFunc) {
1070 (CGSAddWindowsToSpacesFunc)dlsym(RTLD_DEFAULT, "CGSAddWindowsToSpaces");
1071 lookedUpFunc = true;
1075 // Runtime `CGSRemoveWindowsFromSpaces` library function feature detection.
1076 typedef void (*CGSRemoveWindowsFromSpacesFunc)(CGSConnection cid,
1077 CFArrayRef windowIDs,
1078 CFArrayRef spaceIDs);
1079 static CGSRemoveWindowsFromSpacesFunc GetCGSRemoveWindowsFromSpacesFunc() {
1080 static CGSRemoveWindowsFromSpacesFunc func = nullptr;
1081 static bool lookedUpFunc = false;
1082 if (!lookedUpFunc) {
1083 func = (CGSRemoveWindowsFromSpacesFunc)dlsym(RTLD_DEFAULT,
1084 "CGSRemoveWindowsFromSpaces");
1085 lookedUpFunc = true;
1090 void nsCocoaWindow::GetWorkspaceID(nsAString& workspaceID) {
1091 workspaceID.Truncate();
1092 int32_t sid = GetWorkspaceID();
1094 workspaceID.AppendInt(sid);
1098 int32_t nsCocoaWindow::GetWorkspaceID() {
1099 NS_OBJC_BEGIN_TRY_IGNORE_BLOCK;
1101 // Mac OSX space IDs start at '1' (default space), so '0' means 'unknown',
1105 CGSCopySpacesForWindowsFunc CopySpacesForWindows =
1106 GetCGSCopySpacesForWindowsFunc();
1107 if (!CopySpacesForWindows) {
1111 CGSConnection cid = _CGSDefaultConnection();
1112 // Fetch all spaces that this window belongs to (in order).
1113 NSArray<NSNumber*>* spaceIDs = CFBridgingRelease(CopySpacesForWindows(
1114 cid, kCGSAllSpacesMask,
1115 (__bridge CFArrayRef) @[ @([mWindow windowNumber]) ]));
1116 if ([spaceIDs count]) {
1117 // When spaces are found, return the first one.
1118 // We don't support a single window painted across multiple places for now.
1119 sid = [spaceIDs[0] integerValue];
1121 // Fall back to the workspace that's currently active, which is '1' in the
1123 CGSGetActiveSpaceFunc GetActiveSpace = GetCGSGetActiveSpaceFunc();
1124 if (GetActiveSpace) {
1125 sid = GetActiveSpace(cid);
1131 NS_OBJC_END_TRY_IGNORE_BLOCK;
1134 void nsCocoaWindow::MoveToWorkspace(const nsAString& workspaceIDStr) {
1135 NS_OBJC_BEGIN_TRY_IGNORE_BLOCK;
1137 if ([NSScreen screensHaveSeparateSpaces] && [[NSScreen screens] count] > 1) {
1138 // We don't support moving to a workspace when the user has this option
1139 // enabled in Mission Control.
1143 nsresult rv = NS_OK;
1144 int32_t workspaceID = workspaceIDStr.ToInteger(&rv);
1145 if (NS_FAILED(rv)) {
1149 CGSConnection cid = _CGSDefaultConnection();
1150 int32_t currentSpace = GetWorkspaceID();
1151 // If an empty workspace ID is passed in (not valid on OSX), or when the
1152 // window is already on this workspace, we don't need to do anything.
1153 if (!workspaceID || workspaceID == currentSpace) {
1157 CGSCopyManagedDisplaySpacesFunc CopyManagedDisplaySpaces =
1158 GetCGSCopyManagedDisplaySpacesFunc();
1159 CGSAddWindowsToSpacesFunc AddWindowsToSpaces = GetCGSAddWindowsToSpacesFunc();
1160 CGSRemoveWindowsFromSpacesFunc RemoveWindowsFromSpaces =
1161 GetCGSRemoveWindowsFromSpacesFunc();
1162 if (!CopyManagedDisplaySpaces || !AddWindowsToSpaces ||
1163 !RemoveWindowsFromSpaces) {
1167 // Fetch an ordered list of all known spaces.
1168 NSArray* displaySpacesInfo = CFBridgingRelease(CopyManagedDisplaySpaces(cid));
1169 // When we found the space we're looking for, we can bail out of the loop
1170 // early, which this local variable is used for.
1172 for (NSDictionary<NSString*, id>* spacesInfo in displaySpacesInfo) {
1173 NSArray<NSNumber*>* sids =
1174 [spacesInfo[CGSSpacesKey] valueForKey:CGSSpaceIDKey];
1175 for (NSNumber* sid in sids) {
1176 // If we found our space in the list, we're good to go and can jump out of
1178 if ((int)[sid integerValue] == workspaceID) {
1188 // We were unable to find the space to correspond with the workspaceID as
1189 // requested, so let's bail out.
1194 // First we add the window to the appropriate space.
1195 AddWindowsToSpaces(cid, (__bridge CFArrayRef) @[ @([mWindow windowNumber]) ],
1196 (__bridge CFArrayRef) @[ @(workspaceID) ]);
1197 // Then we remove the window from the active space.
1198 RemoveWindowsFromSpaces(cid,
1199 (__bridge CFArrayRef) @[ @([mWindow windowNumber]) ],
1200 (__bridge CFArrayRef) @[ @(currentSpace) ]);
1202 NS_OBJC_END_TRY_IGNORE_BLOCK;
1205 void nsCocoaWindow::SuppressAnimation(bool aSuppress) {
1206 if ([mWindow respondsToSelector:@selector(setAnimationBehavior:)]) {
1207 mWindow.isAnimationSuppressed = aSuppress;
1208 mWindow.animationBehavior =
1209 aSuppress ? NSWindowAnimationBehaviorNone : mWindowAnimationBehavior;
1213 // This has to preserve the window's frame bounds.
1214 // This method requires (as does the Windows impl.) that you call Resize shortly
1215 // after calling HideWindowChrome. See bug 498835 for fixing this.
1216 void nsCocoaWindow::HideWindowChrome(bool aShouldHide) {
1217 NS_OBJC_BEGIN_TRY_IGNORE_BLOCK;
1219 if (!mWindow || !mWindowMadeHere ||
1220 (mWindowType != WindowType::TopLevel &&
1221 mWindowType != WindowType::Dialog)) {
1225 const BOOL isVisible = mWindow.isVisible;
1227 // Remove child windows.
1228 NSArray* childWindows = [mWindow childWindows];
1229 NSEnumerator* enumerator = [childWindows objectEnumerator];
1230 NSWindow* child = nil;
1231 while ((child = [enumerator nextObject])) {
1232 [mWindow removeChildWindow:child];
1235 // Remove the views in the old window's content view.
1236 // The NSArray is autoreleased and retains its NSViews.
1237 NSArray<NSView*>* contentViewContents = [mWindow contentViewContents];
1238 for (NSView* view in contentViewContents) {
1239 [view removeFromSuperviewWithoutNeedingDisplay];
1242 // Save state (like window title).
1243 NSMutableDictionary* state = [mWindow exportState];
1245 // Recreate the window with the right border style.
1246 NSRect frameRect = mWindow.frame;
1247 BOOL restorable = mWindow.restorable;
1248 DestroyNativeWindow();
1249 nsresult rv = CreateNativeWindow(
1250 frameRect, aShouldHide ? BorderStyle::None : mBorderStyle, true,
1252 NS_ENSURE_SUCCESS_VOID(rv);
1255 [mWindow importState:state];
1257 // Add the old content view subviews to the new window's content view.
1258 for (NSView* view in contentViewContents) {
1259 [[mWindow contentView] addSubview:view];
1262 // Reparent child windows.
1263 enumerator = [childWindows objectEnumerator];
1264 while ((child = [enumerator nextObject])) {
1265 [mWindow addChildWindow:child ordered:NSWindowAbove];
1268 // Show the new window.
1270 bool wasAnimationSuppressed = mIsAnimationSuppressed;
1271 mIsAnimationSuppressed = true;
1273 mIsAnimationSuppressed = wasAnimationSuppressed;
1276 NS_OBJC_END_TRY_IGNORE_BLOCK;
1279 class FullscreenTransitionData : public nsISupports {
1283 explicit FullscreenTransitionData(NSWindow* aWindow)
1284 : mTransitionWindow(aWindow) {}
1286 NSWindow* mTransitionWindow;
1289 virtual ~FullscreenTransitionData() { [mTransitionWindow close]; }
1292 NS_IMPL_ISUPPORTS0(FullscreenTransitionData)
1294 @interface FullscreenTransitionDelegate : NSObject <NSAnimationDelegate> {
1296 nsCocoaWindow* mWindow;
1297 nsIRunnable* mCallback;
1301 @implementation FullscreenTransitionDelegate
1302 - (void)cleanupAndDispatch:(NSAnimation*)animation {
1303 [animation setDelegate:nil];
1305 // The caller should have added ref for us.
1306 NS_DispatchToMainThread(already_AddRefed<nsIRunnable>(mCallback));
1309 - (void)animationDidEnd:(NSAnimation*)animation {
1310 MOZ_ASSERT(animation == mWindow->FullscreenTransitionAnimation(),
1311 "Should be handling the only animation on the window");
1312 mWindow->ReleaseFullscreenTransitionAnimation();
1313 [self cleanupAndDispatch:animation];
1316 - (void)animationDidStop:(NSAnimation*)animation {
1317 [self cleanupAndDispatch:animation];
1321 static bool AlwaysUsesNativeFullScreen() {
1322 return Preferences::GetBool("full-screen-api.macos-native-full-screen",
1326 /* virtual */ bool nsCocoaWindow::PrepareForFullscreenTransition(
1327 nsISupports** aData) {
1328 if (AlwaysUsesNativeFullScreen()) {
1332 // Our fullscreen transition creates a new window occluding this window.
1333 // That triggers an occlusion event which can cause DOM fullscreen requests
1334 // to fail due to the context not being focused at the time the focus check
1335 // is performed in the child process. Until the transition is cleaned up in
1336 // CleanupFullscreenTransition(), ignore occlusion events for this window.
1337 // If this method is changed to return false, the transition will not be
1338 // performed and mIgnoreOcclusionCount should not be incremented.
1339 MOZ_ASSERT(mIgnoreOcclusionCount >= 0);
1340 mIgnoreOcclusionCount++;
1342 nsCOMPtr<nsIScreen> widgetScreen = GetWidgetScreen();
1343 NSScreen* cocoaScreen = ScreenHelperCocoa::CocoaScreenForScreen(widgetScreen);
1346 [[NSWindow alloc] initWithContentRect:cocoaScreen.frame
1347 styleMask:NSWindowStyleMaskBorderless
1348 backing:NSBackingStoreBuffered
1350 [win setBackgroundColor:[NSColor blackColor]];
1351 [win setAlphaValue:0];
1352 [win setIgnoresMouseEvents:YES];
1353 [win setLevel:NSScreenSaverWindowLevel];
1354 [win makeKeyAndOrderFront:nil];
1356 auto data = new FullscreenTransitionData(win);
1362 /* virtual */ void nsCocoaWindow::CleanupFullscreenTransition() {
1363 MOZ_ASSERT(mIgnoreOcclusionCount > 0);
1364 mIgnoreOcclusionCount--;
1367 /* virtual */ void nsCocoaWindow::PerformFullscreenTransition(
1368 FullscreenTransitionStage aStage, uint16_t aDuration, nsISupports* aData,
1369 nsIRunnable* aCallback) {
1370 auto data = static_cast<FullscreenTransitionData*>(aData);
1371 FullscreenTransitionDelegate* delegate =
1372 [[FullscreenTransitionDelegate alloc] init];
1373 delegate->mWindow = this;
1374 // Storing already_AddRefed directly could cause static checking fail.
1375 delegate->mCallback = nsCOMPtr<nsIRunnable>(aCallback).forget().take();
1377 if (mFullscreenTransitionAnimation) {
1378 [mFullscreenTransitionAnimation stopAnimation];
1379 ReleaseFullscreenTransitionAnimation();
1382 NSDictionary* dict = @{
1383 NSViewAnimationTargetKey : data->mTransitionWindow,
1384 NSViewAnimationEffectKey : aStage == eBeforeFullscreenToggle
1385 ? NSViewAnimationFadeInEffect
1386 : NSViewAnimationFadeOutEffect
1388 mFullscreenTransitionAnimation =
1389 [[NSViewAnimation alloc] initWithViewAnimations:@[ dict ]];
1390 [mFullscreenTransitionAnimation setDelegate:delegate];
1391 [mFullscreenTransitionAnimation setDuration:aDuration / 1000.0];
1392 [mFullscreenTransitionAnimation startAnimation];
1395 void nsCocoaWindow::CocoaWindowWillEnterFullscreen(bool aFullscreen) {
1396 MOZ_ASSERT(mUpdateFullscreenOnResize.isNothing());
1398 mHasStartedNativeFullscreen = true;
1400 // Ensure that we update our fullscreen state as early as possible, when the
1402 mUpdateFullscreenOnResize =
1403 Some(aFullscreen ? TransitionType::Fullscreen : TransitionType::Windowed);
1406 void nsCocoaWindow::CocoaWindowDidEnterFullscreen(bool aFullscreen) {
1407 EndOurNativeTransition();
1408 mHasStartedNativeFullscreen = false;
1409 DispatchOcclusionEvent();
1411 // Check if aFullscreen matches our expected fullscreen state. It might not if
1412 // there was a failure somewhere along the way, in which case we'll recover
1414 bool receivedExpectedFullscreen = false;
1415 if (mUpdateFullscreenOnResize.isSome()) {
1416 bool expectingFullscreen =
1417 (*mUpdateFullscreenOnResize == TransitionType::Fullscreen);
1418 receivedExpectedFullscreen = (expectingFullscreen == aFullscreen);
1420 receivedExpectedFullscreen = (mInFullScreenMode == aFullscreen);
1423 TransitionType transition =
1424 aFullscreen ? TransitionType::Fullscreen : TransitionType::Windowed;
1425 if (receivedExpectedFullscreen) {
1426 // Everything is as expected. Update our state if needed.
1427 HandleUpdateFullscreenOnResize();
1429 // We weren't expecting this fullscreen state. Update our fullscreen state
1430 // to the new reality.
1431 UpdateFullscreenState(aFullscreen, true);
1433 // If we have a current transition, switch it to match what we just did.
1434 if (mTransitionCurrent.isSome()) {
1435 mTransitionCurrent = Some(transition);
1439 // Whether we expected this transition or not, we're ready to finish it.
1440 FinishCurrentTransitionIfMatching(transition);
1443 void nsCocoaWindow::UpdateFullscreenState(bool aFullScreen, bool aNativeMode) {
1444 bool wasInFullscreen = mInFullScreenMode;
1445 mInFullScreenMode = aFullScreen;
1446 if (aNativeMode || mInNativeFullScreenMode) {
1447 mInNativeFullScreenMode = aFullScreen;
1450 if (aFullScreen == wasInFullscreen) {
1454 DispatchSizeModeEvent();
1456 // Notify the mainChildView with our new fullscreen state.
1457 nsChildView* mainChildView =
1458 static_cast<nsChildView*>([[mWindow mainChildView] widget]);
1459 if (mainChildView) {
1460 mainChildView->UpdateFullscreen(aFullScreen);
1464 nsresult nsCocoaWindow::MakeFullScreen(bool aFullScreen) {
1465 return DoMakeFullScreen(aFullScreen, AlwaysUsesNativeFullScreen());
1468 nsresult nsCocoaWindow::MakeFullScreenWithNativeTransition(bool aFullScreen) {
1469 return DoMakeFullScreen(aFullScreen, true);
1472 nsresult nsCocoaWindow::DoMakeFullScreen(bool aFullScreen,
1473 bool aUseSystemTransition) {
1478 // Figure out what type of transition is being requested.
1479 TransitionType transition = TransitionType::Windowed;
1481 // Decide whether to use fullscreen or emulated fullscreen.
1483 (aUseSystemTransition && (mWindow.collectionBehavior &
1484 NSWindowCollectionBehaviorFullScreenPrimary))
1485 ? TransitionType::Fullscreen
1486 : TransitionType::EmulatedFullscreen;
1489 QueueTransition(transition);
1493 void nsCocoaWindow::QueueTransition(const TransitionType& aTransition) {
1494 mTransitionsPending.push(aTransition);
1495 ProcessTransitions();
1498 void nsCocoaWindow::ProcessTransitions() {
1499 NS_OBJC_BEGIN_TRY_IGNORE_BLOCK
1501 if (mInProcessTransitions) {
1505 mInProcessTransitions = true;
1507 if (mProcessTransitionsPending) {
1508 mProcessTransitionsPending->Cancel();
1509 mProcessTransitionsPending = nullptr;
1512 // Start a loop that will continue as long as we have transitions to process
1513 // and we aren't waiting on an asynchronous transition to complete. Any
1514 // transition that starts something async will `continue` this loop to exit.
1515 while (!mTransitionsPending.empty() && !IsInTransition()) {
1516 TransitionType nextTransition = mTransitionsPending.front();
1518 // We have to check for some incompatible transition states, and if we find
1519 // one, instead perform an alternative transition and leave the queue
1520 // untouched. If we add one of these transitions, we set
1521 // mIsTransitionCurrentAdded because we don't want to confuse listeners who
1522 // are expecting to receive exactly one event when the requested transition
1524 switch (nextTransition) {
1525 case TransitionType::Fullscreen:
1526 case TransitionType::EmulatedFullscreen:
1527 case TransitionType::Windowed:
1528 case TransitionType::Zoom:
1529 // These can't handle miniaturized windows, so deminiaturize first.
1530 if (mWindow.miniaturized) {
1531 mTransitionCurrent = Some(TransitionType::Deminiaturize);
1532 mIsTransitionCurrentAdded = true;
1535 case TransitionType::Miniaturize:
1536 // This can't handle fullscreen, so go to windowed first.
1537 if (mInFullScreenMode) {
1538 mTransitionCurrent = Some(TransitionType::Windowed);
1539 mIsTransitionCurrentAdded = true;
1546 // If mTransitionCurrent is still empty, then we use the nextTransition and
1548 if (mTransitionCurrent.isNothing()) {
1549 mTransitionCurrent = Some(nextTransition);
1550 mTransitionsPending.pop();
1553 switch (*mTransitionCurrent) {
1554 case TransitionType::Fullscreen: {
1555 if (!mInFullScreenMode) {
1556 // Run a local run loop until it is safe to start a native fullscreen
1558 NSRunLoop* localRunLoop = [NSRunLoop currentRunLoop];
1559 while (mWindow && !CanStartNativeTransition() &&
1560 [localRunLoop runMode:NSDefaultRunLoopMode
1561 beforeDate:[NSDate distantFuture]]) {
1562 // This loop continues to process events until
1563 // CanStartNativeTransition() returns true or our native
1564 // window has been destroyed.
1567 // This triggers an async animation, so continue.
1568 [mWindow toggleFullScreen:nil];
1574 case TransitionType::EmulatedFullscreen: {
1575 if (!mInFullScreenMode) {
1576 NSDisableScreenUpdates();
1577 mSuppressSizeModeEvents = true;
1578 // The order here matters. When we exit full screen mode, we need to
1579 // show the Dock first, otherwise the newly-created window won't have
1580 // its minimize button enabled. See bug 526282.
1581 nsCocoaUtils::HideOSChromeOnScreen(true);
1582 nsBaseWidget::InfallibleMakeFullScreen(true);
1583 mSuppressSizeModeEvents = false;
1584 NSEnableScreenUpdates();
1585 UpdateFullscreenState(true, false);
1590 case TransitionType::Windowed: {
1591 if (mInFullScreenMode) {
1592 if (mInNativeFullScreenMode) {
1593 // Run a local run loop until it is safe to start a native
1594 // fullscreen transition.
1595 NSRunLoop* localRunLoop = [NSRunLoop currentRunLoop];
1596 while (mWindow && !CanStartNativeTransition() &&
1597 [localRunLoop runMode:NSDefaultRunLoopMode
1598 beforeDate:[NSDate distantFuture]]) {
1599 // This loop continues to process events until
1600 // CanStartNativeTransition() returns true or our native
1601 // window has been destroyed.
1604 // This triggers an async animation, so continue.
1605 [mWindow toggleFullScreen:nil];
1608 NSDisableScreenUpdates();
1609 mSuppressSizeModeEvents = true;
1610 // The order here matters. When we exit full screen mode, we need to
1611 // show the Dock first, otherwise the newly-created window won't
1612 // have its minimize button enabled. See bug 526282.
1613 nsCocoaUtils::HideOSChromeOnScreen(false);
1614 nsBaseWidget::InfallibleMakeFullScreen(false);
1615 mSuppressSizeModeEvents = false;
1616 NSEnableScreenUpdates();
1617 UpdateFullscreenState(false, false);
1619 } else if (mWindow.zoomed) {
1622 // Check if we're still zoomed. If we are, we need to do *something*
1623 // to make the window smaller than the zoom size so Cocoa will treat
1624 // us as being out of the zoomed state. Otherwise, we could stay
1625 // zoomed and never be able to be "normal" from calls to SetSizeMode.
1626 if (mWindow.zoomed) {
1627 NSRect maximumFrame = mWindow.frame;
1628 const CGFloat INSET_OUT_OF_ZOOM = 20.0f;
1629 [mWindow setFrame:NSInsetRect(maximumFrame, INSET_OUT_OF_ZOOM,
1634 "We should be able to unzoom by shrinking the frame a bit.");
1640 case TransitionType::Miniaturize:
1641 if (!mWindow.miniaturized) {
1642 // This triggers an async animation, so continue.
1643 [mWindow miniaturize:nil];
1648 case TransitionType::Deminiaturize:
1649 if (mWindow.miniaturized) {
1650 // This triggers an async animation, so continue.
1651 [mWindow deminiaturize:nil];
1656 case TransitionType::Zoom:
1657 if (!mWindow.zoomed) {
1666 mTransitionCurrent.reset();
1667 mIsTransitionCurrentAdded = false;
1670 mInProcessTransitions = false;
1672 // When we finish processing transitions, dispatch a size mode event to cover
1673 // the cases where an inserted transition suppressed one, and the original
1674 // transition never sent one because it detected it was at the desired state
1675 // when it ran. If we've already sent a size mode event, then this will be a
1677 if (!IsInTransition()) {
1678 DispatchSizeModeEvent();
1681 NS_OBJC_END_TRY_IGNORE_BLOCK;
1684 void nsCocoaWindow::CancelAllTransitions() {
1685 // Clear our current and pending transitions. This simplifies our
1686 // reasoning about what happens next, and ensures that whatever is
1687 // currently happening won't trigger another call to
1688 // ProcessTransitions().
1689 mTransitionCurrent.reset();
1690 mIsTransitionCurrentAdded = false;
1691 if (mProcessTransitionsPending) {
1692 mProcessTransitionsPending->Cancel();
1693 mProcessTransitionsPending = nullptr;
1695 std::queue<TransitionType>().swap(mTransitionsPending);
1698 void nsCocoaWindow::FinishCurrentTransitionIfMatching(
1699 const TransitionType& aTransition) {
1700 // We've just finished some transition activity, and we're not sure whether it
1701 // was triggered programmatically, or by the user. If it matches our current
1702 // transition, then assume it was triggered programmatically and we can clean
1703 // up that transition and start processing transitions again.
1705 // Whether programmatic or user-initiated, we send out a size mode event.
1706 DispatchSizeModeEvent();
1708 if (mTransitionCurrent.isSome() && (*mTransitionCurrent == aTransition)) {
1709 // This matches our current transition, so do the safe parts of transition
1711 mTransitionCurrent.reset();
1712 mIsTransitionCurrentAdded = false;
1714 // Since this function is called from nsWindowDelegate transition callbacks,
1715 // we want to make sure those callbacks are all the way done before we
1716 // continue processing more transitions. To accomplish this, we dispatch
1717 // ProcessTransitions on the next event loop. Doing this will ensure that
1718 // any async native transition methods we call (like toggleFullScreen) will
1720 if (!mTransitionsPending.empty() && !mProcessTransitionsPending) {
1721 mProcessTransitionsPending = NS_NewCancelableRunnableFunction(
1722 "ProcessTransitionsPending",
1723 [self = RefPtr{this}] { self->ProcessTransitions(); });
1724 NS_DispatchToCurrentThread(mProcessTransitionsPending);
1729 bool nsCocoaWindow::HandleUpdateFullscreenOnResize() {
1730 if (mUpdateFullscreenOnResize.isNothing()) {
1735 (*mUpdateFullscreenOnResize == TransitionType::Fullscreen);
1736 mUpdateFullscreenOnResize.reset();
1737 UpdateFullscreenState(toFullscreen, true);
1742 /* static */ nsCocoaWindow* nsCocoaWindow::sWindowInNativeTransition(nullptr);
1744 bool nsCocoaWindow::CanStartNativeTransition() {
1745 if (sWindowInNativeTransition == nullptr) {
1746 // Claim it and return true, indicating that the caller has permission to
1747 // start the native fullscreen transition.
1748 sWindowInNativeTransition = this;
1754 void nsCocoaWindow::EndOurNativeTransition() {
1755 if (sWindowInNativeTransition == this) {
1756 sWindowInNativeTransition = nullptr;
1760 // Coordinates are desktop pixels
1761 void nsCocoaWindow::DoResize(double aX, double aY, double aWidth,
1762 double aHeight, bool aRepaint,
1763 bool aConstrainToCurrentScreen) {
1764 NS_OBJC_BEGIN_TRY_IGNORE_BLOCK;
1766 if (!mWindow || mInResize) {
1770 // We are able to resize a window outside of any aspect ratio contraints
1771 // applied to it, but in order to "update" the aspect ratio contraint to the
1772 // new window dimensions, we must re-lock the aspect ratio.
1773 auto relockAspectRatio = MakeScopeExit([&]() {
1774 if (mAspectRatioLocked) {
1775 LockAspectRatio(true);
1779 AutoRestore<bool> reentrantResizeGuard(mInResize);
1782 CGFloat scale = mSizeConstraints.mScale.scale;
1783 if (scale == MOZ_WIDGET_INVALID_SCALE) {
1784 scale = BackingScaleFactor();
1787 // mSizeConstraints is in device pixels.
1788 int32_t width = NSToIntRound(aWidth * scale);
1789 int32_t height = NSToIntRound(aHeight * scale);
1791 width = std::max(mSizeConstraints.mMinSize.width,
1792 std::min(mSizeConstraints.mMaxSize.width, width));
1793 height = std::max(mSizeConstraints.mMinSize.height,
1794 std::min(mSizeConstraints.mMaxSize.height, height));
1796 DesktopIntRect newBounds(NSToIntRound(aX), NSToIntRound(aY),
1797 NSToIntRound(width / scale),
1798 NSToIntRound(height / scale));
1800 // convert requested bounds into Cocoa coordinate system
1801 NSRect newFrame = nsCocoaUtils::GeckoRectToCocoaRect(newBounds);
1803 NSRect frame = mWindow.frame;
1804 BOOL isMoving = newFrame.origin.x != frame.origin.x ||
1805 newFrame.origin.y != frame.origin.y;
1806 BOOL isResizing = newFrame.size.width != frame.size.width ||
1807 newFrame.size.height != frame.size.height;
1809 if (!isMoving && !isResizing) {
1813 // We ignore aRepaint -- we have to call display:YES, otherwise the
1814 // title bar doesn't immediately get repainted and is displayed in
1815 // the wrong place, leading to a visual jump.
1816 [mWindow setFrame:newFrame display:YES];
1818 NS_OBJC_END_TRY_IGNORE_BLOCK;
1821 // Coordinates are desktop pixels
1822 void nsCocoaWindow::Resize(double aX, double aY, double aWidth, double aHeight,
1824 DoResize(aX, aY, aWidth, aHeight, aRepaint, false);
1827 // Coordinates are desktop pixels
1828 void nsCocoaWindow::Resize(double aWidth, double aHeight, bool aRepaint) {
1829 double invScale = 1.0 / BackingScaleFactor();
1830 DoResize(mBounds.x * invScale, mBounds.y * invScale, aWidth, aHeight,
1834 // Return the area that the Gecko ChildView in our window should cover, as an
1835 // NSRect in screen coordinates (with 0,0 being the bottom left corner of the
1837 NSRect nsCocoaWindow::GetClientCocoaRect() {
1842 return [mWindow childViewRectForFrameRect:mWindow.frame];
1845 LayoutDeviceIntRect nsCocoaWindow::GetClientBounds() {
1846 NS_OBJC_BEGIN_TRY_BLOCK_RETURN;
1848 CGFloat scaleFactor = BackingScaleFactor();
1849 return nsCocoaUtils::CocoaRectToGeckoRectDevPix(GetClientCocoaRect(),
1852 NS_OBJC_END_TRY_BLOCK_RETURN(LayoutDeviceIntRect(0, 0, 0, 0));
1855 void nsCocoaWindow::UpdateBounds() {
1856 NSRect frame = NSZeroRect;
1858 frame = mWindow.frame;
1861 nsCocoaUtils::CocoaRectToGeckoRectDevPix(frame, BackingScaleFactor());
1863 if (mPopupContentView) {
1864 mPopupContentView->UpdateBoundsFromView();
1868 LayoutDeviceIntRect nsCocoaWindow::GetScreenBounds() {
1869 NS_OBJC_BEGIN_TRY_BLOCK_RETURN;
1872 LayoutDeviceIntRect r = nsCocoaUtils::CocoaRectToGeckoRectDevPix(
1873 mWindow.frame, BackingScaleFactor());
1874 NS_ASSERTION(mWindow && mBounds == r, "mBounds out of sync!");
1879 NS_OBJC_END_TRY_BLOCK_RETURN(LayoutDeviceIntRect(0, 0, 0, 0));
1882 double nsCocoaWindow::GetDefaultScaleInternal() { return BackingScaleFactor(); }
1884 static CGFloat GetBackingScaleFactor(NSWindow* aWindow) {
1885 NSRect frame = aWindow.frame;
1886 if (frame.size.width > 0 && frame.size.height > 0) {
1887 return nsCocoaUtils::GetBackingScaleFactor(aWindow);
1890 // For windows with zero width or height, the backingScaleFactor method
1891 // is broken - it will always return 2 on a retina macbook, even when
1892 // the window position implies it's on a non-hidpi external display
1893 // (to the extent that a zero-area window can be said to be "on" a
1895 // And to make matters worse, Cocoa even fires a
1896 // windowDidChangeBackingProperties notification with the
1897 // NSBackingPropertyOldScaleFactorKey key when a window on an
1898 // external display is resized to/from zero height, even though it hasn't
1899 // really changed screens.
1901 // This causes us to handle popup window sizing incorrectly when the
1902 // popup is resized to zero height (bug 820327) - nsXULPopupManager
1903 // becomes (incorrectly) convinced the popup has been explicitly forced
1904 // to a non-default size and needs to have size attributes attached.
1906 // Workaround: instead of asking the window, we'll find the screen it is on
1907 // and ask that for *its* backing scale factor.
1909 // (See bug 853252 and additional comments in windowDidChangeScreen: below
1910 // for further complications this causes.)
1912 // First, expand the rect so that it actually has a measurable area,
1913 // for FindTargetScreenForRect to use.
1914 if (frame.size.width == 0) {
1915 frame.size.width = 1;
1917 if (frame.size.height == 0) {
1918 frame.size.height = 1;
1921 // Then identify the screen it belongs to, and return its scale factor.
1923 FindTargetScreenForRect(nsCocoaUtils::CocoaRectToGeckoRect(frame));
1924 return nsCocoaUtils::GetBackingScaleFactor(screen);
1927 CGFloat nsCocoaWindow::BackingScaleFactor() {
1928 if (mBackingScaleFactor > 0.0) {
1929 return mBackingScaleFactor;
1934 mBackingScaleFactor = GetBackingScaleFactor(mWindow);
1935 return mBackingScaleFactor;
1938 void nsCocoaWindow::BackingScaleFactorChanged() {
1939 CGFloat newScale = GetBackingScaleFactor(mWindow);
1941 // Ignore notification if it hasn't really changed
1942 if (BackingScaleFactor() == newScale) {
1946 mBackingScaleFactor = newScale;
1947 NotifyAPZOfDPIChange();
1949 if (!mWidgetListener || mWidgetListener->GetAppWindow()) {
1953 if (PresShell* presShell = mWidgetListener->GetPresShell()) {
1954 presShell->BackingScaleFactorChanged();
1958 int32_t nsCocoaWindow::RoundsWidgetCoordinatesTo() {
1959 if (BackingScaleFactor() == 2.0) {
1965 void nsCocoaWindow::SetCursor(const Cursor& aCursor) {
1966 if (mPopupContentView) {
1967 mPopupContentView->SetCursor(aCursor);
1971 nsresult nsCocoaWindow::SetTitle(const nsAString& aTitle) {
1972 NS_OBJC_BEGIN_TRY_BLOCK_RETURN;
1978 const nsString& strTitle = PromiseFlatString(aTitle);
1979 const unichar* uniTitle = reinterpret_cast<const unichar*>(strTitle.get());
1980 NSString* title = [NSString stringWithCharacters:uniTitle
1981 length:strTitle.Length()];
1982 if (mWindow.drawsContentsIntoWindowFrame && !mWindow.wantsTitleDrawn) {
1983 // Don't cause invalidations when the title isn't displayed.
1984 [mWindow disableSetNeedsDisplay];
1985 [mWindow setTitle:title];
1986 [mWindow enableSetNeedsDisplay];
1988 [mWindow setTitle:title];
1993 NS_OBJC_END_TRY_BLOCK_RETURN(NS_ERROR_FAILURE);
1996 void nsCocoaWindow::Invalidate(const LayoutDeviceIntRect& aRect) {
1997 if (mPopupContentView) {
1998 mPopupContentView->Invalidate(aRect);
2002 // Pass notification of some drag event to Gecko
2004 // The drag manager has let us know that something related to a drag has
2005 // occurred in this window. It could be any number of things, ranging from
2006 // a drop, to a drag enter/leave, or a drag over event. The actual event
2007 // is passed in |aMessage| and is passed along to our event hanlder so Gecko
2009 bool nsCocoaWindow::DragEvent(unsigned int aMessage,
2010 mozilla::gfx::Point aMouseGlobal,
2011 UInt16 aKeyModifiers) {
2015 // Invokes callback and ProcessEvent methods on Event Listener object
2016 nsresult nsCocoaWindow::DispatchEvent(WidgetGUIEvent* event,
2017 nsEventStatus& aStatus) {
2018 aStatus = nsEventStatus_eIgnore;
2020 nsCOMPtr<nsIWidget> kungFuDeathGrip(event->mWidget);
2021 mozilla::Unused << kungFuDeathGrip; // Not used within this function
2023 if (mWidgetListener) {
2024 aStatus = mWidgetListener->HandleEvent(event, mUseAttachedEvents);
2030 // aFullScreen should be the window's mInFullScreenMode. We don't have access to
2031 // that from here, so we need to pass it in. mInFullScreenMode should be the
2032 // canonical indicator that a window is currently full screen and it makes sense
2033 // to keep all sizemode logic here.
2034 static nsSizeMode GetWindowSizeMode(NSWindow* aWindow, bool aFullScreen) {
2036 return nsSizeMode_Fullscreen;
2038 if (aWindow.isMiniaturized) {
2039 return nsSizeMode_Minimized;
2041 if ((aWindow.styleMask & NSWindowStyleMaskResizable) && aWindow.isZoomed) {
2042 return nsSizeMode_Maximized;
2044 return nsSizeMode_Normal;
2047 void nsCocoaWindow::ReportMoveEvent() {
2048 NS_OBJC_BEGIN_TRY_IGNORE_BLOCK;
2050 // Prevent recursion, which can become infinite (see bug 708278). This
2051 // can happen when the call to [NSWindow setFrameTopLeftPoint:] in
2052 // nsCocoaWindow::Move() triggers an immediate NSWindowDidMove notification
2053 // (and a call to [WindowDelegate windowDidMove:]).
2054 if (mInReportMoveEvent) {
2057 mInReportMoveEvent = true;
2061 // The zoomed state can change when we're moving, in which case we need to
2062 // update our internal mSizeMode. This can happen either if we're maximized
2063 // and then moved, or if we're not maximized and moved back to zoomed state.
2064 if (mWindow && (mSizeMode == nsSizeMode_Maximized) ^ mWindow.isZoomed) {
2065 DispatchSizeModeEvent();
2068 // Dispatch the move event to Gecko
2069 NotifyWindowMoved(mBounds.x, mBounds.y);
2071 mInReportMoveEvent = false;
2073 NS_OBJC_END_TRY_IGNORE_BLOCK;
2076 void nsCocoaWindow::DispatchSizeModeEvent() {
2081 if (mSuppressSizeModeEvents || mIsTransitionCurrentAdded) {
2085 nsSizeMode newMode = GetWindowSizeMode(mWindow, mInFullScreenMode);
2086 if (mSizeMode == newMode) {
2090 mSizeMode = newMode;
2091 if (mWidgetListener) {
2092 mWidgetListener->SizeModeChanged(newMode);
2096 void nsCocoaWindow::DispatchOcclusionEvent() {
2101 // Our new occlusion state is true if the window is not visible.
2102 bool newOcclusionState =
2103 !(mHasStartedNativeFullscreen ||
2104 ([mWindow occlusionState] & NSWindowOcclusionStateVisible));
2106 // Don't dispatch if the new occlustion state is the same as the current
2108 if (mIsFullyOccluded == newOcclusionState) {
2112 MOZ_ASSERT(mIgnoreOcclusionCount >= 0);
2113 if (newOcclusionState && mIgnoreOcclusionCount > 0) {
2117 mIsFullyOccluded = newOcclusionState;
2118 if (mWidgetListener) {
2119 mWidgetListener->OcclusionStateChanged(mIsFullyOccluded);
2123 void nsCocoaWindow::ReportSizeEvent() {
2124 NS_OBJC_BEGIN_TRY_IGNORE_BLOCK;
2127 if (mWidgetListener) {
2128 LayoutDeviceIntRect innerBounds = GetClientBounds();
2129 mWidgetListener->WindowResized(this, innerBounds.width, innerBounds.height);
2132 NS_OBJC_END_TRY_IGNORE_BLOCK;
2135 void nsCocoaWindow::SetMenuBar(RefPtr<nsMenuBarX>&& aMenuBar) {
2140 mMenuBar = std::move(aMenuBar);
2142 // Only paint for active windows, or paint the hidden window menu bar if no
2143 // other menu bar has been painted yet so that some reasonable menu bar is
2144 // displayed when the app starts up.
2145 if (mMenuBar && ((!gSomeMenuBarPainted &&
2146 nsMenuUtilsX::GetHiddenWindowMenuBar() == mMenuBar) ||
2147 mWindow.isMainWindow)) {
2148 // We do an async paint in order to prevent crashes when macOS is actively
2149 // enumerating the menu items in `NSApp.mainMenu`.
2150 mMenuBar->PaintAsync();
2154 void nsCocoaWindow::SetFocus(Raise aRaise,
2155 mozilla::dom::CallerType aCallerType) {
2156 if (!mWindow) return;
2158 if (mPopupContentView) {
2159 return mPopupContentView->SetFocus(aRaise, aCallerType);
2162 if (aRaise == Raise::Yes && (mWindow.isVisible || mWindow.isMiniaturized)) {
2163 if (mWindow.isMiniaturized) {
2164 [mWindow deminiaturize:nil];
2166 [mWindow makeKeyAndOrderFront:nil];
2170 LayoutDeviceIntPoint nsCocoaWindow::WidgetToScreenOffset() {
2171 NS_OBJC_BEGIN_TRY_BLOCK_RETURN;
2173 return nsCocoaUtils::CocoaRectToGeckoRectDevPix(GetClientCocoaRect(),
2174 BackingScaleFactor())
2177 NS_OBJC_END_TRY_BLOCK_RETURN(LayoutDeviceIntPoint(0, 0));
2180 LayoutDeviceIntPoint nsCocoaWindow::GetClientOffset() {
2181 NS_OBJC_BEGIN_TRY_BLOCK_RETURN;
2183 LayoutDeviceIntRect clientRect = GetClientBounds();
2185 return clientRect.TopLeft() - mBounds.TopLeft();
2187 NS_OBJC_END_TRY_BLOCK_RETURN(LayoutDeviceIntPoint(0, 0));
2190 LayoutDeviceIntMargin nsCocoaWindow::ClientToWindowMargin() {
2191 NS_OBJC_BEGIN_TRY_BLOCK_RETURN;
2193 if (!mWindow || mWindow.drawsContentsIntoWindowFrame ||
2194 mWindowType == WindowType::Popup) {
2198 NSRect clientNSRect = mWindow.contentLayoutRect;
2199 NSRect frameNSRect = [mWindow frameRectForChildViewRect:clientNSRect];
2201 CGFloat backingScale = BackingScaleFactor();
2202 const auto clientRect =
2203 nsCocoaUtils::CocoaRectToGeckoRectDevPix(clientNSRect, backingScale);
2204 const auto frameRect =
2205 nsCocoaUtils::CocoaRectToGeckoRectDevPix(frameNSRect, backingScale);
2207 return frameRect - clientRect;
2209 NS_OBJC_END_TRY_BLOCK_RETURN({});
2212 nsMenuBarX* nsCocoaWindow::GetMenuBar() { return mMenuBar; }
2214 void nsCocoaWindow::CaptureRollupEvents(bool aDoCapture) {
2215 NS_OBJC_BEGIN_TRY_IGNORE_BLOCK;
2218 if (!NSApp.isActive) {
2219 // We need to capture mouse event if we aren't
2220 // the active application. We only set this up when needed
2221 // because they cause spurious mouse event after crash
2222 // and gdb sessions. See bug 699538.
2223 nsToolkit::GetToolkit()->MonitorAllProcessMouseEvents();
2226 // Sometimes more than one popup window can be visible at the same time
2227 // (e.g. nested non-native context menus, or the test case (attachment
2228 // 276885) for bmo bug 392389, which displays a non-native combo-box in a
2229 // non-native popup window). In these cases the "active" popup window
2230 // should be the topmost -- the (nested) context menu the mouse is currently
2231 // over, or the combo-box's drop-down list (when it's displayed). But
2232 // (among windows that have the same "level") OS X makes topmost the window
2233 // that last received a mouse-down event, which may be incorrect (in the
2234 // combo-box case, it makes topmost the window containing the combo-box).
2235 // So here we fiddle with a non-native popup window's level to make sure the
2236 // "active" one is always above any other non-native popup windows that
2238 if (mWindowType == WindowType::Popup) {
2239 SetPopupWindowLevel();
2242 nsToolkit::GetToolkit()->StopMonitoringAllProcessMouseEvents();
2244 // XXXndeakin this doesn't make sense.
2245 // Why is the new window assumed to be a modal panel?
2246 if (mWindow && mWindowType == WindowType::Popup) {
2247 mWindow.level = NSModalPanelWindowLevel;
2251 NS_OBJC_END_TRY_IGNORE_BLOCK;
2254 nsresult nsCocoaWindow::GetAttention(int32_t aCycleCount) {
2255 NS_OBJC_BEGIN_TRY_BLOCK_RETURN;
2257 [NSApp requestUserAttention:NSInformationalRequest];
2260 NS_OBJC_END_TRY_BLOCK_RETURN(NS_ERROR_FAILURE);
2263 bool nsCocoaWindow::HasPendingInputEvent() {
2264 return nsChildView::DoHasPendingInputEvent();
2267 void nsCocoaWindow::SetWindowShadowStyle(WindowShadow aStyle) {
2268 NS_OBJC_BEGIN_TRY_IGNORE_BLOCK;
2270 if (mShadowStyle == aStyle) {
2274 mShadowStyle = aStyle;
2276 if (!mWindow || mWindowType != WindowType::Popup) {
2280 mWindow.shadowStyle = mShadowStyle;
2281 [mWindow setEffectViewWrapperForStyle:mShadowStyle];
2282 [mWindow setHasShadow:aStyle != WindowShadow::None];
2284 NS_OBJC_END_TRY_IGNORE_BLOCK;
2287 void nsCocoaWindow::SetWindowOpacity(float aOpacity) {
2288 NS_OBJC_BEGIN_TRY_IGNORE_BLOCK;
2294 [mWindow setAlphaValue:(CGFloat)aOpacity];
2296 NS_OBJC_END_TRY_IGNORE_BLOCK;
2299 void nsCocoaWindow::SetColorScheme(const Maybe<ColorScheme>& aScheme) {
2300 NS_OBJC_BEGIN_TRY_IGNORE_BLOCK;
2305 NSAppearance* appearance =
2306 aScheme ? NSAppearanceForColorScheme(*aScheme) : nil;
2307 if (mWindow.appearance != appearance) {
2308 mWindow.appearance = appearance;
2310 NS_OBJC_END_TRY_IGNORE_BLOCK;
2313 static inline CGAffineTransform GfxMatrixToCGAffineTransform(
2314 const gfx::Matrix& m) {
2315 CGAffineTransform t;
2325 void nsCocoaWindow::SetWindowTransform(const gfx::Matrix& aTransform) {
2326 NS_OBJC_BEGIN_TRY_IGNORE_BLOCK;
2332 // Calling CGSSetWindowTransform when the window is not visible results in
2333 // misplacing the window into doubled x,y coordinates (see bug 1448132).
2334 if (!mWindow.isVisible || NSIsEmptyRect(mWindow.frame)) {
2338 if (StaticPrefs::widget_window_transforms_disabled()) {
2339 // CGSSetWindowTransform is a private API. In case calling it causes
2340 // problems either now or in the future, we'll want to have an easy kill
2341 // switch. So we allow disabling it with a pref.
2345 gfx::Matrix transform = aTransform;
2347 // aTransform is a transform that should be applied to the window relative
2348 // to its regular position: If aTransform._31 is 100, then we want the
2349 // window to be displayed 100 pixels to the right of its regular position.
2350 // The transform that CGSSetWindowTransform accepts has a different meaning:
2351 // It's used to answer the question "For the screen pixel at x,y (with the
2352 // origin at the top left), what pixel in the window's buffer (again with
2353 // origin top left) should be displayed at that position?"
2354 // In the example above, this means that we need to call
2355 // CGSSetWindowTransform with a horizontal translation of -windowPos.x - 100.
2356 // So we need to invert the transform and adjust it by the window's position.
2357 if (!transform.Invert()) {
2358 // Treat non-invertible transforms as the identity transform.
2359 transform = gfx::Matrix();
2362 bool isIdentity = transform.IsIdentity();
2363 if (isIdentity && mWindowTransformIsIdentity) {
2367 transform.PreTranslate(-mBounds.x, -mBounds.y);
2369 // Snap translations to device pixels, to match what we do for CSS transforms
2370 // and because the window server rounds down instead of to nearest.
2371 if (!transform.HasNonTranslation() && transform.HasNonIntegerTranslation()) {
2372 auto snappedTranslation = gfx::IntPoint::Round(transform.GetTranslation());
2374 gfx::Matrix::Translation(snappedTranslation.x, snappedTranslation.y);
2377 // We also need to account for the backing scale factor: aTransform is given
2378 // in device pixels, but CGSSetWindowTransform works with logical display
2380 CGFloat backingScale = BackingScaleFactor();
2381 transform.PreScale(backingScale, backingScale);
2382 transform.PostScale(1 / backingScale, 1 / backingScale);
2384 CGSConnection cid = _CGSDefaultConnection();
2385 CGSSetWindowTransform(cid, [mWindow windowNumber],
2386 GfxMatrixToCGAffineTransform(transform));
2388 mWindowTransformIsIdentity = isIdentity;
2390 NS_OBJC_END_TRY_IGNORE_BLOCK;
2393 void nsCocoaWindow::SetInputRegion(const InputRegion& aInputRegion) {
2394 MOZ_ASSERT(mWindowType == WindowType::Popup,
2395 "This should only be called on popup windows.");
2396 // TODO: Somehow support aInputRegion.mMargin? Though maybe not.
2397 if (aInputRegion.mFullyTransparent) {
2398 [mWindow setIgnoresMouseEvents:YES];
2400 [mWindow setIgnoresMouseEvents:NO];
2404 void nsCocoaWindow::SetShowsToolbarButton(bool aShow) {
2405 NS_OBJC_BEGIN_TRY_IGNORE_BLOCK;
2407 if (mWindow) [mWindow setShowsToolbarButton:aShow];
2409 NS_OBJC_END_TRY_IGNORE_BLOCK;
2412 bool nsCocoaWindow::GetSupportsNativeFullscreen() {
2413 return mWindow.collectionBehavior &
2414 NSWindowCollectionBehaviorFullScreenPrimary;
2417 void nsCocoaWindow::SetSupportsNativeFullscreen(
2418 bool aSupportsNativeFullscreen) {
2419 NS_OBJC_BEGIN_TRY_IGNORE_BLOCK;
2422 // This determines whether we tell cocoa that the window supports native
2423 // full screen. If we do so, and another window is in native full screen,
2424 // this window will also appear in native full screen. We generally only
2425 // want to do this for primary application windows. We'll set the
2426 // relevant macnativefullscreen attribute on those, which will lead to us
2427 // being called with aSupportsNativeFullscreen set to `true` here.
2428 NSWindowCollectionBehavior newBehavior = [mWindow collectionBehavior];
2429 if (aSupportsNativeFullscreen) {
2430 newBehavior |= NSWindowCollectionBehaviorFullScreenPrimary;
2432 newBehavior &= ~NSWindowCollectionBehaviorFullScreenPrimary;
2434 [mWindow setCollectionBehavior:newBehavior];
2437 NS_OBJC_END_TRY_IGNORE_BLOCK;
2440 void nsCocoaWindow::SetWindowAnimationType(
2441 nsIWidget::WindowAnimationType aType) {
2442 mAnimationType = aType;
2445 void nsCocoaWindow::SetDrawsTitle(bool aDrawTitle) {
2446 NS_OBJC_BEGIN_TRY_IGNORE_BLOCK;
2448 // If we don't draw into the window frame, we always want to display window
2450 mWindow.wantsTitleDrawn = aDrawTitle || !mWindow.drawsContentsIntoWindowFrame;
2452 NS_OBJC_END_TRY_IGNORE_BLOCK;
2455 void nsCocoaWindow::SetCustomTitlebar(bool aState) {
2456 NS_OBJC_BEGIN_TRY_IGNORE_BLOCK;
2459 [mWindow setDrawsContentsIntoWindowFrame:aState];
2462 NS_OBJC_END_TRY_IGNORE_BLOCK;
2465 NS_IMETHODIMP nsCocoaWindow::SynthesizeNativeMouseEvent(
2466 LayoutDeviceIntPoint aPoint, NativeMouseMessage aNativeMessage,
2467 MouseButton aButton, nsIWidget::Modifiers aModifierFlags,
2468 nsIObserver* aObserver) {
2469 NS_OBJC_BEGIN_TRY_BLOCK_RETURN;
2471 AutoObserverNotifier notifier(aObserver, "mouseevent");
2472 if (mPopupContentView) {
2473 return mPopupContentView->SynthesizeNativeMouseEvent(
2474 aPoint, aNativeMessage, aButton, aModifierFlags, nullptr);
2479 NS_OBJC_END_TRY_BLOCK_RETURN(NS_ERROR_FAILURE);
2482 NS_IMETHODIMP nsCocoaWindow::SynthesizeNativeMouseScrollEvent(
2483 LayoutDeviceIntPoint aPoint, uint32_t aNativeMessage, double aDeltaX,
2484 double aDeltaY, double aDeltaZ, uint32_t aModifierFlags,
2485 uint32_t aAdditionalFlags, nsIObserver* aObserver) {
2486 NS_OBJC_BEGIN_TRY_BLOCK_RETURN;
2488 AutoObserverNotifier notifier(aObserver, "mousescrollevent");
2489 if (mPopupContentView) {
2490 // Pass nullptr as the observer so that the AutoObserverNotification in
2491 // nsChildView::SynthesizeNativeMouseScrollEvent will be ignored.
2492 return mPopupContentView->SynthesizeNativeMouseScrollEvent(
2493 aPoint, aNativeMessage, aDeltaX, aDeltaY, aDeltaZ, aModifierFlags,
2494 aAdditionalFlags, nullptr);
2499 NS_OBJC_END_TRY_BLOCK_RETURN(NS_ERROR_FAILURE);
2502 void nsCocoaWindow::LockAspectRatio(bool aShouldLock) {
2503 NS_OBJC_BEGIN_TRY_IGNORE_BLOCK;
2506 [mWindow setContentAspectRatio:mWindow.frame.size];
2507 mAspectRatioLocked = true;
2510 // https://developer.apple.com/documentation/appkit/nswindow/1419507-aspectratio,
2511 // aspect ratios and resize increments are mutually exclusive, and the
2512 // accepted way of cancelling an established aspect ratio is to set the
2513 // resize increments to 1.0, 1.0
2514 [mWindow setResizeIncrements:NSMakeSize(1.0, 1.0)];
2515 mAspectRatioLocked = false;
2518 NS_OBJC_END_TRY_IGNORE_BLOCK;
2521 void nsCocoaWindow::UpdateThemeGeometries(
2522 const nsTArray<ThemeGeometry>& aThemeGeometries) {
2523 NS_OBJC_BEGIN_TRY_IGNORE_BLOCK;
2525 if (mPopupContentView) {
2526 return mPopupContentView->UpdateThemeGeometries(aThemeGeometries);
2529 NS_OBJC_END_TRY_IGNORE_BLOCK;
2532 void nsCocoaWindow::SetPopupWindowLevel() {
2536 // Otherwise, this is a top-level or parent popup. Parent popups always
2537 // appear just above their parent and essentially ignore the level.
2538 mWindow.level = NSPopUpMenuWindowLevel;
2539 mWindow.hidesOnDeactivate = NO;
2542 void nsCocoaWindow::SetInputContext(const InputContext& aContext,
2543 const InputContextAction& aAction) {
2544 NS_OBJC_BEGIN_TRY_IGNORE_BLOCK;
2546 mInputContext = aContext;
2548 NS_OBJC_END_TRY_IGNORE_BLOCK;
2551 bool nsCocoaWindow::GetEditCommands(NativeKeyBindingsType aType,
2552 const WidgetKeyboardEvent& aEvent,
2553 nsTArray<CommandInt>& aCommands) {
2554 // Validate the arguments.
2555 if (NS_WARN_IF(!nsIWidget::GetEditCommands(aType, aEvent, aCommands))) {
2559 NativeKeyBindings* keyBindings = NativeKeyBindings::GetInstance(aType);
2560 // When the keyboard event is fired from this widget, it must mean that no web
2561 // content has focus because any web contents should be on `nsChildView`. And
2562 // in any locales, the system UI is always horizontal layout. So, let's pass
2563 // `Nothing()` for the writing mode here, it won't be treated as in a vertical
2565 keyBindings->GetEditCommands(aEvent, Nothing(), aCommands);
2569 void nsCocoaWindow::PauseOrResumeCompositor(bool aPause) {
2570 if (auto* mainChildView =
2571 static_cast<nsIWidget*>(mWindow.mainChildView.widget)) {
2572 mainChildView->PauseOrResumeCompositor(aPause);
2576 bool nsCocoaWindow::AsyncPanZoomEnabled() const {
2577 if (mPopupContentView) {
2578 return mPopupContentView->AsyncPanZoomEnabled();
2580 return nsBaseWidget::AsyncPanZoomEnabled();
2583 bool nsCocoaWindow::StartAsyncAutoscroll(const ScreenPoint& aAnchorLocation,
2584 const ScrollableLayerGuid& aGuid) {
2585 if (mPopupContentView) {
2586 return mPopupContentView->StartAsyncAutoscroll(aAnchorLocation, aGuid);
2588 return nsBaseWidget::StartAsyncAutoscroll(aAnchorLocation, aGuid);
2591 void nsCocoaWindow::StopAsyncAutoscroll(const ScrollableLayerGuid& aGuid) {
2592 if (mPopupContentView) {
2593 mPopupContentView->StopAsyncAutoscroll(aGuid);
2596 nsBaseWidget::StopAsyncAutoscroll(aGuid);
2599 already_AddRefed<nsIWidget> nsIWidget::CreateTopLevelWindow() {
2600 nsCOMPtr<nsIWidget> window = new nsCocoaWindow();
2601 return window.forget();
2604 already_AddRefed<nsIWidget> nsIWidget::CreateChildWindow() {
2605 nsCOMPtr<nsIWidget> window = new nsChildView();
2606 return window.forget();
2609 @implementation WindowDelegate
2611 // We try to find a gecko menu bar to paint. If one does not exist, just paint
2612 // the application menu by itself so that a window doesn't have some other
2613 // window's menu bar.
2614 + (void)paintMenubarForWindow:(NSWindow*)aWindow {
2615 NS_OBJC_BEGIN_TRY_IGNORE_BLOCK;
2617 // make sure we only act on windows that have this kind of
2618 // object as a delegate
2619 id windowDelegate = [aWindow delegate];
2620 if ([windowDelegate class] != [self class]) return;
2622 nsCocoaWindow* geckoWidget = [windowDelegate geckoWidget];
2623 NS_ASSERTION(geckoWidget, "Window delegate not returning a gecko widget!");
2625 if (nsMenuBarX* geckoMenuBar = geckoWidget->GetMenuBar()) {
2626 // We do an async paint in order to prevent crashes when macOS is actively
2627 // enumerating the menu items in `NSApp.mainMenu`.
2628 geckoMenuBar->PaintAsync();
2630 // sometimes we don't have a native application menu early in launching
2631 if (!sApplicationMenu) {
2635 NSMenu* mainMenu = NSApp.mainMenu;
2637 mainMenu.numberOfItems > 0,
2638 "Main menu does not have any items, something is terribly wrong!");
2640 // Create a new menu bar.
2641 // We create a GeckoNSMenu because all menu bar NSMenu objects should use
2642 // that subclass for key handling reasons.
2643 GeckoNSMenu* newMenuBar =
2644 [[GeckoNSMenu alloc] initWithTitle:@"MainMenuBar"];
2646 // move the application menu from the existing menu bar to the new one
2647 NSMenuItem* firstMenuItem = [[mainMenu itemAtIndex:0] retain];
2648 [mainMenu removeItemAtIndex:0];
2649 [newMenuBar insertItem:firstMenuItem atIndex:0];
2650 [firstMenuItem release];
2652 // set our new menu bar as the main menu
2653 NSApp.mainMenu = newMenuBar;
2654 [newMenuBar release];
2657 NS_OBJC_END_TRY_IGNORE_BLOCK;
2660 - (id)initWithGeckoWindow:(nsCocoaWindow*)geckoWind {
2661 NS_OBJC_BEGIN_TRY_BLOCK_RETURN;
2664 mGeckoWindow = geckoWind;
2665 mToplevelActiveState = false;
2666 mHasEverBeenZoomed = false;
2669 NS_OBJC_END_TRY_BLOCK_RETURN(nil);
2672 - (NSSize)windowWillResize:(NSWindow*)sender toSize:(NSSize)proposedFrameSize {
2674 return proposedFrameSize;
2677 - (NSRect)windowWillUseStandardFrame:(NSWindow*)window
2678 defaultFrame:(NSRect)newFrame {
2679 // This function needs to return a rect representing the frame a window would
2680 // have if it is in its "maximized" size mode. The parameter newFrame is
2681 // supposed to be a frame representing the maximum window size on the screen
2682 // where the window currently appears. However, in practice, newFrame can be a
2683 // much smaller size. So, we ignore newframe and instead return the frame of
2684 // the entire screen associated with the window. That frame is bigger than the
2685 // window could actually be, due to the presence of the menubar and possibly
2686 // the dock, but we never call this function directly, and Cocoa callers will
2687 // shrink it to its true maximum size.
2688 return window.screen.frame;
2691 void nsCocoaWindow::CocoaSendToplevelActivateEvents() {
2692 if (mWidgetListener) {
2693 mWidgetListener->WindowActivated();
2697 void nsCocoaWindow::CocoaSendToplevelDeactivateEvents() {
2698 if (mWidgetListener) {
2699 mWidgetListener->WindowDeactivated();
2703 void nsCocoaWindow::CocoaWindowDidResize() {
2704 // It's important to update our bounds before we trigger any listeners. This
2705 // ensures that our bounds are correct when GetScreenBounds is called.
2708 if (HandleUpdateFullscreenOnResize()) {
2713 // Resizing might have changed our zoom state.
2714 DispatchSizeModeEvent();
2718 - (void)windowDidResize:(NSNotification*)aNotification {
2719 if (!mGeckoWindow) return;
2721 mGeckoWindow->CocoaWindowDidResize();
2724 - (void)windowDidChangeScreen:(NSNotification*)aNotification {
2725 if (!mGeckoWindow) return;
2727 // Because of Cocoa's peculiar treatment of zero-size windows (see comments
2728 // at GetBackingScaleFactor() above), we sometimes have a situation where
2729 // our concept of backing scale (based on the screen where the zero-sized
2730 // window is positioned) differs from Cocoa's idea (always based on the
2731 // Retina screen, AFAICT, even when an external non-Retina screen is the
2732 // primary display).
2734 // As a result, if the window was created with zero size on an external
2735 // display, but then made visible on the (secondary) Retina screen, we
2736 // will *not* get a windowDidChangeBackingProperties notification for it.
2737 // This leads to an incorrect GetDefaultScale(), and widget coordinate
2738 // confusion, as per bug 853252.
2740 // To work around this, we check for a backing scale mismatch when we
2741 // receive a windowDidChangeScreen notification, as we will receive this
2742 // even if Cocoa was already treating the zero-size window as having
2743 // Retina backing scale. Note that BackingScaleFactorChanged() bails early
2744 // if the scale factor did in fact not change.
2745 mGeckoWindow->BackingScaleFactorChanged();
2746 mGeckoWindow->ReportMoveEvent();
2749 - (void)windowWillEnterFullScreen:(NSNotification*)notification {
2750 if (!mGeckoWindow) {
2753 mGeckoWindow->CocoaWindowWillEnterFullscreen(true);
2756 // Lion's full screen mode will bypass our internal fullscreen tracking, so
2757 // we need to catch it when we transition and call our own methods, which in
2758 // turn will fire "fullscreen" events.
2759 - (void)windowDidEnterFullScreen:(NSNotification*)notification {
2760 // On Yosemite, the NSThemeFrame class has two new properties --
2761 // titlebarView (an NSTitlebarView object) and titlebarContainerView (an
2762 // NSTitlebarContainerView object). These are used to display the titlebar
2763 // in fullscreen mode. In Safari they're not transparent. But in Firefox
2764 // for some reason they are, which causes bug 1069658. The following code
2765 // works around this Apple bug or design flaw.
2766 NSWindow* window = notification.object;
2767 NSView* frameView = window.contentView.superview;
2768 NSView* titlebarView = nil;
2769 NSView* titlebarContainerView = nil;
2770 if ([frameView respondsToSelector:@selector(titlebarView)]) {
2771 titlebarView = [frameView titlebarView];
2773 if ([frameView respondsToSelector:@selector(titlebarContainerView)]) {
2774 titlebarContainerView = [frameView titlebarContainerView];
2776 if ([titlebarView respondsToSelector:@selector(setTransparent:)]) {
2777 [titlebarView setTransparent:NO];
2779 if ([titlebarContainerView respondsToSelector:@selector(setTransparent:)]) {
2780 [titlebarContainerView setTransparent:NO];
2783 if (@available(macOS 11.0, *)) {
2784 if ([window isKindOfClass:[ToolbarWindow class]]) {
2785 // In order to work around a drawing bug with windows in full screen
2786 // mode, disable titlebar separators for full screen windows of the
2787 // ToolbarWindow class. The drawing bug was filed as FB9056136. See bug
2788 // 1700211 and bug 1912338 for more details.
2789 window.titlebarSeparatorStyle = NSTitlebarSeparatorStyleNone;
2793 if (!mGeckoWindow) {
2796 mGeckoWindow->CocoaWindowDidEnterFullscreen(true);
2799 - (void)windowWillExitFullScreen:(NSNotification*)notification {
2800 if (!mGeckoWindow) {
2803 mGeckoWindow->CocoaWindowWillEnterFullscreen(false);
2806 - (void)windowDidExitFullScreen:(NSNotification*)notification {
2807 if (!mGeckoWindow) {
2810 mGeckoWindow->CocoaWindowDidEnterFullscreen(false);
2813 - (void)windowDidFailToEnterFullScreen:(NSNotification*)notification {
2814 if (!mGeckoWindow) {
2818 MOZ_ASSERT((mGeckoWindow->GetCocoaWindow().styleMask &
2819 NSWindowStyleMaskFullScreen) == 0);
2820 MOZ_ASSERT(mGeckoWindow->SizeMode() == nsSizeMode_Fullscreen);
2822 // We're in a strange situation. We've told DOM that we are going to
2823 // fullscreen by changing our size mode, and therefore the window
2824 // content is what we would show if we were properly in fullscreen.
2825 // But the window is actually in a windowed style. We have to do
2827 // 1) Clear sWindowInNativeTransition and mTransitionCurrent, both set
2828 // when we started the fullscreen transition.
2829 // 2) Change our size mode to windowed.
2830 // Conveniently, we can do these things by pretending we just arrived
2831 // at windowed mode, and all will be sorted out.
2832 mGeckoWindow->CocoaWindowDidEnterFullscreen(false);
2835 - (void)windowDidFailToExitFullScreen:(NSNotification*)notification {
2836 if (!mGeckoWindow) {
2839 // Similarly to windowDidFailToEnterFullScreen, we can get the right
2840 // result by pretending we just entered fullscreen.
2841 mGeckoWindow->CocoaWindowDidEnterFullscreen(true);
2844 - (void)windowDidBecomeMain:(NSNotification*)aNotification {
2845 NS_OBJC_BEGIN_TRY_IGNORE_BLOCK;
2848 ChildViewMouseTracker::ReEvaluateMouseEnterState();
2850 // [NSApp _isRunningAppModal] will return true if we're running an OS dialog
2851 // app modally. If one of those is up then we want it to retain its menu bar.
2852 if (NSApp._isRunningAppModal) {
2855 NSWindow* window = aNotification.object;
2857 [WindowDelegate paintMenubarForWindow:window];
2860 if ([window isKindOfClass:[ToolbarWindow class]]) {
2861 [(ToolbarWindow*)window windowMainStateChanged];
2864 NS_OBJC_END_TRY_IGNORE_BLOCK;
2867 - (void)windowDidResignMain:(NSNotification*)aNotification {
2869 ChildViewMouseTracker::ReEvaluateMouseEnterState();
2871 // [NSApp _isRunningAppModal] will return true if we're running an OS dialog
2872 // app modally. If one of those is up then we want it to retain its menu bar.
2873 if ([NSApp _isRunningAppModal]) return;
2874 RefPtr<nsMenuBarX> hiddenWindowMenuBar =
2875 nsMenuUtilsX::GetHiddenWindowMenuBar();
2876 if (hiddenWindowMenuBar) {
2877 // We do an async paint in order to prevent crashes when macOS is actively
2878 // enumerating the menu items in `NSApp.mainMenu`.
2879 hiddenWindowMenuBar->PaintAsync();
2882 NSWindow* window = [aNotification object];
2883 if ([window isKindOfClass:[ToolbarWindow class]]) {
2884 [(ToolbarWindow*)window windowMainStateChanged];
2888 - (void)windowDidBecomeKey:(NSNotification*)aNotification {
2889 NS_OBJC_BEGIN_TRY_IGNORE_BLOCK;
2892 ChildViewMouseTracker::ReEvaluateMouseEnterState();
2894 NSWindow* window = [aNotification object];
2895 auto* mainChildView =
2896 static_cast<nsChildView*>([[(BaseWindow*)window mainChildView] widget]);
2897 if (mainChildView) {
2898 if (mainChildView->GetInputContext().IsPasswordEditor()) {
2899 TextInputHandler::EnableSecureEventInput();
2901 TextInputHandler::EnsureSecureEventInputDisabled();
2905 NS_OBJC_END_TRY_IGNORE_BLOCK;
2908 - (void)windowDidResignKey:(NSNotification*)aNotification {
2909 NS_OBJC_BEGIN_TRY_IGNORE_BLOCK;
2911 RollUpPopups(nsIRollupListener::AllowAnimations::No);
2913 ChildViewMouseTracker::ReEvaluateMouseEnterState();
2914 TextInputHandler::EnsureSecureEventInputDisabled();
2916 NS_OBJC_END_TRY_IGNORE_BLOCK;
2919 - (void)windowWillMove:(NSNotification*)aNotification {
2923 - (void)windowDidMove:(NSNotification*)aNotification {
2924 if (mGeckoWindow) mGeckoWindow->ReportMoveEvent();
2927 - (BOOL)windowShouldClose:(id)sender {
2928 nsIWidgetListener* listener =
2929 mGeckoWindow ? mGeckoWindow->GetWidgetListener() : nullptr;
2930 if (listener) listener->RequestWindowClose(mGeckoWindow);
2931 return NO; // gecko will do it
2934 - (void)windowWillClose:(NSNotification*)aNotification {
2938 - (void)windowWillMiniaturize:(NSNotification*)aNotification {
2942 - (void)windowDidMiniaturize:(NSNotification*)aNotification {
2943 if (!mGeckoWindow) {
2946 mGeckoWindow->FinishCurrentTransitionIfMatching(
2947 nsCocoaWindow::TransitionType::Miniaturize);
2950 - (void)windowDidDeminiaturize:(NSNotification*)aNotification {
2951 if (!mGeckoWindow) {
2954 mGeckoWindow->FinishCurrentTransitionIfMatching(
2955 nsCocoaWindow::TransitionType::Deminiaturize);
2958 - (BOOL)windowShouldZoom:(NSWindow*)window toFrame:(NSRect)proposedFrame {
2959 if (!mHasEverBeenZoomed && window.isZoomed) {
2960 return NO; // See bug 429954.
2962 mHasEverBeenZoomed = YES;
2966 - (void)windowDidChangeBackingProperties:(NSNotification*)aNotification {
2967 NS_OBJC_BEGIN_TRY_IGNORE_BLOCK;
2969 mGeckoWindow->BackingScaleFactorChanged();
2971 NS_OBJC_END_TRY_IGNORE_BLOCK;
2974 // This method is on NSWindowDelegate starting with 10.9
2975 - (void)windowDidChangeOcclusionState:(NSNotification*)aNotification {
2977 mGeckoWindow->DispatchOcclusionEvent();
2981 - (nsCocoaWindow*)geckoWidget {
2982 return mGeckoWindow;
2985 - (bool)toplevelActiveState {
2986 return mToplevelActiveState;
2989 - (void)sendToplevelActivateEvents {
2990 if (!mToplevelActiveState && mGeckoWindow) {
2991 mGeckoWindow->CocoaSendToplevelActivateEvents();
2993 mToplevelActiveState = true;
2997 - (void)sendToplevelDeactivateEvents {
2998 if (mToplevelActiveState && mGeckoWindow) {
2999 mGeckoWindow->CocoaSendToplevelDeactivateEvents();
3000 mToplevelActiveState = false;
3006 @interface NSView (FrameViewMethodSwizzling)
3007 - (NSPoint)FrameView__closeButtonOrigin;
3008 - (CGFloat)FrameView__titlebarHeight;
3011 @implementation NSView (FrameViewMethodSwizzling)
3013 - (NSPoint)FrameView__closeButtonOrigin {
3014 if (![self.window isKindOfClass:[ToolbarWindow class]]) {
3015 return self.FrameView__closeButtonOrigin;
3017 auto* win = static_cast<ToolbarWindow*>(self.window);
3018 if (win.drawsContentsIntoWindowFrame && !win.wantsTitleDrawn &&
3019 !(win.styleMask & NSWindowStyleMaskFullScreen) &&
3020 (win.styleMask & NSWindowStyleMaskTitled)) {
3021 const NSRect buttonsRect = win.windowButtonsRect;
3022 if (NSIsEmptyRect(buttonsRect)) {
3023 // Empty rect. Let's hide the buttons.
3024 // Position is in non-flipped window coordinates. Using frame's height
3025 // for the vertical coordinate will move the buttons above the window,
3026 // making them invisible.
3027 return NSMakePoint(buttonsRect.origin.x, win.frame.size.height);
3029 if (win.windowTitlebarLayoutDirection ==
3030 NSUserInterfaceLayoutDirectionRightToLeft) {
3031 // We're in RTL mode, which means that the close button is the rightmost
3032 // button of the three window buttons. and buttonsRect.origin is the
3033 // bottom left corner of the green (zoom) button. The close button is 40px
3034 // to the right of the zoom button. This is confirmed to be the same on
3035 // all macOS versions between 10.12 - 12.0.
3036 return NSMakePoint(buttonsRect.origin.x + 40.0f, buttonsRect.origin.y);
3038 return buttonsRect.origin;
3040 return self.FrameView__closeButtonOrigin;
3043 - (CGFloat)FrameView__titlebarHeight {
3044 // XXX: Shouldn't this be [super FrameView__titlebarHeight]?
3045 CGFloat height = [self FrameView__titlebarHeight];
3046 if ([self.window isKindOfClass:[ToolbarWindow class]]) {
3047 // Make sure that the titlebar height includes our shifted buttons.
3048 // The following coordinates are in window space, with the origin being at
3049 // the bottom left corner of the window.
3050 auto* win = static_cast<ToolbarWindow*>(self.window);
3051 CGFloat frameHeight = self.frame.size.height;
3052 CGFloat windowButtonY = frameHeight;
3053 if (!NSIsEmptyRect(win.windowButtonsRect) &&
3054 win.drawsContentsIntoWindowFrame &&
3055 !(win.styleMask & NSWindowStyleMaskFullScreen) &&
3056 (win.styleMask & NSWindowStyleMaskTitled)) {
3057 windowButtonY = win.windowButtonsRect.origin.y;
3059 height = std::max(height, frameHeight - windowButtonY);
3066 static NSMutableSet* gSwizzledFrameViewClasses = nil;
3068 @interface NSWindow (PrivateSetNeedsDisplayInRectMethod)
3069 - (void)_setNeedsDisplayInRect:(NSRect)aRect;
3072 @interface BaseWindow (Private)
3073 - (void)cursorUpdated:(NSEvent*)aEvent;
3074 - (void)reflowTitlebarElements;
3077 @implementation BaseWindow
3079 // The frame of a window is implemented using undocumented NSView subclasses.
3080 // We offset the window buttons by overriding the method _closeButtonOrigin on
3081 // these frame view classes. The class which is
3082 // used for a window is determined in the window's frameViewClassForStyleMask:
3083 // method, so this is where we make sure that we have swizzled the method on
3084 // all encountered classes.
3085 + (Class)frameViewClassForStyleMask:(NSUInteger)styleMask {
3086 Class frameViewClass = [super frameViewClassForStyleMask:styleMask];
3088 if (!gSwizzledFrameViewClasses) {
3089 gSwizzledFrameViewClasses = [[NSMutableSet setWithCapacity:3] retain];
3090 if (!gSwizzledFrameViewClasses) {
3091 return frameViewClass;
3095 MOZ_RUNINIT static IMP our_closeButtonOrigin = class_getMethodImplementation(
3096 [NSView class], @selector(FrameView__closeButtonOrigin));
3097 MOZ_RUNINIT static IMP our_titlebarHeight = class_getMethodImplementation(
3098 [NSView class], @selector(FrameView__titlebarHeight));
3100 if (![gSwizzledFrameViewClasses containsObject:frameViewClass]) {
3101 // Either of these methods might be implemented in both a subclass of
3102 // NSFrameView and one of its own subclasses. Which means that if we
3103 // aren't careful we might end up swizzling the same method twice.
3104 // Since method swizzling involves swapping pointers, this would break
3106 IMP _closeButtonOrigin = class_getMethodImplementation(
3107 frameViewClass, @selector(_closeButtonOrigin));
3108 if (_closeButtonOrigin && _closeButtonOrigin != our_closeButtonOrigin) {
3109 nsToolkit::SwizzleMethods(frameViewClass, @selector(_closeButtonOrigin),
3110 @selector(FrameView__closeButtonOrigin));
3113 // Override _titlebarHeight so that the floating titlebar doesn't clip the
3114 // bottom of the window buttons which we move down with our override of
3115 // _closeButtonOrigin.
3116 IMP _titlebarHeight = class_getMethodImplementation(
3117 frameViewClass, @selector(_titlebarHeight));
3118 if (_titlebarHeight && _titlebarHeight != our_titlebarHeight) {
3119 nsToolkit::SwizzleMethods(frameViewClass, @selector(_titlebarHeight),
3120 @selector(FrameView__titlebarHeight));
3123 [gSwizzledFrameViewClasses addObject:frameViewClass];
3126 return frameViewClass;
3129 - (id)initWithContentRect:(NSRect)aContentRect
3130 styleMask:(NSUInteger)aStyle
3131 backing:(NSBackingStoreType)aBufferingType
3133 mDrawsIntoWindowFrame = NO;
3134 [super initWithContentRect:aContentRect
3136 backing:aBufferingType
3139 mDisabledNeedsDisplay = NO;
3140 mTrackingArea = nil;
3141 mViewWithTrackingArea = nil;
3142 mDirtyRect = NSZeroRect;
3146 mIsAnimationSuppressed = NO;
3151 // Returns an autoreleased NSImage.
3152 static NSImage* GetMenuMaskImage() {
3153 const CGFloat radius = 6.0f;
3154 const NSSize maskSize = {radius * 3.0f, radius * 3.0f};
3155 NSImage* maskImage = [NSImage imageWithSize:maskSize
3157 drawingHandler:^BOOL(NSRect dstRect) {
3158 NSBezierPath* path = [NSBezierPath
3159 bezierPathWithRoundedRect:dstRect
3162 [NSColor.blackColor set];
3166 maskImage.capInsets = NSEdgeInsetsMake(radius, radius, radius, radius);
3170 // Add an effect view wrapper if needed so that the OS draws the appropriate
3171 // vibrancy effect and window border.
3172 - (void)setEffectViewWrapperForStyle:(WindowShadow)aStyle {
3173 NSView* wrapper = [&]() -> NSView* {
3174 if (aStyle == WindowShadow::Menu || aStyle == WindowShadow::Tooltip) {
3175 const bool isMenu = aStyle == WindowShadow::Menu;
3177 [[NSVisualEffectView alloc] initWithFrame:self.contentView.frame];
3178 effectView.material =
3179 isMenu ? NSVisualEffectMaterialMenu : NSVisualEffectMaterialToolTip;
3180 // Tooltip and menu windows are never "key", so we need to tell the
3181 // vibrancy effect to look active regardless of window state.
3182 effectView.state = NSVisualEffectStateActive;
3183 effectView.blendingMode = NSVisualEffectBlendingModeBehindWindow;
3185 // Turn on rounded corner masking.
3186 effectView.maskImage = GetMenuMaskImage();
3190 return [[NSView alloc] initWithFrame:self.contentView.frame];
3193 wrapper.wantsLayer = YES;
3194 // Swap out our content view by the new view. Setting .contentView releases
3196 NSView* childView = [self.mainChildView retain];
3197 [childView removeFromSuperview];
3198 [wrapper addSubview:childView];
3199 [childView release];
3200 super.contentView = wrapper;
3204 - (NSTouchBar*)makeTouchBar {
3205 mTouchBar = [[nsTouchBar alloc] init];
3207 sTouchBarIsInitialized = YES;
3212 - (void)setBeingShown:(BOOL)aValue {
3213 mBeingShown = aValue;
3216 - (BOOL)isBeingShown {
3220 - (BOOL)isVisibleOrBeingShown {
3221 return [super isVisible] || mBeingShown;
3224 - (void)setIsAnimationSuppressed:(BOOL)aValue {
3225 mIsAnimationSuppressed = aValue;
3228 - (BOOL)isAnimationSuppressed {
3229 return mIsAnimationSuppressed;
3232 - (void)disableSetNeedsDisplay {
3233 mDisabledNeedsDisplay = YES;
3236 - (void)enableSetNeedsDisplay {
3237 mDisabledNeedsDisplay = NO;
3241 [mTouchBar release];
3242 ChildViewMouseTracker::OnDestroyWindow(self);
3246 static const NSString* kStateTitleKey = @"title";
3247 static const NSString* kStateDrawsContentsIntoWindowFrameKey =
3248 @"drawsContentsIntoWindowFrame";
3249 static const NSString* kStateShowsToolbarButton = @"showsToolbarButton";
3250 static const NSString* kStateCollectionBehavior = @"collectionBehavior";
3251 static const NSString* kStateWantsTitleDrawn = @"wantsTitleDrawn";
3253 - (void)importState:(NSDictionary*)aState {
3254 if (NSString* title = [aState objectForKey:kStateTitleKey]) {
3255 [self setTitle:title];
3257 [self setDrawsContentsIntoWindowFrame:
3258 [[aState objectForKey:kStateDrawsContentsIntoWindowFrameKey]
3260 [self setShowsToolbarButton:[[aState objectForKey:kStateShowsToolbarButton]
3262 [self setCollectionBehavior:[[aState objectForKey:kStateCollectionBehavior]
3264 [self setWantsTitleDrawn:[[aState objectForKey:kStateWantsTitleDrawn]
3268 - (NSMutableDictionary*)exportState {
3269 NSMutableDictionary* state = [NSMutableDictionary dictionaryWithCapacity:10];
3270 if (NSString* title = self.title) {
3271 [state setObject:title forKey:kStateTitleKey];
3273 [state setObject:[NSNumber numberWithBool:self.drawsContentsIntoWindowFrame]
3274 forKey:kStateDrawsContentsIntoWindowFrameKey];
3275 [state setObject:[NSNumber numberWithBool:self.showsToolbarButton]
3276 forKey:kStateShowsToolbarButton];
3277 [state setObject:[NSNumber numberWithUnsignedInt:self.collectionBehavior]
3278 forKey:kStateCollectionBehavior];
3279 [state setObject:[NSNumber numberWithBool:self.wantsTitleDrawn]
3280 forKey:kStateWantsTitleDrawn];
3284 - (void)setDrawsContentsIntoWindowFrame:(BOOL)aState {
3285 bool changed = aState != mDrawsIntoWindowFrame;
3286 mDrawsIntoWindowFrame = aState;
3288 [self reflowTitlebarElements];
3292 - (BOOL)drawsContentsIntoWindowFrame {
3293 return mDrawsIntoWindowFrame;
3296 - (NSRect)childViewRectForFrameRect:(NSRect)aFrameRect {
3297 if (mDrawsIntoWindowFrame) {
3300 NSUInteger styleMask = [self styleMask];
3301 styleMask &= ~NSWindowStyleMaskFullSizeContentView;
3302 return [NSWindow contentRectForFrameRect:aFrameRect styleMask:styleMask];
3305 - (NSRect)frameRectForChildViewRect:(NSRect)aChildViewRect {
3306 if (mDrawsIntoWindowFrame) {
3307 return aChildViewRect;
3309 NSUInteger styleMask = [self styleMask];
3310 styleMask &= ~NSWindowStyleMaskFullSizeContentView;
3311 return [NSWindow frameRectForContentRect:aChildViewRect styleMask:styleMask];
3314 - (NSTimeInterval)animationResizeTime:(NSRect)newFrame {
3315 if (mIsAnimationSuppressed) {
3316 // Should not animate the initial session-restore size change
3320 return [super animationResizeTime:newFrame];
3323 - (void)setWantsTitleDrawn:(BOOL)aDrawTitle {
3324 mDrawTitle = aDrawTitle;
3325 [self setTitleVisibility:mDrawTitle ? NSWindowTitleVisible
3326 : NSWindowTitleHidden];
3329 - (BOOL)wantsTitleDrawn {
3333 - (NSView*)trackingAreaView {
3334 NSView* contentView = self.contentView;
3335 return contentView.superview ? contentView.superview : contentView;
3338 - (NSArray<NSView*>*)contentViewContents {
3339 return [[self.contentView.subviews copy] autorelease];
3342 - (ChildView*)mainChildView {
3343 NSView* contentView = self.contentView;
3344 NSView* lastView = contentView.subviews.lastObject;
3345 if ([lastView isKindOfClass:[ChildView class]]) {
3346 return (ChildView*)lastView;
3351 - (void)removeTrackingArea {
3352 [mViewWithTrackingArea removeTrackingArea:mTrackingArea];
3354 [mTrackingArea release];
3355 mTrackingArea = nil;
3357 [mViewWithTrackingArea release];
3358 mViewWithTrackingArea = nil;
3361 - (void)createTrackingArea {
3362 mViewWithTrackingArea = [self.trackingAreaView retain];
3363 const NSTrackingAreaOptions options =
3364 NSTrackingMouseEnteredAndExited | NSTrackingMouseMoved |
3365 NSTrackingActiveAlways | NSTrackingInVisibleRect;
3367 [[NSTrackingArea alloc] initWithRect:[mViewWithTrackingArea bounds]
3371 [mViewWithTrackingArea addTrackingArea:mTrackingArea];
3374 - (void)mouseEntered:(NSEvent*)aEvent {
3375 ChildViewMouseTracker::MouseEnteredWindow(aEvent);
3378 - (void)mouseExited:(NSEvent*)aEvent {
3379 ChildViewMouseTracker::MouseExitedWindow(aEvent);
3382 - (void)mouseMoved:(NSEvent*)aEvent {
3383 ChildViewMouseTracker::MouseMoved(aEvent);
3386 - (void)cursorUpdated:(NSEvent*)aEvent {
3387 // Nothing to do here, but NSTrackingArea wants us to implement this method.
3390 - (void)_setNeedsDisplayInRect:(NSRect)aRect {
3391 // Prevent unnecessary invalidations due to moving NSViews (e.g. for plugins)
3392 if (!mDisabledNeedsDisplay) {
3393 // This method is only called by Cocoa, so when we're here, we know that
3394 // it's available and don't need to check whether our superclass responds
3396 [super _setNeedsDisplayInRect:aRect];
3397 mDirtyRect = NSUnionRect(mDirtyRect, aRect);
3401 - (NSRect)getAndResetNativeDirtyRect {
3402 NSRect dirtyRect = mDirtyRect;
3403 mDirtyRect = NSZeroRect;
3407 // Possibly move the titlebar buttons.
3408 - (void)reflowTitlebarElements {
3409 NSView* frameView = self.contentView.superview;
3410 if ([frameView respondsToSelector:@selector(_tileTitlebarAndRedisplay:)]) {
3411 [frameView _tileTitlebarAndRedisplay:NO];
3415 - (BOOL)respondsToSelector:(SEL)aSelector {
3416 // Claim the window doesn't respond to this so that the system
3417 // doesn't steal keyboard equivalents for it. Bug 613710.
3418 if (aSelector == @selector(cancelOperation:)) {
3422 return [super respondsToSelector:aSelector];
3425 - (void)doCommandBySelector:(SEL)aSelector {
3426 // We override this so that it won't beep if it can't act.
3427 // We want to control the beeping for missing or disabled
3428 // commands ourselves.
3429 [self tryToPerform:aSelector with:nil];
3432 - (id)accessibilityAttributeValue:(NSString*)attribute {
3433 NS_OBJC_BEGIN_TRY_BLOCK_RETURN;
3435 id retval = [super accessibilityAttributeValue:attribute];
3437 // The following works around a problem with Text-to-Speech on OS X 10.7.
3438 // See bug 674612 for more info.
3440 // When accessibility is off, AXUIElementCopyAttributeValue(), when called
3441 // on an AXApplication object to get its AXFocusedUIElement attribute,
3442 // always returns an AXWindow object (the actual browser window -- never a
3443 // mozAccessible object). This also happens with accessibility turned on,
3444 // if no other object in the browser window has yet been focused. But if
3445 // the browser window has a title bar (as it currently always does), the
3446 // AXWindow object will always have four "accessible" children, one of which
3447 // is an AXStaticText object (the title bar's "title"; the other three are
3448 // the close, minimize and zoom buttons). This means that (for complicated
3449 // reasons, for which see bug 674612) Text-to-Speech on OS X 10.7 will often
3450 // "speak" the window title, no matter what text is selected, or even if no
3451 // text at all is selected. (This always happens when accessibility is off.
3452 // It doesn't happen in Firefox releases because Apple has (on OS X 10.7)
3453 // special-cased the handling of apps whose CFBundleIdentifier is
3454 // org.mozilla.firefox.)
3456 // We work around this problem by only returning AXChildren that are
3457 // mozAccessible object or are one of the titlebar's buttons (which
3458 // instantiate subclasses of NSButtonCell).
3459 if ([retval isKindOfClass:[NSArray class]] &&
3460 [attribute isEqualToString:@"AXChildren"]) {
3461 NSMutableArray* holder = [NSMutableArray arrayWithCapacity:10];
3462 [holder addObjectsFromArray:(NSArray*)retval];
3463 NSUInteger count = [holder count];
3464 for (NSInteger i = count - 1; i >= 0; --i) {
3465 id item = [holder objectAtIndex:i];
3466 // Remove anything from holder that isn't one of the titlebar's buttons
3467 // (which instantiate subclasses of NSButtonCell) or a mozAccessible
3468 // object (or one of its subclasses).
3469 if (![item isKindOfClass:[NSButtonCell class]] &&
3470 ![item respondsToSelector:@selector(hasRepresentedView)]) {
3471 [holder removeObjectAtIndex:i];
3474 retval = [NSArray arrayWithArray:holder];
3479 NS_OBJC_END_TRY_BLOCK_RETURN(nil);
3482 - (void)releaseJSObjects {
3483 [mTouchBar releaseJSObjects];
3488 @interface MOZTitlebarAccessoryView : NSView
3491 @implementation MOZTitlebarAccessoryView : NSView
3492 - (void)viewWillMoveToWindow:(NSWindow*)aWindow {
3494 // When entering full screen mode, titlebar accessory views are inserted
3495 // into a floating NSWindow which houses the window titlebar and toolbars.
3496 // In order to work around a drawing bug with windows in full screen mode,
3497 // disable titlebar separators for all NSWindows that this view is used in
3498 // that are not of the ToolbarWindow class, such as the floating full
3499 // screen toolbar window. The drawing bug was filed as FB9056136. See bug
3500 // 1700211 and bug 1912338 for more details.
3501 if (@available(macOS 11.0, *)) {
3502 aWindow.titlebarSeparatorStyle =
3503 [aWindow isKindOfClass:[ToolbarWindow class]]
3504 ? NSTitlebarSeparatorStyleAutomatic
3505 : NSTitlebarSeparatorStyleNone;
3511 @implementation FullscreenTitlebarTracker
3512 - (FullscreenTitlebarTracker*)init {
3519 [[[MOZTitlebarAccessoryView alloc] initWithFrame:NSZeroRect] autorelease];
3523 // Drop all mouse events if a modal window has appeared above us.
3524 // This helps make us behave as if the OS were running a "real" modal event
3526 static bool MaybeDropEventForModalWindow(NSEvent* aEvent, id aDelegate) {
3527 if (!sModalWindowCount) {
3531 NSEventType type = [aEvent type];
3533 case NSEventTypeScrollWheel:
3534 case NSEventTypeLeftMouseDown:
3535 case NSEventTypeLeftMouseUp:
3536 case NSEventTypeRightMouseDown:
3537 case NSEventTypeRightMouseUp:
3538 case NSEventTypeOtherMouseDown:
3539 case NSEventTypeOtherMouseUp:
3540 case NSEventTypeMouseMoved:
3541 case NSEventTypeLeftMouseDragged:
3542 case NSEventTypeRightMouseDragged:
3543 case NSEventTypeOtherMouseDragged:
3549 if (aDelegate && [aDelegate isKindOfClass:[WindowDelegate class]]) {
3550 if (nsCocoaWindow* widget = [(WindowDelegate*)aDelegate geckoWidget]) {
3551 if (!widget->IsModal() || widget->HasModalDescendants()) {
3559 @implementation ToolbarWindow
3561 - (id)initWithContentRect:(NSRect)aChildViewRect
3562 styleMask:(NSUInteger)aStyle
3563 backing:(NSBackingStoreType)aBufferingType
3565 NS_OBJC_BEGIN_TRY_BLOCK_RETURN;
3567 // We treat aChildViewRect as the rectangle that the window's main ChildView
3568 // should be sized to. Get the right frameRect for the requested child view
3570 NSRect frameRect = [NSWindow frameRectForContentRect:aChildViewRect
3573 // Always size the content view to the full frame size of the window.
3574 // We do this even if we want this window to have a titlebar; in that case,
3575 // the window's content view covers the entire window but the ChildView inside
3576 // it will only cover the content area. We do this so that we can render the
3577 // titlebar gradient manually, with a subview of our content view that's
3578 // positioned in the titlebar area. This lets us have a smooth connection
3579 // between titlebar and toolbar gradient in case the window has a "unified
3580 // toolbar + titlebar" look. Moreover, always using a full size content view
3581 // lets us toggle the titlebar on and off without changing the window's style
3582 // mask (which would have other subtle effects, for example on keyboard
3584 aStyle |= NSWindowStyleMaskFullSizeContentView;
3586 // -[NSWindow initWithContentRect:styleMask:backing:defer:] calls
3587 // [self frameRectForContentRect:styleMask:] to convert the supplied content
3588 // rect to the window's frame rect. We've overridden that method to be a
3589 // pass-through function. So, in order to get the intended frameRect, we need
3590 // to supply frameRect itself as the "content rect".
3591 NSRect contentRect = frameRect;
3593 if ((self = [super initWithContentRect:contentRect
3595 backing:aBufferingType
3597 mWindowButtonsRect = NSZeroRect;
3599 mFullscreenTitlebarTracker = [[FullscreenTitlebarTracker alloc] init];
3600 // revealAmount is an undocumented property of
3601 // NSTitlebarAccessoryViewController that updates whenever the menubar
3602 // slides down in fullscreen mode.
3603 [mFullscreenTitlebarTracker addObserver:self
3604 forKeyPath:@"revealAmount"
3605 options:NSKeyValueObservingOptionNew
3607 // Adding this accessory view controller allows us to shift the toolbar down
3608 // when the user mouses to the top of the screen in fullscreen.
3610 addTitlebarAccessoryViewController:mFullscreenTitlebarTracker];
3614 NS_OBJC_END_TRY_BLOCK_RETURN(nil);
3617 - (void)observeValueForKeyPath:(NSString*)keyPath
3619 change:(NSDictionary<NSKeyValueChangeKey, id>*)change
3620 context:(void*)context {
3621 if ([keyPath isEqualToString:@"revealAmount"]) {
3622 [[self mainChildView] ensureNextCompositeIsAtomicWithMainThreadPaint];
3623 NSNumber* revealAmount = (change[NSKeyValueChangeNewKey]);
3624 [self updateTitlebarShownAmount:[revealAmount doubleValue]];
3626 [super observeValueForKeyPath:keyPath
3633 static bool ScreenHasNotch(nsCocoaWindow* aGeckoWindow) {
3634 if (@available(macOS 12.0, *)) {
3635 nsCOMPtr<nsIScreen> widgetScreen = aGeckoWindow->GetWidgetScreen();
3636 NSScreen* cocoaScreen =
3637 ScreenHelperCocoa::CocoaScreenForScreen(widgetScreen);
3638 return cocoaScreen.safeAreaInsets.top != 0.0f;
3643 static bool ShouldShiftByMenubarHeightInFullscreen(nsCocoaWindow* aWindow) {
3644 switch (StaticPrefs::widget_macos_shift_by_menubar_on_fullscreen()) {
3652 return !ScreenHasNotch(aWindow) &&
3653 ![NSUserDefaults.standardUserDefaults
3654 integerForKey:@"AppleMenuBarVisibleInFullscreen"];
3657 - (void)updateTitlebarShownAmount:(CGFloat)aShownAmount {
3658 if (!(self.styleMask & NSWindowStyleMaskFullScreen)) {
3659 // We are not interested in the size of the titlebar unless we are in
3664 // [NSApp mainMenu] menuBarHeight] returns one of two values: the full height
3665 // if the menubar is shown or is in the process of being shown, and 0
3666 // otherwise. Since we are multiplying the menubar height by aShownAmount, we
3667 // always want the full height.
3668 CGFloat menuBarHeight = NSApp.mainMenu.menuBarHeight;
3669 if (menuBarHeight > 0.0f) {
3670 mMenuBarHeight = menuBarHeight;
3672 if ([[self delegate] isKindOfClass:[WindowDelegate class]]) {
3673 WindowDelegate* windowDelegate = (WindowDelegate*)[self delegate];
3674 nsCocoaWindow* geckoWindow = [windowDelegate geckoWidget];
3679 if (nsIWidgetListener* listener = geckoWindow->GetWidgetListener()) {
3680 // titlebarHeight returns 0 when we're in fullscreen, return the default
3682 CGFloat shiftByPixels =
3683 LookAndFeel::GetInt(LookAndFeel::IntID::MacTitlebarHeight) *
3685 if (ShouldShiftByMenubarHeightInFullscreen(geckoWindow)) {
3686 shiftByPixels += mMenuBarHeight * aShownAmount;
3688 // Use desktop pixels rather than the DesktopToLayoutDeviceScale in
3689 // nsCocoaWindow. The latter accounts for screen DPI. We don't want that
3690 // because the revealAmount property already accounts for it, so we'd be
3691 // compounding DPI scales > 1.
3692 listener->MacFullscreenMenubarOverlapChanged(DesktopCoord(shiftByPixels));
3698 [mFullscreenTitlebarTracker removeObserver:self forKeyPath:@"revealAmount"];
3699 [mFullscreenTitlebarTracker removeFromParentViewController];
3700 [mFullscreenTitlebarTracker release];
3705 - (NSArray<NSView*>*)contentViewContents {
3706 return [[self.contentView.subviews copy] autorelease];
3709 - (void)windowMainStateChanged {
3710 [[self mainChildView] ensureNextCompositeIsAtomicWithMainThreadPaint];
3713 // Extending the content area into the title bar works by resizing the
3714 // mainChildView so that it covers the titlebar.
3715 - (void)setDrawsContentsIntoWindowFrame:(BOOL)aState {
3716 BOOL stateChanged = self.drawsContentsIntoWindowFrame != aState;
3717 [super setDrawsContentsIntoWindowFrame:aState];
3718 if (stateChanged && [self.delegate isKindOfClass:[WindowDelegate class]]) {
3719 // Hide the titlebar if we are drawing into it
3720 self.titlebarAppearsTransparent = self.drawsContentsIntoWindowFrame;
3722 // Here we extend / shrink our mainChildView. We do that by firing a resize
3723 // event which will cause the ChildView to be resized to the rect returned
3724 // by nsCocoaWindow::GetClientBounds. GetClientBounds bases its return
3725 // value on what we return from drawsContentsIntoWindowFrame.
3726 auto* windowDelegate = static_cast<WindowDelegate*>(self.delegate);
3727 if (nsCocoaWindow* geckoWindow = windowDelegate.geckoWidget) {
3728 // Re-layout our contents.
3729 geckoWindow->ReportSizeEvent();
3732 // Resizing the content area causes a reflow which would send a synthesized
3733 // mousemove event to the old mouse position relative to the top left
3734 // corner of the content area. But the mouse has shifted relative to the
3735 // content area, so that event would have wrong position information. So
3736 // we'll send a mouse move event with the correct new position.
3737 ChildViewMouseTracker::ResendLastMouseMoveEvent();
3741 - (void)placeWindowButtons:(NSRect)aRect {
3742 if (!NSEqualRects(mWindowButtonsRect, aRect)) {
3743 mWindowButtonsRect = aRect;
3744 [self reflowTitlebarElements];
3748 - (NSRect)windowButtonsRect {
3749 return mWindowButtonsRect;
3752 // Returning YES here makes the setShowsToolbarButton method work even though
3753 // the window doesn't contain an NSToolbar.
3754 - (BOOL)_hasToolbar {
3758 // Dispatch a toolbar pill button clicked message to Gecko.
3759 - (void)_toolbarPillButtonClicked:(id)sender {
3760 NS_OBJC_BEGIN_TRY_IGNORE_BLOCK;
3764 if ([self.delegate isKindOfClass:[WindowDelegate class]]) {
3765 auto* windowDelegate = static_cast<WindowDelegate*>(self.delegate);
3766 nsCocoaWindow* geckoWindow = windowDelegate.geckoWidget;
3771 if (nsIWidgetListener* listener = geckoWindow->GetWidgetListener()) {
3772 listener->OSToolbarButtonPressed();
3776 NS_OBJC_END_TRY_IGNORE_BLOCK;
3779 // Retain and release "self" to avoid crashes when our widget (and its native
3780 // window) is closed as a result of processing a key equivalent (e.g.
3781 // Command+w or Command+q). This workaround is only needed for a window
3782 // that can become key.
3783 - (BOOL)performKeyEquivalent:(NSEvent*)theEvent {
3784 NS_OBJC_BEGIN_TRY_BLOCK_RETURN;
3786 NSWindow* nativeWindow = [self retain];
3787 BOOL retval = [super performKeyEquivalent:theEvent];
3788 [nativeWindow release];
3791 NS_OBJC_END_TRY_BLOCK_RETURN(NO);
3794 - (void)sendEvent:(NSEvent*)anEvent {
3795 if (MaybeDropEventForModalWindow(anEvent, self.delegate)) {
3798 [super sendEvent:anEvent];
3803 @implementation PopupWindow
3805 - (id)initWithContentRect:(NSRect)contentRect
3806 styleMask:(NSUInteger)styleMask
3807 backing:(NSBackingStoreType)bufferingType
3808 defer:(BOOL)deferCreation {
3809 NS_OBJC_BEGIN_TRY_BLOCK_RETURN;
3811 mIsContextMenu = false;
3812 return [super initWithContentRect:contentRect
3814 backing:bufferingType
3815 defer:deferCreation];
3817 NS_OBJC_END_TRY_BLOCK_RETURN(nil);
3820 // Override the private API _backdropBleedAmount. This determines how much the
3821 // desktop wallpaper contributes to the vibrancy backdrop.
3822 // Return 0 in order to match what the system does for sheet windows and
3823 // _NSPopoverWindows.
3824 - (CGFloat)_backdropBleedAmount {
3828 // Override the private API shadowOptions.
3829 // The constants below were found in AppKit's implementations of the
3830 // shadowOptions method on the various window types.
3831 static const NSUInteger kWindowShadowOptionsNoShadow = 0;
3832 static const NSUInteger kWindowShadowOptionsMenu = 2;
3833 static const NSUInteger kWindowShadowOptionsTooltip = 4;
3835 - (NSDictionary*)shadowParameters {
3836 NSDictionary* parent = [super shadowParameters];
3837 // NSLog(@"%@", parent);
3838 if (self.shadowStyle != WindowShadow::Panel) {
3841 NSMutableDictionary* copy = [parent mutableCopy];
3842 for (auto* key : {@"com.apple.WindowShadowRimDensityActive",
3843 @"com.apple.WindowShadowRimDensityInactive"}) {
3844 if ([parent objectForKey:key] != nil) {
3845 [copy setValue:@(0) forKey:key];
3851 - (NSUInteger)shadowOptions {
3852 if (!self.hasShadow) {
3853 return kWindowShadowOptionsNoShadow;
3856 switch (self.shadowStyle) {
3857 case WindowShadow::None:
3858 return kWindowShadowOptionsNoShadow;
3860 case WindowShadow::Menu:
3861 case WindowShadow::Panel:
3862 return kWindowShadowOptionsMenu;
3864 case WindowShadow::Tooltip:
3865 return kWindowShadowOptionsTooltip;
3869 - (BOOL)isContextMenu {
3870 return mIsContextMenu;
3873 - (void)setIsContextMenu:(BOOL)flag {
3874 mIsContextMenu = flag;
3877 - (BOOL)canBecomeMainWindow {
3878 // This is overriden because the default is 'yes' when a titlebar is present.
3884 // According to Apple's docs on [NSWindow canBecomeKeyWindow] and [NSWindow
3885 // canBecomeMainWindow], windows without a title bar or resize bar can't (by
3886 // default) become key or main. But if a window can't become key, it can't
3887 // accept keyboard input (bmo bug 393250). And it should also be possible for
3888 // an otherwise "ordinary" window to become main. We need to override these
3889 // two methods to make this happen.
3890 @implementation BorderlessWindow
3892 - (BOOL)canBecomeKeyWindow {
3896 - (void)sendEvent:(NSEvent*)anEvent {
3897 if (MaybeDropEventForModalWindow(anEvent, self.delegate)) {
3901 [super sendEvent:anEvent];
3904 // Apple's doc on this method says that the NSWindow class's default is not to
3905 // become main if the window isn't "visible" -- so we should replicate that
3906 // behavior here. As best I can tell, the [NSWindow isVisible] method is an
3907 // accurate test of what Apple means by "visibility".
3908 - (BOOL)canBecomeMainWindow {
3909 NS_OBJC_BEGIN_TRY_BLOCK_RETURN;
3911 return self.isVisible;
3913 NS_OBJC_END_TRY_BLOCK_RETURN(NO);
3916 // Retain and release "self" to avoid crashes when our widget (and its native
3917 // window) is closed as a result of processing a key equivalent (e.g.
3918 // Command+w or Command+q). This workaround is only needed for a window
3919 // that can become key.
3920 - (BOOL)performKeyEquivalent:(NSEvent*)theEvent {
3921 NS_OBJC_BEGIN_TRY_BLOCK_RETURN;
3923 NSWindow* nativeWindow = [self retain];
3924 BOOL retval = [super performKeyEquivalent:theEvent];
3925 [nativeWindow release];
3928 NS_OBJC_END_TRY_BLOCK_RETURN(NO);