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