1 // Copyright 2013 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.
5 #include "chrome/browser/android/most_visited_sites.h"
7 #include "base/android/jni_android.h"
8 #include "base/android/jni_array.h"
9 #include "base/android/jni_string.h"
10 #include "base/android/scoped_java_ref.h"
11 #include "base/callback.h"
12 #include "base/command_line.h"
13 #include "base/metrics/histogram.h"
14 #include "base/metrics/sparse_histogram.h"
15 #include "base/strings/string_number_conversions.h"
16 #include "base/strings/stringprintf.h"
17 #include "base/strings/utf_string_conversions.h"
18 #include "base/time/time.h"
19 #include "chrome/browser/android/popular_sites.h"
20 #include "chrome/browser/history/top_sites_factory.h"
21 #include "chrome/browser/profiles/profile.h"
22 #include "chrome/browser/profiles/profile_android.h"
23 #include "chrome/browser/search/suggestions/suggestions_service_factory.h"
24 #include "chrome/browser/search/suggestions/suggestions_source.h"
25 #include "chrome/browser/sync/profile_sync_service.h"
26 #include "chrome/browser/sync/profile_sync_service_factory.h"
27 #include "chrome/browser/thumbnails/thumbnail_list_source.h"
28 #include "chrome/common/chrome_switches.h"
29 #include "components/history/core/browser/top_sites.h"
30 #include "components/suggestions/suggestions_service.h"
31 #include "components/suggestions/suggestions_utils.h"
32 #include "content/public/browser/browser_thread.h"
33 #include "content/public/browser/url_data_source.h"
34 #include "jni/MostVisitedSites_jni.h"
35 #include "third_party/skia/include/core/SkBitmap.h"
36 #include "ui/gfx/android/java_bitmap.h"
37 #include "ui/gfx/codec/jpeg_codec.h"
40 using base::android::AttachCurrentThread
;
41 using base::android::ConvertJavaStringToUTF8
;
42 using base::android::ScopedJavaGlobalRef
;
43 using base::android::ScopedJavaLocalRef
;
44 using base::android::ToJavaArrayOfStrings
;
45 using content::BrowserThread
;
46 using history::TopSites
;
47 using suggestions::ChromeSuggestion
;
48 using suggestions::SuggestionsProfile
;
49 using suggestions::SuggestionsService
;
50 using suggestions::SuggestionsServiceFactory
;
51 using suggestions::SyncState
;
55 // Total number of tiles displayed.
56 const char kNumTilesHistogramName
[] = "NewTabPage.NumberOfTiles";
57 // Tracking thumbnails.
58 const char kNumLocalThumbnailTilesHistogramName
[] =
59 "NewTabPage.NumberOfThumbnailTiles";
60 const char kNumEmptyTilesHistogramName
[] = "NewTabPage.NumberOfGrayTiles";
61 const char kNumServerTilesHistogramName
[] = "NewTabPage.NumberOfExternalTiles";
63 // Format for tile clicks histogram.
64 const char kOpenedItemHistogramFormat
[] = "NewTabPage.MostVisited.%s";
65 // Format for tile impressions histogram.
66 const char kImpressionHistogramFormat
[] = "NewTabPage.SuggestionsImpression.%s";
67 // Identifiers for the various tile sources.
68 const char kHistogramClientName
[] = "client";
69 const char kHistogramServerName
[] = "server";
70 const char kHistogramServerFormat
[] = "server%d";
71 const char kHistogramPopularName
[] = "popular";
73 const char kPopularSitesFieldTrialName
[] = "NTPPopularSites";
75 scoped_ptr
<SkBitmap
> MaybeFetchLocalThumbnail(
77 const scoped_refptr
<TopSites
>& top_sites
) {
78 DCHECK_CURRENTLY_ON(BrowserThread::DB
);
79 scoped_refptr
<base::RefCountedMemory
> image
;
80 scoped_ptr
<SkBitmap
> bitmap
;
81 if (top_sites
&& top_sites
->GetPageThumbnail(url
, false, &image
))
82 bitmap
.reset(gfx::JPEGCodec::Decode(image
->front(), image
->size()));
86 // Log an event for a given |histogram| at a given element |position|. This
87 // routine exists because regular histogram macros are cached thus can't be used
88 // if the name of the histogram will change at a given call site.
89 void LogHistogramEvent(const std::string
& histogram
,
92 base::HistogramBase
* counter
= base::LinearHistogram::FactoryGet(
97 base::Histogram::kUmaTargetedHistogramFlag
);
99 counter
->Add(position
);
102 // Return the current SyncState for use with the SuggestionsService.
103 SyncState
GetSyncState(Profile
* profile
) {
104 ProfileSyncService
* sync
=
105 ProfileSyncServiceFactory::GetInstance()->GetForProfile(profile
);
107 return SyncState::SYNC_OR_HISTORY_SYNC_DISABLED
;
108 return suggestions::GetSyncState(
109 sync
->CanSyncStart(),
110 sync
->IsSyncActive() && sync
->ConfigurationDone(),
111 sync
->GetActiveDataTypes().Has(syncer::HISTORY_DELETE_DIRECTIVES
));
114 bool ShouldShowPopularSites() {
115 // Note: It's important to query the field trial state first, to ensure that
116 // UMA reports the correct group.
117 const std::string group_name
=
118 base::FieldTrialList::FindFullName(kPopularSitesFieldTrialName
);
119 base::CommandLine
* cmd_line
= base::CommandLine::ForCurrentProcess();
120 if (cmd_line
->HasSwitch(switches::kDisableNTPPopularSites
))
122 if (cmd_line
->HasSwitch(switches::kEnableNTPPopularSites
))
124 return group_name
== "Enabled";
127 std::string
GetPopularSitesFilename() {
128 return variations::GetVariationParamValue(kPopularSitesFieldTrialName
,
134 MostVisitedSites::MostVisitedSites(Profile
* profile
)
135 : profile_(profile
), num_sites_(0), received_most_visited_sites_(false),
136 received_popular_sites_(false), recorded_uma_(false),
137 num_local_thumbs_(0), num_server_thumbs_(0), num_empty_thumbs_(0),
138 scoped_observer_(this), weak_ptr_factory_(this) {
139 // Register the debugging page for the Suggestions Service and the thumbnails
141 content::URLDataSource::Add(profile_
,
142 new suggestions::SuggestionsSource(profile_
));
143 content::URLDataSource::Add(profile_
, new ThumbnailListSource(profile_
));
145 // Register this class as an observer to the sync service. It is important to
146 // be notified of changes in the sync state such as initialization, sync
147 // being enabled or disabled, etc.
148 ProfileSyncService
* profile_sync_service
=
149 ProfileSyncServiceFactory::GetForProfile(profile_
);
150 if (profile_sync_service
)
151 profile_sync_service
->AddObserver(this);
153 if (ShouldShowPopularSites()) {
154 popular_sites_
.reset(new PopularSites(
156 GetPopularSitesFilename(),
157 profile_
->GetRequestContext(),
158 base::Bind(&MostVisitedSites::OnPopularSitesAvailable
,
159 base::Unretained(this))));
161 received_popular_sites_
= true;
165 MostVisitedSites::~MostVisitedSites() {
166 ProfileSyncService
* profile_sync_service
=
167 ProfileSyncServiceFactory::GetForProfile(profile_
);
168 if (profile_sync_service
&& profile_sync_service
->HasObserver(this))
169 profile_sync_service
->RemoveObserver(this);
172 void MostVisitedSites::Destroy(JNIEnv
* env
, jobject obj
) {
176 void MostVisitedSites::OnLoadingComplete(JNIEnv
* env
, jobject obj
) {
177 RecordThumbnailUMAMetrics();
180 void MostVisitedSites::SetMostVisitedURLsObserver(JNIEnv
* env
,
184 observer_
.Reset(env
, j_observer
);
185 num_sites_
= num_sites
;
187 QueryMostVisitedURLs();
189 scoped_refptr
<history::TopSites
> top_sites
=
190 TopSitesFactory::GetForProfile(profile_
);
192 // TopSites updates itself after a delay. To ensure up-to-date results,
193 // force an update now.
194 top_sites
->SyncWithHistory();
196 // Register as TopSitesObserver so that we can update ourselves when the
198 scoped_observer_
.Add(top_sites
.get());
202 void MostVisitedSites::GetURLThumbnail(JNIEnv
* env
,
205 jobject j_callback_obj
) {
206 DCHECK_CURRENTLY_ON(BrowserThread::UI
);
207 scoped_ptr
<ScopedJavaGlobalRef
<jobject
>> j_callback(
208 new ScopedJavaGlobalRef
<jobject
>());
209 j_callback
->Reset(env
, j_callback_obj
);
211 GURL
url(ConvertJavaStringToUTF8(env
, j_url
));
212 scoped_refptr
<TopSites
> top_sites(TopSitesFactory::GetForProfile(profile_
));
214 BrowserThread::PostTaskAndReplyWithResult(
215 BrowserThread::DB
, FROM_HERE
,
216 base::Bind(&MaybeFetchLocalThumbnail
, url
, top_sites
),
217 base::Bind(&MostVisitedSites::OnLocalThumbnailFetched
,
218 weak_ptr_factory_
.GetWeakPtr(), url
,
219 base::Passed(&j_callback
)));
222 void MostVisitedSites::OnLocalThumbnailFetched(
224 scoped_ptr
<ScopedJavaGlobalRef
<jobject
>> j_callback
,
225 scoped_ptr
<SkBitmap
> bitmap
) {
226 DCHECK_CURRENTLY_ON(BrowserThread::UI
);
228 // A thumbnail is not locally available for |url|. Make sure it is put in
229 // the list to be fetched at the next visit to this site.
230 scoped_refptr
<TopSites
> top_sites(TopSitesFactory::GetForProfile(profile_
));
232 top_sites
->AddForcedURL(url
, base::Time::Now());
233 // Also fetch a remote thumbnail if possible. PopularSites or the
234 // SuggestionsService can supply a thumbnail download URL.
235 SuggestionsService
* suggestions_service
=
236 SuggestionsServiceFactory::GetForProfile(profile_
);
237 if (suggestions_service
) {
238 if (popular_sites_
) {
239 const std::vector
<PopularSites::Site
>& sites
= popular_sites_
->sites();
240 auto it
= std::find_if(sites
.begin(), sites
.end(),
241 [&url
](const PopularSites::Site
& site
) {
242 return site
.url
== url
;
244 if (it
!= sites
.end() && it
->thumbnail_url
.is_valid()) {
245 return suggestions_service
->GetPageThumbnailWithURL(
246 url
, it
->thumbnail_url
,
247 base::Bind(&MostVisitedSites::OnObtainedThumbnail
,
248 weak_ptr_factory_
.GetWeakPtr(), false,
249 base::Passed(&j_callback
)));
252 if (mv_source_
== SUGGESTIONS_SERVICE
) {
253 return suggestions_service
->GetPageThumbnail(
254 url
, base::Bind(&MostVisitedSites::OnObtainedThumbnail
,
255 weak_ptr_factory_
.GetWeakPtr(), false,
256 base::Passed(&j_callback
)));
260 OnObtainedThumbnail(true, j_callback
.Pass(), url
, bitmap
.get());
263 void MostVisitedSites::OnObtainedThumbnail(
264 bool is_local_thumbnail
,
265 scoped_ptr
<ScopedJavaGlobalRef
<jobject
>> j_callback
,
267 const SkBitmap
* bitmap
) {
268 DCHECK_CURRENTLY_ON(BrowserThread::UI
);
269 JNIEnv
* env
= AttachCurrentThread();
270 ScopedJavaLocalRef
<jobject
> j_bitmap
;
272 j_bitmap
= gfx::ConvertToJavaBitmap(bitmap
);
273 if (is_local_thumbnail
) {
276 ++num_server_thumbs_
;
281 Java_ThumbnailCallback_onMostVisitedURLsThumbnailAvailable(
282 env
, j_callback
->obj(), j_bitmap
.obj());
285 void MostVisitedSites::BlacklistUrl(JNIEnv
* env
,
288 GURL
url(ConvertJavaStringToUTF8(env
, j_url
));
290 // Always blacklist in the local TopSites.
291 scoped_refptr
<TopSites
> top_sites
= TopSitesFactory::GetForProfile(profile_
);
293 top_sites
->AddBlacklistedURL(url
);
295 // Only blacklist in the server-side suggestions service if it's active.
296 if (mv_source_
== SUGGESTIONS_SERVICE
) {
297 SuggestionsService
* suggestions_service
=
298 SuggestionsServiceFactory::GetForProfile(profile_
);
299 DCHECK(suggestions_service
);
300 suggestions_service
->BlacklistURL(
301 url
, base::Bind(&MostVisitedSites::OnSuggestionsProfileAvailable
,
302 weak_ptr_factory_
.GetWeakPtr()),
307 void MostVisitedSites::RecordOpenedMostVisitedItem(JNIEnv
* env
,
311 DCHECK_LT(index
, static_cast<int>(tile_sources_
.size()));
312 std::string histogram
= base::StringPrintf(kOpenedItemHistogramFormat
,
313 tile_sources_
[index
].c_str());
314 LogHistogramEvent(histogram
, index
, num_sites_
);
317 void MostVisitedSites::OnStateChanged() {
318 // There have been changes to the sync state. This class cares about a few
319 // (just initialized, enabled/disabled or history sync state changed). Re-run
320 // the query code which will use the proper state.
321 QueryMostVisitedURLs();
325 bool MostVisitedSites::Register(JNIEnv
* env
) {
326 return RegisterNativesImpl(env
);
329 void MostVisitedSites::QueryMostVisitedURLs() {
330 SuggestionsService
* suggestions_service
=
331 SuggestionsServiceFactory::GetForProfile(profile_
);
332 if (suggestions_service
) {
333 // Suggestions service is enabled, initiate a query.
334 suggestions_service
->FetchSuggestionsData(
335 GetSyncState(profile_
),
336 base::Bind(&MostVisitedSites::OnSuggestionsProfileAvailable
,
337 weak_ptr_factory_
.GetWeakPtr()));
339 InitiateTopSitesQuery();
343 void MostVisitedSites::InitiateTopSitesQuery() {
344 scoped_refptr
<TopSites
> top_sites
= TopSitesFactory::GetForProfile(profile_
);
348 top_sites
->GetMostVisitedURLs(
349 base::Bind(&MostVisitedSites::OnMostVisitedURLsAvailable
,
350 weak_ptr_factory_
.GetWeakPtr()),
354 void MostVisitedSites::OnMostVisitedURLsAvailable(
355 const history::MostVisitedURLList
& visited_list
) {
356 std::vector
<base::string16
> titles
;
357 std::vector
<std::string
> urls
;
358 tile_sources_
.clear();
359 int num_tiles
= std::min(static_cast<int>(visited_list
.size()), num_sites_
);
360 for (int i
= 0; i
< num_tiles
; ++i
) {
361 const history::MostVisitedURL
& visited
= visited_list
[i
];
362 if (visited
.url
.is_empty()) {
364 break; // This is the signal that there are no more real visited sites.
366 titles
.push_back(visited
.title
);
367 urls
.push_back(visited
.url
.spec());
368 tile_sources_
.push_back(kHistogramClientName
);
371 received_most_visited_sites_
= true;
372 mv_source_
= TOP_SITES
;
373 AddPopularSites(&titles
, &urls
);
374 NotifyMostVisitedURLsObserver(titles
, urls
);
377 void MostVisitedSites::OnSuggestionsProfileAvailable(
378 const SuggestionsProfile
& suggestions_profile
) {
379 int num_tiles
= suggestions_profile
.suggestions_size();
380 // With no server suggestions, fall back to local Most Visited.
381 if (num_tiles
== 0) {
382 InitiateTopSitesQuery();
385 if (num_sites_
< num_tiles
)
386 num_tiles
= num_sites_
;
388 std::vector
<base::string16
> titles
;
389 std::vector
<std::string
> urls
;
390 tile_sources_
.clear();
391 for (int i
= 0; i
< num_tiles
; ++i
) {
392 const ChromeSuggestion
& suggestion
= suggestions_profile
.suggestions(i
);
393 titles
.push_back(base::UTF8ToUTF16(suggestion
.title()));
394 urls
.push_back(suggestion
.url());
395 std::string tile_source
;
396 if (suggestion
.providers_size() > 0) {
398 base::StringPrintf(kHistogramServerFormat
, suggestion
.providers(0));
400 tile_source
= kHistogramServerName
;
402 tile_sources_
.push_back(tile_source
);
405 received_most_visited_sites_
= true;
406 mv_source_
= SUGGESTIONS_SERVICE
;
407 AddPopularSites(&titles
, &urls
);
408 NotifyMostVisitedURLsObserver(titles
, urls
);
411 void MostVisitedSites::AddPopularSites(std::vector
<base::string16
>* titles
,
412 std::vector
<std::string
>* urls
) {
416 DCHECK_EQ(titles
->size(), urls
->size());
417 DCHECK_EQ(titles
->size(), tile_sources_
.size());
418 DCHECK_LE(static_cast<int>(titles
->size()), num_sites_
);
420 // Collect all non-blacklisted popular suggestions.
421 std::vector
<base::string16
> popular_titles
;
422 std::vector
<std::string
> popular_urls
;
423 scoped_refptr
<TopSites
> top_sites(TopSitesFactory::GetForProfile(profile_
));
424 for (const PopularSites::Site
& popular_site
: popular_sites_
->sites()) {
425 // Skip blacklisted sites.
426 if (top_sites
&& top_sites
->IsBlacklisted(popular_site
.url
))
429 popular_titles
.push_back(popular_site
.title
);
430 popular_urls
.push_back(popular_site
.url
.spec());
431 if (static_cast<int>(popular_titles
.size()) >= num_sites_
)
436 num_sites_
, popular_titles
, popular_urls
, titles
, urls
, &tile_sources_
);
440 void MostVisitedSites::AddPopularSitesImpl(
442 const std::vector
<base::string16
>& popular_titles
,
443 const std::vector
<std::string
>& popular_urls
,
444 std::vector
<base::string16
>* titles
,
445 std::vector
<std::string
>* urls
,
446 std::vector
<std::string
>* tile_sources
) {
447 // Start off with the popular suggestions.
448 std::vector
<base::string16
> new_titles(popular_titles
);
449 std::vector
<std::string
> new_urls(popular_urls
);
450 std::vector
<std::string
> new_tile_sources(new_titles
.size(),
451 kHistogramPopularName
);
453 // Now, go over the personalized suggestions and replace matching popular
454 // suggestions. This is so that when some of the popular suggestions become
455 // personal, they retain their absolute positions.
456 std::vector
<base::string16
> titles_to_insert
;
457 std::vector
<std::string
> urls_to_insert
;
458 std::vector
<std::string
> tile_sources_to_insert
;
459 for (size_t site_index
= 0; site_index
< titles
->size(); site_index
++) {
460 const base::string16
& title
= (*titles
)[site_index
];
461 const std::string
& url
= (*urls
)[site_index
];
462 const std::string
& tile_source
= (*tile_sources
)[site_index
];
463 // See if we already have a matching popular site.
465 for (size_t i
= 0; i
< new_urls
.size(); i
++) {
466 if (new_tile_sources
[i
] == kHistogramPopularName
&&
467 GURL(new_urls
[i
]).host() == GURL(url
).host()) {
468 // We have a matching popular sites suggestion. Replace it with the
469 // actual URL and title.
470 new_titles
[i
] = title
;
472 new_tile_sources
[i
] = tile_source
;
478 titles_to_insert
.push_back(title
);
479 urls_to_insert
.push_back(url
);
480 tile_sources_to_insert
.push_back(tile_source
);
484 // Append personalized suggestions at the end if there's room.
485 size_t num_to_append
=
486 std::min(static_cast<size_t>(num_sites
) - new_titles
.size(),
487 titles_to_insert
.size());
488 new_titles
.insert(new_titles
.end(),
489 titles_to_insert
.end() - num_to_append
,
490 titles_to_insert
.end());
491 new_urls
.insert(new_urls
.end(),
492 urls_to_insert
.end() - num_to_append
,
493 urls_to_insert
.end());
494 new_tile_sources
.insert(new_tile_sources
.end(),
495 tile_sources_to_insert
.end() - num_to_append
,
496 tile_sources_to_insert
.end());
498 // Finally, go over the remaining personalized suggestions and evict popular
499 // suggestions to accommodate them. Do it in reverse order, so the least
500 // important popular suggestions will be evicted.
501 for (size_t i
= titles_to_insert
.size() - num_to_append
; i
> 0; --i
) {
502 const base::string16
& title
= titles_to_insert
[i
- 1];
503 const std::string
& url
= urls_to_insert
[i
- 1];
504 const std::string
& tile_source
= tile_sources_to_insert
[i
- 1];
505 for (size_t insert_i
= new_titles
.size(); insert_i
> 0; --insert_i
) {
506 size_t insert_index
= insert_i
- 1;
507 if (new_tile_sources
[insert_index
] == kHistogramPopularName
) {
508 new_titles
[insert_index
] = title
;
509 new_urls
[insert_index
] = url
;
510 new_tile_sources
[insert_index
] = tile_source
;
516 titles
->swap(new_titles
);
517 urls
->swap(new_urls
);
518 tile_sources
->swap(new_tile_sources
);
521 void MostVisitedSites::NotifyMostVisitedURLsObserver(
522 const std::vector
<base::string16
>& titles
,
523 const std::vector
<std::string
>& urls
) {
524 DCHECK_EQ(titles
.size(), urls
.size());
525 if (received_most_visited_sites_
&& received_popular_sites_
&&
527 RecordImpressionUMAMetrics();
528 UMA_HISTOGRAM_SPARSE_SLOWLY(kNumTilesHistogramName
, titles
.size());
529 recorded_uma_
= true;
531 JNIEnv
* env
= AttachCurrentThread();
532 Java_MostVisitedURLsObserver_onMostVisitedURLsAvailable(
533 env
, observer_
.obj(), ToJavaArrayOfStrings(env
, titles
).obj(),
534 ToJavaArrayOfStrings(env
, urls
).obj());
537 void MostVisitedSites::OnPopularSitesAvailable(bool success
) {
538 received_popular_sites_
= true;
541 LOG(WARNING
) << "Download of popular sites failed";
545 if (observer_
.is_null())
548 std::vector
<std::string
> urls
;
549 std::vector
<std::string
> favicon_urls
;
550 for (const PopularSites::Site
& popular_site
: popular_sites_
->sites()) {
551 urls
.push_back(popular_site
.url
.spec());
552 favicon_urls
.push_back(popular_site
.favicon_url
.spec());
554 JNIEnv
* env
= AttachCurrentThread();
555 Java_MostVisitedURLsObserver_onPopularURLsAvailable(
556 env
, observer_
.obj(), ToJavaArrayOfStrings(env
, urls
).obj(),
557 ToJavaArrayOfStrings(env
, favicon_urls
).obj());
559 QueryMostVisitedURLs();
562 void MostVisitedSites::RecordThumbnailUMAMetrics() {
563 UMA_HISTOGRAM_SPARSE_SLOWLY(kNumLocalThumbnailTilesHistogramName
,
565 num_local_thumbs_
= 0;
566 UMA_HISTOGRAM_SPARSE_SLOWLY(kNumEmptyTilesHistogramName
, num_empty_thumbs_
);
567 num_empty_thumbs_
= 0;
568 UMA_HISTOGRAM_SPARSE_SLOWLY(kNumServerTilesHistogramName
, num_server_thumbs_
);
569 num_server_thumbs_
= 0;
572 void MostVisitedSites::RecordImpressionUMAMetrics() {
573 for (size_t i
= 0; i
< tile_sources_
.size(); i
++) {
574 std::string histogram
= base::StringPrintf(kImpressionHistogramFormat
,
575 tile_sources_
[i
].c_str());
576 LogHistogramEvent(histogram
, static_cast<int>(i
), num_sites_
);
580 void MostVisitedSites::TopSitesLoaded(history::TopSites
* top_sites
) {
583 void MostVisitedSites::TopSitesChanged(history::TopSites
* top_sites
,
584 ChangeReason change_reason
) {
585 if (mv_source_
== TOP_SITES
) {
586 // The displayed suggestions are invalidated.
587 QueryMostVisitedURLs();
591 static jlong
Init(JNIEnv
* env
,
592 const JavaParamRef
<jobject
>& obj
,
593 const JavaParamRef
<jobject
>& jprofile
) {
594 MostVisitedSites
* most_visited_sites
=
595 new MostVisitedSites(ProfileAndroid::FromProfileAndroid(jprofile
));
596 return reinterpret_cast<intptr_t>(most_visited_sites
);