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