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/form_structure.h"
27 #include "components/autofill/core/browser/personal_data_manager.h"
28 #include "components/autofill/core/common/form_data.h"
42 namespace user_prefs {
43 class PrefRegistrySyncable;
48 class AutofillDataModel;
49 class AutofillDownloadManager;
50 class AutofillExternalDelegate;
53 class AutofillManagerTestDelegate;
54 class AutofillMetrics;
55 class AutofillProfile;
58 class FormStructureBrowserTest;
62 struct PasswordFormFillData;
64 // Manages saving and restoring the user's personal information entered into web
66 class AutofillManager : public AutofillDownloadManager::Observer {
68 enum AutofillDownloadManagerState {
69 ENABLE_AUTOFILL_DOWNLOAD_MANAGER,
70 DISABLE_AUTOFILL_DOWNLOAD_MANAGER,
73 // Registers our Enable/Disable Autofill pref.
74 static void RegisterProfilePrefs(user_prefs::PrefRegistrySyncable* registry);
76 #if defined(OS_MACOSX) && !defined(OS_IOS)
77 static void MigrateUserPrefs(PrefService* prefs);
78 #endif // defined(OS_MACOSX) && !defined(OS_IOS)
80 AutofillManager(AutofillDriver* driver,
81 AutofillClient* client,
82 const std::string& app_locale,
83 AutofillDownloadManagerState enable_download_manager);
84 virtual ~AutofillManager();
86 // Sets an external delegate.
87 void SetExternalDelegate(AutofillExternalDelegate* delegate);
89 void ShowAutofillSettings();
91 #if defined(OS_MACOSX) && !defined(OS_IOS)
92 // Whether the field represented by |fieldData| should show an entry to prompt
93 // the user to give Chrome access to the user's address book.
94 bool ShouldShowAccessAddressBookSuggestion(const FormData& data,
95 const FormFieldData& field_data);
97 // If Chrome has not prompted for access to the user's address book, the
98 // method prompts the user for permission and blocks the process. Otherwise,
99 // this method has no effect. The return value reflects whether the user was
100 // prompted with a modal dialog.
101 bool AccessAddressBook();
102 #endif // defined(OS_MACOSX) && !defined(OS_IOS)
104 // Called from our external delegate so they cannot be private.
105 virtual void FillOrPreviewForm(AutofillDriver::RendererFormDataAction action,
107 const FormData& form,
108 const FormFieldData& field,
110 void DidShowSuggestions(bool is_new_popup);
111 void OnDidFillAutofillFormData(const base::TimeTicks& timestamp);
112 void OnDidPreviewAutofillFormData();
114 // Remove the credit card or Autofill profile that matches |unique_id|
115 // from the database.
116 void RemoveAutofillProfileOrCreditCard(int unique_id);
118 // Remove the specified Autocomplete entry.
119 void RemoveAutocompleteEntry(const base::string16& name,
120 const base::string16& value);
122 // Returns the present form structures seen by Autofill manager.
123 const std::vector<FormStructure*>& GetFormStructures();
125 // Happens when the autocomplete dialog runs its callback when being closed.
126 void RequestAutocompleteDialogClosed();
128 AutofillClient* client() const { return client_; }
130 const std::string& app_locale() const { return app_locale_; }
133 void SetTestDelegate(AutofillManagerTestDelegate* delegate);
135 void OnFormsSeen(const std::vector<FormData>& forms,
136 const base::TimeTicks& timestamp);
138 // Processes the submitted |form|, saving any new Autofill data and uploading
139 // the possible field types for the submitted fields to the crowdsourcing
140 // server. Returns false if this form is not relevant for Autofill.
141 bool OnFormSubmitted(const FormData& form,
142 const base::TimeTicks& timestamp);
144 void OnTextFieldDidChange(const FormData& form,
145 const FormFieldData& field,
146 const base::TimeTicks& timestamp);
148 // The |bounding_box| is a window relative value.
149 void OnQueryFormFieldAutofill(int query_id,
150 const FormData& form,
151 const FormFieldData& field,
152 const gfx::RectF& bounding_box,
153 bool display_warning);
154 void OnDidEndTextFieldEditing();
156 void OnSetDataList(const std::vector<base::string16>& values,
157 const std::vector<base::string16>& labels);
159 // Try to label password fields and upload |form|. This differs from
160 // OnFormSubmitted() in a few ways.
161 // - This function will only label the first <input type="password"> field
162 // as |password_type|. Other fields will stay unlabeled, as they
163 // should have been labeled during the upload for OnFormSubmitted().
164 // - This function does not assume that |form| is being uploaded during
165 // the same browsing session as it was originally submitted (as we may
166 // not have the necessary information to classify the form at that time)
167 // so it bypasses the cache and doesn't log the same quality UMA metrics.
168 bool UploadPasswordForm(const FormData& form,
169 const ServerFieldType& pasword_type);
172 virtual void Reset();
174 // Returns the value of the AutofillEnabled pref.
175 virtual bool IsAutofillEnabled() const;
178 // Test code should prefer to use this constructor.
179 AutofillManager(AutofillDriver* driver,
180 AutofillClient* client,
181 PersonalDataManager* personal_data);
183 // Uploads the form data to the Autofill server.
184 virtual void UploadFormData(const FormStructure& submitted_form);
186 // Logs quality metrics for the |submitted_form| and uploads the form data
187 // to the crowdsourcing server, if appropriate.
188 virtual void UploadFormDataAsyncCallback(
189 const FormStructure* submitted_form,
190 const base::TimeTicks& load_time,
191 const base::TimeTicks& interaction_time,
192 const base::TimeTicks& submission_time);
194 // Maps GUIDs to and from IDs that are used to identify profiles and credit
195 // cards sent to and from the renderer process.
196 virtual int GUIDToID(const PersonalDataManager::GUIDPair& guid) const;
197 virtual const PersonalDataManager::GUIDPair IDToGUID(int id) const;
199 // Methods for packing and unpacking credit card and profile IDs for sending
200 // and receiving to and from the renderer process.
201 int PackGUIDs(const PersonalDataManager::GUIDPair& cc_guid,
202 const PersonalDataManager::GUIDPair& profile_guid) const;
203 void UnpackGUIDs(int id,
204 PersonalDataManager::GUIDPair* cc_guid,
205 PersonalDataManager::GUIDPair* profile_guid) const;
207 const AutofillMetrics* metric_logger() const { return metric_logger_.get(); }
208 void set_metric_logger(const AutofillMetrics* metric_logger);
210 ScopedVector<FormStructure>* form_structures() { return &form_structures_; }
212 // Exposed for testing.
213 AutofillExternalDelegate* external_delegate() {
214 return external_delegate_;
218 // AutofillDownloadManager::Observer:
219 virtual void OnLoadedServerPredictions(
220 const std::string& response_xml) OVERRIDE;
222 // Returns false if Autofill is disabled or if no Autofill data is available.
223 bool RefreshDataModels() const;
225 // Unpacks |unique_id| and fills |form_group| and |variant| with the
226 // appropriate data source and variant index. Sets |is_credit_card| to true
227 // if |data_model| points to a CreditCard data model, false if it's a
228 // profile data model.
229 // Returns false if the unpacked id cannot be found.
230 bool GetProfileOrCreditCard(int unique_id,
231 const AutofillDataModel** data_model,
233 bool* is_credit_card) const WARN_UNUSED_RESULT;
235 // Fills |form_structure| cached element corresponding to |form|.
236 // Returns false if the cached element was not found.
237 bool FindCachedForm(const FormData& form,
238 FormStructure** form_structure) const WARN_UNUSED_RESULT;
240 // Fills |form_structure| and |autofill_field| with the cached elements
241 // corresponding to |form| and |field|. This might have the side-effect of
242 // updating the cache. Returns false if the |form| is not autofillable, or if
243 // it is not already present in the cache and the cache is full.
244 bool GetCachedFormAndField(const FormData& form,
245 const FormFieldData& field,
246 FormStructure** form_structure,
247 AutofillField** autofill_field) WARN_UNUSED_RESULT;
249 // Re-parses |live_form| and adds the result to |form_structures_|.
250 // |cached_form| should be a pointer to the existing version of the form, or
251 // NULL if no cached version exists. The updated form is then written into
252 // |updated_form|. Returns false if the cache could not be updated.
253 bool UpdateCachedForm(const FormData& live_form,
254 const FormStructure* cached_form,
255 FormStructure** updated_form) WARN_UNUSED_RESULT;
257 // Returns a list of values from the stored profiles that match |type| and the
258 // value of |field| and returns the labels of the matching profiles. |labels|
259 // is filled with the Profile label.
260 void GetProfileSuggestions(FormStructure* form,
261 const FormFieldData& field,
262 const AutofillType& type,
263 std::vector<base::string16>* values,
264 std::vector<base::string16>* labels,
265 std::vector<base::string16>* icons,
266 std::vector<int>* unique_ids) const;
268 // Returns a list of values from the stored credit cards that match |type| and
269 // the value of |field| and returns the labels of the matching credit cards.
270 void GetCreditCardSuggestions(const FormFieldData& field,
271 const AutofillType& type,
272 std::vector<base::string16>* values,
273 std::vector<base::string16>* labels,
274 std::vector<base::string16>* icons,
275 std::vector<int>* unique_ids) const;
277 // Parses the forms using heuristic matching and querying the Autofill server.
278 void ParseForms(const std::vector<FormData>& forms);
280 // Imports the form data, submitted by the user, into |personal_data_|.
281 void ImportFormData(const FormStructure& submitted_form);
283 // If |initial_interaction_timestamp_| is unset or is set to a later time than
284 // |interaction_timestamp|, updates the cached timestamp. The latter check is
285 // needed because IPC messages can arrive out of order.
286 void UpdateInitialInteractionTimestamp(
287 const base::TimeTicks& interaction_timestamp);
289 // Shared code to determine if |form| should be uploaded.
290 bool ShouldUploadForm(const FormStructure& form);
292 // Provides driver-level context to the shared code of the component. Must
293 // outlive this object.
294 AutofillDriver* driver_;
296 AutofillClient* const client_;
298 std::string app_locale_;
300 // The personal data manager, used to save and load personal data to/from the
301 // web database. This is overridden by the AutofillManagerTest.
303 // May be NULL. NULL indicates OTR.
304 PersonalDataManager* personal_data_;
306 std::list<std::string> autofilled_form_signatures_;
308 // Handles queries and uploads to Autofill servers. Will be NULL if
309 // the download manager functionality is disabled.
310 scoped_ptr<AutofillDownloadManager> download_manager_;
312 // Handles single-field autocomplete form data.
313 scoped_ptr<AutocompleteHistoryManager> autocomplete_history_manager_;
315 // For logging UMA metrics. Overridden by metrics tests.
316 scoped_ptr<const AutofillMetrics> metric_logger_;
317 // Have we logged whether Autofill is enabled for this page load?
318 bool has_logged_autofill_enabled_;
319 // Have we logged an address suggestions count metric for this page?
320 bool has_logged_address_suggestions_count_;
321 // Have we shown Autofill suggestions at least once?
322 bool did_show_suggestions_;
323 // Has the user manually edited at least one form field among the autofillable
326 // Has the user autofilled a form on this page?
327 bool user_did_autofill_;
328 // Has the user edited a field that was previously autofilled?
329 bool user_did_edit_autofilled_field_;
330 // When the form finished loading.
331 std::map<FormData, base::TimeTicks> forms_loaded_timestamps_;
332 // When the user first interacted with a potentially fillable form on this
334 base::TimeTicks initial_interaction_timestamp_;
336 // Our copy of the form data.
337 ScopedVector<FormStructure> form_structures_;
339 // GUID to ID mapping. We keep two maps to convert back and forth.
340 mutable std::map<PersonalDataManager::GUIDPair, int> guid_id_map_;
341 mutable std::map<int, PersonalDataManager::GUIDPair> id_guid_map_;
343 // Delegate to perform external processing (display, selection) on
345 AutofillExternalDelegate* external_delegate_;
347 // Delegate used in test to get notifications on certain events.
348 AutofillManagerTestDelegate* test_delegate_;
350 base::WeakPtrFactory<AutofillManager> weak_ptr_factory_;
352 friend class AutofillManagerTest;
353 friend class FormStructureBrowserTest;
354 FRIEND_TEST_ALL_PREFIXES(AutofillManagerTest,
355 DeterminePossibleFieldTypesForUpload);
356 FRIEND_TEST_ALL_PREFIXES(AutofillManagerTest,
357 DeterminePossibleFieldTypesForUploadStressTest);
358 FRIEND_TEST_ALL_PREFIXES(AutofillManagerTest,
359 DisabledAutofillDispatchesError);
360 FRIEND_TEST_ALL_PREFIXES(AutofillMetricsTest, AddressSuggestionsCount);
361 FRIEND_TEST_ALL_PREFIXES(AutofillMetricsTest, AutofillIsEnabledAtPageLoad);
362 FRIEND_TEST_ALL_PREFIXES(AutofillMetricsTest, DeveloperEngagement);
363 FRIEND_TEST_ALL_PREFIXES(AutofillMetricsTest, FormFillDuration);
364 FRIEND_TEST_ALL_PREFIXES(AutofillMetricsTest,
365 NoQualityMetricsForNonAutofillableForms);
366 FRIEND_TEST_ALL_PREFIXES(AutofillMetricsTest, QualityMetrics);
367 FRIEND_TEST_ALL_PREFIXES(AutofillMetricsTest, QualityMetricsForFailure);
368 FRIEND_TEST_ALL_PREFIXES(AutofillMetricsTest, QualityMetricsWithExperimentId);
369 FRIEND_TEST_ALL_PREFIXES(AutofillMetricsTest, SaneMetricsWithCacheMismatch);
370 FRIEND_TEST_ALL_PREFIXES(AutofillManagerTest, TestExternalDelegate);
371 FRIEND_TEST_ALL_PREFIXES(AutofillManagerTest,
372 TestTabContentsWithExternalDelegate);
373 FRIEND_TEST_ALL_PREFIXES(AutofillMetricsTest,
374 UserHappinessFormLoadAndSubmission);
375 FRIEND_TEST_ALL_PREFIXES(AutofillMetricsTest, UserHappinessFormInteraction);
376 FRIEND_TEST_ALL_PREFIXES(AutofillManagerTest,
377 FormSubmittedAutocompleteEnabled);
378 DISALLOW_COPY_AND_ASSIGN(AutofillManager);
381 } // namespace autofill
383 #endif // COMPONENTS_AUTOFILL_CORE_BROWSER_AUTOFILL_MANAGER_H_