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