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