[android] Scan new credit card from autofill popup.
[chromium-blink-merge.git] / components / autofill / core / browser / autofill_manager.h
blob326dd8b2cfe120cbfdb66c96ca5839dd26baa665
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.
5 #ifndef COMPONENTS_AUTOFILL_CORE_BROWSER_AUTOFILL_MANAGER_H_
6 #define COMPONENTS_AUTOFILL_CORE_BROWSER_AUTOFILL_MANAGER_H_
8 #include <list>
9 #include <map>
10 #include <string>
11 #include <vector>
13 #include "base/basictypes.h"
14 #include "base/callback_forward.h"
15 #include "base/compiler_specific.h"
16 #include "base/gtest_prod_util.h"
17 #include "base/memory/scoped_ptr.h"
18 #include "base/memory/scoped_vector.h"
19 #include "base/memory/weak_ptr.h"
20 #include "base/strings/string16.h"
21 #include "base/time/time.h"
22 #include "components/autofill/core/browser/autocomplete_history_manager.h"
23 #include "components/autofill/core/browser/autofill_client.h"
24 #include "components/autofill/core/browser/autofill_download_manager.h"
25 #include "components/autofill/core/browser/autofill_driver.h"
26 #include "components/autofill/core/browser/form_structure.h"
27 #include "components/autofill/core/browser/personal_data_manager.h"
28 #include "components/autofill/core/common/form_data.h"
30 namespace gfx {
31 class Rect;
32 class RectF;
35 namespace user_prefs {
36 class PrefRegistrySyncable;
39 namespace autofill {
41 class AutofillDataModel;
42 class AutofillDownloadManager;
43 class AutofillExternalDelegate;
44 class AutofillField;
45 class AutofillClient;
46 class AutofillManagerTestDelegate;
47 class AutofillMetrics;
48 class AutofillProfile;
49 class AutofillType;
50 class CreditCard;
51 class FormStructureBrowserTest;
53 struct FormData;
54 struct FormFieldData;
56 // Manages saving and restoring the user's personal information entered into web
57 // forms.
58 class AutofillManager : public AutofillDownloadManager::Observer {
59 public:
60 enum AutofillDownloadManagerState {
61 ENABLE_AUTOFILL_DOWNLOAD_MANAGER,
62 DISABLE_AUTOFILL_DOWNLOAD_MANAGER,
65 // Registers our Enable/Disable Autofill pref.
66 static void RegisterProfilePrefs(user_prefs::PrefRegistrySyncable* registry);
68 #if defined(OS_MACOSX) && !defined(OS_IOS)
69 static void MigrateUserPrefs(PrefService* prefs);
70 #endif // defined(OS_MACOSX) && !defined(OS_IOS)
72 AutofillManager(AutofillDriver* driver,
73 AutofillClient* client,
74 const std::string& app_locale,
75 AutofillDownloadManagerState enable_download_manager);
76 ~AutofillManager() override;
78 // Sets an external delegate.
79 void SetExternalDelegate(AutofillExternalDelegate* delegate);
81 void ShowAutofillSettings();
83 #if defined(OS_MACOSX) && !defined(OS_IOS)
84 // Whether the |field| should show an entry to prompt the user to give Chrome
85 // access to the user's address book.
86 bool ShouldShowAccessAddressBookSuggestion(const FormData& form,
87 const FormFieldData& field);
89 // If Chrome has not prompted for access to the user's address book, the
90 // method prompts the user for permission and blocks the process. Otherwise,
91 // this method has no effect. The return value reflects whether the user was
92 // prompted with a modal dialog.
93 bool AccessAddressBook();
95 // The access Address Book prompt was shown for a form.
96 void ShowedAccessAddressBookPrompt();
98 // The number of times that the access address book prompt was shown.
99 int AccessAddressBookPromptCount();
100 #endif // defined(OS_MACOSX) && !defined(OS_IOS)
102 // Whether the |field| should show an entry to scan a credit card.
103 bool ShouldShowScanCreditCard(const FormData& form,
104 const FormFieldData& field);
106 // Called from our external delegate so they cannot be private.
107 virtual void FillOrPreviewForm(AutofillDriver::RendererFormDataAction action,
108 int query_id,
109 const FormData& form,
110 const FormFieldData& field,
111 int unique_id);
112 virtual void FillCreditCardForm(int query_id,
113 const FormData& form,
114 const FormFieldData& field,
115 const CreditCard& credit_card);
116 void DidShowSuggestions(bool is_new_popup);
117 void OnDidFillAutofillFormData(const base::TimeTicks& timestamp);
118 void OnDidPreviewAutofillFormData();
120 // Remove the credit card or Autofill profile that matches |unique_id|
121 // from the database.
122 void RemoveAutofillProfileOrCreditCard(int unique_id);
124 // Remove the specified Autocomplete entry.
125 void RemoveAutocompleteEntry(const base::string16& name,
126 const base::string16& value);
128 // Returns the present form structures seen by Autofill manager.
129 const std::vector<FormStructure*>& GetFormStructures();
131 // Happens when the autocomplete dialog runs its callback when being closed.
132 void RequestAutocompleteDialogClosed();
134 AutofillClient* client() const { return client_; }
136 const std::string& app_locale() const { return app_locale_; }
138 // Only for testing.
139 void SetTestDelegate(AutofillManagerTestDelegate* delegate);
141 void OnFormsSeen(const std::vector<FormData>& forms,
142 const base::TimeTicks& timestamp);
144 // Processes the submitted |form|, saving any new Autofill data and uploading
145 // the possible field types for the submitted fields to the crowdsourcing
146 // server. Returns false if this form is not relevant for Autofill.
147 bool OnFormSubmitted(const FormData& form,
148 const base::TimeTicks& timestamp);
150 void OnTextFieldDidChange(const FormData& form,
151 const FormFieldData& field,
152 const base::TimeTicks& timestamp);
154 // The |bounding_box| is a window relative value.
155 void OnQueryFormFieldAutofill(int query_id,
156 const FormData& form,
157 const FormFieldData& field,
158 const gfx::RectF& bounding_box,
159 bool display_warning);
160 void OnDidEndTextFieldEditing();
161 void OnHidePopup();
162 void OnSetDataList(const std::vector<base::string16>& values,
163 const std::vector<base::string16>& labels);
165 // Try to label password fields and upload |form|. This differs from
166 // OnFormSubmitted() in a few ways.
167 // - This function will only label the first <input type="password"> field
168 // as |password_type|. Other fields will stay unlabeled, as they
169 // should have been labeled during the upload for OnFormSubmitted().
170 // - This function does not assume that |form| is being uploaded during
171 // the same browsing session as it was originally submitted (as we may
172 // not have the necessary information to classify the form at that time)
173 // so it bypasses the cache and doesn't log the same quality UMA metrics.
174 virtual bool UploadPasswordForm(const FormData& form,
175 const ServerFieldType& pasword_type);
177 // Resets cache.
178 virtual void Reset();
180 // Returns the value of the AutofillEnabled pref.
181 virtual bool IsAutofillEnabled() const;
183 protected:
184 // Test code should prefer to use this constructor.
185 AutofillManager(AutofillDriver* driver,
186 AutofillClient* client,
187 PersonalDataManager* personal_data);
189 // Uploads the form data to the Autofill server.
190 virtual void UploadFormData(const FormStructure& submitted_form);
192 // Logs quality metrics for the |submitted_form| and uploads the form data
193 // to the crowdsourcing server, if appropriate.
194 virtual void UploadFormDataAsyncCallback(
195 const FormStructure* submitted_form,
196 const base::TimeTicks& load_time,
197 const base::TimeTicks& interaction_time,
198 const base::TimeTicks& submission_time);
200 // Maps GUIDs to and from IDs that are used to identify profiles and credit
201 // cards sent to and from the renderer process.
202 virtual int GUIDToID(const PersonalDataManager::GUIDPair& guid) const;
203 virtual const PersonalDataManager::GUIDPair IDToGUID(int id) const;
205 // Methods for packing and unpacking credit card and profile IDs for sending
206 // and receiving to and from the renderer process.
207 int PackGUIDs(const PersonalDataManager::GUIDPair& cc_guid,
208 const PersonalDataManager::GUIDPair& profile_guid) const;
209 void UnpackGUIDs(int id,
210 PersonalDataManager::GUIDPair* cc_guid,
211 PersonalDataManager::GUIDPair* profile_guid) const;
213 const AutofillMetrics* metric_logger() const { return metric_logger_.get(); }
214 void set_metric_logger(const AutofillMetrics* metric_logger);
216 ScopedVector<FormStructure>* form_structures() { return &form_structures_; }
218 // Exposed for testing.
219 AutofillExternalDelegate* external_delegate() {
220 return external_delegate_;
223 private:
224 // AutofillDownloadManager::Observer:
225 void OnLoadedServerPredictions(const std::string& response_xml) override;
227 // Returns false if Autofill is disabled or if no Autofill data is available.
228 bool RefreshDataModels() const;
230 // Unpacks |unique_id| and fills |form_group| and |variant| with the
231 // appropriate data source and variant index. Sets |is_credit_card| to true
232 // if |data_model| points to a CreditCard data model, false if it's a
233 // profile data model.
234 // Returns false if the unpacked id cannot be found.
235 bool GetProfileOrCreditCard(int unique_id,
236 const AutofillDataModel** data_model,
237 size_t* variant,
238 bool* is_credit_card) const WARN_UNUSED_RESULT;
240 // Fills or previews |data_model| in the |form|.
241 void FillOrPreviewDataModelForm(AutofillDriver::RendererFormDataAction action,
242 int query_id,
243 const FormData& form,
244 const FormFieldData& field,
245 const AutofillDataModel* data_model,
246 size_t variant,
247 bool is_credit_card);
249 // Fills |form_structure| cached element corresponding to |form|.
250 // Returns false if the cached element was not found.
251 bool FindCachedForm(const FormData& form,
252 FormStructure** form_structure) const WARN_UNUSED_RESULT;
254 // Fills |form_structure| and |autofill_field| with the cached elements
255 // corresponding to |form| and |field|. This might have the side-effect of
256 // updating the cache. Returns false if the |form| is not autofillable, or if
257 // it is not already present in the cache and the cache is full.
258 bool GetCachedFormAndField(const FormData& form,
259 const FormFieldData& field,
260 FormStructure** form_structure,
261 AutofillField** autofill_field) WARN_UNUSED_RESULT;
263 // Returns the field corresponding to |form| and |field| that can be
264 // autofilled. Returns NULL if the field cannot be autofilled.
265 AutofillField* GetAutofillField(const FormData& form,
266 const FormFieldData& field)
267 WARN_UNUSED_RESULT;
269 // Re-parses |live_form| and adds the result to |form_structures_|.
270 // |cached_form| should be a pointer to the existing version of the form, or
271 // NULL if no cached version exists. The updated form is then written into
272 // |updated_form|. Returns false if the cache could not be updated.
273 bool UpdateCachedForm(const FormData& live_form,
274 const FormStructure* cached_form,
275 FormStructure** updated_form) WARN_UNUSED_RESULT;
277 // Returns a list of values from the stored profiles that match |type| and the
278 // value of |field| and returns the labels of the matching profiles. |labels|
279 // is filled with the Profile label.
280 void GetProfileSuggestions(const FormStructure& form,
281 const FormFieldData& field,
282 const AutofillField& autofill_field,
283 std::vector<base::string16>* values,
284 std::vector<base::string16>* labels,
285 std::vector<base::string16>* icons,
286 std::vector<int>* unique_ids) const;
288 // Returns a list of values from the stored credit cards that match |type| and
289 // the value of |field| and returns the labels of the matching credit cards.
290 void GetCreditCardSuggestions(const FormFieldData& field,
291 const AutofillType& type,
292 std::vector<base::string16>* values,
293 std::vector<base::string16>* labels,
294 std::vector<base::string16>* icons,
295 std::vector<int>* unique_ids) const;
297 // Parses the forms using heuristic matching and querying the Autofill server.
298 void ParseForms(const std::vector<FormData>& forms);
300 // Imports the form data, submitted by the user, into |personal_data_|.
301 void ImportFormData(const FormStructure& submitted_form);
303 // If |initial_interaction_timestamp_| is unset or is set to a later time than
304 // |interaction_timestamp|, updates the cached timestamp. The latter check is
305 // needed because IPC messages can arrive out of order.
306 void UpdateInitialInteractionTimestamp(
307 const base::TimeTicks& interaction_timestamp);
309 // Shared code to determine if |form| should be uploaded.
310 bool ShouldUploadForm(const FormStructure& form);
312 // Provides driver-level context to the shared code of the component. Must
313 // outlive this object.
314 AutofillDriver* driver_;
316 AutofillClient* const client_;
318 std::string app_locale_;
320 // The personal data manager, used to save and load personal data to/from the
321 // web database. This is overridden by the AutofillManagerTest.
322 // Weak reference.
323 // May be NULL. NULL indicates OTR.
324 PersonalDataManager* personal_data_;
326 std::list<std::string> autofilled_form_signatures_;
328 // Handles queries and uploads to Autofill servers. Will be NULL if
329 // the download manager functionality is disabled.
330 scoped_ptr<AutofillDownloadManager> download_manager_;
332 // Handles single-field autocomplete form data.
333 scoped_ptr<AutocompleteHistoryManager> autocomplete_history_manager_;
335 // For logging UMA metrics. Overridden by metrics tests.
336 scoped_ptr<const AutofillMetrics> metric_logger_;
337 // Have we logged whether Autofill is enabled for this page load?
338 bool has_logged_autofill_enabled_;
339 // Have we logged an address suggestions count metric for this page?
340 bool has_logged_address_suggestions_count_;
341 // Have we shown Autofill suggestions at least once?
342 bool did_show_suggestions_;
343 // Has the user manually edited at least one form field among the autofillable
344 // ones?
345 bool user_did_type_;
346 // Has the user autofilled a form on this page?
347 bool user_did_autofill_;
348 // Has the user edited a field that was previously autofilled?
349 bool user_did_edit_autofilled_field_;
350 // When the form finished loading.
351 std::map<FormData, base::TimeTicks> forms_loaded_timestamps_;
352 // When the user first interacted with a potentially fillable form on this
353 // page.
354 base::TimeTicks initial_interaction_timestamp_;
356 // Our copy of the form data.
357 ScopedVector<FormStructure> form_structures_;
359 // GUID to ID mapping. We keep two maps to convert back and forth.
360 mutable std::map<PersonalDataManager::GUIDPair, int> guid_id_map_;
361 mutable std::map<int, PersonalDataManager::GUIDPair> id_guid_map_;
363 // Delegate to perform external processing (display, selection) on
364 // our behalf. Weak.
365 AutofillExternalDelegate* external_delegate_;
367 // Delegate used in test to get notifications on certain events.
368 AutofillManagerTestDelegate* test_delegate_;
370 base::WeakPtrFactory<AutofillManager> weak_ptr_factory_;
372 friend class AutofillManagerTest;
373 friend class FormStructureBrowserTest;
374 FRIEND_TEST_ALL_PREFIXES(AutofillManagerTest,
375 DeterminePossibleFieldTypesForUpload);
376 FRIEND_TEST_ALL_PREFIXES(AutofillManagerTest,
377 DeterminePossibleFieldTypesForUploadStressTest);
378 FRIEND_TEST_ALL_PREFIXES(AutofillManagerTest,
379 DisabledAutofillDispatchesError);
380 FRIEND_TEST_ALL_PREFIXES(AutofillMetricsTest, AddressSuggestionsCount);
381 FRIEND_TEST_ALL_PREFIXES(AutofillMetricsTest, AutofillIsEnabledAtPageLoad);
382 FRIEND_TEST_ALL_PREFIXES(AutofillMetricsTest, DeveloperEngagement);
383 FRIEND_TEST_ALL_PREFIXES(AutofillMetricsTest, FormFillDuration);
384 FRIEND_TEST_ALL_PREFIXES(AutofillMetricsTest,
385 NoQualityMetricsForNonAutofillableForms);
386 FRIEND_TEST_ALL_PREFIXES(AutofillMetricsTest, QualityMetrics);
387 FRIEND_TEST_ALL_PREFIXES(AutofillMetricsTest, QualityMetricsForFailure);
388 FRIEND_TEST_ALL_PREFIXES(AutofillMetricsTest, QualityMetricsWithExperimentId);
389 FRIEND_TEST_ALL_PREFIXES(AutofillMetricsTest, SaneMetricsWithCacheMismatch);
390 FRIEND_TEST_ALL_PREFIXES(AutofillManagerTest, TestExternalDelegate);
391 FRIEND_TEST_ALL_PREFIXES(AutofillManagerTest,
392 TestTabContentsWithExternalDelegate);
393 FRIEND_TEST_ALL_PREFIXES(AutofillMetricsTest,
394 UserHappinessFormLoadAndSubmission);
395 FRIEND_TEST_ALL_PREFIXES(AutofillMetricsTest, UserHappinessFormInteraction);
396 FRIEND_TEST_ALL_PREFIXES(AutofillManagerTest,
397 FormSubmittedAutocompleteEnabled);
398 FRIEND_TEST_ALL_PREFIXES(AutofillManagerTest,
399 AutocompleteOffRespected);
400 FRIEND_TEST_ALL_PREFIXES(AutofillManagerTest,
401 AutocompleteOffRespectedWithFlag);
402 DISALLOW_COPY_AND_ASSIGN(AutofillManager);
405 } // namespace autofill
407 #endif // COMPONENTS_AUTOFILL_CORE_BROWSER_AUTOFILL_MANAGER_H_