[safe-browsing] Database full hash matches like prefix match.
[chromium-blink-merge.git] / chrome / browser / search_engines / template_url_service.h
blobf8896d52fa419fe78b3684f6f3a667af7039ea18
1 // Copyright (c) 2012 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 CHROME_BROWSER_SEARCH_ENGINES_TEMPLATE_URL_SERVICE_H_
6 #define CHROME_BROWSER_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 "chrome/browser/search_engines/default_search_manager.h"
20 #include "chrome/browser/search_engines/template_url_id.h"
21 #include "chrome/browser/webdata/web_data_service.h"
22 #include "components/keyed_service/core/keyed_service.h"
23 #include "content/public/browser/notification_observer.h"
24 #include "content/public/browser/notification_registrar.h"
25 #include "sync/api/sync_change.h"
26 #include "sync/api/syncable_service.h"
28 class GURL;
29 class PrefService;
30 class Profile;
31 class SearchHostToURLsMap;
32 class SearchTermsData;
33 class TemplateURL;
34 struct TemplateURLData;
35 class TemplateURLServiceObserver;
37 namespace syncer {
38 class SyncData;
39 class SyncErrorFactory;
42 namespace history {
43 struct URLVisitedDetails;
46 // TemplateURLService is the backend for keywords. It's used by
47 // KeywordAutocomplete.
49 // TemplateURLService stores a vector of TemplateURLs. The TemplateURLs are
50 // persisted to the database maintained by WebDataService. *ALL* mutations
51 // to the TemplateURLs must funnel through TemplateURLService. This allows
52 // TemplateURLService to notify listeners of changes as well as keep the
53 // database in sync.
55 // There is a TemplateURLService per Profile.
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 WebDataService, deletion is handled by WebDataService, otherwise
65 // TemplateURLService handles deletion.
67 class TemplateURLService : public WebDataServiceConsumer,
68 public KeyedService,
69 public content::NotificationObserver,
70 public syncer::SyncableService {
71 public:
72 typedef std::map<std::string, std::string> QueryTerms;
73 typedef std::vector<TemplateURL*> TemplateURLVector;
74 // Type for a static function pointer that acts as a time source.
75 typedef base::Time(TimeProvider)();
76 typedef std::map<std::string, syncer::SyncData> SyncDataMap;
77 typedef base::CallbackList<void(void)>::Subscription Subscription;
79 // Struct used for initializing the data store with fake data.
80 // Each initializer is mapped to a TemplateURL.
81 struct Initializer {
82 const char* const keyword;
83 const char* const url;
84 const char* const content;
87 // Struct describes a search engine added by an extension.
88 struct ExtensionKeyword {
89 ExtensionKeyword(const std::string& id,
90 const std::string& name,
91 const std::string& keyword);
92 ~ExtensionKeyword();
94 std::string extension_id;
95 std::string extension_name;
96 std::string extension_keyword;
99 explicit TemplateURLService(Profile* profile);
100 // The following is for testing.
101 TemplateURLService(const Initializer* initializers, const int count);
102 virtual ~TemplateURLService();
104 // Generates a suitable keyword for the specified url, which must be valid.
105 // This is guaranteed not to return an empty string, since TemplateURLs should
106 // never have an empty keyword.
107 static base::string16 GenerateKeyword(const GURL& url);
109 // Removes any unnecessary characters from a user input keyword.
110 // This removes the leading scheme, "www." and any trailing slash.
111 static base::string16 CleanUserInputKeyword(const base::string16& keyword);
113 // Returns the search url for t_url. Returns an empty GURL if t_url has no
114 // url().
115 // NOTE: |t_url| is non-const in this version because of the need to access
116 // t_url->profile().
117 static GURL GenerateSearchURL(TemplateURL* t_url);
119 // Just like GenerateSearchURL except that it takes SearchTermsData to supply
120 // the data for some search terms, e.g. so this can be used on threads other
121 // than the UI thread. See the various TemplateURLRef::XXXUsingTermsData()
122 // functions.
123 static GURL GenerateSearchURLUsingTermsData(
124 const TemplateURL* t_url,
125 const SearchTermsData& search_terms_data);
127 // Returns true if there is no TemplateURL that conflicts with the
128 // keyword/url pair, or there is one but it can be replaced. If there is an
129 // existing keyword that can be replaced and template_url_to_replace is
130 // non-NULL, template_url_to_replace is set to the keyword to replace.
132 // url gives the url of the search query. The url is used to avoid generating
133 // a TemplateURL for an existing TemplateURL that shares the same host.
134 bool CanReplaceKeyword(const base::string16& keyword,
135 const GURL& url,
136 TemplateURL** template_url_to_replace);
138 // Returns (in |matches|) all TemplateURLs whose keywords begin with |prefix|,
139 // sorted shortest keyword-first. If |support_replacement_only| is true, only
140 // TemplateURLs that support replacement are returned.
141 void FindMatchingKeywords(const base::string16& prefix,
142 bool support_replacement_only,
143 TemplateURLVector* matches) const;
145 // Looks up |keyword| and returns the element it maps to. Returns NULL if
146 // the keyword was not found.
147 // The caller should not try to delete the returned pointer; the data store
148 // retains ownership of it.
149 TemplateURL* GetTemplateURLForKeyword(const base::string16& keyword);
151 // Returns that TemplateURL with the specified GUID, or NULL if not found.
152 // The caller should not try to delete the returned pointer; the data store
153 // retains ownership of it.
154 TemplateURL* GetTemplateURLForGUID(const std::string& sync_guid);
156 // Returns the first TemplateURL found with a URL using the specified |host|,
157 // or NULL if there are no such TemplateURLs
158 TemplateURL* GetTemplateURLForHost(const std::string& host);
160 // Takes ownership of |template_url| and adds it to this model. For obvious
161 // reasons, it is illegal to Add() the same |template_url| pointer twice.
162 void Add(TemplateURL* template_url);
164 // Like Add(), but overwrites the |template_url|'s values with the provided
165 // ones.
166 void AddAndSetProfile(TemplateURL* template_url, Profile* profile);
167 void AddWithOverrides(TemplateURL* template_url,
168 const base::string16& short_name,
169 const base::string16& keyword,
170 const std::string& url);
172 // Add the search engine of type NORMAL_CONTROLLED_BY_EXTENSION.
173 void AddExtensionControlledTURL(TemplateURL* template_url,
174 scoped_ptr<AssociatedExtensionInfo> info);
176 // Removes the keyword from the model. This deletes the supplied TemplateURL.
177 // This fails if the supplied template_url is the default search provider.
178 void Remove(TemplateURL* template_url);
180 // Removes any TemplateURL of type NORMAL_CONTROLLED_BY_EXTENSION associated
181 // with |extension_id|. Unlike with Remove(), this can be called when the
182 // TemplateURL in question is the current default search provider.
183 void RemoveExtensionControlledTURL(const std::string& extension_id);
185 // Removes all auto-generated keywords that were created on or after the
186 // date passed in.
187 void RemoveAutoGeneratedSince(base::Time created_after);
189 // Removes all auto-generated keywords that were created in the specified
190 // range.
191 void RemoveAutoGeneratedBetween(base::Time created_after,
192 base::Time created_before);
194 // Removes all auto-generated keywords that were created in the specified
195 // range for a specified |origin|. If |origin| is empty, deletes all
196 // auto-generated keywords in the range.
197 void RemoveAutoGeneratedForOriginBetween(const GURL& origin,
198 base::Time created_after,
199 base::Time created_before);
201 // Adds a TemplateURL for an extension with an omnibox keyword.
202 // Only 1 keyword is allowed for a given extension. If a keyword
203 // already exists for this extension, does nothing.
204 void RegisterOmniboxKeyword(const std::string& extension_id,
205 const std::string& extension_name,
206 const std::string& keyword);
208 // Removes the TemplateURL containing the keyword for the extension with the
209 // given ID, if any.
210 void UnregisterOmniboxKeyword(const std::string& extension_id);
212 // Returns the set of URLs describing the keywords. The elements are owned
213 // by TemplateURLService and should not be deleted.
214 TemplateURLVector GetTemplateURLs();
216 // Increment the usage count of a keyword.
217 // Called when a URL is loaded that was generated from a keyword.
218 void IncrementUsageCount(TemplateURL* url);
220 // Resets the title, keyword and search url of the specified TemplateURL.
221 // The TemplateURL is marked as not replaceable.
222 void ResetTemplateURL(TemplateURL* url,
223 const base::string16& title,
224 const base::string16& keyword,
225 const std::string& search_url);
227 // Return true if the given |url| can be made the default. This returns false
228 // regardless of |url| if the default search provider is managed by policy or
229 // controlled by an extension.
230 bool CanMakeDefault(const TemplateURL* url);
232 // Set the default search provider. |url| may be null.
233 // This will assert if the default search is managed; the UI should not be
234 // invoking this method in that situation.
235 void SetUserSelectedDefaultSearchProvider(TemplateURL* url);
237 // Returns the default search provider. If the TemplateURLService hasn't been
238 // loaded, the default search provider is pulled from preferences.
240 // NOTE: At least in unittest mode, this may return NULL.
241 TemplateURL* GetDefaultSearchProvider();
243 // Returns true if the |url| is a search results page from the default search
244 // provider.
245 bool IsSearchResultsPageFromDefaultSearchProvider(const GURL& url);
247 // Returns true if the default search is managed through group policy.
248 bool is_default_search_managed() const { return is_default_search_managed_; }
250 // Returns true if the default search provider is controlled by an extension.
251 bool IsExtensionControlledDefaultSearch();
253 // Returns the default search specified in the prepopulated data, if it
254 // exists. If not, returns first URL in |template_urls_|, or NULL if that's
255 // empty. The returned object is owned by TemplateURLService and can be
256 // destroyed at any time so should be used right after the call.
257 TemplateURL* FindNewDefaultSearchProvider();
259 // Performs the same actions that happen when the prepopulate data version is
260 // revved: all existing prepopulated entries are checked against the current
261 // prepopulate data, any now-extraneous safe_for_autoreplace() entries are
262 // removed, any existing engines are reset to the provided data (except for
263 // user-edited names or keywords), and any new prepopulated anegines are
264 // added.
266 // After this, the default search engine is reset to the default entry in the
267 // prepopulate data.
268 void RepairPrepopulatedSearchEngines();
270 // Observers used to listen for changes to the model.
271 // TemplateURLService does NOT delete the observers when deleted.
272 void AddObserver(TemplateURLServiceObserver* observer);
273 void RemoveObserver(TemplateURLServiceObserver* observer);
275 // Loads the keywords. This has no effect if the keywords have already been
276 // loaded.
277 // Observers are notified when loading completes via the method
278 // OnTemplateURLServiceChanged.
279 void Load();
281 // Registers a callback to be called when the service has loaded.
283 // If the service has already loaded, this function does nothing.
284 scoped_ptr<Subscription> RegisterOnLoadedCallback(
285 const base::Closure& callback);
287 #if defined(UNIT_TEST)
288 void set_loaded(bool value) { loaded_ = value; }
289 #endif
291 // Whether or not the keywords have been loaded.
292 bool loaded() { return loaded_; }
294 // Notification that the keywords have been loaded.
295 // This is invoked from WebDataService, and should not be directly
296 // invoked.
297 virtual void OnWebDataServiceRequestDone(
298 WebDataService::Handle h,
299 const WDTypedResult* result) OVERRIDE;
301 // Returns the locale-direction-adjusted short name for the given keyword.
302 // Also sets the out param to indicate whether the keyword belongs to an
303 // Omnibox extension.
304 base::string16 GetKeywordShortName(const base::string16& keyword,
305 bool* is_omnibox_api_extension_keyword);
307 // content::NotificationObserver implementation.
308 virtual void Observe(int type,
309 const content::NotificationSource& source,
310 const content::NotificationDetails& details) OVERRIDE;
312 // KeyedService implementation.
313 virtual void Shutdown() OVERRIDE;
315 // syncer::SyncableService implementation.
317 // Returns all syncable TemplateURLs from this model as SyncData. This should
318 // include every search engine and no Extension keywords.
319 virtual syncer::SyncDataList GetAllSyncData(
320 syncer::ModelType type) const OVERRIDE;
321 // Process new search engine changes from Sync, merging them into our local
322 // data. This may send notifications if local search engines are added,
323 // updated or removed.
324 virtual syncer::SyncError ProcessSyncChanges(
325 const tracked_objects::Location& from_here,
326 const syncer::SyncChangeList& change_list) OVERRIDE;
327 // Merge initial search engine data from Sync and push any local changes up
328 // to Sync. This may send notifications if local search engines are added,
329 // updated or removed.
330 virtual syncer::SyncMergeResult MergeDataAndStartSyncing(
331 syncer::ModelType type,
332 const syncer::SyncDataList& initial_sync_data,
333 scoped_ptr<syncer::SyncChangeProcessor> sync_processor,
334 scoped_ptr<syncer::SyncErrorFactory> sync_error_factory) OVERRIDE;
335 virtual void StopSyncing(syncer::ModelType type) OVERRIDE;
337 // Processes a local TemplateURL change for Sync. |turl| is the TemplateURL
338 // that has been modified, and |type| is the Sync ChangeType that took place.
339 // This may send a new SyncChange to the cloud. If our model has not yet been
340 // associated with Sync, or if this is triggered by a Sync change, then this
341 // does nothing.
342 void ProcessTemplateURLChange(const tracked_objects::Location& from_here,
343 const TemplateURL* turl,
344 syncer::SyncChange::SyncChangeType type);
346 Profile* profile() const { return profile_; }
348 // Returns a SyncData with a sync representation of the search engine data
349 // from |turl|.
350 static syncer::SyncData CreateSyncDataFromTemplateURL(
351 const TemplateURL& turl);
353 // Creates a new heap-allocated TemplateURL* which is populated by overlaying
354 // |sync_data| atop |existing_turl|. |existing_turl| may be NULL; if not it
355 // remains unmodified. The caller owns the returned TemplateURL*.
357 // If the created TemplateURL is migrated in some way from out-of-date sync
358 // data, an appropriate SyncChange is added to |change_list|. If the sync
359 // data is bad for some reason, an ACTION_DELETE change is added and the
360 // function returns NULL.
361 static TemplateURL* CreateTemplateURLFromTemplateURLAndSyncData(
362 Profile* profile,
363 TemplateURL* existing_turl,
364 const syncer::SyncData& sync_data,
365 syncer::SyncChangeList* change_list);
367 // Returns a map mapping Sync GUIDs to pointers to syncer::SyncData.
368 static SyncDataMap CreateGUIDToSyncDataMap(
369 const syncer::SyncDataList& sync_data);
371 #if defined(UNIT_TEST)
372 // Set a different time provider function, such as
373 // base::MockTimeProvider::StaticNow, when testing calls to base::Time::Now.
374 void set_time_provider(TimeProvider* time_provider) {
375 time_provider_ = time_provider;
377 #endif
379 protected:
380 // Cover method for the method of the same name on the HistoryService.
381 // url is the one that was visited with the given search terms.
383 // This exists and is virtual for testing.
384 virtual void SetKeywordSearchTermsForURL(const TemplateURL* t_url,
385 const GURL& url,
386 const base::string16& term);
388 private:
389 FRIEND_TEST_ALL_PREFIXES(TemplateURLServiceTest, TestManagedDefaultSearch);
390 FRIEND_TEST_ALL_PREFIXES(TemplateURLServiceTest,
391 UpdateKeywordSearchTermsForURL);
392 FRIEND_TEST_ALL_PREFIXES(TemplateURLServiceTest,
393 DontUpdateKeywordSearchForNonReplaceable);
394 FRIEND_TEST_ALL_PREFIXES(TemplateURLServiceTest, ChangeGoogleBaseValue);
395 FRIEND_TEST_ALL_PREFIXES(TemplateURLServiceTest, MergeDeletesUnusedProviders);
396 FRIEND_TEST_ALL_PREFIXES(TemplateURLServiceSyncTest,
397 CreateSyncDataFromTemplateURL);
398 FRIEND_TEST_ALL_PREFIXES(TemplateURLServiceSyncTest,
399 CreateTemplateURLFromSyncData);
400 FRIEND_TEST_ALL_PREFIXES(TemplateURLServiceSyncTest, UniquifyKeyword);
401 FRIEND_TEST_ALL_PREFIXES(TemplateURLServiceSyncTest,
402 ResolveSyncKeywordConflict);
403 FRIEND_TEST_ALL_PREFIXES(TemplateURLServiceSyncTest, PreSyncDeletes);
404 FRIEND_TEST_ALL_PREFIXES(TemplateURLServiceSyncTest,
405 IsLocalTemplateURLBetter);
406 FRIEND_TEST_ALL_PREFIXES(TemplateURLServiceSyncTest, MergeInSyncTemplateURL);
408 friend class TemplateURLServiceTestUtilBase;
410 typedef std::map<base::string16, TemplateURL*> KeywordToTemplateMap;
411 typedef std::map<std::string, TemplateURL*> GUIDToTemplateMap;
413 // Declaration of values to be used in an enumerated histogram to tally
414 // changes to the default search provider from various entry points. In
415 // particular, we use this to see what proportion of changes are from Sync
416 // entry points, to help spot erroneous Sync activity.
417 enum DefaultSearchChangeOrigin {
418 // Various known Sync entry points.
419 DSP_CHANGE_SYNC_PREF,
420 DSP_CHANGE_SYNC_ADD,
421 DSP_CHANGE_SYNC_DELETE,
422 DSP_CHANGE_SYNC_NOT_MANAGED,
423 // "Other" origins. We differentiate between Sync and not Sync so we know if
424 // certain changes were intentionally from the system, or possibly some
425 // unintentional change from when we were Syncing.
426 DSP_CHANGE_SYNC_UNINTENTIONAL,
427 // All changes that don't fall into another category; we can't reorder the
428 // list for clarity as this would screw up stat collection.
429 DSP_CHANGE_OTHER,
430 // Changed through "Profile Reset" feature.
431 DSP_CHANGE_PROFILE_RESET,
432 // Changed by an extension through the Override Settings API.
433 DSP_CHANGE_OVERRIDE_SETTINGS_EXTENSION,
434 // New DSP during database/prepopulate data load, which was not previously
435 // in the known engine set, and with no previous value in prefs. The
436 // typical time to see this is during first run.
437 DSP_CHANGE_NEW_ENGINE_NO_PREFS,
438 // Boundary value.
439 DSP_CHANGE_MAX,
442 // Helper functor for FindMatchingKeywords(), for finding the range of
443 // keywords which begin with a prefix.
444 class LessWithPrefix;
446 void Init(const Initializer* initializers, int num_initializers);
448 void RemoveFromMaps(TemplateURL* template_url);
450 void AddToMaps(TemplateURL* template_url);
452 // Sets the keywords. This is used once the keywords have been loaded.
453 // This does NOT notify the delegate or the database.
455 // This transfers ownership of the elements in |urls| to |this|, and may
456 // delete some elements, so it's not safe for callers to access any elements
457 // after calling; to reinforce this, this function clears |urls| on exit.
458 void SetTemplateURLs(TemplateURLVector* urls);
460 // Transitions to the loaded state.
461 void ChangeToLoadedState();
463 // Saves enough of url to preferences so that it can be loaded from
464 // preferences on start up.
465 void SaveDefaultSearchProviderToPrefs(const TemplateURL* url);
467 // Creates a TemplateURLData that was previously saved to prefs via
468 // SaveDefaultSearchProviderToPrefs or set via policy.
469 // Returns true if successful, false otherwise.
470 // If the user or the policy has opted for no default search, this
471 // returns true but default_provider is set to NULL.
472 // |*is_managed| specifies whether the default is managed via policy.
473 bool LoadDefaultSearchProviderFromPrefs(
474 scoped_ptr<TemplateURLData>* default_provider,
475 bool* is_managed);
477 // Clears user preferences describing the default search engine.
478 void ClearDefaultProviderFromPrefs();
480 // Returns true if there is no TemplateURL that has a search url with the
481 // specified host, or the only TemplateURLs matching the specified host can
482 // be replaced.
483 bool CanReplaceKeywordForHost(const std::string& host,
484 TemplateURL** to_replace);
486 // Returns true if the TemplateURL is replaceable. This doesn't look at the
487 // uniqueness of the keyword or host and is intended to be called after those
488 // checks have been done. This returns true if the TemplateURL doesn't appear
489 // in the default list and is marked as safe_for_autoreplace.
490 bool CanReplace(const TemplateURL* t_url);
492 // Like GetTemplateURLForKeyword(), but ignores extension-provided keywords.
493 TemplateURL* FindNonExtensionTemplateURLForKeyword(
494 const base::string16& keyword);
496 // Updates the information in |existing_turl| using the information from
497 // |new_values|, but the ID for |existing_turl| is retained. Notifying
498 // observers is the responsibility of the caller. Returns whether
499 // |existing_turl| was found in |template_urls_| and thus could be updated.
500 // |old_search_terms_data| is passed to SearchHostToURLsMap::Remove().
502 // NOTE: This should not be called with an extension keyword as there are no
503 // updates needed in that case.
504 bool UpdateNoNotify(TemplateURL* existing_turl,
505 const TemplateURL& new_values,
506 const SearchTermsData& old_search_terms_data);
508 // If the TemplateURL comes from a prepopulated URL available in the current
509 // country, update all its fields save for the keyword, short name and id so
510 // that they match the internal prepopulated URL. TemplateURLs not coming from
511 // a prepopulated URL are not modified.
512 static void UpdateTemplateURLIfPrepopulated(TemplateURL* existing_turl,
513 Profile* profile);
515 // Returns the preferences we use.
516 PrefService* GetPrefs();
518 // Iterates through the TemplateURLs to see if one matches the visited url.
519 // For each TemplateURL whose url matches the visited url
520 // SetKeywordSearchTermsForURL is invoked.
521 void UpdateKeywordSearchTermsForURL(
522 const history::URLVisitedDetails& details);
524 // If necessary, generates a visit for the site http:// + t_url.keyword().
525 void AddTabToSearchVisit(const TemplateURL& t_url);
527 // Invoked when the Google base URL has changed. Updates the mapping for all
528 // TemplateURLs that have a replacement term of {google:baseURL} or
529 // {google:baseSuggestURL}.
530 void GoogleBaseURLChanged(const GURL& old_base_url);
532 // Update the default search. Called at initialization or when a managed
533 // preference has changed.
534 void UpdateDefaultSearch();
536 // Set the default search provider. |url| may be user-selected or
537 // automatically selected and may be null.
538 // This will assert if the default search is managed.
539 void SetDefaultSearchProvider(TemplateURL* url);
541 // Set the default search provider even if it is managed. |url| may be null.
542 // Caller is responsible for notifying observers. Returns whether |url| was
543 // found in |template_urls_|.
544 // If |url| is an extension-controlled search engine then preferences and the
545 // database are left untouched.
546 // If |url| is a normal search engine and the existing default search engine
547 // is controlled by an extension then |url| is propagated to the database and
548 // prefs but the extension-controlled default engine will continue to hide
549 // this value until the extension is uninstalled.
550 bool SetDefaultSearchProviderNoNotify(TemplateURL* url);
552 // Adds a new TemplateURL to this model. TemplateURLService will own the
553 // reference, and delete it when the TemplateURL is removed.
554 // If |newly_adding| is false, we assume that this TemplateURL was already
555 // part of the model in the past, and therefore we don't need to do things
556 // like assign it an ID or notify sync.
557 // This function guarantees that on return the model will not have two
558 // non-extension TemplateURLs with the same keyword. If that means that it
559 // cannot add the provided argument, it will delete it and return false.
560 // Caller is responsible for notifying observers if this function returns
561 // true.
562 bool AddNoNotify(TemplateURL* template_url, bool newly_adding);
564 // Removes the keyword from the model. This deletes the supplied TemplateURL.
565 // This fails if the supplied template_url is the default search provider.
566 // Caller is responsible for notifying observers.
567 void RemoveNoNotify(TemplateURL* template_url);
569 // Notify the observers that the model has changed. This is done only if the
570 // model is loaded.
571 void NotifyObservers();
573 // Removes from the vector any template URL that was created because of
574 // policy. These TemplateURLs are freed and removed from the database.
575 // Sets default_search_provider to NULL if it was one of them, unless it is
576 // the same as the current default from preferences and it is managed.
577 void RemoveProvidersCreatedByPolicy(
578 TemplateURLVector* template_urls,
579 TemplateURL** default_search_provider,
580 TemplateURLData* default_from_prefs);
582 // Resets the sync GUID of the specified TemplateURL and persists the change
583 // to the database. This does not notify observers.
584 void ResetTemplateURLGUID(TemplateURL* url, const std::string& guid);
586 // Attempts to generate a unique keyword for |turl| based on its original
587 // keyword. If its keyword is already unique, that is returned. Otherwise, it
588 // tries to return the autogenerated keyword if that is unique to the Service,
589 // and finally it repeatedly appends special characters to the keyword until
590 // it is unique to the Service. If |force| is true, then this will only
591 // execute the special character appending functionality.
592 base::string16 UniquifyKeyword(const TemplateURL& turl, bool force);
594 // Returns true iff |local_turl| is considered "better" than |sync_turl| for
595 // the purposes of resolving conflicts. |local_turl| must be a TemplateURL
596 // known to the local model (though it may already be synced), and |sync_turl|
597 // is a new TemplateURL known to Sync but not yet known to the local model.
598 // The criteria for if |local_turl| is better than |sync_turl| is whether any
599 // of the following are true:
600 // * |local_turl|'s last_modified timestamp is newer than sync_turl.
601 // * |local_turl| is created by policy.
602 // * |local_turl| is the local default search provider.
603 bool IsLocalTemplateURLBetter(const TemplateURL* local_turl,
604 const TemplateURL* sync_turl);
606 // Given two synced TemplateURLs with a conflicting keyword, one of which
607 // needs to be added to or updated in the local model (|unapplied_sync_turl|)
608 // and one which is already known to the local model (|applied_sync_turl|),
609 // prepares the local model so that |unapplied_sync_turl| can be added to it,
610 // or applied as an update to an existing TemplateURL.
611 // Since both entries are known to Sync and one of their keywords will change,
612 // an ACTION_UPDATE will be appended to |change_list| to reflect this change.
613 // Note that |applied_sync_turl| must not be an extension keyword.
614 void ResolveSyncKeywordConflict(TemplateURL* unapplied_sync_turl,
615 TemplateURL* applied_sync_turl,
616 syncer::SyncChangeList* change_list);
618 // Adds |sync_turl| into the local model, possibly removing or updating a
619 // local TemplateURL to make room for it. This expects |sync_turl| to be a new
620 // entry from Sync, not currently known to the local model. |sync_data| should
621 // be a SyncDataMap where the contents are entries initially known to Sync
622 // during MergeDataAndStartSyncing.
623 // Any necessary updates to Sync will be appended to |change_list|. This can
624 // include updates on local TemplateURLs, if they are found in |sync_data|.
625 // |initial_data| should be a SyncDataMap of the entries known to the local
626 // model during MergeDataAndStartSyncing. If |sync_turl| replaces a local
627 // entry, that entry is removed from |initial_data| to prevent it from being
628 // sent up to Sync.
629 // |merge_result| tracks the changes made to the local model. Added/modified/
630 // deleted are updated depending on how the |sync_turl| is merged in.
631 // This should only be called from MergeDataAndStartSyncing.
632 void MergeInSyncTemplateURL(TemplateURL* sync_turl,
633 const SyncDataMap& sync_data,
634 syncer::SyncChangeList* change_list,
635 SyncDataMap* local_data,
636 syncer::SyncMergeResult* merge_result);
638 // Checks a newly added TemplateURL from Sync by its sync_guid and sets it as
639 // the default search provider if we were waiting for it.
640 void SetDefaultSearchProviderIfNewlySynced(const std::string& guid);
642 // Retrieve the pending default search provider according to Sync. Returns
643 // NULL if there was no pending search provider from Sync.
644 TemplateURL* GetPendingSyncedDefaultSearchProvider();
646 // Goes through a vector of TemplateURLs and ensure that both the in-memory
647 // and database copies have valid sync_guids. This is to fix crbug.com/102038,
648 // where old entries were being pushed to Sync without a sync_guid.
649 void PatchMissingSyncGUIDs(TemplateURLVector* template_urls);
651 void OnSyncedDefaultSearchProviderGUIDChanged();
653 // Adds |template_urls| to |template_urls_| and sets up the default search
654 // provider. If |default_search_provider| is non-NULL, it must refer to one
655 // of the |template_urls|, and will be used as the new default.
657 // This transfers ownership of the elements in |template_urls| to |this|, and
658 // may delete some elements, so it's not safe for callers to access any
659 // elements after calling; to reinforce this, this function clears
660 // |template_urls| on exit.
661 void AddTemplateURLsAndSetupDefaultEngine(
662 TemplateURLVector* template_urls,
663 TemplateURL* default_search_provider);
665 // If there is no current default search provider, sets the default to the
666 // result of calling FindNewDefaultSearchProvider().
667 void EnsureDefaultSearchProviderExists();
669 // Returns a new TemplateURL for the given extension.
670 TemplateURL* CreateTemplateURLForExtension(
671 const ExtensionKeyword& extension_keyword) const;
673 // Returns the TemplateURL associated with |extension_id|, if any.
674 TemplateURL* FindTemplateURLForExtension(const std::string& extension_id,
675 TemplateURL::Type type) const;
677 // Finds the most recently-installed NORMAL_CONTROLLED_BY_EXTENSION engine
678 // that supports replacement and wants to be default, if any.
679 TemplateURL* FindExtensionDefaultSearchEngine() const;
681 // Sets the default search provider to:
682 // (1) BestDefaultExtensionControlledTURL(), if any; or,
683 // (2) LoadDefaultSearchProviderFromPrefs(), if we have a TURL with that ID;
684 // or,
685 // (3) FindNewDefaultSearchProvider().
686 void SetDefaultSearchProviderAfterRemovingDefaultExtension();
688 content::NotificationRegistrar notification_registrar_;
689 PrefChangeRegistrar pref_change_registrar_;
691 // Mapping from keyword to the TemplateURL.
692 KeywordToTemplateMap keyword_to_template_map_;
694 // Mapping from Sync GUIDs to the TemplateURL.
695 GUIDToTemplateMap guid_to_template_map_;
697 TemplateURLVector template_urls_;
699 ObserverList<TemplateURLServiceObserver> model_observers_;
701 // Maps from host to set of TemplateURLs whose search url host is host.
702 // NOTE: This is always non-NULL; we use a scoped_ptr<> to avoid circular
703 // header dependencies.
704 scoped_ptr<SearchHostToURLsMap> provider_map_;
706 // Used to obtain the WebDataService.
707 // When Load is invoked, if we haven't yet loaded, the WebDataService is
708 // obtained from the Profile. This allows us to lazily access the database.
709 Profile* profile_;
711 // Whether the keywords have been loaded.
712 bool loaded_;
714 // Did loading fail? This is only valid if loaded_ is true.
715 bool load_failed_;
717 // If non-zero, we're waiting on a load.
718 WebDataService::Handle load_handle_;
720 // Service used to store entries.
721 scoped_refptr<WebDataService> service_;
723 // All visits that occurred before we finished loading. Once loaded
724 // UpdateKeywordSearchTermsForURL is invoked for each element of the vector.
725 std::vector<history::URLVisitedDetails> visits_to_add_;
727 // Once loaded, the default search provider. This is a pointer to a
728 // TemplateURL owned by template_urls_.
729 TemplateURL* default_search_provider_;
731 // The initial search provider extracted from preferences. This is only valid
732 // if we haven't been loaded or loading failed.
733 scoped_ptr<TemplateURL> initial_default_search_provider_;
735 // Whether the default search is managed via policy.
736 bool is_default_search_managed_;
738 // ID assigned to next TemplateURL added to this model. This is an ever
739 // increasing integer that is initialized from the database.
740 TemplateURLID next_id_;
742 // Function returning current time in base::Time units.
743 TimeProvider* time_provider_;
745 // Do we have an active association between the TemplateURLs and sync models?
746 // Set in MergeDataAndStartSyncing, reset in StopSyncing. While this is not
747 // set, we ignore any local search engine changes (when we start syncing we
748 // will look up the most recent values anyways).
749 bool models_associated_;
751 // Whether we're currently processing changes from the syncer. While this is
752 // true, we ignore any local search engine changes, since we triggered them.
753 bool processing_syncer_changes_;
755 // Sync's syncer::SyncChange handler. We push all our changes through this.
756 scoped_ptr<syncer::SyncChangeProcessor> sync_processor_;
758 // Sync's error handler. We use it to create a sync error.
759 scoped_ptr<syncer::SyncErrorFactory> sync_error_factory_;
761 // Whether or not we are waiting on the default search provider to come in
762 // from Sync. This is to facilitate the fact that changes to the value of
763 // prefs::kSyncedDefaultSearchProviderGUID do not always come before the
764 // TemplateURL entry it refers to, and to handle the case when we want to use
765 // the Synced default when the default search provider becomes unmanaged.
766 bool pending_synced_default_search_;
768 // A set of sync GUIDs denoting TemplateURLs that have been removed from this
769 // model or the underlying WebDataService prior to MergeDataAndStartSyncing.
770 // This set is used to determine what entries from the server we want to
771 // ignore locally and return a delete command for.
772 std::set<std::string> pre_sync_deletes_;
774 // This is used to log the origin of changes to the default search provider.
775 // We set this value to increasingly specific values when we know what is the
776 // cause/origin of a default search change.
777 DefaultSearchChangeOrigin dsp_change_origin_;
779 // Stores a list of callbacks to be run after TemplateURLService has loaded.
780 base::CallbackList<void(void)> on_loaded_callbacks_;
782 // Helper class to manage the default search engine. This will be NULL when
783 // using the testing-specific constructor.
784 scoped_ptr<DefaultSearchManager> default_search_manager_;
786 DISALLOW_COPY_AND_ASSIGN(TemplateURLService);
789 #endif // CHROME_BROWSER_SEARCH_ENGINES_TEMPLATE_URL_SERVICE_H_