mac: Don't add subviews to NSThemeFrame on OSX 10.10.
[chromium-blink-merge.git] / chrome / browser / ui / cocoa / browser_window_controller_private.mm
blobe1b7885bd2a795e90f310c1899a97478ede4af75
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"
7 #include <cmath>
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_controller.h"
37 #import "chrome/browser/ui/cocoa/tabs/tab_strip_view.h"
38 #import "chrome/browser/ui/cocoa/toolbar/toolbar_controller.h"
39 #import "chrome/browser/ui/cocoa/version_independent_window.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;
52 namespace {
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
62 // left of the icon.
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;
72 }  // namespace
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()
84           delegate:self]);
87 - (void)saveWindowPositionIfNeeded {
88   if (!chrome::ShouldSaveWindowPlacement(browser_.get()))
89     return;
91   // If we're in fullscreen mode, save the position of the regular window
92   // instead.
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
114   // saving.
115   // TODO(rohitrao): We should just not save anything for fullscreen windows.
116   // http://crbug.com/36479.
117   if (!windowScreen)
118     return;
120   // Only save main window information to preferences.
121   PrefService* prefs = browser_->profile()->GetPrefs();
122   if (!prefs || browser_ != chrome::GetLastActiveBrowser())
123     return;
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(
130       prefs,
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
151   //    normal toolbar.
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;
160       break;
161     }
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;
167       } else {
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;
172       }
173       break;
174     }
175   }
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.
223       maxY += std::floor(
224           revealAmount - [fullscreenModeController_ menuBarHeight]);
225     }
226     maxY = [self layoutTabStripAtMaxY:maxY
227                                 width:width
228                            fullscreen:[self isFullscreen]];
229   }
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
252   // hidden.
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);
261   }
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]];
282   // Update the position of the active constrained window sheet.  We force this
283   // here because the |sheetParentView| may not have been resized (e.g., to
284   // prevent jank during a fullscreen mode transition), but constrained window
285   // sheets also compute their position based on the bookmark bar and toolbar.
286   content::WebContents* const activeWebContents =
287       browser_->tab_strip_model()->GetActiveWebContents();
288   NSView* const sheetParentView = activeWebContents ?
289       GetSheetParentViewForWebContents(activeWebContents) : nil;
290   if (sheetParentView) {
291     [[NSNotificationCenter defaultCenter]
292       postNotificationName:NSViewFrameDidChangeNotification
293                     object:sheetParentView];
294   }
297 - (CGFloat)floatingBarHeight {
298   if (![self inPresentationMode])
299     return 0;
301   CGFloat totalHeight = [presentationModeController_ floatingBarVerticalOffset];
303   if ([self hasTabStrip])
304     totalHeight += NSHeight([[self tabStripView] frame]);
306   if ([self hasToolbar]) {
307     totalHeight += NSHeight([[toolbarController_ view] frame]);
308   } else if ([self hasLocationBar]) {
309     totalHeight += NSHeight([[toolbarController_ view] frame]) +
310                    kLocBarTopInset + kLocBarBottomInset;
311   }
313   if (![self placeBookmarkBarBelowInfoBar])
314     totalHeight += NSHeight([[bookmarkBarController_ view] frame]);
316   return totalHeight;
319 - (CGFloat)layoutTabStripAtMaxY:(CGFloat)maxY
320                           width:(CGFloat)width
321                      fullscreen:(BOOL)fullscreen {
322   // Nothing to do if no tab strip.
323   if (![self hasTabStrip])
324     return maxY;
326   NSView* tabStripView = [self tabStripView];
327   CGFloat tabStripHeight = NSHeight([tabStripView frame]);
328   maxY -= tabStripHeight;
329   [tabStripView setFrame:NSMakeRect(0, maxY, width, tabStripHeight)];
331   // Set left indentation based on fullscreen mode status.
332   [tabStripController_ setLeftIndentForControls:(fullscreen ? 0 :
333       [[tabStripController_ class] defaultLeftIndentForControls])];
335   // Lay out the icognito/avatar badge because calculating the indentation on
336   // the right depends on it.
337   NSView* avatarButton = [avatarButtonController_ view];
338   if ([self shouldShowAvatar]) {
339     CGFloat badgeXOffset = -kAvatarRightOffset;
340     CGFloat badgeYOffset = 0;
341     CGFloat buttonHeight = NSHeight([avatarButton frame]);
343     if ([self shouldUseNewAvatarButton]) {
344       // The fullscreen icon is displayed to the right of the avatar button.
345       if (![self isFullscreen])
346         badgeXOffset -= kFullscreenIconWidth;
347       // Center the button vertically on the tabstrip.
348       badgeYOffset = (tabStripHeight - buttonHeight) / 2;
349     } else {
350       // Actually place the badge *above* |maxY|, by +2 to miss the divider.
351       badgeYOffset = 2 * [[avatarButton superview] cr_lineWidth];
352     }
354     [avatarButton setFrameSize:NSMakeSize(NSWidth([avatarButton frame]),
355         std::min(buttonHeight, tabStripHeight))];
356     NSPoint origin =
357         NSMakePoint(width - NSWidth([avatarButton frame]) + badgeXOffset,
358                     maxY + badgeYOffset);
359     [avatarButton setFrameOrigin:origin];
360     [avatarButton setHidden:NO];  // Make sure it's shown.
361   }
363   // Calculate the right indentation.  The default indentation built into the
364   // tabstrip leaves enough room for the fullscreen button or presentation mode
365   // toggle button on Lion.  On non-Lion systems, the right indent needs to be
366   // adjusted to make room for the new tab button when an avatar is present.
367   CGFloat rightIndent = 0;
368   if (base::mac::IsOSLionOrLater() &&
369       [[self window] isKindOfClass:[FramedBrowserWindow class]]) {
370     FramedBrowserWindow* window =
371         static_cast<FramedBrowserWindow*>([self window]);
372     rightIndent += -[window fullScreenButtonOriginAdjustment].x;
374     // The new avatar is wider than the default indentation, so we need to
375     // account for its width.
376     if ([self shouldUseNewAvatarButton])
377       rightIndent += NSWidth([avatarButton frame]) + kAvatarTabStripShrink;
378   } else if ([self shouldShowAvatar]) {
379     rightIndent += kAvatarTabStripShrink +
380         NSWidth([avatarButton frame]) + kAvatarRightOffset;
381   }
382   [tabStripController_ setRightIndentForControls:rightIndent];
384   // Go ahead and layout the tabs.
385   [tabStripController_ layoutTabsWithoutAnimation];
387   return maxY;
390 - (CGFloat)layoutToolbarAtMinX:(CGFloat)minX
391                           maxY:(CGFloat)maxY
392                          width:(CGFloat)width {
393   NSView* toolbarView = [toolbarController_ view];
394   NSRect toolbarFrame = [toolbarView frame];
395   if ([self hasToolbar]) {
396     // The toolbar is present in the window, so we make room for it.
397     DCHECK(![toolbarView isHidden]);
398     toolbarFrame.origin.x = minX;
399     toolbarFrame.origin.y = maxY - NSHeight(toolbarFrame);
400     toolbarFrame.size.width = width;
401     maxY -= NSHeight(toolbarFrame);
402   } else {
403     if ([self hasLocationBar]) {
404       // Location bar is present with no toolbar. Put a border of
405       // |kLocBar...Inset| pixels around the location bar.
406       // TODO(viettrungluu): This is moderately ridiculous. The toolbar should
407       // really be aware of what its height should be (the way the toolbar
408       // compression stuff is currently set up messes things up).
409       DCHECK(![toolbarView isHidden]);
410       toolbarFrame.origin.x = kLocBarLeftRightInset;
411       toolbarFrame.origin.y = maxY - NSHeight(toolbarFrame) - kLocBarTopInset;
412       toolbarFrame.size.width = width - 2 * kLocBarLeftRightInset;
413       maxY -= kLocBarTopInset + NSHeight(toolbarFrame) + kLocBarBottomInset;
414     } else {
415       DCHECK([toolbarView isHidden]);
416     }
417   }
418   [toolbarView setFrame:toolbarFrame];
419   return maxY;
422 - (BOOL)placeBookmarkBarBelowInfoBar {
423   // If we are currently displaying the NTP detached bookmark bar or animating
424   // to/from it (from/to anything else), we display the bookmark bar below the
425   // info bar.
426   return [bookmarkBarController_ isInState:BookmarkBar::DETACHED] ||
427          [bookmarkBarController_ isAnimatingToState:BookmarkBar::DETACHED] ||
428          [bookmarkBarController_ isAnimatingFromState:BookmarkBar::DETACHED];
431 - (CGFloat)layoutBookmarkBarAtMinX:(CGFloat)minX
432                               maxY:(CGFloat)maxY
433                              width:(CGFloat)width {
434   [bookmarkBarController_ updateHiddenState];
436   NSView* bookmarkBarView = [bookmarkBarController_ view];
437   NSRect frame = [bookmarkBarView frame];
438   frame.origin.x = minX;
439   frame.origin.y = maxY - NSHeight(frame);
440   frame.size.width = width;
441   [bookmarkBarView setFrame:frame];
442   maxY -= NSHeight(frame);
444   // Pin the bookmark bar to the top of the window and make the width flexible.
445   [bookmarkBarView setAutoresizingMask:NSViewWidthSizable | NSViewMinYMargin];
447   // TODO(viettrungluu): Does this really belong here? Calling it shouldn't be
448   // necessary in the non-NTP case.
449   [bookmarkBarController_ layoutSubviews];
451   return maxY;
454 - (void)layoutFloatingBarBackingView:(NSRect)frame
455                     presentationMode:(BOOL)presentationMode {
456   // Only display when in presentation mode.
457   if (presentationMode) {
458     // For certain window types such as app windows (e.g., the dev tools
459     // window), there's no actual overlay. (Displaying one would result in an
460     // overly sliding in only under the menu, which gives an ugly effect.)
461     if (floatingBarBackingView_.get()) {
462       // Set its frame.
463       [floatingBarBackingView_ setFrame:frame];
464     }
466     // But we want the logic to work as usual (for show/hide/etc. purposes).
467     [presentationModeController_ overlayFrameChanged:frame];
468   } else {
469     // Okay to call even if |floatingBarBackingView_| is nil.
470     if ([floatingBarBackingView_ superview])
471       [floatingBarBackingView_ removeFromSuperview];
472   }
475 - (CGFloat)layoutInfoBarAtMinX:(CGFloat)minX
476                           maxY:(CGFloat)maxY
477                          width:(CGFloat)width {
478   NSView* containerView = [infoBarContainerController_ view];
479   NSRect containerFrame = [containerView frame];
480   maxY -= NSHeight(containerFrame);
481   maxY += [infoBarContainerController_ overlappingTipHeight];
482   containerFrame.origin.x = minX;
483   containerFrame.origin.y = maxY;
484   containerFrame.size.width = width;
485   [containerView setFrame:containerFrame];
486   return maxY;
489 - (CGFloat)layoutDownloadShelfAtMinX:(CGFloat)minX
490                                 minY:(CGFloat)minY
491                                width:(CGFloat)width {
492   if (downloadShelfController_.get()) {
493     NSView* downloadView = [downloadShelfController_ view];
494     NSRect downloadFrame = [downloadView frame];
495     downloadFrame.origin.x = minX;
496     downloadFrame.origin.y = minY;
497     downloadFrame.size.width = width;
498     [downloadView setFrame:downloadFrame];
499     minY += NSHeight(downloadFrame);
500   }
501   return minY;
504 - (void)layoutTabContentArea:(NSRect)newFrame {
505   NSView* tabContentView = [self tabContentArea];
506   NSRect tabContentFrame = [tabContentView frame];
508   bool contentShifted =
509       NSMaxY(tabContentFrame) != NSMaxY(newFrame) ||
510       NSMinX(tabContentFrame) != NSMinX(newFrame);
512   tabContentFrame = newFrame;
513   [tabContentView setFrame:tabContentFrame];
515   // If the relayout shifts the content area up or down, let the renderer know.
516   if (contentShifted) {
517     if (WebContents* contents =
518             browser_->tab_strip_model()->GetActiveWebContents()) {
519       if (RenderWidgetHostView* rwhv = contents->GetRenderWidgetHostView())
520         rwhv->WindowFrameChanged();
521     }
522   }
525 - (void)adjustToolbarAndBookmarkBarForCompression:(CGFloat)compression {
526   CGFloat newHeight =
527       [toolbarController_ desiredHeightForCompression:compression];
528   NSRect toolbarFrame = [[toolbarController_ view] frame];
529   CGFloat deltaH = newHeight - toolbarFrame.size.height;
531   if (deltaH == 0)
532     return;
534   toolbarFrame.size.height = newHeight;
535   NSRect bookmarkFrame = [[bookmarkBarController_ view] frame];
536   bookmarkFrame.size.height = bookmarkFrame.size.height - deltaH;
537   [[toolbarController_ view] setFrame:toolbarFrame];
538   [[bookmarkBarController_ view] setFrame:bookmarkFrame];
539   [self layoutSubviews];
542 // Fullscreen and presentation mode methods
544 - (void)moveViewsForImmersiveFullscreen:(BOOL)fullscreen
545                           regularWindow:(NSWindow*)regularWindow
546                        fullscreenWindow:(NSWindow*)fullscreenWindow {
547   NSWindow* sourceWindow = fullscreen ? regularWindow : fullscreenWindow;
548   NSWindow* destWindow = fullscreen ? fullscreenWindow : regularWindow;
550   // Close the bookmark bubble, if it's open.  Use |-ok:| instead of |-cancel:|
551   // or |-close| because that matches the behavior when the bubble loses key
552   // status.
553   [bookmarkBubbleController_ ok:self];
555   // Save the current first responder so we can restore after views are moved.
556   base::scoped_nsobject<FocusTracker> focusTracker(
557       [[FocusTracker alloc] initWithWindow:sourceWindow]);
559   // While we move views (and focus) around, disable any bar visibility changes.
560   [self disableBarVisibilityUpdates];
562   // Retain the tab strip view while we remove it from its superview.
563   base::scoped_nsobject<NSView> tabStripView;
564   if ([self hasTabStrip]) {
565     tabStripView.reset([[self tabStripView] retain]);
566     [tabStripView removeFromSuperview];
567   }
569   // Ditto for the content view.
570   base::scoped_nsobject<NSView> contentView(
571       [[sourceWindow contentView] retain]);
572   // Disable autoresizing of subviews while we move views around. This prevents
573   // spurious renderer resizes.
574   [contentView setAutoresizesSubviews:NO];
575   [contentView removeFromSuperview];
577   // Have to do this here, otherwise later calls can crash because the window
578   // has no delegate.
579   [sourceWindow setDelegate:nil];
580   [destWindow setDelegate:self];
582   // With this call, valgrind complains that a "Conditional jump or move depends
583   // on uninitialised value(s)".  The error happens in -[NSThemeFrame
584   // drawOverlayRect:].  I'm pretty convinced this is an Apple bug, but there is
585   // no visual impact.  I have been unable to tickle it away with other window
586   // or view manipulation Cocoa calls.  Stack added to suppressions_mac.txt.
587   [contentView setAutoresizesSubviews:YES];
588   [destWindow setContentView:contentView];
590   // Move the incognito badge if present.
591   if ([self shouldShowAvatar]) {
592     NSView* avatarButtonView = [avatarButtonController_ view];
594     [avatarButtonView removeFromSuperview];
595     [avatarButtonView setHidden:YES];  // Will be shown in layout.
596     [[destWindow cr_windowView] addSubview:avatarButtonView];
597   }
599   // Add the tab strip after setting the content view and moving the incognito
600   // badge (if any), so that the tab strip will be on top (in the z-order).
601   if ([self hasTabStrip])
602     [[destWindow cr_windowView] addSubview:tabStripView];
604   [sourceWindow setWindowController:nil];
605   [self setWindow:destWindow];
606   [destWindow setWindowController:self];
608   // Move the status bubble over, if we have one.
609   if (statusBubble_)
610     statusBubble_->SwitchParentWindow(destWindow);
612   // Move the title over.
613   [destWindow setTitle:[sourceWindow title]];
615   // The window needs to be onscreen before we can set its first responder.
616   // Ordering the window to the front can change the active Space (either to
617   // the window's old Space or to the application's assigned Space). To prevent
618   // this by temporarily change the collectionBehavior.
619   NSWindowCollectionBehavior behavior = [sourceWindow collectionBehavior];
620   [destWindow setCollectionBehavior:
621       NSWindowCollectionBehaviorMoveToActiveSpace];
622   [destWindow makeKeyAndOrderFront:self];
623   [destWindow setCollectionBehavior:behavior];
625   if (![focusTracker restoreFocusInWindow:destWindow]) {
626     // During certain types of fullscreen transitions, the view that had focus
627     // may have gone away (e.g., the one for a Flash FS widget).  In this case,
628     // FocusTracker will fail to restore focus to anything, so we set the focus
629     // to the tab contents as a reasonable fall-back.
630     [self focusTabContents];
631   }
632   [sourceWindow orderOut:self];
634   // We're done moving focus, so re-enable bar visibility changes.
635   [self enableBarVisibilityUpdates];
638 - (void)setPresentationModeInternal:(BOOL)presentationMode
639                       forceDropdown:(BOOL)forceDropdown {
640   if (presentationMode == [self inPresentationMode])
641     return;
643   if (presentationMode) {
644     BOOL fullscreen_for_tab =
645         browser_->fullscreen_controller()->IsWindowFullscreenForTabOrPending();
646     BOOL kiosk_mode =
647         CommandLine::ForCurrentProcess()->HasSwitch(switches::kKioskMode);
648     BOOL showDropdown = !fullscreen_for_tab &&
649         !kiosk_mode &&
650         (forceDropdown || [self floatingBarHasFocus]);
651     NSView* contentView = [[self window] contentView];
652     presentationModeController_.reset(
653         [[PresentationModeController alloc] initWithBrowserController:self]);
654     [presentationModeController_ enterPresentationModeForContentView:contentView
655                                  showDropdown:showDropdown];
656   } else {
657     [presentationModeController_ exitPresentationMode];
658     presentationModeController_.reset();
659   }
661   [self adjustUIForPresentationMode:presentationMode];
662   [self layoutSubviews];
665 - (void)enterImmersiveFullscreen {
666   // |-isFullscreen:| will return YES from here onwards.
667   enteringFullscreen_ = YES;  // Set to NO by |-windowDidEnterFullScreen:|.
669   // Fade to black.
670   const CGDisplayReservationInterval kFadeDurationSeconds = 0.6;
671   Boolean didFadeOut = NO;
672   CGDisplayFadeReservationToken token;
673   if (CGAcquireDisplayFadeReservation(kFadeDurationSeconds, &token)
674       == kCGErrorSuccess) {
675     didFadeOut = YES;
676     CGDisplayFade(token, kFadeDurationSeconds / 2, kCGDisplayBlendNormal,
677         kCGDisplayBlendSolidColor, 0.0, 0.0, 0.0, /*synchronous=*/true);
678   }
680   // Create the fullscreen window.
681   fullscreenWindow_.reset([[self createFullscreenWindow] retain]);
682   savedRegularWindow_ = [[self window] retain];
683   savedRegularWindowFrame_ = [savedRegularWindow_ frame];
685   [self moveViewsForImmersiveFullscreen:YES
686                           regularWindow:[self window]
687                        fullscreenWindow:fullscreenWindow_.get()];
689   // When simplified fullscreen is enabled, do not enter presentation mode.
690   const CommandLine* command_line = CommandLine::ForCurrentProcess();
691   if (command_line->HasSwitch(switches::kEnableSimplifiedFullscreen)) {
692     // TODO(rohitrao): Add code to manage the menubar here.
693   } else {
694     [self adjustUIForPresentationMode:YES];
695     [self setPresentationModeInternal:YES forceDropdown:NO];
696   }
698   [self layoutSubviews];
700   [self windowDidEnterFullScreen:nil];
702   // Fade back in.
703   if (didFadeOut) {
704     CGDisplayFade(token, kFadeDurationSeconds / 2, kCGDisplayBlendSolidColor,
705         kCGDisplayBlendNormal, 0.0, 0.0, 0.0, /*synchronous=*/false);
706     CGReleaseDisplayFadeReservation(token);
707   }
710 - (void)exitImmersiveFullscreen {
711   // Fade to black.
712   const CGDisplayReservationInterval kFadeDurationSeconds = 0.6;
713   Boolean didFadeOut = NO;
714   CGDisplayFadeReservationToken token;
715   if (CGAcquireDisplayFadeReservation(kFadeDurationSeconds, &token)
716       == kCGErrorSuccess) {
717     didFadeOut = YES;
718     CGDisplayFade(token, kFadeDurationSeconds / 2, kCGDisplayBlendNormal,
719         kCGDisplayBlendSolidColor, 0.0, 0.0, 0.0, /*synchronous=*/true);
720   }
722   // When simplified fullscreen is enabled, the menubar status is managed
723   // directly by BWC.
724   const CommandLine* command_line = CommandLine::ForCurrentProcess();
725   if (command_line->HasSwitch(switches::kEnableSimplifiedFullscreen)) {
726     // TODO(rohitrao): Add code to manage the menubar here.
727   }
729   [self windowWillExitFullScreen:nil];
731   [self moveViewsForImmersiveFullscreen:NO
732                           regularWindow:savedRegularWindow_
733                        fullscreenWindow:fullscreenWindow_.get()];
735   // When exiting fullscreen mode, we need to call layoutSubviews manually.
736   [savedRegularWindow_ autorelease];
737   savedRegularWindow_ = nil;
738   fullscreenWindow_.reset();
739   [self layoutSubviews];
741   [self windowDidExitFullScreen:nil];
743   // Fade back in.
744   if (didFadeOut) {
745     CGDisplayFade(token, kFadeDurationSeconds / 2, kCGDisplayBlendSolidColor,
746         kCGDisplayBlendNormal, 0.0, 0.0, 0.0, /*synchronous=*/false);
747     CGReleaseDisplayFadeReservation(token);
748   }
751 // TODO(rohitrao): This function has shrunk into uselessness, and
752 // |-setFullscreen:| has grown rather large.  Find a good way to break up
753 // |-setFullscreen:| into smaller pieces.  http://crbug.com/36449
754 - (void)adjustUIForPresentationMode:(BOOL)fullscreen {
755   // Create the floating bar backing view if necessary.
756   if (fullscreen && !floatingBarBackingView_.get() &&
757       ([self hasTabStrip] || [self hasToolbar] || [self hasLocationBar])) {
758     floatingBarBackingView_.reset(
759         [[FloatingBarBackingView alloc] initWithFrame:NSZeroRect]);
760     [floatingBarBackingView_ setAutoresizingMask:(NSViewWidthSizable |
761                                                   NSViewMinYMargin)];
762   }
764   // Force the bookmark bar z-order to update.
765   [[bookmarkBarController_ view] removeFromSuperview];
766   [self updateSubviewZOrder:fullscreen];
767   [self updateAllowOverlappingViews:fullscreen];
770 - (void)showFullscreenExitBubbleIfNecessary {
771   // This method is called in response to
772   // |-updateFullscreenExitBubbleURL:bubbleType:|. If we're in the middle of the
773   // transition into fullscreen (i.e., using the System Fullscreen API), do not
774   // show the bubble because it will cause visual jank
775   // (http://crbug.com/130649). This will be called again as part of
776   // |-windowDidEnterFullScreen:|, so arrange to do that work then instead.
777   if (enteringFullscreen_)
778     return;
780   [presentationModeController_ ensureOverlayHiddenWithAnimation:NO delay:NO];
782   if (fullscreenBubbleType_ == FEB_TYPE_NONE ||
783       fullscreenBubbleType_ == FEB_TYPE_BROWSER_FULLSCREEN_EXIT_INSTRUCTION) {
784     // Show no exit instruction bubble on Mac when in Browser Fullscreen.
785     [self destroyFullscreenExitBubbleIfNecessary];
786   } else {
787     [fullscreenExitBubbleController_ closeImmediately];
788     fullscreenExitBubbleController_.reset(
789         [[FullscreenExitBubbleController alloc]
790             initWithOwner:self
791                   browser:browser_.get()
792                       url:fullscreenUrl_
793                bubbleType:fullscreenBubbleType_]);
794     [fullscreenExitBubbleController_ showWindow];
795   }
798 - (void)destroyFullscreenExitBubbleIfNecessary {
799   [fullscreenExitBubbleController_ closeImmediately];
800   fullscreenExitBubbleController_.reset();
803 - (void)contentViewDidResize:(NSNotification*)notification {
804   [self layoutSubviews];
807 - (void)registerForContentViewResizeNotifications {
808   [[NSNotificationCenter defaultCenter]
809       addObserver:self
810          selector:@selector(contentViewDidResize:)
811              name:NSViewFrameDidChangeNotification
812            object:[[self window] contentView]];
815 - (void)deregisterForContentViewResizeNotifications {
816   [[NSNotificationCenter defaultCenter]
817       removeObserver:self
818                 name:NSViewFrameDidChangeNotification
819               object:[[self window] contentView]];
822 - (NSSize)window:(NSWindow*)window
823     willUseFullScreenContentSize:(NSSize)proposedSize {
824   return proposedSize;
827 - (NSApplicationPresentationOptions)window:(NSWindow*)window
828     willUseFullScreenPresentationOptions:(NSApplicationPresentationOptions)opt {
829   return (opt |
830           NSApplicationPresentationAutoHideDock |
831           NSApplicationPresentationAutoHideMenuBar);
834 - (void)windowWillEnterFullScreen:(NSNotification*)notification {
835   if (notification)  // For System Fullscreen when non-nil.
836     [self registerForContentViewResizeNotifications];
838   NSWindow* window = [self window];
839   savedRegularWindowFrame_ = [window frame];
840   BOOL mode = enteringPresentationMode_ ||
841        browser_->fullscreen_controller()->IsWindowFullscreenForTabOrPending();
842   enteringFullscreen_ = YES;
843   [self setPresentationModeInternal:mode forceDropdown:NO];
846 - (void)windowDidEnterFullScreen:(NSNotification*)notification {
847   // In Yosemite, some combination of the titlebar and toolbar always show in
848   // full-screen mode. We do not want either to show. Search for the window that
849   // contains the views, and hide it. There is no need to ever unhide the view.
850   // http://crbug.com/380235
851   if (base::mac::IsOSYosemiteOrLater()) {
852     for (NSWindow* window in [[NSApplication sharedApplication] windows]) {
853       if ([window
854               isKindOfClass:NSClassFromString(@"NSToolbarFullScreenWindow")]) {
855         [window.contentView setHidden:YES];
856       }
857     }
858   }
860   if (notification)  // For System Fullscreen when non-nil.
861     [self deregisterForContentViewResizeNotifications];
862   enteringFullscreen_ = NO;
863   enteringPresentationMode_ = NO;
865   const CommandLine* command_line = CommandLine::ForCurrentProcess();
866   if (command_line->HasSwitch(switches::kEnableSimplifiedFullscreen) &&
867       fullscreenUrl_.is_empty()) {
868     fullscreenModeController_.reset([[FullscreenModeController alloc]
869         initWithBrowserWindowController:self]);
870   }
872   [self showFullscreenExitBubbleIfNecessary];
873   browser_->WindowFullscreenStateChanged();
876 - (void)windowWillExitFullScreen:(NSNotification*)notification {
877   if (notification)  // For System Fullscreen when non-nil.
878     [self registerForContentViewResizeNotifications];
879   fullscreenModeController_.reset();
880   [self destroyFullscreenExitBubbleIfNecessary];
881   [self setPresentationModeInternal:NO forceDropdown:NO];
884 - (void)windowDidExitFullScreen:(NSNotification*)notification {
885   if (notification)  // For System Fullscreen when non-nil.
886     [self deregisterForContentViewResizeNotifications];
887   browser_->WindowFullscreenStateChanged();
890 - (void)windowDidFailToEnterFullScreen:(NSWindow*)window {
891   [self deregisterForContentViewResizeNotifications];
892   enteringFullscreen_ = NO;
893   [self setPresentationModeInternal:NO forceDropdown:NO];
895   // Force a relayout to try and get the window back into a reasonable state.
896   [self layoutSubviews];
899 - (void)windowDidFailToExitFullScreen:(NSWindow*)window {
900   [self deregisterForContentViewResizeNotifications];
902   // Force a relayout to try and get the window back into a reasonable state.
903   [self layoutSubviews];
906 - (void)enableBarVisibilityUpdates {
907   // Early escape if there's nothing to do.
908   if (barVisibilityUpdatesEnabled_)
909     return;
911   barVisibilityUpdatesEnabled_ = YES;
913   if ([barVisibilityLocks_ count])
914     [presentationModeController_ ensureOverlayShownWithAnimation:NO delay:NO];
915   else
916     [presentationModeController_ ensureOverlayHiddenWithAnimation:NO delay:NO];
919 - (void)disableBarVisibilityUpdates {
920   // Early escape if there's nothing to do.
921   if (!barVisibilityUpdatesEnabled_)
922     return;
924   barVisibilityUpdatesEnabled_ = NO;
925   [presentationModeController_ cancelAnimationAndTimers];
928 - (CGFloat)toolbarDividerOpacity {
929   return [bookmarkBarController_ toolbarDividerOpacity];
932 - (void)updateSubviewZOrder:(BOOL)inPresentationMode {
933   NSView* contentView = [[self window] contentView];
934   NSView* toolbarView = [toolbarController_ view];
936   if (inPresentationMode) {
937     // Toolbar is above tab contents so that it can slide down from top of
938     // screen.
939     [contentView cr_ensureSubview:toolbarView
940                      isPositioned:NSWindowAbove
941                        relativeTo:[self tabContentArea]];
942   } else {
943     // Toolbar is below tab contents so that the info bar arrow can appear above
944     // it.
945     [contentView cr_ensureSubview:toolbarView
946                      isPositioned:NSWindowBelow
947                        relativeTo:[self tabContentArea]];
948   }
950   // The bookmark bar is always below the toolbar.
951   [contentView cr_ensureSubview:[bookmarkBarController_ view]
952                    isPositioned:NSWindowBelow
953                      relativeTo:toolbarView];
955   if (inPresentationMode) {
956     // In presentation mode the info bar is below all other views.
957     [contentView cr_ensureSubview:[infoBarContainerController_ view]
958                      isPositioned:NSWindowBelow
959                        relativeTo:[self tabContentArea]];
960   } else {
961     // Above the toolbar but still below tab contents. Similar to the bookmark
962     // bar, this allows Instant results to be above the info bar.
963     [contentView cr_ensureSubview:[infoBarContainerController_ view]
964                      isPositioned:NSWindowAbove
965                        relativeTo:toolbarView];
966   }
968   // The find bar is above everything.
969   if (findBarCocoaController_) {
970     NSView* relativeView = nil;
971     if (inPresentationMode)
972       relativeView = toolbarView;
973     else
974       relativeView = [self tabContentArea];
975     [contentView cr_ensureSubview:[findBarCocoaController_ view]
976                      isPositioned:NSWindowAbove
977                        relativeTo:relativeView];
978   }
980   if (floatingBarBackingView_) {
981     if ([floatingBarBackingView_ cr_isBelowView:[self tabContentArea]])
982       [floatingBarBackingView_ removeFromSuperview];
983     if ([self placeBookmarkBarBelowInfoBar]) {
984       [contentView cr_ensureSubview:floatingBarBackingView_
985                        isPositioned:NSWindowAbove
986                          relativeTo:[bookmarkBarController_ view]];
987     } else {
988       [contentView cr_ensureSubview:floatingBarBackingView_
989                        isPositioned:NSWindowBelow
990                          relativeTo:[bookmarkBarController_ view]];
991     }
992   }
995 - (BOOL)shouldAllowOverlappingViews:(BOOL)inPresentationMode {
996   if (inPresentationMode)
997     return YES;
999   if (findBarCocoaController_ &&
1000       ![[findBarCocoaController_ findBarView] isHidden]) {
1001     return YES;
1002   }
1004   if (overlappedViewCount_)
1005     return YES;
1007   return NO;
1010 - (void)updateAllowOverlappingViews:(BOOL)inPresentationMode {
1011   WebContents* contents = browser_->tab_strip_model()->GetActiveWebContents();
1012   if (!contents)
1013     return;
1015   BOOL allowOverlappingViews =
1016       [self shouldAllowOverlappingViews:inPresentationMode];
1018   // The rendering path with overlapping views disabled causes bugs when
1019   // transitioning between composited and non-composited mode.
1020   // http://crbug.com/279472
1021   allowOverlappingViews = YES;
1022   contents->SetAllowOverlappingViews(allowOverlappingViews);
1024   WebContents* devTools = DevToolsWindow::GetInTabWebContents(contents, NULL);
1025   if (devTools)
1026     devTools->SetAllowOverlappingViews(allowOverlappingViews);
1029 - (void)updateInfoBarTipVisibility {
1030   // If there's no toolbar then hide the infobar tip.
1031   [infoBarContainerController_
1032       setShouldSuppressTopInfoBarTip:![self hasToolbar]];
1035 @end  // @implementation BrowserWindowController(Private)