Home | History | Annotate | Download | only in autofill
      1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
      2 // Use of this source code is governed by a BSD-style license that can be
      3 // found in the LICENSE file.
      4 
      5 #ifndef CHROME_BROWSER_UI_AUTOFILL_AUTOFILL_DIALOG_CONTROLLER_IMPL_H_
      6 #define CHROME_BROWSER_UI_AUTOFILL_AUTOFILL_DIALOG_CONTROLLER_IMPL_H_
      7 
      8 #include <set>
      9 #include <vector>
     10 
     11 #include "base/gtest_prod_util.h"
     12 #include "base/memory/scoped_ptr.h"
     13 #include "base/memory/weak_ptr.h"
     14 #include "base/strings/string16.h"
     15 #include "base/time/time.h"
     16 #include "chrome/browser/ui/autofill/account_chooser_model.h"
     17 #include "chrome/browser/ui/autofill/autofill_dialog_controller.h"
     18 #include "chrome/browser/ui/autofill/autofill_dialog_models.h"
     19 #include "chrome/browser/ui/autofill/autofill_dialog_types.h"
     20 #include "chrome/browser/ui/autofill/autofill_dialog_view_delegate.h"
     21 #include "chrome/browser/ui/autofill/autofill_popup_controller_impl.h"
     22 #include "chrome/browser/ui/autofill/country_combobox_model.h"
     23 #include "components/autofill/content/browser/wallet/wallet_client.h"
     24 #include "components/autofill/content/browser/wallet/wallet_client_delegate.h"
     25 #include "components/autofill/content/browser/wallet/wallet_items.h"
     26 #include "components/autofill/content/browser/wallet/wallet_signin_helper_delegate.h"
     27 #include "components/autofill/core/browser/autofill_client.h"
     28 #include "components/autofill/core/browser/autofill_metrics.h"
     29 #include "components/autofill/core/browser/autofill_popup_delegate.h"
     30 #include "components/autofill/core/browser/field_types.h"
     31 #include "components/autofill/core/browser/form_structure.h"
     32 #include "components/autofill/core/browser/personal_data_manager.h"
     33 #include "components/autofill/core/browser/personal_data_manager_observer.h"
     34 #include "content/public/browser/notification_observer.h"
     35 #include "content/public/browser/notification_registrar.h"
     36 #include "content/public/browser/web_contents_observer.h"
     37 #include "content/public/common/ssl_status.h"
     38 #include "third_party/libaddressinput/chromium/cpp/include/libaddressinput/address_validator.h"
     39 #include "third_party/libaddressinput/chromium/cpp/include/libaddressinput/load_rules_delegate.h"
     40 #include "third_party/skia/include/core/SkColor.h"
     41 #include "ui/base/models/simple_menu_model.h"
     42 #include "ui/base/ui_base_types.h"
     43 #include "ui/gfx/animation/animation_delegate.h"
     44 #include "ui/gfx/animation/linear_animation.h"
     45 #include "url/gurl.h"
     46 
     47 class Profile;
     48 
     49 namespace content {
     50 class WebContents;
     51 }
     52 
     53 namespace autofill {
     54 
     55 class AutofillDataModel;
     56 class AutofillDialogView;
     57 class AutofillPopupControllerImpl;
     58 class DataModelWrapper;
     59 
     60 namespace risk {
     61 class Fingerprint;
     62 }
     63 
     64 namespace wallet {
     65 class WalletSigninHelper;
     66 }
     67 
     68 // This class drives the dialog that appears when a site uses the imperative
     69 // autocomplete API to fill out a form.
     70 class AutofillDialogControllerImpl
     71     : public AutofillDialogViewDelegate,
     72       public AutofillDialogController,
     73       public AutofillPopupDelegate,
     74       public content::NotificationObserver,
     75       public content::WebContentsObserver,
     76       public SuggestionsMenuModelDelegate,
     77       public wallet::WalletClientDelegate,
     78       public wallet::WalletSigninHelperDelegate,
     79       public PersonalDataManagerObserver,
     80       public AccountChooserModelDelegate,
     81       public gfx::AnimationDelegate,
     82       public ::i18n::addressinput::LoadRulesDelegate {
     83  public:
     84   virtual ~AutofillDialogControllerImpl();
     85 
     86   static base::WeakPtr<AutofillDialogControllerImpl> Create(
     87       content::WebContents* contents,
     88       const FormData& form_structure,
     89       const GURL& source_url,
     90       const AutofillClient::ResultCallback& callback);
     91 
     92   // AutofillDialogController implementation.
     93   virtual void Show() OVERRIDE;
     94   virtual void Hide() OVERRIDE;
     95   virtual void TabActivated() OVERRIDE;
     96 
     97   // AutofillDialogViewDelegate implementation.
     98   virtual base::string16 DialogTitle() const OVERRIDE;
     99   virtual base::string16 AccountChooserText() const OVERRIDE;
    100   virtual base::string16 SignInLinkText() const OVERRIDE;
    101   virtual base::string16 SpinnerText() const OVERRIDE;
    102   virtual base::string16 EditSuggestionText() const OVERRIDE;
    103   virtual base::string16 CancelButtonText() const OVERRIDE;
    104   virtual base::string16 ConfirmButtonText() const OVERRIDE;
    105   virtual base::string16 SaveLocallyText() const OVERRIDE;
    106   virtual base::string16 SaveLocallyTooltip() const OVERRIDE;
    107   virtual base::string16 LegalDocumentsText() OVERRIDE;
    108   virtual bool ShouldShowSpinner() const OVERRIDE;
    109   virtual bool ShouldShowAccountChooser() const OVERRIDE;
    110   virtual bool ShouldShowSignInWebView() const OVERRIDE;
    111   virtual GURL SignInUrl() const OVERRIDE;
    112   virtual bool ShouldOfferToSaveInChrome() const OVERRIDE;
    113   virtual bool ShouldSaveInChrome() const OVERRIDE;
    114   virtual ui::MenuModel* MenuModelForAccountChooser() OVERRIDE;
    115   virtual gfx::Image AccountChooserImage() OVERRIDE;
    116   virtual gfx::Image ButtonStripImage() const OVERRIDE;
    117   virtual int GetDialogButtons() const OVERRIDE;
    118   virtual bool IsDialogButtonEnabled(ui::DialogButton button) const OVERRIDE;
    119   virtual DialogOverlayState GetDialogOverlay() OVERRIDE;
    120   virtual const std::vector<gfx::Range>& LegalDocumentLinks() OVERRIDE;
    121   virtual bool SectionIsActive(DialogSection section) const OVERRIDE;
    122   virtual const DetailInputs& RequestedFieldsForSection(DialogSection section)
    123       const OVERRIDE;
    124   virtual ui::ComboboxModel* ComboboxModelForAutofillType(
    125       ServerFieldType type) OVERRIDE;
    126   virtual ui::MenuModel* MenuModelForSection(DialogSection section) OVERRIDE;
    127   virtual base::string16 LabelForSection(DialogSection section) const OVERRIDE;
    128   virtual SuggestionState SuggestionStateForSection(
    129       DialogSection section) OVERRIDE;
    130   virtual FieldIconMap IconsForFields(const FieldValueMap& user_inputs)
    131       const OVERRIDE;
    132   virtual bool FieldControlsIcons(ServerFieldType type) const OVERRIDE;
    133   virtual base::string16 TooltipForField(ServerFieldType type) const OVERRIDE;
    134   virtual bool InputIsEditable(const DetailInput& input, DialogSection section)
    135       OVERRIDE;
    136   virtual base::string16 InputValidityMessage(DialogSection section,
    137                                         ServerFieldType type,
    138                                         const base::string16& value) OVERRIDE;
    139   virtual ValidityMessages InputsAreValid(
    140       DialogSection section, const FieldValueMap& inputs) OVERRIDE;
    141   virtual void UserEditedOrActivatedInput(DialogSection section,
    142                                           ServerFieldType type,
    143                                           gfx::NativeView parent_view,
    144                                           const gfx::Rect& content_bounds,
    145                                           const base::string16& field_contents,
    146                                           bool was_edit) OVERRIDE;
    147   virtual bool HandleKeyPressEventInInput(
    148       const content::NativeWebKeyboardEvent& event) OVERRIDE;
    149   virtual void FocusMoved() OVERRIDE;
    150   virtual bool ShouldShowErrorBubble() const OVERRIDE;
    151   virtual void ViewClosed() OVERRIDE;
    152   virtual std::vector<DialogNotification> CurrentNotifications() OVERRIDE;
    153   virtual void LinkClicked(const GURL& url) OVERRIDE;
    154   virtual void SignInLinkClicked() OVERRIDE;
    155   virtual void NotificationCheckboxStateChanged(DialogNotification::Type type,
    156                                                 bool checked) OVERRIDE;
    157   virtual void LegalDocumentLinkClicked(const gfx::Range& range) OVERRIDE;
    158   virtual bool OnCancel() OVERRIDE;
    159   virtual bool OnAccept() OVERRIDE;
    160   virtual Profile* profile() OVERRIDE;
    161   virtual content::WebContents* GetWebContents() OVERRIDE;
    162 
    163   // AutofillPopupDelegate implementation.
    164   virtual void OnPopupShown() OVERRIDE;
    165   virtual void OnPopupHidden() OVERRIDE;
    166   virtual void DidSelectSuggestion(const base::string16& value,
    167                                    int identifier) OVERRIDE;
    168   virtual void DidAcceptSuggestion(const base::string16& value,
    169                                    int identifier) OVERRIDE;
    170   virtual void RemoveSuggestion(const base::string16& value,
    171                                 int identifier) OVERRIDE;
    172   virtual void ClearPreviewedForm() OVERRIDE;
    173 
    174   // content::NotificationObserver implementation.
    175   virtual void Observe(int type,
    176                        const content::NotificationSource& source,
    177                        const content::NotificationDetails& details) OVERRIDE;
    178 
    179   // SuggestionsMenuModelDelegate implementation.
    180   virtual void SuggestionItemSelected(SuggestionsMenuModel* model,
    181                                       size_t index) OVERRIDE;
    182 
    183   // wallet::WalletClientDelegate implementation.
    184   virtual const AutofillMetrics& GetMetricLogger() const OVERRIDE;
    185   virtual std::string GetRiskData() const OVERRIDE;
    186   virtual std::string GetWalletCookieValue() const OVERRIDE;
    187   virtual bool IsShippingAddressRequired() const OVERRIDE;
    188   virtual void OnDidAcceptLegalDocuments() OVERRIDE;
    189   virtual void OnDidAuthenticateInstrument(bool success) OVERRIDE;
    190   virtual void OnDidGetFullWallet(
    191       scoped_ptr<wallet::FullWallet> full_wallet) OVERRIDE;
    192   virtual void OnDidGetWalletItems(
    193       scoped_ptr<wallet::WalletItems> wallet_items) OVERRIDE;
    194   virtual void OnDidSaveToWallet(
    195       const std::string& instrument_id,
    196       const std::string& address_id,
    197       const std::vector<wallet::RequiredAction>& required_actions,
    198       const std::vector<wallet::FormFieldError>& form_field_errors) OVERRIDE;
    199   virtual void OnWalletError(
    200       wallet::WalletClient::ErrorType error_type) OVERRIDE;
    201 
    202   // PersonalDataManagerObserver implementation.
    203   virtual void OnPersonalDataChanged() OVERRIDE;
    204 
    205   // AccountChooserModelDelegate implementation.
    206   virtual void AccountChoiceChanged() OVERRIDE;
    207   virtual void AddAccount() OVERRIDE;
    208   virtual void UpdateAccountChooserView() OVERRIDE;
    209 
    210   // wallet::WalletSigninHelperDelegate implementation.
    211   virtual void OnPassiveSigninSuccess() OVERRIDE;
    212   virtual void OnPassiveSigninFailure(
    213       const GoogleServiceAuthError& error) OVERRIDE;
    214   virtual void OnDidFetchWalletCookieValue(
    215       const std::string& cookie_value) OVERRIDE;
    216 
    217   // gfx::AnimationDelegate implementation.
    218   virtual void AnimationEnded(const gfx::Animation* animation) OVERRIDE;
    219   virtual void AnimationProgressed(const gfx::Animation* animation) OVERRIDE;
    220 
    221   // ::i18n::addressinput::LoadRulesDelegate implementation.
    222   virtual void OnAddressValidationRulesLoaded(const std::string& country_code,
    223                                               bool success) OVERRIDE;
    224 
    225  protected:
    226   enum DialogSignedInState {
    227     NOT_CHECKED,
    228     REQUIRES_RESPONSE,
    229     REQUIRES_SIGN_IN,
    230     REQUIRES_PASSIVE_SIGN_IN,
    231     SIGNED_IN,
    232     SIGN_IN_DISABLED,
    233   };
    234 
    235   // Exposed for testing.
    236   AutofillDialogControllerImpl(content::WebContents* contents,
    237                                const FormData& form_structure,
    238                                const GURL& source_url,
    239                                const AutofillClient::ResultCallback& callback);
    240 
    241   // Exposed for testing.
    242   AutofillDialogView* view() { return view_.get(); }
    243   virtual AutofillDialogView* CreateView();
    244   ServerFieldType popup_input_type() const {
    245     return popup_input_type_;
    246   }
    247 
    248   // Returns the PersonalDataManager for |profile_|.
    249   virtual PersonalDataManager* GetManager() const;
    250 
    251   // Returns an address validation helper. May be NULL during tests.
    252   virtual ::i18n::addressinput::AddressValidator* GetValidator();
    253 
    254   // Returns the WalletClient* this class uses to talk to Online Wallet. Exposed
    255   // for testing.
    256   const wallet::WalletClient* GetWalletClient() const;
    257   virtual wallet::WalletClient* GetWalletClient();
    258 
    259   // Call to disable communication to Online Wallet for this dialog.
    260   // Exposed for testing.
    261   void DisableWallet(wallet::WalletClient::ErrorType error_type);
    262 
    263   // Returns whether Wallet is the current data source. Exposed for testing.
    264   virtual bool IsPayingWithWallet() const;
    265 
    266   // Asks risk module to asynchronously load fingerprint data. Data will be
    267   // returned via |OnDidLoadRiskFingerprintData()|. Exposed for testing.
    268   virtual void LoadRiskFingerprintData();
    269   virtual void OnDidLoadRiskFingerprintData(
    270       scoped_ptr<risk::Fingerprint> fingerprint);
    271 
    272   // Opens the given URL in a new foreground tab.
    273   virtual void OpenTabWithUrl(const GURL& url);
    274 
    275   // The active billing section for the current state of the dialog (e.g. when
    276   // paying for wallet, the combined credit card + billing address section).
    277   DialogSection ActiveBillingSection() const;
    278 
    279   // Whether |section| was sent into edit mode based on existing data. This
    280   // happens when a user clicks "Edit" or a suggestion is invalid.
    281   virtual bool IsEditingExistingData(DialogSection section) const;
    282 
    283   // Whether the user has chosen to enter all new data in |section|. This
    284   // happens via choosing "Add a new X..." from a section's suggestion menu.
    285   bool IsManuallyEditingSection(DialogSection section) const;
    286 
    287   // Should be called on the Wallet sign-in error.
    288   virtual void OnWalletSigninError();
    289 
    290   // Whether submission is currently waiting for |action| to be handled.
    291   bool IsSubmitPausedOn(wallet::RequiredAction action) const;
    292 
    293   // Shows a new credit card saved bubble and passes ownership of |new_card| and
    294   // |billing_profile| to the bubble. Exposed for testing.
    295   virtual void ShowNewCreditCardBubble(
    296       scoped_ptr<CreditCard> new_card,
    297       scoped_ptr<AutofillProfile> billing_profile);
    298 
    299   // Called when there's nothing left to accept, update, save, or authenticate
    300   // in order to fill |form_structure_| and pass data back to the invoking page.
    301   void DoFinishSubmit();
    302 
    303   // Delays enabling submit button for a short period of time. Exposed for
    304   // testing.
    305   virtual void SubmitButtonDelayBegin();
    306 
    307   // Ends the delay for enabling the submit button. Called only from tests.
    308   // Without this method, the tests would have to wait for the delay timer to
    309   // finish, which would be flaky.
    310   void SubmitButtonDelayEndForTesting();
    311 
    312   // Resets |last_wallet_items_fetch_timestamp_| for testing.
    313   void ClearLastWalletItemsFetchTimestampForTesting();
    314 
    315   // Allows tests to inspect the state of the account chooser.
    316   AccountChooserModel* AccountChooserModelForTesting();
    317 
    318   // Returns whether |url| matches the sign in continue URL. If so, also fills
    319   // in |user_index| with the index of the user account that just signed in.
    320   virtual bool IsSignInContinueUrl(const GURL& url, size_t* user_index) const;
    321 
    322   // Whether the user is known to be signed in.
    323   DialogSignedInState SignedInState() const;
    324 
    325  private:
    326   FRIEND_TEST_ALL_PREFIXES(AutofillDialogControllerI18nTest,
    327                            CorrectCountryFromInputs);
    328 
    329   // Initializes or updates |suggested_cc_| et al.
    330   void SuggestionsUpdated();
    331 
    332   // Starts fetching the wallet items from Online Wallet.
    333   void GetWalletItems();
    334 
    335   // Stop showing sign in flow.
    336   void HideSignIn();
    337 
    338   // Handles the SignedInState() on Wallet or sign-in state update.
    339   // Triggers the user name fetch and passive sign-in.
    340   void SignedInStateUpdated();
    341 
    342   // Refreshes the model on Wallet or sign-in state update.
    343   void OnWalletOrSigninUpdate();
    344 
    345   // Called when a Save or Update call to Wallet has validation errors.
    346   void OnWalletFormFieldError(
    347       const std::vector<wallet::FormFieldError>& form_field_errors);
    348 
    349   // Calculates |legal_documents_text_| and |legal_document_link_ranges_|.
    350   void ConstructLegalDocumentsText();
    351 
    352   // Clears previously entered manual input and removes |section| from
    353   // |section_editing_state_|. Does not update the view.
    354   void ResetSectionInput(DialogSection section);
    355 
    356   // Force |section| into edit mode if the current suggestion is invalid.
    357   void ShowEditUiIfBadSuggestion(DialogSection section);
    358 
    359   // Whether the |value| of |input| should be preserved on account change.
    360   bool InputWasEdited(ServerFieldType type,
    361                       const base::string16& value);
    362 
    363   // Takes a snapshot of the newly inputted user data in |view_| (if it exists).
    364   FieldValueMap TakeUserInputSnapshot();
    365 
    366   // Fills the detail inputs from a previously taken user input snapshot. Does
    367   // not update the view.
    368   void RestoreUserInputFromSnapshot(const FieldValueMap& snapshot);
    369 
    370   // Tells the view to update |section|.
    371   void UpdateSection(DialogSection section);
    372 
    373   // Tells |view_| to update the validity status of its detail inputs (if
    374   // |view_| is non-null). Currently this is used solely for highlighting
    375   // invalid suggestions, so if no sections are based on existing data,
    376   // |view_->UpdateForErrors()| is not called.
    377   void UpdateForErrors();
    378 
    379   // Renders and returns one frame of the generated card animation.
    380   gfx::Image GetGeneratedCardImage(const base::string16& card_number,
    381                                    const base::string16& name,
    382                                    const SkColor& gradient_top,
    383                                    const SkColor& gradient_bottom);
    384 
    385   // Kicks off |card_scrambling_refresher_|.
    386   void StartCardScramblingRefresher();
    387 
    388   // Changes |scrambled_card_number_| and pushes an update to the view.
    389   void RefreshCardScramblingOverlay();
    390 
    391   // Tells the view to update the overlay.
    392   void PushOverlayUpdate();
    393 
    394   // Creates a DataModelWrapper item for the item that's checked in the
    395   // suggestion model for |section|. This may represent Autofill
    396   // data or Wallet data, depending on whether Wallet is currently enabled.
    397   scoped_ptr<DataModelWrapper> CreateWrapper(DialogSection section);
    398 
    399   // Helper to return the current Wallet instrument or address. If the dialog
    400   // isn't using Wallet or the user is adding a new instrument or address, NULL
    401   // will be returned.
    402   const wallet::WalletItems::MaskedInstrument* ActiveInstrument() const;
    403   const wallet::Address* ActiveShippingAddress() const;
    404 
    405   // Fills in |section|-related fields in |output_| according to the state of
    406   // |view_|.
    407   void FillOutputForSection(DialogSection section);
    408   // As above, but uses |compare| to determine whether a DetailInput matches
    409   // a field. Saves any new Autofill data to the PersonalDataManager.
    410   void FillOutputForSectionWithComparator(
    411       DialogSection section,
    412       const FormStructure::InputFieldComparator& compare);
    413 
    414   // Returns whether |form_structure|_| has any fields that match the fieldset
    415   // represented by |section|.
    416   bool FormStructureCaresAboutSection(DialogSection section) const;
    417 
    418   // Finds all fields of the given |type| in |form_structure_|, if any, and sets
    419   // each field's value to |output|.
    420   void SetOutputForFieldsOfType(ServerFieldType type,
    421                                 const base::string16& output);
    422 
    423   // Gets the value for |type| in |section|, whether it comes from manual user
    424   // input or the active suggestion.
    425   base::string16 GetValueFromSection(DialogSection section,
    426                                      ServerFieldType type);
    427 
    428   // Returns whether the given section can accept an address with the given
    429   // country code.
    430   bool CanAcceptCountry(DialogSection section, const std::string& country_code);
    431 
    432   // Whether |profile| should be suggested for |section|.
    433   bool ShouldSuggestProfile(DialogSection section,
    434                             const AutofillProfile& profile);
    435 
    436   // Gets the SuggestionsMenuModel for |section|.
    437   SuggestionsMenuModel* SuggestionsMenuModelForSection(DialogSection section);
    438   const SuggestionsMenuModel* SuggestionsMenuModelForSection(
    439       DialogSection section) const;
    440   // And the reverse.
    441   DialogSection SectionForSuggestionsMenuModel(
    442       const SuggestionsMenuModel& model);
    443 
    444   // Gets the CountryComboboxModel for |section|.
    445   CountryComboboxModel* CountryComboboxModelForSection(DialogSection section);
    446 
    447   // Clears and builds the inputs in |section| for |country_name|.
    448   // When |should_clobber| is false, and the view's country value matches
    449   // |country_name|, the inputs won't be rebuilt.
    450   bool RebuildInputsForCountry(DialogSection section,
    451                                const base::string16& country_name,
    452                                bool should_clobber);
    453 
    454   // Suggested text and icons for sections. Suggestion text is used to show an
    455   // abridged overview of the currently used suggestion. Extra text is used when
    456   // part of a section is suggested but part must be manually input (e.g. during
    457   // a CVC challenge or when using Autofill's CC section [never stores CVC]).
    458   bool SuggestionTextForSection(DialogSection section,
    459                                 base::string16* vertically_compact,
    460                                 base::string16* horizontally_compact);
    461   base::string16 RequiredActionTextForSection(DialogSection section) const;
    462   gfx::Image SuggestionIconForSection(DialogSection section);
    463   base::string16 ExtraSuggestionTextForSection(DialogSection section) const;
    464   gfx::Image ExtraSuggestionIconForSection(DialogSection section);
    465 
    466   // Suggests address completions using the downloaded i18n validation rules.
    467   // Stores the suggestions in |i18n_validator_suggestions_|.
    468   void GetI18nValidatorSuggestions(DialogSection section,
    469                                    ServerFieldType type,
    470                                    std::vector<base::string16>* popup_values,
    471                                    std::vector<base::string16>* popup_labels,
    472                                    std::vector<base::string16>* popup_icons);
    473 
    474   // Like RequestedFieldsForSection, but returns a pointer.
    475   DetailInputs* MutableRequestedFieldsForSection(DialogSection section);
    476 
    477   // Returns a pointer to the language code that should be used for formatting
    478   // the address in |section| for display. Returns NULL for a non-address
    479   // |section|.
    480   std::string* MutableAddressLanguageCodeForSection(DialogSection section);
    481 
    482   // Returns the language code that should be used for formatting the address in
    483   // |section|. Returns an empty string for a non-address |section|.
    484   std::string AddressLanguageCodeForSection(DialogSection section);
    485 
    486   // Returns just the |type| attributes of RequestedFieldsForSection(section).
    487   std::vector<ServerFieldType> RequestedTypesForSection(DialogSection section)
    488       const;
    489 
    490   // Returns the country code (e.g. "US") for |section|.
    491   std::string CountryCodeForSection(DialogSection section);
    492 
    493   // Hides |popup_controller_|'s popup view, if it exists.
    494   void HidePopup();
    495 
    496   // Set whether the currently editing |section| was originally based on
    497   // existing Wallet or Autofill data.
    498   void SetEditingExistingData(DialogSection section, bool editing);
    499 
    500   // Whether the user has chosen to enter all new data in at least one section.
    501   bool IsManuallyEditingAnySection() const;
    502 
    503   // Returns validity message for a given credit card number.
    504   base::string16 CreditCardNumberValidityMessage(
    505       const base::string16& number) const;
    506 
    507   // Whether all of the input fields currently showing in the dialog have valid
    508   // contents. This validates only by checking "sure" messages, i.e. messages
    509   // that would have been displayed to the user during editing, as opposed to
    510   // submission.
    511   bool AllSectionsAreValid();
    512 
    513   // Whether all of the input fields currently showing in the given |section| of
    514   // the dialog have valid contents. This validates only by checking "sure"
    515   // messages - see AllSectionsAreValid.
    516   bool SectionIsValid(DialogSection section);
    517 
    518   // Whether validation rules for |section| are loaded.
    519   bool RulesAreLoaded(DialogSection section);
    520 
    521   // Whether the currently active credit card expiration date is valid.
    522   bool IsCreditCardExpirationValid(const base::string16& year,
    523                                    const base::string16& month) const;
    524 
    525   // Returns true if we should reject the given credit card brand. |type| should
    526   // be a display string, such as "Visa".
    527   bool ShouldDisallowCcType(const base::string16& type) const;
    528 
    529   // Returns true if |profile| has an address we can be sure is invalid.
    530   // Profiles with invalid addresses are not suggested in the dropdown menu for
    531   // billing and shipping addresses.
    532   bool HasInvalidAddress(const AutofillProfile& profile);
    533 
    534   // Returns true if |key| refers to a suggestion, as opposed to some control
    535   // menu item.
    536   bool IsASuggestionItemKey(const std::string& key) const;
    537 
    538   // Returns whether Autofill is enabled for |profile_|.
    539   bool IsAutofillEnabled() const;
    540 
    541   // Whether the billing section should be used to fill in the shipping details.
    542   bool ShouldUseBillingForShipping();
    543 
    544   // Whether the user wishes to save information locally to Autofill.
    545   bool ShouldSaveDetailsLocally();
    546 
    547   // Change whether the controller is currently submitting details to Autofill
    548   // or Online Wallet (|is_submitting_|) and update the view.
    549   void SetIsSubmitting(bool submitting);
    550 
    551   // Whether the user has accepted all the current legal documents' terms.
    552   bool AreLegalDocumentsCurrent() const;
    553 
    554   // Accepts any pending legal documents now that the user has pressed Submit.
    555   void AcceptLegalTerms();
    556 
    557   // Start the submit proccess to interact with Online Wallet (might do various
    558   // things like accept documents, save details, update details, respond to
    559   // required actions, etc.).
    560   void SubmitWithWallet();
    561 
    562   // Creates an instrument based on |views_|' contents.
    563   scoped_ptr<wallet::Instrument> CreateTransientInstrument();
    564 
    565   // Creates an address based on the contents of |view_|.
    566   scoped_ptr<wallet::Address> CreateTransientAddress();
    567 
    568   // Gets a full wallet from Online Wallet so the user can purchase something.
    569   // This information is decoded to reveal a fronting (proxy) card.
    570   void GetFullWallet();
    571 
    572   // Updates the state of the controller and |view_| based on any required
    573   // actions returned by Save or Update calls to Wallet.
    574   void HandleSaveOrUpdateRequiredActions(
    575       const std::vector<wallet::RequiredAction>& required_actions);
    576 
    577   // Shows a card generation overlay if necessary, then calls DoFinishSubmit.
    578   void FinishSubmit();
    579 
    580   // Writes to prefs the choice of AutofillDataModel for |section|.
    581   void PersistAutofillChoice(DialogSection section,
    582                              const std::string& guid);
    583 
    584   // Sets the outparams to the default AutofillDataModel for |section| (which is
    585   // the first one in the menu that is a suggestion item).
    586   void GetDefaultAutofillChoice(DialogSection section,
    587                                 std::string* guid);
    588 
    589   // Reads from prefs the choice of AutofillDataModel for |section|. Returns
    590   // whether there was a setting to read.
    591   bool GetAutofillChoice(DialogSection section,
    592                          std::string* guid);
    593 
    594   // Logs metrics when the dialog is submitted.
    595   void LogOnFinishSubmitMetrics();
    596 
    597   // Logs metrics when the dialog is canceled.
    598   void LogOnCancelMetrics();
    599 
    600   // Logs metrics when the edit ui is shown for the given |section|.
    601   void LogEditUiShownMetric(DialogSection section);
    602 
    603   // Logs metrics when a suggestion item from the given |model| is selected.
    604   void LogSuggestionItemSelectedMetric(const SuggestionsMenuModel& model);
    605 
    606   // Logs the time elapsed from when the dialog was shown to when the user could
    607   // interact with it.
    608   void LogDialogLatencyToShow();
    609 
    610   // Returns the metric corresponding to the user's initial state when
    611   // interacting with this dialog.
    612   AutofillMetrics::DialogInitialUserStateMetric GetInitialUserState() const;
    613 
    614   // Shows an educational bubble if a new credit card was saved or the first few
    615   // times an Online Wallet fronting card was generated.
    616   void MaybeShowCreditCardBubble();
    617 
    618   // Called when the delay for enabling the submit button ends.
    619   void OnSubmitButtonDelayEnd();
    620 
    621   // Gets the user's current Wallet cookie (gdToken) from the cookie jar.
    622   void FetchWalletCookie();
    623 
    624   // The |profile| for |contents_|.
    625   Profile* const profile_;
    626 
    627   // For logging UMA metrics.
    628   const AutofillMetrics metric_logger_;
    629   base::Time dialog_shown_timestamp_;
    630   AutofillMetrics::DialogInitialUserStateMetric initial_user_state_;
    631 
    632   FormStructure form_structure_;
    633 
    634   // Whether the URL visible to the user when this dialog was requested to be
    635   // invoked is the same as |source_url_|.
    636   bool invoked_from_same_origin_;
    637 
    638   // The URL of the invoking site.
    639   GURL source_url_;
    640 
    641   // The callback via which we return the collected data.
    642   AutofillClient::ResultCallback callback_;
    643 
    644   // The AccountChooserModel acts as the MenuModel for the account chooser,
    645   // and also tracks which data source the dialog is using.
    646   scoped_ptr<AccountChooserModel> account_chooser_model_;
    647 
    648   // The sign-in helper to fetch the user's Wallet cookie and to perform passive
    649   // sign-in. The helper is set only during fetch/sign-in, and NULL otherwise.
    650   scoped_ptr<wallet::WalletSigninHelper> signin_helper_;
    651 
    652   // A client to talk to the Online Wallet API.
    653   wallet::WalletClient wallet_client_;
    654 
    655   // A helper to validate international address input.
    656   scoped_ptr< ::i18n::addressinput::AddressValidator> validator_;
    657 
    658   // True if |this| has ever called GetWalletItems().
    659   bool wallet_items_requested_;
    660 
    661   // True when the user has clicked the "Use Wallet" link and we're waiting to
    662   // figure out whether we need to ask them to actively sign in.
    663   bool handling_use_wallet_link_click_;
    664 
    665   // True when the current WalletItems has a passive auth action which was
    666   // attempted and failed.
    667   bool passive_failed_;
    668 
    669   // Recently received items retrieved via |wallet_client_|.
    670   scoped_ptr<wallet::WalletItems> wallet_items_;
    671   scoped_ptr<wallet::FullWallet> full_wallet_;
    672 
    673   // The default active instrument and shipping address object IDs as of the
    674   // last time Wallet items were fetched. These variables are only set
    675   // (i.e. non-empty) when the Wallet items are being re-fetched.
    676   std::string previous_default_instrument_id_;
    677   std::string previous_default_shipping_address_id_;
    678   // The last active instrument and shipping address object IDs. These
    679   // variables are only set (i.e. non-empty) when the Wallet items are being
    680   // re-fetched.
    681   std::string previously_selected_instrument_id_;
    682   std::string previously_selected_shipping_address_id_;
    683 
    684   // When the Wallet items were last fetched.
    685   base::TimeTicks last_wallet_items_fetch_timestamp_;
    686 
    687   // Local machine signals to pass along on each request to trigger (or
    688   // discourage) risk challenges; sent if the user is up to date on legal docs.
    689   std::string risk_data_;
    690 
    691   // The text to display when the user is accepting new terms of service, etc.
    692   base::string16 legal_documents_text_;
    693   // The ranges within |legal_documents_text_| to linkify.
    694   std::vector<gfx::Range> legal_document_link_ranges_;
    695 
    696   // The instrument and address IDs from the Online Wallet server to be used
    697   // when getting a full wallet.
    698   std::string active_instrument_id_;
    699   std::string active_address_id_;
    700 
    701   // The fields for billing and shipping which the page has actually requested.
    702   DetailInputs requested_cc_fields_;
    703   DetailInputs requested_billing_fields_;
    704   DetailInputs requested_cc_billing_fields_;
    705   DetailInputs requested_shipping_fields_;
    706 
    707   // The BCP 47 language codes used for formatting the addresses for display.
    708   std::string billing_address_language_code_;
    709   std::string shipping_address_language_code_;
    710 
    711   // Models for the credit card expiration inputs.
    712   MonthComboboxModel cc_exp_month_combobox_model_;
    713   YearComboboxModel cc_exp_year_combobox_model_;
    714 
    715   // Models for country input.
    716   scoped_ptr<CountryComboboxModel> billing_country_combobox_model_;
    717   scoped_ptr<CountryComboboxModel> shipping_country_combobox_model_;
    718 
    719   // Models for the suggestion views.
    720   SuggestionsMenuModel suggested_cc_;
    721   SuggestionsMenuModel suggested_billing_;
    722   SuggestionsMenuModel suggested_cc_billing_;
    723   SuggestionsMenuModel suggested_shipping_;
    724 
    725   // The set of values for cc-type that the site accepts. Empty means all types
    726   // are accepted.
    727   std::set<base::string16> acceptable_cc_types_;
    728 
    729   // |DialogSection|s that are in edit mode that are based on existing data.
    730   std::set<DialogSection> section_editing_state_;
    731 
    732   // Sections that need to be validated when their validation rules load.
    733   std::set<DialogSection> needs_validation_;
    734 
    735   // Whether |form_structure_| has asked for any details that would indicate
    736   // we should show a shipping section.
    737   bool cares_about_shipping_;
    738 
    739   // The GUIDs for the currently showing unverified profiles popup.
    740   std::vector<PersonalDataManager::GUIDPair> popup_guids_;
    741 
    742   // The autofill suggestions based on downloaded i18n validation rules.
    743   std::vector< ::i18n::addressinput::AddressData> i18n_validator_suggestions_;
    744 
    745   // The controller for the currently showing popup (which helps users when
    746   // they're manually filling the dialog).
    747   base::WeakPtr<AutofillPopupControllerImpl> popup_controller_;
    748 
    749   // The type of the visible Autofill popup input (or UNKNOWN_TYPE if none).
    750   ServerFieldType popup_input_type_;
    751 
    752   scoped_ptr<AutofillDialogView> view_;
    753 
    754   // A NotificationRegistrar for tracking the completion of sign-in.
    755   content::NotificationRegistrar signin_registrar_;
    756 
    757   // Set to true when the user presses the sign in link, until we're ready to
    758   // show the normal dialog again. This is used to hide the buttons while
    759   // the spinner is showing after an explicit sign in.
    760   bool waiting_for_explicit_sign_in_response_;
    761 
    762   // Whether a user accepted legal documents while this dialog is running.
    763   bool has_accepted_legal_documents_;
    764 
    765   // True after the user first accepts the dialog and presses "Submit". May
    766   // continue to be true while processing required actions.
    767   bool is_submitting_;
    768 
    769   // True if the last call to |GetFullWallet()| returned a
    770   // CHOOSE_ANOTHER_INSTRUMENT_OR_ADDRESS required action, indicating that the
    771   // selected instrument or address had become invalid since it was originally
    772   // returned in |GetWalletItems()|.
    773   bool choose_another_instrument_or_address_;
    774 
    775   // Whether or not the server side validation errors returned by Wallet were
    776   // recoverable.
    777   bool wallet_server_validation_recoverable_;
    778 
    779   // Whether |callback_| was Run() with a filled |form_structure_|.
    780   bool data_was_passed_back_;
    781 
    782   typedef std::map<ServerFieldType,
    783       std::pair<base::string16, base::string16> > TypeErrorInputMap;
    784   typedef std::map<DialogSection, TypeErrorInputMap> WalletValidationErrors;
    785   // Wallet validation errors. section->type->(error_msg, input_value).
    786   WalletValidationErrors wallet_errors_;
    787 
    788   // The notification that describes the current wallet error, if any.
    789   scoped_ptr<DialogNotification> wallet_error_notification_;
    790 
    791   // Whether the latency to display to the UI was logged to UMA yet.
    792   bool was_ui_latency_logged_;
    793 
    794   // The Google Wallet cookie value, set as an authorization header on requests
    795   // to Wallet.
    796   std::string wallet_cookie_value_;
    797 
    798   // A map from dialog sections to the GUID of a newly saved Autofill data
    799   // models for that section. No entries present that don't have newly saved
    800   // data models.
    801   std::map<DialogSection, std::string> newly_saved_data_model_guids_;
    802 
    803   // Populated if the user chose to save a newly inputted credit card. Used to
    804   // show a bubble as the dialog closes to confirm a user's new card info was
    805   // saved. Never populated while incognito (as nothing's actually saved).
    806   scoped_ptr<CreditCard> newly_saved_card_;
    807 
    808   // The last four digits of the backing card used for the current run of the
    809   // dialog. Only applies to Wallet and is populated on submit.
    810   base::string16 backing_card_last_four_;
    811 
    812   // The timer that delays enabling submit button for a short period of time on
    813   // startup.
    814   base::OneShotTimer<AutofillDialogControllerImpl> submit_button_delay_timer_;
    815 
    816   // The card scrambling animation displays a random number in place of an
    817   // actual credit card number. This is that random number.
    818   base::string16 scrambled_card_number_;
    819 
    820   // Two timers to deal with the card scrambling animation. The first provides
    821   // a one second delay before the numbers start scrambling. The second controls
    822   // the rate of refresh for the number scrambling.
    823   base::OneShotTimer<AutofillDialogControllerImpl> card_scrambling_delay_;
    824   base::RepeatingTimer<AutofillDialogControllerImpl> card_scrambling_refresher_;
    825 
    826   // An animation which controls the background fade when the card is done
    827   // scrambling.
    828   gfx::LinearAnimation card_generated_animation_;
    829 
    830   // A username string we display in the card scrambling/generated overlay.
    831   base::string16 submitted_cardholder_name_;
    832 
    833   base::WeakPtrFactory<AutofillDialogControllerImpl> weak_ptr_factory_;
    834 
    835   DISALLOW_COPY_AND_ASSIGN(AutofillDialogControllerImpl);
    836 };
    837 
    838 }  // namespace autofill
    839 
    840 #endif  // CHROME_BROWSER_UI_AUTOFILL_AUTOFILL_DIALOG_CONTROLLER_IMPL_H_
    841