browser.cc revision 7dbb3d5cf0c15f500944d211057644d6a2f37371
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/browser.h" 6 7#if defined(OS_WIN) 8#include <windows.h> 9#include <shellapi.h> 10#endif // defined(OS_WIN) 11 12#include <algorithm> 13#include <string> 14 15#include "base/base_paths.h" 16#include "base/bind.h" 17#include "base/command_line.h" 18#include "base/logging.h" 19#include "base/metrics/histogram.h" 20#include "base/path_service.h" 21#include "base/prefs/pref_service.h" 22#include "base/process_info.h" 23#include "base/strings/string_number_conversions.h" 24#include "base/strings/string_util.h" 25#include "base/strings/stringprintf.h" 26#include "base/strings/utf_string_conversions.h" 27#include "base/threading/thread.h" 28#include "base/threading/thread_restrictions.h" 29#include "base/time/time.h" 30#include "chrome/app/chrome_command_ids.h" 31#include "chrome/browser/app_mode/app_mode_utils.h" 32#include "chrome/browser/autofill/personal_data_manager_factory.h" 33#include "chrome/browser/background/background_contents_service.h" 34#include "chrome/browser/background/background_contents_service_factory.h" 35#include "chrome/browser/bookmarks/bookmark_model.h" 36#include "chrome/browser/bookmarks/bookmark_utils.h" 37#include "chrome/browser/browser_process.h" 38#include "chrome/browser/browser_shutdown.h" 39#include "chrome/browser/character_encoding.h" 40#include "chrome/browser/chrome_notification_types.h" 41#include "chrome/browser/chrome_page_zoom.h" 42#include "chrome/browser/content_settings/host_content_settings_map.h" 43#include "chrome/browser/content_settings/tab_specific_content_settings.h" 44#include "chrome/browser/custom_handlers/protocol_handler_registry.h" 45#include "chrome/browser/custom_handlers/protocol_handler_registry_factory.h" 46#include "chrome/browser/custom_handlers/register_protocol_handler_infobar_delegate.h" 47#include "chrome/browser/devtools/devtools_toggle_action.h" 48#include "chrome/browser/devtools/devtools_window.h" 49#include "chrome/browser/download/download_item_model.h" 50#include "chrome/browser/download/download_service.h" 51#include "chrome/browser/download/download_service_factory.h" 52#include "chrome/browser/download/download_shelf.h" 53#include "chrome/browser/extensions/browser_extension_window_controller.h" 54#include "chrome/browser/extensions/extension_prefs.h" 55#include "chrome/browser/extensions/extension_service.h" 56#include "chrome/browser/extensions/extension_system.h" 57#include "chrome/browser/extensions/tab_helper.h" 58#include "chrome/browser/favicon/favicon_tab_helper.h" 59#include "chrome/browser/file_select_helper.h" 60#include "chrome/browser/first_run/first_run.h" 61#include "chrome/browser/google/google_url_tracker.h" 62#include "chrome/browser/infobars/infobar_service.h" 63#include "chrome/browser/infobars/simple_alert_infobar_delegate.h" 64#include "chrome/browser/lifetime/application_lifetime.h" 65#include "chrome/browser/media/media_capture_devices_dispatcher.h" 66#include "chrome/browser/net/url_fixer_upper.h" 67#include "chrome/browser/notifications/notification_ui_manager.h" 68#include "chrome/browser/pepper_broker_infobar_delegate.h" 69#include "chrome/browser/prefs/incognito_mode_prefs.h" 70#include "chrome/browser/profiles/profile.h" 71#include "chrome/browser/profiles/profile_destroyer.h" 72#include "chrome/browser/profiles/profile_manager.h" 73#include "chrome/browser/profiles/profile_metrics.h" 74#include "chrome/browser/repost_form_warning_controller.h" 75#include "chrome/browser/search/search.h" 76#include "chrome/browser/sessions/session_service.h" 77#include "chrome/browser/sessions/session_service_factory.h" 78#include "chrome/browser/sessions/session_tab_helper.h" 79#include "chrome/browser/sessions/session_types.h" 80#include "chrome/browser/sessions/tab_restore_service.h" 81#include "chrome/browser/sessions/tab_restore_service_factory.h" 82#include "chrome/browser/sync/profile_sync_service.h" 83#include "chrome/browser/sync/profile_sync_service_factory.h" 84#include "chrome/browser/sync/sync_ui_util.h" 85#include "chrome/browser/tab_contents/background_contents.h" 86#include "chrome/browser/tab_contents/retargeting_details.h" 87#include "chrome/browser/tab_contents/tab_util.h" 88#include "chrome/browser/themes/theme_service.h" 89#include "chrome/browser/themes/theme_service_factory.h" 90#include "chrome/browser/ui/app_modal_dialogs/javascript_dialog_manager.h" 91#include "chrome/browser/ui/blocked_content/blocked_content_tab_helper.h" 92#include "chrome/browser/ui/bookmarks/bookmark_tab_helper.h" 93#include "chrome/browser/ui/browser_command_controller.h" 94#include "chrome/browser/ui/browser_commands.h" 95#include "chrome/browser/ui/browser_content_setting_bubble_model_delegate.h" 96#include "chrome/browser/ui/browser_dialogs.h" 97#include "chrome/browser/ui/browser_finder.h" 98#include "chrome/browser/ui/browser_instant_controller.h" 99#include "chrome/browser/ui/browser_iterator.h" 100#include "chrome/browser/ui/browser_list.h" 101#include "chrome/browser/ui/browser_navigator.h" 102#include "chrome/browser/ui/browser_tab_contents.h" 103#include "chrome/browser/ui/browser_tab_restore_service_delegate.h" 104#include "chrome/browser/ui/browser_tab_strip_model_delegate.h" 105#include "chrome/browser/ui/browser_tabstrip.h" 106#include "chrome/browser/ui/browser_toolbar_model_delegate.h" 107#include "chrome/browser/ui/browser_ui_prefs.h" 108#include "chrome/browser/ui/browser_window.h" 109#include "chrome/browser/ui/chrome_pages.h" 110#include "chrome/browser/ui/chrome_select_file_policy.h" 111#include "chrome/browser/ui/fast_unload_controller.h" 112#include "chrome/browser/ui/find_bar/find_bar.h" 113#include "chrome/browser/ui/find_bar/find_bar_controller.h" 114#include "chrome/browser/ui/find_bar/find_tab_helper.h" 115#include "chrome/browser/ui/fullscreen/fullscreen_controller.h" 116#include "chrome/browser/ui/global_error/global_error.h" 117#include "chrome/browser/ui/global_error/global_error_service.h" 118#include "chrome/browser/ui/global_error/global_error_service_factory.h" 119#include "chrome/browser/ui/omnibox/location_bar.h" 120#include "chrome/browser/ui/search/search_delegate.h" 121#include "chrome/browser/ui/search/search_model.h" 122#include "chrome/browser/ui/search_engines/search_engine_tab_helper.h" 123#include "chrome/browser/ui/singleton_tabs.h" 124#include "chrome/browser/ui/status_bubble.h" 125#include "chrome/browser/ui/sync/browser_synced_window_delegate.h" 126#include "chrome/browser/ui/tab_contents/core_tab_helper.h" 127#include "chrome/browser/ui/tab_modal_confirm_dialog.h" 128#include "chrome/browser/ui/tabs/dock_info.h" 129#include "chrome/browser/ui/tabs/tab_menu_model.h" 130#include "chrome/browser/ui/tabs/tab_strip_model.h" 131#include "chrome/browser/ui/toolbar/toolbar_model_impl.h" 132#include "chrome/browser/ui/unload_controller.h" 133#include "chrome/browser/ui/web_applications/web_app_ui.h" 134#include "chrome/browser/ui/webui/signin/login_ui_service.h" 135#include "chrome/browser/ui/webui/signin/login_ui_service_factory.h" 136#include "chrome/browser/ui/window_sizer/window_sizer.h" 137#include "chrome/browser/ui/zoom/zoom_controller.h" 138#include "chrome/browser/upgrade_detector.h" 139#include "chrome/browser/web_applications/web_app.h" 140#include "chrome/common/chrome_constants.h" 141#include "chrome/common/chrome_switches.h" 142#include "chrome/common/custom_handlers/protocol_handler.h" 143#include "chrome/common/extensions/background_info.h" 144#include "chrome/common/extensions/extension.h" 145#include "chrome/common/extensions/extension_constants.h" 146#include "chrome/common/pref_names.h" 147#include "chrome/common/profiling.h" 148#include "chrome/common/search_types.h" 149#include "chrome/common/startup_metric_utils.h" 150#include "chrome/common/url_constants.h" 151#include "components/web_modal/web_contents_modal_dialog_manager.h" 152#include "content/public/browser/devtools_manager.h" 153#include "content/public/browser/download_item.h" 154#include "content/public/browser/download_manager.h" 155#include "content/public/browser/interstitial_page.h" 156#include "content/public/browser/invalidate_type.h" 157#include "content/public/browser/navigation_controller.h" 158#include "content/public/browser/navigation_entry.h" 159#include "content/public/browser/notification_details.h" 160#include "content/public/browser/notification_service.h" 161#include "content/public/browser/plugin_service.h" 162#include "content/public/browser/render_process_host.h" 163#include "content/public/browser/render_view_host.h" 164#include "content/public/browser/site_instance.h" 165#include "content/public/browser/user_metrics.h" 166#include "content/public/browser/web_contents.h" 167#include "content/public/browser/web_contents_view.h" 168#include "content/public/common/content_restriction.h" 169#include "content/public/common/content_switches.h" 170#include "content/public/common/page_zoom.h" 171#include "content/public/common/renderer_preferences.h" 172#include "extensions/common/constants.h" 173#include "grit/chromium_strings.h" 174#include "grit/generated_resources.h" 175#include "grit/locale_settings.h" 176#include "grit/theme_resources.h" 177#include "net/base/net_util.h" 178#include "net/base/registry_controlled_domains/registry_controlled_domain.h" 179#include "net/cookies/cookie_monster.h" 180#include "net/url_request/url_request_context.h" 181#include "ui/base/l10n/l10n_util.h" 182#include "ui/base/window_open_disposition.h" 183#include "ui/gfx/point.h" 184#include "ui/shell_dialogs/selected_file_info.h" 185#include "webkit/plugins/webplugininfo.h" 186 187#if defined(OS_WIN) 188#include "base/win/metro.h" 189#include "chrome/browser/shell_integration.h" 190#include "chrome/browser/ssl/ssl_error_info.h" 191#include "chrome/browser/task_manager/task_manager.h" 192#include "chrome/browser/ui/view_ids.h" 193#include "components/autofill/core/browser/autofill_ie_toolbar_import_win.h" 194#include "ui/base/win/shell.h" 195#include "ui/views/win/hwnd_util.h" 196#endif // OS_WIN 197 198#if defined(OS_CHROMEOS) 199#include "chrome/browser/chromeos/drive/file_system_util.h" 200#endif 201 202#if defined(USE_ASH) 203#include "ash/ash_switches.h" 204#endif 205 206using base::TimeDelta; 207using content::NativeWebKeyboardEvent; 208using content::NavigationController; 209using content::NavigationEntry; 210using content::OpenURLParams; 211using content::PluginService; 212using content::Referrer; 213using content::SiteInstance; 214using content::UserMetricsAction; 215using content::WebContents; 216using extensions::Extension; 217using ui::WebDialogDelegate; 218using web_modal::WebContentsModalDialogManager; 219 220/////////////////////////////////////////////////////////////////////////////// 221 222namespace { 223 224// The URL to be loaded to display the "Report a broken page" form. 225const char kBrokenPageUrl[] = 226 "https://www.google.com/support/chrome/bin/request.py?contact_type=" 227 "broken_website&format=inproduct&p.page_title=$1&p.page_url=$2"; 228 229// How long we wait before updating the browser chrome while loading a page. 230const int kUIUpdateCoalescingTimeMS = 200; 231 232BrowserWindow* CreateBrowserWindow(Browser* browser) { 233 return BrowserWindow::CreateBrowserWindow(browser); 234} 235 236// Is the fast tab unload experiment enabled? 237bool IsFastTabUnloadEnabled() { 238 return CommandLine::ForCurrentProcess()->HasSwitch( 239 switches::kEnableFastUnload); 240} 241 242} // namespace 243 244//////////////////////////////////////////////////////////////////////////////// 245// Browser, CreateParams: 246 247Browser::CreateParams::CreateParams(Profile* profile, 248 chrome::HostDesktopType host_desktop_type) 249 : type(TYPE_TABBED), 250 profile(profile), 251 host_desktop_type(host_desktop_type), 252 app_type(APP_TYPE_HOST), 253 initial_show_state(ui::SHOW_STATE_DEFAULT), 254 is_session_restore(false), 255 window(NULL) { 256} 257 258Browser::CreateParams::CreateParams(Type type, 259 Profile* profile, 260 chrome::HostDesktopType host_desktop_type) 261 : type(type), 262 profile(profile), 263 host_desktop_type(host_desktop_type), 264 app_type(APP_TYPE_HOST), 265 initial_show_state(ui::SHOW_STATE_DEFAULT), 266 is_session_restore(false), 267 window(NULL) { 268} 269 270// static 271Browser::CreateParams Browser::CreateParams::CreateForApp( 272 Type type, 273 const std::string& app_name, 274 const gfx::Rect& window_bounds, 275 Profile* profile, 276 chrome::HostDesktopType host_desktop_type) { 277 DCHECK(type != TYPE_TABBED); 278 DCHECK(!app_name.empty()); 279 280 CreateParams params(type, profile, host_desktop_type); 281 params.app_name = app_name; 282 params.app_type = APP_TYPE_CHILD; 283 params.initial_bounds = window_bounds; 284 285 return params; 286} 287 288// static 289Browser::CreateParams Browser::CreateParams::CreateForDevTools( 290 Profile* profile, 291 chrome::HostDesktopType host_desktop_type) { 292 CreateParams params(TYPE_POPUP, profile, host_desktop_type); 293 params.app_name = DevToolsWindow::kDevToolsApp; 294 return params; 295} 296 297//////////////////////////////////////////////////////////////////////////////// 298// Browser, InterstitialObserver: 299 300class Browser::InterstitialObserver : public content::WebContentsObserver { 301 public: 302 InterstitialObserver(Browser* browser, content::WebContents* web_contents) 303 : WebContentsObserver(web_contents), 304 browser_(browser) { 305 } 306 307 using content::WebContentsObserver::web_contents; 308 309 virtual void DidAttachInterstitialPage() OVERRIDE { 310 browser_->UpdateBookmarkBarState(BOOKMARK_BAR_STATE_CHANGE_TAB_STATE); 311 } 312 313 virtual void DidDetachInterstitialPage() OVERRIDE { 314 browser_->UpdateBookmarkBarState(BOOKMARK_BAR_STATE_CHANGE_TAB_STATE); 315 } 316 317 private: 318 Browser* browser_; 319 320 DISALLOW_COPY_AND_ASSIGN(InterstitialObserver); 321}; 322 323/////////////////////////////////////////////////////////////////////////////// 324// Browser, Constructors, Creation, Showing: 325 326Browser::Browser(const CreateParams& params) 327 : type_(params.type), 328 profile_(params.profile), 329 window_(NULL), 330 tab_strip_model_delegate_(new chrome::BrowserTabStripModelDelegate(this)), 331 tab_strip_model_(new TabStripModel(tab_strip_model_delegate_.get(), 332 params.profile)), 333 app_name_(params.app_name), 334 app_type_(params.app_type), 335 chrome_updater_factory_(this), 336 cancel_download_confirmation_state_(NOT_PROMPTED), 337 override_bounds_(params.initial_bounds), 338 initial_show_state_(params.initial_show_state), 339 is_session_restore_(params.is_session_restore), 340 host_desktop_type_(params.host_desktop_type), 341 weak_factory_(this), 342 content_setting_bubble_model_delegate_( 343 new BrowserContentSettingBubbleModelDelegate(this)), 344 toolbar_model_delegate_(new BrowserToolbarModelDelegate(this)), 345 tab_restore_service_delegate_(new BrowserTabRestoreServiceDelegate(this)), 346 synced_window_delegate_(new BrowserSyncedWindowDelegate(this)), 347 bookmark_bar_state_(BookmarkBar::HIDDEN), 348 command_controller_(new chrome::BrowserCommandController( 349 this, g_browser_process->profile_manager())), 350 window_has_shown_(false) { 351 // If this causes a crash then a window is being opened using a profile type 352 // that is disallowed by policy. The crash prevents the disabled window type 353 // from opening at all, but the path that triggered it should be fixed. 354 CHECK(IncognitoModePrefs::CanOpenBrowser(profile_)); 355 356 // TODO(jeremy): Move to initializer list once flag is removed. 357 if (IsFastTabUnloadEnabled()) 358 fast_unload_controller_.reset(new chrome::FastUnloadController(this)); 359 else 360 unload_controller_.reset(new chrome::UnloadController(this)); 361 362 if (!app_name_.empty()) 363 chrome::RegisterAppPrefs(app_name_, profile_); 364 tab_strip_model_->AddObserver(this); 365 366 toolbar_model_.reset(new ToolbarModelImpl(toolbar_model_delegate_.get())); 367 search_model_.reset(new SearchModel()); 368 search_delegate_.reset( 369 new SearchDelegate(search_model_.get(), toolbar_model_.get())); 370 371 registrar_.Add(this, chrome::NOTIFICATION_EXTENSION_LOADED, 372 content::Source<Profile>(profile_->GetOriginalProfile())); 373 registrar_.Add(this, chrome::NOTIFICATION_EXTENSION_UNLOADED, 374 content::Source<Profile>(profile_->GetOriginalProfile())); 375 registrar_.Add(this, chrome::NOTIFICATION_EXTENSION_UNINSTALLED, 376 content::Source<Profile>(profile_->GetOriginalProfile())); 377 registrar_.Add(this, chrome::NOTIFICATION_EXTENSION_PROCESS_TERMINATED, 378 content::NotificationService::AllSources()); 379#if defined(ENABLE_THEMES) 380 registrar_.Add( 381 this, chrome::NOTIFICATION_BROWSER_THEME_CHANGED, 382 content::Source<ThemeService>( 383 ThemeServiceFactory::GetForProfile(profile_))); 384#endif 385 registrar_.Add(this, chrome::NOTIFICATION_WEB_CONTENT_SETTINGS_CHANGED, 386 content::NotificationService::AllSources()); 387 388 profile_pref_registrar_.Init(profile_->GetPrefs()); 389 profile_pref_registrar_.Add( 390 prefs::kDevToolsDisabled, 391 base::Bind(&Browser::OnDevToolsDisabledChanged, base::Unretained(this))); 392 profile_pref_registrar_.Add( 393 prefs::kShowBookmarkBar, 394 base::Bind(&Browser::UpdateBookmarkBarState, base::Unretained(this), 395 BOOKMARK_BAR_STATE_CHANGE_PREF_CHANGE)); 396 397 BrowserList::AddBrowser(this); 398 399 // NOTE: These prefs all need to be explicitly destroyed in the destructor 400 // or you'll get a nasty surprise when you run the incognito tests. 401 encoding_auto_detect_.Init(prefs::kWebKitUsesUniversalDetector, 402 profile_->GetPrefs()); 403 404 if (is_type_tabbed()) 405 instant_controller_.reset(new BrowserInstantController(this)); 406 407 UpdateBookmarkBarState(BOOKMARK_BAR_STATE_CHANGE_INIT); 408 409 ProfileMetrics::LogProfileLaunch(profile_); 410 411 window_ = params.window ? params.window : CreateBrowserWindow(this); 412 413 // TODO(beng): move to BrowserFrameWin. 414#if defined(OS_WIN) 415 // Set the app user model id for this application to that of the application 416 // name. See http://crbug.com/7028. 417 ui::win::SetAppIdForWindow( 418 is_app() ? 419 ShellIntegration::GetAppModelIdForProfile(UTF8ToWide(app_name_), 420 profile_->GetPath()) : 421 ShellIntegration::GetChromiumModelIdForProfile(profile_->GetPath()), 422 views::HWNDForNativeWindow(window()->GetNativeWindow())); 423#endif 424 425 // Create the extension window controller before sending notifications. 426 extension_window_controller_.reset( 427 new BrowserExtensionWindowController(this)); 428 429 // TODO(beng): Move BrowserList::AddBrowser() to the end of this function and 430 // replace uses of this with BL's notifications. 431 content::NotificationService::current()->Notify( 432 chrome::NOTIFICATION_BROWSER_WINDOW_READY, 433 content::Source<Browser>(this), 434 content::NotificationService::NoDetails()); 435 436 // TODO(beng): move to ChromeBrowserMain: 437 if (first_run::ShouldDoPersonalDataManagerFirstRun()) { 438#if defined(OS_WIN) 439 // Notify PDM that this is a first run. 440 ImportAutofillDataWin( 441 autofill::PersonalDataManagerFactory::GetForProfile(profile_)); 442#endif // defined(OS_WIN) 443 } 444 445 fullscreen_controller_.reset(new FullscreenController(this)); 446} 447 448Browser::~Browser() { 449 // The tab strip should not have any tabs at this point. 450 if (!browser_shutdown::ShuttingDownWithoutClosingBrowsers()) 451 DCHECK(tab_strip_model_->empty()); 452 453 tab_strip_model_->RemoveObserver(this); 454 455 // Destroy the BrowserCommandController before removing the browser, so that 456 // it doesn't act on any notifications that are sent as a result of removing 457 // the browser. 458 command_controller_.reset(); 459 BrowserList::RemoveBrowser(this); 460 461 SessionService* session_service = 462 SessionServiceFactory::GetForProfile(profile_); 463 if (session_service) 464 session_service->WindowClosed(session_id_); 465 466 TabRestoreService* tab_restore_service = 467 TabRestoreServiceFactory::GetForProfile(profile()); 468 if (tab_restore_service) 469 tab_restore_service->BrowserClosed(tab_restore_service_delegate()); 470 471#if !defined(OS_MACOSX) 472 if (!chrome::GetTotalBrowserCountForProfile(profile_)) { 473 // We're the last browser window with this profile. We need to nuke the 474 // TabRestoreService, which will start the shutdown of the 475 // NavigationControllers and allow for proper shutdown. If we don't do this 476 // chrome won't shutdown cleanly, and may end up crashing when some 477 // thread tries to use the IO thread (or another thread) that is no longer 478 // valid. 479 // This isn't a valid assumption for Mac OS, as it stays running after 480 // the last browser has closed. The Mac equivalent is in its app 481 // controller. 482 TabRestoreServiceFactory::ResetForProfile(profile_); 483 } 484#endif 485 486 profile_pref_registrar_.RemoveAll(); 487 488 encoding_auto_detect_.Destroy(); 489 490 // Destroy BrowserExtensionWindowController before the incognito profile 491 // is destroyed to make sure the chrome.windows.onRemoved event is sent. 492 extension_window_controller_.reset(); 493 494 // Destroy BrowserInstantController before the incongnito profile is destroyed 495 // because the InstantController destructor depends on this profile. 496 instant_controller_.reset(); 497 498 if (profile_->IsOffTheRecord() && 499 !BrowserList::IsOffTheRecordSessionActiveForProfile(profile_)) { 500 // An incognito profile is no longer needed, this indirectly frees 501 // its cache and cookies once it gets destroyed at the appropriate time. 502 ProfileDestroyer::DestroyProfileWhenAppropriate(profile_); 503 } 504 505 // There may be pending file dialogs, we need to tell them that we've gone 506 // away so they don't try and call back to us. 507 if (select_file_dialog_.get()) 508 select_file_dialog_->ListenerDestroyed(); 509} 510 511/////////////////////////////////////////////////////////////////////////////// 512// Getters & Setters 513 514FindBarController* Browser::GetFindBarController() { 515 if (!find_bar_controller_.get()) { 516 FindBar* find_bar = window_->CreateFindBar(); 517 find_bar_controller_.reset(new FindBarController(find_bar)); 518 find_bar->SetFindBarController(find_bar_controller_.get()); 519 find_bar_controller_->ChangeWebContents( 520 tab_strip_model_->GetActiveWebContents()); 521 find_bar_controller_->find_bar()->MoveWindowIfNecessary(gfx::Rect(), true); 522 } 523 return find_bar_controller_.get(); 524} 525 526bool Browser::HasFindBarController() const { 527 return find_bar_controller_.get() != NULL; 528} 529 530bool Browser::is_app() const { 531 return !app_name_.empty(); 532} 533 534bool Browser::is_devtools() const { 535 return app_name_ == DevToolsWindow::kDevToolsApp; 536} 537 538/////////////////////////////////////////////////////////////////////////////// 539// Browser, State Storage and Retrieval for UI: 540 541gfx::Image Browser::GetCurrentPageIcon() const { 542 WebContents* web_contents = tab_strip_model_->GetActiveWebContents(); 543 // |web_contents| can be NULL since GetCurrentPageIcon() is called by the 544 // window during the window's creation (before tabs have been added). 545 FaviconTabHelper* favicon_tab_helper = 546 web_contents ? FaviconTabHelper::FromWebContents(web_contents) : NULL; 547 return favicon_tab_helper ? favicon_tab_helper->GetFavicon() : gfx::Image(); 548} 549 550string16 Browser::GetWindowTitleForCurrentTab() const { 551 WebContents* contents = tab_strip_model_->GetActiveWebContents(); 552 string16 title; 553 554 // |contents| can be NULL because GetWindowTitleForCurrentTab is called by the 555 // window during the window's creation (before tabs have been added). 556 if (contents) { 557 title = contents->GetTitle(); 558 FormatTitleForDisplay(&title); 559 } 560 if (title.empty()) 561 title = CoreTabHelper::GetDefaultTitle(); 562 563#if defined(OS_MACOSX) 564 // On Mac, we don't want to suffix the page title with 565 // the application name. 566 return title; 567#elif defined(USE_ASH) 568 // On Ash, we don't want to suffix the page title with the application name, 569 // but on Windows, where USE_ASH can also be true, we still want the prefix 570 // on desktop. 571 if (host_desktop_type() == chrome::HOST_DESKTOP_TYPE_ASH) 572 return title; 573#endif 574 // Don't append the app name to window titles on app frames and app popups 575 return is_app() ? 576 title : 577 l10n_util::GetStringFUTF16(IDS_BROWSER_WINDOW_TITLE_FORMAT, title); 578} 579 580// static 581void Browser::FormatTitleForDisplay(string16* title) { 582 size_t current_index = 0; 583 size_t match_index; 584 while ((match_index = title->find(L'\n', current_index)) != string16::npos) { 585 title->replace(match_index, 1, string16()); 586 current_index = match_index; 587 } 588} 589 590/////////////////////////////////////////////////////////////////////////////// 591// Browser, OnBeforeUnload handling: 592 593bool Browser::ShouldCloseWindow() { 594 if (!CanCloseWithInProgressDownloads()) 595 return false; 596 597 if (IsFastTabUnloadEnabled()) 598 return fast_unload_controller_->ShouldCloseWindow(); 599 return unload_controller_->ShouldCloseWindow(); 600} 601 602bool Browser::HasCompletedUnloadProcessing() const { 603 DCHECK(IsFastTabUnloadEnabled()); 604 return fast_unload_controller_->HasCompletedUnloadProcessing(); 605} 606 607bool Browser::IsAttemptingToCloseBrowser() const { 608 if (IsFastTabUnloadEnabled()) 609 return fast_unload_controller_->is_attempting_to_close_browser(); 610 return unload_controller_->is_attempting_to_close_browser(); 611} 612 613void Browser::OnWindowClosing() { 614 if (!ShouldCloseWindow()) 615 return; 616 617 // Application should shutdown on last window close if the user is explicitly 618 // trying to quit, or if there is nothing keeping the browser alive (such as 619 // AppController on the Mac, or BackgroundContentsService for background 620 // pages). 621 bool should_quit_if_last_browser = 622 browser_shutdown::IsTryingToQuit() || !chrome::WillKeepAlive(); 623 624 if (should_quit_if_last_browser && 625 BrowserList::GetInstance(host_desktop_type_)->size() == 1) { 626 browser_shutdown::OnShutdownStarting(browser_shutdown::WINDOW_CLOSE); 627 } 628 629 // Don't use GetForProfileIfExisting here, we want to force creation of the 630 // session service so that user can restore what was open. 631 SessionService* session_service = 632 SessionServiceFactory::GetForProfile(profile()); 633 if (session_service) 634 session_service->WindowClosing(session_id()); 635 636 TabRestoreService* tab_restore_service = 637 TabRestoreServiceFactory::GetForProfile(profile()); 638 639#if defined(USE_AURA) 640 if (tab_restore_service && is_app()) 641 tab_restore_service->BrowserClosing(tab_restore_service_delegate()); 642#endif 643 644 if (tab_restore_service && is_type_tabbed() && tab_strip_model_->count()) 645 tab_restore_service->BrowserClosing(tab_restore_service_delegate()); 646 647 // TODO(sky): convert session/tab restore to use notification. 648 content::NotificationService::current()->Notify( 649 chrome::NOTIFICATION_BROWSER_CLOSING, 650 content::Source<Browser>(this), 651 content::NotificationService::NoDetails()); 652 653 if (!IsFastTabUnloadEnabled()) 654 tab_strip_model_->CloseAllTabs(); 655} 656 657//////////////////////////////////////////////////////////////////////////////// 658// In-progress download termination handling: 659 660void Browser::InProgressDownloadResponse(bool cancel_downloads) { 661 if (cancel_downloads) { 662 cancel_download_confirmation_state_ = RESPONSE_RECEIVED; 663 chrome::CloseWindow(this); 664 return; 665 } 666 667 // Sets the confirmation state to NOT_PROMPTED so that if the user tries to 668 // close again we'll show the warning again. 669 cancel_download_confirmation_state_ = NOT_PROMPTED; 670 671 // Show the download page so the user can figure-out what downloads are still 672 // in-progress. 673 chrome::ShowDownloads(this); 674} 675 676Browser::DownloadClosePreventionType Browser::OkToCloseWithInProgressDownloads( 677 int* num_downloads_blocking) const { 678 DCHECK(num_downloads_blocking); 679 *num_downloads_blocking = 0; 680 681 if (IsAttemptingToCloseBrowser()) 682 return DOWNLOAD_CLOSE_OK; 683 684 // If we're not running a full browser process with a profile manager 685 // (testing), it's ok to close the browser. 686 if (!g_browser_process->profile_manager()) 687 return DOWNLOAD_CLOSE_OK; 688 689 int total_download_count = DownloadService::DownloadCountAllProfiles(); 690 if (total_download_count == 0) 691 return DOWNLOAD_CLOSE_OK; // No downloads; can definitely close. 692 693 // Figure out how many windows are open total, and associated with this 694 // profile, that are relevant for the ok-to-close decision. 695 int profile_window_count = 0; 696 int total_window_count = 0; 697 for (chrome::BrowserIterator it; !it.done(); it.Next()) { 698 // Don't count this browser window or any other in the process of closing. 699 Browser* const browser = *it; 700 // Window closing may be delayed, and windows that are in the process of 701 // closing don't count against our totals. 702 if (browser == this || browser->IsAttemptingToCloseBrowser()) 703 continue; 704 705 if (it->profile() == profile()) 706 profile_window_count++; 707 total_window_count++; 708 } 709 710 // If there aren't any other windows, we're at browser shutdown, 711 // which would cancel all current downloads. 712 if (total_window_count == 0) { 713 *num_downloads_blocking = total_download_count; 714 return DOWNLOAD_CLOSE_BROWSER_SHUTDOWN; 715 } 716 717 // If there aren't any other windows on our profile, and we're an incognito 718 // profile, and there are downloads associated with that profile, 719 // those downloads would be cancelled by our window (-> profile) close. 720 DownloadService* download_service = 721 DownloadServiceFactory::GetForProfile(profile()); 722 if (profile_window_count == 0 && download_service->DownloadCount() > 0 && 723 profile()->IsOffTheRecord()) { 724 *num_downloads_blocking = download_service->DownloadCount(); 725 return DOWNLOAD_CLOSE_LAST_WINDOW_IN_INCOGNITO_PROFILE; 726 } 727 728 // Those are the only conditions under which we will block shutdown. 729 return DOWNLOAD_CLOSE_OK; 730} 731 732//////////////////////////////////////////////////////////////////////////////// 733// Browser, Tab adding/showing functions: 734 735void Browser::WindowFullscreenStateChanged() { 736 fullscreen_controller_->WindowFullscreenStateChanged(); 737 command_controller_->FullscreenStateChanged(); 738 UpdateBookmarkBarState(BOOKMARK_BAR_STATE_CHANGE_TOGGLE_FULLSCREEN); 739} 740 741void Browser::VisibleSSLStateChanged(content::WebContents* web_contents) { 742 // When the current tab's SSL state changes, we need to update the URL 743 // bar to reflect the new state. 744 DCHECK(web_contents); 745 if (tab_strip_model_->GetActiveWebContents() == web_contents) 746 UpdateToolbar(false); 747} 748 749/////////////////////////////////////////////////////////////////////////////// 750// Browser, Assorted browser commands: 751 752void Browser::ToggleFullscreenModeWithExtension(const GURL& extension_url) { 753 fullscreen_controller_->ToggleFullscreenModeWithExtension(extension_url); 754} 755 756bool Browser::SupportsWindowFeature(WindowFeature feature) const { 757 return SupportsWindowFeatureImpl(feature, true); 758} 759 760bool Browser::CanSupportWindowFeature(WindowFeature feature) const { 761 return SupportsWindowFeatureImpl(feature, false); 762} 763 764void Browser::ToggleEncodingAutoDetect() { 765 content::RecordAction(UserMetricsAction("AutoDetectChange")); 766 encoding_auto_detect_.SetValue(!encoding_auto_detect_.GetValue()); 767 // If "auto detect" is turned on, then any current override encoding 768 // is cleared. This also implicitly performs a reload. 769 // OTOH, if "auto detect" is turned off, we don't change the currently 770 // active encoding. 771 if (encoding_auto_detect_.GetValue()) { 772 WebContents* contents = tab_strip_model_->GetActiveWebContents(); 773 if (contents) 774 contents->ResetOverrideEncoding(); 775 } 776} 777 778void Browser::OverrideEncoding(int encoding_id) { 779 content::RecordAction(UserMetricsAction("OverrideEncoding")); 780 const std::string selected_encoding = 781 CharacterEncoding::GetCanonicalEncodingNameByCommandId(encoding_id); 782 WebContents* contents = tab_strip_model_->GetActiveWebContents(); 783 if (!selected_encoding.empty() && contents) 784 contents->SetOverrideEncoding(selected_encoding); 785 // Update the list of recently selected encodings. 786 std::string new_selected_encoding_list; 787 if (CharacterEncoding::UpdateRecentlySelectedEncoding( 788 profile_->GetPrefs()->GetString(prefs::kRecentlySelectedEncoding), 789 encoding_id, 790 &new_selected_encoding_list)) { 791 profile_->GetPrefs()->SetString(prefs::kRecentlySelectedEncoding, 792 new_selected_encoding_list); 793 } 794} 795 796void Browser::OpenFile() { 797 content::RecordAction(UserMetricsAction("OpenFile")); 798 select_file_dialog_ = ui::SelectFileDialog::Create( 799 this, new ChromeSelectFilePolicy( 800 tab_strip_model_->GetActiveWebContents())); 801 802 const base::FilePath directory = profile_->last_selected_directory(); 803 804 // TODO(beng): figure out how to juggle this. 805 gfx::NativeWindow parent_window = window_->GetNativeWindow(); 806 ui::SelectFileDialog::FileTypeInfo file_types; 807 file_types.support_drive = true; 808 select_file_dialog_->SelectFile(ui::SelectFileDialog::SELECT_OPEN_FILE, 809 string16(), 810 directory, 811 &file_types, 812 0, 813 base::FilePath::StringType(), 814 parent_window, 815 NULL); 816} 817 818void Browser::UpdateDownloadShelfVisibility(bool visible) { 819 if (GetStatusBubble()) 820 GetStatusBubble()->UpdateDownloadShelfVisibility(visible); 821} 822 823/////////////////////////////////////////////////////////////////////////////// 824 825// static 826bool Browser::RunUnloadEventsHelper(WebContents* contents) { 827 // If the WebContents is not connected yet, then there's no unload 828 // handler we can fire even if the WebContents has an unload listener. 829 // One case where we hit this is in a tab that has an infinite loop 830 // before load. 831 if (contents->NeedToFireBeforeUnload()) { 832 // If the page has unload listeners, then we tell the renderer to fire 833 // them. Once they have fired, we'll get a message back saying whether 834 // to proceed closing the page or not, which sends us back to this method 835 // with the NeedToFireBeforeUnload bit cleared. 836 contents->GetRenderViewHost()->FirePageBeforeUnload(false); 837 return true; 838 } 839 return false; 840} 841 842// static 843void Browser::JSOutOfMemoryHelper(WebContents* web_contents) { 844 InfoBarService* infobar_service = 845 InfoBarService::FromWebContents(web_contents); 846 if (!infobar_service) 847 return; 848 SimpleAlertInfoBarDelegate::Create( 849 infobar_service, InfoBarDelegate::kNoIconID, 850 l10n_util::GetStringUTF16(IDS_JS_OUT_OF_MEMORY_PROMPT), true); 851} 852 853// static 854void Browser::RegisterProtocolHandlerHelper(WebContents* web_contents, 855 const std::string& protocol, 856 const GURL& url, 857 const string16& title, 858 bool user_gesture, 859 BrowserWindow* window) { 860 Profile* profile = 861 Profile::FromBrowserContext(web_contents->GetBrowserContext()); 862 if (profile->IsOffTheRecord()) 863 return; 864 865 ProtocolHandler handler = 866 ProtocolHandler::CreateProtocolHandler(protocol, url, title); 867 868 ProtocolHandlerRegistry* registry = 869 ProtocolHandlerRegistryFactory::GetForProfile(profile); 870 if (registry->SilentlyHandleRegisterHandlerRequest(handler)) 871 return; 872 873 TabSpecificContentSettings* tab_content_settings = 874 TabSpecificContentSettings::FromWebContents(web_contents); 875 if (!user_gesture && window) { 876 tab_content_settings->set_pending_protocol_handler(handler); 877 tab_content_settings->set_previous_protocol_handler( 878 registry->GetHandlerFor(handler.protocol())); 879 window->GetLocationBar()->UpdateContentSettingsIcons(); 880 return; 881 } 882 883 // Make sure content-setting icon is turned off in case the page does 884 // ungestured and gestured RPH calls. 885 if (window) { 886 tab_content_settings->ClearPendingProtocolHandler(); 887 window->GetLocationBar()->UpdateContentSettingsIcons(); 888 } 889 890 RegisterProtocolHandlerInfoBarDelegate::Create( 891 InfoBarService::FromWebContents(web_contents), registry, handler); 892} 893 894// static 895void Browser::FindReplyHelper(WebContents* web_contents, 896 int request_id, 897 int number_of_matches, 898 const gfx::Rect& selection_rect, 899 int active_match_ordinal, 900 bool final_update) { 901 FindTabHelper* find_tab_helper = FindTabHelper::FromWebContents(web_contents); 902 if (!find_tab_helper) 903 return; 904 905 find_tab_helper->HandleFindReply(request_id, 906 number_of_matches, 907 selection_rect, 908 active_match_ordinal, 909 final_update); 910} 911 912void Browser::UpdateUIForNavigationInTab(WebContents* contents, 913 content::PageTransition transition, 914 bool user_initiated) { 915 tab_strip_model_->TabNavigating(contents, transition); 916 917 bool contents_is_selected = 918 contents == tab_strip_model_->GetActiveWebContents(); 919 if (user_initiated && contents_is_selected && window()->GetLocationBar()) { 920 // Forcibly reset the location bar if the url is going to change in the 921 // current tab, since otherwise it won't discard any ongoing user edits, 922 // since it doesn't realize this is a user-initiated action. 923 window()->GetLocationBar()->Revert(); 924 } 925 926 if (GetStatusBubble()) 927 GetStatusBubble()->Hide(); 928 929 // Update the location bar. This is synchronous. We specifically don't 930 // update the load state since the load hasn't started yet and updating it 931 // will put it out of sync with the actual state like whether we're 932 // displaying a favicon, which controls the throbber. If we updated it here, 933 // the throbber will show the default favicon for a split second when 934 // navigating away from the new tab page. 935 ScheduleUIUpdate(contents, content::INVALIDATE_TYPE_URL); 936 937 if (contents_is_selected) 938 contents->GetView()->SetInitialFocus(); 939} 940 941/////////////////////////////////////////////////////////////////////////////// 942// Browser, PageNavigator implementation: 943 944WebContents* Browser::OpenURL(const OpenURLParams& params) { 945 return OpenURLFromTab(NULL, params); 946} 947 948/////////////////////////////////////////////////////////////////////////////// 949// Browser, TabStripModelObserver implementation: 950 951void Browser::TabInsertedAt(WebContents* contents, 952 int index, 953 bool foreground) { 954 SetAsDelegate(contents, this); 955 SessionTabHelper* session_tab_helper = 956 SessionTabHelper::FromWebContents(contents); 957 session_tab_helper->SetWindowID(session_id()); 958 959 content::NotificationService::current()->Notify( 960 chrome::NOTIFICATION_TAB_PARENTED, 961 content::Source<content::WebContents>(contents), 962 content::NotificationService::NoDetails()); 963 964 SyncHistoryWithTabs(index); 965 966 // Make sure the loading state is updated correctly, otherwise the throbber 967 // won't start if the page is loading. 968 LoadingStateChanged(contents); 969 970 interstitial_observers_.push_back(new InterstitialObserver(this, contents)); 971 972 SessionService* session_service = 973 SessionServiceFactory::GetForProfile(profile_); 974 if (session_service) { 975 session_service->TabInserted(contents); 976 int new_active_index = tab_strip_model_->active_index(); 977 if (index < new_active_index) 978 session_service->SetSelectedTabInWindow(session_id(), 979 new_active_index); 980 } 981} 982 983void Browser::TabClosingAt(TabStripModel* tab_strip_model, 984 WebContents* contents, 985 int index) { 986 fullscreen_controller_->OnTabClosing(contents); 987 SessionService* session_service = 988 SessionServiceFactory::GetForProfile(profile_); 989 if (session_service) 990 session_service->TabClosing(contents); 991 content::NotificationService::current()->Notify( 992 chrome::NOTIFICATION_TAB_CLOSING, 993 content::Source<NavigationController>(&contents->GetController()), 994 content::NotificationService::NoDetails()); 995 996 // Sever the WebContents' connection back to us. 997 SetAsDelegate(contents, NULL); 998} 999 1000void Browser::TabDetachedAt(WebContents* contents, int index) { 1001 // TabDetachedAt is called before TabStripModel has updated the 1002 // active index. 1003 int old_active_index = tab_strip_model_->active_index(); 1004 if (index < old_active_index && !tab_strip_model_->closing_all()) { 1005 SessionService* session_service = 1006 SessionServiceFactory::GetForProfileIfExisting(profile_); 1007 if (session_service) 1008 session_service->SetSelectedTabInWindow(session_id(), 1009 old_active_index - 1); 1010 } 1011 TabDetachedAtImpl(contents, index, DETACH_TYPE_DETACH); 1012} 1013 1014void Browser::TabDeactivated(WebContents* contents) { 1015 fullscreen_controller_->OnTabDeactivated(contents); 1016 search_delegate_->OnTabDeactivated(contents); 1017 1018 // Save what the user's currently typing, so it can be restored when we 1019 // switch back to this tab. 1020 window_->GetLocationBar()->SaveStateToContents(contents); 1021 1022 if (instant_controller_) 1023 instant_controller_->TabDeactivated(contents); 1024} 1025 1026void Browser::ActiveTabChanged(WebContents* old_contents, 1027 WebContents* new_contents, 1028 int index, 1029 int reason) { 1030 content::RecordAction(UserMetricsAction("ActiveTabChanged")); 1031 1032 // Discarded tabs always get reloaded. 1033 if (tab_strip_model_->IsTabDiscarded(index)) { 1034 LOG(WARNING) << "Reloading discarded tab at " << index; 1035 static int reload_count = 0; 1036 UMA_HISTOGRAM_CUSTOM_COUNTS( 1037 "Tabs.Discard.ReloadCount", ++reload_count, 1, 1000, 50); 1038 chrome::Reload(this, CURRENT_TAB); 1039 } 1040 1041 // If we have any update pending, do it now. 1042 if (chrome_updater_factory_.HasWeakPtrs() && old_contents) 1043 ProcessPendingUIUpdates(); 1044 1045 // Propagate the profile to the location bar. 1046 UpdateToolbar((reason & CHANGE_REASON_REPLACED) == 0); 1047 1048 // Propagate tab state to toolbar, tab-strip, etc. 1049 UpdateSearchState(new_contents); 1050 1051 // Update reload/stop state. 1052 command_controller_->LoadingStateChanged(new_contents->IsLoading(), true); 1053 1054 // Update commands to reflect current state. 1055 command_controller_->TabStateChanged(); 1056 1057 // Reset the status bubble. 1058 StatusBubble* status_bubble = GetStatusBubble(); 1059 if (status_bubble) { 1060 status_bubble->Hide(); 1061 1062 // Show the loading state (if any). 1063 status_bubble->SetStatus(CoreTabHelper::FromWebContents( 1064 tab_strip_model_->GetActiveWebContents())->GetStatusText()); 1065 } 1066 1067 if (HasFindBarController()) { 1068 find_bar_controller_->ChangeWebContents(new_contents); 1069 find_bar_controller_->find_bar()->MoveWindowIfNecessary(gfx::Rect(), true); 1070 } 1071 1072 // Update sessions. Don't force creation of sessions. If sessions doesn't 1073 // exist, the change will be picked up by sessions when created. 1074 SessionService* session_service = 1075 SessionServiceFactory::GetForProfileIfExisting(profile_); 1076 if (session_service && !tab_strip_model_->closing_all()) { 1077 session_service->SetSelectedTabInWindow(session_id(), 1078 tab_strip_model_->active_index()); 1079 } 1080 1081 UpdateBookmarkBarState(BOOKMARK_BAR_STATE_CHANGE_TAB_SWITCH); 1082 1083 // This needs to be called after UpdateSearchState(). 1084 if (instant_controller_) 1085 instant_controller_->ActiveTabChanged(); 1086} 1087 1088void Browser::TabMoved(WebContents* contents, 1089 int from_index, 1090 int to_index) { 1091 DCHECK(from_index >= 0 && to_index >= 0); 1092 // Notify the history service. 1093 SyncHistoryWithTabs(std::min(from_index, to_index)); 1094} 1095 1096void Browser::TabReplacedAt(TabStripModel* tab_strip_model, 1097 WebContents* old_contents, 1098 WebContents* new_contents, 1099 int index) { 1100 TabDetachedAtImpl(old_contents, index, DETACH_TYPE_REPLACE); 1101 fullscreen_controller_->OnTabClosing(old_contents); 1102 SessionService* session_service = 1103 SessionServiceFactory::GetForProfile(profile_); 1104 if (session_service) 1105 session_service->TabClosing(old_contents); 1106 TabInsertedAt(new_contents, 1107 index, 1108 (index == tab_strip_model_->active_index())); 1109 1110 int entry_count = new_contents->GetController().GetEntryCount(); 1111 if (entry_count > 0) { 1112 // Send out notification so that observers are updated appropriately. 1113 new_contents->GetController().NotifyEntryChanged( 1114 new_contents->GetController().GetEntryAtIndex(entry_count - 1), 1115 entry_count - 1); 1116 } 1117 1118 if (session_service) { 1119 // The new_contents may end up with a different navigation stack. Force 1120 // the session service to update itself. 1121 session_service->TabRestored(new_contents, 1122 tab_strip_model_->IsTabPinned(index)); 1123 } 1124} 1125 1126void Browser::TabPinnedStateChanged(WebContents* contents, int index) { 1127 SessionService* session_service = 1128 SessionServiceFactory::GetForProfileIfExisting(profile()); 1129 if (session_service) { 1130 SessionTabHelper* session_tab_helper = 1131 SessionTabHelper::FromWebContents(contents); 1132 session_service->SetPinnedState(session_id(), 1133 session_tab_helper->session_id(), 1134 tab_strip_model_->IsTabPinned(index)); 1135 } 1136} 1137 1138void Browser::TabStripEmpty() { 1139 // Close the frame after we return to the message loop (not immediately, 1140 // otherwise it will destroy this object before the stack has a chance to 1141 // cleanly unwind.) 1142 // Note: This will be called several times if TabStripEmpty is called several 1143 // times. This is because it does not close the window if tabs are 1144 // still present. 1145 base::MessageLoop::current()->PostTask( 1146 FROM_HERE, base::Bind(&Browser::CloseFrame, weak_factory_.GetWeakPtr())); 1147 1148 // Instant may have visible WebContents that need to be detached before the 1149 // window system closes. 1150 instant_controller_.reset(); 1151} 1152 1153bool Browser::CanOverscrollContent() const { 1154#if defined(USE_AURA) 1155 bool overscroll_enabled = CommandLine::ForCurrentProcess()-> 1156 GetSwitchValueASCII(switches::kOverscrollHistoryNavigation) != "0"; 1157 if (!overscroll_enabled) 1158 return false; 1159 if (is_app() || is_devtools() || !is_type_tabbed()) 1160 return false; 1161 1162 // The detached bookmark bar has appearance of floating above the 1163 // web-contents. This does not play nicely with overscroll navigation 1164 // gestures. So disable overscroll navigation when the bookmark bar is in the 1165 // detached state. 1166 if (bookmark_bar_state_ == BookmarkBar::DETACHED) 1167 return false; 1168 return true; 1169#else 1170 return false; 1171#endif 1172} 1173 1174bool Browser::PreHandleKeyboardEvent(content::WebContents* source, 1175 const NativeWebKeyboardEvent& event, 1176 bool* is_keyboard_shortcut) { 1177 // Escape exits tabbed fullscreen mode. 1178 // TODO(koz): Write a test for this http://crbug.com/100441. 1179 if (event.windowsKeyCode == 27 && 1180 fullscreen_controller_->HandleUserPressedEscape()) { 1181 return true; 1182 } 1183 return window()->PreHandleKeyboardEvent(event, is_keyboard_shortcut); 1184} 1185 1186void Browser::HandleKeyboardEvent(content::WebContents* source, 1187 const NativeWebKeyboardEvent& event) { 1188 window()->HandleKeyboardEvent(event); 1189} 1190 1191bool Browser::TabsNeedBeforeUnloadFired() { 1192 if (IsFastTabUnloadEnabled()) 1193 return fast_unload_controller_->TabsNeedBeforeUnloadFired(); 1194 return unload_controller_->TabsNeedBeforeUnloadFired(); 1195} 1196 1197bool Browser::IsMouseLocked() const { 1198 return fullscreen_controller_->IsMouseLocked(); 1199} 1200 1201void Browser::OnWindowDidShow() { 1202 if (window_has_shown_) 1203 return; 1204 window_has_shown_ = true; 1205 1206// CurrentProcessInfo::CreationTime() is currently only implemented on Mac and 1207// Windows. 1208#if defined(OS_MACOSX) || defined(OS_WIN) 1209 // Measure the latency from startup till the first browser window becomes 1210 // visible. 1211 static bool is_first_browser_window = true; 1212 if (is_first_browser_window && 1213 !startup_metric_utils::WasNonBrowserUIDisplayed()) { 1214 is_first_browser_window = false; 1215 const base::Time* process_creation_time = 1216 base::CurrentProcessInfo::CreationTime(); 1217 1218 if (process_creation_time) { 1219 UMA_HISTOGRAM_LONG_TIMES( 1220 "Startup.BrowserWindowDisplay", 1221 base::Time::Now() - *process_creation_time); 1222 } 1223 } 1224#endif // defined(OS_MACOSX) || defined(OS_WIN) 1225 1226 // Nothing to do for non-tabbed windows. 1227 if (!is_type_tabbed()) 1228 return; 1229 1230 // Show any pending global error bubble. 1231 GlobalErrorService* service = 1232 GlobalErrorServiceFactory::GetForProfile(profile()); 1233 GlobalError* error = service->GetFirstGlobalErrorWithBubbleView(); 1234 if (error) 1235 error->ShowBubbleView(this); 1236} 1237 1238void Browser::ShowFirstRunBubble() { 1239 window()->GetLocationBar()->ShowFirstRunBubble(); 1240} 1241 1242void Browser::ShowDownload(content::DownloadItem* download) { 1243 if (!window()) 1244 return; 1245 1246 // If the download occurs in a new tab, and it's not a save page 1247 // download (started before initial navigation completed) close it. 1248 WebContents* source = download->GetWebContents(); 1249 if (source && source->GetController().IsInitialNavigation() && 1250 tab_strip_model_->count() > 1 && !download->IsSavePackageDownload()) { 1251 CloseContents(source); 1252 } 1253 1254 // Some (app downloads) are not supposed to appear on the shelf. 1255 if (!DownloadItemModel(download).ShouldShowInShelf()) 1256 return; 1257 1258 // GetDownloadShelf creates the download shelf if it was not yet created. 1259 DownloadShelf* shelf = window()->GetDownloadShelf(); 1260 shelf->AddDownload(download); 1261} 1262 1263/////////////////////////////////////////////////////////////////////////////// 1264// Browser, content::WebContentsDelegate implementation: 1265 1266WebContents* Browser::OpenURLFromTab(WebContents* source, 1267 const OpenURLParams& params) { 1268 chrome::NavigateParams nav_params(this, params.url, params.transition); 1269 FillNavigateParamsFromOpenURLParams(&nav_params, params); 1270 nav_params.source_contents = source; 1271 nav_params.tabstrip_add_types = TabStripModel::ADD_NONE; 1272 nav_params.window_action = chrome::NavigateParams::SHOW_WINDOW; 1273 nav_params.user_gesture = params.user_gesture; 1274 1275 BlockedContentTabHelper* blocked_content_helper = NULL; 1276 if (source) 1277 blocked_content_helper = BlockedContentTabHelper::FromWebContents(source); 1278 1279 if (CommandLine::ForCurrentProcess()->HasSwitch( 1280 switches::kEnableBetterPopupBlocking) && 1281 blocked_content_helper) { 1282 1283 if (blocked_content_helper->all_contents_blocked()) { 1284 // TODO(jochen): store information about the blocked pop-up in the 1285 // helper. 1286 return NULL; 1287 } 1288 1289 if ((params.disposition == NEW_POPUP || 1290 params.disposition == NEW_FOREGROUND_TAB || 1291 params.disposition == NEW_BACKGROUND_TAB) && 1292 !params.user_gesture && !CommandLine::ForCurrentProcess()->HasSwitch( 1293 switches::kDisablePopupBlocking)) { 1294 return NULL; 1295 } 1296 } 1297 1298 chrome::Navigate(&nav_params); 1299 1300 return nav_params.target_contents; 1301} 1302 1303void Browser::NavigationStateChanged(const WebContents* source, 1304 unsigned changed_flags) { 1305 // Only update the UI when something visible has changed. 1306 if (changed_flags) 1307 ScheduleUIUpdate(source, changed_flags); 1308 1309 // We can synchronously update commands since they will only change once per 1310 // navigation, so we don't have to worry about flickering. We do, however, 1311 // need to update the command state early on load to always present usable 1312 // actions in the face of slow-to-commit pages. 1313 if (changed_flags & (content::INVALIDATE_TYPE_URL | 1314 content::INVALIDATE_TYPE_LOAD)) 1315 command_controller_->TabStateChanged(); 1316} 1317 1318void Browser::AddNewContents(WebContents* source, 1319 WebContents* new_contents, 1320 WindowOpenDisposition disposition, 1321 const gfx::Rect& initial_pos, 1322 bool user_gesture, 1323 bool* was_blocked) { 1324 chrome::AddWebContents(this, source, new_contents, disposition, initial_pos, 1325 user_gesture, was_blocked); 1326} 1327 1328void Browser::ActivateContents(WebContents* contents) { 1329 tab_strip_model_->ActivateTabAt( 1330 tab_strip_model_->GetIndexOfWebContents(contents), false); 1331 window_->Activate(); 1332} 1333 1334void Browser::DeactivateContents(WebContents* contents) { 1335 window_->Deactivate(); 1336} 1337 1338void Browser::LoadingStateChanged(WebContents* source) { 1339 window_->UpdateLoadingAnimations(tab_strip_model_->TabsAreLoading()); 1340 window_->UpdateTitleBar(); 1341 1342 WebContents* selected_contents = tab_strip_model_->GetActiveWebContents(); 1343 if (source == selected_contents) { 1344 bool is_loading = source->IsLoading(); 1345 command_controller_->LoadingStateChanged(is_loading, false); 1346 if (GetStatusBubble()) { 1347 GetStatusBubble()->SetStatus(CoreTabHelper::FromWebContents( 1348 tab_strip_model_->GetActiveWebContents())->GetStatusText()); 1349 } 1350 } 1351} 1352 1353void Browser::CloseContents(WebContents* source) { 1354 bool can_close_contents; 1355 if (IsFastTabUnloadEnabled()) 1356 can_close_contents = fast_unload_controller_->CanCloseContents(source); 1357 else 1358 can_close_contents = unload_controller_->CanCloseContents(source); 1359 1360 if (can_close_contents) 1361 chrome::CloseWebContents(this, source, true); 1362} 1363 1364void Browser::MoveContents(WebContents* source, const gfx::Rect& pos) { 1365 if (!IsPopupOrPanel(source)) { 1366 NOTREACHED() << "moving invalid browser type"; 1367 return; 1368 } 1369 window_->SetBounds(pos); 1370} 1371 1372bool Browser::IsPopupOrPanel(const WebContents* source) const { 1373 return is_type_popup(); 1374} 1375 1376void Browser::UpdateTargetURL(WebContents* source, int32 page_id, 1377 const GURL& url) { 1378 if (!GetStatusBubble()) 1379 return; 1380 1381 if (source == tab_strip_model_->GetActiveWebContents()) { 1382 PrefService* prefs = profile_->GetPrefs(); 1383 GetStatusBubble()->SetURL(url, prefs->GetString(prefs::kAcceptLanguages)); 1384 } 1385} 1386 1387void Browser::ContentsMouseEvent( 1388 WebContents* source, const gfx::Point& location, bool motion) { 1389 if (!GetStatusBubble()) 1390 return; 1391 1392 if (source == tab_strip_model_->GetActiveWebContents()) { 1393 GetStatusBubble()->MouseMoved(location, !motion); 1394 if (!motion) 1395 GetStatusBubble()->SetURL(GURL(), std::string()); 1396 } 1397} 1398 1399void Browser::ContentsZoomChange(bool zoom_in) { 1400 chrome::ExecuteCommand(this, zoom_in ? IDC_ZOOM_PLUS : IDC_ZOOM_MINUS); 1401} 1402 1403void Browser::WebContentsFocused(WebContents* contents) { 1404 window_->WebContentsFocused(contents); 1405} 1406 1407bool Browser::TakeFocus(content::WebContents* source, 1408 bool reverse) { 1409 content::NotificationService::current()->Notify( 1410 chrome::NOTIFICATION_FOCUS_RETURNED_TO_BROWSER, 1411 content::Source<Browser>(this), 1412 content::NotificationService::NoDetails()); 1413 return false; 1414} 1415 1416gfx::Rect Browser::GetRootWindowResizerRect() const { 1417 return window_->GetRootWindowResizerRect(); 1418} 1419 1420void Browser::BeforeUnloadFired(WebContents* web_contents, 1421 bool proceed, 1422 bool* proceed_to_fire_unload) { 1423 if (IsFastTabUnloadEnabled()) { 1424 *proceed_to_fire_unload = 1425 fast_unload_controller_->BeforeUnloadFired(web_contents, proceed); 1426 } else { 1427 *proceed_to_fire_unload = 1428 unload_controller_->BeforeUnloadFired(web_contents, proceed); 1429 } 1430} 1431 1432bool Browser::ShouldFocusLocationBarByDefault(WebContents* source) { 1433 const content::NavigationEntry* entry = 1434 source->GetController().GetActiveEntry(); 1435 if (entry) { 1436 GURL url = entry->GetURL(); 1437 GURL virtual_url = entry->GetVirtualURL(); 1438 if ((url.SchemeIs(chrome::kChromeUIScheme) && 1439 url.host() == chrome::kChromeUINewTabHost) || 1440 (virtual_url.SchemeIs(chrome::kChromeUIScheme) && 1441 virtual_url.host() == chrome::kChromeUINewTabHost)) { 1442 return true; 1443 } 1444 } 1445 1446 return chrome::NavEntryIsInstantNTP(source, entry); 1447} 1448 1449void Browser::SetFocusToLocationBar(bool select_all) { 1450 // Two differences between this and FocusLocationBar(): 1451 // (1) This doesn't get recorded in user metrics, since it's called 1452 // internally. 1453 // (2) This checks whether the location bar can be focused, and if not, clears 1454 // the focus. FocusLocationBar() is only reached when the location bar is 1455 // focusable, but this may be reached at other times, e.g. while in 1456 // fullscreen mode, where we need to leave focus in a consistent state. 1457 window_->SetFocusToLocationBar(select_all); 1458} 1459 1460void Browser::RenderWidgetShowing() { 1461 window_->DisableInactiveFrame(); 1462} 1463 1464int Browser::GetExtraRenderViewHeight() const { 1465 return window_->GetExtraRenderViewHeight(); 1466} 1467 1468void Browser::ViewSourceForTab(WebContents* source, const GURL& page_url) { 1469 DCHECK(source); 1470 chrome::ViewSource(this, source); 1471} 1472 1473void Browser::ViewSourceForFrame(WebContents* source, 1474 const GURL& frame_url, 1475 const content::PageState& frame_page_state) { 1476 DCHECK(source); 1477 chrome::ViewSource(this, source, frame_url, frame_page_state); 1478} 1479 1480void Browser::ShowRepostFormWarningDialog(WebContents* source) { 1481 TabModalConfirmDialog::Create(new RepostFormWarningController(source), 1482 source); 1483} 1484 1485bool Browser::ShouldCreateWebContents( 1486 WebContents* web_contents, 1487 int route_id, 1488 WindowContainerType window_container_type, 1489 const string16& frame_name, 1490 const GURL& target_url, 1491 WindowOpenDisposition disposition, 1492 bool user_gesture) { 1493 if (window_container_type == WINDOW_CONTAINER_TYPE_BACKGROUND) { 1494 // If a BackgroundContents is created, suppress the normal WebContents. 1495 return !MaybeCreateBackgroundContents( 1496 route_id, web_contents, frame_name, target_url); 1497 } 1498 1499 if (!CommandLine::ForCurrentProcess()->HasSwitch( 1500 switches::kEnableBetterPopupBlocking)) { 1501 return true; 1502 } 1503 1504 BlockedContentTabHelper* blocked_content_helper = 1505 BlockedContentTabHelper::FromWebContents(web_contents); 1506 if (!blocked_content_helper) 1507 return true; 1508 1509 if (blocked_content_helper->all_contents_blocked()) { 1510 // TODO(jochen): store information about the blocked pop-up in the helper. 1511 return false; 1512 } 1513 1514 if ((disposition == NEW_POPUP || disposition == NEW_FOREGROUND_TAB || 1515 disposition == NEW_BACKGROUND_TAB) && !user_gesture && 1516 !CommandLine::ForCurrentProcess()->HasSwitch( 1517 switches::kDisablePopupBlocking)) { 1518 return false; 1519 } 1520 1521 return true; 1522} 1523 1524void Browser::WebContentsCreated(WebContents* source_contents, 1525 int64 source_frame_id, 1526 const string16& frame_name, 1527 const GURL& target_url, 1528 WebContents* new_contents) { 1529 // Adopt the WebContents now, so all observers are in place, as the network 1530 // requests for its initial navigation will start immediately. The WebContents 1531 // will later be inserted into this browser using Browser::Navigate via 1532 // AddNewContents. 1533 BrowserTabContents::AttachTabHelpers(new_contents); 1534 1535 // Notify. 1536 RetargetingDetails details; 1537 details.source_web_contents = source_contents; 1538 details.source_frame_id = source_frame_id; 1539 details.target_url = target_url; 1540 details.target_web_contents = new_contents; 1541 details.not_yet_in_tabstrip = true; 1542 content::NotificationService::current()->Notify( 1543 chrome::NOTIFICATION_RETARGETING, 1544 content::Source<Profile>(profile_), 1545 content::Details<RetargetingDetails>(&details)); 1546} 1547 1548void Browser::ContentRestrictionsChanged(WebContents* source) { 1549 command_controller_->ContentRestrictionsChanged(); 1550} 1551 1552void Browser::RendererUnresponsive(WebContents* source) { 1553 // Ignore hangs if a tab is blocked. 1554 int index = tab_strip_model_->GetIndexOfWebContents(source); 1555 DCHECK_NE(TabStripModel::kNoTab, index); 1556 if (tab_strip_model_->IsTabBlocked(index)) 1557 return; 1558 1559 chrome::ShowHungRendererDialog(source); 1560} 1561 1562void Browser::RendererResponsive(WebContents* source) { 1563 chrome::HideHungRendererDialog(source); 1564} 1565 1566void Browser::WorkerCrashed(WebContents* source) { 1567 SimpleAlertInfoBarDelegate::Create( 1568 InfoBarService::FromWebContents(source), InfoBarDelegate::kNoIconID, 1569 l10n_util::GetStringUTF16(IDS_WEBWORKER_CRASHED_PROMPT), true); 1570} 1571 1572void Browser::DidNavigateMainFramePostCommit(WebContents* web_contents) { 1573 if (web_contents == tab_strip_model_->GetActiveWebContents()) 1574 UpdateBookmarkBarState(BOOKMARK_BAR_STATE_CHANGE_TAB_STATE); 1575} 1576 1577void Browser::DidNavigateToPendingEntry(WebContents* web_contents) { 1578 if (web_contents == tab_strip_model_->GetActiveWebContents()) 1579 UpdateBookmarkBarState(BOOKMARK_BAR_STATE_CHANGE_TAB_STATE); 1580} 1581 1582content::JavaScriptDialogManager* Browser::GetJavaScriptDialogManager() { 1583 return GetJavaScriptDialogManagerInstance(); 1584} 1585 1586content::ColorChooser* Browser::OpenColorChooser(WebContents* web_contents, 1587 SkColor initial_color) { 1588 return chrome::ShowColorChooser(web_contents, initial_color); 1589} 1590 1591void Browser::RunFileChooser(WebContents* web_contents, 1592 const content::FileChooserParams& params) { 1593 FileSelectHelper::RunFileChooser(web_contents, params); 1594} 1595 1596void Browser::EnumerateDirectory(WebContents* web_contents, 1597 int request_id, 1598 const base::FilePath& path) { 1599 FileSelectHelper::EnumerateDirectory(web_contents, request_id, path); 1600} 1601 1602void Browser::ToggleFullscreenModeForTab(WebContents* web_contents, 1603 bool enter_fullscreen) { 1604 fullscreen_controller_->ToggleFullscreenModeForTab(web_contents, 1605 enter_fullscreen); 1606} 1607 1608bool Browser::IsFullscreenForTabOrPending( 1609 const WebContents* web_contents) const { 1610 return fullscreen_controller_->IsFullscreenForTabOrPending(web_contents); 1611} 1612 1613void Browser::JSOutOfMemory(WebContents* web_contents) { 1614 JSOutOfMemoryHelper(web_contents); 1615} 1616 1617void Browser::RegisterProtocolHandler(WebContents* web_contents, 1618 const std::string& protocol, 1619 const GURL& url, 1620 const string16& title, 1621 bool user_gesture) { 1622 RegisterProtocolHandlerHelper( 1623 web_contents, protocol, url, title, user_gesture, window()); 1624} 1625 1626void Browser::UpdatePreferredSize(WebContents* source, 1627 const gfx::Size& pref_size) { 1628 window_->UpdatePreferredSize(source, pref_size); 1629} 1630 1631void Browser::ResizeDueToAutoResize(WebContents* source, 1632 const gfx::Size& new_size) { 1633 window_->ResizeDueToAutoResize(source, new_size); 1634} 1635 1636void Browser::FindReply(WebContents* web_contents, 1637 int request_id, 1638 int number_of_matches, 1639 const gfx::Rect& selection_rect, 1640 int active_match_ordinal, 1641 bool final_update) { 1642 FindReplyHelper(web_contents, request_id, number_of_matches, selection_rect, 1643 active_match_ordinal, final_update); 1644} 1645 1646void Browser::RequestToLockMouse(WebContents* web_contents, 1647 bool user_gesture, 1648 bool last_unlocked_by_target) { 1649 fullscreen_controller_->RequestToLockMouse(web_contents, 1650 user_gesture, 1651 last_unlocked_by_target); 1652} 1653 1654void Browser::LostMouseLock() { 1655 fullscreen_controller_->LostMouseLock(); 1656} 1657 1658void Browser::RequestMediaAccessPermission( 1659 content::WebContents* web_contents, 1660 const content::MediaStreamRequest& request, 1661 const content::MediaResponseCallback& callback) { 1662 const extensions::Extension* extension = NULL; 1663 GURL origin(request.security_origin); 1664 if (origin.SchemeIs(extensions::kExtensionScheme)) { 1665 ExtensionService* extensions_service = 1666 extensions::ExtensionSystem::Get(profile_)->extension_service(); 1667 extension = extensions_service->extensions()->GetByID(origin.host()); 1668 DCHECK(extension); 1669 } 1670 1671 MediaCaptureDevicesDispatcher::GetInstance()->ProcessMediaAccessRequest( 1672 web_contents, request, callback, extension); 1673} 1674 1675bool Browser::RequestPpapiBrokerPermission( 1676 WebContents* web_contents, 1677 const GURL& url, 1678 const base::FilePath& plugin_path, 1679 const base::Callback<void(bool)>& callback) { 1680 PepperBrokerInfoBarDelegate::Create(web_contents, url, plugin_path, callback); 1681 return true; 1682} 1683 1684/////////////////////////////////////////////////////////////////////////////// 1685// Browser, CoreTabHelperDelegate implementation: 1686 1687void Browser::SwapTabContents(content::WebContents* old_contents, 1688 content::WebContents* new_contents) { 1689 int index = tab_strip_model_->GetIndexOfWebContents(old_contents); 1690 DCHECK_NE(TabStripModel::kNoTab, index); 1691 tab_strip_model_->ReplaceWebContentsAt(index, new_contents); 1692} 1693 1694bool Browser::CanReloadContents(content::WebContents* web_contents) const { 1695 return chrome::CanReload(this); 1696} 1697 1698bool Browser::CanSaveContents(content::WebContents* web_contents) const { 1699 return chrome::CanSavePage(this); 1700} 1701 1702/////////////////////////////////////////////////////////////////////////////// 1703// Browser, SearchEngineTabHelperDelegate implementation: 1704 1705void Browser::ConfirmAddSearchProvider(TemplateURL* template_url, 1706 Profile* profile) { 1707 window()->ConfirmAddSearchProvider(template_url, profile); 1708} 1709 1710/////////////////////////////////////////////////////////////////////////////// 1711// Browser, web_modal::WebContentsModalDialogManagerDelegate implementation: 1712 1713void Browser::SetWebContentsBlocked(content::WebContents* web_contents, 1714 bool blocked) { 1715 int index = tab_strip_model_->GetIndexOfWebContents(web_contents); 1716 if (index == TabStripModel::kNoTab) { 1717 NOTREACHED(); 1718 return; 1719 } 1720 tab_strip_model_->SetTabBlocked(index, blocked); 1721 if (!blocked && tab_strip_model_->GetActiveWebContents() == web_contents) 1722 web_contents->GetView()->Focus(); 1723} 1724 1725web_modal::WebContentsModalDialogHost* 1726Browser::GetWebContentsModalDialogHost() { 1727 return window_->GetWebContentsModalDialogHost(); 1728} 1729 1730/////////////////////////////////////////////////////////////////////////////// 1731// Browser, BlockedContentTabHelperDelegate implementation: 1732 1733content::WebContents* Browser::GetConstrainingWebContents( 1734 content::WebContents* source) { 1735 return source; 1736} 1737 1738/////////////////////////////////////////////////////////////////////////////// 1739// Browser, BookmarkTabHelperDelegate implementation: 1740 1741void Browser::URLStarredChanged(content::WebContents* web_contents, 1742 bool starred) { 1743 if (web_contents == tab_strip_model_->GetActiveWebContents()) 1744 window_->SetStarredState(starred); 1745} 1746 1747/////////////////////////////////////////////////////////////////////////////// 1748// Browser, ZoomObserver implementation: 1749 1750void Browser::OnZoomChanged(content::WebContents* source, 1751 bool can_show_bubble) { 1752 if (source == tab_strip_model_->GetActiveWebContents()) { 1753 // Only show the zoom bubble for zoom changes in the active window. 1754 window_->ZoomChangedForActiveTab(can_show_bubble && window_->IsActive()); 1755 } 1756} 1757 1758/////////////////////////////////////////////////////////////////////////////// 1759// Browser, ui::SelectFileDialog::Listener implementation: 1760 1761void Browser::FileSelected(const base::FilePath& path, int index, 1762 void* params) { 1763 FileSelectedWithExtraInfo(ui::SelectedFileInfo(path, path), index, params); 1764} 1765 1766void Browser::FileSelectedWithExtraInfo(const ui::SelectedFileInfo& file_info, 1767 int index, 1768 void* params) { 1769 profile_->set_last_selected_directory(file_info.file_path.DirName()); 1770 1771 GURL url = net::FilePathToFileURL(file_info.local_path); 1772 1773#if defined(OS_CHROMEOS) 1774 drive::util::MaybeSetDriveURL(profile_, file_info.file_path, &url); 1775#endif 1776 1777 if (url.is_empty()) 1778 return; 1779 1780 OpenURL(OpenURLParams( 1781 url, Referrer(), CURRENT_TAB, content::PAGE_TRANSITION_TYPED, false)); 1782} 1783 1784/////////////////////////////////////////////////////////////////////////////// 1785// Browser, content::NotificationObserver implementation: 1786 1787void Browser::Observe(int type, 1788 const content::NotificationSource& source, 1789 const content::NotificationDetails& details) { 1790 switch (type) { 1791 case chrome::NOTIFICATION_EXTENSION_UNLOADED: { 1792 if (window()->GetLocationBar()) 1793 window()->GetLocationBar()->UpdatePageActions(); 1794 1795 const extensions::UnloadedExtensionInfo* extension_info = 1796 content::Details<extensions::UnloadedExtensionInfo>(details).ptr(); 1797 1798 // Close any tabs from the unloaded extension, unless it's terminated, 1799 // in which case let the sad tabs remain. 1800 if (extension_info->reason != extension_misc::UNLOAD_REASON_TERMINATE) { 1801 const Extension* extension = extension_info->extension; 1802 // Iterate backwards as we may remove items while iterating. 1803 for (int i = tab_strip_model_->count() - 1; i >= 0; --i) { 1804 WebContents* web_contents = tab_strip_model_->GetWebContentsAt(i); 1805 // Two cases are handled here: 1806 // - The scheme check is for when an extension page is loaded in a 1807 // tab, e.g. chrome-extension://id/page.html. 1808 // - The extension_app check is for apps, which can have non-extension 1809 // schemes, e.g. https://mail.google.com if you have the Gmail app 1810 // installed. 1811 if ((web_contents->GetURL().SchemeIs(extensions::kExtensionScheme) && 1812 web_contents->GetURL().host() == extension->id()) || 1813 (extensions::TabHelper::FromWebContents( 1814 web_contents)->extension_app() == extension)) { 1815 tab_strip_model_->CloseWebContentsAt(i, TabStripModel::CLOSE_NONE); 1816 } 1817 } 1818 } 1819 break; 1820 } 1821 1822 case chrome::NOTIFICATION_EXTENSION_PROCESS_TERMINATED: { 1823 Profile* profile = content::Source<Profile>(source).ptr(); 1824 if (profile_->IsSameProfile(profile) && window()->GetLocationBar()) 1825 window()->GetLocationBar()->InvalidatePageActions(); 1826 break; 1827 } 1828 1829 case chrome::NOTIFICATION_EXTENSION_UNINSTALLED: 1830 case chrome::NOTIFICATION_EXTENSION_LOADED: 1831 // During window creation on Windows we may end up calling into 1832 // SHAppBarMessage, which internally spawns a nested message loop. This 1833 // makes it possible for us to end up here before window creation has 1834 // completed, at which point window_ is NULL. See 94752 for details. 1835 if (window() && window()->GetLocationBar()) 1836 window()->GetLocationBar()->UpdatePageActions(); 1837 break; 1838 1839#if defined(ENABLE_THEMES) 1840 case chrome::NOTIFICATION_BROWSER_THEME_CHANGED: 1841 window()->UserChangedTheme(); 1842 break; 1843#endif 1844 1845 case chrome::NOTIFICATION_WEB_CONTENT_SETTINGS_CHANGED: { 1846 WebContents* web_contents = content::Source<WebContents>(source).ptr(); 1847 if (web_contents == tab_strip_model_->GetActiveWebContents()) { 1848 LocationBar* location_bar = window()->GetLocationBar(); 1849 if (location_bar) 1850 location_bar->UpdateContentSettingsIcons(); 1851 } 1852 break; 1853 } 1854 1855 default: 1856 NOTREACHED() << "Got a notification we didn't register for."; 1857 } 1858} 1859 1860/////////////////////////////////////////////////////////////////////////////// 1861// Browser, Command and state updating (private): 1862 1863void Browser::OnDevToolsDisabledChanged() { 1864 if (profile_->GetPrefs()->GetBoolean(prefs::kDevToolsDisabled)) 1865 content::DevToolsManager::GetInstance()->CloseAllClientHosts(); 1866} 1867 1868/////////////////////////////////////////////////////////////////////////////// 1869// Browser, UI update coalescing and handling (private): 1870 1871void Browser::UpdateToolbar(bool should_restore_state) { 1872 window_->UpdateToolbar(tab_strip_model_->GetActiveWebContents(), 1873 should_restore_state); 1874} 1875 1876void Browser::UpdateSearchState(WebContents* contents) { 1877 if (chrome::IsInstantExtendedAPIEnabled()) 1878 search_delegate_->OnTabActivated(contents); 1879} 1880 1881void Browser::ScheduleUIUpdate(const WebContents* source, 1882 unsigned changed_flags) { 1883 if (!source) 1884 return; 1885 1886 // Do some synchronous updates. 1887 if (changed_flags & content::INVALIDATE_TYPE_URL && 1888 source == tab_strip_model_->GetActiveWebContents()) { 1889 // Only update the URL for the current tab. Note that we do not update 1890 // the navigation commands since those would have already been updated 1891 // synchronously by NavigationStateChanged. 1892 UpdateToolbar(false); 1893 changed_flags &= ~content::INVALIDATE_TYPE_URL; 1894 } 1895 if (changed_flags & content::INVALIDATE_TYPE_LOAD) { 1896 // Update the loading state synchronously. This is so the throbber will 1897 // immediately start/stop, which gives a more snappy feel. We want to do 1898 // this for any tab so they start & stop quickly. 1899 tab_strip_model_->UpdateWebContentsStateAt( 1900 tab_strip_model_->GetIndexOfWebContents(source), 1901 TabStripModelObserver::LOADING_ONLY); 1902 // The status bubble needs to be updated during INVALIDATE_TYPE_LOAD too, 1903 // but we do that asynchronously by not stripping INVALIDATE_TYPE_LOAD from 1904 // changed_flags. 1905 } 1906 1907 if (changed_flags & content::INVALIDATE_TYPE_TITLE && !source->IsLoading()) { 1908 // To correctly calculate whether the title changed while not loading 1909 // we need to process the update synchronously. This state only matters for 1910 // the TabStripModel, so we notify the TabStripModel now and notify others 1911 // asynchronously. 1912 tab_strip_model_->UpdateWebContentsStateAt( 1913 tab_strip_model_->GetIndexOfWebContents(source), 1914 TabStripModelObserver::TITLE_NOT_LOADING); 1915 } 1916 1917 // If the only updates were synchronously handled above, we're done. 1918 if (changed_flags == 0) 1919 return; 1920 1921 // Save the dirty bits. 1922 scheduled_updates_[source] |= changed_flags; 1923 1924 if (!chrome_updater_factory_.HasWeakPtrs()) { 1925 // No task currently scheduled, start another. 1926 base::MessageLoop::current()->PostDelayedTask( 1927 FROM_HERE, 1928 base::Bind(&Browser::ProcessPendingUIUpdates, 1929 chrome_updater_factory_.GetWeakPtr()), 1930 base::TimeDelta::FromMilliseconds(kUIUpdateCoalescingTimeMS)); 1931 } 1932} 1933 1934void Browser::ProcessPendingUIUpdates() { 1935#ifndef NDEBUG 1936 // Validate that all tabs we have pending updates for exist. This is scary 1937 // because the pending list must be kept in sync with any detached or 1938 // deleted tabs. 1939 for (UpdateMap::const_iterator i = scheduled_updates_.begin(); 1940 i != scheduled_updates_.end(); ++i) { 1941 bool found = false; 1942 for (int tab = 0; tab < tab_strip_model_->count(); tab++) { 1943 if (tab_strip_model_->GetWebContentsAt(tab) == i->first) { 1944 found = true; 1945 break; 1946 } 1947 } 1948 DCHECK(found); 1949 } 1950#endif 1951 1952 chrome_updater_factory_.InvalidateWeakPtrs(); 1953 1954 for (UpdateMap::const_iterator i = scheduled_updates_.begin(); 1955 i != scheduled_updates_.end(); ++i) { 1956 // Do not dereference |contents|, it may be out-of-date! 1957 const WebContents* contents = i->first; 1958 unsigned flags = i->second; 1959 1960 if (contents == tab_strip_model_->GetActiveWebContents()) { 1961 // Updates that only matter when the tab is selected go here. 1962 1963 if (flags & content::INVALIDATE_TYPE_PAGE_ACTIONS) { 1964 LocationBar* location_bar = window()->GetLocationBar(); 1965 if (location_bar) 1966 location_bar->UpdatePageActions(); 1967 } 1968 // Updating the URL happens synchronously in ScheduleUIUpdate. 1969 if (flags & content::INVALIDATE_TYPE_LOAD && GetStatusBubble()) { 1970 GetStatusBubble()->SetStatus(CoreTabHelper::FromWebContents( 1971 tab_strip_model_->GetActiveWebContents())->GetStatusText()); 1972 } 1973 1974 if (flags & (content::INVALIDATE_TYPE_TAB | 1975 content::INVALIDATE_TYPE_TITLE)) { 1976 window_->UpdateTitleBar(); 1977 } 1978 } 1979 1980 // Updates that don't depend upon the selected state go here. 1981 if (flags & 1982 (content::INVALIDATE_TYPE_TAB | content::INVALIDATE_TYPE_TITLE)) { 1983 tab_strip_model_->UpdateWebContentsStateAt( 1984 tab_strip_model_->GetIndexOfWebContents(contents), 1985 TabStripModelObserver::ALL); 1986 } 1987 1988 // Update the bookmark bar. It may happen that the tab is crashed, and if 1989 // so, the bookmark bar should be hidden. 1990 if (flags & content::INVALIDATE_TYPE_TAB) 1991 UpdateBookmarkBarState(BOOKMARK_BAR_STATE_CHANGE_TAB_STATE); 1992 1993 // We don't need to process INVALIDATE_STATE, since that's not visible. 1994 } 1995 1996 scheduled_updates_.clear(); 1997} 1998 1999void Browser::RemoveScheduledUpdatesFor(WebContents* contents) { 2000 if (!contents) 2001 return; 2002 2003 UpdateMap::iterator i = scheduled_updates_.find(contents); 2004 if (i != scheduled_updates_.end()) 2005 scheduled_updates_.erase(i); 2006} 2007 2008/////////////////////////////////////////////////////////////////////////////// 2009// Browser, Getters for UI (private): 2010 2011StatusBubble* Browser::GetStatusBubble() { 2012 // In kiosk and exclusive app mode, we want to always hide the status bubble. 2013 if (chrome::IsRunningInAppMode()) 2014 return NULL; 2015 2016 return window_ ? window_->GetStatusBubble() : NULL; 2017} 2018 2019/////////////////////////////////////////////////////////////////////////////// 2020// Browser, Session restore functions (private): 2021 2022void Browser::SyncHistoryWithTabs(int index) { 2023 SessionService* session_service = 2024 SessionServiceFactory::GetForProfileIfExisting(profile()); 2025 if (session_service) { 2026 for (int i = index; i < tab_strip_model_->count(); ++i) { 2027 WebContents* web_contents = tab_strip_model_->GetWebContentsAt(i); 2028 if (web_contents) { 2029 SessionTabHelper* session_tab_helper = 2030 SessionTabHelper::FromWebContents(web_contents); 2031 session_service->SetTabIndexInWindow( 2032 session_id(), session_tab_helper->session_id(), i); 2033 session_service->SetPinnedState( 2034 session_id(), 2035 session_tab_helper->session_id(), 2036 tab_strip_model_->IsTabPinned(i)); 2037 } 2038 } 2039 } 2040} 2041 2042/////////////////////////////////////////////////////////////////////////////// 2043// Browser, In-progress download termination handling (private): 2044 2045bool Browser::CanCloseWithInProgressDownloads() { 2046 // If we've prompted, we need to hear from the user before we 2047 // can close. 2048 if (cancel_download_confirmation_state_ != NOT_PROMPTED) 2049 return cancel_download_confirmation_state_ != WAITING_FOR_RESPONSE; 2050 2051 int num_downloads_blocking; 2052 if (DOWNLOAD_CLOSE_OK == 2053 OkToCloseWithInProgressDownloads(&num_downloads_blocking)) 2054 return true; 2055 2056 // Closing this window will kill some downloads; prompt to make sure 2057 // that's ok. 2058 cancel_download_confirmation_state_ = WAITING_FOR_RESPONSE; 2059 window_->ConfirmBrowserCloseWithPendingDownloads(); 2060 2061 // Return false so the browser does not close. We'll close if the user 2062 // confirms in the dialog. 2063 return false; 2064} 2065 2066/////////////////////////////////////////////////////////////////////////////// 2067// Browser, Assorted utility functions (private): 2068 2069void Browser::SetAsDelegate(WebContents* web_contents, Browser* delegate) { 2070 // WebContents... 2071 web_contents->SetDelegate(delegate); 2072 2073 // ...and all the helpers. 2074 BlockedContentTabHelper::FromWebContents(web_contents)-> 2075 set_delegate(delegate); 2076 BookmarkTabHelper::FromWebContents(web_contents)->set_delegate(delegate); 2077 WebContentsModalDialogManager::FromWebContents(web_contents)-> 2078 set_delegate(delegate); 2079 CoreTabHelper::FromWebContents(web_contents)->set_delegate(delegate); 2080 SearchEngineTabHelper::FromWebContents(web_contents)->set_delegate(delegate); 2081 ZoomController::FromWebContents(web_contents)->set_observer(delegate); 2082} 2083 2084void Browser::CloseFrame() { 2085 window_->Close(); 2086} 2087 2088void Browser::TabDetachedAtImpl(content::WebContents* contents, 2089 int index, 2090 DetachType type) { 2091 if (type == DETACH_TYPE_DETACH) { 2092 // Save the current location bar state, but only if the tab being detached 2093 // is the selected tab. Because saving state can conditionally revert the 2094 // location bar, saving the current tab's location bar state to a 2095 // non-selected tab can corrupt both tabs. 2096 if (contents == tab_strip_model_->GetActiveWebContents()) { 2097 LocationBar* location_bar = window()->GetLocationBar(); 2098 if (location_bar) 2099 location_bar->SaveStateToContents(contents); 2100 } 2101 2102 if (!tab_strip_model_->closing_all()) 2103 SyncHistoryWithTabs(0); 2104 } 2105 2106 SetAsDelegate(contents, NULL); 2107 RemoveScheduledUpdatesFor(contents); 2108 2109 if (find_bar_controller_.get() && index == tab_strip_model_->active_index()) { 2110 find_bar_controller_->ChangeWebContents(NULL); 2111 } 2112 2113 // Stop observing search model changes for this tab. 2114 search_delegate_->OnTabDetached(contents); 2115 2116 for (size_t i = 0; i < interstitial_observers_.size(); i++) { 2117 if (interstitial_observers_[i]->web_contents() != contents) 2118 continue; 2119 2120 delete interstitial_observers_[i]; 2121 interstitial_observers_.erase(interstitial_observers_.begin() + i); 2122 return; 2123 } 2124} 2125 2126bool Browser::SupportsWindowFeatureImpl(WindowFeature feature, 2127 bool check_fullscreen) const { 2128 bool hide_ui_for_fullscreen = check_fullscreen && ShouldHideUIForFullscreen(); 2129 2130 unsigned int features = FEATURE_INFOBAR | FEATURE_DOWNLOADSHELF; 2131 2132 if (is_type_tabbed()) 2133 features |= FEATURE_BOOKMARKBAR; 2134 2135 if (!hide_ui_for_fullscreen) { 2136 if (!is_type_tabbed()) 2137 features |= FEATURE_TITLEBAR; 2138 2139 if (is_type_tabbed()) 2140 features |= FEATURE_TABSTRIP; 2141 2142 if (is_type_tabbed()) 2143 features |= FEATURE_TOOLBAR; 2144 2145 if (!is_app()) 2146 features |= FEATURE_LOCATIONBAR; 2147 } 2148 return !!(features & feature); 2149} 2150 2151void Browser::UpdateBookmarkBarState(BookmarkBarStateChangeReason reason) { 2152 BookmarkBar::State state; 2153 // The bookmark bar is hidden in fullscreen mode, unless on the new tab page. 2154 if (browser_defaults::bookmarks_enabled && 2155 profile_->GetPrefs()->GetBoolean(prefs::kShowBookmarkBar) && 2156 !ShouldHideUIForFullscreen()) { 2157 state = BookmarkBar::SHOW; 2158 } else { 2159 WebContents* web_contents = tab_strip_model_->GetActiveWebContents(); 2160 BookmarkTabHelper* bookmark_tab_helper = 2161 web_contents ? BookmarkTabHelper::FromWebContents(web_contents) : NULL; 2162 if (bookmark_tab_helper && bookmark_tab_helper->ShouldShowBookmarkBar()) 2163 state = BookmarkBar::DETACHED; 2164 else 2165 state = BookmarkBar::HIDDEN; 2166 } 2167 2168 if (state == bookmark_bar_state_) 2169 return; 2170 2171 bookmark_bar_state_ = state; 2172 2173 if (!window_) 2174 return; // This is called from the constructor when window_ is NULL. 2175 2176 if (reason == BOOKMARK_BAR_STATE_CHANGE_TAB_SWITCH) { 2177 // Don't notify BrowserWindow on a tab switch as at the time this is invoked 2178 // BrowserWindow hasn't yet switched tabs. The BrowserWindow implementations 2179 // end up querying state once they process the tab switch. 2180 return; 2181 } 2182 2183 bool shouldAnimate = reason == BOOKMARK_BAR_STATE_CHANGE_PREF_CHANGE; 2184 window_->BookmarkBarStateChanged(shouldAnimate ? 2185 BookmarkBar::ANIMATE_STATE_CHANGE : 2186 BookmarkBar::DONT_ANIMATE_STATE_CHANGE); 2187} 2188 2189bool Browser::ShouldHideUIForFullscreen() const { 2190 // Windows and GTK remove the top controls in fullscreen, but Mac and Ash 2191 // keep the controls in a slide-down panel. 2192 return window_ && window_->ShouldHideUIForFullscreen(); 2193} 2194 2195bool Browser::MaybeCreateBackgroundContents(int route_id, 2196 WebContents* opener_web_contents, 2197 const string16& frame_name, 2198 const GURL& target_url) { 2199 GURL opener_url = opener_web_contents->GetURL(); 2200 ExtensionService* extensions_service = 2201 extensions::ExtensionSystem::Get(profile_)->extension_service(); 2202 2203 if (!opener_url.is_valid() || 2204 frame_name.empty() || 2205 !extensions_service || 2206 !extensions_service->is_ready()) 2207 return false; 2208 2209 // Only hosted apps have web extents, so this ensures that only hosted apps 2210 // can create BackgroundContents. We don't have to check for background 2211 // permission as that is checked in RenderMessageFilter when the CreateWindow 2212 // message is processed. 2213 const Extension* extension = 2214 extensions_service->extensions()->GetHostedAppByURL( 2215 ExtensionURLInfo(opener_url)); 2216 if (!extension) 2217 return false; 2218 2219 // No BackgroundContents allowed if BackgroundContentsService doesn't exist. 2220 BackgroundContentsService* service = 2221 BackgroundContentsServiceFactory::GetForProfile(profile_); 2222 if (!service) 2223 return false; 2224 2225 // Ensure that we're trying to open this from the extension's process. 2226 SiteInstance* opener_site_instance = opener_web_contents->GetSiteInstance(); 2227 extensions::ProcessMap* process_map = extensions_service->process_map(); 2228 if (!opener_site_instance->GetProcess() || 2229 !process_map->Contains( 2230 extension->id(), opener_site_instance->GetProcess()->GetID())) { 2231 return false; 2232 } 2233 2234 // Only allow a single background contents per app. 2235 bool allow_js_access = extensions::BackgroundInfo::AllowJSAccess(extension); 2236 BackgroundContents* existing = 2237 service->GetAppBackgroundContents(ASCIIToUTF16(extension->id())); 2238 if (existing) { 2239 // For non-scriptable background contents, ignore the request altogether, 2240 // (returning true, so that a regular WebContents isn't created either). 2241 if (!allow_js_access) 2242 return true; 2243 // For scriptable background pages, if one already exists, close it (even 2244 // if it was specified in the manifest). 2245 DLOG(INFO) << "Closing existing BackgroundContents for " << opener_url; 2246 delete existing; 2247 } 2248 2249 // If script access is not allowed, create the the background contents in a 2250 // new SiteInstance, so that a separate process is used. 2251 scoped_refptr<content::SiteInstance> site_instance = 2252 allow_js_access ? 2253 opener_site_instance : 2254 content::SiteInstance::Create(opener_web_contents->GetBrowserContext()); 2255 2256 // Passed all the checks, so this should be created as a BackgroundContents. 2257 BackgroundContents* contents = 2258 service->CreateBackgroundContents(site_instance.get(), 2259 route_id, 2260 profile_, 2261 frame_name, 2262 ASCIIToUTF16(extension->id())); 2263 2264 // When a separate process is used, the original renderer cannot access the 2265 // new window later, thus we need to navigate the window now. 2266 if (contents && !allow_js_access) { 2267 contents->web_contents()->GetController().LoadURL( 2268 target_url, 2269 content::Referrer(), 2270 content::PAGE_TRANSITION_LINK, 2271 std::string()); // No extra headers. 2272 } 2273 2274 return contents != NULL; 2275} 2276