[Metrics] Make MetricsStateManager take a callback param to check if UMA is enabled.
[chromium-blink-merge.git] / chrome / browser / ui / views / frame / browser_view.cc
bloba9a14e0968efcc29983d67b7021fd42e5f7cdcd4
1 // Copyright 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "chrome/browser/ui/views/frame/browser_view.h"
7 #include <algorithm>
9 #include "base/auto_reset.h"
10 #include "base/command_line.h"
11 #include "base/i18n/rtl.h"
12 #include "base/memory/scoped_ptr.h"
13 #include "base/metrics/histogram.h"
14 #include "base/prefs/pref_service.h"
15 #include "base/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/chrome_password_manager_client.h"
26 #include "chrome/browser/profiles/avatar_menu.h"
27 #include "chrome/browser/profiles/profile.h"
28 #include "chrome/browser/profiles/profile_avatar_icon_util.h"
29 #include "chrome/browser/profiles/profile_info_cache.h"
30 #include "chrome/browser/profiles/profile_manager.h"
31 #include "chrome/browser/profiles/profiles_state.h"
32 #include "chrome/browser/search/search.h"
33 #include "chrome/browser/sessions/tab_restore_service.h"
34 #include "chrome/browser/sessions/tab_restore_service_factory.h"
35 #include "chrome/browser/speech/tts_controller.h"
36 #include "chrome/browser/themes/theme_properties.h"
37 #include "chrome/browser/themes/theme_service_factory.h"
38 #include "chrome/browser/translate/translate_tab_helper.h"
39 #include "chrome/browser/ui/app_modal_dialogs/app_modal_dialog.h"
40 #include "chrome/browser/ui/app_modal_dialogs/app_modal_dialog_queue.h"
41 #include "chrome/browser/ui/bookmarks/bookmark_bar_constants.h"
42 #include "chrome/browser/ui/bookmarks/bookmark_bubble_delegate.h"
43 #include "chrome/browser/ui/bookmarks/bookmark_bubble_sign_in_delegate.h"
44 #include "chrome/browser/ui/browser.h"
45 #include "chrome/browser/ui/browser_command_controller.h"
46 #include "chrome/browser/ui/browser_commands.h"
47 #include "chrome/browser/ui/browser_dialogs.h"
48 #include "chrome/browser/ui/browser_finder.h"
49 #include "chrome/browser/ui/browser_list.h"
50 #include "chrome/browser/ui/browser_window_state.h"
51 #include "chrome/browser/ui/ntp_background_util.h"
52 #include "chrome/browser/ui/omnibox/omnibox_popup_model.h"
53 #include "chrome/browser/ui/omnibox/omnibox_popup_view.h"
54 #include "chrome/browser/ui/omnibox/omnibox_view.h"
55 #include "chrome/browser/ui/search/search_delegate.h"
56 #include "chrome/browser/ui/search/search_model.h"
57 #include "chrome/browser/ui/search/search_ui.h"
58 #include "chrome/browser/ui/tabs/tab_menu_model.h"
59 #include "chrome/browser/ui/tabs/tab_strip_model.h"
60 #include "chrome/browser/ui/view_ids.h"
61 #include "chrome/browser/ui/views/accelerator_table.h"
62 #include "chrome/browser/ui/views/accessibility/invert_bubble_view.h"
63 #include "chrome/browser/ui/views/bookmarks/bookmark_bar_view.h"
64 #include "chrome/browser/ui/views/bookmarks/bookmark_bubble_view.h"
65 #include "chrome/browser/ui/views/browser_dialogs.h"
66 #include "chrome/browser/ui/views/download/download_in_progress_dialog_view.h"
67 #include "chrome/browser/ui/views/download/download_shelf_view.h"
68 #include "chrome/browser/ui/views/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/native_browser_frame_factory.h"
74 #include "chrome/browser/ui/views/frame/top_container_view.h"
75 #include "chrome/browser/ui/views/frame/web_contents_close_handler.h"
76 #include "chrome/browser/ui/views/fullscreen_exit_bubble_views.h"
77 #include "chrome/browser/ui/views/infobars/infobar_container_view.h"
78 #include "chrome/browser/ui/views/location_bar/location_bar_view.h"
79 #include "chrome/browser/ui/views/location_bar/location_icon_view.h"
80 #include "chrome/browser/ui/views/omnibox/omnibox_view_views.h"
81 #include "chrome/browser/ui/views/password_generation_bubble_view.h"
82 #include "chrome/browser/ui/views/profiles/avatar_menu_bubble_view.h"
83 #include "chrome/browser/ui/views/profiles/avatar_menu_button.h"
84 #include "chrome/browser/ui/views/profiles/profile_chooser_view.h"
85 #include "chrome/browser/ui/views/settings_api_bubble_helper_views.h"
86 #include "chrome/browser/ui/views/status_bubble_views.h"
87 #include "chrome/browser/ui/views/tabs/browser_tab_strip_controller.h"
88 #include "chrome/browser/ui/views/tabs/tab.h"
89 #include "chrome/browser/ui/views/tabs/tab_strip.h"
90 #include "chrome/browser/ui/views/toolbar/reload_button.h"
91 #include "chrome/browser/ui/views/toolbar/toolbar_view.h"
92 #include "chrome/browser/ui/views/translate/translate_bubble_view.h"
93 #include "chrome/browser/ui/views/update_recommended_message_box.h"
94 #include "chrome/browser/ui/views/website_settings/permissions_bubble_view.h"
95 #include "chrome/browser/ui/views/website_settings/website_settings_popup_view.h"
96 #include "chrome/browser/ui/website_settings/permission_bubble_manager.h"
97 #include "chrome/browser/ui/window_sizer/window_sizer.h"
98 #include "chrome/common/chrome_switches.h"
99 #include "chrome/common/pref_names.h"
100 #include "chrome/common/url_constants.h"
101 #include "components/password_manager/core/browser/password_manager.h"
102 #include "components/signin/core/common/profile_management_switches.h"
103 #include "content/public/browser/download_manager.h"
104 #include "content/public/browser/native_web_keyboard_event.h"
105 #include "content/public/browser/notification_service.h"
106 #include "content/public/browser/render_frame_host.h"
107 #include "content/public/browser/render_view_host.h"
108 #include "content/public/browser/user_metrics.h"
109 #include "content/public/browser/web_contents.h"
110 #include "content/public/common/content_switches.h"
111 #include "grit/chromium_strings.h"
112 #include "grit/generated_resources.h"
113 #include "grit/locale_settings.h"
114 #include "grit/theme_resources.h"
115 #include "grit/ui_resources.h"
116 #include "grit/ui_strings.h"
117 #include "grit/webkit_resources.h"
118 #include "ui/accessibility/ax_view_state.h"
119 #include "ui/aura/client/window_tree_client.h"
120 #include "ui/aura/window.h"
121 #include "ui/aura/window_tree_host.h"
122 #include "ui/base/accelerators/accelerator.h"
123 #include "ui/base/hit_test.h"
124 #include "ui/base/l10n/l10n_util.h"
125 #include "ui/base/resource/resource_bundle.h"
126 #include "ui/base/theme_provider.h"
127 #include "ui/events/event_utils.h"
128 #include "ui/gfx/canvas.h"
129 #include "ui/gfx/color_utils.h"
130 #include "ui/gfx/rect_conversions.h"
131 #include "ui/gfx/screen.h"
132 #include "ui/views/controls/button/menu_button.h"
133 #include "ui/views/controls/textfield/textfield.h"
134 #include "ui/views/controls/webview/webview.h"
135 #include "ui/views/focus/external_focus_tracker.h"
136 #include "ui/views/focus/view_storage.h"
137 #include "ui/views/layout/grid_layout.h"
138 #include "ui/views/widget/native_widget.h"
139 #include "ui/views/widget/root_view.h"
140 #include "ui/views/widget/widget.h"
141 #include "ui/views/window/dialog_delegate.h"
143 #if defined(OS_WIN)
144 #include "base/win/windows_version.h"
145 #include "chrome/browser/jumplist_win.h"
146 #include "ui/views/win/scoped_fullscreen_visibility.h"
147 #endif
149 #if defined(ENABLE_ONE_CLICK_SIGNIN)
150 #include "chrome/browser/ui/sync/one_click_signin_bubble_delegate.h"
151 #include "chrome/browser/ui/sync/one_click_signin_bubble_links_delegate.h"
152 #include "chrome/browser/ui/views/sync/one_click_signin_bubble_view.h"
153 #endif
155 #if defined(OS_CHROMEOS)
156 #include "chrome/browser/ui/ash/multi_user/multi_user_window_manager.h"
157 #endif
159 using base::TimeDelta;
160 using base::UserMetricsAction;
161 using content::NativeWebKeyboardEvent;
162 using content::SSLStatus;
163 using content::WebContents;
164 using views::ColumnSet;
165 using views::GridLayout;
166 using web_modal::WebContentsModalDialogHost;
168 namespace {
169 // The name of a key to store on the window handle so that other code can
170 // locate this object using just the handle.
171 const char* const kBrowserViewKey = "__BROWSER_VIEW__";
173 // The number of milliseconds between loading animation frames.
174 const int kLoadingAnimationFrameTimeMs = 30;
176 // TODO(kuan): These functions are temporarily for the bookmark bar while its
177 // detached state is at the top of the page; it'll be moved to float on the
178 // content page in the very near future, at which time, these local functions
179 // will be removed.
180 void PaintDetachedBookmarkBar(gfx::Canvas* canvas,
181 DetachableToolbarView* view,
182 ThemeService* theme_service) {
183 // Paint background for detached state; if animating, this is fade in/out.
184 canvas->DrawColor(
185 chrome::GetDetachedBookmarkBarBackgroundColor(theme_service));
186 // Draw the separators above and below bookmark bar;
187 // if animating, these are fading in/out.
188 SkColor separator_color =
189 chrome::GetDetachedBookmarkBarSeparatorColor(theme_service);
190 DetachableToolbarView::PaintHorizontalBorder(canvas, view, true,
191 separator_color);
192 // The bottom border needs to be 1-px thick in both regular and retina
193 // displays, so we can't use DetachableToolbarView::PaintHorizontalBorder
194 // which paints a 2-px thick border in retina display.
195 SkPaint paint;
196 paint.setAntiAlias(false);
197 // Sets border to 1-px thick regardless of scale factor.
198 paint.setStrokeWidth(0);
199 // Bottom border is at 50% opacity of top border.
200 paint.setColor(SkColorSetA(separator_color,
201 SkColorGetA(separator_color) / 2));
202 // Calculate thickness of bottom border as per current scale factor to
203 // determine where to draw the 1-px thick border.
204 float thickness = views::NonClientFrameView::kClientEdgeThickness /
205 canvas->image_scale();
206 SkScalar y = SkIntToScalar(view->height()) - SkFloatToScalar(thickness);
207 canvas->sk_canvas()->drawLine(SkIntToScalar(0), y,
208 SkIntToScalar(view->width()), y, paint);
211 void PaintAttachedBookmarkBar(gfx::Canvas* canvas,
212 DetachableToolbarView* view,
213 BrowserView* browser_view,
214 chrome::HostDesktopType host_desktop_type,
215 int toolbar_overlap) {
216 // Paint background for attached state, this is fade in/out.
217 gfx::Point background_image_offset =
218 browser_view->OffsetPointForToolbarBackgroundImage(
219 gfx::Point(view->GetMirroredX(), view->y()));
220 DetachableToolbarView::PaintBackgroundAttachedMode(canvas,
221 view->GetThemeProvider(), view->GetLocalBounds(),
222 background_image_offset, host_desktop_type);
223 if (view->height() >= toolbar_overlap) {
224 // Draw the separator below bookmark bar; this is fading in/out.
225 DetachableToolbarView::PaintHorizontalBorder(canvas, view, false,
226 ThemeProperties::GetDefaultColor(
227 ThemeProperties::COLOR_TOOLBAR_SEPARATOR));
231 } // namespace
233 // static
234 const char BrowserView::kViewClassName[] = "BrowserView";
236 ///////////////////////////////////////////////////////////////////////////////
238 // Delegate implementation for BrowserViewLayout. Usually just forwards calls
239 // into BrowserView.
240 class BrowserViewLayoutDelegateImpl : public BrowserViewLayoutDelegate {
241 public:
242 explicit BrowserViewLayoutDelegateImpl(BrowserView* browser_view)
243 : browser_view_(browser_view) {}
244 virtual ~BrowserViewLayoutDelegateImpl() {}
246 // BrowserViewLayoutDelegate overrides:
247 virtual views::View* GetContentsWebView() const OVERRIDE {
248 return browser_view_->contents_web_view_;
251 virtual bool DownloadShelfNeedsLayout() const OVERRIDE {
252 DownloadShelfView* download_shelf = browser_view_->download_shelf_.get();
253 // Re-layout the shelf either if it is visible or if its close animation
254 // is currently running.
255 return download_shelf &&
256 (download_shelf->IsShowing() || download_shelf->IsClosing());
259 virtual bool IsTabStripVisible() const OVERRIDE {
260 return browser_view_->IsTabStripVisible();
263 virtual gfx::Rect GetBoundsForTabStripInBrowserView() const OVERRIDE {
264 gfx::RectF bounds_f(browser_view_->frame()->GetBoundsForTabStrip(
265 browser_view_->tabstrip()));
266 views::View::ConvertRectToTarget(browser_view_->parent(), browser_view_,
267 &bounds_f);
268 return gfx::ToEnclosingRect(bounds_f);
271 virtual int GetTopInsetInBrowserView() const OVERRIDE {
272 return browser_view_->frame()->GetTopInset() -
273 browser_view_->y();
276 virtual int GetThemeBackgroundXInset() const OVERRIDE {
277 // TODO(pkotwicz): Return the inset with respect to the left edge of the
278 // BrowserView.
279 return browser_view_->frame()->GetThemeBackgroundXInset();
282 virtual bool IsToolbarVisible() const OVERRIDE {
283 return browser_view_->IsToolbarVisible();
286 virtual bool IsBookmarkBarVisible() const OVERRIDE {
287 return browser_view_->IsBookmarkBarVisible();
290 virtual FullscreenExitBubbleViews* GetFullscreenExitBubble() const OVERRIDE {
291 return browser_view_->fullscreen_exit_bubble();
294 private:
295 BrowserView* browser_view_;
297 DISALLOW_COPY_AND_ASSIGN(BrowserViewLayoutDelegateImpl);
300 ///////////////////////////////////////////////////////////////////////////////
301 // BookmarkExtensionBackground, private:
302 // This object serves as the views::Background object which is used to layout
303 // and paint the bookmark bar.
304 class BookmarkExtensionBackground : public views::Background {
305 public:
306 BookmarkExtensionBackground(BrowserView* browser_view,
307 DetachableToolbarView* host_view,
308 Browser* browser);
310 // View methods overridden from views:Background.
311 virtual void Paint(gfx::Canvas* canvas, views::View* view) const OVERRIDE;
313 private:
314 BrowserView* browser_view_;
316 // The view hosting this background.
317 DetachableToolbarView* host_view_;
319 Browser* browser_;
321 DISALLOW_COPY_AND_ASSIGN(BookmarkExtensionBackground);
324 BookmarkExtensionBackground::BookmarkExtensionBackground(
325 BrowserView* browser_view,
326 DetachableToolbarView* host_view,
327 Browser* browser)
328 : browser_view_(browser_view),
329 host_view_(host_view),
330 browser_(browser) {
333 void BookmarkExtensionBackground::Paint(gfx::Canvas* canvas,
334 views::View* view) const {
335 int toolbar_overlap = host_view_->GetToolbarOverlap();
336 if (!host_view_->IsDetached()) {
337 PaintAttachedBookmarkBar(canvas, host_view_, browser_view_,
338 browser_->host_desktop_type(), toolbar_overlap);
339 return;
342 // As 'hidden' according to the animation is the full in-tab state, we invert
343 // the value - when current_state is at '0', we expect the bar to be docked.
344 double current_state = 1 - host_view_->GetAnimationValue();
346 ThemeService* ts =
347 ThemeServiceFactory::GetForProfile(browser_->profile());
348 if (current_state == 0.0 || current_state == 1.0) {
349 PaintDetachedBookmarkBar(canvas, host_view_, ts);
350 return;
352 // While animating, set opacity to cross-fade between attached and detached
353 // backgrounds including their respective separators.
354 int detached_alpha = static_cast<uint8>(current_state * 255);
355 int attached_alpha = 255 - detached_alpha;
356 if (browser_->bookmark_bar_state() == BookmarkBar::DETACHED) {
357 // To animate from attached to detached state:
358 // - fade out attached background
359 // - fade in detached background.
360 canvas->SaveLayerAlpha(attached_alpha);
361 PaintAttachedBookmarkBar(canvas, host_view_, browser_view_,
362 browser_->host_desktop_type(),
363 toolbar_overlap);
364 canvas->Restore();
365 canvas->SaveLayerAlpha(detached_alpha);
366 PaintDetachedBookmarkBar(canvas, host_view_, ts);
367 } else {
368 // To animate from detached to attached state:
369 // - fade out detached background
370 // - fade in attached background.
371 canvas->SaveLayerAlpha(detached_alpha);
372 PaintDetachedBookmarkBar(canvas, host_view_, ts);
373 canvas->Restore();
374 canvas->SaveLayerAlpha(attached_alpha);
375 PaintAttachedBookmarkBar(canvas, host_view_, browser_view_,
376 browser_->host_desktop_type(),
377 toolbar_overlap);
379 canvas->Restore();
382 ///////////////////////////////////////////////////////////////////////////////
383 // BrowserView, public:
385 BrowserView::BrowserView()
386 : views::ClientView(NULL, NULL),
387 last_focused_view_storage_id_(
388 views::ViewStorage::GetInstance()->CreateStorageID()),
389 frame_(NULL),
390 top_container_(NULL),
391 tabstrip_(NULL),
392 toolbar_(NULL),
393 find_bar_host_view_(NULL),
394 infobar_container_(NULL),
395 contents_web_view_(NULL),
396 contents_container_(NULL),
397 devtools_window_(NULL),
398 initialized_(false),
399 in_process_fullscreen_(false),
400 #if defined(OS_WIN)
401 hung_window_detector_(&hung_plugin_action_),
402 ticker_(0),
403 #endif
404 force_location_bar_focus_(false),
405 #if defined(OS_CHROMEOS)
406 scroll_end_effect_controller_(ScrollEndEffectController::Create()),
407 #endif
408 activate_modal_dialog_factory_(this) {
411 BrowserView::~BrowserView() {
412 // All the tabs should have been destroyed already. If we were closed by the
413 // OS with some tabs than the NativeBrowserFrame should have destroyed them.
414 DCHECK_EQ(0, browser_->tab_strip_model()->count());
416 // Immersive mode may need to reparent views before they are removed/deleted.
417 immersive_mode_controller_.reset();
419 browser_->tab_strip_model()->RemoveObserver(this);
421 #if defined(OS_WIN)
422 // Stop hung plugin monitoring.
423 ticker_.Stop();
424 ticker_.UnregisterTickHandler(&hung_window_detector_);
426 // Terminate the jumplist (must be called before browser_->profile() is
427 // destroyed.
428 if (jumplist_) {
429 jumplist_->Terminate();
431 #endif
433 // We destroy the download shelf before |browser_| to remove its child
434 // download views from the set of download observers (since the observed
435 // downloads can be destroyed along with |browser_| and the observer
436 // notifications will call back into deleted objects).
437 BrowserViewLayout* browser_view_layout = GetBrowserViewLayout();
438 if (browser_view_layout)
439 browser_view_layout->set_download_shelf(NULL);
440 download_shelf_.reset();
442 // The TabStrip attaches a listener to the model. Make sure we shut down the
443 // TabStrip first so that it can cleanly remove the listener.
444 if (tabstrip_) {
445 tabstrip_->parent()->RemoveChildView(tabstrip_);
446 if (browser_view_layout)
447 browser_view_layout->set_tab_strip(NULL);
448 delete tabstrip_;
449 tabstrip_ = NULL;
451 // Child views maintain PrefMember attributes that point to
452 // OffTheRecordProfile's PrefService which gets deleted by ~Browser.
453 RemoveAllChildViews(true);
454 toolbar_ = NULL;
456 // Explicitly set browser_ to NULL.
457 browser_.reset();
460 void BrowserView::Init(Browser* browser) {
461 browser_.reset(browser);
462 browser_->tab_strip_model()->AddObserver(this);
463 immersive_mode_controller_.reset(
464 chrome::CreateImmersiveModeController(browser_->host_desktop_type()));
467 // static
468 BrowserView* BrowserView::GetBrowserViewForNativeWindow(
469 gfx::NativeWindow window) {
470 views::Widget* widget = views::Widget::GetWidgetForNativeWindow(window);
471 return widget ?
472 reinterpret_cast<BrowserView*>(widget->GetNativeWindowProperty(
473 kBrowserViewKey)) : NULL;
476 // static
477 BrowserView* BrowserView::GetBrowserViewForBrowser(const Browser* browser) {
478 return static_cast<BrowserView*>(browser->window());
481 void BrowserView::InitStatusBubble() {
482 status_bubble_.reset(new StatusBubbleViews(contents_web_view_));
483 contents_web_view_->SetStatusBubble(status_bubble_.get());
486 void BrowserView::InitPermissionBubbleView() {
487 permission_bubble_view_.reset(new PermissionBubbleViewViews(
488 GetLocationBarView()->location_icon_view()));
491 gfx::Rect BrowserView::GetToolbarBounds() const {
492 gfx::Rect toolbar_bounds(toolbar_->bounds());
493 if (toolbar_bounds.IsEmpty())
494 return toolbar_bounds;
495 // The apparent toolbar edges are outside the "real" toolbar edges.
496 toolbar_bounds.Inset(-views::NonClientFrameView::kClientEdgeThickness, 0);
497 return toolbar_bounds;
500 gfx::Rect BrowserView::GetFindBarBoundingBox() const {
501 return GetBrowserViewLayout()->GetFindBarBoundingBox();
504 int BrowserView::GetTabStripHeight() const {
505 // We want to return tabstrip_->height(), but we might be called in the midst
506 // of layout, when that hasn't yet been updated to reflect the current state.
507 // So return what the tabstrip height _ought_ to be right now.
508 return IsTabStripVisible() ? tabstrip_->GetPreferredSize().height() : 0;
511 gfx::Point BrowserView::OffsetPointForToolbarBackgroundImage(
512 const gfx::Point& point) const {
513 // The background image starts tiling horizontally at the window left edge and
514 // vertically at the top edge of the horizontal tab strip (or where it would
515 // be). We expect our parent's origin to be the window origin.
516 gfx::Point window_point(point + GetMirroredPosition().OffsetFromOrigin());
517 window_point.Offset(frame_->GetThemeBackgroundXInset(),
518 -frame_->GetTopInset());
519 return window_point;
522 bool BrowserView::IsTabStripVisible() const {
523 if (immersive_mode_controller_->ShouldHideTopViews() &&
524 immersive_mode_controller_->ShouldHideTabIndicators())
525 return false;
526 return browser_->SupportsWindowFeature(Browser::FEATURE_TABSTRIP);
529 bool BrowserView::IsOffTheRecord() const {
530 return browser_->profile()->IsOffTheRecord();
533 bool BrowserView::IsGuestSession() const {
534 return browser_->profile()->IsGuestSession();
537 bool BrowserView::IsRegularOrGuestSession() const {
538 return profiles::IsRegularOrGuestSession(browser_.get());
541 bool BrowserView::ShouldShowAvatar() const {
542 #if defined(OS_CHROMEOS)
543 if (!browser_->is_type_tabbed() && !browser_->is_app())
544 return false;
545 // Don't show incognito avatar in the guest session.
546 if (IsOffTheRecord() && !IsGuestSession())
547 return true;
548 // This function is called via BrowserNonClientFrameView::UpdateAvatarInfo
549 // during the creation of the BrowserWindow, so browser->window() will not
550 // yet be set. In this case we can safely return false.
551 if (!browser_->window())
552 return false;
553 return chrome::MultiUserWindowManager::ShouldShowAvatar(
554 browser_->window()->GetNativeWindow());
555 #else
556 if (!IsBrowserTypeNormal())
557 return false;
558 if (IsOffTheRecord()) // Desktop guest is incognito and needs avatar.
559 return true;
560 // Tests may not have a profile manager.
561 if (!g_browser_process->profile_manager())
562 return false;
563 ProfileInfoCache& cache =
564 g_browser_process->profile_manager()->GetProfileInfoCache();
565 if (cache.GetIndexOfProfileWithPath(browser_->profile()->GetPath()) ==
566 std::string::npos) {
567 return false;
570 return AvatarMenu::ShouldShowAvatarMenu();
571 #endif
574 bool BrowserView::GetAccelerator(int cmd_id,
575 ui::Accelerator* accelerator) const {
576 // We retrieve the accelerator information for standard accelerators
577 // for cut, copy and paste.
578 if (chrome::GetStandardAcceleratorForCommandId(cmd_id, accelerator))
579 return true;
580 // Else, we retrieve the accelerator information from the accelerator table.
581 for (std::map<ui::Accelerator, int>::const_iterator it =
582 accelerator_table_.begin(); it != accelerator_table_.end(); ++it) {
583 if (it->second == cmd_id) {
584 *accelerator = it->first;
585 return true;
588 // Else, we retrieve the accelerator information from Ash (if applicable).
589 return chrome::GetAshAcceleratorForCommandId(
590 cmd_id, browser_->host_desktop_type(), accelerator);
593 bool BrowserView::IsAcceleratorRegistered(const ui::Accelerator& accelerator) {
594 return accelerator_table_.find(accelerator) != accelerator_table_.end();
597 WebContents* BrowserView::GetActiveWebContents() const {
598 return browser_->tab_strip_model()->GetActiveWebContents();
601 gfx::ImageSkia BrowserView::GetOTRAvatarIcon() const {
602 return *GetThemeProvider()->GetImageSkiaNamed(IDR_OTR_ICON);
605 ///////////////////////////////////////////////////////////////////////////////
606 // BrowserView, BrowserWindow implementation:
608 void BrowserView::Show() {
609 // If the window is already visible, just activate it.
610 if (frame_->IsVisible()) {
611 frame_->Activate();
612 return;
615 // Showing the window doesn't make the browser window active right away.
616 // This can cause SetFocusToLocationBar() to skip setting focus to the
617 // location bar. To avoid this we explicilty let SetFocusToLocationBar()
618 // know that it's ok to steal focus.
619 force_location_bar_focus_ = true;
621 // Setting the focus doesn't work when the window is invisible, so any focus
622 // initialization that happened before this will be lost.
624 // We really "should" restore the focus whenever the window becomes unhidden,
625 // but I think initializing is the only time where this can happen where
626 // there is some focus change we need to pick up, and this is easier than
627 // plumbing through an un-hide message all the way from the frame.
629 // If we do find there are cases where we need to restore the focus on show,
630 // that should be added and this should be removed.
631 RestoreFocus();
633 frame_->Show();
635 force_location_bar_focus_ = false;
637 browser()->OnWindowDidShow();
639 chrome::MaybeShowInvertBubbleView(this);
642 void BrowserView::ShowInactive() {
643 if (!frame_->IsVisible())
644 frame_->ShowInactive();
647 void BrowserView::Hide() {
648 // Not implemented.
651 void BrowserView::SetBounds(const gfx::Rect& bounds) {
652 ExitFullscreen();
653 GetWidget()->SetBounds(bounds);
656 void BrowserView::Close() {
657 frame_->Close();
660 void BrowserView::Activate() {
661 frame_->Activate();
664 void BrowserView::Deactivate() {
665 frame_->Deactivate();
668 bool BrowserView::IsActive() const {
669 return frame_->IsActive();
672 void BrowserView::FlashFrame(bool flash) {
673 frame_->FlashFrame(flash);
676 bool BrowserView::IsAlwaysOnTop() const {
677 return false;
680 void BrowserView::SetAlwaysOnTop(bool always_on_top) {
681 // Not implemented for browser windows.
682 NOTIMPLEMENTED();
685 gfx::NativeWindow BrowserView::GetNativeWindow() {
686 // While the browser destruction is going on, the widget can already be gone,
687 // but utility functions like FindBrowserWithWindow will come here and crash.
688 // We short circuit therefore.
689 if (!GetWidget())
690 return NULL;
691 return GetWidget()->GetTopLevelWidget()->GetNativeWindow();
694 BrowserWindowTesting* BrowserView::GetBrowserWindowTesting() {
695 return this;
698 StatusBubble* BrowserView::GetStatusBubble() {
699 return status_bubble_.get();
702 namespace {
703 // Only used by ToolbarSizeChanged() below, but placed here because template
704 // arguments (to base::AutoReset<>) must have external linkage.
705 enum CallState { NORMAL, REENTRANT, REENTRANT_FORCE_FAST_RESIZE };
708 void BrowserView::UpdateTitleBar() {
709 frame_->UpdateWindowTitle();
710 if (ShouldShowWindowIcon() && !loading_animation_timer_.IsRunning())
711 frame_->UpdateWindowIcon();
714 void BrowserView::BookmarkBarStateChanged(
715 BookmarkBar::AnimateChangeType change_type) {
716 if (bookmark_bar_view_.get()) {
717 BookmarkBar::State new_state = browser_->bookmark_bar_state();
719 // We don't properly support animating the bookmark bar to and from the
720 // detached state in immersive fullscreen.
721 bool detached_changed = (new_state == BookmarkBar::DETACHED) ||
722 bookmark_bar_view_->IsDetached();
723 if (detached_changed && immersive_mode_controller_->IsEnabled())
724 change_type = BookmarkBar::DONT_ANIMATE_STATE_CHANGE;
726 bookmark_bar_view_->SetBookmarkBarState(new_state, change_type);
728 if (MaybeShowBookmarkBar(GetActiveWebContents()))
729 Layout();
732 void BrowserView::UpdateDevTools() {
733 UpdateDevToolsForContents(GetActiveWebContents(), true);
734 Layout();
737 void BrowserView::UpdateLoadingAnimations(bool should_animate) {
738 if (should_animate) {
739 if (!loading_animation_timer_.IsRunning()) {
740 // Loads are happening, and the timer isn't running, so start it.
741 last_animation_time_ = base::TimeTicks::Now();
742 loading_animation_timer_.Start(FROM_HERE,
743 TimeDelta::FromMilliseconds(kLoadingAnimationFrameTimeMs), this,
744 &BrowserView::LoadingAnimationCallback);
746 } else {
747 if (loading_animation_timer_.IsRunning()) {
748 last_animation_time_ = base::TimeTicks();
749 loading_animation_timer_.Stop();
750 // Loads are now complete, update the state if a task was scheduled.
751 LoadingAnimationCallback();
756 void BrowserView::SetStarredState(bool is_starred) {
757 GetLocationBarView()->SetStarToggled(is_starred);
760 void BrowserView::SetTranslateIconToggled(bool is_lit) {
761 GetLocationBarView()->SetTranslateIconToggled(is_lit);
764 void BrowserView::OnActiveTabChanged(content::WebContents* old_contents,
765 content::WebContents* new_contents,
766 int index,
767 int reason) {
768 DCHECK(new_contents);
770 // If |contents_container_| already has the correct WebContents, we can save
771 // some work. This also prevents extra events from being reported by the
772 // Visibility API under Windows, as ChangeWebContents will briefly hide
773 // the WebContents window.
774 bool change_tab_contents =
775 contents_web_view_->web_contents() != new_contents;
777 // Update various elements that are interested in knowing the current
778 // WebContents.
780 // When we toggle the NTP floating bookmarks bar and/or the info bar,
781 // we don't want any WebContents to be attached, so that we
782 // avoid an unnecessary resize and re-layout of a WebContents.
783 if (change_tab_contents) {
784 contents_web_view_->SetWebContents(NULL);
785 devtools_web_view_->SetWebContents(NULL);
788 infobar_container_->ChangeInfoBarManager(
789 InfoBarService::FromWebContents(new_contents));
791 if (old_contents && PermissionBubbleManager::FromWebContents(old_contents))
792 PermissionBubbleManager::FromWebContents(old_contents)->SetView(NULL);
794 if (new_contents && PermissionBubbleManager::FromWebContents(new_contents)) {
795 PermissionBubbleManager::FromWebContents(new_contents)->SetView(
796 permission_bubble_view_.get());
799 if (bookmark_bar_view_.get()) {
800 bookmark_bar_view_->SetBookmarkBarState(
801 browser_->bookmark_bar_state(),
802 BookmarkBar::DONT_ANIMATE_STATE_CHANGE);
804 UpdateUIForContents(new_contents);
806 // Layout for DevTools _before_ setting the both main and devtools WebContents
807 // to avoid toggling the size of any of them.
808 UpdateDevToolsForContents(new_contents, !change_tab_contents);
810 if (change_tab_contents) {
811 web_contents_close_handler_->ActiveTabChanged();
812 contents_web_view_->SetWebContents(new_contents);
813 // The second layout update should be no-op. It will just set the
814 // DevTools WebContents.
815 UpdateDevToolsForContents(new_contents, true);
818 if (!browser_->tab_strip_model()->closing_all() && GetWidget()->IsActive() &&
819 GetWidget()->IsVisible()) {
820 // We only restore focus if our window is visible, to avoid invoking blur
821 // handlers when we are eventually shown.
822 new_contents->RestoreFocus();
825 // Update all the UI bits.
826 UpdateTitleBar();
829 void BrowserView::ZoomChangedForActiveTab(bool can_show_bubble) {
830 GetLocationBarView()->ZoomChangedForActiveTab(
831 can_show_bubble && !toolbar_->IsWrenchMenuShowing());
834 gfx::Rect BrowserView::GetRestoredBounds() const {
835 gfx::Rect bounds;
836 ui::WindowShowState state;
837 frame_->GetWindowPlacement(&bounds, &state);
838 return bounds;
841 ui::WindowShowState BrowserView::GetRestoredState() const {
842 gfx::Rect bounds;
843 ui::WindowShowState state;
844 frame_->GetWindowPlacement(&bounds, &state);
845 return state;
848 gfx::Rect BrowserView::GetBounds() const {
849 return frame_->GetWindowBoundsInScreen();
852 bool BrowserView::IsMaximized() const {
853 return frame_->IsMaximized();
856 bool BrowserView::IsMinimized() const {
857 return frame_->IsMinimized();
860 void BrowserView::Maximize() {
861 frame_->Maximize();
864 void BrowserView::Minimize() {
865 frame_->Minimize();
868 void BrowserView::Restore() {
869 frame_->Restore();
872 void BrowserView::EnterFullscreen(
873 const GURL& url, FullscreenExitBubbleType bubble_type) {
874 if (IsFullscreen())
875 return; // Nothing to do.
877 ProcessFullscreen(true, NORMAL_FULLSCREEN, url, bubble_type);
880 void BrowserView::ExitFullscreen() {
881 if (!IsFullscreen())
882 return; // Nothing to do.
884 ProcessFullscreen(false, NORMAL_FULLSCREEN, GURL(), FEB_TYPE_NONE);
887 void BrowserView::UpdateFullscreenExitBubbleContent(
888 const GURL& url,
889 FullscreenExitBubbleType bubble_type) {
890 // Immersive mode has no exit bubble because it has a visible strip at the
891 // top that gives the user a hover target.
892 // TODO(jamescook): Figure out what to do with mouse-lock.
893 if (bubble_type == FEB_TYPE_NONE || ShouldUseImmersiveFullscreenForUrl(url)) {
894 fullscreen_bubble_.reset();
895 } else if (fullscreen_bubble_.get()) {
896 fullscreen_bubble_->UpdateContent(url, bubble_type);
897 } else {
898 fullscreen_bubble_.reset(new FullscreenExitBubbleViews(
899 this, url, bubble_type));
903 bool BrowserView::ShouldHideUIForFullscreen() const {
904 #if defined(USE_ASH)
905 // Immersive mode needs UI for the slide-down top panel.
906 if (immersive_mode_controller_->IsEnabled())
907 return false;
908 #endif
909 return IsFullscreen();
912 bool BrowserView::IsFullscreen() const {
913 return frame_->IsFullscreen();
916 bool BrowserView::IsFullscreenBubbleVisible() const {
917 return fullscreen_bubble_ != NULL;
920 #if defined(OS_WIN)
921 void BrowserView::SetMetroSnapMode(bool enable) {
922 HISTOGRAM_COUNTS("Metro.SnapModeToggle", enable);
923 ProcessFullscreen(enable, METRO_SNAP_FULLSCREEN, GURL(), FEB_TYPE_NONE);
926 bool BrowserView::IsInMetroSnapMode() const {
927 return false;
929 #endif // defined(OS_WIN)
931 void BrowserView::RestoreFocus() {
932 WebContents* selected_web_contents = GetActiveWebContents();
933 if (selected_web_contents)
934 selected_web_contents->RestoreFocus();
937 void BrowserView::FullscreenStateChanged() {
938 CHECK(!IsFullscreen());
939 ProcessFullscreen(false, NORMAL_FULLSCREEN, GURL(), FEB_TYPE_NONE);
942 void BrowserView::ToolbarSizeChanged(bool is_animating) {
943 // The call to InfoBarContainer::SetMaxTopArrowHeight() below can result in
944 // reentrancy; |call_state| tracks whether we're reentrant. We can't just
945 // early-return in this case because we need to layout again so the infobar
946 // container's bounds are set correctly.
947 static CallState call_state = NORMAL;
949 // A reentrant call can (and should) use the fast resize path unless both it
950 // and the normal call are both non-animating.
951 bool use_fast_resize =
952 is_animating || (call_state == REENTRANT_FORCE_FAST_RESIZE);
953 if (use_fast_resize)
954 contents_web_view_->SetFastResize(true);
955 UpdateUIForContents(GetActiveWebContents());
956 if (use_fast_resize)
957 contents_web_view_->SetFastResize(false);
959 // Inform the InfoBarContainer that the distance to the location icon may have
960 // changed. We have to do this after the block above so that the toolbars are
961 // laid out correctly for calculating the maximum arrow height below.
963 base::AutoReset<CallState> resetter(&call_state,
964 is_animating ? REENTRANT_FORCE_FAST_RESIZE : REENTRANT);
965 infobar_container_->SetMaxTopArrowHeight(GetMaxTopInfoBarArrowHeight());
968 // When transitioning from animating to not animating we need to make sure the
969 // contents_container_ gets layed out. If we don't do this and the bounds
970 // haven't changed contents_container_ won't get a Layout out and we'll end up
971 // with a gray rect because the clip wasn't updated. Note that a reentrant
972 // call never needs to do this, because after it returns, the normal call
973 // wrapping it will do it.
974 if ((call_state == NORMAL) && !is_animating) {
975 contents_web_view_->InvalidateLayout();
976 contents_container_->Layout();
980 LocationBar* BrowserView::GetLocationBar() const {
981 return GetLocationBarView();
984 void BrowserView::SetFocusToLocationBar(bool select_all) {
985 // On Windows, changing focus to the location bar causes the browser
986 // window to become active. This can steal focus if the user has
987 // another window open already. On ChromeOS, changing focus makes a
988 // view believe it has a focus even if the widget doens't have a
989 // focus. Either cases, we need to ignore this when the browser
990 // window isn't active.
991 if (!force_location_bar_focus_ && !IsActive())
992 return;
994 // Temporarily reveal the top-of-window views (if not already revealed) so
995 // that the location bar view is visible and is considered focusable. If the
996 // location bar view gains focus, |immersive_mode_controller_| will keep the
997 // top-of-window views revealed.
998 scoped_ptr<ImmersiveRevealedLock> focus_reveal_lock(
999 immersive_mode_controller_->GetRevealedLock(
1000 ImmersiveModeController::ANIMATE_REVEAL_YES));
1002 LocationBarView* location_bar = GetLocationBarView();
1003 if (location_bar->omnibox_view()->IsFocusable()) {
1004 // Location bar got focus.
1006 // select_all is true when it's expected that the user may want to copy
1007 // the URL to the clipboard. If the URL is not being shown because the
1008 // origin chip is enabled, show it now to support the same functionality.
1009 if (select_all &&
1010 location_bar->GetToolbarModel()->WouldOmitURLDueToOriginChip())
1011 location_bar->ShowURL();
1012 else
1013 location_bar->FocusLocation(select_all);
1014 } else {
1015 // If none of location bar got focus, then clear focus.
1016 views::FocusManager* focus_manager = GetFocusManager();
1017 DCHECK(focus_manager);
1018 focus_manager->ClearFocus();
1022 void BrowserView::UpdateReloadStopState(bool is_loading, bool force) {
1023 toolbar_->reload_button()->ChangeMode(
1024 is_loading ? ReloadButton::MODE_STOP : ReloadButton::MODE_RELOAD, force);
1027 void BrowserView::UpdateToolbar(content::WebContents* contents) {
1028 // We may end up here during destruction.
1029 if (toolbar_)
1030 toolbar_->Update(contents);
1033 void BrowserView::FocusToolbar() {
1034 // Temporarily reveal the top-of-window views (if not already revealed) so
1035 // that the toolbar is visible and is considered focusable. If the
1036 // toolbar gains focus, |immersive_mode_controller_| will keep the
1037 // top-of-window views revealed.
1038 scoped_ptr<ImmersiveRevealedLock> focus_reveal_lock(
1039 immersive_mode_controller_->GetRevealedLock(
1040 ImmersiveModeController::ANIMATE_REVEAL_YES));
1042 // Start the traversal within the main toolbar. SetPaneFocus stores
1043 // the current focused view before changing focus.
1044 toolbar_->SetPaneFocus(NULL);
1047 void BrowserView::FocusBookmarksToolbar() {
1048 DCHECK(!immersive_mode_controller_->IsEnabled());
1049 if (bookmark_bar_view_.get() &&
1050 bookmark_bar_view_->visible() &&
1051 bookmark_bar_view_->GetPreferredSize().height() != 0) {
1052 bookmark_bar_view_->SetPaneFocusAndFocusDefault();
1056 void BrowserView::FocusInfobars() {
1057 if (infobar_container_->child_count() > 0)
1058 infobar_container_->SetPaneFocusAndFocusDefault();
1061 void BrowserView::FocusAppMenu() {
1062 // Chrome doesn't have a traditional menu bar, but it has a menu button in the
1063 // main toolbar that plays the same role. If the user presses a key that
1064 // would typically focus the menu bar, tell the toolbar to focus the menu
1065 // button. If the user presses the key again, return focus to the previous
1066 // location.
1068 // Not used on the Mac, which has a normal menu bar.
1069 if (toolbar_->IsAppMenuFocused()) {
1070 RestoreFocus();
1071 } else {
1072 DCHECK(!immersive_mode_controller_->IsEnabled());
1073 toolbar_->SetPaneFocusAndFocusAppMenu();
1077 void BrowserView::RotatePaneFocus(bool forwards) {
1078 GetWidget()->GetFocusManager()->RotatePaneFocus(
1079 forwards ?
1080 views::FocusManager::kForward : views::FocusManager::kBackward,
1081 views::FocusManager::kWrap);
1084 void BrowserView::DestroyBrowser() {
1085 // After this returns other parts of Chrome are going to be shutdown. Close
1086 // the window now so that we are deleted immediately and aren't left holding
1087 // references to deleted objects.
1088 GetWidget()->RemoveObserver(this);
1089 GetLocationBar()->GetOmniboxView()->model()->popup_model()->RemoveObserver(
1090 this);
1091 frame_->CloseNow();
1094 bool BrowserView::IsBookmarkBarVisible() const {
1095 if (!browser_->SupportsWindowFeature(Browser::FEATURE_BOOKMARKBAR))
1096 return false;
1097 if (!bookmark_bar_view_.get())
1098 return false;
1099 if (bookmark_bar_view_->GetPreferredSize().height() == 0)
1100 return false;
1101 // New tab page needs visible bookmarks even when top-views are hidden.
1102 if (immersive_mode_controller_->ShouldHideTopViews() &&
1103 !bookmark_bar_view_->IsDetached())
1104 return false;
1105 return true;
1108 bool BrowserView::IsBookmarkBarAnimating() const {
1109 return bookmark_bar_view_.get() && bookmark_bar_view_->is_animating();
1112 bool BrowserView::IsTabStripEditable() const {
1113 return tabstrip_->IsTabStripEditable();
1116 bool BrowserView::IsToolbarVisible() const {
1117 if (immersive_mode_controller_->ShouldHideTopViews())
1118 return false;
1119 return browser_->SupportsWindowFeature(Browser::FEATURE_TOOLBAR) ||
1120 browser_->SupportsWindowFeature(Browser::FEATURE_LOCATIONBAR);
1123 gfx::Rect BrowserView::GetRootWindowResizerRect() const {
1124 // Views does not support resizer rects because they caused page cycler
1125 // performance regressions when they were added. See crrev.com/9654
1126 return gfx::Rect();
1129 void BrowserView::ConfirmAddSearchProvider(TemplateURL* template_url,
1130 Profile* profile) {
1131 chrome::EditSearchEngine(GetWidget()->GetNativeWindow(), template_url, NULL,
1132 profile);
1135 void BrowserView::ShowUpdateChromeDialog() {
1136 UpdateRecommendedMessageBox::Show(GetWidget()->GetNativeWindow());
1139 void BrowserView::ShowBookmarkBubble(const GURL& url, bool already_bookmarked) {
1140 scoped_ptr<BookmarkBubbleDelegate> delegate;
1141 delegate.reset(new BookmarkBubbleSignInDelegate(browser_.get()));
1143 BookmarkBubbleView::ShowBubble(GetToolbarView()->GetBookmarkBubbleAnchor(),
1144 bookmark_bar_view_.get(),
1145 delegate.Pass(),
1146 browser_->profile(),
1147 url,
1148 !already_bookmarked);
1151 void BrowserView::ShowBookmarkAppBubble(
1152 const WebApplicationInfo& web_app_info,
1153 const std::string& extension_id) {
1154 BookmarkAppBubbleView::ShowBubble(GetToolbarView(),
1155 browser_->profile(),
1156 web_app_info,
1157 extension_id);
1160 void BrowserView::ShowTranslateBubble(content::WebContents* web_contents,
1161 translate::TranslateStep step,
1162 TranslateErrors::Type error_type) {
1163 TranslateTabHelper* translate_tab_helper =
1164 TranslateTabHelper::FromWebContents(web_contents);
1165 LanguageState& language_state = translate_tab_helper->GetLanguageState();
1166 language_state.SetTranslateEnabled(true);
1168 TranslateBubbleView::ShowBubble(
1169 GetToolbarView()->GetTranslateBubbleAnchor(), web_contents, step,
1170 error_type);
1173 #if defined(ENABLE_ONE_CLICK_SIGNIN)
1174 void BrowserView::ShowOneClickSigninBubble(
1175 OneClickSigninBubbleType type,
1176 const base::string16& email,
1177 const base::string16& error_message,
1178 const StartSyncCallback& start_sync_callback) {
1179 scoped_ptr<OneClickSigninBubbleDelegate> delegate;
1180 delegate.reset(new OneClickSigninBubbleLinksDelegate(browser()));
1182 views::View* anchor_view;
1183 if (type == BrowserWindow::ONE_CLICK_SIGNIN_BUBBLE_TYPE_BUBBLE)
1184 anchor_view = toolbar_->app_menu();
1185 else
1186 anchor_view = toolbar_->location_bar();
1188 OneClickSigninBubbleView::ShowBubble(type, email, error_message,
1189 delegate.Pass(), anchor_view,
1190 start_sync_callback);
1192 #endif
1194 void BrowserView::SetDownloadShelfVisible(bool visible) {
1195 // This can be called from the superclass destructor, when it destroys our
1196 // child views. At that point, browser_ is already gone.
1197 if (browser_ == NULL)
1198 return;
1200 if (visible && IsDownloadShelfVisible() != visible) {
1201 // Invoke GetDownloadShelf to force the shelf to be created.
1202 GetDownloadShelf();
1205 if (browser_ != NULL)
1206 browser_->UpdateDownloadShelfVisibility(visible);
1208 // SetDownloadShelfVisible can force-close the shelf, so make sure we lay out
1209 // everything correctly, as if the animation had finished. This doesn't
1210 // matter for showing the shelf, as the show animation will do it.
1211 ToolbarSizeChanged(false);
1214 bool BrowserView::IsDownloadShelfVisible() const {
1215 return download_shelf_.get() && download_shelf_->IsShowing();
1218 DownloadShelf* BrowserView::GetDownloadShelf() {
1219 if (!download_shelf_.get()) {
1220 download_shelf_.reset(new DownloadShelfView(browser_.get(), this));
1221 download_shelf_->set_owned_by_client();
1222 GetBrowserViewLayout()->set_download_shelf(download_shelf_.get());
1224 return download_shelf_.get();
1227 void BrowserView::ConfirmBrowserCloseWithPendingDownloads(
1228 int download_count,
1229 Browser::DownloadClosePreventionType dialog_type,
1230 bool app_modal,
1231 const base::Callback<void(bool)>& callback) {
1232 DownloadInProgressDialogView::Show(
1233 GetNativeWindow(), download_count, dialog_type, app_modal, callback);
1236 void BrowserView::UserChangedTheme() {
1237 frame_->FrameTypeChanged();
1240 int BrowserView::GetExtraRenderViewHeight() const {
1241 // Currently this is only used on linux.
1242 return 0;
1245 void BrowserView::WebContentsFocused(WebContents* contents) {
1246 if (contents_web_view_->GetWebContents() == contents)
1247 contents_web_view_->OnWebContentsFocused(contents);
1248 else
1249 devtools_web_view_->OnWebContentsFocused(contents);
1252 void BrowserView::ShowWebsiteSettings(Profile* profile,
1253 content::WebContents* web_contents,
1254 const GURL& url,
1255 const content::SSLStatus& ssl) {
1256 WebsiteSettingsPopupView::ShowPopup(
1257 GetLocationBarView()->location_icon_view(), profile,
1258 web_contents, url, ssl, browser_.get());
1261 void BrowserView::ShowAppMenu() {
1262 // Keep the top-of-window views revealed as long as the app menu is visible.
1263 scoped_ptr<ImmersiveRevealedLock> revealed_lock(
1264 immersive_mode_controller_->GetRevealedLock(
1265 ImmersiveModeController::ANIMATE_REVEAL_NO));
1267 toolbar_->app_menu()->Activate();
1270 bool BrowserView::PreHandleKeyboardEvent(const NativeWebKeyboardEvent& event,
1271 bool* is_keyboard_shortcut) {
1272 *is_keyboard_shortcut = false;
1274 if ((event.type != blink::WebInputEvent::RawKeyDown) &&
1275 (event.type != blink::WebInputEvent::KeyUp)) {
1276 return false;
1279 views::FocusManager* focus_manager = GetFocusManager();
1280 DCHECK(focus_manager);
1282 if (focus_manager->shortcut_handling_suspended())
1283 return false;
1285 ui::Accelerator accelerator(
1286 static_cast<ui::KeyboardCode>(event.windowsKeyCode),
1287 content::GetModifiersFromNativeWebKeyboardEvent(event));
1288 if (event.type == blink::WebInputEvent::KeyUp)
1289 accelerator.set_type(ui::ET_KEY_RELEASED);
1291 // What we have to do here is as follows:
1292 // - If the |browser_| is for an app, do nothing.
1293 // - If the |browser_| is not for an app, and the |accelerator| is not
1294 // associated with the browser (e.g. an Ash shortcut), process it.
1295 // - If the |browser_| is not for an app, and the |accelerator| is associated
1296 // with the browser, and it is a reserved one (e.g. Ctrl+w), process it.
1297 // - If the |browser_| is not for an app, and the |accelerator| is associated
1298 // with the browser, and it is not a reserved one, do nothing.
1300 if (browser_->is_app()) {
1301 // Let all keys fall through to a v1 app's web content, even accelerators.
1302 // We don't have to flip |is_keyboard_shortcut| here. If we do that, the app
1303 // might not be able to see a subsequent Char event. See OnHandleInputEvent
1304 // in content/renderer/render_widget.cc for details.
1305 return false;
1308 chrome::BrowserCommandController* controller = browser_->command_controller();
1310 // Here we need to retrieve the command id (if any) associated to the
1311 // keyboard event. Instead of looking up the command id in the
1312 // |accelerator_table_| by ourselves, we block the command execution of
1313 // the |browser_| object then send the keyboard event to the
1314 // |focus_manager| as if we are activating an accelerator key.
1315 // Then we can retrieve the command id from the |browser_| object.
1316 bool original_block_command_state = controller->block_command_execution();
1317 controller->SetBlockCommandExecution(true);
1318 // If the |accelerator| is a non-browser shortcut (e.g. Ash shortcut), the
1319 // command execution cannot be blocked and true is returned. However, it is
1320 // okay as long as is_app() is false. See comments in this function.
1321 const bool processed = focus_manager->ProcessAccelerator(accelerator);
1322 const int id = controller->GetLastBlockedCommand(NULL);
1323 controller->SetBlockCommandExecution(original_block_command_state);
1325 // Executing the command may cause |this| object to be destroyed.
1326 if (controller->IsReservedCommandOrKey(id, event)) {
1327 UpdateAcceleratorMetrics(accelerator, id);
1328 return chrome::ExecuteCommand(browser_.get(), id);
1331 if (id != -1) {
1332 // |accelerator| is a non-reserved browser shortcut (e.g. Ctrl+f).
1333 if (event.type == blink::WebInputEvent::RawKeyDown)
1334 *is_keyboard_shortcut = true;
1335 } else if (processed) {
1336 // |accelerator| is a non-browser shortcut (e.g. F4-F10 on Ash). Report
1337 // that we handled it.
1338 return true;
1341 return false;
1344 void BrowserView::HandleKeyboardEvent(const NativeWebKeyboardEvent& event) {
1345 unhandled_keyboard_event_handler_.HandleKeyboardEvent(event,
1346 GetFocusManager());
1349 // TODO(devint): http://b/issue?id=1117225 Cut, Copy, and Paste are always
1350 // enabled in the page menu regardless of whether the command will do
1351 // anything. When someone selects the menu item, we just act as if they hit
1352 // the keyboard shortcut for the command by sending the associated key press
1353 // to windows. The real fix to this bug is to disable the commands when they
1354 // won't do anything. We'll need something like an overall clipboard command
1355 // manager to do that.
1356 void BrowserView::Cut() {
1357 // If a WebContent is focused, call WebContents::Cut. Otherwise, e.g. if
1358 // Omnibox is focused, send a Ctrl+x key event to Chrome. Using RWH interface
1359 // rather than the fake key event for a WebContent is important since the fake
1360 // event might be consumed by the web content (crbug.com/137908).
1361 DoCutCopyPaste(&content::WebContents::Cut, IDS_APP_CUT);
1364 void BrowserView::Copy() {
1365 DoCutCopyPaste(&content::WebContents::Copy, IDS_APP_COPY);
1368 void BrowserView::Paste() {
1369 DoCutCopyPaste(&content::WebContents::Paste, IDS_APP_PASTE);
1372 WindowOpenDisposition BrowserView::GetDispositionForPopupBounds(
1373 const gfx::Rect& bounds) {
1374 return NEW_POPUP;
1377 FindBar* BrowserView::CreateFindBar() {
1378 return chrome::CreateFindBar(this);
1381 WebContentsModalDialogHost* BrowserView::GetWebContentsModalDialogHost() {
1382 return GetBrowserViewLayout()->GetWebContentsModalDialogHost();
1385 ///////////////////////////////////////////////////////////////////////////////
1386 // BrowserView, BrowserWindowTesting implementation:
1388 BookmarkBarView* BrowserView::GetBookmarkBarView() const {
1389 return bookmark_bar_view_.get();
1392 LocationBarView* BrowserView::GetLocationBarView() const {
1393 return toolbar_ ? toolbar_->location_bar() : NULL;
1396 views::View* BrowserView::GetTabContentsContainerView() const {
1397 return contents_web_view_;
1400 ToolbarView* BrowserView::GetToolbarView() const {
1401 return toolbar_;
1404 ///////////////////////////////////////////////////////////////////////////////
1405 // BrowserView, TabStripModelObserver implementation:
1407 void BrowserView::TabInsertedAt(WebContents* contents,
1408 int index,
1409 bool foreground) {
1410 // WebContents inserted in tabs might not have been added to the root
1411 // window yet. Per http://crbug/342672 add them now since drawing the
1412 // WebContents requires root window specific data - information about
1413 // the screen the WebContents is drawn on, for example.
1414 if (!contents->GetNativeView()->GetRootWindow()) {
1415 aura::Window* window = contents->GetNativeView();
1416 aura::Window* root_window = GetNativeWindow()->GetRootWindow();
1417 aura::client::ParentWindowWithContext(
1418 window, root_window, root_window->GetBoundsInScreen());
1419 DCHECK(contents->GetNativeView()->GetRootWindow());
1421 web_contents_close_handler_->TabInserted();
1423 if (foreground)
1424 extensions::MaybeShowExtensionControlledNewTabPage(browser(), contents);
1427 void BrowserView::TabDetachedAt(WebContents* contents, int index) {
1428 if (PermissionBubbleManager::FromWebContents(contents))
1429 PermissionBubbleManager::FromWebContents(contents)->SetView(NULL);
1431 // We use index here rather than comparing |contents| because by this time
1432 // the model has already removed |contents| from its list, so
1433 // browser_->GetActiveWebContents() will return NULL or something else.
1434 if (index == browser_->tab_strip_model()->active_index()) {
1435 // We need to reset the current tab contents to NULL before it gets
1436 // freed. This is because the focus manager performs some operations
1437 // on the selected WebContents when it is removed.
1438 web_contents_close_handler_->ActiveTabChanged();
1439 contents_web_view_->SetWebContents(NULL);
1440 infobar_container_->ChangeInfoBarManager(NULL);
1441 UpdateDevToolsForContents(NULL, true);
1445 void BrowserView::TabDeactivated(WebContents* contents) {
1446 if (PermissionBubbleManager::FromWebContents(contents))
1447 PermissionBubbleManager::FromWebContents(contents)->SetView(NULL);
1449 // We do not store the focus when closing the tab to work-around bug 4633.
1450 // Some reports seem to show that the focus manager and/or focused view can
1451 // be garbage at that point, it is not clear why.
1452 if (!contents->IsBeingDestroyed())
1453 contents->StoreFocus();
1456 void BrowserView::TabStripEmpty() {
1457 // Make sure all optional UI is removed before we are destroyed, otherwise
1458 // there will be consequences (since our view hierarchy will still have
1459 // references to freed views).
1460 UpdateUIForContents(NULL);
1463 void BrowserView::WillCloseAllTabs() {
1464 web_contents_close_handler_->WillCloseAllTabs();
1467 void BrowserView::CloseAllTabsCanceled() {
1468 web_contents_close_handler_->CloseAllTabsCanceled();
1471 ///////////////////////////////////////////////////////////////////////////////
1472 // BrowserView, ui::AcceleratorProvider implementation:
1474 bool BrowserView::GetAcceleratorForCommandId(int command_id,
1475 ui::Accelerator* accelerator) {
1476 // Let's let the ToolbarView own the canonical implementation of this method.
1477 return toolbar_->GetAcceleratorForCommandId(command_id, accelerator);
1480 ///////////////////////////////////////////////////////////////////////////////
1481 // BrowserView, views::WidgetDelegate implementation:
1483 bool BrowserView::CanResize() const {
1484 return true;
1487 bool BrowserView::CanMaximize() const {
1488 return true;
1491 bool BrowserView::CanActivate() const {
1492 if (!AppModalDialogQueue::GetInstance()->active_dialog() ||
1493 !AppModalDialogQueue::GetInstance()->active_dialog()->native_dialog())
1494 return true;
1496 #if defined(USE_AURA) && defined(OS_CHROMEOS)
1497 // On Aura window manager controls all windows so settings focus via PostTask
1498 // will make only worse because posted task will keep trying to steal focus.
1499 AppModalDialogQueue::GetInstance()->ActivateModalDialog();
1500 #else
1501 // If another browser is app modal, flash and activate the modal browser. This
1502 // has to be done in a post task, otherwise if the user clicked on a window
1503 // that doesn't have the modal dialog the windows keep trying to get the focus
1504 // from each other on Windows. http://crbug.com/141650.
1505 base::MessageLoop::current()->PostTask(
1506 FROM_HERE,
1507 base::Bind(&BrowserView::ActivateAppModalDialog,
1508 activate_modal_dialog_factory_.GetWeakPtr()));
1509 #endif
1510 return false;
1513 base::string16 BrowserView::GetWindowTitle() const {
1514 return browser_->GetWindowTitleForCurrentTab();
1517 base::string16 BrowserView::GetAccessibleWindowTitle() const {
1518 if (IsOffTheRecord()) {
1519 return l10n_util::GetStringFUTF16(
1520 IDS_ACCESSIBLE_INCOGNITO_WINDOW_TITLE_FORMAT,
1521 GetWindowTitle());
1523 return GetWindowTitle();
1526 views::View* BrowserView::GetInitiallyFocusedView() {
1527 return NULL;
1530 bool BrowserView::ShouldShowWindowTitle() const {
1531 // For Ash only, app host windows do not show an icon, crbug.com/119411.
1532 // Child windows (i.e. popups) do show an icon.
1533 if (browser_->host_desktop_type() == chrome::HOST_DESKTOP_TYPE_ASH &&
1534 browser_->is_app() &&
1535 browser_->is_trusted_source())
1536 return false;
1538 return browser_->SupportsWindowFeature(Browser::FEATURE_TITLEBAR);
1541 gfx::ImageSkia BrowserView::GetWindowAppIcon() {
1542 if (browser_->is_app()) {
1543 WebContents* contents = browser_->tab_strip_model()->GetActiveWebContents();
1544 extensions::TabHelper* extensions_tab_helper =
1545 contents ? extensions::TabHelper::FromWebContents(contents) : NULL;
1546 if (extensions_tab_helper && extensions_tab_helper->GetExtensionAppIcon())
1547 return gfx::ImageSkia::CreateFrom1xBitmap(
1548 *extensions_tab_helper->GetExtensionAppIcon());
1551 return GetWindowIcon();
1554 gfx::ImageSkia BrowserView::GetWindowIcon() {
1555 if (browser_->is_app() || browser_->is_type_popup())
1556 return browser_->GetCurrentPageIcon().AsImageSkia();
1557 return gfx::ImageSkia();
1560 bool BrowserView::ShouldShowWindowIcon() const {
1561 // For Ash only, app host windows do not show an icon, crbug.com/119411.
1562 // Child windows (i.e. popups) do show an icon.
1563 if (browser_->host_desktop_type() == chrome::HOST_DESKTOP_TYPE_ASH &&
1564 browser_->is_app() &&
1565 browser_->is_trusted_source())
1566 return false;
1568 return browser_->SupportsWindowFeature(Browser::FEATURE_TITLEBAR);
1571 bool BrowserView::ExecuteWindowsCommand(int command_id) {
1572 // This function handles WM_SYSCOMMAND, WM_APPCOMMAND, and WM_COMMAND.
1573 #if defined(OS_WIN)
1574 if (command_id == IDC_DEBUG_FRAME_TOGGLE)
1575 GetWidget()->DebugToggleFrameType();
1576 #endif
1577 // Translate WM_APPCOMMAND command ids into a command id that the browser
1578 // knows how to handle.
1579 int command_id_from_app_command = GetCommandIDForAppCommandID(command_id);
1580 if (command_id_from_app_command != -1)
1581 command_id = command_id_from_app_command;
1583 return chrome::ExecuteCommand(browser_.get(), command_id);
1586 std::string BrowserView::GetWindowName() const {
1587 return chrome::GetWindowPlacementKey(browser_.get());
1590 void BrowserView::SaveWindowPlacement(const gfx::Rect& bounds,
1591 ui::WindowShowState show_state) {
1592 // If IsFullscreen() is true, we've just changed into fullscreen mode, and
1593 // we're catching the going-into-fullscreen sizing and positioning calls,
1594 // which we want to ignore.
1595 if (!IsFullscreen() && frame_->ShouldSaveWindowPlacement() &&
1596 chrome::ShouldSaveWindowPlacement(browser_.get())) {
1597 WidgetDelegate::SaveWindowPlacement(bounds, show_state);
1598 chrome::SaveWindowPlacement(browser_.get(), bounds, show_state);
1602 bool BrowserView::GetSavedWindowPlacement(
1603 const views::Widget* widget,
1604 gfx::Rect* bounds,
1605 ui::WindowShowState* show_state) const {
1606 chrome::GetSavedWindowBoundsAndShowState(browser_.get(), bounds, show_state);
1608 if (browser_->is_type_popup() &&
1609 !browser_->is_app() &&
1610 !browser_->is_trusted_source()) {
1611 // This is normal non-app popup window. The value passed in |bounds|
1612 // represents two pieces of information:
1613 // - the position of the window, in screen coordinates (outer position).
1614 // - the size of the content area (inner size).
1615 // We need to use these values to determine the appropriate size and
1616 // position of the resulting window.
1617 if (IsToolbarVisible()) {
1618 // If we're showing the toolbar, we need to adjust |*bounds| to include
1619 // its desired height, since the toolbar is considered part of the
1620 // window's client area as far as GetWindowBoundsForClientBounds is
1621 // concerned...
1622 bounds->set_height(
1623 bounds->height() + toolbar_->GetPreferredSize().height());
1626 gfx::Rect window_rect = frame_->non_client_view()->
1627 GetWindowBoundsForClientBounds(*bounds);
1628 window_rect.set_origin(bounds->origin());
1630 // When we are given x/y coordinates of 0 on a created popup window,
1631 // assume none were given by the window.open() command.
1632 if (window_rect.x() == 0 && window_rect.y() == 0) {
1633 gfx::Size size = window_rect.size();
1634 window_rect.set_origin(
1635 WindowSizer::GetDefaultPopupOrigin(size,
1636 browser_->host_desktop_type()));
1639 *bounds = window_rect;
1640 *show_state = ui::SHOW_STATE_NORMAL;
1643 // We return true because we can _always_ locate reasonable bounds using the
1644 // WindowSizer, and we don't want to trigger the Window's built-in "size to
1645 // default" handling because the browser window has no default preferred
1646 // size.
1647 return true;
1650 views::View* BrowserView::GetContentsView() {
1651 return contents_web_view_;
1654 views::ClientView* BrowserView::CreateClientView(views::Widget* widget) {
1655 return this;
1658 void BrowserView::OnWidgetActivationChanged(views::Widget* widget,
1659 bool active) {
1660 if (active)
1661 BrowserList::SetLastActive(browser_.get());
1664 void BrowserView::OnWindowBeginUserBoundsChange() {
1665 WebContents* web_contents = GetActiveWebContents();
1666 if (!web_contents)
1667 return;
1668 web_contents->GetRenderViewHost()->NotifyMoveOrResizeStarted();
1671 void BrowserView::OnWidgetMove() {
1672 if (!initialized_) {
1673 // Creating the widget can trigger a move. Ignore it until we've initialized
1674 // things.
1675 return;
1678 // Cancel any tabstrip animations, some of them may be invalidated by the
1679 // window being repositioned.
1680 // Comment out for one cycle to see if this fixes dist tests.
1681 // tabstrip_->DestroyDragController();
1683 // status_bubble_ may be NULL if this is invoked during construction.
1684 if (status_bubble_.get())
1685 status_bubble_->Reposition();
1687 BookmarkBubbleView::Hide();
1689 // Close the omnibox popup, if any.
1690 LocationBarView* location_bar_view = GetLocationBarView();
1691 if (location_bar_view)
1692 location_bar_view->GetOmniboxView()->CloseOmniboxPopup();
1695 views::Widget* BrowserView::GetWidget() {
1696 return View::GetWidget();
1699 const views::Widget* BrowserView::GetWidget() const {
1700 return View::GetWidget();
1703 void BrowserView::GetAccessiblePanes(std::vector<views::View*>* panes) {
1704 // This should be in the order of pane traversal of the panes using F6
1705 // (Windows) or Ctrl+Back/Forward (Chrome OS). If one of these is
1706 // invisible or has no focusable children, it will be automatically
1707 // skipped.
1708 panes->push_back(toolbar_);
1709 if (bookmark_bar_view_.get())
1710 panes->push_back(bookmark_bar_view_.get());
1711 if (infobar_container_)
1712 panes->push_back(infobar_container_);
1713 if (download_shelf_.get())
1714 panes->push_back(download_shelf_.get());
1715 panes->push_back(GetTabContentsContainerView());
1716 if (devtools_web_view_->visible())
1717 panes->push_back(devtools_web_view_);
1720 ///////////////////////////////////////////////////////////////////////////////
1721 // BrowserView, views::ClientView overrides:
1723 bool BrowserView::CanClose() {
1724 // You cannot close a frame for which there is an active originating drag
1725 // session.
1726 if (tabstrip_ && !tabstrip_->IsTabStripCloseable())
1727 return false;
1729 // Give beforeunload handlers the chance to cancel the close before we hide
1730 // the window below.
1731 if (!browser_->ShouldCloseWindow())
1732 return false;
1734 bool fast_tab_closing_enabled =
1735 CommandLine::ForCurrentProcess()->HasSwitch(switches::kEnableFastUnload);
1737 if (!browser_->tab_strip_model()->empty()) {
1738 // Tab strip isn't empty. Hide the frame (so it appears to have closed
1739 // immediately) and close all the tabs, allowing the renderers to shut
1740 // down. When the tab strip is empty we'll be called back again.
1741 frame_->Hide();
1742 browser_->OnWindowClosing();
1743 if (fast_tab_closing_enabled)
1744 browser_->tab_strip_model()->CloseAllTabs();
1745 return false;
1746 } else if (fast_tab_closing_enabled &&
1747 !browser_->HasCompletedUnloadProcessing()) {
1748 // The browser needs to finish running unload handlers.
1749 // Hide the frame (so it appears to have closed immediately), and
1750 // the browser will call us back again when it is ready to close.
1751 frame_->Hide();
1752 return false;
1755 // Empty TabStripModel, it's now safe to allow the Window to be closed.
1756 content::NotificationService::current()->Notify(
1757 chrome::NOTIFICATION_WINDOW_CLOSED,
1758 content::Source<gfx::NativeWindow>(frame_->GetNativeWindow()),
1759 content::NotificationService::NoDetails());
1760 return true;
1763 int BrowserView::NonClientHitTest(const gfx::Point& point) {
1764 return GetBrowserViewLayout()->NonClientHitTest(point);
1767 gfx::Size BrowserView::GetMinimumSize() const {
1768 return GetBrowserViewLayout()->GetMinimumSize();
1771 ///////////////////////////////////////////////////////////////////////////////
1772 // BrowserView, views::View overrides:
1774 const char* BrowserView::GetClassName() const {
1775 return kViewClassName;
1778 void BrowserView::Layout() {
1779 if (!initialized_ || in_process_fullscreen_)
1780 return;
1782 views::View::Layout();
1784 // TODO(jamescook): Why was this in the middle of layout code?
1785 toolbar_->location_bar()->omnibox_view()->SetFocusable(IsToolbarVisible());
1788 void BrowserView::PaintChildren(gfx::Canvas* canvas,
1789 const views::CullSet& cull_set) {
1790 // Paint the |infobar_container_| last so that it may paint its
1791 // overlapping tabs.
1792 for (int i = 0; i < child_count(); ++i) {
1793 View* child = child_at(i);
1794 if (child != infobar_container_ && !child->layer())
1795 child->Paint(canvas, cull_set);
1798 infobar_container_->Paint(canvas, cull_set);
1801 void BrowserView::ViewHierarchyChanged(
1802 const ViewHierarchyChangedDetails& details) {
1803 if (!initialized_ && details.is_add && details.child == this && GetWidget()) {
1804 InitViews();
1805 initialized_ = true;
1809 void BrowserView::ChildPreferredSizeChanged(View* child) {
1810 Layout();
1813 void BrowserView::GetAccessibleState(ui::AXViewState* state) {
1814 state->role = ui::AX_ROLE_CLIENT;
1817 void BrowserView::OnNativeThemeChanged(const ui::NativeTheme* theme) {
1818 // Do not handle native theme changes before the browser view is initialized.
1819 if (!initialized_)
1820 return;
1821 ClientView::OnNativeThemeChanged(theme);
1822 UserChangedTheme();
1823 chrome::MaybeShowInvertBubbleView(this);
1826 ///////////////////////////////////////////////////////////////////////////////
1827 // BrowserView, ui::AcceleratorTarget overrides:
1829 bool BrowserView::AcceleratorPressed(const ui::Accelerator& accelerator) {
1830 #if defined(OS_CHROMEOS)
1831 // If accessibility is enabled, stop speech and return false so that key
1832 // combinations involving Search can be used for extra accessibility
1833 // functionality.
1834 if (accelerator.key_code() == ui::VKEY_LWIN &&
1835 g_browser_process->local_state()->GetBoolean(
1836 prefs::kSpokenFeedbackEnabled)) {
1837 TtsController::GetInstance()->Stop();
1838 return false;
1840 #endif
1842 std::map<ui::Accelerator, int>::const_iterator iter =
1843 accelerator_table_.find(accelerator);
1844 DCHECK(iter != accelerator_table_.end());
1845 int command_id = iter->second;
1847 chrome::BrowserCommandController* controller = browser_->command_controller();
1848 if (!controller->block_command_execution())
1849 UpdateAcceleratorMetrics(accelerator, command_id);
1850 return chrome::ExecuteCommand(browser_.get(), command_id);
1853 ///////////////////////////////////////////////////////////////////////////////
1854 // BrowserView, OmniboxPopupModelObserver overrides:
1855 void BrowserView::OnOmniboxPopupShownOrHidden() {
1856 infobar_container_->SetMaxTopArrowHeight(GetMaxTopInfoBarArrowHeight());
1859 ///////////////////////////////////////////////////////////////////////////////
1860 // BrowserView, InfoBarContainer::Delegate overrides:
1862 SkColor BrowserView::GetInfoBarSeparatorColor() const {
1863 // NOTE: Keep this in sync with ToolbarView::OnPaint()!
1864 return (IsTabStripVisible() || !frame_->ShouldUseNativeFrame()) ?
1865 ThemeProperties::GetDefaultColor(
1866 ThemeProperties::COLOR_TOOLBAR_SEPARATOR) :
1867 SK_ColorBLACK;
1870 void BrowserView::InfoBarContainerStateChanged(bool is_animating) {
1871 ToolbarSizeChanged(is_animating);
1874 bool BrowserView::DrawInfoBarArrows(int* x) const {
1875 if (x) {
1876 gfx::Point anchor(toolbar_->location_bar()->GetLocationBarAnchorPoint());
1877 ConvertPointToTarget(toolbar_->location_bar(), this, &anchor);
1878 *x = anchor.x();
1880 return true;
1883 void BrowserView::InitViews() {
1884 GetWidget()->AddObserver(this);
1886 // Stow a pointer to this object onto the window handle so that we can get at
1887 // it later when all we have is a native view.
1888 GetWidget()->SetNativeWindowProperty(kBrowserViewKey, this);
1890 // Stow a pointer to the browser's profile onto the window handle so that we
1891 // can get it later when all we have is a native view.
1892 GetWidget()->SetNativeWindowProperty(Profile::kProfileKey,
1893 browser_->profile());
1895 // Start a hung plugin window detector for this browser object (as long as
1896 // hang detection is not disabled).
1897 if (!CommandLine::ForCurrentProcess()->HasSwitch(
1898 switches::kDisableHangMonitor)) {
1899 InitHangMonitor();
1902 LoadAccelerators();
1904 infobar_container_ = new InfoBarContainerView(this);
1905 AddChildView(infobar_container_);
1907 contents_web_view_ = new ContentsWebView(browser_->profile());
1908 contents_web_view_->set_id(VIEW_ID_TAB_CONTAINER);
1909 contents_web_view_->SetEmbedFullscreenWidgetMode(
1910 implicit_cast<content::WebContentsDelegate*>(browser_.get())->
1911 EmbedsFullscreenWidget());
1913 web_contents_close_handler_.reset(
1914 new WebContentsCloseHandler(contents_web_view_));
1916 devtools_web_view_ = new views::WebView(browser_->profile());
1917 devtools_web_view_->set_id(VIEW_ID_DEV_TOOLS_DOCKED);
1918 devtools_web_view_->SetVisible(false);
1920 contents_container_ = new views::View();
1921 contents_container_->set_background(views::Background::CreateSolidBackground(
1922 ThemeProperties::GetDefaultColor(
1923 ThemeProperties::COLOR_CONTROL_BACKGROUND)));
1924 contents_container_->AddChildView(devtools_web_view_);
1925 contents_container_->AddChildView(contents_web_view_);
1926 contents_container_->SetLayoutManager(new ContentsLayoutManager(
1927 devtools_web_view_, contents_web_view_));
1928 AddChildView(contents_container_);
1929 set_contents_view(contents_container_);
1931 // Top container holds tab strip and toolbar and lives at the front of the
1932 // view hierarchy.
1933 top_container_ = new TopContainerView(this);
1934 AddChildView(top_container_);
1936 // TabStrip takes ownership of the controller.
1937 BrowserTabStripController* tabstrip_controller =
1938 new BrowserTabStripController(browser_.get(),
1939 browser_->tab_strip_model());
1940 tabstrip_ = new TabStrip(tabstrip_controller);
1941 top_container_->AddChildView(tabstrip_);
1942 tabstrip_controller->InitFromModel(tabstrip_);
1944 toolbar_ = new ToolbarView(browser_.get());
1945 top_container_->AddChildView(toolbar_);
1946 toolbar_->Init();
1948 InitStatusBubble();
1949 InitPermissionBubbleView();
1951 // Create do-nothing view for the sake of controlling the z-order of the find
1952 // bar widget.
1953 find_bar_host_view_ = new View();
1954 AddChildView(find_bar_host_view_);
1956 immersive_mode_controller_->Init(this);
1958 BrowserViewLayout* browser_view_layout = new BrowserViewLayout;
1959 browser_view_layout->Init(new BrowserViewLayoutDelegateImpl(this),
1960 browser(),
1961 this,
1962 top_container_,
1963 tabstrip_,
1964 toolbar_,
1965 infobar_container_,
1966 contents_container_,
1967 GetContentsLayoutManager(),
1968 immersive_mode_controller_.get());
1969 SetLayoutManager(browser_view_layout);
1971 #if defined(OS_WIN)
1972 // Create a custom JumpList and add it to an observer of TabRestoreService
1973 // so we can update the custom JumpList when a tab is added or removed.
1974 if (JumpList::Enabled()) {
1975 load_complete_listener_.reset(new LoadCompleteListener(this));
1977 #endif
1979 GetLocationBar()->GetOmniboxView()->model()->popup_model()->AddObserver(this);
1982 void BrowserView::LoadingAnimationCallback() {
1983 base::TimeTicks now = base::TimeTicks::Now();
1984 if (!last_animation_time_.is_null()) {
1985 UMA_HISTOGRAM_TIMES(
1986 "Tabs.LoadingAnimationTime",
1987 now - last_animation_time_);
1989 last_animation_time_ = now;
1990 if (browser_->is_type_tabbed()) {
1991 // Loading animations are shown in the tab for tabbed windows. We check the
1992 // browser type instead of calling IsTabStripVisible() because the latter
1993 // will return false for fullscreen windows, but we still need to update
1994 // their animations (so that when they come out of fullscreen mode they'll
1995 // be correct).
1996 tabstrip_->UpdateLoadingAnimations();
1997 } else if (ShouldShowWindowIcon()) {
1998 // ... or in the window icon area for popups and app windows.
1999 WebContents* web_contents =
2000 browser_->tab_strip_model()->GetActiveWebContents();
2001 // GetActiveWebContents can return NULL for example under Purify when
2002 // the animations are running slowly and this function is called on a timer
2003 // through LoadingAnimationCallback.
2004 frame_->UpdateThrobber(web_contents && web_contents->IsLoading());
2008 void BrowserView::OnLoadCompleted() {
2009 #if defined(OS_WIN)
2010 DCHECK(!jumplist_);
2011 jumplist_ = new JumpList();
2012 jumplist_->AddObserver(browser_->profile());
2013 #endif
2016 BrowserViewLayout* BrowserView::GetBrowserViewLayout() const {
2017 return static_cast<BrowserViewLayout*>(GetLayoutManager());
2020 ContentsLayoutManager* BrowserView::GetContentsLayoutManager() const {
2021 return static_cast<ContentsLayoutManager*>(
2022 contents_container_->GetLayoutManager());
2025 bool BrowserView::MaybeShowBookmarkBar(WebContents* contents) {
2026 bool show_bookmark_bar = contents &&
2027 browser_->SupportsWindowFeature(Browser::FEATURE_BOOKMARKBAR);
2028 if (!show_bookmark_bar && !bookmark_bar_view_.get())
2029 return false;
2030 if (!bookmark_bar_view_.get()) {
2031 bookmark_bar_view_.reset(new BookmarkBarView(browser_.get(), this));
2032 bookmark_bar_view_->set_owned_by_client();
2033 bookmark_bar_view_->set_background(
2034 new BookmarkExtensionBackground(this,
2035 bookmark_bar_view_.get(),
2036 browser_.get()));
2037 bookmark_bar_view_->SetBookmarkBarState(
2038 browser_->bookmark_bar_state(),
2039 BookmarkBar::DONT_ANIMATE_STATE_CHANGE);
2040 GetBrowserViewLayout()->set_bookmark_bar(bookmark_bar_view_.get());
2042 bookmark_bar_view_->SetVisible(show_bookmark_bar);
2043 bookmark_bar_view_->SetPageNavigator(contents);
2045 // Update parenting for the bookmark bar. This may detach it from all views.
2046 bool needs_layout = false;
2047 views::View* new_parent = NULL;
2048 if (show_bookmark_bar) {
2049 if (bookmark_bar_view_->IsDetached())
2050 new_parent = this;
2051 else
2052 new_parent = top_container_;
2054 if (new_parent != bookmark_bar_view_->parent()) {
2055 SetBookmarkBarParent(new_parent);
2056 needs_layout = true;
2059 // Check for updates to the desired size.
2060 if (bookmark_bar_view_->GetPreferredSize().height() !=
2061 bookmark_bar_view_->height())
2062 needs_layout = true;
2064 return needs_layout;
2067 void BrowserView::SetBookmarkBarParent(views::View* new_parent) {
2068 if (new_parent == this) {
2069 // Add it underneath |top_container_| or at the end if top container isn't
2070 // found.
2071 int top_container_index = GetIndexOf(top_container_);
2072 if (top_container_index >= 0)
2073 AddChildViewAt(bookmark_bar_view_.get(), top_container_index);
2074 else
2075 AddChildView(bookmark_bar_view_.get());
2076 } else if (new_parent) {
2077 // No special stacking is required for other parents.
2078 new_parent->AddChildView(bookmark_bar_view_.get());
2079 } else {
2080 // Bookmark bar is being detached from all views because it is hidden.
2081 bookmark_bar_view_->parent()->RemoveChildView(bookmark_bar_view_.get());
2085 bool BrowserView::MaybeShowInfoBar(WebContents* contents) {
2086 // TODO(beng): Remove this function once the interface between
2087 // InfoBarContainer, DownloadShelfView and WebContents and this
2088 // view is sorted out.
2089 return true;
2092 void BrowserView::UpdateDevToolsForContents(
2093 WebContents* web_contents, bool update_devtools_web_contents) {
2094 DevToolsWindow* new_devtools_window = web_contents ?
2095 DevToolsWindow::GetDockedInstanceForInspectedTab(web_contents) : NULL;
2097 // Replace devtools WebContents.
2098 WebContents* new_contents = new_devtools_window ?
2099 new_devtools_window->web_contents() : NULL;
2100 if (devtools_web_view_->web_contents() != new_contents &&
2101 update_devtools_web_contents) {
2102 devtools_web_view_->SetWebContents(new_contents);
2105 if (!devtools_window_ && new_devtools_window &&
2106 !devtools_focus_tracker_.get()) {
2107 // Install devtools focus tracker when dev tools window is shown for the
2108 // first time.
2109 devtools_focus_tracker_.reset(
2110 new views::ExternalFocusTracker(devtools_web_view_,
2111 GetFocusManager()));
2114 // Restore focus to the last focused view when hiding devtools window.
2115 if (devtools_window_ && !new_devtools_window &&
2116 devtools_focus_tracker_.get()) {
2117 devtools_focus_tracker_->FocusLastFocusedExternalView();
2118 devtools_focus_tracker_.reset();
2121 devtools_window_ = new_devtools_window;
2122 if (devtools_window_) {
2123 devtools_web_view_->SetPreferredSize(devtools_window_->GetMinimumSize());
2124 devtools_web_view_->SetVisible(true);
2125 GetContentsLayoutManager()->SetContentsResizingStrategy(
2126 devtools_window_->GetContentsResizingStrategy());
2127 } else {
2128 devtools_web_view_->SetVisible(false);
2129 GetContentsLayoutManager()->SetContentsResizingStrategy(
2130 DevToolsContentsResizingStrategy());
2132 contents_container_->Layout();
2135 void BrowserView::UpdateUIForContents(WebContents* contents) {
2136 bool needs_layout = MaybeShowBookmarkBar(contents);
2137 // TODO(jamescook): This function always returns true. Remove it and figure
2138 // out when layout is actually required.
2139 needs_layout |= MaybeShowInfoBar(contents);
2140 if (needs_layout)
2141 Layout();
2144 void BrowserView::ProcessFullscreen(bool fullscreen,
2145 FullscreenMode mode,
2146 const GURL& url,
2147 FullscreenExitBubbleType bubble_type) {
2148 if (in_process_fullscreen_)
2149 return;
2150 in_process_fullscreen_ = true;
2152 // Reduce jankiness during the following position changes by:
2153 // * Hiding the window until it's in the final position
2154 // * Ignoring all intervening Layout() calls, which resize the webpage and
2155 // thus are slow and look ugly (enforced via |in_process_fullscreen_|).
2156 LocationBarView* location_bar = GetLocationBarView();
2158 if (mode == METRO_SNAP_FULLSCREEN || !fullscreen) {
2159 // Hide the fullscreen bubble as soon as possible, since the mode toggle can
2160 // take enough time for the user to notice.
2161 fullscreen_bubble_.reset();
2164 if (fullscreen) {
2165 // Move focus out of the location bar if necessary.
2166 views::FocusManager* focus_manager = GetFocusManager();
2167 DCHECK(focus_manager);
2168 // Look for focus in the location bar itself or any child view.
2169 if (location_bar->Contains(focus_manager->GetFocusedView()))
2170 focus_manager->ClearFocus();
2173 // Toggle fullscreen mode.
2174 frame_->SetFullscreen(fullscreen);
2176 // Enable immersive before the browser refreshes its list of enabled commands.
2177 if (mode != METRO_SNAP_FULLSCREEN && ShouldUseImmersiveFullscreenForUrl(url))
2178 immersive_mode_controller_->SetEnabled(fullscreen);
2180 browser_->WindowFullscreenStateChanged();
2182 if (fullscreen && !chrome::IsRunningInAppMode() &&
2183 mode != METRO_SNAP_FULLSCREEN) {
2184 UpdateFullscreenExitBubbleContent(url, bubble_type);
2187 // Undo our anti-jankiness hacks and force a re-layout. We also need to
2188 // recompute the height of the infobar top arrow because toggling in and out
2189 // of fullscreen changes it. Calling ToolbarSizeChanged() will do both these
2190 // things since it computes the arrow height directly and forces a layout
2191 // indirectly via UpdateUIForContents(). Reset |in_process_fullscreen_| in
2192 // order to let the layout occur.
2193 in_process_fullscreen_ = false;
2194 ToolbarSizeChanged(false);
2197 bool BrowserView::ShouldUseImmersiveFullscreenForUrl(const GURL& url) const {
2198 // Kiosk mode needs the whole screen, and if we're not in an Ash desktop
2199 // immersive fullscreen doesn't exist.
2200 if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kKioskMode) ||
2201 browser()->host_desktop_type() != chrome::HOST_DESKTOP_TYPE_ASH) {
2202 return false;
2205 return url.is_empty();
2208 void BrowserView::LoadAccelerators() {
2209 views::FocusManager* focus_manager = GetFocusManager();
2210 DCHECK(focus_manager);
2212 // Let's fill our own accelerator table.
2213 const bool is_app_mode = chrome::IsRunningInForcedAppMode();
2214 const std::vector<chrome::AcceleratorMapping> accelerator_list(
2215 chrome::GetAcceleratorList());
2216 for (std::vector<chrome::AcceleratorMapping>::const_iterator it =
2217 accelerator_list.begin(); it != accelerator_list.end(); ++it) {
2218 // In app mode, only allow accelerators of white listed commands to pass
2219 // through.
2220 if (is_app_mode && !chrome::IsCommandAllowedInAppMode(it->command_id))
2221 continue;
2223 ui::Accelerator accelerator(it->keycode, it->modifiers);
2224 accelerator_table_[accelerator] = it->command_id;
2226 // Also register with the focus manager.
2227 focus_manager->RegisterAccelerator(
2228 accelerator, ui::AcceleratorManager::kNormalPriority, this);
2232 int BrowserView::GetCommandIDForAppCommandID(int app_command_id) const {
2233 #if defined(OS_WIN)
2234 switch (app_command_id) {
2235 // NOTE: The order here matches the APPCOMMAND declaration order in the
2236 // Windows headers.
2237 case APPCOMMAND_BROWSER_BACKWARD: return IDC_BACK;
2238 case APPCOMMAND_BROWSER_FORWARD: return IDC_FORWARD;
2239 case APPCOMMAND_BROWSER_REFRESH: return IDC_RELOAD;
2240 case APPCOMMAND_BROWSER_HOME: return IDC_HOME;
2241 case APPCOMMAND_BROWSER_STOP: return IDC_STOP;
2242 case APPCOMMAND_BROWSER_SEARCH: return IDC_FOCUS_SEARCH;
2243 case APPCOMMAND_HELP: return IDC_HELP_PAGE_VIA_KEYBOARD;
2244 case APPCOMMAND_NEW: return IDC_NEW_TAB;
2245 case APPCOMMAND_OPEN: return IDC_OPEN_FILE;
2246 case APPCOMMAND_CLOSE: return IDC_CLOSE_TAB;
2247 case APPCOMMAND_SAVE: return IDC_SAVE_PAGE;
2248 case APPCOMMAND_PRINT: return IDC_PRINT;
2249 case APPCOMMAND_COPY: return IDC_COPY;
2250 case APPCOMMAND_CUT: return IDC_CUT;
2251 case APPCOMMAND_PASTE: return IDC_PASTE;
2253 // TODO(pkasting): http://b/1113069 Handle these.
2254 case APPCOMMAND_UNDO:
2255 case APPCOMMAND_REDO:
2256 case APPCOMMAND_SPELL_CHECK:
2257 default: return -1;
2259 #else
2260 // App commands are Windows-specific so there's nothing to do here.
2261 return -1;
2262 #endif
2265 void BrowserView::InitHangMonitor() {
2266 #if defined(OS_WIN)
2267 PrefService* pref_service = g_browser_process->local_state();
2268 if (!pref_service)
2269 return;
2271 int plugin_message_response_timeout =
2272 pref_service->GetInteger(prefs::kPluginMessageResponseTimeout);
2273 int hung_plugin_detect_freq =
2274 pref_service->GetInteger(prefs::kHungPluginDetectFrequency);
2275 HWND window = GetWidget()->GetNativeView()->GetHost()->
2276 GetAcceleratedWidget();
2277 if ((hung_plugin_detect_freq > 0) &&
2278 hung_window_detector_.Initialize(window,
2279 plugin_message_response_timeout)) {
2280 ticker_.set_tick_interval(hung_plugin_detect_freq);
2281 ticker_.RegisterTickHandler(&hung_window_detector_);
2282 ticker_.Start();
2284 pref_service->SetInteger(prefs::kPluginMessageResponseTimeout,
2285 plugin_message_response_timeout);
2286 pref_service->SetInteger(prefs::kHungPluginDetectFrequency,
2287 hung_plugin_detect_freq);
2289 #endif
2292 void BrowserView::UpdateAcceleratorMetrics(const ui::Accelerator& accelerator,
2293 int command_id) {
2294 const ui::KeyboardCode key_code = accelerator.key_code();
2295 if (command_id == IDC_HELP_PAGE_VIA_KEYBOARD && key_code == ui::VKEY_F1)
2296 content::RecordAction(UserMetricsAction("ShowHelpTabViaF1"));
2298 if (command_id == IDC_BOOKMARK_PAGE)
2299 UMA_HISTOGRAM_ENUMERATION("Bookmarks.EntryPoint",
2300 BOOKMARK_ENTRY_POINT_ACCELERATOR,
2301 BOOKMARK_ENTRY_POINT_LIMIT);
2303 #if defined(OS_CHROMEOS)
2304 // Collect information about the relative popularity of various accelerators
2305 // on Chrome OS.
2306 switch (command_id) {
2307 case IDC_BACK:
2308 if (key_code == ui::VKEY_BACK)
2309 content::RecordAction(UserMetricsAction("Accel_Back_Backspace"));
2310 else if (key_code == ui::VKEY_BROWSER_BACK)
2311 content::RecordAction(UserMetricsAction("Accel_Back_F1"));
2312 else if (key_code == ui::VKEY_LEFT)
2313 content::RecordAction(UserMetricsAction("Accel_Back_Left"));
2314 break;
2315 case IDC_FORWARD:
2316 if (key_code == ui::VKEY_BACK)
2317 content::RecordAction(UserMetricsAction("Accel_Forward_Backspace"));
2318 else if (key_code == ui::VKEY_BROWSER_FORWARD)
2319 content::RecordAction(UserMetricsAction("Accel_Forward_F2"));
2320 else if (key_code == ui::VKEY_RIGHT)
2321 content::RecordAction(UserMetricsAction("Accel_Forward_Right"));
2322 break;
2323 case IDC_RELOAD:
2324 case IDC_RELOAD_IGNORING_CACHE:
2325 if (key_code == ui::VKEY_R)
2326 content::RecordAction(UserMetricsAction("Accel_Reload_R"));
2327 else if (key_code == ui::VKEY_BROWSER_REFRESH)
2328 content::RecordAction(UserMetricsAction("Accel_Reload_F3"));
2329 break;
2330 case IDC_FOCUS_LOCATION:
2331 if (key_code == ui::VKEY_D)
2332 content::RecordAction(UserMetricsAction("Accel_FocusLocation_D"));
2333 else if (key_code == ui::VKEY_L)
2334 content::RecordAction(UserMetricsAction("Accel_FocusLocation_L"));
2335 break;
2336 case IDC_FOCUS_SEARCH:
2337 if (key_code == ui::VKEY_E)
2338 content::RecordAction(UserMetricsAction("Accel_FocusSearch_E"));
2339 else if (key_code == ui::VKEY_K)
2340 content::RecordAction(UserMetricsAction("Accel_FocusSearch_K"));
2341 break;
2342 default:
2343 // Do nothing.
2344 break;
2346 #endif
2349 // static
2350 BrowserWindow* BrowserWindow::CreateBrowserWindow(Browser* browser) {
2351 // Create the view and the frame. The frame will attach itself via the view
2352 // so we don't need to do anything with the pointer.
2353 BrowserView* view = new BrowserView();
2354 view->Init(browser);
2355 (new BrowserFrame(view))->InitBrowserFrame();
2356 view->GetWidget()->non_client_view()->SetAccessibleName(
2357 l10n_util::GetStringUTF16(IDS_PRODUCT_NAME));
2358 return view;
2361 // static
2362 chrome::HostDesktopType BrowserWindow::AdjustHostDesktopType(
2363 chrome::HostDesktopType desktop_type) {
2364 return NativeBrowserFrameFactory::AdjustHostDesktopType(desktop_type);
2367 void BrowserView::ShowAvatarBubble(WebContents* web_contents,
2368 const gfx::Rect& rect) {
2369 gfx::Point origin(rect.origin());
2370 views::View::ConvertPointToScreen(GetTabContentsContainerView(), &origin);
2371 gfx::Rect bounds(origin, rect.size());
2373 AvatarMenuBubbleView::ShowBubble(
2374 this, views::BubbleBorder::TOP_RIGHT, views::BubbleBorder::PAINT_NORMAL,
2375 views::BubbleBorder::ALIGN_EDGE_TO_ANCHOR_EDGE, bounds, browser_.get());
2378 void BrowserView::ShowAvatarBubbleFromAvatarButton(AvatarBubbleMode mode) {
2379 if (switches::IsNewAvatarMenu()) {
2380 NewAvatarButton* button = frame_->GetNewAvatarMenuButton();
2381 if (button) {
2382 gfx::Point origin;
2383 views::View::ConvertPointToScreen(button, &origin);
2384 gfx::Rect bounds(origin, size());
2386 ProfileChooserView::BubbleViewMode view_mode =
2387 (mode == BrowserWindow::AVATAR_BUBBLE_MODE_ACCOUNT_MANAGEMENT) ?
2388 ProfileChooserView::BUBBLE_VIEW_MODE_ACCOUNT_MANAGEMENT :
2389 ProfileChooserView::BUBBLE_VIEW_MODE_PROFILE_CHOOSER;
2390 ProfileChooserView::ShowBubble(
2391 view_mode, button, views::BubbleBorder::TOP_RIGHT,
2392 views::BubbleBorder::ALIGN_EDGE_TO_ANCHOR_EDGE, bounds, browser());
2394 } else {
2395 views::BubbleBorder::Arrow arrow = views::BubbleBorder::TOP_RIGHT;
2396 views::View* anchor_view = frame_->GetAvatarMenuButton();
2397 if (!anchor_view)
2398 anchor_view = toolbar_->app_menu();
2399 else if (!frame_->GetAvatarMenuButton()->button_on_right())
2400 arrow = views::BubbleBorder::TOP_LEFT;
2401 gfx::Point origin;
2402 views::View::ConvertPointToScreen(anchor_view, &origin);
2403 gfx::Rect bounds(origin, anchor_view->size());
2404 views::BubbleBorder::ArrowPaintType arrow_paint_type =
2405 ShouldHideUIForFullscreen() ? views::BubbleBorder::PAINT_TRANSPARENT :
2406 views::BubbleBorder::PAINT_NORMAL;
2407 AvatarMenuBubbleView::ShowBubble(anchor_view, arrow, arrow_paint_type,
2408 views::BubbleBorder::ALIGN_ARROW_TO_MID_ANCHOR, bounds, browser());
2409 ProfileMetrics::LogProfileOpenMethod(ProfileMetrics::ICON_AVATAR_BUBBLE);
2413 void BrowserView::ShowPasswordGenerationBubble(
2414 const gfx::Rect& rect,
2415 const autofill::PasswordForm& form,
2416 autofill::PasswordGenerator* password_generator) {
2417 // Create a rect in the content bounds that the bubble will point to.
2418 gfx::Point origin(rect.origin());
2419 views::View::ConvertPointToScreen(GetTabContentsContainerView(), &origin);
2420 gfx::Rect bounds(origin, rect.size());
2422 // Create the bubble.
2423 WebContents* web_contents = GetActiveWebContents();
2424 if (!web_contents)
2425 return;
2427 PasswordGenerationBubbleView* bubble = new PasswordGenerationBubbleView(
2428 form,
2429 bounds,
2430 this,
2431 web_contents->GetRenderViewHost(),
2432 ChromePasswordManagerClient::GetManagerFromWebContents(web_contents),
2433 password_generator,
2434 GetWidget()->GetThemeProvider());
2436 views::BubbleDelegateView::CreateBubble(bubble);
2437 bubble->SetAlignment(views::BubbleBorder::ALIGN_ARROW_TO_MID_ANCHOR);
2438 bubble->GetWidget()->Show();
2441 void BrowserView::OverscrollUpdate(int delta_y) {
2442 if (scroll_end_effect_controller_)
2443 scroll_end_effect_controller_->OverscrollUpdate(delta_y);
2446 int BrowserView::GetRenderViewHeightInsetWithDetachedBookmarkBar() {
2447 if (browser_->bookmark_bar_state() != BookmarkBar::DETACHED ||
2448 !bookmark_bar_view_.get() || !bookmark_bar_view_->IsDetached()) {
2449 return 0;
2451 // Don't use bookmark_bar_view_->height() which won't be the final height if
2452 // the bookmark bar is animating.
2453 return chrome::kNTPBookmarkBarHeight -
2454 bookmark_bar_view_->GetFullyDetachedToolbarOverlap();
2457 void BrowserView::ExecuteExtensionCommand(
2458 const extensions::Extension* extension,
2459 const extensions::Command& command) {
2460 toolbar_->ExecuteExtensionCommand(extension, command);
2463 void BrowserView::ShowPageActionPopup(
2464 const extensions::Extension* extension) {
2465 toolbar_->ShowPageActionPopup(extension);
2468 void BrowserView::ShowBrowserActionPopup(
2469 const extensions::Extension* extension) {
2470 toolbar_->ShowBrowserActionPopup(extension);
2473 void BrowserView::DoCutCopyPaste(void (WebContents::*method)(),
2474 int command_id) {
2475 WebContents* contents = browser_->tab_strip_model()->GetActiveWebContents();
2476 if (!contents)
2477 return;
2478 if (DoCutCopyPasteForWebContents(contents, method))
2479 return;
2481 DevToolsWindow* devtools_window =
2482 DevToolsWindow::GetDockedInstanceForInspectedTab(contents);
2483 if (devtools_window &&
2484 DoCutCopyPasteForWebContents(devtools_window->web_contents(), method)) {
2485 return;
2488 views::FocusManager* focus_manager = GetFocusManager();
2489 views::View* focused = focus_manager->GetFocusedView();
2490 if (focused &&
2491 (!strcmp(focused->GetClassName(), views::Textfield::kViewClassName) ||
2492 !strcmp(focused->GetClassName(), OmniboxViewViews::kViewClassName))) {
2493 views::Textfield* textfield = static_cast<views::Textfield*>(focused);
2494 textfield->ExecuteCommand(command_id);
2498 bool BrowserView::DoCutCopyPasteForWebContents(
2499 WebContents* contents,
2500 void (WebContents::*method)()) {
2501 gfx::NativeView native_view = contents->GetContentNativeView();
2502 if (!native_view)
2503 return false;
2504 if (native_view->HasFocus()) {
2505 (contents->*method)();
2506 return true;
2509 return false;
2512 void BrowserView::ActivateAppModalDialog() const {
2513 // If another browser is app modal, flash and activate the modal browser.
2514 AppModalDialog* active_dialog =
2515 AppModalDialogQueue::GetInstance()->active_dialog();
2516 if (!active_dialog)
2517 return;
2519 Browser* modal_browser =
2520 chrome::FindBrowserWithWebContents(active_dialog->web_contents());
2521 if (modal_browser && (browser_ != modal_browser)) {
2522 modal_browser->window()->FlashFrame(true);
2523 modal_browser->window()->Activate();
2526 AppModalDialogQueue::GetInstance()->ActivateModalDialog();
2529 int BrowserView::GetMaxTopInfoBarArrowHeight() {
2530 int top_arrow_height = 0;
2531 // Only show the arrows when not in fullscreen and when there's no omnibox
2532 // popup.
2533 if (!IsFullscreen() &&
2534 !GetLocationBar()->GetOmniboxView()->model()->popup_model()->IsOpen()) {
2535 gfx::Point icon_bottom(
2536 toolbar_->location_bar()->GetLocationBarAnchorPoint());
2537 ConvertPointToTarget(toolbar_->location_bar(), this, &icon_bottom);
2538 gfx::Point infobar_top(0, infobar_container_->GetVerticalOverlap(NULL));
2539 ConvertPointToTarget(infobar_container_, this, &infobar_top);
2540 top_arrow_height = infobar_top.y() - icon_bottom.y();
2542 return top_arrow_height;