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