Roll src/third_party/WebKit f36d5e0:68b67cd (svn 193299:193303)
[chromium-blink-merge.git] / components / search_engines / template_url_service.h
blob77c2fd4348a88f8b8c1205e3e80fe2eee07551f9
1 // Copyright 2014 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #ifndef COMPONENTS_SEARCH_ENGINES_TEMPLATE_URL_SERVICE_H_
6 #define COMPONENTS_SEARCH_ENGINES_TEMPLATE_URL_SERVICE_H_
8 #include <list>
9 #include <map>
10 #include <set>
11 #include <string>
12 #include <vector>
14 #include "base/callback_list.h"
15 #include "base/gtest_prod_util.h"
16 #include "base/memory/scoped_ptr.h"
17 #include "base/observer_list.h"
18 #include "base/prefs/pref_change_registrar.h"
19 #include "base/time/clock.h"
20 #include "components/google/core/browser/google_url_tracker.h"
21 #include "components/keyed_service/core/keyed_service.h"
22 #include "components/search_engines/default_search_manager.h"
23 #include "components/search_engines/keyword_web_data_service.h"
24 #include "components/search_engines/template_url.h"
25 #include "components/search_engines/template_url_id.h"
26 #include "components/webdata/common/web_data_service_consumer.h"
27 #include "sync/api/sync_change.h"
28 #include "sync/api/syncable_service.h"
30 class GURL;
31 class PrefService;
32 class SearchHostToURLsMap;
33 class SearchTermsData;
34 class TemplateURL;
35 struct TemplateURLData;
36 class TemplateURLServiceClient;
37 class TemplateURLServiceObserver;
39 namespace rappor {
40 class RapporService;
43 namespace syncer {
44 class SyncData;
45 class SyncErrorFactory;
48 // TemplateURLService is the backend for keywords. It's used by
49 // KeywordAutocomplete.
51 // TemplateURLService stores a vector of TemplateURLs. The TemplateURLs are
52 // persisted to the database maintained by KeywordWebDataService.
53 // *ALL* mutations to the TemplateURLs must funnel through TemplateURLService.
54 // This allows TemplateURLService to notify listeners of changes as well as keep
55 // the database in sync.
57 // TemplateURLService does not load the vector of TemplateURLs in its
58 // constructor (except for testing). Use the Load method to trigger a load.
59 // When TemplateURLService has completed loading, observers are notified via
60 // OnTemplateURLServiceChanged, or by a callback registered prior to calling
61 // the Load method.
63 // TemplateURLService takes ownership of any TemplateURL passed to it. If there
64 // is a KeywordWebDataService, deletion is handled by KeywordWebDataService,
65 // otherwise TemplateURLService handles deletion.
67 class TemplateURLService : public WebDataServiceConsumer,
68 public KeyedService,
69 public syncer::SyncableService {
70 public:
71 typedef std::map<std::string, std::string> QueryTerms;
72 typedef std::vector<TemplateURL*> TemplateURLVector;
73 typedef std::map<std::string, syncer::SyncData> SyncDataMap;
74 typedef base::CallbackList<void(void)>::Subscription Subscription;
76 // Struct used for initializing the data store with fake data.
77 // Each initializer is mapped to a TemplateURL.
78 struct Initializer {
79 const char* const keyword;
80 const char* const url;
81 const char* const content;
84 struct URLVisitedDetails {
85 GURL url;
86 bool is_keyword_transition;
89 TemplateURLService(
90 PrefService* prefs,
91 scoped_ptr<SearchTermsData> search_terms_data,
92 const scoped_refptr<KeywordWebDataService>& web_data_service,
93 scoped_ptr<TemplateURLServiceClient> client,
94 GoogleURLTracker* google_url_tracker,
95 rappor::RapporService* rappor_service,
96 const base::Closure& dsp_change_callback);
97 // The following is for testing.
98 TemplateURLService(const Initializer* initializers, const int count);
99 ~TemplateURLService() override;
101 // Removes any unnecessary characters from a user input keyword.
102 // This removes the leading scheme, "www." and any trailing slash.
103 static base::string16 CleanUserInputKeyword(const base::string16& keyword);
105 // Returns true if there is no TemplateURL that conflicts with the
106 // keyword/url pair, or there is one but it can be replaced. If there is an
107 // existing keyword that can be replaced and template_url_to_replace is
108 // non-NULL, template_url_to_replace is set to the keyword to replace.
110 // url gives the url of the search query. The url is used to avoid generating
111 // a TemplateURL for an existing TemplateURL that shares the same host.
112 bool CanReplaceKeyword(const base::string16& keyword,
113 const GURL& url,
114 TemplateURL** template_url_to_replace);
116 // Returns (in |matches|) all TemplateURLs whose keywords begin with |prefix|,
117 // sorted shortest keyword-first. If |support_replacement_only| is true, only
118 // TemplateURLs that support replacement are returned.
119 void FindMatchingKeywords(const base::string16& prefix,
120 bool support_replacement_only,
121 TemplateURLVector* matches);
123 // Looks up |keyword| and returns the element it maps to. Returns NULL if
124 // the keyword was not found.
125 // The caller should not try to delete the returned pointer; the data store
126 // retains ownership of it.
127 TemplateURL* GetTemplateURLForKeyword(const base::string16& keyword);
129 // Returns that TemplateURL with the specified GUID, or NULL if not found.
130 // The caller should not try to delete the returned pointer; the data store
131 // retains ownership of it.
132 TemplateURL* GetTemplateURLForGUID(const std::string& sync_guid);
134 // Returns the first TemplateURL found with a URL using the specified |host|,
135 // or NULL if there are no such TemplateURLs
136 TemplateURL* GetTemplateURLForHost(const std::string& host);
138 // Takes ownership of |template_url| and adds it to this model. For obvious
139 // reasons, it is illegal to Add() the same |template_url| pointer twice.
140 // Returns true if the Add is successful.
141 bool Add(TemplateURL* template_url);
143 // Like Add(), but overwrites the |template_url|'s values with the provided
144 // ones.
145 void AddWithOverrides(TemplateURL* template_url,
146 const base::string16& short_name,
147 const base::string16& keyword,
148 const std::string& url);
150 // Adds a search engine with the specified info.
151 void AddExtensionControlledTURL(
152 TemplateURL* template_url,
153 scoped_ptr<TemplateURL::AssociatedExtensionInfo> info);
155 // Removes the keyword from the model. This deletes the supplied TemplateURL.
156 // This fails if the supplied template_url is the default search provider.
157 void Remove(TemplateURL* template_url);
159 // Removes any TemplateURL of the specified |type| associated with
160 // |extension_id|. Unlike with Remove(), this can be called when the
161 // TemplateURL in question is the current default search provider.
162 void RemoveExtensionControlledTURL(const std::string& extension_id,
163 TemplateURL::Type type);
165 // Removes all auto-generated keywords that were created on or after the
166 // date passed in.
167 void RemoveAutoGeneratedSince(base::Time created_after);
169 // Removes all auto-generated keywords that were created in the specified
170 // range.
171 void RemoveAutoGeneratedBetween(base::Time created_after,
172 base::Time created_before);
174 // Removes all auto-generated keywords that were created in the specified
175 // range for a specified |origin|. If |origin| is empty, deletes all
176 // auto-generated keywords in the range.
177 void RemoveAutoGeneratedForOriginBetween(const GURL& origin,
178 base::Time created_after,
179 base::Time created_before);
181 // Adds a TemplateURL for an extension with an omnibox keyword.
182 // Only 1 keyword is allowed for a given extension. If a keyword
183 // already exists for this extension, does nothing.
184 void RegisterOmniboxKeyword(const std::string& extension_id,
185 const std::string& extension_name,
186 const std::string& keyword,
187 const std::string& template_url_string);
189 // Returns the set of URLs describing the keywords. The elements are owned
190 // by TemplateURLService and should not be deleted.
191 TemplateURLVector GetTemplateURLs();
193 // Increment the usage count of a keyword.
194 // Called when a URL is loaded that was generated from a keyword.
195 void IncrementUsageCount(TemplateURL* url);
197 // Resets the title, keyword and search url of the specified TemplateURL.
198 // The TemplateURL is marked as not replaceable.
199 void ResetTemplateURL(TemplateURL* url,
200 const base::string16& title,
201 const base::string16& keyword,
202 const std::string& search_url);
204 // Return true if the given |url| can be made the default. This returns false
205 // regardless of |url| if the default search provider is managed by policy or
206 // controlled by an extension.
207 bool CanMakeDefault(const TemplateURL* url);
209 // Set the default search provider. |url| may be null.
210 // This will assert if the default search is managed; the UI should not be
211 // invoking this method in that situation.
212 void SetUserSelectedDefaultSearchProvider(TemplateURL* url);
214 // Returns the default search provider. If the TemplateURLService hasn't been
215 // loaded, the default search provider is pulled from preferences.
217 // NOTE: At least in unittest mode, this may return NULL.
218 TemplateURL* GetDefaultSearchProvider();
220 // Returns true if the |url| is a search results page from the default search
221 // provider.
222 bool IsSearchResultsPageFromDefaultSearchProvider(const GURL& url);
224 // Returns true if the default search is managed through group policy.
225 bool is_default_search_managed() const {
226 return default_search_provider_source_ == DefaultSearchManager::FROM_POLICY;
229 // Returns true if the default search provider is controlled by an extension.
230 bool IsExtensionControlledDefaultSearch();
232 // Returns the default search specified in the prepopulated data, if it
233 // exists. If not, returns first URL in |template_urls_|, or NULL if that's
234 // empty. The returned object is owned by TemplateURLService and can be
235 // destroyed at any time so should be used right after the call.
236 TemplateURL* FindNewDefaultSearchProvider();
238 // Performs the same actions that happen when the prepopulate data version is
239 // revved: all existing prepopulated entries are checked against the current
240 // prepopulate data, any now-extraneous safe_for_autoreplace() entries are
241 // removed, any existing engines are reset to the provided data (except for
242 // user-edited names or keywords), and any new prepopulated engines are
243 // added.
245 // After this, the default search engine is reset to the default entry in the
246 // prepopulate data.
247 void RepairPrepopulatedSearchEngines();
249 // Observers used to listen for changes to the model.
250 // TemplateURLService does NOT delete the observers when deleted.
251 void AddObserver(TemplateURLServiceObserver* observer);
252 void RemoveObserver(TemplateURLServiceObserver* observer);
254 // Loads the keywords. This has no effect if the keywords have already been
255 // loaded.
256 // Observers are notified when loading completes via the method
257 // OnTemplateURLServiceChanged.
258 void Load();
260 // Registers a callback to be called when the service has loaded.
262 // If the service has already loaded, this function does nothing.
263 scoped_ptr<Subscription> RegisterOnLoadedCallback(
264 const base::Closure& callback);
266 #if defined(UNIT_TEST)
267 void set_loaded(bool value) { loaded_ = value; }
268 #endif
270 // Whether or not the keywords have been loaded.
271 bool loaded() { return loaded_; }
273 // Notification that the keywords have been loaded.
274 // This is invoked from WebDataService, and should not be directly
275 // invoked.
276 void OnWebDataServiceRequestDone(KeywordWebDataService::Handle h,
277 const WDTypedResult* result) override;
279 // Returns the locale-direction-adjusted short name for the given keyword.
280 // Also sets the out param to indicate whether the keyword belongs to an
281 // Omnibox extension.
282 base::string16 GetKeywordShortName(const base::string16& keyword,
283 bool* is_omnibox_api_extension_keyword);
285 // Called by the history service when a URL is visited.
286 void OnHistoryURLVisited(const URLVisitedDetails& details);
288 // KeyedService implementation.
289 void Shutdown() override;
291 // syncer::SyncableService implementation.
293 // Returns all syncable TemplateURLs from this model as SyncData. This should
294 // include every search engine and no Extension keywords.
295 syncer::SyncDataList GetAllSyncData(syncer::ModelType type) const override;
296 // Process new search engine changes from Sync, merging them into our local
297 // data. This may send notifications if local search engines are added,
298 // updated or removed.
299 syncer::SyncError ProcessSyncChanges(
300 const tracked_objects::Location& from_here,
301 const syncer::SyncChangeList& change_list) override;
302 // Merge initial search engine data from Sync and push any local changes up
303 // to Sync. This may send notifications if local search engines are added,
304 // updated or removed.
305 syncer::SyncMergeResult MergeDataAndStartSyncing(
306 syncer::ModelType type,
307 const syncer::SyncDataList& initial_sync_data,
308 scoped_ptr<syncer::SyncChangeProcessor> sync_processor,
309 scoped_ptr<syncer::SyncErrorFactory> sync_error_factory) override;
310 void StopSyncing(syncer::ModelType type) override;
312 // Processes a local TemplateURL change for Sync. |turl| is the TemplateURL
313 // that has been modified, and |type| is the Sync ChangeType that took place.
314 // This may send a new SyncChange to the cloud. If our model has not yet been
315 // associated with Sync, or if this is triggered by a Sync change, then this
316 // does nothing.
317 void ProcessTemplateURLChange(const tracked_objects::Location& from_here,
318 const TemplateURL* turl,
319 syncer::SyncChange::SyncChangeType type);
321 // Returns a SearchTermsData which can be used to call TemplateURL methods.
322 const SearchTermsData& search_terms_data() const {
323 return *search_terms_data_;
326 // Returns a SyncData with a sync representation of the search engine data
327 // from |turl|.
328 static syncer::SyncData CreateSyncDataFromTemplateURL(
329 const TemplateURL& turl);
331 // Creates a new heap-allocated TemplateURL* which is populated by overlaying
332 // |sync_data| atop |existing_turl|. |existing_turl| may be NULL; if not it
333 // remains unmodified. The caller owns the returned TemplateURL*.
335 // If the created TemplateURL is migrated in some way from out-of-date sync
336 // data, an appropriate SyncChange is added to |change_list|. If the sync
337 // data is bad for some reason, an ACTION_DELETE change is added and the
338 // function returns NULL.
339 static scoped_ptr<TemplateURL> CreateTemplateURLFromTemplateURLAndSyncData(
340 TemplateURLServiceClient* client,
341 PrefService* prefs,
342 const SearchTermsData& search_terms_data,
343 TemplateURL* existing_turl,
344 const syncer::SyncData& sync_data,
345 syncer::SyncChangeList* change_list);
347 // Returns a map mapping Sync GUIDs to pointers to syncer::SyncData.
348 static SyncDataMap CreateGUIDToSyncDataMap(
349 const syncer::SyncDataList& sync_data);
351 #if defined(UNIT_TEST)
352 void set_clock(scoped_ptr<base::Clock> clock) { clock_ = clock.Pass(); }
353 #endif
355 private:
356 FRIEND_TEST_ALL_PREFIXES(TemplateURLServiceTest, TestManagedDefaultSearch);
357 FRIEND_TEST_ALL_PREFIXES(TemplateURLServiceTest,
358 UpdateKeywordSearchTermsForURL);
359 FRIEND_TEST_ALL_PREFIXES(TemplateURLServiceTest,
360 DontUpdateKeywordSearchForNonReplaceable);
361 FRIEND_TEST_ALL_PREFIXES(TemplateURLServiceTest, ChangeGoogleBaseValue);
362 FRIEND_TEST_ALL_PREFIXES(TemplateURLServiceTest, MergeDeletesUnusedProviders);
363 FRIEND_TEST_ALL_PREFIXES(TemplateURLServiceTest, AddExtensionKeyword);
364 FRIEND_TEST_ALL_PREFIXES(TemplateURLServiceSyncTest, UniquifyKeyword);
365 FRIEND_TEST_ALL_PREFIXES(TemplateURLServiceSyncTest,
366 IsLocalTemplateURLBetter);
367 FRIEND_TEST_ALL_PREFIXES(TemplateURLServiceSyncTest,
368 ResolveSyncKeywordConflict);
369 FRIEND_TEST_ALL_PREFIXES(TemplateURLServiceSyncTest, PreSyncDeletes);
370 FRIEND_TEST_ALL_PREFIXES(TemplateURLServiceSyncTest, MergeInSyncTemplateURL);
372 friend class InstantUnitTestBase;
373 friend class TemplateURLServiceTestUtil;
375 typedef std::map<base::string16, TemplateURL*> KeywordToTemplateMap;
376 typedef std::map<std::string, TemplateURL*> GUIDToTemplateMap;
378 // Declaration of values to be used in an enumerated histogram to tally
379 // changes to the default search provider from various entry points. In
380 // particular, we use this to see what proportion of changes are from Sync
381 // entry points, to help spot erroneous Sync activity.
382 enum DefaultSearchChangeOrigin {
383 // Various known Sync entry points.
384 DSP_CHANGE_SYNC_PREF,
385 DSP_CHANGE_SYNC_ADD,
386 DSP_CHANGE_SYNC_DELETE,
387 DSP_CHANGE_SYNC_NOT_MANAGED,
388 // "Other" origins. We differentiate between Sync and not Sync so we know if
389 // certain changes were intentionally from the system, or possibly some
390 // unintentional change from when we were Syncing.
391 DSP_CHANGE_SYNC_UNINTENTIONAL,
392 // All changes that don't fall into another category; we can't reorder the
393 // list for clarity as this would screw up stat collection.
394 DSP_CHANGE_OTHER,
395 // Changed through "Profile Reset" feature.
396 DSP_CHANGE_PROFILE_RESET,
397 // Changed by an extension through the Override Settings API.
398 DSP_CHANGE_OVERRIDE_SETTINGS_EXTENSION,
399 // New DSP during database/prepopulate data load, which was not previously
400 // in the known engine set, and with no previous value in prefs. The
401 // typical time to see this is during first run.
402 DSP_CHANGE_NEW_ENGINE_NO_PREFS,
403 // Boundary value.
404 DSP_CHANGE_MAX,
407 // Helper functor for FindMatchingKeywords(), for finding the range of
408 // keywords which begin with a prefix.
409 class LessWithPrefix;
411 void Init(const Initializer* initializers, int num_initializers);
413 void RemoveFromMaps(TemplateURL* template_url);
415 void AddToMaps(TemplateURL* template_url);
417 // Sets the keywords. This is used once the keywords have been loaded.
418 // This does NOT notify the delegate or the database.
420 // This transfers ownership of the elements in |urls| to |this|, and may
421 // delete some elements, so it's not safe for callers to access any elements
422 // after calling; to reinforce this, this function clears |urls| on exit.
423 void SetTemplateURLs(TemplateURLVector* urls);
425 // Transitions to the loaded state.
426 void ChangeToLoadedState();
428 // Called by DefaultSearchManager when the effective default search engine has
429 // changed.
430 void OnDefaultSearchChange(const TemplateURLData* new_dse_data,
431 DefaultSearchManager::Source source);
433 // Applies a DSE change and reports metrics if appropriate.
434 void ApplyDefaultSearchChange(const TemplateURLData* new_dse_data,
435 DefaultSearchManager::Source source);
438 // Applies a DSE change. May be called at startup or after transitioning to
439 // the loaded state. Returns true if a change actually occurred.
440 bool ApplyDefaultSearchChangeNoMetrics(const TemplateURLData* new_dse_data,
441 DefaultSearchManager::Source source);
443 // Returns true if there is no TemplateURL that has a search url with the
444 // specified host, or the only TemplateURLs matching the specified host can
445 // be replaced.
446 bool CanReplaceKeywordForHost(const std::string& host,
447 TemplateURL** to_replace);
449 // Returns true if the TemplateURL is replaceable. This doesn't look at the
450 // uniqueness of the keyword or host and is intended to be called after those
451 // checks have been done. This returns true if the TemplateURL doesn't appear
452 // in the default list and is marked as safe_for_autoreplace.
453 bool CanReplace(const TemplateURL* t_url);
455 // Like GetTemplateURLForKeyword(), but ignores extension-provided keywords.
456 TemplateURL* FindNonExtensionTemplateURLForKeyword(
457 const base::string16& keyword);
459 // Updates the information in |existing_turl| using the information from
460 // |new_values|, but the ID for |existing_turl| is retained. Notifying
461 // observers is the responsibility of the caller. Returns whether
462 // |existing_turl| was found in |template_urls_| and thus could be updated.
464 // NOTE: This should not be called with an extension keyword as there are no
465 // updates needed in that case.
466 bool UpdateNoNotify(TemplateURL* existing_turl,
467 const TemplateURL& new_values);
469 // If the TemplateURL comes from a prepopulated URL available in the current
470 // country, update all its fields save for the keyword, short name and id so
471 // that they match the internal prepopulated URL. TemplateURLs not coming from
472 // a prepopulated URL are not modified.
473 static void UpdateTemplateURLIfPrepopulated(TemplateURL* existing_turl,
474 PrefService* prefs);
476 // If the TemplateURL's sync GUID matches the kSyncedDefaultSearchProviderGUID
477 // preference it will be used to update the DSE in memory and as persisted in
478 // preferences.
479 void MaybeUpdateDSEAfterSync(TemplateURL* synced_turl);
481 // Iterates through the TemplateURLs to see if one matches the visited url.
482 // For each TemplateURL whose url matches the visited url
483 // SetKeywordSearchTermsForURL is invoked.
484 void UpdateKeywordSearchTermsForURL(const URLVisitedDetails& details);
486 // If necessary, generates a visit for the site http:// + t_url.keyword().
487 void AddTabToSearchVisit(const TemplateURL& t_url);
489 // Requests the Google URL tracker to check the server if necessary.
490 void RequestGoogleURLTrackerServerCheckIfNecessary();
492 // Invoked when the Google base URL has changed. Updates the mapping for all
493 // TemplateURLs that have a replacement term of {google:baseURL} or
494 // {google:baseSuggestURL}.
495 void GoogleBaseURLChanged();
497 // Adds a new TemplateURL to this model. TemplateURLService will own the
498 // reference, and delete it when the TemplateURL is removed.
499 // If |newly_adding| is false, we assume that this TemplateURL was already
500 // part of the model in the past, and therefore we don't need to do things
501 // like assign it an ID or notify sync.
502 // This function guarantees that on return the model will not have two
503 // non-extension TemplateURLs with the same keyword. If that means that it
504 // cannot add the provided argument, it will delete it and return false.
505 // Caller is responsible for notifying observers if this function returns
506 // true.
507 bool AddNoNotify(TemplateURL* template_url, bool newly_adding);
509 // Removes the keyword from the model. This deletes the supplied TemplateURL.
510 // This fails if the supplied template_url is the default search provider.
511 // Caller is responsible for notifying observers.
512 void RemoveNoNotify(TemplateURL* template_url);
514 // Like ResetTemplateURL(), but instead of notifying observers, returns
515 // whether anything has changed.
516 bool ResetTemplateURLNoNotify(TemplateURL* url,
517 const base::string16& title,
518 const base::string16& keyword,
519 const std::string& search_url);
521 // Notify the observers that the model has changed. This is done only if the
522 // model is loaded.
523 void NotifyObservers();
525 // Updates |template_urls| so that the only "created by policy" entry is
526 // |default_from_prefs|. |default_from_prefs| may be NULL if there is no
527 // policy-defined DSE in effect.
528 void UpdateProvidersCreatedByPolicy(
529 TemplateURLVector* template_urls,
530 const TemplateURLData* default_from_prefs);
532 // Resets the sync GUID of the specified TemplateURL and persists the change
533 // to the database. This does not notify observers.
534 void ResetTemplateURLGUID(TemplateURL* url, const std::string& guid);
536 // Attempts to generate a unique keyword for |turl| based on its original
537 // keyword. If its keyword is already unique, that is returned. Otherwise, it
538 // tries to return the autogenerated keyword if that is unique to the Service,
539 // and finally it repeatedly appends special characters to the keyword until
540 // it is unique to the Service. If |force| is true, then this will only
541 // execute the special character appending functionality.
542 base::string16 UniquifyKeyword(const TemplateURL& turl, bool force);
544 // Returns true iff |local_turl| is considered "better" than |sync_turl| for
545 // the purposes of resolving conflicts. |local_turl| must be a TemplateURL
546 // known to the local model (though it may already be synced), and |sync_turl|
547 // is a new TemplateURL known to Sync but not yet known to the local model.
548 // The criteria for if |local_turl| is better than |sync_turl| is whether any
549 // of the following are true:
550 // * |local_turl|'s last_modified timestamp is newer than sync_turl.
551 // * |local_turl| is created by policy.
552 // * |local_turl| is the local default search provider.
553 bool IsLocalTemplateURLBetter(const TemplateURL* local_turl,
554 const TemplateURL* sync_turl);
556 // Given two synced TemplateURLs with a conflicting keyword, one of which
557 // needs to be added to or updated in the local model (|unapplied_sync_turl|)
558 // and one which is already known to the local model (|applied_sync_turl|),
559 // prepares the local model so that |unapplied_sync_turl| can be added to it,
560 // or applied as an update to an existing TemplateURL.
561 // Since both entries are known to Sync and one of their keywords will change,
562 // an ACTION_UPDATE will be appended to |change_list| to reflect this change.
563 // Note that |applied_sync_turl| must not be an extension keyword.
564 void ResolveSyncKeywordConflict(TemplateURL* unapplied_sync_turl,
565 TemplateURL* applied_sync_turl,
566 syncer::SyncChangeList* change_list);
568 // Adds |sync_turl| into the local model, possibly removing or updating a
569 // local TemplateURL to make room for it. This expects |sync_turl| to be a new
570 // entry from Sync, not currently known to the local model. |sync_data| should
571 // be a SyncDataMap where the contents are entries initially known to Sync
572 // during MergeDataAndStartSyncing.
573 // Any necessary updates to Sync will be appended to |change_list|. This can
574 // include updates on local TemplateURLs, if they are found in |sync_data|.
575 // |initial_data| should be a SyncDataMap of the entries known to the local
576 // model during MergeDataAndStartSyncing. If |sync_turl| replaces a local
577 // entry, that entry is removed from |initial_data| to prevent it from being
578 // sent up to Sync.
579 // |merge_result| tracks the changes made to the local model. Added/modified/
580 // deleted are updated depending on how the |sync_turl| is merged in.
581 // This should only be called from MergeDataAndStartSyncing.
582 void MergeInSyncTemplateURL(TemplateURL* sync_turl,
583 const SyncDataMap& sync_data,
584 syncer::SyncChangeList* change_list,
585 SyncDataMap* local_data,
586 syncer::SyncMergeResult* merge_result);
588 // Goes through a vector of TemplateURLs and ensure that both the in-memory
589 // and database copies have valid sync_guids. This is to fix crbug.com/102038,
590 // where old entries were being pushed to Sync without a sync_guid.
591 void PatchMissingSyncGUIDs(TemplateURLVector* template_urls);
593 void OnSyncedDefaultSearchProviderGUIDChanged();
595 // Adds |template_urls| to |template_urls_|.
597 // This transfers ownership of the elements in |template_urls| to |this|, and
598 // may delete some elements, so it's not safe for callers to access any
599 // elements after calling; to reinforce this, this function clears
600 // |template_urls| on exit.
601 void AddTemplateURLs(TemplateURLVector* template_urls);
603 // Returns the TemplateURL corresponding to |prepopulated_id|, if any.
604 TemplateURL* FindPrepopulatedTemplateURL(int prepopulated_id);
606 // Returns the TemplateURL associated with |extension_id|, if any.
607 TemplateURL* FindTemplateURLForExtension(const std::string& extension_id,
608 TemplateURL::Type type);
610 // Finds the extension-supplied TemplateURL that matches |data|, if any.
611 TemplateURL* FindMatchingExtensionTemplateURL(const TemplateURLData& data,
612 TemplateURL::Type type);
614 // Finds the most recently-installed NORMAL_CONTROLLED_BY_EXTENSION engine
615 // that supports replacement and wants to be default, if any. Notifies the
616 // DefaultSearchManager, which might change the effective default search
617 // engine.
618 void UpdateExtensionDefaultSearchEngine();
621 // ---------- Browser state related members ---------------------------------
622 PrefService* prefs_;
624 scoped_ptr<SearchTermsData> search_terms_data_;
626 // ---------- Dependencies on other components ------------------------------
627 // Service used to store entries.
628 scoped_refptr<KeywordWebDataService> web_data_service_;
630 scoped_ptr<TemplateURLServiceClient> client_;
632 GoogleURLTracker* google_url_tracker_;
634 // ---------- Metrics related members ---------------------------------------
635 rappor::RapporService* rappor_service_;
637 // This closure is run when the default search provider is set to Google.
638 base::Closure dsp_change_callback_;
641 PrefChangeRegistrar pref_change_registrar_;
643 // Mapping from keyword to the TemplateURL.
644 KeywordToTemplateMap keyword_to_template_map_;
646 // Mapping from Sync GUIDs to the TemplateURL.
647 GUIDToTemplateMap guid_to_template_map_;
649 TemplateURLVector template_urls_;
651 ObserverList<TemplateURLServiceObserver> model_observers_;
653 // Maps from host to set of TemplateURLs whose search url host is host.
654 // NOTE: This is always non-NULL; we use a scoped_ptr<> to avoid circular
655 // header dependencies.
656 scoped_ptr<SearchHostToURLsMap> provider_map_;
658 // Whether the keywords have been loaded.
659 bool loaded_;
661 // Set when the web data service fails to load properly. This prevents
662 // further communication with sync or writing to prefs, so we don't persist
663 // inconsistent state data anywhere.
664 bool load_failed_;
666 // If non-zero, we're waiting on a load.
667 KeywordWebDataService::Handle load_handle_;
669 // All visits that occurred before we finished loading. Once loaded
670 // UpdateKeywordSearchTermsForURL is invoked for each element of the vector.
671 std::vector<URLVisitedDetails> visits_to_add_;
673 // Once loaded, the default search provider. This is a pointer to a
674 // TemplateURL owned by |template_urls_|.
675 TemplateURL* default_search_provider_;
677 // A temporary location for the DSE until Web Data has been loaded and it can
678 // be merged into |template_urls_|.
679 scoped_ptr<TemplateURL> initial_default_search_provider_;
681 // Source of the default search provider.
682 DefaultSearchManager::Source default_search_provider_source_;
684 // ID assigned to next TemplateURL added to this model. This is an ever
685 // increasing integer that is initialized from the database.
686 TemplateURLID next_id_;
688 // Used to retrieve the current time, in base::Time units.
689 scoped_ptr<base::Clock> clock_;
691 // Do we have an active association between the TemplateURLs and sync models?
692 // Set in MergeDataAndStartSyncing, reset in StopSyncing. While this is not
693 // set, we ignore any local search engine changes (when we start syncing we
694 // will look up the most recent values anyways).
695 bool models_associated_;
697 // Whether we're currently processing changes from the syncer. While this is
698 // true, we ignore any local search engine changes, since we triggered them.
699 bool processing_syncer_changes_;
701 // Sync's syncer::SyncChange handler. We push all our changes through this.
702 scoped_ptr<syncer::SyncChangeProcessor> sync_processor_;
704 // Sync's error handler. We use it to create a sync error.
705 scoped_ptr<syncer::SyncErrorFactory> sync_error_factory_;
707 // A set of sync GUIDs denoting TemplateURLs that have been removed from this
708 // model or the underlying KeywordWebDataService prior to
709 // MergeDataAndStartSyncing.
710 // This set is used to determine what entries from the server we want to
711 // ignore locally and return a delete command for.
712 std::set<std::string> pre_sync_deletes_;
714 // This is used to log the origin of changes to the default search provider.
715 // We set this value to increasingly specific values when we know what is the
716 // cause/origin of a default search change.
717 DefaultSearchChangeOrigin dsp_change_origin_;
719 // Stores a list of callbacks to be run after TemplateURLService has loaded.
720 base::CallbackList<void(void)> on_loaded_callbacks_;
722 // Helper class to manage the default search engine.
723 DefaultSearchManager default_search_manager_;
725 scoped_ptr<GoogleURLTracker::Subscription> google_url_updated_subscription_;
727 DISALLOW_COPY_AND_ASSIGN(TemplateURLService);
730 #endif // COMPONENTS_SEARCH_ENGINES_TEMPLATE_URL_SERVICE_H_