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