- add sources.
[platform/framework/web/crosswalk.git] / src / components / autofill / core / browser / personal_data_manager.h
1 // Copyright 2013 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.
4
5 #ifndef COMPONENTS_AUTOFILL_CORE_BROWSER_PERSONAL_DATA_MANAGER_H_
6 #define COMPONENTS_AUTOFILL_CORE_BROWSER_PERSONAL_DATA_MANAGER_H_
7
8 #include <set>
9 #include <vector>
10
11 #include "base/basictypes.h"
12 #include "base/memory/scoped_ptr.h"
13 #include "base/memory/scoped_vector.h"
14 #include "base/observer_list.h"
15 #include "base/strings/string16.h"
16 #include "components/autofill/core/browser/autofill_profile.h"
17 #include "components/autofill/core/browser/credit_card.h"
18 #include "components/autofill/core/browser/field_types.h"
19 #include "components/autofill/core/browser/webdata/autofill_webdata_service_observer.h"
20 #include "components/webdata/common/web_data_service_consumer.h"
21
22 class PrefService;
23 class RemoveAutofillTester;
24
25 namespace content {
26 class BrowserContext;
27 }
28
29 namespace autofill {
30 class AutofillInteractiveTest;
31 class AutofillMetrics;
32 class AutofillTest;
33 class FormStructure;
34 class PersonalDataManagerObserver;
35 class PersonalDataManagerFactory;
36 }  // namespace autofill
37
38 namespace autofill_helper {
39 void SetProfiles(int, std::vector<autofill::AutofillProfile>*);
40 void SetCreditCards(int, std::vector<autofill::CreditCard>*);
41 }  // namespace autofill_helper
42
43 namespace autofill {
44
45 // Handles loading and saving Autofill profile information to the web database.
46 // This class also stores the profiles loaded from the database for use during
47 // Autofill.
48 class PersonalDataManager : public WebDataServiceConsumer,
49                             public AutofillWebDataServiceObserverOnUIThread {
50  public:
51   // A pair of GUID and variant index. Represents a single FormGroup and a
52   // specific data variant.
53   typedef std::pair<std::string, size_t> GUIDPair;
54
55   explicit PersonalDataManager(const std::string& app_locale);
56   virtual ~PersonalDataManager();
57
58   // Kicks off asynchronous loading of profiles and credit cards. |context| and
59   // |pref_service| must outlive this instance.
60   void Init(content::BrowserContext* context, PrefService* pref_service);
61
62   // WebDataServiceConsumer:
63   virtual void OnWebDataServiceRequestDone(
64       WebDataServiceBase::Handle h,
65       const WDTypedResult* result) OVERRIDE;
66
67   // AutofillWebDataServiceObserverOnUIThread:
68   virtual void AutofillMultipleChanged() OVERRIDE;
69
70   // Adds a listener to be notified of PersonalDataManager events.
71   virtual void AddObserver(PersonalDataManagerObserver* observer);
72
73   // Removes |observer| as an observer of this PersonalDataManager.
74   virtual void RemoveObserver(PersonalDataManagerObserver* observer);
75
76   // Scans the given |form| for importable Autofill data. If the form includes
77   // sufficient address data, it is immediately imported. If the form includes
78   // sufficient credit card data, it is stored into |credit_card|, so that we
79   // can prompt the user whether to save this data.
80   // Returns |true| if sufficient address or credit card data was found.
81   bool ImportFormData(const FormStructure& form,
82                       const CreditCard** credit_card);
83
84   // Saves |imported_profile| to the WebDB if it exists. Returns the guid of
85   // the new or updated profile, or the empty string if no profile was saved.
86   virtual std::string SaveImportedProfile(
87       const AutofillProfile& imported_profile);
88
89   // Saves a credit card value detected in |ImportedFormData|. Returns the guid
90   // of the new or updated card, or the empty string if no card was saved.
91   virtual std::string SaveImportedCreditCard(
92       const CreditCard& imported_credit_card);
93
94   // Adds |profile| to the web database.
95   void AddProfile(const AutofillProfile& profile);
96
97   // Updates |profile| which already exists in the web database.
98   void UpdateProfile(const AutofillProfile& profile);
99
100   // Removes the profile or credit card represented by |guid|.
101   virtual void RemoveByGUID(const std::string& guid);
102
103   // Returns the profile with the specified |guid|, or NULL if there is no
104   // profile with the specified |guid|. Both web and auxiliary profiles may
105   // be returned.
106   AutofillProfile* GetProfileByGUID(const std::string& guid);
107
108   // Adds |credit_card| to the web database.
109   void AddCreditCard(const CreditCard& credit_card);
110
111   // Updates |credit_card| which already exists in the web database.
112   void UpdateCreditCard(const CreditCard& credit_card);
113
114   // Returns the credit card with the specified |guid|, or NULL if there is
115   // no credit card with the specified |guid|.
116   CreditCard* GetCreditCardByGUID(const std::string& guid);
117
118   // Gets the field types availabe in the stored address and credit card data.
119   void GetNonEmptyTypes(ServerFieldTypeSet* non_empty_types);
120
121   // Returns true if the credit card information is stored with a password.
122   bool HasPassword();
123
124   // Returns whether the personal data has been loaded from the web database.
125   virtual bool IsDataLoaded() const;
126
127   // This PersonalDataManager owns these profiles and credit cards.  Their
128   // lifetime is until the web database is updated with new profile and credit
129   // card information, respectively.  |GetProfiles()| returns both web and
130   // auxiliary profiles.  |web_profiles()| returns only web profiles.
131   virtual const std::vector<AutofillProfile*>& GetProfiles() const;
132   virtual const std::vector<AutofillProfile*>& web_profiles() const;
133   virtual const std::vector<CreditCard*>& GetCreditCards() const;
134
135   // Loads profiles that can suggest data for |type|. |field_contents| is the
136   // part the user has already typed. |field_is_autofilled| is true if the field
137   // has already been autofilled. |other_field_types| represents the rest of
138   // form. Identifying info is loaded into the last four outparams.
139   void GetProfileSuggestions(
140       const AutofillType& type,
141       const base::string16& field_contents,
142       bool field_is_autofilled,
143       std::vector<ServerFieldType> other_field_types,
144       std::vector<base::string16>* values,
145       std::vector<base::string16>* labels,
146       std::vector<base::string16>* icons,
147       std::vector<GUIDPair>* guid_pairs);
148
149   // Gets credit cards that can suggest data for |type|. See
150   // GetProfileSuggestions for argument descriptions. The variant in each
151   // GUID pair should be ignored.
152   void GetCreditCardSuggestions(
153       const AutofillType& type,
154       const base::string16& field_contents,
155       std::vector<base::string16>* values,
156       std::vector<base::string16>* labels,
157       std::vector<base::string16>* icons,
158       std::vector<GUIDPair>* guid_pairs);
159
160   // Re-loads profiles and credit cards from the WebDatabase asynchronously.
161   // In the general case, this is a no-op and will re-create the same
162   // in-memory model as existed prior to the call.  If any change occurred to
163   // profiles in the WebDatabase directly, as is the case if the browser sync
164   // engine processed a change from the cloud, we will learn of these as a
165   // result of this call.
166   //
167   // Also see SetProfile for more details.
168   virtual void Refresh();
169
170   const std::string& app_locale() const { return app_locale_; }
171
172   // Checks suitability of |profile| for adding to the user's set of profiles.
173   static bool IsValidLearnableProfile(const AutofillProfile& profile,
174                                       const std::string& app_locale);
175
176   // Merges |new_profile| into one of the |existing_profiles| if possible;
177   // otherwise appends |new_profile| to the end of that list. Fills
178   // |merged_profiles| with the result. Returns the |guid| of the new or updated
179   // profile.
180   static std::string MergeProfile(
181       const AutofillProfile& new_profile,
182       const std::vector<AutofillProfile*>& existing_profiles,
183       const std::string& app_locale,
184       std::vector<AutofillProfile>* merged_profiles);
185
186   // Returns our best guess for the country a user is likely to use when
187   // inputting a new address. The value is calculated once and cached, so it
188   // will only update when Chrome is restarted.
189   const std::string& GetDefaultCountryCodeForNewAddress() const;
190
191  protected:
192   // Only PersonalDataManagerFactory and certain tests can create instances of
193   // PersonalDataManager.
194   FRIEND_TEST_ALL_PREFIXES(AutofillMetricsTest, FirstMiddleLast);
195   FRIEND_TEST_ALL_PREFIXES(AutofillMetricsTest, AutofillIsEnabledAtStartup);
196   FRIEND_TEST_ALL_PREFIXES(PersonalDataManagerTest,
197                            AggregateExistingAuxiliaryProfile);
198   friend class autofill::AutofillInteractiveTest;
199   friend class autofill::AutofillTest;
200   friend class autofill::PersonalDataManagerFactory;
201   friend class PersonalDataManagerTest;
202   friend class ProfileSyncServiceAutofillTest;
203   friend class ::RemoveAutofillTester;
204   friend class TestingAutomationProvider;
205   friend struct base::DefaultDeleter<PersonalDataManager>;
206   friend void autofill_helper::SetProfiles(
207       int, std::vector<autofill::AutofillProfile>*);
208   friend void autofill_helper::SetCreditCards(
209       int, std::vector<autofill::CreditCard>*);
210
211   // Sets |web_profiles_| to the contents of |profiles| and updates the web
212   // database by adding, updating and removing profiles.
213   // The relationship between this and Refresh is subtle.
214   // A call to |SetProfiles| could include out-of-date data that may conflict
215   // if we didn't refresh-to-latest before an Autofill window was opened for
216   // editing. |SetProfiles| is implemented to make a "best effort" to apply the
217   // changes, but in extremely rare edge cases it is possible not all of the
218   // updates in |profiles| make it to the DB.  This is why SetProfiles will
219   // invoke Refresh after finishing, to ensure we get into a
220   // consistent state.  See Refresh for details.
221   void SetProfiles(std::vector<AutofillProfile>* profiles);
222
223   // Sets |credit_cards_| to the contents of |credit_cards| and updates the web
224   // database by adding, updating and removing credit cards.
225   void SetCreditCards(std::vector<CreditCard>* credit_cards);
226
227   // Loads the saved profiles from the web database.
228   virtual void LoadProfiles();
229
230   // Loads the auxiliary profiles.  Currently Mac and Android only.
231   virtual void LoadAuxiliaryProfiles() const;
232
233   // Loads the saved credit cards from the web database.
234   virtual void LoadCreditCards();
235
236   // Receives the loaded profiles from the web data service and stores them in
237   // |credit_cards_|.
238   void ReceiveLoadedProfiles(WebDataServiceBase::Handle h,
239                              const WDTypedResult* result);
240
241   // Receives the loaded credit cards from the web data service and stores them
242   // in |credit_cards_|.
243   void ReceiveLoadedCreditCards(WebDataServiceBase::Handle h,
244                                 const WDTypedResult* result);
245
246   // Cancels a pending query to the web database.  |handle| is a pointer to the
247   // query handle.
248   void CancelPendingQuery(WebDataServiceBase::Handle* handle);
249
250   // The first time this is called, logs an UMA metrics for the number of
251   // profiles the user has. On subsequent calls, does nothing.
252   void LogProfileCount() const;
253
254   // Returns the value of the AutofillEnabled pref.
255   virtual bool IsAutofillEnabled() const;
256
257   // For tests.
258   const AutofillMetrics* metric_logger() const;
259   void set_metric_logger(const AutofillMetrics* metric_logger);
260   void set_browser_context(content::BrowserContext* context);
261   void set_pref_service(PrefService* pref_service);
262
263   // The browser context this PersonalDataManager is in.
264   content::BrowserContext* browser_context_;
265
266   // True if personal data has been loaded from the web database.
267   bool is_data_loaded_;
268
269   // The loaded web profiles.
270   ScopedVector<AutofillProfile> web_profiles_;
271
272   // Auxiliary profiles.
273   mutable ScopedVector<AutofillProfile> auxiliary_profiles_;
274
275   // Storage for combined web and auxiliary profiles.  Contents are weak
276   // references.  Lifetime managed by |web_profiles_| and |auxiliary_profiles_|.
277   mutable std::vector<AutofillProfile*> profiles_;
278
279   // The loaded credit cards.
280   ScopedVector<CreditCard> credit_cards_;
281
282   // When the manager makes a request from WebDataServiceBase, the database
283   // is queried on another thread, we record the query handle until we
284   // get called back.  We store handles for both profile and credit card queries
285   // so they can be loaded at the same time.
286   WebDataServiceBase::Handle pending_profiles_query_;
287   WebDataServiceBase::Handle pending_creditcards_query_;
288
289   // The observers.
290   ObserverList<PersonalDataManagerObserver> observers_;
291
292  private:
293   // Finds the country code that occurs most frequently among all profiles.
294   // Prefers verified profiles over unverified ones.
295   std::string MostCommonCountryCodeFromProfiles() const;
296
297   const std::string app_locale_;
298
299   // The default country code for new addresses.
300   mutable std::string default_country_code_;
301
302   // For logging UMA metrics. Overridden by metrics tests.
303   scoped_ptr<const AutofillMetrics> metric_logger_;
304
305   // The PrefService that this instance uses. Must outlive this instance.
306   PrefService* pref_service_;
307
308   // Whether we have already logged the number of profiles this session.
309   mutable bool has_logged_profile_count_;
310
311   DISALLOW_COPY_AND_ASSIGN(PersonalDataManager);
312 };
313
314 }  // namespace autofill
315
316 #endif  // COMPONENTS_AUTOFILL_CORE_BROWSER_PERSONAL_DATA_MANAGER_H_