autofill_manager.h revision 46d4c2bc3267f3f028f39e7e311b0f89aba2e4fd
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.
4
5#ifndef COMPONENTS_AUTOFILL_CORE_BROWSER_AUTOFILL_MANAGER_H_
6#define COMPONENTS_AUTOFILL_CORE_BROWSER_AUTOFILL_MANAGER_H_
7
8#include <list>
9#include <map>
10#include <string>
11#include <vector>
12
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_download.h"
24#include "components/autofill/core/browser/autofill_driver.h"
25#include "components/autofill/core/browser/autofill_manager_delegate.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"
29
30class GURL;
31
32namespace content {
33class RenderViewHost;
34class 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#if defined(OS_MACOSX) && !defined(OS_IOS)
77  static void MigrateUserPrefs(PrefService* prefs);
78#endif  // defined(OS_MACOSX) && !defined(OS_IOS)
79
80  AutofillManager(AutofillDriver* driver,
81                  autofill::AutofillManagerDelegate* delegate,
82                  const std::string& app_locale,
83                  AutofillDownloadManagerState enable_download_manager);
84  virtual ~AutofillManager();
85
86  // Sets an external delegate.
87  void SetExternalDelegate(AutofillExternalDelegate* delegate);
88
89  void ShowAutofillSettings();
90
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);
96
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)
103
104  // Called from our external delegate so they cannot be private.
105  virtual void FillOrPreviewForm(AutofillDriver::RendererFormDataAction action,
106                                 int query_id,
107                                 const FormData& form,
108                                 const FormFieldData& field,
109                                 int unique_id);
110  void DidShowSuggestions(bool is_new_popup);
111  void OnDidFillAutofillFormData(const base::TimeTicks& timestamp);
112  void OnDidPreviewAutofillFormData();
113
114  // Remove the credit card or Autofill profile that matches |unique_id|
115  // from the database.
116  void RemoveAutofillProfileOrCreditCard(int unique_id);
117
118  // Remove the specified Autocomplete entry.
119  void RemoveAutocompleteEntry(const base::string16& name,
120                               const base::string16& value);
121
122  // Returns the present form structures seen by Autofill manager.
123  const std::vector<FormStructure*>& GetFormStructures();
124
125  // Happens when the autocomplete dialog runs its callback when being closed.
126  void RequestAutocompleteDialogClosed();
127
128  autofill::AutofillManagerDelegate* delegate() const {
129    return manager_delegate_;
130  }
131
132  const std::string& app_locale() const { return app_locale_; }
133
134  // Only for testing.
135  void SetTestDelegate(autofill::AutofillManagerTestDelegate* delegate);
136
137  void OnFormsSeen(const std::vector<FormData>& forms,
138                   const base::TimeTicks& timestamp);
139
140  // Processes the submitted |form|, saving any new Autofill data and uploading
141  // the possible field types for the submitted fields to the crowdsourcing
142  // server.  Returns false if this form is not relevant for Autofill.
143  bool OnFormSubmitted(const FormData& form,
144                       const base::TimeTicks& timestamp);
145
146  void OnTextFieldDidChange(const FormData& form,
147                            const FormFieldData& field,
148                            const base::TimeTicks& timestamp);
149
150  // The |bounding_box| is a window relative value.
151  void OnQueryFormFieldAutofill(int query_id,
152                                const FormData& form,
153                                const FormFieldData& field,
154                                const gfx::RectF& bounding_box,
155                                bool display_warning);
156  void OnDidEndTextFieldEditing();
157  void OnHidePopup();
158  void OnSetDataList(const std::vector<base::string16>& values,
159                     const std::vector<base::string16>& labels);
160
161  // Try and upload |form|. This differs from OnFormSubmitted() in a few ways.
162  //   - This function will only label the first <input type="password"> field
163  //     as ACCOUNT_CREATION_PASSWORD. Other fields will stay unlabeled, as they
164  //     should have been labeled during the upload for OnFormSubmitted().
165  //   - This function does not assume that |form| is being uploaded during
166  //     the same browsing session as it was originally submitted (as we may
167  //     not have the necessary information to classify the form at that time)
168  //     so it bypasses the cache and doesn't log the same quality UMA metrics.
169  bool UploadPasswordGenerationForm(const FormData& form);
170
171  // Resets cache.
172  virtual void Reset();
173
174  // Returns the value of the AutofillEnabled pref.
175  virtual bool IsAutofillEnabled() const;
176
177 protected:
178  // Test code should prefer to use this constructor.
179  AutofillManager(AutofillDriver* driver,
180                  autofill::AutofillManagerDelegate* delegate,
181                  PersonalDataManager* personal_data);
182
183  // Uploads the form data to the Autofill server.
184  virtual void UploadFormData(const FormStructure& submitted_form);
185
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);
193
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;
198
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;
206
207  const AutofillMetrics* metric_logger() const { return metric_logger_.get(); }
208  void set_metric_logger(const AutofillMetrics* metric_logger);
209
210  ScopedVector<FormStructure>* form_structures() { return &form_structures_; }
211
212  // Exposed for testing.
213  AutofillExternalDelegate* external_delegate() {
214    return external_delegate_;
215  }
216
217 private:
218  // AutofillDownloadManager::Observer:
219  virtual void OnLoadedServerPredictions(
220      const std::string& response_xml) OVERRIDE;
221
222  // Returns false if Autofill is disabled or if no Autofill data is available.
223  bool RefreshDataModels() const;
224
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,
232                              size_t* variant,
233                              bool* is_credit_card) const WARN_UNUSED_RESULT;
234
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;
239
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;
248
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;
256
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;
267
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;
276
277  // Parses the forms using heuristic matching and querying the Autofill server.
278  void ParseForms(const std::vector<FormData>& forms);
279
280  // Imports the form data, submitted by the user, into |personal_data_|.
281  void ImportFormData(const FormStructure& submitted_form);
282
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);
288
289  // Shared code to determine if |form| should be uploaded.
290  bool ShouldUploadForm(const FormStructure& form);
291
292  // Provides driver-level context to the shared code of the component. Must
293  // outlive this object.
294  AutofillDriver* driver_;
295
296  autofill::AutofillManagerDelegate* const manager_delegate_;
297
298  std::string app_locale_;
299
300  // The personal data manager, used to save and load personal data to/from the
301  // web database.  This is overridden by the AutofillManagerTest.
302  // Weak reference.
303  // May be NULL.  NULL indicates OTR.
304  PersonalDataManager* personal_data_;
305
306  std::list<std::string> autofilled_form_signatures_;
307
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_;
311
312  // Handles single-field autocomplete form data.
313  scoped_ptr<AutocompleteHistoryManager> autocomplete_history_manager_;
314
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
324  // ones?
325  bool user_did_type_;
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
333  // page.
334  base::TimeTicks initial_interaction_timestamp_;
335
336  // Our copy of the form data.
337  ScopedVector<FormStructure> form_structures_;
338
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_;
342
343  // Delegate to perform external processing (display, selection) on
344  // our behalf.  Weak.
345  AutofillExternalDelegate* external_delegate_;
346
347  // Delegate used in test to get notifications on certain events.
348  autofill::AutofillManagerTestDelegate* test_delegate_;
349
350  base::WeakPtrFactory<AutofillManager> weak_ptr_factory_;
351
352  friend class AutofillManagerTest;
353  friend class autofill::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);
379};
380
381}  // namespace autofill
382
383#endif  // COMPONENTS_AUTOFILL_CORE_BROWSER_AUTOFILL_MANAGER_H_
384