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"
9 #include "base/auto_reset.h"
10 #include "base/command_line.h"
11 #include "base/i18n/rtl.h"
12 #include "base/memory/scoped_ptr.h"
13 #include "base/metrics/histogram.h"
14 #include "base/prefs/pref_service.h"
15 #include "base/strings/string_number_conversions.h"
16 #include "chrome/app/chrome_command_ids.h"
17 #include "chrome/app/chrome_dll_resource.h"
18 #include "chrome/browser/app_mode/app_mode_utils.h"
19 #include "chrome/browser/bookmarks/bookmark_stats.h"
20 #include "chrome/browser/browser_process.h"
21 #include "chrome/browser/chrome_notification_types.h"
22 #include "chrome/browser/extensions/tab_helper.h"
23 #include "chrome/browser/infobars/infobar_service.h"
24 #include "chrome/browser/native_window_notification_source.h"
25 #include "chrome/browser/password_manager/password_manager.h"
26 #include "chrome/browser/profiles/avatar_menu.h"
27 #include "chrome/browser/profiles/profile.h"
28 #include "chrome/browser/profiles/profile_info_cache.h"
29 #include "chrome/browser/profiles/profile_manager.h"
30 #include "chrome/browser/profiles/profiles_state.h"
31 #include "chrome/browser/search/search.h"
32 #include "chrome/browser/sessions/tab_restore_service.h"
33 #include "chrome/browser/sessions/tab_restore_service_factory.h"
34 #include "chrome/browser/speech/tts_controller.h"
35 #include "chrome/browser/themes/theme_properties.h"
36 #include "chrome/browser/themes/theme_service_factory.h"
37 #include "chrome/browser/translate/translate_tab_helper.h"
38 #include "chrome/browser/ui/app_modal_dialogs/app_modal_dialog.h"
39 #include "chrome/browser/ui/app_modal_dialogs/app_modal_dialog_queue.h"
40 #include "chrome/browser/ui/bookmarks/bookmark_bar_constants.h"
41 #include "chrome/browser/ui/bookmarks/bookmark_bubble_delegate.h"
42 #include "chrome/browser/ui/bookmarks/bookmark_bubble_sign_in_delegate.h"
43 #include "chrome/browser/ui/browser.h"
44 #include "chrome/browser/ui/browser_command_controller.h"
45 #include "chrome/browser/ui/browser_commands.h"
46 #include "chrome/browser/ui/browser_dialogs.h"
47 #include "chrome/browser/ui/browser_finder.h"
48 #include "chrome/browser/ui/browser_list.h"
49 #include "chrome/browser/ui/browser_window_state.h"
50 #include "chrome/browser/ui/ntp_background_util.h"
51 #include "chrome/browser/ui/omnibox/omnibox_popup_model.h"
52 #include "chrome/browser/ui/omnibox/omnibox_popup_view.h"
53 #include "chrome/browser/ui/omnibox/omnibox_view.h"
54 #include "chrome/browser/ui/search/search_delegate.h"
55 #include "chrome/browser/ui/search/search_model.h"
56 #include "chrome/browser/ui/search/search_ui.h"
57 #include "chrome/browser/ui/tabs/tab_menu_model.h"
58 #include "chrome/browser/ui/tabs/tab_strip_model.h"
59 #include "chrome/browser/ui/view_ids.h"
60 #include "chrome/browser/ui/views/accelerator_table.h"
61 #include "chrome/browser/ui/views/accessibility/invert_bubble_view.h"
62 #include "chrome/browser/ui/views/avatar_menu_bubble_view.h"
63 #include "chrome/browser/ui/views/avatar_menu_button.h"
64 #include "chrome/browser/ui/views/bookmarks/bookmark_bar_view.h"
65 #include "chrome/browser/ui/views/bookmarks/bookmark_bubble_view.h"
66 #include "chrome/browser/ui/views/browser_dialogs.h"
67 #include "chrome/browser/ui/views/download/download_in_progress_dialog_view.h"
68 #include "chrome/browser/ui/views/download/download_shelf_view.h"
69 #include "chrome/browser/ui/views/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/native_browser_frame_factory.h"
74 #include "chrome/browser/ui/views/frame/top_container_view.h"
75 #include "chrome/browser/ui/views/fullscreen_exit_bubble_views.h"
76 #include "chrome/browser/ui/views/infobars/infobar_container_view.h"
77 #include "chrome/browser/ui/views/location_bar/location_bar_view.h"
78 #include "chrome/browser/ui/views/location_bar/location_icon_view.h"
79 #include "chrome/browser/ui/views/omnibox/omnibox_view_views.h"
80 #include "chrome/browser/ui/views/password_generation_bubble_view.h"
81 #include "chrome/browser/ui/views/profile_chooser_view.h"
82 #include "chrome/browser/ui/views/status_bubble_views.h"
83 #include "chrome/browser/ui/views/tabs/browser_tab_strip_controller.h"
84 #include "chrome/browser/ui/views/tabs/tab.h"
85 #include "chrome/browser/ui/views/tabs/tab_strip.h"
86 #include "chrome/browser/ui/views/toolbar/reload_button.h"
87 #include "chrome/browser/ui/views/toolbar/toolbar_view.h"
88 #include "chrome/browser/ui/views/translate/translate_bubble_view.h"
89 #include "chrome/browser/ui/views/update_recommended_message_box.h"
90 #include "chrome/browser/ui/views/website_settings/website_settings_popup_view.h"
91 #include "chrome/browser/ui/window_sizer/window_sizer.h"
92 #include "chrome/common/chrome_switches.h"
93 #include "chrome/common/pref_names.h"
94 #include "chrome/common/profile_management_switches.h"
95 #include "chrome/common/url_constants.h"
96 #include "content/public/browser/download_manager.h"
97 #include "content/public/browser/native_web_keyboard_event.h"
98 #include "content/public/browser/notification_service.h"
99 #include "content/public/browser/render_view_host.h"
100 #include "content/public/browser/render_widget_host.h"
101 #include "content/public/browser/user_metrics.h"
102 #include "content/public/browser/web_contents.h"
103 #include "content/public/browser/web_contents_view.h"
104 #include "content/public/common/content_switches.h"
105 #include "grit/chromium_strings.h"
106 #include "grit/generated_resources.h"
107 #include "grit/locale_settings.h"
108 #include "grit/theme_resources.h"
109 #include "grit/ui_resources.h"
110 #include "grit/ui_strings.h"
111 #include "grit/webkit_resources.h"
112 #include "ui/base/accelerators/accelerator.h"
113 #include "ui/base/accessibility/accessible_view_state.h"
114 #include "ui/base/hit_test.h"
115 #include "ui/base/l10n/l10n_util.h"
116 #include "ui/base/resource/resource_bundle.h"
117 #include "ui/base/theme_provider.h"
118 #include "ui/events/event_utils.h"
119 #include "ui/gfx/canvas.h"
120 #include "ui/gfx/color_utils.h"
121 #include "ui/gfx/rect_conversions.h"
122 #include "ui/gfx/sys_color_change_listener.h"
123 #include "ui/views/controls/button/menu_button.h"
124 #include "ui/views/controls/textfield/textfield.h"
125 #include "ui/views/controls/webview/webview.h"
126 #include "ui/views/focus/external_focus_tracker.h"
127 #include "ui/views/focus/view_storage.h"
128 #include "ui/views/layout/grid_layout.h"
129 #include "ui/views/widget/native_widget.h"
130 #include "ui/views/widget/root_view.h"
131 #include "ui/views/widget/widget.h"
132 #include "ui/views/window/dialog_delegate.h"
135 #include "ash/ash_switches.h"
136 #include "ash/shelf/shelf.h"
137 #include "ash/shelf/shelf_model.h"
138 #include "ash/shell.h"
139 #include "chrome/browser/ui/ash/ash_util.h"
142 #if defined(USE_AURA)
143 #include "ui/aura/root_window.h"
144 #include "ui/aura/window.h"
145 #include "ui/gfx/screen.h"
149 #include "base/win/windows_version.h"
150 #include "chrome/browser/jumplist_win.h"
151 #include "ui/views/widget/native_widget_win.h"
152 #include "ui/views/win/scoped_fullscreen_visibility.h"
153 #include "win8/util/win8_util.h"
156 #if defined(ENABLE_ONE_CLICK_SIGNIN)
157 #include "chrome/browser/ui/sync/one_click_signin_bubble_delegate.h"
158 #include "chrome/browser/ui/sync/one_click_signin_bubble_links_delegate.h"
159 #include "chrome/browser/ui/views/sync/one_click_signin_bubble_view.h"
162 #if defined(OS_CHROMEOS)
163 #include "chrome/browser/ui/ash/multi_user/multi_user_window_manager.h"
166 using base::TimeDelta;
167 using base::UserMetricsAction;
168 using content::NativeWebKeyboardEvent;
169 using content::SSLStatus;
170 using content::WebContents;
171 using views::ColumnSet;
172 using views::GridLayout;
173 using web_modal::WebContentsModalDialogHost;
176 // The name of a key to store on the window handle so that other code can
177 // locate this object using just the handle.
178 const char* const kBrowserViewKey = "__BROWSER_VIEW__";
180 // The number of milliseconds between loading animation frames.
181 const int kLoadingAnimationFrameTimeMs = 30;
183 // TODO(kuan): These functions are temporarily for the bookmark bar while its
184 // detached state is at the top of the page; it'll be moved to float on the
185 // content page in the very near future, at which time, these local functions
187 void PaintDetachedBookmarkBar(gfx::Canvas* canvas,
188 DetachableToolbarView* view,
189 ThemeService* theme_service) {
190 // Paint background for detached state; if animating, this is fade in/out.
192 chrome::GetDetachedBookmarkBarBackgroundColor(theme_service));
193 // Draw the separators above and below bookmark bar;
194 // if animating, these are fading in/out.
195 SkColor separator_color =
196 chrome::GetDetachedBookmarkBarSeparatorColor(theme_service);
197 DetachableToolbarView::PaintHorizontalBorder(canvas, view, true,
199 // The bottom border needs to be 1-px thick in both regular and retina
200 // displays, so we can't use DetachableToolbarView::PaintHorizontalBorder
201 // which paints a 2-px thick border in retina display.
203 paint.setAntiAlias(false);
204 // Sets border to 1-px thick regardless of scale factor.
205 paint.setStrokeWidth(0);
206 // Bottom border is at 50% opacity of top border.
207 paint.setColor(SkColorSetA(separator_color,
208 SkColorGetA(separator_color) / 2));
209 // Calculate thickness of bottom border as per current scale factor to
210 // determine where to draw the 1-px thick border.
211 float thickness = views::NonClientFrameView::kClientEdgeThickness /
212 canvas->image_scale();
213 SkScalar y = SkIntToScalar(view->height()) - SkFloatToScalar(thickness);
214 canvas->sk_canvas()->drawLine(SkIntToScalar(0), y,
215 SkIntToScalar(view->width()), y, paint);
218 void PaintAttachedBookmarkBar(gfx::Canvas* canvas,
219 DetachableToolbarView* view,
220 BrowserView* browser_view,
221 chrome::HostDesktopType host_desktop_type,
222 int toolbar_overlap) {
223 // Paint background for attached state, this is fade in/out.
224 gfx::Point background_image_offset =
225 browser_view->OffsetPointForToolbarBackgroundImage(
226 gfx::Point(view->GetMirroredX(), view->y()));
227 DetachableToolbarView::PaintBackgroundAttachedMode(canvas,
228 view->GetThemeProvider(), view->GetLocalBounds(),
229 background_image_offset, host_desktop_type);
230 if (view->height() >= toolbar_overlap) {
231 // Draw the separator below bookmark bar; this is fading in/out.
232 DetachableToolbarView::PaintHorizontalBorder(canvas, view, false,
233 ThemeProperties::GetDefaultColor(
234 ThemeProperties::COLOR_TOOLBAR_SEPARATOR));
241 const char BrowserView::kViewClassName[] = "BrowserView";
245 bool ShouldSaveOrRestoreWindowPos() {
247 // In Windows 8's single window Metro mode the window is always maximized
248 // (without the WS_MAXIMIZE style).
249 if (win8::IsSingleWindowMetroMode())
257 ///////////////////////////////////////////////////////////////////////////////
259 // Delegate implementation for BrowserViewLayout. Usually just forwards calls
261 class BrowserViewLayoutDelegateImpl : public BrowserViewLayoutDelegate {
263 explicit BrowserViewLayoutDelegateImpl(BrowserView* browser_view)
264 : browser_view_(browser_view) {}
265 virtual ~BrowserViewLayoutDelegateImpl() {}
267 // BrowserViewLayoutDelegate overrides:
268 virtual views::View* GetContentsWebView() const OVERRIDE {
269 return browser_view_->contents_web_view_;
272 virtual views::View* GetWindowSwitcherButton() const OVERRIDE {
273 return browser_view_->window_switcher_button();
276 virtual bool DownloadShelfNeedsLayout() const OVERRIDE {
277 DownloadShelfView* download_shelf = browser_view_->download_shelf_.get();
278 // Re-layout the shelf either if it is visible or if its close animation
279 // is currently running.
280 return download_shelf &&
281 (download_shelf->IsShowing() || download_shelf->IsClosing());
284 virtual bool IsTabStripVisible() const OVERRIDE {
285 return browser_view_->IsTabStripVisible();
288 virtual gfx::Rect GetBoundsForTabStripInBrowserView() const OVERRIDE {
289 gfx::RectF bounds_f(browser_view_->frame()->GetBoundsForTabStrip(
290 browser_view_->tabstrip()));
291 views::View::ConvertRectToTarget(browser_view_->parent(), browser_view_,
293 return gfx::ToEnclosingRect(bounds_f);
296 virtual int GetTopInsetInBrowserView() const OVERRIDE {
297 return browser_view_->frame()->GetTopInset() -
301 virtual int GetThemeBackgroundXInset() const OVERRIDE {
302 // TODO(pkotwicz): Return the inset with respect to the left edge of the
304 return browser_view_->frame()->GetThemeBackgroundXInset();
307 virtual bool IsToolbarVisible() const OVERRIDE {
308 return browser_view_->IsToolbarVisible();
311 virtual bool IsBookmarkBarVisible() const OVERRIDE {
312 return browser_view_->IsBookmarkBarVisible();
315 virtual FullscreenExitBubbleViews* GetFullscreenExitBubble() const OVERRIDE {
316 return browser_view_->fullscreen_exit_bubble();
320 BrowserView* browser_view_;
322 DISALLOW_COPY_AND_ASSIGN(BrowserViewLayoutDelegateImpl);
325 ///////////////////////////////////////////////////////////////////////////////
326 // BookmarkExtensionBackground, private:
327 // This object serves as the views::Background object which is used to layout
328 // and paint the bookmark bar.
329 class BookmarkExtensionBackground : public views::Background {
331 BookmarkExtensionBackground(BrowserView* browser_view,
332 DetachableToolbarView* host_view,
335 // View methods overridden from views:Background.
336 virtual void Paint(gfx::Canvas* canvas, views::View* view) const OVERRIDE;
339 BrowserView* browser_view_;
341 // The view hosting this background.
342 DetachableToolbarView* host_view_;
346 DISALLOW_COPY_AND_ASSIGN(BookmarkExtensionBackground);
349 BookmarkExtensionBackground::BookmarkExtensionBackground(
350 BrowserView* browser_view,
351 DetachableToolbarView* host_view,
353 : browser_view_(browser_view),
354 host_view_(host_view),
358 void BookmarkExtensionBackground::Paint(gfx::Canvas* canvas,
359 views::View* view) const {
360 int toolbar_overlap = host_view_->GetToolbarOverlap();
361 if (!host_view_->IsDetached()) {
362 PaintAttachedBookmarkBar(canvas, host_view_, browser_view_,
363 browser_->host_desktop_type(), toolbar_overlap);
367 // As 'hidden' according to the animation is the full in-tab state, we invert
368 // the value - when current_state is at '0', we expect the bar to be docked.
369 double current_state = 1 - host_view_->GetAnimationValue();
372 ThemeServiceFactory::GetForProfile(browser_->profile());
373 if (current_state == 0.0 || current_state == 1.0) {
374 PaintDetachedBookmarkBar(canvas, host_view_, ts);
377 // While animating, set opacity to cross-fade between attached and detached
378 // backgrounds including their respective separators.
379 int detached_alpha = static_cast<uint8>(current_state * 255);
380 int attached_alpha = 255 - detached_alpha;
381 if (browser_->bookmark_bar_state() == BookmarkBar::DETACHED) {
382 // To animate from attached to detached state:
383 // - fade out attached background
384 // - fade in detached background.
385 canvas->SaveLayerAlpha(attached_alpha);
386 PaintAttachedBookmarkBar(canvas, host_view_, browser_view_,
387 browser_->host_desktop_type(),
390 canvas->SaveLayerAlpha(detached_alpha);
391 PaintDetachedBookmarkBar(canvas, host_view_, ts);
393 // To animate from detached to attached state:
394 // - fade out detached background
395 // - fade in attached background.
396 canvas->SaveLayerAlpha(detached_alpha);
397 PaintDetachedBookmarkBar(canvas, host_view_, ts);
399 canvas->SaveLayerAlpha(attached_alpha);
400 PaintAttachedBookmarkBar(canvas, host_view_, browser_view_,
401 browser_->host_desktop_type(),
407 ///////////////////////////////////////////////////////////////////////////////
408 // BrowserView, public:
410 BrowserView::BrowserView()
411 : views::ClientView(NULL, NULL),
412 last_focused_view_storage_id_(
413 views::ViewStorage::GetInstance()->CreateStorageID()),
415 top_container_(NULL),
418 window_switcher_button_(NULL),
419 find_bar_host_view_(NULL),
420 infobar_container_(NULL),
421 contents_web_view_(NULL),
422 contents_container_(NULL),
423 devtools_window_(NULL),
425 in_process_fullscreen_(false),
427 hung_window_detector_(&hung_plugin_action_),
430 force_location_bar_focus_(false),
431 immersive_mode_controller_(chrome::CreateImmersiveModeController()),
432 #if defined(OS_CHROMEOS)
433 scroll_end_effect_controller_(ScrollEndEffectController::Create()),
435 color_change_listener_(this),
436 activate_modal_dialog_factory_(this) {
439 BrowserView::~BrowserView() {
440 // Immersive mode may need to reparent views before they are removed/deleted.
441 immersive_mode_controller_.reset();
443 browser_->tab_strip_model()->RemoveObserver(this);
446 // Stop hung plugin monitoring.
448 ticker_.UnregisterTickHandler(&hung_window_detector_);
450 // Terminate the jumplist (must be called before browser_->profile() is
453 jumplist_->Terminate();
457 // We destroy the download shelf before |browser_| to remove its child
458 // download views from the set of download observers (since the observed
459 // downloads can be destroyed along with |browser_| and the observer
460 // notifications will call back into deleted objects).
461 BrowserViewLayout* browser_view_layout = GetBrowserViewLayout();
462 if (browser_view_layout)
463 browser_view_layout->set_download_shelf(NULL);
464 download_shelf_.reset();
466 // The TabStrip attaches a listener to the model. Make sure we shut down the
467 // TabStrip first so that it can cleanly remove the listener.
469 tabstrip_->parent()->RemoveChildView(tabstrip_);
470 if (browser_view_layout)
471 browser_view_layout->set_tab_strip(NULL);
475 // Child views maintain PrefMember attributes that point to
476 // OffTheRecordProfile's PrefService which gets deleted by ~Browser.
477 RemoveAllChildViews(true);
480 // It is possible that we were forced-closed by the native view system and
481 // that tabs remain in the browser. Close any such remaining tabs. Detach
482 // before destroying in hopes of avoiding less callbacks trying to access
483 // members since destroyed.
485 ScopedVector<content::WebContents> contents;
486 while (browser_->tab_strip_model()->count())
487 contents.push_back(browser_->tab_strip_model()->DetachWebContentsAt(0));
490 // Explicitly set browser_ to NULL.
494 void BrowserView::Init(Browser* browser) {
495 browser_.reset(browser);
496 browser_->tab_strip_model()->AddObserver(this);
500 BrowserView* BrowserView::GetBrowserViewForNativeWindow(
501 gfx::NativeWindow window) {
502 views::Widget* widget = views::Widget::GetWidgetForNativeWindow(window);
504 reinterpret_cast<BrowserView*>(widget->GetNativeWindowProperty(
505 kBrowserViewKey)) : NULL;
509 BrowserView* BrowserView::GetBrowserViewForBrowser(const Browser* browser) {
510 return static_cast<BrowserView*>(browser->window());
513 void BrowserView::InitStatusBubble() {
514 status_bubble_.reset(new StatusBubbleViews(contents_web_view_));
515 contents_web_view_->SetStatusBubble(status_bubble_.get());
518 gfx::Rect BrowserView::GetToolbarBounds() const {
519 gfx::Rect toolbar_bounds(toolbar_->bounds());
520 if (toolbar_bounds.IsEmpty())
521 return toolbar_bounds;
522 // The apparent toolbar edges are outside the "real" toolbar edges.
523 toolbar_bounds.Inset(-views::NonClientFrameView::kClientEdgeThickness, 0);
524 return toolbar_bounds;
527 gfx::Rect BrowserView::GetFindBarBoundingBox() const {
528 return GetBrowserViewLayout()->GetFindBarBoundingBox();
531 int BrowserView::GetTabStripHeight() const {
532 // We want to return tabstrip_->height(), but we might be called in the midst
533 // of layout, when that hasn't yet been updated to reflect the current state.
534 // So return what the tabstrip height _ought_ to be right now.
535 return IsTabStripVisible() ? tabstrip_->GetPreferredSize().height() : 0;
538 gfx::Point BrowserView::OffsetPointForToolbarBackgroundImage(
539 const gfx::Point& point) const {
540 // The background image starts tiling horizontally at the window left edge and
541 // vertically at the top edge of the horizontal tab strip (or where it would
542 // be). We expect our parent's origin to be the window origin.
543 gfx::Point window_point(point + GetMirroredPosition().OffsetFromOrigin());
544 window_point.Offset(frame_->GetThemeBackgroundXInset(),
545 -frame_->GetTopInset());
549 bool BrowserView::IsTabStripVisible() const {
550 if (immersive_mode_controller_->ShouldHideTopViews() &&
551 immersive_mode_controller_->ShouldHideTabIndicators())
553 return browser_->SupportsWindowFeature(Browser::FEATURE_TABSTRIP);
556 bool BrowserView::IsOffTheRecord() const {
557 return browser_->profile()->IsOffTheRecord();
560 bool BrowserView::IsGuestSession() const {
561 return browser_->profile()->IsGuestSession();
564 bool BrowserView::IsRegularOrGuestSession() const {
565 return profiles::IsRegularOrGuestSession(browser_.get());
568 int BrowserView::GetOTRIconResourceID() const {
569 int otr_resource_id = IDR_OTR_ICON;
570 if (ui::GetDisplayLayout() == ui::LAYOUT_TOUCH) {
572 otr_resource_id = IDR_OTR_ICON_FULLSCREEN;
574 if (win8::IsSingleWindowMetroMode())
575 otr_resource_id = IDR_OTR_ICON_FULLSCREEN;
579 return otr_resource_id;
582 int BrowserView::GetGuestIconResourceID() const {
583 return IDR_LOGIN_GUEST;
586 bool BrowserView::ShouldShowAvatar() const {
587 if (!IsBrowserTypeNormal())
589 #if defined(OS_CHROMEOS)
590 if (IsOffTheRecord() && !IsGuestSession())
593 // Note: In case of the M-31 mode the window manager won't exist.
594 if (chrome::MultiUserWindowManager::GetMultiProfileMode() ==
595 chrome::MultiUserWindowManager::MULTI_PROFILE_MODE_SEPARATED) {
596 // This function is called via BrowserNonClientFrameView::UpdateAvatarInfo
597 // during the creation of the BrowserWindow, so browser->window() will not
598 // yet be set. In this case we can safely return false.
599 if (!browser_->window())
602 // If the window is shown on a different desktop than the user, it should
603 // have the avatar icon.
604 aura::Window* window = browser_->window()->GetNativeWindow();
606 // Note: When the window manager the window is either on it's owners desktop
607 // (and shows no icon) or it is now (in which it will show an icon). So we
609 chrome::MultiUserWindowManager* window_manager =
610 chrome::MultiUserWindowManager::GetInstance();
611 return !window_manager->IsWindowOnDesktopOfUser(
613 window_manager->GetWindowOwner(window));
616 if (IsOffTheRecord()) // Desktop guest is incognito and needs avatar.
619 // Tests may not have a profile manager.
620 if (!g_browser_process->profile_manager())
622 ProfileInfoCache& cache =
623 g_browser_process->profile_manager()->GetProfileInfoCache();
624 if (cache.GetIndexOfProfileWithPath(browser_->profile()->GetPath()) ==
629 return AvatarMenu::ShouldShowAvatarMenu();
632 bool BrowserView::GetAccelerator(int cmd_id, ui::Accelerator* accelerator) {
633 // We retrieve the accelerator information for standard accelerators
634 // for cut, copy and paste.
635 if (chrome::GetStandardAcceleratorForCommandId(cmd_id, accelerator))
637 // Else, we retrieve the accelerator information from the accelerator table.
638 for (std::map<ui::Accelerator, int>::const_iterator it =
639 accelerator_table_.begin(); it != accelerator_table_.end(); ++it) {
640 if (it->second == cmd_id) {
641 *accelerator = it->first;
645 // Else, we retrieve the accelerator information from Ash (if applicable).
646 return chrome::GetAshAcceleratorForCommandId(
647 cmd_id, browser_->host_desktop_type(), accelerator);
650 bool BrowserView::IsAcceleratorRegistered(const ui::Accelerator& accelerator) {
651 return accelerator_table_.find(accelerator) != accelerator_table_.end();
654 WebContents* BrowserView::GetActiveWebContents() const {
655 return browser_->tab_strip_model()->GetActiveWebContents();
658 gfx::ImageSkia BrowserView::GetOTRAvatarIcon() const {
659 return *GetThemeProvider()->GetImageSkiaNamed(GetOTRIconResourceID());
662 ///////////////////////////////////////////////////////////////////////////////
663 // BrowserView, BrowserWindow implementation:
665 void BrowserView::Show() {
666 // If the window is already visible, just activate it.
667 if (frame_->IsVisible()) {
672 // Showing the window doesn't make the browser window active right away.
673 // This can cause SetFocusToLocationBar() to skip setting focus to the
674 // location bar. To avoid this we explicilty let SetFocusToLocationBar()
675 // know that it's ok to steal focus.
676 force_location_bar_focus_ = true;
678 // Setting the focus doesn't work when the window is invisible, so any focus
679 // initialization that happened before this will be lost.
681 // We really "should" restore the focus whenever the window becomes unhidden,
682 // but I think initializing is the only time where this can happen where
683 // there is some focus change we need to pick up, and this is easier than
684 // plumbing through an un-hide message all the way from the frame.
686 // If we do find there are cases where we need to restore the focus on show,
687 // that should be added and this should be removed.
692 force_location_bar_focus_ = false;
694 browser()->OnWindowDidShow();
696 chrome::MaybeShowInvertBubbleView(browser_.get(), contents_container_);
699 void BrowserView::ShowInactive() {
700 if (frame_->IsVisible())
702 frame_->ShowInactive();
705 void BrowserView::Hide() {
709 void BrowserView::SetBounds(const gfx::Rect& bounds) {
711 GetWidget()->SetBounds(bounds);
714 void BrowserView::Close() {
718 void BrowserView::Activate() {
722 void BrowserView::Deactivate() {
723 frame_->Deactivate();
726 bool BrowserView::IsActive() const {
727 return frame_->IsActive();
730 void BrowserView::FlashFrame(bool flash) {
731 frame_->FlashFrame(flash);
734 bool BrowserView::IsAlwaysOnTop() const {
738 void BrowserView::SetAlwaysOnTop(bool always_on_top) {
739 // Not implemented for browser windows.
743 gfx::NativeWindow BrowserView::GetNativeWindow() {
744 // While the browser destruction is going on, the widget can already be gone,
745 // but utility functions like FindBrowserWithWindow will come here and crash.
746 // We short circuit therefore.
749 return GetWidget()->GetTopLevelWidget()->GetNativeWindow();
752 BrowserWindowTesting* BrowserView::GetBrowserWindowTesting() {
756 StatusBubble* BrowserView::GetStatusBubble() {
757 return status_bubble_.get();
761 // Only used by ToolbarSizeChanged() below, but placed here because template
762 // arguments (to base::AutoReset<>) must have external linkage.
763 enum CallState { NORMAL, REENTRANT, REENTRANT_FORCE_FAST_RESIZE };
766 void BrowserView::UpdateTitleBar() {
767 frame_->UpdateWindowTitle();
768 if (ShouldShowWindowIcon() && !loading_animation_timer_.IsRunning())
769 frame_->UpdateWindowIcon();
772 void BrowserView::BookmarkBarStateChanged(
773 BookmarkBar::AnimateChangeType change_type) {
774 if (bookmark_bar_view_.get()) {
775 BookmarkBar::State new_state = browser_->bookmark_bar_state();
777 // We don't properly support animating the bookmark bar to and from the
778 // detached state in immersive fullscreen.
779 bool detached_changed = (new_state == BookmarkBar::DETACHED) ||
780 bookmark_bar_view_->IsDetached();
781 if (detached_changed && immersive_mode_controller_->IsEnabled())
782 change_type = BookmarkBar::DONT_ANIMATE_STATE_CHANGE;
784 bookmark_bar_view_->SetBookmarkBarState(new_state, change_type);
786 if (MaybeShowBookmarkBar(GetActiveWebContents()))
790 void BrowserView::UpdateDevTools() {
791 UpdateDevToolsForContents(GetActiveWebContents(), true);
795 void BrowserView::UpdateLoadingAnimations(bool should_animate) {
796 if (should_animate) {
797 if (!loading_animation_timer_.IsRunning()) {
798 // Loads are happening, and the timer isn't running, so start it.
799 last_animation_time_ = base::TimeTicks::Now();
800 loading_animation_timer_.Start(FROM_HERE,
801 TimeDelta::FromMilliseconds(kLoadingAnimationFrameTimeMs), this,
802 &BrowserView::LoadingAnimationCallback);
805 if (loading_animation_timer_.IsRunning()) {
806 last_animation_time_ = base::TimeTicks();
807 loading_animation_timer_.Stop();
808 // Loads are now complete, update the state if a task was scheduled.
809 LoadingAnimationCallback();
814 void BrowserView::SetStarredState(bool is_starred) {
815 GetLocationBarView()->SetStarToggled(is_starred);
818 void BrowserView::SetTranslateIconToggled(bool is_lit) {
819 GetLocationBarView()->SetTranslateIconToggled(is_lit);
822 void BrowserView::OnActiveTabChanged(content::WebContents* old_contents,
823 content::WebContents* new_contents,
826 DCHECK(new_contents);
828 // If |contents_container_| already has the correct WebContents, we can save
829 // some work. This also prevents extra events from being reported by the
830 // Visibility API under Windows, as ChangeWebContents will briefly hide
831 // the WebContents window.
832 bool change_tab_contents =
833 contents_web_view_->web_contents() != new_contents;
835 // Update various elements that are interested in knowing the current
838 // When we toggle the NTP floating bookmarks bar and/or the info bar,
839 // we don't want any WebContents to be attached, so that we
840 // avoid an unnecessary resize and re-layout of a WebContents.
841 if (change_tab_contents) {
842 contents_web_view_->SetWebContents(NULL);
843 devtools_web_view_->SetWebContents(NULL);
845 infobar_container_->ChangeInfoBarService(
846 InfoBarService::FromWebContents(new_contents));
847 if (bookmark_bar_view_.get()) {
848 bookmark_bar_view_->SetBookmarkBarState(
849 browser_->bookmark_bar_state(),
850 BookmarkBar::DONT_ANIMATE_STATE_CHANGE);
852 UpdateUIForContents(new_contents);
854 // Layout for DevTools _before_ setting the both main and devtools WebContents
855 // to avoid toggling the size of any of them.
856 UpdateDevToolsForContents(new_contents, !change_tab_contents);
858 if (change_tab_contents) {
859 contents_web_view_->SetWebContents(new_contents);
860 // The second layout update should be no-op. It will just set the
861 // DevTools WebContents.
862 UpdateDevToolsForContents(new_contents, true);
865 if (!browser_->tab_strip_model()->closing_all() && GetWidget()->IsActive() &&
866 GetWidget()->IsVisible()) {
867 // We only restore focus if our window is visible, to avoid invoking blur
868 // handlers when we are eventually shown.
869 new_contents->GetView()->RestoreFocus();
872 // Update all the UI bits.
876 void BrowserView::ZoomChangedForActiveTab(bool can_show_bubble) {
877 GetLocationBarView()->ZoomChangedForActiveTab(
878 can_show_bubble && !toolbar_->IsWrenchMenuShowing());
881 gfx::Rect BrowserView::GetRestoredBounds() const {
882 return frame_->GetRestoredBounds();
885 ui::WindowShowState BrowserView::GetRestoredState() const {
887 return ui::SHOW_STATE_MAXIMIZED;
889 return ui::SHOW_STATE_MINIMIZED;
890 return ui::SHOW_STATE_NORMAL;
893 gfx::Rect BrowserView::GetBounds() const {
894 return frame_->GetWindowBoundsInScreen();
897 bool BrowserView::IsMaximized() const {
898 return frame_->IsMaximized();
901 bool BrowserView::IsMinimized() const {
902 return frame_->IsMinimized();
905 void BrowserView::Maximize() {
909 void BrowserView::Minimize() {
913 void BrowserView::Restore() {
917 void BrowserView::EnterFullscreen(
918 const GURL& url, FullscreenExitBubbleType bubble_type) {
920 return; // Nothing to do.
922 ProcessFullscreen(true, FOR_DESKTOP, url, bubble_type);
925 void BrowserView::ExitFullscreen() {
927 return; // Nothing to do.
929 ProcessFullscreen(false, FOR_DESKTOP, GURL(), FEB_TYPE_NONE);
932 void BrowserView::UpdateFullscreenExitBubbleContent(
934 FullscreenExitBubbleType bubble_type) {
935 // Immersive mode has no exit bubble because it has a visible strip at the
936 // top that gives the user a hover target.
937 // TODO(jamescook): Figure out what to do with mouse-lock.
938 if (bubble_type == FEB_TYPE_NONE || ShouldUseImmersiveFullscreenForUrl(url)) {
939 fullscreen_bubble_.reset();
940 } else if (fullscreen_bubble_.get()) {
941 fullscreen_bubble_->UpdateContent(url, bubble_type);
943 fullscreen_bubble_.reset(new FullscreenExitBubbleViews(
944 this, url, bubble_type));
948 bool BrowserView::ShouldHideUIForFullscreen() const {
950 // Immersive mode needs UI for the slide-down top panel.
951 return IsFullscreen() && !immersive_mode_controller_->IsEnabled();
953 return IsFullscreen();
956 bool BrowserView::IsFullscreen() const {
957 return frame_->IsFullscreen();
960 bool BrowserView::IsFullscreenBubbleVisible() const {
961 return fullscreen_bubble_ != NULL;
965 void BrowserView::SetMetroSnapMode(bool enable) {
966 HISTOGRAM_COUNTS("Metro.SnapModeToggle", enable);
967 ProcessFullscreen(enable, FOR_METRO, GURL(), FEB_TYPE_NONE);
970 bool BrowserView::IsInMetroSnapMode() const {
971 #if defined(USE_AURA)
974 return static_cast<views::NativeWidgetWin*>(
975 frame_->native_widget())->IsInMetroSnapMode();
978 #endif // defined(OS_WIN)
980 void BrowserView::RestoreFocus() {
981 WebContents* selected_web_contents = GetActiveWebContents();
982 if (selected_web_contents)
983 selected_web_contents->GetView()->RestoreFocus();
986 void BrowserView::SetWindowSwitcherButton(views::Button* button) {
987 if (window_switcher_button_)
988 RemoveChildView(window_switcher_button_);
989 window_switcher_button_ = button;
992 void BrowserView::FullscreenStateChanged() {
993 CHECK(!IsFullscreen());
994 ProcessFullscreen(false, FOR_DESKTOP, GURL(), FEB_TYPE_NONE);
997 void BrowserView::ToolbarSizeChanged(bool is_animating) {
998 // The call to InfoBarContainer::SetMaxTopArrowHeight() below can result in
999 // reentrancy; |call_state| tracks whether we're reentrant. We can't just
1000 // early-return in this case because we need to layout again so the infobar
1001 // container's bounds are set correctly.
1002 static CallState call_state = NORMAL;
1004 // A reentrant call can (and should) use the fast resize path unless both it
1005 // and the normal call are both non-animating.
1006 bool use_fast_resize =
1007 is_animating || (call_state == REENTRANT_FORCE_FAST_RESIZE);
1008 if (use_fast_resize)
1009 contents_web_view_->SetFastResize(true);
1010 UpdateUIForContents(GetActiveWebContents());
1011 if (use_fast_resize)
1012 contents_web_view_->SetFastResize(false);
1014 // Inform the InfoBarContainer that the distance to the location icon may have
1015 // changed. We have to do this after the block above so that the toolbars are
1016 // laid out correctly for calculating the maximum arrow height below.
1018 base::AutoReset<CallState> resetter(&call_state,
1019 is_animating ? REENTRANT_FORCE_FAST_RESIZE : REENTRANT);
1020 infobar_container_->SetMaxTopArrowHeight(GetMaxTopInfoBarArrowHeight());
1023 // When transitioning from animating to not animating we need to make sure the
1024 // contents_container_ gets layed out. If we don't do this and the bounds
1025 // haven't changed contents_container_ won't get a Layout out and we'll end up
1026 // with a gray rect because the clip wasn't updated. Note that a reentrant
1027 // call never needs to do this, because after it returns, the normal call
1028 // wrapping it will do it.
1029 if ((call_state == NORMAL) && !is_animating) {
1030 contents_web_view_->InvalidateLayout();
1031 contents_container_->Layout();
1035 LocationBar* BrowserView::GetLocationBar() const {
1036 return GetLocationBarView();
1039 void BrowserView::SetFocusToLocationBar(bool select_all) {
1040 // On Windows, changing focus to the location bar causes the browser
1041 // window to become active. This can steal focus if the user has
1042 // another window open already. On ChromeOS, changing focus makes a
1043 // view believe it has a focus even if the widget doens't have a
1044 // focus. Either cases, we need to ignore this when the browser
1045 // window isn't active.
1046 if (!force_location_bar_focus_ && !IsActive())
1049 // Temporarily reveal the top-of-window views (if not already revealed) so
1050 // that the location bar view is visible and is considered focusable. If the
1051 // location bar view gains focus, |immersive_mode_controller_| will keep the
1052 // top-of-window views revealed.
1053 scoped_ptr<ImmersiveRevealedLock> focus_reveal_lock(
1054 immersive_mode_controller_->GetRevealedLock(
1055 ImmersiveModeController::ANIMATE_REVEAL_YES));
1057 LocationBarView* location_bar = GetLocationBarView();
1058 if (location_bar->omnibox_view()->IsFocusable()) {
1059 // Location bar got focus.
1060 if (chrome::ShouldDisplayOriginChip())
1061 location_bar->omnibox_view()->ShowURL();
1063 location_bar->FocusLocation(select_all);
1065 // If none of location bar got focus, then clear focus.
1066 views::FocusManager* focus_manager = GetFocusManager();
1067 DCHECK(focus_manager);
1068 focus_manager->ClearFocus();
1072 void BrowserView::UpdateReloadStopState(bool is_loading, bool force) {
1073 toolbar_->reload_button()->ChangeMode(
1074 is_loading ? ReloadButton::MODE_STOP : ReloadButton::MODE_RELOAD, force);
1077 void BrowserView::UpdateToolbar(content::WebContents* contents) {
1078 // We may end up here during destruction.
1080 toolbar_->Update(contents);
1083 void BrowserView::FocusToolbar() {
1084 // Temporarily reveal the top-of-window views (if not already revealed) so
1085 // that the toolbar is visible and is considered focusable. If the
1086 // toolbar gains focus, |immersive_mode_controller_| will keep the
1087 // top-of-window views revealed.
1088 scoped_ptr<ImmersiveRevealedLock> focus_reveal_lock(
1089 immersive_mode_controller_->GetRevealedLock(
1090 ImmersiveModeController::ANIMATE_REVEAL_YES));
1092 // Start the traversal within the main toolbar. SetPaneFocus stores
1093 // the current focused view before changing focus.
1094 toolbar_->SetPaneFocus(NULL);
1097 void BrowserView::FocusBookmarksToolbar() {
1098 DCHECK(!immersive_mode_controller_->IsEnabled());
1099 if (bookmark_bar_view_.get() &&
1100 bookmark_bar_view_->visible() &&
1101 bookmark_bar_view_->GetPreferredSize().height() != 0) {
1102 bookmark_bar_view_->SetPaneFocusAndFocusDefault();
1106 void BrowserView::FocusInfobars() {
1107 if (infobar_container_->child_count() > 0)
1108 infobar_container_->SetPaneFocusAndFocusDefault();
1111 void BrowserView::FocusAppMenu() {
1112 // Chrome doesn't have a traditional menu bar, but it has a menu button in the
1113 // main toolbar that plays the same role. If the user presses a key that
1114 // would typically focus the menu bar, tell the toolbar to focus the menu
1115 // button. If the user presses the key again, return focus to the previous
1118 // Not used on the Mac, which has a normal menu bar.
1119 if (toolbar_->IsAppMenuFocused()) {
1122 DCHECK(!immersive_mode_controller_->IsEnabled());
1123 toolbar_->SetPaneFocusAndFocusAppMenu();
1127 void BrowserView::RotatePaneFocus(bool forwards) {
1128 GetWidget()->GetFocusManager()->RotatePaneFocus(
1130 views::FocusManager::kForward : views::FocusManager::kBackward,
1131 views::FocusManager::kWrap);
1134 void BrowserView::DestroyBrowser() {
1135 // After this returns other parts of Chrome are going to be shutdown. Close
1136 // the window now so that we are deleted immediately and aren't left holding
1137 // references to deleted objects.
1138 GetWidget()->RemoveObserver(this);
1139 GetLocationBar()->GetOmniboxView()->model()->popup_model()->RemoveObserver(
1144 bool BrowserView::IsBookmarkBarVisible() const {
1145 if (!browser_->SupportsWindowFeature(Browser::FEATURE_BOOKMARKBAR))
1147 if (!bookmark_bar_view_.get())
1149 if (bookmark_bar_view_->GetPreferredSize().height() == 0)
1151 // New tab page needs visible bookmarks even when top-views are hidden.
1152 if (immersive_mode_controller_->ShouldHideTopViews() &&
1153 !bookmark_bar_view_->IsDetached())
1158 bool BrowserView::IsBookmarkBarAnimating() const {
1159 return bookmark_bar_view_.get() && bookmark_bar_view_->is_animating();
1162 bool BrowserView::IsTabStripEditable() const {
1163 return tabstrip_->IsTabStripEditable();
1166 bool BrowserView::IsToolbarVisible() const {
1167 if (immersive_mode_controller_->ShouldHideTopViews())
1169 return browser_->SupportsWindowFeature(Browser::FEATURE_TOOLBAR) ||
1170 browser_->SupportsWindowFeature(Browser::FEATURE_LOCATIONBAR);
1173 gfx::Rect BrowserView::GetRootWindowResizerRect() const {
1174 // Views does not support resizer rects because they caused page cycler
1175 // performance regressions when they were added. See crrev.com/9654
1179 void BrowserView::ConfirmAddSearchProvider(TemplateURL* template_url,
1181 chrome::EditSearchEngine(GetWidget()->GetNativeWindow(), template_url, NULL,
1185 void BrowserView::ShowUpdateChromeDialog() {
1186 UpdateRecommendedMessageBox::Show(GetWidget()->GetNativeWindow());
1189 void BrowserView::ShowBookmarkBubble(const GURL& url, bool already_bookmarked) {
1190 scoped_ptr<BookmarkBubbleDelegate> delegate;
1191 delegate.reset(new BookmarkBubbleSignInDelegate(browser_.get()));
1193 BookmarkBubbleView::ShowBubble(GetToolbarView()->GetBookmarkBubbleAnchor(),
1194 bookmark_bar_view_.get(),
1196 browser_->profile(),
1198 !already_bookmarked);
1201 void BrowserView::ShowBookmarkPrompt() {
1202 GetLocationBarView()->ShowBookmarkPrompt();
1205 void BrowserView::ShowTranslateBubble(
1206 content::WebContents* web_contents,
1207 TranslateBubbleModel::ViewState view_state,
1208 TranslateErrors::Type error_type) {
1209 TranslateTabHelper* translate_tab_helper =
1210 TranslateTabHelper::FromWebContents(web_contents);
1211 LanguageState& language_state = translate_tab_helper->GetLanguageState();
1212 language_state.SetTranslateEnabled(true);
1214 TranslateBubbleView::ShowBubble(GetToolbarView()->GetTranslateBubbleAnchor(),
1215 web_contents, view_state, error_type);
1218 #if defined(ENABLE_ONE_CLICK_SIGNIN)
1219 void BrowserView::ShowOneClickSigninBubble(
1220 OneClickSigninBubbleType type,
1221 const base::string16& email,
1222 const base::string16& error_message,
1223 const StartSyncCallback& start_sync_callback) {
1224 scoped_ptr<OneClickSigninBubbleDelegate> delegate;
1225 delegate.reset(new OneClickSigninBubbleLinksDelegate(browser()));
1227 views::View* anchor_view;
1228 if (type == BrowserWindow::ONE_CLICK_SIGNIN_BUBBLE_TYPE_BUBBLE)
1229 anchor_view = toolbar_->app_menu();
1231 anchor_view = toolbar_->location_bar();
1233 OneClickSigninBubbleView::ShowBubble(type, email, error_message,
1234 delegate.Pass(), anchor_view,
1235 start_sync_callback);
1239 void BrowserView::SetDownloadShelfVisible(bool visible) {
1240 // This can be called from the superclass destructor, when it destroys our
1241 // child views. At that point, browser_ is already gone.
1242 if (browser_ == NULL)
1245 if (visible && IsDownloadShelfVisible() != visible) {
1246 // Invoke GetDownloadShelf to force the shelf to be created.
1250 if (browser_ != NULL)
1251 browser_->UpdateDownloadShelfVisibility(visible);
1253 // SetDownloadShelfVisible can force-close the shelf, so make sure we lay out
1254 // everything correctly, as if the animation had finished. This doesn't
1255 // matter for showing the shelf, as the show animation will do it.
1256 ToolbarSizeChanged(false);
1259 bool BrowserView::IsDownloadShelfVisible() const {
1260 return download_shelf_.get() && download_shelf_->IsShowing();
1263 DownloadShelf* BrowserView::GetDownloadShelf() {
1264 if (!download_shelf_.get()) {
1265 download_shelf_.reset(new DownloadShelfView(browser_.get(), this));
1266 download_shelf_->set_owned_by_client();
1267 GetBrowserViewLayout()->set_download_shelf(download_shelf_.get());
1269 return download_shelf_.get();
1272 void BrowserView::ConfirmBrowserCloseWithPendingDownloads(
1274 Browser::DownloadClosePreventionType dialog_type,
1276 const base::Callback<void(bool)>& callback) {
1277 DownloadInProgressDialogView::Show(
1278 GetNativeWindow(), download_count, dialog_type, app_modal, callback);
1281 void BrowserView::UserChangedTheme() {
1282 frame_->FrameTypeChanged();
1285 int BrowserView::GetExtraRenderViewHeight() const {
1286 // Currently this is only used on linux.
1290 void BrowserView::WebContentsFocused(WebContents* contents) {
1291 if (contents_web_view_->GetWebContents() == contents)
1292 contents_web_view_->OnWebContentsFocused(contents);
1294 devtools_web_view_->OnWebContentsFocused(contents);
1297 void BrowserView::ShowWebsiteSettings(Profile* profile,
1298 content::WebContents* web_contents,
1300 const content::SSLStatus& ssl) {
1301 WebsiteSettingsPopupView::ShowPopup(
1302 GetLocationBarView()->GetLocationIconView(), profile,
1303 web_contents, url, ssl, browser_.get());
1306 void BrowserView::ShowAppMenu() {
1307 // Keep the top-of-window views revealed as long as the app menu is visible.
1308 scoped_ptr<ImmersiveRevealedLock> revealed_lock(
1309 immersive_mode_controller_->GetRevealedLock(
1310 ImmersiveModeController::ANIMATE_REVEAL_NO));
1312 toolbar_->app_menu()->Activate();
1315 bool BrowserView::PreHandleKeyboardEvent(const NativeWebKeyboardEvent& event,
1316 bool* is_keyboard_shortcut) {
1317 *is_keyboard_shortcut = false;
1319 if ((event.type != blink::WebInputEvent::RawKeyDown) &&
1320 (event.type != blink::WebInputEvent::KeyUp)) {
1324 views::FocusManager* focus_manager = GetFocusManager();
1325 DCHECK(focus_manager);
1327 if (focus_manager->shortcut_handling_suspended())
1330 ui::Accelerator accelerator(
1331 static_cast<ui::KeyboardCode>(event.windowsKeyCode),
1332 content::GetModifiersFromNativeWebKeyboardEvent(event));
1333 if (event.type == blink::WebInputEvent::KeyUp)
1334 accelerator.set_type(ui::ET_KEY_RELEASED);
1336 // What we have to do here is as follows:
1337 // - If the |browser_| is for an app, do nothing.
1338 // - If the |browser_| is not for an app, and the |accelerator| is not
1339 // associated with the browser (e.g. an Ash shortcut), process it.
1340 // - If the |browser_| is not for an app, and the |accelerator| is associated
1341 // with the browser, and it is a reserved one (e.g. Ctrl+w), process it.
1342 // - If the |browser_| is not for an app, and the |accelerator| is associated
1343 // with the browser, and it is not a reserved one, do nothing.
1345 if (browser_->is_app()) {
1346 // Let all keys fall through to a v1 app's web content, even accelerators.
1347 // We don't have to flip |is_keyboard_shortcut| here. If we do that, the app
1348 // might not be able to see a subsequent Char event. See OnHandleInputEvent
1349 // in content/renderer/render_widget.cc for details.
1353 chrome::BrowserCommandController* controller = browser_->command_controller();
1355 // Here we need to retrieve the command id (if any) associated to the
1356 // keyboard event. Instead of looking up the command id in the
1357 // |accelerator_table_| by ourselves, we block the command execution of
1358 // the |browser_| object then send the keyboard event to the
1359 // |focus_manager| as if we are activating an accelerator key.
1360 // Then we can retrieve the command id from the |browser_| object.
1361 bool original_block_command_state = controller->block_command_execution();
1362 controller->SetBlockCommandExecution(true);
1363 // If the |accelerator| is a non-browser shortcut (e.g. Ash shortcut), the
1364 // command execution cannot be blocked and true is returned. However, it is
1365 // okay as long as is_app() is false. See comments in this function.
1366 const bool processed = focus_manager->ProcessAccelerator(accelerator);
1367 const int id = controller->GetLastBlockedCommand(NULL);
1368 controller->SetBlockCommandExecution(original_block_command_state);
1370 // Executing the command may cause |this| object to be destroyed.
1371 if (controller->IsReservedCommandOrKey(id, event)) {
1372 UpdateAcceleratorMetrics(accelerator, id);
1373 return chrome::ExecuteCommand(browser_.get(), id);
1377 // |accelerator| is a non-reserved browser shortcut (e.g. Ctrl+f).
1378 if (event.type == blink::WebInputEvent::RawKeyDown)
1379 *is_keyboard_shortcut = true;
1380 } else if (processed) {
1381 // |accelerator| is a non-browser shortcut (e.g. F4-F10 on Ash). Report
1382 // that we handled it.
1389 void BrowserView::HandleKeyboardEvent(const NativeWebKeyboardEvent& event) {
1390 unhandled_keyboard_event_handler_.HandleKeyboardEvent(event,
1394 // TODO(devint): http://b/issue?id=1117225 Cut, Copy, and Paste are always
1395 // enabled in the page menu regardless of whether the command will do
1396 // anything. When someone selects the menu item, we just act as if they hit
1397 // the keyboard shortcut for the command by sending the associated key press
1398 // to windows. The real fix to this bug is to disable the commands when they
1399 // won't do anything. We'll need something like an overall clipboard command
1400 // manager to do that.
1401 void BrowserView::Cut() {
1402 // If a WebContent is focused, call RenderWidgetHost::Cut. Otherwise, e.g. if
1403 // Omnibox is focused, send a Ctrl+x key event to Chrome. Using RWH interface
1404 // rather than the fake key event for a WebContent is important since the fake
1405 // event might be consumed by the web content (crbug.com/137908).
1406 DoCutCopyPaste(&content::RenderWidgetHost::Cut, IDS_APP_CUT);
1409 void BrowserView::Copy() {
1410 DoCutCopyPaste(&content::RenderWidgetHost::Copy, IDS_APP_COPY);
1413 void BrowserView::Paste() {
1414 DoCutCopyPaste(&content::RenderWidgetHost::Paste, IDS_APP_PASTE);
1417 WindowOpenDisposition BrowserView::GetDispositionForPopupBounds(
1418 const gfx::Rect& bounds) {
1420 // If we are in Win8's single window Metro mode, we can't allow popup windows.
1421 return win8::IsSingleWindowMetroMode() ? NEW_BACKGROUND_TAB : NEW_POPUP;
1427 FindBar* BrowserView::CreateFindBar() {
1428 return chrome::CreateFindBar(this);
1431 WebContentsModalDialogHost* BrowserView::GetWebContentsModalDialogHost() {
1432 return GetBrowserViewLayout()->GetWebContentsModalDialogHost();
1435 ///////////////////////////////////////////////////////////////////////////////
1436 // BrowserView, BrowserWindowTesting implementation:
1438 BookmarkBarView* BrowserView::GetBookmarkBarView() const {
1439 return bookmark_bar_view_.get();
1442 LocationBarView* BrowserView::GetLocationBarView() const {
1443 return toolbar_ ? toolbar_->location_bar() : NULL;
1446 views::View* BrowserView::GetTabContentsContainerView() const {
1447 return contents_web_view_;
1450 ToolbarView* BrowserView::GetToolbarView() const {
1454 ///////////////////////////////////////////////////////////////////////////////
1455 // BrowserView, TabStripModelObserver implementation:
1457 void BrowserView::TabDetachedAt(WebContents* contents, int index) {
1458 // We use index here rather than comparing |contents| because by this time
1459 // the model has already removed |contents| from its list, so
1460 // browser_->GetActiveWebContents() will return NULL or something else.
1461 if (index == browser_->tab_strip_model()->active_index()) {
1462 // We need to reset the current tab contents to NULL before it gets
1463 // freed. This is because the focus manager performs some operations
1464 // on the selected WebContents when it is removed.
1465 contents_web_view_->SetWebContents(NULL);
1466 infobar_container_->ChangeInfoBarService(NULL);
1467 UpdateDevToolsForContents(NULL, true);
1471 void BrowserView::TabDeactivated(WebContents* contents) {
1472 // We do not store the focus when closing the tab to work-around bug 4633.
1473 // Some reports seem to show that the focus manager and/or focused view can
1474 // be garbage at that point, it is not clear why.
1475 if (!contents->IsBeingDestroyed())
1476 contents->GetView()->StoreFocus();
1479 void BrowserView::TabStripEmpty() {
1480 // Make sure all optional UI is removed before we are destroyed, otherwise
1481 // there will be consequences (since our view hierarchy will still have
1482 // references to freed views).
1483 UpdateUIForContents(NULL);
1486 ///////////////////////////////////////////////////////////////////////////////
1487 // BrowserView, ui::AcceleratorProvider implementation:
1489 bool BrowserView::GetAcceleratorForCommandId(int command_id,
1490 ui::Accelerator* accelerator) {
1491 // Let's let the ToolbarView own the canonical implementation of this method.
1492 return toolbar_->GetAcceleratorForCommandId(command_id, accelerator);
1495 ///////////////////////////////////////////////////////////////////////////////
1496 // BrowserView, views::WidgetDelegate implementation:
1498 bool BrowserView::CanResize() const {
1502 bool BrowserView::CanMaximize() const {
1506 bool BrowserView::CanActivate() const {
1507 if (!AppModalDialogQueue::GetInstance()->active_dialog() ||
1508 !AppModalDialogQueue::GetInstance()->active_dialog()->native_dialog())
1511 #if defined(USE_AURA) && defined(OS_CHROMEOS)
1512 // On Aura window manager controls all windows so settings focus via PostTask
1513 // will make only worse because posted task will keep trying to steal focus.
1514 AppModalDialogQueue::GetInstance()->ActivateModalDialog();
1516 // If another browser is app modal, flash and activate the modal browser. This
1517 // has to be done in a post task, otherwise if the user clicked on a window
1518 // that doesn't have the modal dialog the windows keep trying to get the focus
1519 // from each other on Windows. http://crbug.com/141650.
1520 base::MessageLoop::current()->PostTask(
1522 base::Bind(&BrowserView::ActivateAppModalDialog,
1523 activate_modal_dialog_factory_.GetWeakPtr()));
1528 base::string16 BrowserView::GetWindowTitle() const {
1529 return browser_->GetWindowTitleForCurrentTab();
1532 base::string16 BrowserView::GetAccessibleWindowTitle() const {
1533 if (IsOffTheRecord()) {
1534 return l10n_util::GetStringFUTF16(
1535 IDS_ACCESSIBLE_INCOGNITO_WINDOW_TITLE_FORMAT,
1538 return GetWindowTitle();
1541 views::View* BrowserView::GetInitiallyFocusedView() {
1545 bool BrowserView::ShouldShowWindowTitle() const {
1546 // For Ash only, app host windows do not show an icon, crbug.com/119411.
1547 // Child windows (i.e. popups) do show an icon.
1548 if (browser_->host_desktop_type() == chrome::HOST_DESKTOP_TYPE_ASH &&
1549 browser_->is_app() && browser_->app_type() == Browser::APP_TYPE_HOST)
1552 return browser_->SupportsWindowFeature(Browser::FEATURE_TITLEBAR);
1555 gfx::ImageSkia BrowserView::GetWindowAppIcon() {
1556 if (browser_->is_app()) {
1557 WebContents* contents = browser_->tab_strip_model()->GetActiveWebContents();
1558 extensions::TabHelper* extensions_tab_helper =
1559 contents ? extensions::TabHelper::FromWebContents(contents) : NULL;
1560 if (extensions_tab_helper && extensions_tab_helper->GetExtensionAppIcon())
1561 return gfx::ImageSkia::CreateFrom1xBitmap(
1562 *extensions_tab_helper->GetExtensionAppIcon());
1565 return GetWindowIcon();
1568 gfx::ImageSkia BrowserView::GetWindowIcon() {
1569 if (browser_->is_app() || browser_->is_type_popup())
1570 return browser_->GetCurrentPageIcon().AsImageSkia();
1571 return gfx::ImageSkia();
1574 bool BrowserView::ShouldShowWindowIcon() const {
1575 // For Ash only, app host windows do not show an icon, crbug.com/119411.
1576 // Child windows (i.e. popups) do show an icon.
1577 if (browser_->host_desktop_type() == chrome::HOST_DESKTOP_TYPE_ASH &&
1578 browser_->is_app() && browser_->app_type() == Browser::APP_TYPE_HOST)
1581 return browser_->SupportsWindowFeature(Browser::FEATURE_TITLEBAR);
1584 bool BrowserView::ExecuteWindowsCommand(int command_id) {
1585 // This function handles WM_SYSCOMMAND, WM_APPCOMMAND, and WM_COMMAND.
1587 if (command_id == IDC_DEBUG_FRAME_TOGGLE)
1588 GetWidget()->DebugToggleFrameType();
1590 // In Windows 8 metro mode prevent sizing and moving.
1591 if (win8::IsSingleWindowMetroMode()) {
1592 // Windows uses the 4 lower order bits of |notification_code| for type-
1593 // specific information so we must exclude this when comparing.
1594 static const int sc_mask = 0xFFF0;
1595 if (((command_id & sc_mask) == SC_MOVE) ||
1596 ((command_id & sc_mask) == SC_SIZE) ||
1597 ((command_id & sc_mask) == SC_MAXIMIZE))
1601 // Translate WM_APPCOMMAND command ids into a command id that the browser
1602 // knows how to handle.
1603 int command_id_from_app_command = GetCommandIDForAppCommandID(command_id);
1604 if (command_id_from_app_command != -1)
1605 command_id = command_id_from_app_command;
1607 return chrome::ExecuteCommand(browser_.get(), command_id);
1610 std::string BrowserView::GetWindowName() const {
1611 return chrome::GetWindowPlacementKey(browser_.get());
1614 void BrowserView::SaveWindowPlacement(const gfx::Rect& bounds,
1615 ui::WindowShowState show_state) {
1616 // If IsFullscreen() is true, we've just changed into fullscreen mode, and
1617 // we're catching the going-into-fullscreen sizing and positioning calls,
1618 // which we want to ignore.
1619 if (!ShouldSaveOrRestoreWindowPos())
1622 if (!IsFullscreen() && chrome::ShouldSaveWindowPlacement(browser_.get())) {
1623 WidgetDelegate::SaveWindowPlacement(bounds, show_state);
1624 chrome::SaveWindowPlacement(browser_.get(), bounds, show_state);
1628 bool BrowserView::GetSavedWindowPlacement(
1629 const views::Widget* widget,
1631 ui::WindowShowState* show_state) const {
1632 if (!ShouldSaveOrRestoreWindowPos())
1634 chrome::GetSavedWindowBoundsAndShowState(browser_.get(), bounds, show_state);
1636 if (browser_->is_type_popup() &&
1637 !browser_->is_app() &&
1638 !browser_->is_devtools()) {
1639 // This is non-app popup window. The value passed in |bounds| represents
1640 // two pieces of information:
1641 // - the position of the window, in screen coordinates (outer position).
1642 // - the size of the content area (inner size).
1643 // We need to use these values to determine the appropriate size and
1644 // position of the resulting window.
1645 if (IsToolbarVisible()) {
1646 // If we're showing the toolbar, we need to adjust |*bounds| to include
1647 // its desired height, since the toolbar is considered part of the
1648 // window's client area as far as GetWindowBoundsForClientBounds is
1651 bounds->height() + toolbar_->GetPreferredSize().height());
1654 gfx::Rect window_rect = frame_->non_client_view()->
1655 GetWindowBoundsForClientBounds(*bounds);
1656 window_rect.set_origin(bounds->origin());
1658 // When we are given x/y coordinates of 0 on a created popup window,
1659 // assume none were given by the window.open() command.
1660 if (window_rect.x() == 0 && window_rect.y() == 0) {
1661 gfx::Size size = window_rect.size();
1662 window_rect.set_origin(
1663 WindowSizer::GetDefaultPopupOrigin(size,
1664 browser_->host_desktop_type()));
1667 *bounds = window_rect;
1668 *show_state = ui::SHOW_STATE_NORMAL;
1671 // We return true because we can _always_ locate reasonable bounds using the
1672 // WindowSizer, and we don't want to trigger the Window's built-in "size to
1673 // default" handling because the browser window has no default preferred
1678 views::View* BrowserView::GetContentsView() {
1679 return contents_web_view_;
1682 views::ClientView* BrowserView::CreateClientView(views::Widget* widget) {
1686 void BrowserView::OnWidgetActivationChanged(views::Widget* widget,
1689 BrowserList::SetLastActive(browser_.get());
1692 void BrowserView::OnWindowBeginUserBoundsChange() {
1693 WebContents* web_contents = GetActiveWebContents();
1696 web_contents->GetRenderViewHost()->NotifyMoveOrResizeStarted();
1699 void BrowserView::OnWidgetMove() {
1700 if (!initialized_) {
1701 // Creating the widget can trigger a move. Ignore it until we've initialized
1706 // Cancel any tabstrip animations, some of them may be invalidated by the
1707 // window being repositioned.
1708 // Comment out for one cycle to see if this fixes dist tests.
1709 // tabstrip_->DestroyDragController();
1711 // status_bubble_ may be NULL if this is invoked during construction.
1712 if (status_bubble_.get())
1713 status_bubble_->Reposition();
1715 BookmarkBubbleView::Hide();
1717 // Close the omnibox popup, if any.
1718 LocationBarView* location_bar_view = GetLocationBarView();
1719 if (location_bar_view)
1720 location_bar_view->GetOmniboxView()->CloseOmniboxPopup();
1723 views::Widget* BrowserView::GetWidget() {
1724 return View::GetWidget();
1727 const views::Widget* BrowserView::GetWidget() const {
1728 return View::GetWidget();
1731 void BrowserView::GetAccessiblePanes(std::vector<views::View*>* panes) {
1732 // This should be in the order of pane traversal of the panes using F6
1733 // (Windows) or Ctrl+Back/Forward (Chrome OS). If one of these is
1734 // invisible or has no focusable children, it will be automatically
1736 panes->push_back(toolbar_);
1737 if (bookmark_bar_view_.get())
1738 panes->push_back(bookmark_bar_view_.get());
1739 if (infobar_container_)
1740 panes->push_back(infobar_container_);
1741 if (download_shelf_.get())
1742 panes->push_back(download_shelf_.get());
1743 panes->push_back(GetTabContentsContainerView());
1744 if (devtools_web_view_->visible())
1745 panes->push_back(devtools_web_view_);
1748 ///////////////////////////////////////////////////////////////////////////////
1749 // BrowserView, views::ClientView overrides:
1751 bool BrowserView::CanClose() {
1752 // You cannot close a frame for which there is an active originating drag
1754 if (tabstrip_ && !tabstrip_->IsTabStripCloseable())
1757 // Give beforeunload handlers the chance to cancel the close before we hide
1758 // the window below.
1759 if (!browser_->ShouldCloseWindow())
1762 bool fast_tab_closing_enabled =
1763 CommandLine::ForCurrentProcess()->HasSwitch(switches::kEnableFastUnload);
1765 if (!browser_->tab_strip_model()->empty()) {
1766 // Tab strip isn't empty. Hide the frame (so it appears to have closed
1767 // immediately) and close all the tabs, allowing the renderers to shut
1768 // down. When the tab strip is empty we'll be called back again.
1770 browser_->OnWindowClosing();
1771 if (fast_tab_closing_enabled)
1772 browser_->tab_strip_model()->CloseAllTabs();
1774 } else if (fast_tab_closing_enabled &&
1775 !browser_->HasCompletedUnloadProcessing()) {
1776 // The browser needs to finish running unload handlers.
1777 // Hide the frame (so it appears to have closed immediately), and
1778 // the browser will call us back again when it is ready to close.
1783 // Empty TabStripModel, it's now safe to allow the Window to be closed.
1784 content::NotificationService::current()->Notify(
1785 chrome::NOTIFICATION_WINDOW_CLOSED,
1786 content::Source<gfx::NativeWindow>(frame_->GetNativeWindow()),
1787 content::NotificationService::NoDetails());
1791 int BrowserView::NonClientHitTest(const gfx::Point& point) {
1792 return GetBrowserViewLayout()->NonClientHitTest(point);
1795 gfx::Size BrowserView::GetMinimumSize() {
1796 return GetBrowserViewLayout()->GetMinimumSize();
1799 ///////////////////////////////////////////////////////////////////////////////
1800 // BrowserView, views::View overrides:
1802 const char* BrowserView::GetClassName() const {
1803 return kViewClassName;
1806 void BrowserView::Layout() {
1807 if (!initialized_ || in_process_fullscreen_)
1810 views::View::Layout();
1812 // TODO(jamescook): Why was this in the middle of layout code?
1813 toolbar_->location_bar()->omnibox_view()->SetFocusable(IsToolbarVisible());
1816 void BrowserView::PaintChildren(gfx::Canvas* canvas) {
1817 // Paint the |infobar_container_| last so that it may paint its
1818 // overlapping tabs.
1819 for (int i = 0; i < child_count(); ++i) {
1820 View* child = child_at(i);
1821 if (child != infobar_container_ && !child->layer())
1822 child->Paint(canvas);
1825 infobar_container_->Paint(canvas);
1828 void BrowserView::ViewHierarchyChanged(
1829 const ViewHierarchyChangedDetails& details) {
1830 if (!initialized_ && details.is_add && details.child == this && GetWidget()) {
1832 initialized_ = true;
1836 void BrowserView::ChildPreferredSizeChanged(View* child) {
1840 void BrowserView::GetAccessibleState(ui::AccessibleViewState* state) {
1841 state->role = ui::AccessibilityTypes::ROLE_CLIENT;
1844 ///////////////////////////////////////////////////////////////////////////////
1845 // BrowserView, ui::AcceleratorTarget overrides:
1847 bool BrowserView::AcceleratorPressed(const ui::Accelerator& accelerator) {
1848 #if defined(OS_CHROMEOS)
1849 // If accessibility is enabled, stop speech and return false so that key
1850 // combinations involving Search can be used for extra accessibility
1852 if (accelerator.key_code() == ui::VKEY_LWIN &&
1853 g_browser_process->local_state()->GetBoolean(
1854 prefs::kSpokenFeedbackEnabled)) {
1855 TtsController::GetInstance()->Stop();
1860 std::map<ui::Accelerator, int>::const_iterator iter =
1861 accelerator_table_.find(accelerator);
1862 DCHECK(iter != accelerator_table_.end());
1863 int command_id = iter->second;
1865 chrome::BrowserCommandController* controller = browser_->command_controller();
1866 if (!controller->block_command_execution())
1867 UpdateAcceleratorMetrics(accelerator, command_id);
1868 return chrome::ExecuteCommand(browser_.get(), command_id);
1871 ///////////////////////////////////////////////////////////////////////////////
1872 // BrowserView, OmniboxPopupModelObserver overrides:
1873 void BrowserView::OnOmniboxPopupShownOrHidden() {
1874 infobar_container_->SetMaxTopArrowHeight(GetMaxTopInfoBarArrowHeight());
1877 ///////////////////////////////////////////////////////////////////////////////
1878 // BrowserView, InfoBarContainer::Delegate overrides:
1880 SkColor BrowserView::GetInfoBarSeparatorColor() const {
1881 // NOTE: Keep this in sync with ToolbarView::OnPaint()!
1882 return (IsTabStripVisible() || !frame_->ShouldUseNativeFrame()) ?
1883 ThemeProperties::GetDefaultColor(
1884 ThemeProperties::COLOR_TOOLBAR_SEPARATOR) :
1888 void BrowserView::InfoBarContainerStateChanged(bool is_animating) {
1889 ToolbarSizeChanged(is_animating);
1892 bool BrowserView::DrawInfoBarArrows(int* x) const {
1894 gfx::Point anchor(toolbar_->location_bar()->GetLocationBarAnchorPoint());
1895 ConvertPointToTarget(toolbar_->location_bar(), this, &anchor);
1901 void BrowserView::OnSysColorChange() {
1902 chrome::MaybeShowInvertBubbleView(browser_.get(), contents_container_);
1905 void BrowserView::InitViews() {
1906 GetWidget()->AddObserver(this);
1908 // Stow a pointer to this object onto the window handle so that we can get at
1909 // it later when all we have is a native view.
1910 GetWidget()->SetNativeWindowProperty(kBrowserViewKey, this);
1912 // Stow a pointer to the browser's profile onto the window handle so that we
1913 // can get it later when all we have is a native view.
1914 GetWidget()->SetNativeWindowProperty(Profile::kProfileKey,
1915 browser_->profile());
1917 // Start a hung plugin window detector for this browser object (as long as
1918 // hang detection is not disabled).
1919 if (!CommandLine::ForCurrentProcess()->HasSwitch(
1920 switches::kDisableHangMonitor)) {
1926 infobar_container_ = new InfoBarContainerView(this);
1927 AddChildView(infobar_container_);
1929 contents_web_view_ = new ContentsWebView(browser_->profile());
1930 contents_web_view_->set_id(VIEW_ID_TAB_CONTAINER);
1931 contents_web_view_->SetEmbedFullscreenWidgetMode(
1932 implicit_cast<content::WebContentsDelegate*>(browser_.get())->
1933 EmbedsFullscreenWidget());
1935 devtools_web_view_ = new views::WebView(browser_->profile());
1936 devtools_web_view_->set_id(VIEW_ID_DEV_TOOLS_DOCKED);
1937 devtools_web_view_->SetVisible(false);
1939 contents_container_ = new views::View();
1940 contents_container_->set_background(views::Background::CreateSolidBackground(
1941 ThemeProperties::GetDefaultColor(
1942 ThemeProperties::COLOR_CONTROL_BACKGROUND)));
1943 contents_container_->AddChildView(devtools_web_view_);
1944 contents_container_->AddChildView(contents_web_view_);
1945 contents_container_->SetLayoutManager(new ContentsLayoutManager(
1946 devtools_web_view_, contents_web_view_));
1947 AddChildView(contents_container_);
1948 set_contents_view(contents_container_);
1952 // Top container holds tab strip and toolbar and lives at the front of the
1954 top_container_ = new TopContainerView(this);
1955 AddChildView(top_container_);
1957 // TabStrip takes ownership of the controller.
1958 BrowserTabStripController* tabstrip_controller =
1959 new BrowserTabStripController(browser_.get(),
1960 browser_->tab_strip_model());
1961 tabstrip_ = new TabStrip(tabstrip_controller);
1962 top_container_->AddChildView(tabstrip_);
1963 tabstrip_controller->InitFromModel(tabstrip_);
1965 toolbar_ = new ToolbarView(browser_.get());
1966 top_container_->AddChildView(toolbar_);
1969 // Create do-nothing view for the sake of controlling the z-order of the find
1971 find_bar_host_view_ = new View();
1972 AddChildView(find_bar_host_view_);
1974 if (window_switcher_button_)
1975 AddChildView(window_switcher_button_);
1977 immersive_mode_controller_->Init(this);
1979 BrowserViewLayout* browser_view_layout = new BrowserViewLayout;
1980 browser_view_layout->Init(new BrowserViewLayoutDelegateImpl(this),
1987 contents_container_,
1988 GetContentsLayoutManager(),
1989 immersive_mode_controller_.get());
1990 SetLayoutManager(browser_view_layout);
1993 // Create a custom JumpList and add it to an observer of TabRestoreService
1994 // so we can update the custom JumpList when a tab is added or removed.
1995 if (JumpList::Enabled()) {
1996 load_complete_listener_.reset(new LoadCompleteListener(this));
2000 GetLocationBar()->GetOmniboxView()->model()->popup_model()->AddObserver(this);
2003 void BrowserView::LoadingAnimationCallback() {
2004 base::TimeTicks now = base::TimeTicks::Now();
2005 if (!last_animation_time_.is_null()) {
2006 UMA_HISTOGRAM_TIMES(
2007 "Tabs.LoadingAnimationTime",
2008 now - last_animation_time_);
2010 last_animation_time_ = now;
2011 if (browser_->is_type_tabbed()) {
2012 // Loading animations are shown in the tab for tabbed windows. We check the
2013 // browser type instead of calling IsTabStripVisible() because the latter
2014 // will return false for fullscreen windows, but we still need to update
2015 // their animations (so that when they come out of fullscreen mode they'll
2017 tabstrip_->UpdateLoadingAnimations();
2018 } else if (ShouldShowWindowIcon()) {
2019 // ... or in the window icon area for popups and app windows.
2020 WebContents* web_contents =
2021 browser_->tab_strip_model()->GetActiveWebContents();
2022 // GetActiveWebContents can return NULL for example under Purify when
2023 // the animations are running slowly and this function is called on a timer
2024 // through LoadingAnimationCallback.
2025 frame_->UpdateThrobber(web_contents && web_contents->IsLoading());
2029 void BrowserView::OnLoadCompleted() {
2032 jumplist_ = new JumpList();
2033 jumplist_->AddObserver(browser_->profile());
2037 BrowserViewLayout* BrowserView::GetBrowserViewLayout() const {
2038 return static_cast<BrowserViewLayout*>(GetLayoutManager());
2041 ContentsLayoutManager* BrowserView::GetContentsLayoutManager() const {
2042 return static_cast<ContentsLayoutManager*>(
2043 contents_container_->GetLayoutManager());
2046 bool BrowserView::MaybeShowBookmarkBar(WebContents* contents) {
2047 bool show_bookmark_bar = contents &&
2048 browser_->SupportsWindowFeature(Browser::FEATURE_BOOKMARKBAR);
2049 if (!show_bookmark_bar && !bookmark_bar_view_.get())
2051 if (!bookmark_bar_view_.get()) {
2052 bookmark_bar_view_.reset(new BookmarkBarView(browser_.get(), this));
2053 bookmark_bar_view_->set_owned_by_client();
2054 bookmark_bar_view_->set_background(
2055 new BookmarkExtensionBackground(this,
2056 bookmark_bar_view_.get(),
2058 bookmark_bar_view_->SetBookmarkBarState(
2059 browser_->bookmark_bar_state(),
2060 BookmarkBar::DONT_ANIMATE_STATE_CHANGE);
2061 GetBrowserViewLayout()->set_bookmark_bar(bookmark_bar_view_.get());
2063 bookmark_bar_view_->SetVisible(show_bookmark_bar);
2064 bookmark_bar_view_->SetPageNavigator(contents);
2066 // Update parenting for the bookmark bar. This may detach it from all views.
2067 bool needs_layout = false;
2068 views::View* new_parent = NULL;
2069 if (show_bookmark_bar) {
2070 if (bookmark_bar_view_->IsDetached())
2073 new_parent = top_container_;
2075 if (new_parent != bookmark_bar_view_->parent()) {
2076 SetBookmarkBarParent(new_parent);
2077 needs_layout = true;
2080 // Check for updates to the desired size.
2081 if (bookmark_bar_view_->GetPreferredSize().height() !=
2082 bookmark_bar_view_->height())
2083 needs_layout = true;
2085 return needs_layout;
2088 void BrowserView::SetBookmarkBarParent(views::View* new_parent) {
2089 if (new_parent == this) {
2090 // Add it underneath |top_container_| or at the end if top container isn't
2092 int top_container_index = GetIndexOf(top_container_);
2093 if (top_container_index >= 0)
2094 AddChildViewAt(bookmark_bar_view_.get(), top_container_index);
2096 AddChildView(bookmark_bar_view_.get());
2097 } else if (new_parent) {
2098 // No special stacking is required for other parents.
2099 new_parent->AddChildView(bookmark_bar_view_.get());
2101 // Bookmark bar is being detached from all views because it is hidden.
2102 bookmark_bar_view_->parent()->RemoveChildView(bookmark_bar_view_.get());
2106 bool BrowserView::MaybeShowInfoBar(WebContents* contents) {
2107 // TODO(beng): Remove this function once the interface between
2108 // InfoBarContainer, DownloadShelfView and WebContents and this
2109 // view is sorted out.
2113 void BrowserView::UpdateDevToolsForContents(
2114 WebContents* web_contents, bool update_devtools_web_contents) {
2115 DevToolsWindow* new_devtools_window = web_contents ?
2116 DevToolsWindow::GetDockedInstanceForInspectedTab(web_contents) : NULL;
2118 // Replace devtools WebContents.
2119 WebContents* new_contents = new_devtools_window ?
2120 new_devtools_window->web_contents() : NULL;
2121 if (devtools_web_view_->web_contents() != new_contents &&
2122 update_devtools_web_contents) {
2123 devtools_web_view_->SetWebContents(new_contents);
2126 if (!devtools_window_ && new_devtools_window &&
2127 !devtools_focus_tracker_.get()) {
2128 // Install devtools focus tracker when dev tools window is shown for the
2130 devtools_focus_tracker_.reset(
2131 new views::ExternalFocusTracker(devtools_web_view_,
2132 GetFocusManager()));
2135 // Restore focus to the last focused view when hiding devtools window.
2136 if (devtools_window_ && !new_devtools_window &&
2137 devtools_focus_tracker_.get()) {
2138 devtools_focus_tracker_->FocusLastFocusedExternalView();
2139 devtools_focus_tracker_.reset();
2142 devtools_window_ = new_devtools_window;
2143 if (devtools_window_) {
2144 devtools_web_view_->SetPreferredSize(devtools_window_->GetMinimumSize());
2145 devtools_web_view_->SetVisible(true);
2146 GetContentsLayoutManager()->SetContentsViewInsets(
2147 devtools_window_->GetContentsInsets());
2149 devtools_web_view_->SetVisible(false);
2150 GetContentsLayoutManager()->SetContentsViewInsets(gfx::Insets());
2152 contents_container_->Layout();
2155 void BrowserView::UpdateUIForContents(WebContents* contents) {
2156 bool needs_layout = MaybeShowBookmarkBar(contents);
2157 // TODO(jamescook): This function always returns true. Remove it and figure
2158 // out when layout is actually required.
2159 needs_layout |= MaybeShowInfoBar(contents);
2164 void BrowserView::ProcessFullscreen(bool fullscreen,
2165 FullscreenType type,
2167 FullscreenExitBubbleType bubble_type) {
2168 if (in_process_fullscreen_)
2170 in_process_fullscreen_ = true;
2172 // Reduce jankiness during the following position changes by:
2173 // * Hiding the window until it's in the final position
2174 // * Ignoring all intervening Layout() calls, which resize the webpage and
2175 // thus are slow and look ugly (enforced via |in_process_fullscreen_|).
2176 LocationBarView* location_bar = GetLocationBarView();
2178 if (type == FOR_METRO || !fullscreen) {
2179 // Hide the fullscreen bubble as soon as possible, since the mode toggle can
2180 // take enough time for the user to notice.
2181 fullscreen_bubble_.reset();
2185 // Move focus out of the location bar if necessary.
2186 views::FocusManager* focus_manager = GetFocusManager();
2187 DCHECK(focus_manager);
2188 // Look for focus in the location bar itself or any child view.
2189 if (location_bar->Contains(focus_manager->GetFocusedView()))
2190 focus_manager->ClearFocus();
2192 #if defined(OS_WIN) && !defined(USE_AURA)
2193 views::ScopedFullscreenVisibility visibility(frame_->GetNativeView());
2196 if (type == FOR_METRO) {
2197 #if defined(OS_WIN) && !defined(USE_AURA)
2198 // Enter metro snap mode.
2199 static_cast<views::NativeWidgetWin*>(
2200 frame_->native_widget())->SetMetroSnapFullscreen(fullscreen);
2203 // Toggle fullscreen mode.
2204 frame_->SetFullscreen(fullscreen);
2207 // Enable immersive before the browser refreshes its list of enabled commands.
2208 if (ShouldUseImmersiveFullscreenForUrl(url))
2209 immersive_mode_controller_->SetEnabled(fullscreen);
2211 browser_->WindowFullscreenStateChanged();
2213 if (fullscreen && !chrome::IsRunningInAppMode() && type != FOR_METRO)
2214 UpdateFullscreenExitBubbleContent(url, bubble_type);
2216 // Undo our anti-jankiness hacks and force a re-layout. We also need to
2217 // recompute the height of the infobar top arrow because toggling in and out
2218 // of fullscreen changes it. Calling ToolbarSizeChanged() will do both these
2219 // things since it computes the arrow height directly and forces a layout
2220 // indirectly via UpdateUIForContents(). Reset |in_process_fullscreen_| in
2221 // order to let the layout occur.
2222 in_process_fullscreen_ = false;
2223 ToolbarSizeChanged(false);
2226 bool BrowserView::ShouldUseImmersiveFullscreenForUrl(const GURL& url) const {
2227 #if defined(OS_CHROMEOS)
2228 // Kiosk mode needs the whole screen.
2229 if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kKioskMode))
2231 bool is_browser_fullscreen = url.is_empty();
2232 if (ash::switches::UseImmersiveFullscreenForAllWindows())
2233 return is_browser_fullscreen;
2235 return is_browser_fullscreen && IsBrowserTypeNormal();
2241 void BrowserView::LoadAccelerators() {
2242 views::FocusManager* focus_manager = GetFocusManager();
2243 DCHECK(focus_manager);
2245 // Let's fill our own accelerator table.
2246 const bool is_app_mode = chrome::IsRunningInForcedAppMode();
2247 const std::vector<chrome::AcceleratorMapping> accelerator_list(
2248 chrome::GetAcceleratorList());
2249 for (std::vector<chrome::AcceleratorMapping>::const_iterator it =
2250 accelerator_list.begin(); it != accelerator_list.end(); ++it) {
2251 // In app mode, only allow accelerators of white listed commands to pass
2253 if (is_app_mode && !chrome::IsCommandAllowedInAppMode(it->command_id))
2256 ui::Accelerator accelerator(it->keycode, it->modifiers);
2257 accelerator_table_[accelerator] = it->command_id;
2259 // Also register with the focus manager.
2260 focus_manager->RegisterAccelerator(
2261 accelerator, ui::AcceleratorManager::kNormalPriority, this);
2265 int BrowserView::GetCommandIDForAppCommandID(int app_command_id) const {
2267 switch (app_command_id) {
2268 // NOTE: The order here matches the APPCOMMAND declaration order in the
2270 case APPCOMMAND_BROWSER_BACKWARD: return IDC_BACK;
2271 case APPCOMMAND_BROWSER_FORWARD: return IDC_FORWARD;
2272 case APPCOMMAND_BROWSER_REFRESH: return IDC_RELOAD;
2273 case APPCOMMAND_BROWSER_HOME: return IDC_HOME;
2274 case APPCOMMAND_BROWSER_STOP: return IDC_STOP;
2275 case APPCOMMAND_BROWSER_SEARCH: return IDC_FOCUS_SEARCH;
2276 case APPCOMMAND_HELP: return IDC_HELP_PAGE_VIA_KEYBOARD;
2277 case APPCOMMAND_NEW: return IDC_NEW_TAB;
2278 case APPCOMMAND_OPEN: return IDC_OPEN_FILE;
2279 case APPCOMMAND_CLOSE: return IDC_CLOSE_TAB;
2280 case APPCOMMAND_SAVE: return IDC_SAVE_PAGE;
2281 case APPCOMMAND_PRINT: return IDC_PRINT;
2282 case APPCOMMAND_COPY: return IDC_COPY;
2283 case APPCOMMAND_CUT: return IDC_CUT;
2284 case APPCOMMAND_PASTE: return IDC_PASTE;
2286 // TODO(pkasting): http://b/1113069 Handle these.
2287 case APPCOMMAND_UNDO:
2288 case APPCOMMAND_REDO:
2289 case APPCOMMAND_SPELL_CHECK:
2293 // App commands are Windows-specific so there's nothing to do here.
2298 void BrowserView::InitHangMonitor() {
2300 PrefService* pref_service = g_browser_process->local_state();
2304 int plugin_message_response_timeout =
2305 pref_service->GetInteger(prefs::kPluginMessageResponseTimeout);
2306 int hung_plugin_detect_freq =
2307 pref_service->GetInteger(prefs::kHungPluginDetectFrequency);
2308 #if defined(USE_AURA)
2309 HWND window = GetWidget()->GetNativeView()->GetDispatcher()->host()->
2310 GetAcceleratedWidget();
2312 HWND window = GetWidget()->GetNativeView();
2314 if ((hung_plugin_detect_freq > 0) &&
2315 hung_window_detector_.Initialize(window,
2316 plugin_message_response_timeout)) {
2317 ticker_.set_tick_interval(hung_plugin_detect_freq);
2318 ticker_.RegisterTickHandler(&hung_window_detector_);
2321 pref_service->SetInteger(prefs::kPluginMessageResponseTimeout,
2322 plugin_message_response_timeout);
2323 pref_service->SetInteger(prefs::kHungPluginDetectFrequency,
2324 hung_plugin_detect_freq);
2329 void BrowserView::UpdateAcceleratorMetrics(const ui::Accelerator& accelerator,
2331 const ui::KeyboardCode key_code = accelerator.key_code();
2332 if (command_id == IDC_HELP_PAGE_VIA_KEYBOARD && key_code == ui::VKEY_F1)
2333 content::RecordAction(UserMetricsAction("ShowHelpTabViaF1"));
2335 if (command_id == IDC_BOOKMARK_PAGE)
2336 UMA_HISTOGRAM_ENUMERATION("Bookmarks.EntryPoint",
2337 BOOKMARK_ENTRY_POINT_ACCELERATOR,
2338 BOOKMARK_ENTRY_POINT_LIMIT);
2340 #if defined(OS_CHROMEOS)
2341 // Collect information about the relative popularity of various accelerators
2343 switch (command_id) {
2345 if (key_code == ui::VKEY_BACK)
2346 content::RecordAction(UserMetricsAction("Accel_Back_Backspace"));
2347 else if (key_code == ui::VKEY_BROWSER_BACK)
2348 content::RecordAction(UserMetricsAction("Accel_Back_F1"));
2349 else if (key_code == ui::VKEY_LEFT)
2350 content::RecordAction(UserMetricsAction("Accel_Back_Left"));
2353 if (key_code == ui::VKEY_BACK)
2354 content::RecordAction(UserMetricsAction("Accel_Forward_Backspace"));
2355 else if (key_code == ui::VKEY_BROWSER_FORWARD)
2356 content::RecordAction(UserMetricsAction("Accel_Forward_F2"));
2357 else if (key_code == ui::VKEY_RIGHT)
2358 content::RecordAction(UserMetricsAction("Accel_Forward_Right"));
2361 case IDC_RELOAD_IGNORING_CACHE:
2362 if (key_code == ui::VKEY_R)
2363 content::RecordAction(UserMetricsAction("Accel_Reload_R"));
2364 else if (key_code == ui::VKEY_BROWSER_REFRESH)
2365 content::RecordAction(UserMetricsAction("Accel_Reload_F3"));
2367 case IDC_FOCUS_LOCATION:
2368 if (key_code == ui::VKEY_D)
2369 content::RecordAction(UserMetricsAction("Accel_FocusLocation_D"));
2370 else if (key_code == ui::VKEY_L)
2371 content::RecordAction(UserMetricsAction("Accel_FocusLocation_L"));
2373 case IDC_FOCUS_SEARCH:
2374 if (key_code == ui::VKEY_E)
2375 content::RecordAction(UserMetricsAction("Accel_FocusSearch_E"));
2376 else if (key_code == ui::VKEY_K)
2377 content::RecordAction(UserMetricsAction("Accel_FocusSearch_K"));
2387 BrowserWindow* BrowserWindow::CreateBrowserWindow(Browser* browser) {
2388 // Create the view and the frame. The frame will attach itself via the view
2389 // so we don't need to do anything with the pointer.
2390 BrowserView* view = new BrowserView();
2391 view->Init(browser);
2392 (new BrowserFrame(view))->InitBrowserFrame();
2393 view->GetWidget()->non_client_view()->SetAccessibleName(
2394 l10n_util::GetStringUTF16(IDS_PRODUCT_NAME));
2399 chrome::HostDesktopType BrowserWindow::AdjustHostDesktopType(
2400 chrome::HostDesktopType desktop_type) {
2401 return NativeBrowserFrameFactory::AdjustHostDesktopType(desktop_type);
2404 void BrowserView::ShowAvatarBubble(WebContents* web_contents,
2405 const gfx::Rect& rect) {
2406 gfx::Point origin(rect.origin());
2407 views::View::ConvertPointToScreen(GetTabContentsContainerView(), &origin);
2408 gfx::Rect bounds(origin, rect.size());
2410 AvatarMenuBubbleView::ShowBubble(this, views::BubbleBorder::TOP_RIGHT,
2411 views::BubbleBorder::ALIGN_EDGE_TO_ANCHOR_EDGE, bounds, browser_.get());
2414 void BrowserView::ShowAvatarBubbleFromAvatarButton() {
2415 if (switches::IsNewProfileManagement()) {
2416 NewAvatarButton* button = frame_->GetNewAvatarMenuButton();
2419 views::View::ConvertPointToScreen(button, &origin);
2420 gfx::Rect bounds(origin, size());
2422 ProfileChooserView::ShowBubble(
2423 button, views::BubbleBorder::TOP_RIGHT,
2424 views::BubbleBorder::ALIGN_EDGE_TO_ANCHOR_EDGE, bounds, browser());
2427 AvatarMenuButton* button = frame_->GetAvatarMenuButton();
2429 button->ShowAvatarBubble();
2433 void BrowserView::ShowPasswordGenerationBubble(
2434 const gfx::Rect& rect,
2435 const autofill::PasswordForm& form,
2436 autofill::PasswordGenerator* password_generator) {
2437 // Create a rect in the content bounds that the bubble will point to.
2438 gfx::Point origin(rect.origin());
2439 views::View::ConvertPointToScreen(GetTabContentsContainerView(), &origin);
2440 gfx::Rect bounds(origin, rect.size());
2442 // Create the bubble.
2443 WebContents* web_contents = GetActiveWebContents();
2447 PasswordGenerationBubbleView* bubble =
2448 new PasswordGenerationBubbleView(
2452 web_contents->GetRenderViewHost(),
2453 PasswordManager::FromWebContents(web_contents),
2456 GetWidget()->GetThemeProvider());
2458 views::BubbleDelegateView::CreateBubble(bubble);
2459 bubble->SetAlignment(views::BubbleBorder::ALIGN_ARROW_TO_MID_ANCHOR);
2460 bubble->GetWidget()->Show();
2463 void BrowserView::OverscrollUpdate(int delta_y) {
2464 if (scroll_end_effect_controller_)
2465 scroll_end_effect_controller_->OverscrollUpdate(delta_y);
2468 int BrowserView::GetRenderViewHeightInsetWithDetachedBookmarkBar() {
2469 if (browser_->bookmark_bar_state() != BookmarkBar::DETACHED ||
2470 !bookmark_bar_view_.get() || !bookmark_bar_view_->IsDetached()) {
2473 // Don't use bookmark_bar_view_->height() which won't be the final height if
2474 // the bookmark bar is animating.
2475 return chrome::kNTPBookmarkBarHeight -
2476 bookmark_bar_view_->GetFullyDetachedToolbarOverlap();
2479 void BrowserView::DoCutCopyPaste(void (content::RenderWidgetHost::*method)(),
2481 WebContents* contents = browser_->tab_strip_model()->GetActiveWebContents();
2484 if (DoCutCopyPasteForWebContents(contents, method))
2487 DevToolsWindow* devtools_window =
2488 DevToolsWindow::GetDockedInstanceForInspectedTab(contents);
2489 if (devtools_window &&
2490 DoCutCopyPasteForWebContents(devtools_window->web_contents(), method)) {
2494 views::FocusManager* focus_manager = GetFocusManager();
2495 views::View* focused = focus_manager->GetFocusedView();
2497 (!strcmp(focused->GetClassName(), views::Textfield::kViewClassName) ||
2498 !strcmp(focused->GetClassName(), OmniboxViewViews::kViewClassName))) {
2499 views::Textfield* textfield = static_cast<views::Textfield*>(focused);
2500 textfield->ExecuteCommand(command_id);
2504 bool BrowserView::DoCutCopyPasteForWebContents(
2505 WebContents* contents,
2506 void (content::RenderWidgetHost::*method)()) {
2507 gfx::NativeView native_view = contents->GetView()->GetContentNativeView();
2510 #if defined(USE_AURA)
2511 if (native_view->HasFocus()) {
2512 #elif defined(OS_WIN)
2513 if (native_view == ::GetFocus()) {
2515 (contents->GetRenderViewHost()->*method)();
2522 void BrowserView::ActivateAppModalDialog() const {
2523 // If another browser is app modal, flash and activate the modal browser.
2524 AppModalDialog* active_dialog =
2525 AppModalDialogQueue::GetInstance()->active_dialog();
2529 Browser* modal_browser =
2530 chrome::FindBrowserWithWebContents(active_dialog->web_contents());
2531 if (modal_browser && (browser_ != modal_browser)) {
2532 modal_browser->window()->FlashFrame(true);
2533 modal_browser->window()->Activate();
2536 AppModalDialogQueue::GetInstance()->ActivateModalDialog();
2539 int BrowserView::GetMaxTopInfoBarArrowHeight() {
2540 int top_arrow_height = 0;
2541 // Only show the arrows when not in fullscreen and when there's no omnibox
2543 if (!IsFullscreen() &&
2544 !GetLocationBar()->GetOmniboxView()->model()->popup_model()->IsOpen()) {
2545 gfx::Point icon_bottom(
2546 toolbar_->location_bar()->GetLocationBarAnchorPoint());
2547 ConvertPointToTarget(toolbar_->location_bar(), this, &icon_bottom);
2548 gfx::Point infobar_top(0, infobar_container_->GetVerticalOverlap(NULL));
2549 ConvertPointToTarget(infobar_container_, this, &infobar_top);
2550 top_arrow_height = infobar_top.y() - icon_bottom.y();
2552 return top_arrow_height;