add SK_SUPPORT_LEGACY_HQ_SCALING to suppress changes to HQ scaling
[chromium-blink-merge.git] / components / search_engines / template_url_service.h
blobdda5de4f3dae0106193e2cc0a8aa2ee84d6e02d4
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(
91 PrefService* prefs,
92 scoped_ptr<SearchTermsData> search_terms_data,
93 const scoped_refptr<KeywordWebDataService>& web_data_service,
94 scoped_ptr<TemplateURLServiceClient> client,
95 GoogleURLTracker* google_url_tracker,
96 rappor::RapporService* rappor_service,
97 const base::Closure& dsp_change_callback);
98 // The following is for testing.
99 TemplateURLService(const Initializer* initializers, const int count);
100 ~TemplateURLService() override;
102 // Creates a TemplateURLData that was previously saved to |prefs| via
103 // SaveDefaultSearchProviderToPrefs or set via policy.
104 // Returns true if successful, false otherwise.
105 // If the user or the policy has opted for no default search, this
106 // returns true but default_provider is set to NULL.
107 // |*is_managed| specifies whether the default is managed via policy.
108 static bool LoadDefaultSearchProviderFromPrefs(
109 PrefService* prefs,
110 scoped_ptr<TemplateURLData>* default_provider_data,
111 bool* is_managed);
113 // Removes any unnecessary characters from a user input keyword.
114 // This removes the leading scheme, "www." and any trailing slash.
115 static base::string16 CleanUserInputKeyword(const base::string16& keyword);
117 // Saves enough of url to |prefs| so that it can be loaded from preferences on
118 // start up.
119 static void SaveDefaultSearchProviderToPrefs(const TemplateURL* url,
120 PrefService* prefs);
122 // Returns true if there is no TemplateURL that conflicts with the
123 // keyword/url pair, or there is one but it can be replaced. If there is an
124 // existing keyword that can be replaced and template_url_to_replace is
125 // non-NULL, template_url_to_replace is set to the keyword to replace.
127 // url gives the url of the search query. The url is used to avoid generating
128 // a TemplateURL for an existing TemplateURL that shares the same host.
129 bool CanReplaceKeyword(const base::string16& keyword,
130 const GURL& url,
131 TemplateURL** template_url_to_replace);
133 // Returns (in |matches|) all TemplateURLs whose keywords begin with |prefix|,
134 // sorted shortest keyword-first. If |support_replacement_only| is true, only
135 // TemplateURLs that support replacement are returned.
136 void FindMatchingKeywords(const base::string16& prefix,
137 bool support_replacement_only,
138 TemplateURLVector* matches);
140 // Looks up |keyword| and returns the element it maps to. Returns NULL if
141 // the keyword was not found.
142 // The caller should not try to delete the returned pointer; the data store
143 // retains ownership of it.
144 TemplateURL* GetTemplateURLForKeyword(const base::string16& keyword);
146 // Returns that TemplateURL with the specified GUID, or NULL if not found.
147 // The caller should not try to delete the returned pointer; the data store
148 // retains ownership of it.
149 TemplateURL* GetTemplateURLForGUID(const std::string& sync_guid);
151 // Returns the first TemplateURL found with a URL using the specified |host|,
152 // or NULL if there are no such TemplateURLs
153 TemplateURL* GetTemplateURLForHost(const std::string& host);
155 // Takes ownership of |template_url| and adds it to this model. For obvious
156 // reasons, it is illegal to Add() the same |template_url| pointer twice.
157 // Returns true if the Add is successful.
158 bool Add(TemplateURL* template_url);
160 // Like Add(), but overwrites the |template_url|'s values with the provided
161 // ones.
162 void AddWithOverrides(TemplateURL* template_url,
163 const base::string16& short_name,
164 const base::string16& keyword,
165 const std::string& url);
167 // Adds a search engine with the specified info.
168 void AddExtensionControlledTURL(
169 TemplateURL* template_url,
170 scoped_ptr<TemplateURL::AssociatedExtensionInfo> info);
172 // Removes the keyword from the model. This deletes the supplied TemplateURL.
173 // This fails if the supplied template_url is the default search provider.
174 void Remove(TemplateURL* template_url);
176 // Removes any TemplateURL of the specified |type| associated with
177 // |extension_id|. Unlike with Remove(), this can be called when the
178 // TemplateURL in question is the current default search provider.
179 void RemoveExtensionControlledTURL(const std::string& extension_id,
180 TemplateURL::Type type);
182 // Removes all auto-generated keywords that were created on or after the
183 // date passed in.
184 void RemoveAutoGeneratedSince(base::Time created_after);
186 // Removes all auto-generated keywords that were created in the specified
187 // range.
188 void RemoveAutoGeneratedBetween(base::Time created_after,
189 base::Time created_before);
191 // Removes all auto-generated keywords that were created in the specified
192 // range for a specified |origin|. If |origin| is empty, deletes all
193 // auto-generated keywords in the range.
194 void RemoveAutoGeneratedForOriginBetween(const GURL& origin,
195 base::Time created_after,
196 base::Time created_before);
198 // Adds a TemplateURL for an extension with an omnibox keyword.
199 // Only 1 keyword is allowed for a given extension. If a keyword
200 // already exists for this extension, does nothing.
201 void RegisterOmniboxKeyword(const std::string& extension_id,
202 const std::string& extension_name,
203 const std::string& keyword,
204 const std::string& template_url_string);
206 // Returns the set of URLs describing the keywords. The elements are owned
207 // by TemplateURLService and should not be deleted.
208 TemplateURLVector GetTemplateURLs();
210 // Increment the usage count of a keyword.
211 // Called when a URL is loaded that was generated from a keyword.
212 void IncrementUsageCount(TemplateURL* url);
214 // Resets the title, keyword and search url of the specified TemplateURL.
215 // The TemplateURL is marked as not replaceable.
216 void ResetTemplateURL(TemplateURL* url,
217 const base::string16& title,
218 const base::string16& keyword,
219 const std::string& search_url);
221 // Return true if the given |url| can be made the default. This returns false
222 // regardless of |url| if the default search provider is managed by policy or
223 // controlled by an extension.
224 bool CanMakeDefault(const TemplateURL* url);
226 // Set the default search provider. |url| may be null.
227 // This will assert if the default search is managed; the UI should not be
228 // invoking this method in that situation.
229 void SetUserSelectedDefaultSearchProvider(TemplateURL* url);
231 // Returns the default search provider. If the TemplateURLService hasn't been
232 // loaded, the default search provider is pulled from preferences.
234 // NOTE: At least in unittest mode, this may return NULL.
235 TemplateURL* GetDefaultSearchProvider();
237 // Returns true if the |url| is a search results page from the default search
238 // provider.
239 bool IsSearchResultsPageFromDefaultSearchProvider(const GURL& url);
241 // Returns true if the default search is managed through group policy.
242 bool is_default_search_managed() const {
243 return default_search_provider_source_ == DefaultSearchManager::FROM_POLICY;
246 // Returns true if the default search provider is controlled by an extension.
247 bool IsExtensionControlledDefaultSearch();
249 // Returns the default search specified in the prepopulated data, if it
250 // exists. If not, returns first URL in |template_urls_|, or NULL if that's
251 // empty. The returned object is owned by TemplateURLService and can be
252 // destroyed at any time so should be used right after the call.
253 TemplateURL* FindNewDefaultSearchProvider();
255 // Performs the same actions that happen when the prepopulate data version is
256 // revved: all existing prepopulated entries are checked against the current
257 // prepopulate data, any now-extraneous safe_for_autoreplace() entries are
258 // removed, any existing engines are reset to the provided data (except for
259 // user-edited names or keywords), and any new prepopulated engines are
260 // added.
262 // After this, the default search engine is reset to the default entry in the
263 // prepopulate data.
264 void RepairPrepopulatedSearchEngines();
266 // Observers used to listen for changes to the model.
267 // TemplateURLService does NOT delete the observers when deleted.
268 void AddObserver(TemplateURLServiceObserver* observer);
269 void RemoveObserver(TemplateURLServiceObserver* observer);
271 // Loads the keywords. This has no effect if the keywords have already been
272 // loaded.
273 // Observers are notified when loading completes via the method
274 // OnTemplateURLServiceChanged.
275 void Load();
277 // Registers a callback to be called when the service has loaded.
279 // If the service has already loaded, this function does nothing.
280 scoped_ptr<Subscription> RegisterOnLoadedCallback(
281 const base::Closure& callback);
283 #if defined(UNIT_TEST)
284 void set_loaded(bool value) { loaded_ = value; }
285 #endif
287 // Whether or not the keywords have been loaded.
288 bool loaded() { return loaded_; }
290 // Notification that the keywords have been loaded.
291 // This is invoked from WebDataService, and should not be directly
292 // invoked.
293 void OnWebDataServiceRequestDone(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 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 syncer::SyncDataList GetAllSyncData(syncer::ModelType type) const override;
313 // Process new search engine changes from Sync, merging them into our local
314 // data. This may send notifications if local search engines are added,
315 // updated or removed.
316 syncer::SyncError ProcessSyncChanges(
317 const tracked_objects::Location& from_here,
318 const syncer::SyncChangeList& change_list) override;
319 // Merge initial search engine data from Sync and push any local changes up
320 // to Sync. This may send notifications if local search engines are added,
321 // updated or removed.
322 syncer::SyncMergeResult MergeDataAndStartSyncing(
323 syncer::ModelType type,
324 const syncer::SyncDataList& initial_sync_data,
325 scoped_ptr<syncer::SyncChangeProcessor> sync_processor,
326 scoped_ptr<syncer::SyncErrorFactory> sync_error_factory) override;
327 void StopSyncing(syncer::ModelType type) override;
329 // Processes a local TemplateURL change for Sync. |turl| is the TemplateURL
330 // that has been modified, and |type| is the Sync ChangeType that took place.
331 // This may send a new SyncChange to the cloud. If our model has not yet been
332 // associated with Sync, or if this is triggered by a Sync change, then this
333 // does nothing.
334 void ProcessTemplateURLChange(const tracked_objects::Location& from_here,
335 const TemplateURL* turl,
336 syncer::SyncChange::SyncChangeType type);
338 // Returns a SearchTermsData which can be used to call TemplateURL methods.
339 const SearchTermsData& search_terms_data() const {
340 return *search_terms_data_;
343 // Returns a SyncData with a sync representation of the search engine data
344 // from |turl|.
345 static syncer::SyncData CreateSyncDataFromTemplateURL(
346 const TemplateURL& turl);
348 // Creates a new heap-allocated TemplateURL* which is populated by overlaying
349 // |sync_data| atop |existing_turl|. |existing_turl| may be NULL; if not it
350 // remains unmodified. The caller owns the returned TemplateURL*.
352 // If the created TemplateURL is migrated in some way from out-of-date sync
353 // data, an appropriate SyncChange is added to |change_list|. If the sync
354 // data is bad for some reason, an ACTION_DELETE change is added and the
355 // function returns NULL.
356 static scoped_ptr<TemplateURL> CreateTemplateURLFromTemplateURLAndSyncData(
357 TemplateURLServiceClient* client,
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 private:
377 FRIEND_TEST_ALL_PREFIXES(TemplateURLServiceTest, TestManagedDefaultSearch);
378 FRIEND_TEST_ALL_PREFIXES(TemplateURLServiceTest,
379 UpdateKeywordSearchTermsForURL);
380 FRIEND_TEST_ALL_PREFIXES(TemplateURLServiceTest,
381 DontUpdateKeywordSearchForNonReplaceable);
382 FRIEND_TEST_ALL_PREFIXES(TemplateURLServiceTest, ChangeGoogleBaseValue);
383 FRIEND_TEST_ALL_PREFIXES(TemplateURLServiceTest, MergeDeletesUnusedProviders);
384 FRIEND_TEST_ALL_PREFIXES(TemplateURLServiceTest, AddExtensionKeyword);
385 FRIEND_TEST_ALL_PREFIXES(TemplateURLServiceSyncTest, UniquifyKeyword);
386 FRIEND_TEST_ALL_PREFIXES(TemplateURLServiceSyncTest,
387 IsLocalTemplateURLBetter);
388 FRIEND_TEST_ALL_PREFIXES(TemplateURLServiceSyncTest,
389 ResolveSyncKeywordConflict);
390 FRIEND_TEST_ALL_PREFIXES(TemplateURLServiceSyncTest, PreSyncDeletes);
391 FRIEND_TEST_ALL_PREFIXES(TemplateURLServiceSyncTest, MergeInSyncTemplateURL);
393 friend class InstantUnitTestBase;
394 friend class TemplateURLServiceTestUtil;
396 typedef std::map<base::string16, TemplateURL*> KeywordToTemplateMap;
397 typedef std::map<std::string, TemplateURL*> GUIDToTemplateMap;
399 // Declaration of values to be used in an enumerated histogram to tally
400 // changes to the default search provider from various entry points. In
401 // particular, we use this to see what proportion of changes are from Sync
402 // entry points, to help spot erroneous Sync activity.
403 enum DefaultSearchChangeOrigin {
404 // Various known Sync entry points.
405 DSP_CHANGE_SYNC_PREF,
406 DSP_CHANGE_SYNC_ADD,
407 DSP_CHANGE_SYNC_DELETE,
408 DSP_CHANGE_SYNC_NOT_MANAGED,
409 // "Other" origins. We differentiate between Sync and not Sync so we know if
410 // certain changes were intentionally from the system, or possibly some
411 // unintentional change from when we were Syncing.
412 DSP_CHANGE_SYNC_UNINTENTIONAL,
413 // All changes that don't fall into another category; we can't reorder the
414 // list for clarity as this would screw up stat collection.
415 DSP_CHANGE_OTHER,
416 // Changed through "Profile Reset" feature.
417 DSP_CHANGE_PROFILE_RESET,
418 // Changed by an extension through the Override Settings API.
419 DSP_CHANGE_OVERRIDE_SETTINGS_EXTENSION,
420 // New DSP during database/prepopulate data load, which was not previously
421 // in the known engine set, and with no previous value in prefs. The
422 // typical time to see this is during first run.
423 DSP_CHANGE_NEW_ENGINE_NO_PREFS,
424 // Boundary value.
425 DSP_CHANGE_MAX,
428 // Helper functor for FindMatchingKeywords(), for finding the range of
429 // keywords which begin with a prefix.
430 class LessWithPrefix;
432 void Init(const Initializer* initializers, int num_initializers);
434 void RemoveFromMaps(TemplateURL* template_url);
436 void AddToMaps(TemplateURL* template_url);
438 // Sets the keywords. This is used once the keywords have been loaded.
439 // This does NOT notify the delegate or the database.
441 // This transfers ownership of the elements in |urls| to |this|, and may
442 // delete some elements, so it's not safe for callers to access any elements
443 // after calling; to reinforce this, this function clears |urls| on exit.
444 void SetTemplateURLs(TemplateURLVector* urls);
446 // Transitions to the loaded state.
447 void ChangeToLoadedState();
449 // Called by DefaultSearchManager when the effective default search engine has
450 // changed.
451 void OnDefaultSearchChange(const TemplateURLData* new_dse_data,
452 DefaultSearchManager::Source source);
454 // Applies a DSE change and reports metrics if appropriate.
455 void ApplyDefaultSearchChange(const TemplateURLData* new_dse_data,
456 DefaultSearchManager::Source source);
459 // Applies a DSE change. May be called at startup or after transitioning to
460 // the loaded state. Returns true if a change actually occurred.
461 bool ApplyDefaultSearchChangeNoMetrics(const TemplateURLData* new_dse_data,
462 DefaultSearchManager::Source source);
464 // Returns true if there is no TemplateURL that has a search url with the
465 // specified host, or the only TemplateURLs matching the specified host can
466 // be replaced.
467 bool CanReplaceKeywordForHost(const std::string& host,
468 TemplateURL** to_replace);
470 // Returns true if the TemplateURL is replaceable. This doesn't look at the
471 // uniqueness of the keyword or host and is intended to be called after those
472 // checks have been done. This returns true if the TemplateURL doesn't appear
473 // in the default list and is marked as safe_for_autoreplace.
474 bool CanReplace(const TemplateURL* t_url);
476 // Like GetTemplateURLForKeyword(), but ignores extension-provided keywords.
477 TemplateURL* FindNonExtensionTemplateURLForKeyword(
478 const base::string16& keyword);
480 // Updates the information in |existing_turl| using the information from
481 // |new_values|, but the ID for |existing_turl| is retained. Notifying
482 // observers is the responsibility of the caller. Returns whether
483 // |existing_turl| was found in |template_urls_| and thus could be updated.
485 // NOTE: This should not be called with an extension keyword as there are no
486 // updates needed in that case.
487 bool UpdateNoNotify(TemplateURL* existing_turl,
488 const TemplateURL& new_values);
490 // If the TemplateURL comes from a prepopulated URL available in the current
491 // country, update all its fields save for the keyword, short name and id so
492 // that they match the internal prepopulated URL. TemplateURLs not coming from
493 // a prepopulated URL are not modified.
494 static void UpdateTemplateURLIfPrepopulated(TemplateURL* existing_turl,
495 PrefService* prefs);
497 // If the TemplateURL's sync GUID matches the kSyncedDefaultSearchProviderGUID
498 // preference it will be used to update the DSE in memory and as persisted in
499 // preferences.
500 void MaybeUpdateDSEAfterSync(TemplateURL* synced_turl);
502 // Iterates through the TemplateURLs to see if one matches the visited url.
503 // For each TemplateURL whose url matches the visited url
504 // SetKeywordSearchTermsForURL is invoked.
505 void UpdateKeywordSearchTermsForURL(const URLVisitedDetails& details);
507 // If necessary, generates a visit for the site http:// + t_url.keyword().
508 void AddTabToSearchVisit(const TemplateURL& t_url);
510 // Requests the Google URL tracker to check the server if necessary.
511 void RequestGoogleURLTrackerServerCheckIfNecessary();
513 // Invoked when the Google base URL has changed. Updates the mapping for all
514 // TemplateURLs that have a replacement term of {google:baseURL} or
515 // {google:baseSuggestURL}.
516 void GoogleBaseURLChanged();
518 // Adds a new TemplateURL to this model. TemplateURLService will own the
519 // reference, and delete it when the TemplateURL is removed.
520 // If |newly_adding| is false, we assume that this TemplateURL was already
521 // part of the model in the past, and therefore we don't need to do things
522 // like assign it an ID or notify sync.
523 // This function guarantees that on return the model will not have two
524 // non-extension TemplateURLs with the same keyword. If that means that it
525 // cannot add the provided argument, it will delete it and return false.
526 // Caller is responsible for notifying observers if this function returns
527 // true.
528 bool AddNoNotify(TemplateURL* template_url, bool newly_adding);
530 // Removes the keyword from the model. This deletes the supplied TemplateURL.
531 // This fails if the supplied template_url is the default search provider.
532 // Caller is responsible for notifying observers.
533 void RemoveNoNotify(TemplateURL* template_url);
535 // Like ResetTemplateURL(), but instead of notifying observers, returns
536 // whether anything has changed.
537 bool ResetTemplateURLNoNotify(TemplateURL* url,
538 const base::string16& title,
539 const base::string16& keyword,
540 const std::string& search_url);
542 // Notify the observers that the model has changed. This is done only if the
543 // model is loaded.
544 void NotifyObservers();
546 // Updates |template_urls| so that the only "created by policy" entry is
547 // |default_from_prefs|. |default_from_prefs| may be NULL if there is no
548 // policy-defined DSE in effect.
549 void UpdateProvidersCreatedByPolicy(
550 TemplateURLVector* template_urls,
551 const TemplateURLData* default_from_prefs);
553 // Resets the sync GUID of the specified TemplateURL and persists the change
554 // to the database. This does not notify observers.
555 void ResetTemplateURLGUID(TemplateURL* url, const std::string& guid);
557 // Attempts to generate a unique keyword for |turl| based on its original
558 // keyword. If its keyword is already unique, that is returned. Otherwise, it
559 // tries to return the autogenerated keyword if that is unique to the Service,
560 // and finally it repeatedly appends special characters to the keyword until
561 // it is unique to the Service. If |force| is true, then this will only
562 // execute the special character appending functionality.
563 base::string16 UniquifyKeyword(const TemplateURL& turl, bool force);
565 // Returns true iff |local_turl| is considered "better" than |sync_turl| for
566 // the purposes of resolving conflicts. |local_turl| must be a TemplateURL
567 // known to the local model (though it may already be synced), and |sync_turl|
568 // is a new TemplateURL known to Sync but not yet known to the local model.
569 // The criteria for if |local_turl| is better than |sync_turl| is whether any
570 // of the following are true:
571 // * |local_turl|'s last_modified timestamp is newer than sync_turl.
572 // * |local_turl| is created by policy.
573 // * |local_turl| is the local default search provider.
574 bool IsLocalTemplateURLBetter(const TemplateURL* local_turl,
575 const TemplateURL* sync_turl);
577 // Given two synced TemplateURLs with a conflicting keyword, one of which
578 // needs to be added to or updated in the local model (|unapplied_sync_turl|)
579 // and one which is already known to the local model (|applied_sync_turl|),
580 // prepares the local model so that |unapplied_sync_turl| can be added to it,
581 // or applied as an update to an existing TemplateURL.
582 // Since both entries are known to Sync and one of their keywords will change,
583 // an ACTION_UPDATE will be appended to |change_list| to reflect this change.
584 // Note that |applied_sync_turl| must not be an extension keyword.
585 void ResolveSyncKeywordConflict(TemplateURL* unapplied_sync_turl,
586 TemplateURL* applied_sync_turl,
587 syncer::SyncChangeList* change_list);
589 // Adds |sync_turl| into the local model, possibly removing or updating a
590 // local TemplateURL to make room for it. This expects |sync_turl| to be a new
591 // entry from Sync, not currently known to the local model. |sync_data| should
592 // be a SyncDataMap where the contents are entries initially known to Sync
593 // during MergeDataAndStartSyncing.
594 // Any necessary updates to Sync will be appended to |change_list|. This can
595 // include updates on local TemplateURLs, if they are found in |sync_data|.
596 // |initial_data| should be a SyncDataMap of the entries known to the local
597 // model during MergeDataAndStartSyncing. If |sync_turl| replaces a local
598 // entry, that entry is removed from |initial_data| to prevent it from being
599 // sent up to Sync.
600 // |merge_result| tracks the changes made to the local model. Added/modified/
601 // deleted are updated depending on how the |sync_turl| is merged in.
602 // This should only be called from MergeDataAndStartSyncing.
603 void MergeInSyncTemplateURL(TemplateURL* sync_turl,
604 const SyncDataMap& sync_data,
605 syncer::SyncChangeList* change_list,
606 SyncDataMap* local_data,
607 syncer::SyncMergeResult* merge_result);
609 // Goes through a vector of TemplateURLs and ensure that both the in-memory
610 // and database copies have valid sync_guids. This is to fix crbug.com/102038,
611 // where old entries were being pushed to Sync without a sync_guid.
612 void PatchMissingSyncGUIDs(TemplateURLVector* template_urls);
614 void OnSyncedDefaultSearchProviderGUIDChanged();
616 // Adds |template_urls| to |template_urls_|.
618 // This transfers ownership of the elements in |template_urls| to |this|, and
619 // may delete some elements, so it's not safe for callers to access any
620 // elements after calling; to reinforce this, this function clears
621 // |template_urls| on exit.
622 void AddTemplateURLs(TemplateURLVector* template_urls);
624 // Returns the TemplateURL corresponding to |prepopulated_id|, if any.
625 TemplateURL* FindPrepopulatedTemplateURL(int prepopulated_id);
627 // Returns the TemplateURL associated with |extension_id|, if any.
628 TemplateURL* FindTemplateURLForExtension(const std::string& extension_id,
629 TemplateURL::Type type);
631 // Finds the extension-supplied TemplateURL that matches |data|, if any.
632 TemplateURL* FindMatchingExtensionTemplateURL(const TemplateURLData& data,
633 TemplateURL::Type type);
635 // Finds the most recently-installed NORMAL_CONTROLLED_BY_EXTENSION engine
636 // that supports replacement and wants to be default, if any. Notifies the
637 // DefaultSearchManager, which might change the effective default search
638 // engine.
639 void UpdateExtensionDefaultSearchEngine();
642 // ---------- Browser state related members ---------------------------------
643 PrefService* prefs_;
645 scoped_ptr<SearchTermsData> search_terms_data_;
647 // ---------- Dependencies on other components ------------------------------
648 // Service used to store entries.
649 scoped_refptr<KeywordWebDataService> web_data_service_;
651 scoped_ptr<TemplateURLServiceClient> client_;
653 GoogleURLTracker* google_url_tracker_;
655 // ---------- Metrics related members ---------------------------------------
656 rappor::RapporService* rappor_service_;
658 // This closure is run when the default search provider is set to Google.
659 base::Closure dsp_change_callback_;
662 PrefChangeRegistrar pref_change_registrar_;
664 // Mapping from keyword to the TemplateURL.
665 KeywordToTemplateMap keyword_to_template_map_;
667 // Mapping from Sync GUIDs to the TemplateURL.
668 GUIDToTemplateMap guid_to_template_map_;
670 TemplateURLVector template_urls_;
672 ObserverList<TemplateURLServiceObserver> model_observers_;
674 // Maps from host to set of TemplateURLs whose search url host is host.
675 // NOTE: This is always non-NULL; we use a scoped_ptr<> to avoid circular
676 // header dependencies.
677 scoped_ptr<SearchHostToURLsMap> provider_map_;
679 // Whether the keywords have been loaded.
680 bool loaded_;
682 // Set when the web data service fails to load properly. This prevents
683 // further communication with sync or writing to prefs, so we don't persist
684 // inconsistent state data anywhere.
685 bool load_failed_;
687 // If non-zero, we're waiting on a load.
688 KeywordWebDataService::Handle load_handle_;
690 // All visits that occurred before we finished loading. Once loaded
691 // UpdateKeywordSearchTermsForURL is invoked for each element of the vector.
692 std::vector<URLVisitedDetails> visits_to_add_;
694 // Once loaded, the default search provider. This is a pointer to a
695 // TemplateURL owned by |template_urls_|.
696 TemplateURL* default_search_provider_;
698 // A temporary location for the DSE until Web Data has been loaded and it can
699 // be merged into |template_urls_|.
700 scoped_ptr<TemplateURL> initial_default_search_provider_;
702 // Source of the default search provider.
703 DefaultSearchManager::Source default_search_provider_source_;
705 // ID assigned to next TemplateURL added to this model. This is an ever
706 // increasing integer that is initialized from the database.
707 TemplateURLID next_id_;
709 // Function returning current time in base::Time units.
710 TimeProvider* time_provider_;
712 // Do we have an active association between the TemplateURLs and sync models?
713 // Set in MergeDataAndStartSyncing, reset in StopSyncing. While this is not
714 // set, we ignore any local search engine changes (when we start syncing we
715 // will look up the most recent values anyways).
716 bool models_associated_;
718 // Whether we're currently processing changes from the syncer. While this is
719 // true, we ignore any local search engine changes, since we triggered them.
720 bool processing_syncer_changes_;
722 // Sync's syncer::SyncChange handler. We push all our changes through this.
723 scoped_ptr<syncer::SyncChangeProcessor> sync_processor_;
725 // Sync's error handler. We use it to create a sync error.
726 scoped_ptr<syncer::SyncErrorFactory> sync_error_factory_;
728 // A set of sync GUIDs denoting TemplateURLs that have been removed from this
729 // model or the underlying KeywordWebDataService prior to
730 // MergeDataAndStartSyncing.
731 // This set is used to determine what entries from the server we want to
732 // ignore locally and return a delete command for.
733 std::set<std::string> pre_sync_deletes_;
735 // This is used to log the origin of changes to the default search provider.
736 // We set this value to increasingly specific values when we know what is the
737 // cause/origin of a default search change.
738 DefaultSearchChangeOrigin dsp_change_origin_;
740 // Stores a list of callbacks to be run after TemplateURLService has loaded.
741 base::CallbackList<void(void)> on_loaded_callbacks_;
743 // Helper class to manage the default search engine.
744 DefaultSearchManager default_search_manager_;
746 scoped_ptr<GoogleURLTracker::Subscription> google_url_updated_subscription_;
748 DISALLOW_COPY_AND_ASSIGN(TemplateURLService);
751 #endif // COMPONENTS_SEARCH_ENGINES_TEMPLATE_URL_SERVICE_H_