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/card_unmask_delegate.h"
27 #include "components/autofill/core/browser/form_structure.h"
28 #include "components/autofill/core/browser/personal_data_manager.h"
29 #include "components/autofill/core/browser/wallet/real_pan_wallet_client.h"
30 #include "components/autofill/core/common/form_data.h"
37 namespace user_prefs
{
38 class PrefRegistrySyncable
;
43 class AutofillDataModel
;
44 class AutofillDownloadManager
;
45 class AutofillExternalDelegate
;
48 class AutofillManagerTestDelegate
;
49 class AutofillProfile
;
52 class FormStructureBrowserTest
;
57 // Manages saving and restoring the user's personal information entered into web
58 // forms. One per frame; owned by the AutofillDriver.
59 class AutofillManager
: public AutofillDownloadManager::Observer
,
60 public CardUnmaskDelegate
,
61 public wallet::RealPanWalletClient::Delegate
{
63 enum AutofillDownloadManagerState
{
64 ENABLE_AUTOFILL_DOWNLOAD_MANAGER
,
65 DISABLE_AUTOFILL_DOWNLOAD_MANAGER
,
68 // Registers our Enable/Disable Autofill pref.
69 static void RegisterProfilePrefs(user_prefs::PrefRegistrySyncable
* registry
);
71 #if defined(OS_MACOSX) && !defined(OS_IOS)
72 static void MigrateUserPrefs(PrefService
* prefs
);
73 #endif // defined(OS_MACOSX) && !defined(OS_IOS)
75 AutofillManager(AutofillDriver
* driver
,
76 AutofillClient
* client
,
77 const std::string
& app_locale
,
78 AutofillDownloadManagerState enable_download_manager
);
79 ~AutofillManager() override
;
81 // Sets an external delegate.
82 void SetExternalDelegate(AutofillExternalDelegate
* delegate
);
84 void ShowAutofillSettings();
86 #if defined(OS_MACOSX) && !defined(OS_IOS)
87 // Whether the |field| should show an entry to prompt the user to give Chrome
88 // access to the user's address book.
89 bool ShouldShowAccessAddressBookSuggestion(const FormData
& form
,
90 const FormFieldData
& field
);
92 // If Chrome has not prompted for access to the user's address book, the
93 // method prompts the user for permission and blocks the process. Otherwise,
94 // this method has no effect. The return value reflects whether the user was
95 // prompted with a modal dialog.
96 bool AccessAddressBook();
98 // The access Address Book prompt was shown for a form.
99 void ShowedAccessAddressBookPrompt();
101 // The number of times that the access address book prompt was shown.
102 int AccessAddressBookPromptCount();
103 #endif // defined(OS_MACOSX) && !defined(OS_IOS)
105 // Whether the |field| should show an entry to scan a credit card.
106 virtual bool ShouldShowScanCreditCard(const FormData
& form
,
107 const FormFieldData
& field
);
109 // Called from our external delegate so they cannot be private.
110 virtual void FillOrPreviewForm(AutofillDriver::RendererFormDataAction action
,
112 const FormData
& form
,
113 const FormFieldData
& field
,
115 virtual void FillCreditCardForm(int query_id
,
116 const FormData
& form
,
117 const FormFieldData
& field
,
118 const CreditCard
& credit_card
);
119 void DidShowSuggestions(bool is_new_popup
);
120 void OnDidFillAutofillFormData(const base::TimeTicks
& timestamp
);
121 void OnDidPreviewAutofillFormData();
123 // Remove the credit card or Autofill profile that matches |unique_id|
124 // from the database.
125 void RemoveAutofillProfileOrCreditCard(int unique_id
);
127 // Remove the specified Autocomplete entry.
128 void RemoveAutocompleteEntry(const base::string16
& name
,
129 const base::string16
& value
);
131 // Returns true when the Wallet card unmask prompt is being displayed.
132 bool IsShowingUnmaskPrompt();
134 // Returns the present form structures seen by Autofill manager.
135 const std::vector
<FormStructure
*>& GetFormStructures();
137 // Happens when the autocomplete dialog runs its callback when being closed.
138 void RequestAutocompleteDialogClosed();
140 AutofillClient
* client() const { return client_
; }
142 const std::string
& app_locale() const { return app_locale_
; }
145 void SetTestDelegate(AutofillManagerTestDelegate
* delegate
);
147 void OnFormsSeen(const std::vector
<FormData
>& forms
,
148 const base::TimeTicks
& timestamp
);
150 // Processes the submitted |form|, saving any new Autofill data and uploading
151 // the possible field types for the submitted fields to the crowdsourcing
152 // server. Returns false if this form is not relevant for Autofill.
153 bool OnFormSubmitted(const FormData
& form
,
154 const base::TimeTicks
& timestamp
);
156 void OnTextFieldDidChange(const FormData
& form
,
157 const FormFieldData
& field
,
158 const base::TimeTicks
& timestamp
);
160 // The |bounding_box| is a window relative value.
161 void OnQueryFormFieldAutofill(int query_id
,
162 const FormData
& form
,
163 const FormFieldData
& field
,
164 const gfx::RectF
& bounding_box
,
165 bool display_warning
);
166 void OnDidEndTextFieldEditing();
168 void OnSetDataList(const std::vector
<base::string16
>& values
,
169 const std::vector
<base::string16
>& labels
);
171 // Try to label password fields and upload |form|. This differs from
172 // OnFormSubmitted() in a few ways.
173 // - This function will only label the first <input type="password"> field
174 // as |password_type|. Other fields will stay unlabeled, as they
175 // should have been labeled during the upload for OnFormSubmitted().
176 // - This function does not assume that |form| is being uploaded during
177 // the same browsing session as it was originally submitted (as we may
178 // not have the necessary information to classify the form at that time)
179 // so it bypasses the cache and doesn't log the same quality UMA metrics.
180 virtual bool UploadPasswordForm(const FormData
& form
,
181 const ServerFieldType
& pasword_type
);
184 virtual void Reset();
186 // Returns the value of the AutofillEnabled pref.
187 virtual bool IsAutofillEnabled() const;
190 // Test code should prefer to use this constructor.
191 AutofillManager(AutofillDriver
* driver
,
192 AutofillClient
* client
,
193 PersonalDataManager
* personal_data
);
195 // Uploads the form data to the Autofill server.
196 virtual void UploadFormData(const FormStructure
& submitted_form
);
198 // Logs quality metrics for the |submitted_form| and uploads the form data
199 // to the crowdsourcing server, if appropriate.
200 virtual void UploadFormDataAsyncCallback(
201 const FormStructure
* submitted_form
,
202 const base::TimeTicks
& load_time
,
203 const base::TimeTicks
& interaction_time
,
204 const base::TimeTicks
& submission_time
);
206 // Maps SuggestionBackendID to and from an integer identifying it. Two of
207 // these intermediate integers are packed by MakeFrontendID to make the IDs
208 // that this class generates for the UI and for IPC.
209 virtual int BackendIDToInt(const SuggestionBackendID
& backend_id
) const;
210 virtual SuggestionBackendID
IntToBackendID(int int_id
) const;
212 // Methods for packing and unpacking credit card and profile IDs for sending
213 // and receiving to and from the renderer process.
214 int MakeFrontendID(const SuggestionBackendID
& cc_backend_id
,
215 const SuggestionBackendID
& profile_backend_id
) const;
216 void SplitFrontendID(int frontend_id
,
217 SuggestionBackendID
* cc_backend_id
,
218 SuggestionBackendID
* profile_backend_id
) const;
220 ScopedVector
<FormStructure
>* form_structures() { return &form_structures_
; }
222 // Exposed for testing.
223 AutofillExternalDelegate
* external_delegate() {
224 return external_delegate_
;
228 // AutofillDownloadManager::Observer:
229 void OnLoadedServerPredictions(const std::string
& response_xml
) override
;
231 // CardUnmaskDelegate:
232 void OnUnmaskResponse(const base::string16
& cvc
,
233 const base::string16
& exp_month
,
234 const base::string16
& exp_year
) override
;
235 void OnUnmaskPromptClosed() override
;
237 // wallet::RealPanWalletClient::Delegate:
238 IdentityProvider
* GetIdentityProvider() override
;
239 void OnDidGetRealPan(const std::string
& real_pan
) override
;
241 // Returns false if Autofill is disabled or if no Autofill data is available.
242 bool RefreshDataModels() const;
244 // Unpacks |unique_id| and fills |form_group| and |variant| with the
245 // appropriate data source and variant index. Sets |is_credit_card| to true
246 // if |data_model| points to a CreditCard data model, false if it's a
247 // profile data model.
248 // Returns false if the unpacked id cannot be found.
249 bool GetProfileOrCreditCard(int unique_id
,
250 const AutofillDataModel
** data_model
,
252 bool* is_credit_card
) const WARN_UNUSED_RESULT
;
254 // Fills or previews |data_model| in the |form|.
255 void FillOrPreviewDataModelForm(AutofillDriver::RendererFormDataAction action
,
257 const FormData
& form
,
258 const FormFieldData
& field
,
259 const AutofillDataModel
* data_model
,
261 bool is_credit_card
);
263 // Fills |form_structure| cached element corresponding to |form|.
264 // Returns false if the cached element was not found.
265 bool FindCachedForm(const FormData
& form
,
266 FormStructure
** form_structure
) const WARN_UNUSED_RESULT
;
268 // Fills |form_structure| and |autofill_field| with the cached elements
269 // corresponding to |form| and |field|. This might have the side-effect of
270 // updating the cache. Returns false if the |form| is not autofillable, or if
271 // it is not already present in the cache and the cache is full.
272 bool GetCachedFormAndField(const FormData
& form
,
273 const FormFieldData
& field
,
274 FormStructure
** form_structure
,
275 AutofillField
** autofill_field
) WARN_UNUSED_RESULT
;
277 // Returns the field corresponding to |form| and |field| that can be
278 // autofilled. Returns NULL if the field cannot be autofilled.
279 AutofillField
* GetAutofillField(const FormData
& form
,
280 const FormFieldData
& field
)
283 // Re-parses |live_form| and adds the result to |form_structures_|.
284 // |cached_form| should be a pointer to the existing version of the form, or
285 // NULL if no cached version exists. The updated form is then written into
286 // |updated_form|. Returns false if the cache could not be updated.
287 bool UpdateCachedForm(const FormData
& live_form
,
288 const FormStructure
* cached_form
,
289 FormStructure
** updated_form
) WARN_UNUSED_RESULT
;
291 // Returns a list of values from the stored profiles that match |type| and the
292 // value of |field| and returns the labels of the matching profiles. |labels|
293 // is filled with the Profile label.
294 std::vector
<Suggestion
> GetProfileSuggestions(
295 const FormStructure
& form
,
296 const FormFieldData
& field
,
297 const AutofillField
& autofill_field
) const;
299 // Returns a list of values from the stored credit cards that match |type| and
300 // the value of |field| and returns the labels of the matching credit cards.
301 std::vector
<Suggestion
> GetCreditCardSuggestions(
302 const FormFieldData
& field
,
303 const AutofillType
& type
) const;
305 // Parses the forms using heuristic matching and querying the Autofill server.
306 void ParseForms(const std::vector
<FormData
>& forms
);
308 // Imports the form data, submitted by the user, into |personal_data_|.
309 void ImportFormData(const FormStructure
& submitted_form
);
311 // If |initial_interaction_timestamp_| is unset or is set to a later time than
312 // |interaction_timestamp|, updates the cached timestamp. The latter check is
313 // needed because IPC messages can arrive out of order.
314 void UpdateInitialInteractionTimestamp(
315 const base::TimeTicks
& interaction_timestamp
);
317 // Shared code to determine if |form| should be uploaded.
318 bool ShouldUploadForm(const FormStructure
& form
);
320 // Provides driver-level context to the shared code of the component. Must
321 // outlive this object.
322 AutofillDriver
* driver_
;
324 AutofillClient
* const client_
;
326 // Handles real PAN requests.
327 wallet::RealPanWalletClient real_pan_client_
;
329 std::string app_locale_
;
331 // The personal data manager, used to save and load personal data to/from the
332 // web database. This is overridden by the AutofillManagerTest.
334 // May be NULL. NULL indicates OTR.
335 PersonalDataManager
* personal_data_
;
337 std::list
<std::string
> autofilled_form_signatures_
;
339 // Handles queries and uploads to Autofill servers. Will be NULL if
340 // the download manager functionality is disabled.
341 scoped_ptr
<AutofillDownloadManager
> download_manager_
;
343 // Handles single-field autocomplete form data.
344 scoped_ptr
<AutocompleteHistoryManager
> autocomplete_history_manager_
;
346 // Have we logged whether Autofill is enabled for this page load?
347 bool has_logged_autofill_enabled_
;
348 // Have we logged an address suggestions count metric for this page?
349 bool has_logged_address_suggestions_count_
;
350 // Have we shown Autofill suggestions at least once?
351 bool did_show_suggestions_
;
352 // Has the user manually edited at least one form field among the autofillable
355 // Has the user autofilled a form on this page?
356 bool user_did_autofill_
;
357 // Has the user edited a field that was previously autofilled?
358 bool user_did_edit_autofilled_field_
;
359 // When the form finished loading.
360 std::map
<FormData
, base::TimeTicks
> forms_loaded_timestamps_
;
361 // When the user first interacted with a potentially fillable form on this
363 base::TimeTicks initial_interaction_timestamp_
;
365 // Our copy of the form data.
366 ScopedVector
<FormStructure
> form_structures_
;
368 // A copy of the credit card that's currently being unmasked, and data about
370 CreditCard unmasking_card_
;
371 // CVC is not part of CreditCard, so store it separately.
372 base::string16 unmasking_cvc_
;
373 int unmasking_query_id_
;
374 FormData unmasking_form_
;
375 FormFieldData unmasking_field_
;
377 // SuggestionBackendID to ID mapping. We keep two maps to convert back and
378 // forth. These should be used only by BackendIDToInt and IntToBackendID.
379 // Note that the integers are not frontend IDs.
380 mutable std::map
<SuggestionBackendID
, int> backend_to_int_map_
;
381 mutable std::map
<int, SuggestionBackendID
> int_to_backend_map_
;
383 // Delegate to perform external processing (display, selection) on
385 AutofillExternalDelegate
* external_delegate_
;
387 // Delegate used in test to get notifications on certain events.
388 AutofillManagerTestDelegate
* test_delegate_
;
390 base::WeakPtrFactory
<AutofillManager
> weak_ptr_factory_
;
392 friend class AutofillManagerTest
;
393 friend class FormStructureBrowserTest
;
394 FRIEND_TEST_ALL_PREFIXES(AutofillManagerTest
,
395 DeterminePossibleFieldTypesForUpload
);
396 FRIEND_TEST_ALL_PREFIXES(AutofillManagerTest
,
397 DeterminePossibleFieldTypesForUploadStressTest
);
398 FRIEND_TEST_ALL_PREFIXES(AutofillManagerTest
,
399 DisabledAutofillDispatchesError
);
400 FRIEND_TEST_ALL_PREFIXES(AutofillMetricsTest
, AddressSuggestionsCount
);
401 FRIEND_TEST_ALL_PREFIXES(AutofillMetricsTest
, AutofillIsEnabledAtPageLoad
);
402 FRIEND_TEST_ALL_PREFIXES(AutofillMetricsTest
, DeveloperEngagement
);
403 FRIEND_TEST_ALL_PREFIXES(AutofillMetricsTest
, FormFillDuration
);
404 FRIEND_TEST_ALL_PREFIXES(AutofillMetricsTest
,
405 NoQualityMetricsForNonAutofillableForms
);
406 FRIEND_TEST_ALL_PREFIXES(AutofillMetricsTest
, QualityMetrics
);
407 FRIEND_TEST_ALL_PREFIXES(AutofillMetricsTest
, QualityMetricsForFailure
);
408 FRIEND_TEST_ALL_PREFIXES(AutofillMetricsTest
, QualityMetricsWithExperimentId
);
409 FRIEND_TEST_ALL_PREFIXES(AutofillMetricsTest
, SaneMetricsWithCacheMismatch
);
410 FRIEND_TEST_ALL_PREFIXES(AutofillManagerTest
, TestExternalDelegate
);
411 FRIEND_TEST_ALL_PREFIXES(AutofillManagerTest
,
412 TestTabContentsWithExternalDelegate
);
413 FRIEND_TEST_ALL_PREFIXES(AutofillMetricsTest
,
414 UserHappinessFormLoadAndSubmission
);
415 FRIEND_TEST_ALL_PREFIXES(AutofillMetricsTest
, UserHappinessFormInteraction
);
416 FRIEND_TEST_ALL_PREFIXES(AutofillManagerTest
,
417 FormSubmittedAutocompleteEnabled
);
418 FRIEND_TEST_ALL_PREFIXES(AutofillManagerTest
,
419 AutocompleteOffRespected
);
420 FRIEND_TEST_ALL_PREFIXES(AutofillManagerTest
,
421 AutocompleteOffRespectedWithFlag
);
422 DISALLOW_COPY_AND_ASSIGN(AutofillManager
);
425 } // namespace autofill
427 #endif // COMPONENTS_AUTOFILL_CORE_BROWSER_AUTOFILL_MANAGER_H_