Source code

Revision control

Copy as Markdown

Other Tools

/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=2 et sw=2 tw=80: */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at */
#include "nsCocoaWindow.h"
#include "AppearanceOverride.h"
#include "NativeKeyBindings.h"
#include "ScreenHelperCocoa.h"
#include "TextInputHandler.h"
#include "nsCocoaUtils.h"
#include "nsObjCExceptions.h"
#include "nsCOMPtr.h"
#include "nsWidgetsCID.h"
#include "nsIRollupListener.h"
#include "nsChildView.h"
#include "nsWindowMap.h"
#include "nsAppShell.h"
#include "nsIAppShellService.h"
#include "nsIBaseWindow.h"
#include "nsIInterfaceRequestorUtils.h"
#include "nsIAppWindow.h"
#include "nsToolkit.h"
#include "nsPIDOMWindow.h"
#include "nsThreadUtils.h"
#include "nsMenuBarX.h"
#include "nsMenuUtilsX.h"
#include "nsStyleConsts.h"
#include "nsNativeThemeColors.h"
#include "nsNativeThemeCocoa.h"
#include "nsChildView.h"
#include "nsCocoaFeatures.h"
#include "nsIScreenManager.h"
#include "nsIWidgetListener.h"
#include "nsXULPopupManager.h"
#include "VibrancyManager.h"
#include "nsPresContext.h"
#include "nsDocShell.h"
#include "gfxPlatform.h"
#include "qcms.h"
#include "mozilla/AutoRestore.h"
#include "mozilla/BasicEvents.h"
#include "mozilla/dom/Document.h"
#include "mozilla/Maybe.h"
#include "mozilla/NativeKeyBindingsType.h"
#include "mozilla/Preferences.h"
#include "mozilla/PresShell.h"
#include "mozilla/ScopeExit.h"
#include "mozilla/StaticPrefs_gfx.h"
#include "mozilla/StaticPrefs_widget.h"
#include "mozilla/WritingModes.h"
#include "mozilla/layers/CompositorBridgeChild.h"
#include "mozilla/widget/Screen.h"
#include <algorithm>
namespace mozilla {
namespace layers {
class LayerManager;
} // namespace layers
} // namespace mozilla
using namespace mozilla::layers;
using namespace mozilla::widget;
using namespace mozilla;
int32_t gXULModalLevel = 0;
// In principle there should be only one app-modal window at any given time.
// But sometimes, despite our best efforts, another window appears above the
// current app-modal window. So we need to keep a linked list of app-modal
// windows. (A non-sheet window that appears above an app-modal window is
// also made app-modal.) See nsCocoaWindow::SetModal().
nsCocoaWindowList* gGeckoAppModalWindowList = NULL;
BOOL sTouchBarIsInitialized = NO;
// defined in
extern NSMenu* sApplicationMenu; // Application menu shared by all menubars
// defined in
extern BOOL gSomeMenuBarPainted;
extern "C" {
// CGSPrivate.h
typedef NSInteger CGSConnection;
typedef NSUInteger CGSSpaceID;
typedef NSInteger CGSWindow;
typedef enum {
kCGSSpaceIncludesCurrent = 1 << 0,
kCGSSpaceIncludesOthers = 1 << 1,
kCGSSpaceIncludesUser = 1 << 2,
kCGSAllSpacesMask =
kCGSSpaceIncludesCurrent | kCGSSpaceIncludesOthers | kCGSSpaceIncludesUser
} CGSSpaceMask;
static NSString* const CGSSpaceIDKey = @"ManagedSpaceID";
static NSString* const CGSSpacesKey = @"Spaces";
extern CGSConnection _CGSDefaultConnection(void);
extern CGError CGSSetWindowTransform(CGSConnection cid, CGSWindow wid,
CGAffineTransform transform);
NS_IMPL_ISUPPORTS_INHERITED(nsCocoaWindow, Inherited, nsPIWidgetCocoa)
// A note on testing to see if your object is a sheet...
// |mWindowType == WindowType::Sheet| is true if your gecko nsIWidget is a sheet
// widget - whether or not the sheet is showing. |[mWindow isSheet]| will return
// true *only when the sheet is actually showing*. Choose your test wisely.
static void RollUpPopups(nsIRollupListener::AllowAnimations aAllowAnimations =
nsIRollupListener::AllowAnimations::Yes) {
if (RefPtr pm = nsXULPopupManager::GetInstance()) {
nsIRollupListener* rollupListener = nsBaseWidget::GetActiveRollupListener();
if (!rollupListener) {
if (rollupListener->RollupNativeMenu()) {
nsCOMPtr<nsIWidget> rollupWidget = rollupListener->GetRollupWidget();
if (!rollupWidget) {
nsIRollupListener::RollupOptions options{
0, nsIRollupListener::FlushViews::Yes, nullptr, aAllowAnimations};
: mParent(nullptr),
mWasShown(false) {
// Disable automatic tabbing. We need to do this before we
// orderFront any of our windows.
[NSWindow setAllowsAutomaticWindowTabbing:NO];
void nsCocoaWindow::DestroyNativeWindow() {
if (!mWindow) return;
// Define a helper function for checking our fullscreen window status.
bool (^inNativeFullscreen)(void) = ^{
return ((mWindow.styleMask & NSWindowStyleMaskFullScreen) ==
// If we are in native fullscreen, or we are in the middle of a native
// fullscreen transition, spin our run loop until both those things
// are false. This ensures that we've completed all our native
// fullscreen transitions and updated our class state before we close
// the window. We need to do this here (rather than in some other
// nsCocoaWindow trying to do a native fullscreen transition) because
// part of closing our window is clearing out our delegate, and the
// delegate callback is the only other way to clear our class state.
// While spinning this run loop, check to see if we are still in native
// fullscreen. If we are, request that we leave fullscreen (only once)
// and continue to spin the run loop until we're out of fullscreen.
// We also spin this run loop while mWaitingOnFinishCurrentTransition
// is true, which indicates we are waiting for an async call to
// FinishCurrentTransition to complete. We don't want to allow our own
// destruction while we have this pending runnable.
// However, it's possible that we are *already* in a run loop. In such
// a case, we can't spin the run loop again, so we don't even enter this
// loop if mInLocalRunLoop is true.
if (!mInLocalRunLoop) {
mInLocalRunLoop = true;
bool haveRequestedFullscreenExit = false;
NSRunLoop* localRunLoop = [NSRunLoop currentRunLoop];
while ((mWaitingOnFinishCurrentTransition || inNativeFullscreen() ||
WeAreInNativeTransition()) &&
[localRunLoop runMode:NSDefaultRunLoopMode
beforeDate:[NSDate distantFuture]]) {
// This loop continues to process events until mWindow is fully out
// of native fullscreen.
// Check to see if we should one-time request an exit from fullscreen.
// We do this if we are in native fullscreen and no window is in a
// native fullscreen transition.
if (!haveRequestedFullscreenExit && inNativeFullscreen() &&
CanStartNativeTransition()) {
[mWindow toggleFullScreen:nil];
haveRequestedFullscreenExit = true;
mInLocalRunLoop = false;
[mWindow releaseJSObjects];
// We want to unhook the delegate here because we don't want events
// sent to it after this object has been destroyed.
[mWindow setDelegate:nil];
[mWindow close];
mWindow = nil;
[mDelegate autorelease];
// We've lost access to our delegate. If we are still in a native
// fullscreen transition, we have to give up on it now even if it
// isn't finished, because the delegate is the only way that the
// class state would ever be cleared.
nsCocoaWindow::~nsCocoaWindow() {
// Notify the children that we're gone. Popup windows (e.g. tooltips) can
// have nsChildView children. 'kid' is an nsChildView object if and only if
// its 'type' is 'WindowType::Child'.
// childView->ResetParent() can change our list of children while it's
// being iterated, so the way we iterate the list must allow for this.
for (nsIWidget* kid = mLastChild; kid;) {
WindowType kidType = kid->GetWindowType();
if (kidType == WindowType::Child) {
nsChildView* childView = static_cast<nsChildView*>(kid);
kid = kid->GetPrevSibling();
} else {
nsCocoaWindow* childWindow = static_cast<nsCocoaWindow*>(kid);
childWindow->mParent = nullptr;
childWindow->mAncestorLink = mAncestorLink;
kid = kid->GetPrevSibling();
if (mWindow && mWindowMadeHere) {
// Deal with the possiblity that we're being destroyed while running modal.
if (mModal) {
NS_WARNING("Widget destroyed while running modal!");
NS_ASSERTION(gXULModalLevel >= 0, "Weirdness setting modality!");
// Find the screen that overlaps aRect the most,
// if none are found default to the mainScreen.
static NSScreen* FindTargetScreenForRect(const DesktopIntRect& aRect) {
NSScreen* targetScreen = [NSScreen mainScreen];
NSEnumerator* screenEnum = [[NSScreen screens] objectEnumerator];
int largestIntersectArea = 0;
while (NSScreen* screen = [screenEnum nextObject]) {
DesktopIntRect screenRect =
nsCocoaUtils::CocoaRectToGeckoRect([screen visibleFrame]);
screenRect = screenRect.Intersect(aRect);
int area = screenRect.width * screenRect.height;
if (area > largestIntersectArea) {
largestIntersectArea = area;
targetScreen = screen;
return targetScreen;
// fits the rect to the screen that contains the largest area of it,
// or to aScreen if a screen is passed in
// NB: this operates with aRect in desktop pixels
static void FitRectToVisibleAreaForScreen(DesktopIntRect& aRect,
NSScreen* aScreen) {
if (!aScreen) {
aScreen = FindTargetScreenForRect(aRect);
DesktopIntRect screenBounds =
nsCocoaUtils::CocoaRectToGeckoRect([aScreen visibleFrame]);
if (aRect.width > screenBounds.width) {
aRect.width = screenBounds.width;
if (aRect.height > screenBounds.height) {
aRect.height = screenBounds.height;
if (aRect.x - screenBounds.x + aRect.width > screenBounds.width) {
aRect.x += screenBounds.width - (aRect.x - screenBounds.x + aRect.width);
if (aRect.y - screenBounds.y + aRect.height > screenBounds.height) {
aRect.y += screenBounds.height - (aRect.y - screenBounds.y + aRect.height);
// If the left/top edge of the window is off the screen in either direction,
// then set the window to start at the left/top edge of the screen.
if (aRect.x < screenBounds.x ||
aRect.x > (screenBounds.x + screenBounds.width)) {
aRect.x = screenBounds.x;
if (aRect.y < screenBounds.y ||
aRect.y > (screenBounds.y + screenBounds.height)) {
aRect.y = screenBounds.y;
DesktopToLayoutDeviceScale ParentBackingScaleFactor(nsIWidget* aParent,
NSView* aParentView) {
if (aParent) {
return aParent->GetDesktopToDeviceScale();
NSWindow* parentWindow = [aParentView window];
if (parentWindow) {
return DesktopToLayoutDeviceScale([parentWindow backingScaleFactor]);
return DesktopToLayoutDeviceScale(1.0);
// Returns the screen rectangle for the given widget.
// Child widgets are positioned relative to this rectangle.
// Exactly one of the arguments must be non-null.
static DesktopRect GetWidgetScreenRectForChildren(nsIWidget* aWidget,
NSView* aView) {
if (aWidget) {
mozilla::DesktopToLayoutDeviceScale scale =
if (aWidget->GetWindowType() == WindowType::Child) {
return aWidget->GetScreenBounds() / scale;
return aWidget->GetClientBounds() / scale;
// 1. Transform the view rect into window coords.
// The returned rect is in "origin bottom-left" coordinates.
NSRect rectInWindowCoordinatesOBL = [aView convertRect:[aView bounds]
// 2. Turn the window-coord rect into screen coords, still origin bottom-left.
NSRect rectInScreenCoordinatesOBL =
[[aView window] convertRectToScreen:rectInWindowCoordinatesOBL];
// 3. Convert the NSRect to a DesktopRect. This will convert to coordinates
// with the origin in the top left corner of the primary screen.
return DesktopRect(
// aRect here is specified in desktop pixels
// For child windows (where either aParent or aNativeParent is non-null),
// aRect.{x,y} are offsets from the origin of the parent window and not an
// absolute position.
nsresult nsCocoaWindow::Create(nsIWidget* aParent, nsNativeWidget aNativeParent,
const DesktopIntRect& aRect,
widget::InitData* aInitData) {
// Because the hidden window is created outside of an event loop,
// we have to provide an autorelease pool (see bug 559075).
nsAutoreleasePool localPool;
DesktopIntRect newBounds = aRect;
FitRectToVisibleAreaForScreen(newBounds, nullptr);
// Set defaults which can be overriden from aInitData in BaseCreate
mWindowType = WindowType::TopLevel;
mBorderStyle = BorderStyle::Default;
// Ensure that the toolkit is created.
Inherited::BaseCreate(aParent, aInitData);
mParent = aParent;
mAncestorLink = aParent;
mAlwaysOnTop = aInitData->mAlwaysOnTop;
// If we have a parent widget, the new widget will be offset from the
// parent widget by aRect.{x,y}. Otherwise, we'll use aRect for the
// new widget coordinates.
DesktopIntPoint parentOrigin;
// Do we have a parent widget?
if (aParent || aNativeParent) {
DesktopRect parentDesktopRect =
GetWidgetScreenRectForChildren(aParent, (NSView*)aNativeParent);
parentOrigin = gfx::RoundedToInt(parentDesktopRect.TopLeft());
DesktopIntRect widgetRect = aRect + parentOrigin;
nsresult rv =
mBorderStyle, false, aInitData->mIsPrivate);
if (mWindowType == WindowType::Popup) {
// now we can convert widgetRect to device pixels for the window we created,
// as the child view expects a rect expressed in the dev pix of its parent
LayoutDeviceIntRect devRect =
RoundedToInt(newBounds * GetDesktopToDeviceScale());
return CreatePopupContentView(devRect, aInitData);
mIsAnimationSuppressed = aInitData->mIsAnimationSuppressed;
return NS_OK;
nsresult nsCocoaWindow::Create(nsIWidget* aParent, nsNativeWidget aNativeParent,
const LayoutDeviceIntRect& aRect,
widget::InitData* aInitData) {
DesktopIntRect desktopRect = RoundedToInt(
aRect / ParentBackingScaleFactor(aParent, (NSView*)aNativeParent));
return Create(aParent, aNativeParent, desktopRect, aInitData);
static unsigned int WindowMaskForBorderStyle(BorderStyle aBorderStyle) {
bool allOrDefault = (aBorderStyle == BorderStyle::All ||
aBorderStyle == BorderStyle::Default);
/* Apple's docs on NSWindow styles say that "a window's style mask should
* include NSWindowStyleMaskTitled if it includes any of the others [besides
* NSWindowStyleMaskBorderless]". This implies that a borderless window
* shouldn't have any other styles than NSWindowStyleMaskBorderless.
if (!allOrDefault && !(aBorderStyle & BorderStyle::Title)) {
if (aBorderStyle & BorderStyle::Minimize) {
/* It appears that at a minimum, borderless windows can be miniaturizable,
* effectively contradicting some of Apple's documentation referenced
* above. One such exception is the screen share indicator, see
return NSWindowStyleMaskBorderless | NSWindowStyleMaskMiniaturizable;
return NSWindowStyleMaskBorderless;
unsigned int mask = NSWindowStyleMaskTitled;
if (allOrDefault || aBorderStyle & BorderStyle::Close) {
mask |= NSWindowStyleMaskClosable;
if (allOrDefault || aBorderStyle & BorderStyle::Minimize) {
mask |= NSWindowStyleMaskMiniaturizable;
if (allOrDefault || aBorderStyle & BorderStyle::ResizeH) {
mask |= NSWindowStyleMaskResizable;
return mask;
// If aRectIsFrameRect, aRect specifies the frame rect of the new window.
// Otherwise, aRect.x/y specify the position of the window's frame relative to
// the bottom of the menubar and aRect.width/height specify the size of the
// content rect.
nsresult nsCocoaWindow::CreateNativeWindow(const NSRect& aRect,
BorderStyle aBorderStyle,
bool aRectIsFrameRect,
bool aIsPrivateBrowsing) {
// We default to NSWindowStyleMaskBorderless, add features if needed.
unsigned int features = NSWindowStyleMaskBorderless;
// Configure the window we will create based on the window type.
switch (mWindowType) {
case WindowType::Invisible:
case WindowType::Child:
case WindowType::Popup:
if (aBorderStyle != BorderStyle::Default &&
mBorderStyle & BorderStyle::Title) {
features |= NSWindowStyleMaskTitled;
if (aBorderStyle & BorderStyle::Close) {
features |= NSWindowStyleMaskClosable;
case WindowType::TopLevel:
case WindowType::Dialog:
features = WindowMaskForBorderStyle(aBorderStyle);
case WindowType::Sheet:
if (mParent->GetWindowType() != WindowType::Invisible &&
aBorderStyle & BorderStyle::ResizeH) {
features = NSWindowStyleMaskResizable;
} else {
features = NSWindowStyleMaskMiniaturizable;
features |= NSWindowStyleMaskTitled;
NS_ERROR("Unhandled window type!");
NSRect contentRect;
if (aRectIsFrameRect) {
contentRect = [NSWindow contentRectForFrameRect:aRect styleMask:features];
} else {
* We pass a content area rect to initialize the native Cocoa window. The
* content rect we give is the same size as the size we're given by gecko.
* The origin we're given for non-popup windows is moved down by the height
* of the menu bar so that an origin of (0,100) from gecko puts the window
* 100 pixels below the top of the available desktop area. We also move the
* origin down by the height of a title bar if it exists. This is so the
* origin that gecko gives us for the top-left of the window turns out to
* be the top-left of the window we create. This is how it was done in
* Carbon. If it ought to be different we'll probably need to look at all
* the callers.
* Note: This means that if you put a secondary screen on top of your main
* screen and open a window in the top screen, it'll be incorrectly shifted
* down by the height of the menu bar. Same thing would happen in Carbon.
* Note: If you pass a rect with 0,0 for an origin, the window ends up in a
* weird place for some reason. This stops that without breaking popups.
// Compensate for difference between frame and content area height (e.g.
// title bar).
NSRect newWindowFrame = [NSWindow frameRectForContentRect:aRect
contentRect = aRect;
contentRect.origin.y -= (newWindowFrame.size.height - aRect.size.height);
if (mWindowType != WindowType::Popup)
contentRect.origin.y -= [[NSApp mainMenu] menuBarHeight];
// NSLog(@"Top-level window being created at Cocoa rect: %f, %f, %f, %f\n",
// rect.origin.x, rect.origin.y, rect.size.width, rect.size.height);
Class windowClass = [BaseWindow class];
// If we have a titlebar on a top-level window, we want to be able to control
// the titlebar color (for unified windows), so use the special ToolbarWindow
// class. Note that we need to check the window type because we mark sheets as
// having titlebars.
if ((mWindowType == WindowType::TopLevel ||
mWindowType == WindowType::Dialog) &&
(features & NSWindowStyleMaskTitled))
windowClass = [ToolbarWindow class];
// If we're a popup window we need to use the PopupWindow class.
else if (mWindowType == WindowType::Popup)
windowClass = [PopupWindow class];
// If we're a non-popup borderless window we need to use the
// BorderlessWindow class.
else if (features == NSWindowStyleMaskBorderless)
windowClass = [BorderlessWindow class];
// Create the window
mWindow = [[windowClass alloc] initWithContentRect:contentRect
// Make sure that window titles don't leak to disk in private browsing mode
// due to macOS' resume feature.
[mWindow setRestorable:!aIsPrivateBrowsing];
if (aIsPrivateBrowsing) {
[mWindow disableSnapshotRestoration];
// setup our notification delegate. Note that setDelegate: does NOT retain.
mDelegate = [[WindowDelegate alloc] initWithGeckoWindow:this];
[mWindow setDelegate:mDelegate];
// Make sure that the content rect we gave has been honored.
NSRect wantedFrame = [mWindow frameRectForChildViewRect:contentRect];
if (!NSEqualRects([mWindow frame], wantedFrame)) {
// This can happen when the window is not on the primary screen.
[mWindow setFrame:wantedFrame display:NO];
if (mWindowType == WindowType::Invisible) {
[mWindow setLevel:kCGDesktopWindowLevelKey];
if (mWindowType == WindowType::Popup) {
[mWindow setBackgroundColor:[NSColor clearColor]];
[mWindow setOpaque:NO];
// When multiple spaces are in use and the browser is assigned to a
// particular space, override the "Assign To" space and display popups on
// the active space. Does not work with multiple displays. See
// NeedsRecreateToReshow() for multi-display with multi-space workaround.
if (!mAlwaysOnTop) {
NSWindowCollectionBehavior behavior = [mWindow collectionBehavior];
behavior |= NSWindowCollectionBehaviorMoveToActiveSpace;
[mWindow setCollectionBehavior:behavior];
} else {
// Non-popup windows are always opaque.
[mWindow setOpaque:YES];
NSWindowCollectionBehavior newBehavior = [mWindow collectionBehavior];
if (mAlwaysOnTop) {
[mWindow setLevel:NSFloatingWindowLevel];
newBehavior |= NSWindowCollectionBehaviorCanJoinAllSpaces;
[mWindow setCollectionBehavior:newBehavior];
[mWindow setContentMinSize:NSMakeSize(60, 60)];
[mWindow disableCursorRects];
// Make the window use CoreAnimation from the start, so that we don't
// switch from a non-CA window to a CA-window in the middle.
[[mWindow contentView] setWantsLayer:YES];
// Make sure the window starts out not draggable by the background.
// We will turn it on as necessary.
[mWindow setMovableByWindowBackground:NO];
[[WindowDataMap sharedWindowDataMap] ensureDataForWindow:mWindow];
mWindowMadeHere = true;
// Make the window respect the global appearance, which follows the
// browser.theme.toolbar-theme pref.
mWindow.appearanceSource = MOZGlobalAppearance.sharedInstance;
return NS_OK;
nsresult nsCocoaWindow::CreatePopupContentView(const LayoutDeviceIntRect& aRect,
widget::InitData* aInitData) {
// We need to make our content view a ChildView.
mPopupContentView = new nsChildView();
if (!mPopupContentView) return NS_ERROR_FAILURE;
nsIWidget* thisAsWidget = static_cast<nsIWidget*>(this);
nsresult rv =
mPopupContentView->Create(thisAsWidget, nullptr, aRect, aInitData);
if (NS_WARN_IF(NS_FAILED(rv))) {
return rv;
NSView* contentView = [mWindow contentView];
ChildView* childView =
[childView setFrame:[contentView bounds]];
[childView setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable];
[contentView addSubview:childView];
return NS_OK;
void nsCocoaWindow::Destroy() {
if (mOnDestroyCalled) return;
mOnDestroyCalled = true;
// SetFakeModal(true) is called for non-modal window opened by modal window.
// On Cocoa, it needs corresponding SetFakeModal(false) on destroy to restore
// ancestor windows' state.
if (mFakeModal) {
// If we don't hide here we run into problems with panels, this is not ideal.
// (Bug 891424)
if (mPopupContentView) mPopupContentView->Destroy();
if (mFullscreenTransitionAnimation) {
[mFullscreenTransitionAnimation stopAnimation];
// nsBaseWidget::Destroy() calls GetParent()->RemoveChild(this). But we
// don't implement GetParent(), so we need to do the equivalent here.
if (mParent) {
if (mInFullScreenMode) {
// On Lion we don't have to mess with the OS chrome when in Full Screen
// mode. But we do have to destroy the native window here (and not wait
// for that to happen in our destructor). We don't switch away from the
// native window's space until the window is destroyed, and otherwise this
// might not happen for several seconds (because at least one object
// holding a reference to ourselves is usually waiting to be garbage-
// collected). See bug 757618.
if (mInNativeFullScreenMode) {
} else if (mWindow) {
nsIWidget* nsCocoaWindow::GetSheetWindowParent(void) {
if (mWindowType != WindowType::Sheet) return nullptr;
nsCocoaWindow* parent = static_cast<nsCocoaWindow*>(mParent);
while (parent && (parent->mWindowType == WindowType::Sheet))
parent = static_cast<nsCocoaWindow*>(parent->mParent);
return parent;
void* nsCocoaWindow::GetNativeData(uint32_t aDataType) {
void* retVal = nullptr;
switch (aDataType) {
// to emulate how windows works, we always have to return a NSView
retVal = [mWindow contentView];
retVal = mWindow;
// There isn't anything that makes sense to return here,
// and it doesn't matter so just return nullptr.
NS_ERROR("Requesting NS_NATIVE_GRAPHIC on a top-level window!");
retVal = GetPseudoIMEContext();
if (retVal) {
NSView* view = mWindow ? [mWindow contentView] : nil;
if (view) {
retVal = [view inputContext];
// If inputContext isn't available on this window, return this window's
// pointer instead of nullptr since if this returns nullptr,
// IMEStateManager cannot manage composition with TextComposition
// instance. Although, this case shouldn't occur.
if (NS_WARN_IF(!retVal)) {
retVal = this;
return retVal;
bool nsCocoaWindow::IsVisible() const {
return (mWindow && ([mWindow isVisibleOrBeingShown] || mSheetNeedsShow));
void nsCocoaWindow::SetModal(bool aState) {
if (!mWindow) return;
// This is used during startup (outside the event loop) when creating
// the add-ons compatibility checking dialog and the profile manager UI;
// therefore, it needs to provide an autorelease pool to avoid cocoa
// objects leaking.
nsAutoreleasePool localPool;
mModal = aState;
nsCocoaWindow* ancestor = static_cast<nsCocoaWindow*>(mAncestorLink);
if (aState) {
// When a non-sheet window gets "set modal", make the window(s) that it
// appears over behave as they should. We can't rely on native methods to
// do this, for the following reason: The OS runs modal non-sheet windows
// in an event loop (using [NSApplication runModalForWindow:] or similar
// methods) that's incompatible with the modal event loop in AppWindow::
// ShowModal() (each of these event loops is "exclusive", and can't run at
// the same time as other (similar) event loops).
if (mWindowType != WindowType::Sheet) {
while (ancestor) {
if (ancestor->mNumModalDescendents++ == 0) {
NSWindow* aWindow = ancestor->GetCocoaWindow();
if (ancestor->mWindowType != WindowType::Invisible) {
[[aWindow standardWindowButton:NSWindowCloseButton] setEnabled:NO];
[[aWindow standardWindowButton:NSWindowMiniaturizeButton]
[[aWindow standardWindowButton:NSWindowZoomButton] setEnabled:NO];
ancestor = static_cast<nsCocoaWindow*>(ancestor->mParent);
[mWindow setLevel:NSModalPanelWindowLevel];
nsCocoaWindowList* windowList = new nsCocoaWindowList;
if (windowList) {
windowList->window = this; // Don't ADDREF
windowList->prev = gGeckoAppModalWindowList;
gGeckoAppModalWindowList = windowList;
} else {
NS_ASSERTION(gXULModalLevel >= 0,
"Mismatched call to nsCocoaWindow::SetModal(false)!");
if (mWindowType != WindowType::Sheet) {
while (ancestor) {
if (--ancestor->mNumModalDescendents == 0) {
NSWindow* aWindow = ancestor->GetCocoaWindow();
if (ancestor->mWindowType != WindowType::Invisible) {
[[aWindow standardWindowButton:NSWindowCloseButton] setEnabled:YES];
[[aWindow standardWindowButton:NSWindowMiniaturizeButton]
[[aWindow standardWindowButton:NSWindowZoomButton] setEnabled:YES];
NS_ASSERTION(ancestor->mNumModalDescendents >= 0,
"Widget hierarchy changed while modal!");
ancestor = static_cast<nsCocoaWindow*>(ancestor->mParent);
if (gGeckoAppModalWindowList) {
NS_ASSERTION(gGeckoAppModalWindowList->window == this,
"Widget hierarchy changed while modal!");
nsCocoaWindowList* saved = gGeckoAppModalWindowList;
gGeckoAppModalWindowList = gGeckoAppModalWindowList->prev;
delete saved; // "window" not ADDREFed
if (mWindowType == WindowType::Popup)
[mWindow setLevel:NSNormalWindowLevel];
void nsCocoaWindow::SetFakeModal(bool aState) {
mFakeModal = aState;
bool nsCocoaWindow::IsRunningAppModal() { return [NSApp _isRunningAppModal]; }
// Hide or show this window
void nsCocoaWindow::Show(bool bState) {
if (!mWindow) return;
if (!mSheetNeedsShow) {
// Early exit if our current visibility state is already the requested
// state.
if (bState == ([mWindow isVisible] || [mWindow isBeingShown])) {
[mWindow setBeingShown:bState];
if (bState && !mWasShown) {
mWasShown = true;
nsIWidget* parentWidget = mParent;
nsCOMPtr<nsPIWidgetCocoa> piParentWidget(do_QueryInterface(parentWidget));
NSWindow* nativeParentWindow =
(parentWidget) ? (NSWindow*)parentWidget->GetNativeData(NS_NATIVE_WINDOW)
: nil;
if (bState && !mBounds.IsEmpty()) {
// If we had set the activationPolicy to accessory, then right now we won't
// have a dock icon. Make sure that we undo that and show a dock icon now
// that we're going to show a window.
if ([NSApp activationPolicy] != NSApplicationActivationPolicyRegular) {
[NSApp setActivationPolicy:NSApplicationActivationPolicyRegular];
// Don't try to show a popup when the parent isn't visible or is minimized.
if (mWindowType == WindowType::Popup && nativeParentWindow) {
if (![nativeParentWindow isVisible] ||
[nativeParentWindow isMiniaturized]) {
if (mPopupContentView) {
// Ensure our content view is visible. We never need to hide it.
if (mWindowType == WindowType::Sheet) {
// bail if no parent window (its basically what we do in Carbon)
if (!nativeParentWindow || !piParentWidget) return;
NSWindow* topNonSheetWindow = nativeParentWindow;
// If this sheet is the child of another sheet, hide the parent so that
// this sheet can be displayed. Leave the parent mSheetNeedsShow alone,
// that is only used to handle sibling sheet contention. The parent will
// return once there are no more child sheets.
bool parentIsSheet = false;
if (NS_SUCCEEDED(piParentWidget->GetIsSheet(&parentIsSheet)) &&
parentIsSheet) {
[NSApp endSheet:nativeParentWindow];
[nativeParentWindow.sheetParent endSheet:nativeParentWindow];
nsCOMPtr<nsIWidget> sheetShown;
if (NS_SUCCEEDED(piParentWidget->GetChildSheet(
true, getter_AddRefs(sheetShown))) &&
(!sheetShown || sheetShown == this)) {
// If this sheet is already the sheet actually being shown, don't
// tell it to show again. Otherwise the number of calls to
// [NSApp beginSheet...] won't match up with [NSApp endSheet...].
// [NSWindow beginSheet...] won't match up with [NSWindow endSheet...].
if (![mWindow isVisible]) {
mSheetNeedsShow = false;
mSheetWindowParent = topNonSheetWindow;
// Only set contextInfo if our parent isn't a sheet.
NSWindow* contextInfo = parentIsSheet ? nil : mSheetWindowParent;
[TopLevelWindowData deactivateInWindow:mSheetWindowParent];
[NSApp beginSheet:mWindow
NSWindow* sheet = mWindow;
NSWindow* nonSheetParent = parentIsSheet ? nil : mSheetWindowParent;
[TopLevelWindowData deactivateInWindow:mSheetWindowParent];
[mSheetWindowParent beginSheet:sheet
completionHandler:^(NSModalResponse returnCode) {
// Note: 'nonSheetParent' (if it is set) is the window
// that is the parent of the sheet. If it's set,
// 'nonSheetParent' is always the top- level window,
// not another sheet itself. But 'nonSheetParent' is
// nil if our parent window is also a sheet -- in that
// case we shouldn't send the top-level window any
// activate events (because it's our parent window that
// needs to get these events, not the top-level
// window).
[TopLevelWindowData deactivateInWindow:sheet];
[sheet orderOut:nil];
if (nonSheetParent) {
[TopLevelWindowData activateInWindow:nonSheetParent];
[TopLevelWindowData activateInWindow:mWindow];
} else {
// A sibling of this sheet is active, don't show this sheet yet.
// When the active sheet hides, its brothers and sisters that have
// mSheetNeedsShow set will have their opportunities to display.
mSheetNeedsShow = true;
} else if (mWindowType == WindowType::Popup) {
// For reasons that aren't yet clear, calls to [NSWindow orderFront:] or
// [NSWindow makeKeyAndOrderFront:] can sometimes trigger "Error (1000)
// creating CGSWindow", which in turn triggers an internal inconsistency
// NSException. These errors shouldn't be fatal. So we need to wrap
// calls to ...orderFront: in TRY blocks. See bmo bug 470864.
[[mWindow contentView] setNeedsDisplay:YES];
[mWindow orderFront:nil];
// If our popup window is a non-native context menu, tell the OS (and
// other programs) that a menu has opened. This is how the OS knows to
// close other programs' context menus when ours open.
if ([mWindow isKindOfClass:[PopupWindow class]] &&
[(PopupWindow*)mWindow isContextMenu]) {
[[NSDistributedNotificationCenter defaultCenter]
// If a parent window was supplied and this is a popup at the parent
// level, set its child window. This will cause the child window to
// appear above the parent and move when the parent does. Setting this
// needs to happen after the _setWindowNumber calls above, otherwise the
// window doesn't focus properly.
if (nativeParentWindow && mPopupLevel == PopupLevel::Parent)
[nativeParentWindow addChildWindow:mWindow ordered:NSWindowAbove];
} else {
if (mWindowType == WindowType::TopLevel &&
[mWindow respondsToSelector:@selector(setAnimationBehavior:)]) {
NSWindowAnimationBehavior behavior;
if (mIsAnimationSuppressed) {
behavior = NSWindowAnimationBehaviorNone;
} else {
switch (mAnimationType) {
case nsIWidget::eDocumentWindowAnimation:
behavior = NSWindowAnimationBehaviorDocumentWindow;
MOZ_FALLTHROUGH_ASSERT("unexpected mAnimationType value");
case nsIWidget::eGenericWindowAnimation:
behavior = NSWindowAnimationBehaviorDefault;
[mWindow setAnimationBehavior:behavior];
mWindowAnimationBehavior = behavior;
// We don't want alwaysontop windows to pull focus when they're opened,
// as these tend to be for peripheral indicators and displays.
if (mAlwaysOnTop) {
[mWindow orderFront:nil];
} else {
[mWindow makeKeyAndOrderFront:nil];
} else {
// roll up any popups if a top-level window is going away
if (mWindowType == WindowType::TopLevel ||
mWindowType == WindowType::Dialog) {
// now get rid of the window/sheet
if (mWindowType == WindowType::Sheet) {
if (mSheetNeedsShow) {
// This is an attempt to hide a sheet that never had a chance to
// be shown. There's nothing to do other than make sure that it
// won't show.
mSheetNeedsShow = false;
} else {
// get sheet's parent *before* hiding the sheet (which breaks the
// linkage)
NSWindow* sheetParent = mSheetWindowParent;
// hide the sheet
[NSApp endSheet:mWindow];
[mSheetWindowParent endSheet:mWindow];
[TopLevelWindowData deactivateInWindow:mWindow];
nsCOMPtr<nsIWidget> siblingSheetToShow;
bool parentIsSheet = false;
if (nativeParentWindow && piParentWidget &&
false, getter_AddRefs(siblingSheetToShow))) &&
siblingSheetToShow) {
// First, give sibling sheets an opportunity to show.
} else if (nativeParentWindow && piParentWidget &&
NS_SUCCEEDED(piParentWidget->GetIsSheet(&parentIsSheet)) &&
parentIsSheet) {
// Only set contextInfo if the parent of the parent sheet we're about
// to restore isn't itself a sheet.
NSWindow* contextInfo = sheetParent;
// Only set nonSheetGrandparent if the parent of the parent sheet
// we're about to restore isn't itself a sheet.
NSWindow* nonSheetGrandparent = sheetParent;
nsIWidget* grandparentWidget = nil;
if (NS_SUCCEEDED(piParentWidget->GetRealParent(&grandparentWidget)) &&
grandparentWidget) {
nsCOMPtr<nsPIWidgetCocoa> piGrandparentWidget(
bool grandparentIsSheet = false;
if (piGrandparentWidget &&
piGrandparentWidget->GetIsSheet(&grandparentIsSheet)) &&
grandparentIsSheet) {
contextInfo = nil;
nonSheetGrandparent = nil;
// If there are no sibling sheets, but the parent is a sheet, restore
// it. It wasn't sent any deactivate events when it was hidden, so
// don't call through Show, just let the OS put it back up.
[NSApp beginSheet:nativeParentWindow
modalDelegate:[nativeParentWindow delegate]
completionHandler:^(NSModalResponse returnCode) {
// Note: 'nonSheetGrandparent' (if it is set) is the window that
// is the parent of sheetParent. If it's set,
// 'nonSheetGrandparent' is always the top-level window, not
// another sheet itself. But 'nonSheetGrandparent' is nil if
// our parent window is also a sheet -- in that case we
// shouldn't send the top-level window any activate events
// (because it's our parent window that needs to get these
// events, not the top-level window).
[TopLevelWindowData deactivateInWindow:sheetParent];
[sheetParent orderOut:nil];
if (nonSheetGrandparent) {
[TopLevelWindowData activateInWindow:nonSheetGrandparent];
} else {
// Sheet, that was hard. No more siblings or parents, going back
// to a real window.
[sheetParent makeKeyAndOrderFront:nil];
} else {
// If the window is a popup window with a parent window we need to
// unhook it here before ordering it out. When you order out the child
// of a window it hides the parent window.
if (mWindowType == WindowType::Popup && nativeParentWindow)
[nativeParentWindow removeChildWindow:mWindow];
[mWindow orderOut:nil];
// If our popup window is a non-native context menu, tell the OS (and
// other programs) that a menu has closed.
if ([mWindow isKindOfClass:[PopupWindow class]] &&
[(PopupWindow*)mWindow isContextMenu]) {
[[NSDistributedNotificationCenter defaultCenter]
[mWindow setBeingShown:NO];
// Work around a problem where with multiple displays and multiple spaces
// enabled, where the browser is assigned to a single display or space, popup
// windows that are reshown after being hidden with [NSWindow orderOut] show on
// the assigned space even when opened from another display. Apply the
// workaround whenever more than one display is enabled.
bool nsCocoaWindow::NeedsRecreateToReshow() {
// Limit the workaround to popup windows because only they need to override
// the "Assign To" setting. i.e., to display where the parent window is.
return (mWindowType == WindowType::Popup) && mWasShown &&
([[NSScreen screens] count] > 1);
WindowRenderer* nsCocoaWindow::GetWindowRenderer() {
if (mPopupContentView) {
return mPopupContentView->GetWindowRenderer();
return nullptr;
TransparencyMode nsCocoaWindow::GetTransparencyMode() {
return (!mWindow || [mWindow isOpaque]) ? TransparencyMode::Opaque
: TransparencyMode::Transparent;
// This is called from nsMenuPopupFrame when making a popup transparent.
void nsCocoaWindow::SetTransparencyMode(TransparencyMode aMode) {
// Only respect calls for popup windows.
if (!mWindow || mWindowType != WindowType::Popup) {
BOOL isTransparent = aMode == TransparencyMode::Transparent;
BOOL currentTransparency = ![mWindow isOpaque];
if (isTransparent != currentTransparency) {
[mWindow setOpaque:!isTransparent];
[mWindow setBackgroundColor:(isTransparent ? [NSColor clearColor]
: [NSColor whiteColor])];
void nsCocoaWindow::Enable(bool aState) {}
bool nsCocoaWindow::IsEnabled() const { return true; }
void nsCocoaWindow::ConstrainPosition(DesktopIntPoint& aPoint) {
if (!mWindow || ![mWindow screen]) {
nsIntRect screenBounds;
int32_t width, height;
NSRect frame = [mWindow frame];
// zero size rects confuse the screen manager
width = std::max<int32_t>(frame.size.width, 1);
height = std::max<int32_t>(frame.size.height, 1);
nsCOMPtr<nsIScreenManager> screenMgr =
if (screenMgr) {
nsCOMPtr<nsIScreen> screen;
screenMgr->ScreenForRect(aPoint.x, aPoint.y, width, height,
if (screen) {
screen->GetRectDisplayPix(&(screenBounds.x), &(screenBounds.y),
&(screenBounds.width), &(screenBounds.height));
if (aPoint.x < screenBounds.x) {
aPoint.x = screenBounds.x;
} else if (aPoint.x >= screenBounds.x + screenBounds.width - width) {
aPoint.x = screenBounds.x + screenBounds.width - width;
if (aPoint.y < screenBounds.y) {
aPoint.y = screenBounds.y;
} else if (aPoint.y >= screenBounds.y + screenBounds.height - height) {
aPoint.y = screenBounds.y + screenBounds.height - height;
void nsCocoaWindow::SetSizeConstraints(const SizeConstraints& aConstraints) {
// Popups can be smaller than (32, 32)
NSRect rect = (mWindowType == WindowType::Popup)
? NSZeroRect
: NSMakeRect(0.0, 0.0, 32, 32);
rect = [mWindow frameRectForChildViewRect:rect];
SizeConstraints c = aConstraints;
if (c.mScale.scale == MOZ_WIDGET_INVALID_SCALE) {
c.mScale.scale = BackingScaleFactor();
c.mMinSize.width = std::max(
nsCocoaUtils::CocoaPointsToDevPixels(rect.size.width, c.mScale.scale),
c.mMinSize.height = std::max(
nsCocoaUtils::CocoaPointsToDevPixels(rect.size.height, c.mScale.scale),
NSSize minSize = {
nsCocoaUtils::DevPixelsToCocoaPoints(c.mMinSize.width, c.mScale.scale),
nsCocoaUtils::DevPixelsToCocoaPoints(c.mMinSize.height, c.mScale.scale)};
[mWindow setMinSize:minSize];
c.mMaxSize.width = std::max(
nsCocoaUtils::CocoaPointsToDevPixels(c.mMaxSize.width, c.mScale.scale),
c.mMaxSize.height = std::max(
nsCocoaUtils::CocoaPointsToDevPixels(c.mMaxSize.height, c.mScale.scale),
NSSize maxSize = {
c.mMaxSize.width == NS_MAXSIZE ? FLT_MAX
: nsCocoaUtils::DevPixelsToCocoaPoints(
c.mMaxSize.width, c.mScale.scale),
c.mMaxSize.height == NS_MAXSIZE ? FLT_MAX
: nsCocoaUtils::DevPixelsToCocoaPoints(
c.mMaxSize.height, c.mScale.scale)};
[mWindow setMaxSize:maxSize];
// Coordinates are desktop pixels
void nsCocoaWindow::Move(double aX, double aY) {
if (!mWindow) {
// The point we have is in Gecko coordinates (origin top-left). Convert
// it to Cocoa ones (origin bottom-left).
NSPoint coord = {
NSRect frame = [mWindow frame];
if (frame.origin.x != coord.x ||
frame.origin.y + frame.size.height != coord.y) {
[mWindow setFrameTopLeftPoint:coord];
void nsCocoaWindow::SetSizeMode(nsSizeMode aMode) {
if (aMode == nsSizeMode_Normal) {
} else if (aMode == nsSizeMode_Minimized) {
} else if (aMode == nsSizeMode_Maximized) {
} else if (aMode == nsSizeMode_Fullscreen) {
// The (work)space switching implementation below was inspired by Phoenix:
// License: MIT.
// Runtime `CGSGetActiveSpace` library function feature detection.
typedef CGSSpaceID (*CGSGetActiveSpaceFunc)(CGSConnection cid);
static CGSGetActiveSpaceFunc GetCGSGetActiveSpaceFunc() {
static CGSGetActiveSpaceFunc func = nullptr;
static bool lookedUpFunc = false;
if (!lookedUpFunc) {
func = (CGSGetActiveSpaceFunc)dlsym(RTLD_DEFAULT, "CGSGetActiveSpace");
lookedUpFunc = true;
return func;
// Runtime `CGSCopyManagedDisplaySpaces` library function feature detection.
typedef CFArrayRef (*CGSCopyManagedDisplaySpacesFunc)(CGSConnection cid);
static CGSCopyManagedDisplaySpacesFunc GetCGSCopyManagedDisplaySpacesFunc() {
static CGSCopyManagedDisplaySpacesFunc func = nullptr;
static bool lookedUpFunc = false;
if (!lookedUpFunc) {
func = (CGSCopyManagedDisplaySpacesFunc)dlsym(
RTLD_DEFAULT, "CGSCopyManagedDisplaySpaces");
lookedUpFunc = true;
return func;
// Runtime `CGSCopySpacesForWindows` library function feature detection.
typedef CFArrayRef (*CGSCopySpacesForWindowsFunc)(CGSConnection cid,
CGSSpaceMask mask,
CFArrayRef windowIDs);
static CGSCopySpacesForWindowsFunc GetCGSCopySpacesForWindowsFunc() {
static CGSCopySpacesForWindowsFunc func = nullptr;
static bool lookedUpFunc = false;
if (!lookedUpFunc) {
func = (CGSCopySpacesForWindowsFunc)dlsym(RTLD_DEFAULT,
lookedUpFunc = true;
return func;
// Runtime `CGSAddWindowsToSpaces` library function feature detection.
typedef void (*CGSAddWindowsToSpacesFunc)(CGSConnection cid,
CFArrayRef windowIDs,
CFArrayRef spaceIDs);
static CGSAddWindowsToSpacesFunc GetCGSAddWindowsToSpacesFunc() {
static CGSAddWindowsToSpacesFunc func = nullptr;
static bool lookedUpFunc = false;
if (!lookedUpFunc) {
func =
(CGSAddWindowsToSpacesFunc)dlsym(RTLD_DEFAULT, "CGSAddWindowsToSpaces");
lookedUpFunc = true;
return func;
// Runtime `CGSRemoveWindowsFromSpaces` library function feature detection.
typedef void (*CGSRemoveWindowsFromSpacesFunc)(CGSConnection cid,
CFArrayRef windowIDs,
CFArrayRef spaceIDs);
static CGSRemoveWindowsFromSpacesFunc GetCGSRemoveWindowsFromSpacesFunc() {
static CGSRemoveWindowsFromSpacesFunc func = nullptr;
static bool lookedUpFunc = false;
if (!lookedUpFunc) {
func = (CGSRemoveWindowsFromSpacesFunc)dlsym(RTLD_DEFAULT,
lookedUpFunc = true;
return func;
void nsCocoaWindow::GetWorkspaceID(nsAString& workspaceID) {
int32_t sid = GetWorkspaceID();
if (sid != 0) {
int32_t nsCocoaWindow::GetWorkspaceID() {
// Mac OSX space IDs start at '1' (default space), so '0' means 'unknown',
// effectively.
CGSSpaceID sid = 0;
CGSCopySpacesForWindowsFunc CopySpacesForWindows =
if (!CopySpacesForWindows) {
return sid;
CGSConnection cid = _CGSDefaultConnection();
// Fetch all spaces that this window belongs to (in order).
NSArray<NSNumber*>* spaceIDs = CFBridgingRelease(CopySpacesForWindows(
cid, kCGSAllSpacesMask,
(__bridge CFArrayRef) @[ @([mWindow windowNumber]) ]));
if ([spaceIDs count]) {
// When spaces are found, return the first one.
// We don't support a single window painted across multiple places for now.
sid = [spaceIDs[0] integerValue];
} else {
// Fall back to the workspace that's currently active, which is '1' in the
// common case.
CGSGetActiveSpaceFunc GetActiveSpace = GetCGSGetActiveSpaceFunc();
if (GetActiveSpace) {
sid = GetActiveSpace(cid);
return sid;
void nsCocoaWindow::MoveToWorkspace(const nsAString& workspaceIDStr) {
if ([NSScreen screensHaveSeparateSpaces] && [[NSScreen screens] count] > 1) {
// We don't support moving to a workspace when the user has this option
// enabled in Mission Control.
nsresult rv = NS_OK;
int32_t workspaceID = workspaceIDStr.ToInteger(&rv);
if (NS_FAILED(rv)) {
CGSConnection cid = _CGSDefaultConnection();
int32_t currentSpace = GetWorkspaceID();
// If an empty workspace ID is passed in (not valid on OSX), or when the
// window is already on this workspace, we don't need to do anything.
if (!workspaceID || workspaceID == currentSpace) {
CGSCopyManagedDisplaySpacesFunc CopyManagedDisplaySpaces =
CGSAddWindowsToSpacesFunc AddWindowsToSpaces = GetCGSAddWindowsToSpacesFunc();
CGSRemoveWindowsFromSpacesFunc RemoveWindowsFromSpaces =
if (!CopyManagedDisplaySpaces || !AddWindowsToSpaces ||
!RemoveWindowsFromSpaces) {
// Fetch an ordered list of all known spaces.
NSArray* displaySpacesInfo = CFBridgingRelease(CopyManagedDisplaySpaces(cid));
// When we found the space we're looking for, we can bail out of the loop
// early, which this local variable is used for.
BOOL found = false;
for (NSDictionary<NSString*, id>* spacesInfo in displaySpacesInfo) {
NSArray<NSNumber*>* sids =
[spacesInfo[CGSSpacesKey] valueForKey:CGSSpaceIDKey];
for (NSNumber* sid in sids) {
// If we found our space in the list, we're good to go and can jump out of
// this loop.
if ((int)[sid integerValue] == workspaceID) {
found = true;
if (found) {
// We were unable to find the space to correspond with the workspaceID as
// requested, so let's bail out.
if (!found) {
// First we add the window to the appropriate space.
AddWindowsToSpaces(cid, (__bridge CFArrayRef) @[ @([mWindow windowNumber]) ],
(__bridge CFArrayRef) @[ @(workspaceID) ]);
// Then we remove the window from the active space.
(__bridge CFArrayRef) @[ @([mWindow windowNumber]) ],
(__bridge CFArrayRef) @[ @(currentSpace) ]);
void nsCocoaWindow::SuppressAnimation(bool aSuppress) {
if ([mWindow respondsToSelector:@selector(setAnimationBehavior:)]) {
if (aSuppress) {
[mWindow setIsAnimationSuppressed:YES];
[mWindow setAnimationBehavior:NSWindowAnimationBehaviorNone];
} else {
[mWindow setIsAnimationSuppressed:NO];
[mWindow setAnimationBehavior:mWindowAnimationBehavior];
// This has to preserve the window's frame bounds.
// This method requires (as does the Windows impl.) that you call Resize shortly
// after calling HideWindowChrome. See bug 498835 for fixing this.
void nsCocoaWindow::HideWindowChrome(bool aShouldHide) {
if (!mWindow || !mWindowMadeHere ||
(mWindowType != WindowType::TopLevel &&
mWindowType != WindowType::Dialog))
BOOL isVisible = [mWindow isVisible];
// Remove child windows.
NSArray* childWindows = [mWindow childWindows];
NSEnumerator* enumerator = [childWindows objectEnumerator];
NSWindow* child = nil;
while ((child = [enumerator nextObject])) {
[mWindow removeChildWindow:child];
// Remove the views in the old window's content view.
// The NSArray is autoreleased and retains its NSViews.
NSArray<NSView*>* contentViewContents = [mWindow contentViewContents];
for (NSView* view in contentViewContents) {
[view removeFromSuperviewWithoutNeedingDisplay];
// Save state (like window title).
NSMutableDictionary* state = [mWindow exportState];
// Recreate the window with the right border style.
NSRect frameRect = [mWindow frame];
nsresult rv = CreateNativeWindow(
frameRect, aShouldHide ? BorderStyle::None : mBorderStyle, true,
// Re-import state.
[mWindow importState:state];
// Add the old content view subviews to the new window's content view.
for (NSView* view in contentViewContents) {
[[mWindow contentView] addSubview:view];
// Reparent child windows.
enumerator = [childWindows objectEnumerator];
while ((child = [enumerator nextObject])) {
[mWindow addChildWindow:child ordered:NSWindowAbove];
// Show the new window.
if (isVisible) {
bool wasAnimationSuppressed = mIsAnimationSuppressed;
mIsAnimationSuppressed = true;
mIsAnimationSuppressed = wasAnimationSuppressed;
class FullscreenTransitionData : public nsISupports {
explicit FullscreenTransitionData(NSWindow* aWindow)
: mTransitionWindow(aWindow) {}
NSWindow* mTransitionWindow;
virtual ~FullscreenTransitionData() { [mTransitionWindow close]; }
@interface FullscreenTransitionDelegate : NSObject <NSAnimationDelegate> {
nsCocoaWindow* mWindow;
nsIRunnable* mCallback;
@implementation FullscreenTransitionDelegate
- (void)cleanupAndDispatch:(NSAnimation*)animation {
[animation setDelegate:nil];
[self autorelease];
// The caller should have added ref for us.
- (void)animationDidEnd:(NSAnimation*)animation {
MOZ_ASSERT(animation == mWindow->FullscreenTransitionAnimation(),
"Should be handling the only animation on the window");
[self cleanupAndDispatch:animation];
- (void)animationDidStop:(NSAnimation*)animation {
[self cleanupAndDispatch:animation];
static bool AlwaysUsesNativeFullScreen() {
return Preferences::GetBool("full-screen-api.macos-native-full-screen",
/* virtual */ bool nsCocoaWindow::PrepareForFullscreenTransition(
nsISupports** aData) {
if (AlwaysUsesNativeFullScreen()) {
return false;
// Our fullscreen transition creates a new window occluding this window.
// That triggers an occlusion event which can cause DOM fullscreen requests
// to fail due to the context not being focused at the time the focus check
// is performed in the child process. Until the transition is cleaned up in
// CleanupFullscreenTransition(), ignore occlusion events for this window.
// If this method is changed to return false, the transition will not be
// performed and mIgnoreOcclusionCount should not be incremented.
MOZ_ASSERT(mIgnoreOcclusionCount >= 0);
nsCOMPtr<nsIScreen> widgetScreen = GetWidgetScreen();
NSScreen* cocoaScreen = ScreenHelperCocoa::CocoaScreenForScreen(widgetScreen);
NSWindow* win =
[[NSWindow alloc] initWithContentRect:[cocoaScreen frame]
[win setBackgroundColor:[NSColor blackColor]];
[win setAlphaValue:0];
[win setIgnoresMouseEvents:YES];
[win setLevel:NSScreenSaverWindowLevel];
[win makeKeyAndOrderFront:nil];
auto data = new FullscreenTransitionData(win);
*aData = data;
return true;
/* virtual */ void nsCocoaWindow::CleanupFullscreenTransition() {
MOZ_ASSERT(mIgnoreOcclusionCount > 0);
/* virtual */ void nsCocoaWindow::PerformFullscreenTransition(
FullscreenTransitionStage aStage, uint16_t aDuration, nsISupports* aData,
nsIRunnable* aCallback) {
auto data = static_cast<FullscreenTransitionData*>(aData);
FullscreenTransitionDelegate* delegate =
[[FullscreenTransitionDelegate alloc] init];
delegate->mWindow = this;
// Storing already_AddRefed directly could cause static checking fail.
delegate->mCallback = nsCOMPtr<nsIRunnable>(aCallback).forget().take();
if (mFullscreenTransitionAnimation) {
[mFullscreenTransitionAnimation stopAnimation];
NSDictionary* dict = @{
NSViewAnimationTargetKey : data->mTransitionWindow,
NSViewAnimationEffectKey : aStage == eBeforeFullscreenToggle
? NSViewAnimationFadeInEffect
: NSViewAnimationFadeOutEffect
mFullscreenTransitionAnimation =
[[NSViewAnimation alloc] initWithViewAnimations:@[ dict ]];
[mFullscreenTransitionAnimation setDelegate:delegate];
[mFullscreenTransitionAnimation setDuration:aDuration / 1000.0];
[mFullscreenTransitionAnimation startAnimation];
void nsCocoaWindow::CocoaWindowWillEnterFullscreen(bool aFullscreen) {
mHasStartedNativeFullscreen = true;
// Ensure that we update our fullscreen state as early as possible, when the
// resize happens.
mUpdateFullscreenOnResize =
Some(aFullscreen ? TransitionType::Fullscreen : TransitionType::Windowed);
void nsCocoaWindow::CocoaWindowDidEnterFullscreen(bool aFullscreen) {
mHasStartedNativeFullscreen = false;
// Check if aFullscreen matches our expected fullscreen state. It might not if
// there was a failure somewhere along the way, in which case we'll recover
// from that.
bool receivedExpectedFullscreen = false;
if (mUpdateFullscreenOnResize.isSome()) {
bool expectingFullscreen =
(*mUpdateFullscreenOnResize == TransitionType::Fullscreen);
receivedExpectedFullscreen = (expectingFullscreen == aFullscreen);
} else {
receivedExpectedFullscreen = (mInFullScreenMode == aFullscreen);
TransitionType transition =
aFullscreen ? TransitionType::Fullscreen : TransitionType::Windowed;
if (receivedExpectedFullscreen) {
// Everything is as expected. Update our state if needed.
} else {
// We weren't expecting this fullscreen state. Update our fullscreen state
// to the new reality.
UpdateFullscreenState(aFullscreen, true);
// If we have a current transition, switch it to match what we just did.
if (mTransitionCurrent.isSome()) {
mTransitionCurrent = Some(transition);