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