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 <map>
9 #include <memory>
10 #include <set>
11 #include <string>
12 #include <vector>
13 
14 #include "base/callback_forward.h"
15 #include "base/compiler_specific.h"
16 #include "base/containers/circular_deque.h"
17 #include "base/gtest_prod_util.h"
18 #include "base/macros.h"
19 #include "base/memory/weak_ptr.h"
20 #include "base/optional.h"
21 #include "base/strings/string16.h"
22 #include "base/time/time.h"
23 #include "base/timer/timer.h"
24 #include "build/build_config.h"
25 #include "components/autofill/core/browser/autocomplete_history_manager.h"
26 #include "components/autofill/core/browser/autofill_client.h"
27 #include "components/autofill/core/browser/autofill_download_manager.h"
28 #include "components/autofill/core/browser/autofill_driver.h"
29 #include "components/autofill/core/browser/autofill_handler.h"
30 #include "components/autofill/core/browser/autofill_metrics.h"
31 #include "components/autofill/core/browser/field_filler.h"
32 #include "components/autofill/core/browser/form_types.h"
33 #include "components/autofill/core/browser/metrics/address_form_event_logger.h"
34 #include "components/autofill/core/browser/metrics/credit_card_form_event_logger.h"
35 #include "components/autofill/core/browser/payments/autofill_offer_manager.h"
36 #include "components/autofill/core/browser/payments/card_unmask_delegate.h"
37 #include "components/autofill/core/browser/payments/credit_card_access_manager.h"
38 #include "components/autofill/core/browser/payments/full_card_request.h"
39 #include "components/autofill/core/browser/personal_data_manager.h"
40 #include "components/autofill/core/browser/sync_utils.h"
41 #include "components/autofill/core/browser/ui/popup_types.h"
42 #include "components/autofill/core/common/form_data.h"
43 #include "components/autofill/core/common/signatures.h"
44 
45 namespace gfx {
46 class RectF;
47 }
48 
49 namespace autofill {
50 
51 class AutofillDataModel;
52 class AutofillDownloadManager;
53 class AutofillExternalDelegate;
54 class AutofillField;
55 class AutofillClient;
56 class AutofillManagerTestDelegate;
57 class AutofillProfile;
58 class AutofillType;
59 class CreditCard;
60 class FormStructureBrowserTest;
61 class LogManager;
62 
63 struct FormData;
64 struct FormFieldData;
65 
66 // We show the credit card signin promo only a certain number of times.
67 extern const int kCreditCardSigninPromoImpressionLimit;
68 
69 // Enum for the value patterns metric. Don't renumerate existing value. They are
70 // used for metrics.
71 enum class ValuePatternsMetric {
72   kNoPatternFound = 0,
73   kUpiVpa = 1,  // UPI virtual payment address.
74   kIban = 2,    // International Bank Account Number.
75   kMaxValue = kIban,
76 };
77 
78 // Manages saving and restoring the user's personal information entered into web
79 // forms. One per frame; owned by the AutofillDriver.
80 class AutofillManager : public AutofillHandler,
81                         public AutofillDownloadManager::Observer,
82                         public AutocompleteHistoryManager::SuggestionsHandler,
83                         public CreditCardAccessManager::Accessor {
84  public:
85   AutofillManager(AutofillDriver* driver,
86                   AutofillClient* client,
87                   const std::string& app_locale,
88                   AutofillDownloadManagerState enable_download_manager);
89   ~AutofillManager() override;
90 
91   // Sets an external delegate.
92   void SetExternalDelegate(AutofillExternalDelegate* delegate);
93 
94   void ShowAutofillSettings(bool show_credit_card_settings);
95 
96   // Whether the |field| should show an entry to scan a credit card.
97   virtual bool ShouldShowScanCreditCard(const FormData& form,
98                                         const FormFieldData& field);
99 
100   // Returns the type of the popup being shown.
101   virtual PopupType GetPopupType(const FormData& form,
102                                  const FormFieldData& field);
103 
104   // Whether we should show the signin promo, based on the triggered |field|
105   // inside the |form|.
106   virtual bool ShouldShowCreditCardSigninPromo(const FormData& form,
107                                                const FormFieldData& field);
108 
109   // Handlers for the "Show Cards From Account" row. This row should be shown to
110   // users who have cards in their account and can use Sync Transport. Clicking
111   // the row records the user's consent to see these cards on this device, and
112   // refreshes the popup.
113   virtual bool ShouldShowCardsFromAccountOption(const FormData& form,
114                                                 const FormFieldData& field);
115   virtual void OnUserAcceptedCardsFromAccountOption();
116   virtual void RefetchCardsAndUpdatePopup(int query_id,
117                                           const FormData& form,
118                                           const FormFieldData& field_data);
119 
120 #if !defined(OS_ANDROID) && !defined(OS_IOS)
121   // Returns the list of credit cards that have associated cloud token data.
122   virtual void FetchVirtualCardCandidates();
123 
124   // Callback invoked when an actual card is selected. |selected_card_id| will
125   // be used to identify the card. The selected card's cloud token data will be
126   // fetched from the server.
127   // TODO(crbug.com/1020740): Passes card server id for now. In the future when
128   // one actual credit card can have multiple virtual cards, passes instrument
129   // token instead. Design TBD.
130   virtual void OnVirtualCardCandidateSelected(
131       const std::string& selected_card_id);
132 #endif
133 
134   // Called from our external delegate so they cannot be private.
135   virtual void FillOrPreviewForm(AutofillDriver::RendererFormDataAction action,
136                                  int query_id,
137                                  const FormData& form,
138                                  const FormFieldData& field,
139                                  int unique_id);
140   virtual void FillCreditCardForm(int query_id,
141                                   const FormData& form,
142                                   const FormFieldData& field,
143                                   const CreditCard& credit_card,
144                                   const base::string16& cvc);
145   void DidShowSuggestions(bool has_autofill_suggestions,
146                           const FormData& form,
147                           const FormFieldData& field);
148 
149   // Called from autofill assistant.
150   virtual void FillProfileForm(const autofill::AutofillProfile& profile,
151                                const FormData& form,
152                                const FormFieldData& field);
153 
154   // Returns true if the value/identifier is deletable. Fills out
155   // |title| and |body| with relevant user-facing text.
156   bool GetDeletionConfirmationText(const base::string16& value,
157                                    int identifier,
158                                    base::string16* title,
159                                    base::string16* body);
160 
161   // Remove the credit card or Autofill profile that matches |unique_id|
162   // from the database. Returns true if deletion is allowed.
163   bool RemoveAutofillProfileOrCreditCard(int unique_id);
164 
165   // Remove the specified Autocomplete entry.
166   void RemoveAutocompleteEntry(const base::string16& name,
167                                const base::string16& value);
168 
169   // Invoked when the user selected |value| in the Autocomplete drop-down.
170   void OnAutocompleteEntrySelected(const base::string16& value);
171 
172   // Invoked when the user selects the "Hide Suggestions" item in the
173   // Autocomplete drop-down.
174   virtual void OnUserHideSuggestions(const FormData& form,
175                                      const FormFieldData& field);
176 
177   // Returns true only if the previewed form should be cleared.
178   bool ShouldClearPreviewedForm();
179 
client()180   AutofillClient* client() { return client_; }
181 
download_manager()182   AutofillDownloadManager* download_manager() {
183     return download_manager_.get();
184   }
185 
credit_card_access_manager()186   CreditCardAccessManager* credit_card_access_manager() {
187     return credit_card_access_manager_.get();
188   }
189 
190   payments::FullCardRequest* GetOrCreateFullCardRequest();
191 
192   base::WeakPtr<payments::FullCardRequest::UIDelegate>
193   GetAsFullCardRequestUIDelegate();
194 
app_locale()195   const std::string& app_locale() const { return app_locale_; }
196 
197   // Only for testing.
198   void SetTestDelegate(AutofillManagerTestDelegate* delegate);
199 
200   // Will send an upload based on the |form_structure| data and the local
201   // Autofill profile data. |observed_submission| is specified if the upload
202   // follows an observed submission event. Returns false if the upload couldn't
203   // start.
204   virtual bool MaybeStartVoteUploadProcess(
205       std::unique_ptr<FormStructure> form_structure,
206       bool observed_submission);
207 
208   // Update the pending form with |form|, possibly processing the current
209   // pending form for upload.
210   void UpdatePendingForm(const FormData& form);
211 
212   // Upload the current pending form.
213   void ProcessPendingFormForUpload();
214 
215   // Invoked when the popup view can't be created. Main usage is to collect
216   // metrics.
217   void DidSuppressPopup(const FormData& form, const FormFieldData& field);
218 
219   // AutofillHandler:
220   void OnFocusNoLongerOnForm(bool had_interacted_form) override;
221   void OnFocusOnFormFieldImpl(const FormData& form,
222                               const FormFieldData& field,
223                               const gfx::RectF& bounding_box) override;
224   void OnDidFillAutofillFormData(const FormData& form,
225                                  const base::TimeTicks timestamp) override;
226   void OnDidPreviewAutofillFormData() override;
227   void OnDidEndTextFieldEditing() override;
228   void OnHidePopup() override;
229   void SelectFieldOptionsDidChange(const FormData& form) override;
230   void Reset() override;
231 
232   // AutocompleteHistoryManager::SuggestionsHandler:
233   void OnSuggestionsReturned(
234       int query_id,
235       bool autoselect_first_suggestion,
236       const std::vector<Suggestion>& suggestions) override;
237 
238   // Returns true if either Profile or CreditCard Autofill is enabled.
239   virtual bool IsAutofillEnabled() const;
240 
241   // Returns true if the value of the AutofillProfileEnabled pref is true and
242   // the client supports Autofill.
243   virtual bool IsAutofillProfileEnabled() const;
244 
245   // Returns true if the value of the AutofillCreditCardEnabled pref is true and
246   // the client supports Autofill.
247   virtual bool IsAutofillCreditCardEnabled() const;
248 
249   // Shared code to determine if |form| should be uploaded to the Autofill
250   // server. It verifies that uploading is allowed and |form| meets conditions
251   // to be uploadable. Exposed for testing.
252   bool ShouldUploadForm(const FormStructure& form);
253 
254   // Rich queries are enabled by feature flag iff this chrome instance is
255   // neither on the STABLE nor BETA release channel.
256   static bool IsRichQueryEnabled(version_info::Channel channel);
257 
258   // Returns the last form the autofill manager considered in this frame.
259   virtual const FormData& last_query_form() const;
260 
261   // Exposed to ContentAutofillDriver to help with recording WebOTP metrics.
has_parsed_forms()262   bool has_parsed_forms() const { return has_parsed_forms_; }
has_observed_phone_number_field()263   bool has_observed_phone_number_field() const {
264     return has_observed_phone_number_field_;
265   }
has_observed_one_time_code_field()266   bool has_observed_one_time_code_field() const {
267     return has_observed_one_time_code_field_;
268   }
269 
270 #if defined(UNIT_TEST)
271   // A public wrapper that calls |DeterminePossibleFieldTypesForUpload| for
272   // testing purposes only.
DeterminePossibleFieldTypesForUploadForTest(const std::vector<AutofillProfile> & profiles,const std::vector<CreditCard> & credit_cards,const base::string16 & last_unlocked_credit_card_cvc,const std::string & app_locale,FormStructure * submitted_form)273   static void DeterminePossibleFieldTypesForUploadForTest(
274       const std::vector<AutofillProfile>& profiles,
275       const std::vector<CreditCard>& credit_cards,
276       const base::string16& last_unlocked_credit_card_cvc,
277       const std::string& app_locale,
278       FormStructure* submitted_form) {
279     DeterminePossibleFieldTypesForUpload(profiles, credit_cards,
280                                          last_unlocked_credit_card_cvc,
281                                          app_locale, submitted_form);
282   }
283 
284   // A public wrapper that calls |OnLoadedServerPredictions| for testing
285   // purposes only.
OnLoadedServerPredictionsForTest(std::string response,const std::vector<FormSignature> & queried_form_signatures)286   void OnLoadedServerPredictionsForTest(
287       std::string response,
288       const std::vector<FormSignature>& queried_form_signatures) {
289     OnLoadedServerPredictions(response, queried_form_signatures);
290   }
291 
292   // A public wrapper that calls |MakeFrontendID| for testing purposes only.
MakeFrontendIDForTest(const std::string & cc_backend_id,const std::string & profile_backend_id)293   int MakeFrontendIDForTest(const std::string& cc_backend_id,
294                             const std::string& profile_backend_id) const {
295     return MakeFrontendID(cc_backend_id, profile_backend_id);
296   }
297 
298   // A public wrapper that calls |form_interactions_ukm_logger| for testing
299   // purposes only.
300   AutofillMetrics::FormInteractionsUkmLogger*
form_interactions_ukm_logger_for_test()301   form_interactions_ukm_logger_for_test() {
302     return form_interactions_ukm_logger();
303   }
304 
305   // A public wrapper that calls |ShouldTriggerRefill| for testing purposes
306   // only.
ShouldTriggerRefillForTest(const FormStructure & form_structure)307   bool ShouldTriggerRefillForTest(const FormStructure& form_structure) {
308     return ShouldTriggerRefill(form_structure);
309   }
310 
311   // A public wrapper that calls |TriggerRefill| for testing purposes only.
TriggerRefillForTest(const FormData & form)312   void TriggerRefillForTest(const FormData& form) { TriggerRefill(form); }
313 #endif
314 
315  protected:
316   // Test code should prefer to use this constructor.
317   AutofillManager(
318       AutofillDriver* driver,
319       AutofillClient* client,
320       PersonalDataManager* personal_data,
321       AutocompleteHistoryManager* autocomplete_history_manager,
322       const std::string app_locale = "en-US",
323       AutofillDownloadManagerState enable_download_manager =
324           DISABLE_AUTOFILL_DOWNLOAD_MANAGER,
325       std::unique_ptr<CreditCardAccessManager> cc_access_manager = nullptr);
326 
327   // Uploads the form data to the Autofill server. |observed_submission|
328   // indicates that upload is the result of a submission event.
329   virtual void UploadFormData(const FormStructure& submitted_form,
330                               bool observed_submission);
331 
332   // Logs quality metrics for the |submitted_form| and uploads the form data
333   // to the crowdsourcing server, if appropriate. |observed_submission|
334   // indicates whether the upload is a result of an observed submission event.
335   virtual void UploadFormDataAsyncCallback(
336       const FormStructure* submitted_form,
337       const base::TimeTicks& interaction_time,
338       const base::TimeTicks& submission_time,
339       bool observed_submission);
340 
341   // Maps suggestion backend ID to and from an integer identifying it. Two of
342   // these intermediate integers are packed by MakeFrontendID to make the IDs
343   // that this class generates for the UI and for IPC.
344   virtual int BackendIDToInt(const std::string& backend_id) const;
345   virtual std::string IntToBackendID(int int_id) const;
346 
347   // Methods for packing and unpacking credit card and profile IDs for sending
348   // and receiving to and from the renderer process.
349   int MakeFrontendID(const std::string& cc_backend_id,
350                      const std::string& profile_backend_id) const;
351   void SplitFrontendID(int frontend_id,
352                        std::string* cc_backend_id,
353                        std::string* profile_backend_id) const;
354 
355   // AutofillHandler:
356   void OnFormSubmittedImpl(const FormData& form,
357                            bool known_success,
358                            mojom::SubmissionSource source) override;
359   void OnTextFieldDidChangeImpl(const FormData& form,
360                                 const FormFieldData& field,
361                                 const gfx::RectF& bounding_box,
362                                 const base::TimeTicks timestamp) override;
OnTextFieldDidScrollImpl(const FormData & form,const FormFieldData & field,const gfx::RectF & bounding_box)363   void OnTextFieldDidScrollImpl(const FormData& form,
364                                 const FormFieldData& field,
365                                 const gfx::RectF& bounding_box) override {}
366   void OnQueryFormFieldAutofillImpl(int query_id,
367                                     const FormData& form,
368                                     const FormFieldData& field,
369                                     const gfx::RectF& transformed_box,
370                                     bool autoselect_first_suggestion) override;
371   void OnSelectControlDidChangeImpl(const FormData& form,
372                                     const FormFieldData& field,
373                                     const gfx::RectF& bounding_box) override;
374   bool ShouldParseForms(const std::vector<FormData>& forms,
375                         const base::TimeTicks timestamp) override;
376   void OnFormsParsed(const std::vector<const FormData*>& forms,
377                      const base::TimeTicks timestamp) override;
378 
form_interactions_ukm_logger()379   AutofillMetrics::FormInteractionsUkmLogger* form_interactions_ukm_logger() {
380     return form_interactions_ukm_logger_.get();
381   }
382 
383   // Exposed for testing.
set_download_manager(AutofillDownloadManager * manager)384   void set_download_manager(AutofillDownloadManager* manager) {
385     download_manager_.reset(manager);
386   }
387 
388   // Exposed for testing.
is_rich_query_enabled()389   bool is_rich_query_enabled() const { return is_rich_query_enabled_; }
390 
391   // Exposed for testing.
pending_form_data()392   FormData* pending_form_data() { return pending_form_data_.get(); }
393 
394  private:
395   // Keeps track of the filling context for a form, used to make refill attemps.
396   struct FillingContext {
397     // |optional_profile| or |optional_credit_card| must be non-null.
398     // If |optional_credit_card| is non-null, |optional_cvc| may be non-null.
399     FillingContext(const AutofillField& field,
400                    const AutofillProfile* optional_profile,
401                    const CreditCard* optional_credit_card,
402                    const base::string16* optional_cvc);
403     ~FillingContext();
404 
405     // Whether a refill attempt was made.
406     bool attempted_refill = false;
407     // The profile or credit card that was used for the initial fill.
408     // The std::string associated with the credit card is the CVC, which may be
409     // empty.
410     const base::Optional<AutofillProfile> profile;
411     const base::Optional<std::pair<CreditCard, base::string16>> credit_card;
412     // Possible identifiers of the field that was focused when the form was
413     // initially filled. A refill shall be triggered from the same field.
414     // TODO(crbug/896689): Remove |filled_field_unique_name|.
415     const FieldRendererId filled_field_renderer_id;
416     const FieldSignature filled_field_signature;
417     const base::string16 filled_field_unique_name;
418     // The time at which the initial fill occurred.
419     const base::TimeTicks original_fill_time;
420     // The timer used to trigger a refill.
421     base::OneShotTimer on_refill_timer;
422     // The field type groups that were initially filled.
423     std::set<FieldTypeGroup> type_groups_originally_filled;
424   };
425 
426   // Indicates the reason why autofill suggestions are suppressed.
427   enum class SuppressReason {
428     kNotSuppressed,
429     // Credit card suggestions are not shown because an ablation experiment is
430     // enabled.
431     kCreditCardsAblation,
432     // Address suggestions are not shown because the field is annotated with
433     // autocomplete=off and the directive is being observed by the browser.
434     kAutocompleteOff,
435     // Suggestions are not shown because this form is on a secure site, but
436     // submits insecurely. This is only used when the user has started typing,
437     // otherwise a warning is shown.
438     kInsecureForm,
439   };
440 
441   // The context for the list of suggestions available for a given field to be
442   // returned by GetAvailableSuggestions().
443   struct SuggestionsContext {
444     FormStructure* form_structure = nullptr;
445     AutofillField* focused_field = nullptr;
446     bool is_autofill_available = false;
447     bool is_context_secure = false;
448     bool is_filling_credit_card = false;
449     // Flag to indicate whether all suggestions come from Google Payments.
450     bool should_display_gpay_logo = false;
451     SuppressReason suppress_reason = SuppressReason::kNotSuppressed;
452   };
453 
454   // AutofillDownloadManager::Observer:
455   void OnLoadedServerPredictions(
456       std::string response,
457       const std::vector<FormSignature>& queried_form_signatures) override;
458 
459   // CreditCardAccessManager::Accessor
460   void OnCreditCardFetched(
461       bool did_succeed,
462       const CreditCard* credit_card = nullptr,
463       const base::string16& cvc = base::string16()) override;
464 
465   // Returns false if Autofill is disabled or if no Autofill data is available.
466   bool RefreshDataModels();
467 
468   // Gets the card referred to by the guid |unique_id|. Returns |nullptr| if
469   // card does not exist.
470   CreditCard* GetCreditCard(int unique_id);
471 
472   // Gets the profile referred to by the guid |unique_id|. Returns |nullptr| if
473   // profile does not exist.
474   AutofillProfile* GetProfile(int unique_id);
475 
476   // Determines whether a fill on |form| initiated from |field| will wind up
477   // filling a credit card number. This is useful to determine if we will need
478   // to unmask a card.
479   bool WillFillCreditCardNumber(const FormData& form,
480                                 const FormFieldData& field);
481 
482   // Fills or previews the credit card form.
483   // Assumes the form and field are valid.
484   void FillOrPreviewCreditCardForm(
485       AutofillDriver::RendererFormDataAction action,
486       int query_id,
487       const FormData& form,
488       const FormFieldData& field,
489       const CreditCard* credit_card);
490 
491   // Fills or previews the profile form.
492   // Assumes the form and field are valid.
493   void FillOrPreviewProfileForm(AutofillDriver::RendererFormDataAction action,
494                                 int query_id,
495                                 const FormData& form,
496                                 const FormFieldData& field,
497                                 const AutofillProfile& profile);
498 
499   // Fills or previews |data_model| in the |form|.
500   void FillOrPreviewDataModelForm(AutofillDriver::RendererFormDataAction action,
501                                   int query_id,
502                                   const FormData& form,
503                                   const FormFieldData& field,
504                                   const AutofillProfile* optional_profile,
505                                   const CreditCard* optional_credit_card,
506                                   const base::string16* optional_cvc,
507                                   FormStructure* form_structure,
508                                   AutofillField* autofill_field,
509                                   bool is_refill = false);
510 
511   // Creates a FormStructure using the FormData received from the renderer. Will
512   // return an empty scoped_ptr if the data should not be processed for upload
513   // or personal data.
514   std::unique_ptr<FormStructure> ValidateSubmittedForm(const FormData& form);
515 
516   // Returns the field corresponding to |form| and |field| that can be
517   // autofilled. Returns NULL if the field cannot be autofilled.
518   AutofillField* GetAutofillField(const FormData& form,
519                                   const FormFieldData& field)
520       WARN_UNUSED_RESULT;
521 
522   // Returns true if any form in the field corresponds to an address
523   // |FieldTypeGroup|.
524   bool FormHasAddressField(const FormData& form) WARN_UNUSED_RESULT;
525 
526   // Returns Suggestions corresponding to both the |autofill_field| type and
527   // stored profiles whose values match the contents of |field|. |form| stores
528   // data about the form with which the user is interacting, e.g. the number and
529   // types of form fields.
530   std::vector<Suggestion> GetProfileSuggestions(
531       const FormStructure& form,
532       const FormFieldData& field,
533       const AutofillField& autofill_field) const;
534 
535   // Returns a list of values from the stored credit cards that match |type| and
536   // the value of |field| and returns the labels of the matching credit cards.
537   // |should_display_gpay_logo| will be set to true if there is no credit card
538   // suggestions or all suggestions come from Payments server.
539   std::vector<Suggestion> GetCreditCardSuggestions(
540       const FormFieldData& field,
541       const AutofillType& type,
542       bool* should_display_gpay_logo) const;
543 
544   // If |initial_interaction_timestamp_| is unset or is set to a later time than
545   // |interaction_timestamp|, updates the cached timestamp.  The latter check is
546   // needed because IPC messages can arrive out of order.
547   void UpdateInitialInteractionTimestamp(
548       const base::TimeTicks& interaction_timestamp);
549 
550   // Examines |form| and returns true if it is in a non-secure context or
551   // its action attribute targets a HTTP url.
552   bool IsFormNonSecure(const FormData& form) const;
553 
554   // Uses the existing personal data in |profiles| and |credit_cards| to
555   // determine possible field types for the |submitted_form|.  This is
556   // potentially expensive -- on the order of 50ms even for a small set of
557   // |stored_data|. Hence, it should not run on the UI thread -- to avoid
558   // locking up the UI -- nor on the IO thread -- to avoid blocking IPC calls.
559   static void DeterminePossibleFieldTypesForUpload(
560       const std::vector<AutofillProfile>& profiles,
561       const std::vector<CreditCard>& credit_cards,
562       const base::string16& last_unlocked_credit_card_cvc,
563       const std::string& app_locale,
564       FormStructure* submitted_form);
565 
566   // Uses context about previous and next fields to select the appropriate type
567   // for fields with ambiguous upload types.
568   static void DisambiguateUploadTypes(FormStructure* form);
569 
570   // Disambiguates address field upload types.
571   static void DisambiguateAddressUploadTypes(FormStructure* form,
572                                              size_t current_index);
573 
574   // Disambiguates phone field upload types.
575   static void DisambiguatePhoneUploadTypes(FormStructure* form,
576                                            size_t current_index);
577 
578   // Disambiguates name field upload types.
579   static void DisambiguateNameUploadTypes(
580       FormStructure* form,
581       size_t current_index,
582       const ServerFieldTypeSet& upload_types);
583 
584   void FillFieldWithValue(AutofillField* autofill_field,
585                           const AutofillDataModel& data_model,
586                           FormFieldData* field_data,
587                           bool should_notify,
588                           const base::string16& cvc,
589                           uint32_t profile_form_bitmask,
590                           std::string* failure_to_fill);
591 
592   // TODO(crbug/896689): Remove code duplication once experiment is finished.
593   void SetFillingContext(const FormStructure& form,
594                          std::unique_ptr<FillingContext> context);
595 
596   // TODO(crbug/896689): Remove code duplication once experiment is finished.
597   FillingContext* GetFillingContext(const FormStructure& form);
598 
599   // Whether there should be an attempts to refill the form. Returns true if all
600   // the following are satisfied:
601   //  There have been no refill on that page yet.
602   //  A non empty form name was recorded in a previous fill
603   //  That form name matched the currently parsed form name
604   //  It's been less than kLimitBeforeRefillMs since the original fill.
605   bool ShouldTriggerRefill(const FormStructure& form_structure);
606 
607   // Attempts to refill the form that was changed dynamically. Should only be
608   // called if ShouldTriggerRefill returns true.
609   void TriggerRefill(const FormData& form);
610 
611   // Replaces the contents of |suggestions| with available suggestions for
612   // |field|. |context| will contain additional information about the
613   // suggestions, such as if they correspond to credit card suggestions and
614   // if the context is secure.
615   void GetAvailableSuggestions(const FormData& form,
616                                const FormFieldData& field,
617                                std::vector<Suggestion>* suggestions,
618                                SuggestionsContext* context);
619 
620   // Retrieves the page language from |client_|
621   std::string GetPageLanguage() const override;
622 
623 #if !defined(OS_ANDROID) && !defined(OS_IOS)
624   // Whether to show the option to use virtual card in the autofill popup.
625   bool ShouldShowVirtualCardOption(FormStructure* form_structure);
626 #endif
627 
628   // Returns an appropriate EventFormLogger for the given |field_type_group|.
629   // May return nullptr.
630   FormEventLoggerBase* GetEventFormLogger(
631       FieldTypeGroup field_type_group) const;
632 
633   void SetDataList(const std::vector<base::string16>& values,
634                    const std::vector<base::string16>& labels);
635 
636   AutofillClient* const client_;
637 
638   LogManager* log_manager_;
639 
640   std::string app_locale_;
641 
642   // The personal data manager, used to save and load personal data to/from the
643   // web database.  This is overridden by the AutofillManagerTest.
644   // Weak reference.
645   // May be NULL.  NULL indicates OTR.
646   PersonalDataManager* personal_data_;
647 
648   // Used to help fill data into fields.
649   FieldFiller field_filler_;
650 
651   base::circular_deque<std::string> autofilled_form_signatures_;
652 
653   // Handles queries and uploads to Autofill servers. Will be NULL if
654   // the download manager functionality is disabled.
655   std::unique_ptr<AutofillDownloadManager> download_manager_;
656 
657   // Handles single-field autocomplete form data.
658   // May be NULL.  NULL indicates OTR.
659   base::WeakPtr<AutocompleteHistoryManager> autocomplete_history_manager_;
660 
661   // Utility for logging URL keyed metrics.
662   std::unique_ptr<AutofillMetrics::FormInteractionsUkmLogger>
663       form_interactions_ukm_logger_;
664 
665   // Utilities for logging form events.
666   std::unique_ptr<AddressFormEventLogger> address_form_event_logger_;
667   std::unique_ptr<CreditCardFormEventLogger> credit_card_form_event_logger_;
668 
669   // Have we logged whether Autofill is enabled for this page load?
670   bool has_logged_autofill_enabled_ = false;
671   // Have we logged an address suggestions count metric for this page?
672   bool has_logged_address_suggestions_count_ = false;
673   // Have we shown Autofill suggestions at least once?
674   bool did_show_suggestions_ = false;
675   // Has the user manually edited at least one form field among the autofillable
676   // ones?
677   bool user_did_type_ = false;
678   // Has the user autofilled a form on this page?
679   bool user_did_autofill_ = false;
680   // Has the user edited a field that was previously autofilled?
681   bool user_did_edit_autofilled_field_ = false;
682 
683   // Does |this| have any parsed forms?
684   bool has_parsed_forms_ = false;
685   // Is there a field with autocomplete="one-time-code" observed?
686   bool has_observed_one_time_code_field_ = false;
687   // Is there a field with phone number collection observed?
688   bool has_observed_phone_number_field_ = false;
689 
690   // When the user first interacted with a potentially fillable form on this
691   // page.
692   base::TimeTicks initial_interaction_timestamp_;
693 
694   // A copy of the currently interacted form data.
695   std::unique_ptr<FormData> pending_form_data_;
696 
697   // The credit card access manager, used to access local and server cards.
698   std::unique_ptr<CreditCardAccessManager> credit_card_access_manager_;
699 
700   // The autofill offer manager, used to to retrieve offers for card
701   // suggestions.
702   AutofillOfferManager* offer_manager_;
703 
704   // Collected information about the autofill form where a credit card will be
705   // filled.
706   AutofillDriver::RendererFormDataAction credit_card_action_;
707   int credit_card_query_id_ = -1;
708   FormData credit_card_form_;
709   FormFieldData credit_card_field_;
710   CreditCard credit_card_;
711   base::string16 last_unlocked_credit_card_cvc_;
712 
713   // Ablation experiment turns off autofill, but logging still has to be kept
714   // for metrics analysis.
715   bool enable_ablation_logging_ = false;
716 
717   // Suggestion backend ID to ID mapping. We keep two maps to convert back and
718   // forth. These should be used only by BackendIDToInt and IntToBackendID.
719   // Note that the integers are not frontend IDs.
720   mutable std::map<std::string, int> backend_to_int_map_;
721   mutable std::map<int, std::string> int_to_backend_map_;
722 
723   // Delegate to perform external processing (display, selection) on
724   // our behalf.  Weak.
725   AutofillExternalDelegate* external_delegate_ = nullptr;
726 
727   // Delegate used in test to get notifications on certain events.
728   AutofillManagerTestDelegate* test_delegate_ = nullptr;
729 
730   // A map of form names to FillingContext instances used to make refill
731   // attempts for dynamic forms.
732   // TODO(crbug/896689): Remove code duplication once experiment is finished.
733   std::map<FormRendererId, std::unique_ptr<FillingContext>>
734       filling_context_by_renderer_id_;
735   std::map<base::string16, std::unique_ptr<FillingContext>>
736       filling_context_by_unique_name_;
737 
738   // Tracks whether or not rich query encoding is enabled for this client.
739   const bool is_rich_query_enabled_ = false;
740 
741   // Used to record metrics. This should be set at the beginning of the
742   // interaction and re-used throughout the context of this manager.
743   AutofillSyncSigninState sync_state_ = AutofillSyncSigninState::kNumSyncStates;
744 
745   base::WeakPtrFactory<AutofillManager> weak_ptr_factory_{this};
746 
747   friend class AutofillAssistantTest;
748   friend class AutofillManagerTest;
749   friend class AutofillMetricsTest;
750   friend class FormStructureBrowserTest;
751   friend class GetMatchingTypesTest;
752   friend class CreditCardAccessoryControllerTest;
753   DISALLOW_COPY_AND_ASSIGN(AutofillManager);
754 };
755 
756 }  // namespace autofill
757 
758 #endif  // COMPONENTS_AUTOFILL_CORE_BROWSER_AUTOFILL_MANAGER_H_
759