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