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