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