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