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