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