1 /* -*- Mode: Objective-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 "nsTouchBarNativeAPIDefines.h"
27 #include "nsPIDOMWindow.h"
28 #include "nsThreadUtils.h"
29 #include "nsMenuBarX.h"
30 #include "nsMenuUtilsX.h"
31 #include "nsStyleConsts.h"
32 #include "nsNativeThemeColors.h"
33 #include "nsNativeThemeCocoa.h"
34 #include "nsChildView.h"
35 #include "nsCocoaFeatures.h"
36 #include "nsIScreenManager.h"
37 #include "nsIWidgetListener.h"
38 #include "SDKDeclarations.h"
39 #include "VibrancyManager.h"
40 #include "nsPresContext.h"
41 #include "nsDocShell.h"
43 #include "gfxPlatform.h"
46 #include "mozilla/AutoRestore.h"
47 #include "mozilla/BasicEvents.h"
48 #include "mozilla/dom/Document.h"
49 #include "mozilla/Maybe.h"
50 #include "mozilla/NativeKeyBindingsType.h"
51 #include "mozilla/Preferences.h"
52 #include "mozilla/PresShell.h"
53 #include "mozilla/ScopeExit.h"
54 #include "mozilla/StaticPrefs_gfx.h"
55 #include "mozilla/StaticPrefs_widget.h"
56 #include "mozilla/WritingModes.h"
57 #include "mozilla/layers/CompositorBridgeChild.h"
58 #include "mozilla/widget/Screen.h"
65 } // namespace mozilla
66 using namespace mozilla::layers;
67 using namespace mozilla::widget;
68 using namespace mozilla;
70 int32_t gXULModalLevel = 0;
72 // In principle there should be only one app-modal window at any given time.
73 // But sometimes, despite our best efforts, another window appears above the
74 // current app-modal window. So we need to keep a linked list of app-modal
75 // windows. (A non-sheet window that appears above an app-modal window is
76 // also made app-modal.) See nsCocoaWindow::SetModal().
77 nsCocoaWindowList* gGeckoAppModalWindowList = NULL;
79 BOOL sTouchBarIsInitialized = NO;
81 // defined in nsMenuBarX.mm
82 extern NSMenu* sApplicationMenu; // Application menu shared by all menubars
84 // defined in nsChildView.mm
85 extern BOOL gSomeMenuBarPainted;
89 typedef NSInteger CGSConnection;
90 typedef NSUInteger CGSSpaceID;
91 typedef NSInteger CGSWindow;
93 kCGSSpaceIncludesCurrent = 1 << 0,
94 kCGSSpaceIncludesOthers = 1 << 1,
95 kCGSSpaceIncludesUser = 1 << 2,
97 kCGSAllSpacesMask = 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, CGAffineTransform transform);
105 #define NS_APPSHELLSERVICE_CONTRACTID "@mozilla.org/appshell/appShellService;1"
107 NS_IMPL_ISUPPORTS_INHERITED(nsCocoaWindow, Inherited, nsPIWidgetCocoa)
109 // A note on testing to see if your object is a sheet...
110 // |mWindowType == WindowType::Sheet| is true if your gecko nsIWidget is a sheet
111 // widget - whether or not the sheet is showing. |[mWindow isSheet]| will return
112 // true *only when the sheet is actually showing*. Choose your test wisely.
114 static void RollUpPopups(
115 nsIRollupListener::AllowAnimations aAllowAnimations = nsIRollupListener::AllowAnimations::Yes) {
116 nsIRollupListener* rollupListener = nsBaseWidget::GetActiveRollupListener();
117 NS_ENSURE_TRUE_VOID(rollupListener);
119 if (rollupListener->RollupNativeMenu()) {
123 nsCOMPtr<nsIWidget> rollupWidget = rollupListener->GetRollupWidget();
127 nsIRollupListener::RollupOptions options{0, nsIRollupListener::FlushViews::Yes, nullptr,
129 rollupListener->Rollup(options);
132 nsCocoaWindow::nsCocoaWindow()
134 mAncestorLink(nullptr),
137 mSheetWindowParent(nil),
138 mPopupContentView(nil),
139 mFullscreenTransitionAnimation(nil),
140 mShadowStyle(StyleWindowShadow::Default),
141 mBackingScaleFactor(0.0),
142 mAnimationType(nsIWidget::eGenericWindowAnimation),
143 mWindowMadeHere(false),
144 mSheetNeedsShow(false),
145 mSizeMode(nsSizeMode_Normal),
146 mInFullScreenMode(false),
147 mInNativeFullScreenMode(false),
148 mIgnoreOcclusionCount(0),
149 mHasStartedNativeFullscreen(false),
152 mIsAnimationSuppressed(false),
153 mInReportMoveEvent(false),
155 mWindowTransformIsIdentity(true),
157 mAspectRatioLocked(false),
158 mNumModalDescendents(0),
159 mWindowAnimationBehavior(NSWindowAnimationBehaviorDefault),
161 // Disable automatic tabbing. We need to do this before we
162 // orderFront any of our windows.
163 [NSWindow setAllowsAutomaticWindowTabbing:NO];
166 void nsCocoaWindow::DestroyNativeWindow() {
167 NS_OBJC_BEGIN_TRY_IGNORE_BLOCK;
169 if (!mWindow) return;
171 // Define a helper function for checking our fullscreen window status.
172 bool (^inNativeFullscreen)(void) = ^{
173 return ((mWindow.styleMask & NSFullScreenWindowMask) == NSFullScreenWindowMask);
176 // If we are in native fullscreen, or we are in the middle of a native
177 // fullscreen transition, spin our run loop until both those things
178 // are false. This ensures that we've completed all our native
179 // fullscreen transitions and updated our class state before we close
180 // the window. We need to do this here (rather than in some other
181 // nsCocoaWindow trying to do a native fullscreen transition) because
182 // part of closing our window is clearing out our delegate, and the
183 // delegate callback is the only other way to clear our class state.
185 // While spinning this run loop, check to see if we are still in native
186 // fullscreen. If we are, request that we leave fullscreen (only once)
187 // and continue to spin the run loop until we're out of fullscreen.
189 // However, it's possible that we are *already* in a run loop inside of
190 // ProcessTransitions(), waiting on a native fullscreen transition to
191 // complete. In such a case, we can't spin the run loop again, so we
192 // don't even enter this loop if mInProcessTransitions is true.
193 bool haveRequestedFullscreenExit = false;
194 NSRunLoop* localRunLoop = [NSRunLoop currentRunLoop];
195 while (!mInProcessTransitions && (inNativeFullscreen() || WeAreInNativeTransition()) &&
196 [localRunLoop runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]]) {
197 // This loop continues to process events until mWindow is fully out
198 // of native fullscreen.
200 // Check to see if we should one-time request an exit from fullscreen.
201 // We do this if we are in native fullscreen and no window is in a
202 // native fullscreen transition.
203 if (!haveRequestedFullscreenExit && inNativeFullscreen() && CanStartNativeTransition()) {
204 [mWindow toggleFullScreen:nil];
205 haveRequestedFullscreenExit = true;
209 [mWindow releaseJSObjects];
210 // We want to unhook the delegate here because we don't want events
211 // sent to it after this object has been destroyed.
212 [mWindow setDelegate:nil];
215 [mDelegate autorelease];
217 // We've lost access to our delegate. If we are still in a native
218 // fullscreen transition, we have to give up on it now even if it
219 // isn't finished, because the delegate is the only way that the
220 // class state would ever be cleared.
221 EndOurNativeTransition();
223 NS_OBJC_END_TRY_IGNORE_BLOCK;
226 nsCocoaWindow::~nsCocoaWindow() {
227 NS_OBJC_BEGIN_TRY_IGNORE_BLOCK;
229 // Notify the children that we're gone. Popup windows (e.g. tooltips) can
230 // have nsChildView children. 'kid' is an nsChildView object if and only if
231 // its 'type' is 'WindowType::Child'.
232 // childView->ResetParent() can change our list of children while it's
233 // being iterated, so the way we iterate the list must allow for this.
234 for (nsIWidget* kid = mLastChild; kid;) {
235 WindowType kidType = kid->GetWindowType();
236 if (kidType == WindowType::Child) {
237 nsChildView* childView = static_cast<nsChildView*>(kid);
238 kid = kid->GetPrevSibling();
239 childView->ResetParent();
241 nsCocoaWindow* childWindow = static_cast<nsCocoaWindow*>(kid);
242 childWindow->mParent = nullptr;
243 childWindow->mAncestorLink = mAncestorLink;
244 kid = kid->GetPrevSibling();
248 if (mWindow && mWindowMadeHere) {
249 DestroyNativeWindow();
252 NS_IF_RELEASE(mPopupContentView);
254 // Deal with the possiblity that we're being destroyed while running modal.
256 NS_WARNING("Widget destroyed while running modal!");
258 NS_ASSERTION(gXULModalLevel >= 0, "Weirdness setting modality!");
261 NS_OBJC_END_TRY_IGNORE_BLOCK;
264 // Find the screen that overlaps aRect the most,
265 // if none are found default to the mainScreen.
266 static NSScreen* FindTargetScreenForRect(const DesktopIntRect& aRect) {
267 NSScreen* targetScreen = [NSScreen mainScreen];
268 NSEnumerator* screenEnum = [[NSScreen screens] objectEnumerator];
269 int largestIntersectArea = 0;
270 while (NSScreen* screen = [screenEnum nextObject]) {
271 DesktopIntRect screenRect = nsCocoaUtils::CocoaRectToGeckoRect([screen visibleFrame]);
272 screenRect = screenRect.Intersect(aRect);
273 int area = screenRect.width * screenRect.height;
274 if (area > largestIntersectArea) {
275 largestIntersectArea = area;
276 targetScreen = screen;
282 // fits the rect to the screen that contains the largest area of it,
283 // or to aScreen if a screen is passed in
284 // NB: this operates with aRect in desktop pixels
285 static void FitRectToVisibleAreaForScreen(DesktopIntRect& aRect, NSScreen* aScreen) {
287 aScreen = FindTargetScreenForRect(aRect);
290 DesktopIntRect screenBounds = nsCocoaUtils::CocoaRectToGeckoRect([aScreen visibleFrame]);
292 if (aRect.width > screenBounds.width) {
293 aRect.width = screenBounds.width;
295 if (aRect.height > screenBounds.height) {
296 aRect.height = screenBounds.height;
299 if (aRect.x - screenBounds.x + aRect.width > screenBounds.width) {
300 aRect.x += screenBounds.width - (aRect.x - screenBounds.x + aRect.width);
302 if (aRect.y - screenBounds.y + aRect.height > screenBounds.height) {
303 aRect.y += screenBounds.height - (aRect.y - screenBounds.y + aRect.height);
306 // If the left/top edge of the window is off the screen in either direction,
307 // then set the window to start at the left/top edge of the screen.
308 if (aRect.x < screenBounds.x || aRect.x > (screenBounds.x + screenBounds.width)) {
309 aRect.x = screenBounds.x;
311 if (aRect.y < screenBounds.y || aRect.y > (screenBounds.y + screenBounds.height)) {
312 aRect.y = screenBounds.y;
316 DesktopToLayoutDeviceScale ParentBackingScaleFactor(nsIWidget* aParent, NSView* aParentView) {
318 return aParent->GetDesktopToDeviceScale();
320 NSWindow* parentWindow = [aParentView window];
322 return DesktopToLayoutDeviceScale([parentWindow backingScaleFactor]);
324 return DesktopToLayoutDeviceScale(1.0);
327 // Returns the screen rectangle for the given widget.
328 // Child widgets are positioned relative to this rectangle.
329 // Exactly one of the arguments must be non-null.
330 static DesktopRect GetWidgetScreenRectForChildren(nsIWidget* aWidget, NSView* aView) {
332 mozilla::DesktopToLayoutDeviceScale scale = aWidget->GetDesktopToDeviceScale();
333 if (aWidget->GetWindowType() == WindowType::Child) {
334 return aWidget->GetScreenBounds() / scale;
336 return aWidget->GetClientBounds() / scale;
339 MOZ_RELEASE_ASSERT(aView);
341 // 1. Transform the view rect into window coords.
342 // The returned rect is in "origin bottom-left" coordinates.
343 NSRect rectInWindowCoordinatesOBL = [aView convertRect:[aView bounds] toView:nil];
345 // 2. Turn the window-coord rect into screen coords, still origin bottom-left.
346 NSRect rectInScreenCoordinatesOBL =
347 [[aView window] convertRectToScreen:rectInWindowCoordinatesOBL];
349 // 3. Convert the NSRect to a DesktopRect. This will convert to coordinates
350 // with the origin in the top left corner of the primary screen.
351 return DesktopRect(nsCocoaUtils::CocoaRectToGeckoRect(rectInScreenCoordinatesOBL));
354 // aRect here is specified in desktop pixels
356 // For child windows (where either aParent or aNativeParent is non-null),
357 // aRect.{x,y} are offsets from the origin of the parent window and not an
358 // absolute position.
359 nsresult nsCocoaWindow::Create(nsIWidget* aParent, nsNativeWidget aNativeParent,
360 const DesktopIntRect& aRect, widget::InitData* aInitData) {
361 NS_OBJC_BEGIN_TRY_BLOCK_RETURN;
363 // Because the hidden window is created outside of an event loop,
364 // we have to provide an autorelease pool (see bug 559075).
365 nsAutoreleasePool localPool;
367 DesktopIntRect newBounds = aRect;
368 FitRectToVisibleAreaForScreen(newBounds, nullptr);
370 // Set defaults which can be overriden from aInitData in BaseCreate
371 mWindowType = WindowType::TopLevel;
372 mBorderStyle = BorderStyle::Default;
374 // Ensure that the toolkit is created.
375 nsToolkit::GetToolkit();
377 Inherited::BaseCreate(aParent, aInitData);
380 mAncestorLink = aParent;
381 mAlwaysOnTop = aInitData->mAlwaysOnTop;
383 // If we have a parent widget, the new widget will be offset from the
384 // parent widget by aRect.{x,y}. Otherwise, we'll use aRect for the
385 // new widget coordinates.
386 DesktopIntPoint parentOrigin;
388 // Do we have a parent widget?
389 if (aParent || aNativeParent) {
390 DesktopRect parentDesktopRect = GetWidgetScreenRectForChildren(aParent, (NSView*)aNativeParent);
391 parentOrigin = gfx::RoundedToInt(parentDesktopRect.TopLeft());
394 DesktopIntRect widgetRect = aRect + parentOrigin;
396 nsresult rv = CreateNativeWindow(nsCocoaUtils::GeckoRectToCocoaRect(widgetRect), mBorderStyle,
397 false, aInitData->mIsPrivate);
398 NS_ENSURE_SUCCESS(rv, rv);
400 if (mWindowType == WindowType::Popup) {
401 // now we can convert widgetRect to device pixels for the window we created,
402 // as the child view expects a rect expressed in the dev pix of its parent
403 LayoutDeviceIntRect devRect = RoundedToInt(newBounds * GetDesktopToDeviceScale());
404 return CreatePopupContentView(devRect, aInitData);
407 mIsAnimationSuppressed = aInitData->mIsAnimationSuppressed;
411 NS_OBJC_END_TRY_BLOCK_RETURN(NS_ERROR_FAILURE);
414 nsresult nsCocoaWindow::Create(nsIWidget* aParent, nsNativeWidget aNativeParent,
415 const LayoutDeviceIntRect& aRect, widget::InitData* aInitData) {
416 DesktopIntRect desktopRect =
417 RoundedToInt(aRect / ParentBackingScaleFactor(aParent, (NSView*)aNativeParent));
418 return Create(aParent, aNativeParent, desktopRect, aInitData);
421 static unsigned int WindowMaskForBorderStyle(BorderStyle aBorderStyle) {
422 bool allOrDefault = (aBorderStyle == BorderStyle::All || aBorderStyle == BorderStyle::Default);
424 /* Apple's docs on NSWindow styles say that "a window's style mask should
425 * include NSWindowStyleMaskTitled if it includes any of the others [besides
426 * NSWindowStyleMaskBorderless]". This implies that a borderless window
427 * shouldn't have any other styles than NSWindowStyleMaskBorderless.
429 if (!allOrDefault && !(aBorderStyle & BorderStyle::Title)) {
430 if (aBorderStyle & BorderStyle::Minimize) {
431 /* It appears that at a minimum, borderless windows can be miniaturizable,
432 * effectively contradicting some of Apple's documentation referenced
433 * above. One such exception is the screen share indicator, see
436 return NSWindowStyleMaskBorderless | NSWindowStyleMaskMiniaturizable;
438 return NSWindowStyleMaskBorderless;
441 unsigned int mask = NSWindowStyleMaskTitled;
442 if (allOrDefault || aBorderStyle & BorderStyle::Close) {
443 mask |= NSWindowStyleMaskClosable;
445 if (allOrDefault || aBorderStyle & BorderStyle::Minimize) {
446 mask |= NSWindowStyleMaskMiniaturizable;
448 if (allOrDefault || aBorderStyle & BorderStyle::ResizeH) {
449 mask |= NSWindowStyleMaskResizable;
455 // If aRectIsFrameRect, aRect specifies the frame rect of the new window.
456 // Otherwise, aRect.x/y specify the position of the window's frame relative to
457 // the bottom of the menubar and aRect.width/height specify the size of the
459 nsresult nsCocoaWindow::CreateNativeWindow(const NSRect& aRect, BorderStyle aBorderStyle,
460 bool aRectIsFrameRect, bool aIsPrivateBrowsing) {
461 NS_OBJC_BEGIN_TRY_BLOCK_RETURN;
463 // We default to NSWindowStyleMaskBorderless, add features if needed.
464 unsigned int features = NSWindowStyleMaskBorderless;
466 // Configure the window we will create based on the window type.
467 switch (mWindowType) {
468 case WindowType::Invisible:
469 case WindowType::Child:
471 case WindowType::Popup:
472 if (aBorderStyle != BorderStyle::Default && mBorderStyle & BorderStyle::Title) {
473 features |= NSWindowStyleMaskTitled;
474 if (aBorderStyle & BorderStyle::Close) {
475 features |= NSWindowStyleMaskClosable;
479 case WindowType::TopLevel:
480 case WindowType::Dialog:
481 features = WindowMaskForBorderStyle(aBorderStyle);
483 case WindowType::Sheet:
484 if (mParent->GetWindowType() != WindowType::Invisible &&
485 aBorderStyle & BorderStyle::ResizeH) {
486 features = NSWindowStyleMaskResizable;
488 features = NSWindowStyleMaskMiniaturizable;
490 features |= NSWindowStyleMaskTitled;
493 NS_ERROR("Unhandled window type!");
494 return NS_ERROR_FAILURE;
499 if (aRectIsFrameRect) {
500 contentRect = [NSWindow contentRectForFrameRect:aRect styleMask:features];
503 * We pass a content area rect to initialize the native Cocoa window. The
504 * content rect we give is the same size as the size we're given by gecko.
505 * The origin we're given for non-popup windows is moved down by the height
506 * of the menu bar so that an origin of (0,100) from gecko puts the window
507 * 100 pixels below the top of the available desktop area. We also move the
508 * origin down by the height of a title bar if it exists. This is so the
509 * origin that gecko gives us for the top-left of the window turns out to
510 * be the top-left of the window we create. This is how it was done in
511 * Carbon. If it ought to be different we'll probably need to look at all
514 * Note: This means that if you put a secondary screen on top of your main
515 * screen and open a window in the top screen, it'll be incorrectly shifted
516 * down by the height of the menu bar. Same thing would happen in Carbon.
518 * Note: If you pass a rect with 0,0 for an origin, the window ends up in a
519 * weird place for some reason. This stops that without breaking popups.
521 // Compensate for difference between frame and content area height (e.g. title bar).
522 NSRect newWindowFrame = [NSWindow frameRectForContentRect:aRect styleMask:features];
525 contentRect.origin.y -= (newWindowFrame.size.height - aRect.size.height);
527 if (mWindowType != WindowType::Popup) contentRect.origin.y -= [[NSApp mainMenu] menuBarHeight];
530 // NSLog(@"Top-level window being created at Cocoa rect: %f, %f, %f, %f\n",
531 // rect.origin.x, rect.origin.y, rect.size.width, rect.size.height);
533 Class windowClass = [BaseWindow class];
534 // If we have a titlebar on a top-level window, we want to be able to control the
535 // titlebar color (for unified windows), so use the special ToolbarWindow class.
536 // Note that we need to check the window type because we mark sheets as
538 if ((mWindowType == WindowType::TopLevel || mWindowType == WindowType::Dialog) &&
539 (features & NSWindowStyleMaskTitled))
540 windowClass = [ToolbarWindow class];
541 // If we're a popup window we need to use the PopupWindow class.
542 else if (mWindowType == WindowType::Popup)
543 windowClass = [PopupWindow class];
544 // If we're a non-popup borderless window we need to use the
545 // BorderlessWindow class.
546 else if (features == NSWindowStyleMaskBorderless)
547 windowClass = [BorderlessWindow class];
550 mWindow = [[windowClass alloc] initWithContentRect:contentRect
552 backing:NSBackingStoreBuffered
555 // Make sure that window titles don't leak to disk in private browsing mode
556 // due to macOS' resume feature.
557 [mWindow setRestorable:!aIsPrivateBrowsing];
558 if (aIsPrivateBrowsing) {
559 [mWindow disableSnapshotRestoration];
562 // setup our notification delegate. Note that setDelegate: does NOT retain.
563 mDelegate = [[WindowDelegate alloc] initWithGeckoWindow:this];
564 [mWindow setDelegate:mDelegate];
566 // Make sure that the content rect we gave has been honored.
567 NSRect wantedFrame = [mWindow frameRectForChildViewRect:contentRect];
568 if (!NSEqualRects([mWindow frame], wantedFrame)) {
569 // This can happen when the window is not on the primary screen.
570 [mWindow setFrame:wantedFrame display:NO];
574 if (mWindowType == WindowType::Invisible) {
575 [mWindow setLevel:kCGDesktopWindowLevelKey];
578 if (mWindowType == WindowType::Popup) {
579 SetPopupWindowLevel();
580 [mWindow setBackgroundColor:[NSColor clearColor]];
581 [mWindow setOpaque:NO];
583 // When multiple spaces are in use and the browser is assigned to a
584 // particular space, override the "Assign To" space and display popups on
585 // the active space. Does not work with multiple displays. See
586 // NeedsRecreateToReshow() for multi-display with multi-space workaround.
588 NSWindowCollectionBehavior behavior = [mWindow collectionBehavior];
589 behavior |= NSWindowCollectionBehaviorMoveToActiveSpace;
590 [mWindow setCollectionBehavior:behavior];
593 // Non-popup windows are always opaque.
594 [mWindow setOpaque:YES];
597 NSWindowCollectionBehavior newBehavior = [mWindow collectionBehavior];
599 [mWindow setLevel:NSFloatingWindowLevel];
600 newBehavior |= NSWindowCollectionBehaviorCanJoinAllSpaces;
602 [mWindow setCollectionBehavior:newBehavior];
604 [mWindow setContentMinSize:NSMakeSize(60, 60)];
605 [mWindow disableCursorRects];
607 // Make the window use CoreAnimation from the start, so that we don't
608 // switch from a non-CA window to a CA-window in the middle.
609 [[mWindow contentView] setWantsLayer:YES];
611 // Make sure the window starts out not draggable by the background.
612 // We will turn it on as necessary.
613 [mWindow setMovableByWindowBackground:NO];
615 [[WindowDataMap sharedWindowDataMap] ensureDataForWindow:mWindow];
616 mWindowMadeHere = true;
618 if (@available(macOS 10.14, *)) {
619 // Make the window respect the global appearance, which follows the browser.theme.toolbar-theme
621 mWindow.appearanceSource = MOZGlobalAppearance.sharedInstance;
626 NS_OBJC_END_TRY_BLOCK_RETURN(NS_ERROR_FAILURE);
629 nsresult nsCocoaWindow::CreatePopupContentView(const LayoutDeviceIntRect& aRect,
630 widget::InitData* aInitData) {
631 NS_OBJC_BEGIN_TRY_BLOCK_RETURN;
633 // We need to make our content view a ChildView.
634 mPopupContentView = new nsChildView();
635 if (!mPopupContentView) return NS_ERROR_FAILURE;
637 NS_ADDREF(mPopupContentView);
639 nsIWidget* thisAsWidget = static_cast<nsIWidget*>(this);
640 nsresult rv = mPopupContentView->Create(thisAsWidget, nullptr, aRect, aInitData);
641 if (NS_WARN_IF(NS_FAILED(rv))) {
645 NSView* contentView = [mWindow contentView];
646 ChildView* childView = (ChildView*)mPopupContentView->GetNativeData(NS_NATIVE_WIDGET);
647 [childView setFrame:[contentView bounds]];
648 [childView setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable];
649 [contentView addSubview:childView];
653 NS_OBJC_END_TRY_BLOCK_RETURN(NS_ERROR_FAILURE);
656 void nsCocoaWindow::Destroy() {
657 if (mOnDestroyCalled) return;
658 mOnDestroyCalled = true;
660 // SetFakeModal(true) is called for non-modal window opened by modal window.
661 // On Cocoa, it needs corresponding SetFakeModal(false) on destroy to restore
662 // ancestor windows' state.
667 // If we don't hide here we run into problems with panels, this is not ideal.
671 if (mPopupContentView) mPopupContentView->Destroy();
673 if (mFullscreenTransitionAnimation) {
674 [mFullscreenTransitionAnimation stopAnimation];
675 ReleaseFullscreenTransitionAnimation();
678 nsBaseWidget::Destroy();
679 // nsBaseWidget::Destroy() calls GetParent()->RemoveChild(this). But we
680 // don't implement GetParent(), so we need to do the equivalent here.
682 mParent->RemoveChild(this);
684 nsBaseWidget::OnDestroy();
686 if (mInFullScreenMode) {
687 // On Lion we don't have to mess with the OS chrome when in Full Screen
688 // mode. But we do have to destroy the native window here (and not wait
689 // for that to happen in our destructor). We don't switch away from the
690 // native window's space until the window is destroyed, and otherwise this
691 // might not happen for several seconds (because at least one object
692 // holding a reference to ourselves is usually waiting to be garbage-
693 // collected). See bug 757618.
694 if (mInNativeFullScreenMode) {
695 DestroyNativeWindow();
696 } else if (mWindow) {
697 nsCocoaUtils::HideOSChromeOnScreen(false);
702 nsIWidget* nsCocoaWindow::GetSheetWindowParent(void) {
703 if (mWindowType != WindowType::Sheet) return nullptr;
704 nsCocoaWindow* parent = static_cast<nsCocoaWindow*>(mParent);
705 while (parent && (parent->mWindowType == WindowType::Sheet))
706 parent = static_cast<nsCocoaWindow*>(parent->mParent);
710 void* nsCocoaWindow::GetNativeData(uint32_t aDataType) {
711 NS_OBJC_BEGIN_TRY_BLOCK_RETURN;
713 void* retVal = nullptr;
716 // to emulate how windows works, we always have to return a NSView
717 // for NS_NATIVE_WIDGET
718 case NS_NATIVE_WIDGET:
719 retVal = [mWindow contentView];
722 case NS_NATIVE_WINDOW:
726 case NS_NATIVE_GRAPHIC:
727 // There isn't anything that makes sense to return here,
728 // and it doesn't matter so just return nullptr.
729 NS_ERROR("Requesting NS_NATIVE_GRAPHIC on a top-level window!");
731 case NS_RAW_NATIVE_IME_CONTEXT: {
732 retVal = GetPseudoIMEContext();
736 NSView* view = mWindow ? [mWindow contentView] : nil;
738 retVal = [view inputContext];
740 // If inputContext isn't available on this window, return this window's
741 // pointer instead of nullptr since if this returns nullptr,
742 // IMEStateManager cannot manage composition with TextComposition
743 // instance. Although, this case shouldn't occur.
744 if (NS_WARN_IF(!retVal)) {
753 NS_OBJC_END_TRY_BLOCK_RETURN(nullptr);
756 bool nsCocoaWindow::IsVisible() const {
757 NS_OBJC_BEGIN_TRY_BLOCK_RETURN;
759 return (mWindow && ([mWindow isVisibleOrBeingShown] || mSheetNeedsShow));
761 NS_OBJC_END_TRY_BLOCK_RETURN(false);
764 void nsCocoaWindow::SetModal(bool aState) {
765 NS_OBJC_BEGIN_TRY_IGNORE_BLOCK;
767 if (!mWindow) return;
769 // This is used during startup (outside the event loop) when creating
770 // the add-ons compatibility checking dialog and the profile manager UI;
771 // therefore, it needs to provide an autorelease pool to avoid cocoa
773 nsAutoreleasePool localPool;
776 nsCocoaWindow* ancestor = static_cast<nsCocoaWindow*>(mAncestorLink);
779 // When a non-sheet window gets "set modal", make the window(s) that it
780 // appears over behave as they should. We can't rely on native methods to
781 // do this, for the following reason: The OS runs modal non-sheet windows
782 // in an event loop (using [NSApplication runModalForWindow:] or similar
783 // methods) that's incompatible with the modal event loop in AppWindow::
784 // ShowModal() (each of these event loops is "exclusive", and can't run at
785 // the same time as other (similar) event loops).
786 if (mWindowType != WindowType::Sheet) {
788 if (ancestor->mNumModalDescendents++ == 0) {
789 NSWindow* aWindow = ancestor->GetCocoaWindow();
790 if (ancestor->mWindowType != WindowType::Invisible) {
791 [[aWindow standardWindowButton:NSWindowCloseButton] setEnabled:NO];
792 [[aWindow standardWindowButton:NSWindowMiniaturizeButton] setEnabled:NO];
793 [[aWindow standardWindowButton:NSWindowZoomButton] setEnabled:NO];
796 ancestor = static_cast<nsCocoaWindow*>(ancestor->mParent);
798 [mWindow setLevel:NSModalPanelWindowLevel];
799 nsCocoaWindowList* windowList = new nsCocoaWindowList;
801 windowList->window = this; // Don't ADDREF
802 windowList->prev = gGeckoAppModalWindowList;
803 gGeckoAppModalWindowList = windowList;
808 NS_ASSERTION(gXULModalLevel >= 0, "Mismatched call to nsCocoaWindow::SetModal(false)!");
809 if (mWindowType != WindowType::Sheet) {
811 if (--ancestor->mNumModalDescendents == 0) {
812 NSWindow* aWindow = ancestor->GetCocoaWindow();
813 if (ancestor->mWindowType != WindowType::Invisible) {
814 [[aWindow standardWindowButton:NSWindowCloseButton] setEnabled:YES];
815 [[aWindow standardWindowButton:NSWindowMiniaturizeButton] setEnabled:YES];
816 [[aWindow standardWindowButton:NSWindowZoomButton] setEnabled:YES];
819 NS_ASSERTION(ancestor->mNumModalDescendents >= 0, "Widget hierarchy changed while modal!");
820 ancestor = static_cast<nsCocoaWindow*>(ancestor->mParent);
822 if (gGeckoAppModalWindowList) {
823 NS_ASSERTION(gGeckoAppModalWindowList->window == this,
824 "Widget hierarchy changed while modal!");
825 nsCocoaWindowList* saved = gGeckoAppModalWindowList;
826 gGeckoAppModalWindowList = gGeckoAppModalWindowList->prev;
827 delete saved; // "window" not ADDREFed
829 if (mWindowType == WindowType::Popup)
830 SetPopupWindowLevel();
832 [mWindow setLevel:NSNormalWindowLevel];
836 NS_OBJC_END_TRY_IGNORE_BLOCK;
839 void nsCocoaWindow::SetFakeModal(bool aState) {
844 bool nsCocoaWindow::IsRunningAppModal() { return [NSApp _isRunningAppModal]; }
846 // Hide or show this window
847 void nsCocoaWindow::Show(bool bState) {
848 NS_OBJC_BEGIN_TRY_IGNORE_BLOCK;
850 if (!mWindow) return;
852 if (!mSheetNeedsShow) {
853 // Early exit if our current visibility state is already the requested state.
854 if (bState == ([mWindow isVisible] || [mWindow isBeingShown])) {
859 [mWindow setBeingShown:bState];
860 if (bState && !mWasShown) {
864 nsIWidget* parentWidget = mParent;
865 nsCOMPtr<nsPIWidgetCocoa> piParentWidget(do_QueryInterface(parentWidget));
866 NSWindow* nativeParentWindow =
867 (parentWidget) ? (NSWindow*)parentWidget->GetNativeData(NS_NATIVE_WINDOW) : nil;
869 if (bState && !mBounds.IsEmpty()) {
870 // If we had set the activationPolicy to accessory, then right now we won't
871 // have a dock icon. Make sure that we undo that and show a dock icon now that
872 // we're going to show a window.
873 if ([NSApp activationPolicy] != NSApplicationActivationPolicyRegular) {
874 [NSApp setActivationPolicy:NSApplicationActivationPolicyRegular];
875 PR_SetEnv("MOZ_APP_NO_DOCK=");
878 // Don't try to show a popup when the parent isn't visible or is minimized.
879 if (mWindowType == WindowType::Popup && nativeParentWindow) {
880 if (![nativeParentWindow isVisible] || [nativeParentWindow isMiniaturized]) {
885 if (mPopupContentView) {
886 // Ensure our content view is visible. We never need to hide it.
887 mPopupContentView->Show(true);
890 if (mWindowType == WindowType::Sheet) {
891 // bail if no parent window (its basically what we do in Carbon)
892 if (!nativeParentWindow || !piParentWidget) return;
894 NSWindow* topNonSheetWindow = nativeParentWindow;
896 // If this sheet is the child of another sheet, hide the parent so that
897 // this sheet can be displayed. Leave the parent mSheetNeedsShow alone,
898 // that is only used to handle sibling sheet contention. The parent will
899 // return once there are no more child sheets.
900 bool parentIsSheet = false;
901 if (NS_SUCCEEDED(piParentWidget->GetIsSheet(&parentIsSheet)) && parentIsSheet) {
902 piParentWidget->GetSheetWindowParent(&topNonSheetWindow);
903 #ifdef MOZ_THUNDERBIRD
904 [NSApp endSheet:nativeParentWindow];
906 [nativeParentWindow.sheetParent endSheet:nativeParentWindow];
910 nsCOMPtr<nsIWidget> sheetShown;
911 if (NS_SUCCEEDED(piParentWidget->GetChildSheet(true, getter_AddRefs(sheetShown))) &&
912 (!sheetShown || sheetShown == this)) {
913 // If this sheet is already the sheet actually being shown, don't
914 // tell it to show again. Otherwise the number of calls to
915 #ifdef MOZ_THUNDERBIRD
916 // [NSApp beginSheet...] won't match up with [NSApp endSheet...].
918 // [NSWindow beginSheet...] won't match up with [NSWindow endSheet...].
920 if (![mWindow isVisible]) {
921 mSheetNeedsShow = false;
922 mSheetWindowParent = topNonSheetWindow;
923 #ifdef MOZ_THUNDERBIRD
924 // Only set contextInfo if our parent isn't a sheet.
925 NSWindow* contextInfo = parentIsSheet ? nil : mSheetWindowParent;
926 [TopLevelWindowData deactivateInWindow:mSheetWindowParent];
927 [NSApp beginSheet:mWindow
928 modalForWindow:mSheetWindowParent
929 modalDelegate:mDelegate
930 didEndSelector:@selector(didEndSheet:returnCode:contextInfo:)
931 contextInfo:contextInfo];
933 NSWindow* sheet = mWindow;
934 NSWindow* nonSheetParent = parentIsSheet ? nil : mSheetWindowParent;
935 [TopLevelWindowData deactivateInWindow:mSheetWindowParent];
936 [mSheetWindowParent beginSheet:sheet
937 completionHandler:^(NSModalResponse returnCode) {
938 // Note: 'nonSheetParent' (if it is set) is the window that is the parent
939 // of the sheet. If it's set, 'nonSheetParent' is always the top- level
940 // window, not another sheet itself. But 'nonSheetParent' is nil if our
941 // parent window is also a sheet -- in that case we shouldn't send the
942 // top-level window any activate events (because it's our parent window
943 // that needs to get these events, not the top-level window).
944 [TopLevelWindowData deactivateInWindow:sheet];
945 [sheet orderOut:nil];
946 if (nonSheetParent) {
947 [TopLevelWindowData activateInWindow:nonSheetParent];
951 [TopLevelWindowData activateInWindow:mWindow];
952 SendSetZLevelEvent();
955 // A sibling of this sheet is active, don't show this sheet yet.
956 // When the active sheet hides, its brothers and sisters that have
957 // mSheetNeedsShow set will have their opportunities to display.
958 mSheetNeedsShow = true;
960 } else if (mWindowType == WindowType::Popup) {
961 // For reasons that aren't yet clear, calls to [NSWindow orderFront:] or
962 // [NSWindow makeKeyAndOrderFront:] can sometimes trigger "Error (1000)
963 // creating CGSWindow", which in turn triggers an internal inconsistency
964 // NSException. These errors shouldn't be fatal. So we need to wrap
965 // calls to ...orderFront: in TRY blocks. See bmo bug 470864.
966 NS_OBJC_BEGIN_TRY_IGNORE_BLOCK;
967 [[mWindow contentView] setNeedsDisplay:YES];
968 [mWindow orderFront:nil];
969 NS_OBJC_END_TRY_IGNORE_BLOCK;
970 SendSetZLevelEvent();
971 // If our popup window is a non-native context menu, tell the OS (and
972 // other programs) that a menu has opened. This is how the OS knows to
973 // close other programs' context menus when ours open.
974 if ([mWindow isKindOfClass:[PopupWindow class]] && [(PopupWindow*)mWindow isContextMenu]) {
975 [[NSDistributedNotificationCenter defaultCenter]
976 postNotificationName:@"com.apple.HIToolbox.beginMenuTrackingNotification"
977 object:@"org.mozilla.gecko.PopupWindow"];
980 // If a parent window was supplied and this is a popup at the parent
981 // level, set its child window. This will cause the child window to
982 // appear above the parent and move when the parent does. Setting this
983 // needs to happen after the _setWindowNumber calls above, otherwise the
984 // window doesn't focus properly.
985 if (nativeParentWindow && mPopupLevel == PopupLevel::Parent)
986 [nativeParentWindow addChildWindow:mWindow ordered:NSWindowAbove];
988 NS_OBJC_BEGIN_TRY_IGNORE_BLOCK;
989 if (mWindowType == WindowType::TopLevel &&
990 [mWindow respondsToSelector:@selector(setAnimationBehavior:)]) {
991 NSWindowAnimationBehavior behavior;
992 if (mIsAnimationSuppressed) {
993 behavior = NSWindowAnimationBehaviorNone;
995 switch (mAnimationType) {
996 case nsIWidget::eDocumentWindowAnimation:
997 behavior = NSWindowAnimationBehaviorDocumentWindow;
1000 MOZ_FALLTHROUGH_ASSERT("unexpected mAnimationType value");
1001 case nsIWidget::eGenericWindowAnimation:
1002 behavior = NSWindowAnimationBehaviorDefault;
1006 [mWindow setAnimationBehavior:behavior];
1007 mWindowAnimationBehavior = behavior;
1010 // We don't want alwaysontop windows to pull focus when they're opened,
1011 // as these tend to be for peripheral indicators and displays.
1013 [mWindow orderFront:nil];
1015 [mWindow makeKeyAndOrderFront:nil];
1017 NS_OBJC_END_TRY_IGNORE_BLOCK;
1018 SendSetZLevelEvent();
1021 // roll up any popups if a top-level window is going away
1022 if (mWindowType == WindowType::TopLevel || mWindowType == WindowType::Dialog) {
1026 // now get rid of the window/sheet
1027 if (mWindowType == WindowType::Sheet) {
1028 if (mSheetNeedsShow) {
1029 // This is an attempt to hide a sheet that never had a chance to
1030 // be shown. There's nothing to do other than make sure that it
1032 mSheetNeedsShow = false;
1034 // get sheet's parent *before* hiding the sheet (which breaks the linkage)
1035 NSWindow* sheetParent = mSheetWindowParent;
1038 #ifdef MOZ_THUNDERBIRD
1039 [NSApp endSheet:mWindow];
1041 [mSheetWindowParent endSheet:mWindow];
1043 [TopLevelWindowData deactivateInWindow:mWindow];
1045 nsCOMPtr<nsIWidget> siblingSheetToShow;
1046 bool parentIsSheet = false;
1048 if (nativeParentWindow && piParentWidget &&
1050 piParentWidget->GetChildSheet(false, getter_AddRefs(siblingSheetToShow))) &&
1051 siblingSheetToShow) {
1052 // First, give sibling sheets an opportunity to show.
1053 siblingSheetToShow->Show(true);
1054 } else if (nativeParentWindow && piParentWidget &&
1055 NS_SUCCEEDED(piParentWidget->GetIsSheet(&parentIsSheet)) && parentIsSheet) {
1056 #ifdef MOZ_THUNDERBIRD
1057 // Only set contextInfo if the parent of the parent sheet we're about
1058 // to restore isn't itself a sheet.
1059 NSWindow* contextInfo = sheetParent;
1061 // Only set nonSheetGrandparent if the parent of the parent sheet we're about
1062 // to restore isn't itself a sheet.
1063 NSWindow* nonSheetGrandparent = sheetParent;
1065 nsIWidget* grandparentWidget = nil;
1066 if (NS_SUCCEEDED(piParentWidget->GetRealParent(&grandparentWidget)) &&
1067 grandparentWidget) {
1068 nsCOMPtr<nsPIWidgetCocoa> piGrandparentWidget(do_QueryInterface(grandparentWidget));
1069 bool grandparentIsSheet = false;
1070 if (piGrandparentWidget &&
1071 NS_SUCCEEDED(piGrandparentWidget->GetIsSheet(&grandparentIsSheet)) &&
1072 grandparentIsSheet) {
1073 #ifdef MOZ_THUNDERBIRD
1076 nonSheetGrandparent = nil;
1080 // If there are no sibling sheets, but the parent is a sheet, restore
1081 // it. It wasn't sent any deactivate events when it was hidden, so
1082 // don't call through Show, just let the OS put it back up.
1083 #ifdef MOZ_THUNDERBIRD
1084 [NSApp beginSheet:nativeParentWindow
1085 modalForWindow:sheetParent
1086 modalDelegate:[nativeParentWindow delegate]
1087 didEndSelector:@selector(didEndSheet:returnCode:contextInfo:)
1088 contextInfo:contextInfo];
1090 [nativeParentWindow beginSheet:sheetParent
1091 completionHandler:^(NSModalResponse returnCode) {
1092 // Note: 'nonSheetGrandparent' (if it is set) is the window that is the
1093 // parent of sheetParent. If it's set, 'nonSheetGrandparent' is always the
1094 // top-level window, not another sheet itself. But 'nonSheetGrandparent'
1095 // is nil if our parent window is also a sheet -- in that case we shouldn't
1096 // send the top-level window any activate events (because it's our parent
1097 // window that needs to get these events, not the top-level window).
1098 [TopLevelWindowData deactivateInWindow:sheetParent];
1099 [sheetParent orderOut:nil];
1100 if (nonSheetGrandparent) {
1101 [TopLevelWindowData activateInWindow:nonSheetGrandparent];
1106 // Sheet, that was hard. No more siblings or parents, going back
1107 // to a real window.
1108 NS_OBJC_BEGIN_TRY_IGNORE_BLOCK;
1109 [sheetParent makeKeyAndOrderFront:nil];
1110 NS_OBJC_END_TRY_IGNORE_BLOCK;
1112 SendSetZLevelEvent();
1115 // If the window is a popup window with a parent window we need to
1116 // unhook it here before ordering it out. When you order out the child
1117 // of a window it hides the parent window.
1118 if (mWindowType == WindowType::Popup && nativeParentWindow)
1119 [nativeParentWindow removeChildWindow:mWindow];
1121 [mWindow orderOut:nil];
1123 // If our popup window is a non-native context menu, tell the OS (and
1124 // other programs) that a menu has closed.
1125 if ([mWindow isKindOfClass:[PopupWindow class]] && [(PopupWindow*)mWindow isContextMenu]) {
1126 [[NSDistributedNotificationCenter defaultCenter]
1127 postNotificationName:@"com.apple.HIToolbox.endMenuTrackingNotification"
1128 object:@"org.mozilla.gecko.PopupWindow"];
1133 [mWindow setBeingShown:NO];
1135 NS_OBJC_END_TRY_IGNORE_BLOCK;
1138 // Work around a problem where with multiple displays and multiple spaces
1139 // enabled, where the browser is assigned to a single display or space, popup
1140 // windows that are reshown after being hidden with [NSWindow orderOut] show on
1141 // the assigned space even when opened from another display. Apply the
1142 // workaround whenever more than one display is enabled.
1143 bool nsCocoaWindow::NeedsRecreateToReshow() {
1144 // Limit the workaround to popup windows because only they need to override
1145 // the "Assign To" setting. i.e., to display where the parent window is.
1146 return (mWindowType == WindowType::Popup) && mWasShown && ([[NSScreen screens] count] > 1);
1149 WindowRenderer* nsCocoaWindow::GetWindowRenderer() {
1150 if (mPopupContentView) {
1151 return mPopupContentView->GetWindowRenderer();
1156 TransparencyMode nsCocoaWindow::GetTransparencyMode() {
1157 NS_OBJC_BEGIN_TRY_BLOCK_RETURN;
1159 return (!mWindow || [mWindow isOpaque]) ? TransparencyMode::Opaque
1160 : TransparencyMode::Transparent;
1162 NS_OBJC_END_TRY_BLOCK_RETURN(TransparencyMode::Opaque);
1165 // This is called from nsMenuPopupFrame when making a popup transparent.
1166 void nsCocoaWindow::SetTransparencyMode(TransparencyMode aMode) {
1167 NS_OBJC_BEGIN_TRY_IGNORE_BLOCK;
1169 // Only respect calls for popup windows.
1170 if (!mWindow || mWindowType != WindowType::Popup) {
1174 BOOL isTransparent = aMode == TransparencyMode::Transparent;
1175 BOOL currentTransparency = ![mWindow isOpaque];
1176 if (isTransparent != currentTransparency) {
1177 [mWindow setOpaque:!isTransparent];
1178 [mWindow setBackgroundColor:(isTransparent ? [NSColor clearColor] : [NSColor whiteColor])];
1181 NS_OBJC_END_TRY_IGNORE_BLOCK;
1184 void nsCocoaWindow::Enable(bool aState) {}
1186 bool nsCocoaWindow::IsEnabled() const { return true; }
1188 void nsCocoaWindow::ConstrainPosition(DesktopIntPoint& aPoint) {
1189 NS_OBJC_BEGIN_TRY_IGNORE_BLOCK;
1191 if (!mWindow || ![mWindow screen]) {
1195 nsIntRect screenBounds;
1197 int32_t width, height;
1199 NSRect frame = [mWindow frame];
1201 // zero size rects confuse the screen manager
1202 width = std::max<int32_t>(frame.size.width, 1);
1203 height = std::max<int32_t>(frame.size.height, 1);
1205 nsCOMPtr<nsIScreenManager> screenMgr = do_GetService("@mozilla.org/gfx/screenmanager;1");
1207 nsCOMPtr<nsIScreen> screen;
1208 screenMgr->ScreenForRect(aPoint.x, aPoint.y, width, height, getter_AddRefs(screen));
1211 screen->GetRectDisplayPix(&(screenBounds.x), &(screenBounds.y), &(screenBounds.width),
1212 &(screenBounds.height));
1216 if (aPoint.x < screenBounds.x) {
1217 aPoint.x = screenBounds.x;
1218 } else if (aPoint.x >= screenBounds.x + screenBounds.width - width) {
1219 aPoint.x = screenBounds.x + screenBounds.width - width;
1222 if (aPoint.y < screenBounds.y) {
1223 aPoint.y = screenBounds.y;
1224 } else if (aPoint.y >= screenBounds.y + screenBounds.height - height) {
1225 aPoint.y = screenBounds.y + screenBounds.height - height;
1228 NS_OBJC_END_TRY_IGNORE_BLOCK;
1231 void nsCocoaWindow::SetSizeConstraints(const SizeConstraints& aConstraints) {
1232 NS_OBJC_BEGIN_TRY_IGNORE_BLOCK;
1234 // Popups can be smaller than (32, 32)
1235 NSRect rect = (mWindowType == WindowType::Popup) ? NSZeroRect : NSMakeRect(0.0, 0.0, 32, 32);
1236 rect = [mWindow frameRectForChildViewRect:rect];
1238 SizeConstraints c = aConstraints;
1240 if (c.mScale.scale == MOZ_WIDGET_INVALID_SCALE) {
1241 c.mScale.scale = BackingScaleFactor();
1244 c.mMinSize.width = std::max(nsCocoaUtils::CocoaPointsToDevPixels(rect.size.width, c.mScale.scale),
1246 c.mMinSize.height = std::max(
1247 nsCocoaUtils::CocoaPointsToDevPixels(rect.size.height, c.mScale.scale), c.mMinSize.height);
1249 NSSize minSize = {nsCocoaUtils::DevPixelsToCocoaPoints(c.mMinSize.width, c.mScale.scale),
1250 nsCocoaUtils::DevPixelsToCocoaPoints(c.mMinSize.height, c.mScale.scale)};
1251 [mWindow setMinSize:minSize];
1253 c.mMaxSize.width = std::max(
1254 nsCocoaUtils::CocoaPointsToDevPixels(c.mMaxSize.width, c.mScale.scale), c.mMaxSize.width);
1255 c.mMaxSize.height = std::max(
1256 nsCocoaUtils::CocoaPointsToDevPixels(c.mMaxSize.height, c.mScale.scale), c.mMaxSize.height);
1258 NSSize maxSize = {c.mMaxSize.width == NS_MAXSIZE
1260 : nsCocoaUtils::DevPixelsToCocoaPoints(c.mMaxSize.width, c.mScale.scale),
1261 c.mMaxSize.height == NS_MAXSIZE
1263 : nsCocoaUtils::DevPixelsToCocoaPoints(c.mMaxSize.height, c.mScale.scale)};
1264 [mWindow setMaxSize:maxSize];
1266 nsBaseWidget::SetSizeConstraints(c);
1268 NS_OBJC_END_TRY_IGNORE_BLOCK;
1271 // Coordinates are desktop pixels
1272 void nsCocoaWindow::Move(double aX, double aY) {
1273 NS_OBJC_BEGIN_TRY_IGNORE_BLOCK;
1279 // The point we have is in Gecko coordinates (origin top-left). Convert
1280 // it to Cocoa ones (origin bottom-left).
1281 NSPoint coord = {static_cast<float>(aX),
1282 static_cast<float>(nsCocoaUtils::FlippedScreenY(NSToIntRound(aY)))};
1284 NSRect frame = [mWindow frame];
1285 if (frame.origin.x != coord.x || frame.origin.y + frame.size.height != coord.y) {
1286 [mWindow setFrameTopLeftPoint:coord];
1289 NS_OBJC_END_TRY_IGNORE_BLOCK;
1292 void nsCocoaWindow::SetSizeMode(nsSizeMode aMode) {
1293 if (aMode == nsSizeMode_Normal) {
1294 QueueTransition(TransitionType::Windowed);
1295 } else if (aMode == nsSizeMode_Minimized) {
1296 QueueTransition(TransitionType::Miniaturize);
1297 } else if (aMode == nsSizeMode_Maximized) {
1298 QueueTransition(TransitionType::Zoom);
1299 } else if (aMode == nsSizeMode_Fullscreen) {
1300 MakeFullScreen(true);
1304 // The (work)space switching implementation below was inspired by Phoenix:
1305 // https://github.com/kasper/phoenix/tree/d6c877f62b30a060dff119d8416b0934f76af534
1308 // Runtime `CGSGetActiveSpace` library function feature detection.
1309 typedef CGSSpaceID (*CGSGetActiveSpaceFunc)(CGSConnection cid);
1310 static CGSGetActiveSpaceFunc GetCGSGetActiveSpaceFunc() {
1311 static CGSGetActiveSpaceFunc func = nullptr;
1312 static bool lookedUpFunc = false;
1313 if (!lookedUpFunc) {
1314 func = (CGSGetActiveSpaceFunc)dlsym(RTLD_DEFAULT, "CGSGetActiveSpace");
1315 lookedUpFunc = true;
1319 // Runtime `CGSCopyManagedDisplaySpaces` library function feature detection.
1320 typedef CFArrayRef (*CGSCopyManagedDisplaySpacesFunc)(CGSConnection cid);
1321 static CGSCopyManagedDisplaySpacesFunc GetCGSCopyManagedDisplaySpacesFunc() {
1322 static CGSCopyManagedDisplaySpacesFunc func = nullptr;
1323 static bool lookedUpFunc = false;
1324 if (!lookedUpFunc) {
1325 func = (CGSCopyManagedDisplaySpacesFunc)dlsym(RTLD_DEFAULT, "CGSCopyManagedDisplaySpaces");
1326 lookedUpFunc = true;
1330 // Runtime `CGSCopySpacesForWindows` library function feature detection.
1331 typedef CFArrayRef (*CGSCopySpacesForWindowsFunc)(CGSConnection cid, CGSSpaceMask mask,
1332 CFArrayRef windowIDs);
1333 static CGSCopySpacesForWindowsFunc GetCGSCopySpacesForWindowsFunc() {
1334 static CGSCopySpacesForWindowsFunc func = nullptr;
1335 static bool lookedUpFunc = false;
1336 if (!lookedUpFunc) {
1337 func = (CGSCopySpacesForWindowsFunc)dlsym(RTLD_DEFAULT, "CGSCopySpacesForWindows");
1338 lookedUpFunc = true;
1342 // Runtime `CGSAddWindowsToSpaces` library function feature detection.
1343 typedef void (*CGSAddWindowsToSpacesFunc)(CGSConnection cid, CFArrayRef windowIDs,
1344 CFArrayRef spaceIDs);
1345 static CGSAddWindowsToSpacesFunc GetCGSAddWindowsToSpacesFunc() {
1346 static CGSAddWindowsToSpacesFunc func = nullptr;
1347 static bool lookedUpFunc = false;
1348 if (!lookedUpFunc) {
1349 func = (CGSAddWindowsToSpacesFunc)dlsym(RTLD_DEFAULT, "CGSAddWindowsToSpaces");
1350 lookedUpFunc = true;
1354 // Runtime `CGSRemoveWindowsFromSpaces` library function feature detection.
1355 typedef void (*CGSRemoveWindowsFromSpacesFunc)(CGSConnection cid, CFArrayRef windowIDs,
1356 CFArrayRef spaceIDs);
1357 static CGSRemoveWindowsFromSpacesFunc GetCGSRemoveWindowsFromSpacesFunc() {
1358 static CGSRemoveWindowsFromSpacesFunc func = nullptr;
1359 static bool lookedUpFunc = false;
1360 if (!lookedUpFunc) {
1361 func = (CGSRemoveWindowsFromSpacesFunc)dlsym(RTLD_DEFAULT, "CGSRemoveWindowsFromSpaces");
1362 lookedUpFunc = true;
1367 void nsCocoaWindow::GetWorkspaceID(nsAString& workspaceID) {
1368 workspaceID.Truncate();
1369 int32_t sid = GetWorkspaceID();
1371 workspaceID.AppendInt(sid);
1375 int32_t nsCocoaWindow::GetWorkspaceID() {
1376 NS_OBJC_BEGIN_TRY_IGNORE_BLOCK;
1378 // Mac OSX space IDs start at '1' (default space), so '0' means 'unknown',
1382 CGSCopySpacesForWindowsFunc CopySpacesForWindows = GetCGSCopySpacesForWindowsFunc();
1383 if (!CopySpacesForWindows) {
1387 CGSConnection cid = _CGSDefaultConnection();
1388 // Fetch all spaces that this window belongs to (in order).
1389 NSArray<NSNumber*>* spaceIDs = CFBridgingRelease(CopySpacesForWindows(
1390 cid, kCGSAllSpacesMask, (__bridge CFArrayRef) @[ @([mWindow windowNumber]) ]));
1391 if ([spaceIDs count]) {
1392 // When spaces are found, return the first one.
1393 // We don't support a single window painted across multiple places for now.
1394 sid = [spaceIDs[0] integerValue];
1396 // Fall back to the workspace that's currently active, which is '1' in the
1398 CGSGetActiveSpaceFunc GetActiveSpace = GetCGSGetActiveSpaceFunc();
1399 if (GetActiveSpace) {
1400 sid = GetActiveSpace(cid);
1406 NS_OBJC_END_TRY_IGNORE_BLOCK;
1409 void nsCocoaWindow::MoveToWorkspace(const nsAString& workspaceIDStr) {
1410 NS_OBJC_BEGIN_TRY_IGNORE_BLOCK;
1412 if ([NSScreen screensHaveSeparateSpaces] && [[NSScreen screens] count] > 1) {
1413 // We don't support moving to a workspace when the user has this option
1414 // enabled in Mission Control.
1418 nsresult rv = NS_OK;
1419 int32_t workspaceID = workspaceIDStr.ToInteger(&rv);
1420 if (NS_FAILED(rv)) {
1424 CGSConnection cid = _CGSDefaultConnection();
1425 int32_t currentSpace = GetWorkspaceID();
1426 // If an empty workspace ID is passed in (not valid on OSX), or when the
1427 // window is already on this workspace, we don't need to do anything.
1428 if (!workspaceID || workspaceID == currentSpace) {
1432 CGSCopyManagedDisplaySpacesFunc CopyManagedDisplaySpaces = GetCGSCopyManagedDisplaySpacesFunc();
1433 CGSAddWindowsToSpacesFunc AddWindowsToSpaces = GetCGSAddWindowsToSpacesFunc();
1434 CGSRemoveWindowsFromSpacesFunc RemoveWindowsFromSpaces = GetCGSRemoveWindowsFromSpacesFunc();
1435 if (!CopyManagedDisplaySpaces || !AddWindowsToSpaces || !RemoveWindowsFromSpaces) {
1439 // Fetch an ordered list of all known spaces.
1440 NSArray* displaySpacesInfo = CFBridgingRelease(CopyManagedDisplaySpaces(cid));
1441 // When we found the space we're looking for, we can bail out of the loop
1442 // early, which this local variable is used for.
1444 for (NSDictionary<NSString*, id>* spacesInfo in displaySpacesInfo) {
1445 NSArray<NSNumber*>* sids = [spacesInfo[CGSSpacesKey] valueForKey:CGSSpaceIDKey];
1446 for (NSNumber* sid in sids) {
1447 // If we found our space in the list, we're good to go and can jump out of
1449 if ((int)[sid integerValue] == workspaceID) {
1459 // We were unable to find the space to correspond with the workspaceID as
1460 // requested, so let's bail out.
1465 // First we add the window to the appropriate space.
1466 AddWindowsToSpaces(cid, (__bridge CFArrayRef) @[ @([mWindow windowNumber]) ],
1467 (__bridge CFArrayRef) @[ @(workspaceID) ]);
1468 // Then we remove the window from the active space.
1469 RemoveWindowsFromSpaces(cid, (__bridge CFArrayRef) @[ @([mWindow windowNumber]) ],
1470 (__bridge CFArrayRef) @[ @(currentSpace) ]);
1472 NS_OBJC_END_TRY_IGNORE_BLOCK;
1475 void nsCocoaWindow::SuppressAnimation(bool aSuppress) {
1476 if ([mWindow respondsToSelector:@selector(setAnimationBehavior:)]) {
1478 [mWindow setIsAnimationSuppressed:YES];
1479 [mWindow setAnimationBehavior:NSWindowAnimationBehaviorNone];
1481 [mWindow setIsAnimationSuppressed:NO];
1482 [mWindow setAnimationBehavior:mWindowAnimationBehavior];
1487 // This has to preserve the window's frame bounds.
1488 // This method requires (as does the Windows impl.) that you call Resize shortly
1489 // after calling HideWindowChrome. See bug 498835 for fixing this.
1490 void nsCocoaWindow::HideWindowChrome(bool aShouldHide) {
1491 NS_OBJC_BEGIN_TRY_IGNORE_BLOCK;
1493 if (!mWindow || !mWindowMadeHere ||
1494 (mWindowType != WindowType::TopLevel && mWindowType != WindowType::Dialog))
1497 BOOL isVisible = [mWindow isVisible];
1499 // Remove child windows.
1500 NSArray* childWindows = [mWindow childWindows];
1501 NSEnumerator* enumerator = [childWindows objectEnumerator];
1502 NSWindow* child = nil;
1503 while ((child = [enumerator nextObject])) {
1504 [mWindow removeChildWindow:child];
1507 // Remove the views in the old window's content view.
1508 // The NSArray is autoreleased and retains its NSViews.
1509 NSArray<NSView*>* contentViewContents = [mWindow contentViewContents];
1510 for (NSView* view in contentViewContents) {
1511 [view removeFromSuperviewWithoutNeedingDisplay];
1514 // Save state (like window title).
1515 NSMutableDictionary* state = [mWindow exportState];
1517 // Recreate the window with the right border style.
1518 NSRect frameRect = [mWindow frame];
1519 DestroyNativeWindow();
1520 nsresult rv = CreateNativeWindow(frameRect, aShouldHide ? BorderStyle::None : mBorderStyle, true,
1521 mWindow.restorable);
1522 NS_ENSURE_SUCCESS_VOID(rv);
1525 [mWindow importState:state];
1527 // Add the old content view subviews to the new window's content view.
1528 for (NSView* view in contentViewContents) {
1529 [[mWindow contentView] addSubview:view];
1532 // Reparent child windows.
1533 enumerator = [childWindows objectEnumerator];
1534 while ((child = [enumerator nextObject])) {
1535 [mWindow addChildWindow:child ordered:NSWindowAbove];
1538 // Show the new window.
1540 bool wasAnimationSuppressed = mIsAnimationSuppressed;
1541 mIsAnimationSuppressed = true;
1543 mIsAnimationSuppressed = wasAnimationSuppressed;
1546 NS_OBJC_END_TRY_IGNORE_BLOCK;
1549 class FullscreenTransitionData : public nsISupports {
1553 explicit FullscreenTransitionData(NSWindow* aWindow) : mTransitionWindow(aWindow) {}
1555 NSWindow* mTransitionWindow;
1558 virtual ~FullscreenTransitionData() { [mTransitionWindow close]; }
1561 NS_IMPL_ISUPPORTS0(FullscreenTransitionData)
1563 @interface FullscreenTransitionDelegate : NSObject <NSAnimationDelegate> {
1565 nsCocoaWindow* mWindow;
1566 nsIRunnable* mCallback;
1570 @implementation FullscreenTransitionDelegate
1571 - (void)cleanupAndDispatch:(NSAnimation*)animation {
1572 [animation setDelegate:nil];
1574 // The caller should have added ref for us.
1575 NS_DispatchToMainThread(already_AddRefed<nsIRunnable>(mCallback));
1578 - (void)animationDidEnd:(NSAnimation*)animation {
1579 MOZ_ASSERT(animation == mWindow->FullscreenTransitionAnimation(),
1580 "Should be handling the only animation on the window");
1581 mWindow->ReleaseFullscreenTransitionAnimation();
1582 [self cleanupAndDispatch:animation];
1585 - (void)animationDidStop:(NSAnimation*)animation {
1586 [self cleanupAndDispatch:animation];
1590 static bool AlwaysUsesNativeFullScreen() {
1591 return Preferences::GetBool("full-screen-api.macos-native-full-screen", false);
1594 /* virtual */ bool nsCocoaWindow::PrepareForFullscreenTransition(nsISupports** aData) {
1595 if (AlwaysUsesNativeFullScreen()) {
1599 // Our fullscreen transition creates a new window occluding this window.
1600 // That triggers an occlusion event which can cause DOM fullscreen requests
1601 // to fail due to the context not being focused at the time the focus check
1602 // is performed in the child process. Until the transition is cleaned up in
1603 // CleanupFullscreenTransition(), ignore occlusion events for this window.
1604 // If this method is changed to return false, the transition will not be
1605 // performed and mIgnoreOcclusionCount should not be incremented.
1606 MOZ_ASSERT(mIgnoreOcclusionCount >= 0);
1607 mIgnoreOcclusionCount++;
1609 nsCOMPtr<nsIScreen> widgetScreen = GetWidgetScreen();
1610 NSScreen* cocoaScreen = ScreenHelperCocoa::CocoaScreenForScreen(widgetScreen);
1612 NSWindow* win = [[NSWindow alloc] initWithContentRect:[cocoaScreen frame]
1613 styleMask:NSWindowStyleMaskBorderless
1614 backing:NSBackingStoreBuffered
1616 [win setBackgroundColor:[NSColor blackColor]];
1617 [win setAlphaValue:0];
1618 [win setIgnoresMouseEvents:YES];
1619 [win setLevel:NSScreenSaverWindowLevel];
1620 [win makeKeyAndOrderFront:nil];
1622 auto data = new FullscreenTransitionData(win);
1628 /* virtual */ void nsCocoaWindow::CleanupFullscreenTransition() {
1629 MOZ_ASSERT(mIgnoreOcclusionCount > 0);
1630 mIgnoreOcclusionCount--;
1633 /* virtual */ void nsCocoaWindow::PerformFullscreenTransition(FullscreenTransitionStage aStage,
1636 nsIRunnable* aCallback) {
1637 auto data = static_cast<FullscreenTransitionData*>(aData);
1638 FullscreenTransitionDelegate* delegate = [[FullscreenTransitionDelegate alloc] init];
1639 delegate->mWindow = this;
1640 // Storing already_AddRefed directly could cause static checking fail.
1641 delegate->mCallback = nsCOMPtr<nsIRunnable>(aCallback).forget().take();
1643 if (mFullscreenTransitionAnimation) {
1644 [mFullscreenTransitionAnimation stopAnimation];
1645 ReleaseFullscreenTransitionAnimation();
1648 NSDictionary* dict = @{
1649 NSViewAnimationTargetKey : data->mTransitionWindow,
1650 NSViewAnimationEffectKey : aStage == eBeforeFullscreenToggle ? NSViewAnimationFadeInEffect
1651 : NSViewAnimationFadeOutEffect
1653 mFullscreenTransitionAnimation = [[NSViewAnimation alloc] initWithViewAnimations:@[ dict ]];
1654 [mFullscreenTransitionAnimation setDelegate:delegate];
1655 [mFullscreenTransitionAnimation setDuration:aDuration / 1000.0];
1656 [mFullscreenTransitionAnimation startAnimation];
1659 void nsCocoaWindow::CocoaWindowWillEnterFullscreen(bool aFullscreen) {
1660 MOZ_ASSERT(mUpdateFullscreenOnResize.isNothing());
1662 mHasStartedNativeFullscreen = true;
1664 // Ensure that we update our fullscreen state as early as possible, when the resize
1666 mUpdateFullscreenOnResize =
1667 Some(aFullscreen ? TransitionType::Fullscreen : TransitionType::Windowed);
1670 void nsCocoaWindow::CocoaWindowDidEnterFullscreen(bool aFullscreen) {
1671 mHasStartedNativeFullscreen = false;
1672 EndOurNativeTransition();
1673 DispatchOcclusionEvent();
1674 HandleUpdateFullscreenOnResize();
1675 FinishCurrentTransitionIfMatching(aFullscreen ? TransitionType::Fullscreen
1676 : TransitionType::Windowed);
1679 void nsCocoaWindow::CocoaWindowDidFailFullscreen(bool aAttemptedFullscreen) {
1680 mHasStartedNativeFullscreen = false;
1681 EndOurNativeTransition();
1682 DispatchOcclusionEvent();
1684 // If we already updated our fullscreen state due to a resize, we need to update it again.
1685 if (mUpdateFullscreenOnResize.isNothing()) {
1686 UpdateFullscreenState(!aAttemptedFullscreen, true);
1690 TransitionType transition =
1691 aAttemptedFullscreen ? TransitionType::Fullscreen : TransitionType::Windowed;
1692 FinishCurrentTransitionIfMatching(transition);
1695 void nsCocoaWindow::UpdateFullscreenState(bool aFullScreen, bool aNativeMode) {
1696 bool wasInFullscreen = mInFullScreenMode;
1697 mInFullScreenMode = aFullScreen;
1698 if (aNativeMode || mInNativeFullScreenMode) {
1699 mInNativeFullScreenMode = aFullScreen;
1702 if (aFullScreen == wasInFullscreen) {
1706 DispatchSizeModeEvent();
1708 // Notify the mainChildView with our new fullscreen state.
1709 nsChildView* mainChildView = static_cast<nsChildView*>([[mWindow mainChildView] widget]);
1710 if (mainChildView) {
1711 mainChildView->UpdateFullscreen(aFullScreen);
1715 nsresult nsCocoaWindow::MakeFullScreen(bool aFullScreen) {
1716 return DoMakeFullScreen(aFullScreen, AlwaysUsesNativeFullScreen());
1719 nsresult nsCocoaWindow::MakeFullScreenWithNativeTransition(bool aFullScreen) {
1720 return DoMakeFullScreen(aFullScreen, true);
1723 nsresult nsCocoaWindow::DoMakeFullScreen(bool aFullScreen, bool aUseSystemTransition) {
1728 // Figure out what type of transition is being requested.
1729 TransitionType transition = TransitionType::Windowed;
1731 // Decide whether to use fullscreen or emulated fullscreen.
1732 transition = (aUseSystemTransition &&
1733 (mWindow.collectionBehavior & NSWindowCollectionBehaviorFullScreenPrimary))
1734 ? TransitionType::Fullscreen
1735 : TransitionType::EmulatedFullscreen;
1738 QueueTransition(transition);
1742 void nsCocoaWindow::QueueTransition(const TransitionType& aTransition) {
1743 mTransitionsPending.push(aTransition);
1744 ProcessTransitions();
1747 void nsCocoaWindow::ProcessTransitions() {
1748 NS_OBJC_BEGIN_TRY_IGNORE_BLOCK
1750 if (mInProcessTransitions) {
1754 mInProcessTransitions = true;
1756 // Start a loop that will continue as long as we have transitions to process
1757 // and we aren't waiting on an asynchronous transition to complete. Any
1758 // transition that starts something async will `continue` this loop to exit.
1759 while (!mTransitionsPending.empty() && !IsInTransition()) {
1760 TransitionType nextTransition = mTransitionsPending.front();
1762 // We have to check for some incompatible transition states, and if we find one,
1763 // instead perform an alternative transition and leave the queue untouched. If
1764 // we add one of these transitions, we set mIsTransitionCurrentAdded because we
1765 // don't want to confuse listeners who are expecting to receive exactly one
1766 // event when the requested transition has completed.
1767 switch (nextTransition) {
1768 case TransitionType::Fullscreen:
1769 case TransitionType::EmulatedFullscreen:
1770 case TransitionType::Windowed:
1771 case TransitionType::Zoom:
1772 // These can't handle miniaturized windows, so deminiaturize first.
1773 if (mWindow.miniaturized) {
1774 mTransitionCurrent = Some(TransitionType::Deminiaturize);
1775 mIsTransitionCurrentAdded = true;
1778 case TransitionType::Miniaturize:
1779 // This can't handle fullscreen, so go to windowed first.
1780 if (mInFullScreenMode) {
1781 mTransitionCurrent = Some(TransitionType::Windowed);
1782 mIsTransitionCurrentAdded = true;
1789 // If mTransitionCurrent is still empty, then we use the nextTransition and pop
1791 if (mTransitionCurrent.isNothing()) {
1792 mTransitionCurrent = Some(nextTransition);
1793 mTransitionsPending.pop();
1796 switch (*mTransitionCurrent) {
1797 case TransitionType::Fullscreen: {
1798 if (!mInFullScreenMode) {
1799 // Check our global state to see if it is safe to start a native
1800 // fullscreen transition. While that is false, run our own event loop.
1801 // Eventually, the native fullscreen transition will finish, and we can
1803 NSRunLoop* localRunLoop = [NSRunLoop currentRunLoop];
1804 while (mWindow && !CanStartNativeTransition() &&
1805 [localRunLoop runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]]) {
1806 // This loop continues to process events until CanStartNativeTransition()
1810 // This triggers an async animation, so continue.
1811 [mWindow toggleFullScreen:nil];
1817 case TransitionType::EmulatedFullscreen: {
1818 if (!mInFullScreenMode) {
1819 NSDisableScreenUpdates();
1820 mSuppressSizeModeEvents = true;
1821 // The order here matters. When we exit full screen mode, we need to show the
1822 // Dock first, otherwise the newly-created window won't have its minimize
1823 // button enabled. See bug 526282.
1824 nsCocoaUtils::HideOSChromeOnScreen(true);
1825 nsBaseWidget::InfallibleMakeFullScreen(true);
1826 mSuppressSizeModeEvents = false;
1827 NSEnableScreenUpdates();
1828 UpdateFullscreenState(true, false);
1833 case TransitionType::Windowed: {
1834 if (mInFullScreenMode) {
1835 if (mInNativeFullScreenMode) {
1836 // Check our global state to see if it is safe to start a native
1837 // fullscreen transition. While that is false, run our own event loop.
1838 // Eventually, the native fullscreen transition will finish, and we can
1840 NSRunLoop* localRunLoop = [NSRunLoop currentRunLoop];
1841 while (mWindow && !CanStartNativeTransition() &&
1842 [localRunLoop runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]]) {
1843 // This loop continues to process events until CanStartNativeTransition()
1847 // This triggers an async animation, so continue.
1848 [mWindow toggleFullScreen:nil];
1851 NSDisableScreenUpdates();
1852 mSuppressSizeModeEvents = true;
1853 // The order here matters. When we exit full screen mode, we need to show the
1854 // Dock first, otherwise the newly-created window won't have its minimize
1855 // button enabled. See bug 526282.
1856 nsCocoaUtils::HideOSChromeOnScreen(false);
1857 nsBaseWidget::InfallibleMakeFullScreen(false);
1858 mSuppressSizeModeEvents = false;
1859 NSEnableScreenUpdates();
1860 UpdateFullscreenState(false, false);
1862 } else if (mWindow.zoomed) {
1865 // Check if we're still zoomed. If we are, we need to do *something* to make the
1866 // window smaller than the zoom size so Cocoa will treat us as being out of the
1867 // zoomed state. Otherwise, we could stay zoomed and never be able to be "normal"
1868 // from calls to SetSizeMode.
1869 if (mWindow.zoomed) {
1870 NSRect maximumFrame = mWindow.frame;
1871 const CGFloat INSET_OUT_OF_ZOOM = 20.0f;
1872 [mWindow setFrame:NSInsetRect(maximumFrame, INSET_OUT_OF_ZOOM, INSET_OUT_OF_ZOOM)
1874 MOZ_ASSERT(!mWindow.zoomed,
1875 "We should be able to unzoom by shrinking the frame a bit.");
1881 case TransitionType::Miniaturize:
1882 if (!mWindow.miniaturized) {
1883 // This triggers an async animation, so continue.
1884 [mWindow miniaturize:nil];
1889 case TransitionType::Deminiaturize:
1890 if (mWindow.miniaturized) {
1891 // This triggers an async animation, so continue.
1892 [mWindow deminiaturize:nil];
1897 case TransitionType::Zoom:
1898 if (!mWindow.zoomed) {
1907 mTransitionCurrent.reset();
1908 mIsTransitionCurrentAdded = false;
1911 mInProcessTransitions = false;
1913 // When we finish processing transitions, dispatch a size mode event to cover the
1914 // cases where an inserted transition suppressed one, and the original transition
1915 // never sent one because it detected it was at the desired state when it ran. If
1916 // we've already sent a size mode event, then this will be a no-op.
1917 if (!IsInTransition()) {
1918 DispatchSizeModeEvent();
1921 NS_OBJC_END_TRY_IGNORE_BLOCK;
1924 void nsCocoaWindow::FinishCurrentTransition() {
1925 mTransitionCurrent.reset();
1926 mIsTransitionCurrentAdded = false;
1927 ProcessTransitions();
1930 void nsCocoaWindow::FinishCurrentTransitionIfMatching(const TransitionType& aTransition) {
1931 // We've just finished some transition activity, and we're not sure whether it was
1932 // triggered programmatically, or by the user. If it matches our current transition,
1933 // then assume it was triggered programmatically and we can clean up that transition
1934 // and start processing transitions again.
1936 // Whether programmatic or user-initiated, we send out a size mode event.
1937 DispatchSizeModeEvent();
1939 if (mTransitionCurrent.isSome() && (*mTransitionCurrent == aTransition)) {
1940 // This matches our current transition. Since this function is called from
1941 // nsWindowDelegate transition callbacks, we want to make sure those callbacks are
1942 // all the way done before we start processing more transitions. To accomplish this,
1943 // we dispatch our cleanup to happen on the next event loop. Doing this will ensure
1944 // that any async native transition methods we call (like toggleFullScreen) will
1946 NS_DispatchToCurrentThread(NewRunnableMethod("FinishCurrentTransition", this,
1947 &nsCocoaWindow::FinishCurrentTransition));
1951 bool nsCocoaWindow::HandleUpdateFullscreenOnResize() {
1952 if (mUpdateFullscreenOnResize.isNothing()) {
1956 bool toFullscreen = (*mUpdateFullscreenOnResize == TransitionType::Fullscreen);
1957 mUpdateFullscreenOnResize.reset();
1958 UpdateFullscreenState(toFullscreen, true);
1963 /* static */ mozilla::StaticDataMutex<nsCocoaWindow*> nsCocoaWindow::sWindowInNativeTransition(
1966 bool nsCocoaWindow::CanStartNativeTransition() {
1967 auto window = sWindowInNativeTransition.Lock();
1968 if (*window == nullptr) {
1969 // Claim it and return true, indicating that the caller has permission to start
1970 // the native fullscreen transition.
1977 bool nsCocoaWindow::WeAreInNativeTransition() {
1978 auto window = sWindowInNativeTransition.Lock();
1979 return (*window == this);
1982 void nsCocoaWindow::EndOurNativeTransition() {
1983 auto window = sWindowInNativeTransition.Lock();
1984 if (*window == this) {
1989 // Coordinates are desktop pixels
1990 void nsCocoaWindow::DoResize(double aX, double aY, double aWidth, double aHeight, bool aRepaint,
1991 bool aConstrainToCurrentScreen) {
1992 NS_OBJC_BEGIN_TRY_IGNORE_BLOCK;
1994 if (!mWindow || mInResize) {
1998 // We are able to resize a window outside of any aspect ratio contraints
1999 // applied to it, but in order to "update" the aspect ratio contraint to the
2000 // new window dimensions, we must re-lock the aspect ratio.
2001 auto relockAspectRatio = MakeScopeExit([&]() {
2002 if (mAspectRatioLocked) {
2003 LockAspectRatio(true);
2007 AutoRestore<bool> reentrantResizeGuard(mInResize);
2010 CGFloat scale = mSizeConstraints.mScale.scale;
2011 if (scale == MOZ_WIDGET_INVALID_SCALE) {
2012 scale = BackingScaleFactor();
2015 // mSizeConstraints is in device pixels.
2016 int32_t width = NSToIntRound(aWidth * scale);
2017 int32_t height = NSToIntRound(aHeight * scale);
2020 std::max(mSizeConstraints.mMinSize.width, std::min(mSizeConstraints.mMaxSize.width, width));
2021 height = std::max(mSizeConstraints.mMinSize.height,
2022 std::min(mSizeConstraints.mMaxSize.height, height));
2024 DesktopIntRect newBounds(NSToIntRound(aX), NSToIntRound(aY), NSToIntRound(width / scale),
2025 NSToIntRound(height / scale));
2027 // constrain to the screen that contains the largest area of the new rect
2028 FitRectToVisibleAreaForScreen(newBounds, aConstrainToCurrentScreen ? [mWindow screen] : nullptr);
2030 // convert requested bounds into Cocoa coordinate system
2031 NSRect newFrame = nsCocoaUtils::GeckoRectToCocoaRect(newBounds);
2033 NSRect frame = [mWindow frame];
2034 BOOL isMoving = newFrame.origin.x != frame.origin.x || newFrame.origin.y != frame.origin.y;
2036 newFrame.size.width != frame.size.width || newFrame.size.height != frame.size.height;
2038 if (!isMoving && !isResizing) {
2042 // We ignore aRepaint -- we have to call display:YES, otherwise the
2043 // title bar doesn't immediately get repainted and is displayed in
2044 // the wrong place, leading to a visual jump.
2045 [mWindow setFrame:newFrame display:YES];
2047 NS_OBJC_END_TRY_IGNORE_BLOCK;
2050 // Coordinates are desktop pixels
2051 void nsCocoaWindow::Resize(double aX, double aY, double aWidth, double aHeight, bool aRepaint) {
2052 DoResize(aX, aY, aWidth, aHeight, aRepaint, false);
2055 // Coordinates are desktop pixels
2056 void nsCocoaWindow::Resize(double aWidth, double aHeight, bool aRepaint) {
2057 double invScale = 1.0 / BackingScaleFactor();
2058 DoResize(mBounds.x * invScale, mBounds.y * invScale, aWidth, aHeight, aRepaint, true);
2061 // Return the area that the Gecko ChildView in our window should cover, as an
2062 // NSRect in screen coordinates (with 0,0 being the bottom left corner of the
2064 NSRect nsCocoaWindow::GetClientCocoaRect() {
2069 return [mWindow childViewRectForFrameRect:[mWindow frame]];
2072 LayoutDeviceIntRect nsCocoaWindow::GetClientBounds() {
2073 NS_OBJC_BEGIN_TRY_BLOCK_RETURN;
2075 CGFloat scaleFactor = BackingScaleFactor();
2076 return nsCocoaUtils::CocoaRectToGeckoRectDevPix(GetClientCocoaRect(), scaleFactor);
2078 NS_OBJC_END_TRY_BLOCK_RETURN(LayoutDeviceIntRect(0, 0, 0, 0));
2081 void nsCocoaWindow::UpdateBounds() {
2082 NSRect frame = NSZeroRect;
2084 frame = [mWindow frame];
2086 mBounds = nsCocoaUtils::CocoaRectToGeckoRectDevPix(frame, BackingScaleFactor());
2088 if (mPopupContentView) {
2089 mPopupContentView->UpdateBoundsFromView();
2093 LayoutDeviceIntRect nsCocoaWindow::GetScreenBounds() {
2094 NS_OBJC_BEGIN_TRY_BLOCK_RETURN;
2097 LayoutDeviceIntRect r =
2098 nsCocoaUtils::CocoaRectToGeckoRectDevPix([mWindow frame], BackingScaleFactor());
2099 NS_ASSERTION(mWindow && mBounds == r, "mBounds out of sync!");
2104 NS_OBJC_END_TRY_BLOCK_RETURN(LayoutDeviceIntRect(0, 0, 0, 0));
2107 double nsCocoaWindow::GetDefaultScaleInternal() { return BackingScaleFactor(); }
2109 static CGFloat GetBackingScaleFactor(NSWindow* aWindow) {
2110 NSRect frame = [aWindow frame];
2111 if (frame.size.width > 0 && frame.size.height > 0) {
2112 return nsCocoaUtils::GetBackingScaleFactor(aWindow);
2115 // For windows with zero width or height, the backingScaleFactor method
2116 // is broken - it will always return 2 on a retina macbook, even when
2117 // the window position implies it's on a non-hidpi external display
2118 // (to the extent that a zero-area window can be said to be "on" a
2120 // And to make matters worse, Cocoa even fires a
2121 // windowDidChangeBackingProperties notification with the
2122 // NSBackingPropertyOldScaleFactorKey key when a window on an
2123 // external display is resized to/from zero height, even though it hasn't
2124 // really changed screens.
2126 // This causes us to handle popup window sizing incorrectly when the
2127 // popup is resized to zero height (bug 820327) - nsXULPopupManager
2128 // becomes (incorrectly) convinced the popup has been explicitly forced
2129 // to a non-default size and needs to have size attributes attached.
2131 // Workaround: instead of asking the window, we'll find the screen it is on
2132 // and ask that for *its* backing scale factor.
2134 // (See bug 853252 and additional comments in windowDidChangeScreen: below
2135 // for further complications this causes.)
2137 // First, expand the rect so that it actually has a measurable area,
2138 // for FindTargetScreenForRect to use.
2139 if (frame.size.width == 0) {
2140 frame.size.width = 1;
2142 if (frame.size.height == 0) {
2143 frame.size.height = 1;
2146 // Then identify the screen it belongs to, and return its scale factor.
2147 NSScreen* screen = FindTargetScreenForRect(nsCocoaUtils::CocoaRectToGeckoRect(frame));
2148 return nsCocoaUtils::GetBackingScaleFactor(screen);
2151 CGFloat nsCocoaWindow::BackingScaleFactor() {
2152 if (mBackingScaleFactor > 0.0) {
2153 return mBackingScaleFactor;
2158 mBackingScaleFactor = GetBackingScaleFactor(mWindow);
2159 return mBackingScaleFactor;
2162 void nsCocoaWindow::BackingScaleFactorChanged() {
2163 CGFloat newScale = GetBackingScaleFactor(mWindow);
2165 // ignore notification if it hasn't really changed (or maybe we have
2166 // disabled HiDPI mode via prefs)
2167 if (mBackingScaleFactor == newScale) {
2171 mBackingScaleFactor = newScale;
2173 if (!mWidgetListener || mWidgetListener->GetAppWindow()) {
2177 if (PresShell* presShell = mWidgetListener->GetPresShell()) {
2178 presShell->BackingScaleFactorChanged();
2180 mWidgetListener->UIResolutionChanged();
2183 int32_t nsCocoaWindow::RoundsWidgetCoordinatesTo() {
2184 if (BackingScaleFactor() == 2.0) {
2190 void nsCocoaWindow::SetCursor(const Cursor& aCursor) {
2191 if (mPopupContentView) {
2192 mPopupContentView->SetCursor(aCursor);
2196 nsresult nsCocoaWindow::SetTitle(const nsAString& aTitle) {
2197 NS_OBJC_BEGIN_TRY_BLOCK_RETURN;
2203 const nsString& strTitle = PromiseFlatString(aTitle);
2204 const unichar* uniTitle = reinterpret_cast<const unichar*>(strTitle.get());
2205 NSString* title = [NSString stringWithCharacters:uniTitle length:strTitle.Length()];
2206 if ([mWindow drawsContentsIntoWindowFrame] && ![mWindow wantsTitleDrawn]) {
2207 // Don't cause invalidations when the title isn't displayed.
2208 [mWindow disableSetNeedsDisplay];
2209 [mWindow setTitle:title];
2210 [mWindow enableSetNeedsDisplay];
2212 [mWindow setTitle:title];
2217 NS_OBJC_END_TRY_BLOCK_RETURN(NS_ERROR_FAILURE);
2220 void nsCocoaWindow::Invalidate(const LayoutDeviceIntRect& aRect) {
2221 if (mPopupContentView) {
2222 mPopupContentView->Invalidate(aRect);
2226 // Pass notification of some drag event to Gecko
2228 // The drag manager has let us know that something related to a drag has
2229 // occurred in this window. It could be any number of things, ranging from
2230 // a drop, to a drag enter/leave, or a drag over event. The actual event
2231 // is passed in |aMessage| and is passed along to our event hanlder so Gecko
2233 bool nsCocoaWindow::DragEvent(unsigned int aMessage, mozilla::gfx::Point aMouseGlobal,
2234 UInt16 aKeyModifiers) {
2238 NS_IMETHODIMP nsCocoaWindow::SendSetZLevelEvent() {
2239 nsWindowZ placement = nsWindowZTop;
2240 nsCOMPtr<nsIWidget> actualBelow;
2241 if (mWidgetListener)
2242 mWidgetListener->ZLevelChanged(true, &placement, nullptr, getter_AddRefs(actualBelow));
2246 NS_IMETHODIMP nsCocoaWindow::GetChildSheet(bool aShown, nsIWidget** _retval) {
2247 nsIWidget* child = GetFirstChild();
2250 if (child->GetWindowType() == WindowType::Sheet) {
2251 // if it's a sheet, it must be an nsCocoaWindow
2252 nsCocoaWindow* cocoaWindow = static_cast<nsCocoaWindow*>(child);
2253 if (cocoaWindow->mWindow && ((aShown && [cocoaWindow->mWindow isVisible]) ||
2254 (!aShown && cocoaWindow->mSheetNeedsShow))) {
2255 nsCOMPtr<nsIWidget> widget = cocoaWindow;
2256 widget.forget(_retval);
2260 child = child->GetNextSibling();
2268 NS_IMETHODIMP nsCocoaWindow::GetRealParent(nsIWidget** parent) {
2273 NS_IMETHODIMP nsCocoaWindow::GetIsSheet(bool* isSheet) {
2274 mWindowType == WindowType::Sheet ? * isSheet = true : * isSheet = false;
2278 NS_IMETHODIMP nsCocoaWindow::GetSheetWindowParent(NSWindow** sheetWindowParent) {
2279 *sheetWindowParent = mSheetWindowParent;
2283 // Invokes callback and ProcessEvent methods on Event Listener object
2284 nsresult nsCocoaWindow::DispatchEvent(WidgetGUIEvent* event, nsEventStatus& aStatus) {
2285 aStatus = nsEventStatus_eIgnore;
2287 nsCOMPtr<nsIWidget> kungFuDeathGrip(event->mWidget);
2288 mozilla::Unused << kungFuDeathGrip; // Not used within this function
2290 if (mWidgetListener) aStatus = mWidgetListener->HandleEvent(event, mUseAttachedEvents);
2295 // aFullScreen should be the window's mInFullScreenMode. We don't have access to that
2296 // from here, so we need to pass it in. mInFullScreenMode should be the canonical
2297 // indicator that a window is currently full screen and it makes sense to keep
2298 // all sizemode logic here.
2299 static nsSizeMode GetWindowSizeMode(NSWindow* aWindow, bool aFullScreen) {
2300 if (aFullScreen) return nsSizeMode_Fullscreen;
2301 if ([aWindow isMiniaturized]) return nsSizeMode_Minimized;
2302 if (([aWindow styleMask] & NSWindowStyleMaskResizable) && [aWindow isZoomed])
2303 return nsSizeMode_Maximized;
2304 return nsSizeMode_Normal;
2307 void nsCocoaWindow::ReportMoveEvent() {
2308 NS_OBJC_BEGIN_TRY_IGNORE_BLOCK;
2310 // Prevent recursion, which can become infinite (see bug 708278). This
2311 // can happen when the call to [NSWindow setFrameTopLeftPoint:] in
2312 // nsCocoaWindow::Move() triggers an immediate NSWindowDidMove notification
2313 // (and a call to [WindowDelegate windowDidMove:]).
2314 if (mInReportMoveEvent) {
2317 mInReportMoveEvent = true;
2321 // The zoomed state can change when we're moving, in which case we need to
2322 // update our internal mSizeMode. This can happen either if we're maximized
2323 // and then moved, or if we're not maximized and moved back to zoomed state.
2324 if (mWindow && ((mSizeMode == nsSizeMode_Maximized) ^ [mWindow isZoomed])) {
2325 DispatchSizeModeEvent();
2328 // Dispatch the move event to Gecko
2329 NotifyWindowMoved(mBounds.x, mBounds.y);
2331 mInReportMoveEvent = false;
2333 NS_OBJC_END_TRY_IGNORE_BLOCK;
2336 void nsCocoaWindow::DispatchSizeModeEvent() {
2341 if (mSuppressSizeModeEvents || mIsTransitionCurrentAdded) {
2345 nsSizeMode newMode = GetWindowSizeMode(mWindow, mInFullScreenMode);
2346 if (mSizeMode == newMode) {
2350 mSizeMode = newMode;
2351 if (mWidgetListener) {
2352 mWidgetListener->SizeModeChanged(newMode);
2356 void nsCocoaWindow::DispatchOcclusionEvent() {
2361 // Our new occlusion state is true if the window is not visible.
2362 bool newOcclusionState =
2363 !(mHasStartedNativeFullscreen || ([mWindow occlusionState] & NSWindowOcclusionStateVisible));
2365 // Don't dispatch if the new occlustion state is the same as the current state.
2366 if (mIsFullyOccluded == newOcclusionState) {
2370 MOZ_ASSERT(mIgnoreOcclusionCount >= 0);
2371 if (newOcclusionState && mIgnoreOcclusionCount > 0) {
2375 mIsFullyOccluded = newOcclusionState;
2376 if (mWidgetListener) {
2377 mWidgetListener->OcclusionStateChanged(mIsFullyOccluded);
2381 void nsCocoaWindow::ReportSizeEvent() {
2382 NS_OBJC_BEGIN_TRY_IGNORE_BLOCK;
2385 if (mWidgetListener) {
2386 LayoutDeviceIntRect innerBounds = GetClientBounds();
2387 mWidgetListener->WindowResized(this, innerBounds.width, innerBounds.height);
2390 NS_OBJC_END_TRY_IGNORE_BLOCK;
2393 void nsCocoaWindow::SetMenuBar(RefPtr<nsMenuBarX>&& aMenuBar) {
2398 mMenuBar = std::move(aMenuBar);
2400 // Only paint for active windows, or paint the hidden window menu bar if no
2401 // other menu bar has been painted yet so that some reasonable menu bar is
2402 // displayed when the app starts up.
2403 if (mMenuBar && ((!gSomeMenuBarPainted && nsMenuUtilsX::GetHiddenWindowMenuBar() == mMenuBar) ||
2404 [mWindow isMainWindow]))
2408 void nsCocoaWindow::SetFocus(Raise aRaise, mozilla::dom::CallerType aCallerType) {
2409 if (!mWindow) return;
2411 if (mPopupContentView) {
2412 return mPopupContentView->SetFocus(aRaise, aCallerType);
2415 if (aRaise == Raise::Yes && ([mWindow isVisible] || [mWindow isMiniaturized])) {
2416 if ([mWindow isMiniaturized]) {
2417 [mWindow deminiaturize:nil];
2420 [mWindow makeKeyAndOrderFront:nil];
2421 SendSetZLevelEvent();
2425 LayoutDeviceIntPoint nsCocoaWindow::WidgetToScreenOffset() {
2426 NS_OBJC_BEGIN_TRY_BLOCK_RETURN;
2428 return nsCocoaUtils::CocoaRectToGeckoRectDevPix(GetClientCocoaRect(), BackingScaleFactor())
2431 NS_OBJC_END_TRY_BLOCK_RETURN(LayoutDeviceIntPoint(0, 0));
2434 LayoutDeviceIntPoint nsCocoaWindow::GetClientOffset() {
2435 NS_OBJC_BEGIN_TRY_BLOCK_RETURN;
2437 LayoutDeviceIntRect clientRect = GetClientBounds();
2439 return clientRect.TopLeft() - mBounds.TopLeft();
2441 NS_OBJC_END_TRY_BLOCK_RETURN(LayoutDeviceIntPoint(0, 0));
2444 LayoutDeviceIntMargin nsCocoaWindow::ClientToWindowMargin() {
2445 NS_OBJC_BEGIN_TRY_BLOCK_RETURN;
2447 if (!mWindow || mWindow.drawsContentsIntoWindowFrame || mWindowType == WindowType::Popup) {
2451 NSRect clientNSRect = mWindow.contentLayoutRect;
2452 NSRect frameNSRect = [mWindow frameRectForChildViewRect:clientNSRect];
2454 CGFloat backingScale = BackingScaleFactor();
2455 const auto clientRect = nsCocoaUtils::CocoaRectToGeckoRectDevPix(clientNSRect, backingScale);
2456 const auto frameRect = nsCocoaUtils::CocoaRectToGeckoRectDevPix(frameNSRect, backingScale);
2458 return frameRect - clientRect;
2460 NS_OBJC_END_TRY_BLOCK_RETURN({});
2463 nsMenuBarX* nsCocoaWindow::GetMenuBar() { return mMenuBar; }
2465 void nsCocoaWindow::CaptureRollupEvents(bool aDoCapture) {
2466 NS_OBJC_BEGIN_TRY_IGNORE_BLOCK;
2469 if (![NSApp isActive]) {
2470 // We need to capture mouse event if we aren't
2471 // the active application. We only set this up when needed
2472 // because they cause spurious mouse event after crash
2473 // and gdb sessions. See bug 699538.
2474 nsToolkit::GetToolkit()->MonitorAllProcessMouseEvents();
2477 // Sometimes more than one popup window can be visible at the same time
2478 // (e.g. nested non-native context menus, or the test case (attachment
2479 // 276885) for bmo bug 392389, which displays a non-native combo-box in a
2480 // non-native popup window). In these cases the "active" popup window should
2481 // be the topmost -- the (nested) context menu the mouse is currently over,
2482 // or the combo-box's drop-down list (when it's displayed). But (among
2483 // windows that have the same "level") OS X makes topmost the window that
2484 // last received a mouse-down event, which may be incorrect (in the combo-
2485 // box case, it makes topmost the window containing the combo-box). So
2486 // here we fiddle with a non-native popup window's level to make sure the
2487 // "active" one is always above any other non-native popup windows that
2489 if (mWindow && (mWindowType == WindowType::Popup)) SetPopupWindowLevel();
2491 nsToolkit::GetToolkit()->StopMonitoringAllProcessMouseEvents();
2493 // XXXndeakin this doesn't make sense.
2494 // Why is the new window assumed to be a modal panel?
2495 if (mWindow && (mWindowType == WindowType::Popup)) [mWindow setLevel:NSModalPanelWindowLevel];
2498 NS_OBJC_END_TRY_IGNORE_BLOCK;
2501 nsresult nsCocoaWindow::GetAttention(int32_t aCycleCount) {
2502 NS_OBJC_BEGIN_TRY_BLOCK_RETURN;
2504 [NSApp requestUserAttention:NSInformationalRequest];
2507 NS_OBJC_END_TRY_BLOCK_RETURN(NS_ERROR_FAILURE);
2510 bool nsCocoaWindow::HasPendingInputEvent() { return nsChildView::DoHasPendingInputEvent(); }
2512 void nsCocoaWindow::SetWindowShadowStyle(StyleWindowShadow aStyle) {
2513 NS_OBJC_BEGIN_TRY_IGNORE_BLOCK;
2515 mShadowStyle = aStyle;
2517 if (!mWindow || mWindowType != WindowType::Popup) {
2521 mWindow.shadowStyle = mShadowStyle;
2522 [mWindow setUseMenuStyle:mShadowStyle == StyleWindowShadow::Menu];
2523 [mWindow setHasShadow:aStyle != StyleWindowShadow::None];
2525 NS_OBJC_END_TRY_IGNORE_BLOCK;
2528 void nsCocoaWindow::SetWindowOpacity(float aOpacity) {
2529 NS_OBJC_BEGIN_TRY_IGNORE_BLOCK;
2535 [mWindow setAlphaValue:(CGFloat)aOpacity];
2537 NS_OBJC_END_TRY_IGNORE_BLOCK;
2540 void nsCocoaWindow::SetColorScheme(const Maybe<ColorScheme>& aScheme) {
2541 NS_OBJC_BEGIN_TRY_IGNORE_BLOCK;
2547 mWindow.appearance = aScheme ? NSAppearanceForColorScheme(*aScheme) : nil;
2549 NS_OBJC_END_TRY_IGNORE_BLOCK;
2552 static inline CGAffineTransform GfxMatrixToCGAffineTransform(const gfx::Matrix& m) {
2553 CGAffineTransform t;
2563 void nsCocoaWindow::SetWindowTransform(const gfx::Matrix& aTransform) {
2564 NS_OBJC_BEGIN_TRY_IGNORE_BLOCK;
2570 // Calling CGSSetWindowTransform when the window is not visible results in
2571 // misplacing the window into doubled x,y coordinates (see bug 1448132).
2572 if (![mWindow isVisible] || NSIsEmptyRect([mWindow frame])) {
2576 if (StaticPrefs::widget_window_transforms_disabled()) {
2577 // CGSSetWindowTransform is a private API. In case calling it causes
2578 // problems either now or in the future, we'll want to have an easy kill
2579 // switch. So we allow disabling it with a pref.
2583 gfx::Matrix transform = aTransform;
2585 // aTransform is a transform that should be applied to the window relative
2586 // to its regular position: If aTransform._31 is 100, then we want the
2587 // window to be displayed 100 pixels to the right of its regular position.
2588 // The transform that CGSSetWindowTransform accepts has a different meaning:
2589 // It's used to answer the question "For the screen pixel at x,y (with the
2590 // origin at the top left), what pixel in the window's buffer (again with
2591 // origin top left) should be displayed at that position?"
2592 // In the example above, this means that we need to call
2593 // CGSSetWindowTransform with a horizontal translation of -windowPos.x - 100.
2594 // So we need to invert the transform and adjust it by the window's position.
2595 if (!transform.Invert()) {
2596 // Treat non-invertible transforms as the identity transform.
2597 transform = gfx::Matrix();
2600 bool isIdentity = transform.IsIdentity();
2601 if (isIdentity && mWindowTransformIsIdentity) {
2605 transform.PreTranslate(-mBounds.x, -mBounds.y);
2607 // Snap translations to device pixels, to match what we do for CSS transforms
2608 // and because the window server rounds down instead of to nearest.
2609 if (!transform.HasNonTranslation() && transform.HasNonIntegerTranslation()) {
2610 auto snappedTranslation = gfx::IntPoint::Round(transform.GetTranslation());
2611 transform = gfx::Matrix::Translation(snappedTranslation.x, snappedTranslation.y);
2614 // We also need to account for the backing scale factor: aTransform is given
2615 // in device pixels, but CGSSetWindowTransform works with logical display
2617 CGFloat backingScale = BackingScaleFactor();
2618 transform.PreScale(backingScale, backingScale);
2619 transform.PostScale(1 / backingScale, 1 / backingScale);
2621 CGSConnection cid = _CGSDefaultConnection();
2622 CGSSetWindowTransform(cid, [mWindow windowNumber], GfxMatrixToCGAffineTransform(transform));
2624 mWindowTransformIsIdentity = isIdentity;
2626 NS_OBJC_END_TRY_IGNORE_BLOCK;
2629 void nsCocoaWindow::SetInputRegion(const InputRegion& aInputRegion) {
2630 MOZ_ASSERT(mWindowType == WindowType::Popup, "This should only be called on popup windows.");
2631 // TODO: Somehow support aInputRegion.mMargin? Though maybe not.
2632 if (aInputRegion.mFullyTransparent) {
2633 [mWindow setIgnoresMouseEvents:YES];
2635 [mWindow setIgnoresMouseEvents:NO];
2639 void nsCocoaWindow::SetShowsToolbarButton(bool aShow) {
2640 NS_OBJC_BEGIN_TRY_IGNORE_BLOCK;
2642 if (mWindow) [mWindow setShowsToolbarButton:aShow];
2644 NS_OBJC_END_TRY_IGNORE_BLOCK;
2647 void nsCocoaWindow::SetSupportsNativeFullscreen(bool aSupportsNativeFullscreen) {
2648 NS_OBJC_BEGIN_TRY_IGNORE_BLOCK;
2651 // This determines whether we tell cocoa that the window supports native
2652 // full screen. If we do so, and another window is in native full screen,
2653 // this window will also appear in native full screen. We generally only
2654 // want to do this for primary application windows. We'll set the
2655 // relevant macnativefullscreen attribute on those, which will lead to us
2656 // being called with aSupportsNativeFullscreen set to `true` here.
2657 NSWindowCollectionBehavior newBehavior = [mWindow collectionBehavior];
2658 if (aSupportsNativeFullscreen) {
2659 newBehavior |= NSWindowCollectionBehaviorFullScreenPrimary;
2661 newBehavior &= ~NSWindowCollectionBehaviorFullScreenPrimary;
2663 [mWindow setCollectionBehavior:newBehavior];
2666 NS_OBJC_END_TRY_IGNORE_BLOCK;
2669 void nsCocoaWindow::SetWindowAnimationType(nsIWidget::WindowAnimationType aType) {
2670 mAnimationType = aType;
2673 void nsCocoaWindow::SetDrawsTitle(bool aDrawTitle) {
2674 NS_OBJC_BEGIN_TRY_IGNORE_BLOCK;
2676 if (![mWindow drawsContentsIntoWindowFrame]) {
2677 // If we don't draw into the window frame, we always want to display window
2679 [mWindow setWantsTitleDrawn:YES];
2681 [mWindow setWantsTitleDrawn:aDrawTitle];
2684 NS_OBJC_END_TRY_IGNORE_BLOCK;
2687 nsresult nsCocoaWindow::SetNonClientMargins(const LayoutDeviceIntMargin& margins) {
2688 NS_OBJC_BEGIN_TRY_BLOCK_RETURN;
2690 SetDrawsInTitlebar(margins.top == 0);
2694 NS_OBJC_END_TRY_BLOCK_RETURN(NS_ERROR_FAILURE);
2697 void nsCocoaWindow::SetDrawsInTitlebar(bool aState) {
2698 NS_OBJC_BEGIN_TRY_IGNORE_BLOCK;
2701 [mWindow setDrawsContentsIntoWindowFrame:aState];
2704 NS_OBJC_END_TRY_IGNORE_BLOCK;
2707 NS_IMETHODIMP nsCocoaWindow::SynthesizeNativeMouseEvent(LayoutDeviceIntPoint aPoint,
2708 NativeMouseMessage aNativeMessage,
2709 MouseButton aButton,
2710 nsIWidget::Modifiers aModifierFlags,
2711 nsIObserver* aObserver) {
2712 NS_OBJC_BEGIN_TRY_BLOCK_RETURN;
2714 AutoObserverNotifier notifier(aObserver, "mouseevent");
2715 if (mPopupContentView) {
2716 return mPopupContentView->SynthesizeNativeMouseEvent(aPoint, aNativeMessage, aButton,
2717 aModifierFlags, nullptr);
2722 NS_OBJC_END_TRY_BLOCK_RETURN(NS_ERROR_FAILURE);
2725 NS_IMETHODIMP nsCocoaWindow::SynthesizeNativeMouseScrollEvent(
2726 LayoutDeviceIntPoint aPoint, uint32_t aNativeMessage, double aDeltaX, double aDeltaY,
2727 double aDeltaZ, uint32_t aModifierFlags, uint32_t aAdditionalFlags, nsIObserver* aObserver) {
2728 NS_OBJC_BEGIN_TRY_BLOCK_RETURN;
2730 AutoObserverNotifier notifier(aObserver, "mousescrollevent");
2731 if (mPopupContentView) {
2732 // Pass nullptr as the observer so that the AutoObserverNotification in
2733 // nsChildView::SynthesizeNativeMouseScrollEvent will be ignored.
2734 return mPopupContentView->SynthesizeNativeMouseScrollEvent(aPoint, aNativeMessage, aDeltaX,
2735 aDeltaY, aDeltaZ, aModifierFlags,
2736 aAdditionalFlags, nullptr);
2741 NS_OBJC_END_TRY_BLOCK_RETURN(NS_ERROR_FAILURE);
2744 void nsCocoaWindow::LockAspectRatio(bool aShouldLock) {
2745 NS_OBJC_BEGIN_TRY_IGNORE_BLOCK;
2748 [mWindow setContentAspectRatio:mWindow.frame.size];
2749 mAspectRatioLocked = true;
2751 // According to https://developer.apple.com/documentation/appkit/nswindow/1419507-aspectratio,
2752 // aspect ratios and resize increments are mutually exclusive, and the accepted way of
2753 // cancelling an established aspect ratio is to set the resize increments to 1.0, 1.0
2754 [mWindow setResizeIncrements:NSMakeSize(1.0, 1.0)];
2755 mAspectRatioLocked = false;
2758 NS_OBJC_END_TRY_IGNORE_BLOCK;
2761 void nsCocoaWindow::UpdateThemeGeometries(const nsTArray<ThemeGeometry>& aThemeGeometries) {
2762 NS_OBJC_BEGIN_TRY_IGNORE_BLOCK;
2764 if (mPopupContentView) {
2765 return mPopupContentView->UpdateThemeGeometries(aThemeGeometries);
2768 NS_OBJC_END_TRY_IGNORE_BLOCK;
2771 void nsCocoaWindow::SetPopupWindowLevel() {
2772 if (!mWindow) return;
2774 // Floating popups are at the floating level and hide when the window is
2776 if (mPopupLevel == PopupLevel::Floating) {
2777 [mWindow setLevel:NSFloatingWindowLevel];
2778 [mWindow setHidesOnDeactivate:YES];
2780 // Otherwise, this is a top-level or parent popup. Parent popups always
2781 // appear just above their parent and essentially ignore the level.
2782 [mWindow setLevel:NSPopUpMenuWindowLevel];
2783 [mWindow setHidesOnDeactivate:NO];
2787 void nsCocoaWindow::SetInputContext(const InputContext& aContext,
2788 const InputContextAction& aAction) {
2789 NS_OBJC_BEGIN_TRY_IGNORE_BLOCK;
2791 mInputContext = aContext;
2793 NS_OBJC_END_TRY_IGNORE_BLOCK;
2796 bool nsCocoaWindow::GetEditCommands(NativeKeyBindingsType aType, const WidgetKeyboardEvent& aEvent,
2797 nsTArray<CommandInt>& aCommands) {
2798 // Validate the arguments.
2799 if (NS_WARN_IF(!nsIWidget::GetEditCommands(aType, aEvent, aCommands))) {
2803 NativeKeyBindings* keyBindings = NativeKeyBindings::GetInstance(aType);
2804 // When the keyboard event is fired from this widget, it must mean that no web content has focus
2805 // because any web contents should be on `nsChildView`. And in any locales, the system UI is
2806 // always horizontal layout. So, let's pass `Nothing()` for the writing mode here, it won't be
2807 // treated as in a vertical content.
2808 keyBindings->GetEditCommands(aEvent, Nothing(), aCommands);
2812 void nsCocoaWindow::PauseOrResumeCompositor(bool aPause) {
2813 if (auto* mainChildView = static_cast<nsIWidget*>([[mWindow mainChildView] widget])) {
2814 mainChildView->PauseOrResumeCompositor(aPause);
2818 bool nsCocoaWindow::AsyncPanZoomEnabled() const {
2819 if (mPopupContentView) {
2820 return mPopupContentView->AsyncPanZoomEnabled();
2822 return nsBaseWidget::AsyncPanZoomEnabled();
2825 bool nsCocoaWindow::StartAsyncAutoscroll(const ScreenPoint& aAnchorLocation,
2826 const ScrollableLayerGuid& aGuid) {
2827 if (mPopupContentView) {
2828 return mPopupContentView->StartAsyncAutoscroll(aAnchorLocation, aGuid);
2830 return nsBaseWidget::StartAsyncAutoscroll(aAnchorLocation, aGuid);
2833 void nsCocoaWindow::StopAsyncAutoscroll(const ScrollableLayerGuid& aGuid) {
2834 if (mPopupContentView) {
2835 mPopupContentView->StopAsyncAutoscroll(aGuid);
2838 nsBaseWidget::StopAsyncAutoscroll(aGuid);
2841 already_AddRefed<nsIWidget> nsIWidget::CreateTopLevelWindow() {
2842 nsCOMPtr<nsIWidget> window = new nsCocoaWindow();
2843 return window.forget();
2846 already_AddRefed<nsIWidget> nsIWidget::CreateChildWindow() {
2847 nsCOMPtr<nsIWidget> window = new nsChildView();
2848 return window.forget();
2851 @implementation WindowDelegate
2853 // We try to find a gecko menu bar to paint. If one does not exist, just paint
2854 // the application menu by itself so that a window doesn't have some other
2855 // window's menu bar.
2856 + (void)paintMenubarForWindow:(NSWindow*)aWindow {
2857 NS_OBJC_BEGIN_TRY_IGNORE_BLOCK;
2859 // make sure we only act on windows that have this kind of
2860 // object as a delegate
2861 id windowDelegate = [aWindow delegate];
2862 if ([windowDelegate class] != [self class]) return;
2864 nsCocoaWindow* geckoWidget = [windowDelegate geckoWidget];
2865 NS_ASSERTION(geckoWidget, "Window delegate not returning a gecko widget!");
2867 nsMenuBarX* geckoMenuBar = geckoWidget->GetMenuBar();
2869 geckoMenuBar->Paint();
2871 // sometimes we don't have a native application menu early in launching
2872 if (!sApplicationMenu) return;
2874 NSMenu* mainMenu = [NSApp mainMenu];
2875 NS_ASSERTION([mainMenu numberOfItems] > 0,
2876 "Main menu does not have any items, something is terribly wrong!");
2878 // Create a new menu bar.
2879 // We create a GeckoNSMenu because all menu bar NSMenu objects should use that subclass for
2880 // key handling reasons.
2881 GeckoNSMenu* newMenuBar = [[GeckoNSMenu alloc] initWithTitle:@"MainMenuBar"];
2883 // move the application menu from the existing menu bar to the new one
2884 NSMenuItem* firstMenuItem = [[mainMenu itemAtIndex:0] retain];
2885 [mainMenu removeItemAtIndex:0];
2886 [newMenuBar insertItem:firstMenuItem atIndex:0];
2887 [firstMenuItem release];
2889 // set our new menu bar as the main menu
2890 [NSApp setMainMenu:newMenuBar];
2891 [newMenuBar release];
2894 NS_OBJC_END_TRY_IGNORE_BLOCK;
2897 - (id)initWithGeckoWindow:(nsCocoaWindow*)geckoWind {
2898 NS_OBJC_BEGIN_TRY_BLOCK_RETURN;
2901 mGeckoWindow = geckoWind;
2902 mToplevelActiveState = false;
2903 mHasEverBeenZoomed = false;
2906 NS_OBJC_END_TRY_BLOCK_RETURN(nil);
2909 - (NSSize)windowWillResize:(NSWindow*)sender toSize:(NSSize)proposedFrameSize {
2911 return proposedFrameSize;
2914 - (NSRect)windowWillUseStandardFrame:(NSWindow*)window defaultFrame:(NSRect)newFrame {
2915 // This function needs to return a rect representing the frame a window would
2916 // have if it is in its "maximized" size mode. The parameter newFrame is supposed
2917 // to be a frame representing the maximum window size on the screen where the
2918 // window currently appears. However, in practice, newFrame can be a much smaller
2919 // size. So, we ignore newframe and instead return the frame of the entire screen
2920 // associated with the window. That frame is bigger than the window could actually
2921 // be, due to the presence of the menubar and possibly the dock, but we never call
2922 // this function directly, and Cocoa callers will shrink it to its true maximum
2924 return window.screen.frame;
2927 void nsCocoaWindow::CocoaSendToplevelActivateEvents() {
2928 if (mWidgetListener) {
2929 mWidgetListener->WindowActivated();
2933 void nsCocoaWindow::CocoaSendToplevelDeactivateEvents() {
2934 if (mWidgetListener) {
2935 mWidgetListener->WindowDeactivated();
2939 void nsCocoaWindow::CocoaWindowDidResize() {
2940 // It's important to update our bounds before we trigger any listeners. This
2941 // ensures that our bounds are correct when GetScreenBounds is called.
2944 if (HandleUpdateFullscreenOnResize()) {
2949 // Resizing might have changed our zoom state.
2950 DispatchSizeModeEvent();
2954 - (void)windowDidResize:(NSNotification*)aNotification {
2955 BaseWindow* window = [aNotification object];
2956 [window updateTrackingArea];
2958 if (!mGeckoWindow) return;
2960 mGeckoWindow->CocoaWindowDidResize();
2963 - (void)windowDidChangeScreen:(NSNotification*)aNotification {
2964 if (!mGeckoWindow) return;
2966 // Because of Cocoa's peculiar treatment of zero-size windows (see comments
2967 // at GetBackingScaleFactor() above), we sometimes have a situation where
2968 // our concept of backing scale (based on the screen where the zero-sized
2969 // window is positioned) differs from Cocoa's idea (always based on the
2970 // Retina screen, AFAICT, even when an external non-Retina screen is the
2971 // primary display).
2973 // As a result, if the window was created with zero size on an external
2974 // display, but then made visible on the (secondary) Retina screen, we
2975 // will *not* get a windowDidChangeBackingProperties notification for it.
2976 // This leads to an incorrect GetDefaultScale(), and widget coordinate
2977 // confusion, as per bug 853252.
2979 // To work around this, we check for a backing scale mismatch when we
2980 // receive a windowDidChangeScreen notification, as we will receive this
2981 // even if Cocoa was already treating the zero-size window as having
2982 // Retina backing scale.
2983 NSWindow* window = (NSWindow*)[aNotification object];
2984 if ([window respondsToSelector:@selector(backingScaleFactor)]) {
2985 if (GetBackingScaleFactor(window) != mGeckoWindow->BackingScaleFactor()) {
2986 mGeckoWindow->BackingScaleFactorChanged();
2990 mGeckoWindow->ReportMoveEvent();
2993 - (void)windowWillEnterFullScreen:(NSNotification*)notification {
2994 if (!mGeckoWindow) {
2997 mGeckoWindow->CocoaWindowWillEnterFullscreen(true);
3000 // Lion's full screen mode will bypass our internal fullscreen tracking, so
3001 // we need to catch it when we transition and call our own methods, which in
3002 // turn will fire "fullscreen" events.
3003 - (void)windowDidEnterFullScreen:(NSNotification*)notification {
3004 // On Yosemite, the NSThemeFrame class has two new properties --
3005 // titlebarView (an NSTitlebarView object) and titlebarContainerView (an
3006 // NSTitlebarContainerView object). These are used to display the titlebar
3007 // in fullscreen mode. In Safari they're not transparent. But in Firefox
3008 // for some reason they are, which causes bug 1069658. The following code
3009 // works around this Apple bug or design flaw.
3010 NSWindow* window = (NSWindow*)[notification object];
3011 NSView* frameView = [[window contentView] superview];
3012 NSView* titlebarView = nil;
3013 NSView* titlebarContainerView = nil;
3014 if ([frameView respondsToSelector:@selector(titlebarView)]) {
3015 titlebarView = [frameView titlebarView];
3017 if ([frameView respondsToSelector:@selector(titlebarContainerView)]) {
3018 titlebarContainerView = [frameView titlebarContainerView];
3020 if ([titlebarView respondsToSelector:@selector(setTransparent:)]) {
3021 [titlebarView setTransparent:NO];
3023 if ([titlebarContainerView respondsToSelector:@selector(setTransparent:)]) {
3024 [titlebarContainerView setTransparent:NO];
3027 if (!mGeckoWindow) {
3030 mGeckoWindow->CocoaWindowDidEnterFullscreen(true);
3033 - (void)windowWillExitFullScreen:(NSNotification*)notification {
3034 if (!mGeckoWindow) {
3037 mGeckoWindow->CocoaWindowWillEnterFullscreen(false);
3040 - (void)windowDidExitFullScreen:(NSNotification*)notification {
3041 if (!mGeckoWindow) {
3044 mGeckoWindow->CocoaWindowDidEnterFullscreen(false);
3047 - (void)windowDidFailToEnterFullScreen:(NSWindow*)window {
3048 if (!mGeckoWindow) {
3051 mGeckoWindow->CocoaWindowDidFailFullscreen(true);
3054 - (void)windowDidFailToExitFullScreen:(NSWindow*)window {
3055 if (!mGeckoWindow) {
3058 mGeckoWindow->CocoaWindowDidFailFullscreen(false);
3061 - (void)windowDidBecomeMain:(NSNotification*)aNotification {
3062 NS_OBJC_BEGIN_TRY_IGNORE_BLOCK;
3065 ChildViewMouseTracker::ReEvaluateMouseEnterState();
3067 // [NSApp _isRunningAppModal] will return true if we're running an OS dialog
3068 // app modally. If one of those is up then we want it to retain its menu bar.
3069 if ([NSApp _isRunningAppModal]) return;
3070 NSWindow* window = [aNotification object];
3071 if (window) [WindowDelegate paintMenubarForWindow:window];
3073 if ([window isKindOfClass:[ToolbarWindow class]]) {
3074 [(ToolbarWindow*)window windowMainStateChanged];
3077 NS_OBJC_END_TRY_IGNORE_BLOCK;
3080 - (void)windowDidResignMain:(NSNotification*)aNotification {
3082 ChildViewMouseTracker::ReEvaluateMouseEnterState();
3084 // [NSApp _isRunningAppModal] will return true if we're running an OS dialog
3085 // app modally. If one of those is up then we want it to retain its menu bar.
3086 if ([NSApp _isRunningAppModal]) return;
3087 RefPtr<nsMenuBarX> hiddenWindowMenuBar = nsMenuUtilsX::GetHiddenWindowMenuBar();
3088 if (hiddenWindowMenuBar) {
3089 // printf("painting hidden window menu bar due to window losing main status\n");
3090 hiddenWindowMenuBar->Paint();
3093 NSWindow* window = [aNotification object];
3094 if ([window isKindOfClass:[ToolbarWindow class]]) {
3095 [(ToolbarWindow*)window windowMainStateChanged];
3099 - (void)windowDidBecomeKey:(NSNotification*)aNotification {
3100 NS_OBJC_BEGIN_TRY_IGNORE_BLOCK;
3103 ChildViewMouseTracker::ReEvaluateMouseEnterState();
3105 NSWindow* window = [aNotification object];
3106 if ([window isSheet]) [WindowDelegate paintMenubarForWindow:window];
3108 nsChildView* mainChildView =
3109 static_cast<nsChildView*>([[(BaseWindow*)window mainChildView] widget]);
3110 if (mainChildView) {
3111 if (mainChildView->GetInputContext().IsPasswordEditor()) {
3112 TextInputHandler::EnableSecureEventInput();
3114 TextInputHandler::EnsureSecureEventInputDisabled();
3118 NS_OBJC_END_TRY_IGNORE_BLOCK;
3121 - (void)windowDidResignKey:(NSNotification*)aNotification {
3122 NS_OBJC_BEGIN_TRY_IGNORE_BLOCK;
3124 RollUpPopups(nsIRollupListener::AllowAnimations::No);
3126 ChildViewMouseTracker::ReEvaluateMouseEnterState();
3128 // If a sheet just resigned key then we should paint the menu bar
3129 // for whatever window is now main.
3130 NSWindow* window = [aNotification object];
3131 if ([window isSheet]) [WindowDelegate paintMenubarForWindow:[NSApp mainWindow]];
3133 TextInputHandler::EnsureSecureEventInputDisabled();
3135 NS_OBJC_END_TRY_IGNORE_BLOCK;
3138 - (void)windowWillMove:(NSNotification*)aNotification {
3142 - (void)windowDidMove:(NSNotification*)aNotification {
3143 if (mGeckoWindow) mGeckoWindow->ReportMoveEvent();
3146 - (BOOL)windowShouldClose:(id)sender {
3147 nsIWidgetListener* listener = mGeckoWindow ? mGeckoWindow->GetWidgetListener() : nullptr;
3148 if (listener) listener->RequestWindowClose(mGeckoWindow);
3149 return NO; // gecko will do it
3152 - (void)windowWillClose:(NSNotification*)aNotification {
3156 - (void)windowWillMiniaturize:(NSNotification*)aNotification {
3160 - (void)windowDidMiniaturize:(NSNotification*)aNotification {
3161 if (!mGeckoWindow) {
3164 mGeckoWindow->FinishCurrentTransitionIfMatching(nsCocoaWindow::TransitionType::Miniaturize);
3167 - (void)windowDidDeminiaturize:(NSNotification*)aNotification {
3168 if (!mGeckoWindow) {
3171 mGeckoWindow->FinishCurrentTransitionIfMatching(nsCocoaWindow::TransitionType::Deminiaturize);
3174 - (BOOL)windowShouldZoom:(NSWindow*)window toFrame:(NSRect)proposedFrame {
3175 if (!mHasEverBeenZoomed && [window isZoomed]) return NO; // See bug 429954.
3177 mHasEverBeenZoomed = YES;
3181 - (NSRect)window:(NSWindow*)window willPositionSheet:(NSWindow*)sheet usingRect:(NSRect)rect {
3182 if ([window isKindOfClass:[ToolbarWindow class]]) {
3183 rect.origin.y = [(ToolbarWindow*)window sheetAttachmentPosition];
3188 #ifdef MOZ_THUNDERBIRD
3189 - (void)didEndSheet:(NSWindow*)sheet returnCode:(int)returnCode contextInfo:(void*)contextInfo {
3190 NS_OBJC_BEGIN_TRY_ABORT_BLOCK;
3192 // Note: 'contextInfo' (if it is set) is the window that is the parent of
3193 // the sheet. The value of contextInfo is determined in
3194 // nsCocoaWindow::Show(). If it's set, 'contextInfo' is always the top-
3195 // level window, not another sheet itself. But 'contextInfo' is nil if
3196 // our parent window is also a sheet -- in that case we shouldn't send
3197 // the top-level window any activate events (because it's our parent
3198 // window that needs to get these events, not the top-level window).
3199 [TopLevelWindowData deactivateInWindow:sheet];
3200 [sheet orderOut:self];
3201 if (contextInfo) [TopLevelWindowData activateInWindow:(NSWindow*)contextInfo];
3203 NS_OBJC_END_TRY_ABORT_BLOCK;
3207 - (void)windowDidChangeBackingProperties:(NSNotification*)aNotification {
3208 NS_OBJC_BEGIN_TRY_IGNORE_BLOCK;
3210 NSWindow* window = (NSWindow*)[aNotification object];
3212 if ([window respondsToSelector:@selector(backingScaleFactor)]) {
3214 [[[aNotification userInfo] objectForKey:@"NSBackingPropertyOldScaleFactorKey"] doubleValue];
3215 if ([window backingScaleFactor] != oldFactor) {
3216 mGeckoWindow->BackingScaleFactorChanged();
3220 NS_OBJC_END_TRY_IGNORE_BLOCK;
3223 // This method is on NSWindowDelegate starting with 10.9
3224 - (void)windowDidChangeOcclusionState:(NSNotification*)aNotification {
3226 mGeckoWindow->DispatchOcclusionEvent();
3230 - (nsCocoaWindow*)geckoWidget {
3231 return mGeckoWindow;
3234 - (bool)toplevelActiveState {
3235 return mToplevelActiveState;
3238 - (void)sendToplevelActivateEvents {
3239 if (!mToplevelActiveState && mGeckoWindow) {
3240 mGeckoWindow->CocoaSendToplevelActivateEvents();
3242 mToplevelActiveState = true;
3246 - (void)sendToplevelDeactivateEvents {
3247 if (mToplevelActiveState && mGeckoWindow) {
3248 mGeckoWindow->CocoaSendToplevelDeactivateEvents();
3249 mToplevelActiveState = false;
3255 @interface NSView (FrameViewMethodSwizzling)
3256 - (NSPoint)FrameView__closeButtonOrigin;
3257 - (CGFloat)FrameView__titlebarHeight;
3260 @implementation NSView (FrameViewMethodSwizzling)
3262 - (NSPoint)FrameView__closeButtonOrigin {
3263 if (![self.window isKindOfClass:[ToolbarWindow class]]) {
3264 return self.FrameView__closeButtonOrigin;
3266 ToolbarWindow* win = (ToolbarWindow*)[self window];
3267 if (win.drawsContentsIntoWindowFrame && !(win.styleMask & NSWindowStyleMaskFullScreen) &&
3268 (win.styleMask & NSWindowStyleMaskTitled)) {
3269 const NSRect buttonsRect = win.windowButtonsRect;
3270 if (NSIsEmptyRect(buttonsRect)) {
3271 // Empty rect. Let's hide the buttons.
3272 // Position is in non-flipped window coordinates. Using frame's height
3273 // for the vertical coordinate will move the buttons above the window,
3274 // making them invisible.
3275 return NSMakePoint(buttonsRect.origin.x, win.frame.size.height);
3276 } else if (win.windowTitlebarLayoutDirection == NSUserInterfaceLayoutDirectionRightToLeft) {
3277 // We're in RTL mode, which means that the close button is the rightmost
3278 // button of the three window buttons. and buttonsRect.origin is the
3279 // bottom left corner of the green (zoom) button. The close button is 40px
3280 // to the right of the zoom button. This is confirmed to be the same on
3281 // all macOS versions between 10.12 - 12.0.
3282 return NSMakePoint(buttonsRect.origin.x + 40.0f, buttonsRect.origin.y);
3284 return buttonsRect.origin;
3286 return self.FrameView__closeButtonOrigin;
3289 - (CGFloat)FrameView__titlebarHeight {
3290 CGFloat height = [self FrameView__titlebarHeight];
3291 if ([[self window] isKindOfClass:[ToolbarWindow class]]) {
3292 // Make sure that the titlebar height includes our shifted buttons.
3293 // The following coordinates are in window space, with the origin being at the bottom left
3294 // corner of the window.
3295 ToolbarWindow* win = (ToolbarWindow*)[self window];
3296 CGFloat frameHeight = [self frame].size.height;
3297 CGFloat windowButtonY = frameHeight;
3298 if (!NSIsEmptyRect(win.windowButtonsRect) && win.drawsContentsIntoWindowFrame &&
3299 !(win.styleMask & NSWindowStyleMaskFullScreen) &&
3300 (win.styleMask & NSWindowStyleMaskTitled)) {
3301 windowButtonY = win.windowButtonsRect.origin.y;
3303 height = std::max(height, frameHeight - windowButtonY);
3310 static NSMutableSet* gSwizzledFrameViewClasses = nil;
3312 @interface NSWindow (PrivateSetNeedsDisplayInRectMethod)
3313 - (void)_setNeedsDisplayInRect:(NSRect)aRect;
3316 @interface NSView (NSVisualEffectViewSetMaskImage)
3317 - (void)setMaskImage:(NSImage*)image;
3320 @interface BaseWindow (Private)
3321 - (void)removeTrackingArea;
3322 - (void)cursorUpdated:(NSEvent*)aEvent;
3323 - (void)reflowTitlebarElements;
3326 @implementation BaseWindow
3328 // The frame of a window is implemented using undocumented NSView subclasses.
3329 // We offset the window buttons by overriding the method _closeButtonOrigin on
3330 // these frame view classes. The class which is
3331 // used for a window is determined in the window's frameViewClassForStyleMask:
3332 // method, so this is where we make sure that we have swizzled the method on
3333 // all encountered classes.
3334 + (Class)frameViewClassForStyleMask:(NSUInteger)styleMask {
3335 Class frameViewClass = [super frameViewClassForStyleMask:styleMask];
3337 if (!gSwizzledFrameViewClasses) {
3338 gSwizzledFrameViewClasses = [[NSMutableSet setWithCapacity:3] retain];
3339 if (!gSwizzledFrameViewClasses) {
3340 return frameViewClass;
3344 static IMP our_closeButtonOrigin =
3345 class_getMethodImplementation([NSView class], @selector(FrameView__closeButtonOrigin));
3346 static IMP our_titlebarHeight =
3347 class_getMethodImplementation([NSView class], @selector(FrameView__titlebarHeight));
3349 if (![gSwizzledFrameViewClasses containsObject:frameViewClass]) {
3350 // Either of these methods might be implemented in both a subclass of
3351 // NSFrameView and one of its own subclasses. Which means that if we
3352 // aren't careful we might end up swizzling the same method twice.
3353 // Since method swizzling involves swapping pointers, this would break
3355 IMP _closeButtonOrigin =
3356 class_getMethodImplementation(frameViewClass, @selector(_closeButtonOrigin));
3357 if (_closeButtonOrigin && _closeButtonOrigin != our_closeButtonOrigin) {
3358 nsToolkit::SwizzleMethods(frameViewClass, @selector(_closeButtonOrigin),
3359 @selector(FrameView__closeButtonOrigin));
3362 // Override _titlebarHeight so that the floating titlebar doesn't clip the bottom of the
3363 // window buttons which we move down with our override of _closeButtonOrigin.
3364 IMP _titlebarHeight = class_getMethodImplementation(frameViewClass, @selector(_titlebarHeight));
3365 if (_titlebarHeight && _titlebarHeight != our_titlebarHeight) {
3366 nsToolkit::SwizzleMethods(frameViewClass, @selector(_titlebarHeight),
3367 @selector(FrameView__titlebarHeight));
3370 [gSwizzledFrameViewClasses addObject:frameViewClass];
3373 return frameViewClass;
3376 - (id)initWithContentRect:(NSRect)aContentRect
3377 styleMask:(NSUInteger)aStyle
3378 backing:(NSBackingStoreType)aBufferingType
3380 mDrawsIntoWindowFrame = NO;
3381 [super initWithContentRect:aContentRect styleMask:aStyle backing:aBufferingType defer:aFlag];
3383 mDisabledNeedsDisplay = NO;
3384 mTrackingArea = nil;
3385 mDirtyRect = NSZeroRect;
3390 mIsAnimationSuppressed = NO;
3391 [self updateTrackingArea];
3396 // Returns an autoreleased NSImage.
3397 static NSImage* GetMenuMaskImage() {
3398 CGFloat radius = 4.0f;
3399 NSEdgeInsets insets = {5, 5, 5, 5};
3400 NSSize maskSize = {12, 12};
3401 NSImage* maskImage = [NSImage imageWithSize:maskSize
3403 drawingHandler:^BOOL(NSRect dstRect) {
3404 NSBezierPath* path =
3405 [NSBezierPath bezierPathWithRoundedRect:dstRect
3408 [[NSColor colorWithDeviceWhite:1.0 alpha:1.0] set];
3412 [maskImage setCapInsets:insets];
3416 - (void)swapOutChildViewWrapper:(NSView*)aNewWrapper {
3417 [aNewWrapper setFrame:[[self contentView] frame]];
3418 NSView* childView = [[self mainChildView] retain];
3419 [childView removeFromSuperview];
3420 [aNewWrapper addSubview:childView];
3421 [childView release];
3422 [super setContentView:aNewWrapper];
3425 - (void)setUseMenuStyle:(BOOL)aValue {
3426 if (aValue && !mUseMenuStyle) {
3427 // Turn on rounded corner masking.
3428 NSView* effectView = VibrancyManager::CreateEffectView(VibrancyType::MENU, YES);
3429 [effectView setMaskImage:GetMenuMaskImage()];
3430 [self swapOutChildViewWrapper:effectView];
3431 [effectView release];
3432 } else if (mUseMenuStyle && !aValue) {
3433 // Turn off rounded corner masking.
3434 NSView* wrapper = [[NSView alloc] initWithFrame:NSZeroRect];
3435 [wrapper setWantsLayer:YES];
3436 [self swapOutChildViewWrapper:wrapper];
3439 mUseMenuStyle = aValue;
3442 - (NSTouchBar*)makeTouchBar {
3443 mTouchBar = [[nsTouchBar alloc] init];
3445 sTouchBarIsInitialized = YES;
3450 - (void)setBeingShown:(BOOL)aValue {
3451 mBeingShown = aValue;
3454 - (BOOL)isBeingShown {
3458 - (BOOL)isVisibleOrBeingShown {
3459 return [super isVisible] || mBeingShown;
3462 - (void)setIsAnimationSuppressed:(BOOL)aValue {
3463 mIsAnimationSuppressed = aValue;
3466 - (BOOL)isAnimationSuppressed {
3467 return mIsAnimationSuppressed;
3470 - (void)disableSetNeedsDisplay {
3471 mDisabledNeedsDisplay = YES;
3474 - (void)enableSetNeedsDisplay {
3475 mDisabledNeedsDisplay = NO;
3479 [mTouchBar release];
3480 [self removeTrackingArea];
3481 ChildViewMouseTracker::OnDestroyWindow(self);
3485 static const NSString* kStateTitleKey = @"title";
3486 static const NSString* kStateDrawsContentsIntoWindowFrameKey = @"drawsContentsIntoWindowFrame";
3487 static const NSString* kStateShowsToolbarButton = @"showsToolbarButton";
3488 static const NSString* kStateCollectionBehavior = @"collectionBehavior";
3489 static const NSString* kStateWantsTitleDrawn = @"wantsTitleDrawn";
3491 - (void)importState:(NSDictionary*)aState {
3492 if (NSString* title = [aState objectForKey:kStateTitleKey]) {
3493 [self setTitle:title];
3495 [self setDrawsContentsIntoWindowFrame:[[aState objectForKey:kStateDrawsContentsIntoWindowFrameKey]
3497 [self setShowsToolbarButton:[[aState objectForKey:kStateShowsToolbarButton] boolValue]];
3498 [self setCollectionBehavior:[[aState objectForKey:kStateCollectionBehavior] unsignedIntValue]];
3499 [self setWantsTitleDrawn:[[aState objectForKey:kStateWantsTitleDrawn] boolValue]];
3502 - (NSMutableDictionary*)exportState {
3503 NSMutableDictionary* state = [NSMutableDictionary dictionaryWithCapacity:10];
3504 if (NSString* title = [self title]) {
3505 [state setObject:title forKey:kStateTitleKey];
3507 [state setObject:[NSNumber numberWithBool:[self drawsContentsIntoWindowFrame]]
3508 forKey:kStateDrawsContentsIntoWindowFrameKey];
3509 [state setObject:[NSNumber numberWithBool:[self showsToolbarButton]]
3510 forKey:kStateShowsToolbarButton];
3511 [state setObject:[NSNumber numberWithUnsignedInt:[self collectionBehavior]]
3512 forKey:kStateCollectionBehavior];
3513 [state setObject:[NSNumber numberWithBool:[self wantsTitleDrawn]] forKey:kStateWantsTitleDrawn];
3517 - (void)setDrawsContentsIntoWindowFrame:(BOOL)aState {
3518 bool changed = (aState != mDrawsIntoWindowFrame);
3519 mDrawsIntoWindowFrame = aState;
3521 [self reflowTitlebarElements];
3525 - (BOOL)drawsContentsIntoWindowFrame {
3526 return mDrawsIntoWindowFrame;
3529 - (NSRect)childViewRectForFrameRect:(NSRect)aFrameRect {
3530 if (mDrawsIntoWindowFrame) {
3533 NSUInteger styleMask = [self styleMask];
3534 styleMask &= ~NSWindowStyleMaskFullSizeContentView;
3535 return [NSWindow contentRectForFrameRect:aFrameRect styleMask:styleMask];
3538 - (NSRect)frameRectForChildViewRect:(NSRect)aChildViewRect {
3539 if (mDrawsIntoWindowFrame) {
3540 return aChildViewRect;
3542 NSUInteger styleMask = [self styleMask];
3543 styleMask &= ~NSWindowStyleMaskFullSizeContentView;
3544 return [NSWindow frameRectForContentRect:aChildViewRect styleMask:styleMask];
3547 - (NSTimeInterval)animationResizeTime:(NSRect)newFrame {
3548 if (mIsAnimationSuppressed) {
3549 // Should not animate the initial session-restore size change
3553 return [super animationResizeTime:newFrame];
3556 - (void)setWantsTitleDrawn:(BOOL)aDrawTitle {
3557 mDrawTitle = aDrawTitle;
3558 [self setTitleVisibility:mDrawTitle ? NSWindowTitleVisible : NSWindowTitleHidden];
3561 - (BOOL)wantsTitleDrawn {
3565 - (NSView*)trackingAreaView {
3566 NSView* contentView = [self contentView];
3567 return [contentView superview] ? [contentView superview] : contentView;
3570 - (NSArray<NSView*>*)contentViewContents {
3571 return [[[[self contentView] subviews] copy] autorelease];
3574 - (ChildView*)mainChildView {
3575 NSView* contentView = [self contentView];
3576 NSView* lastView = [[contentView subviews] lastObject];
3577 if ([lastView isKindOfClass:[ChildView class]]) {
3578 return (ChildView*)lastView;
3583 - (void)removeTrackingArea {
3584 if (mTrackingArea) {
3585 [[self trackingAreaView] removeTrackingArea:mTrackingArea];
3586 [mTrackingArea release];
3587 mTrackingArea = nil;
3591 - (void)updateTrackingArea {
3592 [self removeTrackingArea];
3594 NSView* view = [self trackingAreaView];
3595 const NSTrackingAreaOptions options =
3596 NSTrackingMouseEnteredAndExited | NSTrackingMouseMoved | NSTrackingActiveAlways;
3597 mTrackingArea = [[NSTrackingArea alloc] initWithRect:[view bounds]
3601 [view addTrackingArea:mTrackingArea];
3604 - (void)mouseEntered:(NSEvent*)aEvent {
3605 ChildViewMouseTracker::MouseEnteredWindow(aEvent);
3608 - (void)mouseExited:(NSEvent*)aEvent {
3609 ChildViewMouseTracker::MouseExitedWindow(aEvent);
3612 - (void)mouseMoved:(NSEvent*)aEvent {
3613 ChildViewMouseTracker::MouseMoved(aEvent);
3616 - (void)cursorUpdated:(NSEvent*)aEvent {
3617 // Nothing to do here, but NSTrackingArea wants us to implement this method.
3620 - (void)_setNeedsDisplayInRect:(NSRect)aRect {
3621 // Prevent unnecessary invalidations due to moving NSViews (e.g. for plugins)
3622 if (!mDisabledNeedsDisplay) {
3623 // This method is only called by Cocoa, so when we're here, we know that
3624 // it's available and don't need to check whether our superclass responds
3626 [super _setNeedsDisplayInRect:aRect];
3627 mDirtyRect = NSUnionRect(mDirtyRect, aRect);
3631 - (NSRect)getAndResetNativeDirtyRect {
3632 NSRect dirtyRect = mDirtyRect;
3633 mDirtyRect = NSZeroRect;
3637 // Possibly move the titlebar buttons.
3638 - (void)reflowTitlebarElements {
3639 NSView* frameView = [[self contentView] superview];
3640 if ([frameView respondsToSelector:@selector(_tileTitlebarAndRedisplay:)]) {
3641 [frameView _tileTitlebarAndRedisplay:NO];
3645 - (BOOL)respondsToSelector:(SEL)aSelector {
3646 // Claim the window doesn't respond to this so that the system
3647 // doesn't steal keyboard equivalents for it. Bug 613710.
3648 if (aSelector == @selector(cancelOperation:)) {
3652 return [super respondsToSelector:aSelector];
3655 - (void)doCommandBySelector:(SEL)aSelector {
3656 // We override this so that it won't beep if it can't act.
3657 // We want to control the beeping for missing or disabled
3658 // commands ourselves.
3659 [self tryToPerform:aSelector with:nil];
3662 - (id)accessibilityAttributeValue:(NSString*)attribute {
3663 NS_OBJC_BEGIN_TRY_BLOCK_RETURN;
3665 id retval = [super accessibilityAttributeValue:attribute];
3667 // The following works around a problem with Text-to-Speech on OS X 10.7.
3668 // See bug 674612 for more info.
3670 // When accessibility is off, AXUIElementCopyAttributeValue(), when called
3671 // on an AXApplication object to get its AXFocusedUIElement attribute,
3672 // always returns an AXWindow object (the actual browser window -- never a
3673 // mozAccessible object). This also happens with accessibility turned on,
3674 // if no other object in the browser window has yet been focused. But if
3675 // the browser window has a title bar (as it currently always does), the
3676 // AXWindow object will always have four "accessible" children, one of which
3677 // is an AXStaticText object (the title bar's "title"; the other three are
3678 // the close, minimize and zoom buttons). This means that (for complicated
3679 // reasons, for which see bug 674612) Text-to-Speech on OS X 10.7 will often
3680 // "speak" the window title, no matter what text is selected, or even if no
3681 // text at all is selected. (This always happens when accessibility is off.
3682 // It doesn't happen in Firefox releases because Apple has (on OS X 10.7)
3683 // special-cased the handling of apps whose CFBundleIdentifier is
3684 // org.mozilla.firefox.)
3686 // We work around this problem by only returning AXChildren that are
3687 // mozAccessible object or are one of the titlebar's buttons (which
3688 // instantiate subclasses of NSButtonCell).
3689 if ([retval isKindOfClass:[NSArray class]] && [attribute isEqualToString:@"AXChildren"]) {
3690 NSMutableArray* holder = [NSMutableArray arrayWithCapacity:10];
3691 [holder addObjectsFromArray:(NSArray*)retval];
3692 NSUInteger count = [holder count];
3693 for (NSInteger i = count - 1; i >= 0; --i) {
3694 id item = [holder objectAtIndex:i];
3695 // Remove anything from holder that isn't one of the titlebar's buttons
3696 // (which instantiate subclasses of NSButtonCell) or a mozAccessible
3697 // object (or one of its subclasses).
3698 if (![item isKindOfClass:[NSButtonCell class]] &&
3699 ![item respondsToSelector:@selector(hasRepresentedView)]) {
3700 [holder removeObjectAtIndex:i];
3703 retval = [NSArray arrayWithArray:holder];
3708 NS_OBJC_END_TRY_BLOCK_RETURN(nil);
3711 - (void)releaseJSObjects {
3712 [mTouchBar releaseJSObjects];
3717 @interface NSView (NSThemeFrame)
3718 - (void)_drawTitleStringInClip:(NSRect)aRect;
3719 - (void)_maskCorners:(NSUInteger)aFlags clipRect:(NSRect)aRect;
3722 @implementation MOZTitlebarView
3724 - (instancetype)initWithFrame:(NSRect)aFrame {
3725 self = [super initWithFrame:aFrame];
3727 self.material = NSVisualEffectMaterialTitlebar;
3728 self.blendingMode = NSVisualEffectBlendingModeWithinWindow;
3730 // Add a separator line at the bottom of the titlebar. NSBoxSeparator isn't a perfect match for
3731 // a native titlebar separator, but it's better than nothing.
3732 // We really want the appearance that _NSTitlebarDecorationView creates with the help of CoreUI,
3733 // but there's no public API for that.
3734 NSBox* separatorLine = [[NSBox alloc] initWithFrame:NSMakeRect(0, 0, aFrame.size.width, 1)];
3735 separatorLine.autoresizingMask = NSViewWidthSizable | NSViewMaxYMargin;
3736 separatorLine.boxType = NSBoxSeparator;
3737 [self addSubview:separatorLine];
3738 [separatorLine release];
3743 - (BOOL)mouseDownCanMoveWindow {
3747 - (void)mouseUp:(NSEvent*)event {
3748 if ([event clickCount] == 2) {
3749 // Handle titlebar double click. We don't get the window's default behavior here because the
3750 // window uses NSWindowStyleMaskFullSizeContentView, and this view (the titlebar gradient view)
3751 // is technically part of the window "contents" (it's a subview of the content view).
3752 if (nsCocoaUtils::ShouldZoomOnTitlebarDoubleClick()) {
3753 [[self window] performZoom:nil];
3754 } else if (nsCocoaUtils::ShouldMinimizeOnTitlebarDoubleClick()) {
3755 [[self window] performMiniaturize:nil];
3762 @interface MOZTitlebarAccessoryView : NSView
3765 @implementation MOZTitlebarAccessoryView : NSView
3766 - (void)viewWillMoveToWindow:(NSWindow*)aWindow {
3768 // When entering full screen mode, titlebar accessory views are inserted
3769 // into a floating NSWindow which houses the window titlebar and toolbars.
3770 // In order to work around a drawing bug with titlebarAppearsTransparent
3771 // windows in full screen mode, disable titlebar separators for all
3772 // NSWindows that this view is used in, including the floating full screen
3773 // toolbar window. The drawing bug was filed as FB9056136. See bug 1700211
3774 // for more details.
3775 #if !defined(MAC_OS_VERSION_11_0) || MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_VERSION_11_0
3776 if (nsCocoaFeatures::OnBigSurOrLater()) {
3778 if (@available(macOS 11.0, *)) {
3780 aWindow.titlebarSeparatorStyle = NSTitlebarSeparatorStyleNone;
3786 @implementation FullscreenTitlebarTracker
3787 - (FullscreenTitlebarTracker*)init {
3789 self.view = [[[MOZTitlebarAccessoryView alloc] initWithFrame:NSZeroRect] autorelease];
3795 // This class allows us to exercise control over the window's title bar. It is
3796 // used for all windows with titlebars.
3798 // ToolbarWindow supports two modes:
3799 // - drawsContentsIntoWindowFrame mode: In this mode, the Gecko ChildView is
3800 // sized to cover the entire window frame and manages titlebar drawing.
3801 // - separate titlebar mode, with support for unified toolbars: In this mode,
3802 // the Gecko ChildView does not extend into the titlebar. However, this
3803 // window's content view (which is the ChildView's superview) *does* extend
3804 // into the titlebar. Moreover, in this mode, we place a MOZTitlebarView
3805 // in the content view, as a sibling of the ChildView.
3807 // The "separate titlebar mode" supports the "unified toolbar" look:
3808 // If there's a toolbar right below the titlebar, the two can "connect" and
3809 // form a single gradient without a separator line in between.
3811 // The following mechanism communicates the height of the unified toolbar to
3812 // the ToolbarWindow:
3814 // 1) In the style sheet we set the toolbar's -moz-appearance to toolbar.
3815 // 2) When the toolbar is visible and we paint the application chrome
3816 // window, the array that Gecko passes nsChildView::UpdateThemeGeometries
3817 // will contain an entry for the widget type StyleAppearance::Toolbar.
3818 // 3) nsChildView::UpdateThemeGeometries passes the toolbar's height, plus the
3819 // titlebar height, to -[ToolbarWindow setUnifiedToolbarHeight:].
3821 // The actual drawing of the gradient happens in two parts: The titlebar part
3822 // (i.e. the top 22 pixels of the gradient) is drawn by the MOZTitlebarView,
3823 // which is a subview of the window's content view and a sibling of the ChildView.
3824 // The rest of the gradient is drawn by Gecko into the ChildView, as part of the
3825 // -moz-appearance rendering of the toolbar.
3826 @implementation ToolbarWindow
3828 - (id)initWithContentRect:(NSRect)aChildViewRect
3829 styleMask:(NSUInteger)aStyle
3830 backing:(NSBackingStoreType)aBufferingType
3832 NS_OBJC_BEGIN_TRY_BLOCK_RETURN;
3834 // We treat aChildViewRect as the rectangle that the window's main ChildView
3835 // should be sized to. Get the right frameRect for the requested child view
3837 NSRect frameRect = [NSWindow frameRectForContentRect:aChildViewRect styleMask:aStyle];
3839 // Always size the content view to the full frame size of the window.
3840 // We do this even if we want this window to have a titlebar; in that case, the window's content
3841 // view covers the entire window but the ChildView inside it will only cover the content area. We
3842 // do this so that we can render the titlebar gradient manually, with a subview of our content
3843 // view that's positioned in the titlebar area. This lets us have a smooth connection between
3844 // titlebar and toolbar gradient in case the window has a "unified toolbar + titlebar" look.
3845 // Moreover, always using a full size content view lets us toggle the titlebar on and off without
3846 // changing the window's style mask (which would have other subtle effects, for example on
3848 aStyle |= NSWindowStyleMaskFullSizeContentView;
3850 // -[NSWindow initWithContentRect:styleMask:backing:defer:] calls
3851 // [self frameRectForContentRect:styleMask:] to convert the supplied content
3852 // rect to the window's frame rect. We've overridden that method to be a
3853 // pass-through function. So, in order to get the intended frameRect, we need
3854 // to supply frameRect itself as the "content rect".
3855 NSRect contentRect = frameRect;
3857 if ((self = [super initWithContentRect:contentRect
3859 backing:aBufferingType
3861 mTitlebarView = nil;
3862 mUnifiedToolbarHeight = 22.0f;
3863 mSheetAttachmentPosition = aChildViewRect.size.height;
3864 mWindowButtonsRect = NSZeroRect;
3865 mInitialTitlebarHeight = [self titlebarHeight];
3867 [self setTitlebarAppearsTransparent:YES];
3868 #if !defined(MAC_OS_VERSION_11_0) || MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_VERSION_11_0
3869 if (nsCocoaFeatures::OnBigSurOrLater()) {
3871 if (@available(macOS 11.0, *)) {
3873 self.titlebarSeparatorStyle = NSTitlebarSeparatorStyleNone;
3875 [self updateTitlebarView];
3877 mFullscreenTitlebarTracker = [[FullscreenTitlebarTracker alloc] init];
3878 // revealAmount is an undocumented property of
3879 // NSTitlebarAccessoryViewController that updates whenever the menubar
3880 // slides down in fullscreen mode.
3881 [mFullscreenTitlebarTracker addObserver:self
3882 forKeyPath:@"revealAmount"
3883 options:NSKeyValueObservingOptionNew
3885 // Adding this accessory view controller allows us to shift the toolbar down
3886 // when the user mouses to the top of the screen in fullscreen.
3887 [(NSWindow*)self addTitlebarAccessoryViewController:mFullscreenTitlebarTracker];
3891 NS_OBJC_END_TRY_BLOCK_RETURN(nil);
3894 - (void)observeValueForKeyPath:(NSString*)keyPath
3896 change:(NSDictionary<NSKeyValueChangeKey, id>*)change
3897 context:(void*)context {
3898 if ([keyPath isEqualToString:@"revealAmount"]) {
3899 [[self mainChildView] ensureNextCompositeIsAtomicWithMainThreadPaint];
3900 NSNumber* revealAmount = (change[NSKeyValueChangeNewKey]);
3901 [self updateTitlebarShownAmount:[revealAmount doubleValue]];
3903 [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
3907 static bool ScreenHasNotch(nsCocoaWindow* aGeckoWindow) {
3908 if (@available(macOS 12.0, *)) {
3909 nsCOMPtr<nsIScreen> widgetScreen = aGeckoWindow->GetWidgetScreen();
3910 NSScreen* cocoaScreen = ScreenHelperCocoa::CocoaScreenForScreen(widgetScreen);
3911 return cocoaScreen.safeAreaInsets.top != 0.0f;
3916 static bool ShouldShiftByMenubarHeightInFullscreen(nsCocoaWindow* aWindow) {
3917 switch (StaticPrefs::widget_macos_shift_by_menubar_on_fullscreen()) {
3925 // TODO: On notch-less macbooks, this creates extra space when the
3926 // "automatically show and hide the menubar on fullscreen" option is unchecked
3927 // (default checked). We tried to detect that in bug 1737831 but it wasn't
3928 // reliable enough, see the regressions from that bug. For now, stick to the
3929 // good behavior for default configurations (that is, shift by menubar height
3930 // on notch-less macbooks, and don't for devices that have a notch). This will
3931 // need refinement in the future.
3932 return !ScreenHasNotch(aWindow);
3935 - (void)updateTitlebarShownAmount:(CGFloat)aShownAmount {
3936 NSInteger styleMask = [self styleMask];
3937 if (!(styleMask & NSWindowStyleMaskFullScreen)) {
3938 // We are not interested in the size of the titlebar unless we are in
3943 // [NSApp mainMenu] menuBarHeight] returns one of two values: the full height
3944 // if the menubar is shown or is in the process of being shown, and 0
3945 // otherwise. Since we are multiplying the menubar height by aShownAmount, we
3946 // always want the full height.
3947 CGFloat menuBarHeight = NSApp.mainMenu.menuBarHeight;
3948 if (menuBarHeight > 0.0f) {
3949 mMenuBarHeight = menuBarHeight;
3951 if ([[self delegate] isKindOfClass:[WindowDelegate class]]) {
3952 WindowDelegate* windowDelegate = (WindowDelegate*)[self delegate];
3953 nsCocoaWindow* geckoWindow = [windowDelegate geckoWidget];
3958 if (nsIWidgetListener* listener = geckoWindow->GetWidgetListener()) {
3959 // Use the titlebar height cached in our frame rather than
3960 // [ToolbarWindow titlebarHeight]. titlebarHeight returns 0 when we're in
3962 CGFloat shiftByPixels = mInitialTitlebarHeight * aShownAmount;
3963 if (ShouldShiftByMenubarHeightInFullscreen(geckoWindow)) {
3964 shiftByPixels += mMenuBarHeight * aShownAmount;
3966 // Use mozilla::DesktopToLayoutDeviceScale rather than the
3967 // DesktopToLayoutDeviceScale in nsCocoaWindow. The latter accounts for
3968 // screen DPI. We don't want that because the revealAmount property
3969 // already accounts for it, so we'd be compounding DPI scales > 1.
3970 mozilla::DesktopCoord coord =
3971 LayoutDeviceCoord(shiftByPixels) / mozilla::DesktopToLayoutDeviceScale();
3973 listener->MacFullscreenMenubarOverlapChanged(coord);
3979 [mTitlebarView release];
3980 [mFullscreenTitlebarTracker removeObserver:self forKeyPath:@"revealAmount"];
3981 [mFullscreenTitlebarTracker removeFromParentViewController];
3982 [mFullscreenTitlebarTracker release];
3987 - (NSArray<NSView*>*)contentViewContents {
3988 NSMutableArray<NSView*>* contents = [[[self contentView] subviews] mutableCopy];
3989 if (mTitlebarView) {
3990 // Do not include the titlebar gradient view in the returned array.
3991 [contents removeObject:mTitlebarView];
3993 return [contents autorelease];
3996 - (void)updateTitlebarView {
3997 BOOL needTitlebarView = ![self drawsContentsIntoWindowFrame] || mUnifiedToolbarHeight > 0;
3998 if (needTitlebarView && !mTitlebarView) {
3999 mTitlebarView = [[MOZTitlebarView alloc] initWithFrame:[self unifiedToolbarRect]];
4000 mTitlebarView.autoresizingMask = NSViewWidthSizable | NSViewMinYMargin;
4001 [self.contentView addSubview:mTitlebarView positioned:NSWindowBelow relativeTo:nil];
4002 } else if (needTitlebarView && mTitlebarView) {
4003 mTitlebarView.frame = [self unifiedToolbarRect];
4004 } else if (!needTitlebarView && mTitlebarView) {
4005 [mTitlebarView removeFromSuperview];
4006 [mTitlebarView release];
4007 mTitlebarView = nil;
4011 - (void)windowMainStateChanged {
4012 [self setTitlebarNeedsDisplay];
4013 [[self mainChildView] ensureNextCompositeIsAtomicWithMainThreadPaint];
4016 - (void)setTitlebarNeedsDisplay {
4017 [mTitlebarView setNeedsDisplay:YES];
4020 - (NSRect)titlebarRect {
4021 CGFloat titlebarHeight = [self titlebarHeight];
4022 return NSMakeRect(0, [self frame].size.height - titlebarHeight, [self frame].size.width,
4026 // In window contentView coordinates (origin bottom left)
4027 - (NSRect)unifiedToolbarRect {
4028 return NSMakeRect(0, [self frame].size.height - mUnifiedToolbarHeight, [self frame].size.width,
4029 mUnifiedToolbarHeight);
4032 // Returns the unified height of titlebar + toolbar.
4033 - (CGFloat)unifiedToolbarHeight {
4034 return mUnifiedToolbarHeight;
4037 - (CGFloat)titlebarHeight {
4038 // We use the original content rect here, not what we return from
4039 // [self contentRectForFrameRect:], because that would give us a
4040 // titlebarHeight of zero.
4041 NSRect frameRect = [self frame];
4042 NSUInteger styleMask = [self styleMask];
4043 styleMask &= ~NSWindowStyleMaskFullSizeContentView;
4044 NSRect originalContentRect = [NSWindow contentRectForFrameRect:frameRect styleMask:styleMask];
4045 return NSMaxY(frameRect) - NSMaxY(originalContentRect);
4048 // Stores the complete height of titlebar + toolbar.
4049 - (void)setUnifiedToolbarHeight:(CGFloat)aHeight {
4050 if (aHeight == mUnifiedToolbarHeight) return;
4052 mUnifiedToolbarHeight = aHeight;
4054 [self updateTitlebarView];
4057 // Extending the content area into the title bar works by resizing the
4058 // mainChildView so that it covers the titlebar.
4059 - (void)setDrawsContentsIntoWindowFrame:(BOOL)aState {
4060 BOOL stateChanged = ([self drawsContentsIntoWindowFrame] != aState);
4061 [super setDrawsContentsIntoWindowFrame:aState];
4062 if (stateChanged && [[self delegate] isKindOfClass:[WindowDelegate class]]) {
4063 // Here we extend / shrink our mainChildView. We do that by firing a resize
4064 // event which will cause the ChildView to be resized to the rect returned
4065 // by nsCocoaWindow::GetClientBounds. GetClientBounds bases its return
4066 // value on what we return from drawsContentsIntoWindowFrame.
4067 WindowDelegate* windowDelegate = (WindowDelegate*)[self delegate];
4068 nsCocoaWindow* geckoWindow = [windowDelegate geckoWidget];
4070 // Re-layout our contents.
4071 geckoWindow->ReportSizeEvent();
4074 // Resizing the content area causes a reflow which would send a synthesized
4075 // mousemove event to the old mouse position relative to the top left
4076 // corner of the content area. But the mouse has shifted relative to the
4077 // content area, so that event would have wrong position information. So
4078 // we'll send a mouse move event with the correct new position.
4079 ChildViewMouseTracker::ResendLastMouseMoveEvent();
4082 [self updateTitlebarView];
4085 - (void)setWantsTitleDrawn:(BOOL)aDrawTitle {
4086 [super setWantsTitleDrawn:aDrawTitle];
4087 [self setTitlebarNeedsDisplay];
4090 - (void)setSheetAttachmentPosition:(CGFloat)aY {
4091 mSheetAttachmentPosition = aY;
4094 - (CGFloat)sheetAttachmentPosition {
4095 return mSheetAttachmentPosition;
4098 - (void)placeWindowButtons:(NSRect)aRect {
4099 if (!NSEqualRects(mWindowButtonsRect, aRect)) {
4100 mWindowButtonsRect = aRect;
4101 [self reflowTitlebarElements];
4105 - (NSRect)windowButtonsRect {
4106 return mWindowButtonsRect;
4109 // Returning YES here makes the setShowsToolbarButton method work even though
4110 // the window doesn't contain an NSToolbar.
4111 - (BOOL)_hasToolbar {
4115 // Dispatch a toolbar pill button clicked message to Gecko.
4116 - (void)_toolbarPillButtonClicked:(id)sender {
4117 NS_OBJC_BEGIN_TRY_IGNORE_BLOCK;
4121 if ([[self delegate] isKindOfClass:[WindowDelegate class]]) {
4122 WindowDelegate* windowDelegate = (WindowDelegate*)[self delegate];
4123 nsCocoaWindow* geckoWindow = [windowDelegate geckoWidget];
4124 if (!geckoWindow) return;
4126 nsIWidgetListener* listener = geckoWindow->GetWidgetListener();
4127 if (listener) listener->OSToolbarButtonPressed();
4130 NS_OBJC_END_TRY_IGNORE_BLOCK;
4133 // Retain and release "self" to avoid crashes when our widget (and its native
4134 // window) is closed as a result of processing a key equivalent (e.g.
4135 // Command+w or Command+q). This workaround is only needed for a window
4136 // that can become key.
4137 - (BOOL)performKeyEquivalent:(NSEvent*)theEvent {
4138 NS_OBJC_BEGIN_TRY_BLOCK_RETURN;
4140 NSWindow* nativeWindow = [self retain];
4141 BOOL retval = [super performKeyEquivalent:theEvent];
4142 [nativeWindow release];
4145 NS_OBJC_END_TRY_BLOCK_RETURN(NO);
4148 - (void)sendEvent:(NSEvent*)anEvent {
4149 NSEventType type = [anEvent type];
4152 case NSEventTypeScrollWheel:
4153 case NSEventTypeLeftMouseDown:
4154 case NSEventTypeLeftMouseUp:
4155 case NSEventTypeRightMouseDown:
4156 case NSEventTypeRightMouseUp:
4157 case NSEventTypeOtherMouseDown:
4158 case NSEventTypeOtherMouseUp:
4159 case NSEventTypeMouseMoved:
4160 case NSEventTypeLeftMouseDragged:
4161 case NSEventTypeRightMouseDragged:
4162 case NSEventTypeOtherMouseDragged: {
4163 // Drop all mouse events if a modal window has appeared above us.
4164 // This helps make us behave as if the OS were running a "real" modal
4166 id delegate = [self delegate];
4167 if (delegate && [delegate isKindOfClass:[WindowDelegate class]]) {
4168 nsCocoaWindow* widget = [(WindowDelegate*)delegate geckoWidget];
4170 if (gGeckoAppModalWindowList && (widget != gGeckoAppModalWindowList->window)) return;
4171 if (widget->HasModalDescendents()) return;
4180 [super sendEvent:anEvent];
4185 @implementation PopupWindow
4187 - (id)initWithContentRect:(NSRect)contentRect
4188 styleMask:(NSUInteger)styleMask
4189 backing:(NSBackingStoreType)bufferingType
4190 defer:(BOOL)deferCreation {
4191 NS_OBJC_BEGIN_TRY_BLOCK_RETURN;
4193 mIsContextMenu = false;
4194 return [super initWithContentRect:contentRect
4196 backing:bufferingType
4197 defer:deferCreation];
4199 NS_OBJC_END_TRY_BLOCK_RETURN(nil);
4202 // Override the private API _backdropBleedAmount. This determines how much the
4203 // desktop wallpaper contributes to the vibrancy backdrop.
4204 // Return 0 in order to match what the system does for sheet windows and
4205 // _NSPopoverWindows.
4206 - (CGFloat)_backdropBleedAmount {
4210 // Override the private API shadowOptions.
4211 // The constants below were found in AppKit's implementations of the
4212 // shadowOptions method on the various window types.
4213 static const NSUInteger kWindowShadowOptionsNoShadow = 0;
4214 static const NSUInteger kWindowShadowOptionsMenu = 2;
4215 static const NSUInteger kWindowShadowOptionsTooltipMojaveOrLater = 4;
4216 - (NSUInteger)shadowOptions {
4217 if (!self.hasShadow) {
4218 return kWindowShadowOptionsNoShadow;
4221 switch (self.shadowStyle) {
4222 case StyleWindowShadow::None:
4223 return kWindowShadowOptionsNoShadow;
4225 case StyleWindowShadow::Default: // we treat "default" as "default panel"
4226 case StyleWindowShadow::Menu:
4227 return kWindowShadowOptionsMenu;
4229 case StyleWindowShadow::Tooltip:
4230 if (nsCocoaFeatures::OnMojaveOrLater()) {
4231 return kWindowShadowOptionsTooltipMojaveOrLater;
4233 return kWindowShadowOptionsMenu;
4237 - (BOOL)isContextMenu {
4238 return mIsContextMenu;
4241 - (void)setIsContextMenu:(BOOL)flag {
4242 mIsContextMenu = flag;
4245 - (BOOL)canBecomeMainWindow {
4246 // This is overriden because the default is 'yes' when a titlebar is present.
4252 // According to Apple's docs on [NSWindow canBecomeKeyWindow] and [NSWindow
4253 // canBecomeMainWindow], windows without a title bar or resize bar can't (by
4254 // default) become key or main. But if a window can't become key, it can't
4255 // accept keyboard input (bmo bug 393250). And it should also be possible for
4256 // an otherwise "ordinary" window to become main. We need to override these
4257 // two methods to make this happen.
4258 @implementation BorderlessWindow
4260 - (BOOL)canBecomeKeyWindow {
4264 - (void)sendEvent:(NSEvent*)anEvent {
4265 NSEventType type = [anEvent type];
4268 case NSEventTypeScrollWheel:
4269 case NSEventTypeLeftMouseDown:
4270 case NSEventTypeLeftMouseUp:
4271 case NSEventTypeRightMouseDown:
4272 case NSEventTypeRightMouseUp:
4273 case NSEventTypeOtherMouseDown:
4274 case NSEventTypeOtherMouseUp:
4275 case NSEventTypeMouseMoved:
4276 case NSEventTypeLeftMouseDragged:
4277 case NSEventTypeRightMouseDragged:
4278 case NSEventTypeOtherMouseDragged: {
4279 // Drop all mouse events if a modal window has appeared above us.
4280 // This helps make us behave as if the OS were running a "real" modal
4282 id delegate = [self delegate];
4283 if (delegate && [delegate isKindOfClass:[WindowDelegate class]]) {
4284 nsCocoaWindow* widget = [(WindowDelegate*)delegate geckoWidget];
4286 if (gGeckoAppModalWindowList && (widget != gGeckoAppModalWindowList->window)) return;
4287 if (widget->HasModalDescendents()) return;
4296 [super sendEvent:anEvent];
4299 // Apple's doc on this method says that the NSWindow class's default is not to
4300 // become main if the window isn't "visible" -- so we should replicate that
4301 // behavior here. As best I can tell, the [NSWindow isVisible] method is an
4302 // accurate test of what Apple means by "visibility".
4303 - (BOOL)canBecomeMainWindow {
4304 NS_OBJC_BEGIN_TRY_BLOCK_RETURN;
4306 if (![self isVisible]) return NO;
4309 NS_OBJC_END_TRY_BLOCK_RETURN(NO);
4312 // Retain and release "self" to avoid crashes when our widget (and its native
4313 // window) is closed as a result of processing a key equivalent (e.g.
4314 // Command+w or Command+q). This workaround is only needed for a window
4315 // that can become key.
4316 - (BOOL)performKeyEquivalent:(NSEvent*)theEvent {
4317 NS_OBJC_BEGIN_TRY_BLOCK_RETURN;
4319 NSWindow* nativeWindow = [self retain];
4320 BOOL retval = [super performKeyEquivalent:theEvent];
4321 [nativeWindow release];
4324 NS_OBJC_END_TRY_BLOCK_RETURN(NO);