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