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

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

Powered by Google App Engine
This is Rietveld 408576698