browser_view.cc revision ca12bfac764ba476d6cd062bf1dde12cc64c3f40
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. 4 5#include "chrome/browser/ui/views/frame/browser_view.h" 6 7#include <algorithm> 8 9#include "base/auto_reset.h" 10#include "base/command_line.h" 11#include "base/i18n/rtl.h" 12#include "base/metrics/histogram.h" 13#include "base/prefs/pref_service.h" 14#include "base/strings/string_number_conversions.h" 15#include "base/strings/utf_string_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_utils.h" 20#include "chrome/browser/browser_process.h" 21#include "chrome/browser/chrome_notification_types.h" 22#include "chrome/browser/extensions/tab_helper.h" 23#include "chrome/browser/infobars/infobar_service.h" 24#include "chrome/browser/native_window_notification_source.h" 25#include "chrome/browser/password_manager/password_manager.h" 26#include "chrome/browser/profiles/avatar_menu_model.h" 27#include "chrome/browser/profiles/profile.h" 28#include "chrome/browser/profiles/profile_info_cache.h" 29#include "chrome/browser/profiles/profile_manager.h" 30#include "chrome/browser/search/search.h" 31#include "chrome/browser/sessions/tab_restore_service.h" 32#include "chrome/browser/sessions/tab_restore_service_factory.h" 33#include "chrome/browser/speech/tts_controller.h" 34#include "chrome/browser/themes/theme_properties.h" 35#include "chrome/browser/themes/theme_service_factory.h" 36#include "chrome/browser/ui/app_modal_dialogs/app_modal_dialog.h" 37#include "chrome/browser/ui/app_modal_dialogs/app_modal_dialog_queue.h" 38#include "chrome/browser/ui/bookmarks/bookmark_bubble_delegate.h" 39#include "chrome/browser/ui/bookmarks/bookmark_bubble_sign_in_delegate.h" 40#include "chrome/browser/ui/bookmarks/bookmark_utils.h" 41#include "chrome/browser/ui/browser.h" 42#include "chrome/browser/ui/browser_command_controller.h" 43#include "chrome/browser/ui/browser_commands.h" 44#include "chrome/browser/ui/browser_dialogs.h" 45#include "chrome/browser/ui/browser_finder.h" 46#include "chrome/browser/ui/browser_list.h" 47#include "chrome/browser/ui/browser_window_state.h" 48#include "chrome/browser/ui/immersive_fullscreen_configuration.h" 49#include "chrome/browser/ui/ntp_background_util.h" 50#include "chrome/browser/ui/omnibox/omnibox_popup_model.h" 51#include "chrome/browser/ui/omnibox/omnibox_popup_view.h" 52#include "chrome/browser/ui/omnibox/omnibox_view.h" 53#include "chrome/browser/ui/search/search_delegate.h" 54#include "chrome/browser/ui/search/search_model.h" 55#include "chrome/browser/ui/search/search_ui.h" 56#include "chrome/browser/ui/tabs/tab_menu_model.h" 57#include "chrome/browser/ui/tabs/tab_strip_model.h" 58#include "chrome/browser/ui/view_ids.h" 59#include "chrome/browser/ui/views/accelerator_table.h" 60#include "chrome/browser/ui/views/accessibility/invert_bubble_view.h" 61#include "chrome/browser/ui/views/avatar_menu_bubble_view.h" 62#include "chrome/browser/ui/views/avatar_menu_button.h" 63#include "chrome/browser/ui/views/bookmarks/bookmark_bar_view.h" 64#include "chrome/browser/ui/views/browser_dialogs.h" 65#include "chrome/browser/ui/views/download/download_in_progress_dialog_view.h" 66#include "chrome/browser/ui/views/download/download_shelf_view.h" 67#include "chrome/browser/ui/views/frame/browser_view_layout.h" 68#include "chrome/browser/ui/views/frame/browser_view_layout_delegate.h" 69#include "chrome/browser/ui/views/frame/contents_container.h" 70#include "chrome/browser/ui/views/frame/immersive_mode_controller.h" 71#include "chrome/browser/ui/views/frame/top_container_view.h" 72#include "chrome/browser/ui/views/fullscreen_exit_bubble_views.h" 73#include "chrome/browser/ui/views/infobars/infobar_container_view.h" 74#include "chrome/browser/ui/views/location_bar/location_icon_view.h" 75#include "chrome/browser/ui/views/omnibox/omnibox_view_views.h" 76#include "chrome/browser/ui/views/omnibox/omnibox_views.h" 77#include "chrome/browser/ui/views/password_generation_bubble_view.h" 78#include "chrome/browser/ui/views/status_bubble_views.h" 79#include "chrome/browser/ui/views/tabs/browser_tab_strip_controller.h" 80#include "chrome/browser/ui/views/tabs/tab.h" 81#include "chrome/browser/ui/views/tabs/tab_strip.h" 82#include "chrome/browser/ui/views/toolbar_view.h" 83#include "chrome/browser/ui/views/update_recommended_message_box.h" 84#include "chrome/browser/ui/views/website_settings/website_settings_popup_view.h" 85#include "chrome/browser/ui/window_sizer/window_sizer.h" 86#include "chrome/common/chrome_switches.h" 87#include "chrome/common/pref_names.h" 88#include "chrome/common/url_constants.h" 89#include "content/public/browser/download_manager.h" 90#include "content/public/browser/native_web_keyboard_event.h" 91#include "content/public/browser/notification_service.h" 92#include "content/public/browser/render_view_host.h" 93#include "content/public/browser/render_widget_host.h" 94#include "content/public/browser/user_metrics.h" 95#include "content/public/browser/web_contents.h" 96#include "content/public/browser/web_contents_view.h" 97#include "content/public/common/content_switches.h" 98#include "grit/chromium_strings.h" 99#include "grit/generated_resources.h" 100#include "grit/locale_settings.h" 101#include "grit/theme_resources.h" 102#include "grit/ui_resources.h" 103#include "grit/ui_strings.h" 104#include "grit/webkit_resources.h" 105#include "ui/base/accelerators/accelerator.h" 106#include "ui/base/accessibility/accessible_view_state.h" 107#include "ui/base/events/event_utils.h" 108#include "ui/base/hit_test.h" 109#include "ui/base/l10n/l10n_util.h" 110#include "ui/base/resource/resource_bundle.h" 111#include "ui/base/theme_provider.h" 112#include "ui/gfx/canvas.h" 113#include "ui/gfx/color_utils.h" 114#include "ui/gfx/sys_color_change_listener.h" 115#include "ui/views/controls/single_split_view.h" 116#include "ui/views/controls/textfield/textfield.h" 117#include "ui/views/controls/webview/webview.h" 118#include "ui/views/focus/external_focus_tracker.h" 119#include "ui/views/focus/view_storage.h" 120#include "ui/views/layout/grid_layout.h" 121#include "ui/views/widget/native_widget.h" 122#include "ui/views/widget/root_view.h" 123#include "ui/views/widget/widget.h" 124#include "ui/views/window/dialog_delegate.h" 125 126#if defined(USE_ASH) 127#include "ash/launcher/launcher.h" 128#include "ash/launcher/launcher_model.h" 129#include "ash/shell.h" 130#include "chrome/browser/ui/ash/ash_util.h" 131#include "chrome/browser/ui/ash/chrome_shell_delegate.h" 132#include "chrome/browser/ui/ash/launcher/browser_launcher_item_controller.h" 133#include "chrome/browser/ui/ash/window_positioner.h" 134#endif 135 136#if defined(USE_AURA) 137#include "ui/aura/window.h" 138#include "ui/gfx/screen.h" 139#elif defined(OS_WIN) // !defined(USE_AURA) 140#include "chrome/browser/jumplist_win.h" 141#include "chrome/browser/ui/views/omnibox/omnibox_view_win.h" 142#include "ui/views/widget/native_widget_win.h" 143#include "ui/views/win/scoped_fullscreen_visibility.h" 144#endif 145 146#if defined(OS_WIN) 147#include "base/win/windows_version.h" 148#include "win8/util/win8_util.h" 149#endif 150 151#if defined(ENABLE_ONE_CLICK_SIGNIN) 152#include "chrome/browser/ui/views/sync/one_click_signin_bubble_view.h" 153#endif 154 155using base::TimeDelta; 156using content::NativeWebKeyboardEvent; 157using content::SSLStatus; 158using content::UserMetricsAction; 159using content::WebContents; 160using views::ColumnSet; 161using views::GridLayout; 162using web_modal::WebContentsModalDialogHost; 163 164namespace { 165// The height of the status bubble. 166const int kStatusBubbleHeight = 20; 167// The name of a key to store on the window handle so that other code can 168// locate this object using just the handle. 169const char* const kBrowserViewKey = "__BROWSER_VIEW__"; 170 171// The number of milliseconds between loading animation frames. 172const int kLoadingAnimationFrameTimeMs = 30; 173// The amount of space we expect the window border to take up. 174const int kWindowBorderWidth = 5; 175 176// How round the 'new tab' style bookmarks bar is. 177const int kNewtabBarRoundness = 5; 178 179// TODO(kuan): These functions are temporarily for the bookmark bar while its 180// detached state is at the top of the page; it'll be moved to float on the 181// content page in the very near future, at which time, these local functions 182// will be removed. 183void PaintDetachedBookmarkBar(gfx::Canvas* canvas, 184 DetachableToolbarView* view, 185 ThemeService* theme_service) { 186 // Paint background for detached state; if animating, this is fade in/out. 187 canvas->DrawColor( 188 chrome::GetDetachedBookmarkBarBackgroundColor(theme_service)); 189 // Draw the separators above and below bookmark bar; 190 // if animating, these are fading in/out. 191 SkColor separator_color = 192 chrome::GetDetachedBookmarkBarSeparatorColor(theme_service); 193 DetachableToolbarView::PaintHorizontalBorder(canvas, view, true, 194 separator_color); 195 // The bottom border needs to be 1-px thick in both regular and retina 196 // displays, so we can't use DetachableToolbarView::PaintHorizontalBorder 197 // which paints a 2-px thick border in retina display. 198 SkPaint paint; 199 paint.setAntiAlias(false); 200 // Sets border to 1-px thick regardless of scale factor. 201 paint.setStrokeWidth(0); 202 // Bottom border is at 50% opacity of top border. 203 paint.setColor(SkColorSetA(separator_color, 204 SkColorGetA(separator_color) / 2)); 205 // Calculate thickness of bottom border as per current scale factor to 206 // determine where to draw the 1-px thick border. 207 float thickness = views::NonClientFrameView::kClientEdgeThickness / 208 ui::GetScaleFactorScale(canvas->scale_factor()); 209 SkScalar y = SkIntToScalar(view->height()) - SkFloatToScalar(thickness); 210 canvas->sk_canvas()->drawLine(SkIntToScalar(0), y, 211 SkIntToScalar(view->width()), y, paint); 212} 213 214void PaintAttachedBookmarkBar(gfx::Canvas* canvas, 215 DetachableToolbarView* view, 216 BrowserView* browser_view, 217 chrome::HostDesktopType host_desktop_type, 218 int toolbar_overlap) { 219 // Paint background for attached state, this is fade in/out. 220 gfx::Point background_image_offset = 221 browser_view->OffsetPointForToolbarBackgroundImage( 222 gfx::Point(view->GetMirroredX(), view->y())); 223 DetachableToolbarView::PaintBackgroundAttachedMode(canvas, 224 view->GetThemeProvider(), view->GetLocalBounds(), 225 background_image_offset, host_desktop_type); 226 if (view->height() >= toolbar_overlap) { 227 // Draw the separator below bookmark bar; this is fading in/out. 228 DetachableToolbarView::PaintHorizontalBorder(canvas, view, false, 229 ThemeProperties::GetDefaultColor( 230 ThemeProperties::COLOR_TOOLBAR_SEPARATOR)); 231 } 232} 233 234} // namespace 235 236// static 237const char BrowserView::kViewClassName[] = "BrowserView"; 238 239namespace { 240 241bool ShouldSaveOrRestoreWindowPos() { 242#if defined(OS_WIN) 243 // In Windows 8's single window Metro mode the window is always maximized 244 // (without the WS_MAXIMIZE style). 245 if (win8::IsSingleWindowMetroMode()) 246 return false; 247#endif 248 return true; 249} 250 251} // namespace 252 253/////////////////////////////////////////////////////////////////////////////// 254 255// Delegate implementation for BrowserViewLayout. Usually just forwards calls 256// into BrowserView. 257class BrowserViewLayoutDelegateImpl : public BrowserViewLayoutDelegate { 258 public: 259 explicit BrowserViewLayoutDelegateImpl(BrowserView* browser_view) 260 : browser_view_(browser_view) {} 261 virtual ~BrowserViewLayoutDelegateImpl() {} 262 263 // BrowserViewLayoutDelegate overrides: 264 virtual views::View* GetWindowSwitcherButton() const OVERRIDE { 265 return browser_view_->window_switcher_button(); 266 } 267 268 virtual bool DownloadShelfNeedsLayout() const OVERRIDE { 269 DownloadShelfView* download_shelf = browser_view_->download_shelf_.get(); 270 // Re-layout the shelf either if it is visible or if its close animation 271 // is currently running. 272 return download_shelf && 273 (download_shelf->IsShowing() || download_shelf->IsClosing()); 274 } 275 276 virtual bool IsTabStripVisible() const OVERRIDE { 277 return browser_view_->IsTabStripVisible(); 278 } 279 280 virtual gfx::Rect GetBoundsForTabStrip( 281 views::View* tab_strip) const OVERRIDE { 282 return browser_view_->frame()->GetBoundsForTabStrip(tab_strip); 283 } 284 285 virtual bool IsToolbarVisible() const OVERRIDE { 286 return browser_view_->IsToolbarVisible(); 287 } 288 289 virtual bool IsBookmarkBarVisible() const OVERRIDE { 290 return browser_view_->IsBookmarkBarVisible(); 291 } 292 293 virtual FullscreenExitBubbleViews* GetFullscreenExitBubble() const OVERRIDE { 294 return browser_view_->fullscreen_exit_bubble(); 295 } 296 297 private: 298 BrowserView* browser_view_; 299 300 DISALLOW_COPY_AND_ASSIGN(BrowserViewLayoutDelegateImpl); 301}; 302 303/////////////////////////////////////////////////////////////////////////////// 304// BookmarkExtensionBackground, private: 305// This object serves as the views::Background object which is used to layout 306// and paint the bookmark bar. 307class BookmarkExtensionBackground : public views::Background { 308 public: 309 BookmarkExtensionBackground(BrowserView* browser_view, 310 DetachableToolbarView* host_view, 311 Browser* browser); 312 313 // View methods overridden from views:Background. 314 virtual void Paint(gfx::Canvas* canvas, views::View* view) const OVERRIDE; 315 316 private: 317 BrowserView* browser_view_; 318 319 // The view hosting this background. 320 DetachableToolbarView* host_view_; 321 322 Browser* browser_; 323 324 DISALLOW_COPY_AND_ASSIGN(BookmarkExtensionBackground); 325}; 326 327BookmarkExtensionBackground::BookmarkExtensionBackground( 328 BrowserView* browser_view, 329 DetachableToolbarView* host_view, 330 Browser* browser) 331 : browser_view_(browser_view), 332 host_view_(host_view), 333 browser_(browser) { 334} 335 336void BookmarkExtensionBackground::Paint(gfx::Canvas* canvas, 337 views::View* view) const { 338 int toolbar_overlap = host_view_->GetToolbarOverlap(); 339 if (!host_view_->IsDetached()) { 340 PaintAttachedBookmarkBar(canvas, host_view_, browser_view_, 341 browser_->host_desktop_type(), toolbar_overlap); 342 return; 343 } 344 345 // As 'hidden' according to the animation is the full in-tab state, we invert 346 // the value - when current_state is at '0', we expect the bar to be docked. 347 double current_state = 1 - host_view_->GetAnimationValue(); 348 349 ThemeService* ts = 350 ThemeServiceFactory::GetForProfile(browser_->profile()); 351 if (current_state == 0.0 || current_state == 1.0) { 352 PaintDetachedBookmarkBar(canvas, host_view_, ts); 353 return; 354 } 355 // While animating, set opacity to cross-fade between attached and detached 356 // backgrounds including their respective separators. 357 int detached_alpha = static_cast<uint8>(current_state * 255); 358 int attached_alpha = 255 - detached_alpha; 359 if (browser_->bookmark_bar_state() == BookmarkBar::DETACHED) { 360 // To animate from attached to detached state: 361 // - fade out attached background 362 // - fade in detached background. 363 canvas->SaveLayerAlpha(attached_alpha); 364 PaintAttachedBookmarkBar(canvas, host_view_, browser_view_, 365 browser_->host_desktop_type(), 366 toolbar_overlap); 367 canvas->Restore(); 368 canvas->SaveLayerAlpha(detached_alpha); 369 PaintDetachedBookmarkBar(canvas, host_view_, ts); 370 } else { 371 // To animate from detached to attached state: 372 // - fade out detached background 373 // - fade in attached background. 374 canvas->SaveLayerAlpha(detached_alpha); 375 PaintDetachedBookmarkBar(canvas, host_view_, ts); 376 canvas->Restore(); 377 canvas->SaveLayerAlpha(attached_alpha); 378 PaintAttachedBookmarkBar(canvas, host_view_, browser_view_, 379 browser_->host_desktop_type(), 380 toolbar_overlap); 381 } 382 canvas->Restore(); 383} 384 385/////////////////////////////////////////////////////////////////////////////// 386// BrowserView, public: 387 388BrowserView::BrowserView() 389 : views::ClientView(NULL, NULL), 390 last_focused_view_storage_id_( 391 views::ViewStorage::GetInstance()->CreateStorageID()), 392 frame_(NULL), 393 top_container_(NULL), 394 tabstrip_(NULL), 395 toolbar_(NULL), 396 window_switcher_button_(NULL), 397 find_bar_host_view_(NULL), 398 infobar_container_(NULL), 399 contents_web_view_(NULL), 400 devtools_container_(NULL), 401 contents_container_(NULL), 402 contents_split_(NULL), 403 devtools_dock_side_(DEVTOOLS_DOCK_SIDE_BOTTOM), 404 devtools_window_(NULL), 405 initialized_(false), 406 ignore_layout_(true), 407#if defined(OS_WIN) && !defined(USE_AURA) 408 hung_window_detector_(&hung_plugin_action_), 409 ticker_(0), 410#endif 411 force_location_bar_focus_(false), 412 immersive_mode_controller_(chrome::CreateImmersiveModeController()), 413 color_change_listener_(this), 414 activate_modal_dialog_factory_(this) { 415} 416 417BrowserView::~BrowserView() { 418#if defined(USE_ASH) 419 // Destroy BrowserLauncherItemController early on as it listens to the 420 // TabstripModel, which is destroyed by the browser. 421 launcher_item_controller_.reset(); 422#endif 423 424 // Immersive mode may need to reparent views before they are removed/deleted. 425 immersive_mode_controller_.reset(); 426 427 browser_->tab_strip_model()->RemoveObserver(this); 428 429#if defined(OS_WIN) && !defined(USE_AURA) 430 // Stop hung plugin monitoring. 431 ticker_.Stop(); 432 ticker_.UnregisterTickHandler(&hung_window_detector_); 433 434 // Terminate the jumplist (must be called before browser_->profile() is 435 // destroyed. 436 if (jumplist_) { 437 jumplist_->Terminate(); 438 } 439#endif 440 441 // We destroy the download shelf before |browser_| to remove its child 442 // download views from the set of download observers (since the observed 443 // downloads can be destroyed along with |browser_| and the observer 444 // notifications will call back into deleted objects). 445 BrowserViewLayout* browser_view_layout = GetBrowserViewLayout(); 446 if (browser_view_layout) 447 browser_view_layout->set_download_shelf(NULL); 448 download_shelf_.reset(); 449 450 // The TabStrip attaches a listener to the model. Make sure we shut down the 451 // TabStrip first so that it can cleanly remove the listener. 452 if (tabstrip_) { 453 tabstrip_->parent()->RemoveChildView(tabstrip_); 454 if (browser_view_layout) 455 browser_view_layout->set_tab_strip(NULL); 456 delete tabstrip_; 457 tabstrip_ = NULL; 458 } 459 // Child views maintain PrefMember attributes that point to 460 // OffTheRecordProfile's PrefService which gets deleted by ~Browser. 461 RemoveAllChildViews(true); 462 463 // It is possible that we were forced-closed by the native view system and 464 // that tabs remain in the browser. Close any such remaining tabs. 465 while (browser_->tab_strip_model()->count()) 466 delete browser_->tab_strip_model()->GetWebContentsAt(0); 467 468 // Explicitly set browser_ to NULL. 469 browser_.reset(); 470} 471 472void BrowserView::Init(Browser* browser) { 473 browser_.reset(browser); 474 browser_->tab_strip_model()->AddObserver(this); 475} 476 477// static 478BrowserView* BrowserView::GetBrowserViewForNativeWindow( 479 gfx::NativeWindow window) { 480 views::Widget* widget = views::Widget::GetWidgetForNativeWindow(window); 481 return widget ? 482 reinterpret_cast<BrowserView*>(widget->GetNativeWindowProperty( 483 kBrowserViewKey)) : NULL; 484} 485 486// static 487BrowserView* BrowserView::GetBrowserViewForBrowser(const Browser* browser) { 488 return static_cast<BrowserView*>(browser->window()); 489} 490 491void BrowserView::InitStatusBubble() { 492 status_bubble_.reset(new StatusBubbleViews(contents_container_)); 493} 494 495gfx::Rect BrowserView::GetToolbarBounds() const { 496 gfx::Rect toolbar_bounds(toolbar_->bounds()); 497 if (toolbar_bounds.IsEmpty()) 498 return toolbar_bounds; 499 // The apparent toolbar edges are outside the "real" toolbar edges. 500 toolbar_bounds.Inset(-views::NonClientFrameView::kClientEdgeThickness, 0); 501 return toolbar_bounds; 502} 503 504gfx::Rect BrowserView::GetClientAreaBounds() const { 505 gfx::Rect container_bounds = contents_container_->bounds(); 506 gfx::Point container_origin = container_bounds.origin(); 507 ConvertPointToTarget(this, parent(), &container_origin); 508 container_bounds.set_origin(container_origin); 509 return container_bounds; 510} 511 512gfx::Rect BrowserView::GetFindBarBoundingBox() const { 513 return GetBrowserViewLayout()->GetFindBarBoundingBox(); 514} 515 516int BrowserView::GetTabStripHeight() const { 517 // We want to return tabstrip_->height(), but we might be called in the midst 518 // of layout, when that hasn't yet been updated to reflect the current state. 519 // So return what the tabstrip height _ought_ to be right now. 520 return IsTabStripVisible() ? tabstrip_->GetPreferredSize().height() : 0; 521} 522 523gfx::Point BrowserView::OffsetPointForToolbarBackgroundImage( 524 const gfx::Point& point) const { 525 // The background image starts tiling horizontally at the window left edge and 526 // vertically at the top edge of the horizontal tab strip (or where it would 527 // be). We expect our parent's origin to be the window origin. 528 gfx::Point window_point(point + GetMirroredPosition().OffsetFromOrigin()); 529 window_point.Offset(frame_->GetThemeBackgroundXInset(), 530 -frame_->GetTabStripInsets(false).top); 531 return window_point; 532} 533 534bool BrowserView::IsTabStripVisible() const { 535 if (immersive_mode_controller_->ShouldHideTopViews() && 536 immersive_mode_controller_->ShouldHideTabIndicators()) 537 return false; 538 return browser_->SupportsWindowFeature(Browser::FEATURE_TABSTRIP); 539} 540 541bool BrowserView::IsOffTheRecord() const { 542 return browser_->profile()->IsOffTheRecord(); 543} 544 545int BrowserView::GetOTRIconResourceID() const { 546 int otr_resource_id = IDR_OTR_ICON; 547 if (ui::GetDisplayLayout() == ui::LAYOUT_TOUCH) { 548 if (IsFullscreen()) 549 otr_resource_id = IDR_OTR_ICON_FULLSCREEN; 550#if defined(OS_WIN) 551 if (win8::IsSingleWindowMetroMode()) 552 otr_resource_id = IDR_OTR_ICON_FULLSCREEN; 553#endif 554 } 555 556 return otr_resource_id; 557} 558 559bool BrowserView::IsGuestSession() const { 560 return browser_->profile()->IsGuestSession(); 561} 562 563bool BrowserView::ShouldShowAvatar() const { 564 if (!IsBrowserTypeNormal()) 565 return false; 566 if (IsOffTheRecord() && !IsGuestSession()) 567 return true; 568 // Tests may not have a profile manager. 569 if (!g_browser_process->profile_manager()) 570 return false; 571 ProfileInfoCache& cache = 572 g_browser_process->profile_manager()->GetProfileInfoCache(); 573 if (cache.GetIndexOfProfileWithPath(browser_->profile()->GetPath()) == 574 std::string::npos) { 575 return false; 576 } 577 578 return AvatarMenuModel::ShouldShowAvatarMenu(); 579} 580 581bool BrowserView::GetAccelerator(int cmd_id, ui::Accelerator* accelerator) { 582 // We retrieve the accelerator information for standard accelerators 583 // for cut, copy and paste. 584 if (chrome::GetStandardAcceleratorForCommandId(cmd_id, accelerator)) 585 return true; 586 // Else, we retrieve the accelerator information from the accelerator table. 587 for (std::map<ui::Accelerator, int>::const_iterator it = 588 accelerator_table_.begin(); it != accelerator_table_.end(); ++it) { 589 if (it->second == cmd_id) { 590 *accelerator = it->first; 591 return true; 592 } 593 } 594 // Else, we retrieve the accelerator information from Ash (if applicable). 595 return chrome::GetAshAcceleratorForCommandId( 596 cmd_id, browser_->host_desktop_type(), accelerator); 597} 598 599bool BrowserView::IsAcceleratorRegistered(const ui::Accelerator& accelerator) { 600 return accelerator_table_.find(accelerator) != accelerator_table_.end(); 601} 602 603WebContents* BrowserView::GetActiveWebContents() const { 604 return browser_->tab_strip_model()->GetActiveWebContents(); 605} 606 607gfx::ImageSkia BrowserView::GetOTRAvatarIcon() const { 608 return *GetThemeProvider()->GetImageSkiaNamed(GetOTRIconResourceID()); 609} 610 611bool BrowserView::IsPositionInWindowCaption(const gfx::Point& point) { 612 if (window_switcher_button_) { 613 gfx::Point window_switcher_point(point); 614 views::View::ConvertPointToTarget(this, window_switcher_button_, 615 &window_switcher_point); 616 if (window_switcher_button_->HitTestPoint(window_switcher_point)) 617 return false; 618 } 619 return GetBrowserViewLayout()->IsPositionInWindowCaption(point); 620} 621 622/////////////////////////////////////////////////////////////////////////////// 623// BrowserView, BrowserWindow implementation: 624 625void BrowserView::Show() { 626 // If the window is already visible, just activate it. 627 if (frame_->IsVisible()) { 628 frame_->Activate(); 629 return; 630 } 631 632 CreateLauncherIcon(); 633 634 // Showing the window doesn't make the browser window active right away. 635 // This can cause SetFocusToLocationBar() to skip setting focus to the 636 // location bar. To avoid this we explicilty let SetFocusToLocationBar() 637 // know that it's ok to steal focus. 638 force_location_bar_focus_ = true; 639 640 // Setting the focus doesn't work when the window is invisible, so any focus 641 // initialization that happened before this will be lost. 642 // 643 // We really "should" restore the focus whenever the window becomes unhidden, 644 // but I think initializing is the only time where this can happen where 645 // there is some focus change we need to pick up, and this is easier than 646 // plumbing through an un-hide message all the way from the frame. 647 // 648 // If we do find there are cases where we need to restore the focus on show, 649 // that should be added and this should be removed. 650 RestoreFocus(); 651 652 frame_->Show(); 653 654 force_location_bar_focus_ = false; 655 656 browser()->OnWindowDidShow(); 657 658 chrome::MaybeShowInvertBubbleView(browser_.get(), contents_container_); 659} 660 661void BrowserView::ShowInactive() { 662 if (frame_->IsVisible()) 663 return; 664 CreateLauncherIcon(); 665 frame_->ShowInactive(); 666} 667 668void BrowserView::Hide() { 669 // Not implemented. 670} 671 672void BrowserView::SetBounds(const gfx::Rect& bounds) { 673 ExitFullscreen(); 674 GetWidget()->SetBounds(bounds); 675} 676 677void BrowserView::Close() { 678 frame_->Close(); 679} 680 681void BrowserView::Activate() { 682 frame_->Activate(); 683} 684 685void BrowserView::Deactivate() { 686 frame_->Deactivate(); 687} 688 689bool BrowserView::IsActive() const { 690 return frame_->IsActive(); 691} 692 693void BrowserView::FlashFrame(bool flash) { 694 frame_->FlashFrame(flash); 695} 696 697bool BrowserView::IsAlwaysOnTop() const { 698 return false; 699} 700 701gfx::NativeWindow BrowserView::GetNativeWindow() { 702 // While the browser destruction is going on, the widget can already be gone, 703 // but utility functions like FindBrowserWithWindow will come here and crash. 704 // We short circuit therefore. 705 if (!GetWidget()) 706 return NULL; 707 return GetWidget()->GetTopLevelWidget()->GetNativeWindow(); 708} 709 710BrowserWindowTesting* BrowserView::GetBrowserWindowTesting() { 711 return this; 712} 713 714StatusBubble* BrowserView::GetStatusBubble() { 715 return status_bubble_.get(); 716} 717 718namespace { 719 // Only used by ToolbarSizeChanged() below, but placed here because template 720 // arguments (to base::AutoReset<>) must have external linkage. 721 enum CallState { NORMAL, REENTRANT, REENTRANT_FORCE_FAST_RESIZE }; 722} 723 724void BrowserView::UpdateTitleBar() { 725 frame_->UpdateWindowTitle(); 726 if (ShouldShowWindowIcon() && !loading_animation_timer_.IsRunning()) 727 frame_->UpdateWindowIcon(); 728} 729 730void BrowserView::BookmarkBarStateChanged( 731 BookmarkBar::AnimateChangeType change_type) { 732 if (bookmark_bar_view_.get()) { 733 BookmarkBar::State new_state = browser_->bookmark_bar_state(); 734 735 // We don't properly support animating the bookmark bar to and from the 736 // detached state in immersive fullscreen. 737 bool detached_changed = (new_state == BookmarkBar::DETACHED) || 738 bookmark_bar_view_->IsDetached(); 739 if (detached_changed && immersive_mode_controller_->IsEnabled()) 740 change_type = BookmarkBar::DONT_ANIMATE_STATE_CHANGE; 741 742 bookmark_bar_view_->SetBookmarkBarState(new_state, change_type); 743 } 744 if (MaybeShowBookmarkBar(GetActiveWebContents())) 745 Layout(); 746} 747 748void BrowserView::UpdateDevTools() { 749 UpdateDevToolsForContents(GetActiveWebContents()); 750 Layout(); 751} 752 753void BrowserView::UpdateLoadingAnimations(bool should_animate) { 754 if (should_animate) { 755 if (!loading_animation_timer_.IsRunning()) { 756 // Loads are happening, and the timer isn't running, so start it. 757 last_animation_time_ = base::TimeTicks::Now(); 758 loading_animation_timer_.Start(FROM_HERE, 759 TimeDelta::FromMilliseconds(kLoadingAnimationFrameTimeMs), this, 760 &BrowserView::LoadingAnimationCallback); 761 } 762 } else { 763 if (loading_animation_timer_.IsRunning()) { 764 last_animation_time_ = base::TimeTicks(); 765 loading_animation_timer_.Stop(); 766 // Loads are now complete, update the state if a task was scheduled. 767 LoadingAnimationCallback(); 768 } 769 } 770} 771 772void BrowserView::SetStarredState(bool is_starred) { 773 GetLocationBarView()->SetStarToggled(is_starred); 774} 775 776void BrowserView::ZoomChangedForActiveTab(bool can_show_bubble) { 777 GetLocationBarView()->ZoomChangedForActiveTab( 778 can_show_bubble && !toolbar_->IsWrenchMenuShowing()); 779} 780 781gfx::Rect BrowserView::GetRestoredBounds() const { 782 return frame_->GetRestoredBounds(); 783} 784 785ui::WindowShowState BrowserView::GetRestoredState() const { 786 if (IsMaximized()) 787 return ui::SHOW_STATE_MAXIMIZED; 788 if (IsMinimized()) 789 return ui::SHOW_STATE_MINIMIZED; 790 return ui::SHOW_STATE_NORMAL; 791} 792 793gfx::Rect BrowserView::GetBounds() const { 794 return frame_->GetWindowBoundsInScreen(); 795} 796 797bool BrowserView::IsMaximized() const { 798 return frame_->IsMaximized(); 799} 800 801bool BrowserView::IsMinimized() const { 802 return frame_->IsMinimized(); 803} 804 805void BrowserView::Maximize() { 806 frame_->Maximize(); 807} 808 809void BrowserView::Minimize() { 810 frame_->Minimize(); 811} 812 813void BrowserView::Restore() { 814 frame_->Restore(); 815} 816 817void BrowserView::EnterFullscreen( 818 const GURL& url, FullscreenExitBubbleType bubble_type) { 819 if (IsFullscreen()) 820 return; // Nothing to do. 821 822 ProcessFullscreen(true, FOR_DESKTOP, url, bubble_type); 823} 824 825void BrowserView::ExitFullscreen() { 826 if (!IsFullscreen()) 827 return; // Nothing to do. 828 829 ProcessFullscreen(false, FOR_DESKTOP, GURL(), FEB_TYPE_NONE); 830} 831 832void BrowserView::UpdateFullscreenExitBubbleContent( 833 const GURL& url, 834 FullscreenExitBubbleType bubble_type) { 835 // Immersive mode has no exit bubble because it has a visible strip at the 836 // top that gives the user a hover target. 837 // TODO(jamescook): Figure out what to do with mouse-lock. 838 if (bubble_type == FEB_TYPE_NONE || ShouldUseImmersiveFullscreenForUrl(url)) { 839 fullscreen_bubble_.reset(); 840 } else if (fullscreen_bubble_.get()) { 841 fullscreen_bubble_->UpdateContent(url, bubble_type); 842 } else { 843 fullscreen_bubble_.reset(new FullscreenExitBubbleViews( 844 this, url, bubble_type)); 845 } 846} 847 848bool BrowserView::ShouldHideUIForFullscreen() const { 849#if defined(USE_ASH) 850 // Immersive mode needs UI for the slide-down top panel. 851 return IsFullscreen() && !immersive_mode_controller_->IsEnabled(); 852#endif 853 return IsFullscreen(); 854} 855 856bool BrowserView::IsFullscreen() const { 857 return frame_->IsFullscreen(); 858} 859 860bool BrowserView::IsFullscreenBubbleVisible() const { 861 return fullscreen_bubble_ != NULL; 862} 863 864#if defined(OS_WIN) 865void BrowserView::SetMetroSnapMode(bool enable) { 866 HISTOGRAM_COUNTS("Metro.SnapModeToggle", enable); 867 ProcessFullscreen(enable, FOR_METRO, GURL(), FEB_TYPE_NONE); 868} 869 870bool BrowserView::IsInMetroSnapMode() const { 871#if defined(USE_AURA) 872 return false; 873#else 874 return static_cast<views::NativeWidgetWin*>( 875 frame_->native_widget())->IsInMetroSnapMode(); 876#endif 877} 878#endif // defined(OS_WIN) 879 880void BrowserView::RestoreFocus() { 881 WebContents* selected_web_contents = GetActiveWebContents(); 882 if (selected_web_contents) 883 selected_web_contents->GetView()->RestoreFocus(); 884} 885 886void BrowserView::SetWindowSwitcherButton(views::Button* button) { 887 if (window_switcher_button_) 888 RemoveChildView(window_switcher_button_); 889 window_switcher_button_ = button; 890} 891 892void BrowserView::ToolbarSizeChanged(bool is_animating) { 893 // The call to InfoBarContainer::SetMaxTopArrowHeight() below can result in 894 // reentrancy; |call_state| tracks whether we're reentrant. We can't just 895 // early-return in this case because we need to layout again so the infobar 896 // container's bounds are set correctly. 897 static CallState call_state = NORMAL; 898 899 // A reentrant call can (and should) use the fast resize path unless both it 900 // and the normal call are both non-animating. 901 bool use_fast_resize = 902 is_animating || (call_state == REENTRANT_FORCE_FAST_RESIZE); 903 if (use_fast_resize) 904 contents_web_view_->SetFastResize(true); 905 UpdateUIForContents(GetActiveWebContents()); 906 if (use_fast_resize) 907 contents_web_view_->SetFastResize(false); 908 909 // Inform the InfoBarContainer that the distance to the location icon may have 910 // changed. We have to do this after the block above so that the toolbars are 911 // laid out correctly for calculating the maximum arrow height below. 912 { 913 base::AutoReset<CallState> resetter(&call_state, 914 is_animating ? REENTRANT_FORCE_FAST_RESIZE : REENTRANT); 915 infobar_container_->SetMaxTopArrowHeight(GetMaxTopInfoBarArrowHeight()); 916 } 917 918 // When transitioning from animating to not animating we need to make sure the 919 // contents_container_ gets layed out. If we don't do this and the bounds 920 // haven't changed contents_container_ won't get a Layout out and we'll end up 921 // with a gray rect because the clip wasn't updated. Note that a reentrant 922 // call never needs to do this, because after it returns, the normal call 923 // wrapping it will do it. 924 if ((call_state == NORMAL) && !is_animating) { 925 contents_web_view_->InvalidateLayout(); 926 contents_split_->Layout(); 927 } 928} 929 930LocationBar* BrowserView::GetLocationBar() const { 931 return GetLocationBarView(); 932} 933 934void BrowserView::SetFocusToLocationBar(bool select_all) { 935 // On Windows, changing focus to the location bar causes the browser 936 // window to become active. This can steal focus if the user has 937 // another window open already. On ChromeOS, changing focus makes a 938 // view believe it has a focus even if the widget doens't have a 939 // focus. Either cases, we need to ignore this when the browser 940 // window isn't active. 941 if (!force_location_bar_focus_ && !IsActive()) 942 return; 943 944 // Temporarily reveal the top-of-window views (if not already revealed) so 945 // that the location bar view is visible and is considered focusable. If the 946 // location bar view gains focus, |immersive_mode_controller_| will keep the 947 // top-of-window views revealed. 948 scoped_ptr<ImmersiveRevealedLock> focus_reveal_lock( 949 immersive_mode_controller_->GetRevealedLock( 950 ImmersiveModeController::ANIMATE_REVEAL_YES)); 951 952 LocationBarView* location_bar = GetLocationBarView(); 953 if (location_bar->IsLocationEntryFocusableInRootView()) { 954 // Location bar got focus. 955 location_bar->FocusLocation(select_all); 956 } else { 957 // If none of location bar got focus, 958 // then clear focus. 959 views::FocusManager* focus_manager = GetFocusManager(); 960 DCHECK(focus_manager); 961 focus_manager->ClearFocus(); 962 } 963} 964 965void BrowserView::UpdateReloadStopState(bool is_loading, bool force) { 966 toolbar_->reload_button()->ChangeMode( 967 is_loading ? ReloadButton::MODE_STOP : ReloadButton::MODE_RELOAD, force); 968} 969 970void BrowserView::UpdateToolbar(content::WebContents* contents, 971 bool should_restore_state) { 972 toolbar_->Update(contents, should_restore_state); 973} 974 975void BrowserView::FocusToolbar() { 976 // Temporarily reveal the top-of-window views (if not already revealed) so 977 // that the toolbar is visible and is considered focusable. If the 978 // toolbar gains focus, |immersive_mode_controller_| will keep the 979 // top-of-window views revealed. 980 scoped_ptr<ImmersiveRevealedLock> focus_reveal_lock( 981 immersive_mode_controller_->GetRevealedLock( 982 ImmersiveModeController::ANIMATE_REVEAL_YES)); 983 984 // Start the traversal within the main toolbar. SetPaneFocus stores 985 // the current focused view before changing focus. 986 toolbar_->SetPaneFocus(NULL); 987} 988 989void BrowserView::FocusBookmarksToolbar() { 990 DCHECK(!immersive_mode_controller_->IsEnabled()); 991 if (bookmark_bar_view_.get() && 992 bookmark_bar_view_->visible() && 993 bookmark_bar_view_->GetPreferredSize().height() != 0) { 994 bookmark_bar_view_->SetPaneFocusAndFocusDefault(); 995 } 996} 997 998void BrowserView::FocusInfobars() { 999 if (infobar_container_->child_count() > 0) 1000 infobar_container_->SetPaneFocusAndFocusDefault(); 1001} 1002 1003void BrowserView::FocusAppMenu() { 1004 // Chrome doesn't have a traditional menu bar, but it has a menu button in the 1005 // main toolbar that plays the same role. If the user presses a key that 1006 // would typically focus the menu bar, tell the toolbar to focus the menu 1007 // button. If the user presses the key again, return focus to the previous 1008 // location. 1009 // 1010 // Not used on the Mac, which has a normal menu bar. 1011 if (toolbar_->IsAppMenuFocused()) { 1012 RestoreFocus(); 1013 } else { 1014 DCHECK(!immersive_mode_controller_->IsEnabled()); 1015 toolbar_->SetPaneFocusAndFocusAppMenu(); 1016 } 1017} 1018 1019void BrowserView::RotatePaneFocus(bool forwards) { 1020 GetWidget()->GetFocusManager()->RotatePaneFocus( 1021 forwards ? 1022 views::FocusManager::kForward : views::FocusManager::kBackward, 1023 views::FocusManager::kWrap); 1024} 1025 1026void BrowserView::DestroyBrowser() { 1027 // After this returns other parts of Chrome are going to be shutdown. Close 1028 // the window now so that we are deleted immediately and aren't left holding 1029 // references to deleted objects. 1030 GetWidget()->RemoveObserver(this); 1031 GetLocationBar()->GetLocationEntry()->model()->popup_model()->RemoveObserver( 1032 this); 1033 frame_->CloseNow(); 1034} 1035 1036bool BrowserView::IsBookmarkBarVisible() const { 1037 if (!browser_->SupportsWindowFeature(Browser::FEATURE_BOOKMARKBAR)) 1038 return false; 1039 if (!bookmark_bar_view_.get()) 1040 return false; 1041 if (bookmark_bar_view_->GetPreferredSize().height() == 0) 1042 return false; 1043 // New tab page needs visible bookmarks even when top-views are hidden. 1044 if (immersive_mode_controller_->ShouldHideTopViews() && 1045 !bookmark_bar_view_->IsDetached()) 1046 return false; 1047 return true; 1048} 1049 1050bool BrowserView::IsBookmarkBarAnimating() const { 1051 return bookmark_bar_view_.get() && bookmark_bar_view_->is_animating(); 1052} 1053 1054bool BrowserView::IsTabStripEditable() const { 1055 return tabstrip_->IsTabStripEditable(); 1056} 1057 1058bool BrowserView::IsToolbarVisible() const { 1059 if (immersive_mode_controller_->ShouldHideTopViews()) 1060 return false; 1061 return browser_->SupportsWindowFeature(Browser::FEATURE_TOOLBAR) || 1062 browser_->SupportsWindowFeature(Browser::FEATURE_LOCATIONBAR); 1063} 1064 1065gfx::Rect BrowserView::GetRootWindowResizerRect() const { 1066 // Views does not support resizer rects because they caused page cycler 1067 // performance regressions when they were added. See crrev.com/9654 1068 return gfx::Rect(); 1069} 1070 1071void BrowserView::DisableInactiveFrame() { 1072#if defined(OS_WIN) && !defined(USE_AURA) 1073 frame_->DisableInactiveRendering(); 1074#endif // No tricks are needed to get the right behavior on Linux. 1075} 1076 1077void BrowserView::ConfirmAddSearchProvider(TemplateURL* template_url, 1078 Profile* profile) { 1079 chrome::EditSearchEngine(GetWidget()->GetNativeWindow(), template_url, NULL, 1080 profile); 1081} 1082 1083void BrowserView::ToggleBookmarkBar() { 1084 chrome::ToggleBookmarkBarWhenVisible(browser_->profile()); 1085} 1086 1087void BrowserView::ShowUpdateChromeDialog() { 1088 UpdateRecommendedMessageBox::Show(GetWidget()->GetNativeWindow()); 1089} 1090 1091void BrowserView::ShowBookmarkBubble(const GURL& url, bool already_bookmarked) { 1092 scoped_ptr<BookmarkBubbleDelegate> delegate; 1093 delegate.reset(new BookmarkBubbleSignInDelegate(browser_.get())); 1094 1095 chrome::ShowBookmarkBubbleView(GetToolbarView()->GetBookmarkBubbleAnchor(), 1096 bookmark_bar_view_.get(), 1097 delegate.Pass(), 1098 browser_->profile(), 1099 url, 1100 !already_bookmarked); 1101} 1102 1103void BrowserView::ShowBookmarkPrompt() { 1104 GetLocationBarView()->ShowBookmarkPrompt(); 1105} 1106 1107#if defined(ENABLE_ONE_CLICK_SIGNIN) 1108void BrowserView::ShowOneClickSigninBubble( 1109 OneClickSigninBubbleType type, 1110 const string16& email, 1111 const string16& error_message, 1112 const StartSyncCallback& start_sync_callback) { 1113 OneClickSigninBubbleView::ShowBubble(type, email, error_message, 1114 toolbar_, start_sync_callback); 1115} 1116#endif 1117 1118void BrowserView::SetDownloadShelfVisible(bool visible) { 1119 // This can be called from the superclass destructor, when it destroys our 1120 // child views. At that point, browser_ is already gone. 1121 if (browser_ == NULL) 1122 return; 1123 1124 if (visible && IsDownloadShelfVisible() != visible) { 1125 // Invoke GetDownloadShelf to force the shelf to be created. 1126 GetDownloadShelf(); 1127 } 1128 1129 if (browser_ != NULL) 1130 browser_->UpdateDownloadShelfVisibility(visible); 1131 1132 // SetDownloadShelfVisible can force-close the shelf, so make sure we lay out 1133 // everything correctly, as if the animation had finished. This doesn't 1134 // matter for showing the shelf, as the show animation will do it. 1135 ToolbarSizeChanged(false); 1136} 1137 1138bool BrowserView::IsDownloadShelfVisible() const { 1139 return download_shelf_.get() && download_shelf_->IsShowing(); 1140} 1141 1142DownloadShelf* BrowserView::GetDownloadShelf() { 1143 if (!download_shelf_.get()) { 1144 download_shelf_.reset(new DownloadShelfView(browser_.get(), this)); 1145 download_shelf_->set_owned_by_client(); 1146 GetBrowserViewLayout()->set_download_shelf(download_shelf_.get()); 1147 } 1148 return download_shelf_.get(); 1149} 1150 1151void BrowserView::ConfirmBrowserCloseWithPendingDownloads() { 1152 DownloadInProgressDialogView::Show(browser_.get(), GetNativeWindow()); 1153} 1154 1155void BrowserView::ShowCreateChromeAppShortcutsDialog( 1156 Profile* profile, 1157 const extensions::Extension* app) { 1158 chrome::ShowCreateChromeAppShortcutsDialog(GetNativeWindow(), profile, app); 1159} 1160 1161void BrowserView::UserChangedTheme() { 1162 frame_->FrameTypeChanged(); 1163} 1164 1165int BrowserView::GetExtraRenderViewHeight() const { 1166 // Currently this is only used on linux. 1167 return 0; 1168} 1169 1170void BrowserView::WebContentsFocused(WebContents* contents) { 1171 if (contents_web_view_->GetWebContents() == contents) 1172 contents_web_view_->OnWebContentsFocused(contents); 1173 else 1174 devtools_container_->OnWebContentsFocused(contents); 1175} 1176 1177void BrowserView::ShowWebsiteSettings(Profile* profile, 1178 content::WebContents* web_contents, 1179 const GURL& url, 1180 const content::SSLStatus& ssl) { 1181 WebsiteSettingsPopupView::ShowPopup( 1182 GetLocationBarView()->location_icon_view(), profile, 1183 web_contents, url, ssl, browser_.get()); 1184} 1185 1186void BrowserView::ShowAppMenu() { 1187 // Keep the top-of-window views revealed as long as the app menu is visible. 1188 scoped_ptr<ImmersiveRevealedLock> revealed_lock( 1189 immersive_mode_controller_->GetRevealedLock( 1190 ImmersiveModeController::ANIMATE_REVEAL_NO)); 1191 1192 toolbar_->app_menu()->Activate(); 1193} 1194 1195bool BrowserView::PreHandleKeyboardEvent(const NativeWebKeyboardEvent& event, 1196 bool* is_keyboard_shortcut) { 1197 *is_keyboard_shortcut = false; 1198 1199 if ((event.type != WebKit::WebInputEvent::RawKeyDown) && 1200 (event.type != WebKit::WebInputEvent::KeyUp)) { 1201 return false; 1202 } 1203 1204#if defined(OS_WIN) && !defined(USE_AURA) 1205 // As Alt+F4 is the close-app keyboard shortcut, it needs processing 1206 // immediately. 1207 if (event.windowsKeyCode == ui::VKEY_F4 && 1208 event.type == WebKit::WebInputEvent::RawKeyDown && 1209 event.modifiers == NativeWebKeyboardEvent::AltKey) { 1210 DefWindowProc(event.os_event.hwnd, event.os_event.message, 1211 event.os_event.wParam, event.os_event.lParam); 1212 return true; 1213 } 1214#endif 1215 1216 views::FocusManager* focus_manager = GetFocusManager(); 1217 DCHECK(focus_manager); 1218 1219 if (focus_manager->shortcut_handling_suspended()) 1220 return false; 1221 1222 ui::Accelerator accelerator( 1223 static_cast<ui::KeyboardCode>(event.windowsKeyCode), 1224 content::GetModifiersFromNativeWebKeyboardEvent(event)); 1225 if (event.type == WebKit::WebInputEvent::KeyUp) 1226 accelerator.set_type(ui::ET_KEY_RELEASED); 1227 1228 // What we have to do here is as follows: 1229 // - If the |browser_| is for an app, do nothing. 1230 // - If the |browser_| is not for an app, and the |accelerator| is not 1231 // associated with the browser (e.g. an Ash shortcut), process it. 1232 // - If the |browser_| is not for an app, and the |accelerator| is associated 1233 // with the browser, and it is a reserved one (e.g. Ctrl+w), process it. 1234 // - If the |browser_| is not for an app, and the |accelerator| is associated 1235 // with the browser, and it is not a reserved one, do nothing. 1236 1237 if (browser_->is_app()) { 1238 // We don't have to flip |is_keyboard_shortcut| here. If we do that, the app 1239 // might not be able to see a subsequent Char event. See OnHandleInputEvent 1240 // in content/renderer/render_widget.cc for details. 1241 return false; 1242 } 1243 1244 chrome::BrowserCommandController* controller = browser_->command_controller(); 1245 1246 // Here we need to retrieve the command id (if any) associated to the 1247 // keyboard event. Instead of looking up the command id in the 1248 // |accelerator_table_| by ourselves, we block the command execution of 1249 // the |browser_| object then send the keyboard event to the 1250 // |focus_manager| as if we are activating an accelerator key. 1251 // Then we can retrieve the command id from the |browser_| object. 1252 controller->SetBlockCommandExecution(true); 1253 // If the |accelerator| is a non-browser shortcut (e.g. Ash shortcut), the 1254 // command execution cannot be blocked and true is returned. However, it is 1255 // okay as long as is_app() is false. See comments in this function. 1256 const bool processed = focus_manager->ProcessAccelerator(accelerator); 1257 const int id = controller->GetLastBlockedCommand(NULL); 1258 controller->SetBlockCommandExecution(false); 1259 1260 // Executing the command may cause |this| object to be destroyed. 1261 if (controller->IsReservedCommandOrKey(id, event)) { 1262 UpdateAcceleratorMetrics(accelerator, id); 1263 return chrome::ExecuteCommand(browser_.get(), id); 1264 } 1265 1266 if (id != -1) { 1267 // |accelerator| is a non-reserved browser shortcut (e.g. Ctrl+f). 1268 if (event.type == WebKit::WebInputEvent::RawKeyDown) 1269 *is_keyboard_shortcut = true; 1270 } else if (processed) { 1271 // |accelerator| is a non-browser shortcut (e.g. F4-F10 on Ash). 1272 return true; 1273 } 1274 1275 return false; 1276} 1277 1278void BrowserView::HandleKeyboardEvent(const NativeWebKeyboardEvent& event) { 1279 unhandled_keyboard_event_handler_.HandleKeyboardEvent(event, 1280 GetFocusManager()); 1281} 1282 1283// TODO(devint): http://b/issue?id=1117225 Cut, Copy, and Paste are always 1284// enabled in the page menu regardless of whether the command will do 1285// anything. When someone selects the menu item, we just act as if they hit 1286// the keyboard shortcut for the command by sending the associated key press 1287// to windows. The real fix to this bug is to disable the commands when they 1288// won't do anything. We'll need something like an overall clipboard command 1289// manager to do that. 1290void BrowserView::Cut() { 1291 // If a WebContent is focused, call RenderWidgetHost::Cut. Otherwise, e.g. if 1292 // Omnibox is focused, send a Ctrl+x key event to Chrome. Using RWH interface 1293 // rather than the fake key event for a WebContent is important since the fake 1294 // event might be consumed by the web content (crbug.com/137908). 1295 DoCutCopyPaste(&content::RenderWidgetHost::Cut, 1296#if defined(OS_WIN) 1297 WM_CUT, 1298#endif 1299 IDS_APP_CUT); 1300} 1301 1302void BrowserView::Copy() { 1303 DoCutCopyPaste(&content::RenderWidgetHost::Copy, 1304#if defined(OS_WIN) 1305 WM_COPY, 1306#endif 1307 IDS_APP_COPY); 1308} 1309 1310void BrowserView::Paste() { 1311 DoCutCopyPaste(&content::RenderWidgetHost::Paste, 1312#if defined(OS_WIN) 1313 WM_PASTE, 1314#endif 1315 IDS_APP_PASTE); 1316} 1317 1318WindowOpenDisposition BrowserView::GetDispositionForPopupBounds( 1319 const gfx::Rect& bounds) { 1320#if defined(OS_WIN) 1321 // If we are in Win8's single window Metro mode, we can't allow popup windows. 1322 return win8::IsSingleWindowMetroMode() ? NEW_BACKGROUND_TAB : NEW_POPUP; 1323#else 1324 return NEW_POPUP; 1325#endif 1326} 1327 1328FindBar* BrowserView::CreateFindBar() { 1329 return chrome::CreateFindBar(this); 1330} 1331 1332WebContentsModalDialogHost* BrowserView::GetWebContentsModalDialogHost() { 1333 return GetBrowserViewLayout()->GetWebContentsModalDialogHost(); 1334} 1335 1336/////////////////////////////////////////////////////////////////////////////// 1337// BrowserView, BrowserWindowTesting implementation: 1338 1339BookmarkBarView* BrowserView::GetBookmarkBarView() const { 1340 return bookmark_bar_view_.get(); 1341} 1342 1343LocationBarView* BrowserView::GetLocationBarView() const { 1344 return toolbar_ ? toolbar_->location_bar() : NULL; 1345} 1346 1347views::View* BrowserView::GetTabContentsContainerView() const { 1348 return contents_web_view_; 1349} 1350 1351ToolbarView* BrowserView::GetToolbarView() const { 1352 return toolbar_; 1353} 1354 1355/////////////////////////////////////////////////////////////////////////////// 1356// BrowserView, TabStripModelObserver implementation: 1357 1358void BrowserView::TabDetachedAt(WebContents* contents, int index) { 1359 // We use index here rather than comparing |contents| because by this time 1360 // the model has already removed |contents| from its list, so 1361 // browser_->GetActiveWebContents() will return NULL or something else. 1362 if (index == browser_->tab_strip_model()->active_index()) { 1363 // We need to reset the current tab contents to NULL before it gets 1364 // freed. This is because the focus manager performs some operations 1365 // on the selected WebContents when it is removed. 1366 contents_web_view_->SetWebContents(NULL); 1367 infobar_container_->ChangeInfoBarService(NULL); 1368 UpdateDevToolsForContents(NULL); 1369 } 1370} 1371 1372void BrowserView::TabDeactivated(WebContents* contents) { 1373 // We do not store the focus when closing the tab to work-around bug 4633. 1374 // Some reports seem to show that the focus manager and/or focused view can 1375 // be garbage at that point, it is not clear why. 1376 if (!contents->IsBeingDestroyed()) 1377 contents->GetView()->StoreFocus(); 1378} 1379 1380void BrowserView::ActiveTabChanged(content::WebContents* old_contents, 1381 content::WebContents* new_contents, 1382 int index, 1383 int reason) { 1384 DCHECK(new_contents); 1385 1386 // If |contents_container_| already has the correct WebContents, we can save 1387 // some work. This also prevents extra events from being reported by the 1388 // Visibility API under Windows, as ChangeWebContents will briefly hide 1389 // the WebContents window. 1390 bool change_tab_contents = 1391 contents_web_view_->web_contents() != new_contents; 1392 1393 // Update various elements that are interested in knowing the current 1394 // WebContents. 1395 1396 // When we toggle the NTP floating bookmarks bar and/or the info bar, 1397 // we don't want any WebContents to be attached, so that we 1398 // avoid an unnecessary resize and re-layout of a WebContents. 1399 if (change_tab_contents) 1400 contents_web_view_->SetWebContents(NULL); 1401 infobar_container_->ChangeInfoBarService( 1402 InfoBarService::FromWebContents(new_contents)); 1403 if (bookmark_bar_view_.get()) { 1404 bookmark_bar_view_->SetBookmarkBarState( 1405 browser_->bookmark_bar_state(), 1406 BookmarkBar::DONT_ANIMATE_STATE_CHANGE); 1407 } 1408 UpdateUIForContents(new_contents); 1409 1410 // Layout for DevTools _before_ setting the main WebContents to avoid 1411 // toggling the size of the main WebContents. 1412 UpdateDevToolsForContents(new_contents); 1413 1414 if (change_tab_contents) 1415 contents_web_view_->SetWebContents(new_contents); 1416 1417 if (!browser_->tab_strip_model()->closing_all() && GetWidget()->IsActive() && 1418 GetWidget()->IsVisible()) { 1419 // We only restore focus if our window is visible, to avoid invoking blur 1420 // handlers when we are eventually shown. 1421 new_contents->GetView()->RestoreFocus(); 1422 } 1423 1424 // Update all the UI bits. 1425 UpdateTitleBar(); 1426 1427 // No need to update Toolbar because it's already updated in 1428 // browser.cc. 1429} 1430 1431void BrowserView::TabStripEmpty() { 1432 // Make sure all optional UI is removed before we are destroyed, otherwise 1433 // there will be consequences (since our view hierarchy will still have 1434 // references to freed views). 1435 UpdateUIForContents(NULL); 1436} 1437 1438/////////////////////////////////////////////////////////////////////////////// 1439// BrowserView, ui::AcceleratorProvider implementation: 1440 1441bool BrowserView::GetAcceleratorForCommandId(int command_id, 1442 ui::Accelerator* accelerator) { 1443 // Let's let the ToolbarView own the canonical implementation of this method. 1444 return toolbar_->GetAcceleratorForCommandId(command_id, accelerator); 1445} 1446 1447/////////////////////////////////////////////////////////////////////////////// 1448// BrowserView, views::WidgetDelegate implementation: 1449 1450bool BrowserView::CanResize() const { 1451 return true; 1452} 1453 1454bool BrowserView::CanMaximize() const { 1455 return true; 1456} 1457 1458bool BrowserView::CanActivate() const { 1459 if (!AppModalDialogQueue::GetInstance()->active_dialog()) 1460 return true; 1461 1462#if defined(USE_AURA) && defined(OS_CHROMEOS) 1463 // On Aura window manager controls all windows so settings focus via PostTask 1464 // will make only worse because posted task will keep trying to steal focus. 1465 AppModalDialogQueue::GetInstance()->ActivateModalDialog(); 1466#else 1467 // If another browser is app modal, flash and activate the modal browser. This 1468 // has to be done in a post task, otherwise if the user clicked on a window 1469 // that doesn't have the modal dialog the windows keep trying to get the focus 1470 // from each other on Windows. http://crbug.com/141650. 1471 base::MessageLoop::current()->PostTask( 1472 FROM_HERE, 1473 base::Bind(&BrowserView::ActivateAppModalDialog, 1474 activate_modal_dialog_factory_.GetWeakPtr())); 1475#endif 1476 return false; 1477} 1478 1479string16 BrowserView::GetWindowTitle() const { 1480 return browser_->GetWindowTitleForCurrentTab(); 1481} 1482 1483string16 BrowserView::GetAccessibleWindowTitle() const { 1484 if (IsOffTheRecord()) { 1485 return l10n_util::GetStringFUTF16( 1486 IDS_ACCESSIBLE_INCOGNITO_WINDOW_TITLE_FORMAT, 1487 GetWindowTitle()); 1488 } 1489 return GetWindowTitle(); 1490} 1491 1492views::View* BrowserView::GetInitiallyFocusedView() { 1493 return NULL; 1494} 1495 1496bool BrowserView::ShouldShowWindowTitle() const { 1497#if defined(USE_ASH) 1498 // For Ash only, app host windows do not show an icon, crbug.com/119411. 1499 // Child windows (i.e. popups) do show an icon. 1500 if (browser_->is_app() && browser_->app_type() == Browser::APP_TYPE_HOST) 1501 return false; 1502#endif 1503 return browser_->SupportsWindowFeature(Browser::FEATURE_TITLEBAR); 1504} 1505 1506gfx::ImageSkia BrowserView::GetWindowAppIcon() { 1507 if (browser_->is_app()) { 1508 WebContents* contents = browser_->tab_strip_model()->GetActiveWebContents(); 1509 extensions::TabHelper* extensions_tab_helper = 1510 contents ? extensions::TabHelper::FromWebContents(contents) : NULL; 1511 if (extensions_tab_helper && extensions_tab_helper->GetExtensionAppIcon()) 1512 return gfx::ImageSkia::CreateFrom1xBitmap( 1513 *extensions_tab_helper->GetExtensionAppIcon()); 1514 } 1515 1516 return GetWindowIcon(); 1517} 1518 1519gfx::ImageSkia BrowserView::GetWindowIcon() { 1520 if (browser_->is_app()) 1521 return browser_->GetCurrentPageIcon().AsImageSkia(); 1522 return gfx::ImageSkia(); 1523} 1524 1525bool BrowserView::ShouldShowWindowIcon() const { 1526#if defined(USE_ASH) 1527 // For Ash only, app host windows do not show an icon, crbug.com/119411. 1528 // Child windows (i.e. popups) do show an icon. 1529 if (browser_->is_app() && browser_->app_type() == Browser::APP_TYPE_HOST) 1530 return false; 1531#endif 1532 return browser_->SupportsWindowFeature(Browser::FEATURE_TITLEBAR); 1533} 1534 1535bool BrowserView::ExecuteWindowsCommand(int command_id) { 1536 // This function handles WM_SYSCOMMAND, WM_APPCOMMAND, and WM_COMMAND. 1537#if defined(OS_WIN) 1538 if (command_id == IDC_DEBUG_FRAME_TOGGLE) 1539 GetWidget()->DebugToggleFrameType(); 1540 1541 // In Windows 8 metro mode prevent sizing and moving. 1542 if (win8::IsSingleWindowMetroMode()) { 1543 // Windows uses the 4 lower order bits of |notification_code| for type- 1544 // specific information so we must exclude this when comparing. 1545 static const int sc_mask = 0xFFF0; 1546 if (((command_id & sc_mask) == SC_MOVE) || 1547 ((command_id & sc_mask) == SC_SIZE) || 1548 ((command_id & sc_mask) == SC_MAXIMIZE)) 1549 return true; 1550 } 1551#endif 1552 // Translate WM_APPCOMMAND command ids into a command id that the browser 1553 // knows how to handle. 1554 int command_id_from_app_command = GetCommandIDForAppCommandID(command_id); 1555 if (command_id_from_app_command != -1) 1556 command_id = command_id_from_app_command; 1557 1558 return chrome::ExecuteCommand(browser_.get(), command_id); 1559} 1560 1561std::string BrowserView::GetWindowName() const { 1562 return chrome::GetWindowPlacementKey(browser_.get()); 1563} 1564 1565void BrowserView::SaveWindowPlacement(const gfx::Rect& bounds, 1566 ui::WindowShowState show_state) { 1567 // If IsFullscreen() is true, we've just changed into fullscreen mode, and 1568 // we're catching the going-into-fullscreen sizing and positioning calls, 1569 // which we want to ignore. 1570 if (!ShouldSaveOrRestoreWindowPos()) 1571 return; 1572 1573 if (!IsFullscreen() && chrome::ShouldSaveWindowPlacement(browser_.get())) { 1574 WidgetDelegate::SaveWindowPlacement(bounds, show_state); 1575 chrome::SaveWindowPlacement(browser_.get(), bounds, show_state); 1576 } 1577} 1578 1579bool BrowserView::GetSavedWindowPlacement( 1580 gfx::Rect* bounds, 1581 ui::WindowShowState* show_state) const { 1582 if (!ShouldSaveOrRestoreWindowPos()) 1583 return false; 1584 chrome::GetSavedWindowBoundsAndShowState(browser_.get(), bounds, show_state); 1585 1586#if defined(USE_ASH) 1587 if (chrome::IsNativeWindowInAsh( 1588 const_cast<BrowserView*>(this)->GetNativeWindow())) { 1589 if (browser_->is_type_popup()) { 1590 // In case of a popup with an 'unspecified' location we are 1591 // looking for a good screen location. We are interpreting (0,0) as an 1592 // unspecified location. 1593 if (bounds->x() == 0 && bounds->y() == 0) { 1594 *bounds = ChromeShellDelegate::instance()->window_positioner()-> 1595 GetPopupPosition(*bounds); 1596 } 1597 } 1598 } 1599#endif 1600 1601 if (browser_->is_type_popup() && 1602 !browser_->is_app() && 1603 !browser_->is_devtools()) { 1604 // This is non-app popup window. The value passed in |bounds| represents 1605 // two pieces of information: 1606 // - the position of the window, in screen coordinates (outer position). 1607 // - the size of the content area (inner size). 1608 // We need to use these values to determine the appropriate size and 1609 // position of the resulting window. 1610 if (IsToolbarVisible()) { 1611 // If we're showing the toolbar, we need to adjust |*bounds| to include 1612 // its desired height, since the toolbar is considered part of the 1613 // window's client area as far as GetWindowBoundsForClientBounds is 1614 // concerned... 1615 bounds->set_height( 1616 bounds->height() + toolbar_->GetPreferredSize().height()); 1617 } 1618 1619 gfx::Rect window_rect = frame_->non_client_view()-> 1620 GetWindowBoundsForClientBounds(*bounds); 1621 window_rect.set_origin(bounds->origin()); 1622 1623 // When we are given x/y coordinates of 0 on a created popup window, 1624 // assume none were given by the window.open() command. 1625 if (window_rect.x() == 0 && window_rect.y() == 0) { 1626 gfx::Size size = window_rect.size(); 1627 window_rect.set_origin( 1628 WindowSizer::GetDefaultPopupOrigin(size, 1629 browser_->host_desktop_type())); 1630 } 1631 1632 *bounds = window_rect; 1633 *show_state = ui::SHOW_STATE_NORMAL; 1634 } 1635 1636 // We return true because we can _always_ locate reasonable bounds using the 1637 // WindowSizer, and we don't want to trigger the Window's built-in "size to 1638 // default" handling because the browser window has no default preferred 1639 // size. 1640 return true; 1641} 1642 1643views::View* BrowserView::GetContentsView() { 1644 return contents_web_view_; 1645} 1646 1647views::ClientView* BrowserView::CreateClientView(views::Widget* widget) { 1648 return this; 1649} 1650 1651void BrowserView::OnWidgetActivationChanged(views::Widget* widget, 1652 bool active) { 1653#if defined(USE_ASH) 1654 if (launcher_item_controller_.get()) 1655 launcher_item_controller_->BrowserActivationStateChanged(); 1656#endif 1657 1658 if (active) 1659 BrowserList::SetLastActive(browser_.get()); 1660} 1661 1662void BrowserView::OnWindowBeginUserBoundsChange() { 1663 WebContents* web_contents = GetActiveWebContents(); 1664 if (!web_contents) 1665 return; 1666 web_contents->GetRenderViewHost()->NotifyMoveOrResizeStarted(); 1667} 1668 1669void BrowserView::OnWidgetMove() { 1670 if (!initialized_) { 1671 // Creating the widget can trigger a move. Ignore it until we've initialized 1672 // things. 1673 return; 1674 } 1675 1676 // Cancel any tabstrip animations, some of them may be invalidated by the 1677 // window being repositioned. 1678 // Comment out for one cycle to see if this fixes dist tests. 1679 // tabstrip_->DestroyDragController(); 1680 1681 // status_bubble_ may be NULL if this is invoked during construction. 1682 if (status_bubble_.get()) 1683 status_bubble_->Reposition(); 1684 1685 chrome::HideBookmarkBubbleView(); 1686 1687 // Close the omnibox popup, if any. 1688 LocationBarView* location_bar_view = GetLocationBarView(); 1689 if (location_bar_view) 1690 location_bar_view->GetLocationEntry()->CloseOmniboxPopup(); 1691} 1692 1693views::Widget* BrowserView::GetWidget() { 1694 return View::GetWidget(); 1695} 1696 1697const views::Widget* BrowserView::GetWidget() const { 1698 return View::GetWidget(); 1699} 1700 1701void BrowserView::GetAccessiblePanes(std::vector<views::View*>* panes) { 1702 // This should be in the order of pane traversal of the panes using F6 1703 // (Windows) or Ctrl+Back/Forward (Chrome OS). If one of these is 1704 // invisible or has no focusable children, it will be automatically 1705 // skipped. 1706 panes->push_back(toolbar_); 1707 if (bookmark_bar_view_.get()) 1708 panes->push_back(bookmark_bar_view_.get()); 1709 if (infobar_container_) 1710 panes->push_back(infobar_container_); 1711 if (download_shelf_.get()) 1712 panes->push_back(download_shelf_.get()); 1713 panes->push_back(GetTabContentsContainerView()); 1714 if (devtools_container_->visible()) 1715 panes->push_back(devtools_container_); 1716} 1717 1718/////////////////////////////////////////////////////////////////////////////// 1719// BrowserView, views::ClientView overrides: 1720 1721bool BrowserView::CanClose() { 1722 // You cannot close a frame for which there is an active originating drag 1723 // session. 1724 if (tabstrip_ && !tabstrip_->IsTabStripCloseable()) 1725 return false; 1726 1727 // Give beforeunload handlers the chance to cancel the close before we hide 1728 // the window below. 1729 if (!browser_->ShouldCloseWindow()) 1730 return false; 1731 1732 bool fast_tab_closing_enabled = 1733 CommandLine::ForCurrentProcess()->HasSwitch(switches::kEnableFastUnload); 1734 1735 if (!browser_->tab_strip_model()->empty()) { 1736 // Tab strip isn't empty. Hide the frame (so it appears to have closed 1737 // immediately) and close all the tabs, allowing the renderers to shut 1738 // down. When the tab strip is empty we'll be called back again. 1739 frame_->Hide(); 1740 browser_->OnWindowClosing(); 1741 if (fast_tab_closing_enabled) 1742 browser_->tab_strip_model()->CloseAllTabs(); 1743 return false; 1744 } else if (fast_tab_closing_enabled && 1745 !browser_->HasCompletedUnloadProcessing()) { 1746 // The browser needs to finish running unload handlers. 1747 // Hide the frame (so it appears to have closed immediately), and 1748 // the browser will call us back again when it is ready to close. 1749 frame_->Hide(); 1750 return false; 1751 } 1752 1753 // Empty TabStripModel, it's now safe to allow the Window to be closed. 1754 content::NotificationService::current()->Notify( 1755 chrome::NOTIFICATION_WINDOW_CLOSED, 1756 content::Source<gfx::NativeWindow>(frame_->GetNativeWindow()), 1757 content::NotificationService::NoDetails()); 1758 return true; 1759} 1760 1761int BrowserView::NonClientHitTest(const gfx::Point& point) { 1762 return GetBrowserViewLayout()->NonClientHitTest(point); 1763} 1764 1765gfx::Size BrowserView::GetMinimumSize() { 1766 return GetBrowserViewLayout()->GetMinimumSize(); 1767} 1768 1769/////////////////////////////////////////////////////////////////////////////// 1770// BrowserView, views::View overrides: 1771 1772const char* BrowserView::GetClassName() const { 1773 return kViewClassName; 1774} 1775 1776void BrowserView::Layout() { 1777 if (ignore_layout_) 1778 return; 1779 1780 views::View::Layout(); 1781 1782 // TODO(jamescook): Why was this in the middle of layout code? 1783 toolbar_->location_bar()->SetLocationEntryFocusable(IsToolbarVisible()); 1784 1785 // The status bubble position requires that all other layout finish first. 1786 LayoutStatusBubble(); 1787} 1788 1789void BrowserView::PaintChildren(gfx::Canvas* canvas) { 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_) 1795 child->Paint(canvas); 1796 } 1797 1798 infobar_container_->Paint(canvas); 1799} 1800 1801void BrowserView::ViewHierarchyChanged( 1802 const ViewHierarchyChangedDetails& details) { 1803 if (!initialized_ && details.is_add && details.child == this && GetWidget()) { 1804 InitViews(); 1805 initialized_ = true; 1806 } 1807} 1808 1809void BrowserView::ChildPreferredSizeChanged(View* child) { 1810 Layout(); 1811} 1812 1813void BrowserView::GetAccessibleState(ui::AccessibleViewState* state) { 1814 state->role = ui::AccessibilityTypes::ROLE_CLIENT; 1815} 1816 1817/////////////////////////////////////////////////////////////////////////////// 1818// BrowserView, ui::AcceleratorTarget overrides: 1819 1820bool BrowserView::AcceleratorPressed(const ui::Accelerator& accelerator) { 1821#if defined(OS_CHROMEOS) 1822 // If accessibility is enabled, stop speech and return false so that key 1823 // combinations involving Search can be used for extra accessibility 1824 // functionality. 1825 if (accelerator.key_code() == ui::VKEY_LWIN && 1826 g_browser_process->local_state()->GetBoolean( 1827 prefs::kSpokenFeedbackEnabled)) { 1828 TtsController::GetInstance()->Stop(); 1829 return false; 1830 } 1831#endif 1832 1833 std::map<ui::Accelerator, int>::const_iterator iter = 1834 accelerator_table_.find(accelerator); 1835 DCHECK(iter != accelerator_table_.end()); 1836 int command_id = iter->second; 1837 1838 chrome::BrowserCommandController* controller = browser_->command_controller(); 1839 if (!controller->block_command_execution()) 1840 UpdateAcceleratorMetrics(accelerator, command_id); 1841 return chrome::ExecuteCommand(browser_.get(), command_id); 1842} 1843 1844/////////////////////////////////////////////////////////////////////////////// 1845// BrowserView, OmniboxPopupModelObserver overrides: 1846void BrowserView::OnOmniboxPopupShownOrHidden() { 1847 infobar_container_->SetMaxTopArrowHeight(GetMaxTopInfoBarArrowHeight()); 1848} 1849 1850/////////////////////////////////////////////////////////////////////////////// 1851// BrowserView, ImmersiveModeController::Delegate overrides: 1852 1853BookmarkBarView* BrowserView::GetBookmarkBar() { 1854 return bookmark_bar_view_.get(); 1855} 1856 1857FullscreenController* BrowserView::GetFullscreenController() { 1858 // Cannot be injected into ImmersiveModeController because it is constructed 1859 // after BrowserView. 1860 return browser()->fullscreen_controller(); 1861} 1862 1863void BrowserView::FullscreenStateChanged() { 1864 if (IsFullscreen()) { 1865 ProcessFullscreen(true, FOR_DESKTOP, GURL(), 1866 FEB_TYPE_BROWSER_FULLSCREEN_EXIT_INSTRUCTION); 1867 } else { 1868 ProcessFullscreen(false, FOR_DESKTOP, GURL(), FEB_TYPE_NONE); 1869 } 1870} 1871 1872void BrowserView::SetImmersiveStyle(bool immersive) { 1873 // Only the tab strip changes its painting style for immersive fullscreen. 1874 if (tabstrip_) 1875 tabstrip_->SetImmersiveStyle(immersive); 1876} 1877 1878WebContents* BrowserView::GetWebContents() { 1879 return GetActiveWebContents(); 1880} 1881 1882/////////////////////////////////////////////////////////////////////////////// 1883// BrowserView, InfoBarContainer::Delegate overrides: 1884 1885SkColor BrowserView::GetInfoBarSeparatorColor() const { 1886 // NOTE: Keep this in sync with ToolbarView::OnPaint()! 1887 return (IsTabStripVisible() || !frame_->ShouldUseNativeFrame()) ? 1888 ThemeProperties::GetDefaultColor( 1889 ThemeProperties::COLOR_TOOLBAR_SEPARATOR) : 1890 SK_ColorBLACK; 1891} 1892 1893void BrowserView::InfoBarContainerStateChanged(bool is_animating) { 1894 ToolbarSizeChanged(is_animating); 1895} 1896 1897bool BrowserView::DrawInfoBarArrows(int* x) const { 1898 if (x) { 1899 const LocationIconView* location_icon_view = 1900 toolbar_->location_bar()->location_icon_view(); 1901 gfx::Point icon_center(location_icon_view->GetImageBounds().CenterPoint()); 1902 ConvertPointToTarget(location_icon_view, this, &icon_center); 1903 *x = icon_center.x(); 1904 } 1905 return true; 1906} 1907 1908bool BrowserView::SplitHandleMoved(views::SingleSplitView* sender) { 1909 for (int i = 0; i < sender->child_count(); ++i) 1910 sender->child_at(i)->InvalidateLayout(); 1911 SchedulePaint(); 1912 Layout(); 1913 return false; 1914} 1915 1916void BrowserView::OnSysColorChange() { 1917 chrome::MaybeShowInvertBubbleView(browser_.get(), contents_container_); 1918} 1919 1920void BrowserView::InitViews() { 1921 GetWidget()->AddObserver(this); 1922 1923 // Stow a pointer to this object onto the window handle so that we can get at 1924 // it later when all we have is a native view. 1925 GetWidget()->SetNativeWindowProperty(kBrowserViewKey, this); 1926 1927 // Stow a pointer to the browser's profile onto the window handle so that we 1928 // can get it later when all we have is a native view. 1929 GetWidget()->SetNativeWindowProperty(Profile::kProfileKey, 1930 browser_->profile()); 1931 1932 // Start a hung plugin window detector for this browser object (as long as 1933 // hang detection is not disabled). 1934 if (!CommandLine::ForCurrentProcess()->HasSwitch( 1935 switches::kDisableHangMonitor)) { 1936 InitHangMonitor(); 1937 } 1938 1939 LoadAccelerators(); 1940 1941 infobar_container_ = new InfoBarContainerView(this); 1942 AddChildView(infobar_container_); 1943 1944 contents_web_view_ = new views::WebView(browser_->profile()); 1945 contents_web_view_->set_id(VIEW_ID_TAB_CONTAINER); 1946 contents_container_ = new ContentsContainer(contents_web_view_); 1947 1948 SkColor bg_color = GetWidget()->GetThemeProvider()-> 1949 GetColor(ThemeProperties::COLOR_TOOLBAR); 1950 1951 devtools_container_ = new views::WebView(browser_->profile()); 1952 devtools_container_->set_id(VIEW_ID_DEV_TOOLS_DOCKED); 1953 devtools_container_->SetVisible(false); 1954 1955 views::View* contents_container_view = contents_container_; 1956 1957 contents_split_ = new views::SingleSplitView( 1958 contents_container_view, 1959 devtools_container_, 1960 views::SingleSplitView::VERTICAL_SPLIT, 1961 this); 1962 contents_split_->set_id(VIEW_ID_CONTENTS_SPLIT); 1963 contents_split_->SetAccessibleName( 1964 l10n_util::GetStringUTF16(IDS_ACCNAME_WEB_CONTENTS)); 1965 contents_split_->set_background( 1966 views::Background::CreateSolidBackground(bg_color)); 1967 AddChildView(contents_split_); 1968 set_contents_view(contents_split_); 1969 1970 InitStatusBubble(); 1971 1972 // Top container holds tab strip and toolbar and lives at the front of the 1973 // view hierarchy. 1974 top_container_ = new TopContainerView(this); 1975 AddChildView(top_container_); 1976 1977 // TabStrip takes ownership of the controller. 1978 BrowserTabStripController* tabstrip_controller = 1979 new BrowserTabStripController(browser_.get(), 1980 browser_->tab_strip_model()); 1981 tabstrip_ = new TabStrip(tabstrip_controller); 1982 top_container_->AddChildView(tabstrip_); 1983 tabstrip_controller->InitFromModel(tabstrip_); 1984 1985 toolbar_ = new ToolbarView(browser_.get()); 1986 top_container_->AddChildView(toolbar_); 1987 toolbar_->Init(); 1988 1989 // Create do-nothing view for the sake of controlling the z-order of the find 1990 // bar widget. 1991 find_bar_host_view_ = new View(); 1992 AddChildView(find_bar_host_view_); 1993 1994 if (window_switcher_button_) 1995 AddChildView(window_switcher_button_); 1996 1997 immersive_mode_controller_->Init(this, GetWidget(), top_container_); 1998 1999 BrowserViewLayout* browser_view_layout = new BrowserViewLayout; 2000 browser_view_layout->Init(new BrowserViewLayoutDelegateImpl(this), 2001 browser(), 2002 this, 2003 top_container_, 2004 tabstrip_, 2005 toolbar_, 2006 infobar_container_, 2007 contents_split_, 2008 contents_container_, 2009 immersive_mode_controller_.get()); 2010 SetLayoutManager(browser_view_layout); 2011 2012#if defined(OS_WIN) && !defined(USE_AURA) 2013 // Create a custom JumpList and add it to an observer of TabRestoreService 2014 // so we can update the custom JumpList when a tab is added or removed. 2015 if (JumpList::Enabled()) { 2016 load_complete_listener_.reset(new LoadCompleteListener(this)); 2017 } 2018#endif 2019 2020 GetLocationBar()->GetLocationEntry()->model()->popup_model()->AddObserver( 2021 this); 2022 2023 // We're now initialized and ready to process Layout requests. 2024 ignore_layout_ = false; 2025} 2026 2027void BrowserView::LoadingAnimationCallback() { 2028 base::TimeTicks now = base::TimeTicks::Now(); 2029 if (!last_animation_time_.is_null()) { 2030 UMA_HISTOGRAM_TIMES( 2031 "Tabs.LoadingAnimationTime", 2032 now - last_animation_time_); 2033 } 2034 last_animation_time_ = now; 2035 if (browser_->is_type_tabbed()) { 2036 // Loading animations are shown in the tab for tabbed windows. We check the 2037 // browser type instead of calling IsTabStripVisible() because the latter 2038 // will return false for fullscreen windows, but we still need to update 2039 // their animations (so that when they come out of fullscreen mode they'll 2040 // be correct). 2041 tabstrip_->UpdateLoadingAnimations(); 2042 } else if (ShouldShowWindowIcon()) { 2043 // ... or in the window icon area for popups and app windows. 2044 WebContents* web_contents = 2045 browser_->tab_strip_model()->GetActiveWebContents(); 2046 // GetActiveWebContents can return NULL for example under Purify when 2047 // the animations are running slowly and this function is called on a timer 2048 // through LoadingAnimationCallback. 2049 frame_->UpdateThrobber(web_contents && web_contents->IsLoading()); 2050 } 2051} 2052 2053void BrowserView::OnLoadCompleted() { 2054#if defined(OS_WIN) && !defined(USE_AURA) 2055 DCHECK(!jumplist_); 2056 jumplist_ = new JumpList(); 2057 jumplist_->AddObserver(browser_->profile()); 2058#endif 2059} 2060 2061BrowserViewLayout* BrowserView::GetBrowserViewLayout() const { 2062 return static_cast<BrowserViewLayout*>(GetLayoutManager()); 2063} 2064 2065void BrowserView::LayoutStatusBubble() { 2066 // In restored mode, the client area has a client edge between it and the 2067 // frame. 2068 int overlap = StatusBubbleViews::kShadowThickness; 2069 // The extra pixels defined by kClientEdgeThickness is only drawn in frame 2070 // content border on windows for non-aura build. 2071#if !defined(USE_ASH) 2072 overlap += 2073 IsMaximized() ? 0 : views::NonClientFrameView::kClientEdgeThickness; 2074#endif 2075 int height = status_bubble_->GetPreferredSize().height(); 2076 int contents_height = status_bubble_->base_view()->bounds().height(); 2077 gfx::Point origin(-overlap, contents_height - height + overlap); 2078 status_bubble_->SetBounds(origin.x(), origin.y(), width() / 3, height); 2079} 2080 2081bool BrowserView::MaybeShowBookmarkBar(WebContents* contents) { 2082 bool show_bookmark_bar = contents && 2083 browser_->SupportsWindowFeature(Browser::FEATURE_BOOKMARKBAR); 2084 if (!show_bookmark_bar && !bookmark_bar_view_.get()) 2085 return false; 2086 if (!bookmark_bar_view_.get()) { 2087 bookmark_bar_view_.reset(new BookmarkBarView(browser_.get(), this)); 2088 bookmark_bar_view_->set_owned_by_client(); 2089 bookmark_bar_view_->set_background( 2090 new BookmarkExtensionBackground(this, 2091 bookmark_bar_view_.get(), 2092 browser_.get())); 2093 bookmark_bar_view_->SetBookmarkBarState( 2094 browser_->bookmark_bar_state(), 2095 BookmarkBar::DONT_ANIMATE_STATE_CHANGE); 2096 GetBrowserViewLayout()->set_bookmark_bar(bookmark_bar_view_.get()); 2097 } 2098 bookmark_bar_view_->SetVisible(show_bookmark_bar); 2099 bookmark_bar_view_->SetPageNavigator(contents); 2100 2101 // Update parenting for the bookmark bar. This may detach it from all views. 2102 bool needs_layout = false; 2103 views::View* new_parent = NULL; 2104 if (show_bookmark_bar) { 2105 if (bookmark_bar_view_->IsDetached()) 2106 new_parent = this; 2107 else 2108 new_parent = top_container_; 2109 } 2110 if (new_parent != bookmark_bar_view_->parent()) { 2111 SetBookmarkBarParent(new_parent); 2112 needs_layout = true; 2113 } 2114 2115 // Check for updates to the desired size. 2116 if (bookmark_bar_view_->GetPreferredSize().height() != 2117 bookmark_bar_view_->height()) 2118 needs_layout = true; 2119 2120 return needs_layout; 2121} 2122 2123void BrowserView::SetBookmarkBarParent(views::View* new_parent) { 2124 if (new_parent == this) { 2125 // Add it underneath |top_container_| or at the end if top container isn't 2126 // found. 2127 int top_container_index = GetIndexOf(top_container_); 2128 if (top_container_index >= 0) 2129 AddChildViewAt(bookmark_bar_view_.get(), top_container_index); 2130 else 2131 AddChildView(bookmark_bar_view_.get()); 2132 } else if (new_parent) { 2133 // No special stacking is required for other parents. 2134 new_parent->AddChildView(bookmark_bar_view_.get()); 2135 } else { 2136 // Bookmark bar is being detached from all views because it is hidden. 2137 bookmark_bar_view_->parent()->RemoveChildView(bookmark_bar_view_.get()); 2138 } 2139} 2140 2141bool BrowserView::MaybeShowInfoBar(WebContents* contents) { 2142 // TODO(beng): Remove this function once the interface between 2143 // InfoBarContainer, DownloadShelfView and WebContents and this 2144 // view is sorted out. 2145 return true; 2146} 2147 2148void BrowserView::UpdateDevToolsForContents(WebContents* web_contents) { 2149 DevToolsWindow* new_devtools_window = web_contents ? 2150 DevToolsWindow::GetDockedInstanceForInspectedTab(web_contents) : NULL; 2151 // Fast return in case of the same window having same orientation. 2152 if (devtools_window_ == new_devtools_window) { 2153 if (!new_devtools_window || 2154 (new_devtools_window->dock_side() == devtools_dock_side_)) { 2155 return; 2156 } 2157 } 2158 2159 // Replace tab contents. 2160 if (devtools_window_ != new_devtools_window) { 2161 devtools_container_->SetWebContents( 2162 new_devtools_window ? new_devtools_window->web_contents() : NULL); 2163 } 2164 2165 // Store last used position. 2166 if (devtools_window_) { 2167 int split_size = contents_split_->GetDividerSize(); 2168 if (devtools_dock_side_ == DEVTOOLS_DOCK_SIDE_RIGHT) { 2169 devtools_window_->SetWidth(contents_split_->width() - 2170 split_size - contents_split_->divider_offset()); 2171 } else if (devtools_dock_side_ == DEVTOOLS_DOCK_SIDE_BOTTOM) { 2172 devtools_window_->SetHeight(contents_split_->height() - 2173 split_size - contents_split_->divider_offset()); 2174 } 2175 } 2176 2177 // Show / hide container if necessary. Changing dock orientation is 2178 // hide + show. 2179 bool should_hide = devtools_window_ && (!new_devtools_window || 2180 devtools_dock_side_ != new_devtools_window->dock_side()); 2181 bool should_show = new_devtools_window && (!devtools_window_ || should_hide); 2182 2183 if (should_hide) 2184 HideDevToolsContainer(); 2185 2186 devtools_window_ = new_devtools_window; 2187 2188 if (should_show) { 2189 devtools_dock_side_ = new_devtools_window->dock_side(); 2190 ShowDevToolsContainer(); 2191 } else if (new_devtools_window) { 2192 UpdateDevToolsSplitPosition(); 2193 contents_split_->Layout(); 2194 } 2195} 2196 2197void BrowserView::ShowDevToolsContainer() { 2198 if (!devtools_focus_tracker_.get()) { 2199 // Install devtools focus tracker when dev tools window is shown for the 2200 // first time. 2201 devtools_focus_tracker_.reset( 2202 new views::ExternalFocusTracker(devtools_container_, 2203 GetFocusManager())); 2204 } 2205 2206 gfx::Size min_devtools_size(devtools_window_->GetMinimumWidth(), 2207 devtools_window_->GetMinimumHeight()); 2208 devtools_container_->SetPreferredSize(min_devtools_size); 2209 2210 devtools_container_->SetVisible(true); 2211 devtools_dock_side_ = devtools_window_->dock_side(); 2212 bool dock_to_right = devtools_dock_side_ == DEVTOOLS_DOCK_SIDE_RIGHT; 2213 contents_split_->set_orientation( 2214 dock_to_right ? views::SingleSplitView::HORIZONTAL_SPLIT 2215 : views::SingleSplitView::VERTICAL_SPLIT); 2216 UpdateDevToolsSplitPosition(); 2217 contents_split_->InvalidateLayout(); 2218 Layout(); 2219} 2220 2221void BrowserView::HideDevToolsContainer() { 2222 // Restore focus to the last focused view when hiding devtools window. 2223 devtools_focus_tracker_->FocusLastFocusedExternalView(); 2224 devtools_container_->SetVisible(false); 2225 contents_split_->InvalidateLayout(); 2226 Layout(); 2227} 2228 2229void BrowserView::UpdateDevToolsSplitPosition() { 2230 contents_split_->set_resize_disabled( 2231 devtools_window_->dock_side() == DEVTOOLS_DOCK_SIDE_MINIMIZED); 2232 int split_size = contents_split_->GetDividerSize(); 2233 if (devtools_window_->dock_side() == DEVTOOLS_DOCK_SIDE_RIGHT) { 2234 int split_offset = contents_split_->width() - split_size - 2235 devtools_window_->GetWidth(contents_split_->width()); 2236 contents_split_->set_divider_offset(split_offset); 2237 } else { 2238 int height = devtools_window_->dock_side() == DEVTOOLS_DOCK_SIDE_MINIMIZED ? 2239 devtools_window_->GetMinimizedHeight() : 2240 devtools_window_->GetHeight(contents_split_->height()); 2241 int split_offset = contents_split_->height() - split_size - height; 2242 contents_split_->set_divider_offset(split_offset); 2243 } 2244} 2245 2246void BrowserView::UpdateUIForContents(WebContents* contents) { 2247 bool needs_layout = MaybeShowBookmarkBar(contents); 2248 // TODO(jamescook): This function always returns true. Remove it and figure 2249 // out when layout is actually required. 2250 needs_layout |= MaybeShowInfoBar(contents); 2251 if (needs_layout) 2252 Layout(); 2253} 2254 2255void BrowserView::ProcessFullscreen(bool fullscreen, 2256 FullscreenType type, 2257 const GURL& url, 2258 FullscreenExitBubbleType bubble_type) { 2259 // Reduce jankiness during the following position changes by: 2260 // * Hiding the window until it's in the final position 2261 // * Ignoring all intervening Layout() calls, which resize the webpage and 2262 // thus are slow and look ugly 2263 ignore_layout_ = true; 2264 LocationBarView* location_bar = GetLocationBarView(); 2265#if defined(OS_WIN) && !defined(USE_AURA) 2266 OmniboxViewWin* omnibox_win = 2267 GetOmniboxViewWin(location_bar->GetLocationEntry()); 2268#endif 2269 2270 if (type == FOR_METRO || !fullscreen) { 2271 // Hide the fullscreen bubble as soon as possible, since the mode toggle can 2272 // take enough time for the user to notice. 2273 fullscreen_bubble_.reset(); 2274 } 2275 2276 if (fullscreen) { 2277 // Move focus out of the location bar if necessary. 2278 views::FocusManager* focus_manager = GetFocusManager(); 2279 DCHECK(focus_manager); 2280 // Look for focus in the location bar itself or any child view. 2281 if (location_bar->Contains(focus_manager->GetFocusedView())) 2282 focus_manager->ClearFocus(); 2283 2284#if defined(OS_WIN) && !defined(USE_AURA) 2285 if (omnibox_win) { 2286 // If we don't hide the edit and force it to not show until we come out of 2287 // fullscreen, then if the user was on the New Tab Page, the edit contents 2288 // will appear atop the web contents once we go into fullscreen mode. This 2289 // has something to do with how we move the main window while it's hidden; 2290 // if we don't hide the main window below, we don't get this problem. 2291 omnibox_win->set_force_hidden(true); 2292 ShowWindow(omnibox_win->m_hWnd, SW_HIDE); 2293 } 2294#endif 2295 } 2296#if defined(OS_WIN) && !defined(USE_AURA) 2297 views::ScopedFullscreenVisibility visibility(frame_->GetNativeView()); 2298#endif 2299 2300 if (type == FOR_METRO) { 2301#if defined(OS_WIN) && !defined(USE_AURA) 2302 // Enter metro snap mode. 2303 static_cast<views::NativeWidgetWin*>( 2304 frame_->native_widget())->SetMetroSnapFullscreen(fullscreen); 2305#endif 2306 } else { 2307 // Toggle fullscreen mode. 2308 frame_->SetFullscreen(fullscreen); 2309 } 2310 2311 // Enable immersive before the browser refreshes its list of enabled commands. 2312 if (ShouldUseImmersiveFullscreenForUrl(url)) 2313 immersive_mode_controller_->SetEnabled(fullscreen); 2314 2315 browser_->WindowFullscreenStateChanged(); 2316 2317 if (fullscreen) { 2318 if (!chrome::IsRunningInAppMode() && 2319 type != FOR_METRO && 2320 !ShouldUseImmersiveFullscreenForUrl(url)) { 2321 fullscreen_bubble_.reset(new FullscreenExitBubbleViews( 2322 this, url, bubble_type)); 2323 } 2324 } else { 2325#if defined(OS_WIN) && !defined(USE_AURA) 2326 if (omnibox_win) { 2327 // Show the edit again since we're no longer in fullscreen mode. 2328 omnibox_win->set_force_hidden(false); 2329 ShowWindow(omnibox_win->m_hWnd, SW_SHOW); 2330 } 2331#endif 2332 } 2333 2334 // Undo our anti-jankiness hacks and force a re-layout. We also need to 2335 // recompute the height of the infobar top arrow because toggling in and out 2336 // of fullscreen changes it. Calling ToolbarSizeChanged() will do both these 2337 // things since it computes the arrow height directly and forces a layout 2338 // indirectly via UpdateUIForContents(). 2339 ignore_layout_ = false; 2340 ToolbarSizeChanged(false); 2341} 2342 2343bool BrowserView::ShouldUseImmersiveFullscreenForUrl(const GURL& url) const { 2344 bool is_browser_fullscreen = url.is_empty(); 2345 return ImmersiveFullscreenConfiguration::UseImmersiveFullscreen() && 2346 is_browser_fullscreen && IsBrowserTypeNormal(); 2347} 2348 2349void BrowserView::LoadAccelerators() { 2350#if defined(OS_WIN) && !defined(USE_AURA) 2351 HACCEL accelerator_table = AtlLoadAccelerators(IDR_MAINFRAME); 2352 DCHECK(accelerator_table); 2353 2354 // We have to copy the table to access its contents. 2355 int count = CopyAcceleratorTable(accelerator_table, 0, 0); 2356 if (count == 0) { 2357 // Nothing to do in that case. 2358 return; 2359 } 2360 2361 ACCEL* accelerators = static_cast<ACCEL*>(malloc(sizeof(ACCEL) * count)); 2362 CopyAcceleratorTable(accelerator_table, accelerators, count); 2363 2364 views::FocusManager* focus_manager = GetFocusManager(); 2365 DCHECK(focus_manager); 2366 2367 // Let's fill our own accelerator table. 2368 for (int i = 0; i < count; ++i) { 2369 ui::Accelerator accelerator( 2370 static_cast<ui::KeyboardCode>(accelerators[i].key), 2371 ui::GetModifiersFromACCEL(accelerators[i])); 2372 accelerator_table_[accelerator] = accelerators[i].cmd; 2373 2374 // Also register with the focus manager. 2375 focus_manager->RegisterAccelerator( 2376 accelerator, ui::AcceleratorManager::kNormalPriority, this); 2377 } 2378 2379 // We don't need the Windows accelerator table anymore. 2380 free(accelerators); 2381#else 2382 views::FocusManager* focus_manager = GetFocusManager(); 2383 DCHECK(focus_manager); 2384 2385 // Let's fill our own accelerator table. 2386 const bool is_app_mode = chrome::IsRunningInForcedAppMode(); 2387 const std::vector<chrome::AcceleratorMapping> accelerator_list( 2388 chrome::GetAcceleratorList()); 2389 for (std::vector<chrome::AcceleratorMapping>::const_iterator it = 2390 accelerator_list.begin(); it != accelerator_list.end(); ++it) { 2391 // In app mode, only allow accelerators of white listed commands to pass 2392 // through. 2393 if (is_app_mode && !chrome::IsCommandAllowedInAppMode(it->command_id)) 2394 continue; 2395 2396 ui::Accelerator accelerator(it->keycode, it->modifiers); 2397 accelerator_table_[accelerator] = it->command_id; 2398 2399 // Also register with the focus manager. 2400 focus_manager->RegisterAccelerator( 2401 accelerator, ui::AcceleratorManager::kNormalPriority, this); 2402 } 2403#endif 2404} 2405 2406int BrowserView::GetCommandIDForAppCommandID(int app_command_id) const { 2407#if defined(OS_WIN) 2408 switch (app_command_id) { 2409 // NOTE: The order here matches the APPCOMMAND declaration order in the 2410 // Windows headers. 2411 case APPCOMMAND_BROWSER_BACKWARD: return IDC_BACK; 2412 case APPCOMMAND_BROWSER_FORWARD: return IDC_FORWARD; 2413 case APPCOMMAND_BROWSER_REFRESH: return IDC_RELOAD; 2414 case APPCOMMAND_BROWSER_HOME: return IDC_HOME; 2415 case APPCOMMAND_BROWSER_STOP: return IDC_STOP; 2416 case APPCOMMAND_BROWSER_SEARCH: return IDC_FOCUS_SEARCH; 2417 case APPCOMMAND_HELP: return IDC_HELP_PAGE_VIA_KEYBOARD; 2418 case APPCOMMAND_NEW: return IDC_NEW_TAB; 2419 case APPCOMMAND_OPEN: return IDC_OPEN_FILE; 2420 case APPCOMMAND_CLOSE: return IDC_CLOSE_TAB; 2421 case APPCOMMAND_SAVE: return IDC_SAVE_PAGE; 2422 case APPCOMMAND_PRINT: return IDC_PRINT; 2423 case APPCOMMAND_COPY: return IDC_COPY; 2424 case APPCOMMAND_CUT: return IDC_CUT; 2425 case APPCOMMAND_PASTE: return IDC_PASTE; 2426 2427 // TODO(pkasting): http://b/1113069 Handle these. 2428 case APPCOMMAND_UNDO: 2429 case APPCOMMAND_REDO: 2430 case APPCOMMAND_SPELL_CHECK: 2431 default: return -1; 2432 } 2433#else 2434 // App commands are Windows-specific so there's nothing to do here. 2435 return -1; 2436#endif 2437} 2438 2439void BrowserView::InitHangMonitor() { 2440#if defined(OS_WIN) && !defined(USE_AURA) 2441 PrefService* pref_service = g_browser_process->local_state(); 2442 if (!pref_service) 2443 return; 2444 2445 int plugin_message_response_timeout = 2446 pref_service->GetInteger(prefs::kPluginMessageResponseTimeout); 2447 int hung_plugin_detect_freq = 2448 pref_service->GetInteger(prefs::kHungPluginDetectFrequency); 2449 if ((hung_plugin_detect_freq > 0) && 2450 hung_window_detector_.Initialize(GetWidget()->GetNativeView(), 2451 plugin_message_response_timeout)) { 2452 ticker_.set_tick_interval(hung_plugin_detect_freq); 2453 ticker_.RegisterTickHandler(&hung_window_detector_); 2454 ticker_.Start(); 2455 2456 pref_service->SetInteger(prefs::kPluginMessageResponseTimeout, 2457 plugin_message_response_timeout); 2458 pref_service->SetInteger(prefs::kHungPluginDetectFrequency, 2459 hung_plugin_detect_freq); 2460 } 2461#endif 2462} 2463 2464void BrowserView::UpdateAcceleratorMetrics( 2465 const ui::Accelerator& accelerator, int command_id) { 2466 const ui::KeyboardCode key_code = accelerator.key_code(); 2467 if (command_id == IDC_HELP_PAGE_VIA_KEYBOARD && key_code == ui::VKEY_F1) 2468 content::RecordAction(UserMetricsAction("ShowHelpTabViaF1")); 2469 2470 if (command_id == IDC_BOOKMARK_PAGE) 2471 UMA_HISTOGRAM_ENUMERATION("Bookmarks.EntryPoint", 2472 bookmark_utils::ENTRY_POINT_ACCELERATOR, 2473 bookmark_utils::ENTRY_POINT_LIMIT); 2474 2475#if defined(OS_CHROMEOS) 2476 // Collect information about the relative popularity of various accelerators 2477 // on Chrome OS. 2478 switch (command_id) { 2479 case IDC_BACK: 2480 if (key_code == ui::VKEY_BACK) 2481 content::RecordAction(UserMetricsAction("Accel_Back_Backspace")); 2482 else if (key_code == ui::VKEY_BROWSER_BACK) 2483 content::RecordAction(UserMetricsAction("Accel_Back_F1")); 2484 else if (key_code == ui::VKEY_LEFT) 2485 content::RecordAction(UserMetricsAction("Accel_Back_Left")); 2486 break; 2487 case IDC_FORWARD: 2488 if (key_code == ui::VKEY_BACK) 2489 content::RecordAction(UserMetricsAction("Accel_Forward_Backspace")); 2490 else if (key_code == ui::VKEY_BROWSER_FORWARD) 2491 content::RecordAction(UserMetricsAction("Accel_Forward_F2")); 2492 else if (key_code == ui::VKEY_RIGHT) 2493 content::RecordAction(UserMetricsAction("Accel_Forward_Right")); 2494 break; 2495 case IDC_RELOAD: 2496 case IDC_RELOAD_IGNORING_CACHE: 2497 if (key_code == ui::VKEY_R) 2498 content::RecordAction(UserMetricsAction("Accel_Reload_R")); 2499 else if (key_code == ui::VKEY_BROWSER_REFRESH) 2500 content::RecordAction(UserMetricsAction("Accel_Reload_F3")); 2501 break; 2502 case IDC_FOCUS_LOCATION: 2503 if (key_code == ui::VKEY_D) 2504 content::RecordAction(UserMetricsAction("Accel_FocusLocation_D")); 2505 else if (key_code == ui::VKEY_L) 2506 content::RecordAction(UserMetricsAction("Accel_FocusLocation_L")); 2507 break; 2508 case IDC_FOCUS_SEARCH: 2509 if (key_code == ui::VKEY_E) 2510 content::RecordAction(UserMetricsAction("Accel_FocusSearch_E")); 2511 else if (key_code == ui::VKEY_K) 2512 content::RecordAction(UserMetricsAction("Accel_FocusSearch_K")); 2513 break; 2514 default: 2515 // Do nothing. 2516 break; 2517 } 2518#endif 2519} 2520 2521void BrowserView::CreateLauncherIcon() { 2522#if defined(USE_ASH) 2523 if (chrome::IsNativeWindowInAsh(GetNativeWindow()) && 2524 !launcher_item_controller_.get()) { 2525 launcher_item_controller_.reset( 2526 BrowserLauncherItemController::Create(browser_.get())); 2527 } 2528#endif // defined(USE_ASH) 2529} 2530 2531// static 2532BrowserWindow* BrowserWindow::CreateBrowserWindow(Browser* browser) { 2533 // Create the view and the frame. The frame will attach itself via the view 2534 // so we don't need to do anything with the pointer. 2535 BrowserView* view = new BrowserView(); 2536 view->Init(browser); 2537 (new BrowserFrame(view))->InitBrowserFrame(); 2538 view->GetWidget()->non_client_view()->SetAccessibleName( 2539 l10n_util::GetStringUTF16(IDS_PRODUCT_NAME)); 2540 return view; 2541} 2542 2543void BrowserView::ShowAvatarBubble(WebContents* web_contents, 2544 const gfx::Rect& rect) { 2545 gfx::Point origin(rect.origin()); 2546 views::View::ConvertPointToScreen(GetTabContentsContainerView(), &origin); 2547 gfx::Rect bounds(origin, rect.size()); 2548 2549 AvatarMenuBubbleView::ShowBubble(this, views::BubbleBorder::TOP_RIGHT, 2550 views::BubbleBorder::ALIGN_EDGE_TO_ANCHOR_EDGE, bounds, browser_.get()); 2551} 2552 2553void BrowserView::ShowAvatarBubbleFromAvatarButton() { 2554 AvatarMenuButton* button = frame_->GetAvatarMenuButton(); 2555 if (button) 2556 button->ShowAvatarBubble(); 2557} 2558 2559void BrowserView::ShowPasswordGenerationBubble( 2560 const gfx::Rect& rect, 2561 const content::PasswordForm& form, 2562 autofill::PasswordGenerator* password_generator) { 2563 // Create a rect in the content bounds that the bubble will point to. 2564 gfx::Point origin(rect.origin()); 2565 views::View::ConvertPointToScreen(GetTabContentsContainerView(), &origin); 2566 gfx::Rect bounds(origin, rect.size()); 2567 2568 // Create the bubble. 2569 WebContents* web_contents = GetActiveWebContents(); 2570 if (!web_contents) 2571 return; 2572 2573 PasswordGenerationBubbleView* bubble = 2574 new PasswordGenerationBubbleView( 2575 form, 2576 bounds, 2577 this, 2578 web_contents->GetRenderViewHost(), 2579 PasswordManager::FromWebContents(web_contents), 2580 password_generator, 2581 browser_.get(), 2582 GetWidget()->GetThemeProvider()); 2583 2584 views::BubbleDelegateView::CreateBubble(bubble); 2585 bubble->SetAlignment(views::BubbleBorder::ALIGN_ARROW_TO_MID_ANCHOR); 2586 bubble->GetWidget()->Show(); 2587} 2588 2589void BrowserView::DoCutCopyPaste(void (content::RenderWidgetHost::*method)(), 2590#if defined(OS_WIN) 2591 int windows_msg_id, 2592#endif 2593 int command_id) { 2594 WebContents* contents = browser_->tab_strip_model()->GetActiveWebContents(); 2595 if (!contents) 2596 return; 2597 if (DoCutCopyPasteForWebContents(contents, method)) 2598 return; 2599 2600 DevToolsWindow* devtools_window = 2601 DevToolsWindow::GetDockedInstanceForInspectedTab(contents); 2602 if (devtools_window && 2603 DoCutCopyPasteForWebContents(devtools_window->web_contents(), method)) { 2604 return; 2605 } 2606 2607 views::FocusManager* focus_manager = GetFocusManager(); 2608 views::View* focused = focus_manager->GetFocusedView(); 2609 if (focused && 2610 (!strcmp(focused->GetClassName(), views::Textfield::kViewClassName) || 2611 !strcmp(focused->GetClassName(), OmniboxViewViews::kViewClassName))) { 2612 views::Textfield* textfield = static_cast<views::Textfield*>(focused); 2613 textfield->ExecuteCommand(command_id); 2614 return; 2615 } 2616 2617#if defined(OS_WIN) && !defined(USE_AURA) 2618 OmniboxView* omnibox_view = GetLocationBarView()->GetLocationEntry(); 2619 if (omnibox_view->model()->has_focus()) { 2620 OmniboxViewWin* omnibox_win = GetOmniboxViewWin(omnibox_view); 2621 ::SendMessage(omnibox_win->GetNativeView(), windows_msg_id, 0, 0); 2622 } 2623#endif 2624} 2625 2626bool BrowserView::DoCutCopyPasteForWebContents( 2627 WebContents* contents, 2628 void (content::RenderWidgetHost::*method)()) { 2629 gfx::NativeView native_view = contents->GetView()->GetContentNativeView(); 2630 if (!native_view) 2631 return false; 2632#if defined(USE_AURA) 2633 if (native_view->HasFocus()) { 2634#elif defined(OS_WIN) 2635 if (native_view == ::GetFocus()) { 2636#endif 2637 (contents->GetRenderViewHost()->*method)(); 2638 return true; 2639 } 2640 2641 return false; 2642} 2643 2644void BrowserView::ActivateAppModalDialog() const { 2645 // If another browser is app modal, flash and activate the modal browser. 2646 AppModalDialog* active_dialog = 2647 AppModalDialogQueue::GetInstance()->active_dialog(); 2648 if (!active_dialog) 2649 return; 2650 2651 Browser* modal_browser = 2652 chrome::FindBrowserWithWebContents(active_dialog->web_contents()); 2653 if (modal_browser && (browser_ != modal_browser)) { 2654 modal_browser->window()->FlashFrame(true); 2655 modal_browser->window()->Activate(); 2656 } 2657 2658 AppModalDialogQueue::GetInstance()->ActivateModalDialog(); 2659} 2660 2661int BrowserView::GetMaxTopInfoBarArrowHeight() { 2662 int top_arrow_height = 0; 2663 // Only show the arrows when not in fullscreen and when there's no omnibox 2664 // popup. 2665 if (!IsFullscreen() && 2666 !GetLocationBar()->GetLocationEntry()->model()->popup_model()->IsOpen()) { 2667 const LocationIconView* location_icon_view = 2668 toolbar_->location_bar()->location_icon_view(); 2669 // The +1 in the next line creates a 1-px gap between icon and arrow tip. 2670 gfx::Point icon_bottom(0, location_icon_view->GetImageBounds().bottom() - 2671 LocationBarView::kIconInternalPadding + 1); 2672 ConvertPointToTarget(location_icon_view, this, &icon_bottom); 2673 gfx::Point infobar_top(0, infobar_container_->GetVerticalOverlap(NULL)); 2674 ConvertPointToTarget(infobar_container_, this, &infobar_top); 2675 top_arrow_height = infobar_top.y() - icon_bottom.y(); 2676 } 2677 return top_arrow_height; 2678} 2679