Popular sites on the NTP: check that experiment group StartsWith (rather than IS...
[chromium-blink-merge.git] / chrome / browser / ui / views / frame / browser_view.cc
blobf3e473ade16ba65957da56cd591b2eec3b21416f
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/location.h"
13 #include "base/memory/scoped_ptr.h"
14 #include "base/metrics/histogram.h"
15 #include "base/prefs/pref_service.h"
16 #include "base/profiler/scoped_tracker.h"
17 #include "base/single_thread_task_runner.h"
18 #include "base/strings/string_number_conversions.h"
19 #include "base/thread_task_runner_handle.h"
20 #include "chrome/app/chrome_command_ids.h"
21 #include "chrome/app/chrome_dll_resource.h"
22 #include "chrome/browser/app_mode/app_mode_utils.h"
23 #include "chrome/browser/bookmarks/bookmark_stats.h"
24 #include "chrome/browser/browser_process.h"
25 #include "chrome/browser/chrome_notification_types.h"
26 #include "chrome/browser/extensions/extension_util.h"
27 #include "chrome/browser/extensions/tab_helper.h"
28 #include "chrome/browser/infobars/infobar_service.h"
29 #include "chrome/browser/native_window_notification_source.h"
30 #include "chrome/browser/profiles/avatar_menu.h"
31 #include "chrome/browser/profiles/profile.h"
32 #include "chrome/browser/profiles/profile_avatar_icon_util.h"
33 #include "chrome/browser/profiles/profile_info_cache.h"
34 #include "chrome/browser/profiles/profile_manager.h"
35 #include "chrome/browser/profiles/profile_window.h"
36 #include "chrome/browser/profiles/profiles_state.h"
37 #include "chrome/browser/search/search.h"
38 #include "chrome/browser/sessions/tab_restore_service.h"
39 #include "chrome/browser/sessions/tab_restore_service_factory.h"
40 #include "chrome/browser/signin/chrome_signin_helper.h"
41 #include "chrome/browser/themes/theme_properties.h"
42 #include "chrome/browser/themes/theme_service_factory.h"
43 #include "chrome/browser/translate/chrome_translate_client.h"
44 #include "chrome/browser/ui/ash/ash_util.h"
45 #include "chrome/browser/ui/bookmarks/bookmark_bar_constants.h"
46 #include "chrome/browser/ui/bookmarks/bookmark_bubble_delegate.h"
47 #include "chrome/browser/ui/bookmarks/bookmark_bubble_sign_in_delegate.h"
48 #include "chrome/browser/ui/browser.h"
49 #include "chrome/browser/ui/browser_command_controller.h"
50 #include "chrome/browser/ui/browser_commands.h"
51 #include "chrome/browser/ui/browser_dialogs.h"
52 #include "chrome/browser/ui/browser_finder.h"
53 #include "chrome/browser/ui/browser_list.h"
54 #include "chrome/browser/ui/browser_window_state.h"
55 #include "chrome/browser/ui/search/search_delegate.h"
56 #include "chrome/browser/ui/search/search_model.h"
57 #include "chrome/browser/ui/search/search_ui.h"
58 #include "chrome/browser/ui/tabs/tab_menu_model.h"
59 #include "chrome/browser/ui/tabs/tab_strip_model.h"
60 #include "chrome/browser/ui/view_ids.h"
61 #include "chrome/browser/ui/views/accelerator_table.h"
62 #include "chrome/browser/ui/views/accessibility/invert_bubble_view.h"
63 #include "chrome/browser/ui/views/bookmarks/bookmark_bar_view.h"
64 #include "chrome/browser/ui/views/bookmarks/bookmark_bubble_view.h"
65 #include "chrome/browser/ui/views/browser_dialogs.h"
66 #include "chrome/browser/ui/views/download/download_in_progress_dialog_view.h"
67 #include "chrome/browser/ui/views/download/download_shelf_view.h"
68 #include "chrome/browser/ui/views/exclusive_access_bubble_views.h"
69 #include "chrome/browser/ui/views/extensions/bookmark_app_bubble_view.h"
70 #include "chrome/browser/ui/views/frame/browser_view_layout.h"
71 #include "chrome/browser/ui/views/frame/browser_view_layout_delegate.h"
72 #include "chrome/browser/ui/views/frame/contents_layout_manager.h"
73 #include "chrome/browser/ui/views/frame/immersive_mode_controller.h"
74 #include "chrome/browser/ui/views/frame/top_container_view.h"
75 #include "chrome/browser/ui/views/frame/web_contents_close_handler.h"
76 #include "chrome/browser/ui/views/infobars/infobar_container_view.h"
77 #include "chrome/browser/ui/views/location_bar/location_bar_view.h"
78 #include "chrome/browser/ui/views/location_bar/location_icon_view.h"
79 #include "chrome/browser/ui/views/location_bar/zoom_bubble_view.h"
80 #include "chrome/browser/ui/views/omnibox/omnibox_view_views.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/browser_actions_container.h"
91 #include "chrome/browser/ui/views/toolbar/reload_button.h"
92 #include "chrome/browser/ui/views/toolbar/toolbar_view.h"
93 #include "chrome/browser/ui/views/toolbar/wrench_toolbar_button.h"
94 #include "chrome/browser/ui/views/translate/translate_bubble_view.h"
95 #include "chrome/browser/ui/views/update_recommended_message_box.h"
96 #include "chrome/browser/ui/views/website_settings/permissions_bubble_view.h"
97 #include "chrome/browser/ui/views/website_settings/website_settings_popup_view.h"
98 #include "chrome/browser/ui/website_settings/permission_bubble_manager.h"
99 #include "chrome/browser/ui/window_sizer/window_sizer.h"
100 #include "chrome/common/chrome_switches.h"
101 #include "chrome/common/pref_names.h"
102 #include "chrome/common/url_constants.h"
103 #include "chrome/grit/chromium_strings.h"
104 #include "chrome/grit/generated_resources.h"
105 #include "chrome/grit/locale_settings.h"
106 #include "components/app_modal/app_modal_dialog.h"
107 #include "components/app_modal/app_modal_dialog_queue.h"
108 #include "components/app_modal/native_app_modal_dialog.h"
109 #include "components/omnibox/browser/omnibox_popup_model.h"
110 #include "components/omnibox/browser/omnibox_popup_view.h"
111 #include "components/omnibox/browser/omnibox_view.h"
112 #include "components/signin/core/common/profile_management_switches.h"
113 #include "components/translate/core/browser/language_state.h"
114 #include "content/app/resources/grit/content_resources.h"
115 #include "content/public/browser/download_manager.h"
116 #include "content/public/browser/notification_service.h"
117 #include "content/public/browser/render_frame_host.h"
118 #include "content/public/browser/render_view_host.h"
119 #include "content/public/browser/render_widget_host_view.h"
120 #include "content/public/browser/user_metrics.h"
121 #include "content/public/browser/web_contents.h"
122 #include "content/public/common/content_switches.h"
123 #include "grit/theme_resources.h"
124 #include "ui/accessibility/ax_view_state.h"
125 #include "ui/base/accelerators/accelerator.h"
126 #include "ui/base/hit_test.h"
127 #include "ui/base/l10n/l10n_util.h"
128 #include "ui/base/resource/material_design/material_design_controller.h"
129 #include "ui/base/resource/resource_bundle.h"
130 #include "ui/base/theme_provider.h"
131 #include "ui/content_accelerators/accelerator_util.h"
132 #include "ui/events/event_utils.h"
133 #include "ui/gfx/canvas.h"
134 #include "ui/gfx/color_utils.h"
135 #include "ui/gfx/geometry/rect_conversions.h"
136 #include "ui/gfx/screen.h"
137 #include "ui/strings/grit/ui_strings.h"
138 #include "ui/views/controls/button/menu_button.h"
139 #include "ui/views/controls/textfield/textfield.h"
140 #include "ui/views/controls/webview/webview.h"
141 #include "ui/views/focus/external_focus_tracker.h"
142 #include "ui/views/focus/view_storage.h"
143 #include "ui/views/layout/grid_layout.h"
144 #include "ui/views/widget/native_widget.h"
145 #include "ui/views/widget/root_view.h"
146 #include "ui/views/widget/widget.h"
147 #include "ui/views/window/dialog_delegate.h"
149 #if defined(USE_AURA)
150 #include "ui/aura/client/window_tree_client.h"
151 #include "ui/aura/window.h"
152 #include "ui/aura/window_tree_host.h"
153 #endif
155 #if defined(OS_WIN)
156 #include "base/win/windows_version.h"
157 #include "chrome/browser/jumplist_win.h"
158 #include "ui/views/win/scoped_fullscreen_visibility.h"
159 #endif
161 #if defined(ENABLE_ONE_CLICK_SIGNIN)
162 #include "chrome/browser/ui/sync/one_click_signin_bubble_delegate.h"
163 #include "chrome/browser/ui/sync/one_click_signin_bubble_links_delegate.h"
164 #include "chrome/browser/ui/views/sync/one_click_signin_bubble_view.h"
165 #endif
167 #if defined(OS_CHROMEOS)
168 #include "chrome/browser/ui/ash/multi_user/multi_user_window_manager.h"
169 #endif
171 using base::TimeDelta;
172 using base::UserMetricsAction;
173 using content::NativeWebKeyboardEvent;
174 using content::SSLStatus;
175 using content::WebContents;
176 using views::ColumnSet;
177 using views::GridLayout;
178 using web_modal::WebContentsModalDialogHost;
180 namespace {
182 // The name of a key to store on the window handle so that other code can
183 // locate this object using just the handle.
184 const char* const kBrowserViewKey = "__BROWSER_VIEW__";
186 // The number of milliseconds between loading animation frames.
187 const int kLoadingAnimationFrameTimeMs = 30;
189 // Paints the horizontal border separating the Bookmarks Bar from the Toolbar
190 // or page content according to |at_top| with |color|.
191 void PaintHorizontalBorder(gfx::Canvas* canvas,
192 BookmarkBarView* view,
193 bool at_top,
194 SkColor color) {
195 int thickness = views::NonClientFrameView::kClientEdgeThickness;
196 int y = at_top ? 0 : (view->height() - thickness);
197 canvas->FillRect(gfx::Rect(0, y, view->width(), thickness), color);
200 // TODO(kuan): These functions are temporarily for the bookmark bar while its
201 // detached state is at the top of the page; it'll be moved to float on the
202 // content page in the very near future, at which time, these local functions
203 // will be removed.
204 void PaintDetachedBookmarkBar(gfx::Canvas* canvas,
205 BookmarkBarView* view,
206 ThemeService* theme_service) {
207 // Paint background for detached state; if animating, this is fade in/out.
208 canvas->DrawColor(
209 chrome::GetDetachedBookmarkBarBackgroundColor(theme_service));
210 // Draw the separators above and below bookmark bar;
211 // if animating, these are fading in/out.
212 SkColor separator_color =
213 chrome::GetDetachedBookmarkBarSeparatorColor(theme_service);
215 if (ui::MaterialDesignController::IsModeMaterial()) {
216 BrowserView::Paint1pxHorizontalLine(
217 canvas, separator_color, gfx::RectF(0, 0, view->width(),
218 views::NonClientFrameView::kClientEdgeThickness));
219 } else {
220 PaintHorizontalBorder(canvas, view, true, separator_color);
223 BrowserView::Paint1pxHorizontalLine(
224 canvas,
225 SkColorSetA(separator_color, SkColorGetA(separator_color) / 2),
226 view->GetLocalBounds());
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 !ui::MaterialDesignController::IsModeMaterial()) {
249 // The pre-material design version of Ash provides additional lightening
250 // at the edges of the toolbar.
251 gfx::ImageSkia* toolbar_left =
252 theme_provider->GetImageSkiaNamed(IDR_TOOLBAR_SHADE_LEFT);
253 canvas->TileImageInt(*toolbar_left,
254 bounds.x(),
255 bounds.y(),
256 toolbar_left->width(),
257 bounds.height());
258 gfx::ImageSkia* toolbar_right =
259 theme_provider->GetImageSkiaNamed(IDR_TOOLBAR_SHADE_RIGHT);
260 canvas->TileImageInt(*toolbar_right,
261 bounds.right() - toolbar_right->width(),
262 bounds.y(),
263 toolbar_right->width(),
264 bounds.height());
268 void PaintAttachedBookmarkBar(gfx::Canvas* canvas,
269 BookmarkBarView* view,
270 BrowserView* browser_view,
271 chrome::HostDesktopType host_desktop_type,
272 int toolbar_overlap) {
273 // Paint background for attached state, this is fade in/out.
274 gfx::Point background_image_offset =
275 browser_view->OffsetPointForToolbarBackgroundImage(
276 gfx::Point(view->GetMirroredX(), view->y()));
277 PaintBackgroundAttachedMode(canvas,
278 view->GetThemeProvider(),
279 view->GetLocalBounds(),
280 background_image_offset,
281 host_desktop_type);
282 if (view->height() >= toolbar_overlap) {
283 // Draw the separator below the Bookmarks Bar; this is fading in/out.
284 if (ui::MaterialDesignController::IsModeMaterial()) {
285 BrowserView::Paint1pxHorizontalLine(
286 canvas,
287 ThemeProperties::GetDefaultColor(
288 ThemeProperties::COLOR_TOOLBAR_SEPARATOR),
289 view->GetLocalBounds());
290 } else {
291 PaintHorizontalBorder(canvas,
292 view,
293 false,
294 ThemeProperties::GetDefaultColor(
295 ThemeProperties::COLOR_TOOLBAR_SEPARATOR));
300 } // namespace
302 ///////////////////////////////////////////////////////////////////////////////
303 // Delegate implementation for BrowserViewLayout. Usually just forwards calls
304 // into BrowserView.
305 class BrowserViewLayoutDelegateImpl : public BrowserViewLayoutDelegate {
306 public:
307 explicit BrowserViewLayoutDelegateImpl(BrowserView* browser_view)
308 : browser_view_(browser_view) {}
309 ~BrowserViewLayoutDelegateImpl() override {}
311 // BrowserViewLayoutDelegate overrides:
312 views::View* GetContentsWebView() const override {
313 return browser_view_->contents_web_view_;
316 bool DownloadShelfNeedsLayout() const override {
317 DownloadShelfView* download_shelf = browser_view_->download_shelf_.get();
318 // Re-layout the shelf either if it is visible or if its close animation
319 // is currently running.
320 return download_shelf &&
321 (download_shelf->IsShowing() || download_shelf->IsClosing());
324 bool IsTabStripVisible() const override {
325 return browser_view_->IsTabStripVisible();
328 gfx::Rect GetBoundsForTabStripInBrowserView() const override {
329 gfx::RectF bounds_f(browser_view_->frame()->GetBoundsForTabStrip(
330 browser_view_->tabstrip()));
331 views::View::ConvertRectToTarget(browser_view_->parent(), browser_view_,
332 &bounds_f);
333 return gfx::ToEnclosingRect(bounds_f);
336 int GetTopInsetInBrowserView() const override {
337 return browser_view_->frame()->GetTopInset() -
338 browser_view_->y();
341 int GetThemeBackgroundXInset() const override {
342 // TODO(pkotwicz): Return the inset with respect to the left edge of the
343 // BrowserView.
344 return browser_view_->frame()->GetThemeBackgroundXInset();
347 bool IsToolbarVisible() const override {
348 return browser_view_->IsToolbarVisible();
351 bool IsBookmarkBarVisible() const override {
352 return browser_view_->IsBookmarkBarVisible();
355 ExclusiveAccessBubbleViews* GetExclusiveAccessBubble() const override {
356 return browser_view_->exclusive_access_bubble();
359 private:
360 BrowserView* browser_view_;
362 DISALLOW_COPY_AND_ASSIGN(BrowserViewLayoutDelegateImpl);
365 // This class is used to paint the background for Bookmarks Bar.
366 class BookmarkBarViewBackground : public views::Background {
367 public:
368 BookmarkBarViewBackground(BrowserView* browser_view,
369 BookmarkBarView* bookmark_bar_view,
370 Browser* browser);
372 // views:Background:
373 void Paint(gfx::Canvas* canvas, views::View* view) const override;
375 private:
376 BrowserView* browser_view_;
378 // The view hosting this background.
379 BookmarkBarView* bookmark_bar_view_;
381 Browser* browser_;
383 DISALLOW_COPY_AND_ASSIGN(BookmarkBarViewBackground);
386 BookmarkBarViewBackground::BookmarkBarViewBackground(
387 BrowserView* browser_view,
388 BookmarkBarView* bookmark_bar_view,
389 Browser* browser)
390 : browser_view_(browser_view),
391 bookmark_bar_view_(bookmark_bar_view),
392 browser_(browser) {
395 void BookmarkBarViewBackground::Paint(gfx::Canvas* canvas,
396 views::View* view) const {
397 int toolbar_overlap = bookmark_bar_view_->GetToolbarOverlap();
398 if (!bookmark_bar_view_->IsDetached()) {
399 PaintAttachedBookmarkBar(canvas,
400 bookmark_bar_view_,
401 browser_view_,
402 browser_->host_desktop_type(),
403 toolbar_overlap);
404 return;
407 // As 'hidden' according to the animation is the full in-tab state, we invert
408 // the value - when current_state is at '0', we expect the bar to be docked.
409 double current_state = 1 - bookmark_bar_view_->GetAnimationValue();
411 ThemeService* ts = ThemeServiceFactory::GetForProfile(browser_->profile());
412 if (current_state == 0.0 || current_state == 1.0) {
413 PaintDetachedBookmarkBar(canvas, bookmark_bar_view_, ts);
414 return;
416 // While animating, set opacity to cross-fade between attached and detached
417 // backgrounds including their respective separators.
418 int detached_alpha = static_cast<uint8>(current_state * 255);
419 int attached_alpha = 255 - detached_alpha;
420 if (browser_->bookmark_bar_state() == BookmarkBar::DETACHED) {
421 // To animate from attached to detached state:
422 // - fade out attached background
423 // - fade in detached background.
424 canvas->SaveLayerAlpha(attached_alpha);
425 PaintAttachedBookmarkBar(canvas,
426 bookmark_bar_view_,
427 browser_view_,
428 browser_->host_desktop_type(),
429 toolbar_overlap);
430 canvas->Restore();
431 canvas->SaveLayerAlpha(detached_alpha);
432 PaintDetachedBookmarkBar(canvas, bookmark_bar_view_, ts);
433 } else {
434 // To animate from detached to attached state:
435 // - fade out detached background
436 // - fade in attached background.
437 canvas->SaveLayerAlpha(detached_alpha);
438 PaintDetachedBookmarkBar(canvas, bookmark_bar_view_, ts);
439 canvas->Restore();
440 canvas->SaveLayerAlpha(attached_alpha);
441 PaintAttachedBookmarkBar(canvas,
442 bookmark_bar_view_,
443 browser_view_,
444 browser_->host_desktop_type(),
445 toolbar_overlap);
447 canvas->Restore();
450 ///////////////////////////////////////////////////////////////////////////////
451 // BrowserView, public:
453 // static
454 const char BrowserView::kViewClassName[] = "BrowserView";
456 BrowserView::BrowserView()
457 : views::ClientView(nullptr, nullptr),
458 last_focused_view_storage_id_(views::ViewStorage::GetInstance()
459 ->CreateStorageID()),
460 frame_(nullptr),
461 top_container_(nullptr),
462 tabstrip_(nullptr),
463 toolbar_(nullptr),
464 find_bar_host_view_(nullptr),
465 infobar_container_(nullptr),
466 contents_web_view_(nullptr),
467 devtools_web_view_(nullptr),
468 contents_container_(nullptr),
469 initialized_(false),
470 in_process_fullscreen_(false),
471 #if defined(OS_WIN)
472 ticker_(0),
473 hung_window_detector_(&hung_plugin_action_),
474 #endif
475 force_location_bar_focus_(false),
476 activate_modal_dialog_factory_(this) {
479 BrowserView::~BrowserView() {
480 // All the tabs should have been destroyed already. If we were closed by the
481 // OS with some tabs than the NativeBrowserFrame should have destroyed them.
482 DCHECK_EQ(0, browser_->tab_strip_model()->count());
484 // Immersive mode may need to reparent views before they are removed/deleted.
485 immersive_mode_controller_.reset();
487 browser_->tab_strip_model()->RemoveObserver(this);
489 #if defined(OS_WIN)
490 // Stop hung plugin monitoring.
491 ticker_.Stop();
492 ticker_.UnregisterTickHandler(&hung_window_detector_);
494 // Terminate the jumplist (must be called before browser_->profile() is
495 // destroyed.
496 if (jumplist_.get()) {
497 jumplist_->Terminate();
499 #endif
501 // We destroy the download shelf before |browser_| to remove its child
502 // download views from the set of download observers (since the observed
503 // downloads can be destroyed along with |browser_| and the observer
504 // notifications will call back into deleted objects).
505 BrowserViewLayout* browser_view_layout = GetBrowserViewLayout();
506 if (browser_view_layout)
507 browser_view_layout->set_download_shelf(nullptr);
508 download_shelf_.reset();
510 // The TabStrip attaches a listener to the model. Make sure we shut down the
511 // TabStrip first so that it can cleanly remove the listener.
512 if (tabstrip_) {
513 tabstrip_->parent()->RemoveChildView(tabstrip_);
514 if (browser_view_layout)
515 browser_view_layout->set_tab_strip(nullptr);
516 delete tabstrip_;
517 tabstrip_ = nullptr;
519 // Child views maintain PrefMember attributes that point to
520 // OffTheRecordProfile's PrefService which gets deleted by ~Browser.
521 RemoveAllChildViews(true);
522 toolbar_ = nullptr;
524 // Explicitly set browser_ to null.
525 browser_.reset();
528 void BrowserView::Init(Browser* browser) {
529 browser_.reset(browser);
530 browser_->tab_strip_model()->AddObserver(this);
531 immersive_mode_controller_.reset(
532 chrome::CreateImmersiveModeController(browser_->host_desktop_type()));
535 // static
536 BrowserView* BrowserView::GetBrowserViewForNativeWindow(
537 gfx::NativeWindow window) {
538 views::Widget* widget = views::Widget::GetWidgetForNativeWindow(window);
539 return widget ?
540 reinterpret_cast<BrowserView*>(widget->GetNativeWindowProperty(
541 kBrowserViewKey)) : nullptr;
544 // static
545 BrowserView* BrowserView::GetBrowserViewForBrowser(const Browser* browser) {
546 return static_cast<BrowserView*>(browser->window());
549 // static
550 void BrowserView::Paint1pxHorizontalLine(
551 gfx::Canvas* canvas,
552 SkColor color,
553 gfx::RectF bounds) {
554 canvas->Save();
555 SkScalar scale_factor = 1.0f / canvas->image_scale();
556 canvas->sk_canvas()->scale(scale_factor, scale_factor);
558 bounds.Scale(canvas->image_scale(), canvas->image_scale());
559 bounds.Inset(0, bounds.height() - 1, 0, 0);
561 SkPaint paint;
562 paint.setColor(color);
563 canvas->sk_canvas()->drawRect(gfx::RectFToSkRect(bounds), paint);
564 canvas->Restore();
567 void BrowserView::InitStatusBubble() {
568 status_bubble_.reset(new StatusBubbleViews(contents_web_view_));
569 contents_web_view_->SetStatusBubble(status_bubble_.get());
572 gfx::Rect BrowserView::GetToolbarBounds() const {
573 gfx::Rect toolbar_bounds(toolbar_->bounds());
574 if (toolbar_bounds.IsEmpty())
575 return toolbar_bounds;
576 // The apparent toolbar edges are outside the "real" toolbar edges.
577 toolbar_bounds.Inset(-views::NonClientFrameView::kClientEdgeThickness, 0);
578 return toolbar_bounds;
581 gfx::Rect BrowserView::GetFindBarBoundingBox() const {
582 return GetBrowserViewLayout()->GetFindBarBoundingBox();
585 int BrowserView::GetTabStripHeight() const {
586 // We want to return tabstrip_->height(), but we might be called in the midst
587 // of layout, when that hasn't yet been updated to reflect the current state.
588 // So return what the tabstrip height _ought_ to be right now.
589 return IsTabStripVisible() ? tabstrip_->GetPreferredSize().height() : 0;
592 gfx::Point BrowserView::OffsetPointForToolbarBackgroundImage(
593 const gfx::Point& point) const {
594 // The background image starts tiling horizontally at the window left edge and
595 // vertically at the top edge of the horizontal tab strip (or where it would
596 // be). We expect our parent's origin to be the window origin.
597 gfx::Point window_point(point + GetMirroredPosition().OffsetFromOrigin());
598 window_point.Offset(frame_->GetThemeBackgroundXInset(),
599 -frame_->GetTopInset());
600 return window_point;
603 bool BrowserView::IsTabStripVisible() const {
604 if (immersive_mode_controller_->ShouldHideTopViews() &&
605 immersive_mode_controller_->ShouldHideTabIndicators())
606 return false;
607 return browser_->SupportsWindowFeature(Browser::FEATURE_TABSTRIP);
610 bool BrowserView::IsOffTheRecord() const {
611 return browser_->profile()->IsOffTheRecord();
614 bool BrowserView::IsGuestSession() const {
615 return browser_->profile()->IsGuestSession();
618 bool BrowserView::IsRegularOrGuestSession() const {
619 return profiles::IsRegularOrGuestSession(browser_.get());
622 bool BrowserView::ShouldShowAvatar() const {
623 #if defined(OS_CHROMEOS)
624 if (!browser_->is_type_tabbed() && !browser_->is_app())
625 return false;
626 // Don't show incognito avatar in the guest session.
627 if (IsOffTheRecord() && !IsGuestSession())
628 return true;
629 // This function is called via BrowserNonClientFrameView::UpdateAvatarInfo
630 // during the creation of the BrowserWindow, so browser->window() will not
631 // yet be set. In this case we can safely return false.
632 if (!browser_->window())
633 return false;
634 return chrome::MultiUserWindowManager::ShouldShowAvatar(
635 browser_->window()->GetNativeWindow());
636 #else
637 if (!IsBrowserTypeNormal())
638 return false;
639 if (IsOffTheRecord()) // Desktop guest is incognito and needs avatar.
640 return true;
641 // Tests may not have a profile manager.
642 if (!g_browser_process->profile_manager())
643 return false;
644 ProfileInfoCache& cache =
645 g_browser_process->profile_manager()->GetProfileInfoCache();
646 if (cache.GetIndexOfProfileWithPath(browser_->profile()->GetPath()) ==
647 std::string::npos) {
648 return false;
651 return AvatarMenu::ShouldShowAvatarMenu();
652 #endif
655 bool BrowserView::GetAccelerator(int cmd_id,
656 ui::Accelerator* accelerator) const {
657 // We retrieve the accelerator information for standard accelerators
658 // for cut, copy and paste.
659 if (chrome::GetStandardAcceleratorForCommandId(cmd_id, accelerator))
660 return true;
661 // Else, we retrieve the accelerator information from the accelerator table.
662 for (std::map<ui::Accelerator, int>::const_iterator it =
663 accelerator_table_.begin(); it != accelerator_table_.end(); ++it) {
664 if (it->second == cmd_id) {
665 *accelerator = it->first;
666 return true;
669 // Else, we retrieve the accelerator information from Ash (if applicable).
670 return chrome::GetAshAcceleratorForCommandId(
671 cmd_id, browser_->host_desktop_type(), accelerator);
674 bool BrowserView::IsAcceleratorRegistered(const ui::Accelerator& accelerator) {
675 return accelerator_table_.find(accelerator) != accelerator_table_.end();
678 WebContents* BrowserView::GetActiveWebContents() const {
679 return browser_->tab_strip_model()->GetActiveWebContents();
682 gfx::ImageSkia BrowserView::GetOTRAvatarIcon() const {
683 return *GetThemeProvider()->GetImageSkiaNamed(IDR_OTR_ICON);
686 ///////////////////////////////////////////////////////////////////////////////
687 // BrowserView, BrowserWindow implementation:
689 void BrowserView::Show() {
690 #if !defined(OS_WIN)
691 // The Browser associated with this browser window must become the active
692 // browser at the time |Show()| is called. This is the natural behavior under
693 // Windows and Ash, but other platforms will not trigger
694 // OnWidgetActivationChanged() until we return to the runloop. Therefore any
695 // calls to Browser::GetLastActive() will return the wrong result if we do not
696 // explicitly set it here.
697 // A similar block also appears in BrowserWindowCocoa::Show().
698 if (browser()->host_desktop_type() != chrome::HOST_DESKTOP_TYPE_ASH)
699 BrowserList::SetLastActive(browser());
700 #endif
702 // If the window is already visible, just activate it.
703 if (frame_->IsVisible()) {
704 frame_->Activate();
705 return;
708 // Showing the window doesn't make the browser window active right away.
709 // This can cause SetFocusToLocationBar() to skip setting focus to the
710 // location bar. To avoid this we explicilty let SetFocusToLocationBar()
711 // know that it's ok to steal focus.
712 force_location_bar_focus_ = true;
714 // Setting the focus doesn't work when the window is invisible, so any focus
715 // initialization that happened before this will be lost.
717 // We really "should" restore the focus whenever the window becomes unhidden,
718 // but I think initializing is the only time where this can happen where
719 // there is some focus change we need to pick up, and this is easier than
720 // plumbing through an un-hide message all the way from the frame.
722 // If we do find there are cases where we need to restore the focus on show,
723 // that should be added and this should be removed.
724 RestoreFocus();
726 frame_->Show();
728 force_location_bar_focus_ = false;
730 browser()->OnWindowDidShow();
732 chrome::MaybeShowInvertBubbleView(this);
735 void BrowserView::ShowInactive() {
736 if (!frame_->IsVisible())
737 frame_->ShowInactive();
740 void BrowserView::Hide() {
741 // Not implemented.
744 void BrowserView::SetBounds(const gfx::Rect& bounds) {
745 ExitFullscreen();
746 GetWidget()->SetBounds(bounds);
749 void BrowserView::Close() {
750 frame_->Close();
753 void BrowserView::Activate() {
754 frame_->Activate();
757 void BrowserView::Deactivate() {
758 frame_->Deactivate();
761 bool BrowserView::IsActive() const {
762 return frame_->IsActive();
765 void BrowserView::FlashFrame(bool flash) {
766 frame_->FlashFrame(flash);
769 bool BrowserView::IsAlwaysOnTop() const {
770 return false;
773 void BrowserView::SetAlwaysOnTop(bool always_on_top) {
774 // Not implemented for browser windows.
775 NOTIMPLEMENTED();
778 gfx::NativeWindow BrowserView::GetNativeWindow() const {
779 // While the browser destruction is going on, the widget can already be gone,
780 // but utility functions like FindBrowserWithWindow will come here and crash.
781 // We short circuit therefore.
782 if (!GetWidget())
783 return nullptr;
784 return GetWidget()->GetTopLevelWidget()->GetNativeWindow();
787 StatusBubble* BrowserView::GetStatusBubble() {
788 return status_bubble_.get();
791 namespace {
792 // Only used by ToolbarSizeChanged() below, but placed here because template
793 // arguments (to base::AutoReset<>) must have external linkage.
794 enum CallState { NORMAL, REENTRANT, REENTRANT_FORCE_FAST_RESIZE };
797 void BrowserView::UpdateTitleBar() {
798 // TODO(robliao): Remove ScopedTracker below once https://crbug.com/467185 is
799 // fixed.
800 tracked_objects::ScopedTracker tracking_profile1(
801 FROM_HERE_WITH_EXPLICIT_FUNCTION("467185 BrowserView::UpdateTitleBar1"));
802 frame_->UpdateWindowTitle();
803 if (ShouldShowWindowIcon() && !loading_animation_timer_.IsRunning()) {
804 // TODO(robliao): Remove ScopedTracker below once https://crbug.com/467185
805 // is fixed.
806 tracked_objects::ScopedTracker tracking_profile2(
807 FROM_HERE_WITH_EXPLICIT_FUNCTION(
808 "467185 BrowserView::UpdateTitleBar2"));
809 frame_->UpdateWindowIcon();
813 void BrowserView::BookmarkBarStateChanged(
814 BookmarkBar::AnimateChangeType change_type) {
815 if (bookmark_bar_view_.get()) {
816 BookmarkBar::State new_state = browser_->bookmark_bar_state();
818 // We don't properly support animating the bookmark bar to and from the
819 // detached state in immersive fullscreen.
820 bool detached_changed = (new_state == BookmarkBar::DETACHED) ||
821 bookmark_bar_view_->IsDetached();
822 if (detached_changed && immersive_mode_controller_->IsEnabled())
823 change_type = BookmarkBar::DONT_ANIMATE_STATE_CHANGE;
825 bookmark_bar_view_->SetBookmarkBarState(new_state, change_type);
827 if (MaybeShowBookmarkBar(GetActiveWebContents()))
828 Layout();
831 void BrowserView::UpdateDevTools() {
832 UpdateDevToolsForContents(GetActiveWebContents(), true);
833 Layout();
836 void BrowserView::UpdateLoadingAnimations(bool should_animate) {
837 if (should_animate) {
838 if (!loading_animation_timer_.IsRunning()) {
839 // Loads are happening, and the timer isn't running, so start it.
840 last_animation_time_ = base::TimeTicks::Now();
841 loading_animation_timer_.Start(FROM_HERE,
842 TimeDelta::FromMilliseconds(kLoadingAnimationFrameTimeMs), this,
843 &BrowserView::LoadingAnimationCallback);
845 } else {
846 if (loading_animation_timer_.IsRunning()) {
847 last_animation_time_ = base::TimeTicks();
848 loading_animation_timer_.Stop();
849 // Loads are now complete, update the state if a task was scheduled.
850 LoadingAnimationCallback();
855 void BrowserView::SetStarredState(bool is_starred) {
856 GetLocationBarView()->SetStarToggled(is_starred);
859 void BrowserView::SetTranslateIconToggled(bool is_lit) {
860 GetLocationBarView()->SetTranslateIconToggled(is_lit);
863 void BrowserView::OnActiveTabChanged(content::WebContents* old_contents,
864 content::WebContents* new_contents,
865 int index,
866 int reason) {
867 DCHECK(new_contents);
869 // If |contents_container_| already has the correct WebContents, we can save
870 // some work. This also prevents extra events from being reported by the
871 // Visibility API under Windows, as ChangeWebContents will briefly hide
872 // the WebContents window.
873 bool change_tab_contents =
874 contents_web_view_->web_contents() != new_contents;
876 // Update various elements that are interested in knowing the current
877 // WebContents.
879 // When we toggle the NTP floating bookmarks bar and/or the info bar,
880 // we don't want any WebContents to be attached, so that we
881 // avoid an unnecessary resize and re-layout of a WebContents.
882 if (change_tab_contents) {
883 contents_web_view_->SetWebContents(nullptr);
884 devtools_web_view_->SetWebContents(nullptr);
887 // Do this before updating InfoBarContainer as the InfoBarContainer may
888 // callback to us and trigger layout.
889 if (bookmark_bar_view_.get()) {
890 bookmark_bar_view_->SetBookmarkBarState(
891 browser_->bookmark_bar_state(),
892 BookmarkBar::DONT_ANIMATE_STATE_CHANGE);
895 infobar_container_->ChangeInfoBarManager(
896 InfoBarService::FromWebContents(new_contents));
898 if (old_contents && PermissionBubbleManager::FromWebContents(old_contents))
899 PermissionBubbleManager::FromWebContents(old_contents)->HideBubble();
901 if (new_contents && PermissionBubbleManager::FromWebContents(new_contents)) {
902 PermissionBubbleManager::FromWebContents(new_contents)
903 ->DisplayPendingRequests();
906 UpdateUIForContents(new_contents);
908 // Layout for DevTools _before_ setting the both main and devtools WebContents
909 // to avoid toggling the size of any of them.
910 UpdateDevToolsForContents(new_contents, !change_tab_contents);
912 if (change_tab_contents) {
913 web_contents_close_handler_->ActiveTabChanged();
914 contents_web_view_->SetWebContents(new_contents);
915 // The second layout update should be no-op. It will just set the
916 // DevTools WebContents.
917 UpdateDevToolsForContents(new_contents, true);
920 if (!browser_->tab_strip_model()->closing_all() && GetWidget()->IsActive() &&
921 GetWidget()->IsVisible()) {
922 // We only restore focus if our window is visible, to avoid invoking blur
923 // handlers when we are eventually shown.
924 new_contents->RestoreFocus();
927 // Update all the UI bits.
928 UpdateTitleBar();
930 TranslateBubbleView::CloseBubble();
931 ZoomBubbleView::CloseBubble();
934 void BrowserView::ZoomChangedForActiveTab(bool can_show_bubble) {
935 GetLocationBarView()->ZoomChangedForActiveTab(
936 can_show_bubble && !toolbar_->IsWrenchMenuShowing());
939 gfx::Rect BrowserView::GetRestoredBounds() const {
940 gfx::Rect bounds;
941 ui::WindowShowState state;
942 frame_->GetWindowPlacement(&bounds, &state);
943 return bounds;
946 ui::WindowShowState BrowserView::GetRestoredState() const {
947 gfx::Rect bounds;
948 ui::WindowShowState state;
949 frame_->GetWindowPlacement(&bounds, &state);
950 return state;
953 gfx::Rect BrowserView::GetBounds() const {
954 return frame_->GetWindowBoundsInScreen();
957 bool BrowserView::IsMaximized() const {
958 return frame_->IsMaximized();
961 bool BrowserView::IsMinimized() const {
962 return frame_->IsMinimized();
965 void BrowserView::Maximize() {
966 frame_->Maximize();
969 void BrowserView::Minimize() {
970 frame_->Minimize();
973 void BrowserView::Restore() {
974 frame_->Restore();
977 void BrowserView::EnterFullscreen(const GURL& url,
978 ExclusiveAccessBubbleType bubble_type,
979 bool with_toolbar) {
980 if (IsFullscreen())
981 return; // Nothing to do.
983 ProcessFullscreen(true, NORMAL_FULLSCREEN, url, bubble_type);
986 void BrowserView::ExitFullscreen() {
987 if (!IsFullscreen())
988 return; // Nothing to do.
990 ProcessFullscreen(false, NORMAL_FULLSCREEN, GURL(),
991 EXCLUSIVE_ACCESS_BUBBLE_TYPE_NONE);
994 void BrowserView::UpdateExclusiveAccessExitBubbleContent(
995 const GURL& url,
996 ExclusiveAccessBubbleType bubble_type) {
997 // Immersive mode has no exit bubble because it has a visible strip at the
998 // top that gives the user a hover target.
999 // TODO(jamescook): Figure out what to do with mouse-lock.
1000 if (bubble_type == EXCLUSIVE_ACCESS_BUBBLE_TYPE_NONE ||
1001 ShouldUseImmersiveFullscreenForUrl(url)) {
1002 exclusive_access_bubble_.reset();
1003 } else if (exclusive_access_bubble_.get()) {
1004 exclusive_access_bubble_->UpdateContent(url, bubble_type);
1005 } else {
1006 exclusive_access_bubble_.reset(
1007 new ExclusiveAccessBubbleViews(this, url, bubble_type));
1011 bool BrowserView::ShouldHideUIForFullscreen() const {
1012 // Immersive mode needs UI for the slide-down top panel.
1013 if (immersive_mode_controller_->IsEnabled())
1014 return false;
1016 return IsFullscreen();
1019 bool BrowserView::IsFullscreen() const {
1020 return frame_->IsFullscreen();
1023 bool BrowserView::IsFullscreenBubbleVisible() const {
1024 return exclusive_access_bubble_ != nullptr;
1027 bool BrowserView::SupportsFullscreenWithToolbar() const {
1028 return false;
1031 void BrowserView::UpdateFullscreenWithToolbar(bool with_toolbar) {
1032 // This is currently a Mac only feature.
1033 NOTIMPLEMENTED();
1036 bool BrowserView::IsFullscreenWithToolbar() const {
1037 return false;
1040 #if defined(OS_WIN)
1041 void BrowserView::SetMetroSnapMode(bool enable) {
1042 LOCAL_HISTOGRAM_COUNTS("Metro.SnapModeToggle", enable);
1043 ProcessFullscreen(enable, METRO_SNAP_FULLSCREEN, GURL(),
1044 EXCLUSIVE_ACCESS_BUBBLE_TYPE_NONE);
1047 bool BrowserView::IsInMetroSnapMode() const {
1048 return false;
1050 #endif // defined(OS_WIN)
1052 void BrowserView::RestoreFocus() {
1053 WebContents* selected_web_contents = GetActiveWebContents();
1054 if (selected_web_contents)
1055 selected_web_contents->RestoreFocus();
1058 void BrowserView::FullscreenStateChanged() {
1059 CHECK(!IsFullscreen());
1060 ProcessFullscreen(false, NORMAL_FULLSCREEN, GURL(),
1061 EXCLUSIVE_ACCESS_BUBBLE_TYPE_NONE);
1064 LocationBar* BrowserView::GetLocationBar() const {
1065 return GetLocationBarView();
1068 void BrowserView::SetFocusToLocationBar(bool select_all) {
1069 // On Windows, changing focus to the location bar causes the browser
1070 // window to become active. This can steal focus if the user has
1071 // another window open already. On ChromeOS, changing focus makes a
1072 // view believe it has a focus even if the widget doens't have a
1073 // focus. Either cases, we need to ignore this when the browser
1074 // window isn't active.
1075 #if defined(OS_WIN) || defined(OS_CHROMEOS)
1076 if (!force_location_bar_focus_ && !IsActive())
1077 return;
1078 #endif
1080 // Temporarily reveal the top-of-window views (if not already revealed) so
1081 // that the location bar view is visible and is considered focusable. If the
1082 // location bar view gains focus, |immersive_mode_controller_| will keep the
1083 // top-of-window views revealed.
1084 scoped_ptr<ImmersiveRevealedLock> focus_reveal_lock(
1085 immersive_mode_controller_->GetRevealedLock(
1086 ImmersiveModeController::ANIMATE_REVEAL_YES));
1088 LocationBarView* location_bar = GetLocationBarView();
1089 if (location_bar->omnibox_view()->IsFocusable()) {
1090 // Location bar got focus.
1091 location_bar->FocusLocation(select_all);
1092 } else {
1093 // If none of location bar got focus, then clear focus.
1094 views::FocusManager* focus_manager = GetFocusManager();
1095 DCHECK(focus_manager);
1096 focus_manager->ClearFocus();
1100 void BrowserView::UpdateReloadStopState(bool is_loading, bool force) {
1101 toolbar_->reload_button()->ChangeMode(
1102 is_loading ? ReloadButton::MODE_STOP : ReloadButton::MODE_RELOAD, force);
1105 void BrowserView::UpdateToolbar(content::WebContents* contents) {
1106 // We may end up here during destruction.
1107 if (toolbar_)
1108 toolbar_->Update(contents);
1109 frame_->UpdateToolbar();
1112 void BrowserView::ResetToolbarTabState(content::WebContents* contents) {
1113 // We may end up here during destruction.
1114 if (toolbar_)
1115 toolbar_->ResetTabState(contents);
1118 void BrowserView::FocusToolbar() {
1119 // Temporarily reveal the top-of-window views (if not already revealed) so
1120 // that the toolbar is visible and is considered focusable. If the
1121 // toolbar gains focus, |immersive_mode_controller_| will keep the
1122 // top-of-window views revealed.
1123 scoped_ptr<ImmersiveRevealedLock> focus_reveal_lock(
1124 immersive_mode_controller_->GetRevealedLock(
1125 ImmersiveModeController::ANIMATE_REVEAL_YES));
1127 // Start the traversal within the main toolbar. SetPaneFocus stores
1128 // the current focused view before changing focus.
1129 toolbar_->SetPaneFocus(nullptr);
1132 ToolbarActionsBar* BrowserView::GetToolbarActionsBar() {
1133 return toolbar_ ?
1134 toolbar_->browser_actions()->toolbar_actions_bar() : nullptr;
1137 void BrowserView::ToolbarSizeChanged(bool is_animating) {
1138 // The call to SetMaxTopArrowHeight() below can result in reentrancy;
1139 // |call_state| tracks whether we're reentrant. We can't just early-return in
1140 // this case because we need to layout again so the infobar container's bounds
1141 // are set correctly.
1142 static CallState call_state = NORMAL;
1144 // A reentrant call can (and should) use the fast resize path unless both it
1145 // and the normal call are both non-animating.
1146 bool use_fast_resize =
1147 is_animating || (call_state == REENTRANT_FORCE_FAST_RESIZE);
1148 if (use_fast_resize)
1149 contents_web_view_->SetFastResize(true);
1150 UpdateUIForContents(GetActiveWebContents());
1151 if (use_fast_resize)
1152 contents_web_view_->SetFastResize(false);
1154 // Inform the InfoBarContainer that the distance to the location icon may have
1155 // changed. We have to do this after the block above so that the toolbars are
1156 // laid out correctly for calculating the maximum arrow height below.
1158 base::AutoReset<CallState> resetter(&call_state,
1159 is_animating ? REENTRANT_FORCE_FAST_RESIZE : REENTRANT);
1160 SetMaxTopArrowHeight(GetMaxTopInfoBarArrowHeight(), infobar_container_);
1163 // When transitioning from animating to not animating we need to make sure the
1164 // contents_container_ gets layed out. If we don't do this and the bounds
1165 // haven't changed contents_container_ won't get a Layout out and we'll end up
1166 // with a gray rect because the clip wasn't updated. Note that a reentrant
1167 // call never needs to do this, because after it returns, the normal call
1168 // wrapping it will do it.
1169 if ((call_state == NORMAL) && !is_animating) {
1170 contents_web_view_->InvalidateLayout();
1171 contents_container_->Layout();
1175 void BrowserView::FocusBookmarksToolbar() {
1176 DCHECK(!immersive_mode_controller_->IsEnabled());
1177 if (bookmark_bar_view_.get() &&
1178 bookmark_bar_view_->visible() &&
1179 bookmark_bar_view_->GetPreferredSize().height() != 0) {
1180 bookmark_bar_view_->SetPaneFocusAndFocusDefault();
1184 void BrowserView::FocusInfobars() {
1185 if (infobar_container_->child_count() > 0)
1186 infobar_container_->SetPaneFocusAndFocusDefault();
1189 void BrowserView::FocusAppMenu() {
1190 // Chrome doesn't have a traditional menu bar, but it has a menu button in the
1191 // main toolbar that plays the same role. If the user presses a key that
1192 // would typically focus the menu bar, tell the toolbar to focus the menu
1193 // button. If the user presses the key again, return focus to the previous
1194 // location.
1196 // Not used on the Mac, which has a normal menu bar.
1197 if (toolbar_->IsAppMenuFocused()) {
1198 RestoreFocus();
1199 } else {
1200 DCHECK(!immersive_mode_controller_->IsEnabled());
1201 toolbar_->SetPaneFocusAndFocusAppMenu();
1205 void BrowserView::RotatePaneFocus(bool forwards) {
1206 GetFocusManager()->RotatePaneFocus(
1207 forwards ?
1208 views::FocusManager::kForward : views::FocusManager::kBackward,
1209 views::FocusManager::kWrap);
1212 void BrowserView::DestroyBrowser() {
1213 // After this returns other parts of Chrome are going to be shutdown. Close
1214 // the window now so that we are deleted immediately and aren't left holding
1215 // references to deleted objects.
1216 GetWidget()->RemoveObserver(this);
1217 GetLocationBar()->GetOmniboxView()->model()->popup_model()->RemoveObserver(
1218 this);
1219 frame_->CloseNow();
1222 bool BrowserView::IsBookmarkBarVisible() const {
1223 if (!browser_->SupportsWindowFeature(Browser::FEATURE_BOOKMARKBAR))
1224 return false;
1225 if (!bookmark_bar_view_.get())
1226 return false;
1227 if (bookmark_bar_view_->GetPreferredSize().height() == 0)
1228 return false;
1229 // New tab page needs visible bookmarks even when top-views are hidden.
1230 if (immersive_mode_controller_->ShouldHideTopViews() &&
1231 !bookmark_bar_view_->IsDetached())
1232 return false;
1233 return true;
1236 bool BrowserView::IsBookmarkBarAnimating() const {
1237 return bookmark_bar_view_.get() && bookmark_bar_view_->is_animating();
1240 bool BrowserView::IsTabStripEditable() const {
1241 return tabstrip_->IsTabStripEditable();
1244 bool BrowserView::IsToolbarVisible() const {
1245 if (immersive_mode_controller_->ShouldHideTopViews())
1246 return false;
1247 return browser_->SupportsWindowFeature(Browser::FEATURE_TOOLBAR) ||
1248 browser_->SupportsWindowFeature(Browser::FEATURE_LOCATIONBAR);
1251 gfx::Rect BrowserView::GetRootWindowResizerRect() const {
1252 // Views does not support resizer rects because they caused page cycler
1253 // performance regressions when they were added. See crrev.com/9654
1254 return gfx::Rect();
1257 void BrowserView::ConfirmAddSearchProvider(TemplateURL* template_url,
1258 Profile* profile) {
1259 chrome::EditSearchEngine(GetWidget()->GetNativeWindow(), template_url,
1260 nullptr, profile);
1263 void BrowserView::ShowUpdateChromeDialog() {
1264 UpdateRecommendedMessageBox::Show(GetWidget()->GetNativeWindow());
1267 void BrowserView::ShowBookmarkBubble(const GURL& url, bool already_bookmarked) {
1268 scoped_ptr<BookmarkBubbleDelegate> delegate;
1269 delegate.reset(new BookmarkBubbleSignInDelegate(browser_.get()));
1271 BookmarkBubbleView::ShowBubble(GetToolbarView()->GetBookmarkBubbleAnchor(),
1272 gfx::Rect(), nullptr, bookmark_bar_view_.get(),
1273 delegate.Pass(), browser_->profile(), url,
1274 already_bookmarked);
1277 void BrowserView::ShowBookmarkAppBubble(
1278 const WebApplicationInfo& web_app_info,
1279 const ShowBookmarkAppBubbleCallback& callback) {
1280 BookmarkAppBubbleView::ShowBubble(GetToolbarView(), web_app_info, callback);
1283 void BrowserView::ShowTranslateBubble(
1284 content::WebContents* web_contents,
1285 translate::TranslateStep step,
1286 translate::TranslateErrors::Type error_type,
1287 bool is_user_gesture) {
1288 if (contents_web_view_->HasFocus() &&
1289 !GetLocationBarView()->IsMouseHovered()) {
1290 content::RenderViewHost* rvh = web_contents->GetRenderViewHost();
1291 if (rvh->IsFocusedElementEditable())
1292 return;
1295 ChromeTranslateClient* chrome_translate_client =
1296 ChromeTranslateClient::FromWebContents(web_contents);
1297 translate::LanguageState& language_state =
1298 chrome_translate_client->GetLanguageState();
1299 language_state.SetTranslateEnabled(true);
1301 if (IsMinimized())
1302 return;
1304 TranslateBubbleView::ShowBubble(
1305 GetToolbarView()->GetTranslateBubbleAnchor(), web_contents, step,
1306 error_type, is_user_gesture);
1309 bool BrowserView::ShowSessionCrashedBubble() {
1310 return SessionCrashedBubbleView::Show(browser_.get());
1313 bool BrowserView::IsProfileResetBubbleSupported() const {
1314 return true;
1317 GlobalErrorBubbleViewBase* BrowserView::ShowProfileResetBubble(
1318 const base::WeakPtr<ProfileResetGlobalError>& global_error) {
1319 return ProfileResetBubbleView::ShowBubble(global_error, browser_.get());
1322 #if defined(ENABLE_ONE_CLICK_SIGNIN)
1323 void BrowserView::ShowOneClickSigninBubble(
1324 OneClickSigninBubbleType type,
1325 const base::string16& email,
1326 const base::string16& error_message,
1327 const StartSyncCallback& start_sync_callback) {
1328 scoped_ptr<OneClickSigninBubbleDelegate> delegate;
1329 delegate.reset(new OneClickSigninBubbleLinksDelegate(browser()));
1331 views::View* anchor_view;
1332 if (type == BrowserWindow::ONE_CLICK_SIGNIN_BUBBLE_TYPE_BUBBLE)
1333 anchor_view = toolbar_->app_menu();
1334 else
1335 anchor_view = toolbar_->location_bar();
1337 OneClickSigninBubbleView::ShowBubble(type, email, error_message,
1338 delegate.Pass(), anchor_view,
1339 start_sync_callback);
1341 #endif
1343 void BrowserView::SetDownloadShelfVisible(bool visible) {
1344 // This can be called from the superclass destructor, when it destroys our
1345 // child views. At that point, browser_ is already gone.
1346 if (!browser_)
1347 return;
1349 if (visible && IsDownloadShelfVisible() != visible) {
1350 // Invoke GetDownloadShelf to force the shelf to be created.
1351 GetDownloadShelf();
1354 browser_->UpdateDownloadShelfVisibility(visible);
1356 // SetDownloadShelfVisible can force-close the shelf, so make sure we lay out
1357 // everything correctly, as if the animation had finished. This doesn't
1358 // matter for showing the shelf, as the show animation will do it.
1359 ToolbarSizeChanged(false);
1362 bool BrowserView::IsDownloadShelfVisible() const {
1363 return download_shelf_.get() && download_shelf_->IsShowing();
1366 DownloadShelf* BrowserView::GetDownloadShelf() {
1367 if (!download_shelf_.get()) {
1368 download_shelf_.reset(new DownloadShelfView(browser_.get(), this));
1369 download_shelf_->set_owned_by_client();
1370 GetBrowserViewLayout()->set_download_shelf(download_shelf_.get());
1372 return download_shelf_.get();
1375 void BrowserView::ConfirmBrowserCloseWithPendingDownloads(
1376 int download_count,
1377 Browser::DownloadClosePreventionType dialog_type,
1378 bool app_modal,
1379 const base::Callback<void(bool)>& callback) {
1380 DownloadInProgressDialogView::Show(
1381 GetNativeWindow(), download_count, dialog_type, app_modal, callback);
1384 void BrowserView::UserChangedTheme() {
1385 frame_->FrameTypeChanged();
1388 void BrowserView::ShowWebsiteSettings(Profile* profile,
1389 content::WebContents* web_contents,
1390 const GURL& url,
1391 const content::SSLStatus& ssl) {
1392 // Some browser windows have a location icon embedded in the frame. Try to
1393 // use that if it exists. If it doesn't exist, use the location icon from
1394 // the location bar.
1395 views::View* popup_anchor = frame_->GetLocationIconView();
1396 if (!popup_anchor)
1397 popup_anchor = GetLocationBarView()->location_icon_view();
1399 WebsiteSettingsPopupView::ShowPopup(popup_anchor, gfx::Rect(), profile,
1400 web_contents, url, ssl);
1403 void BrowserView::ShowAppMenu() {
1404 // Keep the top-of-window views revealed as long as the app menu is visible.
1405 scoped_ptr<ImmersiveRevealedLock> revealed_lock(
1406 immersive_mode_controller_->GetRevealedLock(
1407 ImmersiveModeController::ANIMATE_REVEAL_NO));
1409 toolbar_->app_menu()->Activate();
1412 bool BrowserView::PreHandleKeyboardEvent(const NativeWebKeyboardEvent& event,
1413 bool* is_keyboard_shortcut) {
1414 *is_keyboard_shortcut = false;
1416 if ((event.type != blink::WebInputEvent::RawKeyDown) &&
1417 (event.type != blink::WebInputEvent::KeyUp)) {
1418 return false;
1421 views::FocusManager* focus_manager = GetFocusManager();
1422 DCHECK(focus_manager);
1424 if (focus_manager->shortcut_handling_suspended())
1425 return false;
1427 ui::Accelerator accelerator =
1428 ui::GetAcceleratorFromNativeWebKeyboardEvent(event);
1430 // What we have to do here is as follows:
1431 // - If the |browser_| is for an app, do nothing.
1432 // - On CrOS if |accelerator| is deprecated, we allow web contents to consume
1433 // it if needed.
1434 // - If the |browser_| is not for an app, and the |accelerator| is not
1435 // associated with the browser (e.g. an Ash shortcut), process it.
1436 // - If the |browser_| is not for an app, and the |accelerator| is associated
1437 // with the browser, and it is a reserved one (e.g. Ctrl+w), process it.
1438 // - If the |browser_| is not for an app, and the |accelerator| is associated
1439 // with the browser, and it is not a reserved one, do nothing.
1441 if (browser_->is_app()) {
1442 // Let all keys fall through to a v1 app's web content, even accelerators.
1443 // We don't have to flip |is_keyboard_shortcut| here. If we do that, the app
1444 // might not be able to see a subsequent Char event. See OnHandleInputEvent
1445 // in content/renderer/render_widget.cc for details.
1446 return false;
1449 #if defined(OS_CHROMEOS)
1450 if (chrome::IsAcceleratorDeprecated(accelerator)) {
1451 if (event.type == blink::WebInputEvent::RawKeyDown)
1452 *is_keyboard_shortcut = true;
1453 return false;
1455 #endif // defined(OS_CHROMEOS)
1457 chrome::BrowserCommandController* controller = browser_->command_controller();
1459 // Here we need to retrieve the command id (if any) associated to the
1460 // keyboard event. Instead of looking up the command id in the
1461 // |accelerator_table_| by ourselves, we block the command execution of
1462 // the |browser_| object then send the keyboard event to the
1463 // |focus_manager| as if we are activating an accelerator key.
1464 // Then we can retrieve the command id from the |browser_| object.
1465 bool original_block_command_state = controller->block_command_execution();
1466 controller->SetBlockCommandExecution(true);
1467 // If the |accelerator| is a non-browser shortcut (e.g. Ash shortcut), the
1468 // command execution cannot be blocked and true is returned. However, it is
1469 // okay as long as is_app() is false. See comments in this function.
1470 const bool processed = focus_manager->ProcessAccelerator(accelerator);
1471 const int id = controller->GetLastBlockedCommand(nullptr);
1472 controller->SetBlockCommandExecution(original_block_command_state);
1474 // Executing the command may cause |this| object to be destroyed.
1475 if (controller->IsReservedCommandOrKey(id, event)) {
1476 UpdateAcceleratorMetrics(accelerator, id);
1477 return chrome::ExecuteCommand(browser_.get(), id);
1480 if (id != -1) {
1481 // |accelerator| is a non-reserved browser shortcut (e.g. Ctrl+f).
1482 if (event.type == blink::WebInputEvent::RawKeyDown)
1483 *is_keyboard_shortcut = true;
1484 } else if (processed) {
1485 // |accelerator| is a non-browser shortcut (e.g. F4-F10 on Ash). Report
1486 // that we handled it.
1487 return true;
1490 return false;
1493 void BrowserView::HandleKeyboardEvent(const NativeWebKeyboardEvent& event) {
1494 unhandled_keyboard_event_handler_.HandleKeyboardEvent(event,
1495 GetFocusManager());
1498 // TODO(devint): http://b/issue?id=1117225 Cut, Copy, and Paste are always
1499 // enabled in the page menu regardless of whether the command will do
1500 // anything. When someone selects the menu item, we just act as if they hit
1501 // the keyboard shortcut for the command by sending the associated key press
1502 // to windows. The real fix to this bug is to disable the commands when they
1503 // won't do anything. We'll need something like an overall clipboard command
1504 // manager to do that.
1505 void BrowserView::CutCopyPaste(int command_id) {
1506 // If a WebContents is focused, call its member method.
1508 // We could make WebContents register accelerators and then just use the
1509 // plumbing for accelerators below to dispatch these, but it's not clear
1510 // whether that would still allow keypresses of ctrl-X/C/V to be sent as
1511 // key events (and not accelerators) to the WebContents so it can give the web
1512 // page a chance to override them.
1513 WebContents* contents = browser_->tab_strip_model()->GetActiveWebContents();
1514 if (contents) {
1515 void (WebContents::*method)();
1516 if (command_id == IDC_CUT)
1517 method = &content::WebContents::Cut;
1518 else if (command_id == IDC_COPY)
1519 method = &content::WebContents::Copy;
1520 else
1521 method = &content::WebContents::Paste;
1522 if (DoCutCopyPasteForWebContents(contents, method))
1523 return;
1525 WebContents* devtools =
1526 DevToolsWindow::GetInTabWebContents(contents, nullptr);
1527 if (devtools && DoCutCopyPasteForWebContents(devtools, method))
1528 return;
1531 // Any Views which want to handle the clipboard commands in the Chrome menu
1532 // should:
1533 // (a) Register ctrl-X/C/V as accelerators
1534 // (b) Implement CanHandleAccelerators() to not return true unless they're
1535 // focused, as the FocusManager will try all registered accelerator
1536 // handlers, not just the focused one.
1537 // Currently, Textfield (which covers the omnibox and find bar, and likely any
1538 // other native UI in the future that wants to deal with clipboard commands)
1539 // does the above.
1540 ui::Accelerator accelerator;
1541 GetAccelerator(command_id, &accelerator);
1542 GetFocusManager()->ProcessAccelerator(accelerator);
1545 WindowOpenDisposition BrowserView::GetDispositionForPopupBounds(
1546 const gfx::Rect& bounds) {
1547 return NEW_POPUP;
1550 FindBar* BrowserView::CreateFindBar() {
1551 return chrome::CreateFindBar(this);
1554 WebContentsModalDialogHost* BrowserView::GetWebContentsModalDialogHost() {
1555 return GetBrowserViewLayout()->GetWebContentsModalDialogHost();
1558 BookmarkBarView* BrowserView::GetBookmarkBarView() const {
1559 return bookmark_bar_view_.get();
1562 LocationBarView* BrowserView::GetLocationBarView() const {
1563 return toolbar_ ? toolbar_->location_bar() : nullptr;
1566 views::View* BrowserView::GetTabContentsContainerView() const {
1567 return contents_web_view_;
1570 ToolbarView* BrowserView::GetToolbarView() const {
1571 return toolbar_;
1574 ///////////////////////////////////////////////////////////////////////////////
1575 // BrowserView, TabStripModelObserver implementation:
1577 void BrowserView::TabInsertedAt(WebContents* contents,
1578 int index,
1579 bool foreground) {
1580 #if defined(USE_AURA)
1581 // WebContents inserted in tabs might not have been added to the root
1582 // window yet. Per http://crbug/342672 add them now since drawing the
1583 // WebContents requires root window specific data - information about
1584 // the screen the WebContents is drawn on, for example.
1585 if (!contents->GetNativeView()->GetRootWindow()) {
1586 aura::Window* window = contents->GetNativeView();
1587 aura::Window* root_window = GetNativeWindow()->GetRootWindow();
1588 aura::client::ParentWindowWithContext(
1589 window, root_window, root_window->GetBoundsInScreen());
1590 DCHECK(contents->GetNativeView()->GetRootWindow());
1592 #endif
1593 web_contents_close_handler_->TabInserted();
1595 if (foreground)
1596 extensions::MaybeShowExtensionControlledNewTabPage(browser(), contents);
1599 void BrowserView::TabDetachedAt(WebContents* contents, int index) {
1600 if (PermissionBubbleManager::FromWebContents(contents))
1601 PermissionBubbleManager::FromWebContents(contents)->HideBubble();
1603 // We use index here rather than comparing |contents| because by this time
1604 // the model has already removed |contents| from its list, so
1605 // browser_->GetActiveWebContents() will return null or something else.
1606 if (index == browser_->tab_strip_model()->active_index()) {
1607 // We need to reset the current tab contents to null before it gets
1608 // freed. This is because the focus manager performs some operations
1609 // on the selected WebContents when it is removed.
1610 web_contents_close_handler_->ActiveTabChanged();
1611 contents_web_view_->SetWebContents(nullptr);
1612 infobar_container_->ChangeInfoBarManager(nullptr);
1613 UpdateDevToolsForContents(nullptr, true);
1617 void BrowserView::TabDeactivated(WebContents* contents) {
1618 if (PermissionBubbleManager::FromWebContents(contents))
1619 PermissionBubbleManager::FromWebContents(contents)->HideBubble();
1621 // We do not store the focus when closing the tab to work-around bug 4633.
1622 // Some reports seem to show that the focus manager and/or focused view can
1623 // be garbage at that point, it is not clear why.
1624 if (!contents->IsBeingDestroyed())
1625 contents->StoreFocus();
1628 void BrowserView::TabStripEmpty() {
1629 // Make sure all optional UI is removed before we are destroyed, otherwise
1630 // there will be consequences (since our view hierarchy will still have
1631 // references to freed views).
1632 UpdateUIForContents(nullptr);
1635 void BrowserView::WillCloseAllTabs() {
1636 web_contents_close_handler_->WillCloseAllTabs();
1639 void BrowserView::CloseAllTabsCanceled() {
1640 web_contents_close_handler_->CloseAllTabsCanceled();
1643 ///////////////////////////////////////////////////////////////////////////////
1644 // BrowserView, ui::AcceleratorProvider implementation:
1646 bool BrowserView::GetAcceleratorForCommandId(int command_id,
1647 ui::Accelerator* accelerator) {
1648 // Let's let the ToolbarView own the canonical implementation of this method.
1649 return toolbar_->GetAcceleratorForCommandId(command_id, accelerator);
1652 ///////////////////////////////////////////////////////////////////////////////
1653 // BrowserView, views::WidgetDelegate implementation:
1655 bool BrowserView::CanResize() const {
1656 return true;
1659 bool BrowserView::CanMaximize() const {
1660 return true;
1663 bool BrowserView::CanMinimize() const {
1664 return true;
1667 bool BrowserView::CanActivate() const {
1668 app_modal::AppModalDialogQueue* queue =
1669 app_modal::AppModalDialogQueue::GetInstance();
1670 if (!queue->active_dialog() || !queue->active_dialog()->native_dialog() ||
1671 !queue->active_dialog()->native_dialog()->IsShowing()) {
1672 return true;
1675 #if defined(USE_AURA) && defined(OS_CHROMEOS)
1676 // On Aura window manager controls all windows so settings focus via PostTask
1677 // will make only worse because posted task will keep trying to steal focus.
1678 queue->ActivateModalDialog();
1679 #else
1680 // If another browser is app modal, flash and activate the modal browser. This
1681 // has to be done in a post task, otherwise if the user clicked on a window
1682 // that doesn't have the modal dialog the windows keep trying to get the focus
1683 // from each other on Windows. http://crbug.com/141650.
1684 base::ThreadTaskRunnerHandle::Get()->PostTask(
1685 FROM_HERE, base::Bind(&BrowserView::ActivateAppModalDialog,
1686 activate_modal_dialog_factory_.GetWeakPtr()));
1687 #endif
1688 return false;
1691 base::string16 BrowserView::GetWindowTitle() const {
1692 return browser_->GetWindowTitleForCurrentTab();
1695 base::string16 BrowserView::GetAccessibleWindowTitle() const {
1696 if (IsOffTheRecord()) {
1697 return l10n_util::GetStringFUTF16(
1698 IDS_ACCESSIBLE_INCOGNITO_WINDOW_TITLE_FORMAT,
1699 GetWindowTitle());
1701 return GetWindowTitle();
1704 views::View* BrowserView::GetInitiallyFocusedView() {
1705 return nullptr;
1708 bool BrowserView::ShouldShowWindowTitle() const {
1709 // For Ash only, trusted windows (apps and settings) do not show a title,
1710 // crbug.com/119411. Child windows (i.e. popups) do show a title.
1711 if (browser_->host_desktop_type() == chrome::HOST_DESKTOP_TYPE_ASH &&
1712 browser_->is_trusted_source() &&
1713 !browser_->SupportsWindowFeature(Browser::FEATURE_WEBAPPFRAME))
1714 return false;
1716 return browser_->SupportsWindowFeature(Browser::FEATURE_TITLEBAR);
1719 gfx::ImageSkia BrowserView::GetWindowAppIcon() {
1720 if (browser_->is_app()) {
1721 WebContents* contents = browser_->tab_strip_model()->GetActiveWebContents();
1722 extensions::TabHelper* extensions_tab_helper =
1723 contents ? extensions::TabHelper::FromWebContents(contents) : nullptr;
1724 if (extensions_tab_helper && extensions_tab_helper->GetExtensionAppIcon())
1725 return gfx::ImageSkia::CreateFrom1xBitmap(
1726 *extensions_tab_helper->GetExtensionAppIcon());
1729 return GetWindowIcon();
1732 gfx::ImageSkia BrowserView::GetWindowIcon() {
1733 // Use the default icon for devtools.
1734 if (browser_->is_devtools())
1735 return gfx::ImageSkia();
1737 if (browser_->is_app() || browser_->is_type_popup())
1738 return browser_->GetCurrentPageIcon().AsImageSkia();
1739 return gfx::ImageSkia();
1742 bool BrowserView::ShouldShowWindowIcon() const {
1743 // For Ash only, trusted windows (apps and settings) do not show an icon,
1744 // crbug.com/119411. Child windows (i.e. popups) do show an icon.
1745 if (browser_->host_desktop_type() == chrome::HOST_DESKTOP_TYPE_ASH &&
1746 browser_->is_trusted_source() &&
1747 !browser_->SupportsWindowFeature(Browser::FEATURE_WEBAPPFRAME))
1748 return false;
1750 return browser_->SupportsWindowFeature(Browser::FEATURE_TITLEBAR);
1753 bool BrowserView::ExecuteWindowsCommand(int command_id) {
1754 // This function handles WM_SYSCOMMAND, WM_APPCOMMAND, and WM_COMMAND.
1755 #if defined(OS_WIN)
1756 if (command_id == IDC_DEBUG_FRAME_TOGGLE)
1757 GetWidget()->DebugToggleFrameType();
1758 #endif
1759 // Translate WM_APPCOMMAND command ids into a command id that the browser
1760 // knows how to handle.
1761 int command_id_from_app_command = GetCommandIDForAppCommandID(command_id);
1762 if (command_id_from_app_command != -1)
1763 command_id = command_id_from_app_command;
1765 return chrome::ExecuteCommand(browser_.get(), command_id);
1768 std::string BrowserView::GetWindowName() const {
1769 return chrome::GetWindowName(browser_.get());
1772 void BrowserView::SaveWindowPlacement(const gfx::Rect& bounds,
1773 ui::WindowShowState show_state) {
1774 // If IsFullscreen() is true, we've just changed into fullscreen mode, and
1775 // we're catching the going-into-fullscreen sizing and positioning calls,
1776 // which we want to ignore.
1777 if (!IsFullscreen() && frame_->ShouldSaveWindowPlacement() &&
1778 chrome::ShouldSaveWindowPlacement(browser_.get())) {
1779 WidgetDelegate::SaveWindowPlacement(bounds, show_state);
1780 chrome::SaveWindowPlacement(browser_.get(), bounds, show_state);
1784 bool BrowserView::GetSavedWindowPlacement(
1785 const views::Widget* widget,
1786 gfx::Rect* bounds,
1787 ui::WindowShowState* show_state) const {
1788 chrome::GetSavedWindowBoundsAndShowState(browser_.get(), bounds, show_state);
1790 if (browser_->is_type_popup() &&
1791 !browser_->is_app() &&
1792 !browser_->is_trusted_source()) {
1793 // This is normal non-app popup window. The value passed in |bounds|
1794 // represents two pieces of information:
1795 // - the position of the window, in screen coordinates (outer position).
1796 // - the size of the content area (inner size).
1797 // We need to use these values to determine the appropriate size and
1798 // position of the resulting window.
1799 if (IsToolbarVisible()) {
1800 // If we're showing the toolbar, we need to adjust |*bounds| to include
1801 // its desired height, since the toolbar is considered part of the
1802 // window's client area as far as GetWindowBoundsForClientBounds is
1803 // concerned...
1804 bounds->set_height(
1805 bounds->height() + toolbar_->GetPreferredSize().height());
1808 gfx::Rect window_rect = frame_->non_client_view()->
1809 GetWindowBoundsForClientBounds(*bounds);
1810 window_rect.set_origin(bounds->origin());
1812 // When we are given x/y coordinates of 0 on a created popup window,
1813 // assume none were given by the window.open() command.
1814 if (window_rect.x() == 0 && window_rect.y() == 0) {
1815 gfx::Size size = window_rect.size();
1816 window_rect.set_origin(
1817 WindowSizer::GetDefaultPopupOrigin(size,
1818 browser_->host_desktop_type()));
1821 *bounds = window_rect;
1822 *show_state = ui::SHOW_STATE_NORMAL;
1825 // We return true because we can _always_ locate reasonable bounds using the
1826 // WindowSizer, and we don't want to trigger the Window's built-in "size to
1827 // default" handling because the browser window has no default preferred
1828 // size.
1829 return true;
1832 views::View* BrowserView::GetContentsView() {
1833 return contents_web_view_;
1836 views::ClientView* BrowserView::CreateClientView(views::Widget* widget) {
1837 return this;
1840 void BrowserView::OnWidgetActivationChanged(views::Widget* widget,
1841 bool active) {
1842 if (active)
1843 BrowserList::SetLastActive(browser_.get());
1846 void BrowserView::OnWindowBeginUserBoundsChange() {
1847 WebContents* web_contents = GetActiveWebContents();
1848 if (!web_contents)
1849 return;
1850 web_contents->GetRenderViewHost()->NotifyMoveOrResizeStarted();
1853 void BrowserView::OnWidgetMove() {
1854 if (!initialized_) {
1855 // Creating the widget can trigger a move. Ignore it until we've initialized
1856 // things.
1857 return;
1860 // Cancel any tabstrip animations, some of them may be invalidated by the
1861 // window being repositioned.
1862 // Comment out for one cycle to see if this fixes dist tests.
1863 // tabstrip_->DestroyDragController();
1865 // status_bubble_ may be null if this is invoked during construction.
1866 if (status_bubble_.get())
1867 status_bubble_->Reposition();
1869 BookmarkBubbleView::Hide();
1871 // Close the omnibox popup, if any.
1872 LocationBarView* location_bar_view = GetLocationBarView();
1873 if (location_bar_view)
1874 location_bar_view->GetOmniboxView()->CloseOmniboxPopup();
1877 views::Widget* BrowserView::GetWidget() {
1878 return View::GetWidget();
1881 const views::Widget* BrowserView::GetWidget() const {
1882 return View::GetWidget();
1885 void BrowserView::GetAccessiblePanes(std::vector<views::View*>* panes) {
1886 // This should be in the order of pane traversal of the panes using F6
1887 // (Windows) or Ctrl+Back/Forward (Chrome OS). If one of these is
1888 // invisible or has no focusable children, it will be automatically
1889 // skipped.
1890 panes->push_back(toolbar_);
1891 if (bookmark_bar_view_.get())
1892 panes->push_back(bookmark_bar_view_.get());
1893 if (infobar_container_)
1894 panes->push_back(infobar_container_);
1895 if (download_shelf_.get())
1896 panes->push_back(download_shelf_.get());
1897 panes->push_back(GetTabContentsContainerView());
1898 if (devtools_web_view_->visible())
1899 panes->push_back(devtools_web_view_);
1902 ///////////////////////////////////////////////////////////////////////////////
1903 // BrowserView, views::ClientView overrides:
1905 bool BrowserView::CanClose() {
1906 // You cannot close a frame for which there is an active originating drag
1907 // session.
1908 if (tabstrip_ && !tabstrip_->IsTabStripCloseable())
1909 return false;
1911 // Give beforeunload handlers the chance to cancel the close before we hide
1912 // the window below.
1913 if (!browser_->ShouldCloseWindow())
1914 return false;
1916 bool fast_tab_closing_enabled =
1917 base::CommandLine::ForCurrentProcess()->HasSwitch(
1918 switches::kEnableFastUnload);
1920 if (!browser_->tab_strip_model()->empty()) {
1921 // Tab strip isn't empty. Hide the frame (so it appears to have closed
1922 // immediately) and close all the tabs, allowing the renderers to shut
1923 // down. When the tab strip is empty we'll be called back again.
1924 frame_->Hide();
1925 browser_->OnWindowClosing();
1926 if (fast_tab_closing_enabled)
1927 browser_->tab_strip_model()->CloseAllTabs();
1928 return false;
1929 } else if (fast_tab_closing_enabled &&
1930 !browser_->HasCompletedUnloadProcessing()) {
1931 // The browser needs to finish running unload handlers.
1932 // Hide the frame (so it appears to have closed immediately), and
1933 // the browser will call us back again when it is ready to close.
1934 frame_->Hide();
1935 return false;
1938 return true;
1941 int BrowserView::NonClientHitTest(const gfx::Point& point) {
1942 return GetBrowserViewLayout()->NonClientHitTest(point);
1945 gfx::Size BrowserView::GetMinimumSize() const {
1946 return GetBrowserViewLayout()->GetMinimumSize();
1949 ///////////////////////////////////////////////////////////////////////////////
1950 // BrowserView, views::View overrides:
1952 const char* BrowserView::GetClassName() const {
1953 return kViewClassName;
1956 void BrowserView::Layout() {
1957 if (!initialized_ || in_process_fullscreen_)
1958 return;
1960 views::View::Layout();
1962 // TODO(jamescook): Why was this in the middle of layout code?
1963 toolbar_->location_bar()->omnibox_view()->SetFocusable(IsToolbarVisible());
1966 void BrowserView::PaintChildren(const ui::PaintContext& context) {
1967 // Paint the |infobar_container_| last so that it may paint its
1968 // overlapping tabs.
1969 for (int i = 0; i < child_count(); ++i) {
1970 View* child = child_at(i);
1971 if (child != infobar_container_ && !child->layer())
1972 child->Paint(context);
1975 infobar_container_->Paint(context);
1978 void BrowserView::ViewHierarchyChanged(
1979 const ViewHierarchyChangedDetails& details) {
1980 if (!initialized_ && details.is_add && details.child == this && GetWidget()) {
1981 InitViews();
1982 initialized_ = true;
1986 void BrowserView::ChildPreferredSizeChanged(View* child) {
1987 Layout();
1990 void BrowserView::GetAccessibleState(ui::AXViewState* state) {
1991 state->role = ui::AX_ROLE_CLIENT;
1994 void BrowserView::OnNativeThemeChanged(const ui::NativeTheme* theme) {
1995 // Do not handle native theme changes before the browser view is initialized.
1996 if (!initialized_)
1997 return;
1998 ClientView::OnNativeThemeChanged(theme);
1999 UserChangedTheme();
2000 chrome::MaybeShowInvertBubbleView(this);
2003 ///////////////////////////////////////////////////////////////////////////////
2004 // BrowserView, ui::AcceleratorTarget overrides:
2006 bool BrowserView::AcceleratorPressed(const ui::Accelerator& accelerator) {
2007 std::map<ui::Accelerator, int>::const_iterator iter =
2008 accelerator_table_.find(accelerator);
2009 DCHECK(iter != accelerator_table_.end());
2010 int command_id = iter->second;
2012 chrome::BrowserCommandController* controller = browser_->command_controller();
2013 if (!controller->block_command_execution())
2014 UpdateAcceleratorMetrics(accelerator, command_id);
2015 return chrome::ExecuteCommand(browser_.get(), command_id);
2018 ///////////////////////////////////////////////////////////////////////////////
2019 // BrowserView, OmniboxPopupModelObserver overrides:
2020 void BrowserView::OnOmniboxPopupShownOrHidden() {
2021 SetMaxTopArrowHeight(GetMaxTopInfoBarArrowHeight(), infobar_container_);
2024 ///////////////////////////////////////////////////////////////////////////////
2025 // BrowserView, InfoBarContainerDelegate overrides:
2027 SkColor BrowserView::GetInfoBarSeparatorColor() const {
2028 // NOTE: Keep this in sync with ToolbarView::OnPaint()!
2029 return (IsTabStripVisible() || !frame_->ShouldUseNativeFrame()) ?
2030 ThemeProperties::GetDefaultColor(
2031 ThemeProperties::COLOR_TOOLBAR_SEPARATOR) :
2032 SK_ColorBLACK;
2035 void BrowserView::InfoBarContainerStateChanged(bool is_animating) {
2036 ToolbarSizeChanged(is_animating);
2039 bool BrowserView::DrawInfoBarArrows(int* x) const {
2040 if (x) {
2041 gfx::Point anchor(toolbar_->location_bar()->GetLocationBarAnchorPoint());
2042 ConvertPointToTarget(toolbar_->location_bar(), this, &anchor);
2043 *x = anchor.x();
2045 return true;
2048 void BrowserView::InitViews() {
2049 GetWidget()->AddObserver(this);
2051 // Stow a pointer to this object onto the window handle so that we can get at
2052 // it later when all we have is a native view.
2053 GetWidget()->SetNativeWindowProperty(kBrowserViewKey, this);
2055 // Stow a pointer to the browser's profile onto the window handle so that we
2056 // can get it later when all we have is a native view.
2057 GetWidget()->SetNativeWindowProperty(Profile::kProfileKey,
2058 browser_->profile());
2060 // Start a hung plugin window detector for this browser object (as long as
2061 // hang detection is not disabled).
2062 if (!base::CommandLine::ForCurrentProcess()->HasSwitch(
2063 switches::kDisableHangMonitor)) {
2064 InitHangMonitor();
2067 LoadAccelerators();
2069 infobar_container_ = new InfoBarContainerView(this);
2070 AddChildView(infobar_container_);
2072 contents_web_view_ = new ContentsWebView(browser_->profile());
2073 contents_web_view_->set_id(VIEW_ID_TAB_CONTAINER);
2074 contents_web_view_->SetEmbedFullscreenWidgetMode(true);
2076 web_contents_close_handler_.reset(
2077 new WebContentsCloseHandler(contents_web_view_));
2079 devtools_web_view_ = new views::WebView(browser_->profile());
2080 devtools_web_view_->set_id(VIEW_ID_DEV_TOOLS_DOCKED);
2081 devtools_web_view_->SetVisible(false);
2083 contents_container_ = new views::View();
2084 contents_container_->set_background(views::Background::CreateSolidBackground(
2085 ThemeProperties::GetDefaultColor(
2086 ThemeProperties::COLOR_CONTROL_BACKGROUND)));
2087 contents_container_->AddChildView(devtools_web_view_);
2088 contents_container_->AddChildView(contents_web_view_);
2089 contents_container_->SetLayoutManager(new ContentsLayoutManager(
2090 devtools_web_view_, contents_web_view_));
2091 AddChildView(contents_container_);
2092 set_contents_view(contents_container_);
2094 // Top container holds tab strip and toolbar and lives at the front of the
2095 // view hierarchy.
2096 top_container_ = new TopContainerView(this);
2097 AddChildView(top_container_);
2099 // TabStrip takes ownership of the controller.
2100 BrowserTabStripController* tabstrip_controller =
2101 new BrowserTabStripController(browser_.get(),
2102 browser_->tab_strip_model());
2103 tabstrip_ = new TabStrip(tabstrip_controller);
2104 top_container_->AddChildView(tabstrip_);
2105 tabstrip_controller->InitFromModel(tabstrip_);
2107 toolbar_ = new ToolbarView(browser_.get());
2108 top_container_->AddChildView(toolbar_);
2109 toolbar_->Init();
2111 InitStatusBubble();
2113 // Create do-nothing view for the sake of controlling the z-order of the find
2114 // bar widget.
2115 find_bar_host_view_ = new View();
2116 AddChildView(find_bar_host_view_);
2118 immersive_mode_controller_->Init(this);
2120 BrowserViewLayout* browser_view_layout = new BrowserViewLayout;
2121 browser_view_layout->Init(new BrowserViewLayoutDelegateImpl(this),
2122 browser(),
2123 this,
2124 top_container_,
2125 tabstrip_,
2126 toolbar_,
2127 infobar_container_,
2128 contents_container_,
2129 GetContentsLayoutManager(),
2130 immersive_mode_controller_.get());
2131 SetLayoutManager(browser_view_layout);
2133 #if defined(OS_WIN)
2134 // Create a custom JumpList and add it to an observer of TabRestoreService
2135 // so we can update the custom JumpList when a tab is added or removed.
2136 if (JumpList::Enabled()) {
2137 load_complete_listener_.reset(new LoadCompleteListener(this));
2139 #endif
2141 GetLocationBar()->GetOmniboxView()->model()->popup_model()->AddObserver(this);
2144 void BrowserView::LoadingAnimationCallback() {
2145 base::TimeTicks now = base::TimeTicks::Now();
2146 if (!last_animation_time_.is_null()) {
2147 UMA_HISTOGRAM_TIMES(
2148 "Tabs.LoadingAnimationTime",
2149 now - last_animation_time_);
2151 last_animation_time_ = now;
2152 if (browser_->is_type_tabbed()) {
2153 // Loading animations are shown in the tab for tabbed windows. We check the
2154 // browser type instead of calling IsTabStripVisible() because the latter
2155 // will return false for fullscreen windows, but we still need to update
2156 // their animations (so that when they come out of fullscreen mode they'll
2157 // be correct).
2158 tabstrip_->UpdateLoadingAnimations();
2159 } else if (ShouldShowWindowIcon()) {
2160 // ... or in the window icon area for popups and app windows.
2161 WebContents* web_contents =
2162 browser_->tab_strip_model()->GetActiveWebContents();
2163 // GetActiveWebContents can return null for example under Purify when
2164 // the animations are running slowly and this function is called on a timer
2165 // through LoadingAnimationCallback.
2166 frame_->UpdateThrobber(web_contents && web_contents->IsLoading());
2170 void BrowserView::OnLoadCompleted() {
2171 #if defined(OS_WIN)
2172 DCHECK(!jumplist_.get());
2173 jumplist_ = new JumpList(browser_->profile());
2174 #endif
2177 BrowserViewLayout* BrowserView::GetBrowserViewLayout() const {
2178 return static_cast<BrowserViewLayout*>(GetLayoutManager());
2181 ContentsLayoutManager* BrowserView::GetContentsLayoutManager() const {
2182 return static_cast<ContentsLayoutManager*>(
2183 contents_container_->GetLayoutManager());
2186 bool BrowserView::MaybeShowBookmarkBar(WebContents* contents) {
2187 bool show_bookmark_bar = contents &&
2188 browser_->SupportsWindowFeature(Browser::FEATURE_BOOKMARKBAR);
2189 if (!show_bookmark_bar && !bookmark_bar_view_.get())
2190 return false;
2191 if (!bookmark_bar_view_.get()) {
2192 bookmark_bar_view_.reset(new BookmarkBarView(browser_.get(), this));
2193 bookmark_bar_view_->set_owned_by_client();
2194 bookmark_bar_view_->set_background(new BookmarkBarViewBackground(
2195 this, bookmark_bar_view_.get(), browser_.get()));
2196 bookmark_bar_view_->SetBookmarkBarState(
2197 browser_->bookmark_bar_state(),
2198 BookmarkBar::DONT_ANIMATE_STATE_CHANGE);
2199 GetBrowserViewLayout()->set_bookmark_bar(bookmark_bar_view_.get());
2201 // Don't change the visibility of the BookmarkBarView. BrowserViewLayout
2202 // handles it.
2203 bookmark_bar_view_->SetPageNavigator(GetActiveWebContents());
2205 // Update parenting for the bookmark bar. This may detach it from all views.
2206 bool needs_layout = false;
2207 views::View* new_parent = nullptr;
2208 if (show_bookmark_bar) {
2209 if (bookmark_bar_view_->IsDetached())
2210 new_parent = this;
2211 else
2212 new_parent = top_container_;
2214 if (new_parent != bookmark_bar_view_->parent()) {
2215 SetBookmarkBarParent(new_parent);
2216 needs_layout = true;
2219 // Check for updates to the desired size.
2220 if (bookmark_bar_view_->GetPreferredSize().height() !=
2221 bookmark_bar_view_->height())
2222 needs_layout = true;
2224 return needs_layout;
2227 void BrowserView::SetBookmarkBarParent(views::View* new_parent) {
2228 if (new_parent == this) {
2229 // Add it underneath |top_container_| or at the end if top container isn't
2230 // found.
2231 int top_container_index = GetIndexOf(top_container_);
2232 if (top_container_index >= 0)
2233 AddChildViewAt(bookmark_bar_view_.get(), top_container_index);
2234 else
2235 AddChildView(bookmark_bar_view_.get());
2236 } else if (new_parent) {
2237 // No special stacking is required for other parents.
2238 new_parent->AddChildView(bookmark_bar_view_.get());
2239 } else {
2240 // Bookmark bar is being detached from all views because it is hidden.
2241 bookmark_bar_view_->parent()->RemoveChildView(bookmark_bar_view_.get());
2245 bool BrowserView::MaybeShowInfoBar(WebContents* contents) {
2246 // TODO(beng): Remove this function once the interface between
2247 // InfoBarContainer, DownloadShelfView and WebContents and this
2248 // view is sorted out.
2249 return true;
2252 void BrowserView::UpdateDevToolsForContents(
2253 WebContents* web_contents, bool update_devtools_web_contents) {
2254 DevToolsContentsResizingStrategy strategy;
2255 WebContents* devtools = DevToolsWindow::GetInTabWebContents(
2256 web_contents, &strategy);
2258 if (!devtools_web_view_->web_contents() && devtools &&
2259 !devtools_focus_tracker_.get()) {
2260 // Install devtools focus tracker when dev tools window is shown for the
2261 // first time.
2262 devtools_focus_tracker_.reset(
2263 new views::ExternalFocusTracker(devtools_web_view_,
2264 GetFocusManager()));
2267 // Restore focus to the last focused view when hiding devtools window.
2268 if (devtools_web_view_->web_contents() && !devtools &&
2269 devtools_focus_tracker_.get()) {
2270 devtools_focus_tracker_->FocusLastFocusedExternalView();
2271 devtools_focus_tracker_.reset();
2274 // Replace devtools WebContents.
2275 if (devtools_web_view_->web_contents() != devtools &&
2276 update_devtools_web_contents) {
2277 devtools_web_view_->SetWebContents(devtools);
2280 if (devtools) {
2281 devtools_web_view_->SetVisible(true);
2282 GetContentsLayoutManager()->SetContentsResizingStrategy(strategy);
2283 } else {
2284 devtools_web_view_->SetVisible(false);
2285 GetContentsLayoutManager()->SetContentsResizingStrategy(
2286 DevToolsContentsResizingStrategy());
2288 contents_container_->Layout();
2290 if (devtools) {
2291 // When strategy.hide_inspected_contents() returns true, we are hiding
2292 // contents_web_view_ behind the devtools_web_view_. Otherwise,
2293 // contents_web_view_ should be right above the devtools_web_view_.
2294 int devtools_index = contents_container_->GetIndexOf(devtools_web_view_);
2295 int contents_index = contents_container_->GetIndexOf(contents_web_view_);
2296 bool devtools_is_on_top = devtools_index > contents_index;
2297 if (strategy.hide_inspected_contents() != devtools_is_on_top)
2298 contents_container_->ReorderChildView(contents_web_view_, devtools_index);
2302 void BrowserView::UpdateUIForContents(WebContents* contents) {
2303 bool needs_layout = MaybeShowBookmarkBar(contents);
2304 // TODO(jamescook): This function always returns true. Remove it and figure
2305 // out when layout is actually required.
2306 needs_layout |= MaybeShowInfoBar(contents);
2307 if (needs_layout)
2308 Layout();
2311 void BrowserView::ProcessFullscreen(bool fullscreen,
2312 FullscreenMode mode,
2313 const GURL& url,
2314 ExclusiveAccessBubbleType bubble_type) {
2315 if (in_process_fullscreen_)
2316 return;
2317 in_process_fullscreen_ = true;
2319 // Reduce jankiness during the following position changes by:
2320 // * Hiding the window until it's in the final position
2321 // * Ignoring all intervening Layout() calls, which resize the webpage and
2322 // thus are slow and look ugly (enforced via |in_process_fullscreen_|).
2323 LocationBarView* location_bar = GetLocationBarView();
2325 if (mode == METRO_SNAP_FULLSCREEN || !fullscreen) {
2326 // Hide the fullscreen bubble as soon as possible, since the mode toggle can
2327 // take enough time for the user to notice.
2328 exclusive_access_bubble_.reset();
2331 if (fullscreen) {
2332 // Move focus out of the location bar if necessary.
2333 views::FocusManager* focus_manager = GetFocusManager();
2334 DCHECK(focus_manager);
2335 // Look for focus in the location bar itself or any child view.
2336 if (location_bar->Contains(focus_manager->GetFocusedView()))
2337 focus_manager->ClearFocus();
2340 // Toggle fullscreen mode.
2341 frame_->SetFullscreen(fullscreen);
2343 // Enable immersive before the browser refreshes its list of enabled commands.
2344 if (mode != METRO_SNAP_FULLSCREEN && ShouldUseImmersiveFullscreenForUrl(url))
2345 immersive_mode_controller_->SetEnabled(fullscreen);
2347 browser_->WindowFullscreenStateChanged();
2349 if (fullscreen && !chrome::IsRunningInAppMode() &&
2350 mode != METRO_SNAP_FULLSCREEN) {
2351 UpdateExclusiveAccessExitBubbleContent(url, bubble_type);
2354 // Undo our anti-jankiness hacks and force a re-layout. We also need to
2355 // recompute the height of the infobar top arrow because toggling in and out
2356 // of fullscreen changes it. Calling ToolbarSizeChanged() will do both these
2357 // things since it computes the arrow height directly and forces a layout
2358 // indirectly via UpdateUIForContents(). Reset |in_process_fullscreen_| in
2359 // order to let the layout occur.
2360 in_process_fullscreen_ = false;
2361 ToolbarSizeChanged(false);
2363 WebContents* contents = browser_->tab_strip_model()->GetActiveWebContents();
2364 if (contents && PermissionBubbleManager::FromWebContents(contents))
2365 PermissionBubbleManager::FromWebContents(contents)->UpdateAnchorPosition();
2368 bool BrowserView::ShouldUseImmersiveFullscreenForUrl(const GURL& url) const {
2369 // Kiosk mode needs the whole screen, and if we're not in an Ash desktop
2370 // immersive fullscreen doesn't exist.
2371 if (base::CommandLine::ForCurrentProcess()->HasSwitch(switches::kKioskMode) ||
2372 browser()->host_desktop_type() != chrome::HOST_DESKTOP_TYPE_ASH) {
2373 return false;
2376 return url.is_empty();
2379 void BrowserView::LoadAccelerators() {
2380 views::FocusManager* focus_manager = GetFocusManager();
2381 DCHECK(focus_manager);
2383 // Let's fill our own accelerator table.
2384 const bool is_app_mode = chrome::IsRunningInForcedAppMode();
2385 const std::vector<chrome::AcceleratorMapping> accelerator_list(
2386 chrome::GetAcceleratorList());
2387 for (std::vector<chrome::AcceleratorMapping>::const_iterator it =
2388 accelerator_list.begin(); it != accelerator_list.end(); ++it) {
2389 // In app mode, only allow accelerators of white listed commands to pass
2390 // through.
2391 if (is_app_mode && !chrome::IsCommandAllowedInAppMode(it->command_id))
2392 continue;
2394 ui::Accelerator accelerator(it->keycode, it->modifiers);
2395 accelerator_table_[accelerator] = it->command_id;
2397 // Also register with the focus manager.
2398 focus_manager->RegisterAccelerator(
2399 accelerator, ui::AcceleratorManager::kNormalPriority, this);
2403 int BrowserView::GetCommandIDForAppCommandID(int app_command_id) const {
2404 #if defined(OS_WIN)
2405 switch (app_command_id) {
2406 // NOTE: The order here matches the APPCOMMAND declaration order in the
2407 // Windows headers.
2408 case APPCOMMAND_BROWSER_BACKWARD: return IDC_BACK;
2409 case APPCOMMAND_BROWSER_FORWARD: return IDC_FORWARD;
2410 case APPCOMMAND_BROWSER_REFRESH: return IDC_RELOAD;
2411 case APPCOMMAND_BROWSER_HOME: return IDC_HOME;
2412 case APPCOMMAND_BROWSER_STOP: return IDC_STOP;
2413 case APPCOMMAND_BROWSER_SEARCH: return IDC_FOCUS_SEARCH;
2414 case APPCOMMAND_HELP: return IDC_HELP_PAGE_VIA_KEYBOARD;
2415 case APPCOMMAND_NEW: return IDC_NEW_TAB;
2416 case APPCOMMAND_OPEN: return IDC_OPEN_FILE;
2417 case APPCOMMAND_CLOSE: return IDC_CLOSE_TAB;
2418 case APPCOMMAND_SAVE: return IDC_SAVE_PAGE;
2419 case APPCOMMAND_PRINT: return IDC_PRINT;
2420 case APPCOMMAND_COPY: return IDC_COPY;
2421 case APPCOMMAND_CUT: return IDC_CUT;
2422 case APPCOMMAND_PASTE: return IDC_PASTE;
2424 // TODO(pkasting): http://b/1113069 Handle these.
2425 case APPCOMMAND_UNDO:
2426 case APPCOMMAND_REDO:
2427 case APPCOMMAND_SPELL_CHECK:
2428 default: return -1;
2430 #else
2431 // App commands are Windows-specific so there's nothing to do here.
2432 return -1;
2433 #endif
2436 void BrowserView::InitHangMonitor() {
2437 #if defined(OS_WIN)
2438 PrefService* pref_service = g_browser_process->local_state();
2439 if (!pref_service)
2440 return;
2442 int plugin_message_response_timeout =
2443 pref_service->GetInteger(prefs::kPluginMessageResponseTimeout);
2444 int hung_plugin_detect_freq =
2445 pref_service->GetInteger(prefs::kHungPluginDetectFrequency);
2446 HWND window = GetWidget()->GetNativeView()->GetHost()->
2447 GetAcceleratedWidget();
2448 if ((hung_plugin_detect_freq > 0) &&
2449 hung_window_detector_.Initialize(window,
2450 plugin_message_response_timeout)) {
2451 ticker_.set_tick_interval(hung_plugin_detect_freq);
2452 ticker_.RegisterTickHandler(&hung_window_detector_);
2453 ticker_.Start();
2455 pref_service->SetInteger(prefs::kPluginMessageResponseTimeout,
2456 plugin_message_response_timeout);
2457 pref_service->SetInteger(prefs::kHungPluginDetectFrequency,
2458 hung_plugin_detect_freq);
2460 #endif
2463 void BrowserView::UpdateAcceleratorMetrics(const ui::Accelerator& accelerator,
2464 int command_id) {
2465 const ui::KeyboardCode key_code = accelerator.key_code();
2466 if (command_id == IDC_HELP_PAGE_VIA_KEYBOARD && key_code == ui::VKEY_F1)
2467 content::RecordAction(UserMetricsAction("ShowHelpTabViaF1"));
2469 if (command_id == IDC_BOOKMARK_PAGE)
2470 UMA_HISTOGRAM_ENUMERATION("Bookmarks.EntryPoint",
2471 BOOKMARK_ENTRY_POINT_ACCELERATOR,
2472 BOOKMARK_ENTRY_POINT_LIMIT);
2474 #if defined(OS_CHROMEOS)
2475 // Collect information about the relative popularity of various accelerators
2476 // on Chrome OS.
2477 switch (command_id) {
2478 case IDC_BACK:
2479 if (key_code == ui::VKEY_BACK)
2480 content::RecordAction(UserMetricsAction("Accel_Back_Backspace"));
2481 else if (key_code == ui::VKEY_BROWSER_BACK)
2482 content::RecordAction(UserMetricsAction("Accel_Back_F1"));
2483 else if (key_code == ui::VKEY_LEFT)
2484 content::RecordAction(UserMetricsAction("Accel_Back_Left"));
2485 break;
2486 case IDC_FORWARD:
2487 if (key_code == ui::VKEY_BACK)
2488 content::RecordAction(UserMetricsAction("Accel_Forward_Backspace"));
2489 else if (key_code == ui::VKEY_BROWSER_FORWARD)
2490 content::RecordAction(UserMetricsAction("Accel_Forward_F2"));
2491 else if (key_code == ui::VKEY_RIGHT)
2492 content::RecordAction(UserMetricsAction("Accel_Forward_Right"));
2493 break;
2494 case IDC_RELOAD:
2495 case IDC_RELOAD_IGNORING_CACHE:
2496 if (key_code == ui::VKEY_R)
2497 content::RecordAction(UserMetricsAction("Accel_Reload_R"));
2498 else if (key_code == ui::VKEY_BROWSER_REFRESH)
2499 content::RecordAction(UserMetricsAction("Accel_Reload_F3"));
2500 break;
2501 case IDC_FOCUS_LOCATION:
2502 if (key_code == ui::VKEY_D)
2503 content::RecordAction(UserMetricsAction("Accel_FocusLocation_D"));
2504 else if (key_code == ui::VKEY_L)
2505 content::RecordAction(UserMetricsAction("Accel_FocusLocation_L"));
2506 break;
2507 case IDC_FOCUS_SEARCH:
2508 if (key_code == ui::VKEY_E)
2509 content::RecordAction(UserMetricsAction("Accel_FocusSearch_E"));
2510 else if (key_code == ui::VKEY_K)
2511 content::RecordAction(UserMetricsAction("Accel_FocusSearch_K"));
2512 break;
2513 default:
2514 // Do nothing.
2515 break;
2517 #endif
2520 void BrowserView::ShowAvatarBubbleFromAvatarButton(
2521 AvatarBubbleMode mode,
2522 const signin::ManageAccountsParams& manage_accounts_params) {
2523 #if defined(FRAME_AVATAR_BUTTON)
2524 profiles::BubbleViewMode bubble_view_mode;
2525 profiles::TutorialMode tutorial_mode;
2526 profiles::BubbleViewModeFromAvatarBubbleMode(mode, &bubble_view_mode,
2527 &tutorial_mode);
2528 ProfileChooserView::ShowBubble(
2529 bubble_view_mode, tutorial_mode, manage_accounts_params,
2530 frame_->GetNewAvatarMenuButton(), views::BubbleBorder::TOP_RIGHT,
2531 views::BubbleBorder::ALIGN_EDGE_TO_ANCHOR_EDGE, browser());
2532 ProfileMetrics::LogProfileOpenMethod(ProfileMetrics::ICON_AVATAR_BUBBLE);
2533 #else
2534 NOTREACHED();
2535 #endif
2538 int BrowserView::GetRenderViewHeightInsetWithDetachedBookmarkBar() {
2539 if (browser_->bookmark_bar_state() != BookmarkBar::DETACHED ||
2540 !bookmark_bar_view_.get() || !bookmark_bar_view_->IsDetached()) {
2541 return 0;
2543 // Don't use bookmark_bar_view_->height() which won't be the final height if
2544 // the bookmark bar is animating.
2545 return chrome::kNTPBookmarkBarHeight -
2546 bookmark_bar_view_->GetFullyDetachedToolbarOverlap();
2549 void BrowserView::ExecuteExtensionCommand(
2550 const extensions::Extension* extension,
2551 const extensions::Command& command) {
2552 toolbar_->ExecuteExtensionCommand(extension, command);
2555 ExclusiveAccessContext* BrowserView::GetExclusiveAccessContext() {
2556 return this;
2559 bool BrowserView::DoCutCopyPasteForWebContents(
2560 WebContents* contents,
2561 void (WebContents::*method)()) {
2562 // It's possible for a non-null WebContents to have a null RWHV if it's
2563 // crashed or otherwise been killed.
2564 content::RenderWidgetHostView* rwhv = contents->GetRenderWidgetHostView();
2565 if (!rwhv || !rwhv->HasFocus())
2566 return false;
2567 // Calling |method| rather than using a fake key event is important since a
2568 // fake event might be consumed by the web content.
2569 (contents->*method)();
2570 return true;
2573 void BrowserView::ActivateAppModalDialog() const {
2574 // If another browser is app modal, flash and activate the modal browser.
2575 app_modal::AppModalDialog* active_dialog =
2576 app_modal::AppModalDialogQueue::GetInstance()->active_dialog();
2577 if (!active_dialog)
2578 return;
2580 Browser* modal_browser =
2581 chrome::FindBrowserWithWebContents(active_dialog->web_contents());
2582 if (modal_browser && (browser_ != modal_browser)) {
2583 modal_browser->window()->FlashFrame(true);
2584 modal_browser->window()->Activate();
2587 app_modal::AppModalDialogQueue::GetInstance()->ActivateModalDialog();
2590 int BrowserView::GetMaxTopInfoBarArrowHeight() {
2591 int top_arrow_height = 0;
2592 // Only show the arrows when not in fullscreen and when there's no omnibox
2593 // popup.
2594 if (!IsFullscreen() &&
2595 !GetLocationBar()->GetOmniboxView()->model()->popup_model()->IsOpen()) {
2596 gfx::Point icon_bottom(
2597 toolbar_->location_bar()->GetLocationBarAnchorPoint());
2598 ConvertPointToTarget(toolbar_->location_bar(), this, &icon_bottom);
2599 gfx::Point infobar_top(0, infobar_container_->GetVerticalOverlap(nullptr));
2600 ConvertPointToTarget(infobar_container_, this, &infobar_top);
2601 top_arrow_height = infobar_top.y() - icon_bottom.y();
2603 return top_arrow_height;
2606 ///////////////////////////////////////////////////////////////////////////////
2607 // BrowserView, ExclusiveAccessContext overrides
2608 Profile* BrowserView::GetProfile() {
2609 return browser_->profile();
2612 WebContents* BrowserView::GetActiveWebContents() {
2613 return browser_->tab_strip_model()->GetActiveWebContents();
2616 void BrowserView::UnhideDownloadShelf() {
2617 GetDownloadShelf()->Unhide();
2620 void BrowserView::HideDownloadShelf() {
2621 GetDownloadShelf()->Hide();
2622 StatusBubble* statusBubble = GetStatusBubble();
2623 if (statusBubble)
2624 statusBubble->Hide();
2627 ///////////////////////////////////////////////////////////////////////////////
2628 // BrowserView, ExclusiveAccessBubbleViewsContext overrides
2629 ExclusiveAccessManager* BrowserView::GetExclusiveAccessManager() {
2630 return browser_->exclusive_access_manager();
2633 bool BrowserView::IsImmersiveModeEnabled() {
2634 return immersive_mode_controller()->IsEnabled();
2637 views::Widget* BrowserView::GetBubbleAssociatedWidget() {
2638 return GetWidget();
2641 gfx::Rect BrowserView::GetTopContainerBoundsInScreen() {
2642 return top_container_->GetBoundsInScreen();