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