Don't show supervised user as "already on this device" while they're being imported.
[chromium-blink-merge.git] / chrome / browser / ui / views / frame / browser_view.cc
blobb5c17fb15e71e9b7e202041aa9628d64a321b239
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 defined(OS_WIN) || defined(OS_CHROMEOS)
1050 if (!force_location_bar_focus_ && !IsActive())
1051 return;
1052 #endif
1054 // Temporarily reveal the top-of-window views (if not already revealed) so
1055 // that the location bar view is visible and is considered focusable. If the
1056 // location bar view gains focus, |immersive_mode_controller_| will keep the
1057 // top-of-window views revealed.
1058 scoped_ptr<ImmersiveRevealedLock> focus_reveal_lock(
1059 immersive_mode_controller_->GetRevealedLock(
1060 ImmersiveModeController::ANIMATE_REVEAL_YES));
1062 LocationBarView* location_bar = GetLocationBarView();
1063 if (location_bar->omnibox_view()->IsFocusable()) {
1064 // Location bar got focus.
1065 location_bar->FocusLocation(select_all);
1066 } else {
1067 // If none of location bar got focus, then clear focus.
1068 views::FocusManager* focus_manager = GetFocusManager();
1069 DCHECK(focus_manager);
1070 focus_manager->ClearFocus();
1074 void BrowserView::UpdateReloadStopState(bool is_loading, bool force) {
1075 toolbar_->reload_button()->ChangeMode(
1076 is_loading ? ReloadButton::MODE_STOP : ReloadButton::MODE_RELOAD, force);
1079 void BrowserView::UpdateToolbar(content::WebContents* contents) {
1080 // We may end up here during destruction.
1081 if (toolbar_)
1082 toolbar_->Update(contents);
1083 frame_->UpdateToolbar();
1086 void BrowserView::ResetToolbarTabState(content::WebContents* contents) {
1087 // We may end up here during destruction.
1088 if (toolbar_)
1089 toolbar_->ResetTabState(contents);
1092 void BrowserView::FocusToolbar() {
1093 // Temporarily reveal the top-of-window views (if not already revealed) so
1094 // that the toolbar is visible and is considered focusable. If the
1095 // toolbar gains focus, |immersive_mode_controller_| will keep the
1096 // top-of-window views revealed.
1097 scoped_ptr<ImmersiveRevealedLock> focus_reveal_lock(
1098 immersive_mode_controller_->GetRevealedLock(
1099 ImmersiveModeController::ANIMATE_REVEAL_YES));
1101 // Start the traversal within the main toolbar. SetPaneFocus stores
1102 // the current focused view before changing focus.
1103 toolbar_->SetPaneFocus(nullptr);
1106 void BrowserView::ToolbarSizeChanged(bool is_animating) {
1107 // The call to SetMaxTopArrowHeight() below can result in reentrancy;
1108 // |call_state| tracks whether we're reentrant. We can't just early-return in
1109 // this case because we need to layout again so the infobar container's bounds
1110 // are set correctly.
1111 static CallState call_state = NORMAL;
1113 // A reentrant call can (and should) use the fast resize path unless both it
1114 // and the normal call are both non-animating.
1115 bool use_fast_resize =
1116 is_animating || (call_state == REENTRANT_FORCE_FAST_RESIZE);
1117 if (use_fast_resize)
1118 contents_web_view_->SetFastResize(true);
1119 UpdateUIForContents(GetActiveWebContents());
1120 if (use_fast_resize)
1121 contents_web_view_->SetFastResize(false);
1123 // Inform the InfoBarContainer that the distance to the location icon may have
1124 // changed. We have to do this after the block above so that the toolbars are
1125 // laid out correctly for calculating the maximum arrow height below.
1127 base::AutoReset<CallState> resetter(&call_state,
1128 is_animating ? REENTRANT_FORCE_FAST_RESIZE : REENTRANT);
1129 SetMaxTopArrowHeight(GetMaxTopInfoBarArrowHeight(), infobar_container_);
1132 // When transitioning from animating to not animating we need to make sure the
1133 // contents_container_ gets layed out. If we don't do this and the bounds
1134 // haven't changed contents_container_ won't get a Layout out and we'll end up
1135 // with a gray rect because the clip wasn't updated. Note that a reentrant
1136 // call never needs to do this, because after it returns, the normal call
1137 // wrapping it will do it.
1138 if ((call_state == NORMAL) && !is_animating) {
1139 contents_web_view_->InvalidateLayout();
1140 contents_container_->Layout();
1144 void BrowserView::FocusBookmarksToolbar() {
1145 DCHECK(!immersive_mode_controller_->IsEnabled());
1146 if (bookmark_bar_view_.get() &&
1147 bookmark_bar_view_->visible() &&
1148 bookmark_bar_view_->GetPreferredSize().height() != 0) {
1149 bookmark_bar_view_->SetPaneFocusAndFocusDefault();
1153 void BrowserView::FocusInfobars() {
1154 if (infobar_container_->child_count() > 0)
1155 infobar_container_->SetPaneFocusAndFocusDefault();
1158 void BrowserView::FocusAppMenu() {
1159 // Chrome doesn't have a traditional menu bar, but it has a menu button in the
1160 // main toolbar that plays the same role. If the user presses a key that
1161 // would typically focus the menu bar, tell the toolbar to focus the menu
1162 // button. If the user presses the key again, return focus to the previous
1163 // location.
1165 // Not used on the Mac, which has a normal menu bar.
1166 if (toolbar_->IsAppMenuFocused()) {
1167 RestoreFocus();
1168 } else {
1169 DCHECK(!immersive_mode_controller_->IsEnabled());
1170 toolbar_->SetPaneFocusAndFocusAppMenu();
1174 void BrowserView::RotatePaneFocus(bool forwards) {
1175 GetWidget()->GetFocusManager()->RotatePaneFocus(
1176 forwards ?
1177 views::FocusManager::kForward : views::FocusManager::kBackward,
1178 views::FocusManager::kWrap);
1181 void BrowserView::DestroyBrowser() {
1182 // After this returns other parts of Chrome are going to be shutdown. Close
1183 // the window now so that we are deleted immediately and aren't left holding
1184 // references to deleted objects.
1185 GetWidget()->RemoveObserver(this);
1186 GetLocationBar()->GetOmniboxView()->model()->popup_model()->RemoveObserver(
1187 this);
1188 frame_->CloseNow();
1191 bool BrowserView::IsBookmarkBarVisible() const {
1192 if (!browser_->SupportsWindowFeature(Browser::FEATURE_BOOKMARKBAR))
1193 return false;
1194 if (!bookmark_bar_view_.get())
1195 return false;
1196 if (bookmark_bar_view_->GetPreferredSize().height() == 0)
1197 return false;
1198 // New tab page needs visible bookmarks even when top-views are hidden.
1199 if (immersive_mode_controller_->ShouldHideTopViews() &&
1200 !bookmark_bar_view_->IsDetached())
1201 return false;
1202 return true;
1205 bool BrowserView::IsBookmarkBarAnimating() const {
1206 return bookmark_bar_view_.get() && bookmark_bar_view_->is_animating();
1209 bool BrowserView::IsTabStripEditable() const {
1210 return tabstrip_->IsTabStripEditable();
1213 bool BrowserView::IsToolbarVisible() const {
1214 if (immersive_mode_controller_->ShouldHideTopViews())
1215 return false;
1216 return browser_->SupportsWindowFeature(Browser::FEATURE_TOOLBAR) ||
1217 browser_->SupportsWindowFeature(Browser::FEATURE_LOCATIONBAR);
1220 gfx::Rect BrowserView::GetRootWindowResizerRect() const {
1221 // Views does not support resizer rects because they caused page cycler
1222 // performance regressions when they were added. See crrev.com/9654
1223 return gfx::Rect();
1226 void BrowserView::ConfirmAddSearchProvider(TemplateURL* template_url,
1227 Profile* profile) {
1228 chrome::EditSearchEngine(GetWidget()->GetNativeWindow(), template_url,
1229 nullptr, profile);
1232 void BrowserView::ShowUpdateChromeDialog() {
1233 UpdateRecommendedMessageBox::Show(GetWidget()->GetNativeWindow());
1236 void BrowserView::ShowBookmarkBubble(const GURL& url, bool already_bookmarked) {
1237 scoped_ptr<BookmarkBubbleDelegate> delegate;
1238 delegate.reset(new BookmarkBubbleSignInDelegate(browser_.get()));
1240 BookmarkBubbleView::ShowBubble(GetToolbarView()->GetBookmarkBubbleAnchor(),
1241 bookmark_bar_view_.get(),
1242 delegate.Pass(),
1243 browser_->profile(),
1244 url,
1245 !already_bookmarked);
1248 void BrowserView::ShowBookmarkAppBubble(
1249 const WebApplicationInfo& web_app_info,
1250 const ShowBookmarkAppBubbleCallback& callback) {
1251 BookmarkAppBubbleView::ShowBubble(GetToolbarView(), web_app_info, callback);
1254 void BrowserView::ShowTranslateBubble(
1255 content::WebContents* web_contents,
1256 translate::TranslateStep step,
1257 translate::TranslateErrors::Type error_type,
1258 bool is_user_gesture) {
1259 if (contents_web_view_->HasFocus() &&
1260 !GetLocationBarView()->IsMouseHovered()) {
1261 content::RenderViewHost* rvh = web_contents->GetRenderViewHost();
1262 if (rvh->IsFocusedElementEditable())
1263 return;
1266 ChromeTranslateClient* chrome_translate_client =
1267 ChromeTranslateClient::FromWebContents(web_contents);
1268 translate::LanguageState& language_state =
1269 chrome_translate_client->GetLanguageState();
1270 language_state.SetTranslateEnabled(true);
1272 if (IsMinimized())
1273 return;
1275 TranslateBubbleView::ShowBubble(
1276 GetToolbarView()->GetTranslateBubbleAnchor(), web_contents, step,
1277 error_type, is_user_gesture);
1280 bool BrowserView::ShowSessionCrashedBubble() {
1281 return SessionCrashedBubbleView::Show(browser_.get());
1284 bool BrowserView::IsProfileResetBubbleSupported() const {
1285 return true;
1288 GlobalErrorBubbleViewBase* BrowserView::ShowProfileResetBubble(
1289 const base::WeakPtr<ProfileResetGlobalError>& global_error) {
1290 return ProfileResetBubbleView::ShowBubble(global_error, browser_.get());
1293 #if defined(ENABLE_ONE_CLICK_SIGNIN)
1294 void BrowserView::ShowOneClickSigninBubble(
1295 OneClickSigninBubbleType type,
1296 const base::string16& email,
1297 const base::string16& error_message,
1298 const StartSyncCallback& start_sync_callback) {
1299 scoped_ptr<OneClickSigninBubbleDelegate> delegate;
1300 delegate.reset(new OneClickSigninBubbleLinksDelegate(browser()));
1302 views::View* anchor_view;
1303 if (type == BrowserWindow::ONE_CLICK_SIGNIN_BUBBLE_TYPE_BUBBLE)
1304 anchor_view = toolbar_->app_menu();
1305 else
1306 anchor_view = toolbar_->location_bar();
1308 OneClickSigninBubbleView::ShowBubble(type, email, error_message,
1309 delegate.Pass(), anchor_view,
1310 start_sync_callback);
1312 #endif
1314 void BrowserView::SetDownloadShelfVisible(bool visible) {
1315 // This can be called from the superclass destructor, when it destroys our
1316 // child views. At that point, browser_ is already gone.
1317 if (!browser_)
1318 return;
1320 if (visible && IsDownloadShelfVisible() != visible) {
1321 // Invoke GetDownloadShelf to force the shelf to be created.
1322 GetDownloadShelf();
1325 browser_->UpdateDownloadShelfVisibility(visible);
1327 // SetDownloadShelfVisible can force-close the shelf, so make sure we lay out
1328 // everything correctly, as if the animation had finished. This doesn't
1329 // matter for showing the shelf, as the show animation will do it.
1330 ToolbarSizeChanged(false);
1333 bool BrowserView::IsDownloadShelfVisible() const {
1334 return download_shelf_.get() && download_shelf_->IsShowing();
1337 DownloadShelf* BrowserView::GetDownloadShelf() {
1338 if (!download_shelf_.get()) {
1339 download_shelf_.reset(new DownloadShelfView(browser_.get(), this));
1340 download_shelf_->set_owned_by_client();
1341 GetBrowserViewLayout()->set_download_shelf(download_shelf_.get());
1343 return download_shelf_.get();
1346 void BrowserView::ConfirmBrowserCloseWithPendingDownloads(
1347 int download_count,
1348 Browser::DownloadClosePreventionType dialog_type,
1349 bool app_modal,
1350 const base::Callback<void(bool)>& callback) {
1351 DownloadInProgressDialogView::Show(
1352 GetNativeWindow(), download_count, dialog_type, app_modal, callback);
1355 void BrowserView::UserChangedTheme() {
1356 frame_->FrameTypeChanged();
1359 void BrowserView::ShowWebsiteSettings(Profile* profile,
1360 content::WebContents* web_contents,
1361 const GURL& url,
1362 const content::SSLStatus& ssl) {
1363 // Some browser windows have a location icon embedded in the frame. Try to
1364 // use that if it exists. If it doesn't exist, use the location icon from
1365 // the location bar.
1366 views::View* popup_anchor = frame_->GetLocationIconView();
1367 if (!popup_anchor)
1368 popup_anchor = GetLocationBarView()->location_icon_view();
1370 WebsiteSettingsPopupView::ShowPopup(popup_anchor, profile, web_contents, url,
1371 ssl, browser_.get());
1374 void BrowserView::ShowAppMenu() {
1375 // Keep the top-of-window views revealed as long as the app menu is visible.
1376 scoped_ptr<ImmersiveRevealedLock> revealed_lock(
1377 immersive_mode_controller_->GetRevealedLock(
1378 ImmersiveModeController::ANIMATE_REVEAL_NO));
1380 toolbar_->app_menu()->Activate();
1383 bool BrowserView::PreHandleKeyboardEvent(const NativeWebKeyboardEvent& event,
1384 bool* is_keyboard_shortcut) {
1385 *is_keyboard_shortcut = false;
1387 if ((event.type != blink::WebInputEvent::RawKeyDown) &&
1388 (event.type != blink::WebInputEvent::KeyUp)) {
1389 return false;
1392 views::FocusManager* focus_manager = GetFocusManager();
1393 DCHECK(focus_manager);
1395 if (focus_manager->shortcut_handling_suspended())
1396 return false;
1398 ui::Accelerator accelerator =
1399 ui::GetAcceleratorFromNativeWebKeyboardEvent(event);
1401 // What we have to do here is as follows:
1402 // - If the |browser_| is for an app, do nothing.
1403 // - If the |browser_| is not for an app, and the |accelerator| is not
1404 // associated with the browser (e.g. an Ash shortcut), process it.
1405 // - If the |browser_| is not for an app, and the |accelerator| is associated
1406 // with the browser, and it is a reserved one (e.g. Ctrl+w), process it.
1407 // - If the |browser_| is not for an app, and the |accelerator| is associated
1408 // with the browser, and it is not a reserved one, do nothing.
1410 if (browser_->is_app()) {
1411 // Let all keys fall through to a v1 app's web content, even accelerators.
1412 // We don't have to flip |is_keyboard_shortcut| here. If we do that, the app
1413 // might not be able to see a subsequent Char event. See OnHandleInputEvent
1414 // in content/renderer/render_widget.cc for details.
1415 return false;
1418 chrome::BrowserCommandController* controller = browser_->command_controller();
1420 // Here we need to retrieve the command id (if any) associated to the
1421 // keyboard event. Instead of looking up the command id in the
1422 // |accelerator_table_| by ourselves, we block the command execution of
1423 // the |browser_| object then send the keyboard event to the
1424 // |focus_manager| as if we are activating an accelerator key.
1425 // Then we can retrieve the command id from the |browser_| object.
1426 bool original_block_command_state = controller->block_command_execution();
1427 controller->SetBlockCommandExecution(true);
1428 // If the |accelerator| is a non-browser shortcut (e.g. Ash shortcut), the
1429 // command execution cannot be blocked and true is returned. However, it is
1430 // okay as long as is_app() is false. See comments in this function.
1431 const bool processed = focus_manager->ProcessAccelerator(accelerator);
1432 const int id = controller->GetLastBlockedCommand(nullptr);
1433 controller->SetBlockCommandExecution(original_block_command_state);
1435 // Executing the command may cause |this| object to be destroyed.
1436 if (controller->IsReservedCommandOrKey(id, event)) {
1437 UpdateAcceleratorMetrics(accelerator, id);
1438 return chrome::ExecuteCommand(browser_.get(), id);
1441 if (id != -1) {
1442 // |accelerator| is a non-reserved browser shortcut (e.g. Ctrl+f).
1443 if (event.type == blink::WebInputEvent::RawKeyDown)
1444 *is_keyboard_shortcut = true;
1445 } else if (processed) {
1446 // |accelerator| is a non-browser shortcut (e.g. F4-F10 on Ash). Report
1447 // that we handled it.
1448 return true;
1451 return false;
1454 void BrowserView::HandleKeyboardEvent(const NativeWebKeyboardEvent& event) {
1455 unhandled_keyboard_event_handler_.HandleKeyboardEvent(event,
1456 GetFocusManager());
1459 // TODO(devint): http://b/issue?id=1117225 Cut, Copy, and Paste are always
1460 // enabled in the page menu regardless of whether the command will do
1461 // anything. When someone selects the menu item, we just act as if they hit
1462 // the keyboard shortcut for the command by sending the associated key press
1463 // to windows. The real fix to this bug is to disable the commands when they
1464 // won't do anything. We'll need something like an overall clipboard command
1465 // manager to do that.
1466 void BrowserView::CutCopyPaste(int command_id) {
1467 // If a WebContents is focused, call its member method.
1468 WebContents* contents = browser_->tab_strip_model()->GetActiveWebContents();
1469 if (contents) {
1470 void (WebContents::*method)();
1471 if (command_id == IDC_CUT)
1472 method = &content::WebContents::Cut;
1473 else if (command_id == IDC_COPY)
1474 method = &content::WebContents::Copy;
1475 else
1476 method = &content::WebContents::Paste;
1477 if (DoCutCopyPasteForWebContents(contents, method))
1478 return;
1480 WebContents* devtools =
1481 DevToolsWindow::GetInTabWebContents(contents, nullptr);
1482 if (devtools && DoCutCopyPasteForWebContents(devtools, method))
1483 return;
1486 // Execute the command on the focused view, if possible, by calling
1487 // AcceleratorPressed(). Textfields override this to translate and execute
1488 // the provided accelerator.
1489 views::View* focused = GetFocusManager()->GetFocusedView();
1490 if (focused && focused->CanHandleAccelerators()) {
1491 ui::Accelerator accelerator;
1492 GetAccelerator(command_id, &accelerator);
1493 focused->AcceleratorPressed(accelerator);
1497 WindowOpenDisposition BrowserView::GetDispositionForPopupBounds(
1498 const gfx::Rect& bounds) {
1499 return NEW_POPUP;
1502 FindBar* BrowserView::CreateFindBar() {
1503 return chrome::CreateFindBar(this);
1506 WebContentsModalDialogHost* BrowserView::GetWebContentsModalDialogHost() {
1507 return GetBrowserViewLayout()->GetWebContentsModalDialogHost();
1510 BookmarkBarView* BrowserView::GetBookmarkBarView() const {
1511 return bookmark_bar_view_.get();
1514 LocationBarView* BrowserView::GetLocationBarView() const {
1515 return toolbar_ ? toolbar_->location_bar() : nullptr;
1518 views::View* BrowserView::GetTabContentsContainerView() const {
1519 return contents_web_view_;
1522 ToolbarView* BrowserView::GetToolbarView() const {
1523 return toolbar_;
1526 ///////////////////////////////////////////////////////////////////////////////
1527 // BrowserView, TabStripModelObserver implementation:
1529 void BrowserView::TabInsertedAt(WebContents* contents,
1530 int index,
1531 bool foreground) {
1532 #if defined(USE_AURA)
1533 // WebContents inserted in tabs might not have been added to the root
1534 // window yet. Per http://crbug/342672 add them now since drawing the
1535 // WebContents requires root window specific data - information about
1536 // the screen the WebContents is drawn on, for example.
1537 if (!contents->GetNativeView()->GetRootWindow()) {
1538 aura::Window* window = contents->GetNativeView();
1539 aura::Window* root_window = GetNativeWindow()->GetRootWindow();
1540 aura::client::ParentWindowWithContext(
1541 window, root_window, root_window->GetBoundsInScreen());
1542 DCHECK(contents->GetNativeView()->GetRootWindow());
1544 #endif
1545 web_contents_close_handler_->TabInserted();
1547 if (foreground)
1548 extensions::MaybeShowExtensionControlledNewTabPage(browser(), contents);
1551 void BrowserView::TabDetachedAt(WebContents* contents, int index) {
1552 if (PermissionBubbleManager::FromWebContents(contents))
1553 PermissionBubbleManager::FromWebContents(contents)->SetView(nullptr);
1555 // We use index here rather than comparing |contents| because by this time
1556 // the model has already removed |contents| from its list, so
1557 // browser_->GetActiveWebContents() will return null or something else.
1558 if (index == browser_->tab_strip_model()->active_index()) {
1559 // We need to reset the current tab contents to null before it gets
1560 // freed. This is because the focus manager performs some operations
1561 // on the selected WebContents when it is removed.
1562 web_contents_close_handler_->ActiveTabChanged();
1563 contents_web_view_->SetWebContents(nullptr);
1564 infobar_container_->ChangeInfoBarManager(nullptr);
1565 UpdateDevToolsForContents(nullptr, true);
1569 void BrowserView::TabDeactivated(WebContents* contents) {
1570 if (PermissionBubbleManager::FromWebContents(contents))
1571 PermissionBubbleManager::FromWebContents(contents)->SetView(nullptr);
1573 // We do not store the focus when closing the tab to work-around bug 4633.
1574 // Some reports seem to show that the focus manager and/or focused view can
1575 // be garbage at that point, it is not clear why.
1576 if (!contents->IsBeingDestroyed())
1577 contents->StoreFocus();
1580 void BrowserView::TabStripEmpty() {
1581 // Make sure all optional UI is removed before we are destroyed, otherwise
1582 // there will be consequences (since our view hierarchy will still have
1583 // references to freed views).
1584 UpdateUIForContents(nullptr);
1587 void BrowserView::WillCloseAllTabs() {
1588 web_contents_close_handler_->WillCloseAllTabs();
1591 void BrowserView::CloseAllTabsCanceled() {
1592 web_contents_close_handler_->CloseAllTabsCanceled();
1595 ///////////////////////////////////////////////////////////////////////////////
1596 // BrowserView, ui::AcceleratorProvider implementation:
1598 bool BrowserView::GetAcceleratorForCommandId(int command_id,
1599 ui::Accelerator* accelerator) {
1600 // Let's let the ToolbarView own the canonical implementation of this method.
1601 return toolbar_->GetAcceleratorForCommandId(command_id, accelerator);
1604 ///////////////////////////////////////////////////////////////////////////////
1605 // BrowserView, views::WidgetDelegate implementation:
1607 bool BrowserView::CanResize() const {
1608 return true;
1611 bool BrowserView::CanMaximize() const {
1612 return true;
1615 bool BrowserView::CanMinimize() const {
1616 return true;
1619 bool BrowserView::CanActivate() const {
1620 app_modal::AppModalDialogQueue* queue =
1621 app_modal::AppModalDialogQueue::GetInstance();
1622 if (!queue->active_dialog() || !queue->active_dialog()->native_dialog() ||
1623 !queue->active_dialog()->native_dialog()->IsShowing()) {
1624 return true;
1627 #if defined(USE_AURA) && defined(OS_CHROMEOS)
1628 // On Aura window manager controls all windows so settings focus via PostTask
1629 // will make only worse because posted task will keep trying to steal focus.
1630 queue->ActivateModalDialog();
1631 #else
1632 // If another browser is app modal, flash and activate the modal browser. This
1633 // has to be done in a post task, otherwise if the user clicked on a window
1634 // that doesn't have the modal dialog the windows keep trying to get the focus
1635 // from each other on Windows. http://crbug.com/141650.
1636 base::MessageLoop::current()->PostTask(
1637 FROM_HERE,
1638 base::Bind(&BrowserView::ActivateAppModalDialog,
1639 activate_modal_dialog_factory_.GetWeakPtr()));
1640 #endif
1641 return false;
1644 base::string16 BrowserView::GetWindowTitle() const {
1645 return browser_->GetWindowTitleForCurrentTab();
1648 base::string16 BrowserView::GetAccessibleWindowTitle() const {
1649 if (IsOffTheRecord()) {
1650 return l10n_util::GetStringFUTF16(
1651 IDS_ACCESSIBLE_INCOGNITO_WINDOW_TITLE_FORMAT,
1652 GetWindowTitle());
1654 return GetWindowTitle();
1657 views::View* BrowserView::GetInitiallyFocusedView() {
1658 return nullptr;
1661 bool BrowserView::ShouldShowWindowTitle() const {
1662 // For Ash only, trusted windows (apps and settings) do not show a title,
1663 // crbug.com/119411. Child windows (i.e. popups) do show a title.
1664 if (browser_->host_desktop_type() == chrome::HOST_DESKTOP_TYPE_ASH &&
1665 browser_->is_trusted_source() &&
1666 !browser_->SupportsWindowFeature(Browser::FEATURE_WEBAPPFRAME))
1667 return false;
1669 return browser_->SupportsWindowFeature(Browser::FEATURE_TITLEBAR);
1672 gfx::ImageSkia BrowserView::GetWindowAppIcon() {
1673 if (browser_->is_app()) {
1674 WebContents* contents = browser_->tab_strip_model()->GetActiveWebContents();
1675 extensions::TabHelper* extensions_tab_helper =
1676 contents ? extensions::TabHelper::FromWebContents(contents) : nullptr;
1677 if (extensions_tab_helper && extensions_tab_helper->GetExtensionAppIcon())
1678 return gfx::ImageSkia::CreateFrom1xBitmap(
1679 *extensions_tab_helper->GetExtensionAppIcon());
1682 return GetWindowIcon();
1685 gfx::ImageSkia BrowserView::GetWindowIcon() {
1686 if (browser_->is_app() || browser_->is_type_popup())
1687 return browser_->GetCurrentPageIcon().AsImageSkia();
1688 return gfx::ImageSkia();
1691 bool BrowserView::ShouldShowWindowIcon() const {
1692 // For Ash only, trusted windows (apps and settings) do not show an icon,
1693 // crbug.com/119411. Child windows (i.e. popups) do show an icon.
1694 if (browser_->host_desktop_type() == chrome::HOST_DESKTOP_TYPE_ASH &&
1695 browser_->is_trusted_source() &&
1696 !browser_->SupportsWindowFeature(Browser::FEATURE_WEBAPPFRAME))
1697 return false;
1699 return browser_->SupportsWindowFeature(Browser::FEATURE_TITLEBAR);
1702 bool BrowserView::ExecuteWindowsCommand(int command_id) {
1703 // This function handles WM_SYSCOMMAND, WM_APPCOMMAND, and WM_COMMAND.
1704 #if defined(OS_WIN)
1705 if (command_id == IDC_DEBUG_FRAME_TOGGLE)
1706 GetWidget()->DebugToggleFrameType();
1707 #endif
1708 // Translate WM_APPCOMMAND command ids into a command id that the browser
1709 // knows how to handle.
1710 int command_id_from_app_command = GetCommandIDForAppCommandID(command_id);
1711 if (command_id_from_app_command != -1)
1712 command_id = command_id_from_app_command;
1714 return chrome::ExecuteCommand(browser_.get(), command_id);
1717 std::string BrowserView::GetWindowName() const {
1718 return chrome::GetWindowName(browser_.get());
1721 void BrowserView::SaveWindowPlacement(const gfx::Rect& bounds,
1722 ui::WindowShowState show_state) {
1723 // If IsFullscreen() is true, we've just changed into fullscreen mode, and
1724 // we're catching the going-into-fullscreen sizing and positioning calls,
1725 // which we want to ignore.
1726 if (!IsFullscreen() && frame_->ShouldSaveWindowPlacement() &&
1727 chrome::ShouldSaveWindowPlacement(browser_.get())) {
1728 WidgetDelegate::SaveWindowPlacement(bounds, show_state);
1729 chrome::SaveWindowPlacement(browser_.get(), bounds, show_state);
1733 bool BrowserView::GetSavedWindowPlacement(
1734 const views::Widget* widget,
1735 gfx::Rect* bounds,
1736 ui::WindowShowState* show_state) const {
1737 chrome::GetSavedWindowBoundsAndShowState(browser_.get(), bounds, show_state);
1739 if (browser_->is_type_popup() &&
1740 !browser_->is_app() &&
1741 !browser_->is_trusted_source()) {
1742 // This is normal non-app popup window. The value passed in |bounds|
1743 // represents two pieces of information:
1744 // - the position of the window, in screen coordinates (outer position).
1745 // - the size of the content area (inner size).
1746 // We need to use these values to determine the appropriate size and
1747 // position of the resulting window.
1748 if (IsToolbarVisible()) {
1749 // If we're showing the toolbar, we need to adjust |*bounds| to include
1750 // its desired height, since the toolbar is considered part of the
1751 // window's client area as far as GetWindowBoundsForClientBounds is
1752 // concerned...
1753 bounds->set_height(
1754 bounds->height() + toolbar_->GetPreferredSize().height());
1757 gfx::Rect window_rect = frame_->non_client_view()->
1758 GetWindowBoundsForClientBounds(*bounds);
1759 window_rect.set_origin(bounds->origin());
1761 // When we are given x/y coordinates of 0 on a created popup window,
1762 // assume none were given by the window.open() command.
1763 if (window_rect.x() == 0 && window_rect.y() == 0) {
1764 gfx::Size size = window_rect.size();
1765 window_rect.set_origin(
1766 WindowSizer::GetDefaultPopupOrigin(size,
1767 browser_->host_desktop_type()));
1770 *bounds = window_rect;
1771 *show_state = ui::SHOW_STATE_NORMAL;
1774 // We return true because we can _always_ locate reasonable bounds using the
1775 // WindowSizer, and we don't want to trigger the Window's built-in "size to
1776 // default" handling because the browser window has no default preferred
1777 // size.
1778 return true;
1781 views::View* BrowserView::GetContentsView() {
1782 return contents_web_view_;
1785 views::ClientView* BrowserView::CreateClientView(views::Widget* widget) {
1786 return this;
1789 void BrowserView::OnWidgetActivationChanged(views::Widget* widget,
1790 bool active) {
1791 if (active)
1792 BrowserList::SetLastActive(browser_.get());
1795 void BrowserView::OnWindowBeginUserBoundsChange() {
1796 WebContents* web_contents = GetActiveWebContents();
1797 if (!web_contents)
1798 return;
1799 web_contents->GetRenderViewHost()->NotifyMoveOrResizeStarted();
1802 void BrowserView::OnWidgetMove() {
1803 if (!initialized_) {
1804 // Creating the widget can trigger a move. Ignore it until we've initialized
1805 // things.
1806 return;
1809 // Cancel any tabstrip animations, some of them may be invalidated by the
1810 // window being repositioned.
1811 // Comment out for one cycle to see if this fixes dist tests.
1812 // tabstrip_->DestroyDragController();
1814 // status_bubble_ may be null if this is invoked during construction.
1815 if (status_bubble_.get())
1816 status_bubble_->Reposition();
1818 BookmarkBubbleView::Hide();
1820 // Close the omnibox popup, if any.
1821 LocationBarView* location_bar_view = GetLocationBarView();
1822 if (location_bar_view)
1823 location_bar_view->GetOmniboxView()->CloseOmniboxPopup();
1826 views::Widget* BrowserView::GetWidget() {
1827 return View::GetWidget();
1830 const views::Widget* BrowserView::GetWidget() const {
1831 return View::GetWidget();
1834 void BrowserView::GetAccessiblePanes(std::vector<views::View*>* panes) {
1835 // This should be in the order of pane traversal of the panes using F6
1836 // (Windows) or Ctrl+Back/Forward (Chrome OS). If one of these is
1837 // invisible or has no focusable children, it will be automatically
1838 // skipped.
1839 panes->push_back(toolbar_);
1840 if (bookmark_bar_view_.get())
1841 panes->push_back(bookmark_bar_view_.get());
1842 if (infobar_container_)
1843 panes->push_back(infobar_container_);
1844 if (download_shelf_.get())
1845 panes->push_back(download_shelf_.get());
1846 panes->push_back(GetTabContentsContainerView());
1847 if (devtools_web_view_->visible())
1848 panes->push_back(devtools_web_view_);
1851 ///////////////////////////////////////////////////////////////////////////////
1852 // BrowserView, views::ClientView overrides:
1854 bool BrowserView::CanClose() {
1855 // You cannot close a frame for which there is an active originating drag
1856 // session.
1857 if (tabstrip_ && !tabstrip_->IsTabStripCloseable())
1858 return false;
1860 // Give beforeunload handlers the chance to cancel the close before we hide
1861 // the window below.
1862 if (!browser_->ShouldCloseWindow())
1863 return false;
1865 bool fast_tab_closing_enabled =
1866 base::CommandLine::ForCurrentProcess()->HasSwitch(
1867 switches::kEnableFastUnload);
1869 if (!browser_->tab_strip_model()->empty()) {
1870 // Tab strip isn't empty. Hide the frame (so it appears to have closed
1871 // immediately) and close all the tabs, allowing the renderers to shut
1872 // down. When the tab strip is empty we'll be called back again.
1873 frame_->Hide();
1874 browser_->OnWindowClosing();
1875 if (fast_tab_closing_enabled)
1876 browser_->tab_strip_model()->CloseAllTabs();
1877 return false;
1878 } else if (fast_tab_closing_enabled &&
1879 !browser_->HasCompletedUnloadProcessing()) {
1880 // The browser needs to finish running unload handlers.
1881 // Hide the frame (so it appears to have closed immediately), and
1882 // the browser will call us back again when it is ready to close.
1883 frame_->Hide();
1884 return false;
1887 // Empty TabStripModel, it's now safe to allow the Window to be closed.
1888 content::NotificationService::current()->Notify(
1889 chrome::NOTIFICATION_WINDOW_CLOSED,
1890 content::Source<gfx::NativeWindow>(frame_->GetNativeWindow()),
1891 content::NotificationService::NoDetails());
1892 return true;
1895 int BrowserView::NonClientHitTest(const gfx::Point& point) {
1896 return GetBrowserViewLayout()->NonClientHitTest(point);
1899 gfx::Size BrowserView::GetMinimumSize() const {
1900 return GetBrowserViewLayout()->GetMinimumSize();
1903 ///////////////////////////////////////////////////////////////////////////////
1904 // BrowserView, views::View overrides:
1906 const char* BrowserView::GetClassName() const {
1907 return kViewClassName;
1910 void BrowserView::Layout() {
1911 if (!initialized_ || in_process_fullscreen_)
1912 return;
1914 views::View::Layout();
1916 // TODO(jamescook): Why was this in the middle of layout code?
1917 toolbar_->location_bar()->omnibox_view()->SetFocusable(IsToolbarVisible());
1920 void BrowserView::PaintChildren(const ui::PaintContext& context) {
1921 // Paint the |infobar_container_| last so that it may paint its
1922 // overlapping tabs.
1923 for (int i = 0; i < child_count(); ++i) {
1924 View* child = child_at(i);
1925 if (child != infobar_container_ && !child->layer())
1926 child->Paint(context);
1929 infobar_container_->Paint(context);
1932 void BrowserView::ViewHierarchyChanged(
1933 const ViewHierarchyChangedDetails& details) {
1934 if (!initialized_ && details.is_add && details.child == this && GetWidget()) {
1935 InitViews();
1936 initialized_ = true;
1940 void BrowserView::ChildPreferredSizeChanged(View* child) {
1941 Layout();
1944 void BrowserView::GetAccessibleState(ui::AXViewState* state) {
1945 state->role = ui::AX_ROLE_CLIENT;
1948 void BrowserView::OnNativeThemeChanged(const ui::NativeTheme* theme) {
1949 // Do not handle native theme changes before the browser view is initialized.
1950 if (!initialized_)
1951 return;
1952 ClientView::OnNativeThemeChanged(theme);
1953 UserChangedTheme();
1954 chrome::MaybeShowInvertBubbleView(this);
1957 ///////////////////////////////////////////////////////////////////////////////
1958 // BrowserView, ui::AcceleratorTarget overrides:
1960 bool BrowserView::AcceleratorPressed(const ui::Accelerator& accelerator) {
1961 std::map<ui::Accelerator, int>::const_iterator iter =
1962 accelerator_table_.find(accelerator);
1963 DCHECK(iter != accelerator_table_.end());
1964 int command_id = iter->second;
1966 chrome::BrowserCommandController* controller = browser_->command_controller();
1967 if (!controller->block_command_execution())
1968 UpdateAcceleratorMetrics(accelerator, command_id);
1969 return chrome::ExecuteCommand(browser_.get(), command_id);
1972 ///////////////////////////////////////////////////////////////////////////////
1973 // BrowserView, OmniboxPopupModelObserver overrides:
1974 void BrowserView::OnOmniboxPopupShownOrHidden() {
1975 SetMaxTopArrowHeight(GetMaxTopInfoBarArrowHeight(), infobar_container_);
1978 ///////////////////////////////////////////////////////////////////////////////
1979 // BrowserView, InfoBarContainerDelegate overrides:
1981 SkColor BrowserView::GetInfoBarSeparatorColor() const {
1982 // NOTE: Keep this in sync with ToolbarView::OnPaint()!
1983 return (IsTabStripVisible() || !frame_->ShouldUseNativeFrame()) ?
1984 ThemeProperties::GetDefaultColor(
1985 ThemeProperties::COLOR_TOOLBAR_SEPARATOR) :
1986 SK_ColorBLACK;
1989 void BrowserView::InfoBarContainerStateChanged(bool is_animating) {
1990 ToolbarSizeChanged(is_animating);
1993 bool BrowserView::DrawInfoBarArrows(int* x) const {
1994 if (x) {
1995 gfx::Point anchor(toolbar_->location_bar()->GetLocationBarAnchorPoint());
1996 ConvertPointToTarget(toolbar_->location_bar(), this, &anchor);
1997 *x = anchor.x();
1999 return true;
2002 void BrowserView::InitViews() {
2003 GetWidget()->AddObserver(this);
2005 // Stow a pointer to this object onto the window handle so that we can get at
2006 // it later when all we have is a native view.
2007 GetWidget()->SetNativeWindowProperty(kBrowserViewKey, this);
2009 // Stow a pointer to the browser's profile onto the window handle so that we
2010 // can get it later when all we have is a native view.
2011 GetWidget()->SetNativeWindowProperty(Profile::kProfileKey,
2012 browser_->profile());
2014 // Start a hung plugin window detector for this browser object (as long as
2015 // hang detection is not disabled).
2016 if (!base::CommandLine::ForCurrentProcess()->HasSwitch(
2017 switches::kDisableHangMonitor)) {
2018 InitHangMonitor();
2021 LoadAccelerators();
2023 infobar_container_ = new InfoBarContainerView(this);
2024 AddChildView(infobar_container_);
2026 contents_web_view_ = new ContentsWebView(browser_->profile());
2027 contents_web_view_->set_id(VIEW_ID_TAB_CONTAINER);
2028 contents_web_view_->SetEmbedFullscreenWidgetMode(true);
2030 web_contents_close_handler_.reset(
2031 new WebContentsCloseHandler(contents_web_view_));
2033 devtools_web_view_ = new views::WebView(browser_->profile());
2034 devtools_web_view_->set_id(VIEW_ID_DEV_TOOLS_DOCKED);
2035 devtools_web_view_->SetVisible(false);
2037 contents_container_ = new views::View();
2038 contents_container_->set_background(views::Background::CreateSolidBackground(
2039 ThemeProperties::GetDefaultColor(
2040 ThemeProperties::COLOR_CONTROL_BACKGROUND)));
2041 contents_container_->AddChildView(devtools_web_view_);
2042 contents_container_->AddChildView(contents_web_view_);
2043 contents_container_->SetLayoutManager(new ContentsLayoutManager(
2044 devtools_web_view_, contents_web_view_));
2045 AddChildView(contents_container_);
2046 set_contents_view(contents_container_);
2048 // Top container holds tab strip and toolbar and lives at the front of the
2049 // view hierarchy.
2050 top_container_ = new TopContainerView(this);
2051 AddChildView(top_container_);
2053 // TabStrip takes ownership of the controller.
2054 BrowserTabStripController* tabstrip_controller =
2055 new BrowserTabStripController(browser_.get(),
2056 browser_->tab_strip_model());
2057 tabstrip_ = new TabStrip(tabstrip_controller);
2058 top_container_->AddChildView(tabstrip_);
2059 tabstrip_controller->InitFromModel(tabstrip_);
2061 toolbar_ = new ToolbarView(browser_.get());
2062 top_container_->AddChildView(toolbar_);
2063 toolbar_->Init();
2065 InitStatusBubble();
2067 // Create do-nothing view for the sake of controlling the z-order of the find
2068 // bar widget.
2069 find_bar_host_view_ = new View();
2070 AddChildView(find_bar_host_view_);
2072 immersive_mode_controller_->Init(this);
2074 BrowserViewLayout* browser_view_layout = new BrowserViewLayout;
2075 browser_view_layout->Init(new BrowserViewLayoutDelegateImpl(this),
2076 browser(),
2077 this,
2078 top_container_,
2079 tabstrip_,
2080 toolbar_,
2081 infobar_container_,
2082 contents_container_,
2083 GetContentsLayoutManager(),
2084 immersive_mode_controller_.get());
2085 SetLayoutManager(browser_view_layout);
2087 #if defined(OS_WIN)
2088 // Create a custom JumpList and add it to an observer of TabRestoreService
2089 // so we can update the custom JumpList when a tab is added or removed.
2090 if (JumpList::Enabled()) {
2091 load_complete_listener_.reset(new LoadCompleteListener(this));
2093 #endif
2095 GetLocationBar()->GetOmniboxView()->model()->popup_model()->AddObserver(this);
2098 void BrowserView::LoadingAnimationCallback() {
2099 base::TimeTicks now = base::TimeTicks::Now();
2100 if (!last_animation_time_.is_null()) {
2101 UMA_HISTOGRAM_TIMES(
2102 "Tabs.LoadingAnimationTime",
2103 now - last_animation_time_);
2105 last_animation_time_ = now;
2106 if (browser_->is_type_tabbed()) {
2107 // Loading animations are shown in the tab for tabbed windows. We check the
2108 // browser type instead of calling IsTabStripVisible() because the latter
2109 // will return false for fullscreen windows, but we still need to update
2110 // their animations (so that when they come out of fullscreen mode they'll
2111 // be correct).
2112 tabstrip_->UpdateLoadingAnimations();
2113 } else if (ShouldShowWindowIcon()) {
2114 // ... or in the window icon area for popups and app windows.
2115 WebContents* web_contents =
2116 browser_->tab_strip_model()->GetActiveWebContents();
2117 // GetActiveWebContents can return null for example under Purify when
2118 // the animations are running slowly and this function is called on a timer
2119 // through LoadingAnimationCallback.
2120 frame_->UpdateThrobber(web_contents && web_contents->IsLoading());
2124 void BrowserView::OnLoadCompleted() {
2125 #if defined(OS_WIN)
2126 DCHECK(!jumplist_.get());
2127 jumplist_ = new JumpList(browser_->profile());
2128 #endif
2131 BrowserViewLayout* BrowserView::GetBrowserViewLayout() const {
2132 return static_cast<BrowserViewLayout*>(GetLayoutManager());
2135 ContentsLayoutManager* BrowserView::GetContentsLayoutManager() const {
2136 return static_cast<ContentsLayoutManager*>(
2137 contents_container_->GetLayoutManager());
2140 bool BrowserView::MaybeShowBookmarkBar(WebContents* contents) {
2141 bool show_bookmark_bar = contents &&
2142 browser_->SupportsWindowFeature(Browser::FEATURE_BOOKMARKBAR);
2143 if (!show_bookmark_bar && !bookmark_bar_view_.get())
2144 return false;
2145 if (!bookmark_bar_view_.get()) {
2146 bookmark_bar_view_.reset(new BookmarkBarView(browser_.get(), this));
2147 bookmark_bar_view_->set_owned_by_client();
2148 bookmark_bar_view_->set_background(new BookmarkBarViewBackground(
2149 this, bookmark_bar_view_.get(), browser_.get()));
2150 bookmark_bar_view_->SetBookmarkBarState(
2151 browser_->bookmark_bar_state(),
2152 BookmarkBar::DONT_ANIMATE_STATE_CHANGE);
2153 GetBrowserViewLayout()->set_bookmark_bar(bookmark_bar_view_.get());
2155 // Don't change the visibility of the BookmarkBarView. BrowserViewLayout
2156 // handles it.
2157 bookmark_bar_view_->SetPageNavigator(GetActiveWebContents());
2159 // Update parenting for the bookmark bar. This may detach it from all views.
2160 bool needs_layout = false;
2161 views::View* new_parent = nullptr;
2162 if (show_bookmark_bar) {
2163 if (bookmark_bar_view_->IsDetached())
2164 new_parent = this;
2165 else
2166 new_parent = top_container_;
2168 if (new_parent != bookmark_bar_view_->parent()) {
2169 SetBookmarkBarParent(new_parent);
2170 needs_layout = true;
2173 // Check for updates to the desired size.
2174 if (bookmark_bar_view_->GetPreferredSize().height() !=
2175 bookmark_bar_view_->height())
2176 needs_layout = true;
2178 return needs_layout;
2181 void BrowserView::SetBookmarkBarParent(views::View* new_parent) {
2182 if (new_parent == this) {
2183 // Add it underneath |top_container_| or at the end if top container isn't
2184 // found.
2185 int top_container_index = GetIndexOf(top_container_);
2186 if (top_container_index >= 0)
2187 AddChildViewAt(bookmark_bar_view_.get(), top_container_index);
2188 else
2189 AddChildView(bookmark_bar_view_.get());
2190 } else if (new_parent) {
2191 // No special stacking is required for other parents.
2192 new_parent->AddChildView(bookmark_bar_view_.get());
2193 } else {
2194 // Bookmark bar is being detached from all views because it is hidden.
2195 bookmark_bar_view_->parent()->RemoveChildView(bookmark_bar_view_.get());
2199 bool BrowserView::MaybeShowInfoBar(WebContents* contents) {
2200 // TODO(beng): Remove this function once the interface between
2201 // InfoBarContainer, DownloadShelfView and WebContents and this
2202 // view is sorted out.
2203 return true;
2206 void BrowserView::UpdateDevToolsForContents(
2207 WebContents* web_contents, bool update_devtools_web_contents) {
2208 DevToolsContentsResizingStrategy strategy;
2209 WebContents* devtools = DevToolsWindow::GetInTabWebContents(
2210 web_contents, &strategy);
2212 if (!devtools_web_view_->web_contents() && devtools &&
2213 !devtools_focus_tracker_.get()) {
2214 // Install devtools focus tracker when dev tools window is shown for the
2215 // first time.
2216 devtools_focus_tracker_.reset(
2217 new views::ExternalFocusTracker(devtools_web_view_,
2218 GetFocusManager()));
2221 // Restore focus to the last focused view when hiding devtools window.
2222 if (devtools_web_view_->web_contents() && !devtools &&
2223 devtools_focus_tracker_.get()) {
2224 devtools_focus_tracker_->FocusLastFocusedExternalView();
2225 devtools_focus_tracker_.reset();
2228 // Replace devtools WebContents.
2229 if (devtools_web_view_->web_contents() != devtools &&
2230 update_devtools_web_contents) {
2231 devtools_web_view_->SetWebContents(devtools);
2234 if (devtools) {
2235 devtools_web_view_->SetVisible(true);
2236 GetContentsLayoutManager()->SetContentsResizingStrategy(strategy);
2237 } else {
2238 devtools_web_view_->SetVisible(false);
2239 GetContentsLayoutManager()->SetContentsResizingStrategy(
2240 DevToolsContentsResizingStrategy());
2242 contents_container_->Layout();
2244 if (devtools) {
2245 // When strategy.hide_inspected_contents() returns true, we are hiding
2246 // contents_web_view_ behind the devtools_web_view_. Otherwise,
2247 // contents_web_view_ should be right above the devtools_web_view_.
2248 int devtools_index = contents_container_->GetIndexOf(devtools_web_view_);
2249 int contents_index = contents_container_->GetIndexOf(contents_web_view_);
2250 bool devtools_is_on_top = devtools_index > contents_index;
2251 if (strategy.hide_inspected_contents() != devtools_is_on_top)
2252 contents_container_->ReorderChildView(contents_web_view_, devtools_index);
2256 void BrowserView::UpdateUIForContents(WebContents* contents) {
2257 bool needs_layout = MaybeShowBookmarkBar(contents);
2258 // TODO(jamescook): This function always returns true. Remove it and figure
2259 // out when layout is actually required.
2260 needs_layout |= MaybeShowInfoBar(contents);
2261 if (needs_layout)
2262 Layout();
2265 void BrowserView::ProcessFullscreen(bool fullscreen,
2266 FullscreenMode mode,
2267 const GURL& url,
2268 ExclusiveAccessBubbleType bubble_type) {
2269 if (in_process_fullscreen_)
2270 return;
2271 in_process_fullscreen_ = true;
2273 // Reduce jankiness during the following position changes by:
2274 // * Hiding the window until it's in the final position
2275 // * Ignoring all intervening Layout() calls, which resize the webpage and
2276 // thus are slow and look ugly (enforced via |in_process_fullscreen_|).
2277 LocationBarView* location_bar = GetLocationBarView();
2279 if (mode == METRO_SNAP_FULLSCREEN || !fullscreen) {
2280 // Hide the fullscreen bubble as soon as possible, since the mode toggle can
2281 // take enough time for the user to notice.
2282 exclusive_access_bubble_.reset();
2285 if (fullscreen) {
2286 // Move focus out of the location bar if necessary.
2287 views::FocusManager* focus_manager = GetFocusManager();
2288 DCHECK(focus_manager);
2289 // Look for focus in the location bar itself or any child view.
2290 if (location_bar->Contains(focus_manager->GetFocusedView()))
2291 focus_manager->ClearFocus();
2294 // Toggle fullscreen mode.
2295 frame_->SetFullscreen(fullscreen);
2297 // Enable immersive before the browser refreshes its list of enabled commands.
2298 if (mode != METRO_SNAP_FULLSCREEN && ShouldUseImmersiveFullscreenForUrl(url))
2299 immersive_mode_controller_->SetEnabled(fullscreen);
2301 browser_->WindowFullscreenStateChanged();
2303 if (fullscreen && !chrome::IsRunningInAppMode() &&
2304 mode != METRO_SNAP_FULLSCREEN) {
2305 UpdateExclusiveAccessExitBubbleContent(url, bubble_type);
2308 // Undo our anti-jankiness hacks and force a re-layout. We also need to
2309 // recompute the height of the infobar top arrow because toggling in and out
2310 // of fullscreen changes it. Calling ToolbarSizeChanged() will do both these
2311 // things since it computes the arrow height directly and forces a layout
2312 // indirectly via UpdateUIForContents(). Reset |in_process_fullscreen_| in
2313 // order to let the layout occur.
2314 in_process_fullscreen_ = false;
2315 ToolbarSizeChanged(false);
2317 if (permission_bubble_.get())
2318 permission_bubble_->UpdateAnchorPosition();
2321 bool BrowserView::ShouldUseImmersiveFullscreenForUrl(const GURL& url) const {
2322 // Kiosk mode needs the whole screen, and if we're not in an Ash desktop
2323 // immersive fullscreen doesn't exist.
2324 if (base::CommandLine::ForCurrentProcess()->HasSwitch(switches::kKioskMode) ||
2325 browser()->host_desktop_type() != chrome::HOST_DESKTOP_TYPE_ASH) {
2326 return false;
2329 return url.is_empty();
2332 void BrowserView::LoadAccelerators() {
2333 views::FocusManager* focus_manager = GetFocusManager();
2334 DCHECK(focus_manager);
2336 // Let's fill our own accelerator table.
2337 const bool is_app_mode = chrome::IsRunningInForcedAppMode();
2338 const std::vector<chrome::AcceleratorMapping> accelerator_list(
2339 chrome::GetAcceleratorList());
2340 for (std::vector<chrome::AcceleratorMapping>::const_iterator it =
2341 accelerator_list.begin(); it != accelerator_list.end(); ++it) {
2342 // In app mode, only allow accelerators of white listed commands to pass
2343 // through.
2344 if (is_app_mode && !chrome::IsCommandAllowedInAppMode(it->command_id))
2345 continue;
2347 ui::Accelerator accelerator(it->keycode, it->modifiers);
2348 accelerator_table_[accelerator] = it->command_id;
2350 // Also register with the focus manager.
2351 focus_manager->RegisterAccelerator(
2352 accelerator, ui::AcceleratorManager::kNormalPriority, this);
2356 int BrowserView::GetCommandIDForAppCommandID(int app_command_id) const {
2357 #if defined(OS_WIN)
2358 switch (app_command_id) {
2359 // NOTE: The order here matches the APPCOMMAND declaration order in the
2360 // Windows headers.
2361 case APPCOMMAND_BROWSER_BACKWARD: return IDC_BACK;
2362 case APPCOMMAND_BROWSER_FORWARD: return IDC_FORWARD;
2363 case APPCOMMAND_BROWSER_REFRESH: return IDC_RELOAD;
2364 case APPCOMMAND_BROWSER_HOME: return IDC_HOME;
2365 case APPCOMMAND_BROWSER_STOP: return IDC_STOP;
2366 case APPCOMMAND_BROWSER_SEARCH: return IDC_FOCUS_SEARCH;
2367 case APPCOMMAND_HELP: return IDC_HELP_PAGE_VIA_KEYBOARD;
2368 case APPCOMMAND_NEW: return IDC_NEW_TAB;
2369 case APPCOMMAND_OPEN: return IDC_OPEN_FILE;
2370 case APPCOMMAND_CLOSE: return IDC_CLOSE_TAB;
2371 case APPCOMMAND_SAVE: return IDC_SAVE_PAGE;
2372 case APPCOMMAND_PRINT: return IDC_PRINT;
2373 case APPCOMMAND_COPY: return IDC_COPY;
2374 case APPCOMMAND_CUT: return IDC_CUT;
2375 case APPCOMMAND_PASTE: return IDC_PASTE;
2377 // TODO(pkasting): http://b/1113069 Handle these.
2378 case APPCOMMAND_UNDO:
2379 case APPCOMMAND_REDO:
2380 case APPCOMMAND_SPELL_CHECK:
2381 default: return -1;
2383 #else
2384 // App commands are Windows-specific so there's nothing to do here.
2385 return -1;
2386 #endif
2389 void BrowserView::InitHangMonitor() {
2390 #if defined(OS_WIN)
2391 PrefService* pref_service = g_browser_process->local_state();
2392 if (!pref_service)
2393 return;
2395 int plugin_message_response_timeout =
2396 pref_service->GetInteger(prefs::kPluginMessageResponseTimeout);
2397 int hung_plugin_detect_freq =
2398 pref_service->GetInteger(prefs::kHungPluginDetectFrequency);
2399 HWND window = GetWidget()->GetNativeView()->GetHost()->
2400 GetAcceleratedWidget();
2401 if ((hung_plugin_detect_freq > 0) &&
2402 hung_window_detector_.Initialize(window,
2403 plugin_message_response_timeout)) {
2404 ticker_.set_tick_interval(hung_plugin_detect_freq);
2405 ticker_.RegisterTickHandler(&hung_window_detector_);
2406 ticker_.Start();
2408 pref_service->SetInteger(prefs::kPluginMessageResponseTimeout,
2409 plugin_message_response_timeout);
2410 pref_service->SetInteger(prefs::kHungPluginDetectFrequency,
2411 hung_plugin_detect_freq);
2413 #endif
2416 void BrowserView::UpdateAcceleratorMetrics(const ui::Accelerator& accelerator,
2417 int command_id) {
2418 const ui::KeyboardCode key_code = accelerator.key_code();
2419 if (command_id == IDC_HELP_PAGE_VIA_KEYBOARD && key_code == ui::VKEY_F1)
2420 content::RecordAction(UserMetricsAction("ShowHelpTabViaF1"));
2422 if (command_id == IDC_BOOKMARK_PAGE)
2423 UMA_HISTOGRAM_ENUMERATION("Bookmarks.EntryPoint",
2424 BOOKMARK_ENTRY_POINT_ACCELERATOR,
2425 BOOKMARK_ENTRY_POINT_LIMIT);
2427 #if defined(OS_CHROMEOS)
2428 // Collect information about the relative popularity of various accelerators
2429 // on Chrome OS.
2430 switch (command_id) {
2431 case IDC_BACK:
2432 if (key_code == ui::VKEY_BACK)
2433 content::RecordAction(UserMetricsAction("Accel_Back_Backspace"));
2434 else if (key_code == ui::VKEY_BROWSER_BACK)
2435 content::RecordAction(UserMetricsAction("Accel_Back_F1"));
2436 else if (key_code == ui::VKEY_LEFT)
2437 content::RecordAction(UserMetricsAction("Accel_Back_Left"));
2438 break;
2439 case IDC_FORWARD:
2440 if (key_code == ui::VKEY_BACK)
2441 content::RecordAction(UserMetricsAction("Accel_Forward_Backspace"));
2442 else if (key_code == ui::VKEY_BROWSER_FORWARD)
2443 content::RecordAction(UserMetricsAction("Accel_Forward_F2"));
2444 else if (key_code == ui::VKEY_RIGHT)
2445 content::RecordAction(UserMetricsAction("Accel_Forward_Right"));
2446 break;
2447 case IDC_RELOAD:
2448 case IDC_RELOAD_IGNORING_CACHE:
2449 if (key_code == ui::VKEY_R)
2450 content::RecordAction(UserMetricsAction("Accel_Reload_R"));
2451 else if (key_code == ui::VKEY_BROWSER_REFRESH)
2452 content::RecordAction(UserMetricsAction("Accel_Reload_F3"));
2453 break;
2454 case IDC_FOCUS_LOCATION:
2455 if (key_code == ui::VKEY_D)
2456 content::RecordAction(UserMetricsAction("Accel_FocusLocation_D"));
2457 else if (key_code == ui::VKEY_L)
2458 content::RecordAction(UserMetricsAction("Accel_FocusLocation_L"));
2459 break;
2460 case IDC_FOCUS_SEARCH:
2461 if (key_code == ui::VKEY_E)
2462 content::RecordAction(UserMetricsAction("Accel_FocusSearch_E"));
2463 else if (key_code == ui::VKEY_K)
2464 content::RecordAction(UserMetricsAction("Accel_FocusSearch_K"));
2465 break;
2466 default:
2467 // Do nothing.
2468 break;
2470 #endif
2473 void BrowserView::ShowAvatarBubbleFromAvatarButton(
2474 AvatarBubbleMode mode,
2475 const signin::ManageAccountsParams& manage_accounts_params) {
2476 views::BubbleBorder::Arrow arrow = views::BubbleBorder::TOP_RIGHT;
2477 views::BubbleBorder::BubbleAlignment alignment =
2478 views::BubbleBorder::ALIGN_ARROW_TO_MID_ANCHOR;
2479 views::View* anchor_view = frame_->GetAvatarMenuButton();
2480 if (!anchor_view)
2481 anchor_view = toolbar_->app_menu();
2482 else if (!frame_->GetAvatarMenuButton()->button_on_right())
2483 arrow = views::BubbleBorder::TOP_LEFT;
2485 if (switches::IsNewAvatarMenu()) {
2486 NewAvatarButton* button = frame_->GetNewAvatarMenuButton();
2487 if (button) {
2488 anchor_view = button;
2489 arrow = views::BubbleBorder::TOP_RIGHT;
2490 alignment = views::BubbleBorder::ALIGN_EDGE_TO_ANCHOR_EDGE;
2493 profiles::BubbleViewMode bubble_view_mode;
2494 profiles::TutorialMode tutorial_mode;
2495 profiles::BubbleViewModeFromAvatarBubbleMode(
2496 mode, &bubble_view_mode, &tutorial_mode);
2497 ProfileChooserView::ShowBubble(
2498 bubble_view_mode, tutorial_mode,
2499 manage_accounts_params, anchor_view, arrow, alignment, browser());
2500 } else {
2501 gfx::Point origin;
2502 views::View::ConvertPointToScreen(anchor_view, &origin);
2503 gfx::Rect bounds(origin, anchor_view->size());
2504 views::BubbleBorder::ArrowPaintType arrow_paint_type =
2505 ShouldHideUIForFullscreen() ? views::BubbleBorder::PAINT_TRANSPARENT :
2506 views::BubbleBorder::PAINT_NORMAL;
2507 AvatarMenuBubbleView::ShowBubble(anchor_view, arrow, arrow_paint_type,
2508 alignment, bounds, browser());
2510 ProfileMetrics::LogProfileOpenMethod(ProfileMetrics::ICON_AVATAR_BUBBLE);
2513 void BrowserView::CloseAvatarBubbleFromAvatarButton() {
2514 if (switches::IsNewAvatarMenu())
2515 ProfileChooserView::Hide();
2516 else
2517 AvatarMenuBubbleView::Hide();
2520 int BrowserView::GetRenderViewHeightInsetWithDetachedBookmarkBar() {
2521 if (browser_->bookmark_bar_state() != BookmarkBar::DETACHED ||
2522 !bookmark_bar_view_.get() || !bookmark_bar_view_->IsDetached()) {
2523 return 0;
2525 // Don't use bookmark_bar_view_->height() which won't be the final height if
2526 // the bookmark bar is animating.
2527 return chrome::kNTPBookmarkBarHeight -
2528 bookmark_bar_view_->GetFullyDetachedToolbarOverlap();
2531 void BrowserView::ExecuteExtensionCommand(
2532 const extensions::Extension* extension,
2533 const extensions::Command& command) {
2534 toolbar_->ExecuteExtensionCommand(extension, command);
2537 ExclusiveAccessContext* BrowserView::GetExclusiveAccessContext() {
2538 return this;
2541 bool BrowserView::DoCutCopyPasteForWebContents(
2542 WebContents* contents,
2543 void (WebContents::*method)()) {
2544 // Using RWH interface rather than a fake key event for a WebContent is
2545 // important since a fake event might be consumed by the web content.
2546 if (contents->GetRenderWidgetHostView()->HasFocus()) {
2547 (contents->*method)();
2548 return true;
2551 return false;
2554 void BrowserView::ActivateAppModalDialog() const {
2555 // If another browser is app modal, flash and activate the modal browser.
2556 app_modal::AppModalDialog* active_dialog =
2557 app_modal::AppModalDialogQueue::GetInstance()->active_dialog();
2558 if (!active_dialog)
2559 return;
2561 Browser* modal_browser =
2562 chrome::FindBrowserWithWebContents(active_dialog->web_contents());
2563 if (modal_browser && (browser_ != modal_browser)) {
2564 modal_browser->window()->FlashFrame(true);
2565 modal_browser->window()->Activate();
2568 app_modal::AppModalDialogQueue::GetInstance()->ActivateModalDialog();
2571 int BrowserView::GetMaxTopInfoBarArrowHeight() {
2572 int top_arrow_height = 0;
2573 // Only show the arrows when not in fullscreen and when there's no omnibox
2574 // popup.
2575 if (!IsFullscreen() &&
2576 !GetLocationBar()->GetOmniboxView()->model()->popup_model()->IsOpen()) {
2577 gfx::Point icon_bottom(
2578 toolbar_->location_bar()->GetLocationBarAnchorPoint());
2579 ConvertPointToTarget(toolbar_->location_bar(), this, &icon_bottom);
2580 gfx::Point infobar_top(0, infobar_container_->GetVerticalOverlap(nullptr));
2581 ConvertPointToTarget(infobar_container_, this, &infobar_top);
2582 top_arrow_height = infobar_top.y() - icon_bottom.y();
2584 return top_arrow_height;
2587 ///////////////////////////////////////////////////////////////////////////////
2588 // BrowserView, ExclusiveAccessContext overrides
2589 Profile* BrowserView::GetProfile() {
2590 return browser_->profile();
2593 WebContents* BrowserView::GetActiveWebContents() {
2594 return browser_->tab_strip_model()->GetActiveWebContents();
2597 void BrowserView::UnhideDownloadShelf() {
2598 GetDownloadShelf()->Unhide();
2601 void BrowserView::HideDownloadShelf() {
2602 GetDownloadShelf()->Hide();
2603 StatusBubble* statusBubble = GetStatusBubble();
2604 if (statusBubble)
2605 statusBubble->Hide();
2608 ///////////////////////////////////////////////////////////////////////////////
2609 // BrowserView, ExclusiveAccessBubbleViewsContext overrides
2610 ExclusiveAccessManager* BrowserView::GetExclusiveAccessManager() {
2611 return browser_->exclusive_access_manager();
2614 bool BrowserView::IsImmersiveModeEnabled() {
2615 return immersive_mode_controller()->IsEnabled();
2618 views::Widget* BrowserView::GetBubbleAssociatedWidget() {
2619 return GetWidget();
2622 gfx::Rect BrowserView::GetTopContainerBoundsInScreen() {
2623 return top_container_->GetBoundsInScreen();