1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #import "chrome/browser/ui/cocoa/browser_window_controller_private.h"
9 #include "base/command_line.h"
10 #include "base/mac/mac_util.h"
11 #import "base/mac/scoped_nsobject.h"
12 #include "base/prefs/pref_service.h"
13 #include "base/prefs/scoped_user_pref_update.h"
14 #include "chrome/browser/browser_process.h"
15 #include "chrome/browser/fullscreen.h"
16 #include "chrome/browser/profiles/profile.h"
17 #include "chrome/browser/profiles/profile_avatar_icon_util.h"
18 #include "chrome/browser/ui/bookmarks/bookmark_tab_helper.h"
19 #include "chrome/browser/ui/browser.h"
20 #include "chrome/browser/ui/browser_window_state.h"
21 #import "chrome/browser/ui/cocoa/dev_tools_controller.h"
22 #import "chrome/browser/ui/cocoa/fast_resize_view.h"
23 #import "chrome/browser/ui/cocoa/find_bar/find_bar_cocoa_controller.h"
24 #import "chrome/browser/ui/cocoa/floating_bar_backing_view.h"
25 #import "chrome/browser/ui/cocoa/framed_browser_window.h"
26 #import "chrome/browser/ui/cocoa/fullscreen_mode_controller.h"
27 #import "chrome/browser/ui/cocoa/fullscreen_window.h"
28 #import "chrome/browser/ui/cocoa/infobars/infobar_container_controller.h"
29 #include "chrome/browser/ui/cocoa/last_active_browser_cocoa.h"
30 #import "chrome/browser/ui/cocoa/nsview_additions.h"
31 #import "chrome/browser/ui/cocoa/presentation_mode_controller.h"
32 #import "chrome/browser/ui/cocoa/profiles/avatar_button_controller.h"
33 #import "chrome/browser/ui/cocoa/profiles/avatar_icon_controller.h"
34 #import "chrome/browser/ui/cocoa/status_bubble_mac.h"
35 #import "chrome/browser/ui/cocoa/tab_contents/overlayable_contents_controller.h"
36 #import "chrome/browser/ui/cocoa/tabs/tab_strip_view.h"
37 #import "chrome/browser/ui/cocoa/toolbar/toolbar_controller.h"
38 #import "chrome/browser/ui/cocoa/version_independent_window.h"
39 #import "chrome/browser/ui/cocoa/website_settings/permission_bubble_cocoa.h"
40 #include "chrome/browser/ui/fullscreen/fullscreen_controller.h"
41 #include "chrome/browser/ui/tabs/tab_strip_model.h"
42 #include "chrome/common/chrome_switches.h"
43 #include "chrome/common/pref_names.h"
44 #include "content/public/browser/render_widget_host_view.h"
45 #include "content/public/browser/web_contents.h"
46 #import "ui/base/cocoa/focus_tracker.h"
47 #include "ui/base/ui_base_types.h"
49 using content::RenderWidgetHostView;
50 using content::WebContents;
54 // Space between the incognito badge and the right edge of the window.
55 const CGFloat kAvatarRightOffset = 4;
57 // The amount by which to shrink the tab strip (on the right) when the
58 // incognito badge is present.
59 const CGFloat kAvatarTabStripShrink = 18;
61 // Width of the full screen icon. Used to position the AvatarButton to the
63 const CGFloat kFullscreenIconWidth = 32;
65 // Insets for the location bar, used when the full toolbar is hidden.
66 // TODO(viettrungluu): We can argue about the "correct" insetting; I like the
67 // following best, though arguably 0 inset is better/more correct.
68 const CGFloat kLocBarLeftRightInset = 1;
69 const CGFloat kLocBarTopInset = 0;
70 const CGFloat kLocBarBottomInset = 1;
74 @implementation BrowserWindowController(Private)
76 // Create the tab strip controller.
77 - (void)createTabStripController {
78 DCHECK([overlayableContentsController_ activeContainer]);
79 DCHECK([[overlayableContentsController_ activeContainer] window]);
80 tabStripController_.reset([[TabStripController alloc]
81 initWithView:[self tabStripView]
82 switchView:[overlayableContentsController_ activeContainer]
83 browser:browser_.get()
87 - (void)saveWindowPositionIfNeeded {
88 if (!chrome::ShouldSaveWindowPlacement(browser_.get()))
91 // If we're in fullscreen mode, save the position of the regular window
93 NSWindow* window = [self isFullscreen] ? savedRegularWindow_ : [self window];
95 // Window positions are stored relative to the origin of the primary monitor.
96 NSRect monitorFrame = [[[NSScreen screens] objectAtIndex:0] frame];
97 NSScreen* windowScreen = [window screen];
99 // Start with the window's frame, which is in virtual coordinates.
100 // Do some y twiddling to flip the coordinate system.
101 gfx::Rect bounds(NSRectToCGRect([window frame]));
102 bounds.set_y(monitorFrame.size.height - bounds.y() - bounds.height());
104 // Browser::SaveWindowPlacement saves information for session restore.
105 ui::WindowShowState show_state = ui::SHOW_STATE_NORMAL;
106 if ([window isMiniaturized])
107 show_state = ui::SHOW_STATE_MINIMIZED;
108 else if ([self isFullscreen])
109 show_state = ui::SHOW_STATE_FULLSCREEN;
110 chrome::SaveWindowPlacement(browser_.get(), bounds, show_state);
112 // |windowScreen| can be nil (for example, if the monitor arrangement was
113 // changed while in fullscreen mode). If we see a nil screen, return without
115 // TODO(rohitrao): We should just not save anything for fullscreen windows.
116 // http://crbug.com/36479.
120 // Only save main window information to preferences.
121 PrefService* prefs = browser_->profile()->GetPrefs();
122 if (!prefs || browser_ != chrome::GetLastActiveBrowser())
125 // Save the current work area, in flipped coordinates.
126 gfx::Rect workArea(NSRectToCGRect([windowScreen visibleFrame]));
127 workArea.set_y(monitorFrame.size.height - workArea.y() - workArea.height());
129 DictionaryPrefUpdate update(
131 chrome::GetWindowPlacementKey(browser_.get()).c_str());
132 base::DictionaryValue* windowPreferences = update.Get();
133 windowPreferences->SetInteger("left", bounds.x());
134 windowPreferences->SetInteger("top", bounds.y());
135 windowPreferences->SetInteger("right", bounds.right());
136 windowPreferences->SetInteger("bottom", bounds.bottom());
137 windowPreferences->SetBoolean("maximized", false);
138 windowPreferences->SetBoolean("always_on_top", false);
139 windowPreferences->SetInteger("work_area_left", workArea.x());
140 windowPreferences->SetInteger("work_area_top", workArea.y());
141 windowPreferences->SetInteger("work_area_right", workArea.right());
142 windowPreferences->SetInteger("work_area_bottom", workArea.bottom());
145 - (NSRect)window:(NSWindow*)window
146 willPositionSheet:(NSWindow*)sheet
147 usingRect:(NSRect)defaultSheetRect {
148 // Position the sheet as follows:
149 // - If the bookmark bar is hidden or shown as a bubble (on the NTP when the
150 // bookmark bar is disabled), position the sheet immediately below the
152 // - If the bookmark bar is shown (attached to the normal toolbar), position
153 // the sheet below the bookmark bar.
154 // - If the bookmark bar is currently animating, position the sheet according
155 // to where the bar will be when the animation ends.
156 switch ([bookmarkBarController_ currentState]) {
157 case BookmarkBar::SHOW: {
158 NSRect bookmarkBarFrame = [[bookmarkBarController_ view] frame];
159 defaultSheetRect.origin.y = bookmarkBarFrame.origin.y;
162 case BookmarkBar::HIDDEN:
163 case BookmarkBar::DETACHED: {
164 if ([self hasToolbar]) {
165 NSRect toolbarFrame = [[toolbarController_ view] frame];
166 defaultSheetRect.origin.y = toolbarFrame.origin.y;
168 // The toolbar is not shown in application mode. The sheet should be
169 // located at the top of the window, under the title of the window.
170 defaultSheetRect.origin.y = NSHeight([[window contentView] frame]) -
171 defaultSheetRect.size.height;
176 return defaultSheetRect;
179 - (void)layoutSubviews {
180 // With the exception of the top tab strip, the subviews which we lay out are
181 // subviews of the content view, so we mainly work in the content view's
182 // coordinate system. Note, however, that the content view's coordinate system
183 // and the window's base coordinate system should coincide.
184 NSWindow* window = [self window];
185 NSView* contentView = [window contentView];
186 NSRect contentBounds = [contentView bounds];
187 CGFloat minX = NSMinX(contentBounds);
188 CGFloat minY = NSMinY(contentBounds);
189 CGFloat width = NSWidth(contentBounds);
191 BOOL useSimplifiedFullscreen = CommandLine::ForCurrentProcess()->HasSwitch(
192 switches::kEnableSimplifiedFullscreen);
194 // Suppress title drawing if necessary.
195 if ([window respondsToSelector:@selector(setShouldHideTitle:)])
196 [(id)window setShouldHideTitle:![self hasTitleBar]];
198 // Update z-order. The code below depends on this.
199 [self updateSubviewZOrder:[self inPresentationMode]];
201 BOOL inPresentationMode = [self inPresentationMode];
202 CGFloat floatingBarHeight = [self floatingBarHeight];
203 // In presentation mode, |yOffset| accounts for the sliding position of the
204 // floating bar and the extra offset needed to dodge the menu bar.
205 CGFloat yOffset = inPresentationMode && !useSimplifiedFullscreen ?
206 (std::floor((1 - floatingBarShownFraction_) * floatingBarHeight) -
207 [presentationModeController_ floatingBarVerticalOffset]) : 0;
208 CGFloat maxY = NSMaxY(contentBounds) + yOffset;
210 if ([self hasTabStrip]) {
211 // If we need to lay out the top tab strip, replace |maxY| with a higher
212 // value, and then lay out the tab strip.
213 NSRect windowFrame = [contentView convertRect:[window frame] fromView:nil];
214 maxY = NSHeight(windowFrame) + yOffset;
215 if (useSimplifiedFullscreen && [self isFullscreen]) {
216 CGFloat tabStripHeight = NSHeight([[self tabStripView] frame]);
217 CGFloat revealAmount = (1 - floatingBarShownFraction_) * tabStripHeight;
218 // In simplified fullscreen, only the toolbar is visible by default, and
219 // the tabstrip and menu bar come down (each separately) when the user
220 // mouses near the top of the window. Push the maxY of the toolbar up by
221 // the amount of the tabstrip that is revealed, while removing the amount
222 // of space needed by the menu bar.
224 revealAmount - [fullscreenModeController_ menuBarHeight]);
226 maxY = [self layoutTabStripAtMaxY:maxY
228 fullscreen:[self isFullscreen]];
231 // Sanity-check |maxY|.
232 DCHECK_GE(maxY, minY);
233 DCHECK_LE(maxY, NSMaxY(contentBounds) + yOffset);
235 // Place the toolbar at the top of the reserved area.
236 maxY = [self layoutToolbarAtMinX:minX maxY:maxY width:width];
238 // If we're not displaying the bookmark bar below the info bar, then it goes
239 // immediately below the toolbar.
240 BOOL placeBookmarkBarBelowInfoBar = [self placeBookmarkBarBelowInfoBar];
241 if (!placeBookmarkBarBelowInfoBar)
242 maxY = [self layoutBookmarkBarAtMinX:minX maxY:maxY width:width];
244 // The floating bar backing view doesn't actually add any height.
245 NSRect floatingBarBackingRect =
246 NSMakeRect(minX, maxY, width, floatingBarHeight);
247 [self layoutFloatingBarBackingView:floatingBarBackingRect
248 presentationMode:inPresentationMode];
250 // Place the find bar immediately below the toolbar/attached bookmark bar. In
251 // presentation mode, it hangs off the top of the screen when the bar is
253 [findBarCocoaController_ positionFindBarViewAtMaxY:maxY maxWidth:width];
254 [fullscreenExitBubbleController_ positionInWindowAtTop:maxY width:width];
256 // If in presentation mode, reset |maxY| to top of screen, so that the
257 // floating bar slides over the things which appear to be in the content area.
258 if (inPresentationMode ||
259 (useSimplifiedFullscreen && !fullscreenUrl_.is_empty())) {
260 maxY = NSMaxY(contentBounds);
263 // Also place the info bar container immediate below the toolbar, except in
264 // presentation mode in which case it's at the top of the visual content area.
265 maxY = [self layoutInfoBarAtMinX:minX maxY:maxY width:width];
267 // If the bookmark bar is detached, place it next in the visual content area.
268 if (placeBookmarkBarBelowInfoBar)
269 maxY = [self layoutBookmarkBarAtMinX:minX maxY:maxY width:width];
271 // Place the download shelf, if any, at the bottom of the view.
272 minY = [self layoutDownloadShelfAtMinX:minX minY:minY width:width];
274 // Finally, the content area takes up all of the remaining space.
275 NSRect contentAreaRect = NSMakeRect(minX, minY, width, maxY - minY);
276 [self layoutTabContentArea:contentAreaRect];
278 // Normally, we don't need to tell the toolbar whether or not to show the
279 // divider, but things break down during animation.
280 [toolbarController_ setDividerOpacity:[self toolbarDividerOpacity]];
283 - (CGFloat)floatingBarHeight {
284 if (![self inPresentationMode])
287 CGFloat totalHeight = [presentationModeController_ floatingBarVerticalOffset];
289 if ([self hasTabStrip])
290 totalHeight += NSHeight([[self tabStripView] frame]);
292 if ([self hasToolbar]) {
293 totalHeight += NSHeight([[toolbarController_ view] frame]);
294 } else if ([self hasLocationBar]) {
295 totalHeight += NSHeight([[toolbarController_ view] frame]) +
296 kLocBarTopInset + kLocBarBottomInset;
299 if (![self placeBookmarkBarBelowInfoBar])
300 totalHeight += NSHeight([[bookmarkBarController_ view] frame]);
305 - (CGFloat)layoutTabStripAtMaxY:(CGFloat)maxY
307 fullscreen:(BOOL)fullscreen {
308 // Nothing to do if no tab strip.
309 if (![self hasTabStrip])
312 NSView* tabStripView = [self tabStripView];
313 CGFloat tabStripHeight = NSHeight([tabStripView frame]);
314 maxY -= tabStripHeight;
315 [tabStripView setFrame:NSMakeRect(0, maxY, width, tabStripHeight)];
317 // Set left indentation based on fullscreen mode status.
318 [tabStripController_ setLeftIndentForControls:(fullscreen ? 0 :
319 [[tabStripController_ class] defaultLeftIndentForControls])];
321 // Lay out the icognito/avatar badge because calculating the indentation on
322 // the right depends on it.
323 NSView* avatarButton = [avatarButtonController_ view];
324 if ([self shouldShowAvatar]) {
325 CGFloat badgeXOffset = -kAvatarRightOffset;
326 CGFloat badgeYOffset = 0;
327 CGFloat buttonHeight = NSHeight([avatarButton frame]);
329 if ([self shouldUseNewAvatarButton]) {
330 // The fullscreen icon is displayed to the right of the avatar button.
331 if (![self isFullscreen])
332 badgeXOffset -= kFullscreenIconWidth;
333 // Center the button vertically on the tabstrip.
334 badgeYOffset = (tabStripHeight - buttonHeight) / 2;
336 // Actually place the badge *above* |maxY|, by +2 to miss the divider.
337 badgeYOffset = 2 * [[avatarButton superview] cr_lineWidth];
340 [avatarButton setFrameSize:NSMakeSize(NSWidth([avatarButton frame]),
341 std::min(buttonHeight, tabStripHeight))];
343 NSMakePoint(width - NSWidth([avatarButton frame]) + badgeXOffset,
344 maxY + badgeYOffset);
345 [avatarButton setFrameOrigin:origin];
346 [avatarButton setHidden:NO]; // Make sure it's shown.
349 // Calculate the right indentation. The default indentation built into the
350 // tabstrip leaves enough room for the fullscreen button or presentation mode
351 // toggle button on Lion. On non-Lion systems, the right indent needs to be
352 // adjusted to make room for the new tab button when an avatar is present.
353 CGFloat rightIndent = 0;
354 if (base::mac::IsOSLionOrLater() &&
355 [[self window] isKindOfClass:[FramedBrowserWindow class]]) {
356 FramedBrowserWindow* window =
357 static_cast<FramedBrowserWindow*>([self window]);
358 rightIndent += -[window fullScreenButtonOriginAdjustment].x;
360 if ([self shouldUseNewAvatarButton]) {
361 // The new avatar is wider than the default indentation, so we need to
362 // account for its width.
363 rightIndent += NSWidth([avatarButton frame]) + kAvatarTabStripShrink;
365 // When the fullscreen icon is not displayed, return its width to the
367 if ([self isFullscreen])
368 rightIndent -= kFullscreenIconWidth;
370 } else if ([self shouldShowAvatar]) {
371 rightIndent += kAvatarTabStripShrink +
372 NSWidth([avatarButton frame]) + kAvatarRightOffset;
374 [tabStripController_ setRightIndentForControls:rightIndent];
376 // Go ahead and layout the tabs.
377 [tabStripController_ layoutTabsWithoutAnimation];
382 - (CGFloat)layoutToolbarAtMinX:(CGFloat)minX
384 width:(CGFloat)width {
385 NSView* toolbarView = [toolbarController_ view];
386 NSRect toolbarFrame = [toolbarView frame];
387 if ([self hasToolbar]) {
388 // The toolbar is present in the window, so we make room for it.
389 DCHECK(![toolbarView isHidden]);
390 toolbarFrame.origin.x = minX;
391 toolbarFrame.origin.y = maxY - NSHeight(toolbarFrame);
392 toolbarFrame.size.width = width;
393 maxY -= NSHeight(toolbarFrame);
395 if ([self hasLocationBar]) {
396 // Location bar is present with no toolbar. Put a border of
397 // |kLocBar...Inset| pixels around the location bar.
398 // TODO(viettrungluu): This is moderately ridiculous. The toolbar should
399 // really be aware of what its height should be (the way the toolbar
400 // compression stuff is currently set up messes things up).
401 DCHECK(![toolbarView isHidden]);
402 toolbarFrame.origin.x = kLocBarLeftRightInset;
403 toolbarFrame.origin.y = maxY - NSHeight(toolbarFrame) - kLocBarTopInset;
404 toolbarFrame.size.width = width - 2 * kLocBarLeftRightInset;
405 maxY -= kLocBarTopInset + NSHeight(toolbarFrame) + kLocBarBottomInset;
407 DCHECK([toolbarView isHidden]);
410 [toolbarView setFrame:toolbarFrame];
414 - (BOOL)placeBookmarkBarBelowInfoBar {
415 // If we are currently displaying the NTP detached bookmark bar or animating
416 // to/from it (from/to anything else), we display the bookmark bar below the
418 return [bookmarkBarController_ isInState:BookmarkBar::DETACHED] ||
419 [bookmarkBarController_ isAnimatingToState:BookmarkBar::DETACHED] ||
420 [bookmarkBarController_ isAnimatingFromState:BookmarkBar::DETACHED];
423 - (CGFloat)layoutBookmarkBarAtMinX:(CGFloat)minX
425 width:(CGFloat)width {
426 [bookmarkBarController_ updateHiddenState];
428 NSView* bookmarkBarView = [bookmarkBarController_ view];
429 NSRect frame = [bookmarkBarView frame];
430 frame.origin.x = minX;
431 frame.origin.y = maxY - NSHeight(frame);
432 frame.size.width = width;
433 [bookmarkBarView setFrame:frame];
434 maxY -= NSHeight(frame);
436 // Pin the bookmark bar to the top of the window and make the width flexible.
437 [bookmarkBarView setAutoresizingMask:NSViewWidthSizable | NSViewMinYMargin];
439 // TODO(viettrungluu): Does this really belong here? Calling it shouldn't be
440 // necessary in the non-NTP case.
441 [bookmarkBarController_ layoutSubviews];
446 - (void)layoutFloatingBarBackingView:(NSRect)frame
447 presentationMode:(BOOL)presentationMode {
448 // Only display when in presentation mode.
449 if (presentationMode) {
450 // For certain window types such as app windows (e.g., the dev tools
451 // window), there's no actual overlay. (Displaying one would result in an
452 // overly sliding in only under the menu, which gives an ugly effect.)
453 if (floatingBarBackingView_.get()) {
455 [floatingBarBackingView_ setFrame:frame];
458 // But we want the logic to work as usual (for show/hide/etc. purposes).
459 [presentationModeController_ overlayFrameChanged:frame];
461 // Okay to call even if |floatingBarBackingView_| is nil.
462 if ([floatingBarBackingView_ superview])
463 [floatingBarBackingView_ removeFromSuperview];
467 - (CGFloat)layoutInfoBarAtMinX:(CGFloat)minX
469 width:(CGFloat)width {
470 NSView* containerView = [infoBarContainerController_ view];
471 NSRect containerFrame = [containerView frame];
472 maxY -= NSHeight(containerFrame);
473 maxY += [infoBarContainerController_ overlappingTipHeight];
474 containerFrame.origin.x = minX;
475 containerFrame.origin.y = maxY;
476 containerFrame.size.width = width;
477 [containerView setFrame:containerFrame];
481 - (CGFloat)layoutDownloadShelfAtMinX:(CGFloat)minX
483 width:(CGFloat)width {
484 if (downloadShelfController_.get()) {
485 NSView* downloadView = [downloadShelfController_ view];
486 NSRect downloadFrame = [downloadView frame];
487 downloadFrame.origin.x = minX;
488 downloadFrame.origin.y = minY;
489 downloadFrame.size.width = width;
490 [downloadView setFrame:downloadFrame];
491 minY += NSHeight(downloadFrame);
496 - (void)layoutTabContentArea:(NSRect)newFrame {
497 NSView* tabContentView = [self tabContentArea];
498 NSRect tabContentFrame = [tabContentView frame];
500 bool contentShifted =
501 NSMaxY(tabContentFrame) != NSMaxY(newFrame) ||
502 NSMinX(tabContentFrame) != NSMinX(newFrame);
504 tabContentFrame = newFrame;
505 [tabContentView setFrame:tabContentFrame];
507 // If the relayout shifts the content area up or down, let the renderer know.
508 if (contentShifted) {
509 if (WebContents* contents =
510 browser_->tab_strip_model()->GetActiveWebContents()) {
511 if (RenderWidgetHostView* rwhv = contents->GetRenderWidgetHostView())
512 rwhv->WindowFrameChanged();
517 - (void)updateRoundedBottomCorners {
518 [[self tabContentArea] setRoundedBottomCorners:![self isFullscreen]];
521 - (void)adjustToolbarAndBookmarkBarForCompression:(CGFloat)compression {
523 [toolbarController_ desiredHeightForCompression:compression];
524 NSRect toolbarFrame = [[toolbarController_ view] frame];
525 CGFloat deltaH = newHeight - toolbarFrame.size.height;
530 toolbarFrame.size.height = newHeight;
531 NSRect bookmarkFrame = [[bookmarkBarController_ view] frame];
532 bookmarkFrame.size.height = bookmarkFrame.size.height - deltaH;
533 [[toolbarController_ view] setFrame:toolbarFrame];
534 [[bookmarkBarController_ view] setFrame:bookmarkFrame];
535 [self layoutSubviews];
538 // Fullscreen and presentation mode methods
540 - (void)moveViewsForImmersiveFullscreen:(BOOL)fullscreen
541 regularWindow:(NSWindow*)regularWindow
542 fullscreenWindow:(NSWindow*)fullscreenWindow {
543 NSWindow* sourceWindow = fullscreen ? regularWindow : fullscreenWindow;
544 NSWindow* destWindow = fullscreen ? fullscreenWindow : regularWindow;
546 // Close the bookmark bubble, if it's open. Use |-ok:| instead of |-cancel:|
547 // or |-close| because that matches the behavior when the bubble loses key
549 [bookmarkBubbleController_ ok:self];
551 // Save the current first responder so we can restore after views are moved.
552 base::scoped_nsobject<FocusTracker> focusTracker(
553 [[FocusTracker alloc] initWithWindow:sourceWindow]);
555 // While we move views (and focus) around, disable any bar visibility changes.
556 [self disableBarVisibilityUpdates];
558 // Retain the tab strip view while we remove it from its superview.
559 base::scoped_nsobject<NSView> tabStripView;
560 if ([self hasTabStrip]) {
561 tabStripView.reset([[self tabStripView] retain]);
562 [tabStripView removeFromSuperview];
565 // Ditto for the content view.
566 base::scoped_nsobject<NSView> contentView(
567 [[sourceWindow contentView] retain]);
568 // Disable autoresizing of subviews while we move views around. This prevents
569 // spurious renderer resizes.
570 [contentView setAutoresizesSubviews:NO];
571 [contentView removeFromSuperview];
573 // Have to do this here, otherwise later calls can crash because the window
575 [sourceWindow setDelegate:nil];
576 [destWindow setDelegate:self];
578 // With this call, valgrind complains that a "Conditional jump or move depends
579 // on uninitialised value(s)". The error happens in -[NSThemeFrame
580 // drawOverlayRect:]. I'm pretty convinced this is an Apple bug, but there is
581 // no visual impact. I have been unable to tickle it away with other window
582 // or view manipulation Cocoa calls. Stack added to suppressions_mac.txt.
583 [contentView setAutoresizesSubviews:YES];
584 [destWindow setContentView:contentView];
586 // Move the incognito badge if present.
587 if ([self shouldShowAvatar]) {
588 NSView* avatarButtonView = [avatarButtonController_ view];
590 [avatarButtonView removeFromSuperview];
591 [avatarButtonView setHidden:YES]; // Will be shown in layout.
592 [[destWindow cr_windowView] addSubview:avatarButtonView];
595 // Add the tab strip after setting the content view and moving the incognito
596 // badge (if any), so that the tab strip will be on top (in the z-order).
597 if ([self hasTabStrip])
598 [[destWindow cr_windowView] addSubview:tabStripView];
600 [sourceWindow setWindowController:nil];
601 [self setWindow:destWindow];
602 [destWindow setWindowController:self];
604 // Move the status bubble over, if we have one.
606 statusBubble_->SwitchParentWindow(destWindow);
608 // Move the title over.
609 [destWindow setTitle:[sourceWindow title]];
611 // The window needs to be onscreen before we can set its first responder.
612 // Ordering the window to the front can change the active Space (either to
613 // the window's old Space or to the application's assigned Space). To prevent
614 // this by temporarily change the collectionBehavior.
615 NSWindowCollectionBehavior behavior = [sourceWindow collectionBehavior];
616 [destWindow setCollectionBehavior:
617 NSWindowCollectionBehaviorMoveToActiveSpace];
618 [destWindow makeKeyAndOrderFront:self];
619 [destWindow setCollectionBehavior:behavior];
621 if (![focusTracker restoreFocusInWindow:destWindow]) {
622 // During certain types of fullscreen transitions, the view that had focus
623 // may have gone away (e.g., the one for a Flash FS widget). In this case,
624 // FocusTracker will fail to restore focus to anything, so we set the focus
625 // to the tab contents as a reasonable fall-back.
626 [self focusTabContents];
628 [sourceWindow orderOut:self];
630 // We're done moving focus, so re-enable bar visibility changes.
631 [self enableBarVisibilityUpdates];
634 - (void)permissionBubbleWindowWillClose:(NSNotification*)notification {
635 DCHECK(permissionBubbleCocoa_);
637 NSNotificationCenter* center = [NSNotificationCenter defaultCenter];
638 [center removeObserver:self
639 name:NSWindowWillCloseNotification
640 object:[notification object]];
641 [self releaseBarVisibilityForOwner:[notification object]
646 - (void)setPresentationModeInternal:(BOOL)presentationMode
647 forceDropdown:(BOOL)forceDropdown {
648 if (presentationMode == [self inPresentationMode])
651 if (presentationMode) {
652 BOOL fullscreen_for_tab =
653 browser_->fullscreen_controller()->IsWindowFullscreenForTabOrPending();
655 CommandLine::ForCurrentProcess()->HasSwitch(switches::kKioskMode);
656 BOOL showDropdown = !fullscreen_for_tab &&
658 (forceDropdown || [self floatingBarHasFocus]);
659 presentationModeController_.reset(
660 [[PresentationModeController alloc] initWithBrowserController:self]);
662 if (permissionBubbleCocoa_ && permissionBubbleCocoa_->IsVisible()) {
663 DCHECK(permissionBubbleCocoa_->window());
664 // A visible permission bubble will force the dropdown to remain visible.
665 [self lockBarVisibilityForOwner:permissionBubbleCocoa_->window()
669 // Register to be notified when the permission bubble is closed, to
670 // allow fullscreen to hide the dropdown.
671 NSNotificationCenter* center = [NSNotificationCenter defaultCenter];
672 [center addObserver:self
673 selector:@selector(permissionBubbleWindowWillClose:)
674 name:NSWindowWillCloseNotification
675 object:permissionBubbleCocoa_->window()];
678 // Turn on layered mode for the window's root view for the entry
679 // animation. Without this, the OS fullscreen animation for entering
680 // fullscreen mode does not correctly draw the tab strip.
681 // It will be turned off (set back to NO) when the animation finishes,
682 // in -windowDidEnterFullScreen:.
683 // Leaving wantsLayer on for the duration of presentation mode causes
684 // performance issues when the dropdown is animated in/out. It also does
685 // not seem to be required for the exit animation.
686 [[[self window] cr_windowView] setWantsLayer:YES];
688 NSView* contentView = [[self window] contentView];
689 [presentationModeController_ enterPresentationModeForContentView:contentView
690 showDropdown:showDropdown];
692 [presentationModeController_ exitPresentationMode];
693 presentationModeController_.reset();
696 [self adjustUIForPresentationMode:presentationMode];
697 [self layoutSubviews];
700 - (void)enterImmersiveFullscreen {
701 // |-isFullscreen:| will return YES from here onwards.
702 enteringFullscreen_ = YES; // Set to NO by |-windowDidEnterFullScreen:|.
705 const CGDisplayReservationInterval kFadeDurationSeconds = 0.6;
706 Boolean didFadeOut = NO;
707 CGDisplayFadeReservationToken token;
708 if (CGAcquireDisplayFadeReservation(kFadeDurationSeconds, &token)
709 == kCGErrorSuccess) {
711 CGDisplayFade(token, kFadeDurationSeconds / 2, kCGDisplayBlendNormal,
712 kCGDisplayBlendSolidColor, 0.0, 0.0, 0.0, /*synchronous=*/true);
715 // Create the fullscreen window.
716 fullscreenWindow_.reset([[self createFullscreenWindow] retain]);
717 savedRegularWindow_ = [[self window] retain];
718 savedRegularWindowFrame_ = [savedRegularWindow_ frame];
720 [self moveViewsForImmersiveFullscreen:YES
721 regularWindow:[self window]
722 fullscreenWindow:fullscreenWindow_.get()];
724 // When simplified fullscreen is enabled, do not enter presentation mode.
725 const CommandLine* command_line = CommandLine::ForCurrentProcess();
726 if (command_line->HasSwitch(switches::kEnableSimplifiedFullscreen)) {
727 // TODO(rohitrao): Add code to manage the menubar here.
729 [self adjustUIForPresentationMode:YES];
730 [self setPresentationModeInternal:YES forceDropdown:NO];
733 [self layoutSubviews];
735 [self windowDidEnterFullScreen:nil];
739 CGDisplayFade(token, kFadeDurationSeconds / 2, kCGDisplayBlendSolidColor,
740 kCGDisplayBlendNormal, 0.0, 0.0, 0.0, /*synchronous=*/false);
741 CGReleaseDisplayFadeReservation(token);
745 - (void)exitImmersiveFullscreen {
747 const CGDisplayReservationInterval kFadeDurationSeconds = 0.6;
748 Boolean didFadeOut = NO;
749 CGDisplayFadeReservationToken token;
750 if (CGAcquireDisplayFadeReservation(kFadeDurationSeconds, &token)
751 == kCGErrorSuccess) {
753 CGDisplayFade(token, kFadeDurationSeconds / 2, kCGDisplayBlendNormal,
754 kCGDisplayBlendSolidColor, 0.0, 0.0, 0.0, /*synchronous=*/true);
757 // When simplified fullscreen is enabled, the menubar status is managed
759 const CommandLine* command_line = CommandLine::ForCurrentProcess();
760 if (command_line->HasSwitch(switches::kEnableSimplifiedFullscreen)) {
761 // TODO(rohitrao): Add code to manage the menubar here.
764 [self windowWillExitFullScreen:nil];
766 [self moveViewsForImmersiveFullscreen:NO
767 regularWindow:savedRegularWindow_
768 fullscreenWindow:fullscreenWindow_.get()];
770 // When exiting fullscreen mode, we need to call layoutSubviews manually.
771 [savedRegularWindow_ autorelease];
772 savedRegularWindow_ = nil;
773 fullscreenWindow_.reset();
774 [self layoutSubviews];
776 [self windowDidExitFullScreen:nil];
780 CGDisplayFade(token, kFadeDurationSeconds / 2, kCGDisplayBlendSolidColor,
781 kCGDisplayBlendNormal, 0.0, 0.0, 0.0, /*synchronous=*/false);
782 CGReleaseDisplayFadeReservation(token);
786 // TODO(rohitrao): This function has shrunk into uselessness, and
787 // |-setFullscreen:| has grown rather large. Find a good way to break up
788 // |-setFullscreen:| into smaller pieces. http://crbug.com/36449
789 - (void)adjustUIForPresentationMode:(BOOL)fullscreen {
790 // Create the floating bar backing view if necessary.
791 if (fullscreen && !floatingBarBackingView_.get() &&
792 ([self hasTabStrip] || [self hasToolbar] || [self hasLocationBar])) {
793 floatingBarBackingView_.reset(
794 [[FloatingBarBackingView alloc] initWithFrame:NSZeroRect]);
795 [floatingBarBackingView_ setAutoresizingMask:(NSViewWidthSizable |
799 // Force the bookmark bar z-order to update.
800 [[bookmarkBarController_ view] removeFromSuperview];
801 [self updateSubviewZOrder:fullscreen];
802 [self updateAllowOverlappingViews:fullscreen];
805 - (void)showFullscreenExitBubbleIfNecessary {
806 // This method is called in response to
807 // |-updateFullscreenExitBubbleURL:bubbleType:|. If we're in the middle of the
808 // transition into fullscreen (i.e., using the System Fullscreen API), do not
809 // show the bubble because it will cause visual jank
810 // (http://crbug.com/130649). This will be called again as part of
811 // |-windowDidEnterFullScreen:|, so arrange to do that work then instead.
812 if (enteringFullscreen_)
815 [self hideOverlayIfPossibleWithAnimation:NO delay:NO];
817 if (fullscreenBubbleType_ == FEB_TYPE_NONE ||
818 fullscreenBubbleType_ == FEB_TYPE_BROWSER_FULLSCREEN_EXIT_INSTRUCTION) {
819 // Show no exit instruction bubble on Mac when in Browser Fullscreen.
820 [self destroyFullscreenExitBubbleIfNecessary];
822 [fullscreenExitBubbleController_ closeImmediately];
823 fullscreenExitBubbleController_.reset(
824 [[FullscreenExitBubbleController alloc]
826 browser:browser_.get()
828 bubbleType:fullscreenBubbleType_]);
829 [fullscreenExitBubbleController_ showWindow];
833 - (void)destroyFullscreenExitBubbleIfNecessary {
834 [fullscreenExitBubbleController_ closeImmediately];
835 fullscreenExitBubbleController_.reset();
838 - (void)contentViewDidResize:(NSNotification*)notification {
839 [self layoutSubviews];
842 - (void)registerForContentViewResizeNotifications {
843 [[NSNotificationCenter defaultCenter]
845 selector:@selector(contentViewDidResize:)
846 name:NSViewFrameDidChangeNotification
847 object:[[self window] contentView]];
850 - (void)deregisterForContentViewResizeNotifications {
851 [[NSNotificationCenter defaultCenter]
853 name:NSViewFrameDidChangeNotification
854 object:[[self window] contentView]];
857 - (NSSize)window:(NSWindow*)window
858 willUseFullScreenContentSize:(NSSize)proposedSize {
862 - (NSApplicationPresentationOptions)window:(NSWindow*)window
863 willUseFullScreenPresentationOptions:(NSApplicationPresentationOptions)opt {
865 NSApplicationPresentationAutoHideDock |
866 NSApplicationPresentationAutoHideMenuBar);
869 - (void)windowWillEnterFullScreen:(NSNotification*)notification {
870 if (notification) // For System Fullscreen when non-nil.
871 [self registerForContentViewResizeNotifications];
873 NSWindow* window = [self window];
874 savedRegularWindowFrame_ = [window frame];
875 BOOL mode = enteringPresentationMode_ ||
876 browser_->fullscreen_controller()->IsWindowFullscreenForTabOrPending();
877 enteringFullscreen_ = YES;
878 [self setPresentationModeInternal:mode forceDropdown:NO];
881 - (void)windowDidEnterFullScreen:(NSNotification*)notification {
882 // In Yosemite, some combination of the titlebar and toolbar always show in
883 // full-screen mode. We do not want either to show. Search for the window that
884 // contains the views, and hide it. There is no need to ever unhide the view.
885 // http://crbug.com/380235
886 if (base::mac::IsOSYosemiteOrLater()) {
887 for (NSWindow* window in [[NSApplication sharedApplication] windows]) {
889 isKindOfClass:NSClassFromString(@"NSToolbarFullScreenWindow")]) {
890 [window.contentView setHidden:YES];
895 if (notification) // For System Fullscreen when non-nil.
896 [self deregisterForContentViewResizeNotifications];
897 enteringFullscreen_ = NO;
898 enteringPresentationMode_ = NO;
900 const CommandLine* command_line = CommandLine::ForCurrentProcess();
901 if (command_line->HasSwitch(switches::kEnableSimplifiedFullscreen) &&
902 fullscreenUrl_.is_empty()) {
903 fullscreenModeController_.reset([[FullscreenModeController alloc]
904 initWithBrowserWindowController:self]);
907 [self showFullscreenExitBubbleIfNecessary];
908 browser_->WindowFullscreenStateChanged();
909 [[[self window] cr_windowView] setWantsLayer:NO];
910 [self updateRoundedBottomCorners];
913 - (void)windowWillExitFullScreen:(NSNotification*)notification {
914 if (notification) // For System Fullscreen when non-nil.
915 [self registerForContentViewResizeNotifications];
916 fullscreenModeController_.reset();
917 [self destroyFullscreenExitBubbleIfNecessary];
918 [self setPresentationModeInternal:NO forceDropdown:NO];
921 - (void)windowDidExitFullScreen:(NSNotification*)notification {
922 if (notification) // For System Fullscreen when non-nil.
923 [self deregisterForContentViewResizeNotifications];
924 browser_->WindowFullscreenStateChanged();
925 [self updateRoundedBottomCorners];
928 - (void)windowDidFailToEnterFullScreen:(NSWindow*)window {
929 [self deregisterForContentViewResizeNotifications];
930 enteringFullscreen_ = NO;
931 [self setPresentationModeInternal:NO forceDropdown:NO];
933 // Force a relayout to try and get the window back into a reasonable state.
934 [self layoutSubviews];
937 - (void)windowDidFailToExitFullScreen:(NSWindow*)window {
938 [self deregisterForContentViewResizeNotifications];
940 // Force a relayout to try and get the window back into a reasonable state.
941 [self layoutSubviews];
944 - (void)enableBarVisibilityUpdates {
945 // Early escape if there's nothing to do.
946 if (barVisibilityUpdatesEnabled_)
949 barVisibilityUpdatesEnabled_ = YES;
951 if ([barVisibilityLocks_ count])
952 [presentationModeController_ ensureOverlayShownWithAnimation:NO delay:NO];
954 [presentationModeController_ ensureOverlayHiddenWithAnimation:NO delay:NO];
957 - (void)disableBarVisibilityUpdates {
958 // Early escape if there's nothing to do.
959 if (!barVisibilityUpdatesEnabled_)
962 barVisibilityUpdatesEnabled_ = NO;
963 [presentationModeController_ cancelAnimationAndTimers];
966 - (void)hideOverlayIfPossibleWithAnimation:(BOOL)animation delay:(BOOL)delay {
967 if (!barVisibilityUpdatesEnabled_ || [barVisibilityLocks_ count])
969 [presentationModeController_ ensureOverlayHiddenWithAnimation:animation
973 - (CGFloat)toolbarDividerOpacity {
974 return [bookmarkBarController_ toolbarDividerOpacity];
977 - (void)updateSubviewZOrder:(BOOL)inPresentationMode {
978 NSView* contentView = [[self window] contentView];
979 NSView* toolbarView = [toolbarController_ view];
981 if (inPresentationMode) {
982 // Toolbar is above tab contents so that it can slide down from top of
984 [contentView cr_ensureSubview:toolbarView
985 isPositioned:NSWindowAbove
986 relativeTo:[self tabContentArea]];
988 // Toolbar is below tab contents so that the info bar arrow can appear above
990 [contentView cr_ensureSubview:toolbarView
991 isPositioned:NSWindowBelow
992 relativeTo:[self tabContentArea]];
995 // The bookmark bar is always below the toolbar.
996 [contentView cr_ensureSubview:[bookmarkBarController_ view]
997 isPositioned:NSWindowBelow
998 relativeTo:toolbarView];
1000 if (inPresentationMode) {
1001 // In presentation mode the info bar is below all other views.
1002 [contentView cr_ensureSubview:[infoBarContainerController_ view]
1003 isPositioned:NSWindowBelow
1004 relativeTo:[self tabContentArea]];
1006 // Above the toolbar but still below tab contents. Similar to the bookmark
1007 // bar, this allows Instant results to be above the info bar.
1008 [contentView cr_ensureSubview:[infoBarContainerController_ view]
1009 isPositioned:NSWindowAbove
1010 relativeTo:toolbarView];
1013 // The find bar is above everything.
1014 if (findBarCocoaController_) {
1015 NSView* relativeView = nil;
1016 if (inPresentationMode)
1017 relativeView = toolbarView;
1019 relativeView = [self tabContentArea];
1020 [contentView cr_ensureSubview:[findBarCocoaController_ view]
1021 isPositioned:NSWindowAbove
1022 relativeTo:relativeView];
1025 if (floatingBarBackingView_) {
1026 if ([floatingBarBackingView_ cr_isBelowView:[self tabContentArea]])
1027 [floatingBarBackingView_ removeFromSuperview];
1028 if ([self placeBookmarkBarBelowInfoBar]) {
1029 [contentView cr_ensureSubview:floatingBarBackingView_
1030 isPositioned:NSWindowAbove
1031 relativeTo:[bookmarkBarController_ view]];
1033 [contentView cr_ensureSubview:floatingBarBackingView_
1034 isPositioned:NSWindowBelow
1035 relativeTo:[bookmarkBarController_ view]];
1040 - (BOOL)shouldAllowOverlappingViews:(BOOL)inPresentationMode {
1041 if (inPresentationMode)
1044 if (findBarCocoaController_ &&
1045 ![[findBarCocoaController_ findBarView] isHidden]) {
1049 if (overlappedViewCount_)
1055 - (void)updateAllowOverlappingViews:(BOOL)inPresentationMode {
1056 WebContents* contents = browser_->tab_strip_model()->GetActiveWebContents();
1060 BOOL allowOverlappingViews =
1061 [self shouldAllowOverlappingViews:inPresentationMode];
1063 // The rendering path with overlapping views disabled causes bugs when
1064 // transitioning between composited and non-composited mode.
1065 // http://crbug.com/279472
1066 allowOverlappingViews = YES;
1067 contents->SetAllowOverlappingViews(allowOverlappingViews);
1069 WebContents* devTools = DevToolsWindow::GetInTabWebContents(contents, NULL);
1071 devTools->SetAllowOverlappingViews(allowOverlappingViews);
1074 - (void)updateInfoBarTipVisibility {
1075 // If there's no toolbar then hide the infobar tip.
1076 [infoBarContainerController_
1077 setShouldSuppressTopInfoBarTip:![self hasToolbar]];
1080 @end // @implementation BrowserWindowController(Private)