browser_main_parts_impl.cc 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304
  1. // Copyright 2019 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. #include "weblayer/browser/browser_main_parts_impl.h"
  5. #include "base/base_switches.h"
  6. #include "base/bind.h"
  7. #include "base/callback_helpers.h"
  8. #include "base/json/json_reader.h"
  9. #include "base/run_loop.h"
  10. #include "base/task/current_thread.h"
  11. #include "base/task/task_traits.h"
  12. #include "base/threading/thread.h"
  13. #include "base/threading/thread_restrictions.h"
  14. #include "build/build_config.h"
  15. #include "build/chromeos_buildflags.h"
  16. #include "cc/base/switches.h"
  17. #include "components/captive_portal/core/buildflags.h"
  18. #include "components/performance_manager/embedder/graph_features.h"
  19. #include "components/performance_manager/embedder/performance_manager_lifetime.h"
  20. #include "components/prefs/pref_service.h"
  21. #include "components/startup_metric_utils/browser/startup_metric_utils.h"
  22. #include "components/subresource_filter/content/browser/ruleset_service.h"
  23. #include "components/translate/core/browser/translate_download_manager.h"
  24. #include "content/public/browser/browser_task_traits.h"
  25. #include "content/public/browser/browser_thread.h"
  26. #include "content/public/browser/devtools_agent_host.h"
  27. #include "content/public/browser/render_process_host.h"
  28. #include "content/public/common/main_function_params.h"
  29. #include "content/public/common/page_visibility_state.h"
  30. #include "content/public/common/result_codes.h"
  31. #include "content/public/common/url_constants.h"
  32. #include "ui/base/resource/resource_bundle.h"
  33. #include "weblayer/browser/accept_languages_service_factory.h"
  34. #include "weblayer/browser/browser_process.h"
  35. #include "weblayer/browser/cookie_settings_factory.h"
  36. #include "weblayer/browser/feature_list_creator.h"
  37. #include "weblayer/browser/heavy_ad_service_factory.h"
  38. #include "weblayer/browser/host_content_settings_map_factory.h"
  39. #include "weblayer/browser/i18n_util.h"
  40. #include "weblayer/browser/no_state_prefetch/no_state_prefetch_link_manager_factory.h"
  41. #include "weblayer/browser/no_state_prefetch/no_state_prefetch_manager_factory.h"
  42. #include "weblayer/browser/permissions/weblayer_permissions_client.h"
  43. #include "weblayer/browser/stateful_ssl_host_state_delegate_factory.h"
  44. #include "weblayer/browser/subresource_filter_profile_context_factory.h"
  45. #include "weblayer/browser/translate_ranker_factory.h"
  46. #include "weblayer/browser/web_data_service_factory.h"
  47. #include "weblayer/browser/webui/web_ui_controller_factory.h"
  48. #include "weblayer/grit/weblayer_resources.h"
  49. #include "weblayer/public/main.h"
  50. #if BUILDFLAG(IS_ANDROID)
  51. #include "base/command_line.h"
  52. #include "components/crash/content/browser/child_exit_observer_android.h"
  53. #include "components/crash/content/browser/child_process_crash_observer_android.h"
  54. #include "components/crash/core/common/crash_key.h"
  55. #include "components/javascript_dialogs/android/app_modal_dialog_view_android.h" // nogncheck
  56. #include "components/javascript_dialogs/app_modal_dialog_manager.h" // nogncheck
  57. #include "components/metrics/metrics_service.h"
  58. #include "components/variations/synthetic_trials_active_group_id_provider.h"
  59. #include "components/variations/variations_ids_provider.h"
  60. #include "content/public/browser/web_contents.h"
  61. #include "content/public/common/content_switches.h"
  62. #include "net/android/network_change_notifier_factory_android.h"
  63. #include "net/base/network_change_notifier.h"
  64. #include "weblayer/browser/android/metrics/uma_utils.h"
  65. #include "weblayer/browser/android/metrics/weblayer_metrics_service_client.h"
  66. #include "weblayer/browser/java/jni/MojoInterfaceRegistrar_jni.h"
  67. #include "weblayer/browser/media/local_presentation_manager_factory.h"
  68. #include "weblayer/browser/media/media_router_factory.h"
  69. #include "weblayer/browser/safe_browsing/safe_browsing_metrics_collector_factory.h"
  70. #include "weblayer/browser/safe_browsing/safe_browsing_navigation_observer_manager_factory.h"
  71. #include "weblayer/browser/site_engagement/site_engagement_service_factory.h"
  72. #include "weblayer/browser/webapps/weblayer_webapps_client.h"
  73. #include "weblayer/browser/weblayer_factory_impl_android.h"
  74. #include "weblayer/common/features.h"
  75. #endif
  76. // TODO(crbug.com/1052397): Revisit once build flag switch of lacros-chrome is
  77. // complete.
  78. #if defined(USE_AURA) && (BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS_LACROS))
  79. #include "ui/base/ime/init/input_method_initializer.h"
  80. #endif
  81. #if BUILDFLAG(ENABLE_CAPTIVE_PORTAL_DETECTION)
  82. #include "weblayer/browser/captive_portal_service_factory.h"
  83. #endif
  84. namespace weblayer {
  85. namespace {
  86. // Indexes and publishes the subresource filter ruleset data from resources in
  87. // the resource bundle.
  88. void PublishSubresourceFilterRulesetFromResourceBundle() {
  89. // First obtain the version of the ruleset data from the manifest.
  90. std::string ruleset_manifest_string =
  91. ui::ResourceBundle::GetSharedInstance().LoadDataResourceString(
  92. IDR_SUBRESOURCE_FILTER_UNINDEXED_RULESET_MANIFEST_JSON);
  93. auto ruleset_manifest = base::JSONReader::Read(ruleset_manifest_string);
  94. DCHECK(ruleset_manifest);
  95. std::string* content_version = ruleset_manifest->FindStringKey("version");
  96. // Instruct the RulesetService to obtain the unindexed ruleset data from the
  97. // ResourceBundle and give it the version of that data.
  98. auto* ruleset_service =
  99. BrowserProcess::GetInstance()->subresource_filter_ruleset_service();
  100. subresource_filter::UnindexedRulesetInfo ruleset_info;
  101. ruleset_info.resource_id = IDR_SUBRESOURCE_FILTER_UNINDEXED_RULESET;
  102. ruleset_info.content_version = *content_version;
  103. ruleset_service->IndexAndStoreAndPublishRulesetIfNeeded(ruleset_info);
  104. }
  105. // Instantiates all weblayer KeyedService factories, which is
  106. // especially important for services that should be created at profile
  107. // creation time as compared to lazily on first access.
  108. void EnsureBrowserContextKeyedServiceFactoriesBuilt() {
  109. #if BUILDFLAG(ENABLE_CAPTIVE_PORTAL_DETECTION)
  110. CaptivePortalServiceFactory::GetInstance();
  111. #endif
  112. HeavyAdServiceFactory::GetInstance();
  113. HostContentSettingsMapFactory::GetInstance();
  114. StatefulSSLHostStateDelegateFactory::GetInstance();
  115. CookieSettingsFactory::GetInstance();
  116. AcceptLanguagesServiceFactory::GetInstance();
  117. TranslateRankerFactory::GetInstance();
  118. NoStatePrefetchLinkManagerFactory::GetInstance();
  119. NoStatePrefetchManagerFactory::GetInstance();
  120. SubresourceFilterProfileContextFactory::GetInstance();
  121. #if BUILDFLAG(IS_ANDROID)
  122. SiteEngagementServiceFactory::GetInstance();
  123. SafeBrowsingMetricsCollectorFactory::GetInstance();
  124. SafeBrowsingNavigationObserverManagerFactory::GetInstance();
  125. if (MediaRouterFactory::IsFeatureEnabled()) {
  126. LocalPresentationManagerFactory::GetInstance();
  127. MediaRouterFactory::GetInstance();
  128. }
  129. #endif
  130. WebDataServiceFactory::GetInstance();
  131. }
  132. void StopMessageLoop(base::OnceClosure quit_closure) {
  133. for (auto it = content::RenderProcessHost::AllHostsIterator(); !it.IsAtEnd();
  134. it.Advance()) {
  135. it.GetCurrentValue()->DisableRefCounts();
  136. }
  137. std::move(quit_closure).Run();
  138. }
  139. } // namespace
  140. BrowserMainPartsImpl::BrowserMainPartsImpl(
  141. MainParams* params,
  142. std::unique_ptr<PrefService> local_state)
  143. : params_(params), local_state_(std::move(local_state)) {}
  144. BrowserMainPartsImpl::~BrowserMainPartsImpl() = default;
  145. int BrowserMainPartsImpl::PreCreateThreads() {
  146. // Make sure permissions client has been set.
  147. WebLayerPermissionsClient::GetInstance();
  148. #if BUILDFLAG(IS_ANDROID)
  149. // The ChildExitObserver needs to be created before any child process is
  150. // created because it needs to be notified during process creation.
  151. child_exit_observer_ = std::make_unique<crash_reporter::ChildExitObserver>();
  152. child_exit_observer_->RegisterClient(
  153. std::make_unique<crash_reporter::ChildProcessCrashObserver>());
  154. crash_reporter::InitializeCrashKeys();
  155. // WebLayer initializes the MetricsService once consent is determined.
  156. // Determining consent is async and potentially slow. VariationsIdsProvider
  157. // is responsible for updating the X-Client-Data header.
  158. // SyntheticTrialsActiveGroupIdProvider is responsible for updating the
  159. // variations crash keys. To ensure the header and crash keys are always
  160. // provided, they are registered now.
  161. //
  162. // Chrome registers these providers from PreCreateThreads() as well.
  163. auto* synthetic_trial_registry = WebLayerMetricsServiceClient::GetInstance()
  164. ->GetMetricsService()
  165. ->GetSyntheticTrialRegistry();
  166. synthetic_trial_registry->AddSyntheticTrialObserver(
  167. variations::VariationsIdsProvider::GetInstance());
  168. synthetic_trial_registry->AddSyntheticTrialObserver(
  169. variations::SyntheticTrialsActiveGroupIdProvider::GetInstance());
  170. #endif
  171. return content::RESULT_CODE_NORMAL_EXIT;
  172. }
  173. int BrowserMainPartsImpl::PreEarlyInitialization() {
  174. browser_process_ = std::make_unique<BrowserProcess>(std::move(local_state_));
  175. // TODO(crbug.com/1052397): Revisit once build flag switch of lacros-chrome is
  176. // complete.
  177. #if defined(USE_AURA) && (BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS_LACROS))
  178. ui::InitializeInputMethodForTesting();
  179. #endif
  180. #if BUILDFLAG(IS_ANDROID)
  181. net::NetworkChangeNotifier::SetFactory(
  182. new net::NetworkChangeNotifierFactoryAndroid());
  183. WebLayerWebappsClient::Create();
  184. #endif
  185. return content::RESULT_CODE_NORMAL_EXIT;
  186. }
  187. void BrowserMainPartsImpl::PostCreateThreads() {
  188. performance_manager_lifetime_ =
  189. std::make_unique<performance_manager::PerformanceManagerLifetime>(
  190. performance_manager::GraphFeatures::WithMinimal()
  191. // Reports performance-related UMA/UKM.
  192. .EnableMetricsCollector(),
  193. base::DoNothing());
  194. translate::TranslateDownloadManager* download_manager =
  195. translate::TranslateDownloadManager::GetInstance();
  196. download_manager->set_url_loader_factory(
  197. BrowserProcess::GetInstance()->GetSharedURLLoaderFactory());
  198. download_manager->set_application_locale(i18n::GetApplicationLocale());
  199. }
  200. int BrowserMainPartsImpl::PreMainMessageLoopRun() {
  201. FeatureListCreator::GetInstance()->PerformPreMainMessageLoopStartup();
  202. // It's necessary to have a complete dependency graph of
  203. // BrowserContextKeyedServices before calling out to the delegate (which
  204. // will potentially create a profile), so that a profile creation message is
  205. // properly dispatched to the factories that want to create their services
  206. // at profile creation time.
  207. EnsureBrowserContextKeyedServiceFactoriesBuilt();
  208. params_->delegate->PreMainMessageLoopRun();
  209. content::WebUIControllerFactory::RegisterFactory(
  210. WebUIControllerFactory::GetInstance());
  211. BrowserProcess::GetInstance()->PreMainMessageLoopRun();
  212. // Publish the ruleset data. On the vast majority of runs this will
  213. // effectively be a no-op as the version of the data changes at most once per
  214. // release. Nonetheless, post it as a best-effort task to take it off the
  215. // critical path of startup. Note that best-effort tasks are guaranteed to
  216. // execute within a reasonable delay (assuming of course that the app isn't
  217. // shut down first).
  218. content::GetUIThreadTaskRunner({base::TaskPriority::BEST_EFFORT})
  219. ->PostTask(
  220. FROM_HERE,
  221. base::BindOnce(&PublishSubresourceFilterRulesetFromResourceBundle));
  222. #if BUILDFLAG(IS_ANDROID)
  223. // On Android, retrieve the application start time from Java and record it. On
  224. // other platforms, the application start time was already recorded in the
  225. // constructor of ContentMainDelegateImpl.
  226. startup_metric_utils::RecordApplicationStartTime(GetApplicationStartTime());
  227. #endif // BUILDFLAG(IS_ANDROID)
  228. // Record the time at which the main message loop starts. Must be recorded
  229. // after application start time (see startup_metric_utils.h).
  230. startup_metric_utils::RecordBrowserMainMessageLoopStart(
  231. base::TimeTicks::Now(), /* is_first_run */ false);
  232. #if BUILDFLAG(IS_ANDROID)
  233. memory_metrics_logger_ = std::make_unique<metrics::MemoryMetricsLogger>();
  234. // Set the global singleton app modal dialog factory.
  235. javascript_dialogs::AppModalDialogManager::GetInstance()
  236. ->SetNativeDialogFactory(base::BindRepeating(
  237. [](javascript_dialogs::AppModalDialogController* controller)
  238. -> javascript_dialogs::AppModalDialogView* {
  239. return new javascript_dialogs::AppModalDialogViewAndroid(
  240. base::android::AttachCurrentThread(), controller,
  241. controller->web_contents()->GetTopLevelNativeWindow());
  242. }));
  243. Java_MojoInterfaceRegistrar_registerMojoInterfaces(
  244. base::android::AttachCurrentThread());
  245. #endif
  246. return content::RESULT_CODE_NORMAL_EXIT;
  247. }
  248. void BrowserMainPartsImpl::WillRunMainMessageLoop(
  249. std::unique_ptr<base::RunLoop>& run_loop) {
  250. // Wrap the method that stops the message loop so we can do other shutdown
  251. // cleanup inside content.
  252. params_->delegate->SetMainMessageLoopQuitClosure(
  253. base::BindOnce(StopMessageLoop, run_loop->QuitClosure()));
  254. }
  255. void BrowserMainPartsImpl::OnFirstIdle() {
  256. startup_metric_utils::RecordBrowserMainLoopFirstIdle(base::TimeTicks::Now());
  257. }
  258. void BrowserMainPartsImpl::PostMainMessageLoopRun() {
  259. params_->delegate->PostMainMessageLoopRun();
  260. browser_process_->StartTearDown();
  261. performance_manager_lifetime_.reset();
  262. }
  263. } // namespace weblayer