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_
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"
32 class SearchHostToURLsMap
;
33 class SearchTermsData
;
35 struct TemplateURLData
;
36 class TemplateURLServiceClient
;
37 class TemplateURLServiceObserver
;
45 class SyncErrorFactory
;
48 namespace user_prefs
{
49 class PrefRegistrySyncable
;
52 // TemplateURLService is the backend for keywords. It's used by
53 // KeywordAutocomplete.
55 // TemplateURLService stores a vector of TemplateURLs. The TemplateURLs are
56 // persisted to the database maintained by KeywordWebDataService.
57 // *ALL* mutations to the TemplateURLs must funnel through TemplateURLService.
58 // This allows TemplateURLService to notify listeners of changes as well as keep
59 // the database in sync.
61 // TemplateURLService does not load the vector of TemplateURLs in its
62 // constructor (except for testing). Use the Load method to trigger a load.
63 // When TemplateURLService has completed loading, observers are notified via
64 // OnTemplateURLServiceChanged, or by a callback registered prior to calling
67 // TemplateURLService takes ownership of any TemplateURL passed to it. If there
68 // is a KeywordWebDataService, deletion is handled by KeywordWebDataService,
69 // otherwise TemplateURLService handles deletion.
71 class TemplateURLService
: public WebDataServiceConsumer
,
73 public syncer::SyncableService
{
75 typedef std::map
<std::string
, std::string
> QueryTerms
;
76 typedef std::vector
<TemplateURL
*> TemplateURLVector
;
77 typedef std::map
<std::string
, syncer::SyncData
> SyncDataMap
;
78 typedef base::CallbackList
<void(void)>::Subscription Subscription
;
80 // Struct used for initializing the data store with fake data.
81 // Each initializer is mapped to a TemplateURL.
83 const char* const keyword
;
84 const char* const url
;
85 const char* const content
;
88 struct URLVisitedDetails
{
90 bool is_keyword_transition
;
95 scoped_ptr
<SearchTermsData
> search_terms_data
,
96 const scoped_refptr
<KeywordWebDataService
>& web_data_service
,
97 scoped_ptr
<TemplateURLServiceClient
> client
,
98 GoogleURLTracker
* google_url_tracker
,
99 rappor::RapporService
* rappor_service
,
100 const base::Closure
& dsp_change_callback
);
101 // The following is for testing.
102 TemplateURLService(const Initializer
* initializers
, const int count
);
103 ~TemplateURLService() override
;
105 // Register Profile preferences in |registry|.
106 static void RegisterProfilePrefs(user_prefs::PrefRegistrySyncable
* registry
);
108 // Removes any unnecessary characters from a user input keyword.
109 // This removes the leading scheme, "www." and any trailing slash.
110 static base::string16
CleanUserInputKeyword(const base::string16
& keyword
);
112 // Returns true if there is no TemplateURL that conflicts with the
113 // keyword/url pair, or there is one but it can be replaced. If there is an
114 // existing keyword that can be replaced and template_url_to_replace is
115 // non-NULL, template_url_to_replace is set to the keyword to replace.
117 // |url| is the URL of the search query. This is used to prevent auto-adding
118 // a keyword for hosts already associated with a manually-edited keyword.
119 bool CanAddAutogeneratedKeyword(const base::string16
& keyword
,
121 TemplateURL
** template_url_to_replace
);
123 // Returns (in |matches|) all TemplateURLs whose keywords begin with |prefix|,
124 // sorted shortest keyword-first. If |support_replacement_only| is true, only
125 // TemplateURLs that support replacement are returned.
126 void FindMatchingKeywords(const base::string16
& prefix
,
127 bool support_replacement_only
,
128 TemplateURLVector
* matches
);
130 // Looks up |keyword| and returns the element it maps to. Returns NULL if
131 // the keyword was not found.
132 // The caller should not try to delete the returned pointer; the data store
133 // retains ownership of it.
134 TemplateURL
* GetTemplateURLForKeyword(const base::string16
& keyword
);
136 // Returns that TemplateURL with the specified GUID, or NULL if not found.
137 // The caller should not try to delete the returned pointer; the data store
138 // retains ownership of it.
139 TemplateURL
* GetTemplateURLForGUID(const std::string
& sync_guid
);
141 // Returns the first TemplateURL found with a URL using the specified |host|,
142 // or NULL if there are no such TemplateURLs
143 TemplateURL
* GetTemplateURLForHost(const std::string
& host
);
145 // Takes ownership of |template_url| and adds it to this model. For obvious
146 // reasons, it is illegal to Add() the same |template_url| pointer twice.
147 // Returns true if the Add is successful.
148 bool Add(TemplateURL
* template_url
);
150 // Like Add(), but overwrites the |template_url|'s values with the provided
152 void AddWithOverrides(TemplateURL
* template_url
,
153 const base::string16
& short_name
,
154 const base::string16
& keyword
,
155 const std::string
& url
);
157 // Adds a search engine with the specified info.
158 void AddExtensionControlledTURL(
159 TemplateURL
* template_url
,
160 scoped_ptr
<TemplateURL::AssociatedExtensionInfo
> info
);
162 // Removes the keyword from the model. This deletes the supplied TemplateURL.
163 // This fails if the supplied template_url is the default search provider.
164 void Remove(TemplateURL
* template_url
);
166 // Removes any TemplateURL of the specified |type| associated with
167 // |extension_id|. Unlike with Remove(), this can be called when the
168 // TemplateURL in question is the current default search provider.
169 void RemoveExtensionControlledTURL(const std::string
& extension_id
,
170 TemplateURL::Type type
);
172 // Removes all auto-generated keywords that were created on or after the
174 void RemoveAutoGeneratedSince(base::Time created_after
);
176 // Removes all auto-generated keywords that were created in the specified
178 void RemoveAutoGeneratedBetween(base::Time created_after
,
179 base::Time created_before
);
181 // Removes all auto-generated keywords that were created in the specified
182 // range for a specified |origin|. If |origin| is empty, deletes all
183 // auto-generated keywords in the range.
184 void RemoveAutoGeneratedForOriginBetween(const GURL
& origin
,
185 base::Time created_after
,
186 base::Time created_before
);
188 // Adds a TemplateURL for an extension with an omnibox keyword.
189 // Only 1 keyword is allowed for a given extension. If a keyword
190 // already exists for this extension, does nothing.
191 void RegisterOmniboxKeyword(const std::string
& extension_id
,
192 const std::string
& extension_name
,
193 const std::string
& keyword
,
194 const std::string
& template_url_string
);
196 // Returns the set of URLs describing the keywords. The elements are owned
197 // by TemplateURLService and should not be deleted.
198 TemplateURLVector
GetTemplateURLs();
200 // Increment the usage count of a keyword.
201 // Called when a URL is loaded that was generated from a keyword.
202 void IncrementUsageCount(TemplateURL
* url
);
204 // Resets the title, keyword and search url of the specified TemplateURL.
205 // The TemplateURL is marked as not replaceable.
206 void ResetTemplateURL(TemplateURL
* url
,
207 const base::string16
& title
,
208 const base::string16
& keyword
,
209 const std::string
& search_url
);
211 // Return true if the given |url| can be made the default. This returns false
212 // regardless of |url| if the default search provider is managed by policy or
213 // controlled by an extension.
214 bool CanMakeDefault(const TemplateURL
* url
);
216 // Set the default search provider. |url| may be null.
217 // This will assert if the default search is managed; the UI should not be
218 // invoking this method in that situation.
219 void SetUserSelectedDefaultSearchProvider(TemplateURL
* url
);
221 // Returns the default search provider. If the TemplateURLService hasn't been
222 // loaded, the default search provider is pulled from preferences.
224 // NOTE: At least in unittest mode, this may return NULL.
225 // TODO(blundell): See if all callers can be converted to take in const
226 // pointers and eliminate this version of the method.
227 TemplateURL
* GetDefaultSearchProvider();
228 const TemplateURL
* GetDefaultSearchProvider() const;
230 // Returns true if the |url| is a search results page from the default search
232 bool IsSearchResultsPageFromDefaultSearchProvider(const GURL
& url
) const;
234 // Returns true if the default search is managed through group policy.
235 bool is_default_search_managed() const {
236 return default_search_provider_source_
== DefaultSearchManager::FROM_POLICY
;
239 // Returns true if the default search provider is controlled by an extension.
240 bool IsExtensionControlledDefaultSearch();
242 // Returns the default search specified in the prepopulated data, if it
243 // exists. If not, returns first URL in |template_urls_|, or NULL if that's
244 // empty. The returned object is owned by TemplateURLService and can be
245 // destroyed at any time so should be used right after the call.
246 TemplateURL
* FindNewDefaultSearchProvider();
248 // Performs the same actions that happen when the prepopulate data version is
249 // revved: all existing prepopulated entries are checked against the current
250 // prepopulate data, any now-extraneous safe_for_autoreplace() entries are
251 // removed, any existing engines are reset to the provided data (except for
252 // user-edited names or keywords), and any new prepopulated engines are
255 // After this, the default search engine is reset to the default entry in the
257 void RepairPrepopulatedSearchEngines();
259 // Observers used to listen for changes to the model.
260 // TemplateURLService does NOT delete the observers when deleted.
261 void AddObserver(TemplateURLServiceObserver
* observer
);
262 void RemoveObserver(TemplateURLServiceObserver
* observer
);
264 // Loads the keywords. This has no effect if the keywords have already been
266 // Observers are notified when loading completes via the method
267 // OnTemplateURLServiceChanged.
270 // Registers a callback to be called when the service has loaded.
272 // If the service has already loaded, this function does nothing.
273 scoped_ptr
<Subscription
> RegisterOnLoadedCallback(
274 const base::Closure
& callback
);
276 #if defined(UNIT_TEST)
277 void set_loaded(bool value
) { loaded_
= value
; }
280 // Whether or not the keywords have been loaded.
281 bool loaded() { return loaded_
; }
283 // Notification that the keywords have been loaded.
284 // This is invoked from WebDataService, and should not be directly
286 void OnWebDataServiceRequestDone(KeywordWebDataService::Handle h
,
287 const WDTypedResult
* result
) override
;
289 // Returns the locale-direction-adjusted short name for the given keyword.
290 // Also sets the out param to indicate whether the keyword belongs to an
291 // Omnibox extension.
292 base::string16
GetKeywordShortName(const base::string16
& keyword
,
293 bool* is_omnibox_api_extension_keyword
);
295 // Called by the history service when a URL is visited.
296 void OnHistoryURLVisited(const URLVisitedDetails
& details
);
298 // KeyedService implementation.
299 void Shutdown() override
;
301 // syncer::SyncableService implementation.
303 // Returns all syncable TemplateURLs from this model as SyncData. This should
304 // include every search engine and no Extension keywords.
305 syncer::SyncDataList
GetAllSyncData(syncer::ModelType type
) const override
;
306 // Process new search engine changes from Sync, merging them into our local
307 // data. This may send notifications if local search engines are added,
308 // updated or removed.
309 syncer::SyncError
ProcessSyncChanges(
310 const tracked_objects::Location
& from_here
,
311 const syncer::SyncChangeList
& change_list
) override
;
312 // Merge initial search engine data from Sync and push any local changes up
313 // to Sync. This may send notifications if local search engines are added,
314 // updated or removed.
315 syncer::SyncMergeResult
MergeDataAndStartSyncing(
316 syncer::ModelType type
,
317 const syncer::SyncDataList
& initial_sync_data
,
318 scoped_ptr
<syncer::SyncChangeProcessor
> sync_processor
,
319 scoped_ptr
<syncer::SyncErrorFactory
> sync_error_factory
) override
;
320 void StopSyncing(syncer::ModelType type
) override
;
322 // Processes a local TemplateURL change for Sync. |turl| is the TemplateURL
323 // that has been modified, and |type| is the Sync ChangeType that took place.
324 // This may send a new SyncChange to the cloud. If our model has not yet been
325 // associated with Sync, or if this is triggered by a Sync change, then this
327 void ProcessTemplateURLChange(const tracked_objects::Location
& from_here
,
328 const TemplateURL
* turl
,
329 syncer::SyncChange::SyncChangeType type
);
331 // Returns a SearchTermsData which can be used to call TemplateURL methods.
332 const SearchTermsData
& search_terms_data() const {
333 return *search_terms_data_
;
336 // Returns a SyncData with a sync representation of the search engine data
338 static syncer::SyncData
CreateSyncDataFromTemplateURL(
339 const TemplateURL
& turl
);
341 // Creates a new heap-allocated TemplateURL* which is populated by overlaying
342 // |sync_data| atop |existing_turl|. |existing_turl| may be NULL; if not it
343 // remains unmodified. The caller owns the returned TemplateURL*.
345 // If the created TemplateURL is migrated in some way from out-of-date sync
346 // data, an appropriate SyncChange is added to |change_list|. If the sync
347 // data is bad for some reason, an ACTION_DELETE change is added and the
348 // function returns NULL.
349 static scoped_ptr
<TemplateURL
> CreateTemplateURLFromTemplateURLAndSyncData(
350 TemplateURLServiceClient
* client
,
352 const SearchTermsData
& search_terms_data
,
353 TemplateURL
* existing_turl
,
354 const syncer::SyncData
& sync_data
,
355 syncer::SyncChangeList
* change_list
);
357 // Returns a map mapping Sync GUIDs to pointers to syncer::SyncData.
358 static SyncDataMap
CreateGUIDToSyncDataMap(
359 const syncer::SyncDataList
& sync_data
);
361 #if defined(UNIT_TEST)
362 void set_clock(scoped_ptr
<base::Clock
> clock
) { clock_
= clock
.Pass(); }
366 FRIEND_TEST_ALL_PREFIXES(TemplateURLServiceTest
, TestManagedDefaultSearch
);
367 FRIEND_TEST_ALL_PREFIXES(TemplateURLServiceTest
,
368 UpdateKeywordSearchTermsForURL
);
369 FRIEND_TEST_ALL_PREFIXES(TemplateURLServiceTest
,
370 DontUpdateKeywordSearchForNonReplaceable
);
371 FRIEND_TEST_ALL_PREFIXES(TemplateURLServiceTest
, ChangeGoogleBaseValue
);
372 FRIEND_TEST_ALL_PREFIXES(TemplateURLServiceTest
, MergeDeletesUnusedProviders
);
373 FRIEND_TEST_ALL_PREFIXES(TemplateURLServiceTest
, AddExtensionKeyword
);
374 FRIEND_TEST_ALL_PREFIXES(TemplateURLServiceSyncTest
, UniquifyKeyword
);
375 FRIEND_TEST_ALL_PREFIXES(TemplateURLServiceSyncTest
,
376 IsLocalTemplateURLBetter
);
377 FRIEND_TEST_ALL_PREFIXES(TemplateURLServiceSyncTest
,
378 ResolveSyncKeywordConflict
);
379 FRIEND_TEST_ALL_PREFIXES(TemplateURLServiceSyncTest
, PreSyncDeletes
);
380 FRIEND_TEST_ALL_PREFIXES(TemplateURLServiceSyncTest
, MergeInSyncTemplateURL
);
382 friend class InstantUnitTestBase
;
383 friend class TemplateURLServiceTestUtil
;
385 typedef std::map
<base::string16
, TemplateURL
*> KeywordToTemplateMap
;
386 typedef std::map
<std::string
, TemplateURL
*> GUIDToTemplateMap
;
388 // Declaration of values to be used in an enumerated histogram to tally
389 // changes to the default search provider from various entry points. In
390 // particular, we use this to see what proportion of changes are from Sync
391 // entry points, to help spot erroneous Sync activity.
392 enum DefaultSearchChangeOrigin
{
393 // Various known Sync entry points.
394 DSP_CHANGE_SYNC_PREF
,
396 DSP_CHANGE_SYNC_DELETE
,
397 DSP_CHANGE_SYNC_NOT_MANAGED
,
398 // "Other" origins. We differentiate between Sync and not Sync so we know if
399 // certain changes were intentionally from the system, or possibly some
400 // unintentional change from when we were Syncing.
401 DSP_CHANGE_SYNC_UNINTENTIONAL
,
402 // All changes that don't fall into another category; we can't reorder the
403 // list for clarity as this would screw up stat collection.
405 // Changed through "Profile Reset" feature.
406 DSP_CHANGE_PROFILE_RESET
,
407 // Changed by an extension through the Override Settings API.
408 DSP_CHANGE_OVERRIDE_SETTINGS_EXTENSION
,
409 // New DSP during database/prepopulate data load, which was not previously
410 // in the known engine set, and with no previous value in prefs. The
411 // typical time to see this is during first run.
412 DSP_CHANGE_NEW_ENGINE_NO_PREFS
,
417 // Helper functor for FindMatchingKeywords(), for finding the range of
418 // keywords which begin with a prefix.
419 class LessWithPrefix
;
421 void Init(const Initializer
* initializers
, int num_initializers
);
423 void RemoveFromMaps(TemplateURL
* template_url
);
425 void AddToMaps(TemplateURL
* template_url
);
427 // Sets the keywords. This is used once the keywords have been loaded.
428 // This does NOT notify the delegate or the database.
430 // This transfers ownership of the elements in |urls| to |this|, and may
431 // delete some elements, so it's not safe for callers to access any elements
432 // after calling; to reinforce this, this function clears |urls| on exit.
433 void SetTemplateURLs(TemplateURLVector
* urls
);
435 // Transitions to the loaded state.
436 void ChangeToLoadedState();
438 // Called by DefaultSearchManager when the effective default search engine has
440 void OnDefaultSearchChange(const TemplateURLData
* new_dse_data
,
441 DefaultSearchManager::Source source
);
443 // Applies a DSE change and reports metrics if appropriate.
444 void ApplyDefaultSearchChange(const TemplateURLData
* new_dse_data
,
445 DefaultSearchManager::Source source
);
448 // Applies a DSE change. May be called at startup or after transitioning to
449 // the loaded state. Returns true if a change actually occurred.
450 bool ApplyDefaultSearchChangeNoMetrics(const TemplateURLData
* new_dse_data
,
451 DefaultSearchManager::Source source
);
453 // Returns false if there is a TemplateURL that has a search url with the
454 // specified host and that TemplateURL has been manually modified.
455 bool CanAddAutogeneratedKeywordForHost(const std::string
& host
);
457 // Returns true if the TemplateURL is replaceable. This doesn't look at the
458 // uniqueness of the keyword or host and is intended to be called after those
459 // checks have been done. This returns true if the TemplateURL doesn't appear
460 // in the default list and is marked as safe_for_autoreplace.
461 bool CanReplace(const TemplateURL
* t_url
);
463 // Like GetTemplateURLForKeyword(), but ignores extension-provided keywords.
464 TemplateURL
* FindNonExtensionTemplateURLForKeyword(
465 const base::string16
& keyword
);
467 // Updates the information in |existing_turl| using the information from
468 // |new_values|, but the ID for |existing_turl| is retained. Notifying
469 // observers is the responsibility of the caller. Returns whether
470 // |existing_turl| was found in |template_urls_| and thus could be updated.
472 // NOTE: This should not be called with an extension keyword as there are no
473 // updates needed in that case.
474 bool UpdateNoNotify(TemplateURL
* existing_turl
,
475 const TemplateURL
& new_values
);
477 // If the TemplateURL comes from a prepopulated URL available in the current
478 // country, update all its fields save for the keyword, short name and id so
479 // that they match the internal prepopulated URL. TemplateURLs not coming from
480 // a prepopulated URL are not modified.
481 static void UpdateTemplateURLIfPrepopulated(TemplateURL
* existing_turl
,
484 // If the TemplateURL's sync GUID matches the kSyncedDefaultSearchProviderGUID
485 // preference it will be used to update the DSE in memory and as persisted in
487 void MaybeUpdateDSEAfterSync(TemplateURL
* synced_turl
);
489 // Iterates through the TemplateURLs to see if one matches the visited url.
490 // For each TemplateURL whose url matches the visited url
491 // SetKeywordSearchTermsForURL is invoked.
492 void UpdateKeywordSearchTermsForURL(const URLVisitedDetails
& details
);
494 // If necessary, generates a visit for the site http:// + t_url.keyword().
495 void AddTabToSearchVisit(const TemplateURL
& t_url
);
497 // Requests the Google URL tracker to check the server if necessary.
498 void RequestGoogleURLTrackerServerCheckIfNecessary();
500 // Invoked when the Google base URL has changed. Updates the mapping for all
501 // TemplateURLs that have a replacement term of {google:baseURL} or
502 // {google:baseSuggestURL}.
503 void GoogleBaseURLChanged();
505 // Adds a new TemplateURL to this model. TemplateURLService will own the
506 // reference, and delete it when the TemplateURL is removed.
507 // If |newly_adding| is false, we assume that this TemplateURL was already
508 // part of the model in the past, and therefore we don't need to do things
509 // like assign it an ID or notify sync.
510 // This function guarantees that on return the model will not have two
511 // non-extension TemplateURLs with the same keyword. If that means that it
512 // cannot add the provided argument, it will delete it and return false.
513 // Caller is responsible for notifying observers if this function returns
515 bool AddNoNotify(TemplateURL
* template_url
, bool newly_adding
);
517 // Removes the keyword from the model. This deletes the supplied TemplateURL.
518 // This fails if the supplied template_url is the default search provider.
519 // Caller is responsible for notifying observers.
520 void RemoveNoNotify(TemplateURL
* template_url
);
522 // Like ResetTemplateURL(), but instead of notifying observers, returns
523 // whether anything has changed.
524 bool ResetTemplateURLNoNotify(TemplateURL
* url
,
525 const base::string16
& title
,
526 const base::string16
& keyword
,
527 const std::string
& search_url
);
529 // Notify the observers that the model has changed. This is done only if the
531 void NotifyObservers();
533 // Updates |template_urls| so that the only "created by policy" entry is
534 // |default_from_prefs|. |default_from_prefs| may be NULL if there is no
535 // policy-defined DSE in effect.
536 void UpdateProvidersCreatedByPolicy(
537 TemplateURLVector
* template_urls
,
538 const TemplateURLData
* default_from_prefs
);
540 // Resets the sync GUID of the specified TemplateURL and persists the change
541 // to the database. This does not notify observers.
542 void ResetTemplateURLGUID(TemplateURL
* url
, const std::string
& guid
);
544 // Attempts to generate a unique keyword for |turl| based on its original
545 // keyword. If its keyword is already unique, that is returned. Otherwise, it
546 // tries to return the autogenerated keyword if that is unique to the Service,
547 // and finally it repeatedly appends special characters to the keyword until
548 // it is unique to the Service. If |force| is true, then this will only
549 // execute the special character appending functionality.
550 base::string16
UniquifyKeyword(const TemplateURL
& turl
, bool force
);
552 // Returns true iff |local_turl| is considered "better" than |sync_turl| for
553 // the purposes of resolving conflicts. |local_turl| must be a TemplateURL
554 // known to the local model (though it may already be synced), and |sync_turl|
555 // is a new TemplateURL known to Sync but not yet known to the local model.
556 // The criteria for if |local_turl| is better than |sync_turl| is whether any
557 // of the following are true:
558 // * |local_turl|'s last_modified timestamp is newer than sync_turl.
559 // * |local_turl| is created by policy.
560 // * |local_turl| is the local default search provider.
561 bool IsLocalTemplateURLBetter(const TemplateURL
* local_turl
,
562 const TemplateURL
* sync_turl
);
564 // Given two synced TemplateURLs with a conflicting keyword, one of which
565 // needs to be added to or updated in the local model (|unapplied_sync_turl|)
566 // and one which is already known to the local model (|applied_sync_turl|),
567 // prepares the local model so that |unapplied_sync_turl| can be added to it,
568 // or applied as an update to an existing TemplateURL.
569 // Since both entries are known to Sync and one of their keywords will change,
570 // an ACTION_UPDATE will be appended to |change_list| to reflect this change.
571 // Note that |applied_sync_turl| must not be an extension keyword.
572 void ResolveSyncKeywordConflict(TemplateURL
* unapplied_sync_turl
,
573 TemplateURL
* applied_sync_turl
,
574 syncer::SyncChangeList
* change_list
);
576 // Adds |sync_turl| into the local model, possibly removing or updating a
577 // local TemplateURL to make room for it. This expects |sync_turl| to be a new
578 // entry from Sync, not currently known to the local model. |sync_data| should
579 // be a SyncDataMap where the contents are entries initially known to Sync
580 // during MergeDataAndStartSyncing.
581 // Any necessary updates to Sync will be appended to |change_list|. This can
582 // include updates on local TemplateURLs, if they are found in |sync_data|.
583 // |initial_data| should be a SyncDataMap of the entries known to the local
584 // model during MergeDataAndStartSyncing. If |sync_turl| replaces a local
585 // entry, that entry is removed from |initial_data| to prevent it from being
587 // |merge_result| tracks the changes made to the local model. Added/modified/
588 // deleted are updated depending on how the |sync_turl| is merged in.
589 // This should only be called from MergeDataAndStartSyncing.
590 void MergeInSyncTemplateURL(TemplateURL
* sync_turl
,
591 const SyncDataMap
& sync_data
,
592 syncer::SyncChangeList
* change_list
,
593 SyncDataMap
* local_data
,
594 syncer::SyncMergeResult
* merge_result
);
596 // Goes through a vector of TemplateURLs and ensure that both the in-memory
597 // and database copies have valid sync_guids. This is to fix crbug.com/102038,
598 // where old entries were being pushed to Sync without a sync_guid.
599 void PatchMissingSyncGUIDs(TemplateURLVector
* template_urls
);
601 void OnSyncedDefaultSearchProviderGUIDChanged();
603 // Adds |template_urls| to |template_urls_|.
605 // This transfers ownership of the elements in |template_urls| to |this|, and
606 // may delete some elements, so it's not safe for callers to access any
607 // elements after calling; to reinforce this, this function clears
608 // |template_urls| on exit.
609 void AddTemplateURLs(TemplateURLVector
* template_urls
);
611 // Returns the TemplateURL corresponding to |prepopulated_id|, if any.
612 TemplateURL
* FindPrepopulatedTemplateURL(int prepopulated_id
);
614 // Returns the TemplateURL associated with |extension_id|, if any.
615 TemplateURL
* FindTemplateURLForExtension(const std::string
& extension_id
,
616 TemplateURL::Type type
);
618 // Finds the extension-supplied TemplateURL that matches |data|, if any.
619 TemplateURL
* FindMatchingExtensionTemplateURL(const TemplateURLData
& data
,
620 TemplateURL::Type type
);
622 // Finds the most recently-installed NORMAL_CONTROLLED_BY_EXTENSION engine
623 // that supports replacement and wants to be default, if any. Notifies the
624 // DefaultSearchManager, which might change the effective default search
626 void UpdateExtensionDefaultSearchEngine();
629 // ---------- Browser state related members ---------------------------------
632 scoped_ptr
<SearchTermsData
> search_terms_data_
;
634 // ---------- Dependencies on other components ------------------------------
635 // Service used to store entries.
636 scoped_refptr
<KeywordWebDataService
> web_data_service_
;
638 scoped_ptr
<TemplateURLServiceClient
> client_
;
640 GoogleURLTracker
* google_url_tracker_
;
642 // ---------- Metrics related members ---------------------------------------
643 rappor::RapporService
* rappor_service_
;
645 // This closure is run when the default search provider is set to Google.
646 base::Closure dsp_change_callback_
;
649 PrefChangeRegistrar pref_change_registrar_
;
651 // Mapping from keyword to the TemplateURL.
652 KeywordToTemplateMap keyword_to_template_map_
;
654 // Mapping from Sync GUIDs to the TemplateURL.
655 GUIDToTemplateMap guid_to_template_map_
;
657 TemplateURLVector template_urls_
;
659 base::ObserverList
<TemplateURLServiceObserver
> model_observers_
;
661 // Maps from host to set of TemplateURLs whose search url host is host.
662 // NOTE: This is always non-NULL; we use a scoped_ptr<> to avoid circular
663 // header dependencies.
664 scoped_ptr
<SearchHostToURLsMap
> provider_map_
;
666 // Whether the keywords have been loaded.
669 // Set when the web data service fails to load properly. This prevents
670 // further communication with sync or writing to prefs, so we don't persist
671 // inconsistent state data anywhere.
674 // If non-zero, we're waiting on a load.
675 KeywordWebDataService::Handle load_handle_
;
677 // All visits that occurred before we finished loading. Once loaded
678 // UpdateKeywordSearchTermsForURL is invoked for each element of the vector.
679 std::vector
<URLVisitedDetails
> visits_to_add_
;
681 // Once loaded, the default search provider. This is a pointer to a
682 // TemplateURL owned by |template_urls_|.
683 TemplateURL
* default_search_provider_
;
685 // A temporary location for the DSE until Web Data has been loaded and it can
686 // be merged into |template_urls_|.
687 scoped_ptr
<TemplateURL
> initial_default_search_provider_
;
689 // Source of the default search provider.
690 DefaultSearchManager::Source default_search_provider_source_
;
692 // ID assigned to next TemplateURL added to this model. This is an ever
693 // increasing integer that is initialized from the database.
694 TemplateURLID next_id_
;
696 // Used to retrieve the current time, in base::Time units.
697 scoped_ptr
<base::Clock
> clock_
;
699 // Do we have an active association between the TemplateURLs and sync models?
700 // Set in MergeDataAndStartSyncing, reset in StopSyncing. While this is not
701 // set, we ignore any local search engine changes (when we start syncing we
702 // will look up the most recent values anyways).
703 bool models_associated_
;
705 // Whether we're currently processing changes from the syncer. While this is
706 // true, we ignore any local search engine changes, since we triggered them.
707 bool processing_syncer_changes_
;
709 // Sync's syncer::SyncChange handler. We push all our changes through this.
710 scoped_ptr
<syncer::SyncChangeProcessor
> sync_processor_
;
712 // Sync's error handler. We use it to create a sync error.
713 scoped_ptr
<syncer::SyncErrorFactory
> sync_error_factory_
;
715 // A set of sync GUIDs denoting TemplateURLs that have been removed from this
716 // model or the underlying KeywordWebDataService prior to
717 // MergeDataAndStartSyncing.
718 // This set is used to determine what entries from the server we want to
719 // ignore locally and return a delete command for.
720 std::set
<std::string
> pre_sync_deletes_
;
722 // This is used to log the origin of changes to the default search provider.
723 // We set this value to increasingly specific values when we know what is the
724 // cause/origin of a default search change.
725 DefaultSearchChangeOrigin dsp_change_origin_
;
727 // Stores a list of callbacks to be run after TemplateURLService has loaded.
728 base::CallbackList
<void(void)> on_loaded_callbacks_
;
730 // Helper class to manage the default search engine.
731 DefaultSearchManager default_search_manager_
;
733 scoped_ptr
<GoogleURLTracker::Subscription
> google_url_updated_subscription_
;
735 DISALLOW_COPY_AND_ASSIGN(TemplateURLService
);
738 #endif // COMPONENTS_SEARCH_ENGINES_TEMPLATE_URL_SERVICE_H_