summaryrefslogtreecommitdiffstats
path: root/chrome/browser/ui/cocoa/browser_window_controller_private.mm
blob: 3874f2005a146a1393b43bd605710d18c9cbd265 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#import "chrome/browser/ui/cocoa/browser_window_controller_private.h"

#include <cmath>

#include "base/command_line.h"
#include "base/mac/mac_util.h"
#import "base/mac/scoped_nsobject.h"
#import "base/mac/sdk_forward_declarations.h"
#include "base/metrics/histogram.h"
#include "base/prefs/pref_service.h"
#include "base/prefs/scoped_user_pref_update.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/fullscreen.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/profiles/profile_avatar_icon_util.h"
#include "chrome/browser/ui/bookmarks/bookmark_tab_helper.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_window_state.h"
#import "chrome/browser/ui/cocoa/browser_window_layout.h"
#import "chrome/browser/ui/cocoa/dev_tools_controller.h"
#import "chrome/browser/ui/cocoa/fast_resize_view.h"
#import "chrome/browser/ui/cocoa/find_bar/find_bar_cocoa_controller.h"
#import "chrome/browser/ui/cocoa/floating_bar_backing_view.h"
#import "chrome/browser/ui/cocoa/framed_browser_window.h"
#import "chrome/browser/ui/cocoa/fullscreen_window.h"
#import "chrome/browser/ui/cocoa/infobars/infobar_container_controller.h"
#include "chrome/browser/ui/cocoa/last_active_browser_cocoa.h"
#import "chrome/browser/ui/cocoa/presentation_mode_controller.h"
#import "chrome/browser/ui/cocoa/profiles/avatar_button_controller.h"
#import "chrome/browser/ui/cocoa/profiles/avatar_icon_controller.h"
#import "chrome/browser/ui/cocoa/status_bubble_mac.h"
#import "chrome/browser/ui/cocoa/tab_contents/overlayable_contents_controller.h"
#import "chrome/browser/ui/cocoa/tabs/tab_strip_view.h"
#import "chrome/browser/ui/cocoa/toolbar/toolbar_controller.h"
#import "chrome/browser/ui/cocoa/version_independent_window.h"
#import "chrome/browser/ui/cocoa/website_settings/permission_bubble_cocoa.h"
#include "chrome/browser/ui/fullscreen/fullscreen_controller.h"
#include "chrome/browser/ui/tabs/tab_strip_model.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/pref_names.h"
#include "content/public/browser/render_widget_host_view.h"
#include "content/public/browser/web_contents.h"
#import "ui/base/cocoa/focus_tracker.h"
#import "ui/base/cocoa/nsview_additions.h"
#include "ui/base/ui_base_types.h"

using content::RenderWidgetHostView;
using content::WebContents;

namespace {

// Each time the user enters fullscreen, a single histogram enumeration is
// recorded. There are several relevant parameters, whose values are mapped
// directly into individual bits of the enumeration.
//
// + Fullscreen Mechanism: The mechanism by which the window's size is changed
// to encompass the entire screen. Bit 0.
//   - AppKit (value of bit: 1)
//   - Immersive (value of bit: 0)
//
// + Primary Screen: Whether the window is located on the screen at index 0.
// Depending on OSX version, this has different implications for menu bar
// visibility. Bit 1.
//   - Primary (value of bit: 1)
//   - Secondary (value of bit: 0)
//
// + Displays have separate spaces: An option available in Mission Control in
// OSX 10.9+. Bit 2.
//   - On (value of bit: 1)
//   - Off (value of bit: 0)
//
// + Multiple screens: Whether the user has multiple screens. If the window is
// located on a secondary screen, then there must be multiple screens. Bit 3.
//   - Yes (value of bit: 1)
//   - No (value of bit: 0)

enum FullscreenMechanism {
  IMMERSIVE_FULLSCREEN_MECHANISM,
  APPKIT_FULLSCREEN_MECHANISM,
};

enum {
  FULLSCREEN_MECHANISM_BIT = 0,
  PRIMARY_SCREEN_BIT = 1,
  DISPLAYS_SEPARATE_SPACES_BIT = 2,
  MULTIPLE_SCREENS_BIT = 3,
  BIT_COUNT
};

// Emits a histogram entry indicating that |window| is being made fullscreen.
void RecordFullscreenHistogram(FullscreenMechanism mechanism,
                               NSWindow* window) {
  NSArray* screens = [NSScreen screens];
  bool primary_screen = ([[window screen] isEqual:[screens objectAtIndex:0]]);
  bool displays_have_separate_spaces =
      [NSScreen respondsToSelector:@selector(screensHaveSeparateSpaces)] &&
      [NSScreen screensHaveSeparateSpaces];
  bool multiple_screens = [screens count] > 1;

  int output = 0;
  if (mechanism == APPKIT_FULLSCREEN_MECHANISM)
    output += 1 << FULLSCREEN_MECHANISM_BIT;

  if (primary_screen)
    output += 1 << PRIMARY_SCREEN_BIT;

  if (displays_have_separate_spaces)
    output += 1 << DISPLAYS_SEPARATE_SPACES_BIT;

  if (multiple_screens)
    output += 1 << MULTIPLE_SCREENS_BIT;

  int max_output = 1 << BIT_COUNT;
  UMA_HISTOGRAM_ENUMERATION("OSX.Fullscreen.Enter", output, max_output);
}

}  // namespace

@implementation BrowserWindowController(Private)

// Create the tab strip controller.
- (void)createTabStripController {
  DCHECK([overlayableContentsController_ activeContainer]);
  DCHECK([[overlayableContentsController_ activeContainer] window]);
  tabStripController_.reset([[TabStripController alloc]
      initWithView:[self tabStripView]
        switchView:[overlayableContentsController_ activeContainer]
           browser:browser_.get()
          delegate:self]);
}

- (void)saveWindowPositionIfNeeded {
  if (!chrome::ShouldSaveWindowPlacement(browser_.get()))
    return;

  // If we're in fullscreen mode, save the position of the regular window
  // instead.
  NSWindow* window =
      [self isInAnyFullscreenMode] ? savedRegularWindow_ : [self window];

  // Window positions are stored relative to the origin of the primary monitor.
  NSRect monitorFrame = [[[NSScreen screens] objectAtIndex:0] frame];
  NSScreen* windowScreen = [window screen];

  // Start with the window's frame, which is in virtual coordinates.
  // Do some y twiddling to flip the coordinate system.
  gfx::Rect bounds(NSRectToCGRect([window frame]));
  bounds.set_y(monitorFrame.size.height - bounds.y() - bounds.height());

  // Browser::SaveWindowPlacement saves information for session restore.
  ui::WindowShowState show_state = ui::SHOW_STATE_NORMAL;
  if ([window isMiniaturized])
    show_state = ui::SHOW_STATE_MINIMIZED;
  else if ([self isInAnyFullscreenMode])
    show_state = ui::SHOW_STATE_FULLSCREEN;
  chrome::SaveWindowPlacement(browser_.get(), bounds, show_state);

  // |windowScreen| can be nil (for example, if the monitor arrangement was
  // changed while in fullscreen mode).  If we see a nil screen, return without
  // saving.
  // TODO(rohitrao): We should just not save anything for fullscreen windows.
  // http://crbug.com/36479.
  if (!windowScreen)
    return;

  // Only save main window information to preferences.
  PrefService* prefs = browser_->profile()->GetPrefs();
  if (!prefs || browser_ != chrome::GetLastActiveBrowser())
    return;

  // Save the current work area, in flipped coordinates.
  gfx::Rect workArea(NSRectToCGRect([windowScreen visibleFrame]));
  workArea.set_y(monitorFrame.size.height - workArea.y() - workArea.height());

  scoped_ptr<DictionaryPrefUpdate> update =
      chrome::GetWindowPlacementDictionaryReadWrite(
          chrome::GetWindowName(browser_.get()),
          browser_->profile()->GetPrefs());
  base::DictionaryValue* windowPreferences = update->Get();
  windowPreferences->SetInteger("left", bounds.x());
  windowPreferences->SetInteger("top", bounds.y());
  windowPreferences->SetInteger("right", bounds.right());
  windowPreferences->SetInteger("bottom", bounds.bottom());
  windowPreferences->SetBoolean("maximized", false);
  windowPreferences->SetBoolean("always_on_top", false);
  windowPreferences->SetInteger("work_area_left", workArea.x());
  windowPreferences->SetInteger("work_area_top", workArea.y());
  windowPreferences->SetInteger("work_area_right", workArea.right());
  windowPreferences->SetInteger("work_area_bottom", workArea.bottom());
}

- (NSRect)window:(NSWindow*)window
willPositionSheet:(NSWindow*)sheet
       usingRect:(NSRect)defaultSheetRect {
  // Position the sheet as follows:
  //  - If the bookmark bar is hidden or shown as a bubble (on the NTP when the
  //    bookmark bar is disabled), position the sheet immediately below the
  //    normal toolbar.
  //  - If the bookmark bar is shown (attached to the normal toolbar), position
  //    the sheet below the bookmark bar.
  //  - If the bookmark bar is currently animating, position the sheet according
  //    to where the bar will be when the animation ends.
  switch ([bookmarkBarController_ currentState]) {
    case BookmarkBar::SHOW: {
      NSRect bookmarkBarFrame = [[bookmarkBarController_ view] frame];
      defaultSheetRect.origin.y = bookmarkBarFrame.origin.y;
      break;
    }
    case BookmarkBar::HIDDEN:
    case BookmarkBar::DETACHED: {
      if ([self hasToolbar]) {
        NSRect toolbarFrame = [[toolbarController_ view] frame];
        defaultSheetRect.origin.y = toolbarFrame.origin.y;
      } else {
        // The toolbar is not shown in application mode. The sheet should be
        // located at the top of the window, under the title of the window.
        defaultSheetRect.origin.y = NSHeight([[window contentView] frame]) -
                                    defaultSheetRect.size.height;
      }
      break;
    }
  }
  return defaultSheetRect;
}

- (void)layoutSubviews {
  // Suppress title drawing if necessary.
  if ([self.window respondsToSelector:@selector(setShouldHideTitle:)])
    [(id)self.window setShouldHideTitle:![self hasTitleBar]];

  [bookmarkBarController_ updateHiddenState];
  [self updateSubviewZOrder];

  base::scoped_nsobject<BrowserWindowLayout> layout(
      [[BrowserWindowLayout alloc] init]);
  [self updateLayoutParameters:layout];
  [self applyLayout:layout];

  [toolbarController_ setDividerOpacity:[self toolbarDividerOpacity]];
}

- (void)applyTabStripLayout:(const chrome::TabStripLayout&)layout {
  // Update the presence of the window controls.
  if (layout.addCustomWindowControls)
    [tabStripController_ addCustomWindowControls];
  else
    [tabStripController_ removeCustomWindowControls];

  // Update the layout of the avatar.
  if (!NSIsEmptyRect(layout.avatarFrame)) {
    NSView* avatarButton = [avatarButtonController_ view];
    [avatarButton setFrame:layout.avatarFrame];
    [avatarButton setHidden:NO];
  }

  // Check if the tab strip's frame has changed.
  BOOL requiresRelayout =
      !NSEqualRects([[self tabStripView] frame], layout.frame);

  // Check if the left indent has changed.
  if (layout.leftIndent != [tabStripController_ leftIndentForControls]) {
    [tabStripController_ setLeftIndentForControls:layout.leftIndent];
    requiresRelayout = YES;
  }

  // Check if the right indent has changed.
  if (layout.rightIndent != [tabStripController_ rightIndentForControls]) {
    [tabStripController_ setRightIndentForControls:layout.rightIndent];
    requiresRelayout = YES;
  }

  // It is undesirable to force tabs relayout when the tap strip's frame did
  // not change, because it will interrupt tab animations in progress.
  // In addition, there appears to be an AppKit bug on <10.9 where interrupting
  // a tab animation resulted in the tab frame being the animator's target
  // frame instead of the interrupting setFrame. (See http://crbug.com/415093)
  if (requiresRelayout) {
    [[self tabStripView] setFrame:layout.frame];
    [tabStripController_ layoutTabsWithoutAnimation];
  }
}

- (BOOL)placeBookmarkBarBelowInfoBar {
  // If we are currently displaying the NTP detached bookmark bar or animating
  // to/from it (from/to anything else), we display the bookmark bar below the
  // info bar.
  return [bookmarkBarController_ isInState:BookmarkBar::DETACHED] ||
         [bookmarkBarController_ isAnimatingToState:BookmarkBar::DETACHED] ||
         [bookmarkBarController_ isAnimatingFromState:BookmarkBar::DETACHED];
}

- (void)layoutTabContentArea:(NSRect)newFrame {
  NSView* tabContentView = [self tabContentArea];
  NSRect tabContentFrame = [tabContentView frame];

  bool contentShifted =
      NSMaxY(tabContentFrame) != NSMaxY(newFrame) ||
      NSMinX(tabContentFrame) != NSMinX(newFrame);

  tabContentFrame = newFrame;
  [tabContentView setFrame:tabContentFrame];

  // If the relayout shifts the content area up or down, let the renderer know.
  if (contentShifted) {
    if (WebContents* contents =
            browser_->tab_strip_model()->GetActiveWebContents()) {
      if (RenderWidgetHostView* rwhv = contents->GetRenderWidgetHostView())
        rwhv->WindowFrameChanged();
    }
  }
}

- (void)adjustToolbarAndBookmarkBarForCompression:(CGFloat)compression {
  CGFloat newHeight =
      [toolbarController_ desiredHeightForCompression:compression];
  NSRect toolbarFrame = [[toolbarController_ view] frame];
  CGFloat deltaH = newHeight - toolbarFrame.size.height;

  if (deltaH == 0)
    return;

  toolbarFrame.size.height = newHeight;
  NSRect bookmarkFrame = [[bookmarkBarController_ view] frame];
  bookmarkFrame.size.height = bookmarkFrame.size.height - deltaH;
  [[toolbarController_ view] setFrame:toolbarFrame];
  [[bookmarkBarController_ view] setFrame:bookmarkFrame];
  [self layoutSubviews];
}

// Fullscreen and presentation mode methods

- (void)moveViewsForImmersiveFullscreen:(BOOL)fullscreen
                          regularWindow:(NSWindow*)regularWindow
                       fullscreenWindow:(NSWindow*)fullscreenWindow {
  NSWindow* sourceWindow = fullscreen ? regularWindow : fullscreenWindow;
  NSWindow* destWindow = fullscreen ? fullscreenWindow : regularWindow;

  // Close the bookmark bubble, if it's open.  Use |-ok:| instead of |-cancel:|
  // or |-close| because that matches the behavior when the bubble loses key
  // status.
  [bookmarkBubbleController_ ok:self];

  // Save the current first responder so we can restore after views are moved.
  base::scoped_nsobject<FocusTracker> focusTracker(
      [[FocusTracker alloc] initWithWindow:sourceWindow]);

  // While we move views (and focus) around, disable any bar visibility changes.
  [self disableBarVisibilityUpdates];

  // Retain the tab strip view while we remove it from its superview.
  base::scoped_nsobject<NSView> tabStripView;
  if ([self hasTabStrip]) {
    tabStripView.reset([[self tabStripView] retain]);
    [tabStripView removeFromSuperview];
  }

  // Disable autoresizing of subviews while we move views around. This prevents
  // spurious renderer resizes.
  [self.chromeContentView setAutoresizesSubviews:NO];
  [self.chromeContentView removeFromSuperview];

  // Have to do this here, otherwise later calls can crash because the window
  // has no delegate.
  [sourceWindow setDelegate:nil];
  [destWindow setDelegate:self];

  // With this call, valgrind complains that a "Conditional jump or move depends
  // on uninitialised value(s)".  The error happens in -[NSThemeFrame
  // drawOverlayRect:].  I'm pretty convinced this is an Apple bug, but there is
  // no visual impact.  I have been unable to tickle it away with other window
  // or view manipulation Cocoa calls.  Stack added to suppressions_mac.txt.
  [self.chromeContentView setAutoresizesSubviews:YES];
  [[destWindow contentView] addSubview:self.chromeContentView
                            positioned:NSWindowBelow
                            relativeTo:nil];
  [self.chromeContentView setFrame:[[destWindow contentView] bounds]];

  // Move the incognito badge if present.
  if ([self shouldShowAvatar]) {
    NSView* avatarButtonView = [avatarButtonController_ view];

    [avatarButtonView removeFromSuperview];
    [avatarButtonView setHidden:YES];  // Will be shown in layout.
    [[destWindow cr_windowView] addSubview:avatarButtonView];
  }

  // Add the tab strip after setting the content view and moving the incognito
  // badge (if any), so that the tab strip will be on top (in the z-order).
  if ([self hasTabStrip])
    [self insertTabStripView:tabStripView intoWindow:destWindow];

  [sourceWindow setWindowController:nil];
  [self setWindow:destWindow];
  [destWindow setWindowController:self];

  // Move the status bubble over, if we have one.
  if (statusBubble_)
    statusBubble_->SwitchParentWindow(destWindow);

  // Move the title over.
  [destWindow setTitle:[sourceWindow title]];

  // The window needs to be onscreen before we can set its first responder.
  // Ordering the window to the front can change the active Space (either to
  // the window's old Space or to the application's assigned Space). To prevent
  // this by temporarily change the collectionBehavior.
  NSWindowCollectionBehavior behavior = [sourceWindow collectionBehavior];
  [destWindow setCollectionBehavior:
      NSWindowCollectionBehaviorMoveToActiveSpace];
  [destWindow makeKeyAndOrderFront:self];
  [destWindow setCollectionBehavior:behavior];

  if (![focusTracker restoreFocusInWindow:destWindow]) {
    // During certain types of fullscreen transitions, the view that had focus
    // may have gone away (e.g., the one for a Flash FS widget).  In this case,
    // FocusTracker will fail to restore focus to anything, so we set the focus
    // to the tab contents as a reasonable fall-back.
    [self focusTabContents];
  }
  [sourceWindow orderOut:self];

  // We're done moving focus, so re-enable bar visibility changes.
  [self enableBarVisibilityUpdates];
}

- (void)permissionBubbleWindowWillClose:(NSNotification*)notification {
  DCHECK(permissionBubbleCocoa_);

  NSNotificationCenter* center = [NSNotificationCenter defaultCenter];
  [center removeObserver:self
                    name:NSWindowWillCloseNotification
                  object:[notification object]];
  [self releaseBarVisibilityForOwner:[notification object]
                       withAnimation:YES
                               delay:YES];
}

- (void)configurePresentationModeController {
  BOOL fullscreen_for_tab =
      browser_->fullscreen_controller()->IsWindowFullscreenForTabOrPending();
  BOOL kiosk_mode =
      CommandLine::ForCurrentProcess()->HasSwitch(switches::kKioskMode);
  BOOL showDropdown =
      !fullscreen_for_tab && !kiosk_mode && ([self floatingBarHasFocus]);
  if (permissionBubbleCocoa_ && permissionBubbleCocoa_->IsVisible()) {
    DCHECK(permissionBubbleCocoa_->window());
    // A visible permission bubble will force the dropdown to remain visible.
    [self lockBarVisibilityForOwner:permissionBubbleCocoa_->window()
                      withAnimation:NO
                              delay:NO];
    showDropdown = YES;
    // Register to be notified when the permission bubble is closed, to
    // allow fullscreen to hide the dropdown.
    NSNotificationCenter* center = [NSNotificationCenter defaultCenter];
    [center addObserver:self
               selector:@selector(permissionBubbleWindowWillClose:)
                   name:NSWindowWillCloseNotification
                 object:permissionBubbleCocoa_->window()];
  }
  if (showDropdown) {
    // Turn on layered mode for the window's root view for the entry
    // animation.  Without this, the OS fullscreen animation for entering
    // fullscreen mode does not correctly draw the tab strip.
    // It will be turned off (set back to NO) when the animation finishes,
    // in -windowDidEnterFullScreen:.
    // Leaving wantsLayer on for the duration of presentation mode causes
    // performance issues when the dropdown is animated in/out.  It also does
    // not seem to be required for the exit animation.
    windowViewWantsLayer_ = [[[self window] cr_windowView] wantsLayer];
    [[[self window] cr_windowView] setWantsLayer:YES];
  }

  NSView* contentView = [[self window] contentView];
  [presentationModeController_
      enterPresentationModeForContentView:contentView
                             showDropdown:showDropdown];
}

- (void)adjustUIForExitingFullscreenAndStopOmniboxSliding {
  [presentationModeController_ exitPresentationMode];
  presentationModeController_.reset();

  // Force the bookmark bar z-order to update.
  [[bookmarkBarController_ view] removeFromSuperview];
  [self layoutSubviews];
}

- (void)adjustUIForSlidingFullscreenStyle:(fullscreen_mac::SlidingStyle)style {
  if (!presentationModeController_) {
    presentationModeController_.reset(
        [self newPresentationModeControllerWithStyle:style]);
    [self configurePresentationModeController];
  } else {
    presentationModeController_.get().slidingStyle = style;
  }

  if (!floatingBarBackingView_.get() &&
      ([self hasTabStrip] || [self hasToolbar] || [self hasLocationBar])) {
    floatingBarBackingView_.reset(
        [[FloatingBarBackingView alloc] initWithFrame:NSZeroRect]);
    [floatingBarBackingView_
        setAutoresizingMask:(NSViewWidthSizable | NSViewMinYMargin)];
  }

  // Force the bookmark bar z-order to update.
  [[bookmarkBarController_ view] removeFromSuperview];
  [self layoutSubviews];
}

- (PresentationModeController*)newPresentationModeControllerWithStyle:
    (fullscreen_mac::SlidingStyle)style {
  return [[PresentationModeController alloc] initWithBrowserController:self
                                                                 style:style];
}

- (void)enterImmersiveFullscreen {
  RecordFullscreenHistogram(IMMERSIVE_FULLSCREEN_MECHANISM, [self window]);

  // Set to NO by |-windowDidEnterFullScreen:|.
  enteringImmersiveFullscreen_ = YES;

  // Fade to black.
  const CGDisplayReservationInterval kFadeDurationSeconds = 0.6;
  Boolean didFadeOut = NO;
  CGDisplayFadeReservationToken token;
  if (CGAcquireDisplayFadeReservation(kFadeDurationSeconds, &token)
      == kCGErrorSuccess) {
    didFadeOut = YES;
    CGDisplayFade(token, kFadeDurationSeconds / 2, kCGDisplayBlendNormal,
        kCGDisplayBlendSolidColor, 0.0, 0.0, 0.0, /*synchronous=*/true);
  }

  // Create the fullscreen window.
  fullscreenWindow_.reset([[self createFullscreenWindow] retain]);
  savedRegularWindow_ = [[self window] retain];
  savedRegularWindowFrame_ = [savedRegularWindow_ frame];

  [self moveViewsForImmersiveFullscreen:YES
                          regularWindow:[self window]
                       fullscreenWindow:fullscreenWindow_.get()];

  fullscreen_mac::SlidingStyle style = fullscreen_mac::OMNIBOX_TABS_HIDDEN;
  [self adjustUIForSlidingFullscreenStyle:style];

  // AppKit is helpful and prevents NSWindows from having the same height as
  // the screen while the menu bar is showing. This only applies to windows on
  // a secondary screen, in a separate space. Calling [NSWindow
  // setFrame:display:] with the screen's height will always reduce the
  // height by the height of the MenuBar. Calling the method with any other
  // height works fine. The relevant method in the 10.10 AppKit SDK is called:
  // _canAdjustSizeForScreensHaveSeparateSpacesIfFillingSecondaryScreen
  //
  // TODO(erikchen): Refactor the logic to allow the window to be shown after
  // the menubar has been hidden. This would remove the need for this hack.
  // http://crbug.com/403203
  NSRect frame = [[[self window] screen] frame];
  if (!NSEqualRects(frame, [fullscreenWindow_ frame]))
    [fullscreenWindow_ setFrame:[[[self window] screen] frame] display:YES];

  [self layoutSubviews];

  [self windowDidEnterFullScreen:nil];

  // Fade back in.
  if (didFadeOut) {
    CGDisplayFade(token, kFadeDurationSeconds / 2, kCGDisplayBlendSolidColor,
        kCGDisplayBlendNormal, 0.0, 0.0, 0.0, /*synchronous=*/false);
    CGReleaseDisplayFadeReservation(token);
  }
}

- (void)exitImmersiveFullscreen {
  // Fade to black.
  const CGDisplayReservationInterval kFadeDurationSeconds = 0.6;
  Boolean didFadeOut = NO;
  CGDisplayFadeReservationToken token;
  if (CGAcquireDisplayFadeReservation(kFadeDurationSeconds, &token)
      == kCGErrorSuccess) {
    didFadeOut = YES;
    CGDisplayFade(token, kFadeDurationSeconds / 2, kCGDisplayBlendNormal,
        kCGDisplayBlendSolidColor, 0.0, 0.0, 0.0, /*synchronous=*/true);
  }

  [self windowWillExitFullScreen:nil];

  [self moveViewsForImmersiveFullscreen:NO
                          regularWindow:savedRegularWindow_
                       fullscreenWindow:fullscreenWindow_.get()];

  // When exiting fullscreen mode, we need to call layoutSubviews manually.
  [savedRegularWindow_ autorelease];
  savedRegularWindow_ = nil;
  fullscreenWindow_.reset();
  [self layoutSubviews];

  [self windowDidExitFullScreen:nil];

  // Fade back in.
  if (didFadeOut) {
    CGDisplayFade(token, kFadeDurationSeconds / 2, kCGDisplayBlendSolidColor,
        kCGDisplayBlendNormal, 0.0, 0.0, 0.0, /*synchronous=*/false);
    CGReleaseDisplayFadeReservation(token);
  }
}

- (void)showFullscreenExitBubbleIfNecessary {
  // This method is called in response to
  // |-updateFullscreenExitBubbleURL:bubbleType:|. If we're in the middle of the
  // transition into fullscreen (i.e., using the AppKit Fullscreen API), do not
  // show the bubble because it will cause visual jank
  // (http://crbug.com/130649). This will be called again as part of
  // |-windowDidEnterFullScreen:|, so arrange to do that work then instead.
  if (enteringAppKitFullscreen_)
    return;

  [self hideOverlayIfPossibleWithAnimation:NO delay:NO];

  if (fullscreenBubbleType_ == FEB_TYPE_NONE ||
      fullscreenBubbleType_ == FEB_TYPE_BROWSER_FULLSCREEN_EXIT_INSTRUCTION) {
    // Show no exit instruction bubble on Mac when in Browser Fullscreen.
    [self destroyFullscreenExitBubbleIfNecessary];
  } else {
    [fullscreenExitBubbleController_ closeImmediately];
    fullscreenExitBubbleController_.reset(
        [[FullscreenExitBubbleController alloc]
            initWithOwner:self
                  browser:browser_.get()
                      url:fullscreenUrl_
               bubbleType:fullscreenBubbleType_]);
    [fullscreenExitBubbleController_ showWindow];
  }
}

- (void)destroyFullscreenExitBubbleIfNecessary {
  [fullscreenExitBubbleController_ closeImmediately];
  fullscreenExitBubbleController_.reset();
}

- (void)contentViewDidResize:(NSNotification*)notification {
  [self layoutSubviews];
}

- (void)registerForContentViewResizeNotifications {
  [[NSNotificationCenter defaultCenter]
      addObserver:self
         selector:@selector(contentViewDidResize:)
             name:NSViewFrameDidChangeNotification
           object:[[self window] contentView]];
}

- (void)deregisterForContentViewResizeNotifications {
  [[NSNotificationCenter defaultCenter]
      removeObserver:self
                name:NSViewFrameDidChangeNotification
              object:[[self window] contentView]];
}

- (NSSize)window:(NSWindow*)window
    willUseFullScreenContentSize:(NSSize)proposedSize {
  return proposedSize;
}

- (NSApplicationPresentationOptions)window:(NSWindow*)window
    willUseFullScreenPresentationOptions:(NSApplicationPresentationOptions)opt {
  return (opt |
          NSApplicationPresentationAutoHideDock |
          NSApplicationPresentationAutoHideMenuBar);
}

- (void)windowWillEnterFullScreen:(NSNotification*)notification {
  RecordFullscreenHistogram(APPKIT_FULLSCREEN_MECHANISM, [self window]);

  if (notification)  // For System Fullscreen when non-nil.
    [self registerForContentViewResizeNotifications];

  NSWindow* window = [self window];
  savedRegularWindowFrame_ = [window frame];
  BOOL mode = enteringPresentationMode_ ||
       browser_->fullscreen_controller()->IsWindowFullscreenForTabOrPending();
  enteringAppKitFullscreen_ = YES;

  fullscreen_mac::SlidingStyle style =
      mode ? fullscreen_mac::OMNIBOX_TABS_HIDDEN
           : fullscreen_mac::OMNIBOX_TABS_PRESENT;

  [self adjustUIForSlidingFullscreenStyle:style];
}

- (void)windowDidEnterFullScreen:(NSNotification*)notification {
  // In Yosemite, some combination of the titlebar and toolbar always show in
  // full-screen mode. We do not want either to show. Search for the window that
  // contains the views, and hide it. There is no need to ever unhide the view.
  // http://crbug.com/380235
  if (base::mac::IsOSYosemiteOrLater()) {
    for (NSWindow* window in [[NSApplication sharedApplication] windows]) {
      if ([window
              isKindOfClass:NSClassFromString(@"NSToolbarFullScreenWindow")]) {
        [[window contentView] setHidden:YES];
      }
    }
  }

  if (notification)  // For System Fullscreen when non-nil.
    [self deregisterForContentViewResizeNotifications];
  enteringAppKitFullscreen_ = NO;
  enteringImmersiveFullscreen_ = NO;
  enteringPresentationMode_ = NO;

  [self showFullscreenExitBubbleIfNecessary];
  browser_->WindowFullscreenStateChanged();
  [[[self window] cr_windowView] setWantsLayer:windowViewWantsLayer_];
}

- (void)windowWillExitFullScreen:(NSNotification*)notification {
  if (notification)  // For System Fullscreen when non-nil.
    [self registerForContentViewResizeNotifications];
  [self destroyFullscreenExitBubbleIfNecessary];
  [self adjustUIForExitingFullscreenAndStopOmniboxSliding];
}

- (void)windowDidExitFullScreen:(NSNotification*)notification {
  if (notification)  // For System Fullscreen when non-nil.
    [self deregisterForContentViewResizeNotifications];
  browser_->WindowFullscreenStateChanged();
}

- (void)windowDidFailToEnterFullScreen:(NSWindow*)window {
  [self deregisterForContentViewResizeNotifications];
  enteringAppKitFullscreen_ = NO;
  [self adjustUIForExitingFullscreenAndStopOmniboxSliding];
}

- (void)windowDidFailToExitFullScreen:(NSWindow*)window {
  [self deregisterForContentViewResizeNotifications];

  // Force a relayout to try and get the window back into a reasonable state.
  [self layoutSubviews];
}

- (void)enableBarVisibilityUpdates {
  // Early escape if there's nothing to do.
  if (barVisibilityUpdatesEnabled_)
    return;

  barVisibilityUpdatesEnabled_ = YES;

  if ([barVisibilityLocks_ count])
    [presentationModeController_ ensureOverlayShownWithAnimation:NO delay:NO];
  else
    [presentationModeController_ ensureOverlayHiddenWithAnimation:NO delay:NO];
}

- (void)disableBarVisibilityUpdates {
  // Early escape if there's nothing to do.
  if (!barVisibilityUpdatesEnabled_)
    return;

  barVisibilityUpdatesEnabled_ = NO;
  [presentationModeController_ cancelAnimationAndTimers];
}

- (void)hideOverlayIfPossibleWithAnimation:(BOOL)animation delay:(BOOL)delay {
  if (!barVisibilityUpdatesEnabled_ || [barVisibilityLocks_ count])
    return;
  [presentationModeController_ ensureOverlayHiddenWithAnimation:animation
                                                          delay:delay];
}

- (CGFloat)toolbarDividerOpacity {
  return [bookmarkBarController_ toolbarDividerOpacity];
}

- (void)updateLayerOrdering:(NSView*)view {
  // Hold a reference to the view so that it doesn't accidentally get
  // dealloc'ed.
  base::scoped_nsobject<NSView> reference([view retain]);

  // If the superview has a layer, then this hack isn't required.
  NSView* superview = [view superview];
  if ([superview layer])
    return;

  // Get the current position of the view.
  NSArray* subviews = [superview subviews];
  NSInteger index = [subviews indexOfObject:view];
  NSView* siblingBelow = nil;
  if (index > 0)
    siblingBelow = [subviews objectAtIndex:index - 1];

  // Remove the view.
  [view removeFromSuperview];

  // Add it to the same position.
  if (siblingBelow) {
    [superview addSubview:view
               positioned:NSWindowAbove
               relativeTo:siblingBelow];
  } else {
    [superview addSubview:view
               positioned:NSWindowBelow
               relativeTo:nil];
  }
}

- (void)updateInfoBarTipVisibility {
  // If there's no toolbar then hide the infobar tip.
  [infoBarContainerController_
      setShouldSuppressTopInfoBarTip:![self hasToolbar]];
}

- (NSInteger)pageInfoBubblePointY {
  LocationBarViewMac* locationBarView = [self locationBarBridge];

  // The point, in window coordinates.
  NSPoint iconBottom = locationBarView->GetPageInfoBubblePoint();

  // The toolbar, in window coordinates.
  NSView* toolbar = [toolbarController_ view];
  CGFloat toolbarY = NSMinY([toolbar convertRect:[toolbar bounds] toView:nil]);

  return iconBottom.y - toolbarY;
}

- (void)enterAppKitFullscreen {
  DCHECK(base::mac::IsOSLionOrLater());
  if (FramedBrowserWindow* framedBrowserWindow =
          base::mac::ObjCCast<FramedBrowserWindow>([self window])) {
    [framedBrowserWindow toggleSystemFullScreen];
  }
}

- (void)exitAppKitFullscreen {
  DCHECK(base::mac::IsOSLionOrLater());
  if (FramedBrowserWindow* framedBrowserWindow =
          base::mac::ObjCCast<FramedBrowserWindow>([self window])) {
    [framedBrowserWindow toggleSystemFullScreen];
  }
}

- (void)updateLayoutParameters:(BrowserWindowLayout*)layout {
  [layout setContentViewSize:[[[self window] contentView] bounds].size];
  [layout setWindowSize:[[self window] frame].size];

  [layout setInAnyFullscreen:[self isInAnyFullscreenMode]];
  [layout setFullscreenSlidingStyle:
      presentationModeController_.get().slidingStyle];
  [layout setFullscreenMenubarOffset:
      [presentationModeController_ menubarOffset]];
  [layout setFullscreenToolbarFraction:
      [presentationModeController_ toolbarFraction]];

  [layout setHasTabStrip:[self hasTabStrip]];
  NSButton* fullScreenButton =
      [[self window] standardWindowButton:NSWindowFullScreenButton];
  [layout setFullscreenButtonFrame:fullScreenButton ? [fullScreenButton frame]
                                                    : NSZeroRect];
  if ([self shouldShowAvatar]) {
    NSView* avatar = [avatarButtonController_ view];
    [layout setShouldShowAvatar:YES];
    [layout setShouldUseNewAvatar:[self shouldUseNewAvatarButton]];
    [layout setAvatarSize:[avatar frame].size];
    [layout setAvatarLineWidth:[[avatar superview] cr_lineWidth]];
  }

  [layout setHasToolbar:[self hasToolbar]];
  [layout setToolbarHeight:NSHeight([[toolbarController_ view] bounds])];

  [layout setHasLocationBar:[self hasLocationBar]];

  [layout setPlaceBookmarkBarBelowInfoBar:[self placeBookmarkBarBelowInfoBar]];
  [layout setBookmarkBarHidden:[bookmarkBarController_ view].isHidden];
  [layout setBookmarkBarHeight:
      NSHeight([[bookmarkBarController_ view] bounds])];

  [layout setInfoBarHeight:[infoBarContainerController_ heightOfInfoBars]];
  [layout setPageInfoBubblePointY:[self pageInfoBubblePointY]];

  [layout setHasDownloadShelf:(downloadShelfController_.get() != nil)];
  [layout setDownloadShelfHeight:
      NSHeight([[downloadShelfController_ view] bounds])];
}

- (void)applyLayout:(BrowserWindowLayout*)layout {
  chrome::LayoutOutput output = [layout computeLayout];

  if (!NSIsEmptyRect(output.tabStripLayout.frame))
    [self applyTabStripLayout:output.tabStripLayout];

  if (!NSIsEmptyRect(output.toolbarFrame))
    [[toolbarController_ view] setFrame:output.toolbarFrame];

  if (!NSIsEmptyRect(output.bookmarkFrame)) {
    NSView* bookmarkBarView = [bookmarkBarController_ view];
    [bookmarkBarView setFrame:output.bookmarkFrame];

    // Pin the bookmark bar to the top of the window and make the width
    // flexible.
    [bookmarkBarView setAutoresizingMask:NSViewWidthSizable | NSViewMinYMargin];

    [bookmarkBarController_ layoutSubviews];
  }

  // The info bar is never hidden. Sometimes it has zero effective height.
  [[infoBarContainerController_ view] setFrame:output.infoBarFrame];
  [infoBarContainerController_
      setMaxTopArrowHeight:output.infoBarMaxTopArrowHeight];

  if (!NSIsEmptyRect(output.downloadShelfFrame))
    [[downloadShelfController_ view] setFrame:output.downloadShelfFrame];

  [self layoutTabContentArea:output.contentAreaFrame];

  if (!NSIsEmptyRect(output.fullscreenBackingBarFrame)) {
    [floatingBarBackingView_ setFrame:output.fullscreenBackingBarFrame];
    [presentationModeController_
        overlayFrameChanged:output.fullscreenBackingBarFrame];
  }

  [findBarCocoaController_
      positionFindBarViewAtMaxY:output.findBarMaxY
                       maxWidth:NSWidth(output.contentAreaFrame)];

  [fullscreenExitBubbleController_
      positionInWindowAtTop:output.fullscreenExitButtonMaxY
                      width:NSWidth(output.contentAreaFrame)];
}

- (void)updateSubviewZOrder {
  if ([self isInAnyFullscreenMode])
    [self updateSubviewZOrderFullscreen];
  else
    [self updateSubviewZOrderNormal];

  [self updateSubviewZOrderHack];
}

- (void)updateSubviewZOrderNormal {
  base::scoped_nsobject<NSMutableArray> subviews([[NSMutableArray alloc] init]);
  if ([downloadShelfController_ view])
    [subviews addObject:[downloadShelfController_ view]];
  if ([bookmarkBarController_ view])
    [subviews addObject:[bookmarkBarController_ view]];
  if ([toolbarController_ view])
    [subviews addObject:[toolbarController_ view]];
  if ([infoBarContainerController_ view])
    [subviews addObject:[infoBarContainerController_ view]];
  if ([self tabContentArea])
    [subviews addObject:[self tabContentArea]];
  if ([findBarCocoaController_ view])
    [subviews addObject:[findBarCocoaController_ view]];

  [self setContentViewSubviews:subviews];
}

- (void)updateSubviewZOrderFullscreen {
  base::scoped_nsobject<NSMutableArray> subviews([[NSMutableArray alloc] init]);
  if ([downloadShelfController_ view])
    [subviews addObject:[downloadShelfController_ view]];
  if ([self tabContentArea])
    [subviews addObject:[self tabContentArea]];
  if ([self placeBookmarkBarBelowInfoBar]) {
    if ([bookmarkBarController_ view])
      [subviews addObject:[bookmarkBarController_ view]];
    if (floatingBarBackingView_)
      [subviews addObject:floatingBarBackingView_];
  } else {
    if (floatingBarBackingView_)
      [subviews addObject:floatingBarBackingView_];
    if ([bookmarkBarController_ view])
      [subviews addObject:[bookmarkBarController_ view]];
  }
  if ([toolbarController_ view])
    [subviews addObject:[toolbarController_ view]];
  if ([infoBarContainerController_ view])
    [subviews addObject:[infoBarContainerController_ view]];
  if ([findBarCocoaController_ view])
    [subviews addObject:[findBarCocoaController_ view]];

  [self setContentViewSubviews:subviews];
}

- (void)setContentViewSubviews:(NSArray*)subviews {
  // Subviews already match.
  if ([[self.chromeContentView subviews] isEqual:subviews])
    return;

  // The tabContentArea isn't a subview, so just set all the subviews.
  NSView* tabContentArea = [self tabContentArea];
  if (![[self.chromeContentView subviews] containsObject:tabContentArea]) {
    [self.chromeContentView setSubviews:subviews];
    return;
  }

  // Remove all subviews that aren't the tabContentArea.
  for (NSView* view in [[self.chromeContentView subviews] copy]) {
    if (view != tabContentArea)
      [view removeFromSuperview];
  }

  // Add in the subviews below the tabContentArea.
  NSInteger index = [subviews indexOfObject:tabContentArea];
  for (int i = index - 1; i >= 0; --i) {
    NSView* view = [subviews objectAtIndex:i];
    [self.chromeContentView addSubview:view
                            positioned:NSWindowBelow
                            relativeTo:nil];
  }

  // Add in the subviews above the tabContentArea.
  for (NSUInteger i = index + 1; i < [subviews count]; ++i) {
    NSView* view = [subviews objectAtIndex:i];
    [self.chromeContentView addSubview:view
                            positioned:NSWindowAbove
                            relativeTo:nil];
  }
}

- (void)updateSubviewZOrderHack {
  // TODO(erikchen): Remove and then add the tabStripView to the root NSView.
  // This fixes a layer ordering problem that occurs between the contentView
  // and the tabStripView. This is a hack required because NSThemeFrame is not
  // layer backed, and because Chrome adds subviews directly to the
  // NSThemeFrame.
  // http://crbug.com/407921
  if (enteringAppKitFullscreen_) {
    // The tabstrip frequently lies outside the bounds of its superview.
    // Repeatedly adding/removing the tabstrip from its superview during the
    // AppKit Fullscreen transition causes graphical glitches on 10.10. The
    // correct solution is to use the AppKit fullscreen transition APIs added
    // in 10.7+.
    // http://crbug.com/408791
    if (!hasAdjustedTabStripWhileEnteringAppKitFullscreen_) {
      // Disable implicit animations.
      [CATransaction begin];
      [CATransaction setDisableActions:YES];

      [self updateLayerOrdering:[self tabStripView]];
      [self updateLayerOrdering:[avatarButtonController_ view]];

      [CATransaction commit];
      hasAdjustedTabStripWhileEnteringAppKitFullscreen_ = YES;
    }
  } else {
    hasAdjustedTabStripWhileEnteringAppKitFullscreen_ = NO;
  }
}

@end  // @implementation BrowserWindowController(Private)