Add ENABLE_MEDIA_ROUTER define to builds other than Android and iOS.
[chromium-blink-merge.git] / chrome / browser / ui / views / frame / browser_view.cc
blob3b892dea35ee0da1d73657faa09fc6c2f509e863
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.
5 #include "chrome/browser/ui/views/frame/browser_view.h"
7 #include <algorithm>
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/profiler/scoped_tracker.h"
16 #include "base/strings/string_number_conversions.h"
17 #include "chrome/app/chrome_command_ids.h"
18 #include "chrome/app/chrome_dll_resource.h"
19 #include "chrome/browser/app_mode/app_mode_utils.h"
20 #include "chrome/browser/bookmarks/bookmark_stats.h"
21 #include "chrome/browser/browser_process.h"
22 #include "chrome/browser/chrome_notification_types.h"
23 #include "chrome/browser/extensions/extension_util.h"
24 #include "chrome/browser/extensions/tab_helper.h"
25 #include "chrome/browser/infobars/infobar_service.h"
26 #include "chrome/browser/native_window_notification_source.h"
27 #include "chrome/browser/profiles/avatar_menu.h"
28 #include "chrome/browser/profiles/profile.h"
29 #include "chrome/browser/profiles/profile_avatar_icon_util.h"
30 #include "chrome/browser/profiles/profile_info_cache.h"
31 #include "chrome/browser/profiles/profile_manager.h"
32 #include "chrome/browser/profiles/profile_window.h"
33 #include "chrome/browser/profiles/profiles_state.h"
34 #include "chrome/browser/search/search.h"
35 #include "chrome/browser/sessions/tab_restore_service.h"
36 #include "chrome/browser/sessions/tab_restore_service_factory.h"
37 #include "chrome/browser/signin/signin_header_helper.h"
38 #include "chrome/browser/themes/theme_properties.h"
39 #include "chrome/browser/themes/theme_service_factory.h"
40 #include "chrome/browser/translate/chrome_translate_client.h"
41 #include "chrome/browser/ui/bookmarks/bookmark_bar_constants.h"
42 #include "chrome/browser/ui/bookmarks/bookmark_bubble_delegate.h"
43 #include "chrome/browser/ui/bookmarks/bookmark_bubble_sign_in_delegate.h"
44 #include "chrome/browser/ui/browser.h"
45 #include "chrome/browser/ui/browser_command_controller.h"
46 #include "chrome/browser/ui/browser_commands.h"
47 #include "chrome/browser/ui/browser_dialogs.h"
48 #include "chrome/browser/ui/browser_finder.h"
49 #include "chrome/browser/ui/browser_list.h"
50 #include "chrome/browser/ui/browser_window_state.h"
51 #include "chrome/browser/ui/omnibox/omnibox_popup_model.h"
52 #include "chrome/browser/ui/omnibox/omnibox_popup_view.h"
53 #include "chrome/browser/ui/omnibox/omnibox_view.h"
54 #include "chrome/browser/ui/search/search_delegate.h"
55 #include "chrome/browser/ui/search/search_model.h"
56 #include "chrome/browser/ui/search/search_ui.h"
57 #include "chrome/browser/ui/tabs/tab_menu_model.h"
58 #include "chrome/browser/ui/tabs/tab_strip_model.h"
59 #include "chrome/browser/ui/view_ids.h"
60 #include "chrome/browser/ui/views/accelerator_table.h"
61 #include "chrome/browser/ui/views/accessibility/invert_bubble_view.h"
62 #include "chrome/browser/ui/views/bookmarks/bookmark_bar_view.h"
63 #include "chrome/browser/ui/views/bookmarks/bookmark_bubble_view.h"
64 #include "chrome/browser/ui/views/browser_dialogs.h"
65 #include "chrome/browser/ui/views/download/download_in_progress_dialog_view.h"
66 #include "chrome/browser/ui/views/download/download_shelf_view.h"
67 #include "chrome/browser/ui/views/exclusive_access_bubble_views.h"
68 #include "chrome/browser/ui/views/extensions/bookmark_app_bubble_view.h"
69 #include "chrome/browser/ui/views/frame/browser_view_layout.h"
70 #include "chrome/browser/ui/views/frame/browser_view_layout_delegate.h"
71 #include "chrome/browser/ui/views/frame/contents_layout_manager.h"
72 #include "chrome/browser/ui/views/frame/immersive_mode_controller.h"
73 #include "chrome/browser/ui/views/frame/top_container_view.h"
74 #include "chrome/browser/ui/views/frame/web_contents_close_handler.h"
75 #include "chrome/browser/ui/views/infobars/infobar_container_view.h"
76 #include "chrome/browser/ui/views/location_bar/location_bar_view.h"
77 #include "chrome/browser/ui/views/location_bar/location_icon_view.h"
78 #include "chrome/browser/ui/views/location_bar/zoom_bubble_view.h"
79 #include "chrome/browser/ui/views/omnibox/omnibox_view_views.h"
80 #include "chrome/browser/ui/views/profiles/avatar_menu_bubble_view.h"
81 #include "chrome/browser/ui/views/profiles/avatar_menu_button.h"
82 #include "chrome/browser/ui/views/profiles/profile_chooser_view.h"
83 #include "chrome/browser/ui/views/profiles/profile_reset_bubble_view.h"
84 #include "chrome/browser/ui/views/session_crashed_bubble_view.h"
85 #include "chrome/browser/ui/views/settings_api_bubble_helper_views.h"
86 #include "chrome/browser/ui/views/status_bubble_views.h"
87 #include "chrome/browser/ui/views/tabs/browser_tab_strip_controller.h"
88 #include "chrome/browser/ui/views/tabs/tab.h"
89 #include "chrome/browser/ui/views/tabs/tab_strip.h"
90 #include "chrome/browser/ui/views/toolbar/reload_button.h"
91 #include "chrome/browser/ui/views/toolbar/toolbar_view.h"
92 #include "chrome/browser/ui/views/toolbar/wrench_toolbar_button.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 "chrome/grit/chromium_strings.h"
103 #include "chrome/grit/generated_resources.h"
104 #include "chrome/grit/locale_settings.h"
105 #include "components/app_modal/app_modal_dialog.h"
106 #include "components/app_modal/app_modal_dialog_queue.h"
107 #include "components/app_modal/native_app_modal_dialog.h"
108 #include "components/signin/core/common/profile_management_switches.h"
109 #include "components/translate/core/browser/language_state.h"
110 #include "content/app/resources/grit/content_resources.h"
111 #include "content/public/browser/download_manager.h"
112 #include "content/public/browser/notification_service.h"
113 #include "content/public/browser/render_frame_host.h"
114 #include "content/public/browser/render_view_host.h"
115 #include "content/public/browser/render_widget_host_view.h"
116 #include "content/public/browser/user_metrics.h"
117 #include "content/public/browser/web_contents.h"
118 #include "content/public/common/content_switches.h"
119 #include "grit/theme_resources.h"
120 #include "ui/accessibility/ax_view_state.h"
121 #include "ui/base/accelerators/accelerator.h"
122 #include "ui/base/hit_test.h"
123 #include "ui/base/l10n/l10n_util.h"
124 #include "ui/base/resource/resource_bundle.h"
125 #include "ui/base/theme_provider.h"
126 #include "ui/content_accelerators/accelerator_util.h"
127 #include "ui/events/event_utils.h"
128 #include "ui/gfx/canvas.h"
129 #include "ui/gfx/color_utils.h"
130 #include "ui/gfx/geometry/rect_conversions.h"
131 #include "ui/gfx/screen.h"
132 #include "ui/strings/grit/ui_strings.h"
133 #include "ui/views/controls/button/menu_button.h"
134 #include "ui/views/controls/textfield/textfield.h"
135 #include "ui/views/controls/webview/webview.h"
136 #include "ui/views/focus/external_focus_tracker.h"
137 #include "ui/views/focus/view_storage.h"
138 #include "ui/views/layout/grid_layout.h"
139 #include "ui/views/widget/native_widget.h"
140 #include "ui/views/widget/root_view.h"
141 #include "ui/views/widget/widget.h"
142 #include "ui/views/window/dialog_delegate.h"
144 #if defined(USE_AURA)
145 #include "ui/aura/client/window_tree_client.h"
146 #include "ui/aura/window.h"
147 #include "ui/aura/window_tree_host.h"
148 #endif
150 #if defined(OS_WIN)
151 #include "base/win/windows_version.h"
152 #include "chrome/browser/jumplist_win.h"
153 #include "ui/views/win/scoped_fullscreen_visibility.h"
154 #endif
156 #if defined(ENABLE_ONE_CLICK_SIGNIN)
157 #include "chrome/browser/ui/sync/one_click_signin_bubble_delegate.h"
158 #include "chrome/browser/ui/sync/one_click_signin_bubble_links_delegate.h"
159 #include "chrome/browser/ui/views/sync/one_click_signin_bubble_view.h"
160 #endif
162 #if defined(OS_CHROMEOS)
163 #include "chrome/browser/ui/ash/multi_user/multi_user_window_manager.h"
164 #endif
166 using base::TimeDelta;
167 using base::UserMetricsAction;
168 using content::NativeWebKeyboardEvent;
169 using content::SSLStatus;
170 using content::WebContents;
171 using views::ColumnSet;
172 using views::GridLayout;
173 using web_modal::WebContentsModalDialogHost;
175 namespace {
177 // The name of a key to store on the window handle so that other code can
178 // locate this object using just the handle.
179 const char* const kBrowserViewKey = "__BROWSER_VIEW__";
181 // The number of milliseconds between loading animation frames.
182 const int kLoadingAnimationFrameTimeMs = 30;
184 // Paints the horizontal border separating the Bookmarks Bar from the Toolbar
185 // or page content according to |at_top| with |color|.
186 void PaintHorizontalBorder(gfx::Canvas* canvas,
187 BookmarkBarView* view,
188 bool at_top,
189 SkColor color) {
190 int thickness = views::NonClientFrameView::kClientEdgeThickness;
191 int y = at_top ? 0 : (view->height() - thickness);
192 canvas->FillRect(gfx::Rect(0, y, view->width(), thickness), color);
195 // TODO(kuan): These functions are temporarily for the bookmark bar while its
196 // detached state is at the top of the page; it'll be moved to float on the
197 // content page in the very near future, at which time, these local functions
198 // will be removed.
199 void PaintDetachedBookmarkBar(gfx::Canvas* canvas,
200 BookmarkBarView* view,
201 ThemeService* theme_service) {
202 // Paint background for detached state; if animating, this is fade in/out.
203 canvas->DrawColor(
204 chrome::GetDetachedBookmarkBarBackgroundColor(theme_service));
205 // Draw the separators above and below bookmark bar;
206 // if animating, these are fading in/out.
207 SkColor separator_color =
208 chrome::GetDetachedBookmarkBarSeparatorColor(theme_service);
209 PaintHorizontalBorder(canvas, view, true, separator_color);
210 // The bottom border needs to be 1-px thick in both regular and retina
211 // displays, so we can't use PaintHorizontalBorder which paints a 2-px thick
212 // border in retina display.
213 SkPaint paint;
214 paint.setAntiAlias(false);
215 // Sets border to 1-px thick regardless of scale factor.
216 paint.setStrokeWidth(0);
217 // Bottom border is at 50% opacity of top border.
218 paint.setColor(SkColorSetA(separator_color,
219 SkColorGetA(separator_color) / 2));
220 // Calculate thickness of bottom border as per current scale factor to
221 // determine where to draw the 1-px thick border.
222 float thickness = views::NonClientFrameView::kClientEdgeThickness /
223 canvas->image_scale();
224 SkScalar y = SkIntToScalar(view->height()) - SkFloatToScalar(thickness);
225 canvas->sk_canvas()->drawLine(SkIntToScalar(0), y,
226 SkIntToScalar(view->width()), y, paint);
229 // Paints the background (including the theme image behind content area) for
230 // the Bookmarks Bar when it is attached to the Toolbar into |bounds|.
231 // |background_origin| is the origin to use for painting the theme image.
232 void PaintBackgroundAttachedMode(gfx::Canvas* canvas,
233 ui::ThemeProvider* theme_provider,
234 const gfx::Rect& bounds,
235 const gfx::Point& background_origin,
236 chrome::HostDesktopType host_desktop_type) {
237 canvas->FillRect(bounds,
238 theme_provider->GetColor(ThemeProperties::COLOR_TOOLBAR));
239 canvas->TileImageInt(*theme_provider->GetImageSkiaNamed(IDR_THEME_TOOLBAR),
240 background_origin.x(),
241 background_origin.y(),
242 bounds.x(),
243 bounds.y(),
244 bounds.width(),
245 bounds.height());
247 if (host_desktop_type == chrome::HOST_DESKTOP_TYPE_ASH) {
248 // Ash provides additional lightening at the edges of the toolbar.
249 gfx::ImageSkia* toolbar_left =
250 theme_provider->GetImageSkiaNamed(IDR_TOOLBAR_SHADE_LEFT);
251 canvas->TileImageInt(*toolbar_left,
252 bounds.x(),
253 bounds.y(),
254 toolbar_left->width(),
255 bounds.height());
256 gfx::ImageSkia* toolbar_right =
257 theme_provider->GetImageSkiaNamed(IDR_TOOLBAR_SHADE_RIGHT);
258 canvas->TileImageInt(*toolbar_right,
259 bounds.right() - toolbar_right->width(),
260 bounds.y(),
261 toolbar_right->width(),
262 bounds.height());
266 void PaintAttachedBookmarkBar(gfx::Canvas* canvas,
267 BookmarkBarView* view,
268 BrowserView* browser_view,
269 chrome::HostDesktopType host_desktop_type,
270 int toolbar_overlap) {
271 // Paint background for attached state, this is fade in/out.
272 gfx::Point background_image_offset =
273 browser_view->OffsetPointForToolbarBackgroundImage(
274 gfx::Point(view->GetMirroredX(), view->y()));
275 PaintBackgroundAttachedMode(canvas,
276 view->GetThemeProvider(),
277 view->GetLocalBounds(),
278 background_image_offset,
279 host_desktop_type);
280 if (view->height() >= toolbar_overlap) {
281 // Draw the separator below the Bookmarks Bar; this is fading in/out.
282 PaintHorizontalBorder(canvas,
283 view,
284 false,
285 ThemeProperties::GetDefaultColor(
286 ThemeProperties::COLOR_TOOLBAR_SEPARATOR));
290 } // namespace
292 ///////////////////////////////////////////////////////////////////////////////
293 // Delegate implementation for BrowserViewLayout. Usually just forwards calls
294 // into BrowserView.
295 class BrowserViewLayoutDelegateImpl : public BrowserViewLayoutDelegate {
296 public:
297 explicit BrowserViewLayoutDelegateImpl(BrowserView* browser_view)
298 : browser_view_(browser_view) {}
299 ~BrowserViewLayoutDelegateImpl() override {}
301 // BrowserViewLayoutDelegate overrides:
302 views::View* GetContentsWebView() const override {
303 return browser_view_->contents_web_view_;
306 bool DownloadShelfNeedsLayout() const override {
307 DownloadShelfView* download_shelf = browser_view_->download_shelf_.get();
308 // Re-layout the shelf either if it is visible or if its close animation
309 // is currently running.
310 return download_shelf &&
311 (download_shelf->IsShowing() || download_shelf->IsClosing());
314 bool IsTabStripVisible() const override {
315 return browser_view_->IsTabStripVisible();
318 gfx::Rect GetBoundsForTabStripInBrowserView() const override {
319 gfx::RectF bounds_f(browser_view_->frame()->GetBoundsForTabStrip(
320 browser_view_->tabstrip()));
321 views::View::ConvertRectToTarget(browser_view_->parent(), browser_view_,
322 &bounds_f);
323 return gfx::ToEnclosingRect(bounds_f);
326 int GetTopInsetInBrowserView() const override {
327 return browser_view_->frame()->GetTopInset() -
328 browser_view_->y();
331 int GetThemeBackgroundXInset() const override {
332 // TODO(pkotwicz): Return the inset with respect to the left edge of the
333 // BrowserView.
334 return browser_view_->frame()->GetThemeBackgroundXInset();
337 bool IsToolbarVisible() const override {
338 return browser_view_->IsToolbarVisible();
341 bool IsBookmarkBarVisible() const override {
342 return browser_view_->IsBookmarkBarVisible();
345 ExclusiveAccessBubbleViews* GetExclusiveAccessBubble() const override {
346 return browser_view_->exclusive_access_bubble();
349 private:
350 BrowserView* browser_view_;
352 DISALLOW_COPY_AND_ASSIGN(BrowserViewLayoutDelegateImpl);
355 // This class is used to paint the background for Bookmarks Bar.
356 class BookmarkBarViewBackground : public views::Background {
357 public:
358 BookmarkBarViewBackground(BrowserView* browser_view,
359 BookmarkBarView* bookmark_bar_view,
360 Browser* browser);
362 // views:Background:
363 void Paint(gfx::Canvas* canvas, views::View* view) const override;
365 private:
366 BrowserView* browser_view_;
368 // The view hosting this background.
369 BookmarkBarView* bookmark_bar_view_;
371 Browser* browser_;
373 DISALLOW_COPY_AND_ASSIGN(BookmarkBarViewBackground);
376 BookmarkBarViewBackground::BookmarkBarViewBackground(
377 BrowserView* browser_view,
378 BookmarkBarView* bookmark_bar_view,
379 Browser* browser)
380 : browser_view_(browser_view),
381 bookmark_bar_view_(bookmark_bar_view),
382 browser_(browser) {
385 void BookmarkBarViewBackground::Paint(gfx::Canvas* canvas,
386 views::View* view) const {
387 int toolbar_overlap = bookmark_bar_view_->GetToolbarOverlap();
388 if (!bookmark_bar_view_->IsDetached()) {
389 PaintAttachedBookmarkBar(canvas,
390 bookmark_bar_view_,
391 browser_view_,
392 browser_->host_desktop_type(),
393 toolbar_overlap);
394 return;
397 // As 'hidden' according to the animation is the full in-tab state, we invert
398 // the value - when current_state is at '0', we expect the bar to be docked.
399 double current_state = 1 - bookmark_bar_view_->GetAnimationValue();
401 ThemeService* ts = ThemeServiceFactory::GetForProfile(browser_->profile());
402 if (current_state == 0.0 || current_state == 1.0) {
403 PaintDetachedBookmarkBar(canvas, bookmark_bar_view_, ts);
404 return;
406 // While animating, set opacity to cross-fade between attached and detached
407 // backgrounds including their respective separators.
408 int detached_alpha = static_cast<uint8>(current_state * 255);
409 int attached_alpha = 255 - detached_alpha;
410 if (browser_->bookmark_bar_state() == BookmarkBar::DETACHED) {
411 // To animate from attached to detached state:
412 // - fade out attached background
413 // - fade in detached background.
414 canvas->SaveLayerAlpha(attached_alpha);
415 PaintAttachedBookmarkBar(canvas,
416 bookmark_bar_view_,
417 browser_view_,
418 browser_->host_desktop_type(),
419 toolbar_overlap);
420 canvas->Restore();
421 canvas->SaveLayerAlpha(detached_alpha);
422 PaintDetachedBookmarkBar(canvas, bookmark_bar_view_, ts);
423 } else {
424 // To animate from detached to attached state:
425 // - fade out detached background
426 // - fade in attached background.
427 canvas->SaveLayerAlpha(detached_alpha);
428 PaintDetachedBookmarkBar(canvas, bookmark_bar_view_, ts);
429 canvas->Restore();
430 canvas->SaveLayerAlpha(attached_alpha);
431 PaintAttachedBookmarkBar(canvas,
432 bookmark_bar_view_,
433 browser_view_,
434 browser_->host_desktop_type(),
435 toolbar_overlap);
437 canvas->Restore();
440 ///////////////////////////////////////////////////////////////////////////////
441 // BrowserView, public:
443 // static
444 const char BrowserView::kViewClassName[] = "BrowserView";
446 BrowserView::BrowserView()
447 : views::ClientView(nullptr, nullptr),
448 last_focused_view_storage_id_(
449 views::ViewStorage::GetInstance()->CreateStorageID()),
450 frame_(nullptr),
451 top_container_(nullptr),
452 tabstrip_(nullptr),
453 toolbar_(nullptr),
454 find_bar_host_view_(nullptr),
455 infobar_container_(nullptr),
456 contents_web_view_(nullptr),
457 contents_container_(nullptr),
458 initialized_(false),
459 in_process_fullscreen_(false),
460 #if defined(OS_WIN)
461 hung_window_detector_(&hung_plugin_action_),
462 ticker_(0),
463 #endif
464 force_location_bar_focus_(false),
465 activate_modal_dialog_factory_(this) {
468 BrowserView::~BrowserView() {
469 // All the tabs should have been destroyed already. If we were closed by the
470 // OS with some tabs than the NativeBrowserFrame should have destroyed them.
471 DCHECK_EQ(0, browser_->tab_strip_model()->count());
473 // Immersive mode may need to reparent views before they are removed/deleted.
474 immersive_mode_controller_.reset();
476 browser_->tab_strip_model()->RemoveObserver(this);
478 #if defined(OS_WIN)
479 // Stop hung plugin monitoring.
480 ticker_.Stop();
481 ticker_.UnregisterTickHandler(&hung_window_detector_);
483 // Terminate the jumplist (must be called before browser_->profile() is
484 // destroyed.
485 if (jumplist_.get()) {
486 jumplist_->Terminate();
488 #endif
490 // We destroy the download shelf before |browser_| to remove its child
491 // download views from the set of download observers (since the observed
492 // downloads can be destroyed along with |browser_| and the observer
493 // notifications will call back into deleted objects).
494 BrowserViewLayout* browser_view_layout = GetBrowserViewLayout();
495 if (browser_view_layout)
496 browser_view_layout->set_download_shelf(nullptr);
497 download_shelf_.reset();
499 // The TabStrip attaches a listener to the model. Make sure we shut down the
500 // TabStrip first so that it can cleanly remove the listener.
501 if (tabstrip_) {
502 tabstrip_->parent()->RemoveChildView(tabstrip_);
503 if (browser_view_layout)
504 browser_view_layout->set_tab_strip(nullptr);
505 delete tabstrip_;
506 tabstrip_ = nullptr;
508 // Child views maintain PrefMember attributes that point to
509 // OffTheRecordProfile's PrefService which gets deleted by ~Browser.
510 RemoveAllChildViews(true);
511 toolbar_ = nullptr;
513 // Explicitly set browser_ to null.
514 browser_.reset();
517 void BrowserView::Init(Browser* browser) {
518 browser_.reset(browser);
519 browser_->tab_strip_model()->AddObserver(this);
520 immersive_mode_controller_.reset(
521 chrome::CreateImmersiveModeController(browser_->host_desktop_type()));
524 // static
525 BrowserView* BrowserView::GetBrowserViewForNativeWindow(
526 gfx::NativeWindow window) {
527 views::Widget* widget = views::Widget::GetWidgetForNativeWindow(window);
528 return widget ?
529 reinterpret_cast<BrowserView*>(widget->GetNativeWindowProperty(
530 kBrowserViewKey)) : nullptr;
533 // static
534 BrowserView* BrowserView::GetBrowserViewForBrowser(const Browser* browser) {
535 return static_cast<BrowserView*>(browser->window());
538 void BrowserView::InitStatusBubble() {
539 status_bubble_.reset(new StatusBubbleViews(contents_web_view_));
540 contents_web_view_->SetStatusBubble(status_bubble_.get());
543 gfx::Rect BrowserView::GetToolbarBounds() const {
544 gfx::Rect toolbar_bounds(toolbar_->bounds());
545 if (toolbar_bounds.IsEmpty())
546 return toolbar_bounds;
547 // The apparent toolbar edges are outside the "real" toolbar edges.
548 toolbar_bounds.Inset(-views::NonClientFrameView::kClientEdgeThickness, 0);
549 return toolbar_bounds;
552 gfx::Rect BrowserView::GetFindBarBoundingBox() const {
553 return GetBrowserViewLayout()->GetFindBarBoundingBox();
556 int BrowserView::GetTabStripHeight() const {
557 // We want to return tabstrip_->height(), but we might be called in the midst
558 // of layout, when that hasn't yet been updated to reflect the current state.
559 // So return what the tabstrip height _ought_ to be right now.
560 return IsTabStripVisible() ? tabstrip_->GetPreferredSize().height() : 0;
563 gfx::Point BrowserView::OffsetPointForToolbarBackgroundImage(
564 const gfx::Point& point) const {
565 // The background image starts tiling horizontally at the window left edge and
566 // vertically at the top edge of the horizontal tab strip (or where it would
567 // be). We expect our parent's origin to be the window origin.
568 gfx::Point window_point(point + GetMirroredPosition().OffsetFromOrigin());
569 window_point.Offset(frame_->GetThemeBackgroundXInset(),
570 -frame_->GetTopInset());
571 return window_point;
574 bool BrowserView::IsTabStripVisible() const {
575 if (immersive_mode_controller_->ShouldHideTopViews() &&
576 immersive_mode_controller_->ShouldHideTabIndicators())
577 return false;
578 return browser_->SupportsWindowFeature(Browser::FEATURE_TABSTRIP);
581 bool BrowserView::IsOffTheRecord() const {
582 return browser_->profile()->IsOffTheRecord();
585 bool BrowserView::IsGuestSession() const {
586 return browser_->profile()->IsGuestSession();
589 bool BrowserView::IsRegularOrGuestSession() const {
590 return profiles::IsRegularOrGuestSession(browser_.get());
593 bool BrowserView::ShouldShowAvatar() const {
594 #if defined(OS_CHROMEOS)
595 if (!browser_->is_type_tabbed() && !browser_->is_app())
596 return false;
597 // Don't show incognito avatar in the guest session.
598 if (IsOffTheRecord() && !IsGuestSession())
599 return true;
600 // This function is called via BrowserNonClientFrameView::UpdateAvatarInfo
601 // during the creation of the BrowserWindow, so browser->window() will not
602 // yet be set. In this case we can safely return false.
603 if (!browser_->window())
604 return false;
605 return chrome::MultiUserWindowManager::ShouldShowAvatar(
606 browser_->window()->GetNativeWindow());
607 #else
608 if (!IsBrowserTypeNormal())
609 return false;
610 if (IsOffTheRecord()) // Desktop guest is incognito and needs avatar.
611 return true;
612 // Tests may not have a profile manager.
613 if (!g_browser_process->profile_manager())
614 return false;
615 ProfileInfoCache& cache =
616 g_browser_process->profile_manager()->GetProfileInfoCache();
617 if (cache.GetIndexOfProfileWithPath(browser_->profile()->GetPath()) ==
618 std::string::npos) {
619 return false;
622 return AvatarMenu::ShouldShowAvatarMenu();
623 #endif
626 bool BrowserView::GetAccelerator(int cmd_id,
627 ui::Accelerator* accelerator) const {
628 // We retrieve the accelerator information for standard accelerators
629 // for cut, copy and paste.
630 if (chrome::GetStandardAcceleratorForCommandId(cmd_id, accelerator))
631 return true;
632 // Else, we retrieve the accelerator information from the accelerator table.
633 for (std::map<ui::Accelerator, int>::const_iterator it =
634 accelerator_table_.begin(); it != accelerator_table_.end(); ++it) {
635 if (it->second == cmd_id) {
636 *accelerator = it->first;
637 return true;
640 // Else, we retrieve the accelerator information from Ash (if applicable).
641 return chrome::GetAshAcceleratorForCommandId(
642 cmd_id, browser_->host_desktop_type(), accelerator);
645 bool BrowserView::IsAcceleratorRegistered(const ui::Accelerator& accelerator) {
646 return accelerator_table_.find(accelerator) != accelerator_table_.end();
649 WebContents* BrowserView::GetActiveWebContents() const {
650 return browser_->tab_strip_model()->GetActiveWebContents();
653 gfx::ImageSkia BrowserView::GetOTRAvatarIcon() const {
654 return *GetThemeProvider()->GetImageSkiaNamed(IDR_OTR_ICON);
657 ///////////////////////////////////////////////////////////////////////////////
658 // BrowserView, BrowserWindow implementation:
660 void BrowserView::Show() {
661 #if !defined(OS_WIN)
662 // The Browser associated with this browser window must become the active
663 // browser at the time |Show()| is called. This is the natural behavior under
664 // Windows and Ash, but other platforms will not trigger
665 // OnWidgetActivationChanged() until we return to the runloop. Therefore any
666 // calls to Browser::GetLastActive() will return the wrong result if we do not
667 // explicitly set it here.
668 // A similar block also appears in BrowserWindowCocoa::Show().
669 if (browser()->host_desktop_type() != chrome::HOST_DESKTOP_TYPE_ASH)
670 BrowserList::SetLastActive(browser());
671 #endif
673 // If the window is already visible, just activate it.
674 if (frame_->IsVisible()) {
675 frame_->Activate();
676 return;
679 // Showing the window doesn't make the browser window active right away.
680 // This can cause SetFocusToLocationBar() to skip setting focus to the
681 // location bar. To avoid this we explicilty let SetFocusToLocationBar()
682 // know that it's ok to steal focus.
683 force_location_bar_focus_ = true;
685 // Setting the focus doesn't work when the window is invisible, so any focus
686 // initialization that happened before this will be lost.
688 // We really "should" restore the focus whenever the window becomes unhidden,
689 // but I think initializing is the only time where this can happen where
690 // there is some focus change we need to pick up, and this is easier than
691 // plumbing through an un-hide message all the way from the frame.
693 // If we do find there are cases where we need to restore the focus on show,
694 // that should be added and this should be removed.
695 RestoreFocus();
697 frame_->Show();
699 force_location_bar_focus_ = false;
701 browser()->OnWindowDidShow();
703 chrome::MaybeShowInvertBubbleView(this);
706 void BrowserView::ShowInactive() {
707 if (!frame_->IsVisible())
708 frame_->ShowInactive();
711 void BrowserView::Hide() {
712 // Not implemented.
715 void BrowserView::SetBounds(const gfx::Rect& bounds) {
716 ExitFullscreen();
717 GetWidget()->SetBounds(bounds);
720 void BrowserView::Close() {
721 frame_->Close();
724 void BrowserView::Activate() {
725 frame_->Activate();
728 void BrowserView::Deactivate() {
729 frame_->Deactivate();
732 bool BrowserView::IsActive() const {
733 return frame_->IsActive();
736 void BrowserView::FlashFrame(bool flash) {
737 frame_->FlashFrame(flash);
740 bool BrowserView::IsAlwaysOnTop() const {
741 return false;
744 void BrowserView::SetAlwaysOnTop(bool always_on_top) {
745 // Not implemented for browser windows.
746 NOTIMPLEMENTED();
749 gfx::NativeWindow BrowserView::GetNativeWindow() const {
750 // While the browser destruction is going on, the widget can already be gone,
751 // but utility functions like FindBrowserWithWindow will come here and crash.
752 // We short circuit therefore.
753 if (!GetWidget())
754 return nullptr;
755 return GetWidget()->GetTopLevelWidget()->GetNativeWindow();
758 StatusBubble* BrowserView::GetStatusBubble() {
759 return status_bubble_.get();
762 namespace {
763 // Only used by ToolbarSizeChanged() below, but placed here because template
764 // arguments (to base::AutoReset<>) must have external linkage.
765 enum CallState { NORMAL, REENTRANT, REENTRANT_FORCE_FAST_RESIZE };
768 void BrowserView::UpdateTitleBar() {
769 // TODO(robliao): Remove ScopedTracker below once https://crbug.com/467185 is
770 // fixed.
771 tracked_objects::ScopedTracker tracking_profile1(
772 FROM_HERE_WITH_EXPLICIT_FUNCTION("467185 BrowserView::UpdateTitleBar1"));
773 frame_->UpdateWindowTitle();
774 if (ShouldShowWindowIcon() && !loading_animation_timer_.IsRunning()) {
775 // TODO(robliao): Remove ScopedTracker below once https://crbug.com/467185
776 // is fixed.
777 tracked_objects::ScopedTracker tracking_profile2(
778 FROM_HERE_WITH_EXPLICIT_FUNCTION(
779 "467185 BrowserView::UpdateTitleBar2"));
780 frame_->UpdateWindowIcon();
784 void BrowserView::BookmarkBarStateChanged(
785 BookmarkBar::AnimateChangeType change_type) {
786 if (bookmark_bar_view_.get()) {
787 BookmarkBar::State new_state = browser_->bookmark_bar_state();
789 // We don't properly support animating the bookmark bar to and from the
790 // detached state in immersive fullscreen.
791 bool detached_changed = (new_state == BookmarkBar::DETACHED) ||
792 bookmark_bar_view_->IsDetached();
793 if (detached_changed && immersive_mode_controller_->IsEnabled())
794 change_type = BookmarkBar::DONT_ANIMATE_STATE_CHANGE;
796 bookmark_bar_view_->SetBookmarkBarState(new_state, change_type);
798 if (MaybeShowBookmarkBar(GetActiveWebContents()))
799 Layout();
802 void BrowserView::UpdateDevTools() {
803 UpdateDevToolsForContents(GetActiveWebContents(), true);
804 Layout();
807 void BrowserView::UpdateLoadingAnimations(bool should_animate) {
808 if (should_animate) {
809 if (!loading_animation_timer_.IsRunning()) {
810 // Loads are happening, and the timer isn't running, so start it.
811 last_animation_time_ = base::TimeTicks::Now();
812 loading_animation_timer_.Start(FROM_HERE,
813 TimeDelta::FromMilliseconds(kLoadingAnimationFrameTimeMs), this,
814 &BrowserView::LoadingAnimationCallback);
816 } else {
817 if (loading_animation_timer_.IsRunning()) {
818 last_animation_time_ = base::TimeTicks();
819 loading_animation_timer_.Stop();
820 // Loads are now complete, update the state if a task was scheduled.
821 LoadingAnimationCallback();
826 void BrowserView::SetStarredState(bool is_starred) {
827 GetLocationBarView()->SetStarToggled(is_starred);
830 void BrowserView::SetTranslateIconToggled(bool is_lit) {
831 GetLocationBarView()->SetTranslateIconToggled(is_lit);
834 void BrowserView::OnActiveTabChanged(content::WebContents* old_contents,
835 content::WebContents* new_contents,
836 int index,
837 int reason) {
838 DCHECK(new_contents);
840 // If |contents_container_| already has the correct WebContents, we can save
841 // some work. This also prevents extra events from being reported by the
842 // Visibility API under Windows, as ChangeWebContents will briefly hide
843 // the WebContents window.
844 bool change_tab_contents =
845 contents_web_view_->web_contents() != new_contents;
847 // Update various elements that are interested in knowing the current
848 // WebContents.
850 // When we toggle the NTP floating bookmarks bar and/or the info bar,
851 // we don't want any WebContents to be attached, so that we
852 // avoid an unnecessary resize and re-layout of a WebContents.
853 if (change_tab_contents) {
854 contents_web_view_->SetWebContents(nullptr);
855 devtools_web_view_->SetWebContents(nullptr);
858 // Do this before updating InfoBarContainer as the InfoBarContainer may
859 // callback to us and trigger layout.
860 if (bookmark_bar_view_.get()) {
861 bookmark_bar_view_->SetBookmarkBarState(
862 browser_->bookmark_bar_state(),
863 BookmarkBar::DONT_ANIMATE_STATE_CHANGE);
866 infobar_container_->ChangeInfoBarManager(
867 InfoBarService::FromWebContents(new_contents));
869 if (old_contents && PermissionBubbleManager::FromWebContents(old_contents))
870 PermissionBubbleManager::FromWebContents(old_contents)->SetView(nullptr);
872 if (new_contents && PermissionBubbleManager::FromWebContents(new_contents)) {
873 if (!permission_bubble_.get())
874 permission_bubble_.reset(new PermissionBubbleViewViews(browser_.get()));
876 PermissionBubbleManager::FromWebContents(new_contents)->SetView(
877 permission_bubble_.get());
880 UpdateUIForContents(new_contents);
882 // Layout for DevTools _before_ setting the both main and devtools WebContents
883 // to avoid toggling the size of any of them.
884 UpdateDevToolsForContents(new_contents, !change_tab_contents);
886 if (change_tab_contents) {
887 web_contents_close_handler_->ActiveTabChanged();
888 contents_web_view_->SetWebContents(new_contents);
889 // The second layout update should be no-op. It will just set the
890 // DevTools WebContents.
891 UpdateDevToolsForContents(new_contents, true);
894 if (!browser_->tab_strip_model()->closing_all() && GetWidget()->IsActive() &&
895 GetWidget()->IsVisible()) {
896 // We only restore focus if our window is visible, to avoid invoking blur
897 // handlers when we are eventually shown.
898 new_contents->RestoreFocus();
901 // Update all the UI bits.
902 UpdateTitleBar();
904 TranslateBubbleView::CloseBubble();
905 ZoomBubbleView::CloseBubble();
908 void BrowserView::ZoomChangedForActiveTab(bool can_show_bubble) {
909 GetLocationBarView()->ZoomChangedForActiveTab(
910 can_show_bubble && !toolbar_->IsWrenchMenuShowing());
913 gfx::Rect BrowserView::GetRestoredBounds() const {
914 gfx::Rect bounds;
915 ui::WindowShowState state;
916 frame_->GetWindowPlacement(&bounds, &state);
917 return bounds;
920 ui::WindowShowState BrowserView::GetRestoredState() const {
921 gfx::Rect bounds;
922 ui::WindowShowState state;
923 frame_->GetWindowPlacement(&bounds, &state);
924 return state;
927 gfx::Rect BrowserView::GetBounds() const {
928 return frame_->GetWindowBoundsInScreen();
931 bool BrowserView::IsMaximized() const {
932 return frame_->IsMaximized();
935 bool BrowserView::IsMinimized() const {
936 return frame_->IsMinimized();
939 void BrowserView::Maximize() {
940 frame_->Maximize();
943 void BrowserView::Minimize() {
944 frame_->Minimize();
947 void BrowserView::Restore() {
948 frame_->Restore();
951 void BrowserView::EnterFullscreen(const GURL& url,
952 ExclusiveAccessBubbleType bubble_type,
953 bool with_toolbar) {
954 if (IsFullscreen())
955 return; // Nothing to do.
957 ProcessFullscreen(true, NORMAL_FULLSCREEN, url, bubble_type);
960 void BrowserView::ExitFullscreen() {
961 if (!IsFullscreen())
962 return; // Nothing to do.
964 ProcessFullscreen(false, NORMAL_FULLSCREEN, GURL(),
965 EXCLUSIVE_ACCESS_BUBBLE_TYPE_NONE);
968 void BrowserView::UpdateExclusiveAccessExitBubbleContent(
969 const GURL& url,
970 ExclusiveAccessBubbleType bubble_type) {
971 // Immersive mode has no exit bubble because it has a visible strip at the
972 // top that gives the user a hover target.
973 // TODO(jamescook): Figure out what to do with mouse-lock.
974 if (bubble_type == EXCLUSIVE_ACCESS_BUBBLE_TYPE_NONE ||
975 ShouldUseImmersiveFullscreenForUrl(url)) {
976 exclusive_access_bubble_.reset();
977 } else if (exclusive_access_bubble_.get()) {
978 exclusive_access_bubble_->UpdateContent(url, bubble_type);
979 } else {
980 exclusive_access_bubble_.reset(
981 new ExclusiveAccessBubbleViews(this, url, bubble_type));
985 bool BrowserView::ShouldHideUIForFullscreen() const {
986 // Immersive mode needs UI for the slide-down top panel.
987 if (immersive_mode_controller_->IsEnabled())
988 return false;
990 return IsFullscreen();
993 bool BrowserView::IsFullscreen() const {
994 return frame_->IsFullscreen();
997 bool BrowserView::IsFullscreenBubbleVisible() const {
998 return exclusive_access_bubble_ != nullptr;
1001 bool BrowserView::SupportsFullscreenWithToolbar() const {
1002 return false;
1005 void BrowserView::UpdateFullscreenWithToolbar(bool with_toolbar) {
1006 // This is currently a Mac only feature.
1007 NOTIMPLEMENTED();
1010 bool BrowserView::IsFullscreenWithToolbar() const {
1011 return false;
1014 #if defined(OS_WIN)
1015 void BrowserView::SetMetroSnapMode(bool enable) {
1016 LOCAL_HISTOGRAM_COUNTS("Metro.SnapModeToggle", enable);
1017 ProcessFullscreen(enable, METRO_SNAP_FULLSCREEN, GURL(),
1018 EXCLUSIVE_ACCESS_BUBBLE_TYPE_NONE);
1021 bool BrowserView::IsInMetroSnapMode() const {
1022 return false;
1024 #endif // defined(OS_WIN)
1026 void BrowserView::RestoreFocus() {
1027 WebContents* selected_web_contents = GetActiveWebContents();
1028 if (selected_web_contents)
1029 selected_web_contents->RestoreFocus();
1032 void BrowserView::FullscreenStateChanged() {
1033 CHECK(!IsFullscreen());
1034 ProcessFullscreen(false, NORMAL_FULLSCREEN, GURL(),
1035 EXCLUSIVE_ACCESS_BUBBLE_TYPE_NONE);
1038 LocationBar* BrowserView::GetLocationBar() const {
1039 return GetLocationBarView();
1042 void BrowserView::SetFocusToLocationBar(bool select_all) {
1043 // On Windows, changing focus to the location bar causes the browser
1044 // window to become active. This can steal focus if the user has
1045 // another window open already. On ChromeOS, changing focus makes a
1046 // view believe it has a focus even if the widget doens't have a
1047 // focus. Either cases, we need to ignore this when the browser
1048 // window isn't active.
1049 if (!force_location_bar_focus_ && !IsActive())
1050 return;
1052 // Temporarily reveal the top-of-window views (if not already revealed) so
1053 // that the location bar view is visible and is considered focusable. If the
1054 // location bar view gains focus, |immersive_mode_controller_| will keep the
1055 // top-of-window views revealed.
1056 scoped_ptr<ImmersiveRevealedLock> focus_reveal_lock(
1057 immersive_mode_controller_->GetRevealedLock(
1058 ImmersiveModeController::ANIMATE_REVEAL_YES));
1060 LocationBarView* location_bar = GetLocationBarView();
1061 if (location_bar->omnibox_view()->IsFocusable()) {
1062 // Location bar got focus.
1063 location_bar->FocusLocation(select_all);
1064 } else {
1065 // If none of location bar got focus, then clear focus.
1066 views::FocusManager* focus_manager = GetFocusManager();
1067 DCHECK(focus_manager);
1068 focus_manager->ClearFocus();
1072 void BrowserView::UpdateReloadStopState(bool is_loading, bool force) {
1073 toolbar_->reload_button()->ChangeMode(
1074 is_loading ? ReloadButton::MODE_STOP : ReloadButton::MODE_RELOAD, force);
1077 void BrowserView::UpdateToolbar(content::WebContents* contents) {
1078 // We may end up here during destruction.
1079 if (toolbar_)
1080 toolbar_->Update(contents);
1081 frame_->UpdateToolbar();
1084 void BrowserView::ResetToolbarTabState(content::WebContents* contents) {
1085 // We may end up here during destruction.
1086 if (toolbar_)
1087 toolbar_->ResetTabState(contents);
1090 void BrowserView::FocusToolbar() {
1091 // Temporarily reveal the top-of-window views (if not already revealed) so
1092 // that the toolbar is visible and is considered focusable. If the
1093 // toolbar gains focus, |immersive_mode_controller_| will keep the
1094 // top-of-window views revealed.
1095 scoped_ptr<ImmersiveRevealedLock> focus_reveal_lock(
1096 immersive_mode_controller_->GetRevealedLock(
1097 ImmersiveModeController::ANIMATE_REVEAL_YES));
1099 // Start the traversal within the main toolbar. SetPaneFocus stores
1100 // the current focused view before changing focus.
1101 toolbar_->SetPaneFocus(nullptr);
1104 void BrowserView::ToolbarSizeChanged(bool is_animating) {
1105 // The call to SetMaxTopArrowHeight() below can result in reentrancy;
1106 // |call_state| tracks whether we're reentrant. We can't just early-return in
1107 // this case because we need to layout again so the infobar container's bounds
1108 // are set correctly.
1109 static CallState call_state = NORMAL;
1111 // A reentrant call can (and should) use the fast resize path unless both it
1112 // and the normal call are both non-animating.
1113 bool use_fast_resize =
1114 is_animating || (call_state == REENTRANT_FORCE_FAST_RESIZE);
1115 if (use_fast_resize)
1116 contents_web_view_->SetFastResize(true);
1117 UpdateUIForContents(GetActiveWebContents());
1118 if (use_fast_resize)
1119 contents_web_view_->SetFastResize(false);
1121 // Inform the InfoBarContainer that the distance to the location icon may have
1122 // changed. We have to do this after the block above so that the toolbars are
1123 // laid out correctly for calculating the maximum arrow height below.
1125 base::AutoReset<CallState> resetter(&call_state,
1126 is_animating ? REENTRANT_FORCE_FAST_RESIZE : REENTRANT);
1127 SetMaxTopArrowHeight(GetMaxTopInfoBarArrowHeight(), infobar_container_);
1130 // When transitioning from animating to not animating we need to make sure the
1131 // contents_container_ gets layed out. If we don't do this and the bounds
1132 // haven't changed contents_container_ won't get a Layout out and we'll end up
1133 // with a gray rect because the clip wasn't updated. Note that a reentrant
1134 // call never needs to do this, because after it returns, the normal call
1135 // wrapping it will do it.
1136 if ((call_state == NORMAL) && !is_animating) {
1137 contents_web_view_->InvalidateLayout();
1138 contents_container_->Layout();
1142 void BrowserView::FocusBookmarksToolbar() {
1143 DCHECK(!immersive_mode_controller_->IsEnabled());
1144 if (bookmark_bar_view_.get() &&
1145 bookmark_bar_view_->visible() &&
1146 bookmark_bar_view_->GetPreferredSize().height() != 0) {
1147 bookmark_bar_view_->SetPaneFocusAndFocusDefault();
1151 void BrowserView::FocusInfobars() {
1152 if (infobar_container_->child_count() > 0)
1153 infobar_container_->SetPaneFocusAndFocusDefault();
1156 void BrowserView::FocusAppMenu() {
1157 // Chrome doesn't have a traditional menu bar, but it has a menu button in the
1158 // main toolbar that plays the same role. If the user presses a key that
1159 // would typically focus the menu bar, tell the toolbar to focus the menu
1160 // button. If the user presses the key again, return focus to the previous
1161 // location.
1163 // Not used on the Mac, which has a normal menu bar.
1164 if (toolbar_->IsAppMenuFocused()) {
1165 RestoreFocus();
1166 } else {
1167 DCHECK(!immersive_mode_controller_->IsEnabled());
1168 toolbar_->SetPaneFocusAndFocusAppMenu();
1172 void BrowserView::RotatePaneFocus(bool forwards) {
1173 GetWidget()->GetFocusManager()->RotatePaneFocus(
1174 forwards ?
1175 views::FocusManager::kForward : views::FocusManager::kBackward,
1176 views::FocusManager::kWrap);
1179 void BrowserView::DestroyBrowser() {
1180 // After this returns other parts of Chrome are going to be shutdown. Close
1181 // the window now so that we are deleted immediately and aren't left holding
1182 // references to deleted objects.
1183 GetWidget()->RemoveObserver(this);
1184 GetLocationBar()->GetOmniboxView()->model()->popup_model()->RemoveObserver(
1185 this);
1186 frame_->CloseNow();
1189 bool BrowserView::IsBookmarkBarVisible() const {
1190 if (!browser_->SupportsWindowFeature(Browser::FEATURE_BOOKMARKBAR))
1191 return false;
1192 if (!bookmark_bar_view_.get())
1193 return false;
1194 if (bookmark_bar_view_->GetPreferredSize().height() == 0)
1195 return false;
1196 // New tab page needs visible bookmarks even when top-views are hidden.
1197 if (immersive_mode_controller_->ShouldHideTopViews() &&
1198 !bookmark_bar_view_->IsDetached())
1199 return false;
1200 return true;
1203 bool BrowserView::IsBookmarkBarAnimating() const {
1204 return bookmark_bar_view_.get() && bookmark_bar_view_->is_animating();
1207 bool BrowserView::IsTabStripEditable() const {
1208 return tabstrip_->IsTabStripEditable();
1211 bool BrowserView::IsToolbarVisible() const {
1212 if (immersive_mode_controller_->ShouldHideTopViews())
1213 return false;
1214 return browser_->SupportsWindowFeature(Browser::FEATURE_TOOLBAR) ||
1215 browser_->SupportsWindowFeature(Browser::FEATURE_LOCATIONBAR);
1218 gfx::Rect BrowserView::GetRootWindowResizerRect() const {
1219 // Views does not support resizer rects because they caused page cycler
1220 // performance regressions when they were added. See crrev.com/9654
1221 return gfx::Rect();
1224 void BrowserView::ConfirmAddSearchProvider(TemplateURL* template_url,
1225 Profile* profile) {
1226 chrome::EditSearchEngine(GetWidget()->GetNativeWindow(), template_url,
1227 nullptr, profile);
1230 void BrowserView::ShowUpdateChromeDialog() {
1231 UpdateRecommendedMessageBox::Show(GetWidget()->GetNativeWindow());
1234 void BrowserView::ShowBookmarkBubble(const GURL& url, bool already_bookmarked) {
1235 scoped_ptr<BookmarkBubbleDelegate> delegate;
1236 delegate.reset(new BookmarkBubbleSignInDelegate(browser_.get()));
1238 BookmarkBubbleView::ShowBubble(GetToolbarView()->GetBookmarkBubbleAnchor(),
1239 bookmark_bar_view_.get(),
1240 delegate.Pass(),
1241 browser_->profile(),
1242 url,
1243 !already_bookmarked);
1246 void BrowserView::ShowBookmarkAppBubble(
1247 const WebApplicationInfo& web_app_info,
1248 const ShowBookmarkAppBubbleCallback& callback) {
1249 BookmarkAppBubbleView::ShowBubble(GetToolbarView(), web_app_info, callback);
1252 void BrowserView::ShowTranslateBubble(
1253 content::WebContents* web_contents,
1254 translate::TranslateStep step,
1255 translate::TranslateErrors::Type error_type,
1256 bool is_user_gesture) {
1257 if (contents_web_view_->HasFocus() &&
1258 !GetLocationBarView()->IsMouseHovered()) {
1259 content::RenderViewHost* rvh = web_contents->GetRenderViewHost();
1260 if (rvh->IsFocusedElementEditable())
1261 return;
1264 ChromeTranslateClient* chrome_translate_client =
1265 ChromeTranslateClient::FromWebContents(web_contents);
1266 translate::LanguageState& language_state =
1267 chrome_translate_client->GetLanguageState();
1268 language_state.SetTranslateEnabled(true);
1270 if (IsMinimized())
1271 return;
1273 TranslateBubbleView::ShowBubble(
1274 GetToolbarView()->GetTranslateBubbleAnchor(), web_contents, step,
1275 error_type, is_user_gesture);
1278 bool BrowserView::ShowSessionCrashedBubble() {
1279 return SessionCrashedBubbleView::Show(browser_.get());
1282 bool BrowserView::IsProfileResetBubbleSupported() const {
1283 return true;
1286 GlobalErrorBubbleViewBase* BrowserView::ShowProfileResetBubble(
1287 const base::WeakPtr<ProfileResetGlobalError>& global_error) {
1288 return ProfileResetBubbleView::ShowBubble(global_error, browser_.get());
1291 #if defined(ENABLE_ONE_CLICK_SIGNIN)
1292 void BrowserView::ShowOneClickSigninBubble(
1293 OneClickSigninBubbleType type,
1294 const base::string16& email,
1295 const base::string16& error_message,
1296 const StartSyncCallback& start_sync_callback) {
1297 scoped_ptr<OneClickSigninBubbleDelegate> delegate;
1298 delegate.reset(new OneClickSigninBubbleLinksDelegate(browser()));
1300 views::View* anchor_view;
1301 if (type == BrowserWindow::ONE_CLICK_SIGNIN_BUBBLE_TYPE_BUBBLE)
1302 anchor_view = toolbar_->app_menu();
1303 else
1304 anchor_view = toolbar_->location_bar();
1306 OneClickSigninBubbleView::ShowBubble(type, email, error_message,
1307 delegate.Pass(), anchor_view,
1308 start_sync_callback);
1310 #endif
1312 void BrowserView::SetDownloadShelfVisible(bool visible) {
1313 // This can be called from the superclass destructor, when it destroys our
1314 // child views. At that point, browser_ is already gone.
1315 if (!browser_)
1316 return;
1318 if (visible && IsDownloadShelfVisible() != visible) {
1319 // Invoke GetDownloadShelf to force the shelf to be created.
1320 GetDownloadShelf();
1323 browser_->UpdateDownloadShelfVisibility(visible);
1325 // SetDownloadShelfVisible can force-close the shelf, so make sure we lay out
1326 // everything correctly, as if the animation had finished. This doesn't
1327 // matter for showing the shelf, as the show animation will do it.
1328 ToolbarSizeChanged(false);
1331 bool BrowserView::IsDownloadShelfVisible() const {
1332 return download_shelf_.get() && download_shelf_->IsShowing();
1335 DownloadShelf* BrowserView::GetDownloadShelf() {
1336 if (!download_shelf_.get()) {
1337 download_shelf_.reset(new DownloadShelfView(browser_.get(), this));
1338 download_shelf_->set_owned_by_client();
1339 GetBrowserViewLayout()->set_download_shelf(download_shelf_.get());
1341 return download_shelf_.get();
1344 void BrowserView::ConfirmBrowserCloseWithPendingDownloads(
1345 int download_count,
1346 Browser::DownloadClosePreventionType dialog_type,
1347 bool app_modal,
1348 const base::Callback<void(bool)>& callback) {
1349 DownloadInProgressDialogView::Show(
1350 GetNativeWindow(), download_count, dialog_type, app_modal, callback);
1353 void BrowserView::UserChangedTheme() {
1354 frame_->FrameTypeChanged();
1357 void BrowserView::WebContentsFocused(WebContents* contents) {
1358 if (contents_web_view_->GetWebContents() == contents)
1359 contents_web_view_->OnWebContentsFocused(contents);
1360 else
1361 devtools_web_view_->OnWebContentsFocused(contents);
1364 void BrowserView::ShowWebsiteSettings(Profile* profile,
1365 content::WebContents* web_contents,
1366 const GURL& url,
1367 const content::SSLStatus& ssl) {
1368 // Some browser windows have a location icon embedded in the frame. Try to
1369 // use that if it exists. If it doesn't exist, use the location icon from
1370 // the location bar.
1371 views::View* popup_anchor = frame_->GetLocationIconView();
1372 if (!popup_anchor)
1373 popup_anchor = GetLocationBarView()->location_icon_view();
1375 WebsiteSettingsPopupView::ShowPopup(popup_anchor, profile, web_contents, url,
1376 ssl, browser_.get());
1379 void BrowserView::ShowAppMenu() {
1380 // Keep the top-of-window views revealed as long as the app menu is visible.
1381 scoped_ptr<ImmersiveRevealedLock> revealed_lock(
1382 immersive_mode_controller_->GetRevealedLock(
1383 ImmersiveModeController::ANIMATE_REVEAL_NO));
1385 toolbar_->app_menu()->Activate();
1388 bool BrowserView::PreHandleKeyboardEvent(const NativeWebKeyboardEvent& event,
1389 bool* is_keyboard_shortcut) {
1390 *is_keyboard_shortcut = false;
1392 if ((event.type != blink::WebInputEvent::RawKeyDown) &&
1393 (event.type != blink::WebInputEvent::KeyUp)) {
1394 return false;
1397 views::FocusManager* focus_manager = GetFocusManager();
1398 DCHECK(focus_manager);
1400 if (focus_manager->shortcut_handling_suspended())
1401 return false;
1403 ui::Accelerator accelerator =
1404 ui::GetAcceleratorFromNativeWebKeyboardEvent(event);
1406 // What we have to do here is as follows:
1407 // - If the |browser_| is for an app, do nothing.
1408 // - If the |browser_| is not for an app, and the |accelerator| is not
1409 // associated with the browser (e.g. an Ash shortcut), process it.
1410 // - If the |browser_| is not for an app, and the |accelerator| is associated
1411 // with the browser, and it is a reserved one (e.g. Ctrl+w), process it.
1412 // - If the |browser_| is not for an app, and the |accelerator| is associated
1413 // with the browser, and it is not a reserved one, do nothing.
1415 if (browser_->is_app()) {
1416 // Let all keys fall through to a v1 app's web content, even accelerators.
1417 // We don't have to flip |is_keyboard_shortcut| here. If we do that, the app
1418 // might not be able to see a subsequent Char event. See OnHandleInputEvent
1419 // in content/renderer/render_widget.cc for details.
1420 return false;
1423 chrome::BrowserCommandController* controller = browser_->command_controller();
1425 // Here we need to retrieve the command id (if any) associated to the
1426 // keyboard event. Instead of looking up the command id in the
1427 // |accelerator_table_| by ourselves, we block the command execution of
1428 // the |browser_| object then send the keyboard event to the
1429 // |focus_manager| as if we are activating an accelerator key.
1430 // Then we can retrieve the command id from the |browser_| object.
1431 bool original_block_command_state = controller->block_command_execution();
1432 controller->SetBlockCommandExecution(true);
1433 // If the |accelerator| is a non-browser shortcut (e.g. Ash shortcut), the
1434 // command execution cannot be blocked and true is returned. However, it is
1435 // okay as long as is_app() is false. See comments in this function.
1436 const bool processed = focus_manager->ProcessAccelerator(accelerator);
1437 const int id = controller->GetLastBlockedCommand(nullptr);
1438 controller->SetBlockCommandExecution(original_block_command_state);
1440 // Executing the command may cause |this| object to be destroyed.
1441 if (controller->IsReservedCommandOrKey(id, event)) {
1442 UpdateAcceleratorMetrics(accelerator, id);
1443 return chrome::ExecuteCommand(browser_.get(), id);
1446 if (id != -1) {
1447 // |accelerator| is a non-reserved browser shortcut (e.g. Ctrl+f).
1448 if (event.type == blink::WebInputEvent::RawKeyDown)
1449 *is_keyboard_shortcut = true;
1450 } else if (processed) {
1451 // |accelerator| is a non-browser shortcut (e.g. F4-F10 on Ash). Report
1452 // that we handled it.
1453 return true;
1456 return false;
1459 void BrowserView::HandleKeyboardEvent(const NativeWebKeyboardEvent& event) {
1460 unhandled_keyboard_event_handler_.HandleKeyboardEvent(event,
1461 GetFocusManager());
1464 // TODO(devint): http://b/issue?id=1117225 Cut, Copy, and Paste are always
1465 // enabled in the page menu regardless of whether the command will do
1466 // anything. When someone selects the menu item, we just act as if they hit
1467 // the keyboard shortcut for the command by sending the associated key press
1468 // to windows. The real fix to this bug is to disable the commands when they
1469 // won't do anything. We'll need something like an overall clipboard command
1470 // manager to do that.
1471 void BrowserView::Cut() {
1472 // If a WebContent is focused, call WebContents::Cut. Otherwise, e.g. if
1473 // Omnibox is focused, send a Ctrl+x key event to Chrome. Using RWH interface
1474 // rather than the fake key event for a WebContent is important since the fake
1475 // event might be consumed by the web content (crbug.com/137908).
1476 DoCutCopyPaste(&content::WebContents::Cut, IDS_APP_CUT);
1479 void BrowserView::Copy() {
1480 DoCutCopyPaste(&content::WebContents::Copy, IDS_APP_COPY);
1483 void BrowserView::Paste() {
1484 DoCutCopyPaste(&content::WebContents::Paste, IDS_APP_PASTE);
1487 WindowOpenDisposition BrowserView::GetDispositionForPopupBounds(
1488 const gfx::Rect& bounds) {
1489 return NEW_POPUP;
1492 FindBar* BrowserView::CreateFindBar() {
1493 return chrome::CreateFindBar(this);
1496 WebContentsModalDialogHost* BrowserView::GetWebContentsModalDialogHost() {
1497 return GetBrowserViewLayout()->GetWebContentsModalDialogHost();
1500 BookmarkBarView* BrowserView::GetBookmarkBarView() const {
1501 return bookmark_bar_view_.get();
1504 LocationBarView* BrowserView::GetLocationBarView() const {
1505 return toolbar_ ? toolbar_->location_bar() : nullptr;
1508 views::View* BrowserView::GetTabContentsContainerView() const {
1509 return contents_web_view_;
1512 ToolbarView* BrowserView::GetToolbarView() const {
1513 return toolbar_;
1516 ///////////////////////////////////////////////////////////////////////////////
1517 // BrowserView, TabStripModelObserver implementation:
1519 void BrowserView::TabInsertedAt(WebContents* contents,
1520 int index,
1521 bool foreground) {
1522 #if defined(USE_AURA)
1523 // WebContents inserted in tabs might not have been added to the root
1524 // window yet. Per http://crbug/342672 add them now since drawing the
1525 // WebContents requires root window specific data - information about
1526 // the screen the WebContents is drawn on, for example.
1527 if (!contents->GetNativeView()->GetRootWindow()) {
1528 aura::Window* window = contents->GetNativeView();
1529 aura::Window* root_window = GetNativeWindow()->GetRootWindow();
1530 aura::client::ParentWindowWithContext(
1531 window, root_window, root_window->GetBoundsInScreen());
1532 DCHECK(contents->GetNativeView()->GetRootWindow());
1534 #endif
1535 web_contents_close_handler_->TabInserted();
1537 if (foreground)
1538 extensions::MaybeShowExtensionControlledNewTabPage(browser(), contents);
1541 void BrowserView::TabDetachedAt(WebContents* contents, int index) {
1542 if (PermissionBubbleManager::FromWebContents(contents))
1543 PermissionBubbleManager::FromWebContents(contents)->SetView(nullptr);
1545 // We use index here rather than comparing |contents| because by this time
1546 // the model has already removed |contents| from its list, so
1547 // browser_->GetActiveWebContents() will return null or something else.
1548 if (index == browser_->tab_strip_model()->active_index()) {
1549 // We need to reset the current tab contents to null before it gets
1550 // freed. This is because the focus manager performs some operations
1551 // on the selected WebContents when it is removed.
1552 web_contents_close_handler_->ActiveTabChanged();
1553 contents_web_view_->SetWebContents(nullptr);
1554 infobar_container_->ChangeInfoBarManager(nullptr);
1555 UpdateDevToolsForContents(nullptr, true);
1559 void BrowserView::TabDeactivated(WebContents* contents) {
1560 if (PermissionBubbleManager::FromWebContents(contents))
1561 PermissionBubbleManager::FromWebContents(contents)->SetView(nullptr);
1563 // We do not store the focus when closing the tab to work-around bug 4633.
1564 // Some reports seem to show that the focus manager and/or focused view can
1565 // be garbage at that point, it is not clear why.
1566 if (!contents->IsBeingDestroyed())
1567 contents->StoreFocus();
1570 void BrowserView::TabStripEmpty() {
1571 // Make sure all optional UI is removed before we are destroyed, otherwise
1572 // there will be consequences (since our view hierarchy will still have
1573 // references to freed views).
1574 UpdateUIForContents(nullptr);
1577 void BrowserView::WillCloseAllTabs() {
1578 web_contents_close_handler_->WillCloseAllTabs();
1581 void BrowserView::CloseAllTabsCanceled() {
1582 web_contents_close_handler_->CloseAllTabsCanceled();
1585 ///////////////////////////////////////////////////////////////////////////////
1586 // BrowserView, ui::AcceleratorProvider implementation:
1588 bool BrowserView::GetAcceleratorForCommandId(int command_id,
1589 ui::Accelerator* accelerator) {
1590 // Let's let the ToolbarView own the canonical implementation of this method.
1591 return toolbar_->GetAcceleratorForCommandId(command_id, accelerator);
1594 ///////////////////////////////////////////////////////////////////////////////
1595 // BrowserView, views::WidgetDelegate implementation:
1597 bool BrowserView::CanResize() const {
1598 return true;
1601 bool BrowserView::CanMaximize() const {
1602 return true;
1605 bool BrowserView::CanMinimize() const {
1606 return true;
1609 bool BrowserView::CanActivate() const {
1610 app_modal::AppModalDialogQueue* queue =
1611 app_modal::AppModalDialogQueue::GetInstance();
1612 if (!queue->active_dialog() || !queue->active_dialog()->native_dialog() ||
1613 !queue->active_dialog()->native_dialog()->IsShowing()) {
1614 return true;
1617 #if defined(USE_AURA) && defined(OS_CHROMEOS)
1618 // On Aura window manager controls all windows so settings focus via PostTask
1619 // will make only worse because posted task will keep trying to steal focus.
1620 queue->ActivateModalDialog();
1621 #else
1622 // If another browser is app modal, flash and activate the modal browser. This
1623 // has to be done in a post task, otherwise if the user clicked on a window
1624 // that doesn't have the modal dialog the windows keep trying to get the focus
1625 // from each other on Windows. http://crbug.com/141650.
1626 base::MessageLoop::current()->PostTask(
1627 FROM_HERE,
1628 base::Bind(&BrowserView::ActivateAppModalDialog,
1629 activate_modal_dialog_factory_.GetWeakPtr()));
1630 #endif
1631 return false;
1634 base::string16 BrowserView::GetWindowTitle() const {
1635 return browser_->GetWindowTitleForCurrentTab();
1638 base::string16 BrowserView::GetAccessibleWindowTitle() const {
1639 if (IsOffTheRecord()) {
1640 return l10n_util::GetStringFUTF16(
1641 IDS_ACCESSIBLE_INCOGNITO_WINDOW_TITLE_FORMAT,
1642 GetWindowTitle());
1644 return GetWindowTitle();
1647 views::View* BrowserView::GetInitiallyFocusedView() {
1648 return nullptr;
1651 bool BrowserView::ShouldShowWindowTitle() const {
1652 // For Ash only, trusted windows (apps and settings) do not show a title,
1653 // crbug.com/119411. Child windows (i.e. popups) do show a title.
1654 if (browser_->host_desktop_type() == chrome::HOST_DESKTOP_TYPE_ASH &&
1655 browser_->is_trusted_source() &&
1656 !browser_->SupportsWindowFeature(Browser::FEATURE_WEBAPPFRAME))
1657 return false;
1659 return browser_->SupportsWindowFeature(Browser::FEATURE_TITLEBAR);
1662 gfx::ImageSkia BrowserView::GetWindowAppIcon() {
1663 if (browser_->is_app()) {
1664 WebContents* contents = browser_->tab_strip_model()->GetActiveWebContents();
1665 extensions::TabHelper* extensions_tab_helper =
1666 contents ? extensions::TabHelper::FromWebContents(contents) : nullptr;
1667 if (extensions_tab_helper && extensions_tab_helper->GetExtensionAppIcon())
1668 return gfx::ImageSkia::CreateFrom1xBitmap(
1669 *extensions_tab_helper->GetExtensionAppIcon());
1672 return GetWindowIcon();
1675 gfx::ImageSkia BrowserView::GetWindowIcon() {
1676 if (browser_->is_app() || browser_->is_type_popup())
1677 return browser_->GetCurrentPageIcon().AsImageSkia();
1678 return gfx::ImageSkia();
1681 bool BrowserView::ShouldShowWindowIcon() const {
1682 // For Ash only, trusted windows (apps and settings) do not show an icon,
1683 // crbug.com/119411. Child windows (i.e. popups) do show an icon.
1684 if (browser_->host_desktop_type() == chrome::HOST_DESKTOP_TYPE_ASH &&
1685 browser_->is_trusted_source() &&
1686 !browser_->SupportsWindowFeature(Browser::FEATURE_WEBAPPFRAME))
1687 return false;
1689 return browser_->SupportsWindowFeature(Browser::FEATURE_TITLEBAR);
1692 bool BrowserView::ExecuteWindowsCommand(int command_id) {
1693 // This function handles WM_SYSCOMMAND, WM_APPCOMMAND, and WM_COMMAND.
1694 #if defined(OS_WIN)
1695 if (command_id == IDC_DEBUG_FRAME_TOGGLE)
1696 GetWidget()->DebugToggleFrameType();
1697 #endif
1698 // Translate WM_APPCOMMAND command ids into a command id that the browser
1699 // knows how to handle.
1700 int command_id_from_app_command = GetCommandIDForAppCommandID(command_id);
1701 if (command_id_from_app_command != -1)
1702 command_id = command_id_from_app_command;
1704 return chrome::ExecuteCommand(browser_.get(), command_id);
1707 std::string BrowserView::GetWindowName() const {
1708 return chrome::GetWindowName(browser_.get());
1711 void BrowserView::SaveWindowPlacement(const gfx::Rect& bounds,
1712 ui::WindowShowState show_state) {
1713 // If IsFullscreen() is true, we've just changed into fullscreen mode, and
1714 // we're catching the going-into-fullscreen sizing and positioning calls,
1715 // which we want to ignore.
1716 if (!IsFullscreen() && frame_->ShouldSaveWindowPlacement() &&
1717 chrome::ShouldSaveWindowPlacement(browser_.get())) {
1718 WidgetDelegate::SaveWindowPlacement(bounds, show_state);
1719 chrome::SaveWindowPlacement(browser_.get(), bounds, show_state);
1723 bool BrowserView::GetSavedWindowPlacement(
1724 const views::Widget* widget,
1725 gfx::Rect* bounds,
1726 ui::WindowShowState* show_state) const {
1727 chrome::GetSavedWindowBoundsAndShowState(browser_.get(), bounds, show_state);
1729 if (browser_->is_type_popup() &&
1730 !browser_->is_app() &&
1731 !browser_->is_trusted_source()) {
1732 // This is normal non-app popup window. The value passed in |bounds|
1733 // represents two pieces of information:
1734 // - the position of the window, in screen coordinates (outer position).
1735 // - the size of the content area (inner size).
1736 // We need to use these values to determine the appropriate size and
1737 // position of the resulting window.
1738 if (IsToolbarVisible()) {
1739 // If we're showing the toolbar, we need to adjust |*bounds| to include
1740 // its desired height, since the toolbar is considered part of the
1741 // window's client area as far as GetWindowBoundsForClientBounds is
1742 // concerned...
1743 bounds->set_height(
1744 bounds->height() + toolbar_->GetPreferredSize().height());
1747 gfx::Rect window_rect = frame_->non_client_view()->
1748 GetWindowBoundsForClientBounds(*bounds);
1749 window_rect.set_origin(bounds->origin());
1751 // When we are given x/y coordinates of 0 on a created popup window,
1752 // assume none were given by the window.open() command.
1753 if (window_rect.x() == 0 && window_rect.y() == 0) {
1754 gfx::Size size = window_rect.size();
1755 window_rect.set_origin(
1756 WindowSizer::GetDefaultPopupOrigin(size,
1757 browser_->host_desktop_type()));
1760 *bounds = window_rect;
1761 *show_state = ui::SHOW_STATE_NORMAL;
1764 // We return true because we can _always_ locate reasonable bounds using the
1765 // WindowSizer, and we don't want to trigger the Window's built-in "size to
1766 // default" handling because the browser window has no default preferred
1767 // size.
1768 return true;
1771 views::View* BrowserView::GetContentsView() {
1772 return contents_web_view_;
1775 views::ClientView* BrowserView::CreateClientView(views::Widget* widget) {
1776 return this;
1779 void BrowserView::OnWidgetActivationChanged(views::Widget* widget,
1780 bool active) {
1781 if (active)
1782 BrowserList::SetLastActive(browser_.get());
1785 void BrowserView::OnWindowBeginUserBoundsChange() {
1786 WebContents* web_contents = GetActiveWebContents();
1787 if (!web_contents)
1788 return;
1789 web_contents->GetRenderViewHost()->NotifyMoveOrResizeStarted();
1792 void BrowserView::OnWidgetMove() {
1793 if (!initialized_) {
1794 // Creating the widget can trigger a move. Ignore it until we've initialized
1795 // things.
1796 return;
1799 // Cancel any tabstrip animations, some of them may be invalidated by the
1800 // window being repositioned.
1801 // Comment out for one cycle to see if this fixes dist tests.
1802 // tabstrip_->DestroyDragController();
1804 // status_bubble_ may be null if this is invoked during construction.
1805 if (status_bubble_.get())
1806 status_bubble_->Reposition();
1808 BookmarkBubbleView::Hide();
1810 // Close the omnibox popup, if any.
1811 LocationBarView* location_bar_view = GetLocationBarView();
1812 if (location_bar_view)
1813 location_bar_view->GetOmniboxView()->CloseOmniboxPopup();
1816 views::Widget* BrowserView::GetWidget() {
1817 return View::GetWidget();
1820 const views::Widget* BrowserView::GetWidget() const {
1821 return View::GetWidget();
1824 void BrowserView::GetAccessiblePanes(std::vector<views::View*>* panes) {
1825 // This should be in the order of pane traversal of the panes using F6
1826 // (Windows) or Ctrl+Back/Forward (Chrome OS). If one of these is
1827 // invisible or has no focusable children, it will be automatically
1828 // skipped.
1829 panes->push_back(toolbar_);
1830 if (bookmark_bar_view_.get())
1831 panes->push_back(bookmark_bar_view_.get());
1832 if (infobar_container_)
1833 panes->push_back(infobar_container_);
1834 if (download_shelf_.get())
1835 panes->push_back(download_shelf_.get());
1836 panes->push_back(GetTabContentsContainerView());
1837 if (devtools_web_view_->visible())
1838 panes->push_back(devtools_web_view_);
1841 ///////////////////////////////////////////////////////////////////////////////
1842 // BrowserView, views::ClientView overrides:
1844 bool BrowserView::CanClose() {
1845 // You cannot close a frame for which there is an active originating drag
1846 // session.
1847 if (tabstrip_ && !tabstrip_->IsTabStripCloseable())
1848 return false;
1850 // Give beforeunload handlers the chance to cancel the close before we hide
1851 // the window below.
1852 if (!browser_->ShouldCloseWindow())
1853 return false;
1855 bool fast_tab_closing_enabled =
1856 base::CommandLine::ForCurrentProcess()->HasSwitch(
1857 switches::kEnableFastUnload);
1859 if (!browser_->tab_strip_model()->empty()) {
1860 // Tab strip isn't empty. Hide the frame (so it appears to have closed
1861 // immediately) and close all the tabs, allowing the renderers to shut
1862 // down. When the tab strip is empty we'll be called back again.
1863 frame_->Hide();
1864 browser_->OnWindowClosing();
1865 if (fast_tab_closing_enabled)
1866 browser_->tab_strip_model()->CloseAllTabs();
1867 return false;
1868 } else if (fast_tab_closing_enabled &&
1869 !browser_->HasCompletedUnloadProcessing()) {
1870 // The browser needs to finish running unload handlers.
1871 // Hide the frame (so it appears to have closed immediately), and
1872 // the browser will call us back again when it is ready to close.
1873 frame_->Hide();
1874 return false;
1877 // Empty TabStripModel, it's now safe to allow the Window to be closed.
1878 content::NotificationService::current()->Notify(
1879 chrome::NOTIFICATION_WINDOW_CLOSED,
1880 content::Source<gfx::NativeWindow>(frame_->GetNativeWindow()),
1881 content::NotificationService::NoDetails());
1882 return true;
1885 int BrowserView::NonClientHitTest(const gfx::Point& point) {
1886 return GetBrowserViewLayout()->NonClientHitTest(point);
1889 gfx::Size BrowserView::GetMinimumSize() const {
1890 return GetBrowserViewLayout()->GetMinimumSize();
1893 ///////////////////////////////////////////////////////////////////////////////
1894 // BrowserView, views::View overrides:
1896 const char* BrowserView::GetClassName() const {
1897 return kViewClassName;
1900 void BrowserView::Layout() {
1901 if (!initialized_ || in_process_fullscreen_)
1902 return;
1904 views::View::Layout();
1906 // TODO(jamescook): Why was this in the middle of layout code?
1907 toolbar_->location_bar()->omnibox_view()->SetFocusable(IsToolbarVisible());
1910 void BrowserView::PaintChildren(const ui::PaintContext& context) {
1911 // Paint the |infobar_container_| last so that it may paint its
1912 // overlapping tabs.
1913 for (int i = 0; i < child_count(); ++i) {
1914 View* child = child_at(i);
1915 if (child != infobar_container_ && !child->layer())
1916 child->Paint(context);
1919 infobar_container_->Paint(context);
1922 void BrowserView::ViewHierarchyChanged(
1923 const ViewHierarchyChangedDetails& details) {
1924 if (!initialized_ && details.is_add && details.child == this && GetWidget()) {
1925 InitViews();
1926 initialized_ = true;
1930 void BrowserView::ChildPreferredSizeChanged(View* child) {
1931 Layout();
1934 void BrowserView::GetAccessibleState(ui::AXViewState* state) {
1935 state->role = ui::AX_ROLE_CLIENT;
1938 void BrowserView::OnNativeThemeChanged(const ui::NativeTheme* theme) {
1939 // Do not handle native theme changes before the browser view is initialized.
1940 if (!initialized_)
1941 return;
1942 ClientView::OnNativeThemeChanged(theme);
1943 UserChangedTheme();
1944 chrome::MaybeShowInvertBubbleView(this);
1947 ///////////////////////////////////////////////////////////////////////////////
1948 // BrowserView, ui::AcceleratorTarget overrides:
1950 bool BrowserView::AcceleratorPressed(const ui::Accelerator& accelerator) {
1951 std::map<ui::Accelerator, int>::const_iterator iter =
1952 accelerator_table_.find(accelerator);
1953 DCHECK(iter != accelerator_table_.end());
1954 int command_id = iter->second;
1956 chrome::BrowserCommandController* controller = browser_->command_controller();
1957 if (!controller->block_command_execution())
1958 UpdateAcceleratorMetrics(accelerator, command_id);
1959 return chrome::ExecuteCommand(browser_.get(), command_id);
1962 ///////////////////////////////////////////////////////////////////////////////
1963 // BrowserView, OmniboxPopupModelObserver overrides:
1964 void BrowserView::OnOmniboxPopupShownOrHidden() {
1965 SetMaxTopArrowHeight(GetMaxTopInfoBarArrowHeight(), infobar_container_);
1968 ///////////////////////////////////////////////////////////////////////////////
1969 // BrowserView, InfoBarContainerDelegate overrides:
1971 SkColor BrowserView::GetInfoBarSeparatorColor() const {
1972 // NOTE: Keep this in sync with ToolbarView::OnPaint()!
1973 return (IsTabStripVisible() || !frame_->ShouldUseNativeFrame()) ?
1974 ThemeProperties::GetDefaultColor(
1975 ThemeProperties::COLOR_TOOLBAR_SEPARATOR) :
1976 SK_ColorBLACK;
1979 void BrowserView::InfoBarContainerStateChanged(bool is_animating) {
1980 ToolbarSizeChanged(is_animating);
1983 bool BrowserView::DrawInfoBarArrows(int* x) const {
1984 if (x) {
1985 gfx::Point anchor(toolbar_->location_bar()->GetLocationBarAnchorPoint());
1986 ConvertPointToTarget(toolbar_->location_bar(), this, &anchor);
1987 *x = anchor.x();
1989 return true;
1992 void BrowserView::InitViews() {
1993 GetWidget()->AddObserver(this);
1995 // Stow a pointer to this object onto the window handle so that we can get at
1996 // it later when all we have is a native view.
1997 GetWidget()->SetNativeWindowProperty(kBrowserViewKey, this);
1999 // Stow a pointer to the browser's profile onto the window handle so that we
2000 // can get it later when all we have is a native view.
2001 GetWidget()->SetNativeWindowProperty(Profile::kProfileKey,
2002 browser_->profile());
2004 // Start a hung plugin window detector for this browser object (as long as
2005 // hang detection is not disabled).
2006 if (!base::CommandLine::ForCurrentProcess()->HasSwitch(
2007 switches::kDisableHangMonitor)) {
2008 InitHangMonitor();
2011 LoadAccelerators();
2013 infobar_container_ = new InfoBarContainerView(this);
2014 AddChildView(infobar_container_);
2016 contents_web_view_ = new ContentsWebView(browser_->profile());
2017 contents_web_view_->set_id(VIEW_ID_TAB_CONTAINER);
2018 contents_web_view_->SetEmbedFullscreenWidgetMode(true);
2020 web_contents_close_handler_.reset(
2021 new WebContentsCloseHandler(contents_web_view_));
2023 devtools_web_view_ = new views::WebView(browser_->profile());
2024 devtools_web_view_->set_id(VIEW_ID_DEV_TOOLS_DOCKED);
2025 devtools_web_view_->SetVisible(false);
2027 contents_container_ = new views::View();
2028 contents_container_->set_background(views::Background::CreateSolidBackground(
2029 ThemeProperties::GetDefaultColor(
2030 ThemeProperties::COLOR_CONTROL_BACKGROUND)));
2031 contents_container_->AddChildView(devtools_web_view_);
2032 contents_container_->AddChildView(contents_web_view_);
2033 contents_container_->SetLayoutManager(new ContentsLayoutManager(
2034 devtools_web_view_, contents_web_view_));
2035 AddChildView(contents_container_);
2036 set_contents_view(contents_container_);
2038 // Top container holds tab strip and toolbar and lives at the front of the
2039 // view hierarchy.
2040 top_container_ = new TopContainerView(this);
2041 AddChildView(top_container_);
2043 // TabStrip takes ownership of the controller.
2044 BrowserTabStripController* tabstrip_controller =
2045 new BrowserTabStripController(browser_.get(),
2046 browser_->tab_strip_model());
2047 tabstrip_ = new TabStrip(tabstrip_controller);
2048 top_container_->AddChildView(tabstrip_);
2049 tabstrip_controller->InitFromModel(tabstrip_);
2051 toolbar_ = new ToolbarView(browser_.get());
2052 top_container_->AddChildView(toolbar_);
2053 toolbar_->Init();
2055 InitStatusBubble();
2057 // Create do-nothing view for the sake of controlling the z-order of the find
2058 // bar widget.
2059 find_bar_host_view_ = new View();
2060 AddChildView(find_bar_host_view_);
2062 immersive_mode_controller_->Init(this);
2064 BrowserViewLayout* browser_view_layout = new BrowserViewLayout;
2065 browser_view_layout->Init(new BrowserViewLayoutDelegateImpl(this),
2066 browser(),
2067 this,
2068 top_container_,
2069 tabstrip_,
2070 toolbar_,
2071 infobar_container_,
2072 contents_container_,
2073 GetContentsLayoutManager(),
2074 immersive_mode_controller_.get());
2075 SetLayoutManager(browser_view_layout);
2077 #if defined(OS_WIN)
2078 // Create a custom JumpList and add it to an observer of TabRestoreService
2079 // so we can update the custom JumpList when a tab is added or removed.
2080 if (JumpList::Enabled()) {
2081 load_complete_listener_.reset(new LoadCompleteListener(this));
2083 #endif
2085 GetLocationBar()->GetOmniboxView()->model()->popup_model()->AddObserver(this);
2088 void BrowserView::LoadingAnimationCallback() {
2089 base::TimeTicks now = base::TimeTicks::Now();
2090 if (!last_animation_time_.is_null()) {
2091 UMA_HISTOGRAM_TIMES(
2092 "Tabs.LoadingAnimationTime",
2093 now - last_animation_time_);
2095 last_animation_time_ = now;
2096 if (browser_->is_type_tabbed()) {
2097 // Loading animations are shown in the tab for tabbed windows. We check the
2098 // browser type instead of calling IsTabStripVisible() because the latter
2099 // will return false for fullscreen windows, but we still need to update
2100 // their animations (so that when they come out of fullscreen mode they'll
2101 // be correct).
2102 tabstrip_->UpdateLoadingAnimations();
2103 } else if (ShouldShowWindowIcon()) {
2104 // ... or in the window icon area for popups and app windows.
2105 WebContents* web_contents =
2106 browser_->tab_strip_model()->GetActiveWebContents();
2107 // GetActiveWebContents can return null for example under Purify when
2108 // the animations are running slowly and this function is called on a timer
2109 // through LoadingAnimationCallback.
2110 frame_->UpdateThrobber(web_contents && web_contents->IsLoading());
2114 void BrowserView::OnLoadCompleted() {
2115 #if defined(OS_WIN)
2116 DCHECK(!jumplist_.get());
2117 jumplist_ = new JumpList(browser_->profile());
2118 #endif
2121 BrowserViewLayout* BrowserView::GetBrowserViewLayout() const {
2122 return static_cast<BrowserViewLayout*>(GetLayoutManager());
2125 ContentsLayoutManager* BrowserView::GetContentsLayoutManager() const {
2126 return static_cast<ContentsLayoutManager*>(
2127 contents_container_->GetLayoutManager());
2130 bool BrowserView::MaybeShowBookmarkBar(WebContents* contents) {
2131 bool show_bookmark_bar = contents &&
2132 browser_->SupportsWindowFeature(Browser::FEATURE_BOOKMARKBAR);
2133 if (!show_bookmark_bar && !bookmark_bar_view_.get())
2134 return false;
2135 if (!bookmark_bar_view_.get()) {
2136 bookmark_bar_view_.reset(new BookmarkBarView(browser_.get(), this));
2137 bookmark_bar_view_->set_owned_by_client();
2138 bookmark_bar_view_->set_background(new BookmarkBarViewBackground(
2139 this, bookmark_bar_view_.get(), browser_.get()));
2140 bookmark_bar_view_->SetBookmarkBarState(
2141 browser_->bookmark_bar_state(),
2142 BookmarkBar::DONT_ANIMATE_STATE_CHANGE);
2143 GetBrowserViewLayout()->set_bookmark_bar(bookmark_bar_view_.get());
2145 // Don't change the visibility of the BookmarkBarView. BrowserViewLayout
2146 // handles it.
2147 bookmark_bar_view_->SetPageNavigator(GetActiveWebContents());
2149 // Update parenting for the bookmark bar. This may detach it from all views.
2150 bool needs_layout = false;
2151 views::View* new_parent = nullptr;
2152 if (show_bookmark_bar) {
2153 if (bookmark_bar_view_->IsDetached())
2154 new_parent = this;
2155 else
2156 new_parent = top_container_;
2158 if (new_parent != bookmark_bar_view_->parent()) {
2159 SetBookmarkBarParent(new_parent);
2160 needs_layout = true;
2163 // Check for updates to the desired size.
2164 if (bookmark_bar_view_->GetPreferredSize().height() !=
2165 bookmark_bar_view_->height())
2166 needs_layout = true;
2168 return needs_layout;
2171 void BrowserView::SetBookmarkBarParent(views::View* new_parent) {
2172 if (new_parent == this) {
2173 // Add it underneath |top_container_| or at the end if top container isn't
2174 // found.
2175 int top_container_index = GetIndexOf(top_container_);
2176 if (top_container_index >= 0)
2177 AddChildViewAt(bookmark_bar_view_.get(), top_container_index);
2178 else
2179 AddChildView(bookmark_bar_view_.get());
2180 } else if (new_parent) {
2181 // No special stacking is required for other parents.
2182 new_parent->AddChildView(bookmark_bar_view_.get());
2183 } else {
2184 // Bookmark bar is being detached from all views because it is hidden.
2185 bookmark_bar_view_->parent()->RemoveChildView(bookmark_bar_view_.get());
2189 bool BrowserView::MaybeShowInfoBar(WebContents* contents) {
2190 // TODO(beng): Remove this function once the interface between
2191 // InfoBarContainer, DownloadShelfView and WebContents and this
2192 // view is sorted out.
2193 return true;
2196 void BrowserView::UpdateDevToolsForContents(
2197 WebContents* web_contents, bool update_devtools_web_contents) {
2198 DevToolsContentsResizingStrategy strategy;
2199 WebContents* devtools = DevToolsWindow::GetInTabWebContents(
2200 web_contents, &strategy);
2202 if (!devtools_web_view_->web_contents() && devtools &&
2203 !devtools_focus_tracker_.get()) {
2204 // Install devtools focus tracker when dev tools window is shown for the
2205 // first time.
2206 devtools_focus_tracker_.reset(
2207 new views::ExternalFocusTracker(devtools_web_view_,
2208 GetFocusManager()));
2211 // Restore focus to the last focused view when hiding devtools window.
2212 if (devtools_web_view_->web_contents() && !devtools &&
2213 devtools_focus_tracker_.get()) {
2214 devtools_focus_tracker_->FocusLastFocusedExternalView();
2215 devtools_focus_tracker_.reset();
2218 // Replace devtools WebContents.
2219 if (devtools_web_view_->web_contents() != devtools &&
2220 update_devtools_web_contents) {
2221 devtools_web_view_->SetWebContents(devtools);
2224 if (devtools) {
2225 devtools_web_view_->SetVisible(true);
2226 GetContentsLayoutManager()->SetContentsResizingStrategy(strategy);
2227 } else {
2228 devtools_web_view_->SetVisible(false);
2229 GetContentsLayoutManager()->SetContentsResizingStrategy(
2230 DevToolsContentsResizingStrategy());
2232 contents_container_->Layout();
2234 if (devtools) {
2235 // When strategy.hide_inspected_contents() returns true, we are hiding
2236 // contents_web_view_ behind the devtools_web_view_. Otherwise,
2237 // contents_web_view_ should be right above the devtools_web_view_.
2238 int devtools_index = contents_container_->GetIndexOf(devtools_web_view_);
2239 int contents_index = contents_container_->GetIndexOf(contents_web_view_);
2240 bool devtools_is_on_top = devtools_index > contents_index;
2241 if (strategy.hide_inspected_contents() != devtools_is_on_top)
2242 contents_container_->ReorderChildView(contents_web_view_, devtools_index);
2246 void BrowserView::UpdateUIForContents(WebContents* contents) {
2247 bool needs_layout = MaybeShowBookmarkBar(contents);
2248 // TODO(jamescook): This function always returns true. Remove it and figure
2249 // out when layout is actually required.
2250 needs_layout |= MaybeShowInfoBar(contents);
2251 if (needs_layout)
2252 Layout();
2255 void BrowserView::ProcessFullscreen(bool fullscreen,
2256 FullscreenMode mode,
2257 const GURL& url,
2258 ExclusiveAccessBubbleType bubble_type) {
2259 if (in_process_fullscreen_)
2260 return;
2261 in_process_fullscreen_ = true;
2263 // Reduce jankiness during the following position changes by:
2264 // * Hiding the window until it's in the final position
2265 // * Ignoring all intervening Layout() calls, which resize the webpage and
2266 // thus are slow and look ugly (enforced via |in_process_fullscreen_|).
2267 LocationBarView* location_bar = GetLocationBarView();
2269 if (mode == METRO_SNAP_FULLSCREEN || !fullscreen) {
2270 // Hide the fullscreen bubble as soon as possible, since the mode toggle can
2271 // take enough time for the user to notice.
2272 exclusive_access_bubble_.reset();
2275 if (fullscreen) {
2276 // Move focus out of the location bar if necessary.
2277 views::FocusManager* focus_manager = GetFocusManager();
2278 DCHECK(focus_manager);
2279 // Look for focus in the location bar itself or any child view.
2280 if (location_bar->Contains(focus_manager->GetFocusedView()))
2281 focus_manager->ClearFocus();
2284 // Toggle fullscreen mode.
2285 frame_->SetFullscreen(fullscreen);
2287 // Enable immersive before the browser refreshes its list of enabled commands.
2288 if (mode != METRO_SNAP_FULLSCREEN && ShouldUseImmersiveFullscreenForUrl(url))
2289 immersive_mode_controller_->SetEnabled(fullscreen);
2291 browser_->WindowFullscreenStateChanged();
2293 if (fullscreen && !chrome::IsRunningInAppMode() &&
2294 mode != METRO_SNAP_FULLSCREEN) {
2295 UpdateExclusiveAccessExitBubbleContent(url, bubble_type);
2298 // Undo our anti-jankiness hacks and force a re-layout. We also need to
2299 // recompute the height of the infobar top arrow because toggling in and out
2300 // of fullscreen changes it. Calling ToolbarSizeChanged() will do both these
2301 // things since it computes the arrow height directly and forces a layout
2302 // indirectly via UpdateUIForContents(). Reset |in_process_fullscreen_| in
2303 // order to let the layout occur.
2304 in_process_fullscreen_ = false;
2305 ToolbarSizeChanged(false);
2307 if (permission_bubble_.get())
2308 permission_bubble_->UpdateAnchorPosition();
2311 bool BrowserView::ShouldUseImmersiveFullscreenForUrl(const GURL& url) const {
2312 // Kiosk mode needs the whole screen, and if we're not in an Ash desktop
2313 // immersive fullscreen doesn't exist.
2314 if (base::CommandLine::ForCurrentProcess()->HasSwitch(switches::kKioskMode) ||
2315 browser()->host_desktop_type() != chrome::HOST_DESKTOP_TYPE_ASH) {
2316 return false;
2319 return url.is_empty();
2322 void BrowserView::LoadAccelerators() {
2323 views::FocusManager* focus_manager = GetFocusManager();
2324 DCHECK(focus_manager);
2326 // Let's fill our own accelerator table.
2327 const bool is_app_mode = chrome::IsRunningInForcedAppMode();
2328 const std::vector<chrome::AcceleratorMapping> accelerator_list(
2329 chrome::GetAcceleratorList());
2330 for (std::vector<chrome::AcceleratorMapping>::const_iterator it =
2331 accelerator_list.begin(); it != accelerator_list.end(); ++it) {
2332 // In app mode, only allow accelerators of white listed commands to pass
2333 // through.
2334 if (is_app_mode && !chrome::IsCommandAllowedInAppMode(it->command_id))
2335 continue;
2337 ui::Accelerator accelerator(it->keycode, it->modifiers);
2338 accelerator_table_[accelerator] = it->command_id;
2340 // Also register with the focus manager.
2341 focus_manager->RegisterAccelerator(
2342 accelerator, ui::AcceleratorManager::kNormalPriority, this);
2346 int BrowserView::GetCommandIDForAppCommandID(int app_command_id) const {
2347 #if defined(OS_WIN)
2348 switch (app_command_id) {
2349 // NOTE: The order here matches the APPCOMMAND declaration order in the
2350 // Windows headers.
2351 case APPCOMMAND_BROWSER_BACKWARD: return IDC_BACK;
2352 case APPCOMMAND_BROWSER_FORWARD: return IDC_FORWARD;
2353 case APPCOMMAND_BROWSER_REFRESH: return IDC_RELOAD;
2354 case APPCOMMAND_BROWSER_HOME: return IDC_HOME;
2355 case APPCOMMAND_BROWSER_STOP: return IDC_STOP;
2356 case APPCOMMAND_BROWSER_SEARCH: return IDC_FOCUS_SEARCH;
2357 case APPCOMMAND_HELP: return IDC_HELP_PAGE_VIA_KEYBOARD;
2358 case APPCOMMAND_NEW: return IDC_NEW_TAB;
2359 case APPCOMMAND_OPEN: return IDC_OPEN_FILE;
2360 case APPCOMMAND_CLOSE: return IDC_CLOSE_TAB;
2361 case APPCOMMAND_SAVE: return IDC_SAVE_PAGE;
2362 case APPCOMMAND_PRINT: return IDC_PRINT;
2363 case APPCOMMAND_COPY: return IDC_COPY;
2364 case APPCOMMAND_CUT: return IDC_CUT;
2365 case APPCOMMAND_PASTE: return IDC_PASTE;
2367 // TODO(pkasting): http://b/1113069 Handle these.
2368 case APPCOMMAND_UNDO:
2369 case APPCOMMAND_REDO:
2370 case APPCOMMAND_SPELL_CHECK:
2371 default: return -1;
2373 #else
2374 // App commands are Windows-specific so there's nothing to do here.
2375 return -1;
2376 #endif
2379 void BrowserView::InitHangMonitor() {
2380 #if defined(OS_WIN)
2381 PrefService* pref_service = g_browser_process->local_state();
2382 if (!pref_service)
2383 return;
2385 int plugin_message_response_timeout =
2386 pref_service->GetInteger(prefs::kPluginMessageResponseTimeout);
2387 int hung_plugin_detect_freq =
2388 pref_service->GetInteger(prefs::kHungPluginDetectFrequency);
2389 HWND window = GetWidget()->GetNativeView()->GetHost()->
2390 GetAcceleratedWidget();
2391 if ((hung_plugin_detect_freq > 0) &&
2392 hung_window_detector_.Initialize(window,
2393 plugin_message_response_timeout)) {
2394 ticker_.set_tick_interval(hung_plugin_detect_freq);
2395 ticker_.RegisterTickHandler(&hung_window_detector_);
2396 ticker_.Start();
2398 pref_service->SetInteger(prefs::kPluginMessageResponseTimeout,
2399 plugin_message_response_timeout);
2400 pref_service->SetInteger(prefs::kHungPluginDetectFrequency,
2401 hung_plugin_detect_freq);
2403 #endif
2406 void BrowserView::UpdateAcceleratorMetrics(const ui::Accelerator& accelerator,
2407 int command_id) {
2408 const ui::KeyboardCode key_code = accelerator.key_code();
2409 if (command_id == IDC_HELP_PAGE_VIA_KEYBOARD && key_code == ui::VKEY_F1)
2410 content::RecordAction(UserMetricsAction("ShowHelpTabViaF1"));
2412 if (command_id == IDC_BOOKMARK_PAGE)
2413 UMA_HISTOGRAM_ENUMERATION("Bookmarks.EntryPoint",
2414 BOOKMARK_ENTRY_POINT_ACCELERATOR,
2415 BOOKMARK_ENTRY_POINT_LIMIT);
2417 #if defined(OS_CHROMEOS)
2418 // Collect information about the relative popularity of various accelerators
2419 // on Chrome OS.
2420 switch (command_id) {
2421 case IDC_BACK:
2422 if (key_code == ui::VKEY_BACK)
2423 content::RecordAction(UserMetricsAction("Accel_Back_Backspace"));
2424 else if (key_code == ui::VKEY_BROWSER_BACK)
2425 content::RecordAction(UserMetricsAction("Accel_Back_F1"));
2426 else if (key_code == ui::VKEY_LEFT)
2427 content::RecordAction(UserMetricsAction("Accel_Back_Left"));
2428 break;
2429 case IDC_FORWARD:
2430 if (key_code == ui::VKEY_BACK)
2431 content::RecordAction(UserMetricsAction("Accel_Forward_Backspace"));
2432 else if (key_code == ui::VKEY_BROWSER_FORWARD)
2433 content::RecordAction(UserMetricsAction("Accel_Forward_F2"));
2434 else if (key_code == ui::VKEY_RIGHT)
2435 content::RecordAction(UserMetricsAction("Accel_Forward_Right"));
2436 break;
2437 case IDC_RELOAD:
2438 case IDC_RELOAD_IGNORING_CACHE:
2439 if (key_code == ui::VKEY_R)
2440 content::RecordAction(UserMetricsAction("Accel_Reload_R"));
2441 else if (key_code == ui::VKEY_BROWSER_REFRESH)
2442 content::RecordAction(UserMetricsAction("Accel_Reload_F3"));
2443 break;
2444 case IDC_FOCUS_LOCATION:
2445 if (key_code == ui::VKEY_D)
2446 content::RecordAction(UserMetricsAction("Accel_FocusLocation_D"));
2447 else if (key_code == ui::VKEY_L)
2448 content::RecordAction(UserMetricsAction("Accel_FocusLocation_L"));
2449 break;
2450 case IDC_FOCUS_SEARCH:
2451 if (key_code == ui::VKEY_E)
2452 content::RecordAction(UserMetricsAction("Accel_FocusSearch_E"));
2453 else if (key_code == ui::VKEY_K)
2454 content::RecordAction(UserMetricsAction("Accel_FocusSearch_K"));
2455 break;
2456 default:
2457 // Do nothing.
2458 break;
2460 #endif
2463 void BrowserView::ShowAvatarBubbleFromAvatarButton(
2464 AvatarBubbleMode mode,
2465 const signin::ManageAccountsParams& manage_accounts_params) {
2466 views::BubbleBorder::Arrow arrow = views::BubbleBorder::TOP_RIGHT;
2467 views::BubbleBorder::BubbleAlignment alignment =
2468 views::BubbleBorder::ALIGN_ARROW_TO_MID_ANCHOR;
2469 views::View* anchor_view = frame_->GetAvatarMenuButton();
2470 if (!anchor_view)
2471 anchor_view = toolbar_->app_menu();
2472 else if (!frame_->GetAvatarMenuButton()->button_on_right())
2473 arrow = views::BubbleBorder::TOP_LEFT;
2475 if (switches::IsNewAvatarMenu()) {
2476 NewAvatarButton* button = frame_->GetNewAvatarMenuButton();
2477 if (button) {
2478 anchor_view = button;
2479 arrow = views::BubbleBorder::TOP_RIGHT;
2480 alignment = views::BubbleBorder::ALIGN_EDGE_TO_ANCHOR_EDGE;
2483 profiles::BubbleViewMode bubble_view_mode;
2484 profiles::TutorialMode tutorial_mode;
2485 profiles::BubbleViewModeFromAvatarBubbleMode(
2486 mode, &bubble_view_mode, &tutorial_mode);
2487 ProfileChooserView::ShowBubble(
2488 bubble_view_mode, tutorial_mode,
2489 manage_accounts_params, anchor_view, arrow, alignment, browser());
2490 } else {
2491 gfx::Point origin;
2492 views::View::ConvertPointToScreen(anchor_view, &origin);
2493 gfx::Rect bounds(origin, anchor_view->size());
2494 views::BubbleBorder::ArrowPaintType arrow_paint_type =
2495 ShouldHideUIForFullscreen() ? views::BubbleBorder::PAINT_TRANSPARENT :
2496 views::BubbleBorder::PAINT_NORMAL;
2497 AvatarMenuBubbleView::ShowBubble(anchor_view, arrow, arrow_paint_type,
2498 alignment, bounds, browser());
2500 ProfileMetrics::LogProfileOpenMethod(ProfileMetrics::ICON_AVATAR_BUBBLE);
2503 int BrowserView::GetRenderViewHeightInsetWithDetachedBookmarkBar() {
2504 if (browser_->bookmark_bar_state() != BookmarkBar::DETACHED ||
2505 !bookmark_bar_view_.get() || !bookmark_bar_view_->IsDetached()) {
2506 return 0;
2508 // Don't use bookmark_bar_view_->height() which won't be the final height if
2509 // the bookmark bar is animating.
2510 return chrome::kNTPBookmarkBarHeight -
2511 bookmark_bar_view_->GetFullyDetachedToolbarOverlap();
2514 void BrowserView::ExecuteExtensionCommand(
2515 const extensions::Extension* extension,
2516 const extensions::Command& command) {
2517 toolbar_->ExecuteExtensionCommand(extension, command);
2520 ExclusiveAccessContext* BrowserView::GetExclusiveAccessContext() {
2521 return this;
2524 void BrowserView::DoCutCopyPaste(void (WebContents::*method)(),
2525 int command_id) {
2526 WebContents* contents = browser_->tab_strip_model()->GetActiveWebContents();
2527 if (!contents)
2528 return;
2529 if (DoCutCopyPasteForWebContents(contents, method))
2530 return;
2532 WebContents* devtools = DevToolsWindow::GetInTabWebContents(contents,
2533 nullptr);
2534 if (devtools && DoCutCopyPasteForWebContents(devtools, method))
2535 return;
2537 views::FocusManager* focus_manager = GetFocusManager();
2538 views::View* focused = focus_manager->GetFocusedView();
2539 if (focused &&
2540 (!strcmp(focused->GetClassName(), views::Textfield::kViewClassName) ||
2541 !strcmp(focused->GetClassName(), OmniboxViewViews::kViewClassName))) {
2542 views::Textfield* textfield = static_cast<views::Textfield*>(focused);
2543 textfield->ExecuteCommand(command_id);
2547 bool BrowserView::DoCutCopyPasteForWebContents(
2548 WebContents* contents,
2549 void (WebContents::*method)()) {
2550 if (contents->GetRenderWidgetHostView()->HasFocus()) {
2551 (contents->*method)();
2552 return true;
2555 return false;
2558 void BrowserView::ActivateAppModalDialog() const {
2559 // If another browser is app modal, flash and activate the modal browser.
2560 app_modal::AppModalDialog* active_dialog =
2561 app_modal::AppModalDialogQueue::GetInstance()->active_dialog();
2562 if (!active_dialog)
2563 return;
2565 Browser* modal_browser =
2566 chrome::FindBrowserWithWebContents(active_dialog->web_contents());
2567 if (modal_browser && (browser_ != modal_browser)) {
2568 modal_browser->window()->FlashFrame(true);
2569 modal_browser->window()->Activate();
2572 app_modal::AppModalDialogQueue::GetInstance()->ActivateModalDialog();
2575 int BrowserView::GetMaxTopInfoBarArrowHeight() {
2576 int top_arrow_height = 0;
2577 // Only show the arrows when not in fullscreen and when there's no omnibox
2578 // popup.
2579 if (!IsFullscreen() &&
2580 !GetLocationBar()->GetOmniboxView()->model()->popup_model()->IsOpen()) {
2581 gfx::Point icon_bottom(
2582 toolbar_->location_bar()->GetLocationBarAnchorPoint());
2583 ConvertPointToTarget(toolbar_->location_bar(), this, &icon_bottom);
2584 gfx::Point infobar_top(0, infobar_container_->GetVerticalOverlap(nullptr));
2585 ConvertPointToTarget(infobar_container_, this, &infobar_top);
2586 top_arrow_height = infobar_top.y() - icon_bottom.y();
2588 return top_arrow_height;
2591 ///////////////////////////////////////////////////////////////////////////////
2592 // BrowserView, ExclusiveAccessContext overrides
2593 Profile* BrowserView::GetProfile() {
2594 return browser_->profile();
2597 WebContents* BrowserView::GetActiveWebContents() {
2598 return browser_->tab_strip_model()->GetActiveWebContents();
2601 void BrowserView::UnhideDownloadShelf() {
2602 GetDownloadShelf()->Unhide();
2605 void BrowserView::HideDownloadShelf() {
2606 GetDownloadShelf()->Hide();
2607 StatusBubble* statusBubble = GetStatusBubble();
2608 if (statusBubble)
2609 statusBubble->Hide();
2612 ///////////////////////////////////////////////////////////////////////////////
2613 // BrowserView, ExclusiveAccessBubbleViewsContext overrides
2614 ExclusiveAccessManager* BrowserView::GetExclusiveAccessManager() {
2615 return browser_->exclusive_access_manager();
2618 bool BrowserView::IsImmersiveModeEnabled() {
2619 return immersive_mode_controller()->IsEnabled();
2622 views::Widget* BrowserView::GetBubbleAssociatedWidget() {
2623 return GetWidget();
2626 gfx::Rect BrowserView::GetTopContainerBoundsInScreen() {
2627 return top_container_->GetBoundsInScreen();