Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(209)

Side by Side Diff: chrome/browser/search_engines/template_url_service.cc

Issue 268643002: Use the DefaultSearchManager as the exclusive authority on DSE, ignoring Web Data. (Closed) Base URL: svn://svn.chromium.org/chrome/trunk/src
Patch Set: Restore DSP origin change metric. Restore some naming and ordering. Created 6 years, 7 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch | Annotate | Revision Log
OLDNEW
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved. 1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be 2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file. 3 // found in the LICENSE file.
4 4
5 #include "chrome/browser/search_engines/template_url_service.h" 5 #include "chrome/browser/search_engines/template_url_service.h"
6 6
7 #include <algorithm> 7 #include <algorithm>
8 #include <utility> 8 #include <utility>
9 9
10 #include "base/auto_reset.h" 10 #include "base/auto_reset.h"
(...skipping 40 matching lines...) Expand 10 before | Expand all | Expand 10 after
51 #include "sync/protocol/search_engine_specifics.pb.h" 51 #include "sync/protocol/search_engine_specifics.pb.h"
52 #include "sync/protocol/sync.pb.h" 52 #include "sync/protocol/sync.pb.h"
53 #include "ui/base/l10n/l10n_util.h" 53 #include "ui/base/l10n/l10n_util.h"
54 #include "url/gurl.h" 54 #include "url/gurl.h"
55 55
56 typedef SearchHostToURLsMap::TemplateURLSet TemplateURLSet; 56 typedef SearchHostToURLsMap::TemplateURLSet TemplateURLSet;
57 typedef TemplateURLService::SyncDataMap SyncDataMap; 57 typedef TemplateURLService::SyncDataMap SyncDataMap;
58 58
59 namespace { 59 namespace {
60 60
61 const char kFirstPotentialEngineHistogramName[] = 61 bool IdenticalSyncGUIDs(const TemplateURLData* data, const TemplateURL* turl) {
62 "Search.FirstPotentialEngineCalled"; 62 if (!data || !turl)
63 return !data && !turl;
63 64
64 // Values for an enumerated histogram used to track whenever 65 return data->sync_guid == turl->sync_guid();
65 // FirstPotentialDefaultEngine is called, and from where. 66 }
66 enum FirstPotentialEngineCaller {
67 FIRST_POTENTIAL_CALLSITE_FIND_NEW_DSP,
68 FIRST_POTENTIAL_CALLSITE_FIND_NEW_DSP_PROCESSING_SYNC_CHANGES,
69 FIRST_POTENTIAL_CALLSITE_ON_LOAD,
70 FIRST_POTENTIAL_CALLSITE_FIND_NEW_DSP_SYNCING,
71 FIRST_POTENTIAL_CALLSITE_FIND_NEW_DSP_NOT_SYNCING,
72 FIRST_POTENTIAL_CALLSITE_MAX,
73 };
74 67
75 const char kDeleteSyncedEngineHistogramName[] = 68 const char kDeleteSyncedEngineHistogramName[] =
76 "Search.DeleteSyncedSearchEngine"; 69 "Search.DeleteSyncedSearchEngine";
77 70
78 // Values for an enumerated histogram used to track whenever an ACTION_DELETE is 71 // Values for an enumerated histogram used to track whenever an ACTION_DELETE is
79 // sent to the server for search engines. 72 // sent to the server for search engines.
80 enum DeleteSyncedSearchEngineEvent { 73 enum DeleteSyncedSearchEngineEvent {
81 DELETE_ENGINE_USER_ACTION, 74 DELETE_ENGINE_USER_ACTION,
82 DELETE_ENGINE_PRE_SYNC, 75 DELETE_ENGINE_PRE_SYNC,
83 DELETE_ENGINE_EMPTY_FIELD, 76 DELETE_ENGINE_EMPTY_FIELD,
84 DELETE_ENGINE_MAX, 77 DELETE_ENGINE_MAX,
85 }; 78 };
86 79
87 TemplateURL* FirstPotentialDefaultEngine(
88 const TemplateURLService::TemplateURLVector& template_urls) {
89 for (TemplateURLService::TemplateURLVector::const_iterator i(
90 template_urls.begin()); i != template_urls.end(); ++i) {
91 if ((*i)->ShowInDefaultList() &&
92 ((*i)->GetType() == TemplateURL::NORMAL))
93 return *i;
94 }
95 return NULL;
96 }
97
98 // Returns true iff the change in |change_list| at index |i| should not be sent 80 // Returns true iff the change in |change_list| at index |i| should not be sent
99 // up to the server based on its GUIDs presence in |sync_data| or when compared 81 // up to the server based on its GUIDs presence in |sync_data| or when compared
100 // to changes after it in |change_list|. 82 // to changes after it in |change_list|.
101 // The criteria is: 83 // The criteria is:
102 // 1) It is an ACTION_UPDATE or ACTION_DELETE and the sync_guid associated 84 // 1) It is an ACTION_UPDATE or ACTION_DELETE and the sync_guid associated
103 // with it is NOT found in |sync_data|. We can only update and remove 85 // with it is NOT found in |sync_data|. We can only update and remove
104 // entries that were originally from the Sync server. 86 // entries that were originally from the Sync server.
105 // 2) It is an ACTION_ADD and the sync_guid associated with it is found in 87 // 2) It is an ACTION_ADD and the sync_guid associated with it is found in
106 // |sync_data|. We cannot re-add entries that Sync already knew about. 88 // |sync_data|. We cannot re-add entries that Sync already knew about.
107 // 3) There is an update after an update for the same GUID. We prune earlier 89 // 3) There is an update after an update for the same GUID. We prune earlier
(...skipping 132 matching lines...) Expand 10 before | Expand all | Expand 10 after
240 // Unfortunately the calling convention is not "prefix and element" but 222 // Unfortunately the calling convention is not "prefix and element" but
241 // rather "two elements", so we pass the prefix as a fake "element" which has 223 // rather "two elements", so we pass the prefix as a fake "element" which has
242 // a NULL KeywordDataElement pointer. 224 // a NULL KeywordDataElement pointer.
243 bool operator()(const KeywordToTemplateMap::value_type& elem1, 225 bool operator()(const KeywordToTemplateMap::value_type& elem1,
244 const KeywordToTemplateMap::value_type& elem2) const { 226 const KeywordToTemplateMap::value_type& elem2) const {
245 return (elem1.second == NULL) ? 227 return (elem1.second == NULL) ?
246 (elem2.first.compare(0, elem1.first.length(), elem1.first) > 0) : 228 (elem2.first.compare(0, elem1.first.length(), elem1.first) > 0) :
247 (elem1.first < elem2.first); 229 (elem1.first < elem2.first);
248 } 230 }
249 }; 231 };
250 232
Peter Kasting 2014/05/08 22:46:46 Nit: Should still have 2 blank lines here
233 // TemplateURLService ---------------------------------------------------------
251 234
252 // TemplateURLService --------------------------------------------------------- 235 // static
236 bool TemplateURLService::g_fallback_search_engines_disabled = false;
253 237
254 TemplateURLService::TemplateURLService(Profile* profile) 238 TemplateURLService::TemplateURLService(Profile* profile)
255 : provider_map_(new SearchHostToURLsMap), 239 : provider_map_(new SearchHostToURLsMap),
256 profile_(profile), 240 profile_(profile),
257 loaded_(false), 241 loaded_(false),
258 load_failed_(false), 242 load_failed_(false),
259 load_handle_(0), 243 load_handle_(0),
260 default_search_provider_(NULL), 244 default_search_provider_(NULL),
261 is_default_search_managed_(false),
262 next_id_(kInvalidTemplateURLID + 1), 245 next_id_(kInvalidTemplateURLID + 1),
263 time_provider_(&base::Time::Now), 246 time_provider_(&base::Time::Now),
264 models_associated_(false), 247 models_associated_(false),
265 processing_syncer_changes_(false), 248 processing_syncer_changes_(false),
266 pending_synced_default_search_(false),
267 dsp_change_origin_(DSP_CHANGE_OTHER), 249 dsp_change_origin_(DSP_CHANGE_OTHER),
268 default_search_manager_( 250 default_search_manager_(
269 GetPrefs(), 251 GetPrefs(),
270 DefaultSearchManager::ObserverCallback()) { 252 base::Bind(&TemplateURLService::OnDefaultSearchChange,
253 base::Unretained(this))) {
271 DCHECK(profile_); 254 DCHECK(profile_);
272 Init(NULL, 0); 255 Init(NULL, 0);
273 } 256 }
274 257
275 TemplateURLService::TemplateURLService(const Initializer* initializers, 258 TemplateURLService::TemplateURLService(const Initializer* initializers,
276 const int count) 259 const int count)
277 : provider_map_(new SearchHostToURLsMap), 260 : provider_map_(new SearchHostToURLsMap),
278 profile_(NULL), 261 profile_(NULL),
279 loaded_(false), 262 loaded_(false),
280 load_failed_(false), 263 load_failed_(false),
281 load_handle_(0), 264 load_handle_(0),
282 service_(NULL), 265 service_(NULL),
283 default_search_provider_(NULL), 266 default_search_provider_(NULL),
284 is_default_search_managed_(false),
285 next_id_(kInvalidTemplateURLID + 1), 267 next_id_(kInvalidTemplateURLID + 1),
286 time_provider_(&base::Time::Now), 268 time_provider_(&base::Time::Now),
287 models_associated_(false), 269 models_associated_(false),
288 processing_syncer_changes_(false), 270 processing_syncer_changes_(false),
289 pending_synced_default_search_(false),
290 dsp_change_origin_(DSP_CHANGE_OTHER), 271 dsp_change_origin_(DSP_CHANGE_OTHER),
291 default_search_manager_( 272 default_search_manager_(
292 GetPrefs(), 273 GetPrefs(),
293 DefaultSearchManager::ObserverCallback()) { 274 base::Bind(&TemplateURLService::OnDefaultSearchChange,
275 base::Unretained(this))) {
294 Init(initializers, count); 276 Init(initializers, count);
295 } 277 }
296 278
297 TemplateURLService::~TemplateURLService() { 279 TemplateURLService::~TemplateURLService() {
298 // |service_| should be deleted during Shutdown(). 280 // |service_| should be deleted during Shutdown().
299 DCHECK(!service_); 281 DCHECK(!service_);
300 STLDeleteElements(&template_urls_); 282 STLDeleteElements(&template_urls_);
301 } 283 }
302 284
303 // static 285 // static
(...skipping 164 matching lines...) Expand 10 before | Expand all | Expand 10 after
468 // case the term replaces the URL it's unlikely another keyword would have the 450 // case the term replaces the URL it's unlikely another keyword would have the
469 // same url. 451 // same url.
470 // TODO(jnd): Add additional parameters to get post data when the search URL 452 // TODO(jnd): Add additional parameters to get post data when the search URL
471 // has post parameters. 453 // has post parameters.
472 return GURL(search_ref.ReplaceSearchTermsUsingTermsData( 454 return GURL(search_ref.ReplaceSearchTermsUsingTermsData(
473 TemplateURLRef::SearchTermsArgs( 455 TemplateURLRef::SearchTermsArgs(
474 base::ASCIIToUTF16("blah.blah.blah.blah.blah")), 456 base::ASCIIToUTF16("blah.blah.blah.blah.blah")),
475 search_terms_data, NULL)); 457 search_terms_data, NULL));
476 } 458 }
477 459
460 // static
478 void TemplateURLService::SaveDefaultSearchProviderToPrefs( 461 void TemplateURLService::SaveDefaultSearchProviderToPrefs(
479 const TemplateURL* t_url, 462 const TemplateURL* t_url,
480 PrefService* prefs) const { 463 PrefService* prefs) {
481 if (!prefs || load_failed_) 464 if (!prefs)
Peter Kasting 2014/05/08 22:46:46 The functionality that was here -- not persisting
erikwright (departed) 2014/05/09 18:00:22 OK - I added some new code in SetUserSelectedDefau
482 return; 465 return;
483 466
484 bool enabled = false; 467 bool enabled = false;
485 std::string search_url; 468 std::string search_url;
486 std::string suggest_url; 469 std::string suggest_url;
487 std::string instant_url; 470 std::string instant_url;
488 std::string image_url; 471 std::string image_url;
489 std::string new_tab_url; 472 std::string new_tab_url;
490 std::string search_url_post_params; 473 std::string search_url_post_params;
491 std::string suggest_url_post_params; 474 std::string suggest_url_post_params;
(...skipping 111 matching lines...) Expand 10 before | Expand all | Expand 10 after
603 matches->push_back(i->second); 586 matches->push_back(i->second);
604 } 587 }
605 } 588 }
606 589
607 TemplateURL* TemplateURLService::GetTemplateURLForKeyword( 590 TemplateURL* TemplateURLService::GetTemplateURLForKeyword(
608 const base::string16& keyword) { 591 const base::string16& keyword) {
609 KeywordToTemplateMap::const_iterator elem( 592 KeywordToTemplateMap::const_iterator elem(
610 keyword_to_template_map_.find(keyword)); 593 keyword_to_template_map_.find(keyword));
611 if (elem != keyword_to_template_map_.end()) 594 if (elem != keyword_to_template_map_.end())
612 return elem->second; 595 return elem->second;
613 return ((!loaded_ || load_failed_) && 596 return (!loaded_ &&
614 initial_default_search_provider_.get() && 597 initial_default_search_provider_.get() &&
615 (initial_default_search_provider_->keyword() == keyword)) ? 598 (initial_default_search_provider_->keyword() == keyword)) ?
616 initial_default_search_provider_.get() : NULL; 599 initial_default_search_provider_.get() : NULL;
617 } 600 }
618 601
619 TemplateURL* TemplateURLService::GetTemplateURLForGUID( 602 TemplateURL* TemplateURLService::GetTemplateURLForGUID(
620 const std::string& sync_guid) { 603 const std::string& sync_guid) {
621 GUIDToTemplateMap::const_iterator elem(guid_to_template_map_.find(sync_guid)); 604 GUIDToTemplateMap::const_iterator elem(guid_to_template_map_.find(sync_guid));
622 if (elem != guid_to_template_map_.end()) 605 if (elem != guid_to_template_map_.end())
623 return elem->second; 606 return elem->second;
624 return ((!loaded_ || load_failed_) && 607 return (!loaded_ &&
625 initial_default_search_provider_.get() && 608 initial_default_search_provider_.get() &&
626 (initial_default_search_provider_->sync_guid() == sync_guid)) ? 609 (initial_default_search_provider_->sync_guid() == sync_guid)) ?
627 initial_default_search_provider_.get() : NULL; 610 initial_default_search_provider_.get() : NULL;
628 } 611 }
629 612
630 TemplateURL* TemplateURLService::GetTemplateURLForHost( 613 TemplateURL* TemplateURLService::GetTemplateURLForHost(
631 const std::string& host) { 614 const std::string& host) {
632 if (loaded_) { 615 if (loaded_) {
633 TemplateURL* t_url = provider_map_->GetTemplateURLForHost(host); 616 TemplateURL* t_url = provider_map_->GetTemplateURLForHost(host);
634 if (t_url) 617 if (t_url)
635 return t_url; 618 return t_url;
636 } 619 }
637 return ((!loaded_ || load_failed_) && 620 return (!loaded_ &&
638 initial_default_search_provider_.get() && 621 initial_default_search_provider_.get() &&
639 (GenerateSearchURL(initial_default_search_provider_.get()).host() == 622 (GenerateSearchURL(initial_default_search_provider_.get()).host() ==
640 host)) ? initial_default_search_provider_.get() : NULL; 623 host)) ? initial_default_search_provider_.get() : NULL;
641 } 624 }
642 625
643 void TemplateURLService::Add(TemplateURL* template_url) { 626 bool TemplateURLService::Add(TemplateURL* template_url) {
644 WebDataService::KeywordBatchModeScoper keyword_scoper(service_.get()); 627 WebDataService::KeywordBatchModeScoper keyword_scoper(service_.get());
645 if (AddNoNotify(template_url, true)) 628 if (!AddNoNotify(template_url, true))
646 NotifyObservers(); 629 return false;
630 NotifyObservers();
631 return true;
647 } 632 }
648 633
649 void TemplateURLService::AddAndSetProfile(TemplateURL* template_url, 634 void TemplateURLService::AddAndSetProfile(TemplateURL* template_url,
650 Profile* profile) { 635 Profile* profile) {
651 template_url->profile_ = profile; 636 template_url->profile_ = profile;
652 Add(template_url); 637 Add(template_url);
653 } 638 }
654 639
655 void TemplateURLService::AddWithOverrides(TemplateURL* template_url, 640 void TemplateURLService::AddWithOverrides(TemplateURL* template_url,
656 const base::string16& short_name, 641 const base::string16& short_name,
(...skipping 16 matching lines...) Expand all
673 DCHECK(info); 658 DCHECK(info);
674 DCHECK_EQ(info->wants_to_be_default_engine, 659 DCHECK_EQ(info->wants_to_be_default_engine,
675 template_url->show_in_default_list()); 660 template_url->show_in_default_list());
676 template_url->extension_info_.swap(info); 661 template_url->extension_info_.swap(info);
677 DCHECK(!FindTemplateURLForExtension( 662 DCHECK(!FindTemplateURLForExtension(
678 template_url->GetExtensionId(), 663 template_url->GetExtensionId(),
679 TemplateURL::NORMAL_CONTROLLED_BY_EXTENSION)); 664 TemplateURL::NORMAL_CONTROLLED_BY_EXTENSION));
680 665
681 WebDataService::KeywordBatchModeScoper keyword_scoper(service_.get()); 666 WebDataService::KeywordBatchModeScoper keyword_scoper(service_.get());
682 if (AddNoNotify(template_url, true)) { 667 if (AddNoNotify(template_url, true)) {
683 // Note that we can't call CanMakeDefault() here, since it would return 668 if (template_url->extension_info_->wants_to_be_default_engine)
684 // false when another extension is already controlling the default search 669 UpdateExtensionDefaultSearchEngine();
685 // engine, and we want to allow new extensions to take over.
686 if (template_url->extension_info_->wants_to_be_default_engine &&
687 !is_default_search_managed()) {
688 TemplateURL* default_candidate = FindExtensionDefaultSearchEngine();
689 if (default_candidate == template_url) {
690 base::AutoReset<DefaultSearchChangeOrigin> change_origin(
691 &dsp_change_origin_, DSP_CHANGE_OVERRIDE_SETTINGS_EXTENSION);
692 SetDefaultSearchProviderNoNotify(template_url);
693 }
694 }
695 NotifyObservers(); 670 NotifyObservers();
696 } 671 }
697 } 672 }
698 673
699 void TemplateURLService::Remove(TemplateURL* template_url) { 674 void TemplateURLService::Remove(TemplateURL* template_url) {
700 RemoveNoNotify(template_url); 675 RemoveNoNotify(template_url);
701 NotifyObservers(); 676 NotifyObservers();
702 } 677 }
703 678
704 void TemplateURLService::RemoveExtensionControlledTURL( 679 void TemplateURLService::RemoveExtensionControlledTURL(
705 const std::string& extension_id) { 680 const std::string& extension_id) {
706 DCHECK(loaded_); 681 DCHECK(loaded_);
707 TemplateURL* url = FindTemplateURLForExtension( 682 TemplateURL* url = FindTemplateURLForExtension(
708 extension_id, TemplateURL::NORMAL_CONTROLLED_BY_EXTENSION); 683 extension_id, TemplateURL::NORMAL_CONTROLLED_BY_EXTENSION);
709 if (!url) 684 if (!url)
710 return; 685 return;
711 bool restore_dse = (url == GetDefaultSearchProvider()); 686 // NULL this out so that we can call RemoveNoNotify. The subsequent
Peter Kasting 2014/05/08 22:46:46 Nit: Remove "The subsequent"
712 if (restore_dse) { 687 // UpdateExtensionDefaultSearchEngine will cause it to be reset.
713 DCHECK(!is_default_search_managed()); 688 if (default_search_provider_ == url)
714 default_search_provider_ = NULL; 689 default_search_provider_ = NULL;
715 }
716 WebDataService::KeywordBatchModeScoper keyword_scoper(service_.get()); 690 WebDataService::KeywordBatchModeScoper keyword_scoper(service_.get());
717 RemoveNoNotify(url); 691 RemoveNoNotify(url);
718 if (restore_dse) 692 UpdateExtensionDefaultSearchEngine();
719 SetDefaultSearchProviderAfterRemovingDefaultExtension();
720 NotifyObservers(); 693 NotifyObservers();
721 } 694 }
722 695
723 void TemplateURLService::RemoveAutoGeneratedSince(base::Time created_after) { 696 void TemplateURLService::RemoveAutoGeneratedSince(base::Time created_after) {
724 RemoveAutoGeneratedBetween(created_after, base::Time()); 697 RemoveAutoGeneratedBetween(created_after, base::Time());
725 } 698 }
726 699
727 void TemplateURLService::RemoveAutoGeneratedBetween(base::Time created_after, 700 void TemplateURLService::RemoveAutoGeneratedBetween(base::Time created_after,
728 base::Time created_before) { 701 base::Time created_before) {
729 RemoveAutoGeneratedForOriginBetween(GURL(), created_after, created_before); 702 RemoveAutoGeneratedForOriginBetween(GURL(), created_after, created_before);
(...skipping 66 matching lines...) Expand 10 before | Expand all | Expand 10 after
796 769
797 void TemplateURLService::ResetTemplateURL(TemplateURL* url, 770 void TemplateURLService::ResetTemplateURL(TemplateURL* url,
798 const base::string16& title, 771 const base::string16& title,
799 const base::string16& keyword, 772 const base::string16& keyword,
800 const std::string& search_url) { 773 const std::string& search_url) {
801 if (ResetTemplateURLNoNotify(url, title, keyword, search_url)) 774 if (ResetTemplateURLNoNotify(url, title, keyword, search_url))
802 NotifyObservers(); 775 NotifyObservers();
803 } 776 }
804 777
805 bool TemplateURLService::CanMakeDefault(const TemplateURL* url) { 778 bool TemplateURLService::CanMakeDefault(const TemplateURL* url) {
806 return !is_default_search_managed() && 779 return
807 !IsExtensionControlledDefaultSearch() && 780 ((default_search_provider_source_ == DefaultSearchManager::FROM_USER) ||
808 (url != GetDefaultSearchProvider()) && 781 (default_search_provider_source_ ==
809 url->url_ref().SupportsReplacement() && 782 DefaultSearchManager::FROM_FALLBACK)) &&
810 (url->GetType() == TemplateURL::NORMAL); 783 (url != GetDefaultSearchProvider()) &&
784 url->url_ref().SupportsReplacement() &&
785 (url->GetType() == TemplateURL::NORMAL);
811 } 786 }
812 787
813 void TemplateURLService::SetUserSelectedDefaultSearchProvider( 788 void TemplateURLService::SetUserSelectedDefaultSearchProvider(
814 TemplateURL* url) { 789 TemplateURL* url) {
815 SetDefaultSearchProvider(url); 790 // Omnibox keywords cannot be made default. Extension-controlled search
791 // engines can be made default only by the extension itself because they
792 // aren't persisted.
793 DCHECK(!url || (url->GetType() == TemplateURL::NORMAL));
794 // We rely on the DefaultSearchManager to push this back to us if, in fact,
795 // the effective DSE changes.
816 if (url) 796 if (url)
817 default_search_manager_.SetUserSelectedDefaultSearchEngine(url->data()); 797 default_search_manager_.SetUserSelectedDefaultSearchEngine(url->data());
818 else 798 else
819 default_search_manager_.ClearUserSelectedDefaultSearchEngine(); 799 default_search_manager_.ClearUserSelectedDefaultSearchEngine();
820 } 800 }
821 801
822 TemplateURL* TemplateURLService::GetDefaultSearchProvider() { 802 TemplateURL* TemplateURLService::GetDefaultSearchProvider() {
823 return (loaded_ && !load_failed_) ? 803 return loaded_ ?
824 default_search_provider_ : initial_default_search_provider_.get(); 804 default_search_provider_ : initial_default_search_provider_.get();
825 } 805 }
826 806
827 bool TemplateURLService::IsSearchResultsPageFromDefaultSearchProvider( 807 bool TemplateURLService::IsSearchResultsPageFromDefaultSearchProvider(
828 const GURL& url) { 808 const GURL& url) {
829 TemplateURL* default_provider = GetDefaultSearchProvider(); 809 TemplateURL* default_provider = GetDefaultSearchProvider();
830 return default_provider && default_provider->IsSearchURL(url); 810 return default_provider && default_provider->IsSearchURL(url);
831 } 811 }
832 812
833 bool TemplateURLService::IsExtensionControlledDefaultSearch() { 813 bool TemplateURLService::IsExtensionControlledDefaultSearch() {
834 const TemplateURL* default_provider = GetDefaultSearchProvider(); 814 return default_search_provider_source_ ==
835 return default_provider && (default_provider->GetType() == 815 DefaultSearchManager::FROM_EXTENSION;
836 TemplateURL::NORMAL_CONTROLLED_BY_EXTENSION);
837 }
838
839 TemplateURL* TemplateURLService::FindNewDefaultSearchProvider() {
840 // See if the prepopulated default still exists.
841 scoped_ptr<TemplateURLData> prepopulated_default =
842 TemplateURLPrepopulateData::GetPrepopulatedDefaultSearch(GetPrefs());
843
844 for (TemplateURLVector::iterator i = template_urls_.begin();
845 i != template_urls_.end(); ++i) {
846 if ((*i)->prepopulate_id() == prepopulated_default->prepopulate_id)
847 return *i;
848 }
849 // If not, use the first non-extension keyword of the templates that supports
850 // search term replacement.
851 if (processing_syncer_changes_) {
852 UMA_HISTOGRAM_ENUMERATION(
853 kFirstPotentialEngineHistogramName,
854 FIRST_POTENTIAL_CALLSITE_FIND_NEW_DSP_PROCESSING_SYNC_CHANGES,
855 FIRST_POTENTIAL_CALLSITE_MAX);
856 } else {
857 if (sync_processor_.get()) {
858 // We're not currently in a sync cycle, but we're syncing.
859 UMA_HISTOGRAM_ENUMERATION(kFirstPotentialEngineHistogramName,
860 FIRST_POTENTIAL_CALLSITE_FIND_NEW_DSP_SYNCING,
861 FIRST_POTENTIAL_CALLSITE_MAX);
862 } else {
863 // We're not syncing at all.
864 UMA_HISTOGRAM_ENUMERATION(
865 kFirstPotentialEngineHistogramName,
866 FIRST_POTENTIAL_CALLSITE_FIND_NEW_DSP_NOT_SYNCING,
867 FIRST_POTENTIAL_CALLSITE_MAX);
868 }
869 }
870 return FirstPotentialDefaultEngine(template_urls_);
871 } 816 }
872 817
873 void TemplateURLService::RepairPrepopulatedSearchEngines() { 818 void TemplateURLService::RepairPrepopulatedSearchEngines() {
874 // Can't clean DB if it hasn't been loaded. 819 // Can't clean DB if it hasn't been loaded.
875 DCHECK(loaded()); 820 DCHECK(loaded());
876 821
822 if ((default_search_provider_source_ == DefaultSearchManager::FROM_USER) ||
823 (default_search_provider_source_ ==
824 DefaultSearchManager::FROM_FALLBACK)) {
825 // Clear |default_search_provider_| in case we want to remove the engine it
826 // points to. This will get reset at the end of the function anyway.
827 default_search_provider_ = NULL;
828 }
829
877 size_t default_search_provider_index = 0; 830 size_t default_search_provider_index = 0;
878 ScopedVector<TemplateURLData> prepopulated_urls = 831 ScopedVector<TemplateURLData> prepopulated_urls =
879 TemplateURLPrepopulateData::GetPrepopulatedEngines( 832 TemplateURLPrepopulateData::GetPrepopulatedEngines(
880 GetPrefs(), &default_search_provider_index); 833 GetPrefs(), &default_search_provider_index);
881 DCHECK(!prepopulated_urls.empty()); 834 DCHECK(!prepopulated_urls.empty());
882 int default_search_engine_id =
883 prepopulated_urls[default_search_provider_index]->prepopulate_id;
884 TemplateURL* current_dse = default_search_provider_;
885 ActionsFromPrepopulateData actions(CreateActionsFromCurrentPrepopulateData( 835 ActionsFromPrepopulateData actions(CreateActionsFromCurrentPrepopulateData(
886 &prepopulated_urls, template_urls_, current_dse)); 836 &prepopulated_urls, template_urls_, default_search_provider_));
887 837
888 WebDataService::KeywordBatchModeScoper keyword_scoper(service_.get()); 838 WebDataService::KeywordBatchModeScoper keyword_scoper(service_.get());
889 839
890 // Remove items. 840 // Remove items.
891 for (std::vector<TemplateURL*>::iterator i = actions.removed_engines.begin(); 841 for (std::vector<TemplateURL*>::iterator i = actions.removed_engines.begin();
892 i < actions.removed_engines.end(); ++i) 842 i < actions.removed_engines.end(); ++i)
893 RemoveNoNotify(*i); 843 RemoveNoNotify(*i);
894 844
895 // Edit items. 845 // Edit items.
896 for (EditedEngines::iterator i(actions.edited_engines.begin()); 846 for (EditedEngines::iterator i(actions.edited_engines.begin());
897 i < actions.edited_engines.end(); ++i) { 847 i < actions.edited_engines.end(); ++i) {
898 UIThreadSearchTermsData search_terms_data(profile()); 848 UIThreadSearchTermsData search_terms_data(profile());
899 TemplateURL new_values(profile(), i->second); 849 TemplateURL new_values(profile(), i->second);
900 UpdateNoNotify(i->first, new_values, search_terms_data); 850 UpdateNoNotify(i->first, new_values, search_terms_data);
901 } 851 }
902 852
903 // Add items. 853 // Add items.
904 for (std::vector<TemplateURLData>::const_iterator i = 854 for (std::vector<TemplateURLData>::const_iterator i =
905 actions.added_engines.begin(); 855 actions.added_engines.begin();
906 i < actions.added_engines.end(); 856 i < actions.added_engines.end();
907 ++i) { 857 ++i) {
908 AddNoNotify(new TemplateURL(profile_, *i), true); 858 AddNoNotify(new TemplateURL(profile_, *i), true);
909 } 859 }
910 860
911 // Change the DSE. 861 base::AutoReset<DefaultSearchChangeOrigin> change_origin(
912 TemplateURL* new_dse = FindURLByPrepopulateID(template_urls_, 862 &dsp_change_origin_, DSP_CHANGE_PROFILE_RESET);
913 default_search_engine_id); 863
914 DCHECK(new_dse); 864 default_search_manager_.ClearUserSelectedDefaultSearchEngine();
915 if (CanMakeDefault(new_dse)) { 865
916 base::AutoReset<DefaultSearchChangeOrigin> change_origin( 866 if (!default_search_provider_) {
917 &dsp_change_origin_, DSP_CHANGE_PROFILE_RESET); 867 DefaultSearchManager::Source source;
918 SetDefaultSearchProviderNoNotify(new_dse); 868 const TemplateURLData* new_dse =
869 default_search_manager_.GetDefaultSearchEngine(&source);
870 // ApplyDefaultSearchChange will notify observers once it is done.
871 ApplyDefaultSearchChange(new_dse, source);
872 } else {
873 NotifyObservers();
919 } 874 }
920 NotifyObservers();
921 } 875 }
922 876
923 void TemplateURLService::AddObserver(TemplateURLServiceObserver* observer) { 877 void TemplateURLService::AddObserver(TemplateURLServiceObserver* observer) {
924 model_observers_.AddObserver(observer); 878 model_observers_.AddObserver(observer);
925 } 879 }
926 880
927 void TemplateURLService::RemoveObserver(TemplateURLServiceObserver* observer) { 881 void TemplateURLService::RemoveObserver(TemplateURLServiceObserver* observer) {
928 model_observers_.RemoveObserver(observer); 882 model_observers_.RemoveObserver(observer);
929 } 883 }
930 884
931 void TemplateURLService::Load() { 885 void TemplateURLService::Load() {
932 if (loaded_ || load_handle_) 886 if (loaded_ || load_handle_)
933 return; 887 return;
934 888
935 if (!service_) 889 if (!service_)
936 service_ = WebDataService::FromBrowserContext(profile_); 890 service_ = WebDataService::FromBrowserContext(profile_);
937 891
938 if (service_) { 892 if (service_)
939 load_handle_ = service_->GetKeywords(this); 893 load_handle_ = service_->GetKeywords(this);
940 } else { 894 else
941 ChangeToLoadedState(); 895 ChangeToLoadedState();
942 on_loaded_callbacks_.Notify();
943 }
944 } 896 }
945 897
946 scoped_ptr<TemplateURLService::Subscription> 898 scoped_ptr<TemplateURLService::Subscription>
947 TemplateURLService::RegisterOnLoadedCallback( 899 TemplateURLService::RegisterOnLoadedCallback(
948 const base::Closure& callback) { 900 const base::Closure& callback) {
949 return loaded_ ? 901 return loaded_ ?
950 scoped_ptr<TemplateURLService::Subscription>() : 902 scoped_ptr<TemplateURLService::Subscription>() :
951 on_loaded_callbacks_.Add(callback); 903 on_loaded_callbacks_.Add(callback);
952 } 904 }
953 905
954 void TemplateURLService::OnWebDataServiceRequestDone( 906 void TemplateURLService::OnWebDataServiceRequestDone(
955 WebDataService::Handle h, 907 WebDataService::Handle h,
956 const WDTypedResult* result) { 908 const WDTypedResult* result) {
957 // Reset the load_handle so that we don't try and cancel the load in 909 // Reset the load_handle so that we don't try and cancel the load in
958 // the destructor. 910 // the destructor.
959 load_handle_ = 0; 911 load_handle_ = 0;
960 912
961 if (!result) { 913 if (!result) {
962 // Results are null if the database went away or (most likely) wasn't 914 // Results are null if the database went away or (most likely) wasn't
963 // loaded. 915 // loaded.
964 load_failed_ = true; 916 load_failed_ = true;
965 service_ = NULL; 917 service_ = NULL;
966 ChangeToLoadedState(); 918 ChangeToLoadedState();
967 on_loaded_callbacks_.Notify();
968 return; 919 return;
969 } 920 }
970 921
971 // initial_default_search_provider_ is only needed before we've finished
972 // loading. Now that we've loaded we can nuke it.
973 initial_default_search_provider_.reset();
974
975 TemplateURLVector template_urls; 922 TemplateURLVector template_urls;
976 TemplateURL* default_search_provider = NULL;
977 int new_resource_keyword_version = 0; 923 int new_resource_keyword_version = 0;
978 GetSearchProvidersUsingKeywordResult(*result, service_.get(), profile_, 924 GetSearchProvidersUsingKeywordResult(
979 &template_urls, &default_search_provider, &new_resource_keyword_version, 925 *result,
926 service_.get(),
927 profile_,
928 &template_urls,
929 (default_search_provider_source_ == DefaultSearchManager::FROM_USER) ?
930 initial_default_search_provider_.get() : NULL,
931 &new_resource_keyword_version,
980 &pre_sync_deletes_); 932 &pre_sync_deletes_);
981 933
982 WebDataService::KeywordBatchModeScoper keyword_scoper(service_.get()); 934 WebDataService::KeywordBatchModeScoper keyword_scoper(service_.get());
983 935
984 AddTemplateURLsAndSetupDefaultEngine(&template_urls, default_search_provider); 936 PatchMissingSyncGUIDs(&template_urls);
937 SetTemplateURLs(&template_urls);
985 938
986 // This initializes provider_map_ which should be done before 939 // This initializes provider_map_ which should be done before
987 // calling UpdateKeywordSearchTermsForURL. 940 // calling UpdateKeywordSearchTermsForURL.
941 // This also calls NotifyObservers.
988 ChangeToLoadedState(); 942 ChangeToLoadedState();
989 943
990 // Index any visits that occurred before we finished loading. 944 // Index any visits that occurred before we finished loading.
991 for (size_t i = 0; i < visits_to_add_.size(); ++i) 945 for (size_t i = 0; i < visits_to_add_.size(); ++i)
992 UpdateKeywordSearchTermsForURL(visits_to_add_[i]); 946 UpdateKeywordSearchTermsForURL(visits_to_add_[i]);
993 visits_to_add_.clear(); 947 visits_to_add_.clear();
994 948
995 if (new_resource_keyword_version) 949 if (new_resource_keyword_version)
996 service_->SetBuiltinKeywordVersion(new_resource_keyword_version); 950 service_->SetBuiltinKeywordVersion(new_resource_keyword_version);
997
998 EnsureDefaultSearchProviderExists();
999
1000 NotifyObservers();
1001 on_loaded_callbacks_.Notify();
1002 } 951 }
1003 952
1004 base::string16 TemplateURLService::GetKeywordShortName( 953 base::string16 TemplateURLService::GetKeywordShortName(
1005 const base::string16& keyword, 954 const base::string16& keyword,
1006 bool* is_omnibox_api_extension_keyword) { 955 bool* is_omnibox_api_extension_keyword) {
1007 const TemplateURL* template_url = GetTemplateURLForKeyword(keyword); 956 const TemplateURL* template_url = GetTemplateURLForKeyword(keyword);
1008 957
1009 // TODO(sky): Once LocationBarView adds a listener to the TemplateURLService 958 // TODO(sky): Once LocationBarView adds a listener to the TemplateURLService
1010 // to track changes to the model, this should become a DCHECK. 959 // to track changes to the model, this should become a DCHECK.
1011 if (template_url) { 960 if (template_url) {
1012 *is_omnibox_api_extension_keyword = 961 *is_omnibox_api_extension_keyword =
1013 template_url->GetType() == TemplateURL::OMNIBOX_API_EXTENSION; 962 template_url->GetType() == TemplateURL::OMNIBOX_API_EXTENSION;
1014 return template_url->AdjustedShortNameForLocaleDirection(); 963 return template_url->AdjustedShortNameForLocaleDirection();
1015 } 964 }
1016 *is_omnibox_api_extension_keyword = false; 965 *is_omnibox_api_extension_keyword = false;
1017 return base::string16(); 966 return base::string16();
1018 } 967 }
1019 968
1020 void TemplateURLService::Observe(int type, 969 void TemplateURLService::Observe(int type,
1021 const content::NotificationSource& source, 970 const content::NotificationSource& source,
1022 const content::NotificationDetails& details) { 971 const content::NotificationDetails& details) {
1023 if (type == chrome::NOTIFICATION_HISTORY_URL_VISITED) { 972 if (type == chrome::NOTIFICATION_HISTORY_URL_VISITED) {
1024 content::Details<history::URLVisitedDetails> visit_details(details); 973 content::Details<history::URLVisitedDetails> visit_details(details);
1025 if (!loaded_) 974 if (!loaded_)
1026 visits_to_add_.push_back(*visit_details.ptr()); 975 visits_to_add_.push_back(*visit_details.ptr());
1027 else 976 else
1028 UpdateKeywordSearchTermsForURL(*visit_details.ptr()); 977 UpdateKeywordSearchTermsForURL(*visit_details.ptr());
1029 } else if (type == chrome::NOTIFICATION_DEFAULT_SEARCH_POLICY_CHANGED) {
1030 // Policy has been updated, so the default search prefs may be different.
1031 // Reload the default search provider from them.
1032 // TODO(pkasting): Rather than communicating via prefs, we should eventually
1033 // observe policy changes directly.
1034 UpdateDefaultSearch();
1035 } else { 978 } else {
1036 DCHECK_EQ(chrome::NOTIFICATION_GOOGLE_URL_UPDATED, type); 979 DCHECK_EQ(chrome::NOTIFICATION_GOOGLE_URL_UPDATED, type);
1037 if (loaded_) { 980 if (loaded_) {
1038 GoogleBaseURLChanged( 981 GoogleBaseURLChanged(
1039 content::Details<GoogleURLTracker::UpdatedDetails>(details)->first); 982 content::Details<GoogleURLTracker::UpdatedDetails>(details)->first);
1040 } 983 }
1041 } 984 }
1042 } 985 }
1043 986
1044 void TemplateURLService::Shutdown() { 987 void TemplateURLService::Shutdown() {
1045 // This check has to be done at Shutdown() instead of in the dtor to ensure 988 // This check has to be done at Shutdown() instead of in the dtor to ensure
1046 // that no clients of WebDataService are holding ptrs to it after the first 989 // that no clients of WebDataService are holding ptrs to it after the first
1047 // phase of the KeyedService Shutdown() process. 990 // phase of the KeyedService Shutdown() process.
1048 if (load_handle_) { 991 if (load_handle_) {
1049 DCHECK(service_.get()); 992 DCHECK(service_.get());
1050 service_->CancelRequest(load_handle_); 993 service_->CancelRequest(load_handle_);
1051 } 994 }
1052 service_ = NULL; 995 service_ = NULL;
1053 } 996 }
1054 997
1055 void TemplateURLService::OnSyncedDefaultSearchProviderGUIDChanged() {
1056 // Listen for changes to the default search from Sync.
1057 PrefService* prefs = GetPrefs();
1058 TemplateURL* new_default_search = GetTemplateURLForGUID(
1059 prefs->GetString(prefs::kSyncedDefaultSearchProviderGUID));
1060 if (new_default_search && !is_default_search_managed_) {
1061 if (new_default_search != GetDefaultSearchProvider()) {
1062 base::AutoReset<DefaultSearchChangeOrigin> change_origin(
1063 &dsp_change_origin_, DSP_CHANGE_SYNC_PREF);
1064 SetUserSelectedDefaultSearchProvider(new_default_search);
1065 pending_synced_default_search_ = false;
1066 }
1067 } else {
1068 // If it's not there, or if default search is currently managed, set a
1069 // flag to indicate that we waiting on the search engine entry to come
1070 // in through Sync.
1071 pending_synced_default_search_ = true;
1072 }
1073 UpdateDefaultSearch();
1074 }
1075
1076 syncer::SyncDataList TemplateURLService::GetAllSyncData( 998 syncer::SyncDataList TemplateURLService::GetAllSyncData(
1077 syncer::ModelType type) const { 999 syncer::ModelType type) const {
1078 DCHECK_EQ(syncer::SEARCH_ENGINES, type); 1000 DCHECK_EQ(syncer::SEARCH_ENGINES, type);
1079 1001
1080 syncer::SyncDataList current_data; 1002 syncer::SyncDataList current_data;
1081 for (TemplateURLVector::const_iterator iter = template_urls_.begin(); 1003 for (TemplateURLVector::const_iterator iter = template_urls_.begin();
1082 iter != template_urls_.end(); ++iter) { 1004 iter != template_urls_.end(); ++iter) {
1083 // We don't sync keywords managed by policy. 1005 // We don't sync keywords managed by policy.
1084 if ((*iter)->created_by_policy()) 1006 if ((*iter)->created_by_policy())
1085 continue; 1007 continue;
(...skipping 95 matching lines...) Expand 10 before | Expand all | Expand 10 after
1181 FROM_HERE, 1103 FROM_HERE,
1182 "ProcessSyncChanges failed on ChangeType ACTION_ADD"); 1104 "ProcessSyncChanges failed on ChangeType ACTION_ADD");
1183 continue; 1105 continue;
1184 } 1106 }
1185 const std::string guid = turl->sync_guid(); 1107 const std::string guid = turl->sync_guid();
1186 if (existing_keyword_turl) { 1108 if (existing_keyword_turl) {
1187 // Resolve any conflicts so we can safely add the new entry. 1109 // Resolve any conflicts so we can safely add the new entry.
1188 ResolveSyncKeywordConflict(turl.get(), existing_keyword_turl, 1110 ResolveSyncKeywordConflict(turl.get(), existing_keyword_turl,
1189 &new_changes); 1111 &new_changes);
1190 } 1112 }
1113 base::AutoReset<DefaultSearchChangeOrigin> change_origin(
1114 &dsp_change_origin_, DSP_CHANGE_SYNC_ADD);
1191 // Force the local ID to kInvalidTemplateURLID so we can add it. 1115 // Force the local ID to kInvalidTemplateURLID so we can add it.
1192 TemplateURLData data(turl->data()); 1116 TemplateURLData data(turl->data());
1193 data.id = kInvalidTemplateURLID; 1117 data.id = kInvalidTemplateURLID;
1194 Add(new TemplateURL(profile_, data)); 1118 TemplateURL* added = new TemplateURL(profile_, data);
1195 1119 if (Add(added))
1196 // Possibly set the newly added |turl| as the default search provider. 1120 MaybeUpdateDSEAfterSync(added);
1197 SetDefaultSearchProviderIfNewlySynced(guid);
1198 } else if (iter->change_type() == syncer::SyncChange::ACTION_UPDATE) { 1121 } else if (iter->change_type() == syncer::SyncChange::ACTION_UPDATE) {
1199 if (!existing_turl) { 1122 if (!existing_turl) {
1200 error = sync_error_factory_->CreateAndUploadError( 1123 error = sync_error_factory_->CreateAndUploadError(
1201 FROM_HERE, 1124 FROM_HERE,
1202 "ProcessSyncChanges failed on ChangeType ACTION_UPDATE"); 1125 "ProcessSyncChanges failed on ChangeType ACTION_UPDATE");
1203 continue; 1126 continue;
1204 } 1127 }
1205 if (existing_keyword_turl && (existing_keyword_turl != existing_turl)) { 1128 if (existing_keyword_turl && (existing_keyword_turl != existing_turl)) {
1206 // Resolve any conflicts with other entries so we can safely update the 1129 // Resolve any conflicts with other entries so we can safely update the
1207 // keyword. 1130 // keyword.
1208 ResolveSyncKeywordConflict(turl.get(), existing_keyword_turl, 1131 ResolveSyncKeywordConflict(turl.get(), existing_keyword_turl,
1209 &new_changes); 1132 &new_changes);
1210 } 1133 }
1211 UIThreadSearchTermsData search_terms_data(existing_turl->profile()); 1134 UIThreadSearchTermsData search_terms_data(existing_turl->profile());
1212 if (UpdateNoNotify(existing_turl, *turl, search_terms_data)) 1135 if (UpdateNoNotify(existing_turl, *turl, search_terms_data)) {
1213 NotifyObservers(); 1136 NotifyObservers();
1137 MaybeUpdateDSEAfterSync(existing_turl);
1138 }
1214 } else { 1139 } else {
1215 // We've unexpectedly received an ACTION_INVALID. 1140 // We've unexpectedly received an ACTION_INVALID.
1216 error = sync_error_factory_->CreateAndUploadError( 1141 error = sync_error_factory_->CreateAndUploadError(
1217 FROM_HERE, 1142 FROM_HERE,
1218 "ProcessSyncChanges received an ACTION_INVALID"); 1143 "ProcessSyncChanges received an ACTION_INVALID");
1219 } 1144 }
1220 } 1145 }
1221 1146
1222 // If something went wrong, we want to prematurely exit to avoid pushing 1147 // If something went wrong, we want to prematurely exit to avoid pushing
1223 // inconsistent data to Sync. We return the last error we received. 1148 // inconsistent data to Sync. We return the last error we received.
(...skipping 21 matching lines...) Expand all
1245 if (load_failed_) { 1170 if (load_failed_) {
1246 merge_result.set_error(syncer::SyncError( 1171 merge_result.set_error(syncer::SyncError(
1247 FROM_HERE, syncer::SyncError::DATATYPE_ERROR, 1172 FROM_HERE, syncer::SyncError::DATATYPE_ERROR,
1248 "Local database load failed.", syncer::SEARCH_ENGINES)); 1173 "Local database load failed.", syncer::SEARCH_ENGINES));
1249 return merge_result; 1174 return merge_result;
1250 } 1175 }
1251 1176
1252 sync_processor_ = sync_processor.Pass(); 1177 sync_processor_ = sync_processor.Pass();
1253 sync_error_factory_ = sync_error_factory.Pass(); 1178 sync_error_factory_ = sync_error_factory.Pass();
1254 1179
1255 // We just started syncing, so set our wait-for-default flag if we are
1256 // expecting a default from Sync.
1257 if (GetPrefs()) {
1258 std::string default_guid = GetPrefs()->GetString(
1259 prefs::kSyncedDefaultSearchProviderGUID);
1260 const TemplateURL* current_default = GetDefaultSearchProvider();
1261
1262 if (!default_guid.empty() &&
1263 (!current_default || current_default->sync_guid() != default_guid))
1264 pending_synced_default_search_ = true;
1265 }
1266
1267 // We do a lot of calls to Add/Remove/ResetTemplateURL here, so ensure we 1180 // We do a lot of calls to Add/Remove/ResetTemplateURL here, so ensure we
1268 // don't step on our own toes. 1181 // don't step on our own toes.
1269 base::AutoReset<bool> processing_changes(&processing_syncer_changes_, true); 1182 base::AutoReset<bool> processing_changes(&processing_syncer_changes_, true);
1270 1183
1271 // We've started syncing, so set our origin member to the base Sync value. 1184 // We've started syncing, so set our origin member to the base Sync value.
1272 // As we move through Sync Code, we may set this to increasingly specific 1185 // As we move through Sync Code, we may set this to increasingly specific
1273 // origins so we can tell what exactly caused a DSP change. 1186 // origins so we can tell what exactly caused a DSP change.
1274 base::AutoReset<DefaultSearchChangeOrigin> change_origin(&dsp_change_origin_, 1187 base::AutoReset<DefaultSearchChangeOrigin> change_origin(&dsp_change_origin_,
1275 DSP_CHANGE_SYNC_UNINTENTIONAL); 1188 DSP_CHANGE_SYNC_UNINTENTIONAL);
1276 1189
(...skipping 58 matching lines...) Expand 10 before | Expand all | Expand 10 after
1335 } else { 1248 } else {
1336 // The search engine from the cloud has not been synced locally. Merge it 1249 // The search engine from the cloud has not been synced locally. Merge it
1337 // into our local model. This will handle any conflicts with local (and 1250 // into our local model. This will handle any conflicts with local (and
1338 // already-synced) TemplateURLs. It will prefer to keep entries from Sync 1251 // already-synced) TemplateURLs. It will prefer to keep entries from Sync
1339 // over not-yet-synced TemplateURLs. 1252 // over not-yet-synced TemplateURLs.
1340 MergeInSyncTemplateURL(sync_turl.get(), sync_data_map, &new_changes, 1253 MergeInSyncTemplateURL(sync_turl.get(), sync_data_map, &new_changes,
1341 &local_data_map, &merge_result); 1254 &local_data_map, &merge_result);
1342 } 1255 }
1343 } 1256 }
1344 1257
1345 // If there is a pending synced default search provider that was processed
1346 // above, set it now.
1347 TemplateURL* pending_default = GetPendingSyncedDefaultSearchProvider();
1348 if (pending_default) {
1349 base::AutoReset<DefaultSearchChangeOrigin> change_origin(
1350 &dsp_change_origin_, DSP_CHANGE_SYNC_ADD);
1351 SetUserSelectedDefaultSearchProvider(pending_default);
1352 }
1353
1354 // The remaining SyncData in local_data_map should be everything that needs to 1258 // The remaining SyncData in local_data_map should be everything that needs to
1355 // be pushed as ADDs to sync. 1259 // be pushed as ADDs to sync.
1356 for (SyncDataMap::const_iterator iter = local_data_map.begin(); 1260 for (SyncDataMap::const_iterator iter = local_data_map.begin();
1357 iter != local_data_map.end(); ++iter) { 1261 iter != local_data_map.end(); ++iter) {
1358 new_changes.push_back( 1262 new_changes.push_back(
1359 syncer::SyncChange(FROM_HERE, 1263 syncer::SyncChange(FROM_HERE,
1360 syncer::SyncChange::ACTION_ADD, 1264 syncer::SyncChange::ACTION_ADD,
1361 iter->second)); 1265 iter->second));
1362 } 1266 }
1363 1267
(...skipping 231 matching lines...) Expand 10 before | Expand all | Expand 10 after
1595 profile_source); 1499 profile_source);
1596 notification_registrar_.Add(this, chrome::NOTIFICATION_GOOGLE_URL_UPDATED, 1500 notification_registrar_.Add(this, chrome::NOTIFICATION_GOOGLE_URL_UPDATED,
1597 profile_source); 1501 profile_source);
1598 pref_change_registrar_.Init(GetPrefs()); 1502 pref_change_registrar_.Init(GetPrefs());
1599 pref_change_registrar_.Add( 1503 pref_change_registrar_.Add(
1600 prefs::kSyncedDefaultSearchProviderGUID, 1504 prefs::kSyncedDefaultSearchProviderGUID,
1601 base::Bind( 1505 base::Bind(
1602 &TemplateURLService::OnSyncedDefaultSearchProviderGUIDChanged, 1506 &TemplateURLService::OnSyncedDefaultSearchProviderGUIDChanged,
1603 base::Unretained(this))); 1507 base::Unretained(this)));
1604 } 1508 }
1605 notification_registrar_.Add( 1509
1606 this, chrome::NOTIFICATION_DEFAULT_SEARCH_POLICY_CHANGED, 1510 DefaultSearchManager::Source source = DefaultSearchManager::FROM_USER;
1607 content::NotificationService::AllSources()); 1511 TemplateURLData* dse =
1512 default_search_manager_.GetDefaultSearchEngine(&source);
1513 ApplyDefaultSearchChange(dse, source);
1608 1514
1609 if (num_initializers > 0) { 1515 if (num_initializers > 0) {
1610 // This path is only hit by test code and is used to simulate a loaded 1516 // This path is only hit by test code and is used to simulate a loaded
1611 // TemplateURLService. 1517 // TemplateURLService.
1612 ChangeToLoadedState(); 1518 ChangeToLoadedState();
1613 1519
1614 // Add specific initializers, if any. 1520 // Add specific initializers, if any.
1615 WebDataService::KeywordBatchModeScoper keyword_scoper(service_.get()); 1521 WebDataService::KeywordBatchModeScoper keyword_scoper(service_.get());
1616 for (int i(0); i < num_initializers; ++i) { 1522 for (int i(0); i < num_initializers; ++i) {
1617 DCHECK(initializers[i].keyword); 1523 DCHECK(initializers[i].keyword);
1618 DCHECK(initializers[i].url); 1524 DCHECK(initializers[i].url);
1619 DCHECK(initializers[i].content); 1525 DCHECK(initializers[i].content);
1620 1526
1621 // TemplateURLService ends up owning the TemplateURL, don't try and free 1527 // TemplateURLService ends up owning the TemplateURL, don't try and free
1622 // it. 1528 // it.
1623 TemplateURLData data; 1529 TemplateURLData data;
1624 data.short_name = base::UTF8ToUTF16(initializers[i].content); 1530 data.short_name = base::UTF8ToUTF16(initializers[i].content);
1625 data.SetKeyword(base::UTF8ToUTF16(initializers[i].keyword)); 1531 data.SetKeyword(base::UTF8ToUTF16(initializers[i].keyword));
1626 data.SetURL(initializers[i].url); 1532 data.SetURL(initializers[i].url);
1627 TemplateURL* template_url = new TemplateURL(profile_, data); 1533 TemplateURL* template_url = new TemplateURL(profile_, data);
1628 AddNoNotify(template_url, true); 1534 AddNoNotify(template_url, true);
1629 1535
1630 // Set the first provided identifier to be the default. 1536 // Set the first provided identifier to be the default.
1631 if (i == 0) 1537 if (i == 0)
1632 SetDefaultSearchProviderNoNotify(template_url); 1538 default_search_manager_.SetUserSelectedDefaultSearchEngine(data);
1633 } 1539 }
1634 } 1540 }
1635 1541
1636 // Initialize default search.
1637 UpdateDefaultSearch();
1638
1639 // Request a server check for the correct Google URL if Google is the 1542 // Request a server check for the correct Google URL if Google is the
1640 // default search engine and not in headless mode. 1543 // default search engine and not in headless mode.
1641 if (profile_ && initial_default_search_provider_ && 1544 TemplateURL* default_search_provider = GetDefaultSearchProvider();
1642 initial_default_search_provider_->HasGoogleBaseURLs()) { 1545 if (profile_ && default_search_provider &&
1546 default_search_provider->HasGoogleBaseURLs()) {
1643 scoped_ptr<base::Environment> env(base::Environment::Create()); 1547 scoped_ptr<base::Environment> env(base::Environment::Create());
1644 if (!env->HasVar(env_vars::kHeadless)) 1548 if (!env->HasVar(env_vars::kHeadless))
1645 GoogleURLTracker::RequestServerCheck(profile_, false); 1549 GoogleURLTracker::RequestServerCheck(profile_, false);
1646 } 1550 }
1647 } 1551 }
1648 1552
1649 void TemplateURLService::RemoveFromMaps(TemplateURL* template_url) { 1553 void TemplateURLService::RemoveFromMaps(TemplateURL* template_url) {
1650 const base::string16& keyword = template_url->keyword(); 1554 const base::string16& keyword = template_url->keyword();
1651 DCHECK_NE(0U, keyword_to_template_map_.count(keyword)); 1555 DCHECK_NE(0U, keyword_to_template_map_.count(keyword));
1652 if (keyword_to_template_map_[keyword] == template_url) { 1556 if (keyword_to_template_map_[keyword] == template_url) {
(...skipping 92 matching lines...) Expand 10 before | Expand all | Expand 10 after
1745 // (possibly deleted) entry. 1649 // (possibly deleted) entry.
1746 urls->clear(); 1650 urls->clear();
1747 } 1651 }
1748 1652
1749 void TemplateURLService::ChangeToLoadedState() { 1653 void TemplateURLService::ChangeToLoadedState() {
1750 DCHECK(!loaded_); 1654 DCHECK(!loaded_);
1751 1655
1752 UIThreadSearchTermsData search_terms_data(profile_); 1656 UIThreadSearchTermsData search_terms_data(profile_);
1753 provider_map_->Init(template_urls_, search_terms_data); 1657 provider_map_->Init(template_urls_, search_terms_data);
1754 loaded_ = true; 1658 loaded_ = true;
1755 }
1756 1659
1757 void TemplateURLService::ClearDefaultProviderFromPrefs() { 1660 // This will cause a call to NotifyObservers().
1758 // We overwrite user preferences. If the default search engine is managed, 1661 ApplyDefaultSearchChange(initial_default_search_provider_ ?
1759 // there is no effect. 1662 &initial_default_search_provider_->data() : NULL,
1760 SaveDefaultSearchProviderToPrefs(NULL, GetPrefs()); 1663 default_search_provider_source_);
1761 // Default value for kDefaultSearchProviderEnabled is true. 1664 initial_default_search_provider_.reset();
1762 PrefService* prefs = GetPrefs(); 1665 on_loaded_callbacks_.Notify();
1763 if (prefs)
1764 prefs->SetBoolean(prefs::kDefaultSearchProviderEnabled, true);
1765 } 1666 }
1766 1667
1767 bool TemplateURLService::CanReplaceKeywordForHost( 1668 bool TemplateURLService::CanReplaceKeywordForHost(
1768 const std::string& host, 1669 const std::string& host,
1769 TemplateURL** to_replace) { 1670 TemplateURL** to_replace) {
1770 DCHECK(!to_replace || !*to_replace); 1671 DCHECK(!to_replace || !*to_replace);
1771 const TemplateURLSet* urls = provider_map_->GetURLsForHost(host); 1672 const TemplateURLSet* urls = provider_map_->GetURLsForHost(host);
1772 if (!urls) 1673 if (!urls)
1773 return true; 1674 return true;
1774 for (TemplateURLSet::const_iterator i(urls->begin()); i != urls->end(); ++i) { 1675 for (TemplateURLSet::const_iterator i(urls->begin()); i != urls->end(); ++i) {
(...skipping 76 matching lines...) Expand 10 before | Expand all | Expand 10 after
1851 } 1752 }
1852 } 1753 }
1853 } 1754 }
1854 if (!existing_turl->sync_guid().empty()) 1755 if (!existing_turl->sync_guid().empty())
1855 guid_to_template_map_[existing_turl->sync_guid()] = existing_turl; 1756 guid_to_template_map_[existing_turl->sync_guid()] = existing_turl;
1856 1757
1857 if (service_) 1758 if (service_)
1858 service_->UpdateKeyword(existing_turl->data()); 1759 service_->UpdateKeyword(existing_turl->data());
1859 1760
1860 // Inform sync of the update. 1761 // Inform sync of the update.
1861 ProcessTemplateURLChange(FROM_HERE, 1762 ProcessTemplateURLChange(
1862 existing_turl, 1763 FROM_HERE, existing_turl, syncer::SyncChange::ACTION_UPDATE);
1863 syncer::SyncChange::ACTION_UPDATE);
1864 1764
1865 if (default_search_provider_ == existing_turl) { 1765 if (default_search_provider_ == existing_turl &&
1866 bool success = SetDefaultSearchProviderNoNotify(existing_turl); 1766 default_search_provider_source_ == DefaultSearchManager::FROM_USER) {
1867 DCHECK(success); 1767 default_search_manager_.SetUserSelectedDefaultSearchEngine(
1768 default_search_provider_->data());
1868 } 1769 }
1869 return true; 1770 return true;
1870 } 1771 }
1871 1772
1872 // static 1773 // static
1873 void TemplateURLService::UpdateTemplateURLIfPrepopulated( 1774 void TemplateURLService::UpdateTemplateURLIfPrepopulated(
1874 TemplateURL* template_url, 1775 TemplateURL* template_url,
1875 Profile* profile) { 1776 Profile* profile) {
1876 int prepopulate_id = template_url->prepopulate_id(); 1777 int prepopulate_id = template_url->prepopulate_id();
1877 if (template_url->prepopulate_id() == 0) 1778 if (template_url->prepopulate_id() == 0)
1878 return; 1779 return;
1879 1780
1880 size_t default_search_index; 1781 size_t default_search_index;
1881 ScopedVector<TemplateURLData> prepopulated_urls = 1782 ScopedVector<TemplateURLData> prepopulated_urls =
1882 TemplateURLPrepopulateData::GetPrepopulatedEngines( 1783 TemplateURLPrepopulateData::GetPrepopulatedEngines(
1883 profile ? profile->GetPrefs() : NULL, &default_search_index); 1784 profile ? profile->GetPrefs() : NULL, &default_search_index);
1884 1785
1885 for (size_t i = 0; i < prepopulated_urls.size(); ++i) { 1786 for (size_t i = 0; i < prepopulated_urls.size(); ++i) {
1886 if (prepopulated_urls[i]->prepopulate_id == prepopulate_id) { 1787 if (prepopulated_urls[i]->prepopulate_id == prepopulate_id) {
1887 MergeIntoPrepopulatedEngineData(template_url, prepopulated_urls[i]); 1788 MergeIntoPrepopulatedEngineData(template_url, prepopulated_urls[i]);
1888 template_url->CopyFrom(TemplateURL(profile, *prepopulated_urls[i])); 1789 template_url->CopyFrom(TemplateURL(profile, *prepopulated_urls[i]));
1889 } 1790 }
1890 } 1791 }
1891 } 1792 }
1892 1793
1794 void TemplateURLService::MaybeUpdateDSEAfterSync(TemplateURL* synced_turl) {
1795 if (GetPrefs() &&
1796 (synced_turl->sync_guid() ==
1797 GetPrefs()->GetString(prefs::kSyncedDefaultSearchProviderGUID))) {
1798 default_search_manager_.SetUserSelectedDefaultSearchEngine(
1799 synced_turl->data());
1800 }
1801 }
1802
1893 PrefService* TemplateURLService::GetPrefs() { 1803 PrefService* TemplateURLService::GetPrefs() {
1894 return profile_ ? profile_->GetPrefs() : NULL; 1804 return profile_ ? profile_->GetPrefs() : NULL;
1895 } 1805 }
1896 1806
1897 void TemplateURLService::UpdateKeywordSearchTermsForURL( 1807 void TemplateURLService::UpdateKeywordSearchTermsForURL(
1898 const history::URLVisitedDetails& details) { 1808 const history::URLVisitedDetails& details) {
1899 const history::URLRow& row = details.row; 1809 const history::URLRow& row = details.row;
1900 if (!row.url().is_valid()) 1810 if (!row.url().is_valid())
1901 return; 1811 return;
1902 1812
(...skipping 77 matching lines...) Expand 10 before | Expand all | Expand 10 after
1980 // need to reset the keyword to an appropriate local value when this 1890 // need to reset the keyword to an appropriate local value when this
1981 // change arrives; see CreateTemplateURLFromTemplateURLAndSyncData(). 1891 // change arrives; see CreateTemplateURLFromTemplateURLAndSyncData().
1982 UpdateNoNotify(t_url, updated_turl, 1892 UpdateNoNotify(t_url, updated_turl,
1983 OldBaseURLSearchTermsData(t_url->profile(), old_base_url.spec())); 1893 OldBaseURLSearchTermsData(t_url->profile(), old_base_url.spec()));
1984 } 1894 }
1985 } 1895 }
1986 if (something_changed) 1896 if (something_changed)
1987 NotifyObservers(); 1897 NotifyObservers();
1988 } 1898 }
1989 1899
1990 void TemplateURLService::UpdateDefaultSearch() { 1900 void TemplateURLService::OnDefaultSearchChange(
1901 const TemplateURLData* data,
1902 DefaultSearchManager::Source source) {
1903 if (GetPrefs() && (source == DefaultSearchManager::FROM_USER) &&
1904 ((source != default_search_provider_source_) ||
1905 !IdenticalSyncGUIDs(data, GetDefaultSearchProvider()))) {
1906 GetPrefs()->SetString(prefs::kSyncedDefaultSearchProviderGUID,
1907 data->sync_guid);
1908 }
1909 ApplyDefaultSearchChange(data, source);
1910 }
1911
1912 void TemplateURLService::ApplyDefaultSearchChange(
1913 const TemplateURLData* data,
1914 DefaultSearchManager::Source source) {
1991 if (!loaded_) { 1915 if (!loaded_) {
1992 // Set |initial_default_search_provider_| from the preferences. We use this 1916 // Set |initial_default_search_provider_| from the preferences. This is
1993 // value for default search provider until the database has been loaded. 1917 // mainly so we can hold ownership until we get to the point where the list
1994 scoped_ptr<TemplateURLData> data; 1918 // of keywords from Web Data is the owner of everything including the
1995 if (!LoadDefaultSearchProviderFromPrefs( 1919 // default.
1996 GetPrefs(), &data, &is_default_search_managed_)) { 1920 initial_default_search_provider_.reset(
1997 // Prefs does not specify, so rely on the prepopulated engines. This 1921 data ? new TemplateURL(profile_, *data) : NULL);
1998 // should happen only the first time Chrome is started. 1922 default_search_provider_source_ = source;
1999 data = 1923 return;
2000 TemplateURLPrepopulateData::GetPrepopulatedDefaultSearch(GetPrefs()); 1924 }
2001 is_default_search_managed_ = false; 1925
1926 // Prevent recursion if we update the value stored in default_search_manager_.
1927 // Note that we exclude the case of data == NULL because that could cause a
1928 // false positive for recursion when the initial_default_search_provider_ is
1929 // NULL due to policy. We'll never actually get recursion with data == NULL.
1930 if (source == default_search_provider_source_ && data != NULL &&
1931 TemplateURL::MatchesData(default_search_provider_, data))
1932 return;
1933
1934 UMA_HISTOGRAM_ENUMERATION("Search.DefaultSearchChangeOrigin",
1935 dsp_change_origin_, DSP_CHANGE_MAX);
1936
1937 WebDataService::KeywordBatchModeScoper keyword_scoper(service_.get());
1938 if (default_search_provider_source_ == DefaultSearchManager::FROM_POLICY ||
1939 source == DefaultSearchManager::FROM_POLICY) {
1940 // We do this both to remove any no-longer-applicable policy-defined DSE as
1941 // well as to add the new one, if appropriate.
1942 UpdateProvidersCreatedByPolicy(
1943 &template_urls_,
1944 source == DefaultSearchManager::FROM_POLICY ? data : NULL);
1945 }
1946
1947 if (!data) {
1948 default_search_provider_ = NULL;
1949 default_search_provider_source_ = source;
1950 NotifyObservers();
1951 return;
1952 }
1953
1954 if (source == DefaultSearchManager::FROM_EXTENSION) {
1955 default_search_provider_ = FindMatchingExtensionTemplateURL(
1956 *data, TemplateURL::NORMAL_CONTROLLED_BY_EXTENSION);
1957 }
1958
1959 if (source == DefaultSearchManager::FROM_FALLBACK) {
1960 default_search_provider_ =
1961 FindPrepopulatedTemplateURL(data->prepopulate_id);
1962 if (default_search_provider_) {
1963 TemplateURLData update_data(*data);
1964 update_data.sync_guid = default_search_provider_->sync_guid();
1965 if (!default_search_provider_->safe_for_autoreplace()) {
1966 update_data.safe_for_autoreplace = false;
1967 update_data.SetKeyword(default_search_provider_->keyword());
1968 update_data.short_name = default_search_provider_->short_name();
1969 }
1970 UIThreadSearchTermsData search_terms_data(
1971 default_search_provider_->profile());
1972 UpdateNoNotify(default_search_provider_,
1973 TemplateURL(profile_, update_data),
1974 search_terms_data);
1975 } else {
1976 // Normally the prepopulated fallback should be present in
1977 // |template_urls_|, but in a few cases it might not be:
1978 // (1) Tests that initialize the TemplateURLService in peculiar ways.
1979 // (2) If the user deleted the pre-populated default and we subsequently
1980 // lost their user-selected value.
1981 TemplateURL* new_dse = new TemplateURL(profile_, *data);
1982 if (AddNoNotify(new_dse, true))
1983 default_search_provider_ = new_dse;
1984 }
1985 }
1986 if (source == DefaultSearchManager::FROM_USER) {
1987 default_search_provider_ = GetTemplateURLForGUID(data->sync_guid);
1988 if (!default_search_provider_ && data->prepopulate_id) {
1989 default_search_provider_ =
1990 FindPrepopulatedTemplateURL(data->prepopulate_id);
1991 }
1992 TemplateURLData new_data(*data);
1993 new_data.show_in_default_list = true;
1994 if (default_search_provider_) {
1995 UIThreadSearchTermsData search_terms_data(
1996 default_search_provider_->profile());
1997 UpdateNoNotify(default_search_provider_,
1998 TemplateURL(profile_, new_data),
1999 search_terms_data);
2000 } else {
2001 new_data.id = kInvalidTemplateURLID;
2002 TemplateURL* new_dse = new TemplateURL(profile_, new_data);
2003 if (AddNoNotify(new_dse, true))
2004 default_search_provider_ = new_dse;
2005 }
2006 if (default_search_provider_ && GetPrefs()) {
2007 GetPrefs()->SetString(
2008 prefs::kSyncedDefaultSearchProviderGUID,
2009 default_search_provider_->sync_guid());
2002 } 2010 }
2003 2011
2004 initial_default_search_provider_.reset( 2012 }
2005 data ? new TemplateURL(profile_, *data) : NULL);
2006 2013
2007 return; 2014 default_search_provider_source_ = source;
2015
2016 if (default_search_provider_ &&
2017 default_search_provider_->HasGoogleBaseURLs()) {
2018 if (profile_)
2019 GoogleURLTracker::RequestServerCheck(profile_, false);
2020 #if defined(ENABLE_RLZ)
2021 RLZTracker::RecordProductEvent(rlz_lib::CHROME,
2022 RLZTracker::CHROME_OMNIBOX,
2023 rlz_lib::SET_TO_GOOGLE);
2024 #endif
2008 } 2025 }
2009 // Load the default search specified in prefs.
2010 scoped_ptr<TemplateURLData> new_default_from_prefs;
2011 bool new_is_default_managed = false;
2012 // Load the default from prefs. It's possible that it won't succeed
2013 // because we are in the middle of doing SaveDefaultSearchProviderToPrefs()
2014 // and all the preference items have not been saved. In that case, we
2015 // don't have yet a default. It would be much better if we could save
2016 // preferences in batches and trigger notifications at the end.
2017 LoadDefaultSearchProviderFromPrefs(
2018 GetPrefs(), &new_default_from_prefs, &new_is_default_managed);
2019 if (!is_default_search_managed_ && !new_is_default_managed) {
2020 // We're not interested in cases where the default was and remains
2021 // unmanaged. In that case, preferences have no impact on the default.
2022 return;
2023 }
2024 WebDataService::KeywordBatchModeScoper keyword_scoper(service_.get());
2025 if (is_default_search_managed_ && new_is_default_managed) {
2026 // The default was managed and remains managed. Update the default only
2027 // if it has changed; we don't want to respond to changes triggered by
2028 // SaveDefaultSearchProviderToPrefs.
2029 if (TemplateURL::MatchesData(default_search_provider_,
2030 new_default_from_prefs.get()))
2031 return;
2032 if (!new_default_from_prefs) {
2033 // |default_search_provider_| can't be NULL or MatchesData() would have
2034 // returned true. Remove this now invalid value.
2035 TemplateURL* old_default = default_search_provider_;
2036 bool success = SetDefaultSearchProviderNoNotify(NULL);
2037 DCHECK(success);
2038 RemoveNoNotify(old_default);
2039 } else if (default_search_provider_) {
2040 new_default_from_prefs->created_by_policy = true;
2041 TemplateURL new_values(profile_, *new_default_from_prefs);
2042 UIThreadSearchTermsData search_terms_data(
2043 default_search_provider_->profile());
2044 UpdateNoNotify(default_search_provider_, new_values, search_terms_data);
2045 } else {
2046 TemplateURL* new_template = NULL;
2047 if (new_default_from_prefs) {
2048 new_default_from_prefs->created_by_policy = true;
2049 new_template = new TemplateURL(profile_, *new_default_from_prefs);
2050 if (!AddNoNotify(new_template, true))
2051 return;
2052 }
2053 bool success = SetDefaultSearchProviderNoNotify(new_template);
2054 DCHECK(success);
2055 }
2056 } else if (!is_default_search_managed_ && new_is_default_managed) {
2057 // The default used to be unmanaged and is now managed. Add the new
2058 // managed default to the list of URLs and set it as default.
2059 is_default_search_managed_ = new_is_default_managed;
2060 TemplateURL* new_template = NULL;
2061 if (new_default_from_prefs) {
2062 new_default_from_prefs->created_by_policy = true;
2063 new_template = new TemplateURL(profile_, *new_default_from_prefs);
2064 if (!AddNoNotify(new_template, true))
2065 return;
2066 }
2067 bool success = SetDefaultSearchProviderNoNotify(new_template);
2068 DCHECK(success);
2069 } else {
2070 // The default was managed and is no longer.
2071 DCHECK(is_default_search_managed_ && !new_is_default_managed);
2072 is_default_search_managed_ = new_is_default_managed;
2073 // If we had a default, delete the previous default if created by policy
2074 // and set a likely default.
2075 if ((default_search_provider_ != NULL) &&
2076 default_search_provider_->created_by_policy()) {
2077 TemplateURL* old_default = default_search_provider_;
2078 default_search_provider_ = NULL;
2079 RemoveNoNotify(old_default);
2080 }
2081 2026
2082 // The likely default should be from Sync if we were waiting on Sync.
2083 // Otherwise, it should be FindNewDefaultSearchProvider.
2084 TemplateURL* synced_default = GetPendingSyncedDefaultSearchProvider();
2085 if (synced_default) {
2086 pending_synced_default_search_ = false;
2087
2088 base::AutoReset<DefaultSearchChangeOrigin> change_origin(
2089 &dsp_change_origin_, DSP_CHANGE_SYNC_NOT_MANAGED);
2090 SetDefaultSearchProviderNoNotify(synced_default);
2091 } else {
2092 SetDefaultSearchProviderNoNotify(FindNewDefaultSearchProvider());
2093 }
2094 }
2095 NotifyObservers(); 2027 NotifyObservers();
2096 } 2028 }
2097 2029
2098 void TemplateURLService::SetDefaultSearchProvider(
2099 TemplateURL* url) {
2100 DCHECK(!is_default_search_managed_);
2101 // Omnibox keywords cannot be made default. Extension-controlled search
2102 // engines can be made default only by the extension itself because they
2103 // aren't persisted.
2104 DCHECK(!url || (url->GetType() == TemplateURL::NORMAL));
2105
2106 // Always persist the setting in the database, that way if the backup
2107 // signature has changed out from under us it gets reset correctly.
2108 if (SetDefaultSearchProviderNoNotify(url))
2109 NotifyObservers();
2110 }
2111
2112 bool TemplateURLService::SetDefaultSearchProviderNoNotify(TemplateURL* url) {
2113 if (url) {
2114 if (std::find(template_urls_.begin(), template_urls_.end(), url) ==
2115 template_urls_.end())
2116 return false;
2117 // Omnibox keywords cannot be made default.
2118 DCHECK_NE(TemplateURL::OMNIBOX_API_EXTENSION, url->GetType());
2119 }
2120
2121 // Only bother reassigning |url| if it has changed. Notice that we don't just
2122 // early exit if they are equal, because |url| may have had its fields
2123 // changed, and needs to be persisted below (for example, when this is called
2124 // from UpdateNoNotify).
2125 if (default_search_provider_ != url) {
2126 // Engines set by policy override extension-controlled engines, which
2127 // override other engines.
2128 DCHECK(!is_default_search_managed() || !url ||
2129 (url->GetType() == TemplateURL::NORMAL));
2130 if (is_default_search_managed() || !default_search_provider_ ||
2131 (default_search_provider_->GetType() == TemplateURL::NORMAL) ||
2132 (url &&
2133 (url->GetType() == TemplateURL::NORMAL_CONTROLLED_BY_EXTENSION))){
2134 UMA_HISTOGRAM_ENUMERATION("Search.DefaultSearchChangeOrigin",
2135 dsp_change_origin_, DSP_CHANGE_MAX);
2136 default_search_provider_ = url;
2137 }
2138 }
2139
2140 if (url) {
2141 // Don't mark the url as edited, otherwise we won't be able to rev the
2142 // template urls we ship with.
2143 url->data_.show_in_default_list = true;
2144 if (service_ && (url->GetType() == TemplateURL::NORMAL))
2145 service_->UpdateKeyword(url->data());
2146
2147 if (url->HasGoogleBaseURLs()) {
2148 GoogleURLTracker::RequestServerCheck(profile_, false);
2149 #if defined(ENABLE_RLZ)
2150 RLZTracker::RecordProductEvent(rlz_lib::CHROME,
2151 RLZTracker::CHROME_OMNIBOX,
2152 rlz_lib::SET_TO_GOOGLE);
2153 #endif
2154 }
2155 }
2156
2157 // Extension-controlled search engines shouldn't be persisted anywhere.
2158 if (url && (url->GetType() == TemplateURL::NORMAL_CONTROLLED_BY_EXTENSION))
2159 return true;
2160
2161 if (!is_default_search_managed_) {
2162 SaveDefaultSearchProviderToPrefs(url, GetPrefs());
2163
2164 // If we are syncing, we want to set the synced pref that will notify other
2165 // instances to change their default to this new search provider.
2166 // Note: we don't update the pref if we're currently in the middle of
2167 // handling a sync operation. Sync operations from other clients are not
2168 // guaranteed to arrive together, and any client that deletes the default
2169 // needs to set a new default as well. If we update the default here, we're
2170 // likely to race with the update from the other client, resulting in
2171 // a possibly random default search provider.
2172 if (sync_processor_.get() && url && !url->sync_guid().empty() &&
2173 GetPrefs() && !processing_syncer_changes_) {
2174 GetPrefs()->SetString(prefs::kSyncedDefaultSearchProviderGUID,
2175 url->sync_guid());
2176 }
2177 }
2178
2179 if (service_)
2180 service_->SetDefaultSearchProviderID(url ? url->id() : 0);
2181
2182 // Inform sync the change to the show_in_default_list flag.
2183 if (url)
2184 ProcessTemplateURLChange(FROM_HERE,
2185 url,
2186 syncer::SyncChange::ACTION_UPDATE);
2187 return true;
2188 }
2189
2190 bool TemplateURLService::AddNoNotify(TemplateURL* template_url, 2030 bool TemplateURLService::AddNoNotify(TemplateURL* template_url,
2191 bool newly_adding) { 2031 bool newly_adding) {
2192 DCHECK(template_url); 2032 DCHECK(template_url);
2193 2033
2194 if (newly_adding) { 2034 if (newly_adding) {
2195 DCHECK_EQ(kInvalidTemplateURLID, template_url->id()); 2035 DCHECK_EQ(kInvalidTemplateURLID, template_url->id());
2196 DCHECK(std::find(template_urls_.begin(), template_urls_.end(), 2036 DCHECK(std::find(template_urls_.begin(), template_urls_.end(),
2197 template_url) == template_urls_.end()); 2037 template_url) == template_urls_.end());
2198 template_url->data_.id = ++next_id_; 2038 template_url->data_.id = ++next_id_;
2199 } 2039 }
(...skipping 92 matching lines...) Expand 10 before | Expand all | Expand 10 after
2292 TemplateURLData data(url->data()); 2132 TemplateURLData data(url->data());
2293 data.short_name = title; 2133 data.short_name = title;
2294 data.SetKeyword(keyword); 2134 data.SetKeyword(keyword);
2295 if (search_url != data.url()) { 2135 if (search_url != data.url()) {
2296 data.SetURL(search_url); 2136 data.SetURL(search_url);
2297 // The urls have changed, reset the favicon url. 2137 // The urls have changed, reset the favicon url.
2298 data.favicon_url = GURL(); 2138 data.favicon_url = GURL();
2299 } 2139 }
2300 data.safe_for_autoreplace = false; 2140 data.safe_for_autoreplace = false;
2301 data.last_modified = time_provider_(); 2141 data.last_modified = time_provider_();
2302 TemplateURL new_url(url->profile(), data);
2303 UIThreadSearchTermsData search_terms_data(url->profile()); 2142 UIThreadSearchTermsData search_terms_data(url->profile());
2304 return UpdateNoNotify(url, new_url, search_terms_data); 2143 return UpdateNoNotify(url, TemplateURL(profile_, data), search_terms_data);
2305 } 2144 }
2306 2145
2307 void TemplateURLService::NotifyObservers() { 2146 void TemplateURLService::NotifyObservers() {
2308 if (!loaded_) 2147 if (!loaded_)
2309 return; 2148 return;
2310 2149
2311 FOR_EACH_OBSERVER(TemplateURLServiceObserver, model_observers_, 2150 FOR_EACH_OBSERVER(TemplateURLServiceObserver, model_observers_,
2312 OnTemplateURLServiceChanged()); 2151 OnTemplateURLServiceChanged());
2313 } 2152 }
2314 2153
2315 // |template_urls| are the TemplateURLs loaded from the database. 2154 // |template_urls| are the TemplateURLs loaded from the database.
2316 // |default_search_provider| points to one of them, if it was set in the db. 2155 // |default_from_prefs| is the default search provider from the preferences, or
2317 // |default_from_prefs| is the default search provider from the preferences. 2156 // NULL if the DSE is not policy-defined.
2318 // Check |is_default_search_managed_| to determine if it was set by policy.
2319 // 2157 //
2320 // This function removes from the vector and the database all the TemplateURLs 2158 // This function removes from the vector and the database all the TemplateURLs
2321 // that were set by policy, unless it is the current default search provider 2159 // that were set by policy, unless it is the current default search provider, in
2322 // and matches what is set by a managed preference. 2160 // which case it is updated with the data from prefs.
2323 void TemplateURLService::RemoveProvidersCreatedByPolicy( 2161 void TemplateURLService::UpdateProvidersCreatedByPolicy(
2324 TemplateURLVector* template_urls, 2162 TemplateURLVector* template_urls,
2325 TemplateURL** default_search_provider, 2163 const TemplateURLData* default_from_prefs) {
2326 TemplateURLData* default_from_prefs) {
2327 DCHECK(template_urls); 2164 DCHECK(template_urls);
2328 DCHECK(default_search_provider); 2165
2329 for (TemplateURLVector::iterator i = template_urls->begin(); 2166 for (TemplateURLVector::iterator i = template_urls->begin();
2330 i != template_urls->end(); ) { 2167 i != template_urls->end(); ) {
2331 TemplateURL* template_url = *i; 2168 TemplateURL* template_url = *i;
2332 if (template_url->created_by_policy()) { 2169 if (template_url->created_by_policy()) {
2333 if (template_url == *default_search_provider && 2170 if (default_from_prefs &&
2334 is_default_search_managed_ &&
2335 TemplateURL::MatchesData(template_url, default_from_prefs)) { 2171 TemplateURL::MatchesData(template_url, default_from_prefs)) {
2336 // If the database specified a default search provider that was set 2172 // If the database specified a default search provider that was set
2337 // by policy, and the default search provider from the preferences 2173 // by policy, and the default search provider from the preferences
2338 // is also set by policy and they are the same, keep the entry in the 2174 // is also set by policy and they are the same, keep the entry in the
2339 // database and the |default_search_provider|. 2175 // database and the |default_search_provider|.
2176 default_search_provider_ = template_url;
2177 // Prevent us from saving any other entries, or creating a new one.
2178 default_from_prefs = NULL;
2340 ++i; 2179 ++i;
2341 continue; 2180 continue;
2342 } 2181 }
2343 2182
2344 // The database loaded a managed |default_search_provider|, but it has 2183 RemoveFromMaps(template_url);
2345 // been updated in the prefs. Remove it from the database, and update the
2346 // |default_search_provider| pointer here.
2347 if (*default_search_provider &&
2348 (*default_search_provider)->id() == template_url->id())
2349 *default_search_provider = NULL;
2350
2351 i = template_urls->erase(i); 2184 i = template_urls->erase(i);
2352 if (service_) 2185 if (service_)
2353 service_->RemoveKeyword(template_url->id()); 2186 service_->RemoveKeyword(template_url->id());
2354 delete template_url; 2187 delete template_url;
2355 } else { 2188 } else {
2356 ++i; 2189 ++i;
2357 } 2190 }
2358 } 2191 }
2192
2193 if (default_from_prefs) {
2194 default_search_provider_ = NULL;
2195 default_search_provider_source_ = DefaultSearchManager::FROM_POLICY;
2196 TemplateURLData new_data(*default_from_prefs);
2197 new_data.created_by_policy = true;
2198 TemplateURL* new_dse = new TemplateURL(profile_, new_data);
2199 if (AddNoNotify(new_dse, true))
2200 default_search_provider_ = new_dse;
2201 }
2359 } 2202 }
2360 2203
2361 void TemplateURLService::ResetTemplateURLGUID(TemplateURL* url, 2204 void TemplateURLService::ResetTemplateURLGUID(TemplateURL* url,
2362 const std::string& guid) { 2205 const std::string& guid) {
2363 DCHECK(loaded_); 2206 DCHECK(loaded_);
2364 DCHECK(!guid.empty()); 2207 DCHECK(!guid.empty());
2365 2208
2366 TemplateURLData data(url->data()); 2209 TemplateURLData data(url->data());
2367 data.sync_guid = guid; 2210 data.sync_guid = guid;
2368 TemplateURL new_url(url->profile(), data);
2369 UIThreadSearchTermsData search_terms_data(url->profile()); 2211 UIThreadSearchTermsData search_terms_data(url->profile());
2370 UpdateNoNotify(url, new_url, search_terms_data); 2212 UpdateNoNotify(url, TemplateURL(profile_, data), search_terms_data);
2371 } 2213 }
2372 2214
2373 base::string16 TemplateURLService::UniquifyKeyword(const TemplateURL& turl, 2215 base::string16 TemplateURLService::UniquifyKeyword(const TemplateURL& turl,
2374 bool force) { 2216 bool force) {
2375 if (!force) { 2217 if (!force) {
2376 // Already unique. 2218 // Already unique.
2377 if (!GetTemplateURLForKeyword(turl.keyword())) 2219 if (!GetTemplateURLForKeyword(turl.keyword()))
2378 return turl.keyword(); 2220 return turl.keyword();
2379 2221
2380 // First, try to return the generated keyword for the TemplateURL (except 2222 // First, try to return the generated keyword for the TemplateURL (except
(...skipping 50 matching lines...) Expand 10 before | Expand all | Expand 10 after
2431 base::string16 new_keyword = UniquifyKeyword(*loser, false); 2273 base::string16 new_keyword = UniquifyKeyword(*loser, false);
2432 DCHECK(!GetTemplateURLForKeyword(new_keyword)); 2274 DCHECK(!GetTemplateURLForKeyword(new_keyword));
2433 if (applied_turl_is_better) { 2275 if (applied_turl_is_better) {
2434 // Just set the keyword of |unapplied_sync_turl|. The caller is responsible 2276 // Just set the keyword of |unapplied_sync_turl|. The caller is responsible
2435 // for adding or updating unapplied_sync_turl in the local model. 2277 // for adding or updating unapplied_sync_turl in the local model.
2436 unapplied_sync_turl->data_.SetKeyword(new_keyword); 2278 unapplied_sync_turl->data_.SetKeyword(new_keyword);
2437 } else { 2279 } else {
2438 // Update |applied_sync_turl| in the local model with the new keyword. 2280 // Update |applied_sync_turl| in the local model with the new keyword.
2439 TemplateURLData data(applied_sync_turl->data()); 2281 TemplateURLData data(applied_sync_turl->data());
2440 data.SetKeyword(new_keyword); 2282 data.SetKeyword(new_keyword);
2441 TemplateURL new_turl(applied_sync_turl->profile(), data);
2442 UIThreadSearchTermsData search_terms_data(applied_sync_turl->profile()); 2283 UIThreadSearchTermsData search_terms_data(applied_sync_turl->profile());
2443 if (UpdateNoNotify(applied_sync_turl, new_turl, search_terms_data)) 2284 if (UpdateNoNotify(
2285 applied_sync_turl, TemplateURL(profile_, data), search_terms_data))
2444 NotifyObservers(); 2286 NotifyObservers();
2445 } 2287 }
2446 // The losing TemplateURL should have their keyword updated. Send a change to 2288 // The losing TemplateURL should have their keyword updated. Send a change to
2447 // the server to reflect this change. 2289 // the server to reflect this change.
2448 syncer::SyncData sync_data = CreateSyncDataFromTemplateURL(*loser); 2290 syncer::SyncData sync_data = CreateSyncDataFromTemplateURL(*loser);
2449 change_list->push_back(syncer::SyncChange(FROM_HERE, 2291 change_list->push_back(syncer::SyncChange(FROM_HERE,
2450 syncer::SyncChange::ACTION_UPDATE, 2292 syncer::SyncChange::ACTION_UPDATE,
2451 sync_data)); 2293 sync_data));
2452 } 2294 }
2453 2295
(...skipping 28 matching lines...) Expand all
2482 // |conflicting_turl| is not yet known to Sync. If it is better, then we 2324 // |conflicting_turl| is not yet known to Sync. If it is better, then we
2483 // want to transfer its values up to sync. Otherwise, we remove it and 2325 // want to transfer its values up to sync. Otherwise, we remove it and
2484 // allow the entry from Sync to overtake it in the model. 2326 // allow the entry from Sync to overtake it in the model.
2485 const std::string guid = conflicting_turl->sync_guid(); 2327 const std::string guid = conflicting_turl->sync_guid();
2486 if (IsLocalTemplateURLBetter(conflicting_turl, sync_turl)) { 2328 if (IsLocalTemplateURLBetter(conflicting_turl, sync_turl)) {
2487 ResetTemplateURLGUID(conflicting_turl, sync_turl->sync_guid()); 2329 ResetTemplateURLGUID(conflicting_turl, sync_turl->sync_guid());
2488 syncer::SyncData sync_data = 2330 syncer::SyncData sync_data =
2489 CreateSyncDataFromTemplateURL(*conflicting_turl); 2331 CreateSyncDataFromTemplateURL(*conflicting_turl);
2490 change_list->push_back(syncer::SyncChange( 2332 change_list->push_back(syncer::SyncChange(
2491 FROM_HERE, syncer::SyncChange::ACTION_UPDATE, sync_data)); 2333 FROM_HERE, syncer::SyncChange::ACTION_UPDATE, sync_data));
2492 if (conflicting_turl == GetDefaultSearchProvider() &&
2493 !pending_synced_default_search_) {
2494 // If we're not waiting for the Synced default to come in, we should
2495 // override the pref with our new GUID. If we are waiting for the
2496 // arrival of a synced default, setting the pref here would cause us
2497 // to lose the GUID we are waiting on.
2498 PrefService* prefs = GetPrefs();
2499 if (prefs) {
2500 prefs->SetString(prefs::kSyncedDefaultSearchProviderGUID,
2501 conflicting_turl->sync_guid());
2502 }
2503 }
2504 // Note that in this case we do not add the Sync TemplateURL to the 2334 // Note that in this case we do not add the Sync TemplateURL to the
2505 // local model, since we've effectively "merged" it in by updating the 2335 // local model, since we've effectively "merged" it in by updating the
2506 // local conflicting entry with its sync_guid. 2336 // local conflicting entry with its sync_guid.
2507 should_add_sync_turl = false; 2337 should_add_sync_turl = false;
2508 merge_result->set_num_items_modified( 2338 merge_result->set_num_items_modified(
2509 merge_result->num_items_modified() + 1); 2339 merge_result->num_items_modified() + 1);
2510 } else { 2340 } else {
2511 // We guarantee that this isn't the local search provider. Otherwise, 2341 // We guarantee that this isn't the local search provider. Otherwise,
2512 // local would have won. 2342 // local would have won.
2513 DCHECK(conflicting_turl != GetDefaultSearchProvider()); 2343 DCHECK(conflicting_turl != GetDefaultSearchProvider());
2514 Remove(conflicting_turl); 2344 Remove(conflicting_turl);
2515 merge_result->set_num_items_deleted( 2345 merge_result->set_num_items_deleted(
2516 merge_result->num_items_deleted() + 1); 2346 merge_result->num_items_deleted() + 1);
2517 } 2347 }
2518 // This TemplateURL was either removed or overwritten in the local model. 2348 // This TemplateURL was either removed or overwritten in the local model.
2519 // Remove the entry from the local data so it isn't pushed up to Sync. 2349 // Remove the entry from the local data so it isn't pushed up to Sync.
2520 local_data->erase(guid); 2350 local_data->erase(guid);
2521 } 2351 }
2522 } 2352 }
2523 2353
2524 if (should_add_sync_turl) { 2354 if (should_add_sync_turl) {
2525 // Force the local ID to kInvalidTemplateURLID so we can add it. 2355 // Force the local ID to kInvalidTemplateURLID so we can add it.
2526 TemplateURLData data(sync_turl->data()); 2356 TemplateURLData data(sync_turl->data());
2527 data.id = kInvalidTemplateURLID; 2357 data.id = kInvalidTemplateURLID;
2528 Add(new TemplateURL(profile_, data)); 2358 TemplateURL* added = new TemplateURL(profile_, data);
2359 base::AutoReset<DefaultSearchChangeOrigin> change_origin(
2360 &dsp_change_origin_, DSP_CHANGE_SYNC_ADD);
2361 if (Add(added))
2362 MaybeUpdateDSEAfterSync(added);
2529 merge_result->set_num_items_added( 2363 merge_result->set_num_items_added(
2530 merge_result->num_items_added() + 1); 2364 merge_result->num_items_added() + 1);
2531 } 2365 }
2532 } 2366 }
2533 2367
2534 void TemplateURLService::SetDefaultSearchProviderIfNewlySynced(
2535 const std::string& guid) {
2536 // If we're not syncing or if default search is managed by policy, ignore.
2537 if (!sync_processor_.get() || is_default_search_managed_)
2538 return;
2539
2540 PrefService* prefs = GetPrefs();
2541 if (prefs && pending_synced_default_search_ &&
2542 prefs->GetString(prefs::kSyncedDefaultSearchProviderGUID) == guid) {
2543 // Make sure this actually exists. We should not be calling this unless we
2544 // really just added this TemplateURL.
2545 TemplateURL* turl_from_sync = GetTemplateURLForGUID(guid);
2546 if (turl_from_sync && turl_from_sync->SupportsReplacement()) {
2547 base::AutoReset<DefaultSearchChangeOrigin> change_origin(
2548 &dsp_change_origin_, DSP_CHANGE_SYNC_ADD);
2549 SetDefaultSearchProvider(turl_from_sync);
2550 }
2551 pending_synced_default_search_ = false;
2552 }
2553 }
2554
2555 TemplateURL* TemplateURLService::GetPendingSyncedDefaultSearchProvider() {
2556 PrefService* prefs = GetPrefs();
2557 if (!prefs || !pending_synced_default_search_)
2558 return NULL;
2559
2560 // Could be NULL if no such thing exists.
2561 return GetTemplateURLForGUID(
2562 prefs->GetString(prefs::kSyncedDefaultSearchProviderGUID));
2563 }
2564
2565 void TemplateURLService::PatchMissingSyncGUIDs( 2368 void TemplateURLService::PatchMissingSyncGUIDs(
2566 TemplateURLVector* template_urls) { 2369 TemplateURLVector* template_urls) {
2567 DCHECK(template_urls); 2370 DCHECK(template_urls);
2568 for (TemplateURLVector::iterator i = template_urls->begin(); 2371 for (TemplateURLVector::iterator i = template_urls->begin();
2569 i != template_urls->end(); ++i) { 2372 i != template_urls->end(); ++i) {
2570 TemplateURL* template_url = *i; 2373 TemplateURL* template_url = *i;
2571 DCHECK(template_url); 2374 DCHECK(template_url);
2572 if (template_url->sync_guid().empty() && 2375 if (template_url->sync_guid().empty() &&
2573 (template_url->GetType() != 2376 (template_url->GetType() !=
2574 TemplateURL::NORMAL_CONTROLLED_BY_EXTENSION)) { 2377 TemplateURL::NORMAL_CONTROLLED_BY_EXTENSION)) {
2575 template_url->data_.sync_guid = base::GenerateGUID(); 2378 template_url->data_.sync_guid = base::GenerateGUID();
2576 if (service_) 2379 if (service_)
2577 service_->UpdateKeyword(template_url->data()); 2380 service_->UpdateKeyword(template_url->data());
2578 } 2381 }
2579 } 2382 }
2580 } 2383 }
2581 2384
2582 void TemplateURLService::AddTemplateURLsAndSetupDefaultEngine( 2385 void TemplateURLService::OnSyncedDefaultSearchProviderGUIDChanged() {
2583 TemplateURLVector* template_urls, 2386 base::AutoReset<DefaultSearchChangeOrigin> change_origin(
2584 TemplateURL* default_search_provider) { 2387 &dsp_change_origin_, DSP_CHANGE_SYNC_PREF);
2585 DCHECK(template_urls);
2586 is_default_search_managed_ = false;
2587 bool database_specified_a_default = (default_search_provider != NULL);
2588 2388
2589 // Check if default search provider is now managed. 2389 std::string new_guid =
2590 scoped_ptr<TemplateURLData> default_from_prefs; 2390 GetPrefs()->GetString(prefs::kSyncedDefaultSearchProviderGUID);
2591 LoadDefaultSearchProviderFromPrefs( 2391 if (new_guid.empty()) {
2592 GetPrefs(), &default_from_prefs, &is_default_search_managed_); 2392 default_search_manager_.ClearUserSelectedDefaultSearchEngine();
2393 return;
2394 }
2593 2395
2594 // Remove entries that were created because of policy as they may have 2396 TemplateURL* turl = GetTemplateURLForGUID(new_guid);
2595 // changed since the database was saved. 2397 if (turl)
2596 RemoveProvidersCreatedByPolicy(template_urls, 2398 default_search_manager_.SetUserSelectedDefaultSearchEngine(turl->data());
2597 &default_search_provider,
2598 default_from_prefs.get());
2599
2600 PatchMissingSyncGUIDs(template_urls);
2601
2602 if (is_default_search_managed_) {
2603 SetTemplateURLs(template_urls);
2604
2605 if (TemplateURL::MatchesData(default_search_provider,
2606 default_from_prefs.get())) {
2607 // The value from the preferences was previously stored in the database.
2608 // Reuse it.
2609 } else {
2610 // The value from the preferences takes over.
2611 default_search_provider = NULL;
2612 if (default_from_prefs) {
2613 default_from_prefs->created_by_policy = true;
2614 default_from_prefs->id = kInvalidTemplateURLID;
2615 default_search_provider =
2616 new TemplateURL(profile_, *default_from_prefs);
2617 if (!AddNoNotify(default_search_provider, true))
2618 default_search_provider = NULL;
2619 }
2620 }
2621 // Note that this saves the default search provider to prefs.
2622 if (!default_search_provider ||
2623 ((default_search_provider->GetType() !=
2624 TemplateURL::OMNIBOX_API_EXTENSION) &&
2625 default_search_provider->SupportsReplacement())) {
2626 bool success = SetDefaultSearchProviderNoNotify(default_search_provider);
2627 DCHECK(success);
2628 }
2629 } else {
2630 // If we had a managed default, replace it with the synced default if
2631 // applicable, or the first provider of the list.
2632 TemplateURL* synced_default = GetPendingSyncedDefaultSearchProvider();
2633 if (synced_default) {
2634 default_search_provider = synced_default;
2635 pending_synced_default_search_ = false;
2636 } else if (database_specified_a_default &&
2637 default_search_provider == NULL) {
2638 UMA_HISTOGRAM_ENUMERATION(kFirstPotentialEngineHistogramName,
2639 FIRST_POTENTIAL_CALLSITE_ON_LOAD,
2640 FIRST_POTENTIAL_CALLSITE_MAX);
2641 default_search_provider = FirstPotentialDefaultEngine(*template_urls);
2642 }
2643
2644 // If the default search provider existed previously, then just
2645 // set the member variable. Otherwise, we'll set it using the method
2646 // to ensure that it is saved properly after its id is set.
2647 if (default_search_provider &&
2648 (default_search_provider->id() != kInvalidTemplateURLID)) {
2649 default_search_provider_ = default_search_provider;
2650 default_search_provider = NULL;
2651 }
2652 SetTemplateURLs(template_urls);
2653
2654 if (default_search_provider) {
2655 base::AutoReset<DefaultSearchChangeOrigin> change_origin(
2656 &dsp_change_origin_, default_from_prefs ?
2657 dsp_change_origin_ : DSP_CHANGE_NEW_ENGINE_NO_PREFS);
2658 // Note that this saves the default search provider to prefs.
2659 SetDefaultSearchProvider(default_search_provider);
2660 } else {
2661 // Always save the default search provider to prefs. That way we don't
2662 // have to worry about it being out of sync.
2663 if (default_search_provider_)
2664 SaveDefaultSearchProviderToPrefs(default_search_provider_, GetPrefs());
2665 }
2666 }
2667 } 2399 }
2668 2400
2669 void TemplateURLService::EnsureDefaultSearchProviderExists() { 2401 TemplateURL* TemplateURLService::FindPrepopulatedTemplateURL(
2670 if (!is_default_search_managed()) { 2402 int prepopulated_id) {
2671 bool has_default_search_provider = default_search_provider_ && 2403 for (TemplateURLVector::const_iterator i = template_urls_.begin();
2672 default_search_provider_->SupportsReplacement(); 2404 i != template_urls_.end(); ++i) {
2673 UMA_HISTOGRAM_BOOLEAN("Search.HasDefaultSearchProvider", 2405 if ((*i)->prepopulate_id() == prepopulated_id)
2674 has_default_search_provider); 2406 return *i;
2675 // Ensure that default search provider exists. See http://crbug.com/116952.
2676 if (!has_default_search_provider) {
2677 bool success =
2678 SetDefaultSearchProviderNoNotify(FindNewDefaultSearchProvider());
2679 DCHECK(success);
2680 }
2681 // Don't log anything if the user has a NULL default search provider.
2682 if (default_search_provider_) {
2683 UMA_HISTOGRAM_ENUMERATION("Search.DefaultSearchProviderType",
2684 TemplateURLPrepopulateData::GetEngineType(*default_search_provider_),
2685 SEARCH_ENGINE_MAX);
2686 }
2687 } 2407 }
2408
Peter Kasting 2014/05/08 22:46:46 Nit: I'd probably omit the blank line here (and in
2409 return NULL;
2688 } 2410 }
2689 2411
2690 TemplateURL* TemplateURLService::CreateTemplateURLForExtension( 2412 TemplateURL* TemplateURLService::CreateTemplateURLForExtension(
2691 const ExtensionKeyword& extension_keyword) { 2413 const ExtensionKeyword& extension_keyword) {
2692 TemplateURLData data; 2414 TemplateURLData data;
2693 data.short_name = base::UTF8ToUTF16(extension_keyword.extension_name); 2415 data.short_name = base::UTF8ToUTF16(extension_keyword.extension_name);
2694 data.SetKeyword(base::UTF8ToUTF16(extension_keyword.extension_keyword)); 2416 data.SetKeyword(base::UTF8ToUTF16(extension_keyword.extension_keyword));
2695 // This URL is not actually used for navigation. It holds the extension's 2417 // This URL is not actually used for navigation. It holds the extension's
2696 // ID, as well as forcing the TemplateURL to be treated as a search keyword. 2418 // ID, as well as forcing the TemplateURL to be treated as a search keyword.
2697 data.SetURL(std::string(extensions::kExtensionScheme) + "://" + 2419 data.SetURL(std::string(extensions::kExtensionScheme) + "://" +
2698 extension_keyword.extension_id + "/?q={searchTerms}"); 2420 extension_keyword.extension_id + "/?q={searchTerms}");
2699 return new TemplateURL(profile_, data); 2421 return new TemplateURL(profile_, data);
2700 } 2422 }
2701 2423
2702 TemplateURL* TemplateURLService::FindTemplateURLForExtension( 2424 TemplateURL* TemplateURLService::FindTemplateURLForExtension(
2703 const std::string& extension_id, 2425 const std::string& extension_id,
2704 TemplateURL::Type type) { 2426 TemplateURL::Type type) {
2705 DCHECK_NE(TemplateURL::NORMAL, type); 2427 DCHECK_NE(TemplateURL::NORMAL, type);
2706 for (TemplateURLVector::const_iterator i = template_urls_.begin(); 2428 for (TemplateURLVector::const_iterator i = template_urls_.begin();
2707 i != template_urls_.end(); ++i) { 2429 i != template_urls_.end(); ++i) {
2708 if ((*i)->GetType() == type && 2430 if ((*i)->GetType() == type &&
2709 (*i)->GetExtensionId() == extension_id) 2431 (*i)->GetExtensionId() == extension_id)
2710 return *i; 2432 return *i;
2711 } 2433 }
2712 2434
2713 return NULL; 2435 return NULL;
2714 } 2436 }
2715 2437
2716 TemplateURL* TemplateURLService::FindExtensionDefaultSearchEngine() const { 2438 TemplateURL* TemplateURLService::FindMatchingExtensionTemplateURL(
2439 const TemplateURLData& data,
2440 TemplateURL::Type type) {
2441 DCHECK_NE(TemplateURL::NORMAL, type);
2442 for (TemplateURLVector::const_iterator i = template_urls_.begin();
2443 i != template_urls_.end(); ++i) {
2444 if ((*i)->GetType() == type && TemplateURL::MatchesData(*i, &data))
2445 return *i;
2446 }
2447
2448 return NULL;
2449 }
2450
2451 void TemplateURLService::UpdateExtensionDefaultSearchEngine() {
2717 TemplateURL* most_recently_intalled_default = NULL; 2452 TemplateURL* most_recently_intalled_default = NULL;
2718 for (TemplateURLVector::const_iterator i = template_urls_.begin(); 2453 for (TemplateURLVector::const_iterator i = template_urls_.begin();
2719 i != template_urls_.end(); ++i) { 2454 i != template_urls_.end(); ++i) {
2720 if (((*i)->GetType() == TemplateURL::NORMAL_CONTROLLED_BY_EXTENSION) && 2455 if (((*i)->GetType() == TemplateURL::NORMAL_CONTROLLED_BY_EXTENSION) &&
2721 (*i)->extension_info_->wants_to_be_default_engine && 2456 (*i)->extension_info_->wants_to_be_default_engine &&
2722 (*i)->SupportsReplacement() && 2457 (*i)->SupportsReplacement() &&
2723 (!most_recently_intalled_default || 2458 (!most_recently_intalled_default ||
2724 (most_recently_intalled_default->extension_info_->install_time < 2459 (most_recently_intalled_default->extension_info_->install_time <
2725 (*i)->extension_info_->install_time))) 2460 (*i)->extension_info_->install_time)))
2726 most_recently_intalled_default = *i; 2461 most_recently_intalled_default = *i;
2727 } 2462 }
2728 2463
2729 return most_recently_intalled_default; 2464 if (most_recently_intalled_default) {
2465 base::AutoReset<DefaultSearchChangeOrigin> change_origin(
2466 &dsp_change_origin_, DSP_CHANGE_OVERRIDE_SETTINGS_EXTENSION);
2467 default_search_manager_.SetExtensionControlledDefaultSearchEngine(
2468 most_recently_intalled_default->data());
2469 } else {
2470 default_search_manager_.ClearExtensionControlledDefaultSearchEngine();
2471 }
2730 } 2472 }
2731
2732 void TemplateURLService::
2733 SetDefaultSearchProviderAfterRemovingDefaultExtension() {
2734 DCHECK(!is_default_search_managed());
2735 TemplateURL* new_dse = FindExtensionDefaultSearchEngine();
2736 if (!new_dse) {
2737 scoped_ptr<TemplateURLData> default_provider;
2738 bool is_managed;
2739 if (LoadDefaultSearchProviderFromPrefs(
2740 GetPrefs(), &default_provider, &is_managed) &&
2741 default_provider) {
2742 for (TemplateURLVector::const_iterator i = template_urls_.begin();
2743 i != template_urls_.end(); ++i) {
2744 if ((*i)->id() == default_provider->id) {
2745 new_dse = *i;
2746 break;
2747 }
2748 }
2749 }
2750 }
2751 if (!new_dse)
2752 new_dse = FindNewDefaultSearchProvider();
2753 SetDefaultSearchProviderNoNotify(new_dse);
2754 }
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698