1 // Copyright 2013 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "chrome/browser/ui/autofill/autofill_dialog_controller_impl.h"
11 #include "base/bind.h"
12 #include "base/bind_helpers.h"
13 #include "base/i18n/case_conversion.h"
14 #include "base/i18n/rtl.h"
15 #include "base/logging.h"
16 #include "base/prefs/pref_registry_simple.h"
17 #include "base/prefs/pref_service.h"
18 #include "base/prefs/scoped_user_pref_update.h"
19 #include "base/rand_util.h"
20 #include "base/strings/string_number_conversions.h"
21 #include "base/strings/string_split.h"
22 #include "base/strings/utf_string_conversions.h"
23 #include "base/time/time.h"
24 #include "chrome/browser/autofill/personal_data_manager_factory.h"
25 #include "chrome/browser/autofill/risk_util.h"
26 #include "chrome/browser/autofill/validation_rules_storage_factory.h"
27 #include "chrome/browser/browser_process.h"
28 #include "chrome/browser/profiles/profile.h"
29 #include "chrome/browser/ui/autofill/autofill_dialog_common.h"
30 #include "chrome/browser/ui/autofill/autofill_dialog_i18n_input.h"
31 #include "chrome/browser/ui/autofill/autofill_dialog_view.h"
32 #include "chrome/browser/ui/autofill/data_model_wrapper.h"
33 #include "chrome/browser/ui/autofill/generated_credit_card_bubble_controller.h"
34 #include "chrome/browser/ui/autofill/new_credit_card_bubble_controller.h"
35 #include "chrome/browser/ui/browser.h"
36 #include "chrome/browser/ui/browser_finder.h"
37 #include "chrome/browser/ui/browser_navigator.h"
38 #include "chrome/browser/ui/browser_window.h"
39 #include "chrome/common/pref_names.h"
40 #include "chrome/common/render_messages.h"
41 #include "chrome/common/url_constants.h"
42 #include "chrome/grit/chromium_strings.h"
43 #include "chrome/grit/generated_resources.h"
44 #include "components/autofill/content/browser/wallet/form_field_error.h"
45 #include "components/autofill/content/browser/wallet/full_wallet.h"
46 #include "components/autofill/content/browser/wallet/gaia_account.h"
47 #include "components/autofill/content/browser/wallet/instrument.h"
48 #include "components/autofill/content/browser/wallet/wallet_address.h"
49 #include "components/autofill/content/browser/wallet/wallet_items.h"
50 #include "components/autofill/content/browser/wallet/wallet_service_url.h"
51 #include "components/autofill/content/browser/wallet/wallet_signin_helper.h"
52 #include "components/autofill/core/browser/address_i18n.h"
53 #include "components/autofill/core/browser/autofill_country.h"
54 #include "components/autofill/core/browser/autofill_data_model.h"
55 #include "components/autofill/core/browser/autofill_manager.h"
56 #include "components/autofill/core/browser/autofill_type.h"
57 #include "components/autofill/core/browser/detail_input.h"
58 #include "components/autofill/core/browser/field_types.h"
59 #include "components/autofill/core/browser/personal_data_manager.h"
60 #include "components/autofill/core/browser/phone_number_i18n.h"
61 #include "components/autofill/core/browser/server_field_types_util.h"
62 #include "components/autofill/core/browser/validation.h"
63 #include "components/autofill/core/common/autofill_pref_names.h"
64 #include "components/autofill/core/common/form_data.h"
65 #include "components/pref_registry/pref_registry_syncable.h"
66 #include "content/public/browser/browser_thread.h"
67 #include "content/public/browser/geolocation_provider.h"
68 #include "content/public/browser/navigation_controller.h"
69 #include "content/public/browser/navigation_details.h"
70 #include "content/public/browser/navigation_entry.h"
71 #include "content/public/browser/notification_service.h"
72 #include "content/public/browser/notification_types.h"
73 #include "content/public/browser/render_view_host.h"
74 #include "content/public/browser/web_contents.h"
75 #include "content/public/common/url_constants.h"
76 #include "grit/components_scaled_resources.h"
77 #include "grit/components_strings.h"
78 #include "grit/platform_locale_settings.h"
79 #include "grit/theme_resources.h"
80 #include "net/cert/cert_status_flags.h"
81 #include "third_party/libaddressinput/chromium/chrome_metadata_source.h"
82 #include "third_party/libaddressinput/chromium/chrome_storage_impl.h"
83 #include "third_party/libaddressinput/messages.h"
84 #include "third_party/libaddressinput/src/cpp/include/libaddressinput/address_data.h"
85 #include "third_party/libaddressinput/src/cpp/include/libaddressinput/address_field.h"
86 #include "third_party/libaddressinput/src/cpp/include/libaddressinput/address_problem.h"
87 #include "third_party/libaddressinput/src/cpp/include/libaddressinput/localization.h"
88 #include "ui/base/l10n/l10n_util.h"
89 #include "ui/base/models/combobox_model.h"
90 #include "ui/base/resource/resource_bundle.h"
91 #include "ui/gfx/canvas.h"
92 #include "ui/gfx/geometry/vector2d.h"
93 #include "ui/gfx/image/image_skia_operations.h"
94 #include "ui/gfx/skia_util.h"
96 using ::i18n::addressinput::AddressData
;
97 using ::i18n::addressinput::AddressField
;
98 using ::i18n::addressinput::AddressProblem
;
99 using ::i18n::addressinput::ADMIN_AREA
;
100 using ::i18n::addressinput::DEPENDENT_LOCALITY
;
101 using ::i18n::addressinput::FieldProblemMap
;
102 using ::i18n::addressinput::Localization
;
103 using ::i18n::addressinput::MISSING_REQUIRED_FIELD
;
109 const char kAddNewItemKey
[] = "add-new-item";
110 const char kManageItemsKey
[] = "manage-items";
111 const char kSameAsBillingKey
[] = "same-as-billing";
113 // URLs for Wallet error messages.
114 const char kBuyerLegalAddressStatusUrl
[] =
115 "https://wallet.google.com/manage/settings";
116 const char kKnowYourCustomerStatusUrl
[] = "https://wallet.google.com/kyc";
118 // Keys for the kAutofillDialogAutofillDefault pref dictionary (do not change
120 const char kGuidPrefKey
[] = "guid";
122 // This string is stored along with saved addresses and credit cards in the
123 // WebDB, and hence should not be modified, so that it remains consistent over
125 const char kAutofillDialogOrigin
[] = "Chrome Autofill dialog";
127 // HSL shift to gray out an image.
128 const color_utils::HSL kGrayImageShift
= {-1, 0, 0.8};
130 // Limit Wallet items refresh rate to at most once per minute.
131 const int64 kWalletItemsRefreshRateSeconds
= 60;
133 // The number of milliseconds to delay enabling the submit button after showing
134 // the dialog. This delay prevents users from accidentally clicking the submit
135 // button on startup.
136 const int kSubmitButtonDelayMs
= 1000;
138 // A helper class to make sure an AutofillDialogView knows when a series of
139 // updates is incoming.
140 class ScopedViewUpdates
{
142 explicit ScopedViewUpdates(AutofillDialogView
* view
) : view_(view
) {
144 view_
->UpdatesStarted();
147 ~ScopedViewUpdates() {
149 view_
->UpdatesFinished();
153 AutofillDialogView
* view_
;
155 DISALLOW_COPY_AND_ASSIGN(ScopedViewUpdates
);
158 base::string16
NullGetInfo(const AutofillType
& type
) {
159 return base::string16();
162 // Extract |type| from |inputs| using |section| to determine whether the info
163 // should be billing or shipping specific (for sections with address info).
164 base::string16
GetInfoFromInputs(const FieldValueMap
& inputs
,
165 DialogSection section
,
166 const AutofillType
& type
) {
167 ServerFieldType field_type
= type
.GetStorableType();
168 if (section
!= SECTION_SHIPPING
)
169 field_type
= AutofillType::GetEquivalentBillingFieldType(field_type
);
172 FieldValueMap::const_iterator it
= inputs
.find(field_type
);
173 if (it
!= inputs
.end())
176 if (!info
.empty() && type
.html_type() == HTML_TYPE_COUNTRY_CODE
) {
177 info
= base::ASCIIToUTF16(AutofillCountry::GetCountryCode(
178 info
, g_browser_process
->GetApplicationLocale()));
184 // Returns true if |input| should be used to fill a site-requested |field| which
185 // is notated with a "shipping" tag, for use when the user has decided to use
186 // the billing address as the shipping address.
187 bool ServerTypeMatchesShippingField(ServerFieldType type
,
188 const AutofillField
& field
) {
189 // Equivalent billing field type is used to support UseBillingAsShipping
191 return ServerTypeEncompassesFieldType(
192 type
, AutofillType(AutofillType::GetEquivalentBillingFieldType(
193 field
.Type().GetStorableType())));
196 // Initializes |form_group| from user-entered data.
197 void FillFormGroupFromOutputs(const FieldValueMap
& detail_outputs
,
198 FormGroup
* form_group
) {
199 for (FieldValueMap::const_iterator iter
= detail_outputs
.begin();
200 iter
!= detail_outputs
.end(); ++iter
) {
201 ServerFieldType type
= iter
->first
;
202 if (!iter
->second
.empty()) {
203 form_group
->SetInfo(AutofillType(type
),
205 g_browser_process
->GetApplicationLocale());
210 // Get billing info from |output| and put it into |card|, |cvc|, and |profile|.
211 // These outparams are required because |card|/|profile| accept different types
212 // of raw info, and CreditCard doesn't save CVCs.
213 void GetBillingInfoFromOutputs(const FieldValueMap
& output
,
216 AutofillProfile
* profile
) {
217 for (FieldValueMap::const_iterator it
= output
.begin();
218 it
!= output
.end(); ++it
) {
219 const ServerFieldType type
= it
->first
;
220 base::string16 trimmed
;
221 base::TrimWhitespace(it
->second
, base::TRIM_ALL
, &trimmed
);
223 // Special case CVC as CreditCard just swallows it.
224 if (type
== CREDIT_CARD_VERIFICATION_CODE
) {
226 cvc
->assign(trimmed
);
227 } else if (IsCreditCardType(type
)) {
228 card
->SetRawInfo(type
, trimmed
);
230 // Copy the credit card name to |profile| in addition to |card| as
231 // wallet::Instrument requires a recipient name for its billing address.
232 if (card
&& type
== NAME_FULL
)
233 card
->SetRawInfo(CREDIT_CARD_NAME
, trimmed
);
236 profile
->SetInfo(AutofillType(AutofillType(type
).GetStorableType()),
238 g_browser_process
->GetApplicationLocale());
245 // Returns a string descriptor for a DialogSection, for use with prefs (do not
246 // change these values).
247 std::string
SectionToPrefString(DialogSection section
) {
252 case SECTION_BILLING
:
255 case SECTION_CC_BILLING
:
256 // The SECTION_CC_BILLING section isn't active when using Autofill.
258 return std::string();
260 case SECTION_SHIPPING
:
265 return std::string();
268 // Check if a given MaskedInstrument is allowed for the purchase.
269 bool IsInstrumentAllowed(
270 const wallet::WalletItems::MaskedInstrument
& instrument
) {
271 switch (instrument
.status()) {
272 case wallet::WalletItems::MaskedInstrument::VALID
:
273 case wallet::WalletItems::MaskedInstrument::PENDING
:
274 case wallet::WalletItems::MaskedInstrument::EXPIRED
:
275 case wallet::WalletItems::MaskedInstrument::BILLING_INCOMPLETE
:
282 // Loops through |addresses_| comparing to |address| ignoring ID. If a match
283 // is not found, NULL is returned.
284 const wallet::Address
* FindDuplicateAddress(
285 const std::vector
<wallet::Address
*>& addresses
,
286 const wallet::Address
& address
) {
287 for (size_t i
= 0; i
< addresses
.size(); ++i
) {
288 if (addresses
[i
]->EqualsIgnoreID(address
))
294 bool IsCardHolderNameValidForWallet(const base::string16
& name
) {
295 base::string16 whitespace_collapsed_name
=
296 base::CollapseWhitespace(name
, true);
297 std::vector
<base::string16
> split_name
;
298 base::SplitString(whitespace_collapsed_name
, ' ', &split_name
);
299 return split_name
.size() >= 2;
302 DialogSection
SectionFromLocation(wallet::FormFieldError::Location location
) {
304 case wallet::FormFieldError::PAYMENT_INSTRUMENT
:
305 case wallet::FormFieldError::LEGAL_ADDRESS
:
306 return SECTION_CC_BILLING
;
308 case wallet::FormFieldError::SHIPPING_ADDRESS
:
309 return SECTION_SHIPPING
;
311 case wallet::FormFieldError::UNKNOWN_LOCATION
:
320 scoped_ptr
<DialogNotification
> GetWalletError(
321 wallet::WalletClient::ErrorType error_type
) {
325 switch (error_type
) {
326 case wallet::WalletClient::UNVERIFIED_KNOW_YOUR_CUSTOMER_STATUS
:
327 text
= l10n_util::GetStringUTF16(
328 IDS_AUTOFILL_WALLET_UNVERIFIED_KNOW_YOUR_CUSTOMER_STATUS
);
329 url
= GURL(kKnowYourCustomerStatusUrl
);
332 case wallet::WalletClient::BUYER_LEGAL_ADDRESS_NOT_SUPPORTED
:
333 text
= l10n_util::GetStringUTF16(
334 IDS_AUTOFILL_WALLET_BUYER_COUNTRY_NOT_SUPPORTED
);
335 url
= GURL(kBuyerLegalAddressStatusUrl
);
339 // The notification will not have a link; it's handled in the next
345 scoped_ptr
<DialogNotification
> notification(new DialogNotification(
346 DialogNotification::WALLET_ERROR
,
348 notification
->set_link_url(url
);
349 return notification
.Pass();
355 switch (error_type
) {
356 case wallet::WalletClient::UNSUPPORTED_MERCHANT
:
357 error_ids
= IDS_AUTOFILL_WALLET_UNSUPPORTED_MERCHANT
;
360 case wallet::WalletClient::BAD_REQUEST
:
361 error_ids
= IDS_AUTOFILL_WALLET_UPGRADE_CHROME_ERROR
;
365 case wallet::WalletClient::INVALID_PARAMS
:
366 error_ids
= IDS_AUTOFILL_WALLET_BAD_TRANSACTION_AMOUNT
;
370 case wallet::WalletClient::BUYER_ACCOUNT_ERROR
:
371 error_ids
= IDS_AUTOFILL_WALLET_BUYER_ACCOUNT_ERROR
;
375 case wallet::WalletClient::UNSUPPORTED_API_VERSION
:
376 error_ids
= IDS_AUTOFILL_WALLET_UPGRADE_CHROME_ERROR
;
380 case wallet::WalletClient::SERVICE_UNAVAILABLE
:
381 error_ids
= IDS_AUTOFILL_WALLET_SERVICE_UNAVAILABLE_ERROR
;
385 case wallet::WalletClient::INTERNAL_ERROR
:
386 error_ids
= IDS_AUTOFILL_WALLET_UPGRADE_CHROME_ERROR
;
390 case wallet::WalletClient::MALFORMED_RESPONSE
:
391 error_ids
= IDS_AUTOFILL_WALLET_UNKNOWN_ERROR
;
395 case wallet::WalletClient::NETWORK_ERROR
:
396 error_ids
= IDS_AUTOFILL_WALLET_UNKNOWN_ERROR
;
400 case wallet::WalletClient::UNKNOWN_ERROR
:
401 error_ids
= IDS_AUTOFILL_WALLET_UNKNOWN_ERROR
;
405 case wallet::WalletClient::UNSUPPORTED_USER_AGENT_OR_API_KEY
:
406 error_ids
= IDS_AUTOFILL_WALLET_UNSUPPORTED_AGENT_OR_API_KEY
;
410 case wallet::WalletClient::SPENDING_LIMIT_EXCEEDED
:
411 error_ids
= IDS_AUTOFILL_WALLET_BAD_TRANSACTION_AMOUNT
;
414 // Handled in the prior switch().
415 case wallet::WalletClient::UNVERIFIED_KNOW_YOUR_CUSTOMER_STATUS
:
416 case wallet::WalletClient::BUYER_LEGAL_ADDRESS_NOT_SUPPORTED
:
421 DCHECK_NE(0, error_ids
);
423 // The other error types are strings of the form "XXX. You can pay without
425 scoped_ptr
<DialogNotification
> notification(new DialogNotification(
426 DialogNotification::WALLET_ERROR
,
427 l10n_util::GetStringFUTF16(IDS_AUTOFILL_DIALOG_COMPLETE_WITHOUT_WALLET
,
428 l10n_util::GetStringUTF16(error_ids
))));
431 notification
->set_tooltip_text(
432 l10n_util::GetStringFUTF16(IDS_AUTOFILL_WALLET_ERROR_CODE_TOOLTIP
,
433 base::IntToString16(error_code
)));
436 return notification
.Pass();
439 // Returns the ID of the address or instrument that should be selected in the
440 // UI, given that the |default_id| is currently the default ID on the Wallet
441 // server, |previous_default_id| was the default ID prior to re-fetching the
442 // Wallet data, and |previously_selected_id| was the ID of the item selected in
443 // the dialog prior to re-fetching the Wallet data.
444 std::string
GetIdToSelect(const std::string
& default_id
,
445 const std::string
& previous_default_id
,
446 const std::string
& previously_selected_id
) {
447 // If the default ID changed since the last fetch of the Wallet data, select
448 // it rather than the previously selected item, as the user's intention in
449 // changing the default was probably to use it.
450 if (default_id
!= previous_default_id
)
453 // Otherwise, prefer the previously selected item, if there was one.
454 return !previously_selected_id
.empty() ? previously_selected_id
: default_id
;
457 // Generate a random card number in a user displayable format.
458 base::string16
GenerateRandomCardNumber() {
459 std::string card_number
;
460 for (size_t i
= 0; i
< 4; ++i
) {
461 int part
= base::RandInt(0, 10000);
462 base::StringAppendF(&card_number
, "%04d ", part
);
464 return base::ASCIIToUTF16(card_number
);
467 gfx::Image
CreditCardIconForType(const std::string
& credit_card_type
) {
468 const int input_card_idr
= CreditCard::IconResourceId(credit_card_type
);
469 ui::ResourceBundle
& rb
= ui::ResourceBundle::GetSharedInstance();
470 if (input_card_idr
== IDR_AUTOFILL_CC_GENERIC
) {
471 // When the credit card type is unknown, no image should be shown. However,
472 // to simplify the view code on Mac, save space for the credit card image by
473 // returning a transparent image of the appropriate size. All credit card
474 // icons are the same size.
475 return gfx::Image(gfx::ImageSkiaOperations::CreateTransparentImage(
476 rb
.GetImageNamed(IDR_AUTOFILL_CC_GENERIC
).AsImageSkia(), 0));
478 return rb
.GetImageNamed(input_card_idr
);
481 gfx::Image
CvcIconForCreditCardType(const base::string16
& credit_card_type
) {
482 ui::ResourceBundle
& rb
= ui::ResourceBundle::GetSharedInstance();
483 if (credit_card_type
== l10n_util::GetStringUTF16(IDS_AUTOFILL_CC_AMEX
))
484 return rb
.GetImageNamed(IDR_CREDIT_CARD_CVC_HINT_AMEX
);
486 return rb
.GetImageNamed(IDR_CREDIT_CARD_CVC_HINT
);
489 ServerFieldType
CountryTypeForSection(DialogSection section
) {
490 return section
== SECTION_SHIPPING
? ADDRESS_HOME_COUNTRY
:
491 ADDRESS_BILLING_COUNTRY
;
494 // Attempts to canonicalize the administrative area name in |profile| using the
495 // rules in |validator|.
496 void CanonicalizeState(const AddressValidator
* validator
,
497 AutofillProfile
* profile
) {
498 base::string16 administrative_area
;
499 scoped_ptr
<AddressData
> address_data
=
500 i18n::CreateAddressDataFromAutofillProfile(
501 *profile
, g_browser_process
->GetApplicationLocale());
503 validator
->CanonicalizeAdministrativeArea(address_data
.get());
504 administrative_area
= base::UTF8ToUTF16(address_data
->administrative_area
);
506 profile
->SetInfo(AutofillType(ADDRESS_HOME_STATE
),
508 g_browser_process
->GetApplicationLocale());
511 ValidityMessage
GetPhoneValidityMessage(const base::string16
& country_name
,
512 const base::string16
& number
) {
513 std::string region
= AutofillCountry::GetCountryCode(
515 g_browser_process
->GetApplicationLocale());
516 i18n::PhoneObject
phone_object(number
, region
);
517 ValidityMessage
phone_message(base::string16(), true);
519 // Check if the phone number is invalid. Allow valid international
520 // numbers that don't match the address's country only if they have an
521 // international calling code.
522 if (!phone_object
.IsValidNumber() ||
523 (phone_object
.country_code().empty() &&
524 phone_object
.region() != region
)) {
525 phone_message
.text
= l10n_util::GetStringUTF16(
526 IDS_AUTOFILL_DIALOG_VALIDATION_INVALID_PHONE_NUMBER
);
529 return phone_message
;
532 // Constructs |inputs| from template data for a given |dialog_section|.
533 // |country_country| specifies the country code that the inputs should be built
534 // for. Sets the |language_code| to be used for address formatting, if
535 // internationalized address input is enabled. The |language_code| parameter can
537 void BuildInputsForSection(DialogSection dialog_section
,
538 const std::string
& country_code
,
539 DetailInputs
* inputs
,
540 std::string
* language_code
) {
541 using l10n_util::GetStringUTF16
;
543 const DetailInput kCCInputs
[] = {
546 GetStringUTF16(IDS_AUTOFILL_DIALOG_PLACEHOLDER_CARD_NUMBER
) },
547 { DetailInput::SHORT
,
548 CREDIT_CARD_EXP_MONTH
,
549 GetStringUTF16(IDS_AUTOFILL_DIALOG_PLACEHOLDER_EXPIRY_MONTH
) },
550 { DetailInput::SHORT
,
551 CREDIT_CARD_EXP_4_DIGIT_YEAR
,
552 GetStringUTF16(IDS_AUTOFILL_DIALOG_PLACEHOLDER_EXPIRY_YEAR
) },
553 { DetailInput::SHORT_EOL
,
554 CREDIT_CARD_VERIFICATION_CODE
,
555 GetStringUTF16(IDS_AUTOFILL_DIALOG_PLACEHOLDER_CVC
),
559 const DetailInput kBillingPhoneInputs
[] = {
561 PHONE_BILLING_WHOLE_NUMBER
,
562 GetStringUTF16(IDS_AUTOFILL_DIALOG_PLACEHOLDER_PHONE_NUMBER
) },
565 const DetailInput kEmailInputs
[] = {
568 GetStringUTF16(IDS_AUTOFILL_DIALOG_PLACEHOLDER_EMAIL
) },
571 const DetailInput kShippingPhoneInputs
[] = {
573 PHONE_HOME_WHOLE_NUMBER
,
574 GetStringUTF16(IDS_AUTOFILL_DIALOG_PLACEHOLDER_PHONE_NUMBER
) },
577 switch (dialog_section
) {
579 BuildInputs(kCCInputs
, arraysize(kCCInputs
), inputs
);
583 case SECTION_BILLING
: {
584 i18ninput::BuildAddressInputs(common::ADDRESS_TYPE_BILLING
,
585 country_code
, inputs
, language_code
);
586 BuildInputs(kBillingPhoneInputs
, arraysize(kBillingPhoneInputs
), inputs
);
587 BuildInputs(kEmailInputs
, arraysize(kEmailInputs
), inputs
);
591 case SECTION_CC_BILLING
: {
592 BuildInputs(kCCInputs
, arraysize(kCCInputs
), inputs
);
594 // Wallet only supports US billing addresses.
595 const std::string hardcoded_country_code
= "US";
596 i18ninput::BuildAddressInputs(common::ADDRESS_TYPE_BILLING
,
597 hardcoded_country_code
,
600 DCHECK_EQ(inputs
->back().type
, ADDRESS_BILLING_COUNTRY
);
601 inputs
->back().length
= DetailInput::NONE
;
602 const std::string
& app_locale
=
603 g_browser_process
->GetApplicationLocale();
604 inputs
->back().initial_value
=
605 AutofillCountry(hardcoded_country_code
, app_locale
).name();
607 BuildInputs(kBillingPhoneInputs
, arraysize(kBillingPhoneInputs
), inputs
);
611 case SECTION_SHIPPING
: {
612 i18ninput::BuildAddressInputs(common::ADDRESS_TYPE_SHIPPING
,
613 country_code
, inputs
, language_code
);
614 BuildInputs(kShippingPhoneInputs
, arraysize(kShippingPhoneInputs
),
623 AutofillDialogViewDelegate::~AutofillDialogViewDelegate() {}
625 AutofillDialogControllerImpl::~AutofillDialogControllerImpl() {
626 if (popup_controller_
)
627 popup_controller_
->Hide();
629 AutofillMetrics::LogDialogInitialUserState(initial_user_state_
);
632 // Checks the country code against the values the form structure enumerates.
633 bool AutofillCountryFilter(
634 const std::set
<base::string16
>& form_structure_values
,
635 const std::string
& country_code
) {
636 if (!form_structure_values
.empty() &&
637 !form_structure_values
.count(base::ASCIIToUTF16(country_code
))) {
644 // Checks the country code against the values the form structure enumerates and
645 // against the ones Wallet allows.
646 bool WalletCountryFilter(
647 const std::set
<base::string16
>& form_structure_values
,
648 const std::set
<std::string
>& wallet_allowed_values
,
649 const std::string
& country_code
) {
650 if ((!form_structure_values
.empty() &&
651 !form_structure_values
.count(base::ASCIIToUTF16(country_code
))) ||
652 (!wallet_allowed_values
.empty() &&
653 !wallet_allowed_values
.count(country_code
))) {
661 base::WeakPtr
<AutofillDialogControllerImpl
>
662 AutofillDialogControllerImpl::Create(
663 content::WebContents
* contents
,
664 const FormData
& form_structure
,
665 const GURL
& source_url
,
666 const AutofillClient::ResultCallback
& callback
) {
667 // AutofillDialogControllerImpl owns itself.
668 AutofillDialogControllerImpl
* autofill_dialog_controller
=
669 new AutofillDialogControllerImpl(contents
,
673 return autofill_dialog_controller
->weak_ptr_factory_
.GetWeakPtr();
677 void AutofillDialogController::RegisterPrefs(PrefRegistrySimple
* registry
) {
678 registry
->RegisterListPref(::prefs::kAutofillDialogWalletLocationAcceptance
);
682 void AutofillDialogController::RegisterProfilePrefs(
683 user_prefs::PrefRegistrySyncable
* registry
) {
684 registry
->RegisterBooleanPref(
685 ::prefs::kAutofillDialogPayWithoutWallet
,
687 user_prefs::PrefRegistrySyncable::SYNCABLE_PREF
);
688 registry
->RegisterDictionaryPref(
689 ::prefs::kAutofillDialogAutofillDefault
,
690 user_prefs::PrefRegistrySyncable::SYNCABLE_PREF
);
691 registry
->RegisterBooleanPref(
692 ::prefs::kAutofillDialogSaveData
,
694 user_prefs::PrefRegistrySyncable::SYNCABLE_PREF
);
695 registry
->RegisterBooleanPref(
696 ::prefs::kAutofillDialogWalletShippingSameAsBilling
,
698 user_prefs::PrefRegistrySyncable::SYNCABLE_PREF
);
702 base::WeakPtr
<AutofillDialogController
> AutofillDialogController::Create(
703 content::WebContents
* contents
,
704 const FormData
& form_structure
,
705 const GURL
& source_url
,
706 const AutofillClient::ResultCallback
& callback
) {
707 return AutofillDialogControllerImpl::Create(contents
,
713 void AutofillDialogControllerImpl::Show() {
714 dialog_shown_timestamp_
= base::Time::Now();
716 // Determine what field types should be included in the dialog.
717 bool has_types
= false;
718 bool has_sections
= false;
719 form_structure_
.ParseFieldTypesFromAutocompleteAttributes(
720 &has_types
, &has_sections
);
722 // Fail if the author didn't specify autocomplete types.
725 AutofillClient::AutocompleteResultErrorDisabled
,
726 base::ASCIIToUTF16("Form is missing autocomplete attributes."),
732 // Fail if the author didn't ask for at least some kind of credit card
734 bool has_credit_card_field
= false;
735 for (size_t i
= 0; i
< form_structure_
.field_count(); ++i
) {
736 AutofillType type
= form_structure_
.field(i
)->Type();
737 if (type
.html_type() != HTML_TYPE_UNKNOWN
&& type
.group() == CREDIT_CARD
) {
738 has_credit_card_field
= true;
743 if (!has_credit_card_field
) {
744 callback_
.Run(AutofillClient::AutocompleteResultErrorDisabled
,
746 "Form is not a payment form (must contain "
747 "some autocomplete=\"cc-*\" fields). "),
753 billing_country_combobox_model_
.reset(new CountryComboboxModel());
754 billing_country_combobox_model_
->SetCountries(
756 base::Bind(AutofillCountryFilter
,
757 form_structure_
.PossibleValues(ADDRESS_BILLING_COUNTRY
)));
758 shipping_country_combobox_model_
.reset(new CountryComboboxModel());
759 acceptable_shipping_countries_
=
760 form_structure_
.PossibleValues(ADDRESS_HOME_COUNTRY
);
761 shipping_country_combobox_model_
->SetCountries(
763 base::Bind(AutofillCountryFilter
,
764 base::ConstRef(acceptable_shipping_countries_
)));
766 // If the form has a country <select> but none of the options are valid, bail.
767 if (billing_country_combobox_model_
->GetItemCount() == 0 ||
768 shipping_country_combobox_model_
->GetItemCount() == 0) {
769 callback_
.Run(AutofillClient::AutocompleteResultErrorDisabled
,
770 base::ASCIIToUTF16("No valid/supported country options"
777 // Log any relevant UI metrics and security exceptions.
778 AutofillMetrics::LogDialogUiEvent(AutofillMetrics::DIALOG_UI_SHOWN
);
780 AutofillMetrics::LogDialogSecurityMetric(
781 AutofillMetrics::SECURITY_METRIC_DIALOG_SHOWN
);
783 // The Autofill dialog is shown in response to a message from the renderer and
784 // as such, it can only be made in the context of the current document. A call
785 // to GetActiveEntry would return a pending entry, if there was one, which
786 // would be a security bug. Therefore, we use the last committed URL for the
788 const GURL
& current_url
= web_contents()->GetLastCommittedURL();
789 invoked_from_same_origin_
=
790 current_url
.GetOrigin() == source_url_
.GetOrigin();
792 if (!invoked_from_same_origin_
) {
793 AutofillMetrics::LogDialogSecurityMetric(
794 AutofillMetrics::SECURITY_METRIC_CROSS_ORIGIN_FRAME
);
797 for (size_t i
= SECTION_MIN
; i
<= SECTION_MAX
; ++i
) {
798 DialogSection section
= static_cast<DialogSection
>(i
);
800 std::string country_code
;
801 CountryComboboxModel
* model
= CountryComboboxModelForSection(section
);
803 country_code
= model
->GetDefaultCountryCode();
805 DetailInputs
* inputs
= MutableRequestedFieldsForSection(section
);
806 BuildInputsForSection(
807 section
, country_code
, inputs
,
808 MutableAddressLanguageCodeForSection(section
));
811 // Test whether we need to show the shipping section. If filling that section
812 // would be a no-op, don't show it.
813 cares_about_shipping_
= form_structure_
.FillFields(
814 RequestedTypesForSection(SECTION_SHIPPING
),
815 base::Bind(ServerTypeMatchesField
, SECTION_SHIPPING
),
816 base::Bind(NullGetInfo
), std::string(),
817 g_browser_process
->GetApplicationLocale());
819 transaction_amount_
= form_structure_
.GetUniqueValue(
820 HTML_TYPE_TRANSACTION_AMOUNT
);
821 transaction_currency_
= form_structure_
.GetUniqueValue(
822 HTML_TYPE_TRANSACTION_CURRENCY
);
824 account_chooser_model_
.reset(
825 new AccountChooserModel(this, profile_
, !ShouldShowAccountChooser()));
827 acceptable_cc_types_
= form_structure_
.PossibleValues(CREDIT_CARD_TYPE
);
828 // Wallet generates MC virtual cards, so we have to disable it if MC is not
830 if (ShouldDisallowCcType(CreditCard::TypeForDisplay(kMasterCard
)))
831 DisableWallet(wallet::WalletClient::UNSUPPORTED_MERCHANT
);
833 if (account_chooser_model_
->WalletIsSelected())
836 validator_
.reset(new AddressValidator(
837 scoped_ptr
< ::i18n::addressinput::Source
>(
838 new autofill::ChromeMetadataSource(I18N_ADDRESS_VALIDATION_DATA_URL
,
839 profile_
->GetRequestContext())),
840 ValidationRulesStorageFactory::CreateStorage(),
843 SuggestionsUpdated();
844 SubmitButtonDelayBegin();
845 view_
.reset(CreateView());
847 GetManager()->AddObserver(this);
849 if (!account_chooser_model_
->WalletIsSelected())
850 LogDialogLatencyToShow();
853 void AutofillDialogControllerImpl::Hide() {
858 void AutofillDialogControllerImpl::TabActivated() {
859 // If the user switched away from this tab and then switched back, reload the
860 // Wallet items, in case they've changed.
861 int64 seconds_elapsed_since_last_refresh
=
862 (base::TimeTicks::Now() - last_wallet_items_fetch_timestamp_
).InSeconds();
863 if (IsPayingWithWallet() && wallet_items_
&&
864 seconds_elapsed_since_last_refresh
>= kWalletItemsRefreshRateSeconds
) {
869 ////////////////////////////////////////////////////////////////////////////////
870 // AutofillDialogViewDelegate implementation.
872 base::string16
AutofillDialogControllerImpl::DialogTitle() const {
873 if (ShouldShowSpinner())
874 return base::string16();
876 return l10n_util::GetStringUTF16(IDS_AUTOFILL_DIALOG_TITLE
);
879 base::string16
AutofillDialogControllerImpl::AccountChooserText() const {
880 if (!account_chooser_model_
->WalletIsSelected())
881 return l10n_util::GetStringUTF16(IDS_AUTOFILL_DIALOG_PAYING_WITHOUT_WALLET
);
883 if (SignedInState() == SIGNED_IN
)
884 return account_chooser_model_
->GetActiveWalletAccountName();
886 // In this case, the account chooser should be showing the signin link.
887 return base::string16();
890 base::string16
AutofillDialogControllerImpl::SignInLinkText() const {
891 int ids
= SignedInState() == NOT_CHECKED
?
892 IDS_AUTOFILL_DIALOG_USE_WALLET_LINK
:
893 ShouldShowSignInWebView() ? IDS_AUTOFILL_DIALOG_CANCEL_SIGN_IN
:
894 IDS_AUTOFILL_DIALOG_SIGN_IN
;
896 return l10n_util::GetStringUTF16(ids
);
899 base::string16
AutofillDialogControllerImpl::SpinnerText() const {
900 return l10n_util::GetStringUTF16(IDS_AUTOFILL_DIALOG_LOADING
);
903 base::string16
AutofillDialogControllerImpl::EditSuggestionText() const {
904 return l10n_util::GetStringUTF16(IDS_AUTOFILL_DIALOG_EDIT
);
907 base::string16
AutofillDialogControllerImpl::CancelButtonText() const {
908 return l10n_util::GetStringUTF16(IDS_CANCEL
);
911 base::string16
AutofillDialogControllerImpl::ConfirmButtonText() const {
912 return l10n_util::GetStringUTF16(IsSubmitPausedOn(wallet::VERIFY_CVV
) ?
913 IDS_AUTOFILL_DIALOG_VERIFY_BUTTON
: IDS_AUTOFILL_DIALOG_SUBMIT_BUTTON
);
916 base::string16
AutofillDialogControllerImpl::SaveLocallyText() const {
917 return l10n_util::GetStringUTF16(IDS_AUTOFILL_DIALOG_SAVE_LOCALLY_CHECKBOX
);
920 base::string16
AutofillDialogControllerImpl::SaveLocallyTooltip() const {
921 return l10n_util::GetStringUTF16(IDS_AUTOFILL_DIALOG_SAVE_LOCALLY_TOOLTIP
);
924 base::string16
AutofillDialogControllerImpl::LegalDocumentsText() {
925 if (!IsPayingWithWallet() || ShouldShowSignInWebView())
926 return base::string16();
928 return legal_documents_text_
;
931 bool AutofillDialogControllerImpl::ShouldShowSpinner() const {
932 return SignedInState() == REQUIRES_RESPONSE
||
933 SignedInState() == REQUIRES_PASSIVE_SIGN_IN
;
936 bool AutofillDialogControllerImpl::ShouldShowAccountChooser() const {
937 return !ShouldShowSpinner() && GetManager()->IsCountryOfInterest("US");
940 bool AutofillDialogControllerImpl::ShouldShowSignInWebView() const {
941 return !signin_registrar_
.IsEmpty();
944 bool AutofillDialogControllerImpl::ShouldOfferToSaveInChrome() const {
945 return IsAutofillEnabled() &&
946 !IsPayingWithWallet() &&
947 !profile_
->IsOffTheRecord() &&
948 IsManuallyEditingAnySection() &&
949 !ShouldShowSpinner();
952 bool AutofillDialogControllerImpl::ShouldSaveInChrome() const {
953 return profile_
->GetPrefs()->GetBoolean(::prefs::kAutofillDialogSaveData
);
956 int AutofillDialogControllerImpl::GetDialogButtons() const {
957 if (waiting_for_explicit_sign_in_response_
)
958 return ui::DIALOG_BUTTON_NONE
;
960 if (ShouldShowSpinner() && !handling_use_wallet_link_click_
)
961 return ui::DIALOG_BUTTON_CANCEL
;
963 return ui::DIALOG_BUTTON_OK
| ui::DIALOG_BUTTON_CANCEL
;
966 bool AutofillDialogControllerImpl::IsDialogButtonEnabled(
967 ui::DialogButton button
) const {
968 if (button
== ui::DIALOG_BUTTON_OK
) {
969 if (IsSubmitPausedOn(wallet::VERIFY_CVV
))
972 if (ShouldShowSpinner() || is_submitting_
)
975 if (submit_button_delay_timer_
.IsRunning())
981 DCHECK_EQ(ui::DIALOG_BUTTON_CANCEL
, button
);
982 return !is_submitting_
|| IsSubmitPausedOn(wallet::VERIFY_CVV
);
985 DialogOverlayState
AutofillDialogControllerImpl::GetDialogOverlay() {
986 bool show_wallet_interstitial
= IsPayingWithWallet() && is_submitting_
&&
987 !(full_wallet_
&& !full_wallet_
->required_actions().empty());
988 if (!show_wallet_interstitial
) {
989 card_scrambling_delay_
.Stop();
990 card_scrambling_refresher_
.Stop();
991 return DialogOverlayState();
994 ui::ResourceBundle
* rb
= &ui::ResourceBundle::GetSharedInstance();
995 DialogOverlayState state
;
996 state
.string
.font_list
= rb
->GetFontList(ui::ResourceBundle::MediumFont
);
998 const SkColor start_top_color
= SkColorSetRGB(0xD6, 0xD6, 0xD6);
999 const SkColor start_bottom_color
= SkColorSetRGB(0x98, 0x98, 0x98);
1000 const SkColor final_top_color
= SkColorSetRGB(0x52, 0x9F, 0xF8);
1001 const SkColor final_bottom_color
= SkColorSetRGB(0x22, 0x75, 0xE5);
1003 if (full_wallet_
&& full_wallet_
->required_actions().empty()) {
1004 card_scrambling_delay_
.Stop();
1005 card_scrambling_refresher_
.Stop();
1007 base::string16 cc_number
= base::ASCIIToUTF16(full_wallet_
->GetPan());
1008 DCHECK_GE(cc_number
.size(), 4U);
1009 state
.image
= GetGeneratedCardImage(
1010 base::ASCIIToUTF16("XXXX XXXX XXXX ") +
1011 cc_number
.substr(cc_number
.size() - 4),
1012 full_wallet_
->billing_address()->recipient_name(),
1013 color_utils::AlphaBlend(
1016 255 * card_generated_animation_
.GetCurrentValue()),
1017 color_utils::AlphaBlend(
1020 255 * card_generated_animation_
.GetCurrentValue()));
1022 state
.string
.text
= l10n_util::GetStringUTF16(
1023 IDS_AUTOFILL_DIALOG_CARD_GENERATION_DONE
);
1025 // Start the refresher if it isn't running. Wait one second before pumping
1026 // updates to the view.
1027 if (!card_scrambling_delay_
.IsRunning() &&
1028 !card_scrambling_refresher_
.IsRunning()) {
1029 scrambled_card_number_
= GenerateRandomCardNumber();
1030 card_scrambling_delay_
.Start(
1032 base::TimeDelta::FromSeconds(1),
1034 &AutofillDialogControllerImpl::StartCardScramblingRefresher
);
1037 DCHECK(!scrambled_card_number_
.empty());
1038 state
.image
= GetGeneratedCardImage(
1039 scrambled_card_number_
,
1040 submitted_cardholder_name_
,
1042 start_bottom_color
);
1044 // "Submitting" waiting page.
1045 state
.string
.text
= l10n_util::GetStringUTF16(
1046 IDS_AUTOFILL_DIALOG_CARD_GENERATION_IN_PROGRESS
);
1052 const std::vector
<gfx::Range
>& AutofillDialogControllerImpl::
1053 LegalDocumentLinks() {
1054 return legal_document_link_ranges_
;
1057 bool AutofillDialogControllerImpl::SectionIsActive(DialogSection section
)
1059 if (IsSubmitPausedOn(wallet::VERIFY_CVV
))
1060 return section
== SECTION_CC_BILLING
;
1062 if (!FormStructureCaresAboutSection(section
))
1065 if (IsPayingWithWallet())
1066 return section
== SECTION_CC_BILLING
|| section
== SECTION_SHIPPING
;
1068 return section
!= SECTION_CC_BILLING
;
1071 void AutofillDialogControllerImpl::GetWalletItems() {
1072 ScopedViewUpdates
updates(view_
.get());
1074 wallet_items_requested_
= true;
1075 wallet::WalletClient
* wallet_client
= GetWalletClient();
1076 wallet_client
->CancelRequest();
1078 previously_selected_instrument_id_
.clear();
1079 previously_selected_shipping_address_id_
.clear();
1080 if (wallet_items_
) {
1081 previous_default_instrument_id_
= wallet_items_
->default_instrument_id();
1082 previous_default_shipping_address_id_
= wallet_items_
->default_address_id();
1084 const wallet::WalletItems::MaskedInstrument
* instrument
=
1087 previously_selected_instrument_id_
= instrument
->object_id();
1089 const wallet::Address
* address
= ActiveShippingAddress();
1091 previously_selected_shipping_address_id_
= address
->object_id();
1094 last_wallet_items_fetch_timestamp_
= base::TimeTicks::Now();
1095 passive_failed_
= false;
1096 wallet_items_
.reset();
1098 // The "Loading..." page should be showing now, which should cause the
1099 // account chooser to hide.
1100 view_
->UpdateAccountChooser();
1101 wallet_client
->GetWalletItems(transaction_amount_
, transaction_currency_
);
1104 void AutofillDialogControllerImpl::HideSignIn() {
1105 ScopedViewUpdates
updates(view_
.get());
1106 signin_registrar_
.RemoveAll();
1107 view_
->HideSignIn();
1108 view_
->UpdateAccountChooser();
1111 AutofillDialogControllerImpl::DialogSignedInState
1112 AutofillDialogControllerImpl::SignedInState() const {
1113 if (wallet_error_notification_
)
1114 return SIGN_IN_DISABLED
;
1116 if (signin_helper_
|| (wallet_items_requested_
&& !wallet_items_
))
1117 return REQUIRES_RESPONSE
;
1119 if (!wallet_items_requested_
)
1122 if (wallet_items_
->HasRequiredAction(wallet::GAIA_AUTH
) ||
1124 return REQUIRES_SIGN_IN
;
1127 if (wallet_items_
->HasRequiredAction(wallet::PASSIVE_GAIA_AUTH
))
1128 return REQUIRES_PASSIVE_SIGN_IN
;
1133 void AutofillDialogControllerImpl::SignedInStateUpdated() {
1134 if (!ShouldShowSpinner())
1135 waiting_for_explicit_sign_in_response_
= false;
1137 switch (SignedInState()) {
1139 LogDialogLatencyToShow();
1142 case REQUIRES_SIGN_IN
:
1143 if (handling_use_wallet_link_click_
)
1144 ShowSignIn(wallet::GetSignInUrl(GetWalletClient()->user_index()));
1146 case SIGN_IN_DISABLED
:
1147 // Switch to the local account and refresh the dialog.
1148 signin_helper_
.reset();
1149 OnWalletSigninError();
1150 handling_use_wallet_link_click_
= false;
1153 case REQUIRES_PASSIVE_SIGN_IN
:
1154 // Attempt to passively sign in the user.
1155 DCHECK(!signin_helper_
);
1156 signin_helper_
.reset(new wallet::WalletSigninHelper(
1158 profile_
->GetRequestContext()));
1159 signin_helper_
->StartPassiveSignin(GetWalletClient()->user_index());
1163 case REQUIRES_RESPONSE
:
1168 void AutofillDialogControllerImpl::OnWalletOrSigninUpdate() {
1169 ScopedViewUpdates
updates(view_
.get());
1170 SignedInStateUpdated();
1171 SuggestionsUpdated();
1172 UpdateAccountChooserView();
1175 view_
->UpdateButtonStrip();
1176 view_
->UpdateOverlay();
1179 // On the first successful response, compute the initial user state metric.
1180 if (initial_user_state_
== AutofillMetrics::DIALOG_USER_STATE_UNKNOWN
)
1181 initial_user_state_
= GetInitialUserState();
1184 void AutofillDialogControllerImpl::OnWalletFormFieldError(
1185 const std::vector
<wallet::FormFieldError
>& form_field_errors
) {
1186 if (form_field_errors
.empty())
1189 for (std::vector
<wallet::FormFieldError
>::const_iterator it
=
1190 form_field_errors
.begin();
1191 it
!= form_field_errors
.end(); ++it
) {
1192 if (it
->error_type() == wallet::FormFieldError::UNKNOWN_ERROR
||
1193 it
->GetAutofillType() == MAX_VALID_FIELD_TYPE
||
1194 it
->location() == wallet::FormFieldError::UNKNOWN_LOCATION
) {
1195 wallet_server_validation_recoverable_
= false;
1198 DialogSection section
= SectionFromLocation(it
->location());
1199 wallet_errors_
[section
][it
->GetAutofillType()] =
1200 std::make_pair(it
->GetErrorMessage(),
1201 GetValueFromSection(section
, it
->GetAutofillType()));
1204 // Unrecoverable validation errors.
1205 if (!wallet_server_validation_recoverable_
)
1206 DisableWallet(wallet::WalletClient::UNKNOWN_ERROR
);
1211 void AutofillDialogControllerImpl::ConstructLegalDocumentsText() {
1212 legal_documents_text_
.clear();
1213 legal_document_link_ranges_
.clear();
1218 PrefService
* local_state
= g_browser_process
->local_state();
1219 // List of users who have accepted location sharing for fraud protection
1221 const base::ListValue
* accepted
=
1222 local_state
->GetList(::prefs::kAutofillDialogWalletLocationAcceptance
);
1223 bool has_accepted_location_sharing
=
1224 accepted
->Find(base::StringValue(
1225 account_chooser_model_
->GetActiveWalletAccountName())) !=
1228 if (wallet_items_
->legal_documents().empty()) {
1229 if (!has_accepted_location_sharing
) {
1230 legal_documents_text_
= l10n_util::GetStringUTF16(
1231 IDS_AUTOFILL_DIALOG_LOCATION_DISCLOSURE
);
1237 const std::vector
<wallet::WalletItems::LegalDocument
*>& documents
=
1238 wallet_items_
->legal_documents();
1239 // There should never be just one document because the privacy policy doc gets
1240 // tacked on the end of other documents.
1241 DCHECK_GE(documents
.size(), 2U);
1243 std::vector
<base::string16
> link_names
;
1244 for (size_t i
= 0; i
< documents
.size(); ++i
) {
1245 link_names
.push_back(documents
[i
]->display_name());
1248 int resource_id
= 0;
1249 switch (documents
.size()) {
1251 resource_id
= IDS_AUTOFILL_DIALOG_LEGAL_LINKS_2
;
1254 resource_id
= IDS_AUTOFILL_DIALOG_LEGAL_LINKS_3
;
1257 resource_id
= IDS_AUTOFILL_DIALOG_LEGAL_LINKS_4
;
1260 resource_id
= IDS_AUTOFILL_DIALOG_LEGAL_LINKS_5
;
1263 resource_id
= IDS_AUTOFILL_DIALOG_LEGAL_LINKS_6
;
1266 // We can only handle so many documents. For lack of a better way of
1267 // handling document overflow, just error out if there are too many.
1268 DisableWallet(wallet::WalletClient::UNKNOWN_ERROR
);
1272 std::vector
<size_t> offsets
;
1273 base::string16 text
=
1274 l10n_util::GetStringFUTF16(resource_id
, link_names
,&offsets
);
1276 // Tack on the location string if need be.
1277 size_t base_offset
= 0;
1278 if (!has_accepted_location_sharing
) {
1279 text
= l10n_util::GetStringFUTF16(
1280 IDS_AUTOFILL_DIALOG_LOCATION_DISCLOSURE_WITH_LEGAL_DOCS
,
1285 for (size_t i
= 0; i
< documents
.size(); ++i
) {
1286 size_t link_start
= offsets
[i
] + base_offset
;
1287 legal_document_link_ranges_
.push_back(gfx::Range(
1288 link_start
, link_start
+ documents
[i
]->display_name().size()));
1290 legal_documents_text_
= text
;
1293 void AutofillDialogControllerImpl::ResetSectionInput(DialogSection section
) {
1294 SetEditingExistingData(section
, false);
1295 needs_validation_
.erase(section
);
1297 CountryComboboxModel
* model
= CountryComboboxModelForSection(section
);
1299 base::string16 country
= model
->GetItemAt(model
->GetDefaultIndex());
1300 RebuildInputsForCountry(section
, country
, false);
1303 DetailInputs
* inputs
= MutableRequestedFieldsForSection(section
);
1304 for (DetailInputs::iterator it
= inputs
->begin();
1305 it
!= inputs
->end(); ++it
) {
1306 if (it
->length
!= DetailInput::NONE
) {
1307 it
->initial_value
.clear();
1308 } else if (!it
->initial_value
.empty() &&
1309 (it
->type
== ADDRESS_BILLING_COUNTRY
||
1310 it
->type
== ADDRESS_HOME_COUNTRY
)) {
1311 GetValidator()->LoadRules(AutofillCountry::GetCountryCode(
1312 it
->initial_value
, g_browser_process
->GetApplicationLocale()));
1317 void AutofillDialogControllerImpl::ShowEditUiIfBadSuggestion(
1318 DialogSection section
) {
1319 // |CreateWrapper()| returns an empty wrapper if |IsEditingExistingData()|, so
1320 // get the wrapper before this potentially happens below.
1321 scoped_ptr
<DataModelWrapper
> wrapper
= CreateWrapper(section
);
1323 // If the chosen item in |model| yields an empty suggestion text, it is
1324 // invalid. In this case, show the edit UI and highlight invalid fields.
1325 SuggestionsMenuModel
* model
= SuggestionsMenuModelForSection(section
);
1326 base::string16 unused
, unused2
;
1327 if (IsASuggestionItemKey(model
->GetItemKeyForCheckedItem()) &&
1328 !SuggestionTextForSection(section
, &unused
, &unused2
)) {
1329 SetEditingExistingData(section
, true);
1332 if (wrapper
&& IsEditingExistingData(section
)) {
1333 base::string16 country
=
1334 wrapper
->GetInfo(AutofillType(CountryTypeForSection(section
)));
1335 if (!country
.empty()) {
1336 // There's no user input to restore here as this is only called after
1337 // resetting all section input.
1338 if (RebuildInputsForCountry(section
, country
, false))
1339 UpdateSection(section
);
1341 wrapper
->FillInputs(MutableRequestedFieldsForSection(section
));
1345 bool AutofillDialogControllerImpl::InputWasEdited(ServerFieldType type
,
1346 const base::string16
& value
) {
1350 // If this is a combobox at the default value, don't preserve it.
1351 ui::ComboboxModel
* model
= ComboboxModelForAutofillType(type
);
1352 if (model
&& model
->GetItemAt(model
->GetDefaultIndex()) == value
)
1358 FieldValueMap
AutofillDialogControllerImpl::TakeUserInputSnapshot() {
1359 FieldValueMap snapshot
;
1363 for (size_t i
= SECTION_MIN
; i
<= SECTION_MAX
; ++i
) {
1364 DialogSection section
= static_cast<DialogSection
>(i
);
1365 SuggestionsMenuModel
* model
= SuggestionsMenuModelForSection(section
);
1366 if (model
->GetItemKeyForCheckedItem() != kAddNewItemKey
)
1369 FieldValueMap outputs
;
1370 view_
->GetUserInput(section
, &outputs
);
1371 // Remove fields that are empty, at their default values, or invalid.
1372 for (FieldValueMap::iterator it
= outputs
.begin(); it
!= outputs
.end();
1374 if (InputWasEdited(it
->first
, it
->second
) &&
1375 InputValidityMessage(section
, it
->first
, it
->second
).empty()) {
1376 snapshot
.insert(std::make_pair(it
->first
, it
->second
));
1384 void AutofillDialogControllerImpl::RestoreUserInputFromSnapshot(
1385 const FieldValueMap
& snapshot
) {
1386 if (snapshot
.empty())
1389 for (size_t i
= SECTION_MIN
; i
<= SECTION_MAX
; ++i
) {
1390 DialogSection section
= static_cast<DialogSection
>(i
);
1391 if (!SectionIsActive(section
))
1394 DetailInputs
* inputs
= MutableRequestedFieldsForSection(section
);
1395 for (size_t i
= 0; i
< inputs
->size(); ++i
) {
1396 DetailInput
* input
= &(*inputs
)[i
];
1397 if (input
->length
!= DetailInput::NONE
) {
1398 input
->initial_value
=
1399 GetInfoFromInputs(snapshot
, section
, AutofillType(input
->type
));
1401 if (InputWasEdited(input
->type
, input
->initial_value
))
1402 SuggestionsMenuModelForSection(section
)->SetCheckedItem(kAddNewItemKey
);
1407 void AutofillDialogControllerImpl::UpdateSection(DialogSection section
) {
1409 view_
->UpdateSection(section
);
1412 void AutofillDialogControllerImpl::UpdateForErrors() {
1416 // Currently, the view should only need to be updated if there are
1417 // |wallet_errors_| or validating a suggestion that's based on existing data.
1418 bool should_update
= !wallet_errors_
.empty();
1419 if (!should_update
) {
1420 for (size_t i
= SECTION_MIN
; i
<= SECTION_MAX
; ++i
) {
1421 if (IsEditingExistingData(static_cast<DialogSection
>(i
))) {
1422 should_update
= true;
1429 view_
->UpdateForErrors();
1432 gfx::Image
AutofillDialogControllerImpl::GetGeneratedCardImage(
1433 const base::string16
& card_number
,
1434 const base::string16
& name
,
1435 const SkColor
& gradient_top
,
1436 const SkColor
& gradient_bottom
) {
1437 const int kCardWidthPx
= 300;
1438 const int kCardHeightPx
= 190;
1439 const gfx::Size
size(kCardWidthPx
, kCardHeightPx
);
1440 float scale_factor
= ui::GetScaleFactorForNativeView(
1441 web_contents()->GetNativeView());
1442 gfx::Canvas
canvas(size
, scale_factor
, false);
1444 gfx::Rect
display_rect(size
);
1446 skia::RefPtr
<SkShader
> shader
= gfx::CreateGradientShader(
1447 0, size
.height(), gradient_top
, gradient_bottom
);
1449 paint
.setShader(shader
.get());
1450 canvas
.DrawRoundRect(display_rect
, 8, paint
);
1452 display_rect
.Inset(20, 0, 0, 0);
1453 gfx::Font
font(l10n_util::GetStringUTF8(IDS_FIXED_FONT_FAMILY
), 18);
1454 gfx::FontList
font_list(font
);
1455 gfx::ShadowValues shadows
;
1456 shadows
.push_back(gfx::ShadowValue(gfx::Vector2d(0, 1), 1.0, SK_ColorBLACK
));
1457 canvas
.DrawStringRectWithShadows(
1461 display_rect
, 0, 0, shadows
);
1463 base::string16 capitalized_name
= base::i18n::ToUpper(name
);
1464 display_rect
.Inset(0, size
.height() / 2, 0, 0);
1465 canvas
.DrawStringRectWithShadows(
1469 display_rect
, 0, 0, shadows
);
1471 gfx::ImageSkia
skia(canvas
.ExtractImageRep());
1472 return gfx::Image(skia
);
1475 void AutofillDialogControllerImpl::StartCardScramblingRefresher() {
1476 RefreshCardScramblingOverlay();
1477 card_scrambling_refresher_
.Start(
1479 base::TimeDelta::FromMilliseconds(75),
1481 &AutofillDialogControllerImpl::RefreshCardScramblingOverlay
);
1484 void AutofillDialogControllerImpl::RefreshCardScramblingOverlay() {
1485 scrambled_card_number_
= GenerateRandomCardNumber();
1486 PushOverlayUpdate();
1489 void AutofillDialogControllerImpl::PushOverlayUpdate() {
1491 ScopedViewUpdates
updates(view_
.get());
1492 view_
->UpdateOverlay();
1496 const DetailInputs
& AutofillDialogControllerImpl::RequestedFieldsForSection(
1497 DialogSection section
) const {
1500 return requested_cc_fields_
;
1501 case SECTION_BILLING
:
1502 return requested_billing_fields_
;
1503 case SECTION_CC_BILLING
:
1504 return requested_cc_billing_fields_
;
1505 case SECTION_SHIPPING
:
1506 return requested_shipping_fields_
;
1510 return requested_billing_fields_
;
1513 ui::ComboboxModel
* AutofillDialogControllerImpl::ComboboxModelForAutofillType(
1514 ServerFieldType type
) {
1516 case CREDIT_CARD_EXP_MONTH
:
1517 return &cc_exp_month_combobox_model_
;
1519 case CREDIT_CARD_EXP_4_DIGIT_YEAR
:
1520 return &cc_exp_year_combobox_model_
;
1522 case ADDRESS_BILLING_COUNTRY
:
1523 return billing_country_combobox_model_
.get();
1525 case ADDRESS_HOME_COUNTRY
:
1526 return shipping_country_combobox_model_
.get();
1533 ui::MenuModel
* AutofillDialogControllerImpl::MenuModelForSection(
1534 DialogSection section
) {
1535 SuggestionsMenuModel
* model
= SuggestionsMenuModelForSection(section
);
1536 // The shipping section menu is special. It will always show because there is
1537 // a choice between "Use billing" and "enter new".
1538 if (section
== SECTION_SHIPPING
)
1541 // For other sections, only show a menu if there's at least one suggestion.
1542 for (int i
= 0; i
< model
->GetItemCount(); ++i
) {
1543 if (IsASuggestionItemKey(model
->GetItemKeyAt(i
)))
1550 ui::MenuModel
* AutofillDialogControllerImpl::MenuModelForAccountChooser() {
1551 // If there were unrecoverable Wallet errors, or if there are choices other
1552 // than "Pay without the wallet", show the full menu.
1553 // TODO(estade): this can present a braindead menu (only 1 option) when
1554 // there's a wallet error.
1555 if (wallet_error_notification_
||
1556 (SignedInState() == SIGNED_IN
&&
1557 account_chooser_model_
->HasAccountsToChoose() &&
1558 !ShouldShowSignInWebView())) {
1559 return account_chooser_model_
.get();
1562 // Otherwise, there is no menu, just a sign in link.
1566 gfx::Image
AutofillDialogControllerImpl::AccountChooserImage() {
1567 if (!MenuModelForAccountChooser() && !ShouldShowSignInWebView()) {
1568 return ui::ResourceBundle::GetSharedInstance().GetImageNamed(
1572 return gfx::Image();
1575 gfx::Image
AutofillDialogControllerImpl::ButtonStripImage() const {
1576 if (IsPayingWithWallet()) {
1577 return ui::ResourceBundle::GetSharedInstance().GetImageNamed(
1581 return gfx::Image();
1584 base::string16
AutofillDialogControllerImpl::LabelForSection(
1585 DialogSection section
) const {
1588 return l10n_util::GetStringUTF16(IDS_AUTOFILL_DIALOG_SECTION_CC
);
1589 case SECTION_BILLING
:
1590 case SECTION_CC_BILLING
:
1591 return l10n_util::GetStringUTF16(IDS_AUTOFILL_DIALOG_SECTION_BILLING
);
1592 case SECTION_SHIPPING
:
1593 return l10n_util::GetStringUTF16(IDS_AUTOFILL_DIALOG_SECTION_SHIPPING
);
1596 return base::string16();
1599 SuggestionState
AutofillDialogControllerImpl::SuggestionStateForSection(
1600 DialogSection section
) {
1601 base::string16 vertically_compact
, horizontally_compact
;
1602 bool show_suggestion
= SuggestionTextForSection(section
,
1603 &vertically_compact
,
1604 &horizontally_compact
);
1605 return SuggestionState(show_suggestion
,
1607 horizontally_compact
,
1608 SuggestionIconForSection(section
),
1609 ExtraSuggestionTextForSection(section
),
1610 ExtraSuggestionIconForSection(section
));
1613 bool AutofillDialogControllerImpl::SuggestionTextForSection(
1614 DialogSection section
,
1615 base::string16
* vertically_compact
,
1616 base::string16
* horizontally_compact
) {
1617 base::string16 action_text
= RequiredActionTextForSection(section
);
1618 if (!action_text
.empty()) {
1619 *vertically_compact
= *horizontally_compact
= action_text
;
1623 // When the user has clicked 'edit' or a suggestion is somehow invalid (e.g. a
1624 // user selects a credit card that has expired), don't show a suggestion (even
1625 // though there is a profile selected in the model).
1626 if (IsEditingExistingData(section
))
1629 SuggestionsMenuModel
* model
= SuggestionsMenuModelForSection(section
);
1630 std::string item_key
= model
->GetItemKeyForCheckedItem();
1631 if (item_key
== kSameAsBillingKey
) {
1632 *vertically_compact
= *horizontally_compact
= l10n_util::GetStringUTF16(
1633 IDS_AUTOFILL_DIALOG_USING_BILLING_FOR_SHIPPING
);
1637 if (!IsASuggestionItemKey(item_key
))
1640 if (!IsPayingWithWallet() &&
1641 (section
== SECTION_BILLING
|| section
== SECTION_SHIPPING
)) {
1642 // Also check if the address is invalid (rules may have loaded since
1643 // the dialog was shown).
1644 if (HasInvalidAddress(*GetManager()->GetProfileByGUID(item_key
)))
1648 scoped_ptr
<DataModelWrapper
> wrapper
= CreateWrapper(section
);
1649 return wrapper
->GetDisplayText(vertically_compact
, horizontally_compact
);
1652 base::string16
AutofillDialogControllerImpl::RequiredActionTextForSection(
1653 DialogSection section
) const {
1654 if (section
== SECTION_CC_BILLING
&& IsSubmitPausedOn(wallet::VERIFY_CVV
)) {
1655 const wallet::WalletItems::MaskedInstrument
* current_instrument
=
1656 wallet_items_
->GetInstrumentById(active_instrument_id_
);
1657 if (current_instrument
)
1658 return current_instrument
->TypeAndLastFourDigits();
1660 FieldValueMap output
;
1661 view_
->GetUserInput(section
, &output
);
1663 GetBillingInfoFromOutputs(output
, &card
, NULL
, NULL
);
1664 return card
.TypeAndLastFourDigits();
1667 return base::string16();
1670 base::string16
AutofillDialogControllerImpl::ExtraSuggestionTextForSection(
1671 DialogSection section
) const {
1672 if (section
== SECTION_CC
||
1673 (section
== SECTION_CC_BILLING
&& IsSubmitPausedOn(wallet::VERIFY_CVV
))) {
1674 return l10n_util::GetStringUTF16(IDS_AUTOFILL_DIALOG_PLACEHOLDER_CVC
);
1677 return base::string16();
1680 const wallet::WalletItems::MaskedInstrument
* AutofillDialogControllerImpl::
1681 ActiveInstrument() const {
1682 if (!IsPayingWithWallet())
1685 const SuggestionsMenuModel
* model
=
1686 SuggestionsMenuModelForSection(SECTION_CC_BILLING
);
1687 const std::string item_key
= model
->GetItemKeyForCheckedItem();
1688 if (!IsASuggestionItemKey(item_key
))
1692 if (!base::StringToInt(item_key
, &index
) || index
< 0 ||
1693 static_cast<size_t>(index
) >= wallet_items_
->instruments().size()) {
1698 return wallet_items_
->instruments()[index
];
1701 const wallet::Address
* AutofillDialogControllerImpl::
1702 ActiveShippingAddress() const {
1703 if (!IsPayingWithWallet() || !IsShippingAddressRequired())
1706 const SuggestionsMenuModel
* model
=
1707 SuggestionsMenuModelForSection(SECTION_SHIPPING
);
1708 const std::string item_key
= model
->GetItemKeyForCheckedItem();
1709 if (!IsASuggestionItemKey(item_key
))
1713 if (!base::StringToInt(item_key
, &index
) || index
< 0 ||
1714 static_cast<size_t>(index
) >= wallet_items_
->addresses().size()) {
1719 return wallet_items_
->addresses()[index
];
1722 scoped_ptr
<DataModelWrapper
> AutofillDialogControllerImpl::CreateWrapper(
1723 DialogSection section
) {
1724 if (IsPayingWithWallet() && full_wallet_
&&
1725 full_wallet_
->required_actions().empty()) {
1726 if (section
== SECTION_CC_BILLING
) {
1727 return scoped_ptr
<DataModelWrapper
>(
1728 new FullWalletBillingWrapper(full_wallet_
.get()));
1730 if (section
== SECTION_SHIPPING
) {
1731 return scoped_ptr
<DataModelWrapper
>(
1732 new FullWalletShippingWrapper(full_wallet_
.get()));
1736 SuggestionsMenuModel
* model
= SuggestionsMenuModelForSection(section
);
1737 std::string item_key
= model
->GetItemKeyForCheckedItem();
1738 if (!IsASuggestionItemKey(item_key
) || IsManuallyEditingSection(section
))
1739 return scoped_ptr
<DataModelWrapper
>();
1741 if (IsPayingWithWallet()) {
1742 if (section
== SECTION_CC_BILLING
) {
1743 return scoped_ptr
<DataModelWrapper
>(
1744 new WalletInstrumentWrapper(ActiveInstrument()));
1747 if (section
== SECTION_SHIPPING
) {
1748 return scoped_ptr
<DataModelWrapper
>(
1749 new WalletAddressWrapper(ActiveShippingAddress()));
1752 return scoped_ptr
<DataModelWrapper
>();
1755 if (section
== SECTION_CC
) {
1756 CreditCard
* card
= GetManager()->GetCreditCardByGUID(item_key
);
1758 return scoped_ptr
<DataModelWrapper
>(new AutofillCreditCardWrapper(card
));
1761 AutofillProfile
* profile
= GetManager()->GetProfileByGUID(item_key
);
1763 if (section
== SECTION_SHIPPING
) {
1764 return scoped_ptr
<DataModelWrapper
>(
1765 new AutofillShippingAddressWrapper(profile
));
1767 DCHECK_EQ(SECTION_BILLING
, section
);
1768 return scoped_ptr
<DataModelWrapper
>(
1769 new AutofillProfileWrapper(profile
));
1772 gfx::Image
AutofillDialogControllerImpl::SuggestionIconForSection(
1773 DialogSection section
) {
1774 scoped_ptr
<DataModelWrapper
> model
= CreateWrapper(section
);
1776 return gfx::Image();
1778 return model
->GetIcon();
1781 gfx::Image
AutofillDialogControllerImpl::ExtraSuggestionIconForSection(
1782 DialogSection section
) {
1783 if (section
!= SECTION_CC
&& section
!= SECTION_CC_BILLING
)
1784 return gfx::Image();
1786 scoped_ptr
<DataModelWrapper
> model
= CreateWrapper(section
);
1788 return gfx::Image();
1790 return CvcIconForCreditCardType(
1791 model
->GetInfo(AutofillType(CREDIT_CARD_TYPE
)));
1794 FieldIconMap
AutofillDialogControllerImpl::IconsForFields(
1795 const FieldValueMap
& user_inputs
) const {
1796 FieldIconMap result
;
1797 base::string16 credit_card_type
;
1799 FieldValueMap::const_iterator credit_card_iter
=
1800 user_inputs
.find(CREDIT_CARD_NUMBER
);
1801 if (credit_card_iter
!= user_inputs
.end()) {
1802 const base::string16
& number
= credit_card_iter
->second
;
1803 const std::string type
= CreditCard::GetCreditCardType(number
);
1804 credit_card_type
= CreditCard::TypeForDisplay(type
);
1805 result
[CREDIT_CARD_NUMBER
] = CreditCardIconForType(type
);
1808 if (!user_inputs
.count(CREDIT_CARD_VERIFICATION_CODE
))
1811 result
[CREDIT_CARD_VERIFICATION_CODE
] =
1812 CvcIconForCreditCardType(credit_card_type
);
1817 bool AutofillDialogControllerImpl::FieldControlsIcons(
1818 ServerFieldType type
) const {
1819 return type
== CREDIT_CARD_NUMBER
;
1822 base::string16
AutofillDialogControllerImpl::TooltipForField(
1823 ServerFieldType type
) const {
1824 if (type
== PHONE_HOME_WHOLE_NUMBER
|| type
== PHONE_BILLING_WHOLE_NUMBER
)
1825 return l10n_util::GetStringUTF16(IDS_AUTOFILL_DIALOG_TOOLTIP_PHONE_NUMBER
);
1827 return base::string16();
1830 bool AutofillDialogControllerImpl::InputIsEditable(
1831 const DetailInput
& input
,
1832 DialogSection section
) {
1833 if (section
!= SECTION_CC_BILLING
|| !IsPayingWithWallet())
1836 if (input
.type
== CREDIT_CARD_NUMBER
)
1837 return !IsEditingExistingData(section
);
1839 // For CVC, only require (allow) input if the user has edited some other
1840 // aspect of the card.
1841 if (input
.type
== CREDIT_CARD_VERIFICATION_CODE
&&
1842 IsEditingExistingData(section
)) {
1843 FieldValueMap output
;
1844 view_
->GetUserInput(section
, &output
);
1845 WalletInstrumentWrapper
wrapper(ActiveInstrument());
1847 for (FieldValueMap::iterator iter
= output
.begin(); iter
!= output
.end();
1849 if (iter
->first
== input
.type
)
1852 AutofillType
type(iter
->first
);
1853 if (type
.group() == CREDIT_CARD
&&
1854 iter
->second
!= wrapper
.GetInfo(type
)) {
1865 // TODO(groby): Add more tests.
1866 base::string16
AutofillDialogControllerImpl::InputValidityMessage(
1867 DialogSection section
,
1868 ServerFieldType type
,
1869 const base::string16
& value
) {
1870 // If the field is edited, clear any Wallet errors.
1871 if (IsPayingWithWallet()) {
1872 WalletValidationErrors::iterator it
= wallet_errors_
.find(section
);
1873 if (it
!= wallet_errors_
.end()) {
1874 TypeErrorInputMap::const_iterator iter
= it
->second
.find(type
);
1875 if (iter
!= it
->second
.end()) {
1876 if (iter
->second
.second
== value
)
1877 return iter
->second
.first
;
1878 it
->second
.erase(type
);
1883 AutofillType
autofill_type(type
);
1884 if (autofill_type
.group() == ADDRESS_HOME
||
1885 autofill_type
.group() == ADDRESS_BILLING
) {
1886 return base::string16();
1889 switch (autofill_type
.GetStorableType()) {
1891 if (!value
.empty() && !IsValidEmailAddress(value
)) {
1892 return l10n_util::GetStringUTF16(
1893 IDS_AUTOFILL_DIALOG_VALIDATION_INVALID_EMAIL_ADDRESS
);
1897 case CREDIT_CARD_NUMBER
: {
1898 if (!value
.empty()) {
1899 base::string16 message
= CreditCardNumberValidityMessage(value
);
1900 if (!message
.empty())
1906 case CREDIT_CARD_EXP_MONTH
:
1907 if (!InputWasEdited(CREDIT_CARD_EXP_MONTH
, value
)) {
1908 return l10n_util::GetStringUTF16(
1909 IDS_LIBADDRESSINPUT_MISSING_REQUIRED_FIELD
);
1913 case CREDIT_CARD_EXP_4_DIGIT_YEAR
:
1914 if (!InputWasEdited(CREDIT_CARD_EXP_4_DIGIT_YEAR
, value
)) {
1915 return l10n_util::GetStringUTF16(
1916 IDS_LIBADDRESSINPUT_MISSING_REQUIRED_FIELD
);
1920 case CREDIT_CARD_VERIFICATION_CODE
:
1921 if (!value
.empty() && !autofill::IsValidCreditCardSecurityCode(value
)) {
1922 return l10n_util::GetStringUTF16(
1923 IDS_AUTOFILL_DIALOG_VALIDATION_INVALID_CREDIT_CARD_SECURITY_CODE
);
1928 // Wallet requires a first and last billing name.
1929 if (IsPayingWithWallet() && !value
.empty() &&
1930 !IsCardHolderNameValidForWallet(value
)) {
1931 return l10n_util::GetStringUTF16(
1932 IDS_AUTOFILL_DIALOG_VALIDATION_WALLET_REQUIRES_TWO_NAMES
);
1936 case PHONE_HOME_WHOLE_NUMBER
: // Used in shipping section.
1939 case PHONE_BILLING_WHOLE_NUMBER
: // Used in billing section.
1943 NOTREACHED(); // Trying to validate unknown field.
1947 return value
.empty() ? l10n_util::GetStringUTF16(
1948 IDS_LIBADDRESSINPUT_MISSING_REQUIRED_FIELD
) :
1952 // TODO(groby): Also add tests.
1953 ValidityMessages
AutofillDialogControllerImpl::InputsAreValid(
1954 DialogSection section
,
1955 const FieldValueMap
& inputs
) {
1956 ValidityMessages messages
;
1960 AddressValidator::Status status
= AddressValidator::SUCCESS
;
1961 if (section
!= SECTION_CC
) {
1962 AutofillProfile profile
;
1963 FillFormGroupFromOutputs(inputs
, &profile
);
1964 scoped_ptr
<AddressData
> address_data
=
1965 i18n::CreateAddressDataFromAutofillProfile(
1966 profile
, g_browser_process
->GetApplicationLocale());
1967 address_data
->language_code
= AddressLanguageCodeForSection(section
);
1969 Localization localization
;
1970 localization
.SetGetter(l10n_util::GetStringUTF8
);
1971 FieldProblemMap problems
;
1972 status
= GetValidator()->ValidateAddress(*address_data
, NULL
, &problems
);
1973 bool billing
= section
!= SECTION_SHIPPING
;
1975 for (FieldProblemMap::const_iterator iter
= problems
.begin();
1976 iter
!= problems
.end(); ++iter
) {
1977 bool sure
= iter
->second
!= MISSING_REQUIRED_FIELD
;
1978 base::string16 text
= base::UTF8ToUTF16(localization
.GetErrorMessage(
1979 *address_data
, iter
->first
, iter
->second
, true, false));
1980 messages
.Set(i18n::TypeForField(iter
->first
, billing
),
1981 ValidityMessage(text
, sure
));
1985 for (FieldValueMap::const_iterator iter
= inputs
.begin();
1986 iter
!= inputs
.end(); ++iter
) {
1987 const ServerFieldType type
= iter
->first
;
1988 base::string16 text
= InputValidityMessage(section
, type
, iter
->second
);
1990 // Skip empty/unchanged fields in edit mode. If the individual field does
1991 // not have validation errors, assume it to be valid unless later proven
1993 bool sure
= InputWasEdited(type
, iter
->second
);
1995 if (sure
&& status
== AddressValidator::RULES_NOT_READY
&&
1996 !ComboboxModelForAutofillType(type
) &&
1997 (AutofillType(type
).group() == ADDRESS_HOME
||
1998 AutofillType(type
).group() == ADDRESS_BILLING
)) {
1999 DCHECK(text
.empty());
2000 text
= l10n_util::GetStringUTF16(
2001 IDS_AUTOFILL_DIALOG_VALIDATION_WAITING_FOR_RULES
);
2003 needs_validation_
.insert(section
);
2006 messages
.Set(type
, ValidityMessage(text
, sure
));
2009 // For the convenience of using operator[].
2010 FieldValueMap
& field_values
= const_cast<FieldValueMap
&>(inputs
);
2011 // Validate the date formed by month and year field. (Autofill dialog is
2012 // never supposed to have 2-digit years, so not checked).
2013 if (field_values
.count(CREDIT_CARD_EXP_4_DIGIT_YEAR
) &&
2014 field_values
.count(CREDIT_CARD_EXP_MONTH
) &&
2015 InputWasEdited(CREDIT_CARD_EXP_4_DIGIT_YEAR
,
2016 field_values
[CREDIT_CARD_EXP_4_DIGIT_YEAR
]) &&
2017 InputWasEdited(CREDIT_CARD_EXP_MONTH
,
2018 field_values
[CREDIT_CARD_EXP_MONTH
])) {
2019 ValidityMessage
year_message(base::string16(), true);
2020 ValidityMessage
month_message(base::string16(), true);
2021 if (!IsCreditCardExpirationValid(field_values
[CREDIT_CARD_EXP_4_DIGIT_YEAR
],
2022 field_values
[CREDIT_CARD_EXP_MONTH
])) {
2023 // The dialog shows the same error message for the month and year fields.
2024 year_message
.text
= l10n_util::GetStringUTF16(
2025 IDS_AUTOFILL_DIALOG_VALIDATION_INVALID_CREDIT_CARD_EXPIRATION_DATE
);
2026 month_message
.text
= l10n_util::GetStringUTF16(
2027 IDS_AUTOFILL_DIALOG_VALIDATION_INVALID_CREDIT_CARD_EXPIRATION_DATE
);
2029 messages
.Set(CREDIT_CARD_EXP_4_DIGIT_YEAR
, year_message
);
2030 messages
.Set(CREDIT_CARD_EXP_MONTH
, month_message
);
2033 // If there is a credit card number and a CVC, validate them together.
2034 if (field_values
.count(CREDIT_CARD_NUMBER
) &&
2035 field_values
.count(CREDIT_CARD_VERIFICATION_CODE
)) {
2036 ValidityMessage
ccv_message(base::string16(), true);
2037 if (!autofill::IsValidCreditCardSecurityCode(
2038 field_values
[CREDIT_CARD_VERIFICATION_CODE
],
2039 field_values
[CREDIT_CARD_NUMBER
])) {
2040 ccv_message
.text
= l10n_util::GetStringUTF16(
2041 IDS_AUTOFILL_DIALOG_VALIDATION_INVALID_CREDIT_CARD_SECURITY_CODE
);
2043 messages
.Set(CREDIT_CARD_VERIFICATION_CODE
, ccv_message
);
2046 // Validate the shipping phone number against the country code of the address.
2047 if (field_values
.count(ADDRESS_HOME_COUNTRY
) &&
2048 field_values
.count(PHONE_HOME_WHOLE_NUMBER
)) {
2050 PHONE_HOME_WHOLE_NUMBER
,
2051 GetPhoneValidityMessage(field_values
[ADDRESS_HOME_COUNTRY
],
2052 field_values
[PHONE_HOME_WHOLE_NUMBER
]));
2055 // Validate the billing phone number against the country code of the address.
2056 if (field_values
.count(ADDRESS_BILLING_COUNTRY
) &&
2057 field_values
.count(PHONE_BILLING_WHOLE_NUMBER
)) {
2059 PHONE_BILLING_WHOLE_NUMBER
,
2060 GetPhoneValidityMessage(field_values
[ADDRESS_BILLING_COUNTRY
],
2061 field_values
[PHONE_BILLING_WHOLE_NUMBER
]));
2067 void AutofillDialogControllerImpl::UserEditedOrActivatedInput(
2068 DialogSection section
,
2069 ServerFieldType type
,
2070 gfx::NativeView parent_view
,
2071 const gfx::Rect
& content_bounds
,
2072 const base::string16
& field_contents
,
2074 ScopedViewUpdates
updates(view_
.get());
2076 if (type
== ADDRESS_BILLING_COUNTRY
|| type
== ADDRESS_HOME_COUNTRY
) {
2077 const FieldValueMap
& snapshot
= TakeUserInputSnapshot();
2079 // Clobber the inputs because the view's already been updated.
2080 RebuildInputsForCountry(section
, field_contents
, true);
2081 RestoreUserInputFromSnapshot(snapshot
);
2082 UpdateSection(section
);
2085 // The rest of this method applies only to textfields while Autofill is
2086 // enabled. If a combobox or Autofill is disabled, bail.
2087 if (ComboboxModelForAutofillType(type
) || !IsAutofillEnabled())
2090 // If the field is edited down to empty, don't show a popup.
2091 if (was_edit
&& field_contents
.empty()) {
2096 // If the user clicks while the popup is already showing, be sure to hide
2098 if (!was_edit
&& popup_controller_
.get()) {
2103 std::vector
<autofill::Suggestion
> popup_suggestions
;
2104 popup_suggestion_ids_
.clear();
2105 if (IsCreditCardType(type
)) {
2106 popup_suggestions
= GetManager()->GetCreditCardSuggestions(
2107 AutofillType(type
), field_contents
);
2108 for (const auto& suggestion
: popup_suggestions
)
2109 popup_suggestion_ids_
.push_back(suggestion
.backend_id
);
2111 popup_suggestions
= GetManager()->GetProfileSuggestions(
2115 RequestedTypesForSection(section
));
2116 // Filter out ones we don't want.
2117 for (int i
= 0; i
< static_cast<int>(popup_suggestions
.size()); i
++) {
2118 const autofill::AutofillProfile
* profile
=
2119 GetManager()->GetProfileByGUID(popup_suggestions
[i
].backend_id
.guid
);
2120 if (!profile
|| !ShouldSuggestProfile(section
, *profile
)) {
2121 popup_suggestions
.erase(popup_suggestions
.begin() + i
);
2127 for (const auto& suggestion
: popup_suggestions
)
2128 popup_suggestion_ids_
.push_back(suggestion
.backend_id
);
2130 // This will append to the popup_suggestions but not the IDs since there
2131 // are no backend IDs for the I18N validator suggestions.
2132 GetI18nValidatorSuggestions(section
, type
, &popup_suggestions
);
2135 if (popup_suggestions
.empty()) {
2140 // |popup_input_type_| must be set before calling |Show()|.
2141 popup_input_type_
= type
;
2142 popup_section_
= section
;
2144 // Use our own 0-based IDs for the items.
2145 // TODO(estade): do we need separators and control rows like 'Clear
2147 for (size_t i
= 0; i
< popup_suggestions
.size(); ++i
) {
2148 popup_suggestions
[i
].frontend_id
= i
;
2151 popup_controller_
= AutofillPopupControllerImpl::GetOrCreate(
2153 weak_ptr_factory_
.GetWeakPtr(),
2157 base::i18n::IsRTL() ?
2158 base::i18n::RIGHT_TO_LEFT
: base::i18n::LEFT_TO_RIGHT
);
2159 popup_controller_
->Show(popup_suggestions
);
2162 void AutofillDialogControllerImpl::FocusMoved() {
2166 bool AutofillDialogControllerImpl::ShouldShowErrorBubble() const {
2167 return popup_input_type_
== UNKNOWN_TYPE
;
2170 void AutofillDialogControllerImpl::ViewClosed() {
2171 GetManager()->RemoveObserver(this);
2173 // Called from here rather than in ~AutofillDialogControllerImpl as this
2174 // relies on virtual methods that change to their base class in the dtor.
2175 MaybeShowCreditCardBubble();
2180 std::vector
<DialogNotification
> AutofillDialogControllerImpl::
2181 CurrentNotifications() {
2182 std::vector
<DialogNotification
> notifications
;
2184 // TODO(dbeam): figure out a way to dismiss this error after a while.
2185 if (wallet_error_notification_
)
2186 notifications
.push_back(*wallet_error_notification_
);
2188 if (IsSubmitPausedOn(wallet::VERIFY_CVV
)) {
2189 notifications
.push_back(DialogNotification(
2190 DialogNotification::REQUIRED_ACTION
,
2191 l10n_util::GetStringUTF16(IDS_AUTOFILL_DIALOG_VERIFY_CVV
)));
2194 if (!wallet_server_validation_recoverable_
) {
2195 notifications
.push_back(DialogNotification(
2196 DialogNotification::REQUIRED_ACTION
,
2197 l10n_util::GetStringUTF16(
2198 IDS_AUTOFILL_DIALOG_FAILED_TO_SAVE_WALLET_DATA
)));
2201 if (choose_another_instrument_or_address_
) {
2202 notifications
.push_back(DialogNotification(
2203 DialogNotification::REQUIRED_ACTION
,
2204 l10n_util::GetStringUTF16(
2205 IDS_AUTOFILL_DIALOG_CHOOSE_DIFFERENT_WALLET_INSTRUMENT
)));
2208 if (notifications
.empty() && MenuModelForAccountChooser()) {
2209 base::string16 text
= l10n_util::GetStringUTF16(
2210 IsManuallyEditingAnySection() ?
2211 IDS_AUTOFILL_DIALOG_SAVE_DETAILS_IN_WALLET
:
2212 IDS_AUTOFILL_DIALOG_USE_WALLET
);
2213 DialogNotification
notification(
2214 DialogNotification::WALLET_USAGE_CONFIRMATION
,
2216 notification
.set_tooltip_text(
2217 l10n_util::GetStringUTF16(
2218 IDS_AUTOFILL_DIALOG_SAVE_IN_WALLET_TOOLTIP
));
2219 notification
.set_checked(IsPayingWithWallet());
2220 notifications
.push_back(notification
);
2223 if (IsPayingWithWallet() && !wallet::IsUsingProd()) {
2224 notifications
.push_back(DialogNotification(
2225 DialogNotification::DEVELOPER_WARNING
,
2226 l10n_util::GetStringUTF16(IDS_AUTOFILL_DIALOG_NOT_PROD_WARNING
)));
2229 if (!invoked_from_same_origin_
) {
2230 notifications
.push_back(DialogNotification(
2231 DialogNotification::SECURITY_WARNING
,
2232 l10n_util::GetStringFUTF16(IDS_AUTOFILL_DIALOG_SITE_WARNING
,
2233 base::UTF8ToUTF16(source_url_
.host()))));
2236 return notifications
;
2239 void AutofillDialogControllerImpl::LinkClicked(const GURL
& url
) {
2240 OpenTabWithUrl(url
);
2243 void AutofillDialogControllerImpl::SignInLinkClicked() {
2247 void AutofillDialogControllerImpl::ShowSignIn(const GURL
& url
) {
2248 ScopedViewUpdates
updates(view_
.get());
2250 if (SignedInState() == NOT_CHECKED
) {
2251 handling_use_wallet_link_click_
= true;
2252 account_chooser_model_
->SelectWalletAccount(0);
2253 FetchWalletCookie();
2254 } else if (signin_registrar_
.IsEmpty()) {
2256 waiting_for_explicit_sign_in_response_
= true;
2257 content::Source
<content::NavigationController
> source(
2258 view_
->ShowSignIn(url
));
2259 signin_registrar_
.Add(
2260 this, content::NOTIFICATION_NAV_ENTRY_COMMITTED
, source
);
2262 AutofillMetrics::LogDialogUiEvent(AutofillMetrics::DIALOG_UI_SIGNIN_SHOWN
);
2264 waiting_for_explicit_sign_in_response_
= false;
2268 view_
->UpdateAccountChooser();
2269 view_
->UpdateButtonStrip();
2272 void AutofillDialogControllerImpl::NotificationCheckboxStateChanged(
2273 DialogNotification::Type type
, bool checked
) {
2274 if (type
== DialogNotification::WALLET_USAGE_CONFIRMATION
) {
2276 account_chooser_model_
->SelectWalletAccount(
2277 GetWalletClient()->user_index());
2279 account_chooser_model_
->SelectUseAutofill();
2282 AccountChoiceChanged();
2286 void AutofillDialogControllerImpl::LegalDocumentLinkClicked(
2287 const gfx::Range
& range
) {
2288 for (size_t i
= 0; i
< legal_document_link_ranges_
.size(); ++i
) {
2289 if (legal_document_link_ranges_
[i
] == range
) {
2290 OpenTabWithUrl(wallet_items_
->legal_documents()[i
]->url());
2298 bool AutofillDialogControllerImpl::OnCancel() {
2300 if (!is_submitting_
)
2301 LogOnCancelMetrics();
2303 AutofillClient::AutocompleteResultErrorCancel
, base::string16(), NULL
);
2307 bool AutofillDialogControllerImpl::OnAccept() {
2308 ScopedViewUpdates
updates(view_
.get());
2309 choose_another_instrument_or_address_
= false;
2310 wallet_server_validation_recoverable_
= true;
2313 // This must come before SetIsSubmitting().
2314 if (IsPayingWithWallet()) {
2315 // In the VERIFY_CVV case, hold onto the previously submitted cardholder
2317 if (!IsSubmitPausedOn(wallet::VERIFY_CVV
)) {
2318 submitted_cardholder_name_
=
2319 GetValueFromSection(SECTION_CC_BILLING
, NAME_BILLING_FULL
);
2321 // Snag the last four digits of the backing card now as it could be wiped
2322 // out if a CVC challenge happens.
2323 if (ActiveInstrument()) {
2324 backing_card_last_four_
= ActiveInstrument()->TypeAndLastFourDigits();
2326 FieldValueMap output
;
2327 view_
->GetUserInput(SECTION_CC_BILLING
, &output
);
2329 GetBillingInfoFromOutputs(output
, &card
, NULL
, NULL
);
2330 backing_card_last_four_
= card
.TypeAndLastFourDigits();
2333 DCHECK(!submitted_cardholder_name_
.empty());
2334 DCHECK(!backing_card_last_four_
.empty());
2337 SetIsSubmitting(true);
2339 if (IsSubmitPausedOn(wallet::VERIFY_CVV
)) {
2340 DCHECK(!active_instrument_id_
.empty());
2341 full_wallet_
.reset();
2342 GetWalletClient()->AuthenticateInstrument(
2343 active_instrument_id_
,
2344 base::UTF16ToUTF8(view_
->GetCvc()));
2345 view_
->UpdateOverlay();
2346 } else if (IsPayingWithWallet()) {
2355 Profile
* AutofillDialogControllerImpl::profile() {
2359 content::WebContents
* AutofillDialogControllerImpl::GetWebContents() {
2360 return web_contents();
2363 ////////////////////////////////////////////////////////////////////////////////
2364 // AutofillPopupDelegate implementation.
2366 void AutofillDialogControllerImpl::OnPopupShown() {
2367 ScopedViewUpdates
update(view_
.get());
2368 view_
->UpdateErrorBubble();
2370 AutofillMetrics::LogDialogPopupEvent(AutofillMetrics::DIALOG_POPUP_SHOWN
);
2373 void AutofillDialogControllerImpl::OnPopupHidden() {}
2375 void AutofillDialogControllerImpl::DidSelectSuggestion(
2376 const base::string16
& value
,
2378 // TODO(estade): implement.
2381 void AutofillDialogControllerImpl::DidAcceptSuggestion(
2382 const base::string16
& value
,
2384 DCHECK_NE(UNKNOWN_TYPE
, popup_input_type_
);
2385 // Because |HidePopup()| can be called from |UpdateSection()|, remember the
2386 // type of the input for later here.
2387 const ServerFieldType popup_input_type
= popup_input_type_
;
2389 ScopedViewUpdates
updates(view_
.get());
2390 scoped_ptr
<DataModelWrapper
> wrapper
;
2392 if (static_cast<size_t>(identifier
) < popup_suggestion_ids_
.size()) {
2393 const SuggestionBackendID
& sid
= popup_suggestion_ids_
[identifier
];
2394 if (IsCreditCardType(popup_input_type
)) {
2395 wrapper
.reset(new AutofillCreditCardWrapper(
2396 GetManager()->GetCreditCardByGUID(sid
.guid
)));
2398 wrapper
.reset(new AutofillProfileWrapper(
2399 GetManager()->GetProfileByGUID(sid
.guid
),
2400 AutofillType(popup_input_type
),
2404 wrapper
.reset(new I18nAddressDataWrapper(
2405 &i18n_validator_suggestions_
[
2406 identifier
- popup_suggestion_ids_
.size()]));
2409 // If the user hasn't switched away from the default country and |wrapper|'s
2410 // country differs from the |view_|'s, rebuild inputs and restore user data.
2411 const FieldValueMap snapshot
= TakeUserInputSnapshot();
2412 bool billing_rebuilt
= false, shipping_rebuilt
= false;
2414 base::string16 billing_country
=
2415 wrapper
->GetInfo(AutofillType(ADDRESS_BILLING_COUNTRY
));
2416 if (popup_section_
== ActiveBillingSection() &&
2417 !snapshot
.count(ADDRESS_BILLING_COUNTRY
) &&
2418 !billing_country
.empty()) {
2419 billing_rebuilt
= RebuildInputsForCountry(
2420 ActiveBillingSection(), billing_country
, false);
2423 base::string16 shipping_country
=
2424 wrapper
->GetInfo(AutofillType(ADDRESS_HOME_COUNTRY
));
2425 if (popup_section_
== SECTION_SHIPPING
&&
2426 !snapshot
.count(ADDRESS_HOME_COUNTRY
) &&
2427 !shipping_country
.empty()) {
2428 shipping_rebuilt
= RebuildInputsForCountry(
2429 SECTION_SHIPPING
, shipping_country
, false);
2432 if (billing_rebuilt
|| shipping_rebuilt
) {
2433 RestoreUserInputFromSnapshot(snapshot
);
2434 if (billing_rebuilt
)
2435 UpdateSection(ActiveBillingSection());
2436 if (shipping_rebuilt
)
2437 UpdateSection(SECTION_SHIPPING
);
2440 DCHECK(SectionIsActive(popup_section_
));
2441 wrapper
->FillInputs(MutableRequestedFieldsForSection(popup_section_
));
2442 view_
->FillSection(popup_section_
, popup_input_type
);
2444 AutofillMetrics::LogDialogPopupEvent(
2445 AutofillMetrics::DIALOG_POPUP_FORM_FILLED
);
2447 // TODO(estade): not sure why it's necessary to do this explicitly.
2451 void AutofillDialogControllerImpl::RemoveSuggestion(
2452 const base::string16
& value
,
2454 // TODO(estade): implement.
2457 void AutofillDialogControllerImpl::ClearPreviewedForm() {
2458 // TODO(estade): implement.
2461 ////////////////////////////////////////////////////////////////////////////////
2462 // content::NotificationObserver implementation.
2464 void AutofillDialogControllerImpl::Observe(
2466 const content::NotificationSource
& source
,
2467 const content::NotificationDetails
& details
) {
2468 DCHECK_EQ(type
, content::NOTIFICATION_NAV_ENTRY_COMMITTED
);
2469 content::LoadCommittedDetails
* load_details
=
2470 content::Details
<content::LoadCommittedDetails
>(details
).ptr();
2471 size_t user_index
= 0;
2472 if (IsSignInContinueUrl(load_details
->entry
->GetVirtualURL(), &user_index
)) {
2473 GetWalletClient()->SetUserIndex(user_index
);
2474 FetchWalletCookie();
2476 // NOTE: |HideSignIn()| may delete the WebContents which doesn't expect to
2477 // be deleted while committing a nav entry. Just call |HideSignIn()| later.
2478 base::MessageLoop::current()->PostTask(FROM_HERE
,
2479 base::Bind(&AutofillDialogControllerImpl::HideSignIn
,
2480 base::Unretained(this)));
2484 ////////////////////////////////////////////////////////////////////////////////
2485 // SuggestionsMenuModelDelegate implementation.
2487 void AutofillDialogControllerImpl::SuggestionItemSelected(
2488 SuggestionsMenuModel
* model
,
2490 ScopedViewUpdates
updates(view_
.get());
2492 if (model
->GetItemKeyAt(index
) == kManageItemsKey
) {
2494 if (!IsPayingWithWallet()) {
2495 DCHECK(IsAutofillEnabled());
2496 GURL
settings_url(chrome::kChromeUISettingsURL
);
2497 url
= settings_url
.Resolve(chrome::kAutofillSubPage
);
2499 // Reset |last_wallet_items_fetch_timestamp_| to ensure that the Wallet
2500 // data is refreshed as soon as the user switches back to this tab after
2501 // potentially editing his data.
2502 last_wallet_items_fetch_timestamp_
= base::TimeTicks();
2503 size_t user_index
= GetWalletClient()->user_index();
2504 url
= SectionForSuggestionsMenuModel(*model
) == SECTION_SHIPPING
?
2505 wallet::GetManageAddressesUrl(user_index
) :
2506 wallet::GetManageInstrumentsUrl(user_index
);
2509 OpenTabWithUrl(url
);
2513 model
->SetCheckedIndex(index
);
2514 DialogSection section
= SectionForSuggestionsMenuModel(*model
);
2516 ResetSectionInput(section
);
2517 ShowEditUiIfBadSuggestion(section
);
2518 UpdateSection(section
);
2519 view_
->UpdateNotificationArea();
2522 LogSuggestionItemSelectedMetric(*model
);
2525 ////////////////////////////////////////////////////////////////////////////////
2526 // wallet::WalletClientDelegate implementation.
2528 std::string
AutofillDialogControllerImpl::GetRiskData() const {
2529 DCHECK(!risk_data_
.empty());
2533 std::string
AutofillDialogControllerImpl::GetWalletCookieValue() const {
2534 return wallet_cookie_value_
;
2537 bool AutofillDialogControllerImpl::IsShippingAddressRequired() const {
2538 return cares_about_shipping_
;
2541 void AutofillDialogControllerImpl::OnDidAcceptLegalDocuments() {
2542 DCHECK(is_submitting_
&& IsPayingWithWallet());
2543 has_accepted_legal_documents_
= true;
2544 LoadRiskFingerprintData();
2547 void AutofillDialogControllerImpl::OnDidAuthenticateInstrument(bool success
) {
2548 DCHECK(is_submitting_
&& IsPayingWithWallet());
2550 // TODO(dbeam): use the returned full wallet. http://crbug.com/224992
2554 DisableWallet(wallet::WalletClient::UNKNOWN_ERROR
);
2555 SuggestionsUpdated();
2559 void AutofillDialogControllerImpl::OnDidGetFullWallet(
2560 scoped_ptr
<wallet::FullWallet
> full_wallet
) {
2561 DCHECK(is_submitting_
&& IsPayingWithWallet());
2562 ScopedViewUpdates
updates(view_
.get());
2564 full_wallet_
= full_wallet
.Pass();
2566 if (full_wallet_
->required_actions().empty()) {
2571 switch (full_wallet_
->required_actions()[0]) {
2572 case wallet::CHOOSE_ANOTHER_INSTRUMENT_OR_ADDRESS
:
2573 choose_another_instrument_or_address_
= true;
2574 SetIsSubmitting(false);
2578 case wallet::VERIFY_CVV
:
2579 SuggestionsUpdated();
2583 DisableWallet(wallet::WalletClient::UNKNOWN_ERROR
);
2587 view_
->UpdateNotificationArea();
2588 view_
->UpdateButtonStrip();
2589 view_
->UpdateOverlay();
2592 void AutofillDialogControllerImpl::OnPassiveSigninSuccess() {
2593 FetchWalletCookie();
2596 void AutofillDialogControllerImpl::OnPassiveSigninFailure(
2597 const GoogleServiceAuthError
& error
) {
2598 signin_helper_
.reset();
2599 passive_failed_
= true;
2601 // When the user clicks on "use wallet" or a second account and passive auth
2602 // fails, try explicit sign in.
2603 if (handling_use_wallet_link_click_
|| GetWalletClient()->user_index() != 0) {
2604 ShowSignIn(wallet::GetSignInUrl(GetWalletClient()->user_index()));
2605 handling_use_wallet_link_click_
= false;
2608 OnWalletSigninError();
2611 void AutofillDialogControllerImpl::OnDidFetchWalletCookieValue(
2612 const std::string
& cookie_value
) {
2613 wallet_cookie_value_
= cookie_value
;
2614 signin_helper_
.reset();
2618 void AutofillDialogControllerImpl::OnDidGetWalletItems(
2619 scoped_ptr
<wallet::WalletItems
> wallet_items
) {
2620 legal_documents_text_
.clear();
2621 legal_document_link_ranges_
.clear();
2622 has_accepted_legal_documents_
= false;
2624 wallet_items_
= wallet_items
.Pass();
2626 if (wallet_items_
&& !wallet_items_
->ObfuscatedGaiaId().empty()) {
2627 // Making sure the user index is in sync shouldn't be necessary, but is an
2628 // extra precaution. But if there is no active account (such as in the
2629 // PASSIVE_AUTH case), stick with the old active account.
2630 GetWalletClient()->SetUserIndex(wallet_items_
->active_account_index());
2632 std::vector
<std::string
> usernames
;
2633 for (size_t i
= 0; i
< wallet_items_
->gaia_accounts().size(); ++i
) {
2634 usernames
.push_back(wallet_items_
->gaia_accounts()[i
]->email_address());
2636 account_chooser_model_
->SetWalletAccounts(
2637 usernames
, wallet_items_
->active_account_index());
2640 if (wallet_items_
) {
2641 shipping_country_combobox_model_
->SetCountries(
2643 base::Bind(WalletCountryFilter
,
2644 acceptable_shipping_countries_
,
2645 wallet_items_
->allowed_shipping_countries()));
2647 // If the site doesn't ship to any of the countries Wallet allows shipping
2648 // to, the merchant is not supported. (Note we generally shouldn't get here
2649 // as such a merchant wouldn't make it onto the Wallet whitelist.)
2650 if (shipping_country_combobox_model_
->GetItemCount() == 0)
2651 DisableWallet(wallet::WalletClient::UNSUPPORTED_MERCHANT
);
2654 ConstructLegalDocumentsText();
2655 OnWalletOrSigninUpdate();
2658 void AutofillDialogControllerImpl::OnDidSaveToWallet(
2659 const std::string
& instrument_id
,
2660 const std::string
& address_id
,
2661 const std::vector
<wallet::RequiredAction
>& required_actions
,
2662 const std::vector
<wallet::FormFieldError
>& form_field_errors
) {
2663 DCHECK(is_submitting_
&& IsPayingWithWallet());
2665 if (required_actions
.empty()) {
2666 if (!address_id
.empty())
2667 active_address_id_
= address_id
;
2668 if (!instrument_id
.empty())
2669 active_instrument_id_
= instrument_id
;
2672 OnWalletFormFieldError(form_field_errors
);
2673 HandleSaveOrUpdateRequiredActions(required_actions
);
2677 void AutofillDialogControllerImpl::OnWalletError(
2678 wallet::WalletClient::ErrorType error_type
) {
2679 DisableWallet(error_type
);
2682 ////////////////////////////////////////////////////////////////////////////////
2683 // PersonalDataManagerObserver implementation.
2685 void AutofillDialogControllerImpl::OnPersonalDataChanged() {
2689 SuggestionsUpdated();
2692 ////////////////////////////////////////////////////////////////////////////////
2693 // AccountChooserModelDelegate implementation.
2695 void AutofillDialogControllerImpl::AccountChoiceChanged() {
2696 ScopedViewUpdates
updates(view_
.get());
2697 wallet::WalletClient
* client
= GetWalletClient();
2700 client
->CancelRequest();
2702 SetIsSubmitting(false);
2704 size_t selected_user_index
=
2705 account_chooser_model_
->GetActiveWalletAccountIndex();
2706 if (account_chooser_model_
->WalletIsSelected() &&
2707 client
->user_index() != selected_user_index
) {
2708 client
->SetUserIndex(selected_user_index
);
2709 // Clear |wallet_items_| so we don't try to restore the selected instrument
2711 wallet_items_
.reset();
2714 SuggestionsUpdated();
2715 UpdateAccountChooserView();
2719 void AutofillDialogControllerImpl::AddAccount() {
2720 ShowSignIn(wallet::GetAddAccountUrl());
2723 void AutofillDialogControllerImpl::UpdateAccountChooserView() {
2725 ScopedViewUpdates
updates(view_
.get());
2726 view_
->UpdateAccountChooser();
2727 view_
->UpdateNotificationArea();
2731 ////////////////////////////////////////////////////////////////////////////////
2733 bool AutofillDialogControllerImpl::HandleKeyPressEventInInput(
2734 const content::NativeWebKeyboardEvent
& event
) {
2735 if (popup_controller_
.get())
2736 return popup_controller_
->HandleKeyPressEvent(event
);
2741 bool AutofillDialogControllerImpl::IsSubmitPausedOn(
2742 wallet::RequiredAction required_action
) const {
2743 return full_wallet_
&& full_wallet_
->HasRequiredAction(required_action
);
2746 void AutofillDialogControllerImpl::ShowNewCreditCardBubble(
2747 scoped_ptr
<CreditCard
> new_card
,
2748 scoped_ptr
<AutofillProfile
> billing_profile
) {
2749 NewCreditCardBubbleController::Show(web_contents(),
2751 billing_profile
.Pass());
2754 void AutofillDialogControllerImpl::SubmitButtonDelayBegin() {
2755 submit_button_delay_timer_
.Start(
2757 base::TimeDelta::FromMilliseconds(kSubmitButtonDelayMs
),
2759 &AutofillDialogControllerImpl::OnSubmitButtonDelayEnd
);
2762 void AutofillDialogControllerImpl::SubmitButtonDelayEndForTesting() {
2763 DCHECK(submit_button_delay_timer_
.IsRunning());
2764 submit_button_delay_timer_
.user_task().Run();
2765 submit_button_delay_timer_
.Stop();
2768 void AutofillDialogControllerImpl::
2769 ClearLastWalletItemsFetchTimestampForTesting() {
2770 last_wallet_items_fetch_timestamp_
= base::TimeTicks();
2773 AccountChooserModel
* AutofillDialogControllerImpl::
2774 AccountChooserModelForTesting() {
2775 return account_chooser_model_
.get();
2778 bool AutofillDialogControllerImpl::IsSignInContinueUrl(
2780 size_t* user_index
) const {
2781 return wallet::IsSignInContinueUrl(url
, user_index
);
2784 AutofillDialogControllerImpl::AutofillDialogControllerImpl(
2785 content::WebContents
* contents
,
2786 const FormData
& form_structure
,
2787 const GURL
& source_url
,
2788 const AutofillClient::ResultCallback
& callback
)
2789 : WebContentsObserver(contents
),
2790 profile_(Profile::FromBrowserContext(contents
->GetBrowserContext())),
2791 initial_user_state_(AutofillMetrics::DIALOG_USER_STATE_UNKNOWN
),
2792 form_structure_(form_structure
),
2793 invoked_from_same_origin_(true),
2794 source_url_(source_url
),
2795 callback_(callback
),
2796 wallet_client_(profile_
->GetRequestContext(), this, source_url
),
2797 wallet_items_requested_(false),
2798 handling_use_wallet_link_click_(false),
2799 passive_failed_(false),
2800 suggested_cc_(this),
2801 suggested_billing_(this),
2802 suggested_cc_billing_(this),
2803 suggested_shipping_(this),
2804 cares_about_shipping_(true),
2805 popup_input_type_(UNKNOWN_TYPE
),
2806 popup_section_(SECTION_MIN
),
2807 waiting_for_explicit_sign_in_response_(false),
2808 has_accepted_legal_documents_(false),
2809 is_submitting_(false),
2810 choose_another_instrument_or_address_(false),
2811 wallet_server_validation_recoverable_(true),
2812 data_was_passed_back_(false),
2813 was_ui_latency_logged_(false),
2814 card_generated_animation_(2000, 60, this),
2815 weak_ptr_factory_(this) {
2816 DCHECK(!callback_
.is_null());
2819 AutofillDialogView
* AutofillDialogControllerImpl::CreateView() {
2820 return AutofillDialogView::Create(this);
2823 PersonalDataManager
* AutofillDialogControllerImpl::GetManager() const {
2824 return PersonalDataManagerFactory::GetForProfile(profile_
);
2827 AddressValidator
* AutofillDialogControllerImpl::GetValidator() {
2828 return validator_
.get();
2831 const wallet::WalletClient
* AutofillDialogControllerImpl::GetWalletClient()
2833 return const_cast<AutofillDialogControllerImpl
*>(this)->GetWalletClient();
2836 wallet::WalletClient
* AutofillDialogControllerImpl::GetWalletClient() {
2837 return &wallet_client_
;
2840 bool AutofillDialogControllerImpl::IsPayingWithWallet() const {
2841 return account_chooser_model_
->WalletIsSelected() &&
2842 SignedInState() == SIGNED_IN
;
2845 void AutofillDialogControllerImpl::LoadRiskFingerprintData() {
2848 uint64 obfuscated_gaia_id
= 0;
2849 bool success
= base::StringToUint64(wallet_items_
->ObfuscatedGaiaId(),
2850 &obfuscated_gaia_id
);
2854 obfuscated_gaia_id
, web_contents(),
2855 base::Bind(&AutofillDialogControllerImpl::OnDidLoadRiskFingerprintData
,
2856 weak_ptr_factory_
.GetWeakPtr()));
2859 void AutofillDialogControllerImpl::OnDidLoadRiskFingerprintData(
2860 const std::string
& risk_data
) {
2861 DCHECK(AreLegalDocumentsCurrent());
2862 risk_data_
= risk_data
;
2866 void AutofillDialogControllerImpl::OpenTabWithUrl(const GURL
& url
) {
2867 chrome::NavigateParams
params(
2868 chrome::FindBrowserWithWebContents(web_contents()),
2870 ui::PAGE_TRANSITION_LINK
);
2871 params
.disposition
= NEW_FOREGROUND_TAB
;
2872 chrome::Navigate(¶ms
);
2875 DialogSection
AutofillDialogControllerImpl::ActiveBillingSection() const {
2876 return IsPayingWithWallet() ? SECTION_CC_BILLING
: SECTION_BILLING
;
2879 bool AutofillDialogControllerImpl::IsEditingExistingData(
2880 DialogSection section
) const {
2881 return section_editing_state_
.count(section
) > 0;
2884 bool AutofillDialogControllerImpl::IsManuallyEditingSection(
2885 DialogSection section
) const {
2886 return IsEditingExistingData(section
) ||
2887 SuggestionsMenuModelForSection(section
)->
2888 GetItemKeyForCheckedItem() == kAddNewItemKey
;
2891 void AutofillDialogControllerImpl::OnWalletSigninError() {
2892 account_chooser_model_
->SetHadWalletSigninError();
2893 GetWalletClient()->CancelRequest();
2894 LogDialogLatencyToShow();
2897 void AutofillDialogControllerImpl::DisableWallet(
2898 wallet::WalletClient::ErrorType error_type
) {
2899 signin_helper_
.reset();
2900 wallet_items_
.reset();
2901 wallet_errors_
.clear();
2902 GetWalletClient()->CancelRequest();
2903 SetIsSubmitting(false);
2904 wallet_error_notification_
= GetWalletError(error_type
);
2905 account_chooser_model_
->SetHadWalletError();
2908 void AutofillDialogControllerImpl::SuggestionsUpdated() {
2909 ScopedViewUpdates
updates(view_
.get());
2911 const FieldValueMap snapshot
= TakeUserInputSnapshot();
2913 suggested_cc_
.Reset();
2914 suggested_billing_
.Reset();
2915 suggested_cc_billing_
.Reset();
2916 suggested_shipping_
.Reset();
2919 suggested_shipping_
.AddKeyedItem(
2921 l10n_util::GetStringUTF16(IDS_AUTOFILL_DIALOG_USE_BILLING_FOR_SHIPPING
));
2923 if (IsPayingWithWallet()) {
2924 const std::vector
<wallet::Address
*>& addresses
=
2925 wallet_items_
->addresses();
2927 bool shipping_same_as_billing
= profile_
->GetPrefs()->GetBoolean(
2928 ::prefs::kAutofillDialogWalletShippingSameAsBilling
);
2930 if (shipping_same_as_billing
)
2931 suggested_shipping_
.SetCheckedItem(kSameAsBillingKey
);
2933 for (size_t i
= 0; i
< addresses
.size(); ++i
) {
2934 std::string key
= base::IntToString(i
);
2935 suggested_shipping_
.AddKeyedItemWithMinorText(
2937 addresses
[i
]->DisplayName(),
2938 addresses
[i
]->DisplayNameDetail());
2939 suggested_shipping_
.SetEnabled(
2941 CanAcceptCountry(SECTION_SHIPPING
,
2942 addresses
[i
]->country_name_code()));
2944 // TODO(scr): Move this assignment outside the loop or comment why it
2946 const std::string default_shipping_address_id
=
2947 GetIdToSelect(wallet_items_
->default_address_id(),
2948 previous_default_shipping_address_id_
,
2949 previously_selected_shipping_address_id_
);
2951 if (!shipping_same_as_billing
&&
2952 addresses
[i
]->object_id() == default_shipping_address_id
) {
2953 suggested_shipping_
.SetCheckedItem(key
);
2957 if (!IsSubmitPausedOn(wallet::VERIFY_CVV
)) {
2958 const std::vector
<wallet::WalletItems::MaskedInstrument
*>& instruments
=
2959 wallet_items_
->instruments();
2960 std::string first_active_instrument_key
;
2961 std::string default_instrument_key
;
2962 for (size_t i
= 0; i
< instruments
.size(); ++i
) {
2963 bool allowed
= IsInstrumentAllowed(*instruments
[i
]) &&
2964 CanAcceptCountry(SECTION_BILLING
,
2965 instruments
[i
]->address().country_name_code());
2966 gfx::Image icon
= instruments
[i
]->CardIcon();
2967 if (!allowed
&& !icon
.IsEmpty()) {
2968 // Create a grayed disabled icon.
2969 SkBitmap disabled_bitmap
= SkBitmapOperations::CreateHSLShiftedBitmap(
2970 *icon
.ToSkBitmap(), kGrayImageShift
);
2972 gfx::ImageSkia::CreateFrom1xBitmap(disabled_bitmap
));
2974 std::string key
= base::IntToString(i
);
2975 suggested_cc_billing_
.AddKeyedItemWithMinorTextAndIcon(
2977 instruments
[i
]->DisplayName(),
2978 instruments
[i
]->DisplayNameDetail(),
2980 suggested_cc_billing_
.SetEnabled(key
, allowed
);
2983 if (first_active_instrument_key
.empty())
2984 first_active_instrument_key
= key
;
2986 const std::string default_instrument_id
=
2987 GetIdToSelect(wallet_items_
->default_instrument_id(),
2988 previous_default_instrument_id_
,
2989 previously_selected_instrument_id_
);
2990 if (instruments
[i
]->object_id() == default_instrument_id
)
2991 default_instrument_key
= key
;
2995 suggested_cc_billing_
.AddKeyedItem(
2997 l10n_util::GetStringUTF16(IDS_AUTOFILL_DIALOG_ADD_BILLING_DETAILS
));
2998 if (!wallet_items_
->HasRequiredAction(wallet::SETUP_WALLET
)) {
2999 suggested_cc_billing_
.AddKeyedItemWithMinorText(
3001 l10n_util::GetStringUTF16(
3002 IDS_AUTOFILL_DIALOG_MANAGE_BILLING_DETAILS
),
3003 base::UTF8ToUTF16(wallet::GetManageInstrumentsUrl(0U).host()));
3006 // Determine which instrument item should be selected.
3007 if (!default_instrument_key
.empty())
3008 suggested_cc_billing_
.SetCheckedItem(default_instrument_key
);
3009 else if (!first_active_instrument_key
.empty())
3010 suggested_cc_billing_
.SetCheckedItem(first_active_instrument_key
);
3012 suggested_cc_billing_
.SetCheckedItem(kAddNewItemKey
);
3015 shipping_country_combobox_model_
->SetCountries(
3017 base::Bind(AutofillCountryFilter
, acceptable_shipping_countries_
));
3019 if (IsAutofillEnabled()) {
3020 PersonalDataManager
* manager
= GetManager();
3021 const std::vector
<CreditCard
*>& cards
= manager
->GetCreditCards();
3022 ui::ResourceBundle
& rb
= ui::ResourceBundle::GetSharedInstance();
3023 for (size_t i
= 0; i
< cards
.size(); ++i
) {
3024 if (!i18ninput::CardHasCompleteAndVerifiedData(*cards
[i
]))
3027 suggested_cc_
.AddKeyedItemWithIcon(
3030 rb
.GetImageNamed(CreditCard::IconResourceId(cards
[i
]->type())));
3031 suggested_cc_
.SetEnabled(
3033 !ShouldDisallowCcType(cards
[i
]->TypeForDisplay()));
3036 const std::vector
<AutofillProfile
*>& profiles
= manager
->GetProfiles();
3037 std::vector
<base::string16
> labels
;
3038 AutofillProfile::CreateDifferentiatingLabels(
3040 g_browser_process
->GetApplicationLocale(),
3042 DCHECK_EQ(labels
.size(), profiles
.size());
3043 for (size_t i
= 0; i
< profiles
.size(); ++i
) {
3044 const AutofillProfile
& profile
= *profiles
[i
];
3045 if (!i18ninput::AddressHasCompleteAndVerifiedData(
3046 profile
, g_browser_process
->GetApplicationLocale())) {
3050 // Don't add variants for addresses: name is part of credit card and
3051 // we'll just ignore email and phone number variants.
3052 suggested_shipping_
.AddKeyedItem(profile
.guid(), labels
[i
]);
3053 suggested_shipping_
.SetEnabled(
3057 base::UTF16ToUTF8(profile
.GetRawInfo(ADDRESS_HOME_COUNTRY
))));
3058 if (!profile
.GetRawInfo(EMAIL_ADDRESS
).empty() &&
3059 !profile
.IsPresentButInvalid(EMAIL_ADDRESS
)) {
3060 suggested_billing_
.AddKeyedItem(profile
.guid(), labels
[i
]);
3061 suggested_billing_
.SetEnabled(
3065 base::UTF16ToUTF8(profile
.GetRawInfo(ADDRESS_HOME_COUNTRY
))));
3070 suggested_cc_
.AddKeyedItem(
3072 l10n_util::GetStringUTF16(IsAutofillEnabled() ?
3073 IDS_AUTOFILL_DIALOG_ADD_CREDIT_CARD
:
3074 IDS_AUTOFILL_DIALOG_ENTER_CREDIT_CARD
));
3075 suggested_cc_
.AddKeyedItem(
3077 l10n_util::GetStringUTF16(IDS_AUTOFILL_DIALOG_MANAGE_CREDIT_CARD
));
3078 suggested_billing_
.AddKeyedItem(
3080 l10n_util::GetStringUTF16(IsAutofillEnabled() ?
3081 IDS_AUTOFILL_DIALOG_ADD_BILLING_ADDRESS
:
3082 IDS_AUTOFILL_DIALOG_ENTER_BILLING_DETAILS
));
3083 suggested_billing_
.AddKeyedItem(
3085 l10n_util::GetStringUTF16(IDS_AUTOFILL_DIALOG_MANAGE_BILLING_ADDRESS
));
3088 suggested_shipping_
.AddKeyedItem(
3090 l10n_util::GetStringUTF16(IsPayingWithWallet() || IsAutofillEnabled() ?
3091 IDS_AUTOFILL_DIALOG_ADD_SHIPPING_ADDRESS
:
3092 IDS_AUTOFILL_DIALOG_USE_DIFFERENT_SHIPPING_ADDRESS
));
3094 if (!IsPayingWithWallet()) {
3095 if (IsAutofillEnabled()) {
3096 suggested_shipping_
.AddKeyedItem(
3098 l10n_util::GetStringUTF16(
3099 IDS_AUTOFILL_DIALOG_MANAGE_SHIPPING_ADDRESS
));
3101 } else if (!wallet_items_
->HasRequiredAction(wallet::SETUP_WALLET
)) {
3102 suggested_shipping_
.AddKeyedItemWithMinorText(
3104 l10n_util::GetStringUTF16(IDS_AUTOFILL_DIALOG_MANAGE_SHIPPING_ADDRESS
),
3105 base::UTF8ToUTF16(wallet::GetManageAddressesUrl(0U).host()));
3108 if (!IsPayingWithWallet() && IsAutofillEnabled()) {
3109 for (size_t i
= SECTION_MIN
; i
<= SECTION_MAX
; ++i
) {
3110 DialogSection section
= static_cast<DialogSection
>(i
);
3111 if (!SectionIsActive(section
))
3114 // Set the starting choice for the menu. First set to the default in case
3115 // the GUID saved in prefs refers to a profile that no longer exists.
3117 GetDefaultAutofillChoice(section
, &guid
);
3118 SuggestionsMenuModel
* model
= SuggestionsMenuModelForSection(section
);
3119 model
->SetCheckedItem(guid
);
3120 if (GetAutofillChoice(section
, &guid
))
3121 model
->SetCheckedItem(guid
);
3126 view_
->ModelChanged();
3128 for (size_t i
= SECTION_MIN
; i
<= SECTION_MAX
; ++i
) {
3129 ResetSectionInput(static_cast<DialogSection
>(i
));
3132 FieldValueMap::const_iterator billing_it
=
3133 snapshot
.find(ADDRESS_BILLING_COUNTRY
);
3134 if (billing_it
!= snapshot
.end())
3135 RebuildInputsForCountry(ActiveBillingSection(), billing_it
->second
, true);
3137 FieldValueMap::const_iterator shipping_it
=
3138 snapshot
.find(ADDRESS_HOME_COUNTRY
);
3139 if (shipping_it
!= snapshot
.end())
3140 RebuildInputsForCountry(SECTION_SHIPPING
, shipping_it
->second
, true);
3142 RestoreUserInputFromSnapshot(snapshot
);
3144 for (size_t i
= SECTION_MIN
; i
<= SECTION_MAX
; ++i
) {
3145 DialogSection section
= static_cast<DialogSection
>(i
);
3146 if (!SectionIsActive(section
))
3149 ShowEditUiIfBadSuggestion(section
);
3150 UpdateSection(section
);
3156 void AutofillDialogControllerImpl::FillOutputForSectionWithComparator(
3157 DialogSection section
,
3158 const FormStructure::InputFieldComparator
& compare
) {
3159 if (!SectionIsActive(section
))
3162 DetailInputs inputs
;
3163 std::string country_code
= CountryCodeForSection(section
);
3164 BuildInputsForSection(section
, country_code
, &inputs
,
3165 MutableAddressLanguageCodeForSection(section
));
3166 std::vector
<ServerFieldType
> types
= TypesFromInputs(inputs
);
3168 scoped_ptr
<DataModelWrapper
> wrapper
= CreateWrapper(section
);
3170 // Only fill in data that is associated with this section.
3171 wrapper
->FillFormStructure(types
, compare
, &form_structure_
);
3173 // CVC needs special-casing because the CreditCard class doesn't store or
3174 // handle them. This isn't necessary when filling the combined CC and
3175 // billing section as CVC comes from |full_wallet_| in this case.
3176 if (section
== SECTION_CC
)
3177 SetOutputForFieldsOfType(CREDIT_CARD_VERIFICATION_CODE
, view_
->GetCvc());
3179 // When filling from Wallet data, use the email address associated with the
3180 // account. There is no other email address stored as part of a Wallet
3182 if (section
== SECTION_CC_BILLING
) {
3183 SetOutputForFieldsOfType(
3184 EMAIL_ADDRESS
, account_chooser_model_
->GetActiveWalletAccountName());
3187 // The user manually input data. If using Autofill, save the info as new or
3188 // edited data. Always fill local data into |form_structure_|.
3189 FieldValueMap output
;
3190 view_
->GetUserInput(section
, &output
);
3192 if (section
== SECTION_CC
) {
3194 FillFormGroupFromOutputs(output
, &card
);
3196 // The card holder name comes from the billing address section.
3197 card
.SetRawInfo(CREDIT_CARD_NAME
,
3198 GetValueFromSection(SECTION_BILLING
, NAME_BILLING_FULL
));
3200 if (ShouldSaveDetailsLocally()) {
3201 card
.set_origin(kAutofillDialogOrigin
);
3203 std::string guid
= GetManager()->SaveImportedCreditCard(card
);
3204 newly_saved_data_model_guids_
[section
] = guid
;
3205 DCHECK(!profile()->IsOffTheRecord());
3206 newly_saved_card_
.reset(new CreditCard(card
));
3209 AutofillCreditCardWrapper
card_wrapper(&card
);
3210 card_wrapper
.FillFormStructure(types
, compare
, &form_structure_
);
3212 // Again, CVC needs special-casing. Fill it in directly from |output|.
3213 SetOutputForFieldsOfType(
3214 CREDIT_CARD_VERIFICATION_CODE
,
3215 output
[CREDIT_CARD_VERIFICATION_CODE
]);
3217 AutofillProfile profile
;
3218 FillFormGroupFromOutputs(output
, &profile
);
3219 profile
.set_language_code(AddressLanguageCodeForSection(section
));
3221 if (ShouldSaveDetailsLocally()) {
3222 profile
.set_origin(RulesAreLoaded(section
) ?
3223 kAutofillDialogOrigin
: source_url_
.GetOrigin().spec());
3225 std::string guid
= GetManager()->SaveImportedProfile(profile
);
3226 newly_saved_data_model_guids_
[section
] = guid
;
3229 AutofillProfileWrapper
profile_wrapper(&profile
);
3230 profile_wrapper
.FillFormStructure(types
, compare
, &form_structure_
);
3235 void AutofillDialogControllerImpl::FillOutputForSection(DialogSection section
) {
3236 FillOutputForSectionWithComparator(
3237 section
, base::Bind(ServerTypeMatchesField
, section
));
3240 bool AutofillDialogControllerImpl::FormStructureCaresAboutSection(
3241 DialogSection section
) const {
3242 // For now, only SECTION_SHIPPING may be omitted due to a site not asking for
3243 // any of the fields.
3244 if (section
== SECTION_SHIPPING
)
3245 return cares_about_shipping_
;
3250 void AutofillDialogControllerImpl::SetOutputForFieldsOfType(
3251 ServerFieldType type
,
3252 const base::string16
& output
) {
3253 for (size_t i
= 0; i
< form_structure_
.field_count(); ++i
) {
3254 AutofillField
* field
= form_structure_
.field(i
);
3255 if (field
->Type().GetStorableType() == type
)
3256 field
->value
= output
;
3260 base::string16
AutofillDialogControllerImpl::GetValueFromSection(
3261 DialogSection section
,
3262 ServerFieldType type
) {
3263 DCHECK(SectionIsActive(section
));
3265 scoped_ptr
<DataModelWrapper
> wrapper
= CreateWrapper(section
);
3267 return wrapper
->GetInfo(AutofillType(type
));
3269 FieldValueMap output
;
3270 view_
->GetUserInput(section
, &output
);
3271 return output
[type
];
3274 bool AutofillDialogControllerImpl::CanAcceptCountry(
3275 DialogSection section
,
3276 const std::string
& country_code
) {
3277 DCHECK_EQ(2U, country_code
.size());
3279 if (section
== SECTION_CC_BILLING
)
3280 return LowerCaseEqualsASCII(country_code
, "us");
3282 CountryComboboxModel
* model
= CountryComboboxModelForSection(section
);
3283 const std::vector
<AutofillCountry
*>& countries
= model
->countries();
3284 for (size_t i
= 0; i
< countries
.size(); ++i
) {
3285 if (countries
[i
] && countries
[i
]->country_code() == country_code
)
3292 bool AutofillDialogControllerImpl::ShouldSuggestProfile(
3293 DialogSection section
,
3294 const AutofillProfile
& profile
) {
3295 std::string country_code
=
3296 base::UTF16ToASCII(profile
.GetRawInfo(ADDRESS_HOME_COUNTRY
));
3297 return country_code
.empty() || CanAcceptCountry(section
, country_code
);
3300 SuggestionsMenuModel
* AutofillDialogControllerImpl::
3301 SuggestionsMenuModelForSection(DialogSection section
) {
3304 return &suggested_cc_
;
3305 case SECTION_BILLING
:
3306 return &suggested_billing_
;
3307 case SECTION_SHIPPING
:
3308 return &suggested_shipping_
;
3309 case SECTION_CC_BILLING
:
3310 return &suggested_cc_billing_
;
3317 const SuggestionsMenuModel
* AutofillDialogControllerImpl::
3318 SuggestionsMenuModelForSection(DialogSection section
) const {
3319 return const_cast<AutofillDialogControllerImpl
*>(this)->
3320 SuggestionsMenuModelForSection(section
);
3323 DialogSection
AutofillDialogControllerImpl::SectionForSuggestionsMenuModel(
3324 const SuggestionsMenuModel
& model
) {
3325 if (&model
== &suggested_cc_
)
3328 if (&model
== &suggested_billing_
)
3329 return SECTION_BILLING
;
3331 if (&model
== &suggested_cc_billing_
)
3332 return SECTION_CC_BILLING
;
3334 DCHECK_EQ(&model
, &suggested_shipping_
);
3335 return SECTION_SHIPPING
;
3338 CountryComboboxModel
* AutofillDialogControllerImpl::
3339 CountryComboboxModelForSection(DialogSection section
) {
3340 if (section
== SECTION_BILLING
)
3341 return billing_country_combobox_model_
.get();
3343 if (section
== SECTION_SHIPPING
)
3344 return shipping_country_combobox_model_
.get();
3349 void AutofillDialogControllerImpl::GetI18nValidatorSuggestions(
3350 DialogSection section
,
3351 ServerFieldType type
,
3352 std::vector
<autofill::Suggestion
>* popup_suggestions
) {
3353 AddressField focused_field
;
3354 if (!i18n::FieldForType(type
, &focused_field
))
3357 FieldValueMap inputs
;
3358 view_
->GetUserInput(section
, &inputs
);
3360 AutofillProfile profile
;
3361 FillFormGroupFromOutputs(inputs
, &profile
);
3363 scoped_ptr
<AddressData
> user_input
=
3364 i18n::CreateAddressDataFromAutofillProfile(
3365 profile
, g_browser_process
->GetApplicationLocale());
3366 user_input
->language_code
= AddressLanguageCodeForSection(section
);
3368 static const size_t kSuggestionsLimit
= 10;
3369 AddressValidator::Status status
= GetValidator()->GetSuggestions(
3370 *user_input
, focused_field
, kSuggestionsLimit
,
3371 &i18n_validator_suggestions_
);
3373 if (status
!= AddressValidator::SUCCESS
)
3376 for (size_t i
= 0; i
< i18n_validator_suggestions_
.size(); ++i
) {
3377 popup_suggestions
->push_back(autofill::Suggestion(
3379 i18n_validator_suggestions_
[i
].GetFieldValue(focused_field
))));
3381 // Disambiguate the suggestion by showing the smallest administrative
3382 // region of the suggested address:
3383 // ADMIN_AREA > LOCALITY > DEPENDENT_LOCALITY
3384 for (int field
= DEPENDENT_LOCALITY
; field
>= ADMIN_AREA
; --field
) {
3385 const std::string
& field_value
=
3386 i18n_validator_suggestions_
[i
].GetFieldValue(
3387 static_cast<AddressField
>(field
));
3388 if (focused_field
!= field
&& !field_value
.empty()) {
3389 popup_suggestions
->back().label
= base::UTF8ToUTF16(field_value
);
3396 DetailInputs
* AutofillDialogControllerImpl::MutableRequestedFieldsForSection(
3397 DialogSection section
) {
3398 return const_cast<DetailInputs
*>(&RequestedFieldsForSection(section
));
3401 std::string
* AutofillDialogControllerImpl::MutableAddressLanguageCodeForSection(
3402 DialogSection section
) {
3404 case SECTION_BILLING
:
3405 case SECTION_CC_BILLING
:
3406 return &billing_address_language_code_
;
3407 case SECTION_SHIPPING
:
3408 return &shipping_address_language_code_
;
3416 std::string
AutofillDialogControllerImpl::AddressLanguageCodeForSection(
3417 DialogSection section
) {
3418 std::string
* language_code
= MutableAddressLanguageCodeForSection(section
);
3419 return language_code
!= NULL
? *language_code
: std::string();
3422 std::vector
<ServerFieldType
> AutofillDialogControllerImpl::
3423 RequestedTypesForSection(DialogSection section
) const {
3424 return TypesFromInputs(RequestedFieldsForSection(section
));
3427 std::string
AutofillDialogControllerImpl::CountryCodeForSection(
3428 DialogSection section
) {
3429 base::string16 country
;
3431 scoped_ptr
<DataModelWrapper
> wrapper
= CreateWrapper(section
);
3433 country
= wrapper
->GetInfo(AutofillType(CountryTypeForSection(section
)));
3435 FieldValueMap outputs
;
3436 view_
->GetUserInput(section
, &outputs
);
3437 country
= outputs
[CountryTypeForSection(section
)];
3440 return AutofillCountry::GetCountryCode(
3441 country
, g_browser_process
->GetApplicationLocale());
3444 bool AutofillDialogControllerImpl::RebuildInputsForCountry(
3445 DialogSection section
,
3446 const base::string16
& country_name
,
3447 bool should_clobber
) {
3448 CountryComboboxModel
* model
= CountryComboboxModelForSection(section
);
3452 std::string country_code
= AutofillCountry::GetCountryCode(
3453 country_name
, g_browser_process
->GetApplicationLocale());
3454 DCHECK(CanAcceptCountry(section
, country_code
));
3456 if (view_
&& !should_clobber
) {
3457 FieldValueMap outputs
;
3458 view_
->GetUserInput(section
, &outputs
);
3460 // If |country_name| is the same as the view, no-op and let the caller know.
3461 if (outputs
[CountryTypeForSection(section
)] == country_name
)
3465 DetailInputs
* inputs
= MutableRequestedFieldsForSection(section
);
3467 BuildInputsForSection(section
, country_code
, inputs
,
3468 MutableAddressLanguageCodeForSection(section
));
3470 if (!country_code
.empty()) {
3471 GetValidator()->LoadRules(AutofillCountry::GetCountryCode(
3472 country_name
, g_browser_process
->GetApplicationLocale()));
3478 void AutofillDialogControllerImpl::HidePopup() {
3479 if (popup_controller_
)
3480 popup_controller_
->Hide();
3481 popup_input_type_
= UNKNOWN_TYPE
;
3484 void AutofillDialogControllerImpl::SetEditingExistingData(
3485 DialogSection section
, bool editing
) {
3487 section_editing_state_
.insert(section
);
3489 section_editing_state_
.erase(section
);
3492 bool AutofillDialogControllerImpl::IsASuggestionItemKey(
3493 const std::string
& key
) const {
3494 return !key
.empty() &&
3495 key
!= kAddNewItemKey
&&
3496 key
!= kManageItemsKey
&&
3497 key
!= kSameAsBillingKey
;
3500 bool AutofillDialogControllerImpl::IsAutofillEnabled() const {
3501 return profile_
->GetPrefs()->GetBoolean(prefs::kAutofillEnabled
);
3504 bool AutofillDialogControllerImpl::IsManuallyEditingAnySection() const {
3505 for (size_t section
= SECTION_MIN
; section
<= SECTION_MAX
; ++section
) {
3506 if (IsManuallyEditingSection(static_cast<DialogSection
>(section
)))
3512 base::string16
AutofillDialogControllerImpl::CreditCardNumberValidityMessage(
3513 const base::string16
& number
) const {
3514 if (!number
.empty() && !autofill::IsValidCreditCardNumber(number
)) {
3515 return l10n_util::GetStringUTF16(
3516 IDS_AUTOFILL_DIALOG_VALIDATION_INVALID_CREDIT_CARD_NUMBER
);
3519 if (!IsPayingWithWallet() &&
3520 ShouldDisallowCcType(CreditCard::TypeForDisplay(
3521 CreditCard::GetCreditCardType(number
)))) {
3522 int ids
= IDS_AUTOFILL_DIALOG_VALIDATION_UNACCEPTED_GENERIC_CARD
;
3523 const char* const type
= CreditCard::GetCreditCardType(number
);
3524 if (type
== kAmericanExpressCard
)
3525 ids
= IDS_AUTOFILL_DIALOG_VALIDATION_UNACCEPTED_AMEX
;
3526 else if (type
== kDiscoverCard
)
3527 ids
= IDS_AUTOFILL_DIALOG_VALIDATION_UNACCEPTED_DISCOVER
;
3528 else if (type
== kMasterCard
)
3529 ids
= IDS_AUTOFILL_DIALOG_VALIDATION_UNACCEPTED_MASTERCARD
;
3530 else if (type
== kVisaCard
)
3531 ids
= IDS_AUTOFILL_DIALOG_VALIDATION_UNACCEPTED_VISA
;
3533 return l10n_util::GetStringUTF16(ids
);
3536 base::string16 message
;
3537 if (IsPayingWithWallet() && !wallet_items_
->SupportsCard(number
, &message
))
3540 // Card number is good and supported.
3541 return base::string16();
3544 bool AutofillDialogControllerImpl::AllSectionsAreValid() {
3545 for (size_t section
= SECTION_MIN
; section
<= SECTION_MAX
; ++section
) {
3546 if (!SectionIsValid(static_cast<DialogSection
>(section
)))
3552 bool AutofillDialogControllerImpl::SectionIsValid(
3553 DialogSection section
) {
3554 if (!IsManuallyEditingSection(section
))
3557 FieldValueMap detail_outputs
;
3558 view_
->GetUserInput(section
, &detail_outputs
);
3559 return !InputsAreValid(section
, detail_outputs
).HasSureErrors();
3562 bool AutofillDialogControllerImpl::RulesAreLoaded(DialogSection section
) {
3563 AddressData address_data
;
3564 address_data
.region_code
= CountryCodeForSection(section
);
3565 AddressValidator::Status status
= GetValidator()->ValidateAddress(
3566 address_data
, NULL
, NULL
);
3567 return status
== AddressValidator::SUCCESS
;
3570 bool AutofillDialogControllerImpl::IsCreditCardExpirationValid(
3571 const base::string16
& year
,
3572 const base::string16
& month
) const {
3573 // If the expiration is in the past as per the local clock, it's invalid.
3574 base::Time now
= base::Time::Now();
3575 if (!autofill::IsValidCreditCardExpirationDate(year
, month
, now
))
3578 const wallet::WalletItems::MaskedInstrument
* instrument
=
3581 const std::string
& locale
= g_browser_process
->GetApplicationLocale();
3583 if (base::StringToInt(month
, &month_int
) &&
3584 instrument
->status() ==
3585 wallet::WalletItems::MaskedInstrument::EXPIRED
&&
3587 instrument
->GetInfo(
3588 AutofillType(CREDIT_CARD_EXP_4_DIGIT_YEAR
), locale
) &&
3589 month_int
== instrument
->expiration_month()) {
3590 // Otherwise, if the user is editing an instrument that's deemed expired
3591 // by the Online Wallet server, mark it invalid on selection.
3599 bool AutofillDialogControllerImpl::ShouldDisallowCcType(
3600 const base::string16
& type
) const {
3601 if (acceptable_cc_types_
.empty())
3604 if (acceptable_cc_types_
.find(base::i18n::ToUpper(type
)) ==
3605 acceptable_cc_types_
.end()) {
3612 bool AutofillDialogControllerImpl::HasInvalidAddress(
3613 const AutofillProfile
& profile
) {
3614 scoped_ptr
<AddressData
> address_data
=
3615 i18n::CreateAddressDataFromAutofillProfile(
3616 profile
, g_browser_process
->GetApplicationLocale());
3618 FieldProblemMap problems
;
3619 GetValidator()->ValidateAddress(*address_data
, NULL
, &problems
);
3620 return !problems
.empty();
3623 bool AutofillDialogControllerImpl::ShouldUseBillingForShipping() {
3624 return SectionIsActive(SECTION_SHIPPING
) &&
3625 suggested_shipping_
.GetItemKeyForCheckedItem() == kSameAsBillingKey
;
3628 bool AutofillDialogControllerImpl::ShouldSaveDetailsLocally() {
3629 // It's possible that the user checked [X] Save details locally before
3630 // switching payment methods, so only ask the view whether to save details
3631 // locally if that checkbox is showing (currently if not paying with wallet).
3632 // Also, if the user isn't editing any sections, there's no data to save
3634 return ShouldOfferToSaveInChrome() && view_
->SaveDetailsLocally();
3637 void AutofillDialogControllerImpl::SetIsSubmitting(bool submitting
) {
3638 is_submitting_
= submitting
;
3641 full_wallet_
.reset();
3644 ScopedViewUpdates
updates(view_
.get());
3645 view_
->UpdateButtonStrip();
3646 view_
->UpdateOverlay();
3647 view_
->UpdateNotificationArea();
3651 bool AutofillDialogControllerImpl::AreLegalDocumentsCurrent() const {
3652 return has_accepted_legal_documents_
||
3653 (wallet_items_
&& wallet_items_
->legal_documents().empty());
3656 void AutofillDialogControllerImpl::AcceptLegalTerms() {
3657 content::GeolocationProvider::GetInstance()->UserDidOptIntoLocationServices();
3658 PrefService
* local_state
= g_browser_process
->local_state();
3659 ListPrefUpdate
accepted(
3660 local_state
, ::prefs::kAutofillDialogWalletLocationAcceptance
);
3661 accepted
->AppendIfNotPresent(new base::StringValue(
3662 account_chooser_model_
->GetActiveWalletAccountName()));
3664 if (AreLegalDocumentsCurrent()) {
3665 LoadRiskFingerprintData();
3667 GetWalletClient()->AcceptLegalDocuments(
3668 wallet_items_
->legal_documents(),
3669 wallet_items_
->google_transaction_id());
3673 void AutofillDialogControllerImpl::SubmitWithWallet() {
3674 active_instrument_id_
.clear();
3675 active_address_id_
.clear();
3676 full_wallet_
.reset();
3678 const wallet::WalletItems::MaskedInstrument
* active_instrument
=
3680 if (!IsManuallyEditingSection(SECTION_CC_BILLING
)) {
3681 active_instrument_id_
= active_instrument
->object_id();
3682 DCHECK(!active_instrument_id_
.empty());
3685 const wallet::Address
* active_address
= ActiveShippingAddress();
3686 if (!IsManuallyEditingSection(SECTION_SHIPPING
) &&
3687 !ShouldUseBillingForShipping() &&
3688 IsShippingAddressRequired()) {
3689 active_address_id_
= active_address
->object_id();
3690 DCHECK(!active_address_id_
.empty());
3693 scoped_ptr
<wallet::Instrument
> inputted_instrument
=
3694 CreateTransientInstrument();
3696 scoped_ptr
<wallet::Address
> inputted_address
;
3697 if (active_address_id_
.empty() && IsShippingAddressRequired()) {
3698 if (ShouldUseBillingForShipping()) {
3699 const wallet::Address
& address
= inputted_instrument
?
3700 *inputted_instrument
->address() : active_instrument
->address();
3701 // Try to find an exact matched shipping address and use it for shipping,
3702 // otherwise save it as a new shipping address. http://crbug.com/225442
3703 const wallet::Address
* duplicated_address
=
3704 FindDuplicateAddress(wallet_items_
->addresses(), address
);
3705 if (duplicated_address
) {
3706 active_address_id_
= duplicated_address
->object_id();
3707 DCHECK(!active_address_id_
.empty());
3709 inputted_address
.reset(new wallet::Address(address
));
3710 DCHECK(inputted_address
->object_id().empty());
3713 inputted_address
= CreateTransientAddress();
3717 // If there's neither an address nor instrument to save, |GetFullWallet()|
3718 // is called when the risk fingerprint is loaded.
3719 if (!active_instrument_id_
.empty() &&
3720 (!active_address_id_
.empty() || !IsShippingAddressRequired())) {
3725 GetWalletClient()->SaveToWallet(
3726 inputted_instrument
.Pass(),
3727 inputted_address
.Pass(),
3728 IsEditingExistingData(SECTION_CC_BILLING
) ? active_instrument
: NULL
,
3729 IsEditingExistingData(SECTION_SHIPPING
) ? active_address
: NULL
);
3732 scoped_ptr
<wallet::Instrument
> AutofillDialogControllerImpl::
3733 CreateTransientInstrument() {
3734 if (!active_instrument_id_
.empty())
3735 return scoped_ptr
<wallet::Instrument
>();
3737 FieldValueMap output
;
3738 view_
->GetUserInput(SECTION_CC_BILLING
, &output
);
3741 AutofillProfile profile
;
3743 GetBillingInfoFromOutputs(output
, &card
, &cvc
, &profile
);
3744 CanonicalizeState(validator_
.get(), &profile
);
3746 return scoped_ptr
<wallet::Instrument
>(
3747 new wallet::Instrument(card
, cvc
, profile
));
3750 scoped_ptr
<wallet::Address
>AutofillDialogControllerImpl::
3751 CreateTransientAddress() {
3752 // If not using billing for shipping, just scrape the view.
3753 FieldValueMap output
;
3754 view_
->GetUserInput(SECTION_SHIPPING
, &output
);
3756 AutofillProfile profile
;
3757 FillFormGroupFromOutputs(output
, &profile
);
3758 profile
.set_language_code(shipping_address_language_code_
);
3759 CanonicalizeState(validator_
.get(), &profile
);
3761 return scoped_ptr
<wallet::Address
>(new wallet::Address(profile
));
3764 void AutofillDialogControllerImpl::GetFullWallet() {
3765 DCHECK(is_submitting_
);
3766 DCHECK(IsPayingWithWallet());
3767 DCHECK(wallet_items_
);
3768 DCHECK(!active_instrument_id_
.empty());
3769 DCHECK(!active_address_id_
.empty() || !IsShippingAddressRequired());
3771 std::vector
<wallet::WalletClient::RiskCapability
> capabilities
;
3772 capabilities
.push_back(wallet::WalletClient::VERIFY_CVC
);
3774 GetWalletClient()->GetFullWallet(wallet::WalletClient::FullWalletRequest(
3775 active_instrument_id_
,
3777 wallet_items_
->google_transaction_id(),
3779 wallet_items_
->HasRequiredAction(wallet::SETUP_WALLET
)));
3782 void AutofillDialogControllerImpl::HandleSaveOrUpdateRequiredActions(
3783 const std::vector
<wallet::RequiredAction
>& required_actions
) {
3784 DCHECK(!required_actions
.empty());
3786 // TODO(ahutter): Investigate if we need to support more generic actions on
3787 // this call such as GAIA_AUTH. See crbug.com/243457.
3788 for (std::vector
<wallet::RequiredAction
>::const_iterator iter
=
3789 required_actions
.begin();
3790 iter
!= required_actions
.end(); ++iter
) {
3791 if (*iter
!= wallet::INVALID_FORM_FIELD
) {
3792 // TODO(dbeam): handle this more gracefully.
3793 DisableWallet(wallet::WalletClient::UNKNOWN_ERROR
);
3796 SetIsSubmitting(false);
3799 void AutofillDialogControllerImpl::FinishSubmit() {
3800 if (IsPayingWithWallet()) {
3801 ScopedViewUpdates
updates(view_
.get());
3802 view_
->UpdateOverlay();
3804 card_generated_animation_
.Start();
3810 void AutofillDialogControllerImpl::AnimationProgressed(
3811 const gfx::Animation
* animation
) {
3812 DCHECK_EQ(animation
, &card_generated_animation_
);
3813 PushOverlayUpdate();
3816 void AutofillDialogControllerImpl::AnimationEnded(
3817 const gfx::Animation
* animation
) {
3818 DCHECK_EQ(animation
, &card_generated_animation_
);
3822 void AutofillDialogControllerImpl::OnAddressValidationRulesLoaded(
3823 const std::string
& country_code
,
3825 // Rules may load instantly (during initialization, before the view is
3826 // even ready). We'll validate when the view is created.
3830 ScopedViewUpdates
updates(view_
.get());
3832 // TODO(dbeam): should we retry on failure?
3833 for (size_t i
= SECTION_MIN
; i
<= SECTION_MAX
; ++i
) {
3834 DialogSection section
= static_cast<DialogSection
>(i
);
3835 if (!SectionIsActive(section
) ||
3836 CountryCodeForSection(section
) != country_code
) {
3840 if (IsManuallyEditingSection(section
) &&
3841 needs_validation_
.count(section
)) {
3842 view_
->ValidateSection(section
);
3843 needs_validation_
.erase(section
);
3844 } else if (success
) {
3845 ShowEditUiIfBadSuggestion(section
);
3846 UpdateSection(section
);
3851 void AutofillDialogControllerImpl::DoFinishSubmit() {
3852 FillOutputForSection(SECTION_CC
);
3853 FillOutputForSection(SECTION_BILLING
);
3854 FillOutputForSection(SECTION_CC_BILLING
);
3856 if (ShouldUseBillingForShipping()) {
3857 FillOutputForSectionWithComparator(
3859 base::Bind(ServerTypeMatchesShippingField
));
3860 FillOutputForSectionWithComparator(
3862 base::Bind(ServerTypeMatchesShippingField
));
3863 FillOutputForSectionWithComparator(
3865 base::Bind(ServerTypeMatchesShippingField
));
3867 FillOutputForSection(SECTION_SHIPPING
);
3870 if (IsPayingWithWallet()) {
3871 if (SectionIsActive(SECTION_SHIPPING
)) {
3872 profile_
->GetPrefs()->SetBoolean(
3873 ::prefs::kAutofillDialogWalletShippingSameAsBilling
,
3874 suggested_shipping_
.GetItemKeyForCheckedItem() == kSameAsBillingKey
);
3876 } else if (ShouldOfferToSaveInChrome()) {
3877 for (size_t i
= SECTION_MIN
; i
<= SECTION_MAX
; ++i
) {
3878 DialogSection section
= static_cast<DialogSection
>(i
);
3879 if (!SectionIsActive(section
))
3882 SuggestionsMenuModel
* model
= SuggestionsMenuModelForSection(section
);
3883 std::string item_key
= model
->GetItemKeyForCheckedItem();
3884 if (IsASuggestionItemKey(item_key
) || item_key
== kSameAsBillingKey
) {
3885 PersistAutofillChoice(section
, item_key
);
3886 } else if (item_key
== kAddNewItemKey
&& ShouldSaveDetailsLocally()) {
3887 DCHECK(newly_saved_data_model_guids_
.count(section
));
3888 PersistAutofillChoice(section
, newly_saved_data_model_guids_
[section
]);
3892 profile_
->GetPrefs()->SetBoolean(::prefs::kAutofillDialogSaveData
,
3893 view_
->SaveDetailsLocally());
3896 // On a successful submit, if the user manually selected "pay without wallet",
3897 // stop trying to pay with Wallet on future runs of the dialog. On the other
3898 // hand, if there was an error that prevented the user from having the choice
3899 // of using Wallet, leave the pref alone.
3900 if (!wallet_error_notification_
&&
3901 account_chooser_model_
->HasAccountsToChoose()) {
3902 profile_
->GetPrefs()->SetBoolean(
3903 ::prefs::kAutofillDialogPayWithoutWallet
,
3904 !account_chooser_model_
->WalletIsSelected());
3907 LogOnFinishSubmitMetrics();
3909 // Callback should be called as late as possible.
3910 callback_
.Run(AutofillClient::AutocompleteResultSuccess
,
3913 data_was_passed_back_
= true;
3915 // This might delete us.
3919 void AutofillDialogControllerImpl::PersistAutofillChoice(
3920 DialogSection section
,
3921 const std::string
& guid
) {
3922 DCHECK(!IsPayingWithWallet() && ShouldOfferToSaveInChrome());
3923 scoped_ptr
<base::DictionaryValue
> value(new base::DictionaryValue());
3924 value
->SetString(kGuidPrefKey
, guid
);
3926 DictionaryPrefUpdate
updater(profile()->GetPrefs(),
3927 ::prefs::kAutofillDialogAutofillDefault
);
3928 base::DictionaryValue
* autofill_choice
= updater
.Get();
3929 autofill_choice
->Set(SectionToPrefString(section
), value
.release());
3932 void AutofillDialogControllerImpl::GetDefaultAutofillChoice(
3933 DialogSection section
,
3934 std::string
* guid
) {
3935 DCHECK(!IsPayingWithWallet() && IsAutofillEnabled());
3936 // The default choice is the first thing in the menu that is a suggestion
3938 SuggestionsMenuModel
* model
= SuggestionsMenuModelForSection(section
);
3939 for (int i
= 0; i
< model
->GetItemCount(); ++i
) {
3940 // Try the first suggestion item that is enabled.
3941 if (IsASuggestionItemKey(model
->GetItemKeyAt(i
)) && model
->IsEnabledAt(i
)) {
3942 *guid
= model
->GetItemKeyAt(i
);
3944 // Fall back to the first non-suggestion key.
3945 } else if (!IsASuggestionItemKey(model
->GetItemKeyAt(i
)) && guid
->empty()) {
3946 *guid
= model
->GetItemKeyAt(i
);
3951 bool AutofillDialogControllerImpl::GetAutofillChoice(DialogSection section
,
3952 std::string
* guid
) {
3953 DCHECK(!IsPayingWithWallet() && IsAutofillEnabled());
3954 const base::DictionaryValue
* choices
= profile()->GetPrefs()->GetDictionary(
3955 ::prefs::kAutofillDialogAutofillDefault
);
3959 const base::DictionaryValue
* choice
= NULL
;
3960 if (!choices
->GetDictionary(SectionToPrefString(section
), &choice
))
3963 choice
->GetString(kGuidPrefKey
, guid
);
3967 void AutofillDialogControllerImpl::LogOnFinishSubmitMetrics() {
3968 AutofillMetrics::LogDialogUiDuration(
3969 base::Time::Now() - dialog_shown_timestamp_
,
3970 AutofillMetrics::DIALOG_ACCEPTED
);
3972 AutofillMetrics::LogDialogUiEvent(AutofillMetrics::DIALOG_UI_ACCEPTED
);
3974 AutofillMetrics::DialogDismissalState dismissal_state
;
3975 if (!IsManuallyEditingAnySection()) {
3976 dismissal_state
= IsPayingWithWallet() ?
3977 AutofillMetrics::DIALOG_ACCEPTED_EXISTING_WALLET_DATA
:
3978 AutofillMetrics::DIALOG_ACCEPTED_EXISTING_AUTOFILL_DATA
;
3979 } else if (IsPayingWithWallet()) {
3980 dismissal_state
= AutofillMetrics::DIALOG_ACCEPTED_SAVE_TO_WALLET
;
3981 } else if (ShouldSaveDetailsLocally()) {
3982 dismissal_state
= AutofillMetrics::DIALOG_ACCEPTED_SAVE_TO_AUTOFILL
;
3984 dismissal_state
= AutofillMetrics::DIALOG_ACCEPTED_NO_SAVE
;
3987 AutofillMetrics::LogDialogDismissalState(dismissal_state
);
3990 void AutofillDialogControllerImpl::LogOnCancelMetrics() {
3991 AutofillMetrics::LogDialogUiEvent(AutofillMetrics::DIALOG_UI_CANCELED
);
3993 AutofillMetrics::DialogDismissalState dismissal_state
;
3994 if (ShouldShowSignInWebView())
3995 dismissal_state
= AutofillMetrics::DIALOG_CANCELED_DURING_SIGNIN
;
3996 else if (!IsManuallyEditingAnySection())
3997 dismissal_state
= AutofillMetrics::DIALOG_CANCELED_NO_EDITS
;
3998 else if (AllSectionsAreValid())
3999 dismissal_state
= AutofillMetrics::DIALOG_CANCELED_NO_INVALID_FIELDS
;
4001 dismissal_state
= AutofillMetrics::DIALOG_CANCELED_WITH_INVALID_FIELDS
;
4003 AutofillMetrics::LogDialogDismissalState(dismissal_state
);
4005 AutofillMetrics::LogDialogUiDuration(
4006 base::Time::Now() - dialog_shown_timestamp_
,
4007 AutofillMetrics::DIALOG_CANCELED
);
4010 void AutofillDialogControllerImpl::LogSuggestionItemSelectedMetric(
4011 const SuggestionsMenuModel
& model
) {
4012 DialogSection section
= SectionForSuggestionsMenuModel(model
);
4014 AutofillMetrics::DialogUiEvent dialog_ui_event
;
4015 if (model
.GetItemKeyForCheckedItem() == kAddNewItemKey
) {
4016 // Selected to add a new item.
4017 dialog_ui_event
= common::DialogSectionToUiItemAddedEvent(section
);
4018 } else if (IsASuggestionItemKey(model
.GetItemKeyForCheckedItem())) {
4019 // Selected an existing item.
4020 dialog_ui_event
= common::DialogSectionToUiSelectionChangedEvent(section
);
4022 // TODO(estade): add logging for "Manage items" or "Use billing for
4027 AutofillMetrics::LogDialogUiEvent(dialog_ui_event
);
4030 void AutofillDialogControllerImpl::LogDialogLatencyToShow() {
4031 if (was_ui_latency_logged_
)
4034 AutofillMetrics::LogDialogLatencyToShow(base::Time::Now() -
4035 dialog_shown_timestamp_
);
4036 was_ui_latency_logged_
= true;
4039 AutofillMetrics::DialogInitialUserStateMetric
4040 AutofillDialogControllerImpl::GetInitialUserState() const {
4041 // Consider a user to be an Autofill user if the user has any credit cards
4042 // or addresses saved. Check that the item count is greater than 2 because
4043 // an "empty" menu still has the "add new" menu item and "manage" menu item.
4044 const bool has_autofill_profiles
=
4045 suggested_cc_
.GetItemCount() > 2 ||
4046 suggested_billing_
.GetItemCount() > 2;
4048 if (SignedInState() != SIGNED_IN
) {
4050 return has_autofill_profiles
?
4051 AutofillMetrics::DIALOG_USER_NOT_SIGNED_IN_HAS_AUTOFILL
:
4052 AutofillMetrics::DIALOG_USER_NOT_SIGNED_IN_NO_AUTOFILL
;
4056 if (wallet_items_
->instruments().empty()) {
4058 return has_autofill_profiles
?
4059 AutofillMetrics::DIALOG_USER_SIGNED_IN_NO_WALLET_HAS_AUTOFILL
:
4060 AutofillMetrics::DIALOG_USER_SIGNED_IN_NO_WALLET_NO_AUTOFILL
;
4063 // Has Wallet items.
4064 return has_autofill_profiles
?
4065 AutofillMetrics::DIALOG_USER_SIGNED_IN_HAS_WALLET_HAS_AUTOFILL
:
4066 AutofillMetrics::DIALOG_USER_SIGNED_IN_HAS_WALLET_NO_AUTOFILL
;
4069 void AutofillDialogControllerImpl::MaybeShowCreditCardBubble() {
4070 if (!data_was_passed_back_
)
4073 if (newly_saved_card_
) {
4074 scoped_ptr
<AutofillProfile
> billing_profile
;
4075 if (IsManuallyEditingSection(SECTION_BILLING
)) {
4076 // Scrape the view as the user's entering or updating information.
4077 FieldValueMap outputs
;
4078 view_
->GetUserInput(SECTION_BILLING
, &outputs
);
4079 billing_profile
.reset(new AutofillProfile
);
4080 FillFormGroupFromOutputs(outputs
, billing_profile
.get());
4081 billing_profile
->set_language_code(billing_address_language_code_
);
4083 // Just snag the currently suggested profile.
4084 std::string item_key
= SuggestionsMenuModelForSection(SECTION_BILLING
)->
4085 GetItemKeyForCheckedItem();
4086 AutofillProfile
* profile
= GetManager()->GetProfileByGUID(item_key
);
4087 billing_profile
.reset(new AutofillProfile(*profile
));
4090 ShowNewCreditCardBubble(newly_saved_card_
.Pass(),
4091 billing_profile
.Pass());
4095 if (!full_wallet_
|| !full_wallet_
->billing_address())
4098 GeneratedCreditCardBubbleController::Show(
4100 full_wallet_
->TypeAndLastFourDigits(),
4101 backing_card_last_four_
);
4104 void AutofillDialogControllerImpl::OnSubmitButtonDelayEnd() {
4107 ScopedViewUpdates
updates(view_
.get());
4108 view_
->UpdateButtonStrip();
4111 void AutofillDialogControllerImpl::FetchWalletCookie() {
4112 net::URLRequestContextGetter
* request_context
= profile_
->GetRequestContext();
4113 signin_helper_
.reset(new wallet::WalletSigninHelper(this, request_context
));
4114 signin_helper_
->StartWalletCookieValueFetch();
4117 } // namespace autofill