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 bool AutofillDialogControllerImpl::RemoveSuggestion(
2452 const base::string16
& value
,
2454 // TODO(estade): implement.
2458 void AutofillDialogControllerImpl::ClearPreviewedForm() {
2459 // TODO(estade): implement.
2462 ////////////////////////////////////////////////////////////////////////////////
2463 // content::NotificationObserver implementation.
2465 void AutofillDialogControllerImpl::Observe(
2467 const content::NotificationSource
& source
,
2468 const content::NotificationDetails
& details
) {
2469 DCHECK_EQ(type
, content::NOTIFICATION_NAV_ENTRY_COMMITTED
);
2470 content::LoadCommittedDetails
* load_details
=
2471 content::Details
<content::LoadCommittedDetails
>(details
).ptr();
2472 size_t user_index
= 0;
2473 if (IsSignInContinueUrl(load_details
->entry
->GetVirtualURL(), &user_index
)) {
2474 GetWalletClient()->SetUserIndex(user_index
);
2475 FetchWalletCookie();
2477 // NOTE: |HideSignIn()| may delete the WebContents which doesn't expect to
2478 // be deleted while committing a nav entry. Just call |HideSignIn()| later.
2479 base::MessageLoop::current()->PostTask(FROM_HERE
,
2480 base::Bind(&AutofillDialogControllerImpl::HideSignIn
,
2481 base::Unretained(this)));
2485 ////////////////////////////////////////////////////////////////////////////////
2486 // SuggestionsMenuModelDelegate implementation.
2488 void AutofillDialogControllerImpl::SuggestionItemSelected(
2489 SuggestionsMenuModel
* model
,
2491 ScopedViewUpdates
updates(view_
.get());
2493 if (model
->GetItemKeyAt(index
) == kManageItemsKey
) {
2495 if (!IsPayingWithWallet()) {
2496 DCHECK(IsAutofillEnabled());
2497 GURL
settings_url(chrome::kChromeUISettingsURL
);
2498 url
= settings_url
.Resolve(chrome::kAutofillSubPage
);
2500 // Reset |last_wallet_items_fetch_timestamp_| to ensure that the Wallet
2501 // data is refreshed as soon as the user switches back to this tab after
2502 // potentially editing his data.
2503 last_wallet_items_fetch_timestamp_
= base::TimeTicks();
2504 size_t user_index
= GetWalletClient()->user_index();
2505 url
= SectionForSuggestionsMenuModel(*model
) == SECTION_SHIPPING
?
2506 wallet::GetManageAddressesUrl(user_index
) :
2507 wallet::GetManageInstrumentsUrl(user_index
);
2510 OpenTabWithUrl(url
);
2514 model
->SetCheckedIndex(index
);
2515 DialogSection section
= SectionForSuggestionsMenuModel(*model
);
2517 ResetSectionInput(section
);
2518 ShowEditUiIfBadSuggestion(section
);
2519 UpdateSection(section
);
2520 view_
->UpdateNotificationArea();
2523 LogSuggestionItemSelectedMetric(*model
);
2526 ////////////////////////////////////////////////////////////////////////////////
2527 // wallet::WalletClientDelegate implementation.
2529 std::string
AutofillDialogControllerImpl::GetRiskData() const {
2530 DCHECK(!risk_data_
.empty());
2534 std::string
AutofillDialogControllerImpl::GetWalletCookieValue() const {
2535 return wallet_cookie_value_
;
2538 bool AutofillDialogControllerImpl::IsShippingAddressRequired() const {
2539 return cares_about_shipping_
;
2542 void AutofillDialogControllerImpl::OnDidAcceptLegalDocuments() {
2543 DCHECK(is_submitting_
&& IsPayingWithWallet());
2544 has_accepted_legal_documents_
= true;
2545 LoadRiskFingerprintData();
2548 void AutofillDialogControllerImpl::OnDidAuthenticateInstrument(bool success
) {
2549 DCHECK(is_submitting_
&& IsPayingWithWallet());
2551 // TODO(dbeam): use the returned full wallet. http://crbug.com/224992
2555 DisableWallet(wallet::WalletClient::UNKNOWN_ERROR
);
2556 SuggestionsUpdated();
2560 void AutofillDialogControllerImpl::OnDidGetFullWallet(
2561 scoped_ptr
<wallet::FullWallet
> full_wallet
) {
2562 DCHECK(is_submitting_
&& IsPayingWithWallet());
2563 ScopedViewUpdates
updates(view_
.get());
2565 full_wallet_
= full_wallet
.Pass();
2567 if (full_wallet_
->required_actions().empty()) {
2572 switch (full_wallet_
->required_actions()[0]) {
2573 case wallet::CHOOSE_ANOTHER_INSTRUMENT_OR_ADDRESS
:
2574 choose_another_instrument_or_address_
= true;
2575 SetIsSubmitting(false);
2579 case wallet::VERIFY_CVV
:
2580 SuggestionsUpdated();
2584 DisableWallet(wallet::WalletClient::UNKNOWN_ERROR
);
2588 view_
->UpdateNotificationArea();
2589 view_
->UpdateButtonStrip();
2590 view_
->UpdateOverlay();
2593 void AutofillDialogControllerImpl::OnPassiveSigninSuccess() {
2594 FetchWalletCookie();
2597 void AutofillDialogControllerImpl::OnPassiveSigninFailure(
2598 const GoogleServiceAuthError
& error
) {
2599 signin_helper_
.reset();
2600 passive_failed_
= true;
2602 // When the user clicks on "use wallet" or a second account and passive auth
2603 // fails, try explicit sign in.
2604 if (handling_use_wallet_link_click_
|| GetWalletClient()->user_index() != 0) {
2605 ShowSignIn(wallet::GetSignInUrl(GetWalletClient()->user_index()));
2606 handling_use_wallet_link_click_
= false;
2609 OnWalletSigninError();
2612 void AutofillDialogControllerImpl::OnDidFetchWalletCookieValue(
2613 const std::string
& cookie_value
) {
2614 wallet_cookie_value_
= cookie_value
;
2615 signin_helper_
.reset();
2619 void AutofillDialogControllerImpl::OnDidGetWalletItems(
2620 scoped_ptr
<wallet::WalletItems
> wallet_items
) {
2621 legal_documents_text_
.clear();
2622 legal_document_link_ranges_
.clear();
2623 has_accepted_legal_documents_
= false;
2625 wallet_items_
= wallet_items
.Pass();
2627 if (wallet_items_
&& !wallet_items_
->ObfuscatedGaiaId().empty()) {
2628 // Making sure the user index is in sync shouldn't be necessary, but is an
2629 // extra precaution. But if there is no active account (such as in the
2630 // PASSIVE_AUTH case), stick with the old active account.
2631 GetWalletClient()->SetUserIndex(wallet_items_
->active_account_index());
2633 std::vector
<std::string
> usernames
;
2634 for (size_t i
= 0; i
< wallet_items_
->gaia_accounts().size(); ++i
) {
2635 usernames
.push_back(wallet_items_
->gaia_accounts()[i
]->email_address());
2637 account_chooser_model_
->SetWalletAccounts(
2638 usernames
, wallet_items_
->active_account_index());
2641 if (wallet_items_
) {
2642 shipping_country_combobox_model_
->SetCountries(
2644 base::Bind(WalletCountryFilter
,
2645 acceptable_shipping_countries_
,
2646 wallet_items_
->allowed_shipping_countries()));
2648 // If the site doesn't ship to any of the countries Wallet allows shipping
2649 // to, the merchant is not supported. (Note we generally shouldn't get here
2650 // as such a merchant wouldn't make it onto the Wallet whitelist.)
2651 if (shipping_country_combobox_model_
->GetItemCount() == 0)
2652 DisableWallet(wallet::WalletClient::UNSUPPORTED_MERCHANT
);
2655 ConstructLegalDocumentsText();
2656 OnWalletOrSigninUpdate();
2659 void AutofillDialogControllerImpl::OnDidSaveToWallet(
2660 const std::string
& instrument_id
,
2661 const std::string
& address_id
,
2662 const std::vector
<wallet::RequiredAction
>& required_actions
,
2663 const std::vector
<wallet::FormFieldError
>& form_field_errors
) {
2664 DCHECK(is_submitting_
&& IsPayingWithWallet());
2666 if (required_actions
.empty()) {
2667 if (!address_id
.empty())
2668 active_address_id_
= address_id
;
2669 if (!instrument_id
.empty())
2670 active_instrument_id_
= instrument_id
;
2673 OnWalletFormFieldError(form_field_errors
);
2674 HandleSaveOrUpdateRequiredActions(required_actions
);
2678 void AutofillDialogControllerImpl::OnWalletError(
2679 wallet::WalletClient::ErrorType error_type
) {
2680 DisableWallet(error_type
);
2683 ////////////////////////////////////////////////////////////////////////////////
2684 // PersonalDataManagerObserver implementation.
2686 void AutofillDialogControllerImpl::OnPersonalDataChanged() {
2690 SuggestionsUpdated();
2693 ////////////////////////////////////////////////////////////////////////////////
2694 // AccountChooserModelDelegate implementation.
2696 void AutofillDialogControllerImpl::AccountChoiceChanged() {
2697 ScopedViewUpdates
updates(view_
.get());
2698 wallet::WalletClient
* client
= GetWalletClient();
2701 client
->CancelRequest();
2703 SetIsSubmitting(false);
2705 size_t selected_user_index
=
2706 account_chooser_model_
->GetActiveWalletAccountIndex();
2707 if (account_chooser_model_
->WalletIsSelected() &&
2708 client
->user_index() != selected_user_index
) {
2709 client
->SetUserIndex(selected_user_index
);
2710 // Clear |wallet_items_| so we don't try to restore the selected instrument
2712 wallet_items_
.reset();
2715 SuggestionsUpdated();
2716 UpdateAccountChooserView();
2720 void AutofillDialogControllerImpl::AddAccount() {
2721 ShowSignIn(wallet::GetAddAccountUrl());
2724 void AutofillDialogControllerImpl::UpdateAccountChooserView() {
2726 ScopedViewUpdates
updates(view_
.get());
2727 view_
->UpdateAccountChooser();
2728 view_
->UpdateNotificationArea();
2732 ////////////////////////////////////////////////////////////////////////////////
2734 bool AutofillDialogControllerImpl::HandleKeyPressEventInInput(
2735 const content::NativeWebKeyboardEvent
& event
) {
2736 if (popup_controller_
.get())
2737 return popup_controller_
->HandleKeyPressEvent(event
);
2742 bool AutofillDialogControllerImpl::IsSubmitPausedOn(
2743 wallet::RequiredAction required_action
) const {
2744 return full_wallet_
&& full_wallet_
->HasRequiredAction(required_action
);
2747 void AutofillDialogControllerImpl::ShowNewCreditCardBubble(
2748 scoped_ptr
<CreditCard
> new_card
,
2749 scoped_ptr
<AutofillProfile
> billing_profile
) {
2750 NewCreditCardBubbleController::Show(web_contents(),
2752 billing_profile
.Pass());
2755 void AutofillDialogControllerImpl::SubmitButtonDelayBegin() {
2756 submit_button_delay_timer_
.Start(
2758 base::TimeDelta::FromMilliseconds(kSubmitButtonDelayMs
),
2760 &AutofillDialogControllerImpl::OnSubmitButtonDelayEnd
);
2763 void AutofillDialogControllerImpl::SubmitButtonDelayEndForTesting() {
2764 DCHECK(submit_button_delay_timer_
.IsRunning());
2765 submit_button_delay_timer_
.user_task().Run();
2766 submit_button_delay_timer_
.Stop();
2769 void AutofillDialogControllerImpl::
2770 ClearLastWalletItemsFetchTimestampForTesting() {
2771 last_wallet_items_fetch_timestamp_
= base::TimeTicks();
2774 AccountChooserModel
* AutofillDialogControllerImpl::
2775 AccountChooserModelForTesting() {
2776 return account_chooser_model_
.get();
2779 bool AutofillDialogControllerImpl::IsSignInContinueUrl(
2781 size_t* user_index
) const {
2782 return wallet::IsSignInContinueUrl(url
, user_index
);
2785 AutofillDialogControllerImpl::AutofillDialogControllerImpl(
2786 content::WebContents
* contents
,
2787 const FormData
& form_structure
,
2788 const GURL
& source_url
,
2789 const AutofillClient::ResultCallback
& callback
)
2790 : WebContentsObserver(contents
),
2791 profile_(Profile::FromBrowserContext(contents
->GetBrowserContext())),
2792 initial_user_state_(AutofillMetrics::DIALOG_USER_STATE_UNKNOWN
),
2793 form_structure_(form_structure
),
2794 invoked_from_same_origin_(true),
2795 source_url_(source_url
),
2796 callback_(callback
),
2797 wallet_client_(profile_
->GetRequestContext(), this, source_url
),
2798 wallet_items_requested_(false),
2799 handling_use_wallet_link_click_(false),
2800 passive_failed_(false),
2801 suggested_cc_(this),
2802 suggested_billing_(this),
2803 suggested_cc_billing_(this),
2804 suggested_shipping_(this),
2805 cares_about_shipping_(true),
2806 popup_input_type_(UNKNOWN_TYPE
),
2807 popup_section_(SECTION_MIN
),
2808 waiting_for_explicit_sign_in_response_(false),
2809 has_accepted_legal_documents_(false),
2810 is_submitting_(false),
2811 choose_another_instrument_or_address_(false),
2812 wallet_server_validation_recoverable_(true),
2813 data_was_passed_back_(false),
2814 was_ui_latency_logged_(false),
2815 card_generated_animation_(2000, 60, this),
2816 weak_ptr_factory_(this) {
2817 DCHECK(!callback_
.is_null());
2820 AutofillDialogView
* AutofillDialogControllerImpl::CreateView() {
2821 return AutofillDialogView::Create(this);
2824 PersonalDataManager
* AutofillDialogControllerImpl::GetManager() const {
2825 return PersonalDataManagerFactory::GetForProfile(profile_
);
2828 AddressValidator
* AutofillDialogControllerImpl::GetValidator() {
2829 return validator_
.get();
2832 const wallet::WalletClient
* AutofillDialogControllerImpl::GetWalletClient()
2834 return const_cast<AutofillDialogControllerImpl
*>(this)->GetWalletClient();
2837 wallet::WalletClient
* AutofillDialogControllerImpl::GetWalletClient() {
2838 return &wallet_client_
;
2841 bool AutofillDialogControllerImpl::IsPayingWithWallet() const {
2842 return account_chooser_model_
->WalletIsSelected() &&
2843 SignedInState() == SIGNED_IN
;
2846 void AutofillDialogControllerImpl::LoadRiskFingerprintData() {
2849 uint64 obfuscated_gaia_id
= 0;
2850 bool success
= base::StringToUint64(wallet_items_
->ObfuscatedGaiaId(),
2851 &obfuscated_gaia_id
);
2855 obfuscated_gaia_id
, web_contents(),
2856 base::Bind(&AutofillDialogControllerImpl::OnDidLoadRiskFingerprintData
,
2857 weak_ptr_factory_
.GetWeakPtr()));
2860 void AutofillDialogControllerImpl::OnDidLoadRiskFingerprintData(
2861 const std::string
& risk_data
) {
2862 DCHECK(AreLegalDocumentsCurrent());
2863 risk_data_
= risk_data
;
2867 void AutofillDialogControllerImpl::OpenTabWithUrl(const GURL
& url
) {
2868 chrome::NavigateParams
params(
2869 chrome::FindBrowserWithWebContents(web_contents()),
2871 ui::PAGE_TRANSITION_LINK
);
2872 params
.disposition
= NEW_FOREGROUND_TAB
;
2873 chrome::Navigate(¶ms
);
2876 DialogSection
AutofillDialogControllerImpl::ActiveBillingSection() const {
2877 return IsPayingWithWallet() ? SECTION_CC_BILLING
: SECTION_BILLING
;
2880 bool AutofillDialogControllerImpl::IsEditingExistingData(
2881 DialogSection section
) const {
2882 return section_editing_state_
.count(section
) > 0;
2885 bool AutofillDialogControllerImpl::IsManuallyEditingSection(
2886 DialogSection section
) const {
2887 return IsEditingExistingData(section
) ||
2888 SuggestionsMenuModelForSection(section
)->
2889 GetItemKeyForCheckedItem() == kAddNewItemKey
;
2892 void AutofillDialogControllerImpl::OnWalletSigninError() {
2893 account_chooser_model_
->SetHadWalletSigninError();
2894 GetWalletClient()->CancelRequest();
2895 LogDialogLatencyToShow();
2898 void AutofillDialogControllerImpl::DisableWallet(
2899 wallet::WalletClient::ErrorType error_type
) {
2900 signin_helper_
.reset();
2901 wallet_items_
.reset();
2902 wallet_errors_
.clear();
2903 GetWalletClient()->CancelRequest();
2904 SetIsSubmitting(false);
2905 wallet_error_notification_
= GetWalletError(error_type
);
2906 account_chooser_model_
->SetHadWalletError();
2909 void AutofillDialogControllerImpl::SuggestionsUpdated() {
2910 ScopedViewUpdates
updates(view_
.get());
2912 const FieldValueMap snapshot
= TakeUserInputSnapshot();
2914 suggested_cc_
.Reset();
2915 suggested_billing_
.Reset();
2916 suggested_cc_billing_
.Reset();
2917 suggested_shipping_
.Reset();
2920 suggested_shipping_
.AddKeyedItem(
2922 l10n_util::GetStringUTF16(IDS_AUTOFILL_DIALOG_USE_BILLING_FOR_SHIPPING
));
2924 if (IsPayingWithWallet()) {
2925 const std::vector
<wallet::Address
*>& addresses
=
2926 wallet_items_
->addresses();
2928 bool shipping_same_as_billing
= profile_
->GetPrefs()->GetBoolean(
2929 ::prefs::kAutofillDialogWalletShippingSameAsBilling
);
2931 if (shipping_same_as_billing
)
2932 suggested_shipping_
.SetCheckedItem(kSameAsBillingKey
);
2934 for (size_t i
= 0; i
< addresses
.size(); ++i
) {
2935 std::string key
= base::IntToString(i
);
2936 suggested_shipping_
.AddKeyedItemWithMinorText(
2938 addresses
[i
]->DisplayName(),
2939 addresses
[i
]->DisplayNameDetail());
2940 suggested_shipping_
.SetEnabled(
2942 CanAcceptCountry(SECTION_SHIPPING
,
2943 addresses
[i
]->country_name_code()));
2945 // TODO(scr): Move this assignment outside the loop or comment why it
2947 const std::string default_shipping_address_id
=
2948 GetIdToSelect(wallet_items_
->default_address_id(),
2949 previous_default_shipping_address_id_
,
2950 previously_selected_shipping_address_id_
);
2952 if (!shipping_same_as_billing
&&
2953 addresses
[i
]->object_id() == default_shipping_address_id
) {
2954 suggested_shipping_
.SetCheckedItem(key
);
2958 if (!IsSubmitPausedOn(wallet::VERIFY_CVV
)) {
2959 const std::vector
<wallet::WalletItems::MaskedInstrument
*>& instruments
=
2960 wallet_items_
->instruments();
2961 std::string first_active_instrument_key
;
2962 std::string default_instrument_key
;
2963 for (size_t i
= 0; i
< instruments
.size(); ++i
) {
2964 bool allowed
= IsInstrumentAllowed(*instruments
[i
]) &&
2965 CanAcceptCountry(SECTION_BILLING
,
2966 instruments
[i
]->address().country_name_code());
2967 gfx::Image icon
= instruments
[i
]->CardIcon();
2968 if (!allowed
&& !icon
.IsEmpty()) {
2969 // Create a grayed disabled icon.
2970 SkBitmap disabled_bitmap
= SkBitmapOperations::CreateHSLShiftedBitmap(
2971 *icon
.ToSkBitmap(), kGrayImageShift
);
2973 gfx::ImageSkia::CreateFrom1xBitmap(disabled_bitmap
));
2975 std::string key
= base::IntToString(i
);
2976 suggested_cc_billing_
.AddKeyedItemWithMinorTextAndIcon(
2978 instruments
[i
]->DisplayName(),
2979 instruments
[i
]->DisplayNameDetail(),
2981 suggested_cc_billing_
.SetEnabled(key
, allowed
);
2984 if (first_active_instrument_key
.empty())
2985 first_active_instrument_key
= key
;
2987 const std::string default_instrument_id
=
2988 GetIdToSelect(wallet_items_
->default_instrument_id(),
2989 previous_default_instrument_id_
,
2990 previously_selected_instrument_id_
);
2991 if (instruments
[i
]->object_id() == default_instrument_id
)
2992 default_instrument_key
= key
;
2996 suggested_cc_billing_
.AddKeyedItem(
2998 l10n_util::GetStringUTF16(IDS_AUTOFILL_DIALOG_ADD_BILLING_DETAILS
));
2999 if (!wallet_items_
->HasRequiredAction(wallet::SETUP_WALLET
)) {
3000 suggested_cc_billing_
.AddKeyedItemWithMinorText(
3002 l10n_util::GetStringUTF16(
3003 IDS_AUTOFILL_DIALOG_MANAGE_BILLING_DETAILS
),
3004 base::UTF8ToUTF16(wallet::GetManageInstrumentsUrl(0U).host()));
3007 // Determine which instrument item should be selected.
3008 if (!default_instrument_key
.empty())
3009 suggested_cc_billing_
.SetCheckedItem(default_instrument_key
);
3010 else if (!first_active_instrument_key
.empty())
3011 suggested_cc_billing_
.SetCheckedItem(first_active_instrument_key
);
3013 suggested_cc_billing_
.SetCheckedItem(kAddNewItemKey
);
3016 shipping_country_combobox_model_
->SetCountries(
3018 base::Bind(AutofillCountryFilter
, acceptable_shipping_countries_
));
3020 if (IsAutofillEnabled()) {
3021 PersonalDataManager
* manager
= GetManager();
3022 const std::vector
<CreditCard
*>& cards
= manager
->GetCreditCards();
3023 ui::ResourceBundle
& rb
= ui::ResourceBundle::GetSharedInstance();
3024 for (size_t i
= 0; i
< cards
.size(); ++i
) {
3025 if (!i18ninput::CardHasCompleteAndVerifiedData(*cards
[i
]))
3028 suggested_cc_
.AddKeyedItemWithIcon(
3031 rb
.GetImageNamed(CreditCard::IconResourceId(cards
[i
]->type())));
3032 suggested_cc_
.SetEnabled(
3034 !ShouldDisallowCcType(cards
[i
]->TypeForDisplay()));
3037 const std::vector
<AutofillProfile
*>& profiles
= manager
->GetProfiles();
3038 std::vector
<base::string16
> labels
;
3039 AutofillProfile::CreateDifferentiatingLabels(
3041 g_browser_process
->GetApplicationLocale(),
3043 DCHECK_EQ(labels
.size(), profiles
.size());
3044 for (size_t i
= 0; i
< profiles
.size(); ++i
) {
3045 const AutofillProfile
& profile
= *profiles
[i
];
3046 if (!i18ninput::AddressHasCompleteAndVerifiedData(
3047 profile
, g_browser_process
->GetApplicationLocale())) {
3051 // Don't add variants for addresses: name is part of credit card and
3052 // we'll just ignore email and phone number variants.
3053 suggested_shipping_
.AddKeyedItem(profile
.guid(), labels
[i
]);
3054 suggested_shipping_
.SetEnabled(
3058 base::UTF16ToUTF8(profile
.GetRawInfo(ADDRESS_HOME_COUNTRY
))));
3059 if (!profile
.GetRawInfo(EMAIL_ADDRESS
).empty() &&
3060 !profile
.IsPresentButInvalid(EMAIL_ADDRESS
)) {
3061 suggested_billing_
.AddKeyedItem(profile
.guid(), labels
[i
]);
3062 suggested_billing_
.SetEnabled(
3066 base::UTF16ToUTF8(profile
.GetRawInfo(ADDRESS_HOME_COUNTRY
))));
3071 suggested_cc_
.AddKeyedItem(
3073 l10n_util::GetStringUTF16(IsAutofillEnabled() ?
3074 IDS_AUTOFILL_DIALOG_ADD_CREDIT_CARD
:
3075 IDS_AUTOFILL_DIALOG_ENTER_CREDIT_CARD
));
3076 suggested_cc_
.AddKeyedItem(
3078 l10n_util::GetStringUTF16(IDS_AUTOFILL_DIALOG_MANAGE_CREDIT_CARD
));
3079 suggested_billing_
.AddKeyedItem(
3081 l10n_util::GetStringUTF16(IsAutofillEnabled() ?
3082 IDS_AUTOFILL_DIALOG_ADD_BILLING_ADDRESS
:
3083 IDS_AUTOFILL_DIALOG_ENTER_BILLING_DETAILS
));
3084 suggested_billing_
.AddKeyedItem(
3086 l10n_util::GetStringUTF16(IDS_AUTOFILL_DIALOG_MANAGE_BILLING_ADDRESS
));
3089 suggested_shipping_
.AddKeyedItem(
3091 l10n_util::GetStringUTF16(IsPayingWithWallet() || IsAutofillEnabled() ?
3092 IDS_AUTOFILL_DIALOG_ADD_SHIPPING_ADDRESS
:
3093 IDS_AUTOFILL_DIALOG_USE_DIFFERENT_SHIPPING_ADDRESS
));
3095 if (!IsPayingWithWallet()) {
3096 if (IsAutofillEnabled()) {
3097 suggested_shipping_
.AddKeyedItem(
3099 l10n_util::GetStringUTF16(
3100 IDS_AUTOFILL_DIALOG_MANAGE_SHIPPING_ADDRESS
));
3102 } else if (!wallet_items_
->HasRequiredAction(wallet::SETUP_WALLET
)) {
3103 suggested_shipping_
.AddKeyedItemWithMinorText(
3105 l10n_util::GetStringUTF16(IDS_AUTOFILL_DIALOG_MANAGE_SHIPPING_ADDRESS
),
3106 base::UTF8ToUTF16(wallet::GetManageAddressesUrl(0U).host()));
3109 if (!IsPayingWithWallet() && IsAutofillEnabled()) {
3110 for (size_t i
= SECTION_MIN
; i
<= SECTION_MAX
; ++i
) {
3111 DialogSection section
= static_cast<DialogSection
>(i
);
3112 if (!SectionIsActive(section
))
3115 // Set the starting choice for the menu. First set to the default in case
3116 // the GUID saved in prefs refers to a profile that no longer exists.
3118 GetDefaultAutofillChoice(section
, &guid
);
3119 SuggestionsMenuModel
* model
= SuggestionsMenuModelForSection(section
);
3120 model
->SetCheckedItem(guid
);
3121 if (GetAutofillChoice(section
, &guid
))
3122 model
->SetCheckedItem(guid
);
3127 view_
->ModelChanged();
3129 for (size_t i
= SECTION_MIN
; i
<= SECTION_MAX
; ++i
) {
3130 ResetSectionInput(static_cast<DialogSection
>(i
));
3133 FieldValueMap::const_iterator billing_it
=
3134 snapshot
.find(ADDRESS_BILLING_COUNTRY
);
3135 if (billing_it
!= snapshot
.end())
3136 RebuildInputsForCountry(ActiveBillingSection(), billing_it
->second
, true);
3138 FieldValueMap::const_iterator shipping_it
=
3139 snapshot
.find(ADDRESS_HOME_COUNTRY
);
3140 if (shipping_it
!= snapshot
.end())
3141 RebuildInputsForCountry(SECTION_SHIPPING
, shipping_it
->second
, true);
3143 RestoreUserInputFromSnapshot(snapshot
);
3145 for (size_t i
= SECTION_MIN
; i
<= SECTION_MAX
; ++i
) {
3146 DialogSection section
= static_cast<DialogSection
>(i
);
3147 if (!SectionIsActive(section
))
3150 ShowEditUiIfBadSuggestion(section
);
3151 UpdateSection(section
);
3157 void AutofillDialogControllerImpl::FillOutputForSectionWithComparator(
3158 DialogSection section
,
3159 const FormStructure::InputFieldComparator
& compare
) {
3160 if (!SectionIsActive(section
))
3163 DetailInputs inputs
;
3164 std::string country_code
= CountryCodeForSection(section
);
3165 BuildInputsForSection(section
, country_code
, &inputs
,
3166 MutableAddressLanguageCodeForSection(section
));
3167 std::vector
<ServerFieldType
> types
= TypesFromInputs(inputs
);
3169 scoped_ptr
<DataModelWrapper
> wrapper
= CreateWrapper(section
);
3171 // Only fill in data that is associated with this section.
3172 wrapper
->FillFormStructure(types
, compare
, &form_structure_
);
3174 // CVC needs special-casing because the CreditCard class doesn't store or
3175 // handle them. This isn't necessary when filling the combined CC and
3176 // billing section as CVC comes from |full_wallet_| in this case.
3177 if (section
== SECTION_CC
)
3178 SetOutputForFieldsOfType(CREDIT_CARD_VERIFICATION_CODE
, view_
->GetCvc());
3180 // When filling from Wallet data, use the email address associated with the
3181 // account. There is no other email address stored as part of a Wallet
3183 if (section
== SECTION_CC_BILLING
) {
3184 SetOutputForFieldsOfType(
3185 EMAIL_ADDRESS
, account_chooser_model_
->GetActiveWalletAccountName());
3188 // The user manually input data. If using Autofill, save the info as new or
3189 // edited data. Always fill local data into |form_structure_|.
3190 FieldValueMap output
;
3191 view_
->GetUserInput(section
, &output
);
3193 if (section
== SECTION_CC
) {
3195 FillFormGroupFromOutputs(output
, &card
);
3197 // The card holder name comes from the billing address section.
3198 card
.SetRawInfo(CREDIT_CARD_NAME
,
3199 GetValueFromSection(SECTION_BILLING
, NAME_BILLING_FULL
));
3201 if (ShouldSaveDetailsLocally()) {
3202 card
.set_origin(kAutofillDialogOrigin
);
3204 std::string guid
= GetManager()->SaveImportedCreditCard(card
);
3205 newly_saved_data_model_guids_
[section
] = guid
;
3206 DCHECK(!profile()->IsOffTheRecord());
3207 newly_saved_card_
.reset(new CreditCard(card
));
3210 AutofillCreditCardWrapper
card_wrapper(&card
);
3211 card_wrapper
.FillFormStructure(types
, compare
, &form_structure_
);
3213 // Again, CVC needs special-casing. Fill it in directly from |output|.
3214 SetOutputForFieldsOfType(
3215 CREDIT_CARD_VERIFICATION_CODE
,
3216 output
[CREDIT_CARD_VERIFICATION_CODE
]);
3218 AutofillProfile profile
;
3219 FillFormGroupFromOutputs(output
, &profile
);
3220 profile
.set_language_code(AddressLanguageCodeForSection(section
));
3222 if (ShouldSaveDetailsLocally()) {
3223 profile
.set_origin(RulesAreLoaded(section
) ?
3224 kAutofillDialogOrigin
: source_url_
.GetOrigin().spec());
3226 std::string guid
= GetManager()->SaveImportedProfile(profile
);
3227 newly_saved_data_model_guids_
[section
] = guid
;
3230 AutofillProfileWrapper
profile_wrapper(&profile
);
3231 profile_wrapper
.FillFormStructure(types
, compare
, &form_structure_
);
3236 void AutofillDialogControllerImpl::FillOutputForSection(DialogSection section
) {
3237 FillOutputForSectionWithComparator(
3238 section
, base::Bind(ServerTypeMatchesField
, section
));
3241 bool AutofillDialogControllerImpl::FormStructureCaresAboutSection(
3242 DialogSection section
) const {
3243 // For now, only SECTION_SHIPPING may be omitted due to a site not asking for
3244 // any of the fields.
3245 if (section
== SECTION_SHIPPING
)
3246 return cares_about_shipping_
;
3251 void AutofillDialogControllerImpl::SetOutputForFieldsOfType(
3252 ServerFieldType type
,
3253 const base::string16
& output
) {
3254 for (size_t i
= 0; i
< form_structure_
.field_count(); ++i
) {
3255 AutofillField
* field
= form_structure_
.field(i
);
3256 if (field
->Type().GetStorableType() == type
)
3257 field
->value
= output
;
3261 base::string16
AutofillDialogControllerImpl::GetValueFromSection(
3262 DialogSection section
,
3263 ServerFieldType type
) {
3264 DCHECK(SectionIsActive(section
));
3266 scoped_ptr
<DataModelWrapper
> wrapper
= CreateWrapper(section
);
3268 return wrapper
->GetInfo(AutofillType(type
));
3270 FieldValueMap output
;
3271 view_
->GetUserInput(section
, &output
);
3272 return output
[type
];
3275 bool AutofillDialogControllerImpl::CanAcceptCountry(
3276 DialogSection section
,
3277 const std::string
& country_code
) {
3278 DCHECK_EQ(2U, country_code
.size());
3280 if (section
== SECTION_CC_BILLING
)
3281 return LowerCaseEqualsASCII(country_code
, "us");
3283 CountryComboboxModel
* model
= CountryComboboxModelForSection(section
);
3284 const std::vector
<AutofillCountry
*>& countries
= model
->countries();
3285 for (size_t i
= 0; i
< countries
.size(); ++i
) {
3286 if (countries
[i
] && countries
[i
]->country_code() == country_code
)
3293 bool AutofillDialogControllerImpl::ShouldSuggestProfile(
3294 DialogSection section
,
3295 const AutofillProfile
& profile
) {
3296 std::string country_code
=
3297 base::UTF16ToASCII(profile
.GetRawInfo(ADDRESS_HOME_COUNTRY
));
3298 return country_code
.empty() || CanAcceptCountry(section
, country_code
);
3301 SuggestionsMenuModel
* AutofillDialogControllerImpl::
3302 SuggestionsMenuModelForSection(DialogSection section
) {
3305 return &suggested_cc_
;
3306 case SECTION_BILLING
:
3307 return &suggested_billing_
;
3308 case SECTION_SHIPPING
:
3309 return &suggested_shipping_
;
3310 case SECTION_CC_BILLING
:
3311 return &suggested_cc_billing_
;
3318 const SuggestionsMenuModel
* AutofillDialogControllerImpl::
3319 SuggestionsMenuModelForSection(DialogSection section
) const {
3320 return const_cast<AutofillDialogControllerImpl
*>(this)->
3321 SuggestionsMenuModelForSection(section
);
3324 DialogSection
AutofillDialogControllerImpl::SectionForSuggestionsMenuModel(
3325 const SuggestionsMenuModel
& model
) {
3326 if (&model
== &suggested_cc_
)
3329 if (&model
== &suggested_billing_
)
3330 return SECTION_BILLING
;
3332 if (&model
== &suggested_cc_billing_
)
3333 return SECTION_CC_BILLING
;
3335 DCHECK_EQ(&model
, &suggested_shipping_
);
3336 return SECTION_SHIPPING
;
3339 CountryComboboxModel
* AutofillDialogControllerImpl::
3340 CountryComboboxModelForSection(DialogSection section
) {
3341 if (section
== SECTION_BILLING
)
3342 return billing_country_combobox_model_
.get();
3344 if (section
== SECTION_SHIPPING
)
3345 return shipping_country_combobox_model_
.get();
3350 void AutofillDialogControllerImpl::GetI18nValidatorSuggestions(
3351 DialogSection section
,
3352 ServerFieldType type
,
3353 std::vector
<autofill::Suggestion
>* popup_suggestions
) {
3354 AddressField focused_field
;
3355 if (!i18n::FieldForType(type
, &focused_field
))
3358 FieldValueMap inputs
;
3359 view_
->GetUserInput(section
, &inputs
);
3361 AutofillProfile profile
;
3362 FillFormGroupFromOutputs(inputs
, &profile
);
3364 scoped_ptr
<AddressData
> user_input
=
3365 i18n::CreateAddressDataFromAutofillProfile(
3366 profile
, g_browser_process
->GetApplicationLocale());
3367 user_input
->language_code
= AddressLanguageCodeForSection(section
);
3369 static const size_t kSuggestionsLimit
= 10;
3370 AddressValidator::Status status
= GetValidator()->GetSuggestions(
3371 *user_input
, focused_field
, kSuggestionsLimit
,
3372 &i18n_validator_suggestions_
);
3374 if (status
!= AddressValidator::SUCCESS
)
3377 for (size_t i
= 0; i
< i18n_validator_suggestions_
.size(); ++i
) {
3378 popup_suggestions
->push_back(autofill::Suggestion(
3380 i18n_validator_suggestions_
[i
].GetFieldValue(focused_field
))));
3382 // Disambiguate the suggestion by showing the smallest administrative
3383 // region of the suggested address:
3384 // ADMIN_AREA > LOCALITY > DEPENDENT_LOCALITY
3385 for (int field
= DEPENDENT_LOCALITY
; field
>= ADMIN_AREA
; --field
) {
3386 const std::string
& field_value
=
3387 i18n_validator_suggestions_
[i
].GetFieldValue(
3388 static_cast<AddressField
>(field
));
3389 if (focused_field
!= field
&& !field_value
.empty()) {
3390 popup_suggestions
->back().label
= base::UTF8ToUTF16(field_value
);
3397 DetailInputs
* AutofillDialogControllerImpl::MutableRequestedFieldsForSection(
3398 DialogSection section
) {
3399 return const_cast<DetailInputs
*>(&RequestedFieldsForSection(section
));
3402 std::string
* AutofillDialogControllerImpl::MutableAddressLanguageCodeForSection(
3403 DialogSection section
) {
3405 case SECTION_BILLING
:
3406 case SECTION_CC_BILLING
:
3407 return &billing_address_language_code_
;
3408 case SECTION_SHIPPING
:
3409 return &shipping_address_language_code_
;
3417 std::string
AutofillDialogControllerImpl::AddressLanguageCodeForSection(
3418 DialogSection section
) {
3419 std::string
* language_code
= MutableAddressLanguageCodeForSection(section
);
3420 return language_code
!= NULL
? *language_code
: std::string();
3423 std::vector
<ServerFieldType
> AutofillDialogControllerImpl::
3424 RequestedTypesForSection(DialogSection section
) const {
3425 return TypesFromInputs(RequestedFieldsForSection(section
));
3428 std::string
AutofillDialogControllerImpl::CountryCodeForSection(
3429 DialogSection section
) {
3430 base::string16 country
;
3432 scoped_ptr
<DataModelWrapper
> wrapper
= CreateWrapper(section
);
3434 country
= wrapper
->GetInfo(AutofillType(CountryTypeForSection(section
)));
3436 FieldValueMap outputs
;
3437 view_
->GetUserInput(section
, &outputs
);
3438 country
= outputs
[CountryTypeForSection(section
)];
3441 return AutofillCountry::GetCountryCode(
3442 country
, g_browser_process
->GetApplicationLocale());
3445 bool AutofillDialogControllerImpl::RebuildInputsForCountry(
3446 DialogSection section
,
3447 const base::string16
& country_name
,
3448 bool should_clobber
) {
3449 CountryComboboxModel
* model
= CountryComboboxModelForSection(section
);
3453 std::string country_code
= AutofillCountry::GetCountryCode(
3454 country_name
, g_browser_process
->GetApplicationLocale());
3455 DCHECK(CanAcceptCountry(section
, country_code
));
3457 if (view_
&& !should_clobber
) {
3458 FieldValueMap outputs
;
3459 view_
->GetUserInput(section
, &outputs
);
3461 // If |country_name| is the same as the view, no-op and let the caller know.
3462 if (outputs
[CountryTypeForSection(section
)] == country_name
)
3466 DetailInputs
* inputs
= MutableRequestedFieldsForSection(section
);
3468 BuildInputsForSection(section
, country_code
, inputs
,
3469 MutableAddressLanguageCodeForSection(section
));
3471 if (!country_code
.empty()) {
3472 GetValidator()->LoadRules(AutofillCountry::GetCountryCode(
3473 country_name
, g_browser_process
->GetApplicationLocale()));
3479 void AutofillDialogControllerImpl::HidePopup() {
3480 if (popup_controller_
)
3481 popup_controller_
->Hide();
3482 popup_input_type_
= UNKNOWN_TYPE
;
3485 void AutofillDialogControllerImpl::SetEditingExistingData(
3486 DialogSection section
, bool editing
) {
3488 section_editing_state_
.insert(section
);
3490 section_editing_state_
.erase(section
);
3493 bool AutofillDialogControllerImpl::IsASuggestionItemKey(
3494 const std::string
& key
) const {
3495 return !key
.empty() &&
3496 key
!= kAddNewItemKey
&&
3497 key
!= kManageItemsKey
&&
3498 key
!= kSameAsBillingKey
;
3501 bool AutofillDialogControllerImpl::IsAutofillEnabled() const {
3502 return profile_
->GetPrefs()->GetBoolean(prefs::kAutofillEnabled
);
3505 bool AutofillDialogControllerImpl::IsManuallyEditingAnySection() const {
3506 for (size_t section
= SECTION_MIN
; section
<= SECTION_MAX
; ++section
) {
3507 if (IsManuallyEditingSection(static_cast<DialogSection
>(section
)))
3513 base::string16
AutofillDialogControllerImpl::CreditCardNumberValidityMessage(
3514 const base::string16
& number
) const {
3515 if (!number
.empty() && !autofill::IsValidCreditCardNumber(number
)) {
3516 return l10n_util::GetStringUTF16(
3517 IDS_AUTOFILL_DIALOG_VALIDATION_INVALID_CREDIT_CARD_NUMBER
);
3520 if (!IsPayingWithWallet() &&
3521 ShouldDisallowCcType(CreditCard::TypeForDisplay(
3522 CreditCard::GetCreditCardType(number
)))) {
3523 int ids
= IDS_AUTOFILL_DIALOG_VALIDATION_UNACCEPTED_GENERIC_CARD
;
3524 const char* const type
= CreditCard::GetCreditCardType(number
);
3525 if (type
== kAmericanExpressCard
)
3526 ids
= IDS_AUTOFILL_DIALOG_VALIDATION_UNACCEPTED_AMEX
;
3527 else if (type
== kDiscoverCard
)
3528 ids
= IDS_AUTOFILL_DIALOG_VALIDATION_UNACCEPTED_DISCOVER
;
3529 else if (type
== kMasterCard
)
3530 ids
= IDS_AUTOFILL_DIALOG_VALIDATION_UNACCEPTED_MASTERCARD
;
3531 else if (type
== kVisaCard
)
3532 ids
= IDS_AUTOFILL_DIALOG_VALIDATION_UNACCEPTED_VISA
;
3534 return l10n_util::GetStringUTF16(ids
);
3537 base::string16 message
;
3538 if (IsPayingWithWallet() && !wallet_items_
->SupportsCard(number
, &message
))
3541 // Card number is good and supported.
3542 return base::string16();
3545 bool AutofillDialogControllerImpl::AllSectionsAreValid() {
3546 for (size_t section
= SECTION_MIN
; section
<= SECTION_MAX
; ++section
) {
3547 if (!SectionIsValid(static_cast<DialogSection
>(section
)))
3553 bool AutofillDialogControllerImpl::SectionIsValid(
3554 DialogSection section
) {
3555 if (!IsManuallyEditingSection(section
))
3558 FieldValueMap detail_outputs
;
3559 view_
->GetUserInput(section
, &detail_outputs
);
3560 return !InputsAreValid(section
, detail_outputs
).HasSureErrors();
3563 bool AutofillDialogControllerImpl::RulesAreLoaded(DialogSection section
) {
3564 AddressData address_data
;
3565 address_data
.region_code
= CountryCodeForSection(section
);
3566 AddressValidator::Status status
= GetValidator()->ValidateAddress(
3567 address_data
, NULL
, NULL
);
3568 return status
== AddressValidator::SUCCESS
;
3571 bool AutofillDialogControllerImpl::IsCreditCardExpirationValid(
3572 const base::string16
& year
,
3573 const base::string16
& month
) const {
3574 // If the expiration is in the past as per the local clock, it's invalid.
3575 base::Time now
= base::Time::Now();
3576 if (!autofill::IsValidCreditCardExpirationDate(year
, month
, now
))
3579 const wallet::WalletItems::MaskedInstrument
* instrument
=
3582 const std::string
& locale
= g_browser_process
->GetApplicationLocale();
3584 if (base::StringToInt(month
, &month_int
) &&
3585 instrument
->status() ==
3586 wallet::WalletItems::MaskedInstrument::EXPIRED
&&
3588 instrument
->GetInfo(
3589 AutofillType(CREDIT_CARD_EXP_4_DIGIT_YEAR
), locale
) &&
3590 month_int
== instrument
->expiration_month()) {
3591 // Otherwise, if the user is editing an instrument that's deemed expired
3592 // by the Online Wallet server, mark it invalid on selection.
3600 bool AutofillDialogControllerImpl::ShouldDisallowCcType(
3601 const base::string16
& type
) const {
3602 if (acceptable_cc_types_
.empty())
3605 if (acceptable_cc_types_
.find(base::i18n::ToUpper(type
)) ==
3606 acceptable_cc_types_
.end()) {
3613 bool AutofillDialogControllerImpl::HasInvalidAddress(
3614 const AutofillProfile
& profile
) {
3615 scoped_ptr
<AddressData
> address_data
=
3616 i18n::CreateAddressDataFromAutofillProfile(
3617 profile
, g_browser_process
->GetApplicationLocale());
3619 FieldProblemMap problems
;
3620 GetValidator()->ValidateAddress(*address_data
, NULL
, &problems
);
3621 return !problems
.empty();
3624 bool AutofillDialogControllerImpl::ShouldUseBillingForShipping() {
3625 return SectionIsActive(SECTION_SHIPPING
) &&
3626 suggested_shipping_
.GetItemKeyForCheckedItem() == kSameAsBillingKey
;
3629 bool AutofillDialogControllerImpl::ShouldSaveDetailsLocally() {
3630 // It's possible that the user checked [X] Save details locally before
3631 // switching payment methods, so only ask the view whether to save details
3632 // locally if that checkbox is showing (currently if not paying with wallet).
3633 // Also, if the user isn't editing any sections, there's no data to save
3635 return ShouldOfferToSaveInChrome() && view_
->SaveDetailsLocally();
3638 void AutofillDialogControllerImpl::SetIsSubmitting(bool submitting
) {
3639 is_submitting_
= submitting
;
3642 full_wallet_
.reset();
3645 ScopedViewUpdates
updates(view_
.get());
3646 view_
->UpdateButtonStrip();
3647 view_
->UpdateOverlay();
3648 view_
->UpdateNotificationArea();
3652 bool AutofillDialogControllerImpl::AreLegalDocumentsCurrent() const {
3653 return has_accepted_legal_documents_
||
3654 (wallet_items_
&& wallet_items_
->legal_documents().empty());
3657 void AutofillDialogControllerImpl::AcceptLegalTerms() {
3658 content::GeolocationProvider::GetInstance()->UserDidOptIntoLocationServices();
3659 PrefService
* local_state
= g_browser_process
->local_state();
3660 ListPrefUpdate
accepted(
3661 local_state
, ::prefs::kAutofillDialogWalletLocationAcceptance
);
3662 accepted
->AppendIfNotPresent(new base::StringValue(
3663 account_chooser_model_
->GetActiveWalletAccountName()));
3665 if (AreLegalDocumentsCurrent()) {
3666 LoadRiskFingerprintData();
3668 GetWalletClient()->AcceptLegalDocuments(
3669 wallet_items_
->legal_documents(),
3670 wallet_items_
->google_transaction_id());
3674 void AutofillDialogControllerImpl::SubmitWithWallet() {
3675 active_instrument_id_
.clear();
3676 active_address_id_
.clear();
3677 full_wallet_
.reset();
3679 const wallet::WalletItems::MaskedInstrument
* active_instrument
=
3681 if (!IsManuallyEditingSection(SECTION_CC_BILLING
)) {
3682 active_instrument_id_
= active_instrument
->object_id();
3683 DCHECK(!active_instrument_id_
.empty());
3686 const wallet::Address
* active_address
= ActiveShippingAddress();
3687 if (!IsManuallyEditingSection(SECTION_SHIPPING
) &&
3688 !ShouldUseBillingForShipping() &&
3689 IsShippingAddressRequired()) {
3690 active_address_id_
= active_address
->object_id();
3691 DCHECK(!active_address_id_
.empty());
3694 scoped_ptr
<wallet::Instrument
> inputted_instrument
=
3695 CreateTransientInstrument();
3697 scoped_ptr
<wallet::Address
> inputted_address
;
3698 if (active_address_id_
.empty() && IsShippingAddressRequired()) {
3699 if (ShouldUseBillingForShipping()) {
3700 const wallet::Address
& address
= inputted_instrument
?
3701 *inputted_instrument
->address() : active_instrument
->address();
3702 // Try to find an exact matched shipping address and use it for shipping,
3703 // otherwise save it as a new shipping address. http://crbug.com/225442
3704 const wallet::Address
* duplicated_address
=
3705 FindDuplicateAddress(wallet_items_
->addresses(), address
);
3706 if (duplicated_address
) {
3707 active_address_id_
= duplicated_address
->object_id();
3708 DCHECK(!active_address_id_
.empty());
3710 inputted_address
.reset(new wallet::Address(address
));
3711 DCHECK(inputted_address
->object_id().empty());
3714 inputted_address
= CreateTransientAddress();
3718 // If there's neither an address nor instrument to save, |GetFullWallet()|
3719 // is called when the risk fingerprint is loaded.
3720 if (!active_instrument_id_
.empty() &&
3721 (!active_address_id_
.empty() || !IsShippingAddressRequired())) {
3726 GetWalletClient()->SaveToWallet(
3727 inputted_instrument
.Pass(),
3728 inputted_address
.Pass(),
3729 IsEditingExistingData(SECTION_CC_BILLING
) ? active_instrument
: NULL
,
3730 IsEditingExistingData(SECTION_SHIPPING
) ? active_address
: NULL
);
3733 scoped_ptr
<wallet::Instrument
> AutofillDialogControllerImpl::
3734 CreateTransientInstrument() {
3735 if (!active_instrument_id_
.empty())
3736 return scoped_ptr
<wallet::Instrument
>();
3738 FieldValueMap output
;
3739 view_
->GetUserInput(SECTION_CC_BILLING
, &output
);
3742 AutofillProfile profile
;
3744 GetBillingInfoFromOutputs(output
, &card
, &cvc
, &profile
);
3745 CanonicalizeState(validator_
.get(), &profile
);
3747 return scoped_ptr
<wallet::Instrument
>(
3748 new wallet::Instrument(card
, cvc
, profile
));
3751 scoped_ptr
<wallet::Address
>AutofillDialogControllerImpl::
3752 CreateTransientAddress() {
3753 // If not using billing for shipping, just scrape the view.
3754 FieldValueMap output
;
3755 view_
->GetUserInput(SECTION_SHIPPING
, &output
);
3757 AutofillProfile profile
;
3758 FillFormGroupFromOutputs(output
, &profile
);
3759 profile
.set_language_code(shipping_address_language_code_
);
3760 CanonicalizeState(validator_
.get(), &profile
);
3762 return scoped_ptr
<wallet::Address
>(new wallet::Address(profile
));
3765 void AutofillDialogControllerImpl::GetFullWallet() {
3766 DCHECK(is_submitting_
);
3767 DCHECK(IsPayingWithWallet());
3768 DCHECK(wallet_items_
);
3769 DCHECK(!active_instrument_id_
.empty());
3770 DCHECK(!active_address_id_
.empty() || !IsShippingAddressRequired());
3772 std::vector
<wallet::WalletClient::RiskCapability
> capabilities
;
3773 capabilities
.push_back(wallet::WalletClient::VERIFY_CVC
);
3775 GetWalletClient()->GetFullWallet(wallet::WalletClient::FullWalletRequest(
3776 active_instrument_id_
,
3778 wallet_items_
->google_transaction_id(),
3780 wallet_items_
->HasRequiredAction(wallet::SETUP_WALLET
)));
3783 void AutofillDialogControllerImpl::HandleSaveOrUpdateRequiredActions(
3784 const std::vector
<wallet::RequiredAction
>& required_actions
) {
3785 DCHECK(!required_actions
.empty());
3787 // TODO(ahutter): Investigate if we need to support more generic actions on
3788 // this call such as GAIA_AUTH. See crbug.com/243457.
3789 for (std::vector
<wallet::RequiredAction
>::const_iterator iter
=
3790 required_actions
.begin();
3791 iter
!= required_actions
.end(); ++iter
) {
3792 if (*iter
!= wallet::INVALID_FORM_FIELD
) {
3793 // TODO(dbeam): handle this more gracefully.
3794 DisableWallet(wallet::WalletClient::UNKNOWN_ERROR
);
3797 SetIsSubmitting(false);
3800 void AutofillDialogControllerImpl::FinishSubmit() {
3801 if (IsPayingWithWallet()) {
3802 ScopedViewUpdates
updates(view_
.get());
3803 view_
->UpdateOverlay();
3805 card_generated_animation_
.Start();
3811 void AutofillDialogControllerImpl::AnimationProgressed(
3812 const gfx::Animation
* animation
) {
3813 DCHECK_EQ(animation
, &card_generated_animation_
);
3814 PushOverlayUpdate();
3817 void AutofillDialogControllerImpl::AnimationEnded(
3818 const gfx::Animation
* animation
) {
3819 DCHECK_EQ(animation
, &card_generated_animation_
);
3823 void AutofillDialogControllerImpl::OnAddressValidationRulesLoaded(
3824 const std::string
& country_code
,
3826 // Rules may load instantly (during initialization, before the view is
3827 // even ready). We'll validate when the view is created.
3831 ScopedViewUpdates
updates(view_
.get());
3833 // TODO(dbeam): should we retry on failure?
3834 for (size_t i
= SECTION_MIN
; i
<= SECTION_MAX
; ++i
) {
3835 DialogSection section
= static_cast<DialogSection
>(i
);
3836 if (!SectionIsActive(section
) ||
3837 CountryCodeForSection(section
) != country_code
) {
3841 if (IsManuallyEditingSection(section
) &&
3842 needs_validation_
.count(section
)) {
3843 view_
->ValidateSection(section
);
3844 needs_validation_
.erase(section
);
3845 } else if (success
) {
3846 ShowEditUiIfBadSuggestion(section
);
3847 UpdateSection(section
);
3852 void AutofillDialogControllerImpl::DoFinishSubmit() {
3853 FillOutputForSection(SECTION_CC
);
3854 FillOutputForSection(SECTION_BILLING
);
3855 FillOutputForSection(SECTION_CC_BILLING
);
3857 if (ShouldUseBillingForShipping()) {
3858 FillOutputForSectionWithComparator(
3860 base::Bind(ServerTypeMatchesShippingField
));
3861 FillOutputForSectionWithComparator(
3863 base::Bind(ServerTypeMatchesShippingField
));
3864 FillOutputForSectionWithComparator(
3866 base::Bind(ServerTypeMatchesShippingField
));
3868 FillOutputForSection(SECTION_SHIPPING
);
3871 if (IsPayingWithWallet()) {
3872 if (SectionIsActive(SECTION_SHIPPING
)) {
3873 profile_
->GetPrefs()->SetBoolean(
3874 ::prefs::kAutofillDialogWalletShippingSameAsBilling
,
3875 suggested_shipping_
.GetItemKeyForCheckedItem() == kSameAsBillingKey
);
3877 } else if (ShouldOfferToSaveInChrome()) {
3878 for (size_t i
= SECTION_MIN
; i
<= SECTION_MAX
; ++i
) {
3879 DialogSection section
= static_cast<DialogSection
>(i
);
3880 if (!SectionIsActive(section
))
3883 SuggestionsMenuModel
* model
= SuggestionsMenuModelForSection(section
);
3884 std::string item_key
= model
->GetItemKeyForCheckedItem();
3885 if (IsASuggestionItemKey(item_key
) || item_key
== kSameAsBillingKey
) {
3886 PersistAutofillChoice(section
, item_key
);
3887 } else if (item_key
== kAddNewItemKey
&& ShouldSaveDetailsLocally()) {
3888 DCHECK(newly_saved_data_model_guids_
.count(section
));
3889 PersistAutofillChoice(section
, newly_saved_data_model_guids_
[section
]);
3893 profile_
->GetPrefs()->SetBoolean(::prefs::kAutofillDialogSaveData
,
3894 view_
->SaveDetailsLocally());
3897 // On a successful submit, if the user manually selected "pay without wallet",
3898 // stop trying to pay with Wallet on future runs of the dialog. On the other
3899 // hand, if there was an error that prevented the user from having the choice
3900 // of using Wallet, leave the pref alone.
3901 if (!wallet_error_notification_
&&
3902 account_chooser_model_
->HasAccountsToChoose()) {
3903 profile_
->GetPrefs()->SetBoolean(
3904 ::prefs::kAutofillDialogPayWithoutWallet
,
3905 !account_chooser_model_
->WalletIsSelected());
3908 LogOnFinishSubmitMetrics();
3910 // Callback should be called as late as possible.
3911 callback_
.Run(AutofillClient::AutocompleteResultSuccess
,
3914 data_was_passed_back_
= true;
3916 // This might delete us.
3920 void AutofillDialogControllerImpl::PersistAutofillChoice(
3921 DialogSection section
,
3922 const std::string
& guid
) {
3923 DCHECK(!IsPayingWithWallet() && ShouldOfferToSaveInChrome());
3924 scoped_ptr
<base::DictionaryValue
> value(new base::DictionaryValue());
3925 value
->SetString(kGuidPrefKey
, guid
);
3927 DictionaryPrefUpdate
updater(profile()->GetPrefs(),
3928 ::prefs::kAutofillDialogAutofillDefault
);
3929 base::DictionaryValue
* autofill_choice
= updater
.Get();
3930 autofill_choice
->Set(SectionToPrefString(section
), value
.release());
3933 void AutofillDialogControllerImpl::GetDefaultAutofillChoice(
3934 DialogSection section
,
3935 std::string
* guid
) {
3936 DCHECK(!IsPayingWithWallet() && IsAutofillEnabled());
3937 // The default choice is the first thing in the menu that is a suggestion
3939 SuggestionsMenuModel
* model
= SuggestionsMenuModelForSection(section
);
3940 for (int i
= 0; i
< model
->GetItemCount(); ++i
) {
3941 // Try the first suggestion item that is enabled.
3942 if (IsASuggestionItemKey(model
->GetItemKeyAt(i
)) && model
->IsEnabledAt(i
)) {
3943 *guid
= model
->GetItemKeyAt(i
);
3945 // Fall back to the first non-suggestion key.
3946 } else if (!IsASuggestionItemKey(model
->GetItemKeyAt(i
)) && guid
->empty()) {
3947 *guid
= model
->GetItemKeyAt(i
);
3952 bool AutofillDialogControllerImpl::GetAutofillChoice(DialogSection section
,
3953 std::string
* guid
) {
3954 DCHECK(!IsPayingWithWallet() && IsAutofillEnabled());
3955 const base::DictionaryValue
* choices
= profile()->GetPrefs()->GetDictionary(
3956 ::prefs::kAutofillDialogAutofillDefault
);
3960 const base::DictionaryValue
* choice
= NULL
;
3961 if (!choices
->GetDictionary(SectionToPrefString(section
), &choice
))
3964 choice
->GetString(kGuidPrefKey
, guid
);
3968 void AutofillDialogControllerImpl::LogOnFinishSubmitMetrics() {
3969 AutofillMetrics::LogDialogUiDuration(
3970 base::Time::Now() - dialog_shown_timestamp_
,
3971 AutofillMetrics::DIALOG_ACCEPTED
);
3973 AutofillMetrics::LogDialogUiEvent(AutofillMetrics::DIALOG_UI_ACCEPTED
);
3975 AutofillMetrics::DialogDismissalState dismissal_state
;
3976 if (!IsManuallyEditingAnySection()) {
3977 dismissal_state
= IsPayingWithWallet() ?
3978 AutofillMetrics::DIALOG_ACCEPTED_EXISTING_WALLET_DATA
:
3979 AutofillMetrics::DIALOG_ACCEPTED_EXISTING_AUTOFILL_DATA
;
3980 } else if (IsPayingWithWallet()) {
3981 dismissal_state
= AutofillMetrics::DIALOG_ACCEPTED_SAVE_TO_WALLET
;
3982 } else if (ShouldSaveDetailsLocally()) {
3983 dismissal_state
= AutofillMetrics::DIALOG_ACCEPTED_SAVE_TO_AUTOFILL
;
3985 dismissal_state
= AutofillMetrics::DIALOG_ACCEPTED_NO_SAVE
;
3988 AutofillMetrics::LogDialogDismissalState(dismissal_state
);
3991 void AutofillDialogControllerImpl::LogOnCancelMetrics() {
3992 AutofillMetrics::LogDialogUiEvent(AutofillMetrics::DIALOG_UI_CANCELED
);
3994 AutofillMetrics::DialogDismissalState dismissal_state
;
3995 if (ShouldShowSignInWebView())
3996 dismissal_state
= AutofillMetrics::DIALOG_CANCELED_DURING_SIGNIN
;
3997 else if (!IsManuallyEditingAnySection())
3998 dismissal_state
= AutofillMetrics::DIALOG_CANCELED_NO_EDITS
;
3999 else if (AllSectionsAreValid())
4000 dismissal_state
= AutofillMetrics::DIALOG_CANCELED_NO_INVALID_FIELDS
;
4002 dismissal_state
= AutofillMetrics::DIALOG_CANCELED_WITH_INVALID_FIELDS
;
4004 AutofillMetrics::LogDialogDismissalState(dismissal_state
);
4006 AutofillMetrics::LogDialogUiDuration(
4007 base::Time::Now() - dialog_shown_timestamp_
,
4008 AutofillMetrics::DIALOG_CANCELED
);
4011 void AutofillDialogControllerImpl::LogSuggestionItemSelectedMetric(
4012 const SuggestionsMenuModel
& model
) {
4013 DialogSection section
= SectionForSuggestionsMenuModel(model
);
4015 AutofillMetrics::DialogUiEvent dialog_ui_event
;
4016 if (model
.GetItemKeyForCheckedItem() == kAddNewItemKey
) {
4017 // Selected to add a new item.
4018 dialog_ui_event
= common::DialogSectionToUiItemAddedEvent(section
);
4019 } else if (IsASuggestionItemKey(model
.GetItemKeyForCheckedItem())) {
4020 // Selected an existing item.
4021 dialog_ui_event
= common::DialogSectionToUiSelectionChangedEvent(section
);
4023 // TODO(estade): add logging for "Manage items" or "Use billing for
4028 AutofillMetrics::LogDialogUiEvent(dialog_ui_event
);
4031 void AutofillDialogControllerImpl::LogDialogLatencyToShow() {
4032 if (was_ui_latency_logged_
)
4035 AutofillMetrics::LogDialogLatencyToShow(base::Time::Now() -
4036 dialog_shown_timestamp_
);
4037 was_ui_latency_logged_
= true;
4040 AutofillMetrics::DialogInitialUserStateMetric
4041 AutofillDialogControllerImpl::GetInitialUserState() const {
4042 // Consider a user to be an Autofill user if the user has any credit cards
4043 // or addresses saved. Check that the item count is greater than 2 because
4044 // an "empty" menu still has the "add new" menu item and "manage" menu item.
4045 const bool has_autofill_profiles
=
4046 suggested_cc_
.GetItemCount() > 2 ||
4047 suggested_billing_
.GetItemCount() > 2;
4049 if (SignedInState() != SIGNED_IN
) {
4051 return has_autofill_profiles
?
4052 AutofillMetrics::DIALOG_USER_NOT_SIGNED_IN_HAS_AUTOFILL
:
4053 AutofillMetrics::DIALOG_USER_NOT_SIGNED_IN_NO_AUTOFILL
;
4057 if (wallet_items_
->instruments().empty()) {
4059 return has_autofill_profiles
?
4060 AutofillMetrics::DIALOG_USER_SIGNED_IN_NO_WALLET_HAS_AUTOFILL
:
4061 AutofillMetrics::DIALOG_USER_SIGNED_IN_NO_WALLET_NO_AUTOFILL
;
4064 // Has Wallet items.
4065 return has_autofill_profiles
?
4066 AutofillMetrics::DIALOG_USER_SIGNED_IN_HAS_WALLET_HAS_AUTOFILL
:
4067 AutofillMetrics::DIALOG_USER_SIGNED_IN_HAS_WALLET_NO_AUTOFILL
;
4070 void AutofillDialogControllerImpl::MaybeShowCreditCardBubble() {
4071 if (!data_was_passed_back_
)
4074 if (newly_saved_card_
) {
4075 scoped_ptr
<AutofillProfile
> billing_profile
;
4076 if (IsManuallyEditingSection(SECTION_BILLING
)) {
4077 // Scrape the view as the user's entering or updating information.
4078 FieldValueMap outputs
;
4079 view_
->GetUserInput(SECTION_BILLING
, &outputs
);
4080 billing_profile
.reset(new AutofillProfile
);
4081 FillFormGroupFromOutputs(outputs
, billing_profile
.get());
4082 billing_profile
->set_language_code(billing_address_language_code_
);
4084 // Just snag the currently suggested profile.
4085 std::string item_key
= SuggestionsMenuModelForSection(SECTION_BILLING
)->
4086 GetItemKeyForCheckedItem();
4087 AutofillProfile
* profile
= GetManager()->GetProfileByGUID(item_key
);
4088 billing_profile
.reset(new AutofillProfile(*profile
));
4091 ShowNewCreditCardBubble(newly_saved_card_
.Pass(),
4092 billing_profile
.Pass());
4096 if (!full_wallet_
|| !full_wallet_
->billing_address())
4099 GeneratedCreditCardBubbleController::Show(
4101 full_wallet_
->TypeAndLastFourDigits(),
4102 backing_card_last_four_
);
4105 void AutofillDialogControllerImpl::OnSubmitButtonDelayEnd() {
4108 ScopedViewUpdates
updates(view_
.get());
4109 view_
->UpdateButtonStrip();
4112 void AutofillDialogControllerImpl::FetchWalletCookie() {
4113 net::URLRequestContextGetter
* request_context
= profile_
->GetRequestContext();
4114 signin_helper_
.reset(new wallet::WalletSigninHelper(this, request_context
));
4115 signin_helper_
->StartWalletCookieValueFetch();
4118 } // namespace autofill