Update To 11.40.268.0
[platform/framework/web/crosswalk.git] / src / chrome / browser / ui / views / frame / browser_view.cc
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 #include "chrome/browser/ui/views/frame/browser_view.h"
6
7 #include <algorithm>
8
9 #include "base/auto_reset.h"
10 #include "base/command_line.h"
11 #include "base/i18n/rtl.h"
12 #include "base/memory/scoped_ptr.h"
13 #include "base/metrics/histogram.h"
14 #include "base/prefs/pref_service.h"
15 #include "base/strings/string_number_conversions.h"
16 #include "chrome/app/chrome_command_ids.h"
17 #include "chrome/app/chrome_dll_resource.h"
18 #include "chrome/browser/app_mode/app_mode_utils.h"
19 #include "chrome/browser/bookmarks/bookmark_stats.h"
20 #include "chrome/browser/browser_process.h"
21 #include "chrome/browser/chrome_notification_types.h"
22 #include "chrome/browser/extensions/extension_util.h"
23 #include "chrome/browser/extensions/tab_helper.h"
24 #include "chrome/browser/infobars/infobar_service.h"
25 #include "chrome/browser/native_window_notification_source.h"
26 #include "chrome/browser/profiles/avatar_menu.h"
27 #include "chrome/browser/profiles/profile.h"
28 #include "chrome/browser/profiles/profile_avatar_icon_util.h"
29 #include "chrome/browser/profiles/profile_info_cache.h"
30 #include "chrome/browser/profiles/profile_manager.h"
31 #include "chrome/browser/profiles/profiles_state.h"
32 #include "chrome/browser/search/search.h"
33 #include "chrome/browser/sessions/tab_restore_service.h"
34 #include "chrome/browser/sessions/tab_restore_service_factory.h"
35 #include "chrome/browser/signin/signin_header_helper.h"
36 #include "chrome/browser/speech/tts_controller.h"
37 #include "chrome/browser/themes/theme_properties.h"
38 #include "chrome/browser/themes/theme_service_factory.h"
39 #include "chrome/browser/translate/chrome_translate_client.h"
40 #include "chrome/browser/ui/bookmarks/bookmark_bar_constants.h"
41 #include "chrome/browser/ui/bookmarks/bookmark_bubble_delegate.h"
42 #include "chrome/browser/ui/bookmarks/bookmark_bubble_sign_in_delegate.h"
43 #include "chrome/browser/ui/browser.h"
44 #include "chrome/browser/ui/browser_command_controller.h"
45 #include "chrome/browser/ui/browser_commands.h"
46 #include "chrome/browser/ui/browser_dialogs.h"
47 #include "chrome/browser/ui/browser_finder.h"
48 #include "chrome/browser/ui/browser_list.h"
49 #include "chrome/browser/ui/browser_window_state.h"
50 #include "chrome/browser/ui/omnibox/omnibox_popup_model.h"
51 #include "chrome/browser/ui/omnibox/omnibox_popup_view.h"
52 #include "chrome/browser/ui/omnibox/omnibox_view.h"
53 #include "chrome/browser/ui/search/search_delegate.h"
54 #include "chrome/browser/ui/search/search_model.h"
55 #include "chrome/browser/ui/search/search_ui.h"
56 #include "chrome/browser/ui/tabs/tab_menu_model.h"
57 #include "chrome/browser/ui/tabs/tab_strip_model.h"
58 #include "chrome/browser/ui/view_ids.h"
59 #include "chrome/browser/ui/views/accelerator_table.h"
60 #include "chrome/browser/ui/views/accessibility/invert_bubble_view.h"
61 #include "chrome/browser/ui/views/bookmarks/bookmark_bar_view.h"
62 #include "chrome/browser/ui/views/bookmarks/bookmark_bubble_view.h"
63 #include "chrome/browser/ui/views/browser_dialogs.h"
64 #include "chrome/browser/ui/views/download/download_in_progress_dialog_view.h"
65 #include "chrome/browser/ui/views/download/download_shelf_view.h"
66 #include "chrome/browser/ui/views/extensions/bookmark_app_bubble_view.h"
67 #include "chrome/browser/ui/views/frame/browser_view_layout.h"
68 #include "chrome/browser/ui/views/frame/browser_view_layout_delegate.h"
69 #include "chrome/browser/ui/views/frame/contents_layout_manager.h"
70 #include "chrome/browser/ui/views/frame/immersive_mode_controller.h"
71 #include "chrome/browser/ui/views/frame/native_browser_frame_factory.h"
72 #include "chrome/browser/ui/views/frame/top_container_view.h"
73 #include "chrome/browser/ui/views/frame/web_contents_close_handler.h"
74 #include "chrome/browser/ui/views/fullscreen_exit_bubble_views.h"
75 #include "chrome/browser/ui/views/infobars/infobar_container_view.h"
76 #include "chrome/browser/ui/views/location_bar/location_bar_view.h"
77 #include "chrome/browser/ui/views/location_bar/location_icon_view.h"
78 #include "chrome/browser/ui/views/location_bar/zoom_bubble_view.h"
79 #include "chrome/browser/ui/views/omnibox/omnibox_view_views.h"
80 #include "chrome/browser/ui/views/profiles/avatar_menu_bubble_view.h"
81 #include "chrome/browser/ui/views/profiles/avatar_menu_button.h"
82 #include "chrome/browser/ui/views/profiles/profile_chooser_view.h"
83 #include "chrome/browser/ui/views/settings_api_bubble_helper_views.h"
84 #include "chrome/browser/ui/views/status_bubble_views.h"
85 #include "chrome/browser/ui/views/tabs/browser_tab_strip_controller.h"
86 #include "chrome/browser/ui/views/tabs/tab.h"
87 #include "chrome/browser/ui/views/tabs/tab_strip.h"
88 #include "chrome/browser/ui/views/toolbar/reload_button.h"
89 #include "chrome/browser/ui/views/toolbar/toolbar_view.h"
90 #include "chrome/browser/ui/views/translate/translate_bubble_view.h"
91 #include "chrome/browser/ui/views/update_recommended_message_box.h"
92 #include "chrome/browser/ui/views/website_settings/permissions_bubble_view.h"
93 #include "chrome/browser/ui/views/website_settings/website_settings_popup_view.h"
94 #include "chrome/browser/ui/website_settings/permission_bubble_manager.h"
95 #include "chrome/browser/ui/window_sizer/window_sizer.h"
96 #include "chrome/common/chrome_switches.h"
97 #include "chrome/common/pref_names.h"
98 #include "chrome/common/url_constants.h"
99 #include "chrome/grit/chromium_strings.h"
100 #include "chrome/grit/generated_resources.h"
101 #include "chrome/grit/locale_settings.h"
102 #include "components/app_modal_dialogs/app_modal_dialog.h"
103 #include "components/app_modal_dialogs/app_modal_dialog_queue.h"
104 #include "components/signin/core/common/profile_management_switches.h"
105 #include "components/translate/core/browser/language_state.h"
106 #include "content/app/resources/grit/content_resources.h"
107 #include "content/public/browser/download_manager.h"
108 #include "content/public/browser/native_web_keyboard_event.h"
109 #include "content/public/browser/notification_service.h"
110 #include "content/public/browser/render_frame_host.h"
111 #include "content/public/browser/render_view_host.h"
112 #include "content/public/browser/user_metrics.h"
113 #include "content/public/browser/web_contents.h"
114 #include "content/public/common/content_switches.h"
115 #include "grit/theme_resources.h"
116 #include "ui/accessibility/ax_view_state.h"
117 #include "ui/aura/client/window_tree_client.h"
118 #include "ui/aura/window.h"
119 #include "ui/aura/window_tree_host.h"
120 #include "ui/base/accelerators/accelerator.h"
121 #include "ui/base/hit_test.h"
122 #include "ui/base/l10n/l10n_util.h"
123 #include "ui/base/resource/resource_bundle.h"
124 #include "ui/base/theme_provider.h"
125 #include "ui/events/event_utils.h"
126 #include "ui/gfx/canvas.h"
127 #include "ui/gfx/color_utils.h"
128 #include "ui/gfx/rect_conversions.h"
129 #include "ui/gfx/screen.h"
130 #include "ui/strings/grit/ui_strings.h"
131 #include "ui/views/controls/button/menu_button.h"
132 #include "ui/views/controls/textfield/textfield.h"
133 #include "ui/views/controls/webview/webview.h"
134 #include "ui/views/focus/external_focus_tracker.h"
135 #include "ui/views/focus/view_storage.h"
136 #include "ui/views/layout/grid_layout.h"
137 #include "ui/views/widget/native_widget.h"
138 #include "ui/views/widget/root_view.h"
139 #include "ui/views/widget/widget.h"
140 #include "ui/views/window/dialog_delegate.h"
141
142 #if defined(OS_WIN)
143 #include "base/win/windows_version.h"
144 #include "chrome/browser/jumplist_win.h"
145 #include "ui/views/win/scoped_fullscreen_visibility.h"
146 #endif
147
148 #if defined(ENABLE_ONE_CLICK_SIGNIN)
149 #include "chrome/browser/ui/sync/one_click_signin_bubble_delegate.h"
150 #include "chrome/browser/ui/sync/one_click_signin_bubble_links_delegate.h"
151 #include "chrome/browser/ui/views/sync/one_click_signin_bubble_view.h"
152 #endif
153
154 #if defined(OS_CHROMEOS)
155 #include "chrome/browser/ui/ash/multi_user/multi_user_window_manager.h"
156 #endif
157
158 using base::TimeDelta;
159 using base::UserMetricsAction;
160 using content::NativeWebKeyboardEvent;
161 using content::SSLStatus;
162 using content::WebContents;
163 using views::ColumnSet;
164 using views::GridLayout;
165 using web_modal::WebContentsModalDialogHost;
166
167 namespace {
168 // The name of a key to store on the window handle so that other code can
169 // locate this object using just the handle.
170 const char* const kBrowserViewKey = "__BROWSER_VIEW__";
171
172 // The number of milliseconds between loading animation frames.
173 const int kLoadingAnimationFrameTimeMs = 30;
174
175 // TODO(kuan): These functions are temporarily for the bookmark bar while its
176 // detached state is at the top of the page;  it'll be moved to float on the
177 // content page in the very near future, at which time, these local functions
178 // will be removed.
179 void PaintDetachedBookmarkBar(gfx::Canvas* canvas,
180                               DetachableToolbarView* view,
181                               ThemeService* theme_service) {
182   // Paint background for detached state; if animating, this is fade in/out.
183   canvas->DrawColor(
184       chrome::GetDetachedBookmarkBarBackgroundColor(theme_service));
185   // Draw the separators above and below bookmark bar;
186   // if animating, these are fading in/out.
187   SkColor separator_color =
188       chrome::GetDetachedBookmarkBarSeparatorColor(theme_service);
189   DetachableToolbarView::PaintHorizontalBorder(canvas, view, true,
190                                                separator_color);
191   // The bottom border needs to be 1-px thick in both regular and retina
192   // displays, so we can't use DetachableToolbarView::PaintHorizontalBorder
193   // which paints a 2-px thick border in retina display.
194   SkPaint paint;
195   paint.setAntiAlias(false);
196   // Sets border to 1-px thick regardless of scale factor.
197   paint.setStrokeWidth(0);
198   // Bottom border is at 50% opacity of top border.
199   paint.setColor(SkColorSetA(separator_color,
200                              SkColorGetA(separator_color) / 2));
201   // Calculate thickness of bottom border as per current scale factor to
202   // determine where to draw the 1-px thick border.
203   float thickness = views::NonClientFrameView::kClientEdgeThickness /
204                     canvas->image_scale();
205   SkScalar y = SkIntToScalar(view->height()) - SkFloatToScalar(thickness);
206   canvas->sk_canvas()->drawLine(SkIntToScalar(0), y,
207                                 SkIntToScalar(view->width()), y, paint);
208 }
209
210 void PaintAttachedBookmarkBar(gfx::Canvas* canvas,
211                               DetachableToolbarView* view,
212                               BrowserView* browser_view,
213                               chrome::HostDesktopType host_desktop_type,
214                               int toolbar_overlap) {
215   // Paint background for attached state, this is fade in/out.
216   gfx::Point background_image_offset =
217       browser_view->OffsetPointForToolbarBackgroundImage(
218           gfx::Point(view->GetMirroredX(), view->y()));
219   DetachableToolbarView::PaintBackgroundAttachedMode(canvas,
220       view->GetThemeProvider(), view->GetLocalBounds(),
221       background_image_offset, host_desktop_type);
222   if (view->height() >= toolbar_overlap) {
223     // Draw the separator below bookmark bar; this is fading in/out.
224     DetachableToolbarView::PaintHorizontalBorder(canvas, view, false,
225         ThemeProperties::GetDefaultColor(
226             ThemeProperties::COLOR_TOOLBAR_SEPARATOR));
227   }
228 }
229
230 }  // namespace
231
232 // static
233 const char BrowserView::kViewClassName[] = "BrowserView";
234
235 ///////////////////////////////////////////////////////////////////////////////
236
237 // Delegate implementation for BrowserViewLayout. Usually just forwards calls
238 // into BrowserView.
239 class BrowserViewLayoutDelegateImpl : public BrowserViewLayoutDelegate {
240  public:
241   explicit BrowserViewLayoutDelegateImpl(BrowserView* browser_view)
242       : browser_view_(browser_view) {}
243   ~BrowserViewLayoutDelegateImpl() override {}
244
245   // BrowserViewLayoutDelegate overrides:
246   views::View* GetContentsWebView() const override {
247     return browser_view_->contents_web_view_;
248   }
249
250   bool DownloadShelfNeedsLayout() const override {
251     DownloadShelfView* download_shelf = browser_view_->download_shelf_.get();
252     // Re-layout the shelf either if it is visible or if its close animation
253     // is currently running.
254     return download_shelf &&
255            (download_shelf->IsShowing() || download_shelf->IsClosing());
256   }
257
258   bool IsTabStripVisible() const override {
259     return browser_view_->IsTabStripVisible();
260   }
261
262   gfx::Rect GetBoundsForTabStripInBrowserView() const override {
263     gfx::RectF bounds_f(browser_view_->frame()->GetBoundsForTabStrip(
264         browser_view_->tabstrip()));
265     views::View::ConvertRectToTarget(browser_view_->parent(), browser_view_,
266         &bounds_f);
267     return gfx::ToEnclosingRect(bounds_f);
268   }
269
270   int GetTopInsetInBrowserView() const override {
271     return browser_view_->frame()->GetTopInset() -
272         browser_view_->y();
273   }
274
275   int GetThemeBackgroundXInset() const override {
276     // TODO(pkotwicz): Return the inset with respect to the left edge of the
277     // BrowserView.
278     return browser_view_->frame()->GetThemeBackgroundXInset();
279   }
280
281   bool IsToolbarVisible() const override {
282     return browser_view_->IsToolbarVisible();
283   }
284
285   bool IsBookmarkBarVisible() const override {
286     return browser_view_->IsBookmarkBarVisible();
287   }
288
289   FullscreenExitBubbleViews* GetFullscreenExitBubble() const override {
290     return browser_view_->fullscreen_exit_bubble();
291   }
292
293  private:
294   BrowserView* browser_view_;
295
296   DISALLOW_COPY_AND_ASSIGN(BrowserViewLayoutDelegateImpl);
297 };
298
299 ///////////////////////////////////////////////////////////////////////////////
300 // BookmarkExtensionBackground, private:
301 // This object serves as the views::Background object which is used to layout
302 // and paint the bookmark bar.
303 class BookmarkExtensionBackground : public views::Background {
304  public:
305   BookmarkExtensionBackground(BrowserView* browser_view,
306                               DetachableToolbarView* host_view,
307                               Browser* browser);
308
309   // View methods overridden from views:Background.
310   void Paint(gfx::Canvas* canvas, views::View* view) const override;
311
312  private:
313   BrowserView* browser_view_;
314
315   // The view hosting this background.
316   DetachableToolbarView* host_view_;
317
318   Browser* browser_;
319
320   DISALLOW_COPY_AND_ASSIGN(BookmarkExtensionBackground);
321 };
322
323 BookmarkExtensionBackground::BookmarkExtensionBackground(
324     BrowserView* browser_view,
325     DetachableToolbarView* host_view,
326     Browser* browser)
327     : browser_view_(browser_view),
328       host_view_(host_view),
329       browser_(browser) {
330 }
331
332 void BookmarkExtensionBackground::Paint(gfx::Canvas* canvas,
333                                         views::View* view) const {
334   int toolbar_overlap = host_view_->GetToolbarOverlap();
335   if (!host_view_->IsDetached()) {
336     PaintAttachedBookmarkBar(canvas, host_view_, browser_view_,
337                              browser_->host_desktop_type(), toolbar_overlap);
338     return;
339   }
340
341   // As 'hidden' according to the animation is the full in-tab state, we invert
342   // the value - when current_state is at '0', we expect the bar to be docked.
343   double current_state = 1 - host_view_->GetAnimationValue();
344
345   ThemeService* ts =
346       ThemeServiceFactory::GetForProfile(browser_->profile());
347   if (current_state == 0.0 || current_state == 1.0) {
348     PaintDetachedBookmarkBar(canvas, host_view_, ts);
349     return;
350   }
351   // While animating, set opacity to cross-fade between attached and detached
352   // backgrounds including their respective separators.
353   int detached_alpha = static_cast<uint8>(current_state * 255);
354   int attached_alpha = 255 - detached_alpha;
355   if (browser_->bookmark_bar_state() == BookmarkBar::DETACHED) {
356     // To animate from attached to detached state:
357     // - fade out attached background
358     // - fade in detached background.
359     canvas->SaveLayerAlpha(attached_alpha);
360     PaintAttachedBookmarkBar(canvas, host_view_, browser_view_,
361                              browser_->host_desktop_type(),
362                              toolbar_overlap);
363     canvas->Restore();
364     canvas->SaveLayerAlpha(detached_alpha);
365     PaintDetachedBookmarkBar(canvas, host_view_, ts);
366   } else {
367     // To animate from detached to attached state:
368     // - fade out detached background
369     // - fade in attached background.
370     canvas->SaveLayerAlpha(detached_alpha);
371     PaintDetachedBookmarkBar(canvas, host_view_, ts);
372     canvas->Restore();
373     canvas->SaveLayerAlpha(attached_alpha);
374     PaintAttachedBookmarkBar(canvas, host_view_, browser_view_,
375                              browser_->host_desktop_type(),
376                              toolbar_overlap);
377   }
378   canvas->Restore();
379 }
380
381 ///////////////////////////////////////////////////////////////////////////////
382 // BrowserView, public:
383
384 BrowserView::BrowserView()
385     : views::ClientView(NULL, NULL),
386       last_focused_view_storage_id_(
387           views::ViewStorage::GetInstance()->CreateStorageID()),
388       frame_(NULL),
389       top_container_(NULL),
390       tabstrip_(NULL),
391       toolbar_(NULL),
392       find_bar_host_view_(NULL),
393       infobar_container_(NULL),
394       contents_web_view_(NULL),
395       contents_container_(NULL),
396       initialized_(false),
397       in_process_fullscreen_(false),
398 #if defined(OS_WIN)
399       hung_window_detector_(&hung_plugin_action_),
400       ticker_(0),
401 #endif
402       force_location_bar_focus_(false),
403       activate_modal_dialog_factory_(this) {
404 }
405
406 BrowserView::~BrowserView() {
407   // All the tabs should have been destroyed already. If we were closed by the
408   // OS with some tabs than the NativeBrowserFrame should have destroyed them.
409   DCHECK_EQ(0, browser_->tab_strip_model()->count());
410
411   // Immersive mode may need to reparent views before they are removed/deleted.
412   immersive_mode_controller_.reset();
413
414   browser_->tab_strip_model()->RemoveObserver(this);
415
416 #if defined(OS_WIN)
417   // Stop hung plugin monitoring.
418   ticker_.Stop();
419   ticker_.UnregisterTickHandler(&hung_window_detector_);
420
421   // Terminate the jumplist (must be called before browser_->profile() is
422   // destroyed.
423   if (jumplist_) {
424     jumplist_->Terminate();
425   }
426 #endif
427
428   // We destroy the download shelf before |browser_| to remove its child
429   // download views from the set of download observers (since the observed
430   // downloads can be destroyed along with |browser_| and the observer
431   // notifications will call back into deleted objects).
432   BrowserViewLayout* browser_view_layout = GetBrowserViewLayout();
433   if (browser_view_layout)
434     browser_view_layout->set_download_shelf(NULL);
435   download_shelf_.reset();
436
437   // The TabStrip attaches a listener to the model. Make sure we shut down the
438   // TabStrip first so that it can cleanly remove the listener.
439   if (tabstrip_) {
440     tabstrip_->parent()->RemoveChildView(tabstrip_);
441     if (browser_view_layout)
442       browser_view_layout->set_tab_strip(NULL);
443     delete tabstrip_;
444     tabstrip_ = NULL;
445   }
446   // Child views maintain PrefMember attributes that point to
447   // OffTheRecordProfile's PrefService which gets deleted by ~Browser.
448   RemoveAllChildViews(true);
449   toolbar_ = NULL;
450
451   // Explicitly set browser_ to NULL.
452   browser_.reset();
453 }
454
455 void BrowserView::Init(Browser* browser) {
456   browser_.reset(browser);
457   browser_->tab_strip_model()->AddObserver(this);
458   immersive_mode_controller_.reset(
459       chrome::CreateImmersiveModeController(browser_->host_desktop_type()));
460 }
461
462 // static
463 BrowserView* BrowserView::GetBrowserViewForNativeWindow(
464     gfx::NativeWindow window) {
465   views::Widget* widget = views::Widget::GetWidgetForNativeWindow(window);
466   return widget ?
467       reinterpret_cast<BrowserView*>(widget->GetNativeWindowProperty(
468           kBrowserViewKey)) : NULL;
469 }
470
471 // static
472 BrowserView* BrowserView::GetBrowserViewForBrowser(const Browser* browser) {
473   return static_cast<BrowserView*>(browser->window());
474 }
475
476 void BrowserView::InitStatusBubble() {
477   status_bubble_.reset(new StatusBubbleViews(contents_web_view_));
478   contents_web_view_->SetStatusBubble(status_bubble_.get());
479 }
480
481 void BrowserView::InitPermissionBubbleView() {
482   permission_bubble_view_.reset(new PermissionBubbleViewViews(
483       GetLocationBarView()->location_icon_view()));
484 }
485
486 gfx::Rect BrowserView::GetToolbarBounds() const {
487   gfx::Rect toolbar_bounds(toolbar_->bounds());
488   if (toolbar_bounds.IsEmpty())
489     return toolbar_bounds;
490   // The apparent toolbar edges are outside the "real" toolbar edges.
491   toolbar_bounds.Inset(-views::NonClientFrameView::kClientEdgeThickness, 0);
492   return toolbar_bounds;
493 }
494
495 gfx::Rect BrowserView::GetFindBarBoundingBox() const {
496   return GetBrowserViewLayout()->GetFindBarBoundingBox();
497 }
498
499 int BrowserView::GetTabStripHeight() const {
500   // We want to return tabstrip_->height(), but we might be called in the midst
501   // of layout, when that hasn't yet been updated to reflect the current state.
502   // So return what the tabstrip height _ought_ to be right now.
503   return IsTabStripVisible() ? tabstrip_->GetPreferredSize().height() : 0;
504 }
505
506 gfx::Point BrowserView::OffsetPointForToolbarBackgroundImage(
507     const gfx::Point& point) const {
508   // The background image starts tiling horizontally at the window left edge and
509   // vertically at the top edge of the horizontal tab strip (or where it would
510   // be).  We expect our parent's origin to be the window origin.
511   gfx::Point window_point(point + GetMirroredPosition().OffsetFromOrigin());
512   window_point.Offset(frame_->GetThemeBackgroundXInset(),
513                       -frame_->GetTopInset());
514   return window_point;
515 }
516
517 bool BrowserView::IsTabStripVisible() const {
518   if (immersive_mode_controller_->ShouldHideTopViews() &&
519       immersive_mode_controller_->ShouldHideTabIndicators())
520     return false;
521   return browser_->SupportsWindowFeature(Browser::FEATURE_TABSTRIP);
522 }
523
524 bool BrowserView::IsOffTheRecord() const {
525   return browser_->profile()->IsOffTheRecord();
526 }
527
528 bool BrowserView::IsGuestSession() const {
529   return browser_->profile()->IsGuestSession();
530 }
531
532 bool BrowserView::IsRegularOrGuestSession() const {
533   return profiles::IsRegularOrGuestSession(browser_.get());
534 }
535
536 bool BrowserView::ShouldShowAvatar() const {
537 #if defined(OS_CHROMEOS)
538   if (!browser_->is_type_tabbed() && !browser_->is_app())
539     return false;
540   // Don't show incognito avatar in the guest session.
541   if (IsOffTheRecord() && !IsGuestSession())
542     return true;
543   // This function is called via BrowserNonClientFrameView::UpdateAvatarInfo
544   // during the creation of the BrowserWindow, so browser->window() will not
545   // yet be set. In this case we can safely return false.
546   if (!browser_->window())
547     return false;
548   return chrome::MultiUserWindowManager::ShouldShowAvatar(
549       browser_->window()->GetNativeWindow());
550 #else
551   if (!IsBrowserTypeNormal())
552     return false;
553   if (IsOffTheRecord())  // Desktop guest is incognito and needs avatar.
554     return true;
555   // Tests may not have a profile manager.
556   if (!g_browser_process->profile_manager())
557     return false;
558   ProfileInfoCache& cache =
559       g_browser_process->profile_manager()->GetProfileInfoCache();
560   if (cache.GetIndexOfProfileWithPath(browser_->profile()->GetPath()) ==
561       std::string::npos) {
562     return false;
563   }
564
565   return AvatarMenu::ShouldShowAvatarMenu();
566 #endif
567 }
568
569 bool BrowserView::GetAccelerator(int cmd_id,
570                                  ui::Accelerator* accelerator) const {
571   // We retrieve the accelerator information for standard accelerators
572   // for cut, copy and paste.
573   if (chrome::GetStandardAcceleratorForCommandId(cmd_id, accelerator))
574     return true;
575   // Else, we retrieve the accelerator information from the accelerator table.
576   for (std::map<ui::Accelerator, int>::const_iterator it =
577            accelerator_table_.begin(); it != accelerator_table_.end(); ++it) {
578     if (it->second == cmd_id) {
579       *accelerator = it->first;
580       return true;
581     }
582   }
583   // Else, we retrieve the accelerator information from Ash (if applicable).
584   return chrome::GetAshAcceleratorForCommandId(
585       cmd_id, browser_->host_desktop_type(), accelerator);
586 }
587
588 bool BrowserView::IsAcceleratorRegistered(const ui::Accelerator& accelerator) {
589   return accelerator_table_.find(accelerator) != accelerator_table_.end();
590 }
591
592 WebContents* BrowserView::GetActiveWebContents() const {
593   return browser_->tab_strip_model()->GetActiveWebContents();
594 }
595
596 gfx::ImageSkia BrowserView::GetOTRAvatarIcon() const {
597   return *GetThemeProvider()->GetImageSkiaNamed(IDR_OTR_ICON);
598 }
599
600 ///////////////////////////////////////////////////////////////////////////////
601 // BrowserView, BrowserWindow implementation:
602
603 void BrowserView::Show() {
604   // If the window is already visible, just activate it.
605   if (frame_->IsVisible()) {
606     frame_->Activate();
607     return;
608   }
609
610   // Showing the window doesn't make the browser window active right away.
611   // This can cause SetFocusToLocationBar() to skip setting focus to the
612   // location bar. To avoid this we explicilty let SetFocusToLocationBar()
613   // know that it's ok to steal focus.
614   force_location_bar_focus_ = true;
615
616   // Setting the focus doesn't work when the window is invisible, so any focus
617   // initialization that happened before this will be lost.
618   //
619   // We really "should" restore the focus whenever the window becomes unhidden,
620   // but I think initializing is the only time where this can happen where
621   // there is some focus change we need to pick up, and this is easier than
622   // plumbing through an un-hide message all the way from the frame.
623   //
624   // If we do find there are cases where we need to restore the focus on show,
625   // that should be added and this should be removed.
626   RestoreFocus();
627
628   frame_->Show();
629
630   force_location_bar_focus_ = false;
631
632   browser()->OnWindowDidShow();
633
634   chrome::MaybeShowInvertBubbleView(this);
635 }
636
637 void BrowserView::ShowInactive() {
638   if (!frame_->IsVisible())
639     frame_->ShowInactive();
640 }
641
642 void BrowserView::Hide() {
643   // Not implemented.
644 }
645
646 void BrowserView::SetBounds(const gfx::Rect& bounds) {
647   ExitFullscreen();
648   GetWidget()->SetBounds(bounds);
649 }
650
651 void BrowserView::Close() {
652   frame_->Close();
653 }
654
655 void BrowserView::Activate() {
656   frame_->Activate();
657 }
658
659 void BrowserView::Deactivate() {
660   frame_->Deactivate();
661 }
662
663 bool BrowserView::IsActive() const {
664   return frame_->IsActive();
665 }
666
667 void BrowserView::FlashFrame(bool flash) {
668   frame_->FlashFrame(flash);
669 }
670
671 bool BrowserView::IsAlwaysOnTop() const {
672   return false;
673 }
674
675 void BrowserView::SetAlwaysOnTop(bool always_on_top) {
676   // Not implemented for browser windows.
677   NOTIMPLEMENTED();
678 }
679
680 gfx::NativeWindow BrowserView::GetNativeWindow() const {
681   // While the browser destruction is going on, the widget can already be gone,
682   // but utility functions like FindBrowserWithWindow will come here and crash.
683   // We short circuit therefore.
684   if (!GetWidget())
685     return NULL;
686   return GetWidget()->GetTopLevelWidget()->GetNativeWindow();
687 }
688
689 BrowserWindowTesting* BrowserView::GetBrowserWindowTesting() {
690   return this;
691 }
692
693 StatusBubble* BrowserView::GetStatusBubble() {
694   return status_bubble_.get();
695 }
696
697 namespace {
698   // Only used by ToolbarSizeChanged() below, but placed here because template
699   // arguments (to base::AutoReset<>) must have external linkage.
700   enum CallState { NORMAL, REENTRANT, REENTRANT_FORCE_FAST_RESIZE };
701 }
702
703 void BrowserView::UpdateTitleBar() {
704   frame_->UpdateWindowTitle();
705   if (ShouldShowWindowIcon() && !loading_animation_timer_.IsRunning())
706     frame_->UpdateWindowIcon();
707 }
708
709 void BrowserView::BookmarkBarStateChanged(
710     BookmarkBar::AnimateChangeType change_type) {
711   if (bookmark_bar_view_.get()) {
712     BookmarkBar::State new_state = browser_->bookmark_bar_state();
713
714     // We don't properly support animating the bookmark bar to and from the
715     // detached state in immersive fullscreen.
716     bool detached_changed = (new_state == BookmarkBar::DETACHED) ||
717         bookmark_bar_view_->IsDetached();
718     if (detached_changed && immersive_mode_controller_->IsEnabled())
719       change_type = BookmarkBar::DONT_ANIMATE_STATE_CHANGE;
720
721     bookmark_bar_view_->SetBookmarkBarState(new_state, change_type);
722   }
723   if (MaybeShowBookmarkBar(GetActiveWebContents()))
724     Layout();
725 }
726
727 void BrowserView::UpdateDevTools() {
728   UpdateDevToolsForContents(GetActiveWebContents(), true);
729   Layout();
730 }
731
732 void BrowserView::UpdateLoadingAnimations(bool should_animate) {
733   if (should_animate) {
734     if (!loading_animation_timer_.IsRunning()) {
735       // Loads are happening, and the timer isn't running, so start it.
736       last_animation_time_ = base::TimeTicks::Now();
737       loading_animation_timer_.Start(FROM_HERE,
738           TimeDelta::FromMilliseconds(kLoadingAnimationFrameTimeMs), this,
739           &BrowserView::LoadingAnimationCallback);
740     }
741   } else {
742     if (loading_animation_timer_.IsRunning()) {
743       last_animation_time_ = base::TimeTicks();
744       loading_animation_timer_.Stop();
745       // Loads are now complete, update the state if a task was scheduled.
746       LoadingAnimationCallback();
747     }
748   }
749 }
750
751 void BrowserView::SetStarredState(bool is_starred) {
752   GetLocationBarView()->SetStarToggled(is_starred);
753 }
754
755 void BrowserView::SetTranslateIconToggled(bool is_lit) {
756   GetLocationBarView()->SetTranslateIconToggled(is_lit);
757 }
758
759 void BrowserView::OnActiveTabChanged(content::WebContents* old_contents,
760                                      content::WebContents* new_contents,
761                                      int index,
762                                      int reason) {
763   DCHECK(new_contents);
764
765   // If |contents_container_| already has the correct WebContents, we can save
766   // some work.  This also prevents extra events from being reported by the
767   // Visibility API under Windows, as ChangeWebContents will briefly hide
768   // the WebContents window.
769   bool change_tab_contents =
770       contents_web_view_->web_contents() != new_contents;
771
772   // Update various elements that are interested in knowing the current
773   // WebContents.
774
775   // When we toggle the NTP floating bookmarks bar and/or the info bar,
776   // we don't want any WebContents to be attached, so that we
777   // avoid an unnecessary resize and re-layout of a WebContents.
778   if (change_tab_contents) {
779     contents_web_view_->SetWebContents(NULL);
780     devtools_web_view_->SetWebContents(NULL);
781   }
782
783   // Do this before updating InfoBarContainer as the InfoBarContainer may
784   // callback to us and trigger layout.
785   if (bookmark_bar_view_.get()) {
786     bookmark_bar_view_->SetBookmarkBarState(
787         browser_->bookmark_bar_state(),
788         BookmarkBar::DONT_ANIMATE_STATE_CHANGE);
789   }
790
791   infobar_container_->ChangeInfoBarManager(
792       InfoBarService::FromWebContents(new_contents));
793
794   if (old_contents && PermissionBubbleManager::FromWebContents(old_contents))
795     PermissionBubbleManager::FromWebContents(old_contents)->SetView(NULL);
796
797   if (new_contents && PermissionBubbleManager::FromWebContents(new_contents)) {
798     PermissionBubbleManager::FromWebContents(new_contents)->SetView(
799         permission_bubble_view_.get());
800   }
801
802   UpdateUIForContents(new_contents);
803
804   // Layout for DevTools _before_ setting the both main and devtools WebContents
805   // to avoid toggling the size of any of them.
806   UpdateDevToolsForContents(new_contents, !change_tab_contents);
807
808   if (change_tab_contents) {
809     web_contents_close_handler_->ActiveTabChanged();
810     contents_web_view_->SetWebContents(new_contents);
811     // The second layout update should be no-op. It will just set the
812     // DevTools WebContents.
813     UpdateDevToolsForContents(new_contents, true);
814   }
815
816   if (!browser_->tab_strip_model()->closing_all() && GetWidget()->IsActive() &&
817       GetWidget()->IsVisible()) {
818     // We only restore focus if our window is visible, to avoid invoking blur
819     // handlers when we are eventually shown.
820     new_contents->RestoreFocus();
821   }
822
823   // Update all the UI bits.
824   UpdateTitleBar();
825
826   TranslateBubbleView::CloseBubble();
827   ZoomBubbleView::CloseBubble();
828 }
829
830 void BrowserView::ZoomChangedForActiveTab(bool can_show_bubble) {
831   GetLocationBarView()->ZoomChangedForActiveTab(
832       can_show_bubble && !toolbar_->IsWrenchMenuShowing());
833 }
834
835 gfx::Rect BrowserView::GetRestoredBounds() const {
836   gfx::Rect bounds;
837   ui::WindowShowState state;
838   frame_->GetWindowPlacement(&bounds, &state);
839   return bounds;
840 }
841
842 ui::WindowShowState BrowserView::GetRestoredState() const {
843   gfx::Rect bounds;
844   ui::WindowShowState state;
845   frame_->GetWindowPlacement(&bounds, &state);
846   return state;
847 }
848
849 gfx::Rect BrowserView::GetBounds() const {
850   return frame_->GetWindowBoundsInScreen();
851 }
852
853 bool BrowserView::IsMaximized() const {
854   return frame_->IsMaximized();
855 }
856
857 bool BrowserView::IsMinimized() const {
858   return frame_->IsMinimized();
859 }
860
861 void BrowserView::Maximize() {
862   frame_->Maximize();
863 }
864
865 void BrowserView::Minimize() {
866   frame_->Minimize();
867 }
868
869 void BrowserView::Restore() {
870   frame_->Restore();
871 }
872
873 void BrowserView::EnterFullscreen(
874     const GURL& url, FullscreenExitBubbleType bubble_type) {
875   if (IsFullscreen())
876     return;  // Nothing to do.
877
878   ProcessFullscreen(true, NORMAL_FULLSCREEN, url, bubble_type);
879 }
880
881 void BrowserView::ExitFullscreen() {
882   if (!IsFullscreen())
883     return;  // Nothing to do.
884
885   ProcessFullscreen(false, NORMAL_FULLSCREEN, GURL(), FEB_TYPE_NONE);
886 }
887
888 void BrowserView::UpdateFullscreenExitBubbleContent(
889     const GURL& url,
890     FullscreenExitBubbleType bubble_type) {
891   // Immersive mode has no exit bubble because it has a visible strip at the
892   // top that gives the user a hover target.
893   // TODO(jamescook): Figure out what to do with mouse-lock.
894   if (bubble_type == FEB_TYPE_NONE || ShouldUseImmersiveFullscreenForUrl(url)) {
895     fullscreen_bubble_.reset();
896   } else if (fullscreen_bubble_.get()) {
897     fullscreen_bubble_->UpdateContent(url, bubble_type);
898   } else {
899     fullscreen_bubble_.reset(new FullscreenExitBubbleViews(
900         this, url, bubble_type));
901   }
902 }
903
904 bool BrowserView::ShouldHideUIForFullscreen() const {
905   // Immersive mode needs UI for the slide-down top panel.
906   if (immersive_mode_controller_->IsEnabled())
907     return false;
908
909   return IsFullscreen();
910 }
911
912 bool BrowserView::IsFullscreen() const {
913   return frame_->IsFullscreen();
914 }
915
916 bool BrowserView::IsFullscreenBubbleVisible() const {
917   return fullscreen_bubble_ != NULL;
918 }
919
920 #if defined(OS_WIN)
921 void BrowserView::SetMetroSnapMode(bool enable) {
922   LOCAL_HISTOGRAM_COUNTS("Metro.SnapModeToggle", enable);
923   ProcessFullscreen(enable, METRO_SNAP_FULLSCREEN, GURL(), FEB_TYPE_NONE);
924 }
925
926 bool BrowserView::IsInMetroSnapMode() const {
927   return false;
928 }
929 #endif  // defined(OS_WIN)
930
931 void BrowserView::RestoreFocus() {
932   WebContents* selected_web_contents = GetActiveWebContents();
933   if (selected_web_contents)
934     selected_web_contents->RestoreFocus();
935 }
936
937 void BrowserView::FullscreenStateChanged() {
938   CHECK(!IsFullscreen());
939   ProcessFullscreen(false, NORMAL_FULLSCREEN, GURL(), FEB_TYPE_NONE);
940 }
941
942 void BrowserView::ToolbarSizeChanged(bool is_animating) {
943   // The call to InfoBarContainer::SetMaxTopArrowHeight() below can result in
944   // reentrancy; |call_state| tracks whether we're reentrant.  We can't just
945   // early-return in this case because we need to layout again so the infobar
946   // container's bounds are set correctly.
947   static CallState call_state = NORMAL;
948
949   // A reentrant call can (and should) use the fast resize path unless both it
950   // and the normal call are both non-animating.
951   bool use_fast_resize =
952       is_animating || (call_state == REENTRANT_FORCE_FAST_RESIZE);
953   if (use_fast_resize)
954     contents_web_view_->SetFastResize(true);
955   UpdateUIForContents(GetActiveWebContents());
956   if (use_fast_resize)
957     contents_web_view_->SetFastResize(false);
958
959   // Inform the InfoBarContainer that the distance to the location icon may have
960   // changed.  We have to do this after the block above so that the toolbars are
961   // laid out correctly for calculating the maximum arrow height below.
962   {
963     base::AutoReset<CallState> resetter(&call_state,
964         is_animating ? REENTRANT_FORCE_FAST_RESIZE : REENTRANT);
965     infobar_container_->SetMaxTopArrowHeight(GetMaxTopInfoBarArrowHeight());
966   }
967
968   // When transitioning from animating to not animating we need to make sure the
969   // contents_container_ gets layed out. If we don't do this and the bounds
970   // haven't changed contents_container_ won't get a Layout out and we'll end up
971   // with a gray rect because the clip wasn't updated.  Note that a reentrant
972   // call never needs to do this, because after it returns, the normal call
973   // wrapping it will do it.
974   if ((call_state == NORMAL) && !is_animating) {
975     contents_web_view_->InvalidateLayout();
976     contents_container_->Layout();
977   }
978 }
979
980 LocationBar* BrowserView::GetLocationBar() const {
981   return GetLocationBarView();
982 }
983
984 void BrowserView::SetFocusToLocationBar(bool select_all) {
985   // On Windows, changing focus to the location bar causes the browser
986   // window to become active. This can steal focus if the user has
987   // another window open already. On ChromeOS, changing focus makes a
988   // view believe it has a focus even if the widget doens't have a
989   // focus. Either cases, we need to ignore this when the browser
990   // window isn't active.
991   if (!force_location_bar_focus_ && !IsActive())
992     return;
993
994   // Temporarily reveal the top-of-window views (if not already revealed) so
995   // that the location bar view is visible and is considered focusable. If the
996   // location bar view gains focus, |immersive_mode_controller_| will keep the
997   // top-of-window views revealed.
998   scoped_ptr<ImmersiveRevealedLock> focus_reveal_lock(
999       immersive_mode_controller_->GetRevealedLock(
1000           ImmersiveModeController::ANIMATE_REVEAL_YES));
1001
1002   LocationBarView* location_bar = GetLocationBarView();
1003   if (location_bar->omnibox_view()->IsFocusable()) {
1004     // Location bar got focus.
1005     //
1006     // select_all is true when it's expected that the user may want to copy
1007     // the URL to the clipboard. If the URL is not being shown because the
1008     // origin chip is enabled, show it now to support the same functionality.
1009     if (select_all &&
1010         location_bar->GetToolbarModel()->WouldOmitURLDueToOriginChip())
1011       location_bar->ShowURL();
1012     else
1013       location_bar->FocusLocation(select_all);
1014   } else {
1015     // If none of location bar got focus, then clear focus.
1016     views::FocusManager* focus_manager = GetFocusManager();
1017     DCHECK(focus_manager);
1018     focus_manager->ClearFocus();
1019   }
1020 }
1021
1022 void BrowserView::UpdateReloadStopState(bool is_loading, bool force) {
1023   toolbar_->reload_button()->ChangeMode(
1024       is_loading ? ReloadButton::MODE_STOP : ReloadButton::MODE_RELOAD, force);
1025 }
1026
1027 void BrowserView::UpdateToolbar(content::WebContents* contents) {
1028   // We may end up here during destruction.
1029   if (toolbar_)
1030     toolbar_->Update(contents);
1031 }
1032
1033 void BrowserView::FocusToolbar() {
1034   // Temporarily reveal the top-of-window views (if not already revealed) so
1035   // that the toolbar is visible and is considered focusable. If the
1036   // toolbar gains focus, |immersive_mode_controller_| will keep the
1037   // top-of-window views revealed.
1038   scoped_ptr<ImmersiveRevealedLock> focus_reveal_lock(
1039       immersive_mode_controller_->GetRevealedLock(
1040           ImmersiveModeController::ANIMATE_REVEAL_YES));
1041
1042   // Start the traversal within the main toolbar. SetPaneFocus stores
1043   // the current focused view before changing focus.
1044   toolbar_->SetPaneFocus(NULL);
1045 }
1046
1047 void BrowserView::FocusBookmarksToolbar() {
1048   DCHECK(!immersive_mode_controller_->IsEnabled());
1049   if (bookmark_bar_view_.get() &&
1050       bookmark_bar_view_->visible() &&
1051       bookmark_bar_view_->GetPreferredSize().height() != 0) {
1052     bookmark_bar_view_->SetPaneFocusAndFocusDefault();
1053   }
1054 }
1055
1056 void BrowserView::FocusInfobars() {
1057   if (infobar_container_->child_count() > 0)
1058     infobar_container_->SetPaneFocusAndFocusDefault();
1059 }
1060
1061 void BrowserView::FocusAppMenu() {
1062   // Chrome doesn't have a traditional menu bar, but it has a menu button in the
1063   // main toolbar that plays the same role.  If the user presses a key that
1064   // would typically focus the menu bar, tell the toolbar to focus the menu
1065   // button.  If the user presses the key again, return focus to the previous
1066   // location.
1067   //
1068   // Not used on the Mac, which has a normal menu bar.
1069   if (toolbar_->IsAppMenuFocused()) {
1070     RestoreFocus();
1071   } else {
1072     DCHECK(!immersive_mode_controller_->IsEnabled());
1073     toolbar_->SetPaneFocusAndFocusAppMenu();
1074   }
1075 }
1076
1077 void BrowserView::RotatePaneFocus(bool forwards) {
1078   GetWidget()->GetFocusManager()->RotatePaneFocus(
1079       forwards ?
1080           views::FocusManager::kForward : views::FocusManager::kBackward,
1081       views::FocusManager::kWrap);
1082 }
1083
1084 void BrowserView::DestroyBrowser() {
1085   // After this returns other parts of Chrome are going to be shutdown. Close
1086   // the window now so that we are deleted immediately and aren't left holding
1087   // references to deleted objects.
1088   GetWidget()->RemoveObserver(this);
1089   GetLocationBar()->GetOmniboxView()->model()->popup_model()->RemoveObserver(
1090       this);
1091   frame_->CloseNow();
1092 }
1093
1094 bool BrowserView::IsBookmarkBarVisible() const {
1095   if (!browser_->SupportsWindowFeature(Browser::FEATURE_BOOKMARKBAR))
1096     return false;
1097   if (!bookmark_bar_view_.get())
1098     return false;
1099   if (bookmark_bar_view_->GetPreferredSize().height() == 0)
1100     return false;
1101   // New tab page needs visible bookmarks even when top-views are hidden.
1102   if (immersive_mode_controller_->ShouldHideTopViews() &&
1103       !bookmark_bar_view_->IsDetached())
1104     return false;
1105   return true;
1106 }
1107
1108 bool BrowserView::IsBookmarkBarAnimating() const {
1109   return bookmark_bar_view_.get() && bookmark_bar_view_->is_animating();
1110 }
1111
1112 bool BrowserView::IsTabStripEditable() const {
1113   return tabstrip_->IsTabStripEditable();
1114 }
1115
1116 bool BrowserView::IsToolbarVisible() const {
1117   if (immersive_mode_controller_->ShouldHideTopViews())
1118     return false;
1119   return browser_->SupportsWindowFeature(Browser::FEATURE_TOOLBAR) ||
1120          browser_->SupportsWindowFeature(Browser::FEATURE_LOCATIONBAR);
1121 }
1122
1123 gfx::Rect BrowserView::GetRootWindowResizerRect() const {
1124   // Views does not support resizer rects because they caused page cycler
1125   // performance regressions when they were added. See crrev.com/9654
1126   return gfx::Rect();
1127 }
1128
1129 void BrowserView::ConfirmAddSearchProvider(TemplateURL* template_url,
1130                                            Profile* profile) {
1131   chrome::EditSearchEngine(GetWidget()->GetNativeWindow(), template_url, NULL,
1132                            profile);
1133 }
1134
1135 void BrowserView::ShowUpdateChromeDialog() {
1136   UpdateRecommendedMessageBox::Show(GetWidget()->GetNativeWindow());
1137 }
1138
1139 void BrowserView::ShowBookmarkBubble(const GURL& url, bool already_bookmarked) {
1140   scoped_ptr<BookmarkBubbleDelegate> delegate;
1141   delegate.reset(new BookmarkBubbleSignInDelegate(browser_.get()));
1142
1143   BookmarkBubbleView::ShowBubble(GetToolbarView()->GetBookmarkBubbleAnchor(),
1144                                  bookmark_bar_view_.get(),
1145                                  delegate.Pass(),
1146                                  browser_->profile(),
1147                                  url,
1148                                  !already_bookmarked);
1149 }
1150
1151 void BrowserView::ShowBookmarkAppBubble(
1152     const WebApplicationInfo& web_app_info,
1153     const std::string& extension_id) {
1154   BookmarkAppBubbleView::ShowBubble(GetToolbarView(),
1155                                     browser_->profile(),
1156                                     web_app_info,
1157                                     extension_id);
1158 }
1159
1160 void BrowserView::ShowTranslateBubble(
1161     content::WebContents* web_contents,
1162     translate::TranslateStep step,
1163     translate::TranslateErrors::Type error_type,
1164     bool is_user_gesture) {
1165   if (contents_web_view_->HasFocus() &&
1166       !GetLocationBarView()->IsMouseHovered()) {
1167     content::RenderViewHost* rvh = web_contents->GetRenderViewHost();
1168     if (rvh->IsFocusedElementEditable())
1169       return;
1170   }
1171
1172   ChromeTranslateClient* chrome_translate_client =
1173       ChromeTranslateClient::FromWebContents(web_contents);
1174   translate::LanguageState& language_state =
1175       chrome_translate_client->GetLanguageState();
1176   language_state.SetTranslateEnabled(true);
1177
1178   if (IsMinimized())
1179     return;
1180
1181   TranslateBubbleView::ShowBubble(
1182       GetToolbarView()->GetTranslateBubbleAnchor(), web_contents, step,
1183       error_type, is_user_gesture);
1184 }
1185
1186 #if defined(ENABLE_ONE_CLICK_SIGNIN)
1187 void BrowserView::ShowOneClickSigninBubble(
1188     OneClickSigninBubbleType type,
1189     const base::string16& email,
1190     const base::string16& error_message,
1191     const StartSyncCallback& start_sync_callback) {
1192   scoped_ptr<OneClickSigninBubbleDelegate> delegate;
1193   delegate.reset(new OneClickSigninBubbleLinksDelegate(browser()));
1194
1195   views::View* anchor_view;
1196   if (type == BrowserWindow::ONE_CLICK_SIGNIN_BUBBLE_TYPE_BUBBLE)
1197     anchor_view = toolbar_->app_menu();
1198   else
1199     anchor_view = toolbar_->location_bar();
1200
1201   OneClickSigninBubbleView::ShowBubble(type, email, error_message,
1202                                        delegate.Pass(), anchor_view,
1203                                        start_sync_callback);
1204 }
1205 #endif
1206
1207 void BrowserView::SetDownloadShelfVisible(bool visible) {
1208   // This can be called from the superclass destructor, when it destroys our
1209   // child views. At that point, browser_ is already gone.
1210   if (browser_ == NULL)
1211     return;
1212
1213   if (visible && IsDownloadShelfVisible() != visible) {
1214     // Invoke GetDownloadShelf to force the shelf to be created.
1215     GetDownloadShelf();
1216   }
1217
1218   if (browser_ != NULL)
1219     browser_->UpdateDownloadShelfVisibility(visible);
1220
1221   // SetDownloadShelfVisible can force-close the shelf, so make sure we lay out
1222   // everything correctly, as if the animation had finished. This doesn't
1223   // matter for showing the shelf, as the show animation will do it.
1224   ToolbarSizeChanged(false);
1225 }
1226
1227 bool BrowserView::IsDownloadShelfVisible() const {
1228   return download_shelf_.get() && download_shelf_->IsShowing();
1229 }
1230
1231 DownloadShelf* BrowserView::GetDownloadShelf() {
1232   if (!download_shelf_.get()) {
1233     download_shelf_.reset(new DownloadShelfView(browser_.get(), this));
1234     download_shelf_->set_owned_by_client();
1235     GetBrowserViewLayout()->set_download_shelf(download_shelf_.get());
1236   }
1237   return download_shelf_.get();
1238 }
1239
1240 void BrowserView::ConfirmBrowserCloseWithPendingDownloads(
1241     int download_count,
1242     Browser::DownloadClosePreventionType dialog_type,
1243     bool app_modal,
1244     const base::Callback<void(bool)>& callback) {
1245   DownloadInProgressDialogView::Show(
1246       GetNativeWindow(), download_count, dialog_type, app_modal, callback);
1247 }
1248
1249 void BrowserView::UserChangedTheme() {
1250   frame_->FrameTypeChanged();
1251 }
1252
1253 int BrowserView::GetExtraRenderViewHeight() const {
1254   // Currently this is only used on linux.
1255   return 0;
1256 }
1257
1258 void BrowserView::WebContentsFocused(WebContents* contents) {
1259   if (contents_web_view_->GetWebContents() == contents)
1260     contents_web_view_->OnWebContentsFocused(contents);
1261   else
1262     devtools_web_view_->OnWebContentsFocused(contents);
1263 }
1264
1265 void BrowserView::ShowWebsiteSettings(Profile* profile,
1266                                       content::WebContents* web_contents,
1267                                       const GURL& url,
1268                                       const content::SSLStatus& ssl) {
1269   WebsiteSettingsPopupView::ShowPopup(
1270       GetLocationBarView()->location_icon_view(), profile,
1271       web_contents, url, ssl, browser_.get());
1272 }
1273
1274 void BrowserView::ShowAppMenu() {
1275   // Keep the top-of-window views revealed as long as the app menu is visible.
1276   scoped_ptr<ImmersiveRevealedLock> revealed_lock(
1277       immersive_mode_controller_->GetRevealedLock(
1278           ImmersiveModeController::ANIMATE_REVEAL_NO));
1279
1280   toolbar_->app_menu()->Activate();
1281 }
1282
1283 bool BrowserView::PreHandleKeyboardEvent(const NativeWebKeyboardEvent& event,
1284                                          bool* is_keyboard_shortcut) {
1285   *is_keyboard_shortcut = false;
1286
1287   if ((event.type != blink::WebInputEvent::RawKeyDown) &&
1288       (event.type != blink::WebInputEvent::KeyUp)) {
1289     return false;
1290   }
1291
1292   views::FocusManager* focus_manager = GetFocusManager();
1293   DCHECK(focus_manager);
1294
1295   if (focus_manager->shortcut_handling_suspended())
1296     return false;
1297
1298   ui::Accelerator accelerator(
1299       static_cast<ui::KeyboardCode>(event.windowsKeyCode),
1300       content::GetModifiersFromNativeWebKeyboardEvent(event));
1301   if (event.type == blink::WebInputEvent::KeyUp)
1302     accelerator.set_type(ui::ET_KEY_RELEASED);
1303
1304   // What we have to do here is as follows:
1305   // - If the |browser_| is for an app, do nothing.
1306   // - If the |browser_| is not for an app, and the |accelerator| is not
1307   //   associated with the browser (e.g. an Ash shortcut), process it.
1308   // - If the |browser_| is not for an app, and the |accelerator| is associated
1309   //   with the browser, and it is a reserved one (e.g. Ctrl+w), process it.
1310   // - If the |browser_| is not for an app, and the |accelerator| is associated
1311   //   with the browser, and it is not a reserved one, do nothing.
1312
1313   if (browser_->is_app()) {
1314     // Let all keys fall through to a v1 app's web content, even accelerators.
1315     // We don't have to flip |is_keyboard_shortcut| here. If we do that, the app
1316     // might not be able to see a subsequent Char event. See OnHandleInputEvent
1317     // in content/renderer/render_widget.cc for details.
1318     return false;
1319   }
1320
1321   chrome::BrowserCommandController* controller = browser_->command_controller();
1322
1323   // Here we need to retrieve the command id (if any) associated to the
1324   // keyboard event. Instead of looking up the command id in the
1325   // |accelerator_table_| by ourselves, we block the command execution of
1326   // the |browser_| object then send the keyboard event to the
1327   // |focus_manager| as if we are activating an accelerator key.
1328   // Then we can retrieve the command id from the |browser_| object.
1329   bool original_block_command_state = controller->block_command_execution();
1330   controller->SetBlockCommandExecution(true);
1331   // If the |accelerator| is a non-browser shortcut (e.g. Ash shortcut), the
1332   // command execution cannot be blocked and true is returned. However, it is
1333   // okay as long as is_app() is false. See comments in this function.
1334   const bool processed = focus_manager->ProcessAccelerator(accelerator);
1335   const int id = controller->GetLastBlockedCommand(NULL);
1336   controller->SetBlockCommandExecution(original_block_command_state);
1337
1338   // Executing the command may cause |this| object to be destroyed.
1339   if (controller->IsReservedCommandOrKey(id, event)) {
1340     UpdateAcceleratorMetrics(accelerator, id);
1341     return chrome::ExecuteCommand(browser_.get(), id);
1342   }
1343
1344   if (id != -1) {
1345     // |accelerator| is a non-reserved browser shortcut (e.g. Ctrl+f).
1346     if (event.type == blink::WebInputEvent::RawKeyDown)
1347       *is_keyboard_shortcut = true;
1348   } else if (processed) {
1349     // |accelerator| is a non-browser shortcut (e.g. F4-F10 on Ash). Report
1350     // that we handled it.
1351     return true;
1352   }
1353
1354   return false;
1355 }
1356
1357 void BrowserView::HandleKeyboardEvent(const NativeWebKeyboardEvent& event) {
1358   unhandled_keyboard_event_handler_.HandleKeyboardEvent(event,
1359                                                         GetFocusManager());
1360 }
1361
1362 // TODO(devint): http://b/issue?id=1117225 Cut, Copy, and Paste are always
1363 // enabled in the page menu regardless of whether the command will do
1364 // anything. When someone selects the menu item, we just act as if they hit
1365 // the keyboard shortcut for the command by sending the associated key press
1366 // to windows. The real fix to this bug is to disable the commands when they
1367 // won't do anything. We'll need something like an overall clipboard command
1368 // manager to do that.
1369 void BrowserView::Cut() {
1370   // If a WebContent is focused, call WebContents::Cut. Otherwise, e.g. if
1371   // Omnibox is focused, send a Ctrl+x key event to Chrome. Using RWH interface
1372   // rather than the fake key event for a WebContent is important since the fake
1373   // event might be consumed by the web content (crbug.com/137908).
1374   DoCutCopyPaste(&content::WebContents::Cut, IDS_APP_CUT);
1375 }
1376
1377 void BrowserView::Copy() {
1378   DoCutCopyPaste(&content::WebContents::Copy, IDS_APP_COPY);
1379 }
1380
1381 void BrowserView::Paste() {
1382   DoCutCopyPaste(&content::WebContents::Paste, IDS_APP_PASTE);
1383 }
1384
1385 WindowOpenDisposition BrowserView::GetDispositionForPopupBounds(
1386     const gfx::Rect& bounds) {
1387   return NEW_POPUP;
1388 }
1389
1390 FindBar* BrowserView::CreateFindBar() {
1391   return chrome::CreateFindBar(this);
1392 }
1393
1394 WebContentsModalDialogHost* BrowserView::GetWebContentsModalDialogHost() {
1395   return GetBrowserViewLayout()->GetWebContentsModalDialogHost();
1396 }
1397
1398 ///////////////////////////////////////////////////////////////////////////////
1399 // BrowserView, BrowserWindowTesting implementation:
1400
1401 BookmarkBarView* BrowserView::GetBookmarkBarView() const {
1402   return bookmark_bar_view_.get();
1403 }
1404
1405 LocationBarView* BrowserView::GetLocationBarView() const {
1406   return toolbar_ ? toolbar_->location_bar() : NULL;
1407 }
1408
1409 views::View* BrowserView::GetTabContentsContainerView() const {
1410   return contents_web_view_;
1411 }
1412
1413 ToolbarView* BrowserView::GetToolbarView() const {
1414   return toolbar_;
1415 }
1416
1417 ///////////////////////////////////////////////////////////////////////////////
1418 // BrowserView, TabStripModelObserver implementation:
1419
1420 void BrowserView::TabInsertedAt(WebContents* contents,
1421                                 int index,
1422                                 bool foreground) {
1423   // WebContents inserted in tabs might not have been added to the root
1424   // window yet. Per http://crbug/342672 add them now since drawing the
1425   // WebContents requires root window specific data - information about
1426   // the screen the WebContents is drawn on, for example.
1427   if (!contents->GetNativeView()->GetRootWindow()) {
1428     aura::Window* window = contents->GetNativeView();
1429     aura::Window* root_window = GetNativeWindow()->GetRootWindow();
1430     aura::client::ParentWindowWithContext(
1431         window, root_window, root_window->GetBoundsInScreen());
1432     DCHECK(contents->GetNativeView()->GetRootWindow());
1433   }
1434   web_contents_close_handler_->TabInserted();
1435
1436   if (foreground)
1437     extensions::MaybeShowExtensionControlledNewTabPage(browser(), contents);
1438 }
1439
1440 void BrowserView::TabDetachedAt(WebContents* contents, int index) {
1441   if (PermissionBubbleManager::FromWebContents(contents))
1442     PermissionBubbleManager::FromWebContents(contents)->SetView(NULL);
1443
1444   // We use index here rather than comparing |contents| because by this time
1445   // the model has already removed |contents| from its list, so
1446   // browser_->GetActiveWebContents() will return NULL or something else.
1447   if (index == browser_->tab_strip_model()->active_index()) {
1448     // We need to reset the current tab contents to NULL before it gets
1449     // freed. This is because the focus manager performs some operations
1450     // on the selected WebContents when it is removed.
1451     web_contents_close_handler_->ActiveTabChanged();
1452     contents_web_view_->SetWebContents(NULL);
1453     infobar_container_->ChangeInfoBarManager(NULL);
1454     UpdateDevToolsForContents(NULL, true);
1455   }
1456 }
1457
1458 void BrowserView::TabDeactivated(WebContents* contents) {
1459   if (PermissionBubbleManager::FromWebContents(contents))
1460     PermissionBubbleManager::FromWebContents(contents)->SetView(NULL);
1461
1462   // We do not store the focus when closing the tab to work-around bug 4633.
1463   // Some reports seem to show that the focus manager and/or focused view can
1464   // be garbage at that point, it is not clear why.
1465   if (!contents->IsBeingDestroyed())
1466     contents->StoreFocus();
1467 }
1468
1469 void BrowserView::TabStripEmpty() {
1470   // Make sure all optional UI is removed before we are destroyed, otherwise
1471   // there will be consequences (since our view hierarchy will still have
1472   // references to freed views).
1473   UpdateUIForContents(NULL);
1474 }
1475
1476 void BrowserView::WillCloseAllTabs() {
1477   web_contents_close_handler_->WillCloseAllTabs();
1478 }
1479
1480 void BrowserView::CloseAllTabsCanceled() {
1481   web_contents_close_handler_->CloseAllTabsCanceled();
1482 }
1483
1484 ///////////////////////////////////////////////////////////////////////////////
1485 // BrowserView, ui::AcceleratorProvider implementation:
1486
1487 bool BrowserView::GetAcceleratorForCommandId(int command_id,
1488                                              ui::Accelerator* accelerator) {
1489   // Let's let the ToolbarView own the canonical implementation of this method.
1490   return toolbar_->GetAcceleratorForCommandId(command_id, accelerator);
1491 }
1492
1493 ///////////////////////////////////////////////////////////////////////////////
1494 // BrowserView, views::WidgetDelegate implementation:
1495
1496 bool BrowserView::CanResize() const {
1497   return true;
1498 }
1499
1500 bool BrowserView::CanMaximize() const {
1501   return true;
1502 }
1503
1504 bool BrowserView::CanMinimize() const {
1505   return true;
1506 }
1507
1508 bool BrowserView::CanActivate() const {
1509   if (!AppModalDialogQueue::GetInstance()->active_dialog() ||
1510       !AppModalDialogQueue::GetInstance()->active_dialog()->native_dialog())
1511     return true;
1512
1513 #if defined(USE_AURA) && defined(OS_CHROMEOS)
1514   // On Aura window manager controls all windows so settings focus via PostTask
1515   // will make only worse because posted task will keep trying to steal focus.
1516   AppModalDialogQueue::GetInstance()->ActivateModalDialog();
1517 #else
1518   // If another browser is app modal, flash and activate the modal browser. This
1519   // has to be done in a post task, otherwise if the user clicked on a window
1520   // that doesn't have the modal dialog the windows keep trying to get the focus
1521   // from each other on Windows. http://crbug.com/141650.
1522   base::MessageLoop::current()->PostTask(
1523       FROM_HERE,
1524       base::Bind(&BrowserView::ActivateAppModalDialog,
1525                  activate_modal_dialog_factory_.GetWeakPtr()));
1526 #endif
1527   return false;
1528 }
1529
1530 base::string16 BrowserView::GetWindowTitle() const {
1531   return browser_->GetWindowTitleForCurrentTab();
1532 }
1533
1534 base::string16 BrowserView::GetAccessibleWindowTitle() const {
1535   if (IsOffTheRecord()) {
1536     return l10n_util::GetStringFUTF16(
1537         IDS_ACCESSIBLE_INCOGNITO_WINDOW_TITLE_FORMAT,
1538         GetWindowTitle());
1539   }
1540   return GetWindowTitle();
1541 }
1542
1543 views::View* BrowserView::GetInitiallyFocusedView() {
1544   return NULL;
1545 }
1546
1547 bool BrowserView::ShouldShowWindowTitle() const {
1548   // For Ash only, trusted windows (apps and settings) do not show an icon,
1549   // crbug.com/119411. Child windows (i.e. popups) do show an icon.
1550   if (browser_->host_desktop_type() == chrome::HOST_DESKTOP_TYPE_ASH &&
1551       browser_->is_trusted_source() &&
1552       !(browser_->is_app() &&
1553         extensions::util::IsStreamlinedHostedAppsEnabled()))
1554     return false;
1555
1556   return browser_->SupportsWindowFeature(Browser::FEATURE_TITLEBAR);
1557 }
1558
1559 gfx::ImageSkia BrowserView::GetWindowAppIcon() {
1560   if (browser_->is_app()) {
1561     WebContents* contents = browser_->tab_strip_model()->GetActiveWebContents();
1562     extensions::TabHelper* extensions_tab_helper =
1563         contents ? extensions::TabHelper::FromWebContents(contents) : NULL;
1564     if (extensions_tab_helper && extensions_tab_helper->GetExtensionAppIcon())
1565       return gfx::ImageSkia::CreateFrom1xBitmap(
1566           *extensions_tab_helper->GetExtensionAppIcon());
1567   }
1568
1569   return GetWindowIcon();
1570 }
1571
1572 gfx::ImageSkia BrowserView::GetWindowIcon() {
1573   if (browser_->is_app() || browser_->is_type_popup())
1574     return browser_->GetCurrentPageIcon().AsImageSkia();
1575   return gfx::ImageSkia();
1576 }
1577
1578 bool BrowserView::ShouldShowWindowIcon() const {
1579   // For Ash only, trusted windows (apps and settings) do not show an icon,
1580   // crbug.com/119411. Child windows (i.e. popups) do show an icon.
1581   if (browser_->host_desktop_type() == chrome::HOST_DESKTOP_TYPE_ASH &&
1582       browser_->is_trusted_source() &&
1583       !(browser_->is_app() &&
1584         extensions::util::IsStreamlinedHostedAppsEnabled()))
1585     return false;
1586
1587   return browser_->SupportsWindowFeature(Browser::FEATURE_TITLEBAR);
1588 }
1589
1590 bool BrowserView::ExecuteWindowsCommand(int command_id) {
1591   // This function handles WM_SYSCOMMAND, WM_APPCOMMAND, and WM_COMMAND.
1592 #if defined(OS_WIN)
1593   if (command_id == IDC_DEBUG_FRAME_TOGGLE)
1594     GetWidget()->DebugToggleFrameType();
1595 #endif
1596   // Translate WM_APPCOMMAND command ids into a command id that the browser
1597   // knows how to handle.
1598   int command_id_from_app_command = GetCommandIDForAppCommandID(command_id);
1599   if (command_id_from_app_command != -1)
1600     command_id = command_id_from_app_command;
1601
1602   return chrome::ExecuteCommand(browser_.get(), command_id);
1603 }
1604
1605 std::string BrowserView::GetWindowName() const {
1606   return chrome::GetWindowName(browser_.get());
1607 }
1608
1609 void BrowserView::SaveWindowPlacement(const gfx::Rect& bounds,
1610                                       ui::WindowShowState show_state) {
1611   // If IsFullscreen() is true, we've just changed into fullscreen mode, and
1612   // we're catching the going-into-fullscreen sizing and positioning calls,
1613   // which we want to ignore.
1614   if (!IsFullscreen() && frame_->ShouldSaveWindowPlacement() &&
1615       chrome::ShouldSaveWindowPlacement(browser_.get())) {
1616     WidgetDelegate::SaveWindowPlacement(bounds, show_state);
1617     chrome::SaveWindowPlacement(browser_.get(), bounds, show_state);
1618   }
1619 }
1620
1621 bool BrowserView::GetSavedWindowPlacement(
1622     const views::Widget* widget,
1623     gfx::Rect* bounds,
1624     ui::WindowShowState* show_state) const {
1625   chrome::GetSavedWindowBoundsAndShowState(browser_.get(), bounds, show_state);
1626
1627   if (browser_->is_type_popup() &&
1628       !browser_->is_app() &&
1629       !browser_->is_trusted_source()) {
1630     // This is normal non-app popup window. The value passed in |bounds|
1631     // represents two pieces of information:
1632     // - the position of the window, in screen coordinates (outer position).
1633     // - the size of the content area (inner size).
1634     // We need to use these values to determine the appropriate size and
1635     // position of the resulting window.
1636     if (IsToolbarVisible()) {
1637       // If we're showing the toolbar, we need to adjust |*bounds| to include
1638       // its desired height, since the toolbar is considered part of the
1639       // window's client area as far as GetWindowBoundsForClientBounds is
1640       // concerned...
1641       bounds->set_height(
1642           bounds->height() + toolbar_->GetPreferredSize().height());
1643     }
1644
1645     gfx::Rect window_rect = frame_->non_client_view()->
1646         GetWindowBoundsForClientBounds(*bounds);
1647     window_rect.set_origin(bounds->origin());
1648
1649     // When we are given x/y coordinates of 0 on a created popup window,
1650     // assume none were given by the window.open() command.
1651     if (window_rect.x() == 0 && window_rect.y() == 0) {
1652       gfx::Size size = window_rect.size();
1653       window_rect.set_origin(
1654           WindowSizer::GetDefaultPopupOrigin(size,
1655                                              browser_->host_desktop_type()));
1656     }
1657
1658     *bounds = window_rect;
1659     *show_state = ui::SHOW_STATE_NORMAL;
1660   }
1661
1662   // We return true because we can _always_ locate reasonable bounds using the
1663   // WindowSizer, and we don't want to trigger the Window's built-in "size to
1664   // default" handling because the browser window has no default preferred
1665   // size.
1666   return true;
1667 }
1668
1669 views::View* BrowserView::GetContentsView() {
1670   return contents_web_view_;
1671 }
1672
1673 views::ClientView* BrowserView::CreateClientView(views::Widget* widget) {
1674   return this;
1675 }
1676
1677 void BrowserView::OnWidgetActivationChanged(views::Widget* widget,
1678                                             bool active) {
1679   if (active)
1680     BrowserList::SetLastActive(browser_.get());
1681 }
1682
1683 void BrowserView::OnWindowBeginUserBoundsChange() {
1684   WebContents* web_contents = GetActiveWebContents();
1685   if (!web_contents)
1686     return;
1687   web_contents->GetRenderViewHost()->NotifyMoveOrResizeStarted();
1688 }
1689
1690 void BrowserView::OnWidgetMove() {
1691   if (!initialized_) {
1692     // Creating the widget can trigger a move. Ignore it until we've initialized
1693     // things.
1694     return;
1695   }
1696
1697   // Cancel any tabstrip animations, some of them may be invalidated by the
1698   // window being repositioned.
1699   // Comment out for one cycle to see if this fixes dist tests.
1700   // tabstrip_->DestroyDragController();
1701
1702   // status_bubble_ may be NULL if this is invoked during construction.
1703   if (status_bubble_.get())
1704     status_bubble_->Reposition();
1705
1706   BookmarkBubbleView::Hide();
1707
1708   // Close the omnibox popup, if any.
1709   LocationBarView* location_bar_view = GetLocationBarView();
1710   if (location_bar_view)
1711     location_bar_view->GetOmniboxView()->CloseOmniboxPopup();
1712 }
1713
1714 views::Widget* BrowserView::GetWidget() {
1715   return View::GetWidget();
1716 }
1717
1718 const views::Widget* BrowserView::GetWidget() const {
1719   return View::GetWidget();
1720 }
1721
1722 void BrowserView::GetAccessiblePanes(std::vector<views::View*>* panes) {
1723   // This should be in the order of pane traversal of the panes using F6
1724   // (Windows) or Ctrl+Back/Forward (Chrome OS).  If one of these is
1725   // invisible or has no focusable children, it will be automatically
1726   // skipped.
1727   panes->push_back(toolbar_);
1728   if (bookmark_bar_view_.get())
1729     panes->push_back(bookmark_bar_view_.get());
1730   if (infobar_container_)
1731     panes->push_back(infobar_container_);
1732   if (download_shelf_.get())
1733     panes->push_back(download_shelf_.get());
1734   panes->push_back(GetTabContentsContainerView());
1735   if (devtools_web_view_->visible())
1736     panes->push_back(devtools_web_view_);
1737 }
1738
1739 ///////////////////////////////////////////////////////////////////////////////
1740 // BrowserView, views::ClientView overrides:
1741
1742 bool BrowserView::CanClose() {
1743   // You cannot close a frame for which there is an active originating drag
1744   // session.
1745   if (tabstrip_ && !tabstrip_->IsTabStripCloseable())
1746     return false;
1747
1748   // Give beforeunload handlers the chance to cancel the close before we hide
1749   // the window below.
1750   if (!browser_->ShouldCloseWindow())
1751     return false;
1752
1753   bool fast_tab_closing_enabled =
1754     CommandLine::ForCurrentProcess()->HasSwitch(switches::kEnableFastUnload);
1755
1756   if (!browser_->tab_strip_model()->empty()) {
1757     // Tab strip isn't empty.  Hide the frame (so it appears to have closed
1758     // immediately) and close all the tabs, allowing the renderers to shut
1759     // down. When the tab strip is empty we'll be called back again.
1760     frame_->Hide();
1761     browser_->OnWindowClosing();
1762     if (fast_tab_closing_enabled)
1763       browser_->tab_strip_model()->CloseAllTabs();
1764     return false;
1765   } else if (fast_tab_closing_enabled &&
1766         !browser_->HasCompletedUnloadProcessing()) {
1767     // The browser needs to finish running unload handlers.
1768     // Hide the frame (so it appears to have closed immediately), and
1769     // the browser will call us back again when it is ready to close.
1770     frame_->Hide();
1771     return false;
1772   }
1773
1774   // Empty TabStripModel, it's now safe to allow the Window to be closed.
1775   content::NotificationService::current()->Notify(
1776       chrome::NOTIFICATION_WINDOW_CLOSED,
1777       content::Source<gfx::NativeWindow>(frame_->GetNativeWindow()),
1778       content::NotificationService::NoDetails());
1779   return true;
1780 }
1781
1782 int BrowserView::NonClientHitTest(const gfx::Point& point) {
1783   return GetBrowserViewLayout()->NonClientHitTest(point);
1784 }
1785
1786 gfx::Size BrowserView::GetMinimumSize() const {
1787   return GetBrowserViewLayout()->GetMinimumSize();
1788 }
1789
1790 ///////////////////////////////////////////////////////////////////////////////
1791 // BrowserView, views::View overrides:
1792
1793 const char* BrowserView::GetClassName() const {
1794   return kViewClassName;
1795 }
1796
1797 void BrowserView::Layout() {
1798   if (!initialized_ || in_process_fullscreen_)
1799     return;
1800
1801   views::View::Layout();
1802
1803   // TODO(jamescook): Why was this in the middle of layout code?
1804   toolbar_->location_bar()->omnibox_view()->SetFocusable(IsToolbarVisible());
1805 }
1806
1807 void BrowserView::PaintChildren(gfx::Canvas* canvas,
1808                                 const views::CullSet& cull_set) {
1809   // Paint the |infobar_container_| last so that it may paint its
1810   // overlapping tabs.
1811   for (int i = 0; i < child_count(); ++i) {
1812     View* child = child_at(i);
1813     if (child != infobar_container_ && !child->layer())
1814       child->Paint(canvas, cull_set);
1815   }
1816
1817   infobar_container_->Paint(canvas, cull_set);
1818 }
1819
1820 void BrowserView::ViewHierarchyChanged(
1821     const ViewHierarchyChangedDetails& details) {
1822   if (!initialized_ && details.is_add && details.child == this && GetWidget()) {
1823     InitViews();
1824     initialized_ = true;
1825   }
1826 }
1827
1828 void BrowserView::ChildPreferredSizeChanged(View* child) {
1829   Layout();
1830 }
1831
1832 void BrowserView::GetAccessibleState(ui::AXViewState* state) {
1833   state->role = ui::AX_ROLE_CLIENT;
1834 }
1835
1836 void BrowserView::OnNativeThemeChanged(const ui::NativeTheme* theme) {
1837   // Do not handle native theme changes before the browser view is initialized.
1838   if (!initialized_)
1839     return;
1840   ClientView::OnNativeThemeChanged(theme);
1841   UserChangedTheme();
1842   chrome::MaybeShowInvertBubbleView(this);
1843 }
1844
1845 ///////////////////////////////////////////////////////////////////////////////
1846 // BrowserView, ui::AcceleratorTarget overrides:
1847
1848 bool BrowserView::AcceleratorPressed(const ui::Accelerator& accelerator) {
1849 #if defined(OS_CHROMEOS)
1850   // If accessibility is enabled, stop speech and return false so that key
1851   // combinations involving Search can be used for extra accessibility
1852   // functionality.
1853   if (accelerator.key_code() == ui::VKEY_LWIN &&
1854       g_browser_process->local_state()->GetBoolean(
1855           prefs::kAccessibilitySpokenFeedbackEnabled)) {
1856     TtsController::GetInstance()->Stop();
1857     return false;
1858   }
1859 #endif
1860
1861   std::map<ui::Accelerator, int>::const_iterator iter =
1862       accelerator_table_.find(accelerator);
1863   DCHECK(iter != accelerator_table_.end());
1864   int command_id = iter->second;
1865
1866   chrome::BrowserCommandController* controller = browser_->command_controller();
1867   if (!controller->block_command_execution())
1868     UpdateAcceleratorMetrics(accelerator, command_id);
1869   return chrome::ExecuteCommand(browser_.get(), command_id);
1870 }
1871
1872 ///////////////////////////////////////////////////////////////////////////////
1873 // BrowserView, OmniboxPopupModelObserver overrides:
1874 void BrowserView::OnOmniboxPopupShownOrHidden() {
1875   infobar_container_->SetMaxTopArrowHeight(GetMaxTopInfoBarArrowHeight());
1876 }
1877
1878 ///////////////////////////////////////////////////////////////////////////////
1879 // BrowserView, InfoBarContainer::Delegate overrides:
1880
1881 SkColor BrowserView::GetInfoBarSeparatorColor() const {
1882   // NOTE: Keep this in sync with ToolbarView::OnPaint()!
1883   return (IsTabStripVisible() || !frame_->ShouldUseNativeFrame()) ?
1884       ThemeProperties::GetDefaultColor(
1885           ThemeProperties::COLOR_TOOLBAR_SEPARATOR) :
1886       SK_ColorBLACK;
1887 }
1888
1889 void BrowserView::InfoBarContainerStateChanged(bool is_animating) {
1890   ToolbarSizeChanged(is_animating);
1891 }
1892
1893 bool BrowserView::DrawInfoBarArrows(int* x) const {
1894   if (x) {
1895     gfx::Point anchor(toolbar_->location_bar()->GetLocationBarAnchorPoint());
1896     ConvertPointToTarget(toolbar_->location_bar(), this, &anchor);
1897     *x = anchor.x();
1898   }
1899   return true;
1900 }
1901
1902 void BrowserView::InitViews() {
1903   GetWidget()->AddObserver(this);
1904
1905   // Stow a pointer to this object onto the window handle so that we can get at
1906   // it later when all we have is a native view.
1907   GetWidget()->SetNativeWindowProperty(kBrowserViewKey, this);
1908
1909   // Stow a pointer to the browser's profile onto the window handle so that we
1910   // can get it later when all we have is a native view.
1911   GetWidget()->SetNativeWindowProperty(Profile::kProfileKey,
1912                                        browser_->profile());
1913
1914   // Start a hung plugin window detector for this browser object (as long as
1915   // hang detection is not disabled).
1916   if (!CommandLine::ForCurrentProcess()->HasSwitch(
1917           switches::kDisableHangMonitor)) {
1918     InitHangMonitor();
1919   }
1920
1921   LoadAccelerators();
1922
1923   infobar_container_ = new InfoBarContainerView(this);
1924   AddChildView(infobar_container_);
1925
1926   contents_web_view_ = new ContentsWebView(browser_->profile());
1927   contents_web_view_->set_id(VIEW_ID_TAB_CONTAINER);
1928   contents_web_view_->SetEmbedFullscreenWidgetMode(true);
1929
1930   web_contents_close_handler_.reset(
1931       new WebContentsCloseHandler(contents_web_view_));
1932
1933   devtools_web_view_ = new views::WebView(browser_->profile());
1934   devtools_web_view_->set_id(VIEW_ID_DEV_TOOLS_DOCKED);
1935   devtools_web_view_->SetVisible(false);
1936
1937   contents_container_ = new views::View();
1938   contents_container_->set_background(views::Background::CreateSolidBackground(
1939       ThemeProperties::GetDefaultColor(
1940           ThemeProperties::COLOR_CONTROL_BACKGROUND)));
1941   contents_container_->AddChildView(devtools_web_view_);
1942   contents_container_->AddChildView(contents_web_view_);
1943   contents_container_->SetLayoutManager(new ContentsLayoutManager(
1944       devtools_web_view_, contents_web_view_));
1945   AddChildView(contents_container_);
1946   set_contents_view(contents_container_);
1947
1948   // Top container holds tab strip and toolbar and lives at the front of the
1949   // view hierarchy.
1950   top_container_ = new TopContainerView(this);
1951   AddChildView(top_container_);
1952
1953   // TabStrip takes ownership of the controller.
1954   BrowserTabStripController* tabstrip_controller =
1955       new BrowserTabStripController(browser_.get(),
1956                                     browser_->tab_strip_model());
1957   tabstrip_ = new TabStrip(tabstrip_controller);
1958   top_container_->AddChildView(tabstrip_);
1959   tabstrip_controller->InitFromModel(tabstrip_);
1960
1961   toolbar_ = new ToolbarView(browser_.get());
1962   top_container_->AddChildView(toolbar_);
1963   toolbar_->Init();
1964
1965   InitStatusBubble();
1966   InitPermissionBubbleView();
1967
1968   // Create do-nothing view for the sake of controlling the z-order of the find
1969   // bar widget.
1970   find_bar_host_view_ = new View();
1971   AddChildView(find_bar_host_view_);
1972
1973   immersive_mode_controller_->Init(this);
1974
1975   BrowserViewLayout* browser_view_layout = new BrowserViewLayout;
1976   browser_view_layout->Init(new BrowserViewLayoutDelegateImpl(this),
1977                             browser(),
1978                             this,
1979                             top_container_,
1980                             tabstrip_,
1981                             toolbar_,
1982                             infobar_container_,
1983                             contents_container_,
1984                             GetContentsLayoutManager(),
1985                             immersive_mode_controller_.get());
1986   SetLayoutManager(browser_view_layout);
1987
1988 #if defined(OS_WIN)
1989   // Create a custom JumpList and add it to an observer of TabRestoreService
1990   // so we can update the custom JumpList when a tab is added or removed.
1991   if (JumpList::Enabled()) {
1992     load_complete_listener_.reset(new LoadCompleteListener(this));
1993   }
1994 #endif
1995
1996   GetLocationBar()->GetOmniboxView()->model()->popup_model()->AddObserver(this);
1997 }
1998
1999 void BrowserView::LoadingAnimationCallback() {
2000   base::TimeTicks now = base::TimeTicks::Now();
2001   if (!last_animation_time_.is_null()) {
2002     UMA_HISTOGRAM_TIMES(
2003         "Tabs.LoadingAnimationTime",
2004         now - last_animation_time_);
2005   }
2006   last_animation_time_ = now;
2007   if (browser_->is_type_tabbed()) {
2008     // Loading animations are shown in the tab for tabbed windows.  We check the
2009     // browser type instead of calling IsTabStripVisible() because the latter
2010     // will return false for fullscreen windows, but we still need to update
2011     // their animations (so that when they come out of fullscreen mode they'll
2012     // be correct).
2013     tabstrip_->UpdateLoadingAnimations();
2014   } else if (ShouldShowWindowIcon()) {
2015     // ... or in the window icon area for popups and app windows.
2016     WebContents* web_contents =
2017         browser_->tab_strip_model()->GetActiveWebContents();
2018     // GetActiveWebContents can return NULL for example under Purify when
2019     // the animations are running slowly and this function is called on a timer
2020     // through LoadingAnimationCallback.
2021     frame_->UpdateThrobber(web_contents && web_contents->IsLoading());
2022   }
2023 }
2024
2025 void BrowserView::OnLoadCompleted() {
2026 #if defined(OS_WIN)
2027   DCHECK(!jumplist_);
2028   jumplist_ = new JumpList(browser_->profile());
2029 #endif
2030 }
2031
2032 BrowserViewLayout* BrowserView::GetBrowserViewLayout() const {
2033   return static_cast<BrowserViewLayout*>(GetLayoutManager());
2034 }
2035
2036 ContentsLayoutManager* BrowserView::GetContentsLayoutManager() const {
2037   return static_cast<ContentsLayoutManager*>(
2038       contents_container_->GetLayoutManager());
2039 }
2040
2041 bool BrowserView::MaybeShowBookmarkBar(WebContents* contents) {
2042   bool show_bookmark_bar = contents &&
2043       browser_->SupportsWindowFeature(Browser::FEATURE_BOOKMARKBAR);
2044   if (!show_bookmark_bar && !bookmark_bar_view_.get())
2045     return false;
2046   if (!bookmark_bar_view_.get()) {
2047     bookmark_bar_view_.reset(new BookmarkBarView(browser_.get(), this));
2048     bookmark_bar_view_->set_owned_by_client();
2049     bookmark_bar_view_->set_background(
2050         new BookmarkExtensionBackground(this,
2051                                         bookmark_bar_view_.get(),
2052                                         browser_.get()));
2053     bookmark_bar_view_->SetBookmarkBarState(
2054         browser_->bookmark_bar_state(),
2055         BookmarkBar::DONT_ANIMATE_STATE_CHANGE);
2056     GetBrowserViewLayout()->set_bookmark_bar(bookmark_bar_view_.get());
2057   }
2058   // Don't change the visibility of the BookmarkBarView. BrowserViewLayout
2059   // handles it.
2060   bookmark_bar_view_->SetPageNavigator(GetActiveWebContents());
2061
2062   // Update parenting for the bookmark bar. This may detach it from all views.
2063   bool needs_layout = false;
2064   views::View* new_parent = NULL;
2065   if (show_bookmark_bar) {
2066     if (bookmark_bar_view_->IsDetached())
2067       new_parent = this;
2068     else
2069       new_parent = top_container_;
2070   }
2071   if (new_parent != bookmark_bar_view_->parent()) {
2072     SetBookmarkBarParent(new_parent);
2073     needs_layout = true;
2074   }
2075
2076   // Check for updates to the desired size.
2077   if (bookmark_bar_view_->GetPreferredSize().height() !=
2078       bookmark_bar_view_->height())
2079     needs_layout = true;
2080
2081   return needs_layout;
2082 }
2083
2084 void BrowserView::SetBookmarkBarParent(views::View* new_parent) {
2085   if (new_parent == this) {
2086     // Add it underneath |top_container_| or at the end if top container isn't
2087     // found.
2088     int top_container_index = GetIndexOf(top_container_);
2089     if (top_container_index >= 0)
2090       AddChildViewAt(bookmark_bar_view_.get(), top_container_index);
2091     else
2092       AddChildView(bookmark_bar_view_.get());
2093   } else if (new_parent) {
2094     // No special stacking is required for other parents.
2095     new_parent->AddChildView(bookmark_bar_view_.get());
2096   } else {
2097     // Bookmark bar is being detached from all views because it is hidden.
2098     bookmark_bar_view_->parent()->RemoveChildView(bookmark_bar_view_.get());
2099   }
2100 }
2101
2102 bool BrowserView::MaybeShowInfoBar(WebContents* contents) {
2103   // TODO(beng): Remove this function once the interface between
2104   //             InfoBarContainer, DownloadShelfView and WebContents and this
2105   //             view is sorted out.
2106   return true;
2107 }
2108
2109 void BrowserView::UpdateDevToolsForContents(
2110     WebContents* web_contents, bool update_devtools_web_contents) {
2111   DevToolsContentsResizingStrategy strategy;
2112   WebContents* devtools = DevToolsWindow::GetInTabWebContents(
2113       web_contents, &strategy);
2114
2115   if (!devtools_web_view_->web_contents() && devtools &&
2116       !devtools_focus_tracker_.get()) {
2117     // Install devtools focus tracker when dev tools window is shown for the
2118     // first time.
2119     devtools_focus_tracker_.reset(
2120         new views::ExternalFocusTracker(devtools_web_view_,
2121                                         GetFocusManager()));
2122   }
2123
2124   // Restore focus to the last focused view when hiding devtools window.
2125   if (devtools_web_view_->web_contents() && !devtools &&
2126       devtools_focus_tracker_.get()) {
2127     devtools_focus_tracker_->FocusLastFocusedExternalView();
2128     devtools_focus_tracker_.reset();
2129   }
2130
2131   // Replace devtools WebContents.
2132   if (devtools_web_view_->web_contents() != devtools &&
2133       update_devtools_web_contents) {
2134     devtools_web_view_->SetWebContents(devtools);
2135   }
2136
2137   if (devtools) {
2138     devtools_web_view_->SetVisible(true);
2139     GetContentsLayoutManager()->SetContentsResizingStrategy(strategy);
2140   } else {
2141     devtools_web_view_->SetVisible(false);
2142     GetContentsLayoutManager()->SetContentsResizingStrategy(
2143         DevToolsContentsResizingStrategy());
2144   }
2145   contents_container_->Layout();
2146
2147   if (devtools) {
2148     // When strategy.hide_inspected_contents() returns true, we are hiding
2149     // contents_web_view_ behind the devtools_web_view_. Otherwise,
2150     // contents_web_view_ should be right above the devtools_web_view_.
2151     int devtools_index = contents_container_->GetIndexOf(devtools_web_view_);
2152     int contents_index = contents_container_->GetIndexOf(contents_web_view_);
2153     bool devtools_is_on_top = devtools_index > contents_index;
2154     if (strategy.hide_inspected_contents() != devtools_is_on_top)
2155       contents_container_->ReorderChildView(contents_web_view_, devtools_index);
2156   }
2157 }
2158
2159 void BrowserView::UpdateUIForContents(WebContents* contents) {
2160   bool needs_layout = MaybeShowBookmarkBar(contents);
2161   // TODO(jamescook): This function always returns true. Remove it and figure
2162   // out when layout is actually required.
2163   needs_layout |= MaybeShowInfoBar(contents);
2164   if (needs_layout)
2165     Layout();
2166 }
2167
2168 void BrowserView::ProcessFullscreen(bool fullscreen,
2169                                     FullscreenMode mode,
2170                                     const GURL& url,
2171                                     FullscreenExitBubbleType bubble_type) {
2172   if (in_process_fullscreen_)
2173     return;
2174   in_process_fullscreen_ = true;
2175
2176   // Reduce jankiness during the following position changes by:
2177   //   * Hiding the window until it's in the final position
2178   //   * Ignoring all intervening Layout() calls, which resize the webpage and
2179   //     thus are slow and look ugly (enforced via |in_process_fullscreen_|).
2180   LocationBarView* location_bar = GetLocationBarView();
2181
2182   if (mode == METRO_SNAP_FULLSCREEN || !fullscreen) {
2183     // Hide the fullscreen bubble as soon as possible, since the mode toggle can
2184     // take enough time for the user to notice.
2185     fullscreen_bubble_.reset();
2186   }
2187
2188   if (fullscreen) {
2189     // Move focus out of the location bar if necessary.
2190     views::FocusManager* focus_manager = GetFocusManager();
2191     DCHECK(focus_manager);
2192     // Look for focus in the location bar itself or any child view.
2193     if (location_bar->Contains(focus_manager->GetFocusedView()))
2194       focus_manager->ClearFocus();
2195   }
2196
2197   // Toggle fullscreen mode.
2198   frame_->SetFullscreen(fullscreen);
2199
2200   // Enable immersive before the browser refreshes its list of enabled commands.
2201   if (mode != METRO_SNAP_FULLSCREEN && ShouldUseImmersiveFullscreenForUrl(url))
2202     immersive_mode_controller_->SetEnabled(fullscreen);
2203
2204   browser_->WindowFullscreenStateChanged();
2205
2206   if (fullscreen && !chrome::IsRunningInAppMode() &&
2207       mode != METRO_SNAP_FULLSCREEN) {
2208     UpdateFullscreenExitBubbleContent(url, bubble_type);
2209   }
2210
2211   // Undo our anti-jankiness hacks and force a re-layout. We also need to
2212   // recompute the height of the infobar top arrow because toggling in and out
2213   // of fullscreen changes it. Calling ToolbarSizeChanged() will do both these
2214   // things since it computes the arrow height directly and forces a layout
2215   // indirectly via UpdateUIForContents(). Reset |in_process_fullscreen_| in
2216   // order to let the layout occur.
2217   in_process_fullscreen_ = false;
2218   ToolbarSizeChanged(false);
2219 }
2220
2221 bool BrowserView::ShouldUseImmersiveFullscreenForUrl(const GURL& url) const {
2222   // Kiosk mode needs the whole screen, and if we're not in an Ash desktop
2223   // immersive fullscreen doesn't exist.
2224   if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kKioskMode) ||
2225       browser()->host_desktop_type() != chrome::HOST_DESKTOP_TYPE_ASH) {
2226     return false;
2227   }
2228
2229   return url.is_empty();
2230 }
2231
2232 void BrowserView::LoadAccelerators() {
2233   views::FocusManager* focus_manager = GetFocusManager();
2234   DCHECK(focus_manager);
2235
2236   // Let's fill our own accelerator table.
2237   const bool is_app_mode = chrome::IsRunningInForcedAppMode();
2238   const std::vector<chrome::AcceleratorMapping> accelerator_list(
2239       chrome::GetAcceleratorList());
2240   for (std::vector<chrome::AcceleratorMapping>::const_iterator it =
2241            accelerator_list.begin(); it != accelerator_list.end(); ++it) {
2242     // In app mode, only allow accelerators of white listed commands to pass
2243     // through.
2244     if (is_app_mode && !chrome::IsCommandAllowedInAppMode(it->command_id))
2245       continue;
2246
2247     ui::Accelerator accelerator(it->keycode, it->modifiers);
2248     accelerator_table_[accelerator] = it->command_id;
2249
2250     // Also register with the focus manager.
2251     focus_manager->RegisterAccelerator(
2252         accelerator, ui::AcceleratorManager::kNormalPriority, this);
2253   }
2254 }
2255
2256 int BrowserView::GetCommandIDForAppCommandID(int app_command_id) const {
2257 #if defined(OS_WIN)
2258   switch (app_command_id) {
2259     // NOTE: The order here matches the APPCOMMAND declaration order in the
2260     // Windows headers.
2261     case APPCOMMAND_BROWSER_BACKWARD: return IDC_BACK;
2262     case APPCOMMAND_BROWSER_FORWARD:  return IDC_FORWARD;
2263     case APPCOMMAND_BROWSER_REFRESH:  return IDC_RELOAD;
2264     case APPCOMMAND_BROWSER_HOME:     return IDC_HOME;
2265     case APPCOMMAND_BROWSER_STOP:     return IDC_STOP;
2266     case APPCOMMAND_BROWSER_SEARCH:   return IDC_FOCUS_SEARCH;
2267     case APPCOMMAND_HELP:             return IDC_HELP_PAGE_VIA_KEYBOARD;
2268     case APPCOMMAND_NEW:              return IDC_NEW_TAB;
2269     case APPCOMMAND_OPEN:             return IDC_OPEN_FILE;
2270     case APPCOMMAND_CLOSE:            return IDC_CLOSE_TAB;
2271     case APPCOMMAND_SAVE:             return IDC_SAVE_PAGE;
2272     case APPCOMMAND_PRINT:            return IDC_PRINT;
2273     case APPCOMMAND_COPY:             return IDC_COPY;
2274     case APPCOMMAND_CUT:              return IDC_CUT;
2275     case APPCOMMAND_PASTE:            return IDC_PASTE;
2276
2277       // TODO(pkasting): http://b/1113069 Handle these.
2278     case APPCOMMAND_UNDO:
2279     case APPCOMMAND_REDO:
2280     case APPCOMMAND_SPELL_CHECK:
2281     default:                          return -1;
2282   }
2283 #else
2284   // App commands are Windows-specific so there's nothing to do here.
2285   return -1;
2286 #endif
2287 }
2288
2289 void BrowserView::InitHangMonitor() {
2290 #if defined(OS_WIN)
2291   PrefService* pref_service = g_browser_process->local_state();
2292   if (!pref_service)
2293     return;
2294
2295   int plugin_message_response_timeout =
2296       pref_service->GetInteger(prefs::kPluginMessageResponseTimeout);
2297   int hung_plugin_detect_freq =
2298       pref_service->GetInteger(prefs::kHungPluginDetectFrequency);
2299   HWND window = GetWidget()->GetNativeView()->GetHost()->
2300       GetAcceleratedWidget();
2301   if ((hung_plugin_detect_freq > 0) &&
2302       hung_window_detector_.Initialize(window,
2303                                        plugin_message_response_timeout)) {
2304     ticker_.set_tick_interval(hung_plugin_detect_freq);
2305     ticker_.RegisterTickHandler(&hung_window_detector_);
2306     ticker_.Start();
2307
2308     pref_service->SetInteger(prefs::kPluginMessageResponseTimeout,
2309                              plugin_message_response_timeout);
2310     pref_service->SetInteger(prefs::kHungPluginDetectFrequency,
2311                              hung_plugin_detect_freq);
2312   }
2313 #endif
2314 }
2315
2316 void BrowserView::UpdateAcceleratorMetrics(const ui::Accelerator& accelerator,
2317                                            int command_id) {
2318   const ui::KeyboardCode key_code = accelerator.key_code();
2319   if (command_id == IDC_HELP_PAGE_VIA_KEYBOARD && key_code == ui::VKEY_F1)
2320     content::RecordAction(UserMetricsAction("ShowHelpTabViaF1"));
2321
2322   if (command_id == IDC_BOOKMARK_PAGE)
2323     UMA_HISTOGRAM_ENUMERATION("Bookmarks.EntryPoint",
2324                               BOOKMARK_ENTRY_POINT_ACCELERATOR,
2325                               BOOKMARK_ENTRY_POINT_LIMIT);
2326
2327 #if defined(OS_CHROMEOS)
2328   // Collect information about the relative popularity of various accelerators
2329   // on Chrome OS.
2330   switch (command_id) {
2331     case IDC_BACK:
2332       if (key_code == ui::VKEY_BACK)
2333         content::RecordAction(UserMetricsAction("Accel_Back_Backspace"));
2334       else if (key_code == ui::VKEY_BROWSER_BACK)
2335         content::RecordAction(UserMetricsAction("Accel_Back_F1"));
2336       else if (key_code == ui::VKEY_LEFT)
2337         content::RecordAction(UserMetricsAction("Accel_Back_Left"));
2338       break;
2339     case IDC_FORWARD:
2340       if (key_code == ui::VKEY_BACK)
2341         content::RecordAction(UserMetricsAction("Accel_Forward_Backspace"));
2342       else if (key_code == ui::VKEY_BROWSER_FORWARD)
2343         content::RecordAction(UserMetricsAction("Accel_Forward_F2"));
2344       else if (key_code == ui::VKEY_RIGHT)
2345         content::RecordAction(UserMetricsAction("Accel_Forward_Right"));
2346       break;
2347     case IDC_RELOAD:
2348     case IDC_RELOAD_IGNORING_CACHE:
2349       if (key_code == ui::VKEY_R)
2350         content::RecordAction(UserMetricsAction("Accel_Reload_R"));
2351       else if (key_code == ui::VKEY_BROWSER_REFRESH)
2352         content::RecordAction(UserMetricsAction("Accel_Reload_F3"));
2353       break;
2354     case IDC_FOCUS_LOCATION:
2355       if (key_code == ui::VKEY_D)
2356         content::RecordAction(UserMetricsAction("Accel_FocusLocation_D"));
2357       else if (key_code == ui::VKEY_L)
2358         content::RecordAction(UserMetricsAction("Accel_FocusLocation_L"));
2359       break;
2360     case IDC_FOCUS_SEARCH:
2361       if (key_code == ui::VKEY_E)
2362         content::RecordAction(UserMetricsAction("Accel_FocusSearch_E"));
2363       else if (key_code == ui::VKEY_K)
2364         content::RecordAction(UserMetricsAction("Accel_FocusSearch_K"));
2365       break;
2366     default:
2367       // Do nothing.
2368       break;
2369   }
2370 #endif
2371 }
2372
2373 // static
2374 BrowserWindow* BrowserWindow::CreateBrowserWindow(Browser* browser) {
2375   // Create the view and the frame. The frame will attach itself via the view
2376   // so we don't need to do anything with the pointer.
2377   BrowserView* view = new BrowserView();
2378   view->Init(browser);
2379   (new BrowserFrame(view))->InitBrowserFrame();
2380   view->GetWidget()->non_client_view()->SetAccessibleName(
2381       l10n_util::GetStringUTF16(IDS_PRODUCT_NAME));
2382   return view;
2383 }
2384
2385 // static
2386 chrome::HostDesktopType BrowserWindow::AdjustHostDesktopType(
2387     chrome::HostDesktopType desktop_type) {
2388   return NativeBrowserFrameFactory::AdjustHostDesktopType(desktop_type);
2389 }
2390
2391 void BrowserView::ShowAvatarBubble(WebContents* web_contents,
2392                                    const gfx::Rect& rect) {
2393   gfx::Point origin(rect.origin());
2394   views::View::ConvertPointToScreen(GetTabContentsContainerView(), &origin);
2395   gfx::Rect bounds(origin, rect.size());
2396
2397   AvatarMenuBubbleView::ShowBubble(
2398       this, views::BubbleBorder::TOP_RIGHT, views::BubbleBorder::PAINT_NORMAL,
2399       views::BubbleBorder::ALIGN_EDGE_TO_ANCHOR_EDGE, bounds, browser_.get());
2400 }
2401
2402 void BrowserView::ShowAvatarBubbleFromAvatarButton(
2403     AvatarBubbleMode mode,
2404     const signin::ManageAccountsParams& manage_accounts_params) {
2405   views::BubbleBorder::Arrow arrow = views::BubbleBorder::TOP_RIGHT;
2406   views::BubbleBorder::BubbleAlignment alignment =
2407       views::BubbleBorder::ALIGN_ARROW_TO_MID_ANCHOR;
2408   views::View* anchor_view = frame_->GetAvatarMenuButton();
2409   if (!anchor_view)
2410     anchor_view = toolbar_->app_menu();
2411   else if (!frame_->GetAvatarMenuButton()->button_on_right())
2412     arrow = views::BubbleBorder::TOP_LEFT;
2413
2414   if (switches::IsNewAvatarMenu()) {
2415     NewAvatarButton* button = frame_->GetNewAvatarMenuButton();
2416     if (button) {
2417       anchor_view = button;
2418       arrow = views::BubbleBorder::TOP_RIGHT;
2419       alignment = views::BubbleBorder::ALIGN_EDGE_TO_ANCHOR_EDGE;
2420     }
2421
2422     profiles::BubbleViewMode bubble_view_mode;
2423     profiles::TutorialMode tutorial_mode;
2424     profiles::BubbleViewModeFromAvatarBubbleMode(
2425         mode, &bubble_view_mode, &tutorial_mode);
2426     ProfileChooserView::ShowBubble(
2427         bubble_view_mode, tutorial_mode,
2428         manage_accounts_params, anchor_view, arrow, alignment, browser());
2429   } else {
2430     gfx::Point origin;
2431     views::View::ConvertPointToScreen(anchor_view, &origin);
2432     gfx::Rect bounds(origin, anchor_view->size());
2433     views::BubbleBorder::ArrowPaintType arrow_paint_type =
2434         ShouldHideUIForFullscreen() ? views::BubbleBorder::PAINT_TRANSPARENT :
2435                                       views::BubbleBorder::PAINT_NORMAL;
2436     AvatarMenuBubbleView::ShowBubble(anchor_view, arrow, arrow_paint_type,
2437                                      alignment, bounds, browser());
2438   }
2439   ProfileMetrics::LogProfileOpenMethod(ProfileMetrics::ICON_AVATAR_BUBBLE);
2440 }
2441
2442 int BrowserView::GetRenderViewHeightInsetWithDetachedBookmarkBar() {
2443   if (browser_->bookmark_bar_state() != BookmarkBar::DETACHED ||
2444       !bookmark_bar_view_.get() || !bookmark_bar_view_->IsDetached()) {
2445     return 0;
2446   }
2447   // Don't use bookmark_bar_view_->height() which won't be the final height if
2448   // the bookmark bar is animating.
2449   return chrome::kNTPBookmarkBarHeight -
2450       bookmark_bar_view_->GetFullyDetachedToolbarOverlap();
2451 }
2452
2453 void BrowserView::ExecuteExtensionCommand(
2454     const extensions::Extension* extension,
2455     const extensions::Command& command) {
2456   toolbar_->ExecuteExtensionCommand(extension, command);
2457 }
2458
2459 void BrowserView::DoCutCopyPaste(void (WebContents::*method)(),
2460                                  int command_id) {
2461   WebContents* contents = browser_->tab_strip_model()->GetActiveWebContents();
2462   if (!contents)
2463     return;
2464   if (DoCutCopyPasteForWebContents(contents, method))
2465     return;
2466
2467   WebContents* devtools = DevToolsWindow::GetInTabWebContents(contents, NULL);
2468   if (devtools && DoCutCopyPasteForWebContents(devtools, method))
2469     return;
2470
2471   views::FocusManager* focus_manager = GetFocusManager();
2472   views::View* focused = focus_manager->GetFocusedView();
2473   if (focused &&
2474       (!strcmp(focused->GetClassName(), views::Textfield::kViewClassName) ||
2475        !strcmp(focused->GetClassName(), OmniboxViewViews::kViewClassName))) {
2476     views::Textfield* textfield = static_cast<views::Textfield*>(focused);
2477     textfield->ExecuteCommand(command_id);
2478   }
2479 }
2480
2481 bool BrowserView::DoCutCopyPasteForWebContents(
2482     WebContents* contents,
2483     void (WebContents::*method)()) {
2484   gfx::NativeView native_view = contents->GetContentNativeView();
2485   if (!native_view)
2486     return false;
2487   if (native_view->HasFocus()) {
2488     (contents->*method)();
2489     return true;
2490   }
2491
2492   return false;
2493 }
2494
2495 void BrowserView::ActivateAppModalDialog() const {
2496   // If another browser is app modal, flash and activate the modal browser.
2497   AppModalDialog* active_dialog =
2498       AppModalDialogQueue::GetInstance()->active_dialog();
2499   if (!active_dialog)
2500     return;
2501
2502   Browser* modal_browser =
2503       chrome::FindBrowserWithWebContents(active_dialog->web_contents());
2504   if (modal_browser && (browser_ != modal_browser)) {
2505     modal_browser->window()->FlashFrame(true);
2506     modal_browser->window()->Activate();
2507   }
2508
2509   AppModalDialogQueue::GetInstance()->ActivateModalDialog();
2510 }
2511
2512 int BrowserView::GetMaxTopInfoBarArrowHeight() {
2513   int top_arrow_height = 0;
2514   // Only show the arrows when not in fullscreen and when there's no omnibox
2515   // popup.
2516   if (!IsFullscreen() &&
2517       !GetLocationBar()->GetOmniboxView()->model()->popup_model()->IsOpen()) {
2518     gfx::Point icon_bottom(
2519         toolbar_->location_bar()->GetLocationBarAnchorPoint());
2520     ConvertPointToTarget(toolbar_->location_bar(), this, &icon_bottom);
2521     gfx::Point infobar_top(0, infobar_container_->GetVerticalOverlap(NULL));
2522     ConvertPointToTarget(infobar_container_, this, &infobar_top);
2523     top_arrow_height = infobar_top.y() - icon_bottom.y();
2524   }
2525   return top_arrow_height;
2526 }