autofill_manager.h revision cedac228d2dd51db4b79ea1e72c7f249408ee061
15821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)// Copyright 2013 The Chromium Authors. All rights reserved.
25821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)// Use of this source code is governed by a BSD-style license that can be
35821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)// found in the LICENSE file.
45821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
5c2e0dbddbe15c98d52c4786dac06cb8952a8ae6dTorne (Richard Coles)#ifndef COMPONENTS_AUTOFILL_CORE_BROWSER_AUTOFILL_MANAGER_H_
65821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#define COMPONENTS_AUTOFILL_CORE_BROWSER_AUTOFILL_MANAGER_H_
75821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
85821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include <list>
95821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include <map>
105821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include <string>
115821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include <vector>
125821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
135821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include "base/basictypes.h"
145821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include "base/callback_forward.h"
155821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include "base/compiler_specific.h"
165821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include "base/gtest_prod_util.h"
175821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include "base/memory/scoped_ptr.h"
185821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include "base/memory/scoped_vector.h"
195821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include "base/memory/weak_ptr.h"
205821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include "base/strings/string16.h"
215821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include "base/time/time.h"
225821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include "components/autofill/core/browser/autocomplete_history_manager.h"
235821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include "components/autofill/core/browser/autofill_download.h"
245821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include "components/autofill/core/browser/autofill_driver.h"
255821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include "components/autofill/core/browser/autofill_manager_delegate.h"
265821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include "components/autofill/core/browser/form_structure.h"
275821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include "components/autofill/core/browser/personal_data_manager.h"
285821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include "components/autofill/core/common/form_data.h"
295821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
305821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)class GURL;
315821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
325821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)namespace content {
335821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)class RenderViewHost;
345821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)class WebContents;
35}
36
37namespace gfx {
38class Rect;
39class RectF;
40}
41
42namespace user_prefs {
43class PrefRegistrySyncable;
44}
45
46namespace autofill {
47
48class AutofillDataModel;
49class AutofillDownloadManager;
50class AutofillExternalDelegate;
51class AutofillField;
52class AutofillManagerDelegate;
53class AutofillManagerTestDelegate;
54class AutofillMetrics;
55class AutofillProfile;
56class AutofillType;
57class CreditCard;
58class FormStructureBrowserTest;
59
60struct FormData;
61struct FormFieldData;
62struct PasswordFormFillData;
63
64// Manages saving and restoring the user's personal information entered into web
65// forms.
66class AutofillManager : public AutofillDownloadManager::Observer {
67 public:
68  enum AutofillDownloadManagerState {
69    ENABLE_AUTOFILL_DOWNLOAD_MANAGER,
70    DISABLE_AUTOFILL_DOWNLOAD_MANAGER,
71  };
72
73  // Registers our Enable/Disable Autofill pref.
74  static void RegisterProfilePrefs(user_prefs::PrefRegistrySyncable* registry);
75
76  AutofillManager(AutofillDriver* driver,
77                  autofill::AutofillManagerDelegate* delegate,
78                  const std::string& app_locale,
79                  AutofillDownloadManagerState enable_download_manager);
80  virtual ~AutofillManager();
81
82  // Sets an external delegate.
83  void SetExternalDelegate(AutofillExternalDelegate* delegate);
84
85  void ShowAutofillSettings();
86
87  // Called from our external delegate so they cannot be private.
88  virtual void FillOrPreviewForm(AutofillDriver::RendererFormDataAction action,
89                                 int query_id,
90                                 const FormData& form,
91                                 const FormFieldData& field,
92                                 int unique_id);
93  void DidShowSuggestions(bool is_new_popup);
94  void OnDidFillAutofillFormData(const base::TimeTicks& timestamp);
95  void OnDidPreviewAutofillFormData();
96
97  // Remove the credit card or Autofill profile that matches |unique_id|
98  // from the database.
99  void RemoveAutofillProfileOrCreditCard(int unique_id);
100
101  // Remove the specified Autocomplete entry.
102  void RemoveAutocompleteEntry(const base::string16& name,
103                               const base::string16& value);
104
105  // Returns the present form structures seen by Autofill manager.
106  const std::vector<FormStructure*>& GetFormStructures();
107
108  // Happens when the autocomplete dialog runs its callback when being closed.
109  void RequestAutocompleteDialogClosed();
110
111  autofill::AutofillManagerDelegate* delegate() const {
112    return manager_delegate_;
113  }
114
115  const std::string& app_locale() const { return app_locale_; }
116
117  // Only for testing.
118  void SetTestDelegate(autofill::AutofillManagerTestDelegate* delegate);
119
120  void OnFormsSeen(const std::vector<FormData>& forms,
121                   const base::TimeTicks& timestamp);
122
123  // Processes the submitted |form|, saving any new Autofill data and uploading
124  // the possible field types for the submitted fields to the crowdsourcing
125  // server.  Returns false if this form is not relevant for Autofill.
126  bool OnFormSubmitted(const FormData& form,
127                       const base::TimeTicks& timestamp);
128
129  void OnTextFieldDidChange(const FormData& form,
130                            const FormFieldData& field,
131                            const base::TimeTicks& timestamp);
132
133  // The |bounding_box| is a window relative value.
134  void OnQueryFormFieldAutofill(int query_id,
135                                const FormData& form,
136                                const FormFieldData& field,
137                                const gfx::RectF& bounding_box,
138                                bool display_warning);
139  void OnDidEndTextFieldEditing();
140  void OnHidePopup();
141  void OnSetDataList(const std::vector<base::string16>& values,
142                     const std::vector<base::string16>& labels);
143
144  // Try and upload |form|. This differs from OnFormSubmitted() in a few ways.
145  //   - This function will only label the first <input type="password"> field
146  //     as ACCOUNT_CREATION_PASSWORD. Other fields will stay unlabeled, as they
147  //     should have been labeled during the upload for OnFormSubmitted().
148  //   - This function does not assume that |form| is being uploaded during
149  //     the same browsing session as it was originally submitted (as we may
150  //     not have the necessary information to classify the form at that time)
151  //     so it bypasses the cache and doesn't log the same quality UMA metrics.
152  bool UploadPasswordGenerationForm(const FormData& form);
153
154  // Resets cache.
155  virtual void Reset();
156
157  // Returns the value of the AutofillEnabled pref.
158  virtual bool IsAutofillEnabled() const;
159
160 protected:
161  // Test code should prefer to use this constructor.
162  AutofillManager(AutofillDriver* driver,
163                  autofill::AutofillManagerDelegate* delegate,
164                  PersonalDataManager* personal_data);
165
166  // Uploads the form data to the Autofill server.
167  virtual void UploadFormData(const FormStructure& submitted_form);
168
169  // Logs quality metrics for the |submitted_form| and uploads the form data
170  // to the crowdsourcing server, if appropriate.
171  virtual void UploadFormDataAsyncCallback(
172      const FormStructure* submitted_form,
173      const base::TimeTicks& load_time,
174      const base::TimeTicks& interaction_time,
175      const base::TimeTicks& submission_time);
176
177  // Maps GUIDs to and from IDs that are used to identify profiles and credit
178  // cards sent to and from the renderer process.
179  virtual int GUIDToID(const PersonalDataManager::GUIDPair& guid) const;
180  virtual const PersonalDataManager::GUIDPair IDToGUID(int id) const;
181
182  // Methods for packing and unpacking credit card and profile IDs for sending
183  // and receiving to and from the renderer process.
184  int PackGUIDs(const PersonalDataManager::GUIDPair& cc_guid,
185                const PersonalDataManager::GUIDPair& profile_guid) const;
186  void UnpackGUIDs(int id,
187                   PersonalDataManager::GUIDPair* cc_guid,
188                   PersonalDataManager::GUIDPair* profile_guid) const;
189
190  const AutofillMetrics* metric_logger() const { return metric_logger_.get(); }
191  void set_metric_logger(const AutofillMetrics* metric_logger);
192
193  ScopedVector<FormStructure>* form_structures() { return &form_structures_; }
194
195  // Exposed for testing.
196  AutofillExternalDelegate* external_delegate() {
197    return external_delegate_;
198  }
199
200 private:
201  // AutofillDownloadManager::Observer:
202  virtual void OnLoadedServerPredictions(
203      const std::string& response_xml) OVERRIDE;
204
205  // Returns false if Autofill is disabled or if no Autofill data is available.
206  bool RefreshDataModels() const;
207
208  // Unpacks |unique_id| and fills |form_group| and |variant| with the
209  // appropriate data source and variant index. Sets |is_credit_card| to true
210  // if |data_model| points to a CreditCard data model, false if it's a
211  // profile data model.
212  // Returns false if the unpacked id cannot be found.
213  bool GetProfileOrCreditCard(int unique_id,
214                              const AutofillDataModel** data_model,
215                              size_t* variant,
216                              bool* is_credit_card) const WARN_UNUSED_RESULT;
217
218  // Fills |form_structure| cached element corresponding to |form|.
219  // Returns false if the cached element was not found.
220  bool FindCachedForm(const FormData& form,
221                      FormStructure** form_structure) const WARN_UNUSED_RESULT;
222
223  // Fills |form_structure| and |autofill_field| with the cached elements
224  // corresponding to |form| and |field|.  This might have the side-effect of
225  // updating the cache.  Returns false if the |form| is not autofillable, or if
226  // it is not already present in the cache and the cache is full.
227  bool GetCachedFormAndField(const FormData& form,
228                             const FormFieldData& field,
229                             FormStructure** form_structure,
230                             AutofillField** autofill_field) WARN_UNUSED_RESULT;
231
232  // Re-parses |live_form| and adds the result to |form_structures_|.
233  // |cached_form| should be a pointer to the existing version of the form, or
234  // NULL if no cached version exists.  The updated form is then written into
235  // |updated_form|.  Returns false if the cache could not be updated.
236  bool UpdateCachedForm(const FormData& live_form,
237                        const FormStructure* cached_form,
238                        FormStructure** updated_form) WARN_UNUSED_RESULT;
239
240  // Returns a list of values from the stored profiles that match |type| and the
241  // value of |field| and returns the labels of the matching profiles. |labels|
242  // is filled with the Profile label.
243  void GetProfileSuggestions(FormStructure* form,
244                             const FormFieldData& field,
245                             const AutofillType& type,
246                             std::vector<base::string16>* values,
247                             std::vector<base::string16>* labels,
248                             std::vector<base::string16>* icons,
249                             std::vector<int>* unique_ids) const;
250
251  // Returns a list of values from the stored credit cards that match |type| and
252  // the value of |field| and returns the labels of the matching credit cards.
253  void GetCreditCardSuggestions(const FormFieldData& field,
254                                const AutofillType& type,
255                                std::vector<base::string16>* values,
256                                std::vector<base::string16>* labels,
257                                std::vector<base::string16>* icons,
258                                std::vector<int>* unique_ids) const;
259
260  // Parses the forms using heuristic matching and querying the Autofill server.
261  void ParseForms(const std::vector<FormData>& forms);
262
263  // Imports the form data, submitted by the user, into |personal_data_|.
264  void ImportFormData(const FormStructure& submitted_form);
265
266  // If |initial_interaction_timestamp_| is unset or is set to a later time than
267  // |interaction_timestamp|, updates the cached timestamp.  The latter check is
268  // needed because IPC messages can arrive out of order.
269  void UpdateInitialInteractionTimestamp(
270      const base::TimeTicks& interaction_timestamp);
271
272  // Shared code to determine if |form| should be uploaded.
273  bool ShouldUploadForm(const FormStructure& form);
274
275  // Provides driver-level context to the shared code of the component. Must
276  // outlive this object.
277  AutofillDriver* driver_;
278
279  autofill::AutofillManagerDelegate* const manager_delegate_;
280
281  std::string app_locale_;
282
283  // The personal data manager, used to save and load personal data to/from the
284  // web database.  This is overridden by the AutofillManagerTest.
285  // Weak reference.
286  // May be NULL.  NULL indicates OTR.
287  PersonalDataManager* personal_data_;
288
289  std::list<std::string> autofilled_form_signatures_;
290
291  // Handles queries and uploads to Autofill servers. Will be NULL if
292  // the download manager functionality is disabled.
293  scoped_ptr<AutofillDownloadManager> download_manager_;
294
295  // Handles single-field autocomplete form data.
296  scoped_ptr<AutocompleteHistoryManager> autocomplete_history_manager_;
297
298  // For logging UMA metrics. Overridden by metrics tests.
299  scoped_ptr<const AutofillMetrics> metric_logger_;
300  // Have we logged whether Autofill is enabled for this page load?
301  bool has_logged_autofill_enabled_;
302  // Have we logged an address suggestions count metric for this page?
303  bool has_logged_address_suggestions_count_;
304  // Have we shown Autofill suggestions at least once?
305  bool did_show_suggestions_;
306  // Has the user manually edited at least one form field among the autofillable
307  // ones?
308  bool user_did_type_;
309  // Has the user autofilled a form on this page?
310  bool user_did_autofill_;
311  // Has the user edited a field that was previously autofilled?
312  bool user_did_edit_autofilled_field_;
313  // When the form finished loading.
314  std::map<FormData, base::TimeTicks> forms_loaded_timestamps_;
315  // When the user first interacted with a potentially fillable form on this
316  // page.
317  base::TimeTicks initial_interaction_timestamp_;
318
319  // Our copy of the form data.
320  ScopedVector<FormStructure> form_structures_;
321
322  // GUID to ID mapping.  We keep two maps to convert back and forth.
323  mutable std::map<PersonalDataManager::GUIDPair, int> guid_id_map_;
324  mutable std::map<int, PersonalDataManager::GUIDPair> id_guid_map_;
325
326  // Delegate to perform external processing (display, selection) on
327  // our behalf.  Weak.
328  AutofillExternalDelegate* external_delegate_;
329
330  // Delegate used in test to get notifications on certain events.
331  autofill::AutofillManagerTestDelegate* test_delegate_;
332
333  base::WeakPtrFactory<AutofillManager> weak_ptr_factory_;
334
335  friend class AutofillManagerTest;
336  friend class autofill::FormStructureBrowserTest;
337  FRIEND_TEST_ALL_PREFIXES(AutofillManagerTest,
338                           DeterminePossibleFieldTypesForUpload);
339  FRIEND_TEST_ALL_PREFIXES(AutofillManagerTest,
340                           DeterminePossibleFieldTypesForUploadStressTest);
341  FRIEND_TEST_ALL_PREFIXES(AutofillManagerTest,
342                           DisabledAutofillDispatchesError);
343  FRIEND_TEST_ALL_PREFIXES(AutofillMetricsTest, AddressSuggestionsCount);
344  FRIEND_TEST_ALL_PREFIXES(AutofillMetricsTest, AutofillIsEnabledAtPageLoad);
345  FRIEND_TEST_ALL_PREFIXES(AutofillMetricsTest, DeveloperEngagement);
346  FRIEND_TEST_ALL_PREFIXES(AutofillMetricsTest, FormFillDuration);
347  FRIEND_TEST_ALL_PREFIXES(AutofillMetricsTest,
348                           NoQualityMetricsForNonAutofillableForms);
349  FRIEND_TEST_ALL_PREFIXES(AutofillMetricsTest, QualityMetrics);
350  FRIEND_TEST_ALL_PREFIXES(AutofillMetricsTest, QualityMetricsForFailure);
351  FRIEND_TEST_ALL_PREFIXES(AutofillMetricsTest, QualityMetricsWithExperimentId);
352  FRIEND_TEST_ALL_PREFIXES(AutofillMetricsTest, SaneMetricsWithCacheMismatch);
353  FRIEND_TEST_ALL_PREFIXES(AutofillManagerTest, TestExternalDelegate);
354  FRIEND_TEST_ALL_PREFIXES(AutofillManagerTest,
355                           TestTabContentsWithExternalDelegate);
356  FRIEND_TEST_ALL_PREFIXES(AutofillMetricsTest,
357                           UserHappinessFormLoadAndSubmission);
358  FRIEND_TEST_ALL_PREFIXES(AutofillMetricsTest, UserHappinessFormInteraction);
359  FRIEND_TEST_ALL_PREFIXES(AutofillManagerTest,
360                           FormSubmittedAutocompleteEnabled);
361  DISALLOW_COPY_AND_ASSIGN(AutofillManager);
362};
363
364}  // namespace autofill
365
366#endif  // COMPONENTS_AUTOFILL_CORE_BROWSER_AUTOFILL_MANAGER_H_
367