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_client.h"
24#include "components/autofill/core/browser/autofill_download_manager.h"
25#include "components/autofill/core/browser/autofill_driver.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 AutofillClient;
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                  AutofillClient* client,
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
103  // The access Address Book prompt was shown for a form.
104  void ShowedAccessAddressBookPrompt();
105
106  // The number of times that the access address book prompt was shown.
107  int AccessAddressBookPromptCount();
108#endif  // defined(OS_MACOSX) && !defined(OS_IOS)
109
110  // Called from our external delegate so they cannot be private.
111  virtual void FillOrPreviewForm(AutofillDriver::RendererFormDataAction action,
112                                 int query_id,
113                                 const FormData& form,
114                                 const FormFieldData& field,
115                                 int unique_id);
116  void DidShowSuggestions(bool is_new_popup);
117  void OnDidFillAutofillFormData(const base::TimeTicks& timestamp);
118  void OnDidPreviewAutofillFormData();
119
120  // Remove the credit card or Autofill profile that matches |unique_id|
121  // from the database.
122  void RemoveAutofillProfileOrCreditCard(int unique_id);
123
124  // Remove the specified Autocomplete entry.
125  void RemoveAutocompleteEntry(const base::string16& name,
126                               const base::string16& value);
127
128  // Returns the present form structures seen by Autofill manager.
129  const std::vector<FormStructure*>& GetFormStructures();
130
131  // Happens when the autocomplete dialog runs its callback when being closed.
132  void RequestAutocompleteDialogClosed();
133
134  AutofillClient* client() const { return client_; }
135
136  const std::string& app_locale() const { return app_locale_; }
137
138  // Only for testing.
139  void SetTestDelegate(AutofillManagerTestDelegate* delegate);
140
141  void OnFormsSeen(const std::vector<FormData>& forms,
142                   const base::TimeTicks& timestamp);
143
144  // Processes the submitted |form|, saving any new Autofill data and uploading
145  // the possible field types for the submitted fields to the crowdsourcing
146  // server.  Returns false if this form is not relevant for Autofill.
147  bool OnFormSubmitted(const FormData& form,
148                       const base::TimeTicks& timestamp);
149
150  void OnTextFieldDidChange(const FormData& form,
151                            const FormFieldData& field,
152                            const base::TimeTicks& timestamp);
153
154  // The |bounding_box| is a window relative value.
155  void OnQueryFormFieldAutofill(int query_id,
156                                const FormData& form,
157                                const FormFieldData& field,
158                                const gfx::RectF& bounding_box,
159                                bool display_warning);
160  void OnDidEndTextFieldEditing();
161  void OnHidePopup();
162  void OnSetDataList(const std::vector<base::string16>& values,
163                     const std::vector<base::string16>& labels);
164
165  // Try to label password fields and upload |form|. This differs from
166  // OnFormSubmitted() in a few ways.
167  //   - This function will only label the first <input type="password"> field
168  //     as |password_type|. Other fields will stay unlabeled, as they
169  //     should have been labeled during the upload for OnFormSubmitted().
170  //   - This function does not assume that |form| is being uploaded during
171  //     the same browsing session as it was originally submitted (as we may
172  //     not have the necessary information to classify the form at that time)
173  //     so it bypasses the cache and doesn't log the same quality UMA metrics.
174  bool UploadPasswordForm(const FormData& form,
175                          const ServerFieldType& pasword_type);
176
177  // Resets cache.
178  virtual void Reset();
179
180  // Returns the value of the AutofillEnabled pref.
181  virtual bool IsAutofillEnabled() const;
182
183 protected:
184  // Test code should prefer to use this constructor.
185  AutofillManager(AutofillDriver* driver,
186                  AutofillClient* client,
187                  PersonalDataManager* personal_data);
188
189  // Uploads the form data to the Autofill server.
190  virtual void UploadFormData(const FormStructure& submitted_form);
191
192  // Logs quality metrics for the |submitted_form| and uploads the form data
193  // to the crowdsourcing server, if appropriate.
194  virtual void UploadFormDataAsyncCallback(
195      const FormStructure* submitted_form,
196      const base::TimeTicks& load_time,
197      const base::TimeTicks& interaction_time,
198      const base::TimeTicks& submission_time);
199
200  // Maps GUIDs to and from IDs that are used to identify profiles and credit
201  // cards sent to and from the renderer process.
202  virtual int GUIDToID(const PersonalDataManager::GUIDPair& guid) const;
203  virtual const PersonalDataManager::GUIDPair IDToGUID(int id) const;
204
205  // Methods for packing and unpacking credit card and profile IDs for sending
206  // and receiving to and from the renderer process.
207  int PackGUIDs(const PersonalDataManager::GUIDPair& cc_guid,
208                const PersonalDataManager::GUIDPair& profile_guid) const;
209  void UnpackGUIDs(int id,
210                   PersonalDataManager::GUIDPair* cc_guid,
211                   PersonalDataManager::GUIDPair* profile_guid) const;
212
213  const AutofillMetrics* metric_logger() const { return metric_logger_.get(); }
214  void set_metric_logger(const AutofillMetrics* metric_logger);
215
216  ScopedVector<FormStructure>* form_structures() { return &form_structures_; }
217
218  // Exposed for testing.
219  AutofillExternalDelegate* external_delegate() {
220    return external_delegate_;
221  }
222
223 private:
224  // AutofillDownloadManager::Observer:
225  virtual void OnLoadedServerPredictions(
226      const std::string& response_xml) OVERRIDE;
227
228  // Returns false if Autofill is disabled or if no Autofill data is available.
229  bool RefreshDataModels() const;
230
231  // Unpacks |unique_id| and fills |form_group| and |variant| with the
232  // appropriate data source and variant index. Sets |is_credit_card| to true
233  // if |data_model| points to a CreditCard data model, false if it's a
234  // profile data model.
235  // Returns false if the unpacked id cannot be found.
236  bool GetProfileOrCreditCard(int unique_id,
237                              const AutofillDataModel** data_model,
238                              size_t* variant,
239                              bool* is_credit_card) const WARN_UNUSED_RESULT;
240
241  // Fills |form_structure| cached element corresponding to |form|.
242  // Returns false if the cached element was not found.
243  bool FindCachedForm(const FormData& form,
244                      FormStructure** form_structure) const WARN_UNUSED_RESULT;
245
246  // Fills |form_structure| and |autofill_field| with the cached elements
247  // corresponding to |form| and |field|.  This might have the side-effect of
248  // updating the cache.  Returns false if the |form| is not autofillable, or if
249  // it is not already present in the cache and the cache is full.
250  bool GetCachedFormAndField(const FormData& form,
251                             const FormFieldData& field,
252                             FormStructure** form_structure,
253                             AutofillField** autofill_field) WARN_UNUSED_RESULT;
254
255  // Re-parses |live_form| and adds the result to |form_structures_|.
256  // |cached_form| should be a pointer to the existing version of the form, or
257  // NULL if no cached version exists.  The updated form is then written into
258  // |updated_form|.  Returns false if the cache could not be updated.
259  bool UpdateCachedForm(const FormData& live_form,
260                        const FormStructure* cached_form,
261                        FormStructure** updated_form) WARN_UNUSED_RESULT;
262
263  // Returns a list of values from the stored profiles that match |type| and the
264  // value of |field| and returns the labels of the matching profiles. |labels|
265  // is filled with the Profile label.
266  void GetProfileSuggestions(const FormStructure& form,
267                             const FormFieldData& field,
268                             const AutofillField& autofill_field,
269                             std::vector<base::string16>* values,
270                             std::vector<base::string16>* labels,
271                             std::vector<base::string16>* icons,
272                             std::vector<int>* unique_ids) const;
273
274  // Returns a list of values from the stored credit cards that match |type| and
275  // the value of |field| and returns the labels of the matching credit cards.
276  void GetCreditCardSuggestions(const FormFieldData& field,
277                                const AutofillType& type,
278                                std::vector<base::string16>* values,
279                                std::vector<base::string16>* labels,
280                                std::vector<base::string16>* icons,
281                                std::vector<int>* unique_ids) const;
282
283  // Parses the forms using heuristic matching and querying the Autofill server.
284  void ParseForms(const std::vector<FormData>& forms);
285
286  // Imports the form data, submitted by the user, into |personal_data_|.
287  void ImportFormData(const FormStructure& submitted_form);
288
289  // If |initial_interaction_timestamp_| is unset or is set to a later time than
290  // |interaction_timestamp|, updates the cached timestamp.  The latter check is
291  // needed because IPC messages can arrive out of order.
292  void UpdateInitialInteractionTimestamp(
293      const base::TimeTicks& interaction_timestamp);
294
295  // Shared code to determine if |form| should be uploaded.
296  bool ShouldUploadForm(const FormStructure& form);
297
298  // Provides driver-level context to the shared code of the component. Must
299  // outlive this object.
300  AutofillDriver* driver_;
301
302  AutofillClient* const client_;
303
304  std::string app_locale_;
305
306  // The personal data manager, used to save and load personal data to/from the
307  // web database.  This is overridden by the AutofillManagerTest.
308  // Weak reference.
309  // May be NULL.  NULL indicates OTR.
310  PersonalDataManager* personal_data_;
311
312  std::list<std::string> autofilled_form_signatures_;
313
314  // Handles queries and uploads to Autofill servers. Will be NULL if
315  // the download manager functionality is disabled.
316  scoped_ptr<AutofillDownloadManager> download_manager_;
317
318  // Handles single-field autocomplete form data.
319  scoped_ptr<AutocompleteHistoryManager> autocomplete_history_manager_;
320
321  // For logging UMA metrics. Overridden by metrics tests.
322  scoped_ptr<const AutofillMetrics> metric_logger_;
323  // Have we logged whether Autofill is enabled for this page load?
324  bool has_logged_autofill_enabled_;
325  // Have we logged an address suggestions count metric for this page?
326  bool has_logged_address_suggestions_count_;
327  // Have we shown Autofill suggestions at least once?
328  bool did_show_suggestions_;
329  // Has the user manually edited at least one form field among the autofillable
330  // ones?
331  bool user_did_type_;
332  // Has the user autofilled a form on this page?
333  bool user_did_autofill_;
334  // Has the user edited a field that was previously autofilled?
335  bool user_did_edit_autofilled_field_;
336  // When the form finished loading.
337  std::map<FormData, base::TimeTicks> forms_loaded_timestamps_;
338  // When the user first interacted with a potentially fillable form on this
339  // page.
340  base::TimeTicks initial_interaction_timestamp_;
341
342  // Our copy of the form data.
343  ScopedVector<FormStructure> form_structures_;
344
345  // GUID to ID mapping.  We keep two maps to convert back and forth.
346  mutable std::map<PersonalDataManager::GUIDPair, int> guid_id_map_;
347  mutable std::map<int, PersonalDataManager::GUIDPair> id_guid_map_;
348
349  // Delegate to perform external processing (display, selection) on
350  // our behalf.  Weak.
351  AutofillExternalDelegate* external_delegate_;
352
353  // Delegate used in test to get notifications on certain events.
354  AutofillManagerTestDelegate* test_delegate_;
355
356  base::WeakPtrFactory<AutofillManager> weak_ptr_factory_;
357
358  friend class AutofillManagerTest;
359  friend class FormStructureBrowserTest;
360  FRIEND_TEST_ALL_PREFIXES(AutofillManagerTest,
361                           DeterminePossibleFieldTypesForUpload);
362  FRIEND_TEST_ALL_PREFIXES(AutofillManagerTest,
363                           DeterminePossibleFieldTypesForUploadStressTest);
364  FRIEND_TEST_ALL_PREFIXES(AutofillManagerTest,
365                           DisabledAutofillDispatchesError);
366  FRIEND_TEST_ALL_PREFIXES(AutofillMetricsTest, AddressSuggestionsCount);
367  FRIEND_TEST_ALL_PREFIXES(AutofillMetricsTest, AutofillIsEnabledAtPageLoad);
368  FRIEND_TEST_ALL_PREFIXES(AutofillMetricsTest, DeveloperEngagement);
369  FRIEND_TEST_ALL_PREFIXES(AutofillMetricsTest, FormFillDuration);
370  FRIEND_TEST_ALL_PREFIXES(AutofillMetricsTest,
371                           NoQualityMetricsForNonAutofillableForms);
372  FRIEND_TEST_ALL_PREFIXES(AutofillMetricsTest, QualityMetrics);
373  FRIEND_TEST_ALL_PREFIXES(AutofillMetricsTest, QualityMetricsForFailure);
374  FRIEND_TEST_ALL_PREFIXES(AutofillMetricsTest, QualityMetricsWithExperimentId);
375  FRIEND_TEST_ALL_PREFIXES(AutofillMetricsTest, SaneMetricsWithCacheMismatch);
376  FRIEND_TEST_ALL_PREFIXES(AutofillManagerTest, TestExternalDelegate);
377  FRIEND_TEST_ALL_PREFIXES(AutofillManagerTest,
378                           TestTabContentsWithExternalDelegate);
379  FRIEND_TEST_ALL_PREFIXES(AutofillMetricsTest,
380                           UserHappinessFormLoadAndSubmission);
381  FRIEND_TEST_ALL_PREFIXES(AutofillMetricsTest, UserHappinessFormInteraction);
382  FRIEND_TEST_ALL_PREFIXES(AutofillManagerTest,
383                           FormSubmittedAutocompleteEnabled);
384  DISALLOW_COPY_AND_ASSIGN(AutofillManager);
385};
386
387}  // namespace autofill
388
389#endif  // COMPONENTS_AUTOFILL_CORE_BROWSER_AUTOFILL_MANAGER_H_
390