font_prewarmer_tab_helper.cc 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245
  1. // Copyright 2021 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 "chrome/browser/font_prewarmer_tab_helper.h"
  5. #include <set>
  6. #include <string>
  7. #include "base/memory/raw_ptr.h"
  8. #include "base/memory/weak_ptr.h"
  9. #include "base/values.h"
  10. #include "build/build_config.h"
  11. #include "chrome/browser/history/history_service_factory.h"
  12. #include "chrome/browser/history_clusters/history_clusters_tab_helper.h"
  13. #include "chrome/browser/preloading/prefetch/no_state_prefetch/no_state_prefetch_manager_factory.h"
  14. #include "chrome/browser/profiles/profile.h"
  15. #include "chrome/browser/search_engines/template_url_service_factory.h"
  16. #include "chrome/common/font_prewarmer.mojom.h"
  17. #include "components/history/content/browser/history_context_helper.h"
  18. #include "components/history/core/browser/history_constants.h"
  19. #include "components/history/core/browser/history_service.h"
  20. #include "components/no_state_prefetch/browser/no_state_prefetch_manager.h"
  21. #include "components/pref_registry/pref_registry_syncable.h"
  22. #include "components/prefs/pref_service.h"
  23. #include "components/search_engines/template_url_service.h"
  24. #include "content/public/browser/navigation_entry.h"
  25. #include "content/public/browser/navigation_handle.h"
  26. #include "content/public/browser/render_frame_host.h"
  27. #include "content/public/browser/render_process_host.h"
  28. #include "content/public/browser/render_process_host_observer.h"
  29. #include "content/public/browser/web_contents.h"
  30. #include "content/public/common/child_process_host.h"
  31. #include "mojo/public/cpp/bindings/remote.h"
  32. #include "third_party/abseil-cpp/absl/types/optional.h"
  33. #include "third_party/blink/public/common/associated_interfaces/associated_interface_provider.h"
  34. namespace {
  35. const char kSearchResultsPagePrimaryFontsPref[] =
  36. "cached_fonts.search_results_page.primary";
  37. const char kSearchResultsPageFallbackFontsPref[] =
  38. "cached_fonts.search_results_page.fallback";
  39. // Key used to associate FontPrewarmerProfileState with BrowserContext.
  40. const void* const kUserDataKey = &kUserDataKey;
  41. // Returns the font names previously stored to the specified key.
  42. std::vector<std::string> GetFontNamesFromPrefsForKey(Profile* profile,
  43. const char* pref_name) {
  44. const base::Value::List& font_name_list =
  45. profile->GetPrefs()->GetValueList(pref_name);
  46. if (font_name_list.empty())
  47. return {};
  48. std::vector<std::string> font_names;
  49. for (const auto& font_name_value : font_name_list) {
  50. if (const std::string* font_name = font_name_value.GetIfString())
  51. font_names.push_back(*font_name);
  52. }
  53. return font_names;
  54. }
  55. // Saves font names to prefs.
  56. void SaveFontNamesToPref(Profile* profile,
  57. const char* pref_name,
  58. const std::vector<std::string>& font_family_names) {
  59. base::Value::List font_family_names_values;
  60. for (auto& name : font_family_names)
  61. font_family_names_values.Append(name);
  62. profile->GetPrefs()->SetList(pref_name, std::move(font_family_names_values));
  63. }
  64. // FontPrewarmerCoordinator is responsible for coordinating with the renderer
  65. // to request the fonts used by a page as well as prewarm the last set of fonts
  66. // used. There is one FontPrewarmerCoordinator per Profile.
  67. class FontPrewarmerCoordinator : public base::SupportsUserData::Data,
  68. public content::RenderProcessHostObserver {
  69. public:
  70. using RemoteFontPrewarmer = mojo::Remote<chrome::mojom::FontPrewarmer>;
  71. explicit FontPrewarmerCoordinator(Profile* profile) : profile_(profile) {}
  72. FontPrewarmerCoordinator(const FontPrewarmerCoordinator&) = delete;
  73. FontPrewarmerCoordinator& operator=(const FontPrewarmerCoordinator&) = delete;
  74. ~FontPrewarmerCoordinator() override {
  75. for (content::RenderProcessHost* rph : prewarmed_hosts_)
  76. rph->RemoveObserver(this);
  77. }
  78. static FontPrewarmerCoordinator& ForProfile(Profile* profile) {
  79. FontPrewarmerCoordinator* instance = static_cast<FontPrewarmerCoordinator*>(
  80. profile->GetUserData(kUserDataKey));
  81. if (!instance) {
  82. profile->SetUserData(kUserDataKey,
  83. std::make_unique<FontPrewarmerCoordinator>(profile));
  84. instance = static_cast<FontPrewarmerCoordinator*>(
  85. profile->GetUserData(kUserDataKey));
  86. }
  87. return *instance;
  88. }
  89. // Requests the renderer to prewarm the last set of fonts used for displaying
  90. // a search page. Prewarming is done at most once per RenderProcessHost.
  91. void SendFontsToPrewarm(content::RenderProcessHost* rph) {
  92. // Only need to prewarm a particular host once.
  93. if (prewarmed_hosts_.count(rph))
  94. return;
  95. // The following code may early out. Insert the entry to ensure an early out
  96. // doesn't attempt to send the fonts again.
  97. prewarmed_hosts_.insert(rph);
  98. rph->AddObserver(this);
  99. std::vector<std::string> primary_font_names = GetFontNamesFromPrefsForKey(
  100. profile_, kSearchResultsPagePrimaryFontsPref);
  101. std::vector<std::string> fallback_font_names = GetFontNamesFromPrefsForKey(
  102. profile_, kSearchResultsPageFallbackFontsPref);
  103. if (primary_font_names.empty() && fallback_font_names.empty())
  104. return;
  105. RemoteFontPrewarmer remote_font_prewarmer;
  106. rph->BindReceiver(remote_font_prewarmer.BindNewPipeAndPassReceiver());
  107. remote_font_prewarmer->PrewarmFonts(std::move(primary_font_names),
  108. std::move(fallback_font_names));
  109. }
  110. // Requests the set of fonts needed to display a search page from `rfh`.
  111. void RequestFonts(content::RenderFrameHost* rfh) {
  112. mojo::AssociatedRemote<chrome::mojom::RenderFrameFontFamilyAccessor>
  113. font_family_accessor;
  114. rfh->GetRemoteAssociatedInterfaces()->GetInterface(&font_family_accessor);
  115. auto* font_family_accessor_raw = font_family_accessor.get();
  116. // Pass ownership of the remote to the callback as otherwise the callback
  117. // will never be run (because the mojo connection was destroyed).
  118. font_family_accessor_raw->GetFontFamilyNames(base::BindOnce(
  119. &FontPrewarmerCoordinator::OnGotFontsForFrame,
  120. weak_factory_.GetWeakPtr(), std::move(font_family_accessor)));
  121. }
  122. private:
  123. void OnGotFontsForFrame(
  124. mojo::AssociatedRemote<chrome::mojom::RenderFrameFontFamilyAccessor>
  125. font_family_accessor,
  126. const std::vector<std::string>& primary_family_names,
  127. const std::vector<std::string>& fallback_family_names) {
  128. // TODO(sky): add some metrics here so that we know how often the
  129. // fonts change.
  130. SaveFontNamesToPref(profile_, kSearchResultsPagePrimaryFontsPref,
  131. primary_family_names);
  132. SaveFontNamesToPref(profile_, kSearchResultsPageFallbackFontsPref,
  133. fallback_family_names);
  134. }
  135. // content::RenderProcessHostObserver:
  136. void RenderProcessHostDestroyed(content::RenderProcessHost* host) override {
  137. host->RemoveObserver(this);
  138. prewarmed_hosts_.erase(host);
  139. }
  140. raw_ptr<Profile> profile_;
  141. // Set of hosts that were requested to be prewarmed.
  142. std::set<content::RenderProcessHost*> prewarmed_hosts_;
  143. base::WeakPtrFactory<FontPrewarmerCoordinator> weak_factory_{this};
  144. };
  145. } // namespace
  146. // static
  147. void FontPrewarmerTabHelper::RegisterProfilePrefs(
  148. user_prefs::PrefRegistrySyncable* registry) {
  149. registry->RegisterListPref(kSearchResultsPagePrimaryFontsPref);
  150. registry->RegisterListPref(kSearchResultsPageFallbackFontsPref);
  151. }
  152. FontPrewarmerTabHelper::~FontPrewarmerTabHelper() = default;
  153. FontPrewarmerTabHelper::FontPrewarmerTabHelper(
  154. content::WebContents* web_contents)
  155. : content::WebContentsObserver(web_contents),
  156. content::WebContentsUserData<FontPrewarmerTabHelper>(*web_contents) {}
  157. // static
  158. std::string FontPrewarmerTabHelper::GetSearchResultsPagePrimaryFontsPref() {
  159. return kSearchResultsPagePrimaryFontsPref;
  160. }
  161. // static
  162. std::vector<std::string> FontPrewarmerTabHelper::GetPrimaryFontNames(
  163. Profile* profile) {
  164. return GetFontNamesFromPrefsForKey(profile,
  165. kSearchResultsPagePrimaryFontsPref);
  166. }
  167. Profile* FontPrewarmerTabHelper::GetProfile() {
  168. return Profile::FromBrowserContext(web_contents()->GetBrowserContext());
  169. }
  170. bool FontPrewarmerTabHelper::IsSearchResultsPageNavigation(
  171. content::NavigationHandle* navigation_handle) {
  172. if (!navigation_handle->IsInPrimaryMainFrame())
  173. return false;
  174. TemplateURLService* template_url_service =
  175. TemplateURLServiceFactory::GetForProfile(GetProfile());
  176. return template_url_service &&
  177. template_url_service->IsSearchResultsPageFromDefaultSearchProvider(
  178. navigation_handle->GetURL());
  179. }
  180. void FontPrewarmerTabHelper::DidStartNavigation(
  181. content::NavigationHandle* navigation_handle) {
  182. if (!IsSearchResultsPageNavigation(navigation_handle))
  183. return;
  184. const int expected_render_process_host_id =
  185. navigation_handle->GetExpectedRenderProcessHostId();
  186. if (expected_render_process_host_id ==
  187. content::ChildProcessHost::kInvalidUniqueID) {
  188. expected_render_process_host_id_.reset();
  189. } else {
  190. expected_render_process_host_id_ = expected_render_process_host_id;
  191. content::RenderProcessHost* rph =
  192. content::RenderProcessHost::FromID(expected_render_process_host_id);
  193. DCHECK(rph);
  194. FontPrewarmerCoordinator::ForProfile(GetProfile()).SendFontsToPrewarm(rph);
  195. }
  196. }
  197. void FontPrewarmerTabHelper::ReadyToCommitNavigation(
  198. content::NavigationHandle* navigation_handle) {
  199. if (!IsSearchResultsPageNavigation(navigation_handle))
  200. return;
  201. content::RenderFrameHost* rfh = navigation_handle->GetRenderFrameHost();
  202. DCHECK(rfh);
  203. FontPrewarmerCoordinator& coordinator =
  204. FontPrewarmerCoordinator::ForProfile(GetProfile());
  205. if (expected_render_process_host_id_ != rfh->GetProcess()->GetID())
  206. coordinator.SendFontsToPrewarm(rfh->GetProcess());
  207. coordinator.RequestFonts(rfh);
  208. }
  209. WEB_CONTENTS_USER_DATA_KEY_IMPL(FontPrewarmerTabHelper);