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 "AppearanceOverride.h"
10 #include "NativeKeyBindings.h"
11 #include "ScreenHelperCocoa.h"
12 #include "TextInputHandler.h"
13 #include "nsCocoaUtils.h"
14 #include "nsObjCExceptions.h"
16 #include "nsWidgetsCID.h"
17 #include "nsIRollupListener.h"
18 #include "nsChildView.h"
19 #include "nsWindowMap.h"
20 #include "nsAppShell.h"
21 #include "nsIAppShellService.h"
22 #include "nsIBaseWindow.h"
23 #include "nsIInterfaceRequestorUtils.h"
24 #include "nsIAppWindow.h"
25 #include "nsToolkit.h"
26 #include "nsPIDOMWindow.h"
27 #include "nsThreadUtils.h"
28 #include "nsMenuBarX.h"
29 #include "nsMenuUtilsX.h"
30 #include "nsStyleConsts.h"
31 #include "nsNativeThemeColors.h"
32 #include "nsNativeThemeCocoa.h"
33 #include "nsChildView.h"
34 #include "nsCocoaFeatures.h"
35 #include "nsIScreenManager.h"
36 #include "nsIWidgetListener.h"
37 #include "nsXULPopupManager.h"
38 #include "VibrancyManager.h"
39 #include "nsPresContext.h"
40 #include "nsDocShell.h"
42 #include "gfxPlatform.h"
45 #include "mozilla/AutoRestore.h"
46 #include "mozilla/BasicEvents.h"
47 #include "mozilla/dom/Document.h"
48 #include "mozilla/Maybe.h"
49 #include "mozilla/NativeKeyBindingsType.h"
50 #include "mozilla/Preferences.h"
51 #include "mozilla/PresShell.h"
52 #include "mozilla/ScopeExit.h"
53 #include "mozilla/StaticPrefs_gfx.h"
54 #include "mozilla/StaticPrefs_widget.h"
55 #include "mozilla/WritingModes.h"
56 #include "mozilla/layers/CompositorBridgeChild.h"
57 #include "mozilla/widget/Screen.h"
64 } // namespace mozilla
65 using namespace mozilla::layers;
66 using namespace mozilla::widget;
67 using namespace mozilla;
69 int32_t gXULModalLevel = 0;
71 // In principle there should be only one app-modal window at any given time.
72 // But sometimes, despite our best efforts, another window appears above the
73 // current app-modal window. So we need to keep a linked list of app-modal
74 // windows. (A non-sheet window that appears above an app-modal window is
75 // also made app-modal.) See nsCocoaWindow::SetModal().
76 nsCocoaWindowList* gGeckoAppModalWindowList = NULL;
78 BOOL sTouchBarIsInitialized = NO;
80 // defined in nsMenuBarX.mm
81 extern NSMenu* sApplicationMenu; // Application menu shared by all menubars
83 // defined in nsChildView.mm
84 extern BOOL gSomeMenuBarPainted;
88 typedef NSInteger CGSConnection;
89 typedef NSUInteger CGSSpaceID;
90 typedef NSInteger CGSWindow;
92 kCGSSpaceIncludesCurrent = 1 << 0,
93 kCGSSpaceIncludesOthers = 1 << 1,
94 kCGSSpaceIncludesUser = 1 << 2,
97 kCGSSpaceIncludesCurrent | kCGSSpaceIncludesOthers | kCGSSpaceIncludesUser
99 static NSString* const CGSSpaceIDKey = @"ManagedSpaceID";
100 static NSString* const CGSSpacesKey = @"Spaces";
101 extern CGSConnection _CGSDefaultConnection(void);
102 extern CGError CGSSetWindowTransform(CGSConnection cid, CGSWindow wid,
103 CGAffineTransform transform);
106 #define NS_APPSHELLSERVICE_CONTRACTID "@mozilla.org/appshell/appShellService;1"
108 NS_IMPL_ISUPPORTS_INHERITED(nsCocoaWindow, Inherited, nsPIWidgetCocoa)
110 // A note on testing to see if your object is a sheet...
111 // |mWindowType == WindowType::Sheet| is true if your gecko nsIWidget is a sheet
112 // widget - whether or not the sheet is showing. |[mWindow isSheet]| will return
113 // true *only when the sheet is actually showing*. Choose your test wisely.
115 static void RollUpPopups(nsIRollupListener::AllowAnimations aAllowAnimations =
116 nsIRollupListener::AllowAnimations::Yes) {
117 if (RefPtr pm = nsXULPopupManager::GetInstance()) {
118 pm->RollupTooltips();
121 nsIRollupListener* rollupListener = nsBaseWidget::GetActiveRollupListener();
122 if (!rollupListener) {
125 if (rollupListener->RollupNativeMenu()) {
128 nsCOMPtr<nsIWidget> rollupWidget = rollupListener->GetRollupWidget();
132 nsIRollupListener::RollupOptions options{
133 0, nsIRollupListener::FlushViews::Yes, nullptr, aAllowAnimations};
134 rollupListener->Rollup(options);
137 nsCocoaWindow::nsCocoaWindow()
139 mAncestorLink(nullptr),
142 mSheetWindowParent(nil),
143 mPopupContentView(nil),
144 mFullscreenTransitionAnimation(nil),
145 mShadowStyle(WindowShadow::None),
146 mBackingScaleFactor(0.0),
147 mAnimationType(nsIWidget::eGenericWindowAnimation),
148 mWindowMadeHere(false),
149 mSheetNeedsShow(false),
150 mSizeMode(nsSizeMode_Normal),
151 mInFullScreenMode(false),
152 mInNativeFullScreenMode(false),
153 mIgnoreOcclusionCount(0),
154 mHasStartedNativeFullscreen(false),
157 mIsAnimationSuppressed(false),
158 mInReportMoveEvent(false),
160 mWindowTransformIsIdentity(true),
162 mAspectRatioLocked(false),
163 mNumModalDescendents(0),
164 mWindowAnimationBehavior(NSWindowAnimationBehaviorDefault),
166 // Disable automatic tabbing. We need to do this before we
167 // orderFront any of our windows.
168 [NSWindow setAllowsAutomaticWindowTabbing:NO];
171 void nsCocoaWindow::DestroyNativeWindow() {
172 NS_OBJC_BEGIN_TRY_IGNORE_BLOCK;
178 MOZ_ASSERT(mWindowMadeHere,
179 "We shouldn't be trying to destroy a window we didn't create.");
181 // Clear our current and pending transitions. This simplifies our
182 // reasoning about what happens next, and ensures that whatever is
183 // currently happening won't trigger another call to
184 // ProcessTransitions().
185 mTransitionCurrent.reset();
186 mIsTransitionCurrentAdded = false;
187 std::queue<TransitionType>().swap(mTransitionsPending);
189 // Clear our class state, which will ensure that other nsCocoaWindow
190 // instances are not waiting for us to finish a native transition.
191 EndOurNativeTransition();
193 [mWindow releaseJSObjects];
194 // We want to unhook the delegate here because we don't want events
195 // sent to it after this object has been destroyed.
196 [mWindow setDelegate:nil];
199 [mDelegate autorelease];
201 NS_OBJC_END_TRY_IGNORE_BLOCK;
204 nsCocoaWindow::~nsCocoaWindow() {
205 NS_OBJC_BEGIN_TRY_IGNORE_BLOCK;
207 // Notify the children that we're gone. Popup windows (e.g. tooltips) can
208 // have nsChildView children. 'kid' is an nsChildView object if and only if
209 // its 'type' is 'WindowType::Child'.
210 // childView->ResetParent() can change our list of children while it's
211 // being iterated, so the way we iterate the list must allow for this.
212 for (nsIWidget* kid = mLastChild; kid;) {
213 WindowType kidType = kid->GetWindowType();
214 if (kidType == WindowType::Child) {
215 nsChildView* childView = static_cast<nsChildView*>(kid);
216 kid = kid->GetPrevSibling();
217 childView->ResetParent();
219 nsCocoaWindow* childWindow = static_cast<nsCocoaWindow*>(kid);
220 childWindow->mParent = nullptr;
221 childWindow->mAncestorLink = mAncestorLink;
222 kid = kid->GetPrevSibling();
226 if (mWindow && mWindowMadeHere) {
227 DestroyNativeWindow();
230 NS_IF_RELEASE(mPopupContentView);
232 // Deal with the possiblity that we're being destroyed while running modal.
234 NS_WARNING("Widget destroyed while running modal!");
236 NS_ASSERTION(gXULModalLevel >= 0, "Weirdness setting modality!");
239 NS_OBJC_END_TRY_IGNORE_BLOCK;
242 // Find the screen that overlaps aRect the most,
243 // if none are found default to the mainScreen.
244 static NSScreen* FindTargetScreenForRect(const DesktopIntRect& aRect) {
245 NSScreen* targetScreen = [NSScreen mainScreen];
246 NSEnumerator* screenEnum = [[NSScreen screens] objectEnumerator];
247 int largestIntersectArea = 0;
248 while (NSScreen* screen = [screenEnum nextObject]) {
249 DesktopIntRect screenRect =
250 nsCocoaUtils::CocoaRectToGeckoRect([screen visibleFrame]);
251 screenRect = screenRect.Intersect(aRect);
252 int area = screenRect.width * screenRect.height;
253 if (area > largestIntersectArea) {
254 largestIntersectArea = area;
255 targetScreen = screen;
261 DesktopToLayoutDeviceScale ParentBackingScaleFactor(nsIWidget* aParent,
262 NSView* aParentView) {
264 return aParent->GetDesktopToDeviceScale();
266 NSWindow* parentWindow = [aParentView window];
268 return DesktopToLayoutDeviceScale([parentWindow backingScaleFactor]);
270 return DesktopToLayoutDeviceScale(1.0);
273 // Returns the screen rectangle for the given widget.
274 // Child widgets are positioned relative to this rectangle.
275 // Exactly one of the arguments must be non-null.
276 static DesktopRect GetWidgetScreenRectForChildren(nsIWidget* aWidget,
279 mozilla::DesktopToLayoutDeviceScale scale =
280 aWidget->GetDesktopToDeviceScale();
281 if (aWidget->GetWindowType() == WindowType::Child) {
282 return aWidget->GetScreenBounds() / scale;
284 return aWidget->GetClientBounds() / scale;
287 MOZ_RELEASE_ASSERT(aView);
289 // 1. Transform the view rect into window coords.
290 // The returned rect is in "origin bottom-left" coordinates.
291 NSRect rectInWindowCoordinatesOBL = [aView convertRect:[aView bounds]
294 // 2. Turn the window-coord rect into screen coords, still origin bottom-left.
295 NSRect rectInScreenCoordinatesOBL =
296 [[aView window] convertRectToScreen:rectInWindowCoordinatesOBL];
298 // 3. Convert the NSRect to a DesktopRect. This will convert to coordinates
299 // with the origin in the top left corner of the primary screen.
301 nsCocoaUtils::CocoaRectToGeckoRect(rectInScreenCoordinatesOBL));
304 // aRect here is specified in desktop pixels
306 // For child windows (where either aParent or aNativeParent is non-null),
307 // aRect.{x,y} are offsets from the origin of the parent window and not an
308 // absolute position.
309 nsresult nsCocoaWindow::Create(nsIWidget* aParent, nsNativeWidget aNativeParent,
310 const DesktopIntRect& aRect,
311 widget::InitData* aInitData) {
312 NS_OBJC_BEGIN_TRY_BLOCK_RETURN;
314 // Because the hidden window is created outside of an event loop,
315 // we have to provide an autorelease pool (see bug 559075).
316 nsAutoreleasePool localPool;
318 // Set defaults which can be overriden from aInitData in BaseCreate
319 mWindowType = WindowType::TopLevel;
320 mBorderStyle = BorderStyle::Default;
322 // Ensure that the toolkit is created.
323 nsToolkit::GetToolkit();
325 Inherited::BaseCreate(aParent, aInitData);
328 mAncestorLink = aParent;
329 mAlwaysOnTop = aInitData->mAlwaysOnTop;
331 // If we have a parent widget, the new widget will be offset from the
332 // parent widget by aRect.{x,y}. Otherwise, we'll use aRect for the
333 // new widget coordinates.
334 DesktopIntPoint parentOrigin;
336 // Do we have a parent widget?
337 if (aParent || aNativeParent) {
338 DesktopRect parentDesktopRect =
339 GetWidgetScreenRectForChildren(aParent, (NSView*)aNativeParent);
340 parentOrigin = gfx::RoundedToInt(parentDesktopRect.TopLeft());
343 DesktopIntRect widgetRect = aRect + parentOrigin;
346 CreateNativeWindow(nsCocoaUtils::GeckoRectToCocoaRect(widgetRect),
347 mBorderStyle, false, aInitData->mIsPrivate);
348 NS_ENSURE_SUCCESS(rv, rv);
350 if (mWindowType == WindowType::Popup) {
351 // now we can convert widgetRect to device pixels for the window we created,
352 // as the child view expects a rect expressed in the dev pix of its parent
353 LayoutDeviceIntRect devRect =
354 RoundedToInt(aRect * GetDesktopToDeviceScale());
355 return CreatePopupContentView(devRect, aInitData);
358 mIsAnimationSuppressed = aInitData->mIsAnimationSuppressed;
362 NS_OBJC_END_TRY_BLOCK_RETURN(NS_ERROR_FAILURE);
365 nsresult nsCocoaWindow::Create(nsIWidget* aParent, nsNativeWidget aNativeParent,
366 const LayoutDeviceIntRect& aRect,
367 widget::InitData* aInitData) {
368 DesktopIntRect desktopRect = RoundedToInt(
369 aRect / ParentBackingScaleFactor(aParent, (NSView*)aNativeParent));
370 return Create(aParent, aNativeParent, desktopRect, aInitData);
373 static unsigned int WindowMaskForBorderStyle(BorderStyle aBorderStyle) {
374 bool allOrDefault = (aBorderStyle == BorderStyle::All ||
375 aBorderStyle == BorderStyle::Default);
377 /* Apple's docs on NSWindow styles say that "a window's style mask should
378 * include NSWindowStyleMaskTitled if it includes any of the others [besides
379 * NSWindowStyleMaskBorderless]". This implies that a borderless window
380 * shouldn't have any other styles than NSWindowStyleMaskBorderless.
382 if (!allOrDefault && !(aBorderStyle & BorderStyle::Title)) {
383 if (aBorderStyle & BorderStyle::Minimize) {
384 /* It appears that at a minimum, borderless windows can be miniaturizable,
385 * effectively contradicting some of Apple's documentation referenced
386 * above. One such exception is the screen share indicator, see
389 return NSWindowStyleMaskBorderless | NSWindowStyleMaskMiniaturizable;
391 return NSWindowStyleMaskBorderless;
394 unsigned int mask = NSWindowStyleMaskTitled;
395 if (allOrDefault || aBorderStyle & BorderStyle::Close) {
396 mask |= NSWindowStyleMaskClosable;
398 if (allOrDefault || aBorderStyle & BorderStyle::Minimize) {
399 mask |= NSWindowStyleMaskMiniaturizable;
401 if (allOrDefault || aBorderStyle & BorderStyle::ResizeH) {
402 mask |= NSWindowStyleMaskResizable;
408 // If aRectIsFrameRect, aRect specifies the frame rect of the new window.
409 // Otherwise, aRect.x/y specify the position of the window's frame relative to
410 // the bottom of the menubar and aRect.width/height specify the size of the
412 nsresult nsCocoaWindow::CreateNativeWindow(const NSRect& aRect,
413 BorderStyle aBorderStyle,
414 bool aRectIsFrameRect,
415 bool aIsPrivateBrowsing) {
416 NS_OBJC_BEGIN_TRY_BLOCK_RETURN;
418 // We default to NSWindowStyleMaskBorderless, add features if needed.
419 unsigned int features = NSWindowStyleMaskBorderless;
421 // Configure the window we will create based on the window type.
422 switch (mWindowType) {
423 case WindowType::Invisible:
424 case WindowType::Child:
426 case WindowType::Popup:
427 if (aBorderStyle != BorderStyle::Default &&
428 mBorderStyle & BorderStyle::Title) {
429 features |= NSWindowStyleMaskTitled;
430 if (aBorderStyle & BorderStyle::Close) {
431 features |= NSWindowStyleMaskClosable;
435 case WindowType::TopLevel:
436 case WindowType::Dialog:
437 features = WindowMaskForBorderStyle(aBorderStyle);
439 case WindowType::Sheet:
440 if (mParent->GetWindowType() != WindowType::Invisible &&
441 aBorderStyle & BorderStyle::ResizeH) {
442 features = NSWindowStyleMaskResizable;
444 features = NSWindowStyleMaskMiniaturizable;
446 features |= NSWindowStyleMaskTitled;
449 NS_ERROR("Unhandled window type!");
450 return NS_ERROR_FAILURE;
455 if (aRectIsFrameRect) {
456 contentRect = [NSWindow contentRectForFrameRect:aRect styleMask:features];
459 * We pass a content area rect to initialize the native Cocoa window. The
460 * content rect we give is the same size as the size we're given by gecko.
461 * The origin we're given for non-popup windows is moved down by the height
462 * of the menu bar so that an origin of (0,100) from gecko puts the window
463 * 100 pixels below the top of the available desktop area. We also move the
464 * origin down by the height of a title bar if it exists. This is so the
465 * origin that gecko gives us for the top-left of the window turns out to
466 * be the top-left of the window we create. This is how it was done in
467 * Carbon. If it ought to be different we'll probably need to look at all
470 * Note: This means that if you put a secondary screen on top of your main
471 * screen and open a window in the top screen, it'll be incorrectly shifted
472 * down by the height of the menu bar. Same thing would happen in Carbon.
474 * Note: If you pass a rect with 0,0 for an origin, the window ends up in a
475 * weird place for some reason. This stops that without breaking popups.
477 // Compensate for difference between frame and content area height (e.g.
479 NSRect newWindowFrame = [NSWindow frameRectForContentRect:aRect
483 contentRect.origin.y -= (newWindowFrame.size.height - aRect.size.height);
485 if (mWindowType != WindowType::Popup)
486 contentRect.origin.y -= [[NSApp mainMenu] menuBarHeight];
489 // NSLog(@"Top-level window being created at Cocoa rect: %f, %f, %f, %f\n",
490 // rect.origin.x, rect.origin.y, rect.size.width, rect.size.height);
492 Class windowClass = [BaseWindow class];
493 // If we have a titlebar on a top-level window, we want to be able to control
494 // the titlebar color (for unified windows), so use the special ToolbarWindow
495 // class. Note that we need to check the window type because we mark sheets as
497 if ((mWindowType == WindowType::TopLevel ||
498 mWindowType == WindowType::Dialog) &&
499 (features & NSWindowStyleMaskTitled))
500 windowClass = [ToolbarWindow class];
501 // If we're a popup window we need to use the PopupWindow class.
502 else if (mWindowType == WindowType::Popup)
503 windowClass = [PopupWindow class];
504 // If we're a non-popup borderless window we need to use the
505 // BorderlessWindow class.
506 else if (features == NSWindowStyleMaskBorderless)
507 windowClass = [BorderlessWindow class];
510 mWindow = [[windowClass alloc] initWithContentRect:contentRect
512 backing:NSBackingStoreBuffered
515 // Make sure that window titles don't leak to disk in private browsing mode
516 // due to macOS' resume feature.
517 [mWindow setRestorable:!aIsPrivateBrowsing];
518 if (aIsPrivateBrowsing) {
519 [mWindow disableSnapshotRestoration];
522 // setup our notification delegate. Note that setDelegate: does NOT retain.
523 mDelegate = [[WindowDelegate alloc] initWithGeckoWindow:this];
524 [mWindow setDelegate:mDelegate];
526 // Make sure that the content rect we gave has been honored.
527 NSRect wantedFrame = [mWindow frameRectForChildViewRect:contentRect];
528 if (!NSEqualRects([mWindow frame], wantedFrame)) {
529 // This can happen when the window is not on the primary screen.
530 [mWindow setFrame:wantedFrame display:NO];
534 if (mWindowType == WindowType::Invisible) {
535 [mWindow setLevel:kCGDesktopWindowLevelKey];
538 if (mWindowType == WindowType::Popup) {
539 SetPopupWindowLevel();
540 [mWindow setBackgroundColor:NSColor.clearColor];
541 [mWindow setOpaque:NO];
543 // When multiple spaces are in use and the browser is assigned to a
544 // particular space, override the "Assign To" space and display popups on
545 // the active space. Does not work with multiple displays. See
546 // NeedsRecreateToReshow() for multi-display with multi-space workaround.
548 NSWindowCollectionBehavior behavior = [mWindow collectionBehavior];
549 behavior |= NSWindowCollectionBehaviorMoveToActiveSpace;
550 [mWindow setCollectionBehavior:behavior];
553 // Non-popup windows are always opaque.
554 [mWindow setOpaque:YES];
557 NSWindowCollectionBehavior newBehavior = [mWindow collectionBehavior];
559 [mWindow setLevel:NSFloatingWindowLevel];
560 newBehavior |= NSWindowCollectionBehaviorCanJoinAllSpaces;
562 [mWindow setCollectionBehavior:newBehavior];
564 [mWindow setContentMinSize:NSMakeSize(60, 60)];
565 [mWindow disableCursorRects];
567 // Make the window use CoreAnimation from the start, so that we don't
568 // switch from a non-CA window to a CA-window in the middle.
569 [[mWindow contentView] setWantsLayer:YES];
571 // Make sure the window starts out not draggable by the background.
572 // We will turn it on as necessary.
573 [mWindow setMovableByWindowBackground:NO];
575 [[WindowDataMap sharedWindowDataMap] ensureDataForWindow:mWindow];
576 mWindowMadeHere = true;
578 // Make the window respect the global appearance, which follows the
579 // browser.theme.toolbar-theme pref.
580 mWindow.appearanceSource = MOZGlobalAppearance.sharedInstance;
584 NS_OBJC_END_TRY_BLOCK_RETURN(NS_ERROR_FAILURE);
587 nsresult nsCocoaWindow::CreatePopupContentView(const LayoutDeviceIntRect& aRect,
588 widget::InitData* aInitData) {
589 NS_OBJC_BEGIN_TRY_BLOCK_RETURN;
591 // We need to make our content view a ChildView.
592 mPopupContentView = new nsChildView();
593 if (!mPopupContentView) return NS_ERROR_FAILURE;
595 NS_ADDREF(mPopupContentView);
597 nsIWidget* thisAsWidget = static_cast<nsIWidget*>(this);
599 mPopupContentView->Create(thisAsWidget, nullptr, aRect, aInitData);
600 if (NS_WARN_IF(NS_FAILED(rv))) {
604 NSView* contentView = [mWindow contentView];
605 ChildView* childView =
606 (ChildView*)mPopupContentView->GetNativeData(NS_NATIVE_WIDGET);
607 [childView setFrame:[contentView bounds]];
608 [childView setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable];
609 [contentView addSubview:childView];
613 NS_OBJC_END_TRY_BLOCK_RETURN(NS_ERROR_FAILURE);
616 void nsCocoaWindow::Destroy() {
617 if (mOnDestroyCalled) return;
618 mOnDestroyCalled = true;
620 // SetFakeModal(true) is called for non-modal window opened by modal window.
621 // On Cocoa, it needs corresponding SetFakeModal(false) on destroy to restore
622 // ancestor windows' state.
627 // If we don't hide here we run into problems with panels, this is not ideal.
631 if (mPopupContentView) mPopupContentView->Destroy();
633 if (mFullscreenTransitionAnimation) {
634 [mFullscreenTransitionAnimation stopAnimation];
635 ReleaseFullscreenTransitionAnimation();
638 nsBaseWidget::Destroy();
639 // nsBaseWidget::Destroy() calls GetParent()->RemoveChild(this). But we
640 // don't implement GetParent(), so we need to do the equivalent here.
642 mParent->RemoveChild(this);
644 nsBaseWidget::OnDestroy();
646 if (mInFullScreenMode && !mInNativeFullScreenMode) {
647 // Keep these calls balanced for emulated fullscreen.
648 nsCocoaUtils::HideOSChromeOnScreen(false);
651 // Destroy the native window here (and not wait for that to happen in our
652 // destructor). Otherwise this might not happen for several seconds because
653 // at least one object holding a reference to ourselves is usually waiting
654 // to be garbage-collected.
655 if (mWindow && mWindowMadeHere) {
656 DestroyNativeWindow();
660 nsIWidget* nsCocoaWindow::GetSheetWindowParent(void) {
661 if (mWindowType != WindowType::Sheet) return nullptr;
662 nsCocoaWindow* parent = static_cast<nsCocoaWindow*>(mParent);
663 while (parent && (parent->mWindowType == WindowType::Sheet))
664 parent = static_cast<nsCocoaWindow*>(parent->mParent);
668 void* nsCocoaWindow::GetNativeData(uint32_t aDataType) {
669 NS_OBJC_BEGIN_TRY_BLOCK_RETURN;
671 void* retVal = nullptr;
674 // to emulate how windows works, we always have to return a NSView
675 // for NS_NATIVE_WIDGET
676 case NS_NATIVE_WIDGET:
677 retVal = [mWindow contentView];
680 case NS_NATIVE_WINDOW:
684 case NS_NATIVE_GRAPHIC:
685 // There isn't anything that makes sense to return here,
686 // and it doesn't matter so just return nullptr.
687 NS_ERROR("Requesting NS_NATIVE_GRAPHIC on a top-level window!");
689 case NS_RAW_NATIVE_IME_CONTEXT: {
690 retVal = GetPseudoIMEContext();
694 NSView* view = mWindow ? [mWindow contentView] : nil;
696 retVal = [view inputContext];
698 // If inputContext isn't available on this window, return this window's
699 // pointer instead of nullptr since if this returns nullptr,
700 // IMEStateManager cannot manage composition with TextComposition
701 // instance. Although, this case shouldn't occur.
702 if (NS_WARN_IF(!retVal)) {
711 NS_OBJC_END_TRY_BLOCK_RETURN(nullptr);
714 bool nsCocoaWindow::IsVisible() const {
715 NS_OBJC_BEGIN_TRY_BLOCK_RETURN;
717 return (mWindow && ([mWindow isVisibleOrBeingShown] || mSheetNeedsShow));
719 NS_OBJC_END_TRY_BLOCK_RETURN(false);
722 void nsCocoaWindow::SetModal(bool aState) {
723 NS_OBJC_BEGIN_TRY_IGNORE_BLOCK;
725 if (!mWindow) return;
727 // This is used during startup (outside the event loop) when creating
728 // the add-ons compatibility checking dialog and the profile manager UI;
729 // therefore, it needs to provide an autorelease pool to avoid cocoa
731 nsAutoreleasePool localPool;
734 nsCocoaWindow* ancestor = static_cast<nsCocoaWindow*>(mAncestorLink);
737 // When a non-sheet window gets "set modal", make the window(s) that it
738 // appears over behave as they should. We can't rely on native methods to
739 // do this, for the following reason: The OS runs modal non-sheet windows
740 // in an event loop (using [NSApplication runModalForWindow:] or similar
741 // methods) that's incompatible with the modal event loop in AppWindow::
742 // ShowModal() (each of these event loops is "exclusive", and can't run at
743 // the same time as other (similar) event loops).
744 if (mWindowType != WindowType::Sheet) {
746 if (ancestor->mNumModalDescendents++ == 0) {
747 NSWindow* aWindow = ancestor->GetCocoaWindow();
748 if (ancestor->mWindowType != WindowType::Invisible) {
749 [[aWindow standardWindowButton:NSWindowCloseButton] setEnabled:NO];
750 [[aWindow standardWindowButton:NSWindowMiniaturizeButton]
752 [[aWindow standardWindowButton:NSWindowZoomButton] setEnabled:NO];
755 ancestor = static_cast<nsCocoaWindow*>(ancestor->mParent);
757 [mWindow setLevel:NSModalPanelWindowLevel];
758 nsCocoaWindowList* windowList = new nsCocoaWindowList;
760 windowList->window = this; // Don't ADDREF
761 windowList->prev = gGeckoAppModalWindowList;
762 gGeckoAppModalWindowList = windowList;
767 NS_ASSERTION(gXULModalLevel >= 0,
768 "Mismatched call to nsCocoaWindow::SetModal(false)!");
769 if (mWindowType != WindowType::Sheet) {
771 if (--ancestor->mNumModalDescendents == 0) {
772 NSWindow* aWindow = ancestor->GetCocoaWindow();
773 if (ancestor->mWindowType != WindowType::Invisible) {
774 [[aWindow standardWindowButton:NSWindowCloseButton] setEnabled:YES];
775 [[aWindow standardWindowButton:NSWindowMiniaturizeButton]
777 [[aWindow standardWindowButton:NSWindowZoomButton] setEnabled:YES];
780 NS_ASSERTION(ancestor->mNumModalDescendents >= 0,
781 "Widget hierarchy changed while modal!");
782 ancestor = static_cast<nsCocoaWindow*>(ancestor->mParent);
784 if (gGeckoAppModalWindowList) {
785 NS_ASSERTION(gGeckoAppModalWindowList->window == this,
786 "Widget hierarchy changed while modal!");
787 nsCocoaWindowList* saved = gGeckoAppModalWindowList;
788 gGeckoAppModalWindowList = gGeckoAppModalWindowList->prev;
789 delete saved; // "window" not ADDREFed
791 if (mWindowType == WindowType::Popup)
792 SetPopupWindowLevel();
794 [mWindow setLevel:NSNormalWindowLevel];
798 NS_OBJC_END_TRY_IGNORE_BLOCK;
801 void nsCocoaWindow::SetFakeModal(bool aState) {
806 bool nsCocoaWindow::IsRunningAppModal() { return [NSApp _isRunningAppModal]; }
808 // Hide or show this window
809 void nsCocoaWindow::Show(bool bState) {
810 NS_OBJC_BEGIN_TRY_IGNORE_BLOCK;
812 if (!mWindow) return;
814 if (!mSheetNeedsShow) {
815 // Early exit if our current visibility state is already the requested
817 if (bState == ([mWindow isVisible] || [mWindow isBeingShown])) {
822 [mWindow setBeingShown:bState];
823 if (bState && !mWasShown) {
827 nsIWidget* parentWidget = mParent;
828 nsCOMPtr<nsPIWidgetCocoa> piParentWidget(do_QueryInterface(parentWidget));
829 NSWindow* nativeParentWindow =
830 (parentWidget) ? (NSWindow*)parentWidget->GetNativeData(NS_NATIVE_WINDOW)
833 if (bState && !mBounds.IsEmpty()) {
834 // If we had set the activationPolicy to accessory, then right now we won't
835 // have a dock icon. Make sure that we undo that and show a dock icon now
836 // that we're going to show a window.
837 if ([NSApp activationPolicy] != NSApplicationActivationPolicyRegular) {
838 [NSApp setActivationPolicy:NSApplicationActivationPolicyRegular];
839 PR_SetEnv("MOZ_APP_NO_DOCK=");
842 // Don't try to show a popup when the parent isn't visible or is minimized.
843 if (mWindowType == WindowType::Popup && nativeParentWindow) {
844 if (![nativeParentWindow isVisible] ||
845 [nativeParentWindow isMiniaturized]) {
850 if (mPopupContentView) {
851 // Ensure our content view is visible. We never need to hide it.
852 mPopupContentView->Show(true);
855 if (mWindowType == WindowType::Sheet) {
856 // bail if no parent window (its basically what we do in Carbon)
857 if (!nativeParentWindow || !piParentWidget) return;
859 NSWindow* topNonSheetWindow = nativeParentWindow;
861 // If this sheet is the child of another sheet, hide the parent so that
862 // this sheet can be displayed. Leave the parent mSheetNeedsShow alone,
863 // that is only used to handle sibling sheet contention. The parent will
864 // return once there are no more child sheets.
865 bool parentIsSheet = false;
866 if (NS_SUCCEEDED(piParentWidget->GetIsSheet(&parentIsSheet)) &&
868 piParentWidget->GetSheetWindowParent(&topNonSheetWindow);
869 #ifdef MOZ_THUNDERBIRD
870 [NSApp endSheet:nativeParentWindow];
872 [nativeParentWindow.sheetParent endSheet:nativeParentWindow];
876 nsCOMPtr<nsIWidget> sheetShown;
877 if (NS_SUCCEEDED(piParentWidget->GetChildSheet(
878 true, getter_AddRefs(sheetShown))) &&
879 (!sheetShown || sheetShown == this)) {
880 // If this sheet is already the sheet actually being shown, don't
881 // tell it to show again. Otherwise the number of calls to
882 #ifdef MOZ_THUNDERBIRD
883 // [NSApp beginSheet...] won't match up with [NSApp endSheet...].
885 // [NSWindow beginSheet...] won't match up with [NSWindow endSheet...].
887 if (![mWindow isVisible]) {
888 mSheetNeedsShow = false;
889 mSheetWindowParent = topNonSheetWindow;
890 #ifdef MOZ_THUNDERBIRD
891 // Only set contextInfo if our parent isn't a sheet.
892 NSWindow* contextInfo = parentIsSheet ? nil : mSheetWindowParent;
893 [TopLevelWindowData deactivateInWindow:mSheetWindowParent];
894 [NSApp beginSheet:mWindow
895 modalForWindow:mSheetWindowParent
896 modalDelegate:mDelegate
897 didEndSelector:@selector(didEndSheet:returnCode:contextInfo:)
898 contextInfo:contextInfo];
900 NSWindow* sheet = mWindow;
901 NSWindow* nonSheetParent = parentIsSheet ? nil : mSheetWindowParent;
902 [TopLevelWindowData deactivateInWindow:mSheetWindowParent];
903 [mSheetWindowParent beginSheet:sheet
904 completionHandler:^(NSModalResponse returnCode) {
905 // Note: 'nonSheetParent' (if it is set) is the window
906 // that is the parent of the sheet. If it's set,
907 // 'nonSheetParent' is always the top- level window,
908 // not another sheet itself. But 'nonSheetParent' is
909 // nil if our parent window is also a sheet -- in that
910 // case we shouldn't send the top-level window any
911 // activate events (because it's our parent window that
912 // needs to get these events, not the top-level
914 [TopLevelWindowData deactivateInWindow:sheet];
915 [sheet orderOut:nil];
916 if (nonSheetParent) {
917 [TopLevelWindowData activateInWindow:nonSheetParent];
921 [TopLevelWindowData activateInWindow:mWindow];
922 SendSetZLevelEvent();
925 // A sibling of this sheet is active, don't show this sheet yet.
926 // When the active sheet hides, its brothers and sisters that have
927 // mSheetNeedsShow set will have their opportunities to display.
928 mSheetNeedsShow = true;
930 } else if (mWindowType == WindowType::Popup) {
931 // For reasons that aren't yet clear, calls to [NSWindow orderFront:] or
932 // [NSWindow makeKeyAndOrderFront:] can sometimes trigger "Error (1000)
933 // creating CGSWindow", which in turn triggers an internal inconsistency
934 // NSException. These errors shouldn't be fatal. So we need to wrap
935 // calls to ...orderFront: in TRY blocks. See bmo bug 470864.
936 NS_OBJC_BEGIN_TRY_IGNORE_BLOCK;
937 [[mWindow contentView] setNeedsDisplay:YES];
938 [mWindow orderFront:nil];
939 NS_OBJC_END_TRY_IGNORE_BLOCK;
940 SendSetZLevelEvent();
941 // If our popup window is a non-native context menu, tell the OS (and
942 // other programs) that a menu has opened. This is how the OS knows to
943 // close other programs' context menus when ours open.
944 if ([mWindow isKindOfClass:[PopupWindow class]] &&
945 [(PopupWindow*)mWindow isContextMenu]) {
946 [[NSDistributedNotificationCenter defaultCenter]
947 postNotificationName:
948 @"com.apple.HIToolbox.beginMenuTrackingNotification"
949 object:@"org.mozilla.gecko.PopupWindow"];
952 // If a parent window was supplied and this is a popup at the parent
953 // level, set its child window. This will cause the child window to
954 // appear above the parent and move when the parent does. Setting this
955 // needs to happen after the _setWindowNumber calls above, otherwise the
956 // window doesn't focus properly.
957 if (nativeParentWindow && mPopupLevel == PopupLevel::Parent)
958 [nativeParentWindow addChildWindow:mWindow ordered:NSWindowAbove];
960 NS_OBJC_BEGIN_TRY_IGNORE_BLOCK;
961 if (mWindowType == WindowType::TopLevel &&
962 [mWindow respondsToSelector:@selector(setAnimationBehavior:)]) {
963 NSWindowAnimationBehavior behavior;
964 if (mIsAnimationSuppressed) {
965 behavior = NSWindowAnimationBehaviorNone;
967 switch (mAnimationType) {
968 case nsIWidget::eDocumentWindowAnimation:
969 behavior = NSWindowAnimationBehaviorDocumentWindow;
972 MOZ_FALLTHROUGH_ASSERT("unexpected mAnimationType value");
973 case nsIWidget::eGenericWindowAnimation:
974 behavior = NSWindowAnimationBehaviorDefault;
978 [mWindow setAnimationBehavior:behavior];
979 mWindowAnimationBehavior = behavior;
982 // We don't want alwaysontop windows to pull focus when they're opened,
983 // as these tend to be for peripheral indicators and displays.
985 [mWindow orderFront:nil];
987 [mWindow makeKeyAndOrderFront:nil];
989 NS_OBJC_END_TRY_IGNORE_BLOCK;
990 SendSetZLevelEvent();
993 // roll up any popups if a top-level window is going away
994 if (mWindowType == WindowType::TopLevel ||
995 mWindowType == WindowType::Dialog) {
999 // now get rid of the window/sheet
1000 if (mWindowType == WindowType::Sheet) {
1001 if (mSheetNeedsShow) {
1002 // This is an attempt to hide a sheet that never had a chance to
1003 // be shown. There's nothing to do other than make sure that it
1005 mSheetNeedsShow = false;
1007 // get sheet's parent *before* hiding the sheet (which breaks the
1009 NSWindow* sheetParent = mSheetWindowParent;
1012 #ifdef MOZ_THUNDERBIRD
1013 [NSApp endSheet:mWindow];
1015 [mSheetWindowParent endSheet:mWindow];
1017 [TopLevelWindowData deactivateInWindow:mWindow];
1019 nsCOMPtr<nsIWidget> siblingSheetToShow;
1020 bool parentIsSheet = false;
1022 if (nativeParentWindow && piParentWidget &&
1023 NS_SUCCEEDED(piParentWidget->GetChildSheet(
1024 false, getter_AddRefs(siblingSheetToShow))) &&
1025 siblingSheetToShow) {
1026 // First, give sibling sheets an opportunity to show.
1027 siblingSheetToShow->Show(true);
1028 } else if (nativeParentWindow && piParentWidget &&
1029 NS_SUCCEEDED(piParentWidget->GetIsSheet(&parentIsSheet)) &&
1031 #ifdef MOZ_THUNDERBIRD
1032 // Only set contextInfo if the parent of the parent sheet we're about
1033 // to restore isn't itself a sheet.
1034 NSWindow* contextInfo = sheetParent;
1036 // Only set nonSheetGrandparent if the parent of the parent sheet
1037 // we're about to restore isn't itself a sheet.
1038 NSWindow* nonSheetGrandparent = sheetParent;
1040 nsIWidget* grandparentWidget = nil;
1041 if (NS_SUCCEEDED(piParentWidget->GetRealParent(&grandparentWidget)) &&
1042 grandparentWidget) {
1043 nsCOMPtr<nsPIWidgetCocoa> piGrandparentWidget(
1044 do_QueryInterface(grandparentWidget));
1045 bool grandparentIsSheet = false;
1046 if (piGrandparentWidget &&
1048 piGrandparentWidget->GetIsSheet(&grandparentIsSheet)) &&
1049 grandparentIsSheet) {
1050 #ifdef MOZ_THUNDERBIRD
1053 nonSheetGrandparent = nil;
1057 // If there are no sibling sheets, but the parent is a sheet, restore
1058 // it. It wasn't sent any deactivate events when it was hidden, so
1059 // don't call through Show, just let the OS put it back up.
1060 #ifdef MOZ_THUNDERBIRD
1061 [NSApp beginSheet:nativeParentWindow
1062 modalForWindow:sheetParent
1063 modalDelegate:[nativeParentWindow delegate]
1064 didEndSelector:@selector(didEndSheet:returnCode:contextInfo:)
1065 contextInfo:contextInfo];
1068 beginSheet:sheetParent
1069 completionHandler:^(NSModalResponse returnCode) {
1070 // Note: 'nonSheetGrandparent' (if it is set) is the window that
1071 // is the parent of sheetParent. If it's set,
1072 // 'nonSheetGrandparent' is always the top-level window, not
1073 // another sheet itself. But 'nonSheetGrandparent' is nil if
1074 // our parent window is also a sheet -- in that case we
1075 // shouldn't send the top-level window any activate events
1076 // (because it's our parent window that needs to get these
1077 // events, not the top-level window).
1078 [TopLevelWindowData deactivateInWindow:sheetParent];
1079 [sheetParent orderOut:nil];
1080 if (nonSheetGrandparent) {
1081 [TopLevelWindowData activateInWindow:nonSheetGrandparent];
1086 // Sheet, that was hard. No more siblings or parents, going back
1087 // to a real window.
1088 NS_OBJC_BEGIN_TRY_IGNORE_BLOCK;
1089 [sheetParent makeKeyAndOrderFront:nil];
1090 NS_OBJC_END_TRY_IGNORE_BLOCK;
1092 SendSetZLevelEvent();
1095 // If the window is a popup window with a parent window we need to
1096 // unhook it here before ordering it out. When you order out the child
1097 // of a window it hides the parent window.
1098 if (mWindowType == WindowType::Popup && nativeParentWindow)
1099 [nativeParentWindow removeChildWindow:mWindow];
1101 [mWindow orderOut:nil];
1103 // If our popup window is a non-native context menu, tell the OS (and
1104 // other programs) that a menu has closed.
1105 if ([mWindow isKindOfClass:[PopupWindow class]] &&
1106 [(PopupWindow*)mWindow isContextMenu]) {
1107 [[NSDistributedNotificationCenter defaultCenter]
1108 postNotificationName:
1109 @"com.apple.HIToolbox.endMenuTrackingNotification"
1110 object:@"org.mozilla.gecko.PopupWindow"];
1115 [mWindow setBeingShown:NO];
1117 NS_OBJC_END_TRY_IGNORE_BLOCK;
1120 // Work around a problem where with multiple displays and multiple spaces
1121 // enabled, where the browser is assigned to a single display or space, popup
1122 // windows that are reshown after being hidden with [NSWindow orderOut] show on
1123 // the assigned space even when opened from another display. Apply the
1124 // workaround whenever more than one display is enabled.
1125 bool nsCocoaWindow::NeedsRecreateToReshow() {
1126 // Limit the workaround to popup windows because only they need to override
1127 // the "Assign To" setting. i.e., to display where the parent window is.
1128 return (mWindowType == WindowType::Popup) && mWasShown &&
1129 ([[NSScreen screens] count] > 1);
1132 WindowRenderer* nsCocoaWindow::GetWindowRenderer() {
1133 if (mPopupContentView) {
1134 return mPopupContentView->GetWindowRenderer();
1139 TransparencyMode nsCocoaWindow::GetTransparencyMode() {
1140 NS_OBJC_BEGIN_TRY_BLOCK_RETURN;
1142 return (!mWindow || [mWindow isOpaque]) ? TransparencyMode::Opaque
1143 : TransparencyMode::Transparent;
1145 NS_OBJC_END_TRY_BLOCK_RETURN(TransparencyMode::Opaque);
1148 // This is called from nsMenuPopupFrame when making a popup transparent.
1149 void nsCocoaWindow::SetTransparencyMode(TransparencyMode aMode) {
1150 NS_OBJC_BEGIN_TRY_IGNORE_BLOCK;
1156 BOOL isTransparent = aMode == TransparencyMode::Transparent;
1157 BOOL currentTransparency = !mWindow.isOpaque;
1158 if (isTransparent == currentTransparency) {
1161 [mWindow setOpaque:!isTransparent];
1162 [mWindow setBackgroundColor:(isTransparent ? NSColor.clearColor
1163 : NSColor.whiteColor)];
1165 NS_OBJC_END_TRY_IGNORE_BLOCK;
1168 void nsCocoaWindow::Enable(bool aState) {}
1170 bool nsCocoaWindow::IsEnabled() const { return true; }
1172 void nsCocoaWindow::ConstrainPosition(DesktopIntPoint& aPoint) {
1173 NS_OBJC_BEGIN_TRY_IGNORE_BLOCK;
1175 if (!mWindow || ![mWindow screen]) {
1179 nsIntRect screenBounds;
1181 int32_t width, height;
1183 NSRect frame = [mWindow frame];
1185 // zero size rects confuse the screen manager
1186 width = std::max<int32_t>(frame.size.width, 1);
1187 height = std::max<int32_t>(frame.size.height, 1);
1189 nsCOMPtr<nsIScreenManager> screenMgr =
1190 do_GetService("@mozilla.org/gfx/screenmanager;1");
1192 nsCOMPtr<nsIScreen> screen;
1193 screenMgr->ScreenForRect(aPoint.x, aPoint.y, width, height,
1194 getter_AddRefs(screen));
1197 screen->GetRectDisplayPix(&(screenBounds.x), &(screenBounds.y),
1198 &(screenBounds.width), &(screenBounds.height));
1202 if (aPoint.x < screenBounds.x) {
1203 aPoint.x = screenBounds.x;
1204 } else if (aPoint.x >= screenBounds.x + screenBounds.width - width) {
1205 aPoint.x = screenBounds.x + screenBounds.width - width;
1208 if (aPoint.y < screenBounds.y) {
1209 aPoint.y = screenBounds.y;
1210 } else if (aPoint.y >= screenBounds.y + screenBounds.height - height) {
1211 aPoint.y = screenBounds.y + screenBounds.height - height;
1214 NS_OBJC_END_TRY_IGNORE_BLOCK;
1217 void nsCocoaWindow::SetSizeConstraints(const SizeConstraints& aConstraints) {
1218 NS_OBJC_BEGIN_TRY_IGNORE_BLOCK;
1220 // Popups can be smaller than (32, 32)
1221 NSRect rect = (mWindowType == WindowType::Popup)
1223 : NSMakeRect(0.0, 0.0, 32, 32);
1224 rect = [mWindow frameRectForChildViewRect:rect];
1226 SizeConstraints c = aConstraints;
1228 if (c.mScale.scale == MOZ_WIDGET_INVALID_SCALE) {
1229 c.mScale.scale = BackingScaleFactor();
1232 c.mMinSize.width = std::max(
1233 nsCocoaUtils::CocoaPointsToDevPixels(rect.size.width, c.mScale.scale),
1235 c.mMinSize.height = std::max(
1236 nsCocoaUtils::CocoaPointsToDevPixels(rect.size.height, c.mScale.scale),
1240 nsCocoaUtils::DevPixelsToCocoaPoints(c.mMinSize.width, c.mScale.scale),
1241 nsCocoaUtils::DevPixelsToCocoaPoints(c.mMinSize.height, c.mScale.scale)};
1242 [mWindow setMinSize:minSize];
1244 c.mMaxSize.width = std::max(
1245 nsCocoaUtils::CocoaPointsToDevPixels(c.mMaxSize.width, c.mScale.scale),
1247 c.mMaxSize.height = std::max(
1248 nsCocoaUtils::CocoaPointsToDevPixels(c.mMaxSize.height, c.mScale.scale),
1252 c.mMaxSize.width == NS_MAXSIZE ? FLT_MAX
1253 : nsCocoaUtils::DevPixelsToCocoaPoints(
1254 c.mMaxSize.width, c.mScale.scale),
1255 c.mMaxSize.height == NS_MAXSIZE ? FLT_MAX
1256 : nsCocoaUtils::DevPixelsToCocoaPoints(
1257 c.mMaxSize.height, c.mScale.scale)};
1258 [mWindow setMaxSize:maxSize];
1260 nsBaseWidget::SetSizeConstraints(c);
1262 NS_OBJC_END_TRY_IGNORE_BLOCK;
1265 // Coordinates are desktop pixels
1266 void nsCocoaWindow::Move(double aX, double aY) {
1267 NS_OBJC_BEGIN_TRY_IGNORE_BLOCK;
1273 // The point we have is in Gecko coordinates (origin top-left). Convert
1274 // it to Cocoa ones (origin bottom-left).
1276 static_cast<float>(aX),
1277 static_cast<float>(nsCocoaUtils::FlippedScreenY(NSToIntRound(aY)))};
1279 NSRect frame = [mWindow frame];
1280 if (frame.origin.x != coord.x ||
1281 frame.origin.y + frame.size.height != coord.y) {
1282 [mWindow setFrameTopLeftPoint:coord];
1285 NS_OBJC_END_TRY_IGNORE_BLOCK;
1288 void nsCocoaWindow::SetSizeMode(nsSizeMode aMode) {
1289 if (aMode == nsSizeMode_Normal) {
1290 QueueTransition(TransitionType::Windowed);
1291 } else if (aMode == nsSizeMode_Minimized) {
1292 QueueTransition(TransitionType::Miniaturize);
1293 } else if (aMode == nsSizeMode_Maximized) {
1294 QueueTransition(TransitionType::Zoom);
1295 } else if (aMode == nsSizeMode_Fullscreen) {
1296 MakeFullScreen(true);
1300 // The (work)space switching implementation below was inspired by Phoenix:
1301 // https://github.com/kasper/phoenix/tree/d6c877f62b30a060dff119d8416b0934f76af534
1304 // Runtime `CGSGetActiveSpace` library function feature detection.
1305 typedef CGSSpaceID (*CGSGetActiveSpaceFunc)(CGSConnection cid);
1306 static CGSGetActiveSpaceFunc GetCGSGetActiveSpaceFunc() {
1307 static CGSGetActiveSpaceFunc func = nullptr;
1308 static bool lookedUpFunc = false;
1309 if (!lookedUpFunc) {
1310 func = (CGSGetActiveSpaceFunc)dlsym(RTLD_DEFAULT, "CGSGetActiveSpace");
1311 lookedUpFunc = true;
1315 // Runtime `CGSCopyManagedDisplaySpaces` library function feature detection.
1316 typedef CFArrayRef (*CGSCopyManagedDisplaySpacesFunc)(CGSConnection cid);
1317 static CGSCopyManagedDisplaySpacesFunc GetCGSCopyManagedDisplaySpacesFunc() {
1318 static CGSCopyManagedDisplaySpacesFunc func = nullptr;
1319 static bool lookedUpFunc = false;
1320 if (!lookedUpFunc) {
1321 func = (CGSCopyManagedDisplaySpacesFunc)dlsym(
1322 RTLD_DEFAULT, "CGSCopyManagedDisplaySpaces");
1323 lookedUpFunc = true;
1327 // Runtime `CGSCopySpacesForWindows` library function feature detection.
1328 typedef CFArrayRef (*CGSCopySpacesForWindowsFunc)(CGSConnection cid,
1330 CFArrayRef windowIDs);
1331 static CGSCopySpacesForWindowsFunc GetCGSCopySpacesForWindowsFunc() {
1332 static CGSCopySpacesForWindowsFunc func = nullptr;
1333 static bool lookedUpFunc = false;
1334 if (!lookedUpFunc) {
1335 func = (CGSCopySpacesForWindowsFunc)dlsym(RTLD_DEFAULT,
1336 "CGSCopySpacesForWindows");
1337 lookedUpFunc = true;
1341 // Runtime `CGSAddWindowsToSpaces` library function feature detection.
1342 typedef void (*CGSAddWindowsToSpacesFunc)(CGSConnection cid,
1343 CFArrayRef windowIDs,
1344 CFArrayRef spaceIDs);
1345 static CGSAddWindowsToSpacesFunc GetCGSAddWindowsToSpacesFunc() {
1346 static CGSAddWindowsToSpacesFunc func = nullptr;
1347 static bool lookedUpFunc = false;
1348 if (!lookedUpFunc) {
1350 (CGSAddWindowsToSpacesFunc)dlsym(RTLD_DEFAULT, "CGSAddWindowsToSpaces");
1351 lookedUpFunc = true;
1355 // Runtime `CGSRemoveWindowsFromSpaces` library function feature detection.
1356 typedef void (*CGSRemoveWindowsFromSpacesFunc)(CGSConnection cid,
1357 CFArrayRef windowIDs,
1358 CFArrayRef spaceIDs);
1359 static CGSRemoveWindowsFromSpacesFunc GetCGSRemoveWindowsFromSpacesFunc() {
1360 static CGSRemoveWindowsFromSpacesFunc func = nullptr;
1361 static bool lookedUpFunc = false;
1362 if (!lookedUpFunc) {
1363 func = (CGSRemoveWindowsFromSpacesFunc)dlsym(RTLD_DEFAULT,
1364 "CGSRemoveWindowsFromSpaces");
1365 lookedUpFunc = true;
1370 void nsCocoaWindow::GetWorkspaceID(nsAString& workspaceID) {
1371 workspaceID.Truncate();
1372 int32_t sid = GetWorkspaceID();
1374 workspaceID.AppendInt(sid);
1378 int32_t nsCocoaWindow::GetWorkspaceID() {
1379 NS_OBJC_BEGIN_TRY_IGNORE_BLOCK;
1381 // Mac OSX space IDs start at '1' (default space), so '0' means 'unknown',
1385 CGSCopySpacesForWindowsFunc CopySpacesForWindows =
1386 GetCGSCopySpacesForWindowsFunc();
1387 if (!CopySpacesForWindows) {
1391 CGSConnection cid = _CGSDefaultConnection();
1392 // Fetch all spaces that this window belongs to (in order).
1393 NSArray<NSNumber*>* spaceIDs = CFBridgingRelease(CopySpacesForWindows(
1394 cid, kCGSAllSpacesMask,
1395 (__bridge CFArrayRef) @[ @([mWindow windowNumber]) ]));
1396 if ([spaceIDs count]) {
1397 // When spaces are found, return the first one.
1398 // We don't support a single window painted across multiple places for now.
1399 sid = [spaceIDs[0] integerValue];
1401 // Fall back to the workspace that's currently active, which is '1' in the
1403 CGSGetActiveSpaceFunc GetActiveSpace = GetCGSGetActiveSpaceFunc();
1404 if (GetActiveSpace) {
1405 sid = GetActiveSpace(cid);
1411 NS_OBJC_END_TRY_IGNORE_BLOCK;
1414 void nsCocoaWindow::MoveToWorkspace(const nsAString& workspaceIDStr) {
1415 NS_OBJC_BEGIN_TRY_IGNORE_BLOCK;
1417 if ([NSScreen screensHaveSeparateSpaces] && [[NSScreen screens] count] > 1) {
1418 // We don't support moving to a workspace when the user has this option
1419 // enabled in Mission Control.
1423 nsresult rv = NS_OK;
1424 int32_t workspaceID = workspaceIDStr.ToInteger(&rv);
1425 if (NS_FAILED(rv)) {
1429 CGSConnection cid = _CGSDefaultConnection();
1430 int32_t currentSpace = GetWorkspaceID();
1431 // If an empty workspace ID is passed in (not valid on OSX), or when the
1432 // window is already on this workspace, we don't need to do anything.
1433 if (!workspaceID || workspaceID == currentSpace) {
1437 CGSCopyManagedDisplaySpacesFunc CopyManagedDisplaySpaces =
1438 GetCGSCopyManagedDisplaySpacesFunc();
1439 CGSAddWindowsToSpacesFunc AddWindowsToSpaces = GetCGSAddWindowsToSpacesFunc();
1440 CGSRemoveWindowsFromSpacesFunc RemoveWindowsFromSpaces =
1441 GetCGSRemoveWindowsFromSpacesFunc();
1442 if (!CopyManagedDisplaySpaces || !AddWindowsToSpaces ||
1443 !RemoveWindowsFromSpaces) {
1447 // Fetch an ordered list of all known spaces.
1448 NSArray* displaySpacesInfo = CFBridgingRelease(CopyManagedDisplaySpaces(cid));
1449 // When we found the space we're looking for, we can bail out of the loop
1450 // early, which this local variable is used for.
1452 for (NSDictionary<NSString*, id>* spacesInfo in displaySpacesInfo) {
1453 NSArray<NSNumber*>* sids =
1454 [spacesInfo[CGSSpacesKey] valueForKey:CGSSpaceIDKey];
1455 for (NSNumber* sid in sids) {
1456 // If we found our space in the list, we're good to go and can jump out of
1458 if ((int)[sid integerValue] == workspaceID) {
1468 // We were unable to find the space to correspond with the workspaceID as
1469 // requested, so let's bail out.
1474 // First we add the window to the appropriate space.
1475 AddWindowsToSpaces(cid, (__bridge CFArrayRef) @[ @([mWindow windowNumber]) ],
1476 (__bridge CFArrayRef) @[ @(workspaceID) ]);
1477 // Then we remove the window from the active space.
1478 RemoveWindowsFromSpaces(cid,
1479 (__bridge CFArrayRef) @[ @([mWindow windowNumber]) ],
1480 (__bridge CFArrayRef) @[ @(currentSpace) ]);
1482 NS_OBJC_END_TRY_IGNORE_BLOCK;
1485 void nsCocoaWindow::SuppressAnimation(bool aSuppress) {
1486 if ([mWindow respondsToSelector:@selector(setAnimationBehavior:)]) {
1488 [mWindow setIsAnimationSuppressed:YES];
1489 [mWindow setAnimationBehavior:NSWindowAnimationBehaviorNone];
1491 [mWindow setIsAnimationSuppressed:NO];
1492 [mWindow setAnimationBehavior:mWindowAnimationBehavior];
1497 // This has to preserve the window's frame bounds.
1498 // This method requires (as does the Windows impl.) that you call Resize shortly
1499 // after calling HideWindowChrome. See bug 498835 for fixing this.
1500 void nsCocoaWindow::HideWindowChrome(bool aShouldHide) {
1501 NS_OBJC_BEGIN_TRY_IGNORE_BLOCK;
1503 if (!mWindow || !mWindowMadeHere ||
1504 (mWindowType != WindowType::TopLevel &&
1505 mWindowType != WindowType::Dialog))
1508 BOOL isVisible = [mWindow isVisible];
1510 // Remove child windows.
1511 NSArray* childWindows = [mWindow childWindows];
1512 NSEnumerator* enumerator = [childWindows objectEnumerator];
1513 NSWindow* child = nil;
1514 while ((child = [enumerator nextObject])) {
1515 [mWindow removeChildWindow:child];
1518 // Remove the views in the old window's content view.
1519 // The NSArray is autoreleased and retains its NSViews.
1520 NSArray<NSView*>* contentViewContents = [mWindow contentViewContents];
1521 for (NSView* view in contentViewContents) {
1522 [view removeFromSuperviewWithoutNeedingDisplay];
1525 // Save state (like window title).
1526 NSMutableDictionary* state = [mWindow exportState];
1528 // Recreate the window with the right border style.
1529 NSRect frameRect = [mWindow frame];
1530 DestroyNativeWindow();
1531 nsresult rv = CreateNativeWindow(
1532 frameRect, aShouldHide ? BorderStyle::None : mBorderStyle, true,
1533 mWindow.restorable);
1534 NS_ENSURE_SUCCESS_VOID(rv);
1537 [mWindow importState:state];
1539 // Add the old content view subviews to the new window's content view.
1540 for (NSView* view in contentViewContents) {
1541 [[mWindow contentView] addSubview:view];
1544 // Reparent child windows.
1545 enumerator = [childWindows objectEnumerator];
1546 while ((child = [enumerator nextObject])) {
1547 [mWindow addChildWindow:child ordered:NSWindowAbove];
1550 // Show the new window.
1552 bool wasAnimationSuppressed = mIsAnimationSuppressed;
1553 mIsAnimationSuppressed = true;
1555 mIsAnimationSuppressed = wasAnimationSuppressed;
1558 NS_OBJC_END_TRY_IGNORE_BLOCK;
1561 class FullscreenTransitionData : public nsISupports {
1565 explicit FullscreenTransitionData(NSWindow* aWindow)
1566 : mTransitionWindow(aWindow) {}
1568 NSWindow* mTransitionWindow;
1571 virtual ~FullscreenTransitionData() { [mTransitionWindow close]; }
1574 NS_IMPL_ISUPPORTS0(FullscreenTransitionData)
1576 @interface FullscreenTransitionDelegate : NSObject <NSAnimationDelegate> {
1578 nsCocoaWindow* mWindow;
1579 nsIRunnable* mCallback;
1583 @implementation FullscreenTransitionDelegate
1584 - (void)cleanupAndDispatch:(NSAnimation*)animation {
1585 [animation setDelegate:nil];
1587 // The caller should have added ref for us.
1588 NS_DispatchToMainThread(already_AddRefed<nsIRunnable>(mCallback));
1591 - (void)animationDidEnd:(NSAnimation*)animation {
1592 MOZ_ASSERT(animation == mWindow->FullscreenTransitionAnimation(),
1593 "Should be handling the only animation on the window");
1594 mWindow->ReleaseFullscreenTransitionAnimation();
1595 [self cleanupAndDispatch:animation];
1598 - (void)animationDidStop:(NSAnimation*)animation {
1599 [self cleanupAndDispatch:animation];
1603 static bool AlwaysUsesNativeFullScreen() {
1604 return Preferences::GetBool("full-screen-api.macos-native-full-screen",
1608 /* virtual */ bool nsCocoaWindow::PrepareForFullscreenTransition(
1609 nsISupports** aData) {
1610 if (AlwaysUsesNativeFullScreen()) {
1614 // Our fullscreen transition creates a new window occluding this window.
1615 // That triggers an occlusion event which can cause DOM fullscreen requests
1616 // to fail due to the context not being focused at the time the focus check
1617 // is performed in the child process. Until the transition is cleaned up in
1618 // CleanupFullscreenTransition(), ignore occlusion events for this window.
1619 // If this method is changed to return false, the transition will not be
1620 // performed and mIgnoreOcclusionCount should not be incremented.
1621 MOZ_ASSERT(mIgnoreOcclusionCount >= 0);
1622 mIgnoreOcclusionCount++;
1624 nsCOMPtr<nsIScreen> widgetScreen = GetWidgetScreen();
1625 NSScreen* cocoaScreen = ScreenHelperCocoa::CocoaScreenForScreen(widgetScreen);
1628 [[NSWindow alloc] initWithContentRect:[cocoaScreen frame]
1629 styleMask:NSWindowStyleMaskBorderless
1630 backing:NSBackingStoreBuffered
1632 [win setBackgroundColor:[NSColor blackColor]];
1633 [win setAlphaValue:0];
1634 [win setIgnoresMouseEvents:YES];
1635 [win setLevel:NSScreenSaverWindowLevel];
1636 [win makeKeyAndOrderFront:nil];
1638 auto data = new FullscreenTransitionData(win);
1644 /* virtual */ void nsCocoaWindow::CleanupFullscreenTransition() {
1645 MOZ_ASSERT(mIgnoreOcclusionCount > 0);
1646 mIgnoreOcclusionCount--;
1649 /* virtual */ void nsCocoaWindow::PerformFullscreenTransition(
1650 FullscreenTransitionStage aStage, uint16_t aDuration, nsISupports* aData,
1651 nsIRunnable* aCallback) {
1652 auto data = static_cast<FullscreenTransitionData*>(aData);
1653 FullscreenTransitionDelegate* delegate =
1654 [[FullscreenTransitionDelegate alloc] init];
1655 delegate->mWindow = this;
1656 // Storing already_AddRefed directly could cause static checking fail.
1657 delegate->mCallback = nsCOMPtr<nsIRunnable>(aCallback).forget().take();
1659 if (mFullscreenTransitionAnimation) {
1660 [mFullscreenTransitionAnimation stopAnimation];
1661 ReleaseFullscreenTransitionAnimation();
1664 NSDictionary* dict = @{
1665 NSViewAnimationTargetKey : data->mTransitionWindow,
1666 NSViewAnimationEffectKey : aStage == eBeforeFullscreenToggle
1667 ? NSViewAnimationFadeInEffect
1668 : NSViewAnimationFadeOutEffect
1670 mFullscreenTransitionAnimation =
1671 [[NSViewAnimation alloc] initWithViewAnimations:@[ dict ]];
1672 [mFullscreenTransitionAnimation setDelegate:delegate];
1673 [mFullscreenTransitionAnimation setDuration:aDuration / 1000.0];
1674 [mFullscreenTransitionAnimation startAnimation];
1677 void nsCocoaWindow::CocoaWindowWillEnterFullscreen(bool aFullscreen) {
1678 MOZ_ASSERT(mUpdateFullscreenOnResize.isNothing());
1680 mHasStartedNativeFullscreen = true;
1682 // Ensure that we update our fullscreen state as early as possible, when the
1684 mUpdateFullscreenOnResize =
1685 Some(aFullscreen ? TransitionType::Fullscreen : TransitionType::Windowed);
1688 void nsCocoaWindow::CocoaWindowDidEnterFullscreen(bool aFullscreen) {
1689 EndOurNativeTransition();
1690 mHasStartedNativeFullscreen = false;
1691 DispatchOcclusionEvent();
1693 // Check if aFullscreen matches our expected fullscreen state. It might not if
1694 // there was a failure somewhere along the way, in which case we'll recover
1696 bool receivedExpectedFullscreen = false;
1697 if (mUpdateFullscreenOnResize.isSome()) {
1698 bool expectingFullscreen =
1699 (*mUpdateFullscreenOnResize == TransitionType::Fullscreen);
1700 receivedExpectedFullscreen = (expectingFullscreen == aFullscreen);
1702 receivedExpectedFullscreen = (mInFullScreenMode == aFullscreen);
1705 TransitionType transition =
1706 aFullscreen ? TransitionType::Fullscreen : TransitionType::Windowed;
1707 if (receivedExpectedFullscreen) {
1708 // Everything is as expected. Update our state if needed.
1709 HandleUpdateFullscreenOnResize();
1711 // We weren't expecting this fullscreen state. Update our fullscreen state
1712 // to the new reality.
1713 UpdateFullscreenState(aFullscreen, true);
1715 // If we have a current transition, switch it to match what we just did.
1716 if (mTransitionCurrent.isSome()) {
1717 mTransitionCurrent = Some(transition);
1721 // Whether we expected this transition or not, we're ready to finish it.
1722 FinishCurrentTransitionIfMatching(transition);
1725 void nsCocoaWindow::UpdateFullscreenState(bool aFullScreen, bool aNativeMode) {
1726 bool wasInFullscreen = mInFullScreenMode;
1727 mInFullScreenMode = aFullScreen;
1728 if (aNativeMode || mInNativeFullScreenMode) {
1729 mInNativeFullScreenMode = aFullScreen;
1732 if (aFullScreen == wasInFullscreen) {
1736 DispatchSizeModeEvent();
1738 // Notify the mainChildView with our new fullscreen state.
1739 nsChildView* mainChildView =
1740 static_cast<nsChildView*>([[mWindow mainChildView] widget]);
1741 if (mainChildView) {
1742 mainChildView->UpdateFullscreen(aFullScreen);
1746 nsresult nsCocoaWindow::MakeFullScreen(bool aFullScreen) {
1747 return DoMakeFullScreen(aFullScreen, AlwaysUsesNativeFullScreen());
1750 nsresult nsCocoaWindow::MakeFullScreenWithNativeTransition(bool aFullScreen) {
1751 return DoMakeFullScreen(aFullScreen, true);
1754 nsresult nsCocoaWindow::DoMakeFullScreen(bool aFullScreen,
1755 bool aUseSystemTransition) {
1760 // Figure out what type of transition is being requested.
1761 TransitionType transition = TransitionType::Windowed;
1763 // Decide whether to use fullscreen or emulated fullscreen.
1765 (aUseSystemTransition && (mWindow.collectionBehavior &
1766 NSWindowCollectionBehaviorFullScreenPrimary))
1767 ? TransitionType::Fullscreen
1768 : TransitionType::EmulatedFullscreen;
1771 QueueTransition(transition);
1775 void nsCocoaWindow::QueueTransition(const TransitionType& aTransition) {
1776 mTransitionsPending.push(aTransition);
1777 ProcessTransitions();
1780 void nsCocoaWindow::ProcessTransitions() {
1781 NS_OBJC_BEGIN_TRY_IGNORE_BLOCK
1783 if (mInProcessTransitions) {
1787 mInProcessTransitions = true;
1789 // Start a loop that will continue as long as we have transitions to process
1790 // and we aren't waiting on an asynchronous transition to complete. Any
1791 // transition that starts something async will `continue` this loop to exit.
1792 while (!mTransitionsPending.empty() && !IsInTransition()) {
1793 TransitionType nextTransition = mTransitionsPending.front();
1795 // We have to check for some incompatible transition states, and if we find
1796 // one, instead perform an alternative transition and leave the queue
1797 // untouched. If we add one of these transitions, we set
1798 // mIsTransitionCurrentAdded because we don't want to confuse listeners who
1799 // are expecting to receive exactly one event when the requested transition
1801 switch (nextTransition) {
1802 case TransitionType::Fullscreen:
1803 case TransitionType::EmulatedFullscreen:
1804 case TransitionType::Windowed:
1805 case TransitionType::Zoom:
1806 // These can't handle miniaturized windows, so deminiaturize first.
1807 if (mWindow.miniaturized) {
1808 mTransitionCurrent = Some(TransitionType::Deminiaturize);
1809 mIsTransitionCurrentAdded = true;
1812 case TransitionType::Miniaturize:
1813 // This can't handle fullscreen, so go to windowed first.
1814 if (mInFullScreenMode) {
1815 mTransitionCurrent = Some(TransitionType::Windowed);
1816 mIsTransitionCurrentAdded = true;
1823 // If mTransitionCurrent is still empty, then we use the nextTransition and
1825 if (mTransitionCurrent.isNothing()) {
1826 mTransitionCurrent = Some(nextTransition);
1827 mTransitionsPending.pop();
1830 switch (*mTransitionCurrent) {
1831 case TransitionType::Fullscreen: {
1832 if (!mInFullScreenMode) {
1833 // Run a local run loop until it is safe to start a native fullscreen
1835 NSRunLoop* localRunLoop = [NSRunLoop currentRunLoop];
1836 while (mWindow && !CanStartNativeTransition() &&
1837 [localRunLoop runMode:NSDefaultRunLoopMode
1838 beforeDate:[NSDate distantFuture]]) {
1839 // This loop continues to process events until
1840 // CanStartNativeTransition() returns true or our native
1841 // window has been destroyed.
1844 // This triggers an async animation, so continue.
1845 [mWindow toggleFullScreen:nil];
1851 case TransitionType::EmulatedFullscreen: {
1852 if (!mInFullScreenMode) {
1853 NSDisableScreenUpdates();
1854 mSuppressSizeModeEvents = true;
1855 // The order here matters. When we exit full screen mode, we need to
1856 // show the Dock first, otherwise the newly-created window won't have
1857 // its minimize button enabled. See bug 526282.
1858 nsCocoaUtils::HideOSChromeOnScreen(true);
1859 nsBaseWidget::InfallibleMakeFullScreen(true);
1860 mSuppressSizeModeEvents = false;
1861 NSEnableScreenUpdates();
1862 UpdateFullscreenState(true, false);
1867 case TransitionType::Windowed: {
1868 if (mInFullScreenMode) {
1869 if (mInNativeFullScreenMode) {
1870 // Run a local run loop until it is safe to start a native
1871 // fullscreen transition.
1872 NSRunLoop* localRunLoop = [NSRunLoop currentRunLoop];
1873 while (mWindow && !CanStartNativeTransition() &&
1874 [localRunLoop runMode:NSDefaultRunLoopMode
1875 beforeDate:[NSDate distantFuture]]) {
1876 // This loop continues to process events until
1877 // CanStartNativeTransition() returns true or our native
1878 // window has been destroyed.
1881 // This triggers an async animation, so continue.
1882 [mWindow toggleFullScreen:nil];
1885 NSDisableScreenUpdates();
1886 mSuppressSizeModeEvents = true;
1887 // The order here matters. When we exit full screen mode, we need to
1888 // show the Dock first, otherwise the newly-created window won't
1889 // have its minimize button enabled. See bug 526282.
1890 nsCocoaUtils::HideOSChromeOnScreen(false);
1891 nsBaseWidget::InfallibleMakeFullScreen(false);
1892 mSuppressSizeModeEvents = false;
1893 NSEnableScreenUpdates();
1894 UpdateFullscreenState(false, false);
1896 } else if (mWindow.zoomed) {
1899 // Check if we're still zoomed. If we are, we need to do *something*
1900 // to make the window smaller than the zoom size so Cocoa will treat
1901 // us as being out of the zoomed state. Otherwise, we could stay
1902 // zoomed and never be able to be "normal" from calls to SetSizeMode.
1903 if (mWindow.zoomed) {
1904 NSRect maximumFrame = mWindow.frame;
1905 const CGFloat INSET_OUT_OF_ZOOM = 20.0f;
1906 [mWindow setFrame:NSInsetRect(maximumFrame, INSET_OUT_OF_ZOOM,
1911 "We should be able to unzoom by shrinking the frame a bit.");
1917 case TransitionType::Miniaturize:
1918 if (!mWindow.miniaturized) {
1919 // This triggers an async animation, so continue.
1920 [mWindow miniaturize:nil];
1925 case TransitionType::Deminiaturize:
1926 if (mWindow.miniaturized) {
1927 // This triggers an async animation, so continue.
1928 [mWindow deminiaturize:nil];
1933 case TransitionType::Zoom:
1934 if (!mWindow.zoomed) {
1943 mTransitionCurrent.reset();
1944 mIsTransitionCurrentAdded = false;
1947 mInProcessTransitions = false;
1949 // When we finish processing transitions, dispatch a size mode event to cover
1950 // the cases where an inserted transition suppressed one, and the original
1951 // transition never sent one because it detected it was at the desired state
1952 // when it ran. If we've already sent a size mode event, then this will be a
1954 if (!IsInTransition()) {
1955 DispatchSizeModeEvent();
1958 NS_OBJC_END_TRY_IGNORE_BLOCK;
1961 void nsCocoaWindow::FinishCurrentTransitionIfMatching(
1962 const TransitionType& aTransition) {
1963 // We've just finished some transition activity, and we're not sure whether it
1964 // was triggered programmatically, or by the user. If it matches our current
1965 // transition, then assume it was triggered programmatically and we can clean
1966 // up that transition and start processing transitions again.
1968 // Whether programmatic or user-initiated, we send out a size mode event.
1969 DispatchSizeModeEvent();
1971 if (mTransitionCurrent.isSome() && (*mTransitionCurrent == aTransition)) {
1972 // This matches our current transition, so do the safe parts of transition
1974 mTransitionCurrent.reset();
1975 mIsTransitionCurrentAdded = false;
1977 // Since this function is called from nsWindowDelegate transition callbacks,
1978 // we want to make sure those callbacks are all the way done before we
1979 // continue processing more transitions. To accomplish this, we dispatch
1980 // ProcessTransitions on the next event loop. Doing this will ensure that
1981 // any async native transition methods we call (like toggleFullScreen) will
1983 if (!mTransitionsPending.empty()) {
1984 NS_DispatchToCurrentThread(NewRunnableMethod(
1985 "FinishCurrentTransition", this, &nsCocoaWindow::ProcessTransitions));
1990 bool nsCocoaWindow::HandleUpdateFullscreenOnResize() {
1991 if (mUpdateFullscreenOnResize.isNothing()) {
1996 (*mUpdateFullscreenOnResize == TransitionType::Fullscreen);
1997 mUpdateFullscreenOnResize.reset();
1998 UpdateFullscreenState(toFullscreen, true);
2003 /* static */ nsCocoaWindow* nsCocoaWindow::sWindowInNativeTransition(nullptr);
2005 bool nsCocoaWindow::CanStartNativeTransition() {
2006 if (sWindowInNativeTransition == nullptr) {
2007 // Claim it and return true, indicating that the caller has permission to
2008 // start the native fullscreen transition.
2009 sWindowInNativeTransition = this;
2015 void nsCocoaWindow::EndOurNativeTransition() {
2016 if (sWindowInNativeTransition == this) {
2017 sWindowInNativeTransition = nullptr;
2021 // Coordinates are desktop pixels
2022 void nsCocoaWindow::DoResize(double aX, double aY, double aWidth,
2023 double aHeight, bool aRepaint,
2024 bool aConstrainToCurrentScreen) {
2025 NS_OBJC_BEGIN_TRY_IGNORE_BLOCK;
2027 if (!mWindow || mInResize) {
2031 // We are able to resize a window outside of any aspect ratio contraints
2032 // applied to it, but in order to "update" the aspect ratio contraint to the
2033 // new window dimensions, we must re-lock the aspect ratio.
2034 auto relockAspectRatio = MakeScopeExit([&]() {
2035 if (mAspectRatioLocked) {
2036 LockAspectRatio(true);
2040 AutoRestore<bool> reentrantResizeGuard(mInResize);
2043 CGFloat scale = mSizeConstraints.mScale.scale;
2044 if (scale == MOZ_WIDGET_INVALID_SCALE) {
2045 scale = BackingScaleFactor();
2048 // mSizeConstraints is in device pixels.
2049 int32_t width = NSToIntRound(aWidth * scale);
2050 int32_t height = NSToIntRound(aHeight * scale);
2052 width = std::max(mSizeConstraints.mMinSize.width,
2053 std::min(mSizeConstraints.mMaxSize.width, width));
2054 height = std::max(mSizeConstraints.mMinSize.height,
2055 std::min(mSizeConstraints.mMaxSize.height, height));
2057 DesktopIntRect newBounds(NSToIntRound(aX), NSToIntRound(aY),
2058 NSToIntRound(width / scale),
2059 NSToIntRound(height / scale));
2061 // convert requested bounds into Cocoa coordinate system
2062 NSRect newFrame = nsCocoaUtils::GeckoRectToCocoaRect(newBounds);
2064 NSRect frame = [mWindow frame];
2065 BOOL isMoving = newFrame.origin.x != frame.origin.x ||
2066 newFrame.origin.y != frame.origin.y;
2067 BOOL isResizing = newFrame.size.width != frame.size.width ||
2068 newFrame.size.height != frame.size.height;
2070 if (!isMoving && !isResizing) {
2074 // We ignore aRepaint -- we have to call display:YES, otherwise the
2075 // title bar doesn't immediately get repainted and is displayed in
2076 // the wrong place, leading to a visual jump.
2077 [mWindow setFrame:newFrame display:YES];
2079 NS_OBJC_END_TRY_IGNORE_BLOCK;
2082 // Coordinates are desktop pixels
2083 void nsCocoaWindow::Resize(double aX, double aY, double aWidth, double aHeight,
2085 DoResize(aX, aY, aWidth, aHeight, aRepaint, false);
2088 // Coordinates are desktop pixels
2089 void nsCocoaWindow::Resize(double aWidth, double aHeight, bool aRepaint) {
2090 double invScale = 1.0 / BackingScaleFactor();
2091 DoResize(mBounds.x * invScale, mBounds.y * invScale, aWidth, aHeight,
2095 // Return the area that the Gecko ChildView in our window should cover, as an
2096 // NSRect in screen coordinates (with 0,0 being the bottom left corner of the
2098 NSRect nsCocoaWindow::GetClientCocoaRect() {
2103 return [mWindow childViewRectForFrameRect:[mWindow frame]];
2106 LayoutDeviceIntRect nsCocoaWindow::GetClientBounds() {
2107 NS_OBJC_BEGIN_TRY_BLOCK_RETURN;
2109 CGFloat scaleFactor = BackingScaleFactor();
2110 return nsCocoaUtils::CocoaRectToGeckoRectDevPix(GetClientCocoaRect(),
2113 NS_OBJC_END_TRY_BLOCK_RETURN(LayoutDeviceIntRect(0, 0, 0, 0));
2116 void nsCocoaWindow::UpdateBounds() {
2117 NSRect frame = NSZeroRect;
2119 frame = [mWindow frame];
2122 nsCocoaUtils::CocoaRectToGeckoRectDevPix(frame, BackingScaleFactor());
2124 if (mPopupContentView) {
2125 mPopupContentView->UpdateBoundsFromView();
2129 LayoutDeviceIntRect nsCocoaWindow::GetScreenBounds() {
2130 NS_OBJC_BEGIN_TRY_BLOCK_RETURN;
2133 LayoutDeviceIntRect r = nsCocoaUtils::CocoaRectToGeckoRectDevPix(
2134 [mWindow frame], BackingScaleFactor());
2135 NS_ASSERTION(mWindow && mBounds == r, "mBounds out of sync!");
2140 NS_OBJC_END_TRY_BLOCK_RETURN(LayoutDeviceIntRect(0, 0, 0, 0));
2143 double nsCocoaWindow::GetDefaultScaleInternal() { return BackingScaleFactor(); }
2145 static CGFloat GetBackingScaleFactor(NSWindow* aWindow) {
2146 NSRect frame = [aWindow frame];
2147 if (frame.size.width > 0 && frame.size.height > 0) {
2148 return nsCocoaUtils::GetBackingScaleFactor(aWindow);
2151 // For windows with zero width or height, the backingScaleFactor method
2152 // is broken - it will always return 2 on a retina macbook, even when
2153 // the window position implies it's on a non-hidpi external display
2154 // (to the extent that a zero-area window can be said to be "on" a
2156 // And to make matters worse, Cocoa even fires a
2157 // windowDidChangeBackingProperties notification with the
2158 // NSBackingPropertyOldScaleFactorKey key when a window on an
2159 // external display is resized to/from zero height, even though it hasn't
2160 // really changed screens.
2162 // This causes us to handle popup window sizing incorrectly when the
2163 // popup is resized to zero height (bug 820327) - nsXULPopupManager
2164 // becomes (incorrectly) convinced the popup has been explicitly forced
2165 // to a non-default size and needs to have size attributes attached.
2167 // Workaround: instead of asking the window, we'll find the screen it is on
2168 // and ask that for *its* backing scale factor.
2170 // (See bug 853252 and additional comments in windowDidChangeScreen: below
2171 // for further complications this causes.)
2173 // First, expand the rect so that it actually has a measurable area,
2174 // for FindTargetScreenForRect to use.
2175 if (frame.size.width == 0) {
2176 frame.size.width = 1;
2178 if (frame.size.height == 0) {
2179 frame.size.height = 1;
2182 // Then identify the screen it belongs to, and return its scale factor.
2184 FindTargetScreenForRect(nsCocoaUtils::CocoaRectToGeckoRect(frame));
2185 return nsCocoaUtils::GetBackingScaleFactor(screen);
2188 CGFloat nsCocoaWindow::BackingScaleFactor() {
2189 if (mBackingScaleFactor > 0.0) {
2190 return mBackingScaleFactor;
2195 mBackingScaleFactor = GetBackingScaleFactor(mWindow);
2196 return mBackingScaleFactor;
2199 void nsCocoaWindow::BackingScaleFactorChanged() {
2200 CGFloat newScale = GetBackingScaleFactor(mWindow);
2202 // ignore notification if it hasn't really changed (or maybe we have
2203 // disabled HiDPI mode via prefs)
2204 if (mBackingScaleFactor == newScale) {
2208 mBackingScaleFactor = newScale;
2210 if (!mWidgetListener || mWidgetListener->GetAppWindow()) {
2214 if (PresShell* presShell = mWidgetListener->GetPresShell()) {
2215 presShell->BackingScaleFactorChanged();
2217 mWidgetListener->UIResolutionChanged();
2220 int32_t nsCocoaWindow::RoundsWidgetCoordinatesTo() {
2221 if (BackingScaleFactor() == 2.0) {
2227 void nsCocoaWindow::SetCursor(const Cursor& aCursor) {
2228 if (mPopupContentView) {
2229 mPopupContentView->SetCursor(aCursor);
2233 nsresult nsCocoaWindow::SetTitle(const nsAString& aTitle) {
2234 NS_OBJC_BEGIN_TRY_BLOCK_RETURN;
2240 const nsString& strTitle = PromiseFlatString(aTitle);
2241 const unichar* uniTitle = reinterpret_cast<const unichar*>(strTitle.get());
2242 NSString* title = [NSString stringWithCharacters:uniTitle
2243 length:strTitle.Length()];
2244 if ([mWindow drawsContentsIntoWindowFrame] && ![mWindow wantsTitleDrawn]) {
2245 // Don't cause invalidations when the title isn't displayed.
2246 [mWindow disableSetNeedsDisplay];
2247 [mWindow setTitle:title];
2248 [mWindow enableSetNeedsDisplay];
2250 [mWindow setTitle:title];
2255 NS_OBJC_END_TRY_BLOCK_RETURN(NS_ERROR_FAILURE);
2258 void nsCocoaWindow::Invalidate(const LayoutDeviceIntRect& aRect) {
2259 if (mPopupContentView) {
2260 mPopupContentView->Invalidate(aRect);
2264 // Pass notification of some drag event to Gecko
2266 // The drag manager has let us know that something related to a drag has
2267 // occurred in this window. It could be any number of things, ranging from
2268 // a drop, to a drag enter/leave, or a drag over event. The actual event
2269 // is passed in |aMessage| and is passed along to our event hanlder so Gecko
2271 bool nsCocoaWindow::DragEvent(unsigned int aMessage,
2272 mozilla::gfx::Point aMouseGlobal,
2273 UInt16 aKeyModifiers) {
2277 NS_IMETHODIMP nsCocoaWindow::SendSetZLevelEvent() {
2278 nsWindowZ placement = nsWindowZTop;
2279 nsCOMPtr<nsIWidget> actualBelow;
2280 if (mWidgetListener)
2281 mWidgetListener->ZLevelChanged(true, &placement, nullptr,
2282 getter_AddRefs(actualBelow));
2286 NS_IMETHODIMP nsCocoaWindow::GetChildSheet(bool aShown, nsIWidget** _retval) {
2287 nsIWidget* child = GetFirstChild();
2290 if (child->GetWindowType() == WindowType::Sheet) {
2291 // if it's a sheet, it must be an nsCocoaWindow
2292 nsCocoaWindow* cocoaWindow = static_cast<nsCocoaWindow*>(child);
2293 if (cocoaWindow->mWindow &&
2294 ((aShown && [cocoaWindow->mWindow isVisible]) ||
2295 (!aShown && cocoaWindow->mSheetNeedsShow))) {
2296 nsCOMPtr<nsIWidget> widget = cocoaWindow;
2297 widget.forget(_retval);
2301 child = child->GetNextSibling();
2309 NS_IMETHODIMP nsCocoaWindow::GetRealParent(nsIWidget** parent) {
2314 NS_IMETHODIMP nsCocoaWindow::GetIsSheet(bool* isSheet) {
2315 mWindowType == WindowType::Sheet ? * isSheet = true : * isSheet = false;
2319 NS_IMETHODIMP nsCocoaWindow::GetSheetWindowParent(
2320 NSWindow** sheetWindowParent) {
2321 *sheetWindowParent = mSheetWindowParent;
2325 // Invokes callback and ProcessEvent methods on Event Listener object
2326 nsresult nsCocoaWindow::DispatchEvent(WidgetGUIEvent* event,
2327 nsEventStatus& aStatus) {
2328 aStatus = nsEventStatus_eIgnore;
2330 nsCOMPtr<nsIWidget> kungFuDeathGrip(event->mWidget);
2331 mozilla::Unused << kungFuDeathGrip; // Not used within this function
2333 if (mWidgetListener)
2334 aStatus = mWidgetListener->HandleEvent(event, mUseAttachedEvents);
2339 // aFullScreen should be the window's mInFullScreenMode. We don't have access to
2340 // that from here, so we need to pass it in. mInFullScreenMode should be the
2341 // canonical indicator that a window is currently full screen and it makes sense
2342 // to keep all sizemode logic here.
2343 static nsSizeMode GetWindowSizeMode(NSWindow* aWindow, bool aFullScreen) {
2344 if (aFullScreen) return nsSizeMode_Fullscreen;
2345 if ([aWindow isMiniaturized]) return nsSizeMode_Minimized;
2346 if (([aWindow styleMask] & NSWindowStyleMaskResizable) && [aWindow isZoomed])
2347 return nsSizeMode_Maximized;
2348 return nsSizeMode_Normal;
2351 void nsCocoaWindow::ReportMoveEvent() {
2352 NS_OBJC_BEGIN_TRY_IGNORE_BLOCK;
2354 // Prevent recursion, which can become infinite (see bug 708278). This
2355 // can happen when the call to [NSWindow setFrameTopLeftPoint:] in
2356 // nsCocoaWindow::Move() triggers an immediate NSWindowDidMove notification
2357 // (and a call to [WindowDelegate windowDidMove:]).
2358 if (mInReportMoveEvent) {
2361 mInReportMoveEvent = true;
2365 // The zoomed state can change when we're moving, in which case we need to
2366 // update our internal mSizeMode. This can happen either if we're maximized
2367 // and then moved, or if we're not maximized and moved back to zoomed state.
2368 if (mWindow && ((mSizeMode == nsSizeMode_Maximized) ^ [mWindow isZoomed])) {
2369 DispatchSizeModeEvent();
2372 // Dispatch the move event to Gecko
2373 NotifyWindowMoved(mBounds.x, mBounds.y);
2375 mInReportMoveEvent = false;
2377 NS_OBJC_END_TRY_IGNORE_BLOCK;
2380 void nsCocoaWindow::DispatchSizeModeEvent() {
2385 if (mSuppressSizeModeEvents || mIsTransitionCurrentAdded) {
2389 nsSizeMode newMode = GetWindowSizeMode(mWindow, mInFullScreenMode);
2390 if (mSizeMode == newMode) {
2394 mSizeMode = newMode;
2395 if (mWidgetListener) {
2396 mWidgetListener->SizeModeChanged(newMode);
2400 void nsCocoaWindow::DispatchOcclusionEvent() {
2405 // Our new occlusion state is true if the window is not visible.
2406 bool newOcclusionState =
2407 !(mHasStartedNativeFullscreen ||
2408 ([mWindow occlusionState] & NSWindowOcclusionStateVisible));
2410 // Don't dispatch if the new occlustion state is the same as the current
2412 if (mIsFullyOccluded == newOcclusionState) {
2416 MOZ_ASSERT(mIgnoreOcclusionCount >= 0);
2417 if (newOcclusionState && mIgnoreOcclusionCount > 0) {
2421 mIsFullyOccluded = newOcclusionState;
2422 if (mWidgetListener) {
2423 mWidgetListener->OcclusionStateChanged(mIsFullyOccluded);
2427 void nsCocoaWindow::ReportSizeEvent() {
2428 NS_OBJC_BEGIN_TRY_IGNORE_BLOCK;
2431 if (mWidgetListener) {
2432 LayoutDeviceIntRect innerBounds = GetClientBounds();
2433 mWidgetListener->WindowResized(this, innerBounds.width, innerBounds.height);
2436 NS_OBJC_END_TRY_IGNORE_BLOCK;
2439 void nsCocoaWindow::SetMenuBar(RefPtr<nsMenuBarX>&& aMenuBar) {
2444 mMenuBar = std::move(aMenuBar);
2446 // Only paint for active windows, or paint the hidden window menu bar if no
2447 // other menu bar has been painted yet so that some reasonable menu bar is
2448 // displayed when the app starts up.
2449 if (mMenuBar && ((!gSomeMenuBarPainted &&
2450 nsMenuUtilsX::GetHiddenWindowMenuBar() == mMenuBar) ||
2451 [mWindow isMainWindow]))
2455 void nsCocoaWindow::SetFocus(Raise aRaise,
2456 mozilla::dom::CallerType aCallerType) {
2457 if (!mWindow) return;
2459 if (mPopupContentView) {
2460 return mPopupContentView->SetFocus(aRaise, aCallerType);
2463 if (aRaise == Raise::Yes &&
2464 ([mWindow isVisible] || [mWindow isMiniaturized])) {
2465 if ([mWindow isMiniaturized]) {
2466 [mWindow deminiaturize:nil];
2469 [mWindow makeKeyAndOrderFront:nil];
2470 SendSetZLevelEvent();
2474 LayoutDeviceIntPoint nsCocoaWindow::WidgetToScreenOffset() {
2475 NS_OBJC_BEGIN_TRY_BLOCK_RETURN;
2477 return nsCocoaUtils::CocoaRectToGeckoRectDevPix(GetClientCocoaRect(),
2478 BackingScaleFactor())
2481 NS_OBJC_END_TRY_BLOCK_RETURN(LayoutDeviceIntPoint(0, 0));
2484 LayoutDeviceIntPoint nsCocoaWindow::GetClientOffset() {
2485 NS_OBJC_BEGIN_TRY_BLOCK_RETURN;
2487 LayoutDeviceIntRect clientRect = GetClientBounds();
2489 return clientRect.TopLeft() - mBounds.TopLeft();
2491 NS_OBJC_END_TRY_BLOCK_RETURN(LayoutDeviceIntPoint(0, 0));
2494 LayoutDeviceIntMargin nsCocoaWindow::ClientToWindowMargin() {
2495 NS_OBJC_BEGIN_TRY_BLOCK_RETURN;
2497 if (!mWindow || mWindow.drawsContentsIntoWindowFrame ||
2498 mWindowType == WindowType::Popup) {
2502 NSRect clientNSRect = mWindow.contentLayoutRect;
2503 NSRect frameNSRect = [mWindow frameRectForChildViewRect:clientNSRect];
2505 CGFloat backingScale = BackingScaleFactor();
2506 const auto clientRect =
2507 nsCocoaUtils::CocoaRectToGeckoRectDevPix(clientNSRect, backingScale);
2508 const auto frameRect =
2509 nsCocoaUtils::CocoaRectToGeckoRectDevPix(frameNSRect, backingScale);
2511 return frameRect - clientRect;
2513 NS_OBJC_END_TRY_BLOCK_RETURN({});
2516 nsMenuBarX* nsCocoaWindow::GetMenuBar() { return mMenuBar; }
2518 void nsCocoaWindow::CaptureRollupEvents(bool aDoCapture) {
2519 NS_OBJC_BEGIN_TRY_IGNORE_BLOCK;
2522 if (![NSApp isActive]) {
2523 // We need to capture mouse event if we aren't
2524 // the active application. We only set this up when needed
2525 // because they cause spurious mouse event after crash
2526 // and gdb sessions. See bug 699538.
2527 nsToolkit::GetToolkit()->MonitorAllProcessMouseEvents();
2530 // Sometimes more than one popup window can be visible at the same time
2531 // (e.g. nested non-native context menus, or the test case (attachment
2532 // 276885) for bmo bug 392389, which displays a non-native combo-box in a
2533 // non-native popup window). In these cases the "active" popup window
2534 // should be the topmost -- the (nested) context menu the mouse is currently
2535 // over, or the combo-box's drop-down list (when it's displayed). But
2536 // (among windows that have the same "level") OS X makes topmost the window
2537 // that last received a mouse-down event, which may be incorrect (in the
2538 // combo-box case, it makes topmost the window containing the combo-box).
2539 // So here we fiddle with a non-native popup window's level to make sure the
2540 // "active" one is always above any other non-native popup windows that
2542 if (mWindow && (mWindowType == WindowType::Popup)) SetPopupWindowLevel();
2544 nsToolkit::GetToolkit()->StopMonitoringAllProcessMouseEvents();
2546 // XXXndeakin this doesn't make sense.
2547 // Why is the new window assumed to be a modal panel?
2548 if (mWindow && (mWindowType == WindowType::Popup))
2549 [mWindow setLevel:NSModalPanelWindowLevel];
2552 NS_OBJC_END_TRY_IGNORE_BLOCK;
2555 nsresult nsCocoaWindow::GetAttention(int32_t aCycleCount) {
2556 NS_OBJC_BEGIN_TRY_BLOCK_RETURN;
2558 [NSApp requestUserAttention:NSInformationalRequest];
2561 NS_OBJC_END_TRY_BLOCK_RETURN(NS_ERROR_FAILURE);
2564 bool nsCocoaWindow::HasPendingInputEvent() {
2565 return nsChildView::DoHasPendingInputEvent();
2568 void nsCocoaWindow::SetWindowShadowStyle(WindowShadow aStyle) {
2569 NS_OBJC_BEGIN_TRY_IGNORE_BLOCK;
2571 if (mShadowStyle == aStyle) {
2575 mShadowStyle = aStyle;
2577 if (!mWindow || mWindowType != WindowType::Popup) {
2581 mWindow.shadowStyle = mShadowStyle;
2582 [mWindow setEffectViewWrapperForStyle:mShadowStyle];
2583 [mWindow setHasShadow:aStyle != WindowShadow::None];
2585 NS_OBJC_END_TRY_IGNORE_BLOCK;
2588 void nsCocoaWindow::SetWindowOpacity(float aOpacity) {
2589 NS_OBJC_BEGIN_TRY_IGNORE_BLOCK;
2595 [mWindow setAlphaValue:(CGFloat)aOpacity];
2597 NS_OBJC_END_TRY_IGNORE_BLOCK;
2600 void nsCocoaWindow::SetColorScheme(const Maybe<ColorScheme>& aScheme) {
2601 NS_OBJC_BEGIN_TRY_IGNORE_BLOCK;
2607 mWindow.appearance = aScheme ? NSAppearanceForColorScheme(*aScheme) : nil;
2609 NS_OBJC_END_TRY_IGNORE_BLOCK;
2612 static inline CGAffineTransform GfxMatrixToCGAffineTransform(
2613 const gfx::Matrix& m) {
2614 CGAffineTransform t;
2624 void nsCocoaWindow::SetWindowTransform(const gfx::Matrix& aTransform) {
2625 NS_OBJC_BEGIN_TRY_IGNORE_BLOCK;
2631 // Calling CGSSetWindowTransform when the window is not visible results in
2632 // misplacing the window into doubled x,y coordinates (see bug 1448132).
2633 if (![mWindow isVisible] || NSIsEmptyRect([mWindow frame])) {
2637 if (StaticPrefs::widget_window_transforms_disabled()) {
2638 // CGSSetWindowTransform is a private API. In case calling it causes
2639 // problems either now or in the future, we'll want to have an easy kill
2640 // switch. So we allow disabling it with a pref.
2644 gfx::Matrix transform = aTransform;
2646 // aTransform is a transform that should be applied to the window relative
2647 // to its regular position: If aTransform._31 is 100, then we want the
2648 // window to be displayed 100 pixels to the right of its regular position.
2649 // The transform that CGSSetWindowTransform accepts has a different meaning:
2650 // It's used to answer the question "For the screen pixel at x,y (with the
2651 // origin at the top left), what pixel in the window's buffer (again with
2652 // origin top left) should be displayed at that position?"
2653 // In the example above, this means that we need to call
2654 // CGSSetWindowTransform with a horizontal translation of -windowPos.x - 100.
2655 // So we need to invert the transform and adjust it by the window's position.
2656 if (!transform.Invert()) {
2657 // Treat non-invertible transforms as the identity transform.
2658 transform = gfx::Matrix();
2661 bool isIdentity = transform.IsIdentity();
2662 if (isIdentity && mWindowTransformIsIdentity) {
2666 transform.PreTranslate(-mBounds.x, -mBounds.y);
2668 // Snap translations to device pixels, to match what we do for CSS transforms
2669 // and because the window server rounds down instead of to nearest.
2670 if (!transform.HasNonTranslation() && transform.HasNonIntegerTranslation()) {
2671 auto snappedTranslation = gfx::IntPoint::Round(transform.GetTranslation());
2673 gfx::Matrix::Translation(snappedTranslation.x, snappedTranslation.y);
2676 // We also need to account for the backing scale factor: aTransform is given
2677 // in device pixels, but CGSSetWindowTransform works with logical display
2679 CGFloat backingScale = BackingScaleFactor();
2680 transform.PreScale(backingScale, backingScale);
2681 transform.PostScale(1 / backingScale, 1 / backingScale);
2683 CGSConnection cid = _CGSDefaultConnection();
2684 CGSSetWindowTransform(cid, [mWindow windowNumber],
2685 GfxMatrixToCGAffineTransform(transform));
2687 mWindowTransformIsIdentity = isIdentity;
2689 NS_OBJC_END_TRY_IGNORE_BLOCK;
2692 void nsCocoaWindow::SetInputRegion(const InputRegion& aInputRegion) {
2693 MOZ_ASSERT(mWindowType == WindowType::Popup,
2694 "This should only be called on popup windows.");
2695 // TODO: Somehow support aInputRegion.mMargin? Though maybe not.
2696 if (aInputRegion.mFullyTransparent) {
2697 [mWindow setIgnoresMouseEvents:YES];
2699 [mWindow setIgnoresMouseEvents:NO];
2703 void nsCocoaWindow::SetShowsToolbarButton(bool aShow) {
2704 NS_OBJC_BEGIN_TRY_IGNORE_BLOCK;
2706 if (mWindow) [mWindow setShowsToolbarButton:aShow];
2708 NS_OBJC_END_TRY_IGNORE_BLOCK;
2711 void nsCocoaWindow::SetSupportsNativeFullscreen(
2712 bool aSupportsNativeFullscreen) {
2713 NS_OBJC_BEGIN_TRY_IGNORE_BLOCK;
2716 // This determines whether we tell cocoa that the window supports native
2717 // full screen. If we do so, and another window is in native full screen,
2718 // this window will also appear in native full screen. We generally only
2719 // want to do this for primary application windows. We'll set the
2720 // relevant macnativefullscreen attribute on those, which will lead to us
2721 // being called with aSupportsNativeFullscreen set to `true` here.
2722 NSWindowCollectionBehavior newBehavior = [mWindow collectionBehavior];
2723 if (aSupportsNativeFullscreen) {
2724 newBehavior |= NSWindowCollectionBehaviorFullScreenPrimary;
2726 newBehavior &= ~NSWindowCollectionBehaviorFullScreenPrimary;
2728 [mWindow setCollectionBehavior:newBehavior];
2731 NS_OBJC_END_TRY_IGNORE_BLOCK;
2734 void nsCocoaWindow::SetWindowAnimationType(
2735 nsIWidget::WindowAnimationType aType) {
2736 mAnimationType = aType;
2739 void nsCocoaWindow::SetDrawsTitle(bool aDrawTitle) {
2740 NS_OBJC_BEGIN_TRY_IGNORE_BLOCK;
2742 if (![mWindow drawsContentsIntoWindowFrame]) {
2743 // If we don't draw into the window frame, we always want to display window
2745 [mWindow setWantsTitleDrawn:YES];
2747 [mWindow setWantsTitleDrawn:aDrawTitle];
2750 NS_OBJC_END_TRY_IGNORE_BLOCK;
2753 nsresult nsCocoaWindow::SetNonClientMargins(
2754 const LayoutDeviceIntMargin& margins) {
2755 NS_OBJC_BEGIN_TRY_BLOCK_RETURN;
2757 SetDrawsInTitlebar(margins.top == 0);
2761 NS_OBJC_END_TRY_BLOCK_RETURN(NS_ERROR_FAILURE);
2764 void nsCocoaWindow::SetDrawsInTitlebar(bool aState) {
2765 NS_OBJC_BEGIN_TRY_IGNORE_BLOCK;
2768 [mWindow setDrawsContentsIntoWindowFrame:aState];
2771 NS_OBJC_END_TRY_IGNORE_BLOCK;
2774 NS_IMETHODIMP nsCocoaWindow::SynthesizeNativeMouseEvent(
2775 LayoutDeviceIntPoint aPoint, NativeMouseMessage aNativeMessage,
2776 MouseButton aButton, nsIWidget::Modifiers aModifierFlags,
2777 nsIObserver* aObserver) {
2778 NS_OBJC_BEGIN_TRY_BLOCK_RETURN;
2780 AutoObserverNotifier notifier(aObserver, "mouseevent");
2781 if (mPopupContentView) {
2782 return mPopupContentView->SynthesizeNativeMouseEvent(
2783 aPoint, aNativeMessage, aButton, aModifierFlags, nullptr);
2788 NS_OBJC_END_TRY_BLOCK_RETURN(NS_ERROR_FAILURE);
2791 NS_IMETHODIMP nsCocoaWindow::SynthesizeNativeMouseScrollEvent(
2792 LayoutDeviceIntPoint aPoint, uint32_t aNativeMessage, double aDeltaX,
2793 double aDeltaY, double aDeltaZ, uint32_t aModifierFlags,
2794 uint32_t aAdditionalFlags, nsIObserver* aObserver) {
2795 NS_OBJC_BEGIN_TRY_BLOCK_RETURN;
2797 AutoObserverNotifier notifier(aObserver, "mousescrollevent");
2798 if (mPopupContentView) {
2799 // Pass nullptr as the observer so that the AutoObserverNotification in
2800 // nsChildView::SynthesizeNativeMouseScrollEvent will be ignored.
2801 return mPopupContentView->SynthesizeNativeMouseScrollEvent(
2802 aPoint, aNativeMessage, aDeltaX, aDeltaY, aDeltaZ, aModifierFlags,
2803 aAdditionalFlags, nullptr);
2808 NS_OBJC_END_TRY_BLOCK_RETURN(NS_ERROR_FAILURE);
2811 void nsCocoaWindow::LockAspectRatio(bool aShouldLock) {
2812 NS_OBJC_BEGIN_TRY_IGNORE_BLOCK;
2815 [mWindow setContentAspectRatio:mWindow.frame.size];
2816 mAspectRatioLocked = true;
2819 // https://developer.apple.com/documentation/appkit/nswindow/1419507-aspectratio,
2820 // aspect ratios and resize increments are mutually exclusive, and the
2821 // accepted way of cancelling an established aspect ratio is to set the
2822 // resize increments to 1.0, 1.0
2823 [mWindow setResizeIncrements:NSMakeSize(1.0, 1.0)];
2824 mAspectRatioLocked = false;
2827 NS_OBJC_END_TRY_IGNORE_BLOCK;
2830 void nsCocoaWindow::UpdateThemeGeometries(
2831 const nsTArray<ThemeGeometry>& aThemeGeometries) {
2832 NS_OBJC_BEGIN_TRY_IGNORE_BLOCK;
2834 if (mPopupContentView) {
2835 return mPopupContentView->UpdateThemeGeometries(aThemeGeometries);
2838 NS_OBJC_END_TRY_IGNORE_BLOCK;
2841 void nsCocoaWindow::SetPopupWindowLevel() {
2842 if (!mWindow) return;
2844 // Floating popups are at the floating level and hide when the window is
2846 if (mPopupLevel == PopupLevel::Floating) {
2847 [mWindow setLevel:NSFloatingWindowLevel];
2848 [mWindow setHidesOnDeactivate:YES];
2850 // Otherwise, this is a top-level or parent popup. Parent popups always
2851 // appear just above their parent and essentially ignore the level.
2852 [mWindow setLevel:NSPopUpMenuWindowLevel];
2853 [mWindow setHidesOnDeactivate:NO];
2857 void nsCocoaWindow::SetInputContext(const InputContext& aContext,
2858 const InputContextAction& aAction) {
2859 NS_OBJC_BEGIN_TRY_IGNORE_BLOCK;
2861 mInputContext = aContext;
2863 NS_OBJC_END_TRY_IGNORE_BLOCK;
2866 bool nsCocoaWindow::GetEditCommands(NativeKeyBindingsType aType,
2867 const WidgetKeyboardEvent& aEvent,
2868 nsTArray<CommandInt>& aCommands) {
2869 // Validate the arguments.
2870 if (NS_WARN_IF(!nsIWidget::GetEditCommands(aType, aEvent, aCommands))) {
2874 NativeKeyBindings* keyBindings = NativeKeyBindings::GetInstance(aType);
2875 // When the keyboard event is fired from this widget, it must mean that no web
2876 // content has focus because any web contents should be on `nsChildView`. And
2877 // in any locales, the system UI is always horizontal layout. So, let's pass
2878 // `Nothing()` for the writing mode here, it won't be treated as in a vertical
2880 keyBindings->GetEditCommands(aEvent, Nothing(), aCommands);
2884 void nsCocoaWindow::PauseOrResumeCompositor(bool aPause) {
2885 if (auto* mainChildView =
2886 static_cast<nsIWidget*>([[mWindow mainChildView] widget])) {
2887 mainChildView->PauseOrResumeCompositor(aPause);
2891 bool nsCocoaWindow::AsyncPanZoomEnabled() const {
2892 if (mPopupContentView) {
2893 return mPopupContentView->AsyncPanZoomEnabled();
2895 return nsBaseWidget::AsyncPanZoomEnabled();
2898 bool nsCocoaWindow::StartAsyncAutoscroll(const ScreenPoint& aAnchorLocation,
2899 const ScrollableLayerGuid& aGuid) {
2900 if (mPopupContentView) {
2901 return mPopupContentView->StartAsyncAutoscroll(aAnchorLocation, aGuid);
2903 return nsBaseWidget::StartAsyncAutoscroll(aAnchorLocation, aGuid);
2906 void nsCocoaWindow::StopAsyncAutoscroll(const ScrollableLayerGuid& aGuid) {
2907 if (mPopupContentView) {
2908 mPopupContentView->StopAsyncAutoscroll(aGuid);
2911 nsBaseWidget::StopAsyncAutoscroll(aGuid);
2914 already_AddRefed<nsIWidget> nsIWidget::CreateTopLevelWindow() {
2915 nsCOMPtr<nsIWidget> window = new nsCocoaWindow();
2916 return window.forget();
2919 already_AddRefed<nsIWidget> nsIWidget::CreateChildWindow() {
2920 nsCOMPtr<nsIWidget> window = new nsChildView();
2921 return window.forget();
2924 @implementation WindowDelegate
2926 // We try to find a gecko menu bar to paint. If one does not exist, just paint
2927 // the application menu by itself so that a window doesn't have some other
2928 // window's menu bar.
2929 + (void)paintMenubarForWindow:(NSWindow*)aWindow {
2930 NS_OBJC_BEGIN_TRY_IGNORE_BLOCK;
2932 // make sure we only act on windows that have this kind of
2933 // object as a delegate
2934 id windowDelegate = [aWindow delegate];
2935 if ([windowDelegate class] != [self class]) return;
2937 nsCocoaWindow* geckoWidget = [windowDelegate geckoWidget];
2938 NS_ASSERTION(geckoWidget, "Window delegate not returning a gecko widget!");
2940 nsMenuBarX* geckoMenuBar = geckoWidget->GetMenuBar();
2942 geckoMenuBar->Paint();
2944 // sometimes we don't have a native application menu early in launching
2945 if (!sApplicationMenu) return;
2947 NSMenu* mainMenu = [NSApp mainMenu];
2949 [mainMenu numberOfItems] > 0,
2950 "Main menu does not have any items, something is terribly wrong!");
2952 // Create a new menu bar.
2953 // We create a GeckoNSMenu because all menu bar NSMenu objects should use
2954 // that subclass for key handling reasons.
2955 GeckoNSMenu* newMenuBar =
2956 [[GeckoNSMenu alloc] initWithTitle:@"MainMenuBar"];
2958 // move the application menu from the existing menu bar to the new one
2959 NSMenuItem* firstMenuItem = [[mainMenu itemAtIndex:0] retain];
2960 [mainMenu removeItemAtIndex:0];
2961 [newMenuBar insertItem:firstMenuItem atIndex:0];
2962 [firstMenuItem release];
2964 // set our new menu bar as the main menu
2965 [NSApp setMainMenu:newMenuBar];
2966 [newMenuBar release];
2969 NS_OBJC_END_TRY_IGNORE_BLOCK;
2972 - (id)initWithGeckoWindow:(nsCocoaWindow*)geckoWind {
2973 NS_OBJC_BEGIN_TRY_BLOCK_RETURN;
2976 mGeckoWindow = geckoWind;
2977 mToplevelActiveState = false;
2978 mHasEverBeenZoomed = false;
2981 NS_OBJC_END_TRY_BLOCK_RETURN(nil);
2984 - (NSSize)windowWillResize:(NSWindow*)sender toSize:(NSSize)proposedFrameSize {
2986 return proposedFrameSize;
2989 - (NSRect)windowWillUseStandardFrame:(NSWindow*)window
2990 defaultFrame:(NSRect)newFrame {
2991 // This function needs to return a rect representing the frame a window would
2992 // have if it is in its "maximized" size mode. The parameter newFrame is
2993 // supposed to be a frame representing the maximum window size on the screen
2994 // where the window currently appears. However, in practice, newFrame can be a
2995 // much smaller size. So, we ignore newframe and instead return the frame of
2996 // the entire screen associated with the window. That frame is bigger than the
2997 // window could actually be, due to the presence of the menubar and possibly
2998 // the dock, but we never call this function directly, and Cocoa callers will
2999 // shrink it to its true maximum size.
3000 return window.screen.frame;
3003 void nsCocoaWindow::CocoaSendToplevelActivateEvents() {
3004 if (mWidgetListener) {
3005 mWidgetListener->WindowActivated();
3009 void nsCocoaWindow::CocoaSendToplevelDeactivateEvents() {
3010 if (mWidgetListener) {
3011 mWidgetListener->WindowDeactivated();
3015 void nsCocoaWindow::CocoaWindowDidResize() {
3016 // It's important to update our bounds before we trigger any listeners. This
3017 // ensures that our bounds are correct when GetScreenBounds is called.
3020 if (HandleUpdateFullscreenOnResize()) {
3025 // Resizing might have changed our zoom state.
3026 DispatchSizeModeEvent();
3030 - (void)windowDidResize:(NSNotification*)aNotification {
3031 BaseWindow* window = [aNotification object];
3032 [window updateTrackingArea];
3034 if (!mGeckoWindow) return;
3036 mGeckoWindow->CocoaWindowDidResize();
3039 - (void)windowDidChangeScreen:(NSNotification*)aNotification {
3040 if (!mGeckoWindow) return;
3042 // Because of Cocoa's peculiar treatment of zero-size windows (see comments
3043 // at GetBackingScaleFactor() above), we sometimes have a situation where
3044 // our concept of backing scale (based on the screen where the zero-sized
3045 // window is positioned) differs from Cocoa's idea (always based on the
3046 // Retina screen, AFAICT, even when an external non-Retina screen is the
3047 // primary display).
3049 // As a result, if the window was created with zero size on an external
3050 // display, but then made visible on the (secondary) Retina screen, we
3051 // will *not* get a windowDidChangeBackingProperties notification for it.
3052 // This leads to an incorrect GetDefaultScale(), and widget coordinate
3053 // confusion, as per bug 853252.
3055 // To work around this, we check for a backing scale mismatch when we
3056 // receive a windowDidChangeScreen notification, as we will receive this
3057 // even if Cocoa was already treating the zero-size window as having
3058 // Retina backing scale.
3059 NSWindow* window = (NSWindow*)[aNotification object];
3060 if ([window respondsToSelector:@selector(backingScaleFactor)]) {
3061 if (GetBackingScaleFactor(window) != mGeckoWindow->BackingScaleFactor()) {
3062 mGeckoWindow->BackingScaleFactorChanged();
3066 mGeckoWindow->ReportMoveEvent();
3069 - (void)windowWillEnterFullScreen:(NSNotification*)notification {
3070 if (!mGeckoWindow) {
3073 mGeckoWindow->CocoaWindowWillEnterFullscreen(true);
3076 // Lion's full screen mode will bypass our internal fullscreen tracking, so
3077 // we need to catch it when we transition and call our own methods, which in
3078 // turn will fire "fullscreen" events.
3079 - (void)windowDidEnterFullScreen:(NSNotification*)notification {
3080 // On Yosemite, the NSThemeFrame class has two new properties --
3081 // titlebarView (an NSTitlebarView object) and titlebarContainerView (an
3082 // NSTitlebarContainerView object). These are used to display the titlebar
3083 // in fullscreen mode. In Safari they're not transparent. But in Firefox
3084 // for some reason they are, which causes bug 1069658. The following code
3085 // works around this Apple bug or design flaw.
3086 NSWindow* window = (NSWindow*)[notification object];
3087 NSView* frameView = [[window contentView] superview];
3088 NSView* titlebarView = nil;
3089 NSView* titlebarContainerView = nil;
3090 if ([frameView respondsToSelector:@selector(titlebarView)]) {
3091 titlebarView = [frameView titlebarView];
3093 if ([frameView respondsToSelector:@selector(titlebarContainerView)]) {
3094 titlebarContainerView = [frameView titlebarContainerView];
3096 if ([titlebarView respondsToSelector:@selector(setTransparent:)]) {
3097 [titlebarView setTransparent:NO];
3099 if ([titlebarContainerView respondsToSelector:@selector(setTransparent:)]) {
3100 [titlebarContainerView setTransparent:NO];
3103 if (!mGeckoWindow) {
3106 mGeckoWindow->CocoaWindowDidEnterFullscreen(true);
3109 - (void)windowWillExitFullScreen:(NSNotification*)notification {
3110 if (!mGeckoWindow) {
3113 mGeckoWindow->CocoaWindowWillEnterFullscreen(false);
3116 - (void)windowDidExitFullScreen:(NSNotification*)notification {
3117 if (!mGeckoWindow) {
3120 mGeckoWindow->CocoaWindowDidEnterFullscreen(false);
3123 - (void)windowDidBecomeMain:(NSNotification*)aNotification {
3124 NS_OBJC_BEGIN_TRY_IGNORE_BLOCK;
3127 ChildViewMouseTracker::ReEvaluateMouseEnterState();
3129 // [NSApp _isRunningAppModal] will return true if we're running an OS dialog
3130 // app modally. If one of those is up then we want it to retain its menu bar.
3131 if ([NSApp _isRunningAppModal]) return;
3132 NSWindow* window = [aNotification object];
3133 if (window) [WindowDelegate paintMenubarForWindow:window];
3135 if ([window isKindOfClass:[ToolbarWindow class]]) {
3136 [(ToolbarWindow*)window windowMainStateChanged];
3139 NS_OBJC_END_TRY_IGNORE_BLOCK;
3142 - (void)windowDidResignMain:(NSNotification*)aNotification {
3144 ChildViewMouseTracker::ReEvaluateMouseEnterState();
3146 // [NSApp _isRunningAppModal] will return true if we're running an OS dialog
3147 // app modally. If one of those is up then we want it to retain its menu bar.
3148 if ([NSApp _isRunningAppModal]) return;
3149 RefPtr<nsMenuBarX> hiddenWindowMenuBar =
3150 nsMenuUtilsX::GetHiddenWindowMenuBar();
3151 if (hiddenWindowMenuBar) {
3152 // printf("painting hidden window menu bar due to window losing main
3154 hiddenWindowMenuBar->Paint();
3157 NSWindow* window = [aNotification object];
3158 if ([window isKindOfClass:[ToolbarWindow class]]) {
3159 [(ToolbarWindow*)window windowMainStateChanged];
3163 - (void)windowDidBecomeKey:(NSNotification*)aNotification {
3164 NS_OBJC_BEGIN_TRY_IGNORE_BLOCK;
3167 ChildViewMouseTracker::ReEvaluateMouseEnterState();
3169 NSWindow* window = [aNotification object];
3170 if ([window isSheet]) [WindowDelegate paintMenubarForWindow:window];
3172 nsChildView* mainChildView =
3173 static_cast<nsChildView*>([[(BaseWindow*)window mainChildView] widget]);
3174 if (mainChildView) {
3175 if (mainChildView->GetInputContext().IsPasswordEditor()) {
3176 TextInputHandler::EnableSecureEventInput();
3178 TextInputHandler::EnsureSecureEventInputDisabled();
3182 NS_OBJC_END_TRY_IGNORE_BLOCK;
3185 - (void)windowDidResignKey:(NSNotification*)aNotification {
3186 NS_OBJC_BEGIN_TRY_IGNORE_BLOCK;
3188 RollUpPopups(nsIRollupListener::AllowAnimations::No);
3190 ChildViewMouseTracker::ReEvaluateMouseEnterState();
3192 // If a sheet just resigned key then we should paint the menu bar
3193 // for whatever window is now main.
3194 NSWindow* window = [aNotification object];
3195 if ([window isSheet])
3196 [WindowDelegate paintMenubarForWindow:[NSApp mainWindow]];
3198 TextInputHandler::EnsureSecureEventInputDisabled();
3200 NS_OBJC_END_TRY_IGNORE_BLOCK;
3203 - (void)windowWillMove:(NSNotification*)aNotification {
3207 - (void)windowDidMove:(NSNotification*)aNotification {
3208 if (mGeckoWindow) mGeckoWindow->ReportMoveEvent();
3211 - (BOOL)windowShouldClose:(id)sender {
3212 nsIWidgetListener* listener =
3213 mGeckoWindow ? mGeckoWindow->GetWidgetListener() : nullptr;
3214 if (listener) listener->RequestWindowClose(mGeckoWindow);
3215 return NO; // gecko will do it
3218 - (void)windowWillClose:(NSNotification*)aNotification {
3222 - (void)windowWillMiniaturize:(NSNotification*)aNotification {
3226 - (void)windowDidMiniaturize:(NSNotification*)aNotification {
3227 if (!mGeckoWindow) {
3230 mGeckoWindow->FinishCurrentTransitionIfMatching(
3231 nsCocoaWindow::TransitionType::Miniaturize);
3234 - (void)windowDidDeminiaturize:(NSNotification*)aNotification {
3235 if (!mGeckoWindow) {
3238 mGeckoWindow->FinishCurrentTransitionIfMatching(
3239 nsCocoaWindow::TransitionType::Deminiaturize);
3242 - (BOOL)windowShouldZoom:(NSWindow*)window toFrame:(NSRect)proposedFrame {
3243 if (!mHasEverBeenZoomed && [window isZoomed]) return NO; // See bug 429954.
3245 mHasEverBeenZoomed = YES;
3249 - (NSRect)window:(NSWindow*)window
3250 willPositionSheet:(NSWindow*)sheet
3251 usingRect:(NSRect)rect {
3252 if ([window isKindOfClass:[ToolbarWindow class]]) {
3253 rect.origin.y = [(ToolbarWindow*)window sheetAttachmentPosition];
3258 #ifdef MOZ_THUNDERBIRD
3259 - (void)didEndSheet:(NSWindow*)sheet
3260 returnCode:(int)returnCode
3261 contextInfo:(void*)contextInfo {
3262 NS_OBJC_BEGIN_TRY_ABORT_BLOCK;
3264 // Note: 'contextInfo' (if it is set) is the window that is the parent of
3265 // the sheet. The value of contextInfo is determined in
3266 // nsCocoaWindow::Show(). If it's set, 'contextInfo' is always the top-
3267 // level window, not another sheet itself. But 'contextInfo' is nil if
3268 // our parent window is also a sheet -- in that case we shouldn't send
3269 // the top-level window any activate events (because it's our parent
3270 // window that needs to get these events, not the top-level window).
3271 [TopLevelWindowData deactivateInWindow:sheet];
3272 [sheet orderOut:self];
3273 if (contextInfo) [TopLevelWindowData activateInWindow:(NSWindow*)contextInfo];
3275 NS_OBJC_END_TRY_ABORT_BLOCK;
3279 - (void)windowDidChangeBackingProperties:(NSNotification*)aNotification {
3280 NS_OBJC_BEGIN_TRY_IGNORE_BLOCK;
3282 NSWindow* window = (NSWindow*)[aNotification object];
3284 if ([window respondsToSelector:@selector(backingScaleFactor)]) {
3285 CGFloat oldFactor = [[[aNotification userInfo]
3286 objectForKey:@"NSBackingPropertyOldScaleFactorKey"] doubleValue];
3287 if ([window backingScaleFactor] != oldFactor) {
3288 mGeckoWindow->BackingScaleFactorChanged();
3292 NS_OBJC_END_TRY_IGNORE_BLOCK;
3295 // This method is on NSWindowDelegate starting with 10.9
3296 - (void)windowDidChangeOcclusionState:(NSNotification*)aNotification {
3298 mGeckoWindow->DispatchOcclusionEvent();
3302 - (nsCocoaWindow*)geckoWidget {
3303 return mGeckoWindow;
3306 - (bool)toplevelActiveState {
3307 return mToplevelActiveState;
3310 - (void)sendToplevelActivateEvents {
3311 if (!mToplevelActiveState && mGeckoWindow) {
3312 mGeckoWindow->CocoaSendToplevelActivateEvents();
3314 mToplevelActiveState = true;
3318 - (void)sendToplevelDeactivateEvents {
3319 if (mToplevelActiveState && mGeckoWindow) {
3320 mGeckoWindow->CocoaSendToplevelDeactivateEvents();
3321 mToplevelActiveState = false;
3327 @interface NSView (FrameViewMethodSwizzling)
3328 - (NSPoint)FrameView__closeButtonOrigin;
3329 - (CGFloat)FrameView__titlebarHeight;
3332 @implementation NSView (FrameViewMethodSwizzling)
3334 - (NSPoint)FrameView__closeButtonOrigin {
3335 if (![self.window isKindOfClass:[ToolbarWindow class]]) {
3336 return self.FrameView__closeButtonOrigin;
3338 ToolbarWindow* win = (ToolbarWindow*)[self window];
3339 if (win.drawsContentsIntoWindowFrame &&
3340 !(win.styleMask & NSWindowStyleMaskFullScreen) &&
3341 (win.styleMask & NSWindowStyleMaskTitled)) {
3342 const NSRect buttonsRect = win.windowButtonsRect;
3343 if (NSIsEmptyRect(buttonsRect)) {
3344 // Empty rect. Let's hide the buttons.
3345 // Position is in non-flipped window coordinates. Using frame's height
3346 // for the vertical coordinate will move the buttons above the window,
3347 // making them invisible.
3348 return NSMakePoint(buttonsRect.origin.x, win.frame.size.height);
3349 } else if (win.windowTitlebarLayoutDirection ==
3350 NSUserInterfaceLayoutDirectionRightToLeft) {
3351 // We're in RTL mode, which means that the close button is the rightmost
3352 // button of the three window buttons. and buttonsRect.origin is the
3353 // bottom left corner of the green (zoom) button. The close button is 40px
3354 // to the right of the zoom button. This is confirmed to be the same on
3355 // all macOS versions between 10.12 - 12.0.
3356 return NSMakePoint(buttonsRect.origin.x + 40.0f, buttonsRect.origin.y);
3358 return buttonsRect.origin;
3360 return self.FrameView__closeButtonOrigin;
3363 - (CGFloat)FrameView__titlebarHeight {
3364 CGFloat height = [self FrameView__titlebarHeight];
3365 if ([[self window] isKindOfClass:[ToolbarWindow class]]) {
3366 // Make sure that the titlebar height includes our shifted buttons.
3367 // The following coordinates are in window space, with the origin being at
3368 // the bottom left corner of the window.
3369 ToolbarWindow* win = (ToolbarWindow*)[self window];
3370 CGFloat frameHeight = [self frame].size.height;
3371 CGFloat windowButtonY = frameHeight;
3372 if (!NSIsEmptyRect(win.windowButtonsRect) &&
3373 win.drawsContentsIntoWindowFrame &&
3374 !(win.styleMask & NSWindowStyleMaskFullScreen) &&
3375 (win.styleMask & NSWindowStyleMaskTitled)) {
3376 windowButtonY = win.windowButtonsRect.origin.y;
3378 height = std::max(height, frameHeight - windowButtonY);
3385 static NSMutableSet* gSwizzledFrameViewClasses = nil;
3387 @interface NSWindow (PrivateSetNeedsDisplayInRectMethod)
3388 - (void)_setNeedsDisplayInRect:(NSRect)aRect;
3391 @interface NSView (NSVisualEffectViewSetMaskImage)
3392 - (void)setMaskImage:(NSImage*)image;
3395 @interface BaseWindow (Private)
3396 - (void)removeTrackingArea;
3397 - (void)cursorUpdated:(NSEvent*)aEvent;
3398 - (void)reflowTitlebarElements;
3401 @implementation BaseWindow
3403 // The frame of a window is implemented using undocumented NSView subclasses.
3404 // We offset the window buttons by overriding the method _closeButtonOrigin on
3405 // these frame view classes. The class which is
3406 // used for a window is determined in the window's frameViewClassForStyleMask:
3407 // method, so this is where we make sure that we have swizzled the method on
3408 // all encountered classes.
3409 + (Class)frameViewClassForStyleMask:(NSUInteger)styleMask {
3410 Class frameViewClass = [super frameViewClassForStyleMask:styleMask];
3412 if (!gSwizzledFrameViewClasses) {
3413 gSwizzledFrameViewClasses = [[NSMutableSet setWithCapacity:3] retain];
3414 if (!gSwizzledFrameViewClasses) {
3415 return frameViewClass;
3419 static IMP our_closeButtonOrigin = class_getMethodImplementation(
3420 [NSView class], @selector(FrameView__closeButtonOrigin));
3421 static IMP our_titlebarHeight = class_getMethodImplementation(
3422 [NSView class], @selector(FrameView__titlebarHeight));
3424 if (![gSwizzledFrameViewClasses containsObject:frameViewClass]) {
3425 // Either of these methods might be implemented in both a subclass of
3426 // NSFrameView and one of its own subclasses. Which means that if we
3427 // aren't careful we might end up swizzling the same method twice.
3428 // Since method swizzling involves swapping pointers, this would break
3430 IMP _closeButtonOrigin = class_getMethodImplementation(
3431 frameViewClass, @selector(_closeButtonOrigin));
3432 if (_closeButtonOrigin && _closeButtonOrigin != our_closeButtonOrigin) {
3433 nsToolkit::SwizzleMethods(frameViewClass, @selector(_closeButtonOrigin),
3434 @selector(FrameView__closeButtonOrigin));
3437 // Override _titlebarHeight so that the floating titlebar doesn't clip the
3438 // bottom of the window buttons which we move down with our override of
3439 // _closeButtonOrigin.
3440 IMP _titlebarHeight = class_getMethodImplementation(
3441 frameViewClass, @selector(_titlebarHeight));
3442 if (_titlebarHeight && _titlebarHeight != our_titlebarHeight) {
3443 nsToolkit::SwizzleMethods(frameViewClass, @selector(_titlebarHeight),
3444 @selector(FrameView__titlebarHeight));
3447 [gSwizzledFrameViewClasses addObject:frameViewClass];
3450 return frameViewClass;
3453 - (id)initWithContentRect:(NSRect)aContentRect
3454 styleMask:(NSUInteger)aStyle
3455 backing:(NSBackingStoreType)aBufferingType
3457 mDrawsIntoWindowFrame = NO;
3458 [super initWithContentRect:aContentRect
3460 backing:aBufferingType
3463 mDisabledNeedsDisplay = NO;
3464 mTrackingArea = nil;
3465 mDirtyRect = NSZeroRect;
3469 mIsAnimationSuppressed = NO;
3470 [self updateTrackingArea];
3475 // Returns an autoreleased NSImage.
3476 static NSImage* GetMenuMaskImage() {
3477 const CGFloat radius = 6.0f;
3478 const NSSize maskSize = {radius * 3.0f, radius * 3.0f};
3479 NSImage* maskImage = [NSImage imageWithSize:maskSize
3481 drawingHandler:^BOOL(NSRect dstRect) {
3482 NSBezierPath* path = [NSBezierPath
3483 bezierPathWithRoundedRect:dstRect
3486 [NSColor.blackColor set];
3490 maskImage.capInsets = NSEdgeInsetsMake(radius, radius, radius, radius);
3494 - (void)swapOutChildViewWrapper:(NSView*)aNewWrapper {
3495 [aNewWrapper setFrame:[[self contentView] frame]];
3496 NSView* childView = [[self mainChildView] retain];
3497 [childView removeFromSuperview];
3498 [aNewWrapper addSubview:childView];
3499 [childView release];
3500 [super setContentView:aNewWrapper];
3503 - (void)setEffectViewWrapperForStyle:(WindowShadow)aStyle {
3504 if (aStyle == WindowShadow::Menu || aStyle == WindowShadow::Tooltip) {
3505 // Add an effect view wrapper so that the OS draws the appropriate
3506 // vibrancy effect and window border.
3507 BOOL isMenu = aStyle == WindowShadow::Menu;
3508 NSView* effectView = VibrancyManager::CreateEffectView(
3509 isMenu ? VibrancyType::MENU : VibrancyType::TOOLTIP, YES);
3511 // Turn on rounded corner masking.
3512 [effectView setMaskImage:GetMenuMaskImage()];
3514 [self swapOutChildViewWrapper:effectView];
3515 [effectView release];
3517 // Remove the existing wrapper.
3518 NSView* wrapper = [[NSView alloc] initWithFrame:NSZeroRect];
3519 [wrapper setWantsLayer:YES];
3520 [self swapOutChildViewWrapper:wrapper];
3525 - (NSTouchBar*)makeTouchBar {
3526 mTouchBar = [[nsTouchBar alloc] init];
3528 sTouchBarIsInitialized = YES;
3533 - (void)setBeingShown:(BOOL)aValue {
3534 mBeingShown = aValue;
3537 - (BOOL)isBeingShown {
3541 - (BOOL)isVisibleOrBeingShown {
3542 return [super isVisible] || mBeingShown;
3545 - (void)setIsAnimationSuppressed:(BOOL)aValue {
3546 mIsAnimationSuppressed = aValue;
3549 - (BOOL)isAnimationSuppressed {
3550 return mIsAnimationSuppressed;
3553 - (void)disableSetNeedsDisplay {
3554 mDisabledNeedsDisplay = YES;
3557 - (void)enableSetNeedsDisplay {
3558 mDisabledNeedsDisplay = NO;
3562 [mTouchBar release];
3563 [self removeTrackingArea];
3564 ChildViewMouseTracker::OnDestroyWindow(self);
3568 static const NSString* kStateTitleKey = @"title";
3569 static const NSString* kStateDrawsContentsIntoWindowFrameKey =
3570 @"drawsContentsIntoWindowFrame";
3571 static const NSString* kStateShowsToolbarButton = @"showsToolbarButton";
3572 static const NSString* kStateCollectionBehavior = @"collectionBehavior";
3573 static const NSString* kStateWantsTitleDrawn = @"wantsTitleDrawn";
3575 - (void)importState:(NSDictionary*)aState {
3576 if (NSString* title = [aState objectForKey:kStateTitleKey]) {
3577 [self setTitle:title];
3579 [self setDrawsContentsIntoWindowFrame:
3580 [[aState objectForKey:kStateDrawsContentsIntoWindowFrameKey]
3582 [self setShowsToolbarButton:[[aState objectForKey:kStateShowsToolbarButton]
3584 [self setCollectionBehavior:[[aState objectForKey:kStateCollectionBehavior]
3586 [self setWantsTitleDrawn:[[aState objectForKey:kStateWantsTitleDrawn]
3590 - (NSMutableDictionary*)exportState {
3591 NSMutableDictionary* state = [NSMutableDictionary dictionaryWithCapacity:10];
3592 if (NSString* title = [self title]) {
3593 [state setObject:title forKey:kStateTitleKey];
3595 [state setObject:[NSNumber numberWithBool:[self drawsContentsIntoWindowFrame]]
3596 forKey:kStateDrawsContentsIntoWindowFrameKey];
3597 [state setObject:[NSNumber numberWithBool:[self showsToolbarButton]]
3598 forKey:kStateShowsToolbarButton];
3599 [state setObject:[NSNumber numberWithUnsignedInt:[self collectionBehavior]]
3600 forKey:kStateCollectionBehavior];
3601 [state setObject:[NSNumber numberWithBool:[self wantsTitleDrawn]]
3602 forKey:kStateWantsTitleDrawn];
3606 - (void)setDrawsContentsIntoWindowFrame:(BOOL)aState {
3607 bool changed = (aState != mDrawsIntoWindowFrame);
3608 mDrawsIntoWindowFrame = aState;
3610 [self reflowTitlebarElements];
3614 - (BOOL)drawsContentsIntoWindowFrame {
3615 return mDrawsIntoWindowFrame;
3618 - (NSRect)childViewRectForFrameRect:(NSRect)aFrameRect {
3619 if (mDrawsIntoWindowFrame) {
3622 NSUInteger styleMask = [self styleMask];
3623 styleMask &= ~NSWindowStyleMaskFullSizeContentView;
3624 return [NSWindow contentRectForFrameRect:aFrameRect styleMask:styleMask];
3627 - (NSRect)frameRectForChildViewRect:(NSRect)aChildViewRect {
3628 if (mDrawsIntoWindowFrame) {
3629 return aChildViewRect;
3631 NSUInteger styleMask = [self styleMask];
3632 styleMask &= ~NSWindowStyleMaskFullSizeContentView;
3633 return [NSWindow frameRectForContentRect:aChildViewRect styleMask:styleMask];
3636 - (NSTimeInterval)animationResizeTime:(NSRect)newFrame {
3637 if (mIsAnimationSuppressed) {
3638 // Should not animate the initial session-restore size change
3642 return [super animationResizeTime:newFrame];
3645 - (void)setWantsTitleDrawn:(BOOL)aDrawTitle {
3646 mDrawTitle = aDrawTitle;
3647 [self setTitleVisibility:mDrawTitle ? NSWindowTitleVisible
3648 : NSWindowTitleHidden];
3651 - (BOOL)wantsTitleDrawn {
3655 - (NSView*)trackingAreaView {
3656 NSView* contentView = [self contentView];
3657 return [contentView superview] ? [contentView superview] : contentView;
3660 - (NSArray<NSView*>*)contentViewContents {
3661 return [[[[self contentView] subviews] copy] autorelease];
3664 - (ChildView*)mainChildView {
3665 NSView* contentView = [self contentView];
3666 NSView* lastView = [[contentView subviews] lastObject];
3667 if ([lastView isKindOfClass:[ChildView class]]) {
3668 return (ChildView*)lastView;
3673 - (void)removeTrackingArea {
3674 if (mTrackingArea) {
3675 [[self trackingAreaView] removeTrackingArea:mTrackingArea];
3676 [mTrackingArea release];
3677 mTrackingArea = nil;
3681 - (void)updateTrackingArea {
3682 [self removeTrackingArea];
3684 NSView* view = [self trackingAreaView];
3685 const NSTrackingAreaOptions options = NSTrackingMouseEnteredAndExited |
3686 NSTrackingMouseMoved |
3687 NSTrackingActiveAlways;
3688 mTrackingArea = [[NSTrackingArea alloc] initWithRect:[view bounds]
3692 [view addTrackingArea:mTrackingArea];
3695 - (void)mouseEntered:(NSEvent*)aEvent {
3696 ChildViewMouseTracker::MouseEnteredWindow(aEvent);
3699 - (void)mouseExited:(NSEvent*)aEvent {
3700 ChildViewMouseTracker::MouseExitedWindow(aEvent);
3703 - (void)mouseMoved:(NSEvent*)aEvent {
3704 ChildViewMouseTracker::MouseMoved(aEvent);
3707 - (void)cursorUpdated:(NSEvent*)aEvent {
3708 // Nothing to do here, but NSTrackingArea wants us to implement this method.
3711 - (void)_setNeedsDisplayInRect:(NSRect)aRect {
3712 // Prevent unnecessary invalidations due to moving NSViews (e.g. for plugins)
3713 if (!mDisabledNeedsDisplay) {
3714 // This method is only called by Cocoa, so when we're here, we know that
3715 // it's available and don't need to check whether our superclass responds
3717 [super _setNeedsDisplayInRect:aRect];
3718 mDirtyRect = NSUnionRect(mDirtyRect, aRect);
3722 - (NSRect)getAndResetNativeDirtyRect {
3723 NSRect dirtyRect = mDirtyRect;
3724 mDirtyRect = NSZeroRect;
3728 // Possibly move the titlebar buttons.
3729 - (void)reflowTitlebarElements {
3730 NSView* frameView = [[self contentView] superview];
3731 if ([frameView respondsToSelector:@selector(_tileTitlebarAndRedisplay:)]) {
3732 [frameView _tileTitlebarAndRedisplay:NO];
3736 - (BOOL)respondsToSelector:(SEL)aSelector {
3737 // Claim the window doesn't respond to this so that the system
3738 // doesn't steal keyboard equivalents for it. Bug 613710.
3739 if (aSelector == @selector(cancelOperation:)) {
3743 return [super respondsToSelector:aSelector];
3746 - (void)doCommandBySelector:(SEL)aSelector {
3747 // We override this so that it won't beep if it can't act.
3748 // We want to control the beeping for missing or disabled
3749 // commands ourselves.
3750 [self tryToPerform:aSelector with:nil];
3753 - (id)accessibilityAttributeValue:(NSString*)attribute {
3754 NS_OBJC_BEGIN_TRY_BLOCK_RETURN;
3756 id retval = [super accessibilityAttributeValue:attribute];
3758 // The following works around a problem with Text-to-Speech on OS X 10.7.
3759 // See bug 674612 for more info.
3761 // When accessibility is off, AXUIElementCopyAttributeValue(), when called
3762 // on an AXApplication object to get its AXFocusedUIElement attribute,
3763 // always returns an AXWindow object (the actual browser window -- never a
3764 // mozAccessible object). This also happens with accessibility turned on,
3765 // if no other object in the browser window has yet been focused. But if
3766 // the browser window has a title bar (as it currently always does), the
3767 // AXWindow object will always have four "accessible" children, one of which
3768 // is an AXStaticText object (the title bar's "title"; the other three are
3769 // the close, minimize and zoom buttons). This means that (for complicated
3770 // reasons, for which see bug 674612) Text-to-Speech on OS X 10.7 will often
3771 // "speak" the window title, no matter what text is selected, or even if no
3772 // text at all is selected. (This always happens when accessibility is off.
3773 // It doesn't happen in Firefox releases because Apple has (on OS X 10.7)
3774 // special-cased the handling of apps whose CFBundleIdentifier is
3775 // org.mozilla.firefox.)
3777 // We work around this problem by only returning AXChildren that are
3778 // mozAccessible object or are one of the titlebar's buttons (which
3779 // instantiate subclasses of NSButtonCell).
3780 if ([retval isKindOfClass:[NSArray class]] &&
3781 [attribute isEqualToString:@"AXChildren"]) {
3782 NSMutableArray* holder = [NSMutableArray arrayWithCapacity:10];
3783 [holder addObjectsFromArray:(NSArray*)retval];
3784 NSUInteger count = [holder count];
3785 for (NSInteger i = count - 1; i >= 0; --i) {
3786 id item = [holder objectAtIndex:i];
3787 // Remove anything from holder that isn't one of the titlebar's buttons
3788 // (which instantiate subclasses of NSButtonCell) or a mozAccessible
3789 // object (or one of its subclasses).
3790 if (![item isKindOfClass:[NSButtonCell class]] &&
3791 ![item respondsToSelector:@selector(hasRepresentedView)]) {
3792 [holder removeObjectAtIndex:i];
3795 retval = [NSArray arrayWithArray:holder];
3800 NS_OBJC_END_TRY_BLOCK_RETURN(nil);
3803 - (void)releaseJSObjects {
3804 [mTouchBar releaseJSObjects];
3809 @interface NSView (NSThemeFrame)
3810 - (void)_drawTitleStringInClip:(NSRect)aRect;
3811 - (void)_maskCorners:(NSUInteger)aFlags clipRect:(NSRect)aRect;
3814 @implementation MOZTitlebarView
3816 - (instancetype)initWithFrame:(NSRect)aFrame {
3817 self = [super initWithFrame:aFrame];
3819 self.material = NSVisualEffectMaterialTitlebar;
3820 self.blendingMode = NSVisualEffectBlendingModeWithinWindow;
3822 // Add a separator line at the bottom of the titlebar. NSBoxSeparator isn't a
3823 // perfect match for a native titlebar separator, but it's better than
3824 // nothing. We really want the appearance that _NSTitlebarDecorationView
3825 // creates with the help of CoreUI, but there's no public API for that.
3826 NSBox* separatorLine =
3827 [[NSBox alloc] initWithFrame:NSMakeRect(0, 0, aFrame.size.width, 1)];
3828 separatorLine.autoresizingMask = NSViewWidthSizable | NSViewMaxYMargin;
3829 separatorLine.boxType = NSBoxSeparator;
3830 [self addSubview:separatorLine];
3831 [separatorLine release];
3836 - (BOOL)mouseDownCanMoveWindow {
3840 - (void)mouseUp:(NSEvent*)event {
3841 if ([event clickCount] == 2) {
3842 // Handle titlebar double click. We don't get the window's default behavior
3843 // here because the window uses NSWindowStyleMaskFullSizeContentView, and
3844 // this view (the titlebar gradient view) is technically part of the window
3845 // "contents" (it's a subview of the content view).
3846 if (nsCocoaUtils::ShouldZoomOnTitlebarDoubleClick()) {
3847 [[self window] performZoom:nil];
3848 } else if (nsCocoaUtils::ShouldMinimizeOnTitlebarDoubleClick()) {
3849 [[self window] performMiniaturize:nil];
3856 @interface MOZTitlebarAccessoryView : NSView
3859 @implementation MOZTitlebarAccessoryView : NSView
3860 - (void)viewWillMoveToWindow:(NSWindow*)aWindow {
3862 // When entering full screen mode, titlebar accessory views are inserted
3863 // into a floating NSWindow which houses the window titlebar and toolbars.
3864 // In order to work around a drawing bug with titlebarAppearsTransparent
3865 // windows in full screen mode, disable titlebar separators for all
3866 // NSWindows that this view is used in, including the floating full screen
3867 // toolbar window. The drawing bug was filed as FB9056136. See bug 1700211
3868 // for more details.
3869 if (@available(macOS 11.0, *)) {
3870 aWindow.titlebarSeparatorStyle = NSTitlebarSeparatorStyleNone;
3876 @implementation FullscreenTitlebarTracker
3877 - (FullscreenTitlebarTracker*)init {
3880 [[[MOZTitlebarAccessoryView alloc] initWithFrame:NSZeroRect] autorelease];
3886 // This class allows us to exercise control over the window's title bar. It is
3887 // used for all windows with titlebars.
3889 // ToolbarWindow supports two modes:
3890 // - drawsContentsIntoWindowFrame mode: In this mode, the Gecko ChildView is
3891 // sized to cover the entire window frame and manages titlebar drawing.
3892 // - separate titlebar mode, with support for unified toolbars: In this mode,
3893 // the Gecko ChildView does not extend into the titlebar. However, this
3894 // window's content view (which is the ChildView's superview) *does* extend
3895 // into the titlebar. Moreover, in this mode, we place a MOZTitlebarView
3896 // in the content view, as a sibling of the ChildView.
3898 // The "separate titlebar mode" supports the "unified toolbar" look:
3899 // If there's a toolbar right below the titlebar, the two can "connect" and
3900 // form a single gradient without a separator line in between.
3902 // The following mechanism communicates the height of the unified toolbar to
3903 // the ToolbarWindow:
3905 // 1) In the style sheet we set the toolbar's -moz-appearance to toolbar.
3906 // 2) When the toolbar is visible and we paint the application chrome
3907 // window, the array that Gecko passes nsChildView::UpdateThemeGeometries
3908 // will contain an entry for the widget type StyleAppearance::Toolbar.
3909 // 3) nsChildView::UpdateThemeGeometries passes the toolbar's height, plus the
3910 // titlebar height, to -[ToolbarWindow setUnifiedToolbarHeight:].
3912 // The actual drawing of the gradient happens in two parts: The titlebar part
3913 // (i.e. the top 22 pixels of the gradient) is drawn by the MOZTitlebarView,
3914 // which is a subview of the window's content view and a sibling of the
3915 // ChildView. The rest of the gradient is drawn by Gecko into the ChildView, as
3916 // part of the -moz-appearance rendering of the toolbar.
3917 @implementation ToolbarWindow
3919 - (id)initWithContentRect:(NSRect)aChildViewRect
3920 styleMask:(NSUInteger)aStyle
3921 backing:(NSBackingStoreType)aBufferingType
3923 NS_OBJC_BEGIN_TRY_BLOCK_RETURN;
3925 // We treat aChildViewRect as the rectangle that the window's main ChildView
3926 // should be sized to. Get the right frameRect for the requested child view
3928 NSRect frameRect = [NSWindow frameRectForContentRect:aChildViewRect
3931 // Always size the content view to the full frame size of the window.
3932 // We do this even if we want this window to have a titlebar; in that case,
3933 // the window's content view covers the entire window but the ChildView inside
3934 // it will only cover the content area. We do this so that we can render the
3935 // titlebar gradient manually, with a subview of our content view that's
3936 // positioned in the titlebar area. This lets us have a smooth connection
3937 // between titlebar and toolbar gradient in case the window has a "unified
3938 // toolbar + titlebar" look. Moreover, always using a full size content view
3939 // lets us toggle the titlebar on and off without changing the window's style
3940 // mask (which would have other subtle effects, for example on keyboard
3942 aStyle |= NSWindowStyleMaskFullSizeContentView;
3944 // -[NSWindow initWithContentRect:styleMask:backing:defer:] calls
3945 // [self frameRectForContentRect:styleMask:] to convert the supplied content
3946 // rect to the window's frame rect. We've overridden that method to be a
3947 // pass-through function. So, in order to get the intended frameRect, we need
3948 // to supply frameRect itself as the "content rect".
3949 NSRect contentRect = frameRect;
3951 if ((self = [super initWithContentRect:contentRect
3953 backing:aBufferingType
3955 mTitlebarView = nil;
3956 mUnifiedToolbarHeight = 22.0f;
3957 mSheetAttachmentPosition = aChildViewRect.size.height;
3958 mWindowButtonsRect = NSZeroRect;
3959 mInitialTitlebarHeight = [self titlebarHeight];
3961 [self setTitlebarAppearsTransparent:YES];
3962 if (@available(macOS 11.0, *)) {
3963 self.titlebarSeparatorStyle = NSTitlebarSeparatorStyleNone;
3965 [self updateTitlebarView];
3967 mFullscreenTitlebarTracker = [[FullscreenTitlebarTracker alloc] init];
3968 // revealAmount is an undocumented property of
3969 // NSTitlebarAccessoryViewController that updates whenever the menubar
3970 // slides down in fullscreen mode.
3971 [mFullscreenTitlebarTracker addObserver:self
3972 forKeyPath:@"revealAmount"
3973 options:NSKeyValueObservingOptionNew
3975 // Adding this accessory view controller allows us to shift the toolbar down
3976 // when the user mouses to the top of the screen in fullscreen.
3978 addTitlebarAccessoryViewController:mFullscreenTitlebarTracker];
3982 NS_OBJC_END_TRY_BLOCK_RETURN(nil);
3985 - (void)observeValueForKeyPath:(NSString*)keyPath
3987 change:(NSDictionary<NSKeyValueChangeKey, id>*)change
3988 context:(void*)context {
3989 if ([keyPath isEqualToString:@"revealAmount"]) {
3990 [[self mainChildView] ensureNextCompositeIsAtomicWithMainThreadPaint];
3991 NSNumber* revealAmount = (change[NSKeyValueChangeNewKey]);
3992 [self updateTitlebarShownAmount:[revealAmount doubleValue]];
3994 [super observeValueForKeyPath:keyPath
4001 static bool ScreenHasNotch(nsCocoaWindow* aGeckoWindow) {
4002 if (@available(macOS 12.0, *)) {
4003 nsCOMPtr<nsIScreen> widgetScreen = aGeckoWindow->GetWidgetScreen();
4004 NSScreen* cocoaScreen =
4005 ScreenHelperCocoa::CocoaScreenForScreen(widgetScreen);
4006 return cocoaScreen.safeAreaInsets.top != 0.0f;
4011 static bool ShouldShiftByMenubarHeightInFullscreen(nsCocoaWindow* aWindow) {
4012 switch (StaticPrefs::widget_macos_shift_by_menubar_on_fullscreen()) {
4020 // TODO: On notch-less macbooks, this creates extra space when the
4021 // "automatically show and hide the menubar on fullscreen" option is unchecked
4022 // (default checked). We tried to detect that in bug 1737831 but it wasn't
4023 // reliable enough, see the regressions from that bug. For now, stick to the
4024 // good behavior for default configurations (that is, shift by menubar height
4025 // on notch-less macbooks, and don't for devices that have a notch). This will
4026 // need refinement in the future.
4027 return !ScreenHasNotch(aWindow);
4030 - (void)updateTitlebarShownAmount:(CGFloat)aShownAmount {
4031 NSInteger styleMask = [self styleMask];
4032 if (!(styleMask & NSWindowStyleMaskFullScreen)) {
4033 // We are not interested in the size of the titlebar unless we are in
4038 // [NSApp mainMenu] menuBarHeight] returns one of two values: the full height
4039 // if the menubar is shown or is in the process of being shown, and 0
4040 // otherwise. Since we are multiplying the menubar height by aShownAmount, we
4041 // always want the full height.
4042 CGFloat menuBarHeight = NSApp.mainMenu.menuBarHeight;
4043 if (menuBarHeight > 0.0f) {
4044 mMenuBarHeight = menuBarHeight;
4046 if ([[self delegate] isKindOfClass:[WindowDelegate class]]) {
4047 WindowDelegate* windowDelegate = (WindowDelegate*)[self delegate];
4048 nsCocoaWindow* geckoWindow = [windowDelegate geckoWidget];
4053 if (nsIWidgetListener* listener = geckoWindow->GetWidgetListener()) {
4054 // Use the titlebar height cached in our frame rather than
4055 // [ToolbarWindow titlebarHeight]. titlebarHeight returns 0 when we're in
4057 CGFloat shiftByPixels = mInitialTitlebarHeight * aShownAmount;
4058 if (ShouldShiftByMenubarHeightInFullscreen(geckoWindow)) {
4059 shiftByPixels += mMenuBarHeight * aShownAmount;
4061 // Use mozilla::DesktopToLayoutDeviceScale rather than the
4062 // DesktopToLayoutDeviceScale in nsCocoaWindow. The latter accounts for
4063 // screen DPI. We don't want that because the revealAmount property
4064 // already accounts for it, so we'd be compounding DPI scales > 1.
4065 mozilla::DesktopCoord coord = LayoutDeviceCoord(shiftByPixels) /
4066 mozilla::DesktopToLayoutDeviceScale();
4068 listener->MacFullscreenMenubarOverlapChanged(coord);
4074 [mTitlebarView release];
4075 [mFullscreenTitlebarTracker removeObserver:self forKeyPath:@"revealAmount"];
4076 [mFullscreenTitlebarTracker removeFromParentViewController];
4077 [mFullscreenTitlebarTracker release];
4082 - (NSArray<NSView*>*)contentViewContents {
4083 NSMutableArray<NSView*>* contents =
4084 [[[self contentView] subviews] mutableCopy];
4085 if (mTitlebarView) {
4086 // Do not include the titlebar gradient view in the returned array.
4087 [contents removeObject:mTitlebarView];
4089 return [contents autorelease];
4092 - (void)updateTitlebarView {
4093 BOOL needTitlebarView =
4094 ![self drawsContentsIntoWindowFrame] || mUnifiedToolbarHeight > 0;
4095 if (needTitlebarView && !mTitlebarView) {
4097 [[MOZTitlebarView alloc] initWithFrame:[self unifiedToolbarRect]];
4098 mTitlebarView.autoresizingMask = NSViewWidthSizable | NSViewMinYMargin;
4099 [self.contentView addSubview:mTitlebarView
4100 positioned:NSWindowBelow
4102 } else if (needTitlebarView && mTitlebarView) {
4103 mTitlebarView.frame = [self unifiedToolbarRect];
4104 } else if (!needTitlebarView && mTitlebarView) {
4105 [mTitlebarView removeFromSuperview];
4106 [mTitlebarView release];
4107 mTitlebarView = nil;
4111 - (void)windowMainStateChanged {
4112 [self setTitlebarNeedsDisplay];
4113 [[self mainChildView] ensureNextCompositeIsAtomicWithMainThreadPaint];
4116 - (void)setTitlebarNeedsDisplay {
4117 [mTitlebarView setNeedsDisplay:YES];
4120 - (NSRect)titlebarRect {
4121 CGFloat titlebarHeight = [self titlebarHeight];
4122 return NSMakeRect(0, [self frame].size.height - titlebarHeight,
4123 [self frame].size.width, titlebarHeight);
4126 // In window contentView coordinates (origin bottom left)
4127 - (NSRect)unifiedToolbarRect {
4128 return NSMakeRect(0, [self frame].size.height - mUnifiedToolbarHeight,
4129 [self frame].size.width, mUnifiedToolbarHeight);
4132 // Returns the unified height of titlebar + toolbar.
4133 - (CGFloat)unifiedToolbarHeight {
4134 return mUnifiedToolbarHeight;
4137 - (CGFloat)titlebarHeight {
4138 // We use the original content rect here, not what we return from
4139 // [self contentRectForFrameRect:], because that would give us a
4140 // titlebarHeight of zero.
4141 NSRect frameRect = [self frame];
4142 NSUInteger styleMask = [self styleMask];
4143 styleMask &= ~NSWindowStyleMaskFullSizeContentView;
4144 NSRect originalContentRect = [NSWindow contentRectForFrameRect:frameRect
4145 styleMask:styleMask];
4146 return NSMaxY(frameRect) - NSMaxY(originalContentRect);
4149 // Stores the complete height of titlebar + toolbar.
4150 - (void)setUnifiedToolbarHeight:(CGFloat)aHeight {
4151 if (aHeight == mUnifiedToolbarHeight) return;
4153 mUnifiedToolbarHeight = aHeight;
4155 [self updateTitlebarView];
4158 // Extending the content area into the title bar works by resizing the
4159 // mainChildView so that it covers the titlebar.
4160 - (void)setDrawsContentsIntoWindowFrame:(BOOL)aState {
4161 BOOL stateChanged = ([self drawsContentsIntoWindowFrame] != aState);
4162 [super setDrawsContentsIntoWindowFrame:aState];
4163 if (stateChanged && [[self delegate] isKindOfClass:[WindowDelegate class]]) {
4164 // Here we extend / shrink our mainChildView. We do that by firing a resize
4165 // event which will cause the ChildView to be resized to the rect returned
4166 // by nsCocoaWindow::GetClientBounds. GetClientBounds bases its return
4167 // value on what we return from drawsContentsIntoWindowFrame.
4168 WindowDelegate* windowDelegate = (WindowDelegate*)[self delegate];
4169 nsCocoaWindow* geckoWindow = [windowDelegate geckoWidget];
4171 // Re-layout our contents.
4172 geckoWindow->ReportSizeEvent();
4175 // Resizing the content area causes a reflow which would send a synthesized
4176 // mousemove event to the old mouse position relative to the top left
4177 // corner of the content area. But the mouse has shifted relative to the
4178 // content area, so that event would have wrong position information. So
4179 // we'll send a mouse move event with the correct new position.
4180 ChildViewMouseTracker::ResendLastMouseMoveEvent();
4183 [self updateTitlebarView];
4186 - (void)setWantsTitleDrawn:(BOOL)aDrawTitle {
4187 [super setWantsTitleDrawn:aDrawTitle];
4188 [self setTitlebarNeedsDisplay];
4191 - (void)setSheetAttachmentPosition:(CGFloat)aY {
4192 mSheetAttachmentPosition = aY;
4195 - (CGFloat)sheetAttachmentPosition {
4196 return mSheetAttachmentPosition;
4199 - (void)placeWindowButtons:(NSRect)aRect {
4200 if (!NSEqualRects(mWindowButtonsRect, aRect)) {
4201 mWindowButtonsRect = aRect;
4202 [self reflowTitlebarElements];
4206 - (NSRect)windowButtonsRect {
4207 return mWindowButtonsRect;
4210 // Returning YES here makes the setShowsToolbarButton method work even though
4211 // the window doesn't contain an NSToolbar.
4212 - (BOOL)_hasToolbar {
4216 // Dispatch a toolbar pill button clicked message to Gecko.
4217 - (void)_toolbarPillButtonClicked:(id)sender {
4218 NS_OBJC_BEGIN_TRY_IGNORE_BLOCK;
4222 if ([[self delegate] isKindOfClass:[WindowDelegate class]]) {
4223 WindowDelegate* windowDelegate = (WindowDelegate*)[self delegate];
4224 nsCocoaWindow* geckoWindow = [windowDelegate geckoWidget];
4225 if (!geckoWindow) return;
4227 nsIWidgetListener* listener = geckoWindow->GetWidgetListener();
4228 if (listener) listener->OSToolbarButtonPressed();
4231 NS_OBJC_END_TRY_IGNORE_BLOCK;
4234 // Retain and release "self" to avoid crashes when our widget (and its native
4235 // window) is closed as a result of processing a key equivalent (e.g.
4236 // Command+w or Command+q). This workaround is only needed for a window
4237 // that can become key.
4238 - (BOOL)performKeyEquivalent:(NSEvent*)theEvent {
4239 NS_OBJC_BEGIN_TRY_BLOCK_RETURN;
4241 NSWindow* nativeWindow = [self retain];
4242 BOOL retval = [super performKeyEquivalent:theEvent];
4243 [nativeWindow release];
4246 NS_OBJC_END_TRY_BLOCK_RETURN(NO);
4249 - (void)sendEvent:(NSEvent*)anEvent {
4250 NSEventType type = [anEvent type];
4253 case NSEventTypeScrollWheel:
4254 case NSEventTypeLeftMouseDown:
4255 case NSEventTypeLeftMouseUp:
4256 case NSEventTypeRightMouseDown:
4257 case NSEventTypeRightMouseUp:
4258 case NSEventTypeOtherMouseDown:
4259 case NSEventTypeOtherMouseUp:
4260 case NSEventTypeMouseMoved:
4261 case NSEventTypeLeftMouseDragged:
4262 case NSEventTypeRightMouseDragged:
4263 case NSEventTypeOtherMouseDragged: {
4264 // Drop all mouse events if a modal window has appeared above us.
4265 // This helps make us behave as if the OS were running a "real" modal
4267 id delegate = [self delegate];
4268 if (delegate && [delegate isKindOfClass:[WindowDelegate class]]) {
4269 nsCocoaWindow* widget = [(WindowDelegate*)delegate geckoWidget];
4271 if (gGeckoAppModalWindowList &&
4272 (widget != gGeckoAppModalWindowList->window))
4274 if (widget->HasModalDescendents()) return;
4283 [super sendEvent:anEvent];
4288 @implementation PopupWindow
4290 - (id)initWithContentRect:(NSRect)contentRect
4291 styleMask:(NSUInteger)styleMask
4292 backing:(NSBackingStoreType)bufferingType
4293 defer:(BOOL)deferCreation {
4294 NS_OBJC_BEGIN_TRY_BLOCK_RETURN;
4296 mIsContextMenu = false;
4297 return [super initWithContentRect:contentRect
4299 backing:bufferingType
4300 defer:deferCreation];
4302 NS_OBJC_END_TRY_BLOCK_RETURN(nil);
4305 // Override the private API _backdropBleedAmount. This determines how much the
4306 // desktop wallpaper contributes to the vibrancy backdrop.
4307 // Return 0 in order to match what the system does for sheet windows and
4308 // _NSPopoverWindows.
4309 - (CGFloat)_backdropBleedAmount {
4313 // Override the private API shadowOptions.
4314 // The constants below were found in AppKit's implementations of the
4315 // shadowOptions method on the various window types.
4316 static const NSUInteger kWindowShadowOptionsNoShadow = 0;
4317 static const NSUInteger kWindowShadowOptionsMenu = 2;
4318 static const NSUInteger kWindowShadowOptionsTooltip = 4;
4320 - (NSDictionary*)shadowParameters {
4321 NSDictionary* parent = [super shadowParameters];
4322 // NSLog(@"%@", parent);
4323 if (self.shadowStyle != WindowShadow::Panel) {
4326 NSMutableDictionary* copy = [parent mutableCopy];
4327 for (auto* key : {@"com.apple.WindowShadowRimDensityActive",
4328 @"com.apple.WindowShadowRimDensityInactive"}) {
4329 if ([parent objectForKey:key] != nil) {
4330 [copy setValue:@(0) forKey:key];
4336 - (NSUInteger)shadowOptions {
4337 if (!self.hasShadow) {
4338 return kWindowShadowOptionsNoShadow;
4341 switch (self.shadowStyle) {
4342 case WindowShadow::None:
4343 return kWindowShadowOptionsNoShadow;
4345 case WindowShadow::Menu:
4346 case WindowShadow::Panel:
4347 return kWindowShadowOptionsMenu;
4349 case WindowShadow::Tooltip:
4350 return kWindowShadowOptionsTooltip;
4354 - (BOOL)isContextMenu {
4355 return mIsContextMenu;
4358 - (void)setIsContextMenu:(BOOL)flag {
4359 mIsContextMenu = flag;
4362 - (BOOL)canBecomeMainWindow {
4363 // This is overriden because the default is 'yes' when a titlebar is present.
4369 // According to Apple's docs on [NSWindow canBecomeKeyWindow] and [NSWindow
4370 // canBecomeMainWindow], windows without a title bar or resize bar can't (by
4371 // default) become key or main. But if a window can't become key, it can't
4372 // accept keyboard input (bmo bug 393250). And it should also be possible for
4373 // an otherwise "ordinary" window to become main. We need to override these
4374 // two methods to make this happen.
4375 @implementation BorderlessWindow
4377 - (BOOL)canBecomeKeyWindow {
4381 - (void)sendEvent:(NSEvent*)anEvent {
4382 NSEventType type = [anEvent type];
4385 case NSEventTypeScrollWheel:
4386 case NSEventTypeLeftMouseDown:
4387 case NSEventTypeLeftMouseUp:
4388 case NSEventTypeRightMouseDown:
4389 case NSEventTypeRightMouseUp:
4390 case NSEventTypeOtherMouseDown:
4391 case NSEventTypeOtherMouseUp:
4392 case NSEventTypeMouseMoved:
4393 case NSEventTypeLeftMouseDragged:
4394 case NSEventTypeRightMouseDragged:
4395 case NSEventTypeOtherMouseDragged: {
4396 // Drop all mouse events if a modal window has appeared above us.
4397 // This helps make us behave as if the OS were running a "real" modal
4399 id delegate = [self delegate];
4400 if (delegate && [delegate isKindOfClass:[WindowDelegate class]]) {
4401 nsCocoaWindow* widget = [(WindowDelegate*)delegate geckoWidget];
4403 if (gGeckoAppModalWindowList &&
4404 (widget != gGeckoAppModalWindowList->window))
4406 if (widget->HasModalDescendents()) return;
4415 [super sendEvent:anEvent];
4418 // Apple's doc on this method says that the NSWindow class's default is not to
4419 // become main if the window isn't "visible" -- so we should replicate that
4420 // behavior here. As best I can tell, the [NSWindow isVisible] method is an
4421 // accurate test of what Apple means by "visibility".
4422 - (BOOL)canBecomeMainWindow {
4423 NS_OBJC_BEGIN_TRY_BLOCK_RETURN;
4425 if (![self isVisible]) return NO;
4428 NS_OBJC_END_TRY_BLOCK_RETURN(NO);
4431 // Retain and release "self" to avoid crashes when our widget (and its native
4432 // window) is closed as a result of processing a key equivalent (e.g.
4433 // Command+w or Command+q). This workaround is only needed for a window
4434 // that can become key.
4435 - (BOOL)performKeyEquivalent:(NSEvent*)theEvent {
4436 NS_OBJC_BEGIN_TRY_BLOCK_RETURN;
4438 NSWindow* nativeWindow = [self retain];
4439 BOOL retval = [super performKeyEquivalent:theEvent];
4440 [nativeWindow release];
4443 NS_OBJC_END_TRY_BLOCK_RETURN(NO);