autofill_manager.h revision 3240926e260ce088908e02ac07a6cf7b0c0cbf44
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/content/browser/autocheckout_manager.h"
23#include "components/autofill/core/browser/autocomplete_history_manager.h"
24#include "components/autofill/core/browser/autofill_download.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/autocheckout_status.h"
29#include "components/autofill/core/common/form_data.h"
30#include "components/autofill/core/common/forms_seen_state.h"
31#include "third_party/WebKit/public/web/WebFormElement.h"
32
33class GURL;
34
35namespace content {
36class RenderViewHost;
37class WebContents;
38}
39
40namespace gfx {
41class Rect;
42class RectF;
43}
44
45namespace user_prefs {
46class PrefRegistrySyncable;
47}
48
49namespace autofill {
50
51class AutofillDriver;
52class AutofillDataModel;
53class AutofillDownloadManager;
54class AutofillExternalDelegate;
55class AutofillField;
56class AutofillManagerDelegate;
57class AutofillManagerTestDelegate;
58class AutofillMetrics;
59class AutofillProfile;
60class AutofillType;
61class CreditCard;
62class FormStructureBrowserTest;
63
64struct FormData;
65struct FormFieldData;
66struct PasswordFormFillData;
67
68// Manages saving and restoring the user's personal information entered into web
69// forms.
70class AutofillManager : public AutofillDownloadManager::Observer {
71 public:
72  enum AutofillDownloadManagerState {
73    ENABLE_AUTOFILL_DOWNLOAD_MANAGER,
74    DISABLE_AUTOFILL_DOWNLOAD_MANAGER,
75  };
76
77  // Registers our Enable/Disable Autofill pref.
78  static void RegisterProfilePrefs(user_prefs::PrefRegistrySyncable* registry);
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  // Called from our external delegate so they cannot be private.
90  virtual void OnFillAutofillFormData(int query_id,
91                                      const FormData& form,
92                                      const FormFieldData& field,
93                                      int unique_id);
94  void OnDidShowAutofillSuggestions(bool is_new_popup);
95  void OnDidFillAutofillFormData(const base::TimeTicks& timestamp);
96  void OnShowAutofillDialog();
97  void OnDidPreviewAutofillFormData();
98
99  // Remove the credit card or Autofill profile that matches |unique_id|
100  // from the database.
101  void RemoveAutofillProfileOrCreditCard(int unique_id);
102
103  // Remove the specified Autocomplete entry.
104  void RemoveAutocompleteEntry(const base::string16& name,
105                               const base::string16& value);
106
107  // Returns the present web_contents state.
108  content::WebContents* GetWebContents() const;
109
110  // Returns the present form structures seen by Autofill manager.
111  const std::vector<FormStructure*>& GetFormStructures();
112
113  // Causes the dialog for request autocomplete feature to be shown.
114  virtual void ShowRequestAutocompleteDialog(
115      const FormData& form,
116      const GURL& source_url,
117      autofill::DialogType dialog_type,
118      const base::Callback<void(const FormStructure*,
119                                const std::string&)>& callback);
120
121  // Happens when the autocomplete dialog runs its callback when being closed.
122  void RequestAutocompleteDialogClosed();
123
124  autofill::AutofillManagerDelegate* delegate() const {
125    return manager_delegate_;
126  }
127
128  const std::string& app_locale() const { return app_locale_; }
129
130  // Only for testing.
131  void SetTestDelegate(autofill::AutofillManagerTestDelegate* delegate);
132
133  void OnFormsSeen(const std::vector<FormData>& forms,
134                   const base::TimeTicks& timestamp,
135                   autofill::FormsSeenState state);
136
137  // Processes the submitted |form|, saving any new Autofill data and uploading
138  // the possible field types for the submitted fields to the crowdsourcing
139  // server.  Returns false if this form is not relevant for Autofill.
140  bool OnFormSubmitted(const FormData& form,
141                       const base::TimeTicks& timestamp);
142
143  void OnTextFieldDidChange(const FormData& form,
144                            const FormFieldData& field,
145                            const base::TimeTicks& timestamp);
146
147  // The |bounding_box| is a window relative value.
148  void OnQueryFormFieldAutofill(int query_id,
149                                const FormData& form,
150                                const FormFieldData& field,
151                                const gfx::RectF& bounding_box,
152                                bool display_warning);
153  void OnDidEndTextFieldEditing();
154  void OnHideAutofillUI();
155  void OnAddPasswordFormMapping(
156      const FormFieldData& form,
157      const PasswordFormFillData& fill_data);
158  void OnShowPasswordSuggestions(
159      const FormFieldData& field,
160      const gfx::RectF& bounds,
161      const std::vector<base::string16>& suggestions,
162      const std::vector<base::string16>& realms);
163  void OnSetDataList(const std::vector<base::string16>& values,
164                     const std::vector<base::string16>& labels);
165
166  // Requests an interactive autocomplete UI be shown.
167  void OnRequestAutocomplete(const FormData& form,
168                             const GURL& frame_url);
169
170  // Called to signal a page is completed in renderer in the Autocheckout flow.
171  void OnAutocheckoutPageCompleted(autofill::AutocheckoutStatus status);
172
173  // Shows the Autocheckout bubble if conditions are right. See comments for
174  // AutocheckoutManager::MaybeShowAutocheckoutBubble. Input element requesting
175  // bubble belongs to |form|. |bounding_box| is the bounding box of the input
176  // field in focus.
177  virtual void OnMaybeShowAutocheckoutBubble(const FormData& form,
178                                             const gfx::RectF& bounding_box);
179
180  // Resets cache.
181  virtual void Reset();
182
183  autofill::AutocheckoutManager* autocheckout_manager() {
184    return &autocheckout_manager_;
185  }
186
187 protected:
188  // Test code should prefer to use this constructor.
189  AutofillManager(AutofillDriver* driver,
190                  autofill::AutofillManagerDelegate* delegate,
191                  PersonalDataManager* personal_data);
192
193  // Returns the value of the AutofillEnabled pref.
194  virtual bool IsAutofillEnabled() const;
195
196  // Uploads the form data to the Autofill server.
197  virtual void UploadFormData(const FormStructure& submitted_form);
198
199  // Logs quality metrics for the |submitted_form| and uploads the form data
200  // to the crowdsourcing server, if appropriate.
201  virtual void UploadFormDataAsyncCallback(
202      const FormStructure* submitted_form,
203      const base::TimeTicks& load_time,
204      const base::TimeTicks& interaction_time,
205      const base::TimeTicks& submission_time);
206
207  // Maps GUIDs to and from IDs that are used to identify profiles and credit
208  // cards sent to and from the renderer process.
209  virtual int GUIDToID(const PersonalDataManager::GUIDPair& guid) const;
210  virtual const PersonalDataManager::GUIDPair IDToGUID(int id) const;
211
212  // Methods for packing and unpacking credit card and profile IDs for sending
213  // and receiving to and from the renderer process.
214  int PackGUIDs(const PersonalDataManager::GUIDPair& cc_guid,
215                const PersonalDataManager::GUIDPair& profile_guid) const;
216  void UnpackGUIDs(int id,
217                   PersonalDataManager::GUIDPair* cc_guid,
218                   PersonalDataManager::GUIDPair* profile_guid) const;
219
220  const AutofillMetrics* metric_logger() const { return metric_logger_.get(); }
221  void set_metric_logger(const AutofillMetrics* metric_logger);
222
223  ScopedVector<FormStructure>* form_structures() { return &form_structures_; }
224
225  // Exposed for testing.
226  AutofillExternalDelegate* external_delegate() {
227    return external_delegate_;
228  }
229
230  // Tell the renderer the current interactive autocomplete finished.
231  virtual void ReturnAutocompleteResult(
232      WebKit::WebFormElement::AutocompleteResult result,
233      const FormData& form_data);
234
235 private:
236
237  // AutofillDownloadManager::Observer:
238  virtual void OnLoadedServerPredictions(
239      const std::string& response_xml) OVERRIDE;
240
241  // Passes return data for an OnRequestAutocomplete call back to the page.
242  void ReturnAutocompleteData(const FormStructure* result,
243                              const std::string& unused_transaction_id);
244
245  // Returns the matched whitelist URL prefix for the current tab's url.
246  virtual std::string GetAutocheckoutURLPrefix() const;
247
248  // Fills |host| with the RenderViewHost for this tab.
249  // Returns false if Autofill is disabled or if the host is unavailable.
250  bool GetHost(content::RenderViewHost** host) const WARN_UNUSED_RESULT;
251
252  // Unpacks |unique_id| and fills |form_group| and |variant| with the
253  // appropriate data source and variant index.  Returns false if the unpacked
254  // id cannot be found.
255  bool GetProfileOrCreditCard(int unique_id,
256                              const AutofillDataModel** data_model,
257                              size_t* variant) const WARN_UNUSED_RESULT;
258
259  // Fills |form_structure| cached element corresponding to |form|.
260  // Returns false if the cached element was not found.
261  bool FindCachedForm(const FormData& form,
262                      FormStructure** form_structure) const WARN_UNUSED_RESULT;
263
264  // Fills |form_structure| and |autofill_field| with the cached elements
265  // corresponding to |form| and |field|.  This might have the side-effect of
266  // updating the cache.  Returns false if the |form| is not autofillable, or if
267  // it is not already present in the cache and the cache is full.
268  bool GetCachedFormAndField(const FormData& form,
269                             const FormFieldData& field,
270                             FormStructure** form_structure,
271                             AutofillField** autofill_field) WARN_UNUSED_RESULT;
272
273  // Re-parses |live_form| and adds the result to |form_structures_|.
274  // |cached_form| should be a pointer to the existing version of the form, or
275  // NULL if no cached version exists.  The updated form is then written into
276  // |updated_form|.  Returns false if the cache could not be updated.
277  bool UpdateCachedForm(const FormData& live_form,
278                        const FormStructure* cached_form,
279                        FormStructure** updated_form) WARN_UNUSED_RESULT;
280
281  // Returns a list of values from the stored profiles that match |type| and the
282  // value of |field| and returns the labels of the matching profiles. |labels|
283  // is filled with the Profile label.
284  void GetProfileSuggestions(FormStructure* form,
285                             const FormFieldData& field,
286                             const AutofillType& type,
287                             std::vector<base::string16>* values,
288                             std::vector<base::string16>* labels,
289                             std::vector<base::string16>* icons,
290                             std::vector<int>* unique_ids) const;
291
292  // Returns a list of values from the stored credit cards that match |type| and
293  // the value of |field| and returns the labels of the matching credit cards.
294  void GetCreditCardSuggestions(const FormFieldData& field,
295                                const AutofillType& type,
296                                std::vector<base::string16>* values,
297                                std::vector<base::string16>* labels,
298                                std::vector<base::string16>* icons,
299                                std::vector<int>* unique_ids) const;
300
301  // Parses the forms using heuristic matching and querying the Autofill server.
302  void ParseForms(const std::vector<FormData>& forms);
303
304  // Imports the form data, submitted by the user, into |personal_data_|.
305  void ImportFormData(const FormStructure& submitted_form);
306
307  // If |initial_interaction_timestamp_| is unset or is set to a later time than
308  // |interaction_timestamp|, updates the cached timestamp.  The latter check is
309  // needed because IPC messages can arrive out of order.
310  void UpdateInitialInteractionTimestamp(
311      const base::TimeTicks& interaction_timestamp);
312
313  // Provides driver-level context to the shared code of the component. Must
314  // outlive this object.
315  AutofillDriver* driver_;
316
317  autofill::AutofillManagerDelegate* const manager_delegate_;
318
319  std::string app_locale_;
320
321  // The personal data manager, used to save and load personal data to/from the
322  // web database.  This is overridden by the AutofillManagerTest.
323  // Weak reference.
324  // May be NULL.  NULL indicates OTR.
325  PersonalDataManager* personal_data_;
326
327  std::list<std::string> autofilled_form_signatures_;
328
329  // Handles queries and uploads to Autofill servers. Will be NULL if
330  // the download manager functionality is disabled.
331  scoped_ptr<AutofillDownloadManager> download_manager_;
332
333  // Handles single-field autocomplete form data.
334  scoped_ptr<AutocompleteHistoryManager> autocomplete_history_manager_;
335
336  // Handles autocheckout flows.
337  autofill::AutocheckoutManager autocheckout_manager_;
338
339  // For logging UMA metrics. Overridden by metrics tests.
340  scoped_ptr<const AutofillMetrics> metric_logger_;
341  // Have we logged whether Autofill is enabled for this page load?
342  bool has_logged_autofill_enabled_;
343  // Have we logged an address suggestions count metric for this page?
344  bool has_logged_address_suggestions_count_;
345  // Have we shown Autofill suggestions at least once?
346  bool did_show_suggestions_;
347  // Has the user manually edited at least one form field among the autofillable
348  // ones?
349  bool user_did_type_;
350  // Has the user autofilled a form on this page?
351  bool user_did_autofill_;
352  // Has the user edited a field that was previously autofilled?
353  bool user_did_edit_autofilled_field_;
354  // When the page finished loading.
355  base::TimeTicks forms_loaded_timestamp_;
356  // When the user first interacted with a potentially fillable form on this
357  // page.
358  base::TimeTicks initial_interaction_timestamp_;
359
360  // Our copy of the form data.
361  ScopedVector<FormStructure> form_structures_;
362
363  // GUID to ID mapping.  We keep two maps to convert back and forth.
364  mutable std::map<PersonalDataManager::GUIDPair, int> guid_id_map_;
365  mutable std::map<int, PersonalDataManager::GUIDPair> id_guid_map_;
366
367  // Delegate to perform external processing (display, selection) on
368  // our behalf.  Weak.
369  AutofillExternalDelegate* external_delegate_;
370
371  // Delegate used in test to get notifications on certain events.
372  autofill::AutofillManagerTestDelegate* test_delegate_;
373
374  base::WeakPtrFactory<AutofillManager> weak_ptr_factory_;
375
376  friend class AutofillManagerTest;
377  friend class autofill::FormStructureBrowserTest;
378  FRIEND_TEST_ALL_PREFIXES(AutofillManagerTest,
379                           DeterminePossibleFieldTypesForUpload);
380  FRIEND_TEST_ALL_PREFIXES(AutofillManagerTest,
381                           DeterminePossibleFieldTypesForUploadStressTest);
382  FRIEND_TEST_ALL_PREFIXES(AutofillManagerTest,
383                           DisabledAutofillDispatchesError);
384  FRIEND_TEST_ALL_PREFIXES(AutofillMetricsTest, AddressSuggestionsCount);
385  FRIEND_TEST_ALL_PREFIXES(AutofillMetricsTest, AutofillIsEnabledAtPageLoad);
386  FRIEND_TEST_ALL_PREFIXES(AutofillMetricsTest, DeveloperEngagement);
387  FRIEND_TEST_ALL_PREFIXES(AutofillMetricsTest, FormFillDuration);
388  FRIEND_TEST_ALL_PREFIXES(AutofillMetricsTest,
389                           NoQualityMetricsForNonAutofillableForms);
390  FRIEND_TEST_ALL_PREFIXES(AutofillMetricsTest, QualityMetrics);
391  FRIEND_TEST_ALL_PREFIXES(AutofillMetricsTest, QualityMetricsForFailure);
392  FRIEND_TEST_ALL_PREFIXES(AutofillMetricsTest, QualityMetricsWithExperimentId);
393  FRIEND_TEST_ALL_PREFIXES(AutofillMetricsTest, SaneMetricsWithCacheMismatch);
394  FRIEND_TEST_ALL_PREFIXES(AutofillManagerTest, TestExternalDelegate);
395  FRIEND_TEST_ALL_PREFIXES(AutofillManagerTest,
396                           TestTabContentsWithExternalDelegate);
397  FRIEND_TEST_ALL_PREFIXES(AutofillMetricsTest,
398                           UserHappinessFormLoadAndSubmission);
399  FRIEND_TEST_ALL_PREFIXES(AutofillMetricsTest, UserHappinessFormInteraction);
400  FRIEND_TEST_ALL_PREFIXES(AutofillManagerTest,
401                           FormSubmittedAutocompleteEnabled);
402  DISALLOW_COPY_AND_ASSIGN(AutofillManager);
403};
404
405}  // namespace autofill
406
407#endif  // COMPONENTS_AUTOFILL_CORE_BROWSER_AUTOFILL_MANAGER_H_
408