Disable view source for Developer Tools.
[chromium-blink-merge.git] / chrome / browser / search / instant_service.cc
blob1e4fa9fe5fb7b419ae8298193c2bb8dd0f678616
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/search/instant_service.h"
7 #include <vector>
9 #include "base/logging.h"
10 #include "base/prefs/pref_service.h"
11 #include "base/strings/string_number_conversions.h"
12 #include "chrome/browser/chrome_notification_types.h"
13 #include "chrome/browser/history/history_notifications.h"
14 #include "chrome/browser/history/most_visited_tiles_experiment.h"
15 #include "chrome/browser/history/top_sites.h"
16 #include "chrome/browser/profiles/profile.h"
17 #include "chrome/browser/search/instant_io_context.h"
18 #include "chrome/browser/search/instant_service_factory.h"
19 #include "chrome/browser/search/instant_service_observer.h"
20 #include "chrome/browser/search/local_ntp_source.h"
21 #include "chrome/browser/search/most_visited_iframe_source.h"
22 #include "chrome/browser/search/search.h"
23 #include "chrome/browser/search_engines/template_url.h"
24 #include "chrome/browser/search_engines/template_url_service.h"
25 #include "chrome/browser/search_engines/template_url_service_factory.h"
26 #include "chrome/browser/themes/theme_properties.h"
27 #include "chrome/browser/themes/theme_service.h"
28 #include "chrome/browser/themes/theme_service_factory.h"
29 #include "chrome/browser/ui/webui/favicon_source.h"
30 #include "chrome/browser/ui/webui/ntp/thumbnail_list_source.h"
31 #include "chrome/browser/ui/webui/ntp/thumbnail_source.h"
32 #include "chrome/browser/ui/webui/theme_source.h"
33 #include "chrome/common/pref_names.h"
34 #include "chrome/common/render_messages.h"
35 #include "content/public/browser/browser_thread.h"
36 #include "content/public/browser/notification_details.h"
37 #include "content/public/browser/notification_service.h"
38 #include "content/public/browser/notification_source.h"
39 #include "content/public/browser/notification_types.h"
40 #include "content/public/browser/render_process_host.h"
41 #include "content/public/browser/url_data_source.h"
42 #include "grit/theme_resources.h"
43 #include "net/base/net_util.h"
44 #include "net/url_request/url_request.h"
45 #include "ui/gfx/color_utils.h"
46 #include "ui/gfx/image/image_skia.h"
47 #include "ui/gfx/sys_color_change_listener.h"
48 #include "url/gurl.h"
50 using content::BrowserThread;
52 namespace {
54 const int kSectionBorderAlphaTransparency = 80;
56 // Converts SkColor to RGBAColor
57 RGBAColor SkColorToRGBAColor(const SkColor& sKColor) {
58 RGBAColor color;
59 color.r = SkColorGetR(sKColor);
60 color.g = SkColorGetG(sKColor);
61 color.b = SkColorGetB(sKColor);
62 color.a = SkColorGetA(sKColor);
63 return color;
66 } // namespace
68 InstantService::InstantService(Profile* profile)
69 : profile_(profile),
70 weak_ptr_factory_(this) {
71 // Stub for unit tests.
72 if (!BrowserThread::CurrentlyOn(BrowserThread::UI))
73 return;
75 ResetInstantSearchPrerenderer();
77 registrar_.Add(this,
78 content::NOTIFICATION_RENDERER_PROCESS_CREATED,
79 content::NotificationService::AllSources());
80 registrar_.Add(this,
81 content::NOTIFICATION_RENDERER_PROCESS_TERMINATED,
82 content::NotificationService::AllSources());
84 history::TopSites* top_sites = profile_->GetTopSites();
85 if (top_sites) {
86 registrar_.Add(this,
87 chrome::NOTIFICATION_TOP_SITES_CHANGED,
88 content::Source<history::TopSites>(top_sites));
90 instant_io_context_ = new InstantIOContext();
92 if (profile_ && profile_->GetResourceContext()) {
93 BrowserThread::PostTask(
94 BrowserThread::IO, FROM_HERE,
95 base::Bind(&InstantIOContext::SetUserDataOnIO,
96 profile->GetResourceContext(), instant_io_context_));
99 // Set up the data sources that Instant uses on the NTP.
100 #if defined(ENABLE_THEMES)
101 // Listen for theme installation.
102 registrar_.Add(this, chrome::NOTIFICATION_BROWSER_THEME_CHANGED,
103 content::Source<ThemeService>(
104 ThemeServiceFactory::GetForProfile(profile_)));
106 content::URLDataSource::Add(profile_, new ThemeSource(profile_));
107 #endif // defined(ENABLE_THEMES)
109 content::URLDataSource::Add(profile_, new ThumbnailSource(profile_, false));
110 content::URLDataSource::Add(profile_, new ThumbnailSource(profile_, true));
111 content::URLDataSource::Add(profile_, new ThumbnailListSource(profile_));
112 content::URLDataSource::Add(
113 profile_, new FaviconSource(profile_, FaviconSource::FAVICON));
114 content::URLDataSource::Add(profile_, new LocalNtpSource(profile_));
115 content::URLDataSource::Add(profile_, new MostVisitedIframeSource());
117 profile_pref_registrar_.Init(profile_->GetPrefs());
118 profile_pref_registrar_.Add(
119 prefs::kDefaultSearchProviderID,
120 base::Bind(&InstantService::OnDefaultSearchProviderChanged,
121 base::Unretained(this)));
123 registrar_.Add(this, chrome::NOTIFICATION_GOOGLE_URL_UPDATED,
124 content::Source<Profile>(profile_->GetOriginalProfile()));
127 InstantService::~InstantService() {
130 void InstantService::AddInstantProcess(int process_id) {
131 process_ids_.insert(process_id);
133 if (instant_io_context_.get()) {
134 BrowserThread::PostTask(BrowserThread::IO,
135 FROM_HERE,
136 base::Bind(&InstantIOContext::AddInstantProcessOnIO,
137 instant_io_context_,
138 process_id));
142 bool InstantService::IsInstantProcess(int process_id) const {
143 return process_ids_.find(process_id) != process_ids_.end();
146 void InstantService::AddObserver(InstantServiceObserver* observer) {
147 observers_.AddObserver(observer);
150 void InstantService::RemoveObserver(InstantServiceObserver* observer) {
151 observers_.RemoveObserver(observer);
154 void InstantService::DeleteMostVisitedItem(const GURL& url) {
155 history::TopSites* top_sites = profile_->GetTopSites();
156 if (!top_sites)
157 return;
159 top_sites->AddBlacklistedURL(url);
162 void InstantService::UndoMostVisitedDeletion(const GURL& url) {
163 history::TopSites* top_sites = profile_->GetTopSites();
164 if (!top_sites)
165 return;
167 top_sites->RemoveBlacklistedURL(url);
170 void InstantService::UndoAllMostVisitedDeletions() {
171 history::TopSites* top_sites = profile_->GetTopSites();
172 if (!top_sites)
173 return;
175 top_sites->ClearBlacklistedURLs();
178 void InstantService::UpdateThemeInfo() {
179 // Update theme background info.
180 // Initialize |theme_info| if necessary.
181 if (!theme_info_)
182 OnThemeChanged(ThemeServiceFactory::GetForProfile(profile_));
183 else
184 OnThemeChanged(NULL);
187 void InstantService::UpdateMostVisitedItemsInfo() {
188 NotifyAboutMostVisitedItems();
191 void InstantService::Shutdown() {
192 process_ids_.clear();
194 if (instant_io_context_.get()) {
195 BrowserThread::PostTask(
196 BrowserThread::IO,
197 FROM_HERE,
198 base::Bind(&InstantIOContext::ClearInstantProcessesOnIO,
199 instant_io_context_));
201 instant_io_context_ = NULL;
204 void InstantService::Observe(int type,
205 const content::NotificationSource& source,
206 const content::NotificationDetails& details) {
207 switch (type) {
208 case content::NOTIFICATION_RENDERER_PROCESS_CREATED:
209 SendSearchURLsToRenderer(
210 content::Source<content::RenderProcessHost>(source).ptr());
211 break;
212 case content::NOTIFICATION_RENDERER_PROCESS_TERMINATED:
213 OnRendererProcessTerminated(
214 content::Source<content::RenderProcessHost>(source)->GetID());
215 break;
216 case chrome::NOTIFICATION_TOP_SITES_CHANGED: {
217 history::TopSites* top_sites = profile_->GetTopSites();
218 if (top_sites) {
219 top_sites->GetMostVisitedURLs(
220 base::Bind(&InstantService::OnMostVisitedItemsReceived,
221 weak_ptr_factory_.GetWeakPtr()), false);
223 break;
225 #if defined(ENABLE_THEMES)
226 case chrome::NOTIFICATION_BROWSER_THEME_CHANGED: {
227 OnThemeChanged(content::Source<ThemeService>(source).ptr());
228 break;
230 #endif // defined(ENABLE_THEMES)
231 case chrome::NOTIFICATION_GOOGLE_URL_UPDATED: {
232 OnGoogleURLUpdated(
233 content::Source<Profile>(source).ptr(),
234 content::Details<GoogleURLTracker::UpdatedDetails>(details).ptr());
235 break;
237 default:
238 NOTREACHED() << "Unexpected notification type in InstantService.";
242 void InstantService::SendSearchURLsToRenderer(content::RenderProcessHost* rph) {
243 rph->Send(new ChromeViewMsg_SetSearchURLs(
244 chrome::GetSearchURLs(profile_), chrome::GetNewTabPageURL(profile_)));
247 void InstantService::OnRendererProcessTerminated(int process_id) {
248 process_ids_.erase(process_id);
250 if (instant_io_context_.get()) {
251 BrowserThread::PostTask(
252 BrowserThread::IO,
253 FROM_HERE,
254 base::Bind(&InstantIOContext::RemoveInstantProcessOnIO,
255 instant_io_context_,
256 process_id));
260 void InstantService::OnMostVisitedItemsReceived(
261 const history::MostVisitedURLList& data) {
262 history::MostVisitedURLList reordered_data(data);
263 history::MostVisitedTilesExperiment::MaybeShuffle(&reordered_data);
265 std::vector<InstantMostVisitedItem> new_most_visited_items;
266 for (size_t i = 0; i < reordered_data.size(); i++) {
267 const history::MostVisitedURL& url = reordered_data[i];
268 InstantMostVisitedItem item;
269 item.url = url.url;
270 item.title = url.title;
271 new_most_visited_items.push_back(item);
274 most_visited_items_ = new_most_visited_items;
275 NotifyAboutMostVisitedItems();
278 void InstantService::NotifyAboutMostVisitedItems() {
279 FOR_EACH_OBSERVER(InstantServiceObserver, observers_,
280 MostVisitedItemsChanged(most_visited_items_));
283 void InstantService::OnThemeChanged(ThemeService* theme_service) {
284 if (!theme_service) {
285 DCHECK(theme_info_.get());
286 FOR_EACH_OBSERVER(InstantServiceObserver, observers_,
287 ThemeInfoChanged(*theme_info_));
288 return;
291 // Get theme information from theme service.
292 theme_info_.reset(new ThemeBackgroundInfo());
294 // Get if the current theme is the default theme.
295 theme_info_->using_default_theme = theme_service->UsingDefaultTheme();
297 // Get theme colors.
298 SkColor background_color =
299 theme_service->GetColor(ThemeProperties::COLOR_NTP_BACKGROUND);
300 SkColor text_color =
301 theme_service->GetColor(ThemeProperties::COLOR_NTP_TEXT);
302 SkColor link_color =
303 theme_service->GetColor(ThemeProperties::COLOR_NTP_LINK);
304 SkColor text_color_light =
305 theme_service->GetColor(ThemeProperties::COLOR_NTP_TEXT_LIGHT);
306 SkColor header_color =
307 theme_service->GetColor(ThemeProperties::COLOR_NTP_HEADER);
308 // Generate section border color from the header color.
309 SkColor section_border_color =
310 SkColorSetARGB(kSectionBorderAlphaTransparency,
311 SkColorGetR(header_color),
312 SkColorGetG(header_color),
313 SkColorGetB(header_color));
315 // Invert colors if needed.
316 if (gfx::IsInvertedColorScheme()) {
317 background_color = color_utils::InvertColor(background_color);
318 text_color = color_utils::InvertColor(text_color);
319 link_color = color_utils::InvertColor(link_color);
320 text_color_light = color_utils::InvertColor(text_color_light);
321 header_color = color_utils::InvertColor(header_color);
322 section_border_color = color_utils::InvertColor(section_border_color);
325 // Set colors.
326 theme_info_->background_color = SkColorToRGBAColor(background_color);
327 theme_info_->text_color = SkColorToRGBAColor(text_color);
328 theme_info_->link_color = SkColorToRGBAColor(link_color);
329 theme_info_->text_color_light = SkColorToRGBAColor(text_color_light);
330 theme_info_->header_color = SkColorToRGBAColor(header_color);
331 theme_info_->section_border_color = SkColorToRGBAColor(section_border_color);
333 int logo_alternate = theme_service->GetDisplayProperty(
334 ThemeProperties::NTP_LOGO_ALTERNATE);
335 theme_info_->logo_alternate = logo_alternate == 1;
337 if (theme_service->HasCustomImage(IDR_THEME_NTP_BACKGROUND)) {
338 // Set theme id for theme background image url.
339 theme_info_->theme_id = theme_service->GetThemeID();
341 // Set theme background image horizontal alignment.
342 int alignment = theme_service->GetDisplayProperty(
343 ThemeProperties::NTP_BACKGROUND_ALIGNMENT);
344 if (alignment & ThemeProperties::ALIGN_LEFT)
345 theme_info_->image_horizontal_alignment = THEME_BKGRND_IMAGE_ALIGN_LEFT;
346 else if (alignment & ThemeProperties::ALIGN_RIGHT)
347 theme_info_->image_horizontal_alignment = THEME_BKGRND_IMAGE_ALIGN_RIGHT;
348 else
349 theme_info_->image_horizontal_alignment = THEME_BKGRND_IMAGE_ALIGN_CENTER;
351 // Set theme background image vertical alignment.
352 if (alignment & ThemeProperties::ALIGN_TOP)
353 theme_info_->image_vertical_alignment = THEME_BKGRND_IMAGE_ALIGN_TOP;
354 else if (alignment & ThemeProperties::ALIGN_BOTTOM)
355 theme_info_->image_vertical_alignment = THEME_BKGRND_IMAGE_ALIGN_BOTTOM;
356 else
357 theme_info_->image_vertical_alignment = THEME_BKGRND_IMAGE_ALIGN_CENTER;
359 // Set theme backgorund image tiling.
360 int tiling = theme_service->GetDisplayProperty(
361 ThemeProperties::NTP_BACKGROUND_TILING);
362 switch (tiling) {
363 case ThemeProperties::NO_REPEAT:
364 theme_info_->image_tiling = THEME_BKGRND_IMAGE_NO_REPEAT;
365 break;
366 case ThemeProperties::REPEAT_X:
367 theme_info_->image_tiling = THEME_BKGRND_IMAGE_REPEAT_X;
368 break;
369 case ThemeProperties::REPEAT_Y:
370 theme_info_->image_tiling = THEME_BKGRND_IMAGE_REPEAT_Y;
371 break;
372 case ThemeProperties::REPEAT:
373 theme_info_->image_tiling = THEME_BKGRND_IMAGE_REPEAT;
374 break;
377 // Set theme background image height.
378 gfx::ImageSkia* image = theme_service->GetImageSkiaNamed(
379 IDR_THEME_NTP_BACKGROUND);
380 DCHECK(image);
381 theme_info_->image_height = image->height();
383 theme_info_->has_attribution =
384 theme_service->HasCustomImage(IDR_THEME_NTP_ATTRIBUTION);
387 FOR_EACH_OBSERVER(InstantServiceObserver, observers_,
388 ThemeInfoChanged(*theme_info_));
391 void InstantService::OnGoogleURLUpdated(
392 Profile* profile,
393 GoogleURLTracker::UpdatedDetails* details) {
394 GURL last_prompted_url(
395 profile->GetPrefs()->GetString(prefs::kLastPromptedGoogleURL));
397 // See GoogleURLTracker::OnURLFetchComplete().
398 // last_prompted_url.is_empty() indicates very first run of Chrome. So there
399 // is no need to notify, as there won't be any old state.
400 if (last_prompted_url.is_empty())
401 return;
403 ResetInstantSearchPrerenderer();
405 // Only the scheme changed. Ignore it since we do not prompt the user in this
406 // case.
407 if (net::StripWWWFromHost(details->first) ==
408 net::StripWWWFromHost(details->second))
409 return;
411 FOR_EACH_OBSERVER(InstantServiceObserver, observers_, GoogleURLUpdated());
414 void InstantService::OnDefaultSearchProviderChanged(
415 const std::string& pref_name) {
416 DCHECK_EQ(pref_name, std::string(prefs::kDefaultSearchProviderID));
417 const TemplateURL* template_url = TemplateURLServiceFactory::GetForProfile(
418 profile_)->GetDefaultSearchProvider();
419 if (!template_url) {
420 // A NULL |template_url| could mean either this notification is sent during
421 // the browser start up operation or the user now has no default search
422 // provider. There is no way for the user to reach this state using the
423 // Chrome settings. Only explicitly poking at the DB or bugs in the Sync
424 // could cause that, neither of which we support.
425 return;
428 ResetInstantSearchPrerenderer();
430 FOR_EACH_OBSERVER(
431 InstantServiceObserver, observers_, DefaultSearchProviderChanged());
434 void InstantService::ResetInstantSearchPrerenderer() {
435 if (!chrome::ShouldPrefetchSearchResults())
436 return;
438 GURL url(chrome::GetSearchResultPrefetchBaseURL(profile_));
439 if (url.is_valid())
440 instant_prerenderer_.reset(new InstantSearchPrerenderer(profile_, url));
441 else
442 instant_prerenderer_.reset();