1// Copyright (c) 2011 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 CHROME_BROWSER_AUTOFILL_AUTOFILL_MANAGER_H_
6#define CHROME_BROWSER_AUTOFILL_AUTOFILL_MANAGER_H_
7#pragma once
8
9#include <list>
10#include <map>
11#include <string>
12#include <vector>
13
14#ifdef ANDROID
15#include "base/base_api.h"
16#endif
17#include "base/basictypes.h"
18#include "base/compiler_specific.h"
19#include "base/gtest_prod_util.h"
20#include "base/memory/scoped_ptr.h"
21#include "base/memory/scoped_vector.h"
22#include "base/string16.h"
23#include "chrome/browser/autofill/autofill_download.h"
24#include "chrome/browser/autofill/field_types.h"
25#include "chrome/browser/autofill/form_structure.h"
26#ifndef ANDROID
27#include "content/browser/tab_contents/navigation_controller.h"
28#endif
29#include "content/browser/tab_contents/tab_contents_observer.h"
30
31class AutofillField;
32class AutofillProfile;
33class AutofillMetrics;
34class CreditCard;
35class PersonalDataManager;
36class PrefService;
37class RenderViewHost;
38class TabContents;
39
40#ifdef ANDROID
41class AutoFillHost;
42#endif
43
44struct ViewHostMsg_FrameNavigate_Params;
45
46namespace IPC {
47class Message;
48}
49
50namespace webkit_glue {
51struct FormData;
52struct FormField;
53}
54
55// Manages saving and restoring the user's personal information entered into web
56// forms.
57class
58#ifdef ANDROID
59BASE_API
60#endif
61AutofillManager : public TabContentsObserver,
62                        public AutofillDownloadManager::Observer {
63 public:
64  explicit AutofillManager(TabContents* tab_contents);
65  virtual ~AutofillManager();
66
67#ifndef ANDROID
68  // Registers our browser prefs.
69  static void RegisterBrowserPrefs(PrefService* prefs);
70#endif
71
72#ifndef ANDROID
73  // Registers our Enable/Disable Autofill pref.
74  static void RegisterUserPrefs(PrefService* prefs);
75#endif
76
77#ifndef ANDROID
78  // TabContentsObserver implementation.
79  virtual void DidNavigateMainFramePostCommit(
80      const NavigationController::LoadCommittedDetails& details,
81      const ViewHostMsg_FrameNavigate_Params& params);
82  virtual bool OnMessageReceived(const IPC::Message& message);
83#endif
84
85  // AutofillDownloadManager::Observer implementation:
86  virtual void OnLoadedAutofillHeuristics(const std::string& heuristic_xml);
87  virtual void OnUploadedAutofillHeuristics(const std::string& form_signature);
88  virtual void OnHeuristicsRequestError(
89      const std::string& form_signature,
90      AutofillDownloadManager::AutofillRequestType request_type,
91      int http_error);
92
93  // Returns the value of the AutofillEnabled pref.
94  virtual bool IsAutofillEnabled() const;
95
96  // Imports the form data, submitted by the user, into |personal_data_|.
97  void ImportFormData(const FormStructure& submitted_form);
98
99  // Uploads the form data to the Autofill server.
100  void UploadFormData(const FormStructure& submitted_form);
101
102  // Reset cache.
103  void Reset();
104
105#ifdef ANDROID
106  void OnFormsSeenWrapper(const std::vector<webkit_glue::FormData>& forms) {
107    OnFormsSeen(forms);
108  }
109
110  bool OnQueryFormFieldAutoFillWrapper(const webkit_glue::FormData& form,
111                                       const webkit_glue::FormField& field) {
112    return OnQueryFormFieldAutofill(0, form, field);
113  }
114
115  void OnFillAutoFillFormDataWrapper(int query_id,
116                                     const webkit_glue::FormData& form,
117                                     const webkit_glue::FormField& field,
118                                     int unique_id) {
119    OnFillAutofillFormData(query_id, form, field, unique_id);
120  }
121#endif
122
123 protected:
124  // For tests:
125
126  // The string/int pair is composed of the guid string and variant index
127  // respectively.  The variant index is an index into the multi-valued item
128  // (where applicable).
129  typedef std::pair<std::string, size_t> GUIDPair;
130
131  AutofillManager(TabContents* tab_contents,
132                  PersonalDataManager* personal_data);
133
134  void set_personal_data_manager(PersonalDataManager* personal_data) {
135    personal_data_ = personal_data;
136  }
137
138  const AutofillMetrics* metric_logger() const { return metric_logger_.get(); }
139  void set_metric_logger(const AutofillMetrics* metric_logger);
140
141  ScopedVector<FormStructure>* form_structures() { return &form_structures_; }
142
143  // Maps GUIDs to and from IDs that are used to identify profiles and credit
144  // cards sent to and from the renderer process.
145  virtual int GUIDToID(const GUIDPair& guid);
146  virtual const GUIDPair IDToGUID(int id);
147
148  // Methods for packing and unpacking credit card and profile IDs for sending
149  // and receiving to and from the renderer process.
150  int PackGUIDs(const GUIDPair& cc_guid, const GUIDPair& profile_guid);
151  void UnpackGUIDs(int id, GUIDPair* cc_guid, GUIDPair* profile_guid);
152
153 private:
154  void OnFormSubmitted(const webkit_glue::FormData& form);
155  void OnFormsSeen(const std::vector<webkit_glue::FormData>& forms);
156#ifdef ANDROID
157  bool
158#else
159  void
160#endif
161  OnQueryFormFieldAutofill(int query_id,
162                                const webkit_glue::FormData& form,
163                                const webkit_glue::FormField& field);
164  void OnFillAutofillFormData(int query_id,
165                              const webkit_glue::FormData& form,
166                              const webkit_glue::FormField& field,
167                              int unique_id);
168  void OnShowAutofillDialog();
169  void OnDidFillAutofillFormData();
170  void OnDidShowAutofillSuggestions();
171
172  // Fills |host| with the RenderViewHost for this tab.
173  // Returns false if Autofill is disabled or if the host is unavailable.
174  bool GetHost(const std::vector<AutofillProfile*>& profiles,
175               const std::vector<CreditCard*>& credit_cards,
176#ifdef ANDROID
177               AutoFillHost** host) WARN_UNUSED_RESULT;
178#else
179               RenderViewHost** host) const WARN_UNUSED_RESULT;
180#endif
181
182  // Fills |form_structure| cached element corresponding to |form|.
183  // Returns false if the cached element was not found.
184  bool FindCachedForm(const webkit_glue::FormData& form,
185                      FormStructure** form_structure) const WARN_UNUSED_RESULT;
186
187  // Fills |form_structure| and |autofill_field| with the cached elements
188  // corresponding to |form| and |field|. Returns false if the cached elements
189  // were not found.
190  bool FindCachedFormAndField(
191      const webkit_glue::FormData& form,
192      const webkit_glue::FormField& field,
193      FormStructure** form_structure,
194      AutofillField** autofill_field) WARN_UNUSED_RESULT;
195
196  // Returns a list of values from the stored profiles that match |type| and the
197  // value of |field| and returns the labels of the matching profiles. |labels|
198  // is filled with the Profile label.
199  void GetProfileSuggestions(FormStructure* form,
200                             const webkit_glue::FormField& field,
201                             AutofillFieldType type,
202                             std::vector<string16>* values,
203                             std::vector<string16>* labels,
204                             std::vector<string16>* icons,
205                             std::vector<int>* unique_ids);
206
207  // Returns a list of values from the stored credit cards that match |type| and
208  // the value of |field| and returns the labels of the matching credit cards.
209  void GetCreditCardSuggestions(FormStructure* form,
210                                const webkit_glue::FormField& field,
211                                AutofillFieldType type,
212                                std::vector<string16>* values,
213                                std::vector<string16>* labels,
214                                std::vector<string16>* icons,
215                                std::vector<int>* unique_ids);
216
217  // Set |field| argument's value based on |type| and contents of the
218  // |credit_card|.
219  void FillCreditCardFormField(const CreditCard* credit_card,
220                               AutofillFieldType type,
221                               webkit_glue::FormField* field);
222
223  // Set |field| argument's value based on |type| and contents of the |profile|.
224  // The |variant| parameter specifies which value in a multi-valued profile.
225  void FillFormField(const AutofillProfile* profile,
226                     AutofillFieldType type,
227                     size_t variant,
228                     webkit_glue::FormField* field);
229
230  // Set |field| argument's value for phone/fax number based on contents of the
231  // |profile|. |type| is the type of the phone.
232  // The |variant| parameter specifies which value in a multi-valued profile.
233  void FillPhoneNumberField(const AutofillProfile* profile,
234                            AutofillFieldType type,
235                            size_t variant,
236                            webkit_glue::FormField* field);
237
238  // Parses the forms using heuristic matching and querying the Autofill server.
239  void ParseForms(const std::vector<webkit_glue::FormData>& forms);
240
241  // Uses existing personal data to determine possible field types for the
242  // |submitted_form|.
243  void DeterminePossibleFieldTypesForUpload(FormStructure* submitted_form);
244
245  // The personal data manager, used to save and load personal data to/from the
246  // web database.  This is overridden by the AutofillManagerTest.
247  // Weak reference.
248  // May be NULL.  NULL indicates OTR.
249  PersonalDataManager* personal_data_;
250
251  std::list<std::string> autofilled_forms_signatures_;
252  // Handles queries and uploads to Autofill servers.
253  AutofillDownloadManager download_manager_;
254
255  // Should be set to true in AutofillManagerTest and other tests, false in
256  // AutofillDownloadManagerTest and in non-test environment. Is false by
257  // default for the public constructor, and true by default for the test-only
258  // constructors.
259  bool disable_download_manager_requests_;
260
261  // For logging UMA metrics. Overridden by metrics tests.
262  scoped_ptr<const AutofillMetrics> metric_logger_;
263
264  // Have we logged whether Autofill is enabled for this page load?
265  bool has_logged_autofill_enabled_;
266
267  // Have we logged an address suggestions count metric for this page?
268  bool has_logged_address_suggestions_count_;
269
270  // Our copy of the form data.
271  ScopedVector<FormStructure> form_structures_;
272
273  // GUID to ID mapping.  We keep two maps to convert back and forth.
274  std::map<GUIDPair, int> guid_id_map_;
275  std::map<int, GUIDPair> id_guid_map_;
276
277  friend class AutofillManagerTest;
278  friend class FormStructureBrowserTest;
279  FRIEND_TEST_ALL_PREFIXES(AutofillManagerTest, FillCreditCardForm);
280  FRIEND_TEST_ALL_PREFIXES(AutofillManagerTest,
281                           FillCreditCardFormNoYearNoMonth);
282  FRIEND_TEST_ALL_PREFIXES(AutofillManagerTest, FillCreditCardFormYearNoMonth);
283  FRIEND_TEST_ALL_PREFIXES(AutofillManagerTest, FillCreditCardFormNoYearMonth);
284  FRIEND_TEST_ALL_PREFIXES(AutofillManagerTest, FillCreditCardFormYearMonth);
285  FRIEND_TEST_ALL_PREFIXES(AutofillManagerTest, FillAddressForm);
286  FRIEND_TEST_ALL_PREFIXES(AutofillManagerTest, FillAddressAndCreditCardForm);
287  FRIEND_TEST_ALL_PREFIXES(AutofillManagerTest, FillFormWithMultipleSections);
288  FRIEND_TEST_ALL_PREFIXES(AutofillManagerTest, FillFormWithMultipleEmails);
289  FRIEND_TEST_ALL_PREFIXES(AutofillManagerTest, FillAutofilledForm);
290  FRIEND_TEST_ALL_PREFIXES(AutofillManagerTest, FillPhoneNumber);
291  FRIEND_TEST_ALL_PREFIXES(AutofillManagerTest, FormChangesRemoveField);
292  FRIEND_TEST_ALL_PREFIXES(AutofillManagerTest, FormChangesAddField);
293  FRIEND_TEST_ALL_PREFIXES(AutofillManagerTest, FormSubmitted);
294  FRIEND_TEST_ALL_PREFIXES(AutofillManagerTest, FormSubmittedServerTypes);
295  FRIEND_TEST_ALL_PREFIXES(AutofillMetricsTest, AddressSuggestionsCount);
296  FRIEND_TEST_ALL_PREFIXES(AutofillMetricsTest, AutofillIsEnabledAtPageLoad);
297  FRIEND_TEST_ALL_PREFIXES(AutofillMetricsTest,
298                           NoQualityMetricsForNonAutofillableForms);
299  FRIEND_TEST_ALL_PREFIXES(AutofillMetricsTest, QualityMetrics);
300  FRIEND_TEST_ALL_PREFIXES(AutofillMetricsTest, QualityMetricsForFailure);
301  FRIEND_TEST_ALL_PREFIXES(AutofillMetricsTest, QualityMetricsWithExperimentId);
302  FRIEND_TEST_ALL_PREFIXES(AutofillMetricsTest, SaneMetricsWithCacheMismatch);
303
304  DISALLOW_COPY_AND_ASSIGN(AutofillManager);
305};
306
307#endif  // CHROME_BROWSER_AUTOFILL_AUTOFILL_MANAGER_H_
308