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