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