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