Upstream version 11.40.277.0
[platform/framework/web/crosswalk.git] / src / chrome / browser / ui / cocoa / browser_window_controller.mm
1 // Copyright 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.
4
5 #import "chrome/browser/ui/cocoa/browser_window_controller.h"
6
7 #include <cmath>
8 #include <numeric>
9
10 #include "base/command_line.h"
11 #include "base/mac/bundle_locations.h"
12 #import "base/mac/foundation_util.h"
13 #include "base/mac/mac_util.h"
14 #import "base/mac/sdk_forward_declarations.h"
15 #include "base/strings/sys_string_conversions.h"
16 #include "base/strings/utf_string_conversions.h"
17 #include "chrome/app/chrome_command_ids.h"  // IDC_*
18 #include "chrome/browser/bookmarks/bookmark_model_factory.h"
19 #include "chrome/browser/bookmarks/chrome_bookmark_client.h"
20 #include "chrome/browser/bookmarks/chrome_bookmark_client_factory.h"
21 #include "chrome/browser/browser_process.h"
22 #include "chrome/browser/devtools/devtools_window.h"
23 #include "chrome/browser/fullscreen.h"
24 #include "chrome/browser/profiles/avatar_menu.h"
25 #include "chrome/browser/profiles/profile.h"
26 #include "chrome/browser/profiles/profile_info_cache.h"
27 #include "chrome/browser/profiles/profile_manager.h"
28 #include "chrome/browser/profiles/profiles_state.h"
29 #include "chrome/browser/signin/signin_ui_util.h"
30 #include "chrome/browser/themes/theme_service.h"
31 #include "chrome/browser/themes/theme_service_factory.h"
32 #include "chrome/browser/translate/chrome_translate_client.h"
33 #include "chrome/browser/ui/bookmarks/bookmark_editor.h"
34 #include "chrome/browser/ui/bookmarks/bookmark_utils.h"
35 #include "chrome/browser/ui/browser.h"
36 #include "chrome/browser/ui/browser_command_controller.h"
37 #include "chrome/browser/ui/browser_commands.h"
38 #include "chrome/browser/ui/browser_instant_controller.h"
39 #include "chrome/browser/ui/browser_list.h"
40 #include "chrome/browser/ui/browser_window_state.h"
41 #import "chrome/browser/ui/cocoa/background_gradient_view.h"
42 #import "chrome/browser/ui/cocoa/bookmarks/bookmark_bar_controller.h"
43 #import "chrome/browser/ui/cocoa/bookmarks/bookmark_editor_controller.h"
44 #import "chrome/browser/ui/cocoa/browser_window_cocoa.h"
45 #import "chrome/browser/ui/cocoa/browser_window_controller_private.h"
46 #import "chrome/browser/ui/cocoa/browser_window_layout.h"
47 #import "chrome/browser/ui/cocoa/browser_window_utils.h"
48 #import "chrome/browser/ui/cocoa/dev_tools_controller.h"
49 #import "chrome/browser/ui/cocoa/download/download_shelf_controller.h"
50 #include "chrome/browser/ui/cocoa/extensions/extension_keybinding_registry_cocoa.h"
51 #import "chrome/browser/ui/cocoa/fast_resize_view.h"
52 #import "chrome/browser/ui/cocoa/find_bar/find_bar_bridge.h"
53 #import "chrome/browser/ui/cocoa/find_bar/find_bar_cocoa_controller.h"
54 #import "chrome/browser/ui/cocoa/framed_browser_window.h"
55 #import "chrome/browser/ui/cocoa/fullscreen_window.h"
56 #import "chrome/browser/ui/cocoa/infobars/infobar_container_controller.h"
57 #import "chrome/browser/ui/cocoa/location_bar/autocomplete_text_field_editor.h"
58 #import "chrome/browser/ui/cocoa/presentation_mode_controller.h"
59 #import "chrome/browser/ui/cocoa/profiles/avatar_base_controller.h"
60 #import "chrome/browser/ui/cocoa/profiles/avatar_button_controller.h"
61 #import "chrome/browser/ui/cocoa/profiles/avatar_icon_controller.h"
62 #import "chrome/browser/ui/cocoa/status_bubble_mac.h"
63 #import "chrome/browser/ui/cocoa/tab_contents/overlayable_contents_controller.h"
64 #import "chrome/browser/ui/cocoa/tab_contents/sad_tab_controller.h"
65 #import "chrome/browser/ui/cocoa/tab_contents/tab_contents_controller.h"
66 #import "chrome/browser/ui/cocoa/tabs/tab_strip_controller.h"
67 #import "chrome/browser/ui/cocoa/tabs/tab_strip_view.h"
68 #import "chrome/browser/ui/cocoa/tabs/tab_view.h"
69 #import "chrome/browser/ui/cocoa/toolbar/toolbar_controller.h"
70 #import "chrome/browser/ui/cocoa/translate/translate_bubble_controller.h"
71 #include "chrome/browser/ui/cocoa/website_settings/permission_bubble_cocoa.h"
72 #include "chrome/browser/ui/fullscreen/fullscreen_controller.h"
73 #include "chrome/browser/ui/location_bar/location_bar.h"
74 #include "chrome/browser/ui/tabs/tab_strip_model.h"
75 #include "chrome/browser/ui/tabs/tab_strip_model_delegate.h"
76 #include "chrome/browser/ui/toolbar/encoding_menu_controller.h"
77 #include "chrome/browser/ui/translate/translate_bubble_model_impl.h"
78 #include "chrome/browser/ui/website_settings/permission_bubble_manager.h"
79 #include "chrome/browser/ui/window_sizer/window_sizer.h"
80 #include "chrome/common/chrome_switches.h"
81 #include "chrome/common/extensions/command.h"
82 #include "chrome/common/url_constants.h"
83 #include "chrome/grit/generated_resources.h"
84 #include "chrome/grit/locale_settings.h"
85 #include "components/bookmarks/browser/bookmark_model.h"
86 #include "components/signin/core/common/profile_management_switches.h"
87 #include "components/translate/core/browser/translate_manager.h"
88 #include "components/translate/core/browser/translate_ui_delegate.h"
89 #include "components/web_modal/popup_manager.h"
90 #include "components/web_modal/web_contents_modal_dialog_manager.h"
91 #include "content/public/browser/render_view_host.h"
92 #include "content/public/browser/render_widget_host_view.h"
93 #include "content/public/browser/web_contents.h"
94 #import "ui/base/cocoa/cocoa_base_utils.h"
95 #import "ui/base/cocoa/nsview_additions.h"
96 #include "ui/base/l10n/l10n_util.h"
97 #include "ui/base/l10n/l10n_util_mac.h"
98 #include "ui/gfx/mac/scoped_ns_disable_screen_updates.h"
99
100 using l10n_util::GetStringUTF16;
101 using l10n_util::GetNSStringWithFixup;
102 using l10n_util::GetNSStringFWithFixup;
103
104 // ORGANIZATION: This is a big file. It is (in principle) organized as follows
105 // (in order):
106 // 1. Interfaces. Very short, one-time-use classes may include an implementation
107 //    immediately after their interface.
108 // 2. The general implementation section, ordered as follows:
109 //      i. Public methods and overrides.
110 //     ii. Overrides/implementations of undocumented methods.
111 //    iii. Delegate methods for various protocols, formal and informal, to which
112 //        |BrowserWindowController| conforms.
113 // 3. (temporary) Implementation sections for various categories.
114 //
115 // Private methods are defined and implemented separately in
116 // browser_window_controller_private.{h,mm}.
117 //
118 // Not all of the above guidelines are followed and more (re-)organization is
119 // needed. BUT PLEASE TRY TO KEEP THIS FILE ORGANIZED. I'd rather re-organize as
120 // little as possible, since doing so messes up the file's history.
121 //
122 // TODO(viettrungluu): [crbug.com/35543] on-going re-organization, splitting
123 // things into multiple files -- the plan is as follows:
124 // - in general, everything stays in browser_window_controller.h, but is split
125 //   off into categories (see below)
126 // - core stuff stays in browser_window_controller.mm
127 // - ... overrides also stay (without going into a category, in particular)
128 // - private stuff which everyone needs goes into
129 //   browser_window_controller_private.{h,mm}; if no one else needs them, they
130 //   can go in individual files (see below)
131 // - area/task-specific stuff go in browser_window_controller_<area>.mm
132 // - ... in categories called "(<Area>)" or "(<PrivateArea>)"
133 // Plan of action:
134 // - first re-organize into categories
135 // - then split into files
136
137 // Notes on self-inflicted (not user-inflicted) window resizing and moving:
138 //
139 // When the bookmark bar goes from hidden to shown (on a non-NTP) page, or when
140 // the download shelf goes from hidden to shown, we grow the window downwards in
141 // order to maintain a constant content area size. When either goes from shown
142 // to hidden, we consequently shrink the window from the bottom, also to keep
143 // the content area size constant. To keep things simple, if the window is not
144 // entirely on-screen, we don't grow/shrink the window.
145 //
146 // The complications come in when there isn't enough room (on screen) below the
147 // window to accomodate the growth. In this case, we grow the window first
148 // downwards, and then upwards. So, when it comes to shrinking, we do the
149 // opposite: shrink from the top by the amount by which we grew at the top, and
150 // then from the bottom -- unless the user moved/resized/zoomed the window, in
151 // which case we "reset state" and just shrink from the bottom.
152 //
153 // A further complication arises due to the way in which "zoom" ("maximize")
154 // works on Mac OS X. Basically, for our purposes, a window is "zoomed" whenever
155 // it occupies the full available vertical space. (Note that the green zoom
156 // button does not track zoom/unzoomed state per se, but basically relies on
157 // this heuristic.) We don't, in general, want to shrink the window if the
158 // window is zoomed (scenario: window is zoomed, download shelf opens -- which
159 // doesn't cause window growth, download shelf closes -- shouldn't cause the
160 // window to become unzoomed!). However, if we grew the window
161 // (upwards/downwards) to become zoomed in the first place, we *should* shrink
162 // the window by the amounts by which we grew (scenario: window occupies *most*
163 // of vertical space, download shelf opens causing growth so that window
164 // occupies all of vertical space -- i.e., window is effectively zoomed,
165 // download shelf closes -- should return the window to its previous state).
166 //
167 // A major complication is caused by the way grows/shrinks are handled and
168 // animated. Basically, the BWC doesn't see the global picture, but it sees
169 // grows and shrinks in small increments (as dictated by the animation). Thus
170 // window growth/shrinkage (at the top/bottom) have to be tracked incrementally.
171 // Allowing shrinking from the zoomed state also requires tracking: We check on
172 // any shrink whether we're both zoomed and have previously grown -- if so, we
173 // set a flag, and constrain any resize by the allowed amounts. On further
174 // shrinks, we check the flag (since the size/position of the window will no
175 // longer indicate that the window is shrinking from an apparent zoomed state)
176 // and if it's set we continue to constrain the resize.
177
178 using content::OpenURLParams;
179 using content::Referrer;
180 using content::RenderWidgetHostView;
181 using content::WebContents;
182
183 @interface NSWindow (NSPrivateApis)
184 // Note: These functions are private, use -[NSObject respondsToSelector:]
185 // before calling them.
186
187 - (void)setBottomCornerRounded:(BOOL)rounded;
188
189 - (NSRect)_growBoxRect;
190
191 @end
192
193 @implementation BrowserWindowController
194
195 + (BrowserWindowController*)browserWindowControllerForWindow:(NSWindow*)window {
196   while (window) {
197     id controller = [window windowController];
198     if ([controller isKindOfClass:[BrowserWindowController class]])
199       return (BrowserWindowController*)controller;
200     window = [window parentWindow];
201   }
202   return nil;
203 }
204
205 + (BrowserWindowController*)browserWindowControllerForView:(NSView*)view {
206   NSWindow* window = [view window];
207   return [BrowserWindowController browserWindowControllerForWindow:window];
208 }
209
210 + (void)updateSigninItem:(id)signinItem
211               shouldShow:(BOOL)showSigninMenuItem
212           currentProfile:(Profile*)profile {
213   DCHECK([signinItem isKindOfClass:[NSMenuItem class]]);
214   NSMenuItem* signinMenuItem = static_cast<NSMenuItem*>(signinItem);
215
216   // Look for a separator immediately after the menu item so it can be hidden
217   // or shown appropriately along with the signin menu item.
218   NSMenuItem* followingSeparator = nil;
219   NSMenu* menu = [signinItem menu];
220   if (menu) {
221     NSInteger signinItemIndex = [menu indexOfItem:signinMenuItem];
222     DCHECK_NE(signinItemIndex, -1);
223     if ((signinItemIndex + 1) < [menu numberOfItems]) {
224       NSMenuItem* menuItem = [menu itemAtIndex:(signinItemIndex + 1)];
225       if ([menuItem isSeparatorItem]) {
226         followingSeparator = menuItem;
227       }
228     }
229   }
230
231   base::string16 label = signin_ui_util::GetSigninMenuLabel(profile);
232   [signinMenuItem setTitle:l10n_util::FixUpWindowsStyleLabel(label)];
233   [signinMenuItem setHidden:!showSigninMenuItem];
234   [followingSeparator setHidden:!showSigninMenuItem];
235 }
236
237 // Load the browser window nib and do any Cocoa-specific initialization.
238 // Takes ownership of |browser|. Note that the nib also sets this controller
239 // up as the window's delegate.
240 - (id)initWithBrowser:(Browser*)browser {
241   return [self initWithBrowser:browser takeOwnership:YES];
242 }
243
244 // Private(TestingAPI) init routine with testing options.
245 - (id)initWithBrowser:(Browser*)browser takeOwnership:(BOOL)ownIt {
246   bool hasTabStrip = browser->SupportsWindowFeature(Browser::FEATURE_TABSTRIP);
247   if ((self = [super initTabWindowControllerWithTabStrip:hasTabStrip])) {
248     DCHECK(browser);
249     initializing_ = YES;
250     browser_.reset(browser);
251     ownsBrowser_ = ownIt;
252     NSWindow* window = [self window];
253     // Make the content view for the window have a layer. This will make all
254     // sub-views have layers. This is necessary to ensure correct layer
255     // ordering of all child views and their layers.
256     [[window contentView] setWantsLayer:YES];
257     windowShim_.reset(new BrowserWindowCocoa(browser, self));
258
259     // Set different minimum sizes on tabbed windows vs non-tabbed, e.g. popups.
260     // This has to happen before -enforceMinWindowSize: is called further down.
261     NSSize minSize = [self isTabbedWindow] ?
262       NSMakeSize(400, 272) : NSMakeSize(100, 122);
263     [[self window] setMinSize:minSize];
264
265     // Create the bar visibility lock set; 10 is arbitrary, but should hopefully
266     // be big enough to hold all locks that'll ever be needed.
267     barVisibilityLocks_.reset([[NSMutableSet setWithCapacity:10] retain]);
268
269     // Set the window to not have rounded corners, which prevents the resize
270     // control from being inset slightly and looking ugly. Only bother to do
271     // this on Snow Leopard; on Lion and later all windows have rounded bottom
272     // corners, and this won't work anyway.
273     if (base::mac::IsOSSnowLeopard() &&
274         [window respondsToSelector:@selector(setBottomCornerRounded:)])
275       [window setBottomCornerRounded:NO];
276
277     // Lion will attempt to automagically save and restore the UI. This
278     // functionality appears to be leaky (or at least interacts badly with our
279     // architecture) and thus BrowserWindowController never gets released. This
280     // prevents the browser from being able to quit <http://crbug.com/79113>.
281     if ([window respondsToSelector:@selector(setRestorable:)])
282       [window setRestorable:NO];
283
284     // Get the windows to swish in on Lion.
285     if ([window respondsToSelector:@selector(setAnimationBehavior:)])
286       [window setAnimationBehavior:NSWindowAnimationBehaviorDocumentWindow];
287
288     // Get the most appropriate size for the window, then enforce the
289     // minimum width and height. The window shim will handle flipping
290     // the coordinates for us so we can use it to save some code.
291     // Note that this may leave a significant portion of the window
292     // offscreen, but there will always be enough window onscreen to
293     // drag the whole window back into view.
294     ui::WindowShowState show_state = ui::SHOW_STATE_DEFAULT;
295     gfx::Rect desiredContentRect;
296     chrome::GetSavedWindowBoundsAndShowState(browser_.get(),
297                                              &desiredContentRect,
298                                              &show_state);
299     gfx::Rect windowRect = desiredContentRect;
300     windowRect = [self enforceMinWindowSize:windowRect];
301
302     // When we are given x/y coordinates of 0 on a created popup window, assume
303     // none were given by the window.open() command.
304     if (browser_->is_type_popup() &&
305         windowRect.x() == 0 && windowRect.y() == 0) {
306       gfx::Size size = windowRect.size();
307       windowRect.set_origin(
308           WindowSizer::GetDefaultPopupOrigin(size,
309                                              browser_->host_desktop_type()));
310     }
311
312     // Size and position the window.  Note that it is not yet onscreen.  Popup
313     // windows may get resized later on in this function, once the actual size
314     // of the toolbar/tabstrip is known.
315     windowShim_->SetBounds(windowRect);
316
317     // Puts the incognito badge on the window frame, if necessary.
318     [self installAvatar];
319
320     // Create a sub-controller for the docked devTools and add its view to the
321     // hierarchy.
322     devToolsController_.reset([[DevToolsController alloc] init]);
323     [[devToolsController_ view] setFrame:[[self tabContentArea] bounds]];
324     [[self tabContentArea] addSubview:[devToolsController_ view]];
325
326     // Create the overlayable contents controller.  This provides the switch
327     // view that TabStripController needs.
328     overlayableContentsController_.reset(
329         [[OverlayableContentsController alloc] initWithBrowser:browser]);
330     [[overlayableContentsController_ view]
331         setFrame:[[devToolsController_ view] bounds]];
332     [[devToolsController_ view]
333         addSubview:[overlayableContentsController_ view]];
334
335     // Create a controller for the tab strip, giving it the model object for
336     // this window's Browser and the tab strip view. The controller will handle
337     // registering for the appropriate tab notifications from the back-end and
338     // managing the creation of new tabs.
339     [self createTabStripController];
340
341     // Create a controller for the toolbar, giving it the toolbar model object
342     // and the toolbar view from the nib. The controller will handle
343     // registering for the appropriate command state changes from the back-end.
344     // Adds the toolbar to the content area.
345     toolbarController_.reset([[ToolbarController alloc]
346               initWithCommands:browser->command_controller()->command_updater()
347                        profile:browser->profile()
348                        browser:browser
349                 resizeDelegate:self]);
350     [toolbarController_ setHasToolbar:[self hasToolbar]
351                        hasLocationBar:[self hasLocationBar]];
352
353     // Create a sub-controller for the bookmark bar.
354     bookmarkBarController_.reset(
355         [[BookmarkBarController alloc]
356             initWithBrowser:browser_.get()
357                initialWidth:NSWidth([[[self window] contentView] frame])
358                    delegate:self
359              resizeDelegate:self]);
360     [bookmarkBarController_ setBookmarkBarEnabled:[self supportsBookmarkBar]];
361
362     // Create the infobar container view, so we can pass it to the
363     // ToolbarController.
364     infoBarContainerController_.reset(
365         [[InfoBarContainerController alloc] initWithResizeDelegate:self]);
366     [self updateInfoBarTipVisibility];
367
368     // We don't want to try and show the bar before it gets placed in its parent
369     // view, so this step shoudn't be inside the bookmark bar controller's
370     // |-awakeFromNib|.
371     windowShim_->BookmarkBarStateChanged(
372         BookmarkBar::DONT_ANIMATE_STATE_CHANGE);
373
374     // Allow bar visibility to be changed.
375     [self enableBarVisibilityUpdates];
376
377     // Set the window to participate in Lion Fullscreen mode.  Setting this flag
378     // has no effect on Snow Leopard or earlier.  Panels can share a fullscreen
379     // space with a tabbed window, but they can not be primary fullscreen
380     // windows.
381     // This ensures the fullscreen button is appropriately positioned. It must
382     // be done before calling layoutSubviews because the new avatar button's
383     // position depends on the fullscreen button's position, as well as
384     // TabStripController's rightIndentForControls.
385     // The fullscreen button's position may depend on the old avatar button's
386     // width, but that does not require calling layoutSubviews first.
387     NSUInteger collectionBehavior = [window collectionBehavior];
388     collectionBehavior |=
389        browser_->type() == Browser::TYPE_TABBED ||
390            browser_->type() == Browser::TYPE_POPUP ?
391                NSWindowCollectionBehaviorFullScreenPrimary :
392                NSWindowCollectionBehaviorFullScreenAuxiliary;
393     [window setCollectionBehavior:collectionBehavior];
394
395     [self layoutSubviews];
396
397     // For a popup window, |desiredContentRect| contains the desired height of
398     // the content, not of the whole window.  Now that all the views are laid
399     // out, measure the current content area size and grow if needed.  The
400     // window has not been placed onscreen yet, so this extra resize will not
401     // cause visible jank.
402     if (browser_->is_type_popup()) {
403       CGFloat deltaH = desiredContentRect.height() -
404                        NSHeight([[self tabContentArea] frame]);
405       // Do not shrink the window, as that may break minimum size invariants.
406       if (deltaH > 0) {
407         // Convert from tabContentArea coordinates to window coordinates.
408         NSSize convertedSize =
409             [[self tabContentArea] convertSize:NSMakeSize(0, deltaH)
410                                         toView:nil];
411         NSRect frame = [[self window] frame];
412         frame.size.height += convertedSize.height;
413         frame.origin.y -= convertedSize.height;
414         [[self window] setFrame:frame display:NO];
415       }
416     }
417
418     // Create the bridge for the status bubble.
419     statusBubble_ = new StatusBubbleMac([self window], self);
420
421     // Create the permissions bubble.
422     permissionBubbleCocoa_.reset(new PermissionBubbleCocoa([self window]));
423
424     // Register for application hide/unhide notifications.
425     [[NSNotificationCenter defaultCenter]
426          addObserver:self
427             selector:@selector(applicationDidHide:)
428                 name:NSApplicationDidHideNotification
429               object:nil];
430     [[NSNotificationCenter defaultCenter]
431          addObserver:self
432             selector:@selector(applicationDidUnhide:)
433                 name:NSApplicationDidUnhideNotification
434               object:nil];
435
436     // This must be done after the view is added to the window since it relies
437     // on the window bounds to determine whether to show buttons or not.
438     if ([self hasToolbar])  // Do not create the buttons in popups.
439       [toolbarController_ createBrowserActionButtons];
440
441     extension_keybinding_registry_.reset(
442         new ExtensionKeybindingRegistryCocoa(browser_->profile(),
443             [self window],
444             extensions::ExtensionKeybindingRegistry::ALL_EXTENSIONS,
445             windowShim_.get()));
446
447     // We are done initializing now.
448     initializing_ = NO;
449   }
450   return self;
451 }
452
453 - (void)dealloc {
454   browser_->tab_strip_model()->CloseAllTabs();
455   [downloadShelfController_ exiting];
456
457   // Explicitly release |presentationModeController_| here, as it may call back
458   // to this BWC in |-dealloc|.  We are required to call |-exitPresentationMode|
459   // before releasing the controller.
460   [presentationModeController_ exitPresentationMode];
461   presentationModeController_.reset();
462
463   // Under certain testing configurations we may not actually own the browser.
464   if (ownsBrowser_ == NO)
465     ignore_result(browser_.release());
466
467   [[NSNotificationCenter defaultCenter] removeObserver:self];
468
469   [super dealloc];
470 }
471
472 - (gfx::Rect)enforceMinWindowSize:(gfx::Rect)bounds {
473   gfx::Rect checkedBounds = bounds;
474
475   NSSize minSize = [[self window] minSize];
476   if (bounds.width() < minSize.width)
477       checkedBounds.set_width(minSize.width);
478   if (bounds.height() < minSize.height)
479       checkedBounds.set_height(minSize.height);
480
481   return checkedBounds;
482 }
483
484 - (BrowserWindow*)browserWindow {
485   return windowShim_.get();
486 }
487
488 - (ToolbarController*)toolbarController {
489   return toolbarController_.get();
490 }
491
492 - (TabStripController*)tabStripController {
493   return tabStripController_.get();
494 }
495
496 - (FindBarCocoaController*)findBarCocoaController {
497   return findBarCocoaController_.get();
498 }
499
500 - (InfoBarContainerController*)infoBarContainerController {
501   return infoBarContainerController_.get();
502 }
503
504 - (StatusBubbleMac*)statusBubble {
505   return statusBubble_;
506 }
507
508 - (LocationBarViewMac*)locationBarBridge {
509   return [toolbarController_ locationBarBridge];
510 }
511
512 - (NSView*)floatingBarBackingView {
513   return floatingBarBackingView_;
514 }
515
516 - (OverlayableContentsController*)overlayableContentsController {
517   return overlayableContentsController_;
518 }
519
520 - (Profile*)profile {
521   return browser_->profile();
522 }
523
524 - (AvatarBaseController*)avatarButtonController {
525   return avatarButtonController_.get();
526 }
527
528 - (void)destroyBrowser {
529   [NSApp removeWindowsItem:[self window]];
530
531   // We need the window to go away now.
532   // We can't actually use |-autorelease| here because there's an embedded
533   // run loop in the |-performClose:| which contains its own autorelease pool.
534   // Instead call it after a zero-length delay, which gets us back to the main
535   // event loop.
536   [self performSelector:@selector(autorelease)
537              withObject:nil
538              afterDelay:0];
539 }
540
541 // Called when the window meets the criteria to be closed (ie,
542 // |-windowShouldClose:| returns YES). We must be careful to preserve the
543 // semantics of BrowserWindow::Close() and not call the Browser's dtor directly
544 // from this method.
545 - (void)windowWillClose:(NSNotification*)notification {
546   DCHECK_EQ([notification object], [self window]);
547   DCHECK(browser_->tab_strip_model()->empty());
548   [savedRegularWindow_ close];
549   // We delete statusBubble here because we need to kill off the dependency
550   // that its window has on our window before our window goes away.
551   delete statusBubble_;
552   statusBubble_ = NULL;
553   // We can't actually use |-autorelease| here because there's an embedded
554   // run loop in the |-performClose:| which contains its own autorelease pool.
555   // Instead call it after a zero-length delay, which gets us back to the main
556   // event loop.
557   [self performSelector:@selector(autorelease)
558              withObject:nil
559              afterDelay:0];
560 }
561
562 - (void)updateDevToolsForContents:(WebContents*)contents {
563   BOOL layout_changed =
564       [devToolsController_ updateDevToolsForWebContents:contents
565                                             withProfile:browser_->profile()];
566   if (layout_changed && [findBarCocoaController_ isFindBarVisible])
567     [self layoutSubviews];
568 }
569
570 // Called when the user wants to close a window or from the shutdown process.
571 // The Browser object is in control of whether or not we're allowed to close. It
572 // may defer closing due to several states, such as onUnload handlers needing to
573 // be fired. If closing is deferred, the Browser will handle the processing
574 // required to get us to the closing state and (by watching for all the tabs
575 // going away) will again call to close the window when it's finally ready.
576 - (BOOL)windowShouldClose:(id)sender {
577   // Disable updates while closing all tabs to avoid flickering.
578   gfx::ScopedNSDisableScreenUpdates disabler;
579   // Give beforeunload handlers the chance to cancel the close before we hide
580   // the window below.
581   if (!browser_->ShouldCloseWindow())
582     return NO;
583
584   // saveWindowPositionIfNeeded: only works if we are the last active
585   // window, but orderOut: ends up activating another window, so we
586   // have to save the window position before we call orderOut:.
587   [self saveWindowPositionIfNeeded];
588
589   bool fast_tab_closing_enabled =
590       CommandLine::ForCurrentProcess()->HasSwitch(switches::kEnableFastUnload);
591
592   if (!browser_->tab_strip_model()->empty()) {
593     // Tab strip isn't empty.  Hide the frame (so it appears to have closed
594     // immediately) and close all the tabs, allowing the renderers to shut
595     // down. When the tab strip is empty we'll be called back again.
596     [[self window] orderOut:self];
597     browser_->OnWindowClosing();
598     if (fast_tab_closing_enabled)
599       browser_->tab_strip_model()->CloseAllTabs();
600     return NO;
601   } else if (fast_tab_closing_enabled &&
602         !browser_->HasCompletedUnloadProcessing()) {
603     // The browser needs to finish running unload handlers.
604     // Hide the window (so it appears to have closed immediately), and
605     // the browser will call us back again when it is ready to close.
606     [[self window] orderOut:self];
607     return NO;
608   }
609
610   // the tab strip is empty, it's ok to close the window
611   return YES;
612 }
613
614 // Called right after our window became the main window.
615 - (void)windowDidBecomeMain:(NSNotification*)notification {
616   BrowserList::SetLastActive(browser_.get());
617   [self saveWindowPositionIfNeeded];
618
619   // TODO(dmaclach): Instead of redrawing the whole window, views that care
620   // about the active window state should be registering for notifications.
621   [[self window] setViewsNeedDisplay:YES];
622
623   // TODO(viettrungluu): For some reason, the above doesn't suffice.
624   if ([self isInAnyFullscreenMode])
625     [floatingBarBackingView_ setNeedsDisplay:YES];  // Okay even if nil.
626 }
627
628 - (void)windowDidResignMain:(NSNotification*)notification {
629   // TODO(dmaclach): Instead of redrawing the whole window, views that care
630   // about the active window state should be registering for notifications.
631   [[self window] setViewsNeedDisplay:YES];
632
633   // TODO(viettrungluu): For some reason, the above doesn't suffice.
634   if ([self isInAnyFullscreenMode])
635     [floatingBarBackingView_ setNeedsDisplay:YES];  // Okay even if nil.
636 }
637
638 // Called when we are activated (when we gain focus).
639 - (void)windowDidBecomeKey:(NSNotification*)notification {
640   // We need to activate the controls (in the "WebView"). To do this, get the
641   // selected WebContents's RenderWidgetHostView and tell it to activate.
642   if (WebContents* contents =
643           browser_->tab_strip_model()->GetActiveWebContents()) {
644
645     WebContents* devtools = DevToolsWindow::GetInTabWebContents(
646         contents, NULL);
647     if (devtools) {
648       RenderWidgetHostView* devtoolsView = devtools->GetRenderWidgetHostView();
649       if (devtoolsView && devtoolsView->HasFocus()) {
650         devtoolsView->SetActive(true);
651         return;
652       }
653     }
654
655     if (RenderWidgetHostView* rwhv = contents->GetRenderWidgetHostView())
656       rwhv->SetActive(true);
657   }
658 }
659
660 // Called when we are deactivated (when we lose focus).
661 - (void)windowDidResignKey:(NSNotification*)notification {
662   // If our app is still active and we're still the key window, ignore this
663   // message, since it just means that a menu extra (on the "system status bar")
664   // was activated; we'll get another |-windowDidResignKey| if we ever really
665   // lose key window status.
666   if ([NSApp isActive] && ([NSApp keyWindow] == [self window]))
667     return;
668
669   // We need to deactivate the controls (in the "WebView"). To do this, get the
670   // selected WebContents's RenderWidgetHostView and tell it to deactivate.
671   if (WebContents* contents =
672           browser_->tab_strip_model()->GetActiveWebContents()) {
673
674     WebContents* devtools = DevToolsWindow::GetInTabWebContents(
675         contents, NULL);
676     if (devtools) {
677       RenderWidgetHostView* devtoolsView = devtools->GetRenderWidgetHostView();
678       if (devtoolsView && devtoolsView->HasFocus()) {
679         devtoolsView->SetActive(false);
680         return;
681       }
682     }
683
684     if (RenderWidgetHostView* rwhv = contents->GetRenderWidgetHostView())
685       rwhv->SetActive(false);
686   }
687 }
688
689 // Called when we have been minimized.
690 - (void)windowDidMiniaturize:(NSNotification *)notification {
691   [self saveWindowPositionIfNeeded];
692
693   // Let the selected RenderWidgetHostView know, so that it can tell plugins.
694   if (WebContents* contents =
695           browser_->tab_strip_model()->GetActiveWebContents()) {
696     if (RenderWidgetHostView* rwhv = contents->GetRenderWidgetHostView())
697       rwhv->SetWindowVisibility(false);
698   }
699 }
700
701 // Called when we have been unminimized.
702 - (void)windowDidDeminiaturize:(NSNotification *)notification {
703   // Let the selected RenderWidgetHostView know, so that it can tell plugins.
704   if (WebContents* contents =
705           browser_->tab_strip_model()->GetActiveWebContents()) {
706     if (RenderWidgetHostView* rwhv = contents->GetRenderWidgetHostView())
707       rwhv->SetWindowVisibility(true);
708   }
709 }
710
711 // Called when the application has been hidden.
712 - (void)applicationDidHide:(NSNotification *)notification {
713   // Let the selected RenderWidgetHostView know, so that it can tell plugins
714   // (unless we are minimized, in which case nothing has really changed).
715   if (![[self window] isMiniaturized]) {
716   if (WebContents* contents =
717           browser_->tab_strip_model()->GetActiveWebContents()) {
718       if (RenderWidgetHostView* rwhv = contents->GetRenderWidgetHostView())
719         rwhv->SetWindowVisibility(false);
720     }
721   }
722 }
723
724 // Called when the application has been unhidden.
725 - (void)applicationDidUnhide:(NSNotification *)notification {
726   // Let the selected RenderWidgetHostView know, so that it can tell plugins
727   // (unless we are minimized, in which case nothing has really changed).
728   if (![[self window] isMiniaturized]) {
729   if (WebContents* contents =
730           browser_->tab_strip_model()->GetActiveWebContents()) {
731       if (RenderWidgetHostView* rwhv = contents->GetRenderWidgetHostView())
732         rwhv->SetWindowVisibility(true);
733     }
734   }
735 }
736
737 // Called when the user clicks the zoom button (or selects it from the Window
738 // menu) to determine the "standard size" of the window, based on the content
739 // and other factors. If the current size/location differs nontrivally from the
740 // standard size, Cocoa resizes the window to the standard size, and saves the
741 // current size as the "user size". If the current size/location is the same (up
742 // to a fudge factor) as the standard size, Cocoa resizes the window to the
743 // saved user size. (It is possible for the two to coincide.) In this way, the
744 // zoom button acts as a toggle. We determine the standard size based on the
745 // content, but enforce a minimum width (calculated using the dimensions of the
746 // screen) to ensure websites with small intrinsic width (such as google.com)
747 // don't end up with a wee window. Moreover, we always declare the standard
748 // width to be at least as big as the current width, i.e., we never want zooming
749 // to the standard width to shrink the window. This is consistent with other
750 // browsers' behaviour, and is desirable in multi-tab situations. Note, however,
751 // that the "toggle" behaviour means that the window can still be "unzoomed" to
752 // the user size.
753 - (NSRect)windowWillUseStandardFrame:(NSWindow*)window
754                         defaultFrame:(NSRect)frame {
755   // Forget that we grew the window up (if we in fact did).
756   [self resetWindowGrowthState];
757
758   // |frame| already fills the current screen. Never touch y and height since we
759   // always want to fill vertically.
760
761   // If the shift key is down, maximize. Hopefully this should make the
762   // "switchers" happy.
763   if ([[NSApp currentEvent] modifierFlags] & NSShiftKeyMask) {
764     return frame;
765   }
766
767   // To prevent strange results on portrait displays, the basic minimum zoomed
768   // width is the larger of: 60% of available width, 60% of available height
769   // (bounded by available width).
770   const CGFloat kProportion = 0.6;
771   CGFloat zoomedWidth =
772       std::max(kProportion * NSWidth(frame),
773                std::min(kProportion * NSHeight(frame), NSWidth(frame)));
774
775   WebContents* contents = browser_->tab_strip_model()->GetActiveWebContents();
776   if (contents) {
777     // If the intrinsic width is bigger, then make it the zoomed width.
778     const int kScrollbarWidth = 16;  // TODO(viettrungluu): ugh.
779     CGFloat intrinsicWidth = static_cast<CGFloat>(
780         contents->GetPreferredSize().width() + kScrollbarWidth);
781     zoomedWidth = std::max(zoomedWidth,
782                            std::min(intrinsicWidth, NSWidth(frame)));
783   }
784
785   // Never shrink from the current size on zoom (see above).
786   NSRect currentFrame = [[self window] frame];
787   zoomedWidth = std::max(zoomedWidth, NSWidth(currentFrame));
788
789   // |frame| determines our maximum extents. We need to set the origin of the
790   // frame -- and only move it left if necessary.
791   if (currentFrame.origin.x + zoomedWidth > NSMaxX(frame))
792     frame.origin.x = NSMaxX(frame) - zoomedWidth;
793   else
794     frame.origin.x = currentFrame.origin.x;
795
796   // Set the width. Don't touch y or height.
797   frame.size.width = zoomedWidth;
798
799   return frame;
800 }
801
802 - (void)activate {
803   [BrowserWindowUtils activateWindowForController:self];
804 }
805
806 // Determine whether we should let a window zoom/unzoom to the given |newFrame|.
807 // We avoid letting unzoom move windows between screens, because it's really
808 // strange and unintuitive.
809 - (BOOL)windowShouldZoom:(NSWindow*)window toFrame:(NSRect)newFrame {
810   // Figure out which screen |newFrame| is on.
811   NSScreen* newScreen = nil;
812   CGFloat newScreenOverlapArea = 0.0;
813   for (NSScreen* screen in [NSScreen screens]) {
814     NSRect overlap = NSIntersectionRect(newFrame, [screen frame]);
815     CGFloat overlapArea = NSWidth(overlap) * NSHeight(overlap);
816     if (overlapArea > newScreenOverlapArea) {
817       newScreen = screen;
818       newScreenOverlapArea = overlapArea;
819     }
820   }
821   // If we're somehow not on any screen, allow the zoom.
822   if (!newScreen)
823     return YES;
824
825   // If the new screen is the current screen, we can return a definitive YES.
826   // Note: This check is not strictly necessary, but just short-circuits in the
827   // "no-brainer" case. To test the complicated logic below, comment this out!
828   NSScreen* curScreen = [window screen];
829   if (newScreen == curScreen)
830     return YES;
831
832   // Worry a little: What happens when a window is on two (or more) screens?
833   // E.g., what happens in a 50-50 scenario? Cocoa may reasonably elect to zoom
834   // to the other screen rather than staying on the officially current one. So
835   // we compare overlaps with the current window frame, and see if Cocoa's
836   // choice was reasonable (allowing a small rounding error). This should
837   // hopefully avoid us ever erroneously denying a zoom when a window is on
838   // multiple screens.
839   NSRect curFrame = [window frame];
840   NSRect newScrIntersectCurFr = NSIntersectionRect([newScreen frame], curFrame);
841   NSRect curScrIntersectCurFr = NSIntersectionRect([curScreen frame], curFrame);
842   if (NSWidth(newScrIntersectCurFr) * NSHeight(newScrIntersectCurFr) >=
843       (NSWidth(curScrIntersectCurFr) * NSHeight(curScrIntersectCurFr) - 1.0)) {
844     return YES;
845   }
846
847   // If it wasn't reasonable, return NO.
848   return NO;
849 }
850
851 // Adjusts the window height by the given amount.
852 - (BOOL)adjustWindowHeightBy:(CGFloat)deltaH {
853   // By not adjusting the window height when initializing, we can ensure that
854   // the window opens with the same size that was saved on close.
855   if (initializing_ || [self isInAnyFullscreenMode] || deltaH == 0)
856     return NO;
857
858   NSWindow* window = [self window];
859   NSRect windowFrame = [window frame];
860   NSRect workarea = [[window screen] visibleFrame];
861
862   // If the window is not already fully in the workarea, do not adjust its frame
863   // at all.
864   if (!NSContainsRect(workarea, windowFrame))
865     return NO;
866
867   // Record the position of the top/bottom of the window, so we can easily check
868   // whether we grew the window upwards/downwards.
869   CGFloat oldWindowMaxY = NSMaxY(windowFrame);
870   CGFloat oldWindowMinY = NSMinY(windowFrame);
871
872   // We are "zoomed" if we occupy the full vertical space.
873   bool isZoomed = (windowFrame.origin.y == workarea.origin.y &&
874                    NSHeight(windowFrame) == NSHeight(workarea));
875
876   // If we're shrinking the window....
877   if (deltaH < 0) {
878     bool didChange = false;
879
880     // Don't reset if not currently zoomed since shrinking can take several
881     // steps!
882     if (isZoomed)
883       isShrinkingFromZoomed_ = YES;
884
885     // If we previously grew at the top, shrink as much as allowed at the top
886     // first.
887     if (windowTopGrowth_ > 0) {
888       CGFloat shrinkAtTopBy = MIN(-deltaH, windowTopGrowth_);
889       windowFrame.size.height -= shrinkAtTopBy;  // Shrink the window.
890       deltaH += shrinkAtTopBy;            // Update the amount left to shrink.
891       windowTopGrowth_ -= shrinkAtTopBy;  // Update the growth state.
892       didChange = true;
893     }
894
895     // Similarly for the bottom (not an "else if" since we may have to
896     // simultaneously shrink at both the top and at the bottom). Note that
897     // |deltaH| may no longer be nonzero due to the above.
898     if (deltaH < 0 && windowBottomGrowth_ > 0) {
899       CGFloat shrinkAtBottomBy = MIN(-deltaH, windowBottomGrowth_);
900       windowFrame.origin.y += shrinkAtBottomBy;     // Move the window up.
901       windowFrame.size.height -= shrinkAtBottomBy;  // Shrink the window.
902       deltaH += shrinkAtBottomBy;               // Update the amount left....
903       windowBottomGrowth_ -= shrinkAtBottomBy;  // Update the growth state.
904       didChange = true;
905     }
906
907     // If we're shrinking from zoomed but we didn't change the top or bottom
908     // (since we've reached the limits imposed by |window...Growth_|), then stop
909     // here. Don't reset |isShrinkingFromZoomed_| since we might get called
910     // again for the same shrink.
911     if (isShrinkingFromZoomed_ && !didChange)
912       return NO;
913   } else {
914     isShrinkingFromZoomed_ = NO;
915
916     // Don't bother with anything else.
917     if (isZoomed)
918       return NO;
919   }
920
921   // Shrinking from zoomed is handled above (and is constrained by
922   // |window...Growth_|).
923   if (!isShrinkingFromZoomed_) {
924     // Resize the window down until it hits the bottom of the workarea, then if
925     // needed continue resizing upwards.  Do not resize the window to be taller
926     // than the current workarea.
927     // Resize the window as requested, keeping the top left corner fixed.
928     windowFrame.origin.y -= deltaH;
929     windowFrame.size.height += deltaH;
930
931     // If the bottom left corner is now outside the visible frame, move the
932     // window up to make it fit, but make sure not to move the top left corner
933     // out of the visible frame.
934     if (windowFrame.origin.y < workarea.origin.y) {
935       windowFrame.origin.y = workarea.origin.y;
936       windowFrame.size.height =
937           std::min(NSHeight(windowFrame), NSHeight(workarea));
938     }
939
940     // Record (if applicable) how much we grew the window in either direction.
941     // (N.B.: These only record growth, not shrinkage.)
942     if (NSMaxY(windowFrame) > oldWindowMaxY)
943       windowTopGrowth_ += NSMaxY(windowFrame) - oldWindowMaxY;
944     if (NSMinY(windowFrame) < oldWindowMinY)
945       windowBottomGrowth_ += oldWindowMinY - NSMinY(windowFrame);
946   }
947
948   // Disable subview resizing while resizing the window, or else we will get
949   // unwanted renderer resizes.  The calling code must call layoutSubviews to
950   // make things right again.
951   NSView* chromeContentView = [self chromeContentView];
952   BOOL autoresizesSubviews = [chromeContentView autoresizesSubviews];
953   [chromeContentView setAutoresizesSubviews:NO];
954   [window setFrame:windowFrame display:NO];
955   [chromeContentView setAutoresizesSubviews:autoresizesSubviews];
956   return YES;
957 }
958
959 // Main method to resize browser window subviews.  This method should be called
960 // when resizing any child of the content view, rather than resizing the views
961 // directly.  If the view is already the correct height, does not force a
962 // relayout.
963 - (void)resizeView:(NSView*)view newHeight:(CGFloat)height {
964   // We should only ever be called for one of the following four views.
965   // |downloadShelfController_| may be nil. If we are asked to size the bookmark
966   // bar directly, its superview must be this controller's content view.
967   DCHECK(view);
968   DCHECK(view == [toolbarController_ view] ||
969          view == [infoBarContainerController_ view] ||
970          view == [downloadShelfController_ view] ||
971          view == [bookmarkBarController_ view]);
972
973   // The infobar has insufficient information to determine its new height. It
974   // knows the total height of all of the info bars (which is what it passes
975   // into this method), but knows nothing about the maximum arrow height, which
976   // is determined by this class.
977   if (view == [infoBarContainerController_ view]) {
978     base::scoped_nsobject<BrowserWindowLayout> layout(
979         [[BrowserWindowLayout alloc] init]);
980     [self updateLayoutParameters:layout];
981     // Use the new height for the info bar.
982     [layout setInfoBarHeight:height];
983
984     chrome::LayoutOutput output = [layout computeLayout];
985
986     height = NSHeight(output.infoBarFrame);
987   }
988
989   // Change the height of the view and call |-layoutSubViews|. We set the height
990   // here without regard to where the view is on the screen or whether it needs
991   // to "grow up" or "grow down."  The below call to |-layoutSubviews| will
992   // position each view correctly.
993   NSRect frame = [view frame];
994   if (NSHeight(frame) == height)
995     return;
996
997   // Disable screen updates to prevent flickering.
998   gfx::ScopedNSDisableScreenUpdates disabler;
999
1000   // Grow or shrink the window by the amount of the height change.  We adjust
1001   // the window height only in two cases:
1002   // 1) We are adjusting the height of the bookmark bar and it is currently
1003   // animating either open or closed.
1004   // 2) We are adjusting the height of the download shelf.
1005   //
1006   // We do not adjust the window height for bookmark bar changes on the NTP.
1007   BOOL shouldAdjustBookmarkHeight =
1008       [bookmarkBarController_ isAnimatingBetweenState:BookmarkBar::HIDDEN
1009                                              andState:BookmarkBar::SHOW];
1010
1011   BOOL resizeRectDirty = NO;
1012   if ((shouldAdjustBookmarkHeight && view == [bookmarkBarController_ view]) ||
1013       view == [downloadShelfController_ view]) {
1014     CGFloat deltaH = height - NSHeight(frame);
1015     if ([self adjustWindowHeightBy:deltaH] &&
1016         view == [downloadShelfController_ view]) {
1017       // If the window height didn't change, the download shelf will change the
1018       // size of the contents. If the contents size doesn't change, send it
1019       // an explicit grow box invalidation (else, the resize message does that.)
1020       resizeRectDirty = YES;
1021     }
1022   }
1023
1024   frame.size.height = height;
1025   // TODO(rohitrao): Determine if calling setFrame: twice is bad.
1026   [view setFrame:frame];
1027   [self layoutSubviews];
1028
1029   if (resizeRectDirty) {
1030     // Send new resize rect to foreground tab.
1031     if (content::WebContents* contents =
1032             browser_->tab_strip_model()->GetActiveWebContents()) {
1033       if (content::RenderViewHost* rvh = contents->GetRenderViewHost()) {
1034         rvh->ResizeRectChanged(windowShim_->GetRootWindowResizerRect());
1035       }
1036     }
1037   }
1038 }
1039
1040 // Update a toggle state for an NSMenuItem if modified.
1041 // Take care to ensure |item| looks like a NSMenuItem.
1042 // Called by validateUserInterfaceItem:.
1043 - (void)updateToggleStateWithTag:(NSInteger)tag forItem:(id)item {
1044   if (![item respondsToSelector:@selector(state)] ||
1045       ![item respondsToSelector:@selector(setState:)])
1046     return;
1047
1048   // On Windows this logic happens in bookmark_bar_view.cc.  On the
1049   // Mac we're a lot more MVC happy so we've moved it into a
1050   // controller.  To be clear, this simply updates the menu item; it
1051   // does not display the bookmark bar itself.
1052   if (tag == IDC_SHOW_BOOKMARK_BAR) {
1053     bool toggled = windowShim_->IsBookmarkBarVisible();
1054     NSInteger oldState = [(NSMenuItem*)item state];
1055     NSInteger newState = toggled ? NSOnState : NSOffState;
1056     if (oldState != newState)
1057       [item setState:newState];
1058   }
1059
1060   // Update the checked/Unchecked state of items in the encoding menu.
1061   // On Windows, this logic is part of |EncodingMenuModel| in
1062   // browser/ui/views/toolbar_view.h.
1063   EncodingMenuController encoding_controller;
1064   if (encoding_controller.DoesCommandBelongToEncodingMenu(tag)) {
1065     DCHECK(browser_.get());
1066     Profile* profile = browser_->profile();
1067     DCHECK(profile);
1068     WebContents* current_tab =
1069         browser_->tab_strip_model()->GetActiveWebContents();
1070     if (!current_tab)
1071       return;
1072
1073     const std::string encoding = current_tab->GetEncoding();
1074
1075     bool toggled = encoding_controller.IsItemChecked(profile, encoding, tag);
1076     NSInteger oldState = [(NSMenuItem*)item state];
1077     NSInteger newState = toggled ? NSOnState : NSOffState;
1078     if (oldState != newState)
1079       [item setState:newState];
1080   }
1081 }
1082
1083 // Called to validate menu and toolbar items when this window is key. All the
1084 // items we care about have been set with the |-commandDispatch:| or
1085 // |-commandDispatchUsingKeyModifiers:| actions and a target of FirstResponder
1086 // in IB. If it's not one of those, let it continue up the responder chain to be
1087 // handled elsewhere. We pull out the tag as the cross-platform constant to
1088 // differentiate and dispatch the various commands.
1089 // NOTE: we might have to handle state for app-wide menu items,
1090 // although we could cheat and directly ask the app controller if our
1091 // command_updater doesn't support the command. This may or may not be an issue,
1092 // too early to tell.
1093 - (BOOL)validateUserInterfaceItem:(id<NSValidatedUserInterfaceItem>)item {
1094   SEL action = [item action];
1095   BOOL enable = NO;
1096   if (action == @selector(commandDispatch:) ||
1097       action == @selector(commandDispatchUsingKeyModifiers:)) {
1098     NSInteger tag = [item tag];
1099     if (chrome::SupportsCommand(browser_.get(), tag)) {
1100       // Generate return value (enabled state)
1101       enable = chrome::IsCommandEnabled(browser_.get(), tag);
1102       switch (tag) {
1103         case IDC_CLOSE_TAB:
1104           // Disable "close tab" if the receiving window is not tabbed.
1105           // We simply check whether the item has a keyboard shortcut set here;
1106           // app_controller_mac.mm actually determines whether the item should
1107           // be enabled.
1108           if (NSMenuItem* menuItem = base::mac::ObjCCast<NSMenuItem>(item))
1109             enable &= !![[menuItem keyEquivalent] length];
1110           break;
1111         case IDC_FULLSCREEN: {
1112           if (NSMenuItem* menuItem = base::mac::ObjCCast<NSMenuItem>(item)) {
1113             NSString* menuTitle = l10n_util::GetNSString(
1114                 [self isInAppKitFullscreen] && ![self inPresentationMode]
1115                     ? IDS_EXIT_FULLSCREEN_MAC
1116                     : IDS_ENTER_FULLSCREEN_MAC);
1117             [menuItem setTitle:menuTitle];
1118
1119             if (!chrome::mac::SupportsSystemFullscreen())
1120               [menuItem setHidden:YES];
1121           }
1122           break;
1123         }
1124         case IDC_PRESENTATION_MODE: {
1125           if (NSMenuItem* menuItem = base::mac::ObjCCast<NSMenuItem>(item)) {
1126             NSString* menuTitle = l10n_util::GetNSString(
1127                 [self inPresentationMode] ? IDS_EXIT_PRESENTATION_MAC :
1128                                             IDS_ENTER_PRESENTATION_MAC);
1129             [menuItem setTitle:menuTitle];
1130           }
1131           break;
1132         }
1133         case IDC_SHOW_SIGNIN: {
1134           Profile* original_profile =
1135               browser_->profile()->GetOriginalProfile();
1136           [BrowserWindowController updateSigninItem:item
1137                                          shouldShow:enable
1138                                      currentProfile:original_profile];
1139           break;
1140         }
1141         case IDC_BOOKMARK_PAGE: {
1142           // Extensions have the ability to hide the bookmark page menu item.
1143           // This only affects the bookmark page menu item under the main menu.
1144           // The bookmark page menu item under the wrench menu has its
1145           // visibility controlled by WrenchMenuModel.
1146           bool shouldHide =
1147               chrome::ShouldRemoveBookmarkThisPageUI(browser_->profile());
1148           NSMenuItem* menuItem = base::mac::ObjCCast<NSMenuItem>(item);
1149           [menuItem setHidden:shouldHide];
1150           break;
1151         }
1152         case IDC_BOOKMARK_ALL_TABS: {
1153           // Extensions have the ability to hide the bookmark all tabs menu
1154           // item.  This only affects the bookmark page menu item under the main
1155           // menu.  The bookmark page menu item under the wrench menu has its
1156           // visibility controlled by WrenchMenuModel.
1157           bool shouldHide =
1158               chrome::ShouldRemoveBookmarkOpenPagesUI(browser_->profile());
1159           NSMenuItem* menuItem = base::mac::ObjCCast<NSMenuItem>(item);
1160           [menuItem setHidden:shouldHide];
1161           break;
1162         }
1163         default:
1164           // Special handling for the contents of the Text Encoding submenu. On
1165           // Mac OS, instead of enabling/disabling the top-level menu item, we
1166           // enable/disable the submenu's contents (per Apple's HIG).
1167           EncodingMenuController encoding_controller;
1168           if (encoding_controller.DoesCommandBelongToEncodingMenu(tag)) {
1169             enable &= chrome::IsCommandEnabled(browser_.get(),
1170                                                IDC_ENCODING_MENU) ? YES : NO;
1171           }
1172       }
1173
1174       // If the item is toggleable, find its toggle state and
1175       // try to update it.  This is a little awkward, but the alternative is
1176       // to check after a commandDispatch, which seems worse.
1177       [self updateToggleStateWithTag:tag forItem:item];
1178     }
1179   }
1180   return enable;
1181 }
1182
1183 // Called when the user picks a menu or toolbar item when this window is key.
1184 // Calls through to the browser object to execute the command. This assumes that
1185 // the command is supported and doesn't check, otherwise it would have been
1186 // disabled in the UI in validateUserInterfaceItem:.
1187 - (void)commandDispatch:(id)sender {
1188   DCHECK(sender);
1189   // Identify the actual BWC to which the command should be dispatched. It might
1190   // belong to a background window, yet this controller gets it because it is
1191   // the foreground window's controller and thus in the responder chain. Some
1192   // senders don't have this problem (for example, menus only operate on the
1193   // foreground window), so this is only an issue for senders that are part of
1194   // windows.
1195   BrowserWindowController* targetController = self;
1196   if ([sender respondsToSelector:@selector(window)])
1197     targetController = [[sender window] windowController];
1198   DCHECK([targetController isKindOfClass:[BrowserWindowController class]]);
1199   DCHECK(targetController->browser_.get());
1200   chrome::ExecuteCommand(targetController->browser_.get(), [sender tag]);
1201 }
1202
1203 // Same as |-commandDispatch:|, but executes commands using a disposition
1204 // determined by the key flags. If the window is in the background and the
1205 // command key is down, ignore the command key, but process any other modifiers.
1206 - (void)commandDispatchUsingKeyModifiers:(id)sender {
1207   DCHECK(sender);
1208
1209   if (![sender isEnabled]) {
1210     // This code is reachable e.g. if the user mashes the back button, queuing
1211     // up a bunch of events before the button's enabled state is updated:
1212     // http://crbug.com/63254
1213     return;
1214   }
1215
1216   // See comment above for why we do this.
1217   BrowserWindowController* targetController = self;
1218   if ([sender respondsToSelector:@selector(window)])
1219     targetController = [[sender window] windowController];
1220   DCHECK([targetController isKindOfClass:[BrowserWindowController class]]);
1221   DCHECK(targetController->browser_.get());
1222
1223   NSInteger command = [sender tag];
1224   NSUInteger modifierFlags = [[NSApp currentEvent] modifierFlags];
1225   if ((command == IDC_RELOAD) &&
1226       (modifierFlags & (NSShiftKeyMask | NSControlKeyMask))) {
1227     command = IDC_RELOAD_IGNORING_CACHE;
1228     // Mask off Shift and Control so they don't affect the disposition below.
1229     modifierFlags &= ~(NSShiftKeyMask | NSControlKeyMask);
1230   }
1231   if (![[sender window] isMainWindow]) {
1232     // Remove the command key from the flags, it means "keep the window in
1233     // the background" in this case.
1234     modifierFlags &= ~NSCommandKeyMask;
1235   }
1236   chrome::ExecuteCommandWithDisposition(
1237       targetController->browser_.get(), command,
1238       ui::WindowOpenDispositionFromNSEventWithFlags(
1239           [NSApp currentEvent], modifierFlags));
1240 }
1241
1242 // Called when another part of the internal codebase needs to execute a
1243 // command.
1244 - (void)executeCommand:(int)command {
1245   chrome::ExecuteCommand(browser_.get(), command);
1246 }
1247
1248 - (BOOL)handledByExtensionCommand:(NSEvent*)event
1249     priority:(ui::AcceleratorManager::HandlerPriority)priority {
1250   return extension_keybinding_registry_->ProcessKeyEvent(
1251       content::NativeWebKeyboardEvent(event), priority);
1252 }
1253
1254 // StatusBubble delegate method: tell the status bubble the frame it should
1255 // position itself in.
1256 - (NSRect)statusBubbleBaseFrame {
1257   NSView* view = [overlayableContentsController_ view];
1258   return [view convertRect:[view bounds] toView:nil];
1259 }
1260
1261 - (void)updateToolbarWithContents:(WebContents*)tab {
1262   [toolbarController_ updateToolbarWithContents:tab];
1263 }
1264
1265 - (void)setStarredState:(BOOL)isStarred {
1266   [toolbarController_ setStarredState:isStarred];
1267 }
1268
1269 - (void)setCurrentPageIsTranslated:(BOOL)on {
1270   [toolbarController_ setTranslateIconLit:on];
1271 }
1272
1273 - (void)zoomChangedForActiveTab:(BOOL)canShowBubble {
1274   [toolbarController_ zoomChangedForActiveTab:canShowBubble];
1275 }
1276
1277 // Return the rect, in WebKit coordinates (flipped), of the window's grow box
1278 // in the coordinate system of the content area of the currently selected tab.
1279 // |windowGrowBox| needs to be in the window's coordinate system.
1280 - (NSRect)selectedTabGrowBoxRect {
1281   NSWindow* window = [self window];
1282   if (![window respondsToSelector:@selector(_growBoxRect)])
1283     return NSZeroRect;
1284
1285   // Before we return a rect, we need to convert it from window coordinates
1286   // to tab content area coordinates and flip the coordinate system.
1287   NSRect growBoxRect =
1288       [[self tabContentArea] convertRect:[window _growBoxRect] fromView:nil];
1289   growBoxRect.origin.y =
1290       NSHeight([[self tabContentArea] frame]) - NSMaxY(growBoxRect);
1291   return growBoxRect;
1292 }
1293
1294 // Accept tabs from a BrowserWindowController with the same Profile.
1295 - (BOOL)canReceiveFrom:(TabWindowController*)source {
1296   BrowserWindowController* realSource =
1297       base::mac::ObjCCast<BrowserWindowController>(source);
1298   if (!realSource || browser_->profile() != realSource->browser_->profile()) {
1299     return NO;
1300   }
1301
1302   // Can't drag a tab from a normal browser to a pop-up
1303   if (browser_->type() != realSource->browser_->type()) {
1304     return NO;
1305   }
1306
1307   return YES;
1308 }
1309
1310 // Move a given tab view to the location of the current placeholder. If there is
1311 // no placeholder, it will go at the end. |controller| is the window controller
1312 // of a tab being dropped from a different window. It will be nil if the drag is
1313 // within the window, otherwise the tab is removed from that window before being
1314 // placed into this one. The implementation will call |-removePlaceholder| since
1315 // the drag is now complete.  This also calls |-layoutTabs| internally so
1316 // clients do not need to call it again.
1317 - (void)moveTabViews:(NSArray*)views
1318       fromController:(TabWindowController*)dragController {
1319   if (dragController) {
1320     // Moving between windows.
1321     NSView* activeTabView = [dragController activeTabView];
1322     BrowserWindowController* dragBWC =
1323         base::mac::ObjCCastStrict<BrowserWindowController>(dragController);
1324
1325     // We will drop the tabs starting at indexOfPlaceholder, and increment from
1326     // there. We remove the placehoder before dropping the tabs, so that the
1327     // new tab animation's destination frame is correct.
1328     int tabIndex = [tabStripController_ indexOfPlaceholder];
1329     [self removePlaceholder];
1330
1331     for (NSView* view in views) {
1332       // Figure out the WebContents to drop into our tab model from the source
1333       // window's model.
1334       int index = [dragBWC->tabStripController_ modelIndexForTabView:view];
1335       WebContents* contents =
1336           dragBWC->browser_->tab_strip_model()->GetWebContentsAt(index);
1337       // The tab contents may have gone away if given a window.close() while it
1338       // is being dragged. If so, bail, we've got nothing to drop.
1339       if (!contents)
1340         continue;
1341
1342       // Convert |view|'s frame (which starts in the source tab strip's
1343       // coordinate system) to the coordinate system of the destination tab
1344       // strip. This needs to be done before being detached so the window
1345       // transforms can be performed.
1346       NSRect destinationFrame = [view frame];
1347       NSPoint tabOrigin = destinationFrame.origin;
1348       tabOrigin = [[dragController tabStripView] convertPoint:tabOrigin
1349                                                        toView:nil];
1350       tabOrigin = [[dragController window] convertBaseToScreen:tabOrigin];
1351       tabOrigin = [[self window] convertScreenToBase:tabOrigin];
1352       tabOrigin = [[self tabStripView] convertPoint:tabOrigin fromView:nil];
1353       destinationFrame.origin = tabOrigin;
1354
1355       // Before the tab is detached from its originating tab strip, store the
1356       // pinned state so that it can be maintained between the windows.
1357       bool isPinned = dragBWC->browser_->tab_strip_model()->IsTabPinned(index);
1358
1359       // Now that we have enough information about the tab, we can remove it
1360       // from the dragging window. We need to do this *before* we add it to the
1361       // new window as this will remove the WebContents' delegate.
1362       [dragController detachTabView:view];
1363
1364       // Deposit it into our model at the appropriate location (it already knows
1365       // where it should go from tracking the drag). Doing this sets the tab's
1366       // delegate to be the Browser.
1367       [tabStripController_ dropWebContents:contents
1368                                    atIndex:tabIndex++
1369                                  withFrame:destinationFrame
1370                                asPinnedTab:isPinned
1371                                   activate:view == activeTabView];
1372     }
1373   } else {
1374     // Moving within a window.
1375     for (NSView* view in views) {
1376       int index = [tabStripController_ modelIndexForTabView:view];
1377       [tabStripController_ moveTabFromIndex:index];
1378     }
1379     [self removePlaceholder];
1380   }
1381 }
1382
1383 // Tells the tab strip to forget about this tab in preparation for it being
1384 // put into a different tab strip, such as during a drop on another window.
1385 - (void)detachTabView:(NSView*)view {
1386   int index = [tabStripController_ modelIndexForTabView:view];
1387   browser_->tab_strip_model()->DetachWebContentsAt(index);
1388 }
1389
1390 - (NSArray*)tabViews {
1391   return [tabStripController_ tabViews];
1392 }
1393
1394 - (NSView*)activeTabView {
1395   return [tabStripController_ activeTabView];
1396 }
1397
1398 - (void)setIsLoading:(BOOL)isLoading force:(BOOL)force {
1399   [toolbarController_ setIsLoading:isLoading force:force];
1400 }
1401
1402 // Make the location bar the first responder, if possible.
1403 - (void)focusLocationBar:(BOOL)selectAll {
1404   [toolbarController_ focusLocationBar:selectAll];
1405 }
1406
1407 - (void)focusTabContents {
1408   content::WebContents* const activeWebContents =
1409       browser_->tab_strip_model()->GetActiveWebContents();
1410   if (activeWebContents)
1411     activeWebContents->Focus();
1412 }
1413
1414 - (void)layoutTabs {
1415   [tabStripController_ layoutTabs];
1416 }
1417
1418 - (TabWindowController*)detachTabsToNewWindow:(NSArray*)tabViews
1419                                    draggedTab:(NSView*)draggedTab {
1420   DCHECK_GT([tabViews count], 0U);
1421
1422   // Disable screen updates so that this appears as a single visual change.
1423   gfx::ScopedNSDisableScreenUpdates disabler;
1424
1425   // Set the window size. Need to do this before we detach the tab so it's
1426   // still in the window. We have to flip the coordinates as that's what
1427   // is expected by the Browser code.
1428   NSWindow* sourceWindow = [draggedTab window];
1429   NSRect windowRect = [sourceWindow frame];
1430   NSScreen* screen = [sourceWindow screen];
1431   windowRect.origin.y = NSHeight([screen frame]) - NSMaxY(windowRect);
1432   gfx::Rect browserRect(windowRect.origin.x, windowRect.origin.y,
1433                         NSWidth(windowRect), NSHeight(windowRect));
1434
1435   std::vector<TabStripModelDelegate::NewStripContents> contentses;
1436   TabStripModel* model = browser_->tab_strip_model();
1437
1438   for (TabView* tabView in tabViews) {
1439     // Fetch the tab contents for the tab being dragged.
1440     int index = [tabStripController_ modelIndexForTabView:tabView];
1441     bool isPinned = model->IsTabPinned(index);
1442     bool isActive = (index == model->active_index());
1443
1444     TabStripModelDelegate::NewStripContents item;
1445     item.web_contents = model->GetWebContentsAt(index);
1446     item.add_types =
1447         (isActive ? TabStripModel::ADD_ACTIVE : TabStripModel::ADD_NONE) |
1448         (isPinned ? TabStripModel::ADD_PINNED : TabStripModel::ADD_NONE);
1449     contentses.push_back(item);
1450   }
1451
1452   for (TabView* tabView in tabViews) {
1453     int index = [tabStripController_ modelIndexForTabView:tabView];
1454     // Detach it from the source window, which just updates the model without
1455     // deleting the tab contents. This needs to come before creating the new
1456     // Browser because it clears the WebContents' delegate, which gets hooked
1457     // up during creation of the new window.
1458     model->DetachWebContentsAt(index);
1459   }
1460
1461   // Create a new window with the dragged tabs in its model.
1462   Browser* newBrowser = browser_->tab_strip_model()->delegate()->
1463       CreateNewStripWithContents(contentses, browserRect, false);
1464
1465   // Get the new controller by asking the new window for its delegate.
1466   BrowserWindowController* controller =
1467       reinterpret_cast<BrowserWindowController*>(
1468           [newBrowser->window()->GetNativeWindow() delegate]);
1469   DCHECK(controller && [controller isKindOfClass:[TabWindowController class]]);
1470
1471   // And make sure we use the correct frame in the new view.
1472   TabStripController* tabStripController = [controller tabStripController];
1473   NSView* tabStrip = [self tabStripView];
1474   NSEnumerator* tabEnumerator = [tabViews objectEnumerator];
1475   for (NSView* newView in [tabStripController tabViews]) {
1476     NSView* oldView = [tabEnumerator nextObject];
1477     if (oldView) {
1478       // Pushes tabView's frame back inside the tabstrip.
1479       NSRect sourceTabRect = [oldView frame];
1480       NSSize tabOverflow =
1481           [self overflowFrom:[tabStrip convertRect:sourceTabRect toView:nil]
1482                           to:[tabStrip frame]];
1483       NSRect tabRect =
1484           NSOffsetRect(sourceTabRect, -tabOverflow.width, -tabOverflow.height);
1485       // Force the added tab to the right size (remove stretching.)
1486       tabRect.size.height = [TabStripController defaultTabHeight];
1487
1488       [tabStripController setFrame:tabRect ofTabView:newView];
1489     }
1490   }
1491
1492   return controller;
1493 }
1494
1495 - (void)insertPlaceholderForTab:(TabView*)tab
1496                           frame:(NSRect)frame {
1497   [super insertPlaceholderForTab:tab frame:frame];
1498   [tabStripController_ insertPlaceholderForTab:tab frame:frame];
1499 }
1500
1501 - (void)removePlaceholder {
1502   [super removePlaceholder];
1503   [tabStripController_ insertPlaceholderForTab:nil frame:NSZeroRect];
1504 }
1505
1506 - (BOOL)isDragSessionActive {
1507   // The tab can be dragged within the existing tab strip or detached
1508   // into its own window (then the overlay window will be present).
1509   return [[self tabStripController] isDragSessionActive] ||
1510          [self overlayWindow] != nil;
1511 }
1512
1513 - (BOOL)tabDraggingAllowed {
1514   return [tabStripController_ tabDraggingAllowed];
1515 }
1516
1517 - (BOOL)tabTearingAllowed {
1518   return ![self isInAnyFullscreenMode];
1519 }
1520
1521 - (BOOL)windowMovementAllowed {
1522   return ![self isInAnyFullscreenMode];
1523 }
1524
1525 - (BOOL)isTabFullyVisible:(TabView*)tab {
1526   return [tabStripController_ isTabFullyVisible:tab];
1527 }
1528
1529 - (void)showNewTabButton:(BOOL)show {
1530   [tabStripController_ showNewTabButton:show];
1531 }
1532
1533 - (BOOL)shouldShowAvatar {
1534   if (![self hasTabStrip])
1535     return NO;
1536   if (browser_->profile()->IsOffTheRecord())
1537     return YES;
1538
1539   ProfileInfoCache& cache =
1540       g_browser_process->profile_manager()->GetProfileInfoCache();
1541   if (cache.GetIndexOfProfileWithPath(browser_->profile()->GetPath()) ==
1542       std::string::npos) {
1543     return NO;
1544   }
1545
1546   return AvatarMenu::ShouldShowAvatarMenu();
1547 }
1548
1549 - (BOOL)shouldUseNewAvatarButton {
1550   return switches::IsNewAvatarMenu() &&
1551       profiles::IsRegularOrGuestSession(browser_.get());
1552 }
1553
1554 - (BOOL)isBookmarkBarVisible {
1555   return [bookmarkBarController_ isVisible];
1556 }
1557
1558 - (BOOL)isBookmarkBarAnimating {
1559   return [bookmarkBarController_ isAnimationRunning];
1560 }
1561
1562 - (BookmarkBarController*)bookmarkBarController {
1563   return bookmarkBarController_;
1564 }
1565
1566 - (DevToolsController*)devToolsController {
1567   return devToolsController_;
1568 }
1569
1570 - (BOOL)isDownloadShelfVisible {
1571   return downloadShelfController_ != nil &&
1572       [downloadShelfController_ isVisible];
1573 }
1574
1575 - (void)createAndAddDownloadShelf {
1576   if (!downloadShelfController_.get()) {
1577     downloadShelfController_.reset([[DownloadShelfController alloc]
1578         initWithBrowser:browser_.get() resizeDelegate:self]);
1579     [self.chromeContentView addSubview:[downloadShelfController_ view]];
1580   }
1581 }
1582
1583 - (DownloadShelfController*)downloadShelf {
1584   return downloadShelfController_;
1585 }
1586
1587 - (void)addFindBar:(FindBarCocoaController*)findBarCocoaController {
1588   // Shouldn't call addFindBar twice.
1589   DCHECK(!findBarCocoaController_.get());
1590
1591   // Create a controller for the findbar.
1592   findBarCocoaController_.reset([findBarCocoaController retain]);
1593   [self layoutSubviews];
1594   [self updateSubviewZOrder];
1595 }
1596
1597 - (NSWindow*)createFullscreenWindow {
1598   return [[[FullscreenWindow alloc] initForScreen:[[self window] screen]]
1599            autorelease];
1600 }
1601
1602 - (NSInteger)numberOfTabs {
1603   // count() includes pinned tabs.
1604   return browser_->tab_strip_model()->count();
1605 }
1606
1607 - (BOOL)hasLiveTabs {
1608   return !browser_->tab_strip_model()->empty();
1609 }
1610
1611 - (NSString*)activeTabTitle {
1612   WebContents* contents = browser_->tab_strip_model()->GetActiveWebContents();
1613   return base::SysUTF16ToNSString(contents->GetTitle());
1614 }
1615
1616 - (NSRect)regularWindowFrame {
1617   return [self isInAnyFullscreenMode] ? savedRegularWindowFrame_
1618                                       : [[self window] frame];
1619 }
1620
1621 // (Override of |TabWindowController| method.)
1622 - (BOOL)hasTabStrip {
1623   return [self supportsWindowFeature:Browser::FEATURE_TABSTRIP];
1624 }
1625
1626 - (BOOL)isTabDraggable:(NSView*)tabView {
1627   // TODO(avi, thakis): ConstrainedWindowSheetController has no api to move
1628   // tabsheets between windows. Until then, we have to prevent having to move a
1629   // tabsheet between windows, e.g. no tearing off of tabs.
1630   int index = [tabStripController_ modelIndexForTabView:tabView];
1631   WebContents* contents = browser_->tab_strip_model()->GetWebContentsAt(index);
1632   if (!contents)
1633     return NO;
1634
1635   return !web_modal::PopupManager::FromWebContents(contents)->
1636       IsWebModalDialogActive(contents);
1637 }
1638
1639 // TabStripControllerDelegate protocol.
1640 - (void)onActivateTabWithContents:(WebContents*)contents {
1641   // Update various elements that are interested in knowing the current
1642   // WebContents.
1643
1644   // Update all the UI bits.
1645   windowShim_->UpdateTitleBar();
1646
1647   // Update the bookmark bar.
1648   // TODO(viettrungluu): perhaps update to not terminate running animations (if
1649   // applicable)?
1650   windowShim_->BookmarkBarStateChanged(
1651       BookmarkBar::DONT_ANIMATE_STATE_CHANGE);
1652
1653   [infoBarContainerController_ changeWebContents:contents];
1654
1655   // No need to remove previous bubble. It will close itself.
1656   // TODO(leng):  The PermissionBubbleManager for the previous contents should
1657   // have SetView(NULL) called.  Fix this when the previous contents are
1658   // available here or move to BrowserWindowCocoa::OnActiveTabChanged().
1659   // crbug.com/340720
1660   PermissionBubbleManager::FromWebContents(contents)->SetView(
1661       permissionBubbleCocoa_.get());
1662
1663   // Must do this after bookmark and infobar updates to avoid
1664   // unnecesary resize in contents.
1665   [devToolsController_ updateDevToolsForWebContents:contents
1666                                         withProfile:browser_->profile()];
1667 }
1668
1669 - (void)onTabChanged:(TabStripModelObserver::TabChangeType)change
1670         withContents:(WebContents*)contents {
1671   // Update titles if this is the currently selected tab and if it isn't just
1672   // the loading state which changed.
1673   if (change != TabStripModelObserver::LOADING_ONLY)
1674     windowShim_->UpdateTitleBar();
1675
1676   // Update the bookmark bar if this is the currently selected tab and if it
1677   // isn't just the title which changed. This for transitions between the NTP
1678   // (showing its floating bookmark bar) and normal web pages (showing no
1679   // bookmark bar).
1680   // TODO(viettrungluu): perhaps update to not terminate running animations?
1681   if (change != TabStripModelObserver::TITLE_NOT_LOADING) {
1682     windowShim_->BookmarkBarStateChanged(
1683         BookmarkBar::DONT_ANIMATE_STATE_CHANGE);
1684   }
1685 }
1686
1687 - (void)onTabDetachedWithContents:(WebContents*)contents {
1688   [infoBarContainerController_ tabDetachedWithContents:contents];
1689 }
1690
1691 - (void)userChangedTheme {
1692   [[[[self window] contentView] superview] cr_recursivelySetNeedsDisplay:YES];
1693 }
1694
1695 - (ui::ThemeProvider*)themeProvider {
1696   return ThemeServiceFactory::GetForProfile(browser_->profile());
1697 }
1698
1699 - (ThemedWindowStyle)themedWindowStyle {
1700   ThemedWindowStyle style = 0;
1701   if (browser_->profile()->IsOffTheRecord())
1702     style |= THEMED_INCOGNITO;
1703
1704   if (browser_->is_devtools())
1705     style |= THEMED_DEVTOOLS;
1706   if (browser_->is_type_popup())
1707     style |= THEMED_POPUP;
1708
1709   return style;
1710 }
1711
1712 - (NSPoint)themeImagePositionForAlignment:(ThemeImageAlignment)alignment {
1713   NSView* windowChromeView = [[[self window] contentView] superview];
1714   NSView* tabStripView = nil;
1715   if ([self hasTabStrip])
1716     tabStripView = [self tabStripView];
1717   return [BrowserWindowUtils themeImagePositionFor:windowChromeView
1718                                       withTabStrip:tabStripView
1719                                          alignment:alignment];
1720 }
1721
1722 - (NSPoint)bookmarkBubblePoint {
1723   return [toolbarController_ bookmarkBubblePoint];
1724 }
1725
1726 // Show the bookmark bubble (e.g. user just clicked on the STAR).
1727 - (void)showBookmarkBubbleForURL:(const GURL&)url
1728                alreadyBookmarked:(BOOL)alreadyMarked {
1729   if (!bookmarkBubbleController_) {
1730     BookmarkModel* model =
1731         BookmarkModelFactory::GetForProfile(browser_->profile());
1732     ChromeBookmarkClient* client =
1733         ChromeBookmarkClientFactory::GetForProfile(browser_->profile());
1734     const BookmarkNode* node = model->GetMostRecentlyAddedUserNodeForURL(url);
1735     bookmarkBubbleController_ =
1736         [[BookmarkBubbleController alloc] initWithParentWindow:[self window]
1737                                                         client:client
1738                                                          model:model
1739                                                           node:node
1740                                              alreadyBookmarked:alreadyMarked];
1741     [bookmarkBubbleController_ showWindow:self];
1742     NSNotificationCenter* center = [NSNotificationCenter defaultCenter];
1743     [center addObserver:self
1744                selector:@selector(bookmarkBubbleWindowWillClose:)
1745                    name:NSWindowWillCloseNotification
1746                  object:[bookmarkBubbleController_ window]];
1747   }
1748 }
1749
1750 // Nil out the weak bookmark bubble controller reference.
1751 - (void)bookmarkBubbleWindowWillClose:(NSNotification*)notification {
1752   DCHECK_EQ([notification object], [bookmarkBubbleController_ window]);
1753
1754   NSNotificationCenter* center = [NSNotificationCenter defaultCenter];
1755   [center removeObserver:self
1756                     name:NSWindowWillCloseNotification
1757                   object:[bookmarkBubbleController_ window]];
1758   bookmarkBubbleController_ = nil;
1759 }
1760
1761 // Handle the editBookmarkNode: action sent from bookmark bubble controllers.
1762 - (void)editBookmarkNode:(id)sender {
1763   BOOL responds = [sender respondsToSelector:@selector(node)];
1764   DCHECK(responds);
1765   if (responds) {
1766     const BookmarkNode* node = [sender node];
1767     if (node)
1768       BookmarkEditor::Show([self window], browser_->profile(),
1769           BookmarkEditor::EditDetails::EditNode(node),
1770           BookmarkEditor::SHOW_TREE);
1771   }
1772 }
1773
1774 - (void)showTranslateBubbleForWebContents:(content::WebContents*)contents
1775                                      step:(translate::TranslateStep)step
1776                                 errorType:(translate::TranslateErrors::Type)
1777                                 errorType {
1778   // TODO(hajimehoshi): The similar logic exists at TranslateBubbleView::
1779   // ShowBubble. This should be unified.
1780   if (translateBubbleController_) {
1781     // When the user reads the advanced setting panel, the bubble should not be
1782     // changed because he/she is focusing on the bubble.
1783     if (translateBubbleController_.webContents == contents &&
1784         translateBubbleController_.model->GetViewState() ==
1785         TranslateBubbleModel::VIEW_STATE_ADVANCED) {
1786       return;
1787     }
1788     if (step != translate::TRANSLATE_STEP_TRANSLATE_ERROR) {
1789       TranslateBubbleModel::ViewState viewState =
1790           TranslateBubbleModelImpl::TranslateStepToViewState(step);
1791       [translateBubbleController_ switchView:viewState];
1792     } else {
1793       [translateBubbleController_ switchToErrorView:errorType];
1794     }
1795     return;
1796   }
1797
1798   std::string sourceLanguage;
1799   std::string targetLanguage;
1800   ChromeTranslateClient::GetTranslateLanguages(
1801       contents, &sourceLanguage, &targetLanguage);
1802
1803   scoped_ptr<translate::TranslateUIDelegate> uiDelegate(
1804       new translate::TranslateUIDelegate(
1805           ChromeTranslateClient::GetManagerFromWebContents(contents)
1806               ->GetWeakPtr(),
1807           sourceLanguage,
1808           targetLanguage));
1809   scoped_ptr<TranslateBubbleModel> model(
1810       new TranslateBubbleModelImpl(step, uiDelegate.Pass()));
1811   translateBubbleController_ = [[TranslateBubbleController alloc]
1812                                  initWithParentWindow:self
1813                                                 model:model.Pass()
1814                                           webContents:contents];
1815   [translateBubbleController_ showWindow:nil];
1816
1817   NSNotificationCenter* center = [NSNotificationCenter defaultCenter];
1818   [center addObserver:self
1819              selector:@selector(translateBubbleWindowWillClose:)
1820                  name:NSWindowWillCloseNotification
1821                object:[translateBubbleController_ window]];
1822 }
1823
1824 // Nil out the weak translate bubble controller reference.
1825 - (void)translateBubbleWindowWillClose:(NSNotification*)notification {
1826   DCHECK_EQ([notification object], [translateBubbleController_ window]);
1827
1828   NSNotificationCenter* center = [NSNotificationCenter defaultCenter];
1829   [center removeObserver:self
1830                     name:NSWindowWillCloseNotification
1831                   object:[translateBubbleController_ window]];
1832   translateBubbleController_ = nil;
1833 }
1834
1835 // If the browser is in incognito mode or has multi-profiles, install the image
1836 // view to decorate the window at the upper right. Use the same base y
1837 // coordinate as the tab strip.
1838 - (void)installAvatar {
1839   // Install the image into the badge view. Hide it for now; positioning and
1840   // sizing will be done by the layout code. The AvatarIcon will choose which
1841   // image to display based on the browser. The AvatarButton will display
1842   // the browser profile's name unless the browser is incognito.
1843   NSView* view;
1844   if ([self shouldUseNewAvatarButton]) {
1845     avatarButtonController_.reset(
1846       [[AvatarButtonController alloc] initWithBrowser:browser_.get()]);
1847   } else {
1848     avatarButtonController_.reset(
1849       [[AvatarIconController alloc] initWithBrowser:browser_.get()]);
1850   }
1851   view = [avatarButtonController_ view];
1852   [view setAutoresizingMask:NSViewMinXMargin | NSViewMinYMargin];
1853   [view setHidden:![self shouldShowAvatar]];
1854
1855   // Install the view.
1856   [[[self window] cr_windowView] addSubview:view];
1857 }
1858
1859 // Called when we get a three-finger swipe.
1860 - (void)swipeWithEvent:(NSEvent*)event {
1861   CGFloat deltaX = [event deltaX];
1862   CGFloat deltaY = [event deltaY];
1863
1864   // Map forwards and backwards to history; left is positive, right is negative.
1865   unsigned int command = 0;
1866   if (deltaX > 0.5) {
1867     command = IDC_BACK;
1868   } else if (deltaX < -0.5) {
1869     command = IDC_FORWARD;
1870   } else if (deltaY > 0.5) {
1871     // TODO(pinkerton): figure out page-up, http://crbug.com/16305
1872   } else if (deltaY < -0.5) {
1873     // TODO(pinkerton): figure out page-down, http://crbug.com/16305
1874   }
1875
1876   // Ensure the command is valid first (ExecuteCommand() won't do that) and
1877   // then make it so.
1878   if (chrome::IsCommandEnabled(browser_.get(), command)) {
1879     chrome::ExecuteCommandWithDisposition(
1880         browser_.get(),
1881         command,
1882         ui::WindowOpenDispositionFromNSEvent(event));
1883   }
1884 }
1885
1886 // Delegate method called when window is resized.
1887 - (void)windowDidResize:(NSNotification*)notification {
1888   [self saveWindowPositionIfNeeded];
1889
1890   // Resize (and possibly move) the status bubble. Note that we may get called
1891   // when the status bubble does not exist.
1892   if (statusBubble_) {
1893     statusBubble_->UpdateSizeAndPosition();
1894   }
1895
1896   // Let the selected RenderWidgetHostView know, so that it can tell plugins.
1897   if (WebContents* contents =
1898           browser_->tab_strip_model()->GetActiveWebContents()) {
1899     if (RenderWidgetHostView* rwhv = contents->GetRenderWidgetHostView())
1900       rwhv->WindowFrameChanged();
1901   }
1902
1903   // The FindBar needs to know its own position to properly detect overlaps
1904   // with find results. The position changes whenever the window is resized,
1905   // and |layoutSubviews| computes the FindBar's position.
1906   // TODO: calling |layoutSubviews| here is a waste, find a better way to
1907   // do this.
1908   if ([findBarCocoaController_ isFindBarVisible])
1909     [self layoutSubviews];
1910 }
1911
1912 // Handle the openLearnMoreAboutCrashLink: action from SadTabController when
1913 // "Learn more" link in "Aw snap" page (i.e. crash page or sad tab) is
1914 // clicked. Decoupling the action from its target makes unit testing possible.
1915 - (void)openLearnMoreAboutCrashLink:(id)sender {
1916   if (SadTabController* sadTab =
1917           base::mac::ObjCCast<SadTabController>(sender)) {
1918     WebContents* webContents = [sadTab webContents];
1919     if (webContents) {
1920       OpenURLParams params(
1921           GURL(chrome::kCrashReasonURL), Referrer(), CURRENT_TAB,
1922           ui::PAGE_TRANSITION_LINK, false);
1923       webContents->OpenURL(params);
1924     }
1925   }
1926 }
1927
1928 // Delegate method called when window did move. (See below for why we don't use
1929 // |-windowWillMove:|, which is called less frequently than |-windowDidMove|
1930 // instead.)
1931 - (void)windowDidMove:(NSNotification*)notification {
1932   [self saveWindowPositionIfNeeded];
1933
1934   NSWindow* window = [self window];
1935   NSRect windowFrame = [window frame];
1936   NSRect workarea = [[window screen] visibleFrame];
1937
1938   // We reset the window growth state whenever the window is moved out of the
1939   // work area or away (up or down) from the bottom or top of the work area.
1940   // Unfortunately, Cocoa sends |-windowWillMove:| too frequently (including
1941   // when clicking on the title bar to activate), and of course
1942   // |-windowWillMove| is called too early for us to apply our heuristic. (The
1943   // heuristic we use for detecting window movement is that if |windowTopGrowth_
1944   // > 0|, then we should be at the bottom of the work area -- if we're not,
1945   // we've moved. Similarly for the other side.)
1946   if (!NSContainsRect(workarea, windowFrame) ||
1947       (windowTopGrowth_ > 0 && NSMinY(windowFrame) != NSMinY(workarea)) ||
1948       (windowBottomGrowth_ > 0 && NSMaxY(windowFrame) != NSMaxY(workarea)))
1949     [self resetWindowGrowthState];
1950
1951   // Let the selected RenderWidgetHostView know, so that it can tell plugins.
1952   if (WebContents* contents =
1953           browser_->tab_strip_model()->GetActiveWebContents()) {
1954     if (RenderWidgetHostView* rwhv = contents->GetRenderWidgetHostView())
1955       rwhv->WindowFrameChanged();
1956   }
1957 }
1958
1959 // Delegate method called when window will be resized; not called for
1960 // |-setFrame:display:|.
1961 - (NSSize)windowWillResize:(NSWindow*)sender toSize:(NSSize)frameSize {
1962   [self resetWindowGrowthState];
1963   return frameSize;
1964 }
1965
1966 // Delegate method: see |NSWindowDelegate| protocol.
1967 - (id)windowWillReturnFieldEditor:(NSWindow*)sender toObject:(id)obj {
1968   // Ask the toolbar controller if it wants to return a custom field editor
1969   // for the specific object.
1970   return [toolbarController_ customFieldEditorForObject:obj];
1971 }
1972
1973 // (Needed for |BookmarkBarControllerDelegate| protocol.)
1974 - (void)bookmarkBar:(BookmarkBarController*)controller
1975  didChangeFromState:(BookmarkBar::State)oldState
1976             toState:(BookmarkBar::State)newState {
1977   [toolbarController_ setDividerOpacity:[self toolbarDividerOpacity]];
1978   [self adjustToolbarAndBookmarkBarForCompression:
1979           [controller getDesiredToolbarHeightCompression]];
1980 }
1981
1982 // (Needed for |BookmarkBarControllerDelegate| protocol.)
1983 - (void)bookmarkBar:(BookmarkBarController*)controller
1984 willAnimateFromState:(BookmarkBar::State)oldState
1985             toState:(BookmarkBar::State)newState {
1986   [toolbarController_ setDividerOpacity:[self toolbarDividerOpacity]];
1987   [self adjustToolbarAndBookmarkBarForCompression:
1988           [controller getDesiredToolbarHeightCompression]];
1989 }
1990
1991 // (Private/TestingAPI)
1992 - (void)resetWindowGrowthState {
1993   windowTopGrowth_ = 0;
1994   windowBottomGrowth_ = 0;
1995   isShrinkingFromZoomed_ = NO;
1996 }
1997
1998 - (NSSize)overflowFrom:(NSRect)source
1999                     to:(NSRect)target {
2000   // If |source|'s boundary is outside of |target|'s, set its distance
2001   // to |x|.  Note that |source| can overflow to both side, but we
2002   // have nothing to do for such case.
2003   CGFloat x = 0;
2004   if (NSMaxX(target) < NSMaxX(source)) // |source| overflows to right
2005     x = NSMaxX(source) - NSMaxX(target);
2006   else if (NSMinX(source) < NSMinX(target)) // |source| overflows to left
2007     x = NSMinX(source) - NSMinX(target);
2008
2009   // Same as |x| above.
2010   CGFloat y = 0;
2011   if (NSMaxY(target) < NSMaxY(source))
2012     y = NSMaxY(source) - NSMaxY(target);
2013   else if (NSMinY(source) < NSMinY(target))
2014     y = NSMinY(source) - NSMinY(target);
2015
2016   return NSMakeSize(x, y);
2017 }
2018
2019 // (Private/TestingAPI)
2020 - (FullscreenExitBubbleController*)fullscreenExitBubbleController {
2021   return fullscreenExitBubbleController_.get();
2022 }
2023
2024 - (NSRect)omniboxPopupAnchorRect {
2025   // Start with toolbar rect.
2026   NSView* toolbarView = [toolbarController_ view];
2027   NSRect anchorRect = [toolbarView frame];
2028
2029   // Adjust to account for height and possible bookmark bar. Compress by 1
2030   // to account for the separator.
2031   anchorRect.origin.y =
2032       NSMaxY(anchorRect) - [toolbarController_ desiredHeightForCompression:1];
2033
2034   // Shift to window base coordinates.
2035   return [[toolbarView superview] convertRect:anchorRect toView:nil];
2036 }
2037
2038 - (void)layoutInfoBars {
2039   [self layoutSubviews];
2040 }
2041
2042 - (void)sheetDidEnd:(NSWindow*)sheet
2043          returnCode:(NSInteger)code
2044             context:(void*)context {
2045   [sheet orderOut:self];
2046 }
2047
2048 - (void)executeExtensionCommand:(const std::string&)extension_id
2049                         command:(const extensions::Command&)command {
2050   // Global commands are handled by the ExtensionCommandsGlobalRegistry
2051   // instance.
2052   DCHECK(!command.global());
2053   extension_keybinding_registry_->ExecuteCommand(extension_id,
2054                                                  command.accelerator());
2055 }
2056
2057 @end  // @implementation BrowserWindowController
2058
2059 @implementation BrowserWindowController(Fullscreen)
2060
2061 - (void)handleLionToggleFullscreen {
2062   DCHECK(base::mac::IsOSLionOrLater());
2063   chrome::ExecuteCommand(browser_.get(), IDC_FULLSCREEN);
2064 }
2065
2066 - (void)enterFullscreenWithChrome {
2067   if (![self isInAppKitFullscreen]) {
2068     // Invoking the AppKitFullscreen API by default uses Canonical Fullscreen.
2069     [self enterAppKitFullscreen];
2070     return;
2071   }
2072
2073   // If AppKitFullscreen is already enabled, then just switch to Canonical
2074   // Fullscreen.
2075   [self adjustUIForSlidingFullscreenStyle:fullscreen_mac::OMNIBOX_TABS_PRESENT];
2076 }
2077
2078 - (void)updateFullscreenExitBubbleURL:(const GURL&)url
2079                            bubbleType:(FullscreenExitBubbleType)bubbleType {
2080   fullscreenUrl_ = url;
2081   fullscreenBubbleType_ = bubbleType;
2082   [self layoutSubviews];
2083   [self showFullscreenExitBubbleIfNecessary];
2084 }
2085
2086 - (BOOL)isInAnyFullscreenMode {
2087   return [self isInImmersiveFullscreen] || [self isInAppKitFullscreen];
2088 }
2089
2090 - (BOOL)isInImmersiveFullscreen {
2091   return fullscreenWindow_.get() != nil || enteringImmersiveFullscreen_;
2092 }
2093
2094 - (BOOL)isInAppKitFullscreen {
2095   return ([[self window] styleMask] & NSFullScreenWindowMask) ==
2096              NSFullScreenWindowMask ||
2097          enteringAppKitFullscreen_;
2098 }
2099
2100 - (void)enterPresentationMode {
2101   if (!chrome::mac::SupportsSystemFullscreen()) {
2102     if ([self isInImmersiveFullscreen])
2103       return;
2104     [self enterImmersiveFullscreen];
2105     return;
2106   }
2107
2108   if ([self isInAppKitFullscreen]) {
2109     // Already in AppKit Fullscreen. Adjust the UI to use Presentation Mode.
2110     [self
2111         adjustUIForSlidingFullscreenStyle:fullscreen_mac::OMNIBOX_TABS_HIDDEN];
2112   } else {
2113     // Need to invoke AppKit Fullscreen API. Presentation mode will
2114     // automatically be enabled in |-windowWillEnterFullScreen:|.
2115     enteringPresentationMode_ = YES;
2116     [self enterAppKitFullscreen];
2117   }
2118 }
2119
2120 - (void)enterExtensionFullscreenForURL:(const GURL&)url
2121                             bubbleType:(FullscreenExitBubbleType)bubbleType {
2122   if (chrome::mac::SupportsSystemFullscreen()) {
2123     fullscreenUrl_ = url;
2124     fullscreenBubbleType_ = bubbleType;
2125     [self enterPresentationMode];
2126   } else {
2127     [self enterImmersiveFullscreen];
2128     DCHECK(!url.is_empty());
2129     [self updateFullscreenExitBubbleURL:url bubbleType:bubbleType];
2130   }
2131 }
2132
2133 - (void)enterWebContentFullscreenForURL:(const GURL&)url
2134                              bubbleType:(FullscreenExitBubbleType)bubbleType {
2135   [self enterImmersiveFullscreen];
2136   if (!url.is_empty())
2137     [self updateFullscreenExitBubbleURL:url bubbleType:bubbleType];
2138 }
2139
2140 - (void)exitAnyFullscreen {
2141   // TODO(erikchen): Fullscreen modes should stack. Should be able to exit
2142   // Immersive Fullscreen and still be in AppKit Fullscreen.
2143   if ([self isInAppKitFullscreen])
2144     [self exitAppKitFullscreen];
2145   if ([self isInImmersiveFullscreen])
2146     [self exitImmersiveFullscreen];
2147 }
2148
2149 - (BOOL)inPresentationMode {
2150   return presentationModeController_.get() &&
2151          [presentationModeController_ inPresentationMode] &&
2152          presentationModeController_.get().slidingStyle ==
2153              fullscreen_mac::OMNIBOX_TABS_HIDDEN;
2154 }
2155
2156 - (void)resizeFullscreenWindow {
2157   DCHECK([self isInAnyFullscreenMode]);
2158   if (![self isInAnyFullscreenMode])
2159     return;
2160
2161   NSWindow* window = [self window];
2162   [window setFrame:[[window screen] frame] display:YES];
2163   [self layoutSubviews];
2164 }
2165
2166 - (BOOL)isBarVisibilityLockedForOwner:(id)owner {
2167   DCHECK(owner);
2168   DCHECK(barVisibilityLocks_);
2169   return [barVisibilityLocks_ containsObject:owner];
2170 }
2171
2172 - (void)lockBarVisibilityForOwner:(id)owner
2173                     withAnimation:(BOOL)animate
2174                             delay:(BOOL)delay {
2175   if (![self isBarVisibilityLockedForOwner:owner]) {
2176     [barVisibilityLocks_ addObject:owner];
2177
2178     // If enabled, show the overlay if necessary (and if in presentation mode).
2179     if (barVisibilityUpdatesEnabled_) {
2180       [presentationModeController_ ensureOverlayShownWithAnimation:animate
2181                                                              delay:delay];
2182     }
2183   }
2184 }
2185
2186 - (void)releaseBarVisibilityForOwner:(id)owner
2187                        withAnimation:(BOOL)animate
2188                                delay:(BOOL)delay {
2189   if ([self isBarVisibilityLockedForOwner:owner]) {
2190     [barVisibilityLocks_ removeObject:owner];
2191
2192     // If enabled, hide the overlay if necessary (and if in presentation mode).
2193     if (barVisibilityUpdatesEnabled_ &&
2194         ![barVisibilityLocks_ count]) {
2195       [presentationModeController_ ensureOverlayHiddenWithAnimation:animate
2196                                                               delay:delay];
2197     }
2198   }
2199 }
2200
2201 - (BOOL)floatingBarHasFocus {
2202   NSResponder* focused = [[self window] firstResponder];
2203   return [focused isKindOfClass:[AutocompleteTextFieldEditor class]];
2204 }
2205
2206 @end  // @implementation BrowserWindowController(Fullscreen)
2207
2208
2209 @implementation BrowserWindowController(WindowType)
2210
2211 - (BOOL)supportsWindowFeature:(int)feature {
2212   return browser_->SupportsWindowFeature(
2213       static_cast<Browser::WindowFeature>(feature));
2214 }
2215
2216 - (BOOL)hasTitleBar {
2217   return [self supportsWindowFeature:Browser::FEATURE_TITLEBAR];
2218 }
2219
2220 - (BOOL)hasToolbar {
2221   return [self supportsWindowFeature:Browser::FEATURE_TOOLBAR];
2222 }
2223
2224 - (BOOL)hasLocationBar {
2225   return [self supportsWindowFeature:Browser::FEATURE_LOCATIONBAR];
2226 }
2227
2228 - (BOOL)supportsBookmarkBar {
2229   return [self supportsWindowFeature:Browser::FEATURE_BOOKMARKBAR];
2230 }
2231
2232 - (BOOL)isTabbedWindow {
2233   return browser_->is_type_tabbed();
2234 }
2235
2236 @end  // @implementation BrowserWindowController(WindowType)