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