Include all dupe types (event when value is zero) in scan stats.
[chromium-blink-merge.git] / components / autofill / core / browser / autofill_manager.h
blob1822b16630d7b0efd9ef9ec4d37d7423c3627f33
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/autofill_metrics.h"
27 #include "components/autofill/core/browser/card_unmask_delegate.h"
28 #include "components/autofill/core/browser/form_structure.h"
29 #include "components/autofill/core/browser/personal_data_manager.h"
30 #include "components/autofill/core/browser/wallet/real_pan_wallet_client.h"
31 #include "components/autofill/core/common/form_data.h"
33 namespace gfx {
34 class Rect;
35 class RectF;
38 namespace user_prefs {
39 class PrefRegistrySyncable;
42 namespace autofill {
44 class AutofillDataModel;
45 class AutofillDownloadManager;
46 class AutofillExternalDelegate;
47 class AutofillField;
48 class AutofillClient;
49 class AutofillManagerTestDelegate;
50 class AutofillProfile;
51 class AutofillType;
52 class CreditCard;
53 class FormStructureBrowserTest;
55 struct FormData;
56 struct FormFieldData;
58 // Manages saving and restoring the user's personal information entered into web
59 // forms. One per frame; owned by the AutofillDriver.
60 class AutofillManager : public AutofillDownloadManager::Observer,
61 public CardUnmaskDelegate,
62 public wallet::RealPanWalletClient::Delegate {
63 public:
64 enum AutofillDownloadManagerState {
65 ENABLE_AUTOFILL_DOWNLOAD_MANAGER,
66 DISABLE_AUTOFILL_DOWNLOAD_MANAGER,
69 // Registers our Enable/Disable Autofill pref.
70 static void RegisterProfilePrefs(user_prefs::PrefRegistrySyncable* registry);
72 #if defined(OS_MACOSX) && !defined(OS_IOS)
73 static void MigrateUserPrefs(PrefService* prefs);
74 #endif // defined(OS_MACOSX) && !defined(OS_IOS)
76 AutofillManager(AutofillDriver* driver,
77 AutofillClient* client,
78 const std::string& app_locale,
79 AutofillDownloadManagerState enable_download_manager);
80 ~AutofillManager() override;
82 // Sets an external delegate.
83 void SetExternalDelegate(AutofillExternalDelegate* delegate);
85 void ShowAutofillSettings();
87 #if defined(OS_MACOSX) && !defined(OS_IOS)
88 // Whether the |field| should show an entry to prompt the user to give Chrome
89 // access to the user's address book.
90 bool ShouldShowAccessAddressBookSuggestion(const FormData& form,
91 const FormFieldData& field);
93 // If Chrome has not prompted for access to the user's address book, the
94 // method prompts the user for permission and blocks the process. Otherwise,
95 // this method has no effect. The return value reflects whether the user was
96 // prompted with a modal dialog.
97 bool AccessAddressBook();
99 // The access Address Book prompt was shown for a form.
100 void ShowedAccessAddressBookPrompt();
102 // The number of times that the access address book prompt was shown.
103 int AccessAddressBookPromptCount();
104 #endif // defined(OS_MACOSX) && !defined(OS_IOS)
106 // Whether the |field| should show an entry to scan a credit card.
107 virtual bool ShouldShowScanCreditCard(const FormData& form,
108 const FormFieldData& field);
110 // Called from our external delegate so they cannot be private.
111 virtual void FillOrPreviewForm(AutofillDriver::RendererFormDataAction action,
112 int query_id,
113 const FormData& form,
114 const FormFieldData& field,
115 int unique_id);
116 virtual void FillCreditCardForm(int query_id,
117 const FormData& form,
118 const FormFieldData& field,
119 const CreditCard& credit_card);
120 void DidShowSuggestions(bool is_new_popup,
121 const FormData& form,
122 const FormFieldData& field);
123 void OnDidFillAutofillFormData(const base::TimeTicks& timestamp);
124 void OnDidPreviewAutofillFormData();
126 // Returns true if the value/identifier is deletable. Fills out
127 // |title| and |body| with relevant user-facing text.
128 bool GetDeletionConfirmationText(const base::string16& value,
129 int identifier,
130 base::string16* title,
131 base::string16* body);
133 // Remove the credit card or Autofill profile that matches |unique_id|
134 // from the database. Returns true if deletion is allowed.
135 bool RemoveAutofillProfileOrCreditCard(int unique_id);
137 // Remove the specified Autocomplete entry.
138 void RemoveAutocompleteEntry(const base::string16& name,
139 const base::string16& value);
141 // Returns true when the Wallet card unmask prompt is being displayed.
142 bool IsShowingUnmaskPrompt();
144 // Returns the present form structures seen by Autofill manager.
145 const std::vector<FormStructure*>& GetFormStructures();
147 // Happens when the autocomplete dialog runs its callback when being closed.
148 void RequestAutocompleteDialogClosed();
150 AutofillClient* client() const { return client_; }
152 const std::string& app_locale() const { return app_locale_; }
154 // Only for testing.
155 void SetTestDelegate(AutofillManagerTestDelegate* delegate);
157 void OnFormsSeen(const std::vector<FormData>& forms,
158 const base::TimeTicks& timestamp);
160 // Processes the about-to-be-submitted |form|, uploading the possible field
161 // types for the submitted fields to the crowdsourcing server. Returns false
162 // if this form is not relevant for Autofill.
163 bool OnWillSubmitForm(const FormData& form, const base::TimeTicks& timestamp);
165 // Processes the submitted |form|, saving any new Autofill data to the user's
166 // personal profile. Returns false if this form is not relevant for Autofill.
167 bool OnFormSubmitted(const FormData& form);
169 void OnTextFieldDidChange(const FormData& form,
170 const FormFieldData& field,
171 const base::TimeTicks& timestamp);
173 // The |bounding_box| is a window relative value.
174 void OnQueryFormFieldAutofill(int query_id,
175 const FormData& form,
176 const FormFieldData& field,
177 const gfx::RectF& bounding_box);
178 void OnDidEndTextFieldEditing();
179 void OnHidePopup();
180 void OnSetDataList(const std::vector<base::string16>& values,
181 const std::vector<base::string16>& labels);
183 // Try to label password fields and upload |form|. This differs from
184 // OnFormSubmitted() in a few ways.
185 // - This function will only label the first <input type="password"> field
186 // as |password_type|. Other fields will stay unlabeled, as they
187 // should have been labeled during the upload for OnFormSubmitted().
188 // - This function does not assume that |form| is being uploaded during
189 // the same browsing session as it was originally submitted (as we may
190 // not have the necessary information to classify the form at that time)
191 // so it bypasses the cache and doesn't log the same quality UMA metrics.
192 virtual bool UploadPasswordForm(const FormData& form,
193 const ServerFieldType& pasword_type);
195 // Resets cache.
196 virtual void Reset();
198 // Returns the value of the AutofillEnabled pref.
199 virtual bool IsAutofillEnabled() const;
201 protected:
202 // Test code should prefer to use this constructor.
203 AutofillManager(AutofillDriver* driver,
204 AutofillClient* client,
205 PersonalDataManager* personal_data);
207 // Uploads the form data to the Autofill server.
208 virtual void UploadFormData(const FormStructure& submitted_form);
210 // Logs quality metrics for the |submitted_form| and uploads the form data
211 // to the crowdsourcing server, if appropriate.
212 virtual void UploadFormDataAsyncCallback(
213 const FormStructure* submitted_form,
214 const base::TimeTicks& load_time,
215 const base::TimeTicks& interaction_time,
216 const base::TimeTicks& submission_time);
218 // Maps suggestion backend ID to and from an integer identifying it. Two of
219 // these intermediate integers are packed by MakeFrontendID to make the IDs
220 // that this class generates for the UI and for IPC.
221 virtual int BackendIDToInt(const std::string& backend_id) const;
222 virtual std::string IntToBackendID(int int_id) const;
224 // Methods for packing and unpacking credit card and profile IDs for sending
225 // and receiving to and from the renderer process.
226 int MakeFrontendID(const std::string& cc_backend_id,
227 const std::string& profile_backend_id) const;
228 void SplitFrontendID(int frontend_id,
229 std::string* cc_backend_id,
230 std::string* profile_backend_id) const;
232 ScopedVector<FormStructure>* form_structures() { return &form_structures_; }
234 // Exposed for testing.
235 AutofillExternalDelegate* external_delegate() {
236 return external_delegate_;
239 private:
240 // AutofillDownloadManager::Observer:
241 void OnLoadedServerPredictions(const std::string& response_xml) override;
243 // CardUnmaskDelegate:
244 void OnUnmaskResponse(const UnmaskResponse& response) override;
245 void OnUnmaskPromptClosed() override;
247 // wallet::RealPanWalletClient::Delegate:
248 IdentityProvider* GetIdentityProvider() override;
249 void OnDidGetRealPan(AutofillClient::GetRealPanResult result,
250 const std::string& real_pan) override;
252 // Returns false if Autofill is disabled or if no Autofill data is available.
253 bool RefreshDataModels();
255 // Returns true if the unique_id refers to a credit card and false if
256 // it refers to a profile.
257 bool IsCreditCard(int unique_id);
259 // Gets the profile referred by |unique_id|. Returns true if the profile
260 // exists.
261 bool GetProfile(int unique_id, const AutofillProfile** profile);
263 // Gets the credit card referred by |unique_id|. Returns true if the credit
264 // card exists.
265 bool GetCreditCard(int unique_id, const CreditCard** credit_card);
267 // Determines whether a fill on |form| initiated from |field| will wind up
268 // filling a credit card number. This is useful to determine if we will need
269 // to unmask a card.
270 bool WillFillCreditCardNumber(const FormData& form,
271 const FormFieldData& field);
273 // Fills or previews the credit card form.
274 // Assumes the form and field are valid.
275 void FillOrPreviewCreditCardForm(
276 AutofillDriver::RendererFormDataAction action,
277 int query_id,
278 const FormData& form,
279 const FormFieldData& field,
280 const CreditCard& credit_card);
282 // Fills or previews the profile form.
283 // Assumes the form and field are valid.
284 void FillOrPreviewProfileForm(AutofillDriver::RendererFormDataAction action,
285 int query_id,
286 const FormData& form,
287 const FormFieldData& field,
288 const AutofillProfile& profile);
290 // Fills or previews |data_model| in the |form|.
291 void FillOrPreviewDataModelForm(AutofillDriver::RendererFormDataAction action,
292 int query_id,
293 const FormData& form,
294 const FormFieldData& field,
295 const AutofillDataModel& data_model,
296 bool is_credit_card);
298 // Creates a FormStructure using the FormData received from the renderer. Will
299 // return an empty scoped_ptr if the data should not be processed for upload
300 // or personal data.
301 scoped_ptr<FormStructure> ValidateSubmittedForm(const FormData& form);
303 // Fills |form_structure| cached element corresponding to |form|.
304 // Returns false if the cached element was not found.
305 bool FindCachedForm(const FormData& form,
306 FormStructure** form_structure) const WARN_UNUSED_RESULT;
308 // Fills |form_structure| and |autofill_field| with the cached elements
309 // corresponding to |form| and |field|. This might have the side-effect of
310 // updating the cache. Returns false if the |form| is not autofillable, or if
311 // it is not already present in the cache and the cache is full.
312 bool GetCachedFormAndField(const FormData& form,
313 const FormFieldData& field,
314 FormStructure** form_structure,
315 AutofillField** autofill_field) WARN_UNUSED_RESULT;
317 // Returns the field corresponding to |form| and |field| that can be
318 // autofilled. Returns NULL if the field cannot be autofilled.
319 AutofillField* GetAutofillField(const FormData& form,
320 const FormFieldData& field)
321 WARN_UNUSED_RESULT;
323 // Re-parses |live_form| and adds the result to |form_structures_|.
324 // |cached_form| should be a pointer to the existing version of the form, or
325 // NULL if no cached version exists. The updated form is then written into
326 // |updated_form|. Returns false if the cache could not be updated.
327 bool UpdateCachedForm(const FormData& live_form,
328 const FormStructure* cached_form,
329 FormStructure** updated_form) WARN_UNUSED_RESULT;
331 // Returns a list of values from the stored profiles that match |type| and the
332 // value of |field| and returns the labels of the matching profiles. |labels|
333 // is filled with the Profile label.
334 std::vector<Suggestion> GetProfileSuggestions(
335 const FormStructure& form,
336 const FormFieldData& field,
337 const AutofillField& autofill_field) const;
339 // Returns a list of values from the stored credit cards that match |type| and
340 // the value of |field| and returns the labels of the matching credit cards.
341 std::vector<Suggestion> GetCreditCardSuggestions(
342 const FormFieldData& field,
343 const AutofillType& type) const;
345 // Parses the forms using heuristic matching and querying the Autofill server.
346 void ParseForms(const std::vector<FormData>& forms);
348 // Imports the form data, submitted by the user, into |personal_data_|.
349 void ImportFormData(const FormStructure& submitted_form);
351 // If |initial_interaction_timestamp_| is unset or is set to a later time than
352 // |interaction_timestamp|, updates the cached timestamp. The latter check is
353 // needed because IPC messages can arrive out of order.
354 void UpdateInitialInteractionTimestamp(
355 const base::TimeTicks& interaction_timestamp);
357 // Shared code to determine if |form| should be uploaded.
358 bool ShouldUploadForm(const FormStructure& form);
360 #if defined(OS_MACOSX) && !defined(OS_IOS)
361 // Emits a UMA metric indicating whether the accepted Autofill suggestion is
362 // from the Mac Address Book.
363 void EmitIsFromAddressBookMetric(int unique_id);
364 #endif // defined(OS_MACOSX) && !defined(OS_IOS)
366 // Provides driver-level context to the shared code of the component. Must
367 // outlive this object.
368 AutofillDriver* driver_;
370 AutofillClient* const client_;
372 // Handles real PAN requests.
373 wallet::RealPanWalletClient real_pan_client_;
375 std::string app_locale_;
377 // The personal data manager, used to save and load personal data to/from the
378 // web database. This is overridden by the AutofillManagerTest.
379 // Weak reference.
380 // May be NULL. NULL indicates OTR.
381 PersonalDataManager* personal_data_;
383 std::list<std::string> autofilled_form_signatures_;
385 // Handles queries and uploads to Autofill servers. Will be NULL if
386 // the download manager functionality is disabled.
387 scoped_ptr<AutofillDownloadManager> download_manager_;
389 // Handles single-field autocomplete form data.
390 scoped_ptr<AutocompleteHistoryManager> autocomplete_history_manager_;
392 // Utilities for logging form events.
393 scoped_ptr<AutofillMetrics::FormEventLogger> address_form_event_logger_;
394 scoped_ptr<AutofillMetrics::FormEventLogger> credit_card_form_event_logger_;
396 // Have we logged whether Autofill is enabled for this page load?
397 bool has_logged_autofill_enabled_;
398 // Have we logged an address suggestions count metric for this page?
399 bool has_logged_address_suggestions_count_;
400 // Have we shown Autofill suggestions at least once?
401 bool did_show_suggestions_;
402 // Has the user manually edited at least one form field among the autofillable
403 // ones?
404 bool user_did_type_;
405 // Has the user autofilled a form on this page?
406 bool user_did_autofill_;
407 // Has the user edited a field that was previously autofilled?
408 bool user_did_edit_autofilled_field_;
409 // When the form finished loading.
410 std::map<FormData, base::TimeTicks> forms_loaded_timestamps_;
411 // When the user first interacted with a potentially fillable form on this
412 // page.
413 base::TimeTicks initial_interaction_timestamp_;
415 // Our copy of the form data.
416 ScopedVector<FormStructure> form_structures_;
418 // A copy of the credit card that's currently being unmasked, and data about
419 // the form.
420 CreditCard unmasking_card_;
421 // A copy of the latest card unmasking response.
422 UnmaskResponse unmask_response_;
423 int unmasking_query_id_;
424 FormData unmasking_form_;
425 FormFieldData unmasking_field_;
426 // Time when we requested the last real pan
427 base::Time real_pan_request_timestamp_;
429 // Masked copies of recently unmasked cards, to help avoid double-asking to
430 // save the card (in the prompt and in the infobar after submit).
431 std::vector<CreditCard> recently_unmasked_cards_;
433 // Suggestion backend ID to ID mapping. We keep two maps to convert back and
434 // forth. These should be used only by BackendIDToInt and IntToBackendID.
435 // Note that the integers are not frontend IDs.
436 mutable std::map<std::string, int> backend_to_int_map_;
437 mutable std::map<int, std::string> int_to_backend_map_;
439 // Delegate to perform external processing (display, selection) on
440 // our behalf. Weak.
441 AutofillExternalDelegate* external_delegate_;
443 // Delegate used in test to get notifications on certain events.
444 AutofillManagerTestDelegate* test_delegate_;
446 base::WeakPtrFactory<AutofillManager> weak_ptr_factory_;
448 friend class AutofillManagerTest;
449 friend class FormStructureBrowserTest;
450 FRIEND_TEST_ALL_PREFIXES(AutofillManagerTest,
451 DeterminePossibleFieldTypesForUpload);
452 FRIEND_TEST_ALL_PREFIXES(AutofillManagerTest,
453 DeterminePossibleFieldTypesForUploadStressTest);
454 FRIEND_TEST_ALL_PREFIXES(AutofillManagerTest,
455 DisabledAutofillDispatchesError);
456 FRIEND_TEST_ALL_PREFIXES(AutofillMetricsTest, AddressFilledFormEvents);
457 FRIEND_TEST_ALL_PREFIXES(AutofillMetricsTest, AddressSubmittedFormEvents);
458 FRIEND_TEST_ALL_PREFIXES(AutofillMetricsTest, AddressWillSubmitFormEvents);
459 FRIEND_TEST_ALL_PREFIXES(AutofillMetricsTest, AddressSuggestionsCount);
460 FRIEND_TEST_ALL_PREFIXES(AutofillMetricsTest, AutofillIsEnabledAtPageLoad);
461 FRIEND_TEST_ALL_PREFIXES(AutofillMetricsTest, CreditCardSelectedFormEvents);
462 FRIEND_TEST_ALL_PREFIXES(AutofillMetricsTest, CreditCardFilledFormEvents);
463 FRIEND_TEST_ALL_PREFIXES(AutofillMetricsTest, CreditCardGetRealPanDuration);
464 FRIEND_TEST_ALL_PREFIXES(AutofillMetricsTest, CreditCardWillSubmitFormEvents);
465 FRIEND_TEST_ALL_PREFIXES(AutofillMetricsTest, CreditCardSubmittedFormEvents);
466 FRIEND_TEST_ALL_PREFIXES(AutofillMetricsTest, DeveloperEngagement);
467 FRIEND_TEST_ALL_PREFIXES(AutofillMetricsTest, FormFillDuration);
468 FRIEND_TEST_ALL_PREFIXES(AutofillMetricsTest,
469 NoQualityMetricsForNonAutofillableForms);
470 FRIEND_TEST_ALL_PREFIXES(AutofillMetricsTest, QualityMetrics);
471 FRIEND_TEST_ALL_PREFIXES(AutofillMetricsTest, QualityMetricsForFailure);
472 FRIEND_TEST_ALL_PREFIXES(AutofillMetricsTest, QualityMetricsWithExperimentId);
473 FRIEND_TEST_ALL_PREFIXES(AutofillMetricsTest, SaneMetricsWithCacheMismatch);
474 FRIEND_TEST_ALL_PREFIXES(AutofillManagerTest, TestExternalDelegate);
475 FRIEND_TEST_ALL_PREFIXES(AutofillManagerTest,
476 TestTabContentsWithExternalDelegate);
477 FRIEND_TEST_ALL_PREFIXES(AutofillMetricsTest,
478 UserHappinessFormLoadAndSubmission);
479 FRIEND_TEST_ALL_PREFIXES(AutofillMetricsTest, UserHappinessFormInteraction);
480 FRIEND_TEST_ALL_PREFIXES(AutofillManagerTest,
481 FormSubmittedAutocompleteEnabled);
482 FRIEND_TEST_ALL_PREFIXES(AutofillManagerTest,
483 AutocompleteOffRespectedForAutocomplete);
484 FRIEND_TEST_ALL_PREFIXES(AutofillManagerTest,
485 DontSaveCvcInAutocompleteHistory);
486 FRIEND_TEST_ALL_PREFIXES(AutofillManagerTest, DontOfferToSaveWalletCard);
487 DISALLOW_COPY_AND_ASSIGN(AutofillManager);
490 } // namespace autofill
492 #endif // COMPONENTS_AUTOFILL_CORE_BROWSER_AUTOFILL_MANAGER_H_