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