Refactor WebsiteSettings to operate on a SecurityInfo
[chromium-blink-merge.git] / chrome / browser / ui / views / frame / browser_view.cc
blobb1201609ef638e72f540333d2ca92a6b6f08ab1c
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_factory.h"
39 #include "chrome/browser/signin/chrome_signin_helper.h"
40 #include "chrome/browser/themes/theme_properties.h"
41 #include "chrome/browser/themes/theme_service_factory.h"
42 #include "chrome/browser/translate/chrome_translate_client.h"
43 #include "chrome/browser/ui/ash/ash_util.h"
44 #include "chrome/browser/ui/bookmarks/bookmark_bar_constants.h"
45 #include "chrome/browser/ui/bookmarks/bookmark_bubble_delegate.h"
46 #include "chrome/browser/ui/bookmarks/bookmark_bubble_sign_in_delegate.h"
47 #include "chrome/browser/ui/browser.h"
48 #include "chrome/browser/ui/browser_command_controller.h"
49 #include "chrome/browser/ui/browser_commands.h"
50 #include "chrome/browser/ui/browser_dialogs.h"
51 #include "chrome/browser/ui/browser_finder.h"
52 #include "chrome/browser/ui/browser_list.h"
53 #include "chrome/browser/ui/browser_window_state.h"
54 #include "chrome/browser/ui/search/search_delegate.h"
55 #include "chrome/browser/ui/search/search_model.h"
56 #include "chrome/browser/ui/search/search_ui.h"
57 #include "chrome/browser/ui/tabs/tab_menu_model.h"
58 #include "chrome/browser/ui/tabs/tab_strip_model.h"
59 #include "chrome/browser/ui/view_ids.h"
60 #include "chrome/browser/ui/views/accelerator_table.h"
61 #include "chrome/browser/ui/views/accessibility/invert_bubble_view.h"
62 #include "chrome/browser/ui/views/bookmarks/bookmark_bar_view.h"
63 #include "chrome/browser/ui/views/bookmarks/bookmark_bubble_view.h"
64 #include "chrome/browser/ui/views/browser_dialogs.h"
65 #include "chrome/browser/ui/views/download/download_in_progress_dialog_view.h"
66 #include "chrome/browser/ui/views/download/download_shelf_view.h"
67 #include "chrome/browser/ui/views/exclusive_access_bubble_views.h"
68 #include "chrome/browser/ui/views/extensions/bookmark_app_bubble_view.h"
69 #include "chrome/browser/ui/views/frame/browser_view_layout.h"
70 #include "chrome/browser/ui/views/frame/browser_view_layout_delegate.h"
71 #include "chrome/browser/ui/views/frame/contents_layout_manager.h"
72 #include "chrome/browser/ui/views/frame/immersive_mode_controller.h"
73 #include "chrome/browser/ui/views/frame/top_container_view.h"
74 #include "chrome/browser/ui/views/frame/web_contents_close_handler.h"
75 #include "chrome/browser/ui/views/infobars/infobar_container_view.h"
76 #include "chrome/browser/ui/views/location_bar/location_bar_view.h"
77 #include "chrome/browser/ui/views/location_bar/location_icon_view.h"
78 #include "chrome/browser/ui/views/location_bar/zoom_bubble_view.h"
79 #include "chrome/browser/ui/views/omnibox/omnibox_view_views.h"
80 #include "chrome/browser/ui/views/profiles/avatar_menu_button.h"
81 #include "chrome/browser/ui/views/profiles/profile_chooser_view.h"
82 #include "chrome/browser/ui/views/profiles/profile_reset_bubble_view.h"
83 #include "chrome/browser/ui/views/session_crashed_bubble_view.h"
84 #include "chrome/browser/ui/views/settings_api_bubble_helper_views.h"
85 #include "chrome/browser/ui/views/status_bubble_views.h"
86 #include "chrome/browser/ui/views/tabs/browser_tab_strip_controller.h"
87 #include "chrome/browser/ui/views/tabs/tab.h"
88 #include "chrome/browser/ui/views/tabs/tab_strip.h"
89 #include "chrome/browser/ui/views/toolbar/browser_actions_container.h"
90 #include "chrome/browser/ui/views/toolbar/reload_button.h"
91 #include "chrome/browser/ui/views/toolbar/toolbar_view.h"
92 #include "chrome/browser/ui/views/toolbar/wrench_toolbar_button.h"
93 #include "chrome/browser/ui/views/translate/translate_bubble_view.h"
94 #include "chrome/browser/ui/views/update_recommended_message_box.h"
95 #include "chrome/browser/ui/views/website_settings/permissions_bubble_view.h"
96 #include "chrome/browser/ui/views/website_settings/website_settings_popup_view.h"
97 #include "chrome/browser/ui/website_settings/permission_bubble_manager.h"
98 #include "chrome/browser/ui/window_sizer/window_sizer.h"
99 #include "chrome/common/chrome_switches.h"
100 #include "chrome/common/pref_names.h"
101 #include "chrome/common/url_constants.h"
102 #include "chrome/grit/chromium_strings.h"
103 #include "chrome/grit/generated_resources.h"
104 #include "chrome/grit/locale_settings.h"
105 #include "components/app_modal/app_modal_dialog.h"
106 #include "components/app_modal/app_modal_dialog_queue.h"
107 #include "components/app_modal/native_app_modal_dialog.h"
108 #include "components/omnibox/browser/omnibox_popup_model.h"
109 #include "components/omnibox/browser/omnibox_popup_view.h"
110 #include "components/omnibox/browser/omnibox_view.h"
111 #include "components/sessions/core/tab_restore_service.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::WebContents;
175 using views::ColumnSet;
176 using views::GridLayout;
177 using web_modal::WebContentsModalDialogHost;
179 namespace {
181 // The name of a key to store on the window handle so that other code can
182 // locate this object using just the handle.
183 const char* const kBrowserViewKey = "__BROWSER_VIEW__";
185 // The number of milliseconds between loading animation frames.
186 const int kLoadingAnimationFrameTimeMs = 30;
188 // Paints the horizontal border separating the Bookmarks Bar from the Toolbar
189 // or page content according to |at_top| with |color|.
190 void PaintHorizontalBorder(gfx::Canvas* canvas,
191 BookmarkBarView* view,
192 bool at_top,
193 SkColor color) {
194 int thickness = views::NonClientFrameView::kClientEdgeThickness;
195 int y = at_top ? 0 : (view->height() - thickness);
196 canvas->FillRect(gfx::Rect(0, y, view->width(), thickness), color);
199 // TODO(kuan): These functions are temporarily for the bookmark bar while its
200 // detached state is at the top of the page; it'll be moved to float on the
201 // content page in the very near future, at which time, these local functions
202 // will be removed.
203 void PaintDetachedBookmarkBar(gfx::Canvas* canvas,
204 BookmarkBarView* view,
205 ThemeService* theme_service) {
206 // Paint background for detached state; if animating, this is fade in/out.
207 canvas->DrawColor(
208 chrome::GetDetachedBookmarkBarBackgroundColor(theme_service));
209 // Draw the separators above and below bookmark bar;
210 // if animating, these are fading in/out.
211 SkColor separator_color =
212 chrome::GetDetachedBookmarkBarSeparatorColor(theme_service);
214 if (ui::MaterialDesignController::IsModeMaterial()) {
215 BrowserView::Paint1pxHorizontalLine(
216 canvas, separator_color,
217 gfx::Rect(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(gfx::Canvas* canvas,
551 SkColor color,
552 const gfx::Rect& bounds) {
553 canvas->Save();
554 SkScalar scale_factor = 1.0f / canvas->image_scale();
555 canvas->sk_canvas()->scale(scale_factor, scale_factor);
557 gfx::RectF line_rect =
558 gfx::ScaleRect(gfx::RectF(bounds), canvas->image_scale());
559 line_rect.Inset(0, bounds.height() - 1, 0, 0);
561 SkPaint paint;
562 paint.setColor(color);
563 canvas->sk_canvas()->drawRect(gfx::RectFToSkRect(line_rect), 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(
1389 Profile* profile,
1390 content::WebContents* web_contents,
1391 const GURL& url,
1392 const SecurityStateModel::SecurityInfo& security_info) {
1393 // Some browser windows have a location icon embedded in the frame. Try to
1394 // use that if it exists. If it doesn't exist, use the location icon from
1395 // the location bar.
1396 views::View* popup_anchor = frame_->GetLocationIconView();
1397 if (!popup_anchor)
1398 popup_anchor = GetLocationBarView()->location_icon_view();
1400 WebsiteSettingsPopupView::ShowPopup(popup_anchor, gfx::Rect(), profile,
1401 web_contents, url, security_info);
1404 void BrowserView::ShowAppMenu() {
1405 // Keep the top-of-window views revealed as long as the app menu is visible.
1406 scoped_ptr<ImmersiveRevealedLock> revealed_lock(
1407 immersive_mode_controller_->GetRevealedLock(
1408 ImmersiveModeController::ANIMATE_REVEAL_NO));
1410 toolbar_->app_menu()->Activate();
1413 bool BrowserView::PreHandleKeyboardEvent(const NativeWebKeyboardEvent& event,
1414 bool* is_keyboard_shortcut) {
1415 *is_keyboard_shortcut = false;
1417 if ((event.type != blink::WebInputEvent::RawKeyDown) &&
1418 (event.type != blink::WebInputEvent::KeyUp)) {
1419 return false;
1422 views::FocusManager* focus_manager = GetFocusManager();
1423 DCHECK(focus_manager);
1425 if (focus_manager->shortcut_handling_suspended())
1426 return false;
1428 ui::Accelerator accelerator =
1429 ui::GetAcceleratorFromNativeWebKeyboardEvent(event);
1431 // What we have to do here is as follows:
1432 // - If the |browser_| is for an app, do nothing.
1433 // - On CrOS if |accelerator| is deprecated, we allow web contents to consume
1434 // it if needed.
1435 // - If the |browser_| is not for an app, and the |accelerator| is not
1436 // associated with the browser (e.g. an Ash shortcut), process it.
1437 // - If the |browser_| is not for an app, and the |accelerator| is associated
1438 // with the browser, and it is a reserved one (e.g. Ctrl+w), process it.
1439 // - If the |browser_| is not for an app, and the |accelerator| is associated
1440 // with the browser, and it is not a reserved one, do nothing.
1442 if (browser_->is_app()) {
1443 // Let all keys fall through to a v1 app's web content, even accelerators.
1444 // We don't have to flip |is_keyboard_shortcut| here. If we do that, the app
1445 // might not be able to see a subsequent Char event. See OnHandleInputEvent
1446 // in content/renderer/render_widget.cc for details.
1447 return false;
1450 #if defined(OS_CHROMEOS)
1451 if (chrome::IsAcceleratorDeprecated(accelerator)) {
1452 if (event.type == blink::WebInputEvent::RawKeyDown)
1453 *is_keyboard_shortcut = true;
1454 return false;
1456 #endif // defined(OS_CHROMEOS)
1458 chrome::BrowserCommandController* controller = browser_->command_controller();
1460 // Here we need to retrieve the command id (if any) associated to the
1461 // keyboard event. Instead of looking up the command id in the
1462 // |accelerator_table_| by ourselves, we block the command execution of
1463 // the |browser_| object then send the keyboard event to the
1464 // |focus_manager| as if we are activating an accelerator key.
1465 // Then we can retrieve the command id from the |browser_| object.
1466 bool original_block_command_state = controller->block_command_execution();
1467 controller->SetBlockCommandExecution(true);
1468 // If the |accelerator| is a non-browser shortcut (e.g. Ash shortcut), the
1469 // command execution cannot be blocked and true is returned. However, it is
1470 // okay as long as is_app() is false. See comments in this function.
1471 const bool processed = focus_manager->ProcessAccelerator(accelerator);
1472 const int id = controller->GetLastBlockedCommand(nullptr);
1473 controller->SetBlockCommandExecution(original_block_command_state);
1475 // Executing the command may cause |this| object to be destroyed.
1476 if (controller->IsReservedCommandOrKey(id, event)) {
1477 UpdateAcceleratorMetrics(accelerator, id);
1478 return chrome::ExecuteCommand(browser_.get(), id);
1481 if (id != -1) {
1482 // |accelerator| is a non-reserved browser shortcut (e.g. Ctrl+f).
1483 if (event.type == blink::WebInputEvent::RawKeyDown)
1484 *is_keyboard_shortcut = true;
1485 } else if (processed) {
1486 // |accelerator| is a non-browser shortcut (e.g. F4-F10 on Ash). Report
1487 // that we handled it.
1488 return true;
1491 return false;
1494 void BrowserView::HandleKeyboardEvent(const NativeWebKeyboardEvent& event) {
1495 unhandled_keyboard_event_handler_.HandleKeyboardEvent(event,
1496 GetFocusManager());
1499 // TODO(devint): http://b/issue?id=1117225 Cut, Copy, and Paste are always
1500 // enabled in the page menu regardless of whether the command will do
1501 // anything. When someone selects the menu item, we just act as if they hit
1502 // the keyboard shortcut for the command by sending the associated key press
1503 // to windows. The real fix to this bug is to disable the commands when they
1504 // won't do anything. We'll need something like an overall clipboard command
1505 // manager to do that.
1506 void BrowserView::CutCopyPaste(int command_id) {
1507 // If a WebContents is focused, call its member method.
1509 // We could make WebContents register accelerators and then just use the
1510 // plumbing for accelerators below to dispatch these, but it's not clear
1511 // whether that would still allow keypresses of ctrl-X/C/V to be sent as
1512 // key events (and not accelerators) to the WebContents so it can give the web
1513 // page a chance to override them.
1514 WebContents* contents = browser_->tab_strip_model()->GetActiveWebContents();
1515 if (contents) {
1516 void (WebContents::*method)();
1517 if (command_id == IDC_CUT)
1518 method = &content::WebContents::Cut;
1519 else if (command_id == IDC_COPY)
1520 method = &content::WebContents::Copy;
1521 else
1522 method = &content::WebContents::Paste;
1523 if (DoCutCopyPasteForWebContents(contents, method))
1524 return;
1526 WebContents* devtools =
1527 DevToolsWindow::GetInTabWebContents(contents, nullptr);
1528 if (devtools && DoCutCopyPasteForWebContents(devtools, method))
1529 return;
1532 // Any Views which want to handle the clipboard commands in the Chrome menu
1533 // should:
1534 // (a) Register ctrl-X/C/V as accelerators
1535 // (b) Implement CanHandleAccelerators() to not return true unless they're
1536 // focused, as the FocusManager will try all registered accelerator
1537 // handlers, not just the focused one.
1538 // Currently, Textfield (which covers the omnibox and find bar, and likely any
1539 // other native UI in the future that wants to deal with clipboard commands)
1540 // does the above.
1541 ui::Accelerator accelerator;
1542 GetAccelerator(command_id, &accelerator);
1543 GetFocusManager()->ProcessAccelerator(accelerator);
1546 WindowOpenDisposition BrowserView::GetDispositionForPopupBounds(
1547 const gfx::Rect& bounds) {
1548 return NEW_POPUP;
1551 FindBar* BrowserView::CreateFindBar() {
1552 return chrome::CreateFindBar(this);
1555 WebContentsModalDialogHost* BrowserView::GetWebContentsModalDialogHost() {
1556 return GetBrowserViewLayout()->GetWebContentsModalDialogHost();
1559 BookmarkBarView* BrowserView::GetBookmarkBarView() const {
1560 return bookmark_bar_view_.get();
1563 LocationBarView* BrowserView::GetLocationBarView() const {
1564 return toolbar_ ? toolbar_->location_bar() : nullptr;
1567 views::View* BrowserView::GetTabContentsContainerView() const {
1568 return contents_web_view_;
1571 ToolbarView* BrowserView::GetToolbarView() const {
1572 return toolbar_;
1575 ///////////////////////////////////////////////////////////////////////////////
1576 // BrowserView, TabStripModelObserver implementation:
1578 void BrowserView::TabInsertedAt(WebContents* contents,
1579 int index,
1580 bool foreground) {
1581 #if defined(USE_AURA)
1582 // WebContents inserted in tabs might not have been added to the root
1583 // window yet. Per http://crbug/342672 add them now since drawing the
1584 // WebContents requires root window specific data - information about
1585 // the screen the WebContents is drawn on, for example.
1586 if (!contents->GetNativeView()->GetRootWindow()) {
1587 aura::Window* window = contents->GetNativeView();
1588 aura::Window* root_window = GetNativeWindow()->GetRootWindow();
1589 aura::client::ParentWindowWithContext(
1590 window, root_window, root_window->GetBoundsInScreen());
1591 DCHECK(contents->GetNativeView()->GetRootWindow());
1593 #endif
1594 web_contents_close_handler_->TabInserted();
1596 if (foreground)
1597 extensions::MaybeShowExtensionControlledNewTabPage(browser(), contents);
1600 void BrowserView::TabDetachedAt(WebContents* contents, int index) {
1601 if (PermissionBubbleManager::FromWebContents(contents))
1602 PermissionBubbleManager::FromWebContents(contents)->HideBubble();
1604 // We use index here rather than comparing |contents| because by this time
1605 // the model has already removed |contents| from its list, so
1606 // browser_->GetActiveWebContents() will return null or something else.
1607 if (index == browser_->tab_strip_model()->active_index()) {
1608 // We need to reset the current tab contents to null before it gets
1609 // freed. This is because the focus manager performs some operations
1610 // on the selected WebContents when it is removed.
1611 web_contents_close_handler_->ActiveTabChanged();
1612 contents_web_view_->SetWebContents(nullptr);
1613 infobar_container_->ChangeInfoBarManager(nullptr);
1614 UpdateDevToolsForContents(nullptr, true);
1618 void BrowserView::TabDeactivated(WebContents* contents) {
1619 if (PermissionBubbleManager::FromWebContents(contents))
1620 PermissionBubbleManager::FromWebContents(contents)->HideBubble();
1622 // We do not store the focus when closing the tab to work-around bug 4633.
1623 // Some reports seem to show that the focus manager and/or focused view can
1624 // be garbage at that point, it is not clear why.
1625 if (!contents->IsBeingDestroyed())
1626 contents->StoreFocus();
1629 void BrowserView::TabStripEmpty() {
1630 // Make sure all optional UI is removed before we are destroyed, otherwise
1631 // there will be consequences (since our view hierarchy will still have
1632 // references to freed views).
1633 UpdateUIForContents(nullptr);
1636 void BrowserView::WillCloseAllTabs() {
1637 web_contents_close_handler_->WillCloseAllTabs();
1640 void BrowserView::CloseAllTabsCanceled() {
1641 web_contents_close_handler_->CloseAllTabsCanceled();
1644 ///////////////////////////////////////////////////////////////////////////////
1645 // BrowserView, ui::AcceleratorProvider implementation:
1647 bool BrowserView::GetAcceleratorForCommandId(int command_id,
1648 ui::Accelerator* accelerator) {
1649 // Let's let the ToolbarView own the canonical implementation of this method.
1650 return toolbar_->GetAcceleratorForCommandId(command_id, accelerator);
1653 ///////////////////////////////////////////////////////////////////////////////
1654 // BrowserView, views::WidgetDelegate implementation:
1656 bool BrowserView::CanResize() const {
1657 return true;
1660 bool BrowserView::CanMaximize() const {
1661 return true;
1664 bool BrowserView::CanMinimize() const {
1665 return true;
1668 bool BrowserView::CanActivate() const {
1669 app_modal::AppModalDialogQueue* queue =
1670 app_modal::AppModalDialogQueue::GetInstance();
1671 if (!queue->active_dialog() || !queue->active_dialog()->native_dialog() ||
1672 !queue->active_dialog()->native_dialog()->IsShowing()) {
1673 return true;
1676 #if defined(USE_AURA) && defined(OS_CHROMEOS)
1677 // On Aura window manager controls all windows so settings focus via PostTask
1678 // will make only worse because posted task will keep trying to steal focus.
1679 queue->ActivateModalDialog();
1680 #else
1681 // If another browser is app modal, flash and activate the modal browser. This
1682 // has to be done in a post task, otherwise if the user clicked on a window
1683 // that doesn't have the modal dialog the windows keep trying to get the focus
1684 // from each other on Windows. http://crbug.com/141650.
1685 base::ThreadTaskRunnerHandle::Get()->PostTask(
1686 FROM_HERE, base::Bind(&BrowserView::ActivateAppModalDialog,
1687 activate_modal_dialog_factory_.GetWeakPtr()));
1688 #endif
1689 return false;
1692 base::string16 BrowserView::GetWindowTitle() const {
1693 return browser_->GetWindowTitleForCurrentTab();
1696 base::string16 BrowserView::GetAccessibleWindowTitle() const {
1697 if (IsOffTheRecord()) {
1698 return l10n_util::GetStringFUTF16(
1699 IDS_ACCESSIBLE_INCOGNITO_WINDOW_TITLE_FORMAT,
1700 GetWindowTitle());
1702 return GetWindowTitle();
1705 views::View* BrowserView::GetInitiallyFocusedView() {
1706 return nullptr;
1709 bool BrowserView::ShouldShowWindowTitle() const {
1710 // For Ash only, trusted windows (apps and settings) do not show a title,
1711 // crbug.com/119411. Child windows (i.e. popups) do show a title.
1712 if (browser_->host_desktop_type() == chrome::HOST_DESKTOP_TYPE_ASH &&
1713 browser_->is_trusted_source() &&
1714 !browser_->SupportsWindowFeature(Browser::FEATURE_WEBAPPFRAME))
1715 return false;
1717 return browser_->SupportsWindowFeature(Browser::FEATURE_TITLEBAR);
1720 gfx::ImageSkia BrowserView::GetWindowAppIcon() {
1721 if (browser_->is_app()) {
1722 WebContents* contents = browser_->tab_strip_model()->GetActiveWebContents();
1723 extensions::TabHelper* extensions_tab_helper =
1724 contents ? extensions::TabHelper::FromWebContents(contents) : nullptr;
1725 if (extensions_tab_helper && extensions_tab_helper->GetExtensionAppIcon())
1726 return gfx::ImageSkia::CreateFrom1xBitmap(
1727 *extensions_tab_helper->GetExtensionAppIcon());
1730 return GetWindowIcon();
1733 gfx::ImageSkia BrowserView::GetWindowIcon() {
1734 // Use the default icon for devtools.
1735 if (browser_->is_devtools())
1736 return gfx::ImageSkia();
1738 if (browser_->is_app() || browser_->is_type_popup())
1739 return browser_->GetCurrentPageIcon().AsImageSkia();
1740 return gfx::ImageSkia();
1743 bool BrowserView::ShouldShowWindowIcon() const {
1744 // For Ash only, trusted windows (apps and settings) do not show an icon,
1745 // crbug.com/119411. Child windows (i.e. popups) do show an icon.
1746 if (browser_->host_desktop_type() == chrome::HOST_DESKTOP_TYPE_ASH &&
1747 browser_->is_trusted_source() &&
1748 !browser_->SupportsWindowFeature(Browser::FEATURE_WEBAPPFRAME))
1749 return false;
1751 return browser_->SupportsWindowFeature(Browser::FEATURE_TITLEBAR);
1754 bool BrowserView::ExecuteWindowsCommand(int command_id) {
1755 // This function handles WM_SYSCOMMAND, WM_APPCOMMAND, and WM_COMMAND.
1756 #if defined(OS_WIN)
1757 if (command_id == IDC_DEBUG_FRAME_TOGGLE)
1758 GetWidget()->DebugToggleFrameType();
1759 #endif
1760 // Translate WM_APPCOMMAND command ids into a command id that the browser
1761 // knows how to handle.
1762 int command_id_from_app_command = GetCommandIDForAppCommandID(command_id);
1763 if (command_id_from_app_command != -1)
1764 command_id = command_id_from_app_command;
1766 return chrome::ExecuteCommand(browser_.get(), command_id);
1769 std::string BrowserView::GetWindowName() const {
1770 return chrome::GetWindowName(browser_.get());
1773 void BrowserView::SaveWindowPlacement(const gfx::Rect& bounds,
1774 ui::WindowShowState show_state) {
1775 // If IsFullscreen() is true, we've just changed into fullscreen mode, and
1776 // we're catching the going-into-fullscreen sizing and positioning calls,
1777 // which we want to ignore.
1778 if (!IsFullscreen() && frame_->ShouldSaveWindowPlacement() &&
1779 chrome::ShouldSaveWindowPlacement(browser_.get())) {
1780 WidgetDelegate::SaveWindowPlacement(bounds, show_state);
1781 chrome::SaveWindowPlacement(browser_.get(), bounds, show_state);
1785 bool BrowserView::GetSavedWindowPlacement(
1786 const views::Widget* widget,
1787 gfx::Rect* bounds,
1788 ui::WindowShowState* show_state) const {
1789 chrome::GetSavedWindowBoundsAndShowState(browser_.get(), bounds, show_state);
1791 if (browser_->is_type_popup() &&
1792 !browser_->is_app() &&
1793 !browser_->is_trusted_source()) {
1794 // This is normal non-app popup window. The value passed in |bounds|
1795 // represents two pieces of information:
1796 // - the position of the window, in screen coordinates (outer position).
1797 // - the size of the content area (inner size).
1798 // We need to use these values to determine the appropriate size and
1799 // position of the resulting window.
1800 if (IsToolbarVisible()) {
1801 // If we're showing the toolbar, we need to adjust |*bounds| to include
1802 // its desired height, since the toolbar is considered part of the
1803 // window's client area as far as GetWindowBoundsForClientBounds is
1804 // concerned...
1805 bounds->set_height(
1806 bounds->height() + toolbar_->GetPreferredSize().height());
1809 gfx::Rect window_rect = frame_->non_client_view()->
1810 GetWindowBoundsForClientBounds(*bounds);
1811 window_rect.set_origin(bounds->origin());
1813 // When we are given x/y coordinates of 0 on a created popup window,
1814 // assume none were given by the window.open() command.
1815 if (window_rect.x() == 0 && window_rect.y() == 0) {
1816 gfx::Size size = window_rect.size();
1817 window_rect.set_origin(
1818 WindowSizer::GetDefaultPopupOrigin(size,
1819 browser_->host_desktop_type()));
1822 *bounds = window_rect;
1823 *show_state = ui::SHOW_STATE_NORMAL;
1826 // We return true because we can _always_ locate reasonable bounds using the
1827 // WindowSizer, and we don't want to trigger the Window's built-in "size to
1828 // default" handling because the browser window has no default preferred
1829 // size.
1830 return true;
1833 views::View* BrowserView::GetContentsView() {
1834 return contents_web_view_;
1837 views::ClientView* BrowserView::CreateClientView(views::Widget* widget) {
1838 return this;
1841 void BrowserView::OnWidgetActivationChanged(views::Widget* widget,
1842 bool active) {
1843 if (active)
1844 BrowserList::SetLastActive(browser_.get());
1847 void BrowserView::OnWindowBeginUserBoundsChange() {
1848 WebContents* web_contents = GetActiveWebContents();
1849 if (!web_contents)
1850 return;
1851 web_contents->GetRenderViewHost()->NotifyMoveOrResizeStarted();
1854 void BrowserView::OnWidgetMove() {
1855 if (!initialized_) {
1856 // Creating the widget can trigger a move. Ignore it until we've initialized
1857 // things.
1858 return;
1861 // Cancel any tabstrip animations, some of them may be invalidated by the
1862 // window being repositioned.
1863 // Comment out for one cycle to see if this fixes dist tests.
1864 // tabstrip_->DestroyDragController();
1866 // status_bubble_ may be null if this is invoked during construction.
1867 if (status_bubble_.get())
1868 status_bubble_->Reposition();
1870 BookmarkBubbleView::Hide();
1872 // Close the omnibox popup, if any.
1873 LocationBarView* location_bar_view = GetLocationBarView();
1874 if (location_bar_view)
1875 location_bar_view->GetOmniboxView()->CloseOmniboxPopup();
1878 views::Widget* BrowserView::GetWidget() {
1879 return View::GetWidget();
1882 const views::Widget* BrowserView::GetWidget() const {
1883 return View::GetWidget();
1886 void BrowserView::GetAccessiblePanes(std::vector<views::View*>* panes) {
1887 // This should be in the order of pane traversal of the panes using F6
1888 // (Windows) or Ctrl+Back/Forward (Chrome OS). If one of these is
1889 // invisible or has no focusable children, it will be automatically
1890 // skipped.
1891 panes->push_back(toolbar_);
1892 if (bookmark_bar_view_.get())
1893 panes->push_back(bookmark_bar_view_.get());
1894 if (infobar_container_)
1895 panes->push_back(infobar_container_);
1896 if (download_shelf_.get())
1897 panes->push_back(download_shelf_.get());
1898 panes->push_back(GetTabContentsContainerView());
1899 if (devtools_web_view_->visible())
1900 panes->push_back(devtools_web_view_);
1903 ///////////////////////////////////////////////////////////////////////////////
1904 // BrowserView, views::ClientView overrides:
1906 bool BrowserView::CanClose() {
1907 // You cannot close a frame for which there is an active originating drag
1908 // session.
1909 if (tabstrip_ && !tabstrip_->IsTabStripCloseable())
1910 return false;
1912 // Give beforeunload handlers the chance to cancel the close before we hide
1913 // the window below.
1914 if (!browser_->ShouldCloseWindow())
1915 return false;
1917 bool fast_tab_closing_enabled =
1918 base::CommandLine::ForCurrentProcess()->HasSwitch(
1919 switches::kEnableFastUnload);
1921 if (!browser_->tab_strip_model()->empty()) {
1922 // Tab strip isn't empty. Hide the frame (so it appears to have closed
1923 // immediately) and close all the tabs, allowing the renderers to shut
1924 // down. When the tab strip is empty we'll be called back again.
1925 frame_->Hide();
1926 browser_->OnWindowClosing();
1927 if (fast_tab_closing_enabled)
1928 browser_->tab_strip_model()->CloseAllTabs();
1929 return false;
1930 } else if (fast_tab_closing_enabled &&
1931 !browser_->HasCompletedUnloadProcessing()) {
1932 // The browser needs to finish running unload handlers.
1933 // Hide the frame (so it appears to have closed immediately), and
1934 // the browser will call us back again when it is ready to close.
1935 frame_->Hide();
1936 return false;
1939 return true;
1942 int BrowserView::NonClientHitTest(const gfx::Point& point) {
1943 return GetBrowserViewLayout()->NonClientHitTest(point);
1946 gfx::Size BrowserView::GetMinimumSize() const {
1947 return GetBrowserViewLayout()->GetMinimumSize();
1950 ///////////////////////////////////////////////////////////////////////////////
1951 // BrowserView, views::View overrides:
1953 const char* BrowserView::GetClassName() const {
1954 return kViewClassName;
1957 void BrowserView::Layout() {
1958 if (!initialized_ || in_process_fullscreen_)
1959 return;
1961 views::View::Layout();
1963 // TODO(jamescook): Why was this in the middle of layout code?
1964 toolbar_->location_bar()->omnibox_view()->SetFocusable(IsToolbarVisible());
1967 void BrowserView::PaintChildren(const ui::PaintContext& context) {
1968 // Paint the |infobar_container_| last so that it may paint its
1969 // overlapping tabs.
1970 for (int i = 0; i < child_count(); ++i) {
1971 View* child = child_at(i);
1972 if (child != infobar_container_ && !child->layer())
1973 child->Paint(context);
1976 infobar_container_->Paint(context);
1979 void BrowserView::ViewHierarchyChanged(
1980 const ViewHierarchyChangedDetails& details) {
1981 if (!initialized_ && details.is_add && details.child == this && GetWidget()) {
1982 InitViews();
1983 initialized_ = true;
1987 void BrowserView::ChildPreferredSizeChanged(View* child) {
1988 Layout();
1991 void BrowserView::GetAccessibleState(ui::AXViewState* state) {
1992 state->role = ui::AX_ROLE_CLIENT;
1995 void BrowserView::OnNativeThemeChanged(const ui::NativeTheme* theme) {
1996 // Do not handle native theme changes before the browser view is initialized.
1997 if (!initialized_)
1998 return;
1999 ClientView::OnNativeThemeChanged(theme);
2000 UserChangedTheme();
2001 chrome::MaybeShowInvertBubbleView(this);
2004 ///////////////////////////////////////////////////////////////////////////////
2005 // BrowserView, ui::AcceleratorTarget overrides:
2007 bool BrowserView::AcceleratorPressed(const ui::Accelerator& accelerator) {
2008 std::map<ui::Accelerator, int>::const_iterator iter =
2009 accelerator_table_.find(accelerator);
2010 DCHECK(iter != accelerator_table_.end());
2011 int command_id = iter->second;
2013 chrome::BrowserCommandController* controller = browser_->command_controller();
2014 if (!controller->block_command_execution())
2015 UpdateAcceleratorMetrics(accelerator, command_id);
2016 return chrome::ExecuteCommand(browser_.get(), command_id);
2019 ///////////////////////////////////////////////////////////////////////////////
2020 // BrowserView, OmniboxPopupModelObserver overrides:
2021 void BrowserView::OnOmniboxPopupShownOrHidden() {
2022 SetMaxTopArrowHeight(GetMaxTopInfoBarArrowHeight(), infobar_container_);
2025 ///////////////////////////////////////////////////////////////////////////////
2026 // BrowserView, InfoBarContainerDelegate overrides:
2028 SkColor BrowserView::GetInfoBarSeparatorColor() const {
2029 // NOTE: Keep this in sync with ToolbarView::OnPaint()!
2030 return (IsTabStripVisible() || !frame_->ShouldUseNativeFrame()) ?
2031 ThemeProperties::GetDefaultColor(
2032 ThemeProperties::COLOR_TOOLBAR_SEPARATOR) :
2033 SK_ColorBLACK;
2036 void BrowserView::InfoBarContainerStateChanged(bool is_animating) {
2037 ToolbarSizeChanged(is_animating);
2040 bool BrowserView::DrawInfoBarArrows(int* x) const {
2041 if (x) {
2042 gfx::Point anchor(toolbar_->location_bar()->GetLocationBarAnchorPoint());
2043 ConvertPointToTarget(toolbar_->location_bar(), this, &anchor);
2044 *x = anchor.x();
2046 return true;
2049 void BrowserView::InitViews() {
2050 GetWidget()->AddObserver(this);
2052 // Stow a pointer to this object onto the window handle so that we can get at
2053 // it later when all we have is a native view.
2054 GetWidget()->SetNativeWindowProperty(kBrowserViewKey, this);
2056 // Stow a pointer to the browser's profile onto the window handle so that we
2057 // can get it later when all we have is a native view.
2058 GetWidget()->SetNativeWindowProperty(Profile::kProfileKey,
2059 browser_->profile());
2061 // Start a hung plugin window detector for this browser object (as long as
2062 // hang detection is not disabled).
2063 if (!base::CommandLine::ForCurrentProcess()->HasSwitch(
2064 switches::kDisableHangMonitor)) {
2065 InitHangMonitor();
2068 LoadAccelerators();
2070 infobar_container_ = new InfoBarContainerView(this);
2071 AddChildView(infobar_container_);
2073 contents_web_view_ = new ContentsWebView(browser_->profile());
2074 contents_web_view_->set_id(VIEW_ID_TAB_CONTAINER);
2075 contents_web_view_->SetEmbedFullscreenWidgetMode(true);
2077 web_contents_close_handler_.reset(
2078 new WebContentsCloseHandler(contents_web_view_));
2080 devtools_web_view_ = new views::WebView(browser_->profile());
2081 devtools_web_view_->set_id(VIEW_ID_DEV_TOOLS_DOCKED);
2082 devtools_web_view_->SetVisible(false);
2084 contents_container_ = new views::View();
2085 contents_container_->set_background(views::Background::CreateSolidBackground(
2086 ThemeProperties::GetDefaultColor(
2087 ThemeProperties::COLOR_CONTROL_BACKGROUND)));
2088 contents_container_->AddChildView(devtools_web_view_);
2089 contents_container_->AddChildView(contents_web_view_);
2090 contents_container_->SetLayoutManager(new ContentsLayoutManager(
2091 devtools_web_view_, contents_web_view_));
2092 AddChildView(contents_container_);
2093 set_contents_view(contents_container_);
2095 // Top container holds tab strip and toolbar and lives at the front of the
2096 // view hierarchy.
2097 top_container_ = new TopContainerView(this);
2098 AddChildView(top_container_);
2100 // TabStrip takes ownership of the controller.
2101 BrowserTabStripController* tabstrip_controller =
2102 new BrowserTabStripController(browser_.get(),
2103 browser_->tab_strip_model());
2104 tabstrip_ = new TabStrip(tabstrip_controller);
2105 top_container_->AddChildView(tabstrip_);
2106 tabstrip_controller->InitFromModel(tabstrip_);
2108 toolbar_ = new ToolbarView(browser_.get());
2109 top_container_->AddChildView(toolbar_);
2110 toolbar_->Init();
2112 InitStatusBubble();
2114 // Create do-nothing view for the sake of controlling the z-order of the find
2115 // bar widget.
2116 find_bar_host_view_ = new View();
2117 AddChildView(find_bar_host_view_);
2119 immersive_mode_controller_->Init(this);
2121 BrowserViewLayout* browser_view_layout = new BrowserViewLayout;
2122 browser_view_layout->Init(new BrowserViewLayoutDelegateImpl(this),
2123 browser(),
2124 this,
2125 top_container_,
2126 tabstrip_,
2127 toolbar_,
2128 infobar_container_,
2129 contents_container_,
2130 GetContentsLayoutManager(),
2131 immersive_mode_controller_.get());
2132 SetLayoutManager(browser_view_layout);
2134 #if defined(OS_WIN)
2135 // Create a custom JumpList and add it to an observer of TabRestoreService
2136 // so we can update the custom JumpList when a tab is added or removed.
2137 if (JumpList::Enabled()) {
2138 load_complete_listener_.reset(new LoadCompleteListener(this));
2140 #endif
2142 GetLocationBar()->GetOmniboxView()->model()->popup_model()->AddObserver(this);
2145 void BrowserView::LoadingAnimationCallback() {
2146 base::TimeTicks now = base::TimeTicks::Now();
2147 if (!last_animation_time_.is_null()) {
2148 UMA_HISTOGRAM_TIMES(
2149 "Tabs.LoadingAnimationTime",
2150 now - last_animation_time_);
2152 last_animation_time_ = now;
2153 if (browser_->is_type_tabbed()) {
2154 // Loading animations are shown in the tab for tabbed windows. We check the
2155 // browser type instead of calling IsTabStripVisible() because the latter
2156 // will return false for fullscreen windows, but we still need to update
2157 // their animations (so that when they come out of fullscreen mode they'll
2158 // be correct).
2159 tabstrip_->UpdateLoadingAnimations();
2160 } else if (ShouldShowWindowIcon()) {
2161 // ... or in the window icon area for popups and app windows.
2162 WebContents* web_contents =
2163 browser_->tab_strip_model()->GetActiveWebContents();
2164 // GetActiveWebContents can return null for example under Purify when
2165 // the animations are running slowly and this function is called on a timer
2166 // through LoadingAnimationCallback.
2167 frame_->UpdateThrobber(web_contents && web_contents->IsLoading());
2171 void BrowserView::OnLoadCompleted() {
2172 #if defined(OS_WIN)
2173 DCHECK(!jumplist_.get());
2174 jumplist_ = new JumpList(browser_->profile());
2175 #endif
2178 BrowserViewLayout* BrowserView::GetBrowserViewLayout() const {
2179 return static_cast<BrowserViewLayout*>(GetLayoutManager());
2182 ContentsLayoutManager* BrowserView::GetContentsLayoutManager() const {
2183 return static_cast<ContentsLayoutManager*>(
2184 contents_container_->GetLayoutManager());
2187 bool BrowserView::MaybeShowBookmarkBar(WebContents* contents) {
2188 bool show_bookmark_bar = contents &&
2189 browser_->SupportsWindowFeature(Browser::FEATURE_BOOKMARKBAR);
2190 if (!show_bookmark_bar && !bookmark_bar_view_.get())
2191 return false;
2192 if (!bookmark_bar_view_.get()) {
2193 bookmark_bar_view_.reset(new BookmarkBarView(browser_.get(), this));
2194 bookmark_bar_view_->set_owned_by_client();
2195 bookmark_bar_view_->set_background(new BookmarkBarViewBackground(
2196 this, bookmark_bar_view_.get(), browser_.get()));
2197 bookmark_bar_view_->SetBookmarkBarState(
2198 browser_->bookmark_bar_state(),
2199 BookmarkBar::DONT_ANIMATE_STATE_CHANGE);
2200 GetBrowserViewLayout()->set_bookmark_bar(bookmark_bar_view_.get());
2202 // Don't change the visibility of the BookmarkBarView. BrowserViewLayout
2203 // handles it.
2204 bookmark_bar_view_->SetPageNavigator(GetActiveWebContents());
2206 // Update parenting for the bookmark bar. This may detach it from all views.
2207 bool needs_layout = false;
2208 views::View* new_parent = nullptr;
2209 if (show_bookmark_bar) {
2210 if (bookmark_bar_view_->IsDetached())
2211 new_parent = this;
2212 else
2213 new_parent = top_container_;
2215 if (new_parent != bookmark_bar_view_->parent()) {
2216 SetBookmarkBarParent(new_parent);
2217 needs_layout = true;
2220 // Check for updates to the desired size.
2221 if (bookmark_bar_view_->GetPreferredSize().height() !=
2222 bookmark_bar_view_->height())
2223 needs_layout = true;
2225 return needs_layout;
2228 void BrowserView::SetBookmarkBarParent(views::View* new_parent) {
2229 if (new_parent == this) {
2230 // Add it underneath |top_container_| or at the end if top container isn't
2231 // found.
2232 int top_container_index = GetIndexOf(top_container_);
2233 if (top_container_index >= 0)
2234 AddChildViewAt(bookmark_bar_view_.get(), top_container_index);
2235 else
2236 AddChildView(bookmark_bar_view_.get());
2237 } else if (new_parent) {
2238 // No special stacking is required for other parents.
2239 new_parent->AddChildView(bookmark_bar_view_.get());
2240 } else {
2241 // Bookmark bar is being detached from all views because it is hidden.
2242 bookmark_bar_view_->parent()->RemoveChildView(bookmark_bar_view_.get());
2246 bool BrowserView::MaybeShowInfoBar(WebContents* contents) {
2247 // TODO(beng): Remove this function once the interface between
2248 // InfoBarContainer, DownloadShelfView and WebContents and this
2249 // view is sorted out.
2250 return true;
2253 void BrowserView::UpdateDevToolsForContents(
2254 WebContents* web_contents, bool update_devtools_web_contents) {
2255 DevToolsContentsResizingStrategy strategy;
2256 WebContents* devtools = DevToolsWindow::GetInTabWebContents(
2257 web_contents, &strategy);
2259 if (!devtools_web_view_->web_contents() && devtools &&
2260 !devtools_focus_tracker_.get()) {
2261 // Install devtools focus tracker when dev tools window is shown for the
2262 // first time.
2263 devtools_focus_tracker_.reset(
2264 new views::ExternalFocusTracker(devtools_web_view_,
2265 GetFocusManager()));
2268 // Restore focus to the last focused view when hiding devtools window.
2269 if (devtools_web_view_->web_contents() && !devtools &&
2270 devtools_focus_tracker_.get()) {
2271 devtools_focus_tracker_->FocusLastFocusedExternalView();
2272 devtools_focus_tracker_.reset();
2275 // Replace devtools WebContents.
2276 if (devtools_web_view_->web_contents() != devtools &&
2277 update_devtools_web_contents) {
2278 devtools_web_view_->SetWebContents(devtools);
2281 if (devtools) {
2282 devtools_web_view_->SetVisible(true);
2283 GetContentsLayoutManager()->SetContentsResizingStrategy(strategy);
2284 } else {
2285 devtools_web_view_->SetVisible(false);
2286 GetContentsLayoutManager()->SetContentsResizingStrategy(
2287 DevToolsContentsResizingStrategy());
2289 contents_container_->Layout();
2291 if (devtools) {
2292 // When strategy.hide_inspected_contents() returns true, we are hiding
2293 // contents_web_view_ behind the devtools_web_view_. Otherwise,
2294 // contents_web_view_ should be right above the devtools_web_view_.
2295 int devtools_index = contents_container_->GetIndexOf(devtools_web_view_);
2296 int contents_index = contents_container_->GetIndexOf(contents_web_view_);
2297 bool devtools_is_on_top = devtools_index > contents_index;
2298 if (strategy.hide_inspected_contents() != devtools_is_on_top)
2299 contents_container_->ReorderChildView(contents_web_view_, devtools_index);
2303 void BrowserView::UpdateUIForContents(WebContents* contents) {
2304 bool needs_layout = MaybeShowBookmarkBar(contents);
2305 // TODO(jamescook): This function always returns true. Remove it and figure
2306 // out when layout is actually required.
2307 needs_layout |= MaybeShowInfoBar(contents);
2308 if (needs_layout)
2309 Layout();
2312 void BrowserView::ProcessFullscreen(bool fullscreen,
2313 FullscreenMode mode,
2314 const GURL& url,
2315 ExclusiveAccessBubbleType bubble_type) {
2316 if (in_process_fullscreen_)
2317 return;
2318 in_process_fullscreen_ = true;
2320 // Reduce jankiness during the following position changes by:
2321 // * Hiding the window until it's in the final position
2322 // * Ignoring all intervening Layout() calls, which resize the webpage and
2323 // thus are slow and look ugly (enforced via |in_process_fullscreen_|).
2324 LocationBarView* location_bar = GetLocationBarView();
2326 if (mode == METRO_SNAP_FULLSCREEN || !fullscreen) {
2327 // Hide the fullscreen bubble as soon as possible, since the mode toggle can
2328 // take enough time for the user to notice.
2329 exclusive_access_bubble_.reset();
2332 if (fullscreen) {
2333 // Move focus out of the location bar if necessary.
2334 views::FocusManager* focus_manager = GetFocusManager();
2335 DCHECK(focus_manager);
2336 // Look for focus in the location bar itself or any child view.
2337 if (location_bar->Contains(focus_manager->GetFocusedView()))
2338 focus_manager->ClearFocus();
2341 // Toggle fullscreen mode.
2342 frame_->SetFullscreen(fullscreen);
2344 // Enable immersive before the browser refreshes its list of enabled commands.
2345 if (mode != METRO_SNAP_FULLSCREEN && ShouldUseImmersiveFullscreenForUrl(url))
2346 immersive_mode_controller_->SetEnabled(fullscreen);
2348 browser_->WindowFullscreenStateChanged();
2350 if (fullscreen && !chrome::IsRunningInAppMode() &&
2351 mode != METRO_SNAP_FULLSCREEN) {
2352 UpdateExclusiveAccessExitBubbleContent(url, bubble_type);
2355 // Undo our anti-jankiness hacks and force a re-layout. We also need to
2356 // recompute the height of the infobar top arrow because toggling in and out
2357 // of fullscreen changes it. Calling ToolbarSizeChanged() will do both these
2358 // things since it computes the arrow height directly and forces a layout
2359 // indirectly via UpdateUIForContents(). Reset |in_process_fullscreen_| in
2360 // order to let the layout occur.
2361 in_process_fullscreen_ = false;
2362 ToolbarSizeChanged(false);
2364 WebContents* contents = browser_->tab_strip_model()->GetActiveWebContents();
2365 if (contents && PermissionBubbleManager::FromWebContents(contents))
2366 PermissionBubbleManager::FromWebContents(contents)->UpdateAnchorPosition();
2369 bool BrowserView::ShouldUseImmersiveFullscreenForUrl(const GURL& url) const {
2370 // Kiosk mode needs the whole screen, and if we're not in an Ash desktop
2371 // immersive fullscreen doesn't exist.
2372 if (base::CommandLine::ForCurrentProcess()->HasSwitch(switches::kKioskMode) ||
2373 browser()->host_desktop_type() != chrome::HOST_DESKTOP_TYPE_ASH) {
2374 return false;
2377 return url.is_empty();
2380 void BrowserView::LoadAccelerators() {
2381 views::FocusManager* focus_manager = GetFocusManager();
2382 DCHECK(focus_manager);
2384 // Let's fill our own accelerator table.
2385 const bool is_app_mode = chrome::IsRunningInForcedAppMode();
2386 const std::vector<chrome::AcceleratorMapping> accelerator_list(
2387 chrome::GetAcceleratorList());
2388 for (std::vector<chrome::AcceleratorMapping>::const_iterator it =
2389 accelerator_list.begin(); it != accelerator_list.end(); ++it) {
2390 // In app mode, only allow accelerators of white listed commands to pass
2391 // through.
2392 if (is_app_mode && !chrome::IsCommandAllowedInAppMode(it->command_id))
2393 continue;
2395 ui::Accelerator accelerator(it->keycode, it->modifiers);
2396 accelerator_table_[accelerator] = it->command_id;
2398 // Also register with the focus manager.
2399 focus_manager->RegisterAccelerator(
2400 accelerator, ui::AcceleratorManager::kNormalPriority, this);
2404 int BrowserView::GetCommandIDForAppCommandID(int app_command_id) const {
2405 #if defined(OS_WIN)
2406 switch (app_command_id) {
2407 // NOTE: The order here matches the APPCOMMAND declaration order in the
2408 // Windows headers.
2409 case APPCOMMAND_BROWSER_BACKWARD: return IDC_BACK;
2410 case APPCOMMAND_BROWSER_FORWARD: return IDC_FORWARD;
2411 case APPCOMMAND_BROWSER_REFRESH: return IDC_RELOAD;
2412 case APPCOMMAND_BROWSER_HOME: return IDC_HOME;
2413 case APPCOMMAND_BROWSER_STOP: return IDC_STOP;
2414 case APPCOMMAND_BROWSER_SEARCH: return IDC_FOCUS_SEARCH;
2415 case APPCOMMAND_HELP: return IDC_HELP_PAGE_VIA_KEYBOARD;
2416 case APPCOMMAND_NEW: return IDC_NEW_TAB;
2417 case APPCOMMAND_OPEN: return IDC_OPEN_FILE;
2418 case APPCOMMAND_CLOSE: return IDC_CLOSE_TAB;
2419 case APPCOMMAND_SAVE: return IDC_SAVE_PAGE;
2420 case APPCOMMAND_PRINT: return IDC_PRINT;
2421 case APPCOMMAND_COPY: return IDC_COPY;
2422 case APPCOMMAND_CUT: return IDC_CUT;
2423 case APPCOMMAND_PASTE: return IDC_PASTE;
2425 // TODO(pkasting): http://b/1113069 Handle these.
2426 case APPCOMMAND_UNDO:
2427 case APPCOMMAND_REDO:
2428 case APPCOMMAND_SPELL_CHECK:
2429 default: return -1;
2431 #else
2432 // App commands are Windows-specific so there's nothing to do here.
2433 return -1;
2434 #endif
2437 void BrowserView::InitHangMonitor() {
2438 #if defined(OS_WIN)
2439 PrefService* pref_service = g_browser_process->local_state();
2440 if (!pref_service)
2441 return;
2443 int plugin_message_response_timeout =
2444 pref_service->GetInteger(prefs::kPluginMessageResponseTimeout);
2445 int hung_plugin_detect_freq =
2446 pref_service->GetInteger(prefs::kHungPluginDetectFrequency);
2447 HWND window = GetWidget()->GetNativeView()->GetHost()->
2448 GetAcceleratedWidget();
2449 if ((hung_plugin_detect_freq > 0) &&
2450 hung_window_detector_.Initialize(window,
2451 plugin_message_response_timeout)) {
2452 ticker_.set_tick_interval(hung_plugin_detect_freq);
2453 ticker_.RegisterTickHandler(&hung_window_detector_);
2454 ticker_.Start();
2456 pref_service->SetInteger(prefs::kPluginMessageResponseTimeout,
2457 plugin_message_response_timeout);
2458 pref_service->SetInteger(prefs::kHungPluginDetectFrequency,
2459 hung_plugin_detect_freq);
2461 #endif
2464 void BrowserView::UpdateAcceleratorMetrics(const ui::Accelerator& accelerator,
2465 int command_id) {
2466 const ui::KeyboardCode key_code = accelerator.key_code();
2467 if (command_id == IDC_HELP_PAGE_VIA_KEYBOARD && key_code == ui::VKEY_F1)
2468 content::RecordAction(UserMetricsAction("ShowHelpTabViaF1"));
2470 if (command_id == IDC_BOOKMARK_PAGE)
2471 UMA_HISTOGRAM_ENUMERATION("Bookmarks.EntryPoint",
2472 BOOKMARK_ENTRY_POINT_ACCELERATOR,
2473 BOOKMARK_ENTRY_POINT_LIMIT);
2475 #if defined(OS_CHROMEOS)
2476 // Collect information about the relative popularity of various accelerators
2477 // on Chrome OS.
2478 switch (command_id) {
2479 case IDC_BACK:
2480 if (key_code == ui::VKEY_BACK)
2481 content::RecordAction(UserMetricsAction("Accel_Back_Backspace"));
2482 else if (key_code == ui::VKEY_BROWSER_BACK)
2483 content::RecordAction(UserMetricsAction("Accel_Back_F1"));
2484 else if (key_code == ui::VKEY_LEFT)
2485 content::RecordAction(UserMetricsAction("Accel_Back_Left"));
2486 break;
2487 case IDC_FORWARD:
2488 if (key_code == ui::VKEY_BACK)
2489 content::RecordAction(UserMetricsAction("Accel_Forward_Backspace"));
2490 else if (key_code == ui::VKEY_BROWSER_FORWARD)
2491 content::RecordAction(UserMetricsAction("Accel_Forward_F2"));
2492 else if (key_code == ui::VKEY_RIGHT)
2493 content::RecordAction(UserMetricsAction("Accel_Forward_Right"));
2494 break;
2495 case IDC_RELOAD:
2496 case IDC_RELOAD_IGNORING_CACHE:
2497 if (key_code == ui::VKEY_R)
2498 content::RecordAction(UserMetricsAction("Accel_Reload_R"));
2499 else if (key_code == ui::VKEY_BROWSER_REFRESH)
2500 content::RecordAction(UserMetricsAction("Accel_Reload_F3"));
2501 break;
2502 case IDC_FOCUS_LOCATION:
2503 if (key_code == ui::VKEY_D)
2504 content::RecordAction(UserMetricsAction("Accel_FocusLocation_D"));
2505 else if (key_code == ui::VKEY_L)
2506 content::RecordAction(UserMetricsAction("Accel_FocusLocation_L"));
2507 break;
2508 case IDC_FOCUS_SEARCH:
2509 if (key_code == ui::VKEY_E)
2510 content::RecordAction(UserMetricsAction("Accel_FocusSearch_E"));
2511 else if (key_code == ui::VKEY_K)
2512 content::RecordAction(UserMetricsAction("Accel_FocusSearch_K"));
2513 break;
2514 default:
2515 // Do nothing.
2516 break;
2518 #endif
2521 void BrowserView::ShowAvatarBubbleFromAvatarButton(
2522 AvatarBubbleMode mode,
2523 const signin::ManageAccountsParams& manage_accounts_params) {
2524 #if defined(FRAME_AVATAR_BUTTON)
2525 // Do not show avatar bubble if there is no avatar menu button.
2526 if (!frame_->GetNewAvatarMenuButton())
2527 return;
2528 profiles::BubbleViewMode bubble_view_mode;
2529 profiles::TutorialMode tutorial_mode;
2530 profiles::BubbleViewModeFromAvatarBubbleMode(mode, &bubble_view_mode,
2531 &tutorial_mode);
2532 ProfileChooserView::ShowBubble(
2533 bubble_view_mode, tutorial_mode, manage_accounts_params,
2534 frame_->GetNewAvatarMenuButton(), views::BubbleBorder::TOP_RIGHT,
2535 views::BubbleBorder::ALIGN_EDGE_TO_ANCHOR_EDGE, browser());
2536 ProfileMetrics::LogProfileOpenMethod(ProfileMetrics::ICON_AVATAR_BUBBLE);
2537 #else
2538 NOTREACHED();
2539 #endif
2542 int BrowserView::GetRenderViewHeightInsetWithDetachedBookmarkBar() {
2543 if (browser_->bookmark_bar_state() != BookmarkBar::DETACHED ||
2544 !bookmark_bar_view_ || !bookmark_bar_view_->IsDetached()) {
2545 return 0;
2547 // Don't use bookmark_bar_view_->height() which won't be the final height if
2548 // the bookmark bar is animating.
2549 return chrome::kNTPBookmarkBarHeight -
2550 views::NonClientFrameView::kClientEdgeThickness;
2553 void BrowserView::ExecuteExtensionCommand(
2554 const extensions::Extension* extension,
2555 const extensions::Command& command) {
2556 toolbar_->ExecuteExtensionCommand(extension, command);
2559 ExclusiveAccessContext* BrowserView::GetExclusiveAccessContext() {
2560 return this;
2563 bool BrowserView::DoCutCopyPasteForWebContents(
2564 WebContents* contents,
2565 void (WebContents::*method)()) {
2566 // It's possible for a non-null WebContents to have a null RWHV if it's
2567 // crashed or otherwise been killed.
2568 content::RenderWidgetHostView* rwhv = contents->GetRenderWidgetHostView();
2569 if (!rwhv || !rwhv->HasFocus())
2570 return false;
2571 // Calling |method| rather than using a fake key event is important since a
2572 // fake event might be consumed by the web content.
2573 (contents->*method)();
2574 return true;
2577 void BrowserView::ActivateAppModalDialog() const {
2578 // If another browser is app modal, flash and activate the modal browser.
2579 app_modal::AppModalDialog* active_dialog =
2580 app_modal::AppModalDialogQueue::GetInstance()->active_dialog();
2581 if (!active_dialog)
2582 return;
2584 Browser* modal_browser =
2585 chrome::FindBrowserWithWebContents(active_dialog->web_contents());
2586 if (modal_browser && (browser_ != modal_browser)) {
2587 modal_browser->window()->FlashFrame(true);
2588 modal_browser->window()->Activate();
2591 app_modal::AppModalDialogQueue::GetInstance()->ActivateModalDialog();
2594 int BrowserView::GetMaxTopInfoBarArrowHeight() {
2595 int top_arrow_height = 0;
2596 // Only show the arrows when not in fullscreen and when there's no omnibox
2597 // popup.
2598 if (!IsFullscreen() &&
2599 !GetLocationBar()->GetOmniboxView()->model()->popup_model()->IsOpen()) {
2600 gfx::Point icon_bottom(
2601 toolbar_->location_bar()->GetLocationBarAnchorPoint());
2602 ConvertPointToTarget(toolbar_->location_bar(), this, &icon_bottom);
2603 gfx::Point infobar_top(0, infobar_container_->GetVerticalOverlap(nullptr));
2604 ConvertPointToTarget(infobar_container_, this, &infobar_top);
2605 top_arrow_height = infobar_top.y() - icon_bottom.y();
2607 return top_arrow_height;
2610 ///////////////////////////////////////////////////////////////////////////////
2611 // BrowserView, ExclusiveAccessContext overrides
2612 Profile* BrowserView::GetProfile() {
2613 return browser_->profile();
2616 WebContents* BrowserView::GetActiveWebContents() {
2617 return browser_->tab_strip_model()->GetActiveWebContents();
2620 void BrowserView::UnhideDownloadShelf() {
2621 GetDownloadShelf()->Unhide();
2624 void BrowserView::HideDownloadShelf() {
2625 GetDownloadShelf()->Hide();
2626 StatusBubble* statusBubble = GetStatusBubble();
2627 if (statusBubble)
2628 statusBubble->Hide();
2631 ///////////////////////////////////////////////////////////////////////////////
2632 // BrowserView, ExclusiveAccessBubbleViewsContext overrides
2633 ExclusiveAccessManager* BrowserView::GetExclusiveAccessManager() {
2634 return browser_->exclusive_access_manager();
2637 bool BrowserView::IsImmersiveModeEnabled() {
2638 return immersive_mode_controller()->IsEnabled();
2641 views::Widget* BrowserView::GetBubbleAssociatedWidget() {
2642 return GetWidget();
2645 gfx::Rect BrowserView::GetTopContainerBoundsInScreen() {
2646 return top_container_->GetBoundsInScreen();