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