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_
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 // This define protects some debugging code (see DumpAutofillData). This
34 // is here to make it easier to delete this code when the test is complete,
35 // and to prevent adding the code on mobile where there is no desktop (the
36 // debug dump file is written to the desktop) or command-line flags to enable.
37 #if defined(OS_WIN) || defined(OS_MACOSX) || defined(OS_LINUX)
38 #define ENABLE_FORM_DEBUG_DUMP
41 class ChromeUIWebViewWebTest
;
42 class ChromeWKWebViewWebTest
;
49 namespace user_prefs
{
50 class PrefRegistrySyncable
;
55 class AutofillDataModel
;
56 class AutofillDownloadManager
;
57 class AutofillExternalDelegate
;
60 class AutofillManagerTestDelegate
;
61 class AutofillProfile
;
64 class FormStructureBrowserTest
;
65 template <class WebTestT
> class FormStructureBrowserTestIos
;
70 // Manages saving and restoring the user's personal information entered into web
71 // forms. One per frame; owned by the AutofillDriver.
72 class AutofillManager
: public AutofillDownloadManager::Observer
,
73 public CardUnmaskDelegate
,
74 public wallet::RealPanWalletClient::Delegate
{
76 enum AutofillDownloadManagerState
{
77 ENABLE_AUTOFILL_DOWNLOAD_MANAGER
,
78 DISABLE_AUTOFILL_DOWNLOAD_MANAGER
,
81 // Registers our Enable/Disable Autofill pref.
82 static void RegisterProfilePrefs(user_prefs::PrefRegistrySyncable
* registry
);
84 AutofillManager(AutofillDriver
* driver
,
85 AutofillClient
* client
,
86 const std::string
& app_locale
,
87 AutofillDownloadManagerState enable_download_manager
);
88 ~AutofillManager() override
;
90 // Sets an external delegate.
91 void SetExternalDelegate(AutofillExternalDelegate
* delegate
);
93 void ShowAutofillSettings();
95 // Whether the |field| should show an entry to scan a credit card.
96 virtual bool ShouldShowScanCreditCard(const FormData
& form
,
97 const FormFieldData
& field
);
99 // Called from our external delegate so they cannot be private.
100 virtual void FillOrPreviewForm(AutofillDriver::RendererFormDataAction action
,
102 const FormData
& form
,
103 const FormFieldData
& field
,
105 virtual void FillCreditCardForm(int query_id
,
106 const FormData
& form
,
107 const FormFieldData
& field
,
108 const CreditCard
& credit_card
);
109 void DidShowSuggestions(bool is_new_popup
,
110 const FormData
& form
,
111 const FormFieldData
& field
);
112 void OnDidFillAutofillFormData(const base::TimeTicks
& timestamp
);
113 void OnDidPreviewAutofillFormData();
115 // Returns true if the value/identifier is deletable. Fills out
116 // |title| and |body| with relevant user-facing text.
117 bool GetDeletionConfirmationText(const base::string16
& value
,
119 base::string16
* title
,
120 base::string16
* body
);
122 // Remove the credit card or Autofill profile that matches |unique_id|
123 // from the database. Returns true if deletion is allowed.
124 bool RemoveAutofillProfileOrCreditCard(int unique_id
);
126 // Remove the specified Autocomplete entry.
127 void RemoveAutocompleteEntry(const base::string16
& name
,
128 const base::string16
& value
);
130 // Returns true when the Wallet card unmask prompt is being displayed.
131 bool IsShowingUnmaskPrompt();
133 // Returns the present form structures seen by Autofill manager.
134 const std::vector
<FormStructure
*>& GetFormStructures();
136 // Happens when the autocomplete dialog runs its callback when being closed.
137 void RequestAutocompleteDialogClosed();
139 AutofillClient
* client() const { return client_
; }
141 const std::string
& app_locale() const { return app_locale_
; }
144 void SetTestDelegate(AutofillManagerTestDelegate
* delegate
);
146 void OnFormsSeen(const std::vector
<FormData
>& forms
,
147 const base::TimeTicks
& timestamp
);
149 // IMPORTANT: On iOS, this method is called when the form is submitted,
150 // immediately before OnFormSubmitted() is called. Do not assume that
151 // OnWillSubmitForm() will run before the form submits.
152 // TODO(mathp): Revisit this and use a single method to track form submission.
154 // Processes the about-to-be-submitted |form|, uploading the possible field
155 // types for the submitted fields to the crowdsourcing server. Returns false
156 // if this form is not relevant for Autofill.
157 bool OnWillSubmitForm(const FormData
& form
, const base::TimeTicks
& timestamp
);
159 // Processes the submitted |form|, saving any new Autofill data to the user's
160 // personal profile. Returns false if this form is not relevant for Autofill.
161 bool OnFormSubmitted(const FormData
& form
);
163 void OnTextFieldDidChange(const FormData
& form
,
164 const FormFieldData
& field
,
165 const base::TimeTicks
& timestamp
);
167 // The |bounding_box| is a window relative value.
168 void OnQueryFormFieldAutofill(int query_id
,
169 const FormData
& form
,
170 const FormFieldData
& field
,
171 const gfx::RectF
& bounding_box
);
172 void OnDidEndTextFieldEditing();
174 void OnSetDataList(const std::vector
<base::string16
>& values
,
175 const std::vector
<base::string16
>& labels
);
177 // Try to label password fields and upload |form|. This differs from
178 // OnFormSubmitted() in a few ways.
179 // - This function will only label the first <input type="password"> field
180 // as |password_type|. Other fields will stay unlabeled, as they
181 // should have been labeled during the upload for OnFormSubmitted().
182 // - If the |username_field| attribute is nonempty, we will additionally
183 // label the field with that name as the username field.
184 // - This function does not assume that |form| is being uploaded during
185 // the same browsing session as it was originally submitted (as we may
186 // not have the necessary information to classify the form at that time)
187 // so it bypasses the cache and doesn't log the same quality UMA metrics.
188 // |login_form_signature| may be empty. It is non-empty when the user fills
189 // and submits a login form using a generated password. In this case,
190 // |login_form_signature| should be set to the submitted form's signature.
191 // Note that in this case, |form.FormSignature()| gives the signature for the
192 // registration form on which the password was generated, rather than the
193 // submitted form's signature.
194 virtual bool UploadPasswordForm(const FormData
& form
,
195 const base::string16
& username_field
,
196 const ServerFieldType
& pasword_type
,
197 const std::string
& login_form_signature
);
200 virtual void Reset();
202 // Returns the value of the AutofillEnabled pref.
203 virtual bool IsAutofillEnabled() const;
206 // Test code should prefer to use this constructor.
207 AutofillManager(AutofillDriver
* driver
,
208 AutofillClient
* client
,
209 PersonalDataManager
* personal_data
);
211 // Uploads the form data to the Autofill server.
212 virtual void UploadFormData(const FormStructure
& submitted_form
);
214 // Logs quality metrics for the |submitted_form| and uploads the form data
215 // to the crowdsourcing server, if appropriate.
216 virtual void UploadFormDataAsyncCallback(
217 const FormStructure
* submitted_form
,
218 const base::TimeTicks
& load_time
,
219 const base::TimeTicks
& interaction_time
,
220 const base::TimeTicks
& submission_time
);
222 // Maps suggestion backend ID to and from an integer identifying it. Two of
223 // these intermediate integers are packed by MakeFrontendID to make the IDs
224 // that this class generates for the UI and for IPC.
225 virtual int BackendIDToInt(const std::string
& backend_id
) const;
226 virtual std::string
IntToBackendID(int int_id
) const;
228 // Methods for packing and unpacking credit card and profile IDs for sending
229 // and receiving to and from the renderer process.
230 int MakeFrontendID(const std::string
& cc_backend_id
,
231 const std::string
& profile_backend_id
) const;
232 void SplitFrontendID(int frontend_id
,
233 std::string
* cc_backend_id
,
234 std::string
* profile_backend_id
) const;
236 ScopedVector
<FormStructure
>* form_structures() { return &form_structures_
; }
238 // Exposed for testing.
239 AutofillExternalDelegate
* external_delegate() {
240 return external_delegate_
;
244 // AutofillDownloadManager::Observer:
245 void OnLoadedServerPredictions(const std::string
& response_xml
) override
;
247 // CardUnmaskDelegate:
248 void OnUnmaskResponse(const UnmaskResponse
& response
) override
;
249 void OnUnmaskPromptClosed() override
;
251 // wallet::RealPanWalletClient::Delegate:
252 IdentityProvider
* GetIdentityProvider() override
;
253 void OnDidGetRealPan(AutofillClient::GetRealPanResult result
,
254 const std::string
& real_pan
) override
;
256 // Returns false if Autofill is disabled or if no Autofill data is available.
257 bool RefreshDataModels();
259 // Returns true if the unique_id refers to a credit card and false if
260 // it refers to a profile.
261 bool IsCreditCard(int unique_id
);
263 // Gets the profile referred by |unique_id|. Returns true if the profile
265 bool GetProfile(int unique_id
, const AutofillProfile
** profile
);
267 // Gets the credit card referred by |unique_id|. Returns true if the credit
269 bool GetCreditCard(int unique_id
, const CreditCard
** credit_card
);
271 // Determines whether a fill on |form| initiated from |field| will wind up
272 // filling a credit card number. This is useful to determine if we will need
274 bool WillFillCreditCardNumber(const FormData
& form
,
275 const FormFieldData
& field
);
277 // Fills or previews the credit card form.
278 // Assumes the form and field are valid.
279 void FillOrPreviewCreditCardForm(
280 AutofillDriver::RendererFormDataAction action
,
282 const FormData
& form
,
283 const FormFieldData
& field
,
284 const CreditCard
& credit_card
);
286 // Fills or previews the profile form.
287 // Assumes the form and field are valid.
288 void FillOrPreviewProfileForm(AutofillDriver::RendererFormDataAction action
,
290 const FormData
& form
,
291 const FormFieldData
& field
,
292 const AutofillProfile
& profile
);
294 // Fills or previews |data_model| in the |form|.
295 void FillOrPreviewDataModelForm(AutofillDriver::RendererFormDataAction action
,
297 const FormData
& form
,
298 const FormFieldData
& field
,
299 const AutofillDataModel
& data_model
,
300 bool is_credit_card
);
302 // Creates a FormStructure using the FormData received from the renderer. Will
303 // return an empty scoped_ptr if the data should not be processed for upload
305 scoped_ptr
<FormStructure
> ValidateSubmittedForm(const FormData
& form
);
307 // Fills |form_structure| cached element corresponding to |form|.
308 // Returns false if the cached element was not found.
309 bool FindCachedForm(const FormData
& form
,
310 FormStructure
** form_structure
) const WARN_UNUSED_RESULT
;
312 // Fills |form_structure| and |autofill_field| with the cached elements
313 // corresponding to |form| and |field|. This might have the side-effect of
314 // updating the cache. Returns false if the |form| is not autofillable, or if
315 // it is not already present in the cache and the cache is full.
316 bool GetCachedFormAndField(const FormData
& form
,
317 const FormFieldData
& field
,
318 FormStructure
** form_structure
,
319 AutofillField
** autofill_field
) WARN_UNUSED_RESULT
;
321 // Returns the field corresponding to |form| and |field| that can be
322 // autofilled. Returns NULL if the field cannot be autofilled.
323 AutofillField
* GetAutofillField(const FormData
& form
,
324 const FormFieldData
& field
)
327 // Re-parses |live_form| and adds the result to |form_structures_|.
328 // |cached_form| should be a pointer to the existing version of the form, or
329 // NULL if no cached version exists. The updated form is then written into
330 // |updated_form|. Returns false if the cache could not be updated.
331 bool UpdateCachedForm(const FormData
& live_form
,
332 const FormStructure
* cached_form
,
333 FormStructure
** updated_form
) WARN_UNUSED_RESULT
;
335 // Returns a list of values from the stored profiles that match |type| and the
336 // value of |field| and returns the labels of the matching profiles. |labels|
337 // is filled with the Profile label.
338 std::vector
<Suggestion
> GetProfileSuggestions(
339 const FormStructure
& form
,
340 const FormFieldData
& field
,
341 const AutofillField
& autofill_field
) const;
343 // Returns a list of values from the stored credit cards that match |type| and
344 // the value of |field| and returns the labels of the matching credit cards.
345 std::vector
<Suggestion
> GetCreditCardSuggestions(
346 const FormFieldData
& field
,
347 const AutofillType
& type
) const;
349 // Parses the forms using heuristic matching and querying the Autofill server.
350 void ParseForms(const std::vector
<FormData
>& forms
);
352 // Imports the form data, submitted by the user, into |personal_data_|.
353 void ImportFormData(const FormStructure
& submitted_form
);
355 // If |initial_interaction_timestamp_| is unset or is set to a later time than
356 // |interaction_timestamp|, updates the cached timestamp. The latter check is
357 // needed because IPC messages can arrive out of order.
358 void UpdateInitialInteractionTimestamp(
359 const base::TimeTicks
& interaction_timestamp
);
361 // Shared code to determine if |form| should be uploaded.
362 bool ShouldUploadForm(const FormStructure
& form
);
364 #ifdef ENABLE_FORM_DEBUG_DUMP
365 // Dumps the cached forms to a file on disk.
366 void DumpAutofillData(bool imported_cc
) const;
369 // Provides driver-level context to the shared code of the component. Must
370 // outlive this object.
371 AutofillDriver
* driver_
;
373 AutofillClient
* const client_
;
375 // Handles real PAN requests.
376 wallet::RealPanWalletClient real_pan_client_
;
378 std::string app_locale_
;
380 // The personal data manager, used to save and load personal data to/from the
381 // web database. This is overridden by the AutofillManagerTest.
383 // May be NULL. NULL indicates OTR.
384 PersonalDataManager
* personal_data_
;
386 std::list
<std::string
> autofilled_form_signatures_
;
388 // Handles queries and uploads to Autofill servers. Will be NULL if
389 // the download manager functionality is disabled.
390 scoped_ptr
<AutofillDownloadManager
> download_manager_
;
392 // Handles single-field autocomplete form data.
393 scoped_ptr
<AutocompleteHistoryManager
> autocomplete_history_manager_
;
395 // Utilities for logging form events.
396 scoped_ptr
<AutofillMetrics::FormEventLogger
> address_form_event_logger_
;
397 scoped_ptr
<AutofillMetrics::FormEventLogger
> credit_card_form_event_logger_
;
399 // Have we logged whether Autofill is enabled for this page load?
400 bool has_logged_autofill_enabled_
;
401 // Have we logged an address suggestions count metric for this page?
402 bool has_logged_address_suggestions_count_
;
403 // Have we shown Autofill suggestions at least once?
404 bool did_show_suggestions_
;
405 // Has the user manually edited at least one form field among the autofillable
408 // Has the user autofilled a form on this page?
409 bool user_did_autofill_
;
410 // Has the user edited a field that was previously autofilled?
411 bool user_did_edit_autofilled_field_
;
412 // When the form finished loading.
413 std::map
<FormData
, base::TimeTicks
> forms_loaded_timestamps_
;
414 // When the user first interacted with a potentially fillable form on this
416 base::TimeTicks initial_interaction_timestamp_
;
418 // Our copy of the form data.
419 ScopedVector
<FormStructure
> form_structures_
;
421 // A copy of the credit card that's currently being unmasked, and data about
423 CreditCard unmasking_card_
;
424 // A copy of the latest card unmasking response.
425 UnmaskResponse unmask_response_
;
426 int unmasking_query_id_
;
427 FormData unmasking_form_
;
428 FormFieldData unmasking_field_
;
429 // Time when we requested the last real pan
430 base::Time real_pan_request_timestamp_
;
432 // Masked copies of recently unmasked cards, to help avoid double-asking to
433 // save the card (in the prompt and in the infobar after submit).
434 std::vector
<CreditCard
> recently_unmasked_cards_
;
436 #ifdef ENABLE_FORM_DEBUG_DUMP
437 // The last few autofilled forms (key/value pairs) submitted, for debugging.
438 // TODO(brettw) this should be removed. See DumpAutofillData.
439 std::vector
<std::map
<std::string
, base::string16
>>
440 recently_autofilled_forms_
;
443 // Suggestion backend ID to ID mapping. We keep two maps to convert back and
444 // forth. These should be used only by BackendIDToInt and IntToBackendID.
445 // Note that the integers are not frontend IDs.
446 mutable std::map
<std::string
, int> backend_to_int_map_
;
447 mutable std::map
<int, std::string
> int_to_backend_map_
;
449 // Delegate to perform external processing (display, selection) on
451 AutofillExternalDelegate
* external_delegate_
;
453 // Delegate used in test to get notifications on certain events.
454 AutofillManagerTestDelegate
* test_delegate_
;
456 base::WeakPtrFactory
<AutofillManager
> weak_ptr_factory_
;
458 friend class AutofillManagerTest
;
459 friend class FormStructureBrowserTest
;
460 friend class FormStructureBrowserTestIos
<ChromeUIWebViewWebTest
>;
461 friend class FormStructureBrowserTestIos
<ChromeWKWebViewWebTest
>;
462 FRIEND_TEST_ALL_PREFIXES(AutofillManagerTest
,
463 DeterminePossibleFieldTypesForUpload
);
464 FRIEND_TEST_ALL_PREFIXES(AutofillManagerTest
,
465 DeterminePossibleFieldTypesForUploadStressTest
);
466 FRIEND_TEST_ALL_PREFIXES(AutofillManagerTest
,
467 DisabledAutofillDispatchesError
);
468 FRIEND_TEST_ALL_PREFIXES(AutofillMetricsTest
, AddressFilledFormEvents
);
469 FRIEND_TEST_ALL_PREFIXES(AutofillMetricsTest
, AddressSubmittedFormEvents
);
470 FRIEND_TEST_ALL_PREFIXES(AutofillMetricsTest
, AddressWillSubmitFormEvents
);
471 FRIEND_TEST_ALL_PREFIXES(AutofillMetricsTest
, AddressSuggestionsCount
);
472 FRIEND_TEST_ALL_PREFIXES(AutofillMetricsTest
, AutofillIsEnabledAtPageLoad
);
473 FRIEND_TEST_ALL_PREFIXES(AutofillMetricsTest
, CreditCardSelectedFormEvents
);
474 FRIEND_TEST_ALL_PREFIXES(AutofillMetricsTest
, CreditCardFilledFormEvents
);
475 FRIEND_TEST_ALL_PREFIXES(AutofillMetricsTest
, CreditCardGetRealPanDuration
);
476 FRIEND_TEST_ALL_PREFIXES(AutofillMetricsTest
, CreditCardWillSubmitFormEvents
);
477 FRIEND_TEST_ALL_PREFIXES(AutofillMetricsTest
, CreditCardSubmittedFormEvents
);
478 FRIEND_TEST_ALL_PREFIXES(AutofillMetricsTest
, DeveloperEngagement
);
479 FRIEND_TEST_ALL_PREFIXES(AutofillMetricsTest
, FormFillDuration
);
480 FRIEND_TEST_ALL_PREFIXES(AutofillMetricsTest
,
481 NoQualityMetricsForNonAutofillableForms
);
482 FRIEND_TEST_ALL_PREFIXES(AutofillMetricsTest
, QualityMetrics
);
483 FRIEND_TEST_ALL_PREFIXES(AutofillMetricsTest
, QualityMetricsForFailure
);
484 FRIEND_TEST_ALL_PREFIXES(AutofillMetricsTest
, QualityMetricsWithExperimentId
);
485 FRIEND_TEST_ALL_PREFIXES(AutofillMetricsTest
, SaneMetricsWithCacheMismatch
);
486 FRIEND_TEST_ALL_PREFIXES(AutofillManagerTest
, TestExternalDelegate
);
487 FRIEND_TEST_ALL_PREFIXES(AutofillManagerTest
,
488 TestTabContentsWithExternalDelegate
);
489 FRIEND_TEST_ALL_PREFIXES(AutofillMetricsTest
,
490 UserHappinessFormLoadAndSubmission
);
491 FRIEND_TEST_ALL_PREFIXES(AutofillMetricsTest
, UserHappinessFormInteraction
);
492 FRIEND_TEST_ALL_PREFIXES(AutofillManagerTest
,
493 FormSubmittedAutocompleteEnabled
);
494 FRIEND_TEST_ALL_PREFIXES(AutofillManagerTest
,
495 AutocompleteOffRespectedForAutocomplete
);
496 FRIEND_TEST_ALL_PREFIXES(AutofillManagerTest
,
497 DontSaveCvcInAutocompleteHistory
);
498 FRIEND_TEST_ALL_PREFIXES(AutofillManagerTest
, DontOfferToSaveWalletCard
);
499 FRIEND_TEST_ALL_PREFIXES(AutofillManagerTest
, FillInUpdatedExpirationDate
);
500 DISALLOW_COPY_AND_ASSIGN(AutofillManager
);
503 } // namespace autofill
505 #endif // COMPONENTS_AUTOFILL_CORE_BROWSER_AUTOFILL_MANAGER_H_