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