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/base64.h"
12 #include "base/bind.h"
13 #include "base/bind_helpers.h"
14 #include "base/i18n/case_conversion.h"
15 #include "base/i18n/rtl.h"
16 #include "base/logging.h"
17 #include "base/prefs/pref_registry_simple.h"
18 #include "base/prefs/pref_service.h"
19 #include "base/prefs/scoped_user_pref_update.h"
20 #include "base/rand_util.h"
21 #include "base/strings/string_number_conversions.h"
22 #include "base/strings/string_split.h"
23 #include "base/strings/utf_string_conversions.h"
24 #include "base/time/time.h"
25 #include "chrome/browser/apps/app_window_registry_util.h"
26 #include "chrome/browser/autofill/personal_data_manager_factory.h"
27 #include "chrome/browser/autofill/validation_rules_storage_factory.h"
28 #include "chrome/browser/browser_process.h"
29 #include "chrome/browser/profiles/profile.h"
30 #include "chrome/browser/ui/autofill/autofill_dialog_common.h"
31 #include "chrome/browser/ui/autofill/autofill_dialog_i18n_input.h"
32 #include "chrome/browser/ui/autofill/autofill_dialog_view.h"
33 #include "chrome/browser/ui/autofill/data_model_wrapper.h"
34 #include "chrome/browser/ui/autofill/generated_credit_card_bubble_controller.h"
35 #include "chrome/browser/ui/autofill/new_credit_card_bubble_controller.h"
36 #include "chrome/browser/ui/browser.h"
37 #include "chrome/browser/ui/browser_finder.h"
38 #include "chrome/browser/ui/browser_navigator.h"
39 #include "chrome/browser/ui/browser_window.h"
40 #include "chrome/common/chrome_content_client.h"
41 #include "chrome/common/chrome_version_info.h"
42 #include "chrome/common/pref_names.h"
43 #include "chrome/common/render_messages.h"
44 #include "chrome/common/url_constants.h"
45 #include "chrome/grit/chromium_strings.h"
46 #include "chrome/grit/generated_resources.h"
47 #include "components/autofill/content/browser/risk/fingerprint.h"
48 #include "components/autofill/content/browser/risk/proto/fingerprint.pb.h"
49 #include "components/autofill/content/browser/wallet/form_field_error.h"
50 #include "components/autofill/content/browser/wallet/full_wallet.h"
51 #include "components/autofill/content/browser/wallet/gaia_account.h"
52 #include "components/autofill/content/browser/wallet/instrument.h"
53 #include "components/autofill/content/browser/wallet/wallet_address.h"
54 #include "components/autofill/content/browser/wallet/wallet_items.h"
55 #include "components/autofill/content/browser/wallet/wallet_service_url.h"
56 #include "components/autofill/content/browser/wallet/wallet_signin_helper.h"
57 #include "components/autofill/core/browser/address_i18n.h"
58 #include "components/autofill/core/browser/autofill_country.h"
59 #include "components/autofill/core/browser/autofill_data_model.h"
60 #include "components/autofill/core/browser/autofill_manager.h"
61 #include "components/autofill/core/browser/autofill_type.h"
62 #include "components/autofill/core/browser/personal_data_manager.h"
63 #include "components/autofill/core/browser/phone_number_i18n.h"
64 #include "components/autofill/core/browser/validation.h"
65 #include "components/autofill/core/common/autofill_pref_names.h"
66 #include "components/autofill/core/common/form_data.h"
67 #include "components/metrics/metrics_service.h"
68 #include "components/pref_registry/pref_registry_syncable.h"
69 #include "content/public/browser/browser_thread.h"
70 #include "content/public/browser/geolocation_provider.h"
71 #include "content/public/browser/navigation_controller.h"
72 #include "content/public/browser/navigation_details.h"
73 #include "content/public/browser/navigation_entry.h"
74 #include "content/public/browser/notification_service.h"
75 #include "content/public/browser/notification_types.h"
76 #include "content/public/browser/render_view_host.h"
77 #include "content/public/browser/web_contents.h"
78 #include "content/public/common/url_constants.h"
79 #include "extensions/browser/app_window/app_window.h"
80 #include "extensions/browser/app_window/native_app_window.h"
81 #include "grit/components_scaled_resources.h"
82 #include "grit/components_strings.h"
83 #include "grit/platform_locale_settings.h"
84 #include "grit/theme_resources.h"
85 #include "net/cert/cert_status_flags.h"
86 #include "third_party/libaddressinput/chromium/chrome_metadata_source.h"
87 #include "third_party/libaddressinput/chromium/chrome_storage_impl.h"
88 #include "third_party/libaddressinput/messages.h"
89 #include "third_party/libaddressinput/src/cpp/include/libaddressinput/address_data.h"
90 #include "third_party/libaddressinput/src/cpp/include/libaddressinput/address_field.h"
91 #include "third_party/libaddressinput/src/cpp/include/libaddressinput/address_problem.h"
92 #include "third_party/libaddressinput/src/cpp/include/libaddressinput/localization.h"
93 #include "ui/base/base_window.h"
94 #include "ui/base/l10n/l10n_util.h"
95 #include "ui/base/models/combobox_model.h"
96 #include "ui/base/resource/resource_bundle.h"
97 #include "ui/gfx/canvas.h"
98 #include "ui/gfx/image/image_skia_operations.h"
99 #include "ui/gfx/skia_util.h"
101 using ::i18n::addressinput::AddressData;
102 using ::i18n::addressinput::AddressField;
103 using ::i18n::addressinput::AddressProblem;
104 using ::i18n::addressinput::ADMIN_AREA;
105 using ::i18n::addressinput::DEPENDENT_LOCALITY;
106 using ::i18n::addressinput::FieldProblemMap;
107 using ::i18n::addressinput::Localization;
108 using ::i18n::addressinput::MISSING_REQUIRED_FIELD;
114 const char kAddNewItemKey[] = "add-new-item";
115 const char kManageItemsKey[] = "manage-items";
116 const char kSameAsBillingKey[] = "same-as-billing";
118 // URLs for Wallet error messages.
119 const char kBuyerLegalAddressStatusUrl[] =
120 "https://wallet.google.com/manage/settings";
121 const char kKnowYourCustomerStatusUrl[] = "https://wallet.google.com/kyc";
123 // Keys for the kAutofillDialogAutofillDefault pref dictionary (do not change
125 const char kGuidPrefKey[] = "guid";
127 // This string is stored along with saved addresses and credit cards in the
128 // WebDB, and hence should not be modified, so that it remains consistent over
130 const char kAutofillDialogOrigin[] = "Chrome Autofill dialog";
132 // HSL shift to gray out an image.
133 const color_utils::HSL kGrayImageShift = {-1, 0, 0.8};
135 // Limit Wallet items refresh rate to at most once per minute.
136 const int64 kWalletItemsRefreshRateSeconds = 60;
138 // The number of milliseconds to delay enabling the submit button after showing
139 // the dialog. This delay prevents users from accidentally clicking the submit
140 // button on startup.
141 const int kSubmitButtonDelayMs = 1000;
143 // A helper class to make sure an AutofillDialogView knows when a series of
144 // updates is incoming.
145 class ScopedViewUpdates {
147 explicit ScopedViewUpdates(AutofillDialogView* view) : view_(view) {
149 view_->UpdatesStarted();
152 ~ScopedViewUpdates() {
154 view_->UpdatesFinished();
158 AutofillDialogView* view_;
160 DISALLOW_COPY_AND_ASSIGN(ScopedViewUpdates);
163 base::string16 NullGetInfo(const AutofillType& type) {
164 return base::string16();
167 // Extract |type| from |inputs| using |section| to determine whether the info
168 // should be billing or shipping specific (for sections with address info).
169 base::string16 GetInfoFromInputs(const FieldValueMap& inputs,
170 DialogSection section,
171 const AutofillType& type) {
172 ServerFieldType field_type = type.GetStorableType();
173 if (section != SECTION_SHIPPING)
174 field_type = AutofillType::GetEquivalentBillingFieldType(field_type);
177 FieldValueMap::const_iterator it = inputs.find(field_type);
178 if (it != inputs.end())
181 if (!info.empty() && type.html_type() == HTML_TYPE_COUNTRY_CODE) {
182 info = base::ASCIIToUTF16(AutofillCountry::GetCountryCode(
183 info, g_browser_process->GetApplicationLocale()));
189 // Returns true if |input| should be used to fill a site-requested |field| which
190 // is notated with a "shipping" tag, for use when the user has decided to use
191 // the billing address as the shipping address.
192 bool ServerTypeMatchesShippingField(ServerFieldType type,
193 const AutofillField& field) {
194 // Equivalent billing field type is used to support UseBillingAsShipping
196 return common::ServerTypeEncompassesFieldType(
198 AutofillType(AutofillType::GetEquivalentBillingFieldType(
199 field.Type().GetStorableType())));
202 // Initializes |form_group| from user-entered data.
203 void FillFormGroupFromOutputs(const FieldValueMap& detail_outputs,
204 FormGroup* form_group) {
205 for (FieldValueMap::const_iterator iter = detail_outputs.begin();
206 iter != detail_outputs.end(); ++iter) {
207 ServerFieldType type = iter->first;
208 if (!iter->second.empty()) {
209 form_group->SetInfo(AutofillType(type),
211 g_browser_process->GetApplicationLocale());
216 // Get billing info from |output| and put it into |card|, |cvc|, and |profile|.
217 // These outparams are required because |card|/|profile| accept different types
218 // of raw info, and CreditCard doesn't save CVCs.
219 void GetBillingInfoFromOutputs(const FieldValueMap& output,
222 AutofillProfile* profile) {
223 for (FieldValueMap::const_iterator it = output.begin();
224 it != output.end(); ++it) {
225 const ServerFieldType type = it->first;
226 base::string16 trimmed;
227 base::TrimWhitespace(it->second, base::TRIM_ALL, &trimmed);
229 // Special case CVC as CreditCard just swallows it.
230 if (type == CREDIT_CARD_VERIFICATION_CODE) {
232 cvc->assign(trimmed);
233 } else if (common::IsCreditCardType(type)) {
234 card->SetRawInfo(type, trimmed);
236 // Copy the credit card name to |profile| in addition to |card| as
237 // wallet::Instrument requires a recipient name for its billing address.
238 if (card && type == NAME_FULL)
239 card->SetRawInfo(CREDIT_CARD_NAME, trimmed);
242 profile->SetInfo(AutofillType(AutofillType(type).GetStorableType()),
244 g_browser_process->GetApplicationLocale());
250 // Returns the containing window for the given |web_contents|. The containing
251 // window might be a browser window for a Chrome tab, or it might be an app
252 // window for a platform app.
253 ui::BaseWindow* GetBaseWindowForWebContents(
254 content::WebContents* web_contents) {
255 Browser* browser = chrome::FindBrowserWithWebContents(web_contents);
257 return browser->window();
259 gfx::NativeWindow native_window = web_contents->GetTopLevelNativeWindow();
260 extensions::AppWindow* app_window =
261 AppWindowRegistryUtil::GetAppWindowForNativeWindowAnyProfile(
263 return app_window->GetBaseWindow();
266 // Returns a string descriptor for a DialogSection, for use with prefs (do not
267 // change these values).
268 std::string SectionToPrefString(DialogSection section) {
273 case SECTION_BILLING:
276 case SECTION_CC_BILLING:
277 // The SECTION_CC_BILLING section isn't active when using Autofill.
279 return std::string();
281 case SECTION_SHIPPING:
286 return std::string();
289 // Check if a given MaskedInstrument is allowed for the purchase.
290 bool IsInstrumentAllowed(
291 const wallet::WalletItems::MaskedInstrument& instrument) {
292 switch (instrument.status()) {
293 case wallet::WalletItems::MaskedInstrument::VALID:
294 case wallet::WalletItems::MaskedInstrument::PENDING:
295 case wallet::WalletItems::MaskedInstrument::EXPIRED:
296 case wallet::WalletItems::MaskedInstrument::BILLING_INCOMPLETE:
303 // Loops through |addresses_| comparing to |address| ignoring ID. If a match
304 // is not found, NULL is returned.
305 const wallet::Address* FindDuplicateAddress(
306 const std::vector<wallet::Address*>& addresses,
307 const wallet::Address& address) {
308 for (size_t i = 0; i < addresses.size(); ++i) {
309 if (addresses[i]->EqualsIgnoreID(address))
315 bool IsCardHolderNameValidForWallet(const base::string16& name) {
316 base::string16 whitespace_collapsed_name =
317 base::CollapseWhitespace(name, true);
318 std::vector<base::string16> split_name;
319 base::SplitString(whitespace_collapsed_name, ' ', &split_name);
320 return split_name.size() >= 2;
323 DialogSection SectionFromLocation(wallet::FormFieldError::Location location) {
325 case wallet::FormFieldError::PAYMENT_INSTRUMENT:
326 case wallet::FormFieldError::LEGAL_ADDRESS:
327 return SECTION_CC_BILLING;
329 case wallet::FormFieldError::SHIPPING_ADDRESS:
330 return SECTION_SHIPPING;
332 case wallet::FormFieldError::UNKNOWN_LOCATION:
341 scoped_ptr<DialogNotification> GetWalletError(
342 wallet::WalletClient::ErrorType error_type) {
346 switch (error_type) {
347 case wallet::WalletClient::UNVERIFIED_KNOW_YOUR_CUSTOMER_STATUS:
348 text = l10n_util::GetStringUTF16(
349 IDS_AUTOFILL_WALLET_UNVERIFIED_KNOW_YOUR_CUSTOMER_STATUS);
350 url = GURL(kKnowYourCustomerStatusUrl);
353 case wallet::WalletClient::BUYER_LEGAL_ADDRESS_NOT_SUPPORTED:
354 text = l10n_util::GetStringUTF16(
355 IDS_AUTOFILL_WALLET_BUYER_COUNTRY_NOT_SUPPORTED);
356 url = GURL(kBuyerLegalAddressStatusUrl);
360 // The notification will not have a link; it's handled in the next
366 scoped_ptr<DialogNotification> notification(new DialogNotification(
367 DialogNotification::WALLET_ERROR,
369 notification->set_link_url(url);
370 return notification.Pass();
376 switch (error_type) {
377 case wallet::WalletClient::UNSUPPORTED_MERCHANT:
378 error_ids = IDS_AUTOFILL_WALLET_UNSUPPORTED_MERCHANT;
381 case wallet::WalletClient::BAD_REQUEST:
382 error_ids = IDS_AUTOFILL_WALLET_UPGRADE_CHROME_ERROR;
386 case wallet::WalletClient::INVALID_PARAMS:
387 error_ids = IDS_AUTOFILL_WALLET_BAD_TRANSACTION_AMOUNT;
391 case wallet::WalletClient::BUYER_ACCOUNT_ERROR:
392 error_ids = IDS_AUTOFILL_WALLET_BUYER_ACCOUNT_ERROR;
396 case wallet::WalletClient::UNSUPPORTED_API_VERSION:
397 error_ids = IDS_AUTOFILL_WALLET_UPGRADE_CHROME_ERROR;
401 case wallet::WalletClient::SERVICE_UNAVAILABLE:
402 error_ids = IDS_AUTOFILL_WALLET_SERVICE_UNAVAILABLE_ERROR;
406 case wallet::WalletClient::INTERNAL_ERROR:
407 error_ids = IDS_AUTOFILL_WALLET_UPGRADE_CHROME_ERROR;
411 case wallet::WalletClient::MALFORMED_RESPONSE:
412 error_ids = IDS_AUTOFILL_WALLET_UNKNOWN_ERROR;
416 case wallet::WalletClient::NETWORK_ERROR:
417 error_ids = IDS_AUTOFILL_WALLET_UNKNOWN_ERROR;
421 case wallet::WalletClient::UNKNOWN_ERROR:
422 error_ids = IDS_AUTOFILL_WALLET_UNKNOWN_ERROR;
426 case wallet::WalletClient::UNSUPPORTED_USER_AGENT_OR_API_KEY:
427 error_ids = IDS_AUTOFILL_WALLET_UNSUPPORTED_AGENT_OR_API_KEY;
431 case wallet::WalletClient::SPENDING_LIMIT_EXCEEDED:
432 error_ids = IDS_AUTOFILL_WALLET_BAD_TRANSACTION_AMOUNT;
435 // Handled in the prior switch().
436 case wallet::WalletClient::UNVERIFIED_KNOW_YOUR_CUSTOMER_STATUS:
437 case wallet::WalletClient::BUYER_LEGAL_ADDRESS_NOT_SUPPORTED:
442 DCHECK_NE(0, error_ids);
444 // The other error types are strings of the form "XXX. You can pay without
446 scoped_ptr<DialogNotification> notification(new DialogNotification(
447 DialogNotification::WALLET_ERROR,
448 l10n_util::GetStringFUTF16(IDS_AUTOFILL_DIALOG_COMPLETE_WITHOUT_WALLET,
449 l10n_util::GetStringUTF16(error_ids))));
452 notification->set_tooltip_text(
453 l10n_util::GetStringFUTF16(IDS_AUTOFILL_WALLET_ERROR_CODE_TOOLTIP,
454 base::IntToString16(error_code)));
457 return notification.Pass();
460 // Returns the ID of the address or instrument that should be selected in the
461 // UI, given that the |default_id| is currently the default ID on the Wallet
462 // server, |previous_default_id| was the default ID prior to re-fetching the
463 // Wallet data, and |previously_selected_id| was the ID of the item selected in
464 // the dialog prior to re-fetching the Wallet data.
465 std::string GetIdToSelect(const std::string& default_id,
466 const std::string& previous_default_id,
467 const std::string& previously_selected_id) {
468 // If the default ID changed since the last fetch of the Wallet data, select
469 // it rather than the previously selected item, as the user's intention in
470 // changing the default was probably to use it.
471 if (default_id != previous_default_id)
474 // Otherwise, prefer the previously selected item, if there was one.
475 return !previously_selected_id.empty() ? previously_selected_id : default_id;
478 // Generate a random card number in a user displayable format.
479 base::string16 GenerateRandomCardNumber() {
480 std::string card_number;
481 for (size_t i = 0; i < 4; ++i) {
482 int part = base::RandInt(0, 10000);
483 base::StringAppendF(&card_number, "%04d ", part);
485 return base::ASCIIToUTF16(card_number);
488 gfx::Image CreditCardIconForType(const std::string& credit_card_type) {
489 const int input_card_idr = CreditCard::IconResourceId(credit_card_type);
490 ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance();
491 gfx::Image result = rb.GetImageNamed(input_card_idr);
492 if (input_card_idr == IDR_AUTOFILL_CC_GENERIC) {
493 // When the credit card type is unknown, no image should be shown. However,
494 // to simplify the view code on Mac, save space for the credit card image by
495 // returning a transparent image of the appropriate size. Not all credit
496 // card images are the same size, but none is larger than the Visa icon.
497 result = gfx::Image(gfx::ImageSkiaOperations::CreateTransparentImage(
498 rb.GetImageNamed(IDR_AUTOFILL_CC_VISA).AsImageSkia(), 0));
503 gfx::Image CvcIconForCreditCardType(const base::string16& credit_card_type) {
504 ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance();
505 if (credit_card_type == l10n_util::GetStringUTF16(IDS_AUTOFILL_CC_AMEX))
506 return rb.GetImageNamed(IDR_CREDIT_CARD_CVC_HINT_AMEX);
508 return rb.GetImageNamed(IDR_CREDIT_CARD_CVC_HINT);
511 ServerFieldType CountryTypeForSection(DialogSection section) {
512 return section == SECTION_SHIPPING ? ADDRESS_HOME_COUNTRY :
513 ADDRESS_BILLING_COUNTRY;
516 // Attempts to canonicalize the administrative area name in |profile| using the
517 // rules in |validator|.
518 void CanonicalizeState(const AddressValidator* validator,
519 AutofillProfile* profile) {
520 base::string16 administrative_area;
521 scoped_ptr<AddressData> address_data =
522 i18n::CreateAddressDataFromAutofillProfile(
523 *profile, g_browser_process->GetApplicationLocale());
525 validator->CanonicalizeAdministrativeArea(address_data.get());
526 administrative_area = base::UTF8ToUTF16(address_data->administrative_area);
528 profile->SetInfo(AutofillType(ADDRESS_HOME_STATE),
530 g_browser_process->GetApplicationLocale());
533 ValidityMessage GetPhoneValidityMessage(const base::string16& country_name,
534 const base::string16& number) {
535 std::string region = AutofillCountry::GetCountryCode(
537 g_browser_process->GetApplicationLocale());
538 i18n::PhoneObject phone_object(number, region);
539 ValidityMessage phone_message(base::string16(), true);
541 // Check if the phone number is invalid. Allow valid international
542 // numbers that don't match the address's country only if they have an
543 // international calling code.
544 if (!phone_object.IsValidNumber() ||
545 (phone_object.country_code().empty() &&
546 phone_object.region() != region)) {
547 phone_message.text = l10n_util::GetStringUTF16(
548 IDS_AUTOFILL_DIALOG_VALIDATION_INVALID_PHONE_NUMBER);
551 return phone_message;
554 // Constructs |inputs| from template data for a given |dialog_section|.
555 // |country_country| specifies the country code that the inputs should be built
556 // for. Sets the |language_code| to be used for address formatting, if
557 // internationalized address input is enabled. The |language_code| parameter can
559 void BuildInputsForSection(DialogSection dialog_section,
560 const std::string& country_code,
561 DetailInputs* inputs,
562 std::string* language_code) {
563 using l10n_util::GetStringUTF16;
565 const DetailInput kCCInputs[] = {
568 GetStringUTF16(IDS_AUTOFILL_DIALOG_PLACEHOLDER_CARD_NUMBER) },
569 { DetailInput::SHORT,
570 CREDIT_CARD_EXP_MONTH,
571 GetStringUTF16(IDS_AUTOFILL_DIALOG_PLACEHOLDER_EXPIRY_MONTH) },
572 { DetailInput::SHORT,
573 CREDIT_CARD_EXP_4_DIGIT_YEAR,
574 GetStringUTF16(IDS_AUTOFILL_DIALOG_PLACEHOLDER_EXPIRY_YEAR) },
575 { DetailInput::SHORT_EOL,
576 CREDIT_CARD_VERIFICATION_CODE,
577 GetStringUTF16(IDS_AUTOFILL_DIALOG_PLACEHOLDER_CVC),
581 const DetailInput kBillingPhoneInputs[] = {
583 PHONE_BILLING_WHOLE_NUMBER,
584 GetStringUTF16(IDS_AUTOFILL_DIALOG_PLACEHOLDER_PHONE_NUMBER) },
587 const DetailInput kEmailInputs[] = {
590 GetStringUTF16(IDS_AUTOFILL_DIALOG_PLACEHOLDER_EMAIL) },
593 const DetailInput kShippingPhoneInputs[] = {
595 PHONE_HOME_WHOLE_NUMBER,
596 GetStringUTF16(IDS_AUTOFILL_DIALOG_PLACEHOLDER_PHONE_NUMBER) },
599 switch (dialog_section) {
601 common::BuildInputs(kCCInputs, arraysize(kCCInputs), inputs);
605 case SECTION_BILLING: {
606 i18ninput::BuildAddressInputs(common::ADDRESS_TYPE_BILLING,
607 country_code, inputs, language_code);
608 common::BuildInputs(kBillingPhoneInputs, arraysize(kBillingPhoneInputs),
610 common::BuildInputs(kEmailInputs, arraysize(kEmailInputs), inputs);
614 case SECTION_CC_BILLING: {
615 common::BuildInputs(kCCInputs, arraysize(kCCInputs), inputs);
617 // Wallet only supports US billing addresses.
618 const std::string hardcoded_country_code = "US";
619 i18ninput::BuildAddressInputs(common::ADDRESS_TYPE_BILLING,
620 hardcoded_country_code,
623 DCHECK_EQ(inputs->back().type, ADDRESS_BILLING_COUNTRY);
624 inputs->back().length = DetailInput::NONE;
625 const std::string& app_locale =
626 g_browser_process->GetApplicationLocale();
627 inputs->back().initial_value =
628 AutofillCountry(hardcoded_country_code, app_locale).name();
630 common::BuildInputs(kBillingPhoneInputs, arraysize(kBillingPhoneInputs),
635 case SECTION_SHIPPING: {
636 i18ninput::BuildAddressInputs(common::ADDRESS_TYPE_SHIPPING,
637 country_code, inputs, language_code);
638 common::BuildInputs(kShippingPhoneInputs, arraysize(kShippingPhoneInputs),
647 AutofillDialogViewDelegate::~AutofillDialogViewDelegate() {}
649 AutofillDialogControllerImpl::~AutofillDialogControllerImpl() {
650 if (popup_controller_)
651 popup_controller_->Hide();
653 GetMetricLogger().LogDialogInitialUserState(initial_user_state_);
656 // Checks the country code against the values the form structure enumerates.
657 bool AutofillCountryFilter(
658 const std::set<base::string16>& form_structure_values,
659 const std::string& country_code) {
660 if (!form_structure_values.empty() &&
661 !form_structure_values.count(base::ASCIIToUTF16(country_code))) {
668 // Checks the country code against the values the form structure enumerates and
669 // against the ones Wallet allows.
670 bool WalletCountryFilter(
671 const std::set<base::string16>& form_structure_values,
672 const std::set<std::string>& wallet_allowed_values,
673 const std::string& country_code) {
674 if ((!form_structure_values.empty() &&
675 !form_structure_values.count(base::ASCIIToUTF16(country_code))) ||
676 (!wallet_allowed_values.empty() &&
677 !wallet_allowed_values.count(country_code))) {
685 base::WeakPtr<AutofillDialogControllerImpl>
686 AutofillDialogControllerImpl::Create(
687 content::WebContents* contents,
688 const FormData& form_structure,
689 const GURL& source_url,
690 const AutofillClient::ResultCallback& callback) {
691 // AutofillDialogControllerImpl owns itself.
692 AutofillDialogControllerImpl* autofill_dialog_controller =
693 new AutofillDialogControllerImpl(contents,
697 return autofill_dialog_controller->weak_ptr_factory_.GetWeakPtr();
701 void AutofillDialogController::RegisterPrefs(PrefRegistrySimple* registry) {
702 registry->RegisterListPref(::prefs::kAutofillDialogWalletLocationAcceptance);
706 void AutofillDialogController::RegisterProfilePrefs(
707 user_prefs::PrefRegistrySyncable* registry) {
708 registry->RegisterBooleanPref(
709 ::prefs::kAutofillDialogPayWithoutWallet,
711 user_prefs::PrefRegistrySyncable::SYNCABLE_PREF);
712 registry->RegisterDictionaryPref(
713 ::prefs::kAutofillDialogAutofillDefault,
714 user_prefs::PrefRegistrySyncable::SYNCABLE_PREF);
715 registry->RegisterBooleanPref(
716 ::prefs::kAutofillDialogSaveData,
718 user_prefs::PrefRegistrySyncable::SYNCABLE_PREF);
719 registry->RegisterBooleanPref(
720 ::prefs::kAutofillDialogWalletShippingSameAsBilling,
722 user_prefs::PrefRegistrySyncable::SYNCABLE_PREF);
726 base::WeakPtr<AutofillDialogController> AutofillDialogController::Create(
727 content::WebContents* contents,
728 const FormData& form_structure,
729 const GURL& source_url,
730 const AutofillClient::ResultCallback& callback) {
731 return AutofillDialogControllerImpl::Create(contents,
737 void AutofillDialogControllerImpl::Show() {
738 dialog_shown_timestamp_ = base::Time::Now();
740 // Determine what field types should be included in the dialog.
741 bool has_types = false;
742 bool has_sections = false;
743 form_structure_.ParseFieldTypesFromAutocompleteAttributes(
744 &has_types, &has_sections);
746 // Fail if the author didn't specify autocomplete types.
749 AutofillClient::AutocompleteResultErrorDisabled,
750 base::ASCIIToUTF16("Form is missing autocomplete attributes."),
756 // Fail if the author didn't ask for at least some kind of credit card
758 bool has_credit_card_field = false;
759 for (size_t i = 0; i < form_structure_.field_count(); ++i) {
760 AutofillType type = form_structure_.field(i)->Type();
761 if (type.html_type() != HTML_TYPE_UNKNOWN && type.group() == CREDIT_CARD) {
762 has_credit_card_field = true;
767 if (!has_credit_card_field) {
768 callback_.Run(AutofillClient::AutocompleteResultErrorDisabled,
770 "Form is not a payment form (must contain "
771 "some autocomplete=\"cc-*\" fields). "),
777 billing_country_combobox_model_.reset(new CountryComboboxModel());
778 billing_country_combobox_model_->SetCountries(
780 base::Bind(AutofillCountryFilter,
781 form_structure_.PossibleValues(ADDRESS_BILLING_COUNTRY)));
782 shipping_country_combobox_model_.reset(new CountryComboboxModel());
783 acceptable_shipping_countries_ =
784 form_structure_.PossibleValues(ADDRESS_HOME_COUNTRY);
785 shipping_country_combobox_model_->SetCountries(
787 base::Bind(AutofillCountryFilter,
788 base::ConstRef(acceptable_shipping_countries_)));
790 // If the form has a country <select> but none of the options are valid, bail.
791 if (billing_country_combobox_model_->GetItemCount() == 0 ||
792 shipping_country_combobox_model_->GetItemCount() == 0) {
793 callback_.Run(AutofillClient::AutocompleteResultErrorDisabled,
794 base::ASCIIToUTF16("No valid/supported country options"
801 // Log any relevant UI metrics and security exceptions.
802 GetMetricLogger().LogDialogUiEvent(AutofillMetrics::DIALOG_UI_SHOWN);
804 GetMetricLogger().LogDialogSecurityMetric(
805 AutofillMetrics::SECURITY_METRIC_DIALOG_SHOWN);
807 // The Autofill dialog is shown in response to a message from the renderer and
808 // as such, it can only be made in the context of the current document. A call
809 // to GetActiveEntry would return a pending entry, if there was one, which
810 // would be a security bug. Therefore, we use the last committed URL for the
812 const GURL& current_url = web_contents()->GetLastCommittedURL();
813 invoked_from_same_origin_ =
814 current_url.GetOrigin() == source_url_.GetOrigin();
816 if (!invoked_from_same_origin_) {
817 GetMetricLogger().LogDialogSecurityMetric(
818 AutofillMetrics::SECURITY_METRIC_CROSS_ORIGIN_FRAME);
821 for (size_t i = SECTION_MIN; i <= SECTION_MAX; ++i) {
822 DialogSection section = static_cast<DialogSection>(i);
824 std::string country_code;
825 CountryComboboxModel* model = CountryComboboxModelForSection(section);
827 country_code = model->GetDefaultCountryCode();
829 DetailInputs* inputs = MutableRequestedFieldsForSection(section);
830 BuildInputsForSection(
831 section, country_code, inputs,
832 MutableAddressLanguageCodeForSection(section));
835 // Test whether we need to show the shipping section. If filling that section
836 // would be a no-op, don't show it.
837 cares_about_shipping_ = form_structure_.FillFields(
838 RequestedTypesForSection(SECTION_SHIPPING),
839 base::Bind(common::ServerTypeMatchesField, SECTION_SHIPPING),
840 base::Bind(NullGetInfo),
842 g_browser_process->GetApplicationLocale());
844 transaction_amount_ = form_structure_.GetUniqueValue(
845 HTML_TYPE_TRANSACTION_AMOUNT);
846 transaction_currency_ = form_structure_.GetUniqueValue(
847 HTML_TYPE_TRANSACTION_CURRENCY);
849 account_chooser_model_.reset(
850 new AccountChooserModel(this,
852 !ShouldShowAccountChooser(),
855 acceptable_cc_types_ = form_structure_.PossibleValues(CREDIT_CARD_TYPE);
856 // Wallet generates MC virtual cards, so we have to disable it if MC is not
858 if (ShouldDisallowCcType(CreditCard::TypeForDisplay(kMasterCard)))
859 DisableWallet(wallet::WalletClient::UNSUPPORTED_MERCHANT);
861 if (account_chooser_model_->WalletIsSelected())
864 validator_.reset(new AddressValidator(
865 scoped_ptr< ::i18n::addressinput::Source>(
866 new autofill::ChromeMetadataSource(I18N_ADDRESS_VALIDATION_DATA_URL,
867 profile_->GetRequestContext())),
868 ValidationRulesStorageFactory::CreateStorage(),
871 SuggestionsUpdated();
872 SubmitButtonDelayBegin();
873 view_.reset(CreateView());
875 GetManager()->AddObserver(this);
877 if (!account_chooser_model_->WalletIsSelected())
878 LogDialogLatencyToShow();
881 void AutofillDialogControllerImpl::Hide() {
886 void AutofillDialogControllerImpl::TabActivated() {
887 // If the user switched away from this tab and then switched back, reload the
888 // Wallet items, in case they've changed.
889 int64 seconds_elapsed_since_last_refresh =
890 (base::TimeTicks::Now() - last_wallet_items_fetch_timestamp_).InSeconds();
891 if (IsPayingWithWallet() && wallet_items_ &&
892 seconds_elapsed_since_last_refresh >= kWalletItemsRefreshRateSeconds) {
897 ////////////////////////////////////////////////////////////////////////////////
898 // AutofillDialogViewDelegate implementation.
900 base::string16 AutofillDialogControllerImpl::DialogTitle() const {
901 if (ShouldShowSpinner())
902 return base::string16();
904 return l10n_util::GetStringUTF16(IDS_AUTOFILL_DIALOG_TITLE);
907 base::string16 AutofillDialogControllerImpl::AccountChooserText() const {
908 if (!account_chooser_model_->WalletIsSelected())
909 return l10n_util::GetStringUTF16(IDS_AUTOFILL_DIALOG_PAYING_WITHOUT_WALLET);
911 if (SignedInState() == SIGNED_IN)
912 return account_chooser_model_->GetActiveWalletAccountName();
914 // In this case, the account chooser should be showing the signin link.
915 return base::string16();
918 base::string16 AutofillDialogControllerImpl::SignInLinkText() const {
919 int ids = SignedInState() == NOT_CHECKED ?
920 IDS_AUTOFILL_DIALOG_USE_WALLET_LINK :
921 ShouldShowSignInWebView() ? IDS_AUTOFILL_DIALOG_CANCEL_SIGN_IN :
922 IDS_AUTOFILL_DIALOG_SIGN_IN;
924 return l10n_util::GetStringUTF16(ids);
927 base::string16 AutofillDialogControllerImpl::SpinnerText() const {
928 return l10n_util::GetStringUTF16(IDS_AUTOFILL_DIALOG_LOADING);
931 base::string16 AutofillDialogControllerImpl::EditSuggestionText() const {
932 return l10n_util::GetStringUTF16(IDS_AUTOFILL_DIALOG_EDIT);
935 base::string16 AutofillDialogControllerImpl::CancelButtonText() const {
936 return l10n_util::GetStringUTF16(IDS_CANCEL);
939 base::string16 AutofillDialogControllerImpl::ConfirmButtonText() const {
940 return l10n_util::GetStringUTF16(IsSubmitPausedOn(wallet::VERIFY_CVV) ?
941 IDS_AUTOFILL_DIALOG_VERIFY_BUTTON : IDS_AUTOFILL_DIALOG_SUBMIT_BUTTON);
944 base::string16 AutofillDialogControllerImpl::SaveLocallyText() const {
945 return l10n_util::GetStringUTF16(IDS_AUTOFILL_DIALOG_SAVE_LOCALLY_CHECKBOX);
948 base::string16 AutofillDialogControllerImpl::SaveLocallyTooltip() const {
949 return l10n_util::GetStringUTF16(IDS_AUTOFILL_DIALOG_SAVE_LOCALLY_TOOLTIP);
952 base::string16 AutofillDialogControllerImpl::LegalDocumentsText() {
953 if (!IsPayingWithWallet() || ShouldShowSignInWebView())
954 return base::string16();
956 return legal_documents_text_;
959 bool AutofillDialogControllerImpl::ShouldShowSpinner() const {
960 return SignedInState() == REQUIRES_RESPONSE ||
961 SignedInState() == REQUIRES_PASSIVE_SIGN_IN;
964 bool AutofillDialogControllerImpl::ShouldShowAccountChooser() const {
965 return !ShouldShowSpinner() && GetManager()->IsCountryOfInterest("US");
968 bool AutofillDialogControllerImpl::ShouldShowSignInWebView() const {
969 return !signin_registrar_.IsEmpty();
972 bool AutofillDialogControllerImpl::ShouldOfferToSaveInChrome() const {
973 return IsAutofillEnabled() &&
974 !IsPayingWithWallet() &&
975 !profile_->IsOffTheRecord() &&
976 IsManuallyEditingAnySection() &&
977 !ShouldShowSpinner();
980 bool AutofillDialogControllerImpl::ShouldSaveInChrome() const {
981 return profile_->GetPrefs()->GetBoolean(::prefs::kAutofillDialogSaveData);
984 int AutofillDialogControllerImpl::GetDialogButtons() const {
985 if (waiting_for_explicit_sign_in_response_)
986 return ui::DIALOG_BUTTON_NONE;
988 if (ShouldShowSpinner() && !handling_use_wallet_link_click_)
989 return ui::DIALOG_BUTTON_CANCEL;
991 return ui::DIALOG_BUTTON_OK | ui::DIALOG_BUTTON_CANCEL;
994 bool AutofillDialogControllerImpl::IsDialogButtonEnabled(
995 ui::DialogButton button) const {
996 if (button == ui::DIALOG_BUTTON_OK) {
997 if (IsSubmitPausedOn(wallet::VERIFY_CVV))
1000 if (ShouldShowSpinner() || is_submitting_)
1003 if (submit_button_delay_timer_.IsRunning())
1009 DCHECK_EQ(ui::DIALOG_BUTTON_CANCEL, button);
1010 return !is_submitting_ || IsSubmitPausedOn(wallet::VERIFY_CVV);
1013 DialogOverlayState AutofillDialogControllerImpl::GetDialogOverlay() {
1014 bool show_wallet_interstitial = IsPayingWithWallet() && is_submitting_ &&
1015 !(full_wallet_ && !full_wallet_->required_actions().empty());
1016 if (!show_wallet_interstitial) {
1017 card_scrambling_delay_.Stop();
1018 card_scrambling_refresher_.Stop();
1019 return DialogOverlayState();
1022 ui::ResourceBundle* rb = &ui::ResourceBundle::GetSharedInstance();
1023 DialogOverlayState state;
1024 state.string.font_list = rb->GetFontList(ui::ResourceBundle::MediumFont);
1026 const SkColor start_top_color = SkColorSetRGB(0xD6, 0xD6, 0xD6);
1027 const SkColor start_bottom_color = SkColorSetRGB(0x98, 0x98, 0x98);
1028 const SkColor final_top_color = SkColorSetRGB(0x52, 0x9F, 0xF8);
1029 const SkColor final_bottom_color = SkColorSetRGB(0x22, 0x75, 0xE5);
1031 if (full_wallet_ && full_wallet_->required_actions().empty()) {
1032 card_scrambling_delay_.Stop();
1033 card_scrambling_refresher_.Stop();
1035 base::string16 cc_number = base::ASCIIToUTF16(full_wallet_->GetPan());
1036 DCHECK_GE(cc_number.size(), 4U);
1037 state.image = GetGeneratedCardImage(
1038 base::ASCIIToUTF16("XXXX XXXX XXXX ") +
1039 cc_number.substr(cc_number.size() - 4),
1040 full_wallet_->billing_address()->recipient_name(),
1041 color_utils::AlphaBlend(
1044 255 * card_generated_animation_.GetCurrentValue()),
1045 color_utils::AlphaBlend(
1048 255 * card_generated_animation_.GetCurrentValue()));
1050 state.string.text = l10n_util::GetStringUTF16(
1051 IDS_AUTOFILL_DIALOG_CARD_GENERATION_DONE);
1053 // Start the refresher if it isn't running. Wait one second before pumping
1054 // updates to the view.
1055 if (!card_scrambling_delay_.IsRunning() &&
1056 !card_scrambling_refresher_.IsRunning()) {
1057 scrambled_card_number_ = GenerateRandomCardNumber();
1058 card_scrambling_delay_.Start(
1060 base::TimeDelta::FromSeconds(1),
1062 &AutofillDialogControllerImpl::StartCardScramblingRefresher);
1065 DCHECK(!scrambled_card_number_.empty());
1066 state.image = GetGeneratedCardImage(
1067 scrambled_card_number_,
1068 submitted_cardholder_name_,
1070 start_bottom_color);
1072 // "Submitting" waiting page.
1073 state.string.text = l10n_util::GetStringUTF16(
1074 IDS_AUTOFILL_DIALOG_CARD_GENERATION_IN_PROGRESS);
1080 const std::vector<gfx::Range>& AutofillDialogControllerImpl::
1081 LegalDocumentLinks() {
1082 return legal_document_link_ranges_;
1085 bool AutofillDialogControllerImpl::SectionIsActive(DialogSection section)
1087 if (IsSubmitPausedOn(wallet::VERIFY_CVV))
1088 return section == SECTION_CC_BILLING;
1090 if (!FormStructureCaresAboutSection(section))
1093 if (IsPayingWithWallet())
1094 return section == SECTION_CC_BILLING || section == SECTION_SHIPPING;
1096 return section != SECTION_CC_BILLING;
1099 void AutofillDialogControllerImpl::GetWalletItems() {
1100 ScopedViewUpdates updates(view_.get());
1102 wallet_items_requested_ = true;
1103 wallet::WalletClient* wallet_client = GetWalletClient();
1104 wallet_client->CancelRequest();
1106 previously_selected_instrument_id_.clear();
1107 previously_selected_shipping_address_id_.clear();
1108 if (wallet_items_) {
1109 previous_default_instrument_id_ = wallet_items_->default_instrument_id();
1110 previous_default_shipping_address_id_ = wallet_items_->default_address_id();
1112 const wallet::WalletItems::MaskedInstrument* instrument =
1115 previously_selected_instrument_id_ = instrument->object_id();
1117 const wallet::Address* address = ActiveShippingAddress();
1119 previously_selected_shipping_address_id_ = address->object_id();
1122 last_wallet_items_fetch_timestamp_ = base::TimeTicks::Now();
1123 passive_failed_ = false;
1124 wallet_items_.reset();
1126 // The "Loading..." page should be showing now, which should cause the
1127 // account chooser to hide.
1128 view_->UpdateAccountChooser();
1129 wallet_client->GetWalletItems(transaction_amount_, transaction_currency_);
1132 void AutofillDialogControllerImpl::HideSignIn() {
1133 ScopedViewUpdates updates(view_.get());
1134 signin_registrar_.RemoveAll();
1135 view_->HideSignIn();
1136 view_->UpdateAccountChooser();
1139 AutofillDialogControllerImpl::DialogSignedInState
1140 AutofillDialogControllerImpl::SignedInState() const {
1141 if (wallet_error_notification_)
1142 return SIGN_IN_DISABLED;
1144 if (signin_helper_ || (wallet_items_requested_ && !wallet_items_))
1145 return REQUIRES_RESPONSE;
1147 if (!wallet_items_requested_)
1150 if (wallet_items_->HasRequiredAction(wallet::GAIA_AUTH) ||
1152 return REQUIRES_SIGN_IN;
1155 if (wallet_items_->HasRequiredAction(wallet::PASSIVE_GAIA_AUTH))
1156 return REQUIRES_PASSIVE_SIGN_IN;
1161 void AutofillDialogControllerImpl::SignedInStateUpdated() {
1162 if (!ShouldShowSpinner())
1163 waiting_for_explicit_sign_in_response_ = false;
1165 switch (SignedInState()) {
1167 LogDialogLatencyToShow();
1170 case REQUIRES_SIGN_IN:
1171 if (handling_use_wallet_link_click_)
1172 ShowSignIn(wallet::GetSignInUrl(GetWalletClient()->user_index()));
1174 case SIGN_IN_DISABLED:
1175 // Switch to the local account and refresh the dialog.
1176 signin_helper_.reset();
1177 OnWalletSigninError();
1178 handling_use_wallet_link_click_ = false;
1181 case REQUIRES_PASSIVE_SIGN_IN:
1182 // Attempt to passively sign in the user.
1183 DCHECK(!signin_helper_);
1184 signin_helper_.reset(new wallet::WalletSigninHelper(
1186 profile_->GetRequestContext()));
1187 signin_helper_->StartPassiveSignin(GetWalletClient()->user_index());
1191 case REQUIRES_RESPONSE:
1196 void AutofillDialogControllerImpl::OnWalletOrSigninUpdate() {
1197 ScopedViewUpdates updates(view_.get());
1198 SignedInStateUpdated();
1199 SuggestionsUpdated();
1200 UpdateAccountChooserView();
1203 view_->UpdateButtonStrip();
1204 view_->UpdateOverlay();
1207 // On the first successful response, compute the initial user state metric.
1208 if (initial_user_state_ == AutofillMetrics::DIALOG_USER_STATE_UNKNOWN)
1209 initial_user_state_ = GetInitialUserState();
1212 void AutofillDialogControllerImpl::OnWalletFormFieldError(
1213 const std::vector<wallet::FormFieldError>& form_field_errors) {
1214 if (form_field_errors.empty())
1217 for (std::vector<wallet::FormFieldError>::const_iterator it =
1218 form_field_errors.begin();
1219 it != form_field_errors.end(); ++it) {
1220 if (it->error_type() == wallet::FormFieldError::UNKNOWN_ERROR ||
1221 it->GetAutofillType() == MAX_VALID_FIELD_TYPE ||
1222 it->location() == wallet::FormFieldError::UNKNOWN_LOCATION) {
1223 wallet_server_validation_recoverable_ = false;
1226 DialogSection section = SectionFromLocation(it->location());
1227 wallet_errors_[section][it->GetAutofillType()] =
1228 std::make_pair(it->GetErrorMessage(),
1229 GetValueFromSection(section, it->GetAutofillType()));
1232 // Unrecoverable validation errors.
1233 if (!wallet_server_validation_recoverable_)
1234 DisableWallet(wallet::WalletClient::UNKNOWN_ERROR);
1239 void AutofillDialogControllerImpl::ConstructLegalDocumentsText() {
1240 legal_documents_text_.clear();
1241 legal_document_link_ranges_.clear();
1246 PrefService* local_state = g_browser_process->local_state();
1247 // List of users who have accepted location sharing for fraud protection
1249 const base::ListValue* accepted =
1250 local_state->GetList(::prefs::kAutofillDialogWalletLocationAcceptance);
1251 bool has_accepted_location_sharing =
1252 accepted->Find(base::StringValue(
1253 account_chooser_model_->GetActiveWalletAccountName())) !=
1256 if (wallet_items_->legal_documents().empty()) {
1257 if (!has_accepted_location_sharing) {
1258 legal_documents_text_ = l10n_util::GetStringUTF16(
1259 IDS_AUTOFILL_DIALOG_LOCATION_DISCLOSURE);
1265 const std::vector<wallet::WalletItems::LegalDocument*>& documents =
1266 wallet_items_->legal_documents();
1267 // There should never be just one document because the privacy policy doc gets
1268 // tacked on the end of other documents.
1269 DCHECK_GE(documents.size(), 2U);
1271 std::vector<base::string16> link_names;
1272 for (size_t i = 0; i < documents.size(); ++i) {
1273 link_names.push_back(documents[i]->display_name());
1276 int resource_id = 0;
1277 switch (documents.size()) {
1279 resource_id = IDS_AUTOFILL_DIALOG_LEGAL_LINKS_2;
1282 resource_id = IDS_AUTOFILL_DIALOG_LEGAL_LINKS_3;
1285 resource_id = IDS_AUTOFILL_DIALOG_LEGAL_LINKS_4;
1288 resource_id = IDS_AUTOFILL_DIALOG_LEGAL_LINKS_5;
1291 resource_id = IDS_AUTOFILL_DIALOG_LEGAL_LINKS_6;
1294 // We can only handle so many documents. For lack of a better way of
1295 // handling document overflow, just error out if there are too many.
1296 DisableWallet(wallet::WalletClient::UNKNOWN_ERROR);
1300 std::vector<size_t> offsets;
1301 base::string16 text =
1302 l10n_util::GetStringFUTF16(resource_id, link_names,&offsets);
1304 // Tack on the location string if need be.
1305 size_t base_offset = 0;
1306 if (!has_accepted_location_sharing) {
1307 text = l10n_util::GetStringFUTF16(
1308 IDS_AUTOFILL_DIALOG_LOCATION_DISCLOSURE_WITH_LEGAL_DOCS,
1313 for (size_t i = 0; i < documents.size(); ++i) {
1314 size_t link_start = offsets[i] + base_offset;
1315 legal_document_link_ranges_.push_back(gfx::Range(
1316 link_start, link_start + documents[i]->display_name().size()));
1318 legal_documents_text_ = text;
1321 void AutofillDialogControllerImpl::ResetSectionInput(DialogSection section) {
1322 SetEditingExistingData(section, false);
1323 needs_validation_.erase(section);
1325 CountryComboboxModel* model = CountryComboboxModelForSection(section);
1327 base::string16 country = model->GetItemAt(model->GetDefaultIndex());
1328 RebuildInputsForCountry(section, country, false);
1331 DetailInputs* inputs = MutableRequestedFieldsForSection(section);
1332 for (DetailInputs::iterator it = inputs->begin();
1333 it != inputs->end(); ++it) {
1334 if (it->length != DetailInput::NONE) {
1335 it->initial_value.clear();
1336 } else if (!it->initial_value.empty() &&
1337 (it->type == ADDRESS_BILLING_COUNTRY ||
1338 it->type == ADDRESS_HOME_COUNTRY)) {
1339 GetValidator()->LoadRules(AutofillCountry::GetCountryCode(
1340 it->initial_value, g_browser_process->GetApplicationLocale()));
1345 void AutofillDialogControllerImpl::ShowEditUiIfBadSuggestion(
1346 DialogSection section) {
1347 // |CreateWrapper()| returns an empty wrapper if |IsEditingExistingData()|, so
1348 // get the wrapper before this potentially happens below.
1349 scoped_ptr<DataModelWrapper> wrapper = CreateWrapper(section);
1351 // If the chosen item in |model| yields an empty suggestion text, it is
1352 // invalid. In this case, show the edit UI and highlight invalid fields.
1353 SuggestionsMenuModel* model = SuggestionsMenuModelForSection(section);
1354 base::string16 unused, unused2;
1355 if (IsASuggestionItemKey(model->GetItemKeyForCheckedItem()) &&
1356 !SuggestionTextForSection(section, &unused, &unused2)) {
1357 SetEditingExistingData(section, true);
1360 if (wrapper && IsEditingExistingData(section)) {
1361 base::string16 country =
1362 wrapper->GetInfo(AutofillType(CountryTypeForSection(section)));
1363 if (!country.empty()) {
1364 // There's no user input to restore here as this is only called after
1365 // resetting all section input.
1366 if (RebuildInputsForCountry(section, country, false))
1367 UpdateSection(section);
1369 wrapper->FillInputs(MutableRequestedFieldsForSection(section));
1373 bool AutofillDialogControllerImpl::InputWasEdited(ServerFieldType type,
1374 const base::string16& value) {
1378 // If this is a combobox at the default value, don't preserve it.
1379 ui::ComboboxModel* model = ComboboxModelForAutofillType(type);
1380 if (model && model->GetItemAt(model->GetDefaultIndex()) == value)
1386 FieldValueMap AutofillDialogControllerImpl::TakeUserInputSnapshot() {
1387 FieldValueMap snapshot;
1391 for (size_t i = SECTION_MIN; i <= SECTION_MAX; ++i) {
1392 DialogSection section = static_cast<DialogSection>(i);
1393 SuggestionsMenuModel* model = SuggestionsMenuModelForSection(section);
1394 if (model->GetItemKeyForCheckedItem() != kAddNewItemKey)
1397 FieldValueMap outputs;
1398 view_->GetUserInput(section, &outputs);
1399 // Remove fields that are empty, at their default values, or invalid.
1400 for (FieldValueMap::iterator it = outputs.begin(); it != outputs.end();
1402 if (InputWasEdited(it->first, it->second) &&
1403 InputValidityMessage(section, it->first, it->second).empty()) {
1404 snapshot.insert(std::make_pair(it->first, it->second));
1412 void AutofillDialogControllerImpl::RestoreUserInputFromSnapshot(
1413 const FieldValueMap& snapshot) {
1414 if (snapshot.empty())
1417 for (size_t i = SECTION_MIN; i <= SECTION_MAX; ++i) {
1418 DialogSection section = static_cast<DialogSection>(i);
1419 if (!SectionIsActive(section))
1422 DetailInputs* inputs = MutableRequestedFieldsForSection(section);
1423 for (size_t i = 0; i < inputs->size(); ++i) {
1424 DetailInput* input = &(*inputs)[i];
1425 if (input->length != DetailInput::NONE) {
1426 input->initial_value =
1427 GetInfoFromInputs(snapshot, section, AutofillType(input->type));
1429 if (InputWasEdited(input->type, input->initial_value))
1430 SuggestionsMenuModelForSection(section)->SetCheckedItem(kAddNewItemKey);
1435 void AutofillDialogControllerImpl::UpdateSection(DialogSection section) {
1437 view_->UpdateSection(section);
1440 void AutofillDialogControllerImpl::UpdateForErrors() {
1444 // Currently, the view should only need to be updated if there are
1445 // |wallet_errors_| or validating a suggestion that's based on existing data.
1446 bool should_update = !wallet_errors_.empty();
1447 if (!should_update) {
1448 for (size_t i = SECTION_MIN; i <= SECTION_MAX; ++i) {
1449 if (IsEditingExistingData(static_cast<DialogSection>(i))) {
1450 should_update = true;
1457 view_->UpdateForErrors();
1460 gfx::Image AutofillDialogControllerImpl::GetGeneratedCardImage(
1461 const base::string16& card_number,
1462 const base::string16& name,
1463 const SkColor& gradient_top,
1464 const SkColor& gradient_bottom) {
1465 const int kCardWidthPx = 300;
1466 const int kCardHeightPx = 190;
1467 const gfx::Size size(kCardWidthPx, kCardHeightPx);
1468 float scale_factor = ui::GetScaleFactorForNativeView(
1469 web_contents()->GetNativeView());
1470 gfx::Canvas canvas(size, scale_factor, false);
1472 gfx::Rect display_rect(size);
1474 skia::RefPtr<SkShader> shader = gfx::CreateGradientShader(
1475 0, size.height(), gradient_top, gradient_bottom);
1477 paint.setShader(shader.get());
1478 canvas.DrawRoundRect(display_rect, 8, paint);
1480 display_rect.Inset(20, 0, 0, 0);
1481 gfx::Font font(l10n_util::GetStringUTF8(IDS_FIXED_FONT_FAMILY), 18);
1482 gfx::FontList font_list(font);
1483 gfx::ShadowValues shadows;
1484 shadows.push_back(gfx::ShadowValue(gfx::Point(0, 1), 1.0, SK_ColorBLACK));
1485 canvas.DrawStringRectWithShadows(
1489 display_rect, 0, 0, shadows);
1491 base::string16 capitalized_name = base::i18n::ToUpper(name);
1492 display_rect.Inset(0, size.height() / 2, 0, 0);
1493 canvas.DrawStringRectWithShadows(
1497 display_rect, 0, 0, shadows);
1499 gfx::ImageSkia skia(canvas.ExtractImageRep());
1500 return gfx::Image(skia);
1503 void AutofillDialogControllerImpl::StartCardScramblingRefresher() {
1504 RefreshCardScramblingOverlay();
1505 card_scrambling_refresher_.Start(
1507 base::TimeDelta::FromMilliseconds(75),
1509 &AutofillDialogControllerImpl::RefreshCardScramblingOverlay);
1512 void AutofillDialogControllerImpl::RefreshCardScramblingOverlay() {
1513 scrambled_card_number_ = GenerateRandomCardNumber();
1514 PushOverlayUpdate();
1517 void AutofillDialogControllerImpl::PushOverlayUpdate() {
1519 ScopedViewUpdates updates(view_.get());
1520 view_->UpdateOverlay();
1524 const DetailInputs& AutofillDialogControllerImpl::RequestedFieldsForSection(
1525 DialogSection section) const {
1528 return requested_cc_fields_;
1529 case SECTION_BILLING:
1530 return requested_billing_fields_;
1531 case SECTION_CC_BILLING:
1532 return requested_cc_billing_fields_;
1533 case SECTION_SHIPPING:
1534 return requested_shipping_fields_;
1538 return requested_billing_fields_;
1541 ui::ComboboxModel* AutofillDialogControllerImpl::ComboboxModelForAutofillType(
1542 ServerFieldType type) {
1544 case CREDIT_CARD_EXP_MONTH:
1545 return &cc_exp_month_combobox_model_;
1547 case CREDIT_CARD_EXP_4_DIGIT_YEAR:
1548 return &cc_exp_year_combobox_model_;
1550 case ADDRESS_BILLING_COUNTRY:
1551 return billing_country_combobox_model_.get();
1553 case ADDRESS_HOME_COUNTRY:
1554 return shipping_country_combobox_model_.get();
1561 ui::MenuModel* AutofillDialogControllerImpl::MenuModelForSection(
1562 DialogSection section) {
1563 SuggestionsMenuModel* model = SuggestionsMenuModelForSection(section);
1564 // The shipping section menu is special. It will always show because there is
1565 // a choice between "Use billing" and "enter new".
1566 if (section == SECTION_SHIPPING)
1569 // For other sections, only show a menu if there's at least one suggestion.
1570 for (int i = 0; i < model->GetItemCount(); ++i) {
1571 if (IsASuggestionItemKey(model->GetItemKeyAt(i)))
1578 ui::MenuModel* AutofillDialogControllerImpl::MenuModelForAccountChooser() {
1579 // If there were unrecoverable Wallet errors, or if there are choices other
1580 // than "Pay without the wallet", show the full menu.
1581 // TODO(estade): this can present a braindead menu (only 1 option) when
1582 // there's a wallet error.
1583 if (wallet_error_notification_ ||
1584 (SignedInState() == SIGNED_IN &&
1585 account_chooser_model_->HasAccountsToChoose() &&
1586 !ShouldShowSignInWebView())) {
1587 return account_chooser_model_.get();
1590 // Otherwise, there is no menu, just a sign in link.
1594 gfx::Image AutofillDialogControllerImpl::AccountChooserImage() {
1595 if (!MenuModelForAccountChooser() && !ShouldShowSignInWebView()) {
1596 return ui::ResourceBundle::GetSharedInstance().GetImageNamed(
1600 return gfx::Image();
1603 gfx::Image AutofillDialogControllerImpl::ButtonStripImage() const {
1604 if (IsPayingWithWallet()) {
1605 return ui::ResourceBundle::GetSharedInstance().GetImageNamed(
1609 return gfx::Image();
1612 base::string16 AutofillDialogControllerImpl::LabelForSection(
1613 DialogSection section) const {
1616 return l10n_util::GetStringUTF16(IDS_AUTOFILL_DIALOG_SECTION_CC);
1617 case SECTION_BILLING:
1618 case SECTION_CC_BILLING:
1619 return l10n_util::GetStringUTF16(IDS_AUTOFILL_DIALOG_SECTION_BILLING);
1620 case SECTION_SHIPPING:
1621 return l10n_util::GetStringUTF16(IDS_AUTOFILL_DIALOG_SECTION_SHIPPING);
1624 return base::string16();
1627 SuggestionState AutofillDialogControllerImpl::SuggestionStateForSection(
1628 DialogSection section) {
1629 base::string16 vertically_compact, horizontally_compact;
1630 bool show_suggestion = SuggestionTextForSection(section,
1631 &vertically_compact,
1632 &horizontally_compact);
1633 return SuggestionState(show_suggestion,
1635 horizontally_compact,
1636 SuggestionIconForSection(section),
1637 ExtraSuggestionTextForSection(section),
1638 ExtraSuggestionIconForSection(section));
1641 bool AutofillDialogControllerImpl::SuggestionTextForSection(
1642 DialogSection section,
1643 base::string16* vertically_compact,
1644 base::string16* horizontally_compact) {
1645 base::string16 action_text = RequiredActionTextForSection(section);
1646 if (!action_text.empty()) {
1647 *vertically_compact = *horizontally_compact = action_text;
1651 // When the user has clicked 'edit' or a suggestion is somehow invalid (e.g. a
1652 // user selects a credit card that has expired), don't show a suggestion (even
1653 // though there is a profile selected in the model).
1654 if (IsEditingExistingData(section))
1657 SuggestionsMenuModel* model = SuggestionsMenuModelForSection(section);
1658 std::string item_key = model->GetItemKeyForCheckedItem();
1659 if (item_key == kSameAsBillingKey) {
1660 *vertically_compact = *horizontally_compact = l10n_util::GetStringUTF16(
1661 IDS_AUTOFILL_DIALOG_USING_BILLING_FOR_SHIPPING);
1665 if (!IsASuggestionItemKey(item_key))
1668 if (!IsPayingWithWallet() &&
1669 (section == SECTION_BILLING || section == SECTION_SHIPPING)) {
1670 // Also check if the address is invalid (rules may have loaded since
1671 // the dialog was shown).
1672 if (HasInvalidAddress(*GetManager()->GetProfileByGUID(item_key)))
1676 scoped_ptr<DataModelWrapper> wrapper = CreateWrapper(section);
1677 return wrapper->GetDisplayText(vertically_compact, horizontally_compact);
1680 base::string16 AutofillDialogControllerImpl::RequiredActionTextForSection(
1681 DialogSection section) const {
1682 if (section == SECTION_CC_BILLING && IsSubmitPausedOn(wallet::VERIFY_CVV)) {
1683 const wallet::WalletItems::MaskedInstrument* current_instrument =
1684 wallet_items_->GetInstrumentById(active_instrument_id_);
1685 if (current_instrument)
1686 return current_instrument->TypeAndLastFourDigits();
1688 FieldValueMap output;
1689 view_->GetUserInput(section, &output);
1691 GetBillingInfoFromOutputs(output, &card, NULL, NULL);
1692 return card.TypeAndLastFourDigits();
1695 return base::string16();
1698 base::string16 AutofillDialogControllerImpl::ExtraSuggestionTextForSection(
1699 DialogSection section) const {
1700 if (section == SECTION_CC ||
1701 (section == SECTION_CC_BILLING && IsSubmitPausedOn(wallet::VERIFY_CVV))) {
1702 return l10n_util::GetStringUTF16(IDS_AUTOFILL_DIALOG_PLACEHOLDER_CVC);
1705 return base::string16();
1708 const wallet::WalletItems::MaskedInstrument* AutofillDialogControllerImpl::
1709 ActiveInstrument() const {
1710 if (!IsPayingWithWallet())
1713 const SuggestionsMenuModel* model =
1714 SuggestionsMenuModelForSection(SECTION_CC_BILLING);
1715 const std::string item_key = model->GetItemKeyForCheckedItem();
1716 if (!IsASuggestionItemKey(item_key))
1720 if (!base::StringToInt(item_key, &index) || index < 0 ||
1721 static_cast<size_t>(index) >= wallet_items_->instruments().size()) {
1726 return wallet_items_->instruments()[index];
1729 const wallet::Address* AutofillDialogControllerImpl::
1730 ActiveShippingAddress() const {
1731 if (!IsPayingWithWallet() || !IsShippingAddressRequired())
1734 const SuggestionsMenuModel* model =
1735 SuggestionsMenuModelForSection(SECTION_SHIPPING);
1736 const std::string item_key = model->GetItemKeyForCheckedItem();
1737 if (!IsASuggestionItemKey(item_key))
1741 if (!base::StringToInt(item_key, &index) || index < 0 ||
1742 static_cast<size_t>(index) >= wallet_items_->addresses().size()) {
1747 return wallet_items_->addresses()[index];
1750 scoped_ptr<DataModelWrapper> AutofillDialogControllerImpl::CreateWrapper(
1751 DialogSection section) {
1752 if (IsPayingWithWallet() && full_wallet_ &&
1753 full_wallet_->required_actions().empty()) {
1754 if (section == SECTION_CC_BILLING) {
1755 return scoped_ptr<DataModelWrapper>(
1756 new FullWalletBillingWrapper(full_wallet_.get()));
1758 if (section == SECTION_SHIPPING) {
1759 return scoped_ptr<DataModelWrapper>(
1760 new FullWalletShippingWrapper(full_wallet_.get()));
1764 SuggestionsMenuModel* model = SuggestionsMenuModelForSection(section);
1765 std::string item_key = model->GetItemKeyForCheckedItem();
1766 if (!IsASuggestionItemKey(item_key) || IsManuallyEditingSection(section))
1767 return scoped_ptr<DataModelWrapper>();
1769 if (IsPayingWithWallet()) {
1770 if (section == SECTION_CC_BILLING) {
1771 return scoped_ptr<DataModelWrapper>(
1772 new WalletInstrumentWrapper(ActiveInstrument()));
1775 if (section == SECTION_SHIPPING) {
1776 return scoped_ptr<DataModelWrapper>(
1777 new WalletAddressWrapper(ActiveShippingAddress()));
1780 return scoped_ptr<DataModelWrapper>();
1783 if (section == SECTION_CC) {
1784 CreditCard* card = GetManager()->GetCreditCardByGUID(item_key);
1786 return scoped_ptr<DataModelWrapper>(new AutofillCreditCardWrapper(card));
1789 AutofillProfile* profile = GetManager()->GetProfileByGUID(item_key);
1791 if (section == SECTION_SHIPPING) {
1792 return scoped_ptr<DataModelWrapper>(
1793 new AutofillShippingAddressWrapper(profile));
1795 DCHECK_EQ(SECTION_BILLING, section);
1796 return scoped_ptr<DataModelWrapper>(
1797 new AutofillProfileWrapper(profile));
1800 gfx::Image AutofillDialogControllerImpl::SuggestionIconForSection(
1801 DialogSection section) {
1802 scoped_ptr<DataModelWrapper> model = CreateWrapper(section);
1804 return gfx::Image();
1806 return model->GetIcon();
1809 gfx::Image AutofillDialogControllerImpl::ExtraSuggestionIconForSection(
1810 DialogSection section) {
1811 if (section != SECTION_CC && section != SECTION_CC_BILLING)
1812 return gfx::Image();
1814 scoped_ptr<DataModelWrapper> model = CreateWrapper(section);
1816 return gfx::Image();
1818 return CvcIconForCreditCardType(
1819 model->GetInfo(AutofillType(CREDIT_CARD_TYPE)));
1822 FieldIconMap AutofillDialogControllerImpl::IconsForFields(
1823 const FieldValueMap& user_inputs) const {
1824 FieldIconMap result;
1825 base::string16 credit_card_type;
1827 FieldValueMap::const_iterator credit_card_iter =
1828 user_inputs.find(CREDIT_CARD_NUMBER);
1829 if (credit_card_iter != user_inputs.end()) {
1830 const base::string16& number = credit_card_iter->second;
1831 const std::string type = CreditCard::GetCreditCardType(number);
1832 credit_card_type = CreditCard::TypeForDisplay(type);
1833 result[CREDIT_CARD_NUMBER] = CreditCardIconForType(type);
1836 if (!user_inputs.count(CREDIT_CARD_VERIFICATION_CODE))
1839 result[CREDIT_CARD_VERIFICATION_CODE] =
1840 CvcIconForCreditCardType(credit_card_type);
1845 bool AutofillDialogControllerImpl::FieldControlsIcons(
1846 ServerFieldType type) const {
1847 return type == CREDIT_CARD_NUMBER;
1850 base::string16 AutofillDialogControllerImpl::TooltipForField(
1851 ServerFieldType type) const {
1852 if (type == PHONE_HOME_WHOLE_NUMBER || type == PHONE_BILLING_WHOLE_NUMBER)
1853 return l10n_util::GetStringUTF16(IDS_AUTOFILL_DIALOG_TOOLTIP_PHONE_NUMBER);
1855 return base::string16();
1858 bool AutofillDialogControllerImpl::InputIsEditable(
1859 const DetailInput& input,
1860 DialogSection section) {
1861 if (section != SECTION_CC_BILLING || !IsPayingWithWallet())
1864 if (input.type == CREDIT_CARD_NUMBER)
1865 return !IsEditingExistingData(section);
1867 // For CVC, only require (allow) input if the user has edited some other
1868 // aspect of the card.
1869 if (input.type == CREDIT_CARD_VERIFICATION_CODE &&
1870 IsEditingExistingData(section)) {
1871 FieldValueMap output;
1872 view_->GetUserInput(section, &output);
1873 WalletInstrumentWrapper wrapper(ActiveInstrument());
1875 for (FieldValueMap::iterator iter = output.begin(); iter != output.end();
1877 if (iter->first == input.type)
1880 AutofillType type(iter->first);
1881 if (type.group() == CREDIT_CARD &&
1882 iter->second != wrapper.GetInfo(type)) {
1893 // TODO(groby): Add more tests.
1894 base::string16 AutofillDialogControllerImpl::InputValidityMessage(
1895 DialogSection section,
1896 ServerFieldType type,
1897 const base::string16& value) {
1898 // If the field is edited, clear any Wallet errors.
1899 if (IsPayingWithWallet()) {
1900 WalletValidationErrors::iterator it = wallet_errors_.find(section);
1901 if (it != wallet_errors_.end()) {
1902 TypeErrorInputMap::const_iterator iter = it->second.find(type);
1903 if (iter != it->second.end()) {
1904 if (iter->second.second == value)
1905 return iter->second.first;
1906 it->second.erase(type);
1911 AutofillType autofill_type(type);
1912 if (autofill_type.group() == ADDRESS_HOME ||
1913 autofill_type.group() == ADDRESS_BILLING) {
1914 return base::string16();
1917 switch (autofill_type.GetStorableType()) {
1919 if (!value.empty() && !IsValidEmailAddress(value)) {
1920 return l10n_util::GetStringUTF16(
1921 IDS_AUTOFILL_DIALOG_VALIDATION_INVALID_EMAIL_ADDRESS);
1925 case CREDIT_CARD_NUMBER: {
1926 if (!value.empty()) {
1927 base::string16 message = CreditCardNumberValidityMessage(value);
1928 if (!message.empty())
1934 case CREDIT_CARD_EXP_MONTH:
1935 if (!InputWasEdited(CREDIT_CARD_EXP_MONTH, value)) {
1936 return l10n_util::GetStringUTF16(
1937 IDS_LIBADDRESSINPUT_MISSING_REQUIRED_FIELD);
1941 case CREDIT_CARD_EXP_4_DIGIT_YEAR:
1942 if (!InputWasEdited(CREDIT_CARD_EXP_4_DIGIT_YEAR, value)) {
1943 return l10n_util::GetStringUTF16(
1944 IDS_LIBADDRESSINPUT_MISSING_REQUIRED_FIELD);
1948 case CREDIT_CARD_VERIFICATION_CODE:
1949 if (!value.empty() && !autofill::IsValidCreditCardSecurityCode(value)) {
1950 return l10n_util::GetStringUTF16(
1951 IDS_AUTOFILL_DIALOG_VALIDATION_INVALID_CREDIT_CARD_SECURITY_CODE);
1956 // Wallet requires a first and last billing name.
1957 if (IsPayingWithWallet() && !value.empty() &&
1958 !IsCardHolderNameValidForWallet(value)) {
1959 return l10n_util::GetStringUTF16(
1960 IDS_AUTOFILL_DIALOG_VALIDATION_WALLET_REQUIRES_TWO_NAMES);
1964 case PHONE_HOME_WHOLE_NUMBER: // Used in shipping section.
1967 case PHONE_BILLING_WHOLE_NUMBER: // Used in billing section.
1971 NOTREACHED(); // Trying to validate unknown field.
1975 return value.empty() ? l10n_util::GetStringUTF16(
1976 IDS_LIBADDRESSINPUT_MISSING_REQUIRED_FIELD) :
1980 // TODO(groby): Also add tests.
1981 ValidityMessages AutofillDialogControllerImpl::InputsAreValid(
1982 DialogSection section,
1983 const FieldValueMap& inputs) {
1984 ValidityMessages messages;
1988 AddressValidator::Status status = AddressValidator::SUCCESS;
1989 if (section != SECTION_CC) {
1990 AutofillProfile profile;
1991 FillFormGroupFromOutputs(inputs, &profile);
1992 scoped_ptr<AddressData> address_data =
1993 i18n::CreateAddressDataFromAutofillProfile(
1994 profile, g_browser_process->GetApplicationLocale());
1995 address_data->language_code = AddressLanguageCodeForSection(section);
1997 Localization localization;
1998 localization.SetGetter(l10n_util::GetStringUTF8);
1999 FieldProblemMap problems;
2000 status = GetValidator()->ValidateAddress(*address_data, NULL, &problems);
2001 bool billing = section != SECTION_SHIPPING;
2003 for (FieldProblemMap::const_iterator iter = problems.begin();
2004 iter != problems.end(); ++iter) {
2005 bool sure = iter->second != MISSING_REQUIRED_FIELD;
2006 base::string16 text = base::UTF8ToUTF16(localization.GetErrorMessage(
2007 *address_data, iter->first, iter->second, true, false));
2008 messages.Set(i18n::TypeForField(iter->first, billing),
2009 ValidityMessage(text, sure));
2013 for (FieldValueMap::const_iterator iter = inputs.begin();
2014 iter != inputs.end(); ++iter) {
2015 const ServerFieldType type = iter->first;
2016 base::string16 text = InputValidityMessage(section, type, iter->second);
2018 // Skip empty/unchanged fields in edit mode. If the individual field does
2019 // not have validation errors, assume it to be valid unless later proven
2021 bool sure = InputWasEdited(type, iter->second);
2023 if (sure && status == AddressValidator::RULES_NOT_READY &&
2024 !ComboboxModelForAutofillType(type) &&
2025 (AutofillType(type).group() == ADDRESS_HOME ||
2026 AutofillType(type).group() == ADDRESS_BILLING)) {
2027 DCHECK(text.empty());
2028 text = l10n_util::GetStringUTF16(
2029 IDS_AUTOFILL_DIALOG_VALIDATION_WAITING_FOR_RULES);
2031 needs_validation_.insert(section);
2034 messages.Set(type, ValidityMessage(text, sure));
2037 // For the convenience of using operator[].
2038 FieldValueMap& field_values = const_cast<FieldValueMap&>(inputs);
2039 // Validate the date formed by month and year field. (Autofill dialog is
2040 // never supposed to have 2-digit years, so not checked).
2041 if (field_values.count(CREDIT_CARD_EXP_4_DIGIT_YEAR) &&
2042 field_values.count(CREDIT_CARD_EXP_MONTH) &&
2043 InputWasEdited(CREDIT_CARD_EXP_4_DIGIT_YEAR,
2044 field_values[CREDIT_CARD_EXP_4_DIGIT_YEAR]) &&
2045 InputWasEdited(CREDIT_CARD_EXP_MONTH,
2046 field_values[CREDIT_CARD_EXP_MONTH])) {
2047 ValidityMessage year_message(base::string16(), true);
2048 ValidityMessage month_message(base::string16(), true);
2049 if (!IsCreditCardExpirationValid(field_values[CREDIT_CARD_EXP_4_DIGIT_YEAR],
2050 field_values[CREDIT_CARD_EXP_MONTH])) {
2051 // The dialog shows the same error message for the month and year fields.
2052 year_message.text = l10n_util::GetStringUTF16(
2053 IDS_AUTOFILL_DIALOG_VALIDATION_INVALID_CREDIT_CARD_EXPIRATION_DATE);
2054 month_message.text = l10n_util::GetStringUTF16(
2055 IDS_AUTOFILL_DIALOG_VALIDATION_INVALID_CREDIT_CARD_EXPIRATION_DATE);
2057 messages.Set(CREDIT_CARD_EXP_4_DIGIT_YEAR, year_message);
2058 messages.Set(CREDIT_CARD_EXP_MONTH, month_message);
2061 // If there is a credit card number and a CVC, validate them together.
2062 if (field_values.count(CREDIT_CARD_NUMBER) &&
2063 field_values.count(CREDIT_CARD_VERIFICATION_CODE)) {
2064 ValidityMessage ccv_message(base::string16(), true);
2065 if (!autofill::IsValidCreditCardSecurityCode(
2066 field_values[CREDIT_CARD_VERIFICATION_CODE],
2067 field_values[CREDIT_CARD_NUMBER])) {
2068 ccv_message.text = l10n_util::GetStringUTF16(
2069 IDS_AUTOFILL_DIALOG_VALIDATION_INVALID_CREDIT_CARD_SECURITY_CODE);
2071 messages.Set(CREDIT_CARD_VERIFICATION_CODE, ccv_message);
2074 // Validate the shipping phone number against the country code of the address.
2075 if (field_values.count(ADDRESS_HOME_COUNTRY) &&
2076 field_values.count(PHONE_HOME_WHOLE_NUMBER)) {
2078 PHONE_HOME_WHOLE_NUMBER,
2079 GetPhoneValidityMessage(field_values[ADDRESS_HOME_COUNTRY],
2080 field_values[PHONE_HOME_WHOLE_NUMBER]));
2083 // Validate the billing phone number against the country code of the address.
2084 if (field_values.count(ADDRESS_BILLING_COUNTRY) &&
2085 field_values.count(PHONE_BILLING_WHOLE_NUMBER)) {
2087 PHONE_BILLING_WHOLE_NUMBER,
2088 GetPhoneValidityMessage(field_values[ADDRESS_BILLING_COUNTRY],
2089 field_values[PHONE_BILLING_WHOLE_NUMBER]));
2095 void AutofillDialogControllerImpl::UserEditedOrActivatedInput(
2096 DialogSection section,
2097 ServerFieldType type,
2098 gfx::NativeView parent_view,
2099 const gfx::Rect& content_bounds,
2100 const base::string16& field_contents,
2102 ScopedViewUpdates updates(view_.get());
2104 if (type == ADDRESS_BILLING_COUNTRY || type == ADDRESS_HOME_COUNTRY) {
2105 const FieldValueMap& snapshot = TakeUserInputSnapshot();
2107 // Clobber the inputs because the view's already been updated.
2108 RebuildInputsForCountry(section, field_contents, true);
2109 RestoreUserInputFromSnapshot(snapshot);
2110 UpdateSection(section);
2113 // The rest of this method applies only to textfields while Autofill is
2114 // enabled. If a combobox or Autofill is disabled, bail.
2115 if (ComboboxModelForAutofillType(type) || !IsAutofillEnabled())
2118 // If the field is edited down to empty, don't show a popup.
2119 if (was_edit && field_contents.empty()) {
2124 // If the user clicks while the popup is already showing, be sure to hide
2126 if (!was_edit && popup_controller_.get()) {
2131 std::vector<base::string16> popup_values, popup_labels, popup_icons;
2132 if (common::IsCreditCardType(type)) {
2133 GetManager()->GetCreditCardSuggestions(AutofillType(type),
2140 GetManager()->GetProfileSuggestions(
2144 RequestedTypesForSection(section),
2145 base::Bind(&AutofillDialogControllerImpl::ShouldSuggestProfile,
2146 base::Unretained(this), section),
2152 GetI18nValidatorSuggestions(section, type, &popup_values, &popup_labels,
2156 if (popup_values.empty()) {
2161 // |popup_input_type_| must be set before calling |Show()|.
2162 popup_input_type_ = type;
2163 popup_section_ = section;
2165 // TODO(estade): do we need separators and control rows like 'Clear
2167 std::vector<int> popup_ids;
2168 for (size_t i = 0; i < popup_values.size(); ++i) {
2169 popup_ids.push_back(i);
2172 popup_controller_ = AutofillPopupControllerImpl::GetOrCreate(
2174 weak_ptr_factory_.GetWeakPtr(),
2178 base::i18n::IsRTL() ?
2179 base::i18n::RIGHT_TO_LEFT : base::i18n::LEFT_TO_RIGHT);
2180 popup_controller_->Show(popup_values,
2186 void AutofillDialogControllerImpl::FocusMoved() {
2190 bool AutofillDialogControllerImpl::ShouldShowErrorBubble() const {
2191 return popup_input_type_ == UNKNOWN_TYPE;
2194 void AutofillDialogControllerImpl::ViewClosed() {
2195 GetManager()->RemoveObserver(this);
2197 // Called from here rather than in ~AutofillDialogControllerImpl as this
2198 // relies on virtual methods that change to their base class in the dtor.
2199 MaybeShowCreditCardBubble();
2204 std::vector<DialogNotification> AutofillDialogControllerImpl::
2205 CurrentNotifications() {
2206 std::vector<DialogNotification> notifications;
2208 // TODO(dbeam): figure out a way to dismiss this error after a while.
2209 if (wallet_error_notification_)
2210 notifications.push_back(*wallet_error_notification_);
2212 if (IsSubmitPausedOn(wallet::VERIFY_CVV)) {
2213 notifications.push_back(DialogNotification(
2214 DialogNotification::REQUIRED_ACTION,
2215 l10n_util::GetStringUTF16(IDS_AUTOFILL_DIALOG_VERIFY_CVV)));
2218 if (!wallet_server_validation_recoverable_) {
2219 notifications.push_back(DialogNotification(
2220 DialogNotification::REQUIRED_ACTION,
2221 l10n_util::GetStringUTF16(
2222 IDS_AUTOFILL_DIALOG_FAILED_TO_SAVE_WALLET_DATA)));
2225 if (choose_another_instrument_or_address_) {
2226 notifications.push_back(DialogNotification(
2227 DialogNotification::REQUIRED_ACTION,
2228 l10n_util::GetStringUTF16(
2229 IDS_AUTOFILL_DIALOG_CHOOSE_DIFFERENT_WALLET_INSTRUMENT)));
2232 if (notifications.empty() && MenuModelForAccountChooser()) {
2233 base::string16 text = l10n_util::GetStringUTF16(
2234 IsManuallyEditingAnySection() ?
2235 IDS_AUTOFILL_DIALOG_SAVE_DETAILS_IN_WALLET :
2236 IDS_AUTOFILL_DIALOG_USE_WALLET);
2237 DialogNotification notification(
2238 DialogNotification::WALLET_USAGE_CONFIRMATION,
2240 notification.set_tooltip_text(
2241 l10n_util::GetStringUTF16(
2242 IDS_AUTOFILL_DIALOG_SAVE_IN_WALLET_TOOLTIP));
2243 notification.set_checked(IsPayingWithWallet());
2244 notifications.push_back(notification);
2247 if (IsPayingWithWallet() && !wallet::IsUsingProd()) {
2248 notifications.push_back(DialogNotification(
2249 DialogNotification::DEVELOPER_WARNING,
2250 l10n_util::GetStringUTF16(IDS_AUTOFILL_DIALOG_NOT_PROD_WARNING)));
2253 if (!invoked_from_same_origin_) {
2254 notifications.push_back(DialogNotification(
2255 DialogNotification::SECURITY_WARNING,
2256 l10n_util::GetStringFUTF16(IDS_AUTOFILL_DIALOG_SITE_WARNING,
2257 base::UTF8ToUTF16(source_url_.host()))));
2260 return notifications;
2263 void AutofillDialogControllerImpl::LinkClicked(const GURL& url) {
2264 OpenTabWithUrl(url);
2267 void AutofillDialogControllerImpl::SignInLinkClicked() {
2271 void AutofillDialogControllerImpl::ShowSignIn(const GURL& url) {
2272 ScopedViewUpdates updates(view_.get());
2274 if (SignedInState() == NOT_CHECKED) {
2275 handling_use_wallet_link_click_ = true;
2276 account_chooser_model_->SelectWalletAccount(0);
2277 FetchWalletCookie();
2278 } else if (signin_registrar_.IsEmpty()) {
2280 waiting_for_explicit_sign_in_response_ = true;
2281 content::Source<content::NavigationController> source(
2282 view_->ShowSignIn(url));
2283 signin_registrar_.Add(
2284 this, content::NOTIFICATION_NAV_ENTRY_COMMITTED, source);
2286 GetMetricLogger().LogDialogUiEvent(
2287 AutofillMetrics::DIALOG_UI_SIGNIN_SHOWN);
2289 waiting_for_explicit_sign_in_response_ = false;
2293 view_->UpdateAccountChooser();
2294 view_->UpdateButtonStrip();
2297 void AutofillDialogControllerImpl::NotificationCheckboxStateChanged(
2298 DialogNotification::Type type, bool checked) {
2299 if (type == DialogNotification::WALLET_USAGE_CONFIRMATION) {
2301 account_chooser_model_->SelectWalletAccount(
2302 GetWalletClient()->user_index());
2304 account_chooser_model_->SelectUseAutofill();
2307 AccountChoiceChanged();
2311 void AutofillDialogControllerImpl::LegalDocumentLinkClicked(
2312 const gfx::Range& range) {
2313 for (size_t i = 0; i < legal_document_link_ranges_.size(); ++i) {
2314 if (legal_document_link_ranges_[i] == range) {
2315 OpenTabWithUrl(wallet_items_->legal_documents()[i]->url());
2323 bool AutofillDialogControllerImpl::OnCancel() {
2325 if (!is_submitting_)
2326 LogOnCancelMetrics();
2328 AutofillClient::AutocompleteResultErrorCancel, base::string16(), NULL);
2332 bool AutofillDialogControllerImpl::OnAccept() {
2333 ScopedViewUpdates updates(view_.get());
2334 choose_another_instrument_or_address_ = false;
2335 wallet_server_validation_recoverable_ = true;
2338 // This must come before SetIsSubmitting().
2339 if (IsPayingWithWallet()) {
2340 // In the VERIFY_CVV case, hold onto the previously submitted cardholder
2342 if (!IsSubmitPausedOn(wallet::VERIFY_CVV)) {
2343 submitted_cardholder_name_ =
2344 GetValueFromSection(SECTION_CC_BILLING, NAME_BILLING_FULL);
2346 // Snag the last four digits of the backing card now as it could be wiped
2347 // out if a CVC challenge happens.
2348 if (ActiveInstrument()) {
2349 backing_card_last_four_ = ActiveInstrument()->TypeAndLastFourDigits();
2351 FieldValueMap output;
2352 view_->GetUserInput(SECTION_CC_BILLING, &output);
2354 GetBillingInfoFromOutputs(output, &card, NULL, NULL);
2355 backing_card_last_four_ = card.TypeAndLastFourDigits();
2358 DCHECK(!submitted_cardholder_name_.empty());
2359 DCHECK(!backing_card_last_four_.empty());
2362 SetIsSubmitting(true);
2364 if (IsSubmitPausedOn(wallet::VERIFY_CVV)) {
2365 DCHECK(!active_instrument_id_.empty());
2366 full_wallet_.reset();
2367 GetWalletClient()->AuthenticateInstrument(
2368 active_instrument_id_,
2369 base::UTF16ToUTF8(view_->GetCvc()));
2370 view_->UpdateOverlay();
2371 } else if (IsPayingWithWallet()) {
2380 Profile* AutofillDialogControllerImpl::profile() {
2384 content::WebContents* AutofillDialogControllerImpl::GetWebContents() {
2385 return web_contents();
2388 ////////////////////////////////////////////////////////////////////////////////
2389 // AutofillPopupDelegate implementation.
2391 void AutofillDialogControllerImpl::OnPopupShown() {
2392 ScopedViewUpdates update(view_.get());
2393 view_->UpdateErrorBubble();
2395 GetMetricLogger().LogDialogPopupEvent(AutofillMetrics::DIALOG_POPUP_SHOWN);
2398 void AutofillDialogControllerImpl::OnPopupHidden() {}
2400 void AutofillDialogControllerImpl::DidSelectSuggestion(
2401 const base::string16& value,
2403 // TODO(estade): implement.
2406 void AutofillDialogControllerImpl::DidAcceptSuggestion(
2407 const base::string16& value,
2409 DCHECK_NE(UNKNOWN_TYPE, popup_input_type_);
2410 // Because |HidePopup()| can be called from |UpdateSection()|, remember the
2411 // type of the input for later here.
2412 const ServerFieldType popup_input_type = popup_input_type_;
2414 ScopedViewUpdates updates(view_.get());
2415 scoped_ptr<DataModelWrapper> wrapper;
2417 if (static_cast<size_t>(identifier) < popup_guids_.size()) {
2418 const PersonalDataManager::GUIDPair& pair = popup_guids_[identifier];
2419 if (common::IsCreditCardType(popup_input_type)) {
2420 wrapper.reset(new AutofillCreditCardWrapper(
2421 GetManager()->GetCreditCardByGUID(pair.first)));
2423 wrapper.reset(new AutofillProfileWrapper(
2424 GetManager()->GetProfileByGUID(pair.first),
2425 AutofillType(popup_input_type),
2429 wrapper.reset(new I18nAddressDataWrapper(
2430 &i18n_validator_suggestions_[identifier - popup_guids_.size()]));
2433 // If the user hasn't switched away from the default country and |wrapper|'s
2434 // country differs from the |view_|'s, rebuild inputs and restore user data.
2435 const FieldValueMap snapshot = TakeUserInputSnapshot();
2436 bool billing_rebuilt = false, shipping_rebuilt = false;
2438 base::string16 billing_country =
2439 wrapper->GetInfo(AutofillType(ADDRESS_BILLING_COUNTRY));
2440 if (popup_section_ == ActiveBillingSection() &&
2441 !snapshot.count(ADDRESS_BILLING_COUNTRY) &&
2442 !billing_country.empty()) {
2443 billing_rebuilt = RebuildInputsForCountry(
2444 ActiveBillingSection(), billing_country, false);
2447 base::string16 shipping_country =
2448 wrapper->GetInfo(AutofillType(ADDRESS_HOME_COUNTRY));
2449 if (popup_section_ == SECTION_SHIPPING &&
2450 !snapshot.count(ADDRESS_HOME_COUNTRY) &&
2451 !shipping_country.empty()) {
2452 shipping_rebuilt = RebuildInputsForCountry(
2453 SECTION_SHIPPING, shipping_country, false);
2456 if (billing_rebuilt || shipping_rebuilt) {
2457 RestoreUserInputFromSnapshot(snapshot);
2458 if (billing_rebuilt)
2459 UpdateSection(ActiveBillingSection());
2460 if (shipping_rebuilt)
2461 UpdateSection(SECTION_SHIPPING);
2464 DCHECK(SectionIsActive(popup_section_));
2465 wrapper->FillInputs(MutableRequestedFieldsForSection(popup_section_));
2466 view_->FillSection(popup_section_, popup_input_type);
2468 GetMetricLogger().LogDialogPopupEvent(
2469 AutofillMetrics::DIALOG_POPUP_FORM_FILLED);
2471 // TODO(estade): not sure why it's necessary to do this explicitly.
2475 void AutofillDialogControllerImpl::RemoveSuggestion(
2476 const base::string16& value,
2478 // TODO(estade): implement.
2481 void AutofillDialogControllerImpl::ClearPreviewedForm() {
2482 // TODO(estade): implement.
2485 ////////////////////////////////////////////////////////////////////////////////
2486 // content::NotificationObserver implementation.
2488 void AutofillDialogControllerImpl::Observe(
2490 const content::NotificationSource& source,
2491 const content::NotificationDetails& details) {
2492 DCHECK_EQ(type, content::NOTIFICATION_NAV_ENTRY_COMMITTED);
2493 content::LoadCommittedDetails* load_details =
2494 content::Details<content::LoadCommittedDetails>(details).ptr();
2495 size_t user_index = 0;
2496 if (IsSignInContinueUrl(load_details->entry->GetVirtualURL(), &user_index)) {
2497 GetWalletClient()->SetUserIndex(user_index);
2498 FetchWalletCookie();
2500 // NOTE: |HideSignIn()| may delete the WebContents which doesn't expect to
2501 // be deleted while committing a nav entry. Just call |HideSignIn()| later.
2502 base::MessageLoop::current()->PostTask(FROM_HERE,
2503 base::Bind(&AutofillDialogControllerImpl::HideSignIn,
2504 base::Unretained(this)));
2508 ////////////////////////////////////////////////////////////////////////////////
2509 // SuggestionsMenuModelDelegate implementation.
2511 void AutofillDialogControllerImpl::SuggestionItemSelected(
2512 SuggestionsMenuModel* model,
2514 ScopedViewUpdates updates(view_.get());
2516 if (model->GetItemKeyAt(index) == kManageItemsKey) {
2518 if (!IsPayingWithWallet()) {
2519 DCHECK(IsAutofillEnabled());
2520 GURL settings_url(chrome::kChromeUISettingsURL);
2521 url = settings_url.Resolve(chrome::kAutofillSubPage);
2523 // Reset |last_wallet_items_fetch_timestamp_| to ensure that the Wallet
2524 // data is refreshed as soon as the user switches back to this tab after
2525 // potentially editing his data.
2526 last_wallet_items_fetch_timestamp_ = base::TimeTicks();
2527 size_t user_index = GetWalletClient()->user_index();
2528 url = SectionForSuggestionsMenuModel(*model) == SECTION_SHIPPING ?
2529 wallet::GetManageAddressesUrl(user_index) :
2530 wallet::GetManageInstrumentsUrl(user_index);
2533 OpenTabWithUrl(url);
2537 model->SetCheckedIndex(index);
2538 DialogSection section = SectionForSuggestionsMenuModel(*model);
2540 ResetSectionInput(section);
2541 ShowEditUiIfBadSuggestion(section);
2542 UpdateSection(section);
2543 view_->UpdateNotificationArea();
2546 LogSuggestionItemSelectedMetric(*model);
2549 ////////////////////////////////////////////////////////////////////////////////
2550 // wallet::WalletClientDelegate implementation.
2552 const AutofillMetrics& AutofillDialogControllerImpl::GetMetricLogger() const {
2553 return metric_logger_;
2556 std::string AutofillDialogControllerImpl::GetRiskData() const {
2557 DCHECK(!risk_data_.empty());
2561 std::string AutofillDialogControllerImpl::GetWalletCookieValue() const {
2562 return wallet_cookie_value_;
2565 bool AutofillDialogControllerImpl::IsShippingAddressRequired() const {
2566 return cares_about_shipping_;
2569 void AutofillDialogControllerImpl::OnDidAcceptLegalDocuments() {
2570 DCHECK(is_submitting_ && IsPayingWithWallet());
2571 has_accepted_legal_documents_ = true;
2572 LoadRiskFingerprintData();
2575 void AutofillDialogControllerImpl::OnDidAuthenticateInstrument(bool success) {
2576 DCHECK(is_submitting_ && IsPayingWithWallet());
2578 // TODO(dbeam): use the returned full wallet. http://crbug.com/224992
2582 DisableWallet(wallet::WalletClient::UNKNOWN_ERROR);
2583 SuggestionsUpdated();
2587 void AutofillDialogControllerImpl::OnDidGetFullWallet(
2588 scoped_ptr<wallet::FullWallet> full_wallet) {
2589 DCHECK(is_submitting_ && IsPayingWithWallet());
2590 ScopedViewUpdates updates(view_.get());
2592 full_wallet_ = full_wallet.Pass();
2594 if (full_wallet_->required_actions().empty()) {
2599 switch (full_wallet_->required_actions()[0]) {
2600 case wallet::CHOOSE_ANOTHER_INSTRUMENT_OR_ADDRESS:
2601 choose_another_instrument_or_address_ = true;
2602 SetIsSubmitting(false);
2606 case wallet::VERIFY_CVV:
2607 SuggestionsUpdated();
2611 DisableWallet(wallet::WalletClient::UNKNOWN_ERROR);
2615 view_->UpdateNotificationArea();
2616 view_->UpdateButtonStrip();
2617 view_->UpdateOverlay();
2620 void AutofillDialogControllerImpl::OnPassiveSigninSuccess() {
2621 FetchWalletCookie();
2624 void AutofillDialogControllerImpl::OnPassiveSigninFailure(
2625 const GoogleServiceAuthError& error) {
2626 signin_helper_.reset();
2627 passive_failed_ = true;
2629 // When the user clicks on "use wallet" or a second account and passive auth
2630 // fails, try explicit sign in.
2631 if (handling_use_wallet_link_click_ || GetWalletClient()->user_index() != 0) {
2632 ShowSignIn(wallet::GetSignInUrl(GetWalletClient()->user_index()));
2633 handling_use_wallet_link_click_ = false;
2636 OnWalletSigninError();
2639 void AutofillDialogControllerImpl::OnDidFetchWalletCookieValue(
2640 const std::string& cookie_value) {
2641 wallet_cookie_value_ = cookie_value;
2642 signin_helper_.reset();
2646 void AutofillDialogControllerImpl::OnDidGetWalletItems(
2647 scoped_ptr<wallet::WalletItems> wallet_items) {
2648 legal_documents_text_.clear();
2649 legal_document_link_ranges_.clear();
2650 has_accepted_legal_documents_ = false;
2652 wallet_items_ = wallet_items.Pass();
2654 if (wallet_items_ && !wallet_items_->ObfuscatedGaiaId().empty()) {
2655 // Making sure the user index is in sync shouldn't be necessary, but is an
2656 // extra precaution. But if there is no active account (such as in the
2657 // PASSIVE_AUTH case), stick with the old active account.
2658 GetWalletClient()->SetUserIndex(wallet_items_->active_account_index());
2660 std::vector<std::string> usernames;
2661 for (size_t i = 0; i < wallet_items_->gaia_accounts().size(); ++i) {
2662 usernames.push_back(wallet_items_->gaia_accounts()[i]->email_address());
2664 account_chooser_model_->SetWalletAccounts(
2665 usernames, wallet_items_->active_account_index());
2668 if (wallet_items_) {
2669 shipping_country_combobox_model_->SetCountries(
2671 base::Bind(WalletCountryFilter,
2672 acceptable_shipping_countries_,
2673 wallet_items_->allowed_shipping_countries()));
2675 // If the site doesn't ship to any of the countries Wallet allows shipping
2676 // to, the merchant is not supported. (Note we generally shouldn't get here
2677 // as such a merchant wouldn't make it onto the Wallet whitelist.)
2678 if (shipping_country_combobox_model_->GetItemCount() == 0)
2679 DisableWallet(wallet::WalletClient::UNSUPPORTED_MERCHANT);
2682 ConstructLegalDocumentsText();
2683 OnWalletOrSigninUpdate();
2686 void AutofillDialogControllerImpl::OnDidSaveToWallet(
2687 const std::string& instrument_id,
2688 const std::string& address_id,
2689 const std::vector<wallet::RequiredAction>& required_actions,
2690 const std::vector<wallet::FormFieldError>& form_field_errors) {
2691 DCHECK(is_submitting_ && IsPayingWithWallet());
2693 if (required_actions.empty()) {
2694 if (!address_id.empty())
2695 active_address_id_ = address_id;
2696 if (!instrument_id.empty())
2697 active_instrument_id_ = instrument_id;
2700 OnWalletFormFieldError(form_field_errors);
2701 HandleSaveOrUpdateRequiredActions(required_actions);
2705 void AutofillDialogControllerImpl::OnWalletError(
2706 wallet::WalletClient::ErrorType error_type) {
2707 DisableWallet(error_type);
2710 ////////////////////////////////////////////////////////////////////////////////
2711 // PersonalDataManagerObserver implementation.
2713 void AutofillDialogControllerImpl::OnPersonalDataChanged() {
2717 SuggestionsUpdated();
2720 ////////////////////////////////////////////////////////////////////////////////
2721 // AccountChooserModelDelegate implementation.
2723 void AutofillDialogControllerImpl::AccountChoiceChanged() {
2724 ScopedViewUpdates updates(view_.get());
2725 wallet::WalletClient* client = GetWalletClient();
2728 client->CancelRequest();
2730 SetIsSubmitting(false);
2732 size_t selected_user_index =
2733 account_chooser_model_->GetActiveWalletAccountIndex();
2734 if (account_chooser_model_->WalletIsSelected() &&
2735 client->user_index() != selected_user_index) {
2736 client->SetUserIndex(selected_user_index);
2737 // Clear |wallet_items_| so we don't try to restore the selected instrument
2739 wallet_items_.reset();
2742 SuggestionsUpdated();
2743 UpdateAccountChooserView();
2747 void AutofillDialogControllerImpl::AddAccount() {
2748 ShowSignIn(wallet::GetAddAccountUrl());
2751 void AutofillDialogControllerImpl::UpdateAccountChooserView() {
2753 ScopedViewUpdates updates(view_.get());
2754 view_->UpdateAccountChooser();
2755 view_->UpdateNotificationArea();
2759 ////////////////////////////////////////////////////////////////////////////////
2761 bool AutofillDialogControllerImpl::HandleKeyPressEventInInput(
2762 const content::NativeWebKeyboardEvent& event) {
2763 if (popup_controller_.get())
2764 return popup_controller_->HandleKeyPressEvent(event);
2769 bool AutofillDialogControllerImpl::IsSubmitPausedOn(
2770 wallet::RequiredAction required_action) const {
2771 return full_wallet_ && full_wallet_->HasRequiredAction(required_action);
2774 void AutofillDialogControllerImpl::ShowNewCreditCardBubble(
2775 scoped_ptr<CreditCard> new_card,
2776 scoped_ptr<AutofillProfile> billing_profile) {
2777 NewCreditCardBubbleController::Show(web_contents(),
2779 billing_profile.Pass());
2782 void AutofillDialogControllerImpl::SubmitButtonDelayBegin() {
2783 submit_button_delay_timer_.Start(
2785 base::TimeDelta::FromMilliseconds(kSubmitButtonDelayMs),
2787 &AutofillDialogControllerImpl::OnSubmitButtonDelayEnd);
2790 void AutofillDialogControllerImpl::SubmitButtonDelayEndForTesting() {
2791 DCHECK(submit_button_delay_timer_.IsRunning());
2792 submit_button_delay_timer_.user_task().Run();
2793 submit_button_delay_timer_.Stop();
2796 void AutofillDialogControllerImpl::
2797 ClearLastWalletItemsFetchTimestampForTesting() {
2798 last_wallet_items_fetch_timestamp_ = base::TimeTicks();
2801 AccountChooserModel* AutofillDialogControllerImpl::
2802 AccountChooserModelForTesting() {
2803 return account_chooser_model_.get();
2806 bool AutofillDialogControllerImpl::IsSignInContinueUrl(
2808 size_t* user_index) const {
2809 return wallet::IsSignInContinueUrl(url, user_index);
2812 AutofillDialogControllerImpl::AutofillDialogControllerImpl(
2813 content::WebContents* contents,
2814 const FormData& form_structure,
2815 const GURL& source_url,
2816 const AutofillClient::ResultCallback& callback)
2817 : WebContentsObserver(contents),
2818 profile_(Profile::FromBrowserContext(contents->GetBrowserContext())),
2819 initial_user_state_(AutofillMetrics::DIALOG_USER_STATE_UNKNOWN),
2820 form_structure_(form_structure),
2821 invoked_from_same_origin_(true),
2822 source_url_(source_url),
2823 callback_(callback),
2824 wallet_client_(profile_->GetRequestContext(), this, source_url),
2825 wallet_items_requested_(false),
2826 handling_use_wallet_link_click_(false),
2827 passive_failed_(false),
2828 suggested_cc_(this),
2829 suggested_billing_(this),
2830 suggested_cc_billing_(this),
2831 suggested_shipping_(this),
2832 cares_about_shipping_(true),
2833 popup_input_type_(UNKNOWN_TYPE),
2834 popup_section_(SECTION_MIN),
2835 waiting_for_explicit_sign_in_response_(false),
2836 has_accepted_legal_documents_(false),
2837 is_submitting_(false),
2838 choose_another_instrument_or_address_(false),
2839 wallet_server_validation_recoverable_(true),
2840 data_was_passed_back_(false),
2841 was_ui_latency_logged_(false),
2842 card_generated_animation_(2000, 60, this),
2843 weak_ptr_factory_(this) {
2844 DCHECK(!callback_.is_null());
2847 AutofillDialogView* AutofillDialogControllerImpl::CreateView() {
2848 return AutofillDialogView::Create(this);
2851 PersonalDataManager* AutofillDialogControllerImpl::GetManager() const {
2852 return PersonalDataManagerFactory::GetForProfile(profile_);
2855 AddressValidator* AutofillDialogControllerImpl::GetValidator() {
2856 return validator_.get();
2859 const wallet::WalletClient* AutofillDialogControllerImpl::GetWalletClient()
2861 return const_cast<AutofillDialogControllerImpl*>(this)->GetWalletClient();
2864 wallet::WalletClient* AutofillDialogControllerImpl::GetWalletClient() {
2865 return &wallet_client_;
2868 bool AutofillDialogControllerImpl::IsPayingWithWallet() const {
2869 return account_chooser_model_->WalletIsSelected() &&
2870 SignedInState() == SIGNED_IN;
2873 void AutofillDialogControllerImpl::LoadRiskFingerprintData() {
2876 uint64 obfuscated_gaia_id = 0;
2877 bool success = base::StringToUint64(wallet_items_->ObfuscatedGaiaId(),
2878 &obfuscated_gaia_id);
2881 gfx::Rect window_bounds;
2882 window_bounds = GetBaseWindowForWebContents(web_contents())->GetBounds();
2884 PrefService* user_prefs = profile_->GetPrefs();
2885 std::string charset = user_prefs->GetString(::prefs::kDefaultCharset);
2886 std::string accept_languages =
2887 user_prefs->GetString(::prefs::kAcceptLanguages);
2888 base::Time install_time = base::Time::FromTimeT(
2889 g_browser_process->metrics_service()->GetInstallDate());
2891 risk::GetFingerprint(
2892 obfuscated_gaia_id, window_bounds, web_contents(),
2893 chrome::VersionInfo().Version(), charset, accept_languages, install_time,
2894 g_browser_process->GetApplicationLocale(), GetUserAgent(),
2895 base::Bind(&AutofillDialogControllerImpl::OnDidLoadRiskFingerprintData,
2896 weak_ptr_factory_.GetWeakPtr()));
2899 void AutofillDialogControllerImpl::OnDidLoadRiskFingerprintData(
2900 scoped_ptr<risk::Fingerprint> fingerprint) {
2901 DCHECK(AreLegalDocumentsCurrent());
2903 std::string proto_data;
2904 fingerprint->SerializeToString(&proto_data);
2905 base::Base64Encode(proto_data, &risk_data_);
2910 void AutofillDialogControllerImpl::OpenTabWithUrl(const GURL& url) {
2911 chrome::NavigateParams params(
2912 chrome::FindBrowserWithWebContents(web_contents()),
2914 ui::PAGE_TRANSITION_LINK);
2915 params.disposition = NEW_FOREGROUND_TAB;
2916 chrome::Navigate(¶ms);
2919 DialogSection AutofillDialogControllerImpl::ActiveBillingSection() const {
2920 return IsPayingWithWallet() ? SECTION_CC_BILLING : SECTION_BILLING;
2923 bool AutofillDialogControllerImpl::IsEditingExistingData(
2924 DialogSection section) const {
2925 return section_editing_state_.count(section) > 0;
2928 bool AutofillDialogControllerImpl::IsManuallyEditingSection(
2929 DialogSection section) const {
2930 return IsEditingExistingData(section) ||
2931 SuggestionsMenuModelForSection(section)->
2932 GetItemKeyForCheckedItem() == kAddNewItemKey;
2935 void AutofillDialogControllerImpl::OnWalletSigninError() {
2936 account_chooser_model_->SetHadWalletSigninError();
2937 GetWalletClient()->CancelRequest();
2938 LogDialogLatencyToShow();
2941 void AutofillDialogControllerImpl::DisableWallet(
2942 wallet::WalletClient::ErrorType error_type) {
2943 signin_helper_.reset();
2944 wallet_items_.reset();
2945 wallet_errors_.clear();
2946 GetWalletClient()->CancelRequest();
2947 SetIsSubmitting(false);
2948 wallet_error_notification_ = GetWalletError(error_type);
2949 account_chooser_model_->SetHadWalletError();
2952 void AutofillDialogControllerImpl::SuggestionsUpdated() {
2953 ScopedViewUpdates updates(view_.get());
2955 const FieldValueMap snapshot = TakeUserInputSnapshot();
2957 suggested_cc_.Reset();
2958 suggested_billing_.Reset();
2959 suggested_cc_billing_.Reset();
2960 suggested_shipping_.Reset();
2963 suggested_shipping_.AddKeyedItem(
2965 l10n_util::GetStringUTF16(IDS_AUTOFILL_DIALOG_USE_BILLING_FOR_SHIPPING));
2967 if (IsPayingWithWallet()) {
2968 const std::vector<wallet::Address*>& addresses =
2969 wallet_items_->addresses();
2971 bool shipping_same_as_billing = profile_->GetPrefs()->GetBoolean(
2972 ::prefs::kAutofillDialogWalletShippingSameAsBilling);
2974 if (shipping_same_as_billing)
2975 suggested_shipping_.SetCheckedItem(kSameAsBillingKey);
2977 for (size_t i = 0; i < addresses.size(); ++i) {
2978 std::string key = base::IntToString(i);
2979 suggested_shipping_.AddKeyedItemWithMinorText(
2981 addresses[i]->DisplayName(),
2982 addresses[i]->DisplayNameDetail());
2983 suggested_shipping_.SetEnabled(
2985 CanAcceptCountry(SECTION_SHIPPING,
2986 addresses[i]->country_name_code()));
2988 // TODO(scr): Move this assignment outside the loop or comment why it
2990 const std::string default_shipping_address_id =
2991 GetIdToSelect(wallet_items_->default_address_id(),
2992 previous_default_shipping_address_id_,
2993 previously_selected_shipping_address_id_);
2995 if (!shipping_same_as_billing &&
2996 addresses[i]->object_id() == default_shipping_address_id) {
2997 suggested_shipping_.SetCheckedItem(key);
3001 if (!IsSubmitPausedOn(wallet::VERIFY_CVV)) {
3002 const std::vector<wallet::WalletItems::MaskedInstrument*>& instruments =
3003 wallet_items_->instruments();
3004 std::string first_active_instrument_key;
3005 std::string default_instrument_key;
3006 for (size_t i = 0; i < instruments.size(); ++i) {
3007 bool allowed = IsInstrumentAllowed(*instruments[i]) &&
3008 CanAcceptCountry(SECTION_BILLING,
3009 instruments[i]->address().country_name_code());
3010 gfx::Image icon = instruments[i]->CardIcon();
3011 if (!allowed && !icon.IsEmpty()) {
3012 // Create a grayed disabled icon.
3013 SkBitmap disabled_bitmap = SkBitmapOperations::CreateHSLShiftedBitmap(
3014 *icon.ToSkBitmap(), kGrayImageShift);
3016 gfx::ImageSkia::CreateFrom1xBitmap(disabled_bitmap));
3018 std::string key = base::IntToString(i);
3019 suggested_cc_billing_.AddKeyedItemWithMinorTextAndIcon(
3021 instruments[i]->DisplayName(),
3022 instruments[i]->DisplayNameDetail(),
3024 suggested_cc_billing_.SetEnabled(key, allowed);
3027 if (first_active_instrument_key.empty())
3028 first_active_instrument_key = key;
3030 const std::string default_instrument_id =
3031 GetIdToSelect(wallet_items_->default_instrument_id(),
3032 previous_default_instrument_id_,
3033 previously_selected_instrument_id_);
3034 if (instruments[i]->object_id() == default_instrument_id)
3035 default_instrument_key = key;
3039 suggested_cc_billing_.AddKeyedItem(
3041 l10n_util::GetStringUTF16(IDS_AUTOFILL_DIALOG_ADD_BILLING_DETAILS));
3042 if (!wallet_items_->HasRequiredAction(wallet::SETUP_WALLET)) {
3043 suggested_cc_billing_.AddKeyedItemWithMinorText(
3045 l10n_util::GetStringUTF16(
3046 IDS_AUTOFILL_DIALOG_MANAGE_BILLING_DETAILS),
3047 base::UTF8ToUTF16(wallet::GetManageInstrumentsUrl(0U).host()));
3050 // Determine which instrument item should be selected.
3051 if (!default_instrument_key.empty())
3052 suggested_cc_billing_.SetCheckedItem(default_instrument_key);
3053 else if (!first_active_instrument_key.empty())
3054 suggested_cc_billing_.SetCheckedItem(first_active_instrument_key);
3056 suggested_cc_billing_.SetCheckedItem(kAddNewItemKey);
3059 shipping_country_combobox_model_->SetCountries(
3061 base::Bind(AutofillCountryFilter, acceptable_shipping_countries_));
3063 if (IsAutofillEnabled()) {
3064 PersonalDataManager* manager = GetManager();
3065 const std::vector<CreditCard*>& cards = manager->GetCreditCards();
3066 ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance();
3067 for (size_t i = 0; i < cards.size(); ++i) {
3068 if (!i18ninput::CardHasCompleteAndVerifiedData(*cards[i]))
3071 suggested_cc_.AddKeyedItemWithIcon(
3074 rb.GetImageNamed(CreditCard::IconResourceId(cards[i]->type())));
3075 suggested_cc_.SetEnabled(
3077 !ShouldDisallowCcType(cards[i]->TypeForDisplay()));
3080 const std::vector<AutofillProfile*>& profiles = manager->GetProfiles();
3081 std::vector<base::string16> labels;
3082 AutofillProfile::CreateDifferentiatingLabels(
3084 g_browser_process->GetApplicationLocale(),
3086 DCHECK_EQ(labels.size(), profiles.size());
3087 for (size_t i = 0; i < profiles.size(); ++i) {
3088 const AutofillProfile& profile = *profiles[i];
3089 if (!i18ninput::AddressHasCompleteAndVerifiedData(
3090 profile, g_browser_process->GetApplicationLocale())) {
3094 // Don't add variants for addresses: name is part of credit card and
3095 // we'll just ignore email and phone number variants.
3096 suggested_shipping_.AddKeyedItem(profile.guid(), labels[i]);
3097 suggested_shipping_.SetEnabled(
3101 base::UTF16ToUTF8(profile.GetRawInfo(ADDRESS_HOME_COUNTRY))));
3102 if (!profile.GetRawInfo(EMAIL_ADDRESS).empty() &&
3103 !profile.IsPresentButInvalid(EMAIL_ADDRESS)) {
3104 suggested_billing_.AddKeyedItem(profile.guid(), labels[i]);
3105 suggested_billing_.SetEnabled(
3109 base::UTF16ToUTF8(profile.GetRawInfo(ADDRESS_HOME_COUNTRY))));
3114 suggested_cc_.AddKeyedItem(
3116 l10n_util::GetStringUTF16(IsAutofillEnabled() ?
3117 IDS_AUTOFILL_DIALOG_ADD_CREDIT_CARD :
3118 IDS_AUTOFILL_DIALOG_ENTER_CREDIT_CARD));
3119 suggested_cc_.AddKeyedItem(
3121 l10n_util::GetStringUTF16(IDS_AUTOFILL_DIALOG_MANAGE_CREDIT_CARD));
3122 suggested_billing_.AddKeyedItem(
3124 l10n_util::GetStringUTF16(IsAutofillEnabled() ?
3125 IDS_AUTOFILL_DIALOG_ADD_BILLING_ADDRESS :
3126 IDS_AUTOFILL_DIALOG_ENTER_BILLING_DETAILS));
3127 suggested_billing_.AddKeyedItem(
3129 l10n_util::GetStringUTF16(IDS_AUTOFILL_DIALOG_MANAGE_BILLING_ADDRESS));
3132 suggested_shipping_.AddKeyedItem(
3134 l10n_util::GetStringUTF16(IsPayingWithWallet() || IsAutofillEnabled() ?
3135 IDS_AUTOFILL_DIALOG_ADD_SHIPPING_ADDRESS :
3136 IDS_AUTOFILL_DIALOG_USE_DIFFERENT_SHIPPING_ADDRESS));
3138 if (!IsPayingWithWallet()) {
3139 if (IsAutofillEnabled()) {
3140 suggested_shipping_.AddKeyedItem(
3142 l10n_util::GetStringUTF16(
3143 IDS_AUTOFILL_DIALOG_MANAGE_SHIPPING_ADDRESS));
3145 } else if (!wallet_items_->HasRequiredAction(wallet::SETUP_WALLET)) {
3146 suggested_shipping_.AddKeyedItemWithMinorText(
3148 l10n_util::GetStringUTF16(IDS_AUTOFILL_DIALOG_MANAGE_SHIPPING_ADDRESS),
3149 base::UTF8ToUTF16(wallet::GetManageAddressesUrl(0U).host()));
3152 if (!IsPayingWithWallet() && IsAutofillEnabled()) {
3153 for (size_t i = SECTION_MIN; i <= SECTION_MAX; ++i) {
3154 DialogSection section = static_cast<DialogSection>(i);
3155 if (!SectionIsActive(section))
3158 // Set the starting choice for the menu. First set to the default in case
3159 // the GUID saved in prefs refers to a profile that no longer exists.
3161 GetDefaultAutofillChoice(section, &guid);
3162 SuggestionsMenuModel* model = SuggestionsMenuModelForSection(section);
3163 model->SetCheckedItem(guid);
3164 if (GetAutofillChoice(section, &guid))
3165 model->SetCheckedItem(guid);
3170 view_->ModelChanged();
3172 for (size_t i = SECTION_MIN; i <= SECTION_MAX; ++i) {
3173 ResetSectionInput(static_cast<DialogSection>(i));
3176 FieldValueMap::const_iterator billing_it =
3177 snapshot.find(ADDRESS_BILLING_COUNTRY);
3178 if (billing_it != snapshot.end())
3179 RebuildInputsForCountry(ActiveBillingSection(), billing_it->second, true);
3181 FieldValueMap::const_iterator shipping_it =
3182 snapshot.find(ADDRESS_HOME_COUNTRY);
3183 if (shipping_it != snapshot.end())
3184 RebuildInputsForCountry(SECTION_SHIPPING, shipping_it->second, true);
3186 RestoreUserInputFromSnapshot(snapshot);
3188 for (size_t i = SECTION_MIN; i <= SECTION_MAX; ++i) {
3189 DialogSection section = static_cast<DialogSection>(i);
3190 if (!SectionIsActive(section))
3193 ShowEditUiIfBadSuggestion(section);
3194 UpdateSection(section);
3200 void AutofillDialogControllerImpl::FillOutputForSectionWithComparator(
3201 DialogSection section,
3202 const FormStructure::InputFieldComparator& compare) {
3203 if (!SectionIsActive(section))
3206 DetailInputs inputs;
3207 std::string country_code = CountryCodeForSection(section);
3208 BuildInputsForSection(section, country_code, &inputs,
3209 MutableAddressLanguageCodeForSection(section));
3210 std::vector<ServerFieldType> types = common::TypesFromInputs(inputs);
3212 scoped_ptr<DataModelWrapper> wrapper = CreateWrapper(section);
3214 // Only fill in data that is associated with this section.
3215 wrapper->FillFormStructure(types, compare, &form_structure_);
3217 // CVC needs special-casing because the CreditCard class doesn't store or
3218 // handle them. This isn't necessary when filling the combined CC and
3219 // billing section as CVC comes from |full_wallet_| in this case.
3220 if (section == SECTION_CC)
3221 SetOutputForFieldsOfType(CREDIT_CARD_VERIFICATION_CODE, view_->GetCvc());
3223 // When filling from Wallet data, use the email address associated with the
3224 // account. There is no other email address stored as part of a Wallet
3226 if (section == SECTION_CC_BILLING) {
3227 SetOutputForFieldsOfType(
3228 EMAIL_ADDRESS, account_chooser_model_->GetActiveWalletAccountName());
3231 // The user manually input data. If using Autofill, save the info as new or
3232 // edited data. Always fill local data into |form_structure_|.
3233 FieldValueMap output;
3234 view_->GetUserInput(section, &output);
3236 if (section == SECTION_CC) {
3238 FillFormGroupFromOutputs(output, &card);
3240 // The card holder name comes from the billing address section.
3241 card.SetRawInfo(CREDIT_CARD_NAME,
3242 GetValueFromSection(SECTION_BILLING, NAME_BILLING_FULL));
3244 if (ShouldSaveDetailsLocally()) {
3245 card.set_origin(kAutofillDialogOrigin);
3247 std::string guid = GetManager()->SaveImportedCreditCard(card);
3248 newly_saved_data_model_guids_[section] = guid;
3249 DCHECK(!profile()->IsOffTheRecord());
3250 newly_saved_card_.reset(new CreditCard(card));
3253 AutofillCreditCardWrapper card_wrapper(&card);
3254 card_wrapper.FillFormStructure(types, compare, &form_structure_);
3256 // Again, CVC needs special-casing. Fill it in directly from |output|.
3257 SetOutputForFieldsOfType(
3258 CREDIT_CARD_VERIFICATION_CODE,
3259 output[CREDIT_CARD_VERIFICATION_CODE]);
3261 AutofillProfile profile;
3262 FillFormGroupFromOutputs(output, &profile);
3263 profile.set_language_code(AddressLanguageCodeForSection(section));
3265 if (ShouldSaveDetailsLocally()) {
3266 profile.set_origin(RulesAreLoaded(section) ?
3267 kAutofillDialogOrigin : source_url_.GetOrigin().spec());
3269 std::string guid = GetManager()->SaveImportedProfile(profile);
3270 newly_saved_data_model_guids_[section] = guid;
3273 AutofillProfileWrapper profile_wrapper(&profile);
3274 profile_wrapper.FillFormStructure(types, compare, &form_structure_);
3279 void AutofillDialogControllerImpl::FillOutputForSection(DialogSection section) {
3280 FillOutputForSectionWithComparator(
3281 section, base::Bind(common::ServerTypeMatchesField, section));
3284 bool AutofillDialogControllerImpl::FormStructureCaresAboutSection(
3285 DialogSection section) const {
3286 // For now, only SECTION_SHIPPING may be omitted due to a site not asking for
3287 // any of the fields.
3288 if (section == SECTION_SHIPPING)
3289 return cares_about_shipping_;
3294 void AutofillDialogControllerImpl::SetOutputForFieldsOfType(
3295 ServerFieldType type,
3296 const base::string16& output) {
3297 for (size_t i = 0; i < form_structure_.field_count(); ++i) {
3298 AutofillField* field = form_structure_.field(i);
3299 if (field->Type().GetStorableType() == type)
3300 field->value = output;
3304 base::string16 AutofillDialogControllerImpl::GetValueFromSection(
3305 DialogSection section,
3306 ServerFieldType type) {
3307 DCHECK(SectionIsActive(section));
3309 scoped_ptr<DataModelWrapper> wrapper = CreateWrapper(section);
3311 return wrapper->GetInfo(AutofillType(type));
3313 FieldValueMap output;
3314 view_->GetUserInput(section, &output);
3315 return output[type];
3318 bool AutofillDialogControllerImpl::CanAcceptCountry(
3319 DialogSection section,
3320 const std::string& country_code) {
3321 DCHECK_EQ(2U, country_code.size());
3323 if (section == SECTION_CC_BILLING)
3324 return LowerCaseEqualsASCII(country_code, "us");
3326 CountryComboboxModel* model = CountryComboboxModelForSection(section);
3327 const std::vector<AutofillCountry*>& countries = model->countries();
3328 for (size_t i = 0; i < countries.size(); ++i) {
3329 if (countries[i] && countries[i]->country_code() == country_code)
3336 bool AutofillDialogControllerImpl::ShouldSuggestProfile(
3337 DialogSection section,
3338 const AutofillProfile& profile) {
3339 std::string country_code =
3340 base::UTF16ToASCII(profile.GetRawInfo(ADDRESS_HOME_COUNTRY));
3341 return country_code.empty() || CanAcceptCountry(section, country_code);
3344 SuggestionsMenuModel* AutofillDialogControllerImpl::
3345 SuggestionsMenuModelForSection(DialogSection section) {
3348 return &suggested_cc_;
3349 case SECTION_BILLING:
3350 return &suggested_billing_;
3351 case SECTION_SHIPPING:
3352 return &suggested_shipping_;
3353 case SECTION_CC_BILLING:
3354 return &suggested_cc_billing_;
3361 const SuggestionsMenuModel* AutofillDialogControllerImpl::
3362 SuggestionsMenuModelForSection(DialogSection section) const {
3363 return const_cast<AutofillDialogControllerImpl*>(this)->
3364 SuggestionsMenuModelForSection(section);
3367 DialogSection AutofillDialogControllerImpl::SectionForSuggestionsMenuModel(
3368 const SuggestionsMenuModel& model) {
3369 if (&model == &suggested_cc_)
3372 if (&model == &suggested_billing_)
3373 return SECTION_BILLING;
3375 if (&model == &suggested_cc_billing_)
3376 return SECTION_CC_BILLING;
3378 DCHECK_EQ(&model, &suggested_shipping_);
3379 return SECTION_SHIPPING;
3382 CountryComboboxModel* AutofillDialogControllerImpl::
3383 CountryComboboxModelForSection(DialogSection section) {
3384 if (section == SECTION_BILLING)
3385 return billing_country_combobox_model_.get();
3387 if (section == SECTION_SHIPPING)
3388 return shipping_country_combobox_model_.get();
3393 void AutofillDialogControllerImpl::GetI18nValidatorSuggestions(
3394 DialogSection section,
3395 ServerFieldType type,
3396 std::vector<base::string16>* popup_values,
3397 std::vector<base::string16>* popup_labels,
3398 std::vector<base::string16>* popup_icons) {
3399 AddressField focused_field;
3400 if (!i18n::FieldForType(type, &focused_field))
3403 FieldValueMap inputs;
3404 view_->GetUserInput(section, &inputs);
3406 AutofillProfile profile;
3407 FillFormGroupFromOutputs(inputs, &profile);
3409 scoped_ptr<AddressData> user_input =
3410 i18n::CreateAddressDataFromAutofillProfile(
3411 profile, g_browser_process->GetApplicationLocale());
3412 user_input->language_code = AddressLanguageCodeForSection(section);
3414 static const size_t kSuggestionsLimit = 10;
3415 AddressValidator::Status status = GetValidator()->GetSuggestions(
3416 *user_input, focused_field, kSuggestionsLimit,
3417 &i18n_validator_suggestions_);
3419 if (status != AddressValidator::SUCCESS)
3422 for (size_t i = 0; i < i18n_validator_suggestions_.size(); ++i) {
3423 popup_values->push_back(base::UTF8ToUTF16(
3424 i18n_validator_suggestions_[i].GetFieldValue(focused_field)));
3426 // Disambiguate the suggestion by showing the smallest administrative
3427 // region of the suggested address:
3428 // ADMIN_AREA > LOCALITY > DEPENDENT_LOCALITY
3429 popup_labels->push_back(base::string16());
3430 for (int field = DEPENDENT_LOCALITY; field >= ADMIN_AREA; --field) {
3431 const std::string& field_value =
3432 i18n_validator_suggestions_[i].GetFieldValue(
3433 static_cast<AddressField>(field));
3434 if (focused_field != field && !field_value.empty()) {
3435 popup_labels->back().assign(base::UTF8ToUTF16(field_value));
3440 popup_icons->resize(popup_values->size());
3443 DetailInputs* AutofillDialogControllerImpl::MutableRequestedFieldsForSection(
3444 DialogSection section) {
3445 return const_cast<DetailInputs*>(&RequestedFieldsForSection(section));
3448 std::string* AutofillDialogControllerImpl::MutableAddressLanguageCodeForSection(
3449 DialogSection section) {
3451 case SECTION_BILLING:
3452 case SECTION_CC_BILLING:
3453 return &billing_address_language_code_;
3454 case SECTION_SHIPPING:
3455 return &shipping_address_language_code_;
3463 std::string AutofillDialogControllerImpl::AddressLanguageCodeForSection(
3464 DialogSection section) {
3465 std::string* language_code = MutableAddressLanguageCodeForSection(section);
3466 return language_code != NULL ? *language_code : std::string();
3469 std::vector<ServerFieldType> AutofillDialogControllerImpl::
3470 RequestedTypesForSection(DialogSection section) const {
3471 return common::TypesFromInputs(RequestedFieldsForSection(section));
3474 std::string AutofillDialogControllerImpl::CountryCodeForSection(
3475 DialogSection section) {
3476 base::string16 country;
3478 scoped_ptr<DataModelWrapper> wrapper = CreateWrapper(section);
3480 country = wrapper->GetInfo(AutofillType(CountryTypeForSection(section)));
3482 FieldValueMap outputs;
3483 view_->GetUserInput(section, &outputs);
3484 country = outputs[CountryTypeForSection(section)];
3487 return AutofillCountry::GetCountryCode(
3488 country, g_browser_process->GetApplicationLocale());
3491 bool AutofillDialogControllerImpl::RebuildInputsForCountry(
3492 DialogSection section,
3493 const base::string16& country_name,
3494 bool should_clobber) {
3495 CountryComboboxModel* model = CountryComboboxModelForSection(section);
3499 std::string country_code = AutofillCountry::GetCountryCode(
3500 country_name, g_browser_process->GetApplicationLocale());
3501 DCHECK(CanAcceptCountry(section, country_code));
3503 if (view_ && !should_clobber) {
3504 FieldValueMap outputs;
3505 view_->GetUserInput(section, &outputs);
3507 // If |country_name| is the same as the view, no-op and let the caller know.
3508 if (outputs[CountryTypeForSection(section)] == country_name)
3512 DetailInputs* inputs = MutableRequestedFieldsForSection(section);
3514 BuildInputsForSection(section, country_code, inputs,
3515 MutableAddressLanguageCodeForSection(section));
3517 if (!country_code.empty()) {
3518 GetValidator()->LoadRules(AutofillCountry::GetCountryCode(
3519 country_name, g_browser_process->GetApplicationLocale()));
3525 void AutofillDialogControllerImpl::HidePopup() {
3526 if (popup_controller_)
3527 popup_controller_->Hide();
3528 popup_input_type_ = UNKNOWN_TYPE;
3531 void AutofillDialogControllerImpl::SetEditingExistingData(
3532 DialogSection section, bool editing) {
3534 section_editing_state_.insert(section);
3536 section_editing_state_.erase(section);
3539 bool AutofillDialogControllerImpl::IsASuggestionItemKey(
3540 const std::string& key) const {
3541 return !key.empty() &&
3542 key != kAddNewItemKey &&
3543 key != kManageItemsKey &&
3544 key != kSameAsBillingKey;
3547 bool AutofillDialogControllerImpl::IsAutofillEnabled() const {
3548 return profile_->GetPrefs()->GetBoolean(prefs::kAutofillEnabled);
3551 bool AutofillDialogControllerImpl::IsManuallyEditingAnySection() const {
3552 for (size_t section = SECTION_MIN; section <= SECTION_MAX; ++section) {
3553 if (IsManuallyEditingSection(static_cast<DialogSection>(section)))
3559 base::string16 AutofillDialogControllerImpl::CreditCardNumberValidityMessage(
3560 const base::string16& number) const {
3561 if (!number.empty() && !autofill::IsValidCreditCardNumber(number)) {
3562 return l10n_util::GetStringUTF16(
3563 IDS_AUTOFILL_DIALOG_VALIDATION_INVALID_CREDIT_CARD_NUMBER);
3566 if (!IsPayingWithWallet() &&
3567 ShouldDisallowCcType(CreditCard::TypeForDisplay(
3568 CreditCard::GetCreditCardType(number)))) {
3569 int ids = IDS_AUTOFILL_DIALOG_VALIDATION_UNACCEPTED_GENERIC_CARD;
3570 const char* const type = CreditCard::GetCreditCardType(number);
3571 if (type == kAmericanExpressCard)
3572 ids = IDS_AUTOFILL_DIALOG_VALIDATION_UNACCEPTED_AMEX;
3573 else if (type == kDiscoverCard)
3574 ids = IDS_AUTOFILL_DIALOG_VALIDATION_UNACCEPTED_DISCOVER;
3575 else if (type == kMasterCard)
3576 ids = IDS_AUTOFILL_DIALOG_VALIDATION_UNACCEPTED_MASTERCARD;
3577 else if (type == kVisaCard)
3578 ids = IDS_AUTOFILL_DIALOG_VALIDATION_UNACCEPTED_VISA;
3580 return l10n_util::GetStringUTF16(ids);
3583 base::string16 message;
3584 if (IsPayingWithWallet() && !wallet_items_->SupportsCard(number, &message))
3587 // Card number is good and supported.
3588 return base::string16();
3591 bool AutofillDialogControllerImpl::AllSectionsAreValid() {
3592 for (size_t section = SECTION_MIN; section <= SECTION_MAX; ++section) {
3593 if (!SectionIsValid(static_cast<DialogSection>(section)))
3599 bool AutofillDialogControllerImpl::SectionIsValid(
3600 DialogSection section) {
3601 if (!IsManuallyEditingSection(section))
3604 FieldValueMap detail_outputs;
3605 view_->GetUserInput(section, &detail_outputs);
3606 return !InputsAreValid(section, detail_outputs).HasSureErrors();
3609 bool AutofillDialogControllerImpl::RulesAreLoaded(DialogSection section) {
3610 AddressData address_data;
3611 address_data.region_code = CountryCodeForSection(section);
3612 AddressValidator::Status status = GetValidator()->ValidateAddress(
3613 address_data, NULL, NULL);
3614 return status == AddressValidator::SUCCESS;
3617 bool AutofillDialogControllerImpl::IsCreditCardExpirationValid(
3618 const base::string16& year,
3619 const base::string16& month) const {
3620 // If the expiration is in the past as per the local clock, it's invalid.
3621 base::Time now = base::Time::Now();
3622 if (!autofill::IsValidCreditCardExpirationDate(year, month, now))
3625 const wallet::WalletItems::MaskedInstrument* instrument =
3628 const std::string& locale = g_browser_process->GetApplicationLocale();
3630 if (base::StringToInt(month, &month_int) &&
3631 instrument->status() ==
3632 wallet::WalletItems::MaskedInstrument::EXPIRED &&
3634 instrument->GetInfo(
3635 AutofillType(CREDIT_CARD_EXP_4_DIGIT_YEAR), locale) &&
3636 month_int == instrument->expiration_month()) {
3637 // Otherwise, if the user is editing an instrument that's deemed expired
3638 // by the Online Wallet server, mark it invalid on selection.
3646 bool AutofillDialogControllerImpl::ShouldDisallowCcType(
3647 const base::string16& type) const {
3648 if (acceptable_cc_types_.empty())
3651 if (acceptable_cc_types_.find(base::i18n::ToUpper(type)) ==
3652 acceptable_cc_types_.end()) {
3659 bool AutofillDialogControllerImpl::HasInvalidAddress(
3660 const AutofillProfile& profile) {
3661 scoped_ptr<AddressData> address_data =
3662 i18n::CreateAddressDataFromAutofillProfile(
3663 profile, g_browser_process->GetApplicationLocale());
3665 FieldProblemMap problems;
3666 GetValidator()->ValidateAddress(*address_data, NULL, &problems);
3667 return !problems.empty();
3670 bool AutofillDialogControllerImpl::ShouldUseBillingForShipping() {
3671 return SectionIsActive(SECTION_SHIPPING) &&
3672 suggested_shipping_.GetItemKeyForCheckedItem() == kSameAsBillingKey;
3675 bool AutofillDialogControllerImpl::ShouldSaveDetailsLocally() {
3676 // It's possible that the user checked [X] Save details locally before
3677 // switching payment methods, so only ask the view whether to save details
3678 // locally if that checkbox is showing (currently if not paying with wallet).
3679 // Also, if the user isn't editing any sections, there's no data to save
3681 return ShouldOfferToSaveInChrome() && view_->SaveDetailsLocally();
3684 void AutofillDialogControllerImpl::SetIsSubmitting(bool submitting) {
3685 is_submitting_ = submitting;
3688 full_wallet_.reset();
3691 ScopedViewUpdates updates(view_.get());
3692 view_->UpdateButtonStrip();
3693 view_->UpdateOverlay();
3694 view_->UpdateNotificationArea();
3698 bool AutofillDialogControllerImpl::AreLegalDocumentsCurrent() const {
3699 return has_accepted_legal_documents_ ||
3700 (wallet_items_ && wallet_items_->legal_documents().empty());
3703 void AutofillDialogControllerImpl::AcceptLegalTerms() {
3704 content::GeolocationProvider::GetInstance()->UserDidOptIntoLocationServices();
3705 PrefService* local_state = g_browser_process->local_state();
3706 ListPrefUpdate accepted(
3707 local_state, ::prefs::kAutofillDialogWalletLocationAcceptance);
3708 accepted->AppendIfNotPresent(new base::StringValue(
3709 account_chooser_model_->GetActiveWalletAccountName()));
3711 if (AreLegalDocumentsCurrent()) {
3712 LoadRiskFingerprintData();
3714 GetWalletClient()->AcceptLegalDocuments(
3715 wallet_items_->legal_documents(),
3716 wallet_items_->google_transaction_id());
3720 void AutofillDialogControllerImpl::SubmitWithWallet() {
3721 active_instrument_id_.clear();
3722 active_address_id_.clear();
3723 full_wallet_.reset();
3725 const wallet::WalletItems::MaskedInstrument* active_instrument =
3727 if (!IsManuallyEditingSection(SECTION_CC_BILLING)) {
3728 active_instrument_id_ = active_instrument->object_id();
3729 DCHECK(!active_instrument_id_.empty());
3732 const wallet::Address* active_address = ActiveShippingAddress();
3733 if (!IsManuallyEditingSection(SECTION_SHIPPING) &&
3734 !ShouldUseBillingForShipping() &&
3735 IsShippingAddressRequired()) {
3736 active_address_id_ = active_address->object_id();
3737 DCHECK(!active_address_id_.empty());
3740 scoped_ptr<wallet::Instrument> inputted_instrument =
3741 CreateTransientInstrument();
3743 scoped_ptr<wallet::Address> inputted_address;
3744 if (active_address_id_.empty() && IsShippingAddressRequired()) {
3745 if (ShouldUseBillingForShipping()) {
3746 const wallet::Address& address = inputted_instrument ?
3747 *inputted_instrument->address() : active_instrument->address();
3748 // Try to find an exact matched shipping address and use it for shipping,
3749 // otherwise save it as a new shipping address. http://crbug.com/225442
3750 const wallet::Address* duplicated_address =
3751 FindDuplicateAddress(wallet_items_->addresses(), address);
3752 if (duplicated_address) {
3753 active_address_id_ = duplicated_address->object_id();
3754 DCHECK(!active_address_id_.empty());
3756 inputted_address.reset(new wallet::Address(address));
3757 DCHECK(inputted_address->object_id().empty());
3760 inputted_address = CreateTransientAddress();
3764 // If there's neither an address nor instrument to save, |GetFullWallet()|
3765 // is called when the risk fingerprint is loaded.
3766 if (!active_instrument_id_.empty() &&
3767 (!active_address_id_.empty() || !IsShippingAddressRequired())) {
3772 GetWalletClient()->SaveToWallet(
3773 inputted_instrument.Pass(),
3774 inputted_address.Pass(),
3775 IsEditingExistingData(SECTION_CC_BILLING) ? active_instrument : NULL,
3776 IsEditingExistingData(SECTION_SHIPPING) ? active_address : NULL);
3779 scoped_ptr<wallet::Instrument> AutofillDialogControllerImpl::
3780 CreateTransientInstrument() {
3781 if (!active_instrument_id_.empty())
3782 return scoped_ptr<wallet::Instrument>();
3784 FieldValueMap output;
3785 view_->GetUserInput(SECTION_CC_BILLING, &output);
3788 AutofillProfile profile;
3790 GetBillingInfoFromOutputs(output, &card, &cvc, &profile);
3791 CanonicalizeState(validator_.get(), &profile);
3793 return scoped_ptr<wallet::Instrument>(
3794 new wallet::Instrument(card, cvc, profile));
3797 scoped_ptr<wallet::Address>AutofillDialogControllerImpl::
3798 CreateTransientAddress() {
3799 // If not using billing for shipping, just scrape the view.
3800 FieldValueMap output;
3801 view_->GetUserInput(SECTION_SHIPPING, &output);
3803 AutofillProfile profile;
3804 FillFormGroupFromOutputs(output, &profile);
3805 profile.set_language_code(shipping_address_language_code_);
3806 CanonicalizeState(validator_.get(), &profile);
3808 return scoped_ptr<wallet::Address>(new wallet::Address(profile));
3811 void AutofillDialogControllerImpl::GetFullWallet() {
3812 DCHECK(is_submitting_);
3813 DCHECK(IsPayingWithWallet());
3814 DCHECK(wallet_items_);
3815 DCHECK(!active_instrument_id_.empty());
3816 DCHECK(!active_address_id_.empty() || !IsShippingAddressRequired());
3818 std::vector<wallet::WalletClient::RiskCapability> capabilities;
3819 capabilities.push_back(wallet::WalletClient::VERIFY_CVC);
3821 GetWalletClient()->GetFullWallet(wallet::WalletClient::FullWalletRequest(
3822 active_instrument_id_,
3824 wallet_items_->google_transaction_id(),
3826 wallet_items_->HasRequiredAction(wallet::SETUP_WALLET)));
3829 void AutofillDialogControllerImpl::HandleSaveOrUpdateRequiredActions(
3830 const std::vector<wallet::RequiredAction>& required_actions) {
3831 DCHECK(!required_actions.empty());
3833 // TODO(ahutter): Investigate if we need to support more generic actions on
3834 // this call such as GAIA_AUTH. See crbug.com/243457.
3835 for (std::vector<wallet::RequiredAction>::const_iterator iter =
3836 required_actions.begin();
3837 iter != required_actions.end(); ++iter) {
3838 if (*iter != wallet::INVALID_FORM_FIELD) {
3839 // TODO(dbeam): handle this more gracefully.
3840 DisableWallet(wallet::WalletClient::UNKNOWN_ERROR);
3843 SetIsSubmitting(false);
3846 void AutofillDialogControllerImpl::FinishSubmit() {
3847 if (IsPayingWithWallet()) {
3848 ScopedViewUpdates updates(view_.get());
3849 view_->UpdateOverlay();
3851 card_generated_animation_.Start();
3857 void AutofillDialogControllerImpl::AnimationProgressed(
3858 const gfx::Animation* animation) {
3859 DCHECK_EQ(animation, &card_generated_animation_);
3860 PushOverlayUpdate();
3863 void AutofillDialogControllerImpl::AnimationEnded(
3864 const gfx::Animation* animation) {
3865 DCHECK_EQ(animation, &card_generated_animation_);
3869 void AutofillDialogControllerImpl::OnAddressValidationRulesLoaded(
3870 const std::string& country_code,
3872 // Rules may load instantly (during initialization, before the view is
3873 // even ready). We'll validate when the view is created.
3877 ScopedViewUpdates updates(view_.get());
3879 // TODO(dbeam): should we retry on failure?
3880 for (size_t i = SECTION_MIN; i <= SECTION_MAX; ++i) {
3881 DialogSection section = static_cast<DialogSection>(i);
3882 if (!SectionIsActive(section) ||
3883 CountryCodeForSection(section) != country_code) {
3887 if (IsManuallyEditingSection(section) &&
3888 needs_validation_.count(section)) {
3889 view_->ValidateSection(section);
3890 needs_validation_.erase(section);
3891 } else if (success) {
3892 ShowEditUiIfBadSuggestion(section);
3893 UpdateSection(section);
3898 void AutofillDialogControllerImpl::DoFinishSubmit() {
3899 FillOutputForSection(SECTION_CC);
3900 FillOutputForSection(SECTION_BILLING);
3901 FillOutputForSection(SECTION_CC_BILLING);
3903 if (ShouldUseBillingForShipping()) {
3904 FillOutputForSectionWithComparator(
3906 base::Bind(ServerTypeMatchesShippingField));
3907 FillOutputForSectionWithComparator(
3909 base::Bind(ServerTypeMatchesShippingField));
3910 FillOutputForSectionWithComparator(
3912 base::Bind(ServerTypeMatchesShippingField));
3914 FillOutputForSection(SECTION_SHIPPING);
3917 if (IsPayingWithWallet()) {
3918 if (SectionIsActive(SECTION_SHIPPING)) {
3919 profile_->GetPrefs()->SetBoolean(
3920 ::prefs::kAutofillDialogWalletShippingSameAsBilling,
3921 suggested_shipping_.GetItemKeyForCheckedItem() == kSameAsBillingKey);
3923 } else if (ShouldOfferToSaveInChrome()) {
3924 for (size_t i = SECTION_MIN; i <= SECTION_MAX; ++i) {
3925 DialogSection section = static_cast<DialogSection>(i);
3926 if (!SectionIsActive(section))
3929 SuggestionsMenuModel* model = SuggestionsMenuModelForSection(section);
3930 std::string item_key = model->GetItemKeyForCheckedItem();
3931 if (IsASuggestionItemKey(item_key) || item_key == kSameAsBillingKey) {
3932 PersistAutofillChoice(section, item_key);
3933 } else if (item_key == kAddNewItemKey && ShouldSaveDetailsLocally()) {
3934 DCHECK(newly_saved_data_model_guids_.count(section));
3935 PersistAutofillChoice(section, newly_saved_data_model_guids_[section]);
3939 profile_->GetPrefs()->SetBoolean(::prefs::kAutofillDialogSaveData,
3940 view_->SaveDetailsLocally());
3943 // On a successful submit, if the user manually selected "pay without wallet",
3944 // stop trying to pay with Wallet on future runs of the dialog. On the other
3945 // hand, if there was an error that prevented the user from having the choice
3946 // of using Wallet, leave the pref alone.
3947 if (!wallet_error_notification_ &&
3948 account_chooser_model_->HasAccountsToChoose()) {
3949 profile_->GetPrefs()->SetBoolean(
3950 ::prefs::kAutofillDialogPayWithoutWallet,
3951 !account_chooser_model_->WalletIsSelected());
3954 LogOnFinishSubmitMetrics();
3956 // Callback should be called as late as possible.
3957 callback_.Run(AutofillClient::AutocompleteResultSuccess,
3960 data_was_passed_back_ = true;
3962 // This might delete us.
3966 void AutofillDialogControllerImpl::PersistAutofillChoice(
3967 DialogSection section,
3968 const std::string& guid) {
3969 DCHECK(!IsPayingWithWallet() && ShouldOfferToSaveInChrome());
3970 scoped_ptr<base::DictionaryValue> value(new base::DictionaryValue());
3971 value->SetString(kGuidPrefKey, guid);
3973 DictionaryPrefUpdate updater(profile()->GetPrefs(),
3974 ::prefs::kAutofillDialogAutofillDefault);
3975 base::DictionaryValue* autofill_choice = updater.Get();
3976 autofill_choice->Set(SectionToPrefString(section), value.release());
3979 void AutofillDialogControllerImpl::GetDefaultAutofillChoice(
3980 DialogSection section,
3981 std::string* guid) {
3982 DCHECK(!IsPayingWithWallet() && IsAutofillEnabled());
3983 // The default choice is the first thing in the menu that is a suggestion
3985 SuggestionsMenuModel* model = SuggestionsMenuModelForSection(section);
3986 for (int i = 0; i < model->GetItemCount(); ++i) {
3987 // Try the first suggestion item that is enabled.
3988 if (IsASuggestionItemKey(model->GetItemKeyAt(i)) && model->IsEnabledAt(i)) {
3989 *guid = model->GetItemKeyAt(i);
3991 // Fall back to the first non-suggestion key.
3992 } else if (!IsASuggestionItemKey(model->GetItemKeyAt(i)) && guid->empty()) {
3993 *guid = model->GetItemKeyAt(i);
3998 bool AutofillDialogControllerImpl::GetAutofillChoice(DialogSection section,
3999 std::string* guid) {
4000 DCHECK(!IsPayingWithWallet() && IsAutofillEnabled());
4001 const base::DictionaryValue* choices = profile()->GetPrefs()->GetDictionary(
4002 ::prefs::kAutofillDialogAutofillDefault);
4006 const base::DictionaryValue* choice = NULL;
4007 if (!choices->GetDictionary(SectionToPrefString(section), &choice))
4010 choice->GetString(kGuidPrefKey, guid);
4014 void AutofillDialogControllerImpl::LogOnFinishSubmitMetrics() {
4015 GetMetricLogger().LogDialogUiDuration(
4016 base::Time::Now() - dialog_shown_timestamp_,
4017 AutofillMetrics::DIALOG_ACCEPTED);
4019 GetMetricLogger().LogDialogUiEvent(AutofillMetrics::DIALOG_UI_ACCEPTED);
4021 AutofillMetrics::DialogDismissalState dismissal_state;
4022 if (!IsManuallyEditingAnySection()) {
4023 dismissal_state = IsPayingWithWallet() ?
4024 AutofillMetrics::DIALOG_ACCEPTED_EXISTING_WALLET_DATA :
4025 AutofillMetrics::DIALOG_ACCEPTED_EXISTING_AUTOFILL_DATA;
4026 } else if (IsPayingWithWallet()) {
4027 dismissal_state = AutofillMetrics::DIALOG_ACCEPTED_SAVE_TO_WALLET;
4028 } else if (ShouldSaveDetailsLocally()) {
4029 dismissal_state = AutofillMetrics::DIALOG_ACCEPTED_SAVE_TO_AUTOFILL;
4031 dismissal_state = AutofillMetrics::DIALOG_ACCEPTED_NO_SAVE;
4034 GetMetricLogger().LogDialogDismissalState(dismissal_state);
4037 void AutofillDialogControllerImpl::LogOnCancelMetrics() {
4038 GetMetricLogger().LogDialogUiEvent(AutofillMetrics::DIALOG_UI_CANCELED);
4040 AutofillMetrics::DialogDismissalState dismissal_state;
4041 if (ShouldShowSignInWebView())
4042 dismissal_state = AutofillMetrics::DIALOG_CANCELED_DURING_SIGNIN;
4043 else if (!IsManuallyEditingAnySection())
4044 dismissal_state = AutofillMetrics::DIALOG_CANCELED_NO_EDITS;
4045 else if (AllSectionsAreValid())
4046 dismissal_state = AutofillMetrics::DIALOG_CANCELED_NO_INVALID_FIELDS;
4048 dismissal_state = AutofillMetrics::DIALOG_CANCELED_WITH_INVALID_FIELDS;
4050 GetMetricLogger().LogDialogDismissalState(dismissal_state);
4052 GetMetricLogger().LogDialogUiDuration(
4053 base::Time::Now() - dialog_shown_timestamp_,
4054 AutofillMetrics::DIALOG_CANCELED);
4057 void AutofillDialogControllerImpl::LogSuggestionItemSelectedMetric(
4058 const SuggestionsMenuModel& model) {
4059 DialogSection section = SectionForSuggestionsMenuModel(model);
4061 AutofillMetrics::DialogUiEvent dialog_ui_event;
4062 if (model.GetItemKeyForCheckedItem() == kAddNewItemKey) {
4063 // Selected to add a new item.
4064 dialog_ui_event = common::DialogSectionToUiItemAddedEvent(section);
4065 } else if (IsASuggestionItemKey(model.GetItemKeyForCheckedItem())) {
4066 // Selected an existing item.
4067 dialog_ui_event = common::DialogSectionToUiSelectionChangedEvent(section);
4069 // TODO(estade): add logging for "Manage items" or "Use billing for
4074 GetMetricLogger().LogDialogUiEvent(dialog_ui_event);
4077 void AutofillDialogControllerImpl::LogDialogLatencyToShow() {
4078 if (was_ui_latency_logged_)
4081 GetMetricLogger().LogDialogLatencyToShow(
4082 base::Time::Now() - dialog_shown_timestamp_);
4083 was_ui_latency_logged_ = true;
4086 AutofillMetrics::DialogInitialUserStateMetric
4087 AutofillDialogControllerImpl::GetInitialUserState() const {
4088 // Consider a user to be an Autofill user if the user has any credit cards
4089 // or addresses saved. Check that the item count is greater than 2 because
4090 // an "empty" menu still has the "add new" menu item and "manage" menu item.
4091 const bool has_autofill_profiles =
4092 suggested_cc_.GetItemCount() > 2 ||
4093 suggested_billing_.GetItemCount() > 2;
4095 if (SignedInState() != SIGNED_IN) {
4097 return has_autofill_profiles ?
4098 AutofillMetrics::DIALOG_USER_NOT_SIGNED_IN_HAS_AUTOFILL :
4099 AutofillMetrics::DIALOG_USER_NOT_SIGNED_IN_NO_AUTOFILL;
4103 if (wallet_items_->instruments().empty()) {
4105 return has_autofill_profiles ?
4106 AutofillMetrics::DIALOG_USER_SIGNED_IN_NO_WALLET_HAS_AUTOFILL :
4107 AutofillMetrics::DIALOG_USER_SIGNED_IN_NO_WALLET_NO_AUTOFILL;
4110 // Has Wallet items.
4111 return has_autofill_profiles ?
4112 AutofillMetrics::DIALOG_USER_SIGNED_IN_HAS_WALLET_HAS_AUTOFILL :
4113 AutofillMetrics::DIALOG_USER_SIGNED_IN_HAS_WALLET_NO_AUTOFILL;
4116 void AutofillDialogControllerImpl::MaybeShowCreditCardBubble() {
4117 if (!data_was_passed_back_)
4120 if (newly_saved_card_) {
4121 scoped_ptr<AutofillProfile> billing_profile;
4122 if (IsManuallyEditingSection(SECTION_BILLING)) {
4123 // Scrape the view as the user's entering or updating information.
4124 FieldValueMap outputs;
4125 view_->GetUserInput(SECTION_BILLING, &outputs);
4126 billing_profile.reset(new AutofillProfile);
4127 FillFormGroupFromOutputs(outputs, billing_profile.get());
4128 billing_profile->set_language_code(billing_address_language_code_);
4130 // Just snag the currently suggested profile.
4131 std::string item_key = SuggestionsMenuModelForSection(SECTION_BILLING)->
4132 GetItemKeyForCheckedItem();
4133 AutofillProfile* profile = GetManager()->GetProfileByGUID(item_key);
4134 billing_profile.reset(new AutofillProfile(*profile));
4137 ShowNewCreditCardBubble(newly_saved_card_.Pass(),
4138 billing_profile.Pass());
4142 if (!full_wallet_ || !full_wallet_->billing_address())
4145 GeneratedCreditCardBubbleController::Show(
4147 full_wallet_->TypeAndLastFourDigits(),
4148 backing_card_last_four_);
4151 void AutofillDialogControllerImpl::OnSubmitButtonDelayEnd() {
4154 ScopedViewUpdates updates(view_.get());
4155 view_->UpdateButtonStrip();
4158 void AutofillDialogControllerImpl::FetchWalletCookie() {
4159 net::URLRequestContextGetter* request_context = profile_->GetRequestContext();
4160 signin_helper_.reset(new wallet::WalletSigninHelper(this, request_context));
4161 signin_helper_->StartWalletCookieValueFetch();
4164 } // namespace autofill