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 "apps/shell_window.h"
12 #include "apps/shell_window_registry.h"
13 #include "apps/ui/native_app_window.h"
14 #include "base/base64.h"
15 #include "base/bind.h"
16 #include "base/i18n/case_conversion.h"
17 #include "base/i18n/rtl.h"
18 #include "base/logging.h"
19 #include "base/prefs/pref_registry_simple.h"
20 #include "base/prefs/pref_service.h"
21 #include "base/prefs/scoped_user_pref_update.h"
22 #include "base/rand_util.h"
23 #include "base/strings/string_number_conversions.h"
24 #include "base/strings/string_split.h"
25 #include "base/strings/string_util.h"
26 #include "base/strings/utf_string_conversions.h"
27 #include "base/time/time.h"
28 #include "chrome/browser/autofill/personal_data_manager_factory.h"
29 #include "chrome/browser/browser_process.h"
30 #include "chrome/browser/profiles/profile.h"
31 #include "chrome/browser/ui/autofill/autofill_dialog_common.h"
32 #include "chrome/browser/ui/autofill/autofill_dialog_i18n_input.h"
33 #include "chrome/browser/ui/autofill/autofill_dialog_view.h"
34 #include "chrome/browser/ui/autofill/data_model_wrapper.h"
35 #include "chrome/browser/ui/autofill/generated_credit_card_bubble_controller.h"
36 #include "chrome/browser/ui/autofill/new_credit_card_bubble_controller.h"
37 #include "chrome/browser/ui/browser.h"
38 #include "chrome/browser/ui/browser_finder.h"
39 #include "chrome/browser/ui/browser_navigator.h"
40 #include "chrome/browser/ui/browser_window.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 "components/autofill/content/browser/risk/fingerprint.h"
46 #include "components/autofill/content/browser/risk/proto/fingerprint.pb.h"
47 #include "components/autofill/content/browser/wallet/form_field_error.h"
48 #include "components/autofill/content/browser/wallet/full_wallet.h"
49 #include "components/autofill/content/browser/wallet/gaia_account.h"
50 #include "components/autofill/content/browser/wallet/instrument.h"
51 #include "components/autofill/content/browser/wallet/wallet_address.h"
52 #include "components/autofill/content/browser/wallet/wallet_items.h"
53 #include "components/autofill/content/browser/wallet/wallet_service_url.h"
54 #include "components/autofill/content/browser/wallet/wallet_signin_helper.h"
55 #include "components/autofill/core/browser/autofill_country.h"
56 #include "components/autofill/core/browser/autofill_data_model.h"
57 #include "components/autofill/core/browser/autofill_manager.h"
58 #include "components/autofill/core/browser/autofill_type.h"
59 #include "components/autofill/core/browser/personal_data_manager.h"
60 #include "components/autofill/core/browser/phone_number_i18n.h"
61 #include "components/autofill/core/browser/validation.h"
62 #include "components/autofill/core/common/form_data.h"
63 #include "components/user_prefs/pref_registry_syncable.h"
64 #include "content/public/browser/browser_thread.h"
65 #include "content/public/browser/geolocation_provider.h"
66 #include "content/public/browser/navigation_controller.h"
67 #include "content/public/browser/navigation_details.h"
68 #include "content/public/browser/navigation_entry.h"
69 #include "content/public/browser/notification_service.h"
70 #include "content/public/browser/notification_types.h"
71 #include "content/public/browser/render_view_host.h"
72 #include "content/public/browser/web_contents.h"
73 #include "content/public/browser/web_contents_view.h"
74 #include "content/public/common/url_constants.h"
75 #include "grit/chromium_strings.h"
76 #include "grit/component_strings.h"
77 #include "grit/generated_resources.h"
78 #include "grit/platform_locale_settings.h"
79 #include "grit/theme_resources.h"
80 #include "grit/webkit_resources.h"
81 #include "net/cert/cert_status_flags.h"
82 #include "ui/base/base_window.h"
83 #include "ui/base/l10n/l10n_util.h"
84 #include "ui/base/models/combobox_model.h"
85 #include "ui/base/resource/resource_bundle.h"
86 #include "ui/events/event.h"
87 #include "ui/gfx/canvas.h"
88 #include "ui/gfx/image/image_skia_operations.h"
89 #include "ui/gfx/skia_util.h"
95 const char kAddNewItemKey[] = "add-new-item";
96 const char kManageItemsKey[] = "manage-items";
97 const char kSameAsBillingKey[] = "same-as-billing";
99 // URLs for Wallet error messages.
100 const char kBuyerLegalAddressStatusUrl[] =
101 "https://wallet.google.com/manage/settings";
102 const char kKnowYourCustomerStatusUrl[] = "https://wallet.google.com/kyc";
104 // Keys for the kAutofillDialogAutofillDefault pref dictionary (do not change
106 const char kGuidPrefKey[] = "guid";
108 // This string is stored along with saved addresses and credit cards in the
109 // WebDB, and hence should not be modified, so that it remains consistent over
111 const char kAutofillDialogOrigin[] = "Chrome Autofill dialog";
113 // HSL shift to gray out an image.
114 const color_utils::HSL kGrayImageShift = {-1, 0, 0.8};
116 // Limit Wallet items refresh rate to at most once per minute.
117 const int64 kWalletItemsRefreshRateSeconds = 60;
119 // The number of milliseconds to delay enabling the submit button after showing
120 // the dialog. This delay prevents users from accidentally clicking the submit
121 // button on startup.
122 const int kSubmitButtonDelayMs = 1000;
124 // A helper class to make sure an AutofillDialogView knows when a series of
125 // updates is incoming.
126 class ScopedViewUpdates {
128 explicit ScopedViewUpdates(AutofillDialogView* view) : view_(view) {
130 view_->UpdatesStarted();
133 ~ScopedViewUpdates() {
135 view_->UpdatesFinished();
139 AutofillDialogView* view_;
141 DISALLOW_COPY_AND_ASSIGN(ScopedViewUpdates);
144 // Returns true if |input| should be used to fill a site-requested |field| which
145 // is notated with a "shipping" tag, for use when the user has decided to use
146 // the billing address as the shipping address.
147 bool ServerTypeMatchesShippingField(ServerFieldType type,
148 const AutofillField& field) {
149 // Equivalent billing field type is used to support UseBillingAsShipping
151 return common::ServerTypeMatchesFieldType(
153 AutofillType(AutofillType::GetEquivalentBillingFieldType(
154 field.Type().GetStorableType())));
157 // Initializes |form_group| from user-entered data.
158 void FillFormGroupFromOutputs(const FieldValueMap& detail_outputs,
159 FormGroup* form_group) {
160 for (FieldValueMap::const_iterator iter = detail_outputs.begin();
161 iter != detail_outputs.end(); ++iter) {
162 ServerFieldType type = iter->first;
163 if (!iter->second.empty()) {
164 if (type == ADDRESS_HOME_COUNTRY || type == ADDRESS_BILLING_COUNTRY) {
165 form_group->SetInfo(AutofillType(type),
167 g_browser_process->GetApplicationLocale());
169 form_group->SetRawInfo(
170 AutofillType(type).GetStorableType(), iter->second);
176 // Get billing info from |output| and put it into |card|, |cvc|, and |profile|.
177 // These outparams are required because |card|/|profile| accept different types
178 // of raw info, and CreditCard doesn't save CVCs.
179 void GetBillingInfoFromOutputs(const FieldValueMap& output,
182 AutofillProfile* profile) {
183 for (FieldValueMap::const_iterator it = output.begin();
184 it != output.end(); ++it) {
185 const ServerFieldType type = it->first;
186 base::string16 trimmed;
187 TrimWhitespace(it->second, TRIM_ALL, &trimmed);
189 // Special case CVC as CreditCard just swallows it.
190 if (type == CREDIT_CARD_VERIFICATION_CODE) {
192 cvc->assign(trimmed);
193 } else if (type == ADDRESS_HOME_COUNTRY ||
194 type == ADDRESS_BILLING_COUNTRY) {
196 profile->SetInfo(AutofillType(type),
198 g_browser_process->GetApplicationLocale());
201 // Copy the credit card name to |profile| in addition to |card| as
202 // wallet::Instrument requires a recipient name for its billing address.
203 if (card && type == NAME_FULL)
204 card->SetRawInfo(CREDIT_CARD_NAME, trimmed);
206 if (common::IsCreditCardType(type)) {
208 card->SetRawInfo(type, trimmed);
209 } else if (profile) {
210 profile->SetRawInfo(AutofillType(type).GetStorableType(), trimmed);
216 // Returns the containing window for the given |web_contents|. The containing
217 // window might be a browser window for a Chrome tab, or it might be a shell
218 // window for a platform app.
219 ui::BaseWindow* GetBaseWindowForWebContents(
220 const content::WebContents* web_contents) {
221 Browser* browser = chrome::FindBrowserWithWebContents(web_contents);
223 return browser->window();
225 gfx::NativeWindow native_window =
226 web_contents->GetView()->GetTopLevelNativeWindow();
227 apps::ShellWindow* shell_window =
228 apps::ShellWindowRegistry::
229 GetShellWindowForNativeWindowAnyProfile(native_window);
230 return shell_window->GetBaseWindow();
233 // Returns a string descriptor for a DialogSection, for use with prefs (do not
234 // change these values).
235 std::string SectionToPrefString(DialogSection section) {
240 case SECTION_BILLING:
243 case SECTION_CC_BILLING:
244 // The SECTION_CC_BILLING section isn't active when using Autofill.
246 return std::string();
248 case SECTION_SHIPPING:
253 return std::string();
256 // Check if a given MaskedInstrument is allowed for the purchase.
257 bool IsInstrumentAllowed(
258 const wallet::WalletItems::MaskedInstrument& instrument) {
259 switch (instrument.status()) {
260 case wallet::WalletItems::MaskedInstrument::VALID:
261 case wallet::WalletItems::MaskedInstrument::PENDING:
262 case wallet::WalletItems::MaskedInstrument::EXPIRED:
263 case wallet::WalletItems::MaskedInstrument::BILLING_INCOMPLETE:
270 // Signals that the user has opted in to geolocation services. Factored out
271 // into a separate method because all interaction with the geolocation provider
272 // needs to happen on the IO thread, which is not the thread
273 // AutofillDialogViewDelegate lives on.
274 void UserDidOptIntoLocationServices() {
275 content::GeolocationProvider::GetInstance()->UserDidOptIntoLocationServices();
278 // Returns true if |profile| has an invalid address, i.e. an invalid state, zip
279 // code, phone number, or email address. Otherwise returns false. Profiles with
280 // invalid addresses are not suggested in the dropdown menu for billing and
281 // shipping addresses.
282 bool HasInvalidAddress(const AutofillProfile& profile) {
283 return profile.IsPresentButInvalid(ADDRESS_HOME_STATE) ||
284 profile.IsPresentButInvalid(ADDRESS_HOME_ZIP) ||
285 profile.IsPresentButInvalid(PHONE_HOME_WHOLE_NUMBER);
288 // Loops through |addresses_| comparing to |address| ignoring ID. If a match
289 // is not found, NULL is returned.
290 const wallet::Address* FindDuplicateAddress(
291 const std::vector<wallet::Address*>& addresses,
292 const wallet::Address& address) {
293 for (size_t i = 0; i < addresses.size(); ++i) {
294 if (addresses[i]->EqualsIgnoreID(address))
300 bool IsCardHolderNameValidForWallet(const base::string16& name) {
301 base::string16 whitespace_collapsed_name = CollapseWhitespace(name, true);
302 std::vector<base::string16> split_name;
303 base::SplitString(whitespace_collapsed_name, ' ', &split_name);
304 return split_name.size() >= 2;
307 DialogSection SectionFromLocation(wallet::FormFieldError::Location location) {
309 case wallet::FormFieldError::PAYMENT_INSTRUMENT:
310 case wallet::FormFieldError::LEGAL_ADDRESS:
311 return SECTION_CC_BILLING;
313 case wallet::FormFieldError::SHIPPING_ADDRESS:
314 return SECTION_SHIPPING;
316 case wallet::FormFieldError::UNKNOWN_LOCATION:
325 scoped_ptr<DialogNotification> GetWalletError(
326 wallet::WalletClient::ErrorType error_type) {
330 switch (error_type) {
331 case wallet::WalletClient::UNVERIFIED_KNOW_YOUR_CUSTOMER_STATUS:
332 text = l10n_util::GetStringUTF16(
333 IDS_AUTOFILL_WALLET_UNVERIFIED_KNOW_YOUR_CUSTOMER_STATUS);
334 url = GURL(kKnowYourCustomerStatusUrl);
337 case wallet::WalletClient::BUYER_LEGAL_ADDRESS_NOT_SUPPORTED:
338 text = l10n_util::GetStringUTF16(
339 IDS_AUTOFILL_WALLET_BUYER_COUNTRY_NOT_SUPPORTED);
340 url = GURL(kBuyerLegalAddressStatusUrl);
344 // The notification will not have a link; it's handled in the next
350 scoped_ptr<DialogNotification> notification(new DialogNotification(
351 DialogNotification::WALLET_ERROR,
353 notification->set_link_url(url);
354 return notification.Pass();
360 switch (error_type) {
361 case wallet::WalletClient::UNSUPPORTED_MERCHANT:
362 error_ids = IDS_AUTOFILL_WALLET_UNSUPPORTED_MERCHANT;
365 case wallet::WalletClient::BAD_REQUEST:
366 error_ids = IDS_AUTOFILL_WALLET_UPGRADE_CHROME_ERROR;
370 case wallet::WalletClient::INVALID_PARAMS:
371 error_ids = IDS_AUTOFILL_WALLET_UPGRADE_CHROME_ERROR;
375 case wallet::WalletClient::BUYER_ACCOUNT_ERROR:
376 error_ids = IDS_AUTOFILL_WALLET_BUYER_ACCOUNT_ERROR;
380 case wallet::WalletClient::UNSUPPORTED_API_VERSION:
381 error_ids = IDS_AUTOFILL_WALLET_UPGRADE_CHROME_ERROR;
385 case wallet::WalletClient::SERVICE_UNAVAILABLE:
386 error_ids = IDS_AUTOFILL_WALLET_SERVICE_UNAVAILABLE_ERROR;
390 case wallet::WalletClient::INTERNAL_ERROR:
391 error_ids = IDS_AUTOFILL_WALLET_UNKNOWN_ERROR;
395 case wallet::WalletClient::MALFORMED_RESPONSE:
396 error_ids = IDS_AUTOFILL_WALLET_UNKNOWN_ERROR;
400 case wallet::WalletClient::NETWORK_ERROR:
401 error_ids = IDS_AUTOFILL_WALLET_UNKNOWN_ERROR;
405 case wallet::WalletClient::UNKNOWN_ERROR:
406 error_ids = IDS_AUTOFILL_WALLET_UNKNOWN_ERROR;
414 DCHECK_NE(0, error_ids);
416 // The other error types are strings of the form "XXX. You can pay without
418 scoped_ptr<DialogNotification> notification(new DialogNotification(
419 DialogNotification::WALLET_ERROR,
420 l10n_util::GetStringFUTF16(IDS_AUTOFILL_DIALOG_COMPLETE_WITHOUT_WALLET,
421 l10n_util::GetStringUTF16(error_ids))));
424 notification->set_tooltip_text(
425 l10n_util::GetStringFUTF16(IDS_AUTOFILL_WALLET_ERROR_CODE_TOOLTIP,
426 base::IntToString16(error_code)));
429 return notification.Pass();
432 // Returns the ID of the address or instrument that should be selected in the
433 // UI, given that the |default_id| is currently the default ID on the Wallet
434 // server, |previous_default_id| was the default ID prior to re-fetching the
435 // Wallet data, and |previously_selected_id| was the ID of the item selected in
436 // the dialog prior to re-fetching the Wallet data.
437 std::string GetIdToSelect(const std::string& default_id,
438 const std::string& previous_default_id,
439 const std::string& previously_selected_id) {
440 // If the default ID changed since the last fetch of the Wallet data, select
441 // it rather than the previously selected item, as the user's intention in
442 // changing the default was probably to use it.
443 if (default_id != previous_default_id)
446 // Otherwise, prefer the previously selected item, if there was one.
447 return !previously_selected_id.empty() ? previously_selected_id : default_id;
450 // Generate a random card number in a user displayable format.
451 base::string16 GenerateRandomCardNumber() {
452 std::string card_number;
453 for (size_t i = 0; i < 4; ++i) {
454 int part = base::RandInt(0, 10000);
455 base::StringAppendF(&card_number, "%04d ", part);
457 return base::ASCIIToUTF16(card_number);
460 gfx::Image CreditCardIconForType(const std::string& credit_card_type) {
461 const int input_card_idr = CreditCard::IconResourceId(credit_card_type);
462 ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance();
463 gfx::Image result = rb.GetImageNamed(input_card_idr);
464 if (input_card_idr == IDR_AUTOFILL_CC_GENERIC) {
465 // When the credit card type is unknown, no image should be shown. However,
466 // to simplify the view code on Mac, save space for the credit card image by
467 // returning a transparent image of the appropriate size. Not all credit
468 // card images are the same size, but none is larger than the Visa icon.
469 result = gfx::Image(gfx::ImageSkiaOperations::CreateTransparentImage(
470 rb.GetImageNamed(IDR_AUTOFILL_CC_VISA).AsImageSkia(), 0));
475 gfx::Image CvcIconForCreditCardType(const base::string16& credit_card_type) {
476 ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance();
477 if (credit_card_type == l10n_util::GetStringUTF16(IDS_AUTOFILL_CC_AMEX))
478 return rb.GetImageNamed(IDR_CREDIT_CARD_CVC_HINT_AMEX);
480 return rb.GetImageNamed(IDR_CREDIT_CARD_CVC_HINT);
483 ServerFieldType CountryTypeForSection(DialogSection section) {
484 return section == SECTION_SHIPPING ? ADDRESS_HOME_COUNTRY :
485 ADDRESS_BILLING_COUNTRY;
490 AutofillDialogViewDelegate::~AutofillDialogViewDelegate() {}
492 AutofillDialogControllerImpl::~AutofillDialogControllerImpl() {
493 if (popup_controller_)
494 popup_controller_->Hide();
496 GetMetricLogger().LogDialogInitialUserState(initial_user_state_);
500 base::WeakPtr<AutofillDialogControllerImpl>
501 AutofillDialogControllerImpl::Create(
502 content::WebContents* contents,
503 const FormData& form_structure,
504 const GURL& source_url,
505 const base::Callback<void(const FormStructure*)>& callback) {
506 // AutofillDialogControllerImpl owns itself.
507 AutofillDialogControllerImpl* autofill_dialog_controller =
508 new AutofillDialogControllerImpl(contents,
512 return autofill_dialog_controller->weak_ptr_factory_.GetWeakPtr();
516 void AutofillDialogController::RegisterPrefs(PrefRegistrySimple* registry) {
517 registry->RegisterListPref(::prefs::kAutofillDialogWalletLocationAcceptance);
521 void AutofillDialogController::RegisterProfilePrefs(
522 user_prefs::PrefRegistrySyncable* registry) {
523 registry->RegisterBooleanPref(
524 ::prefs::kAutofillDialogPayWithoutWallet,
526 user_prefs::PrefRegistrySyncable::SYNCABLE_PREF);
527 registry->RegisterDictionaryPref(
528 ::prefs::kAutofillDialogAutofillDefault,
529 user_prefs::PrefRegistrySyncable::SYNCABLE_PREF);
530 registry->RegisterBooleanPref(
531 ::prefs::kAutofillDialogSaveData,
533 user_prefs::PrefRegistrySyncable::SYNCABLE_PREF);
534 registry->RegisterBooleanPref(
535 ::prefs::kAutofillDialogWalletShippingSameAsBilling,
537 user_prefs::PrefRegistrySyncable::SYNCABLE_PREF);
541 base::WeakPtr<AutofillDialogController> AutofillDialogController::Create(
542 content::WebContents* contents,
543 const FormData& form_structure,
544 const GURL& source_url,
545 const base::Callback<void(const FormStructure*)>& callback) {
546 return AutofillDialogControllerImpl::Create(contents,
552 void AutofillDialogControllerImpl::Show() {
553 dialog_shown_timestamp_ = base::Time::Now();
555 // Determine what field types should be included in the dialog.
556 bool has_types = false;
557 bool has_sections = false;
558 form_structure_.ParseFieldTypesFromAutocompleteAttributes(
559 &has_types, &has_sections);
561 // Fail if the author didn't specify autocomplete types.
568 // Log any relevant UI metrics and security exceptions.
569 GetMetricLogger().LogDialogUiEvent(AutofillMetrics::DIALOG_UI_SHOWN);
571 GetMetricLogger().LogDialogSecurityMetric(
572 AutofillMetrics::SECURITY_METRIC_DIALOG_SHOWN);
574 // The Autofill dialog is shown in response to a message from the renderer and
575 // as such, it can only be made in the context of the current document. A call
576 // to GetActiveEntry would return a pending entry, if there was one, which
577 // would be a security bug. Therefore, we use the last committed URL for the
579 const GURL& current_url = web_contents()->GetLastCommittedURL();
580 invoked_from_same_origin_ =
581 current_url.GetOrigin() == source_url_.GetOrigin();
583 if (!invoked_from_same_origin_) {
584 GetMetricLogger().LogDialogSecurityMetric(
585 AutofillMetrics::SECURITY_METRIC_CROSS_ORIGIN_FRAME);
588 for (size_t i = SECTION_MIN; i <= SECTION_MAX; ++i) {
589 DialogSection section = static_cast<DialogSection>(i);
591 std::string country_code;
592 CountryComboboxModel* model = CountryComboboxModelForSection(section);
594 country_code = model->GetDefaultCountryCode();
596 DetailInputs* inputs = MutableRequestedFieldsForSection(section);
597 common::BuildInputsForSection(section, country_code, inputs);
600 // Test whether we need to show the shipping section. If filling that section
601 // would be a no-op, don't show it.
602 const DetailInputs& inputs = RequestedFieldsForSection(SECTION_SHIPPING);
603 cares_about_shipping_ = EmptyDataModelWrapper().FillFormStructure(
605 base::Bind(common::ServerTypeMatchesField, SECTION_SHIPPING),
608 account_chooser_model_.reset(
609 new AccountChooserModel(this,
611 !ShouldShowAccountChooser(),
614 if (account_chooser_model_->WalletIsSelected())
617 // TODO(estade): don't show the dialog if the site didn't specify the right
618 // fields. First we must figure out what the "right" fields are.
619 SuggestionsUpdated();
620 SubmitButtonDelayBegin();
621 view_.reset(CreateView());
623 GetManager()->AddObserver(this);
625 if (!account_chooser_model_->WalletIsSelected())
626 LogDialogLatencyToShow();
629 void AutofillDialogControllerImpl::Hide() {
634 void AutofillDialogControllerImpl::TabActivated() {
635 // If the user switched away from this tab and then switched back, reload the
636 // Wallet items, in case they've changed.
637 int64 seconds_elapsed_since_last_refresh =
638 (base::TimeTicks::Now() - last_wallet_items_fetch_timestamp_).InSeconds();
639 if (IsPayingWithWallet() && wallet_items_ &&
640 seconds_elapsed_since_last_refresh >= kWalletItemsRefreshRateSeconds) {
645 TestableAutofillDialogView* AutofillDialogControllerImpl::GetTestableView() {
646 return view_ ? view_->GetTestableView() : NULL;
649 ////////////////////////////////////////////////////////////////////////////////
650 // AutofillDialogViewDelegate implementation.
652 base::string16 AutofillDialogControllerImpl::DialogTitle() const {
653 if (ShouldShowSpinner())
654 return base::string16();
656 return l10n_util::GetStringUTF16(IDS_AUTOFILL_DIALOG_TITLE);
659 base::string16 AutofillDialogControllerImpl::AccountChooserText() const {
660 if (!account_chooser_model_->WalletIsSelected())
661 return l10n_util::GetStringUTF16(IDS_AUTOFILL_DIALOG_PAYING_WITHOUT_WALLET);
663 if (SignedInState() == SIGNED_IN)
664 return account_chooser_model_->GetActiveWalletAccountName();
666 // In this case, the account chooser should be showing the signin link.
667 return base::string16();
670 base::string16 AutofillDialogControllerImpl::SignInLinkText() const {
671 int ids = SignedInState() == NOT_CHECKED ?
672 IDS_AUTOFILL_DIALOG_USE_WALLET_LINK :
673 ShouldShowSignInWebView() ? IDS_AUTOFILL_DIALOG_CANCEL_SIGN_IN :
674 IDS_AUTOFILL_DIALOG_SIGN_IN;
676 return l10n_util::GetStringUTF16(ids);
679 base::string16 AutofillDialogControllerImpl::SpinnerText() const {
680 return l10n_util::GetStringUTF16(IDS_AUTOFILL_DIALOG_LOADING);
683 base::string16 AutofillDialogControllerImpl::EditSuggestionText() const {
684 return l10n_util::GetStringUTF16(IDS_AUTOFILL_DIALOG_EDIT);
687 base::string16 AutofillDialogControllerImpl::CancelButtonText() const {
688 return l10n_util::GetStringUTF16(IDS_CANCEL);
691 base::string16 AutofillDialogControllerImpl::ConfirmButtonText() const {
692 return l10n_util::GetStringUTF16(IsSubmitPausedOn(wallet::VERIFY_CVV) ?
693 IDS_AUTOFILL_DIALOG_VERIFY_BUTTON : IDS_AUTOFILL_DIALOG_SUBMIT_BUTTON);
696 base::string16 AutofillDialogControllerImpl::SaveLocallyText() const {
697 return l10n_util::GetStringUTF16(IDS_AUTOFILL_DIALOG_SAVE_LOCALLY_CHECKBOX);
700 base::string16 AutofillDialogControllerImpl::SaveLocallyTooltip() const {
701 return l10n_util::GetStringUTF16(IDS_AUTOFILL_DIALOG_SAVE_LOCALLY_TOOLTIP);
704 base::string16 AutofillDialogControllerImpl::LegalDocumentsText() {
705 if (!IsPayingWithWallet() || ShouldShowSignInWebView())
706 return base::string16();
708 return legal_documents_text_;
711 bool AutofillDialogControllerImpl::ShouldShowSpinner() const {
712 return SignedInState() == REQUIRES_RESPONSE ||
713 SignedInState() == REQUIRES_PASSIVE_SIGN_IN;
716 bool AutofillDialogControllerImpl::ShouldShowAccountChooser() const {
717 return !ShouldShowSpinner() && GetManager()->IsCountryOfInterest("US");
720 bool AutofillDialogControllerImpl::ShouldShowSignInWebView() const {
721 return !signin_registrar_.IsEmpty();
724 GURL AutofillDialogControllerImpl::SignInUrl() const {
725 return wallet::GetSignInUrl();
728 bool AutofillDialogControllerImpl::ShouldOfferToSaveInChrome() const {
729 return !IsPayingWithWallet() &&
730 !profile_->IsOffTheRecord() &&
731 IsManuallyEditingAnySection() &&
732 !ShouldShowSpinner();
735 bool AutofillDialogControllerImpl::ShouldSaveInChrome() const {
736 return profile_->GetPrefs()->GetBoolean(::prefs::kAutofillDialogSaveData);
739 int AutofillDialogControllerImpl::GetDialogButtons() const {
740 if (waiting_for_explicit_sign_in_response_)
741 return ui::DIALOG_BUTTON_NONE;
743 if (ShouldShowSpinner() && !handling_use_wallet_link_click_)
744 return ui::DIALOG_BUTTON_CANCEL;
746 return ui::DIALOG_BUTTON_OK | ui::DIALOG_BUTTON_CANCEL;
749 bool AutofillDialogControllerImpl::IsDialogButtonEnabled(
750 ui::DialogButton button) const {
751 if (button == ui::DIALOG_BUTTON_OK) {
752 if (IsSubmitPausedOn(wallet::VERIFY_CVV))
755 if (ShouldShowSpinner() || is_submitting_)
758 if (submit_button_delay_timer_.IsRunning())
764 DCHECK_EQ(ui::DIALOG_BUTTON_CANCEL, button);
765 return !is_submitting_ || IsSubmitPausedOn(wallet::VERIFY_CVV);
768 DialogOverlayState AutofillDialogControllerImpl::GetDialogOverlay() {
769 bool show_wallet_interstitial = IsPayingWithWallet() && is_submitting_ &&
770 !(full_wallet_ && !full_wallet_->required_actions().empty());
771 if (!show_wallet_interstitial) {
772 card_scrambling_delay_.Stop();
773 card_scrambling_refresher_.Stop();
774 return DialogOverlayState();
777 ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance();
778 DialogOverlayState state;
779 state.string.font = rb.GetFont(ui::ResourceBundle::BaseFont).DeriveFont(3);
781 const SkColor start_top_color = SkColorSetRGB(0xD6, 0xD6, 0xD6);
782 const SkColor start_bottom_color = SkColorSetRGB(0x98, 0x98, 0x98);
783 const SkColor final_top_color = SkColorSetRGB(0x52, 0x9F, 0xF8);
784 const SkColor final_bottom_color = SkColorSetRGB(0x22, 0x75, 0xE5);
786 if (full_wallet_ && full_wallet_->required_actions().empty()) {
787 card_scrambling_delay_.Stop();
788 card_scrambling_refresher_.Stop();
790 base::string16 cc_number =
791 full_wallet_->GetInfo(AutofillType(CREDIT_CARD_NUMBER));
792 DCHECK_GE(cc_number.size(), 4U);
793 state.image = GetGeneratedCardImage(
794 base::ASCIIToUTF16("XXXX XXXX XXXX ") +
795 cc_number.substr(cc_number.size() - 4),
796 full_wallet_->billing_address()->recipient_name(),
797 color_utils::AlphaBlend(
800 255 * card_generated_animation_.GetCurrentValue()),
801 color_utils::AlphaBlend(
804 255 * card_generated_animation_.GetCurrentValue()));
806 state.string.text = l10n_util::GetStringUTF16(
807 IDS_AUTOFILL_DIALOG_CARD_GENERATION_DONE);
809 // Start the refresher if it isn't running. Wait one second before pumping
810 // updates to the view.
811 if (!card_scrambling_delay_.IsRunning() &&
812 !card_scrambling_refresher_.IsRunning()) {
813 scrambled_card_number_ = GenerateRandomCardNumber();
814 card_scrambling_delay_.Start(
816 base::TimeDelta::FromSeconds(1),
818 &AutofillDialogControllerImpl::StartCardScramblingRefresher);
821 DCHECK(!scrambled_card_number_.empty());
822 state.image = GetGeneratedCardImage(
823 scrambled_card_number_,
824 submitted_cardholder_name_,
828 // "Submitting" waiting page.
829 state.string.text = l10n_util::GetStringUTF16(
830 IDS_AUTOFILL_DIALOG_CARD_GENERATION_IN_PROGRESS);
836 const std::vector<gfx::Range>& AutofillDialogControllerImpl::
837 LegalDocumentLinks() {
838 return legal_document_link_ranges_;
841 bool AutofillDialogControllerImpl::SectionIsActive(DialogSection section)
843 if (IsSubmitPausedOn(wallet::VERIFY_CVV))
844 return section == SECTION_CC_BILLING;
846 if (!FormStructureCaresAboutSection(section))
849 if (IsPayingWithWallet())
850 return section == SECTION_CC_BILLING || section == SECTION_SHIPPING;
852 return section != SECTION_CC_BILLING;
855 void AutofillDialogControllerImpl::GetWalletItems() {
856 ScopedViewUpdates updates(view_.get());
858 wallet_items_requested_ = true;
859 wallet::WalletClient* wallet_client = GetWalletClient();
860 wallet_client->CancelRequest();
862 previously_selected_instrument_id_.clear();
863 previously_selected_shipping_address_id_.clear();
865 previous_default_instrument_id_ = wallet_items_->default_instrument_id();
866 previous_default_shipping_address_id_ = wallet_items_->default_address_id();
868 const wallet::WalletItems::MaskedInstrument* instrument =
871 previously_selected_instrument_id_ = instrument->object_id();
873 const wallet::Address* address = ActiveShippingAddress();
875 previously_selected_shipping_address_id_ = address->object_id();
878 last_wallet_items_fetch_timestamp_ = base::TimeTicks::Now();
879 passive_failed_ = false;
880 wallet_items_.reset();
882 // The "Loading..." page should be showing now, which should cause the
883 // account chooser to hide.
884 view_->UpdateAccountChooser();
885 wallet_client->GetWalletItems();
888 void AutofillDialogControllerImpl::HideSignIn() {
889 ScopedViewUpdates updates(view_.get());
890 signin_registrar_.RemoveAll();
892 view_->UpdateAccountChooser();
895 AutofillDialogControllerImpl::DialogSignedInState
896 AutofillDialogControllerImpl::SignedInState() const {
897 if (wallet_error_notification_)
898 return SIGN_IN_DISABLED;
900 if (signin_helper_ || (wallet_items_requested_ && !wallet_items_))
901 return REQUIRES_RESPONSE;
903 if (!wallet_items_requested_)
906 if (wallet_items_->HasRequiredAction(wallet::GAIA_AUTH) ||
908 return REQUIRES_SIGN_IN;
911 if (wallet_items_->HasRequiredAction(wallet::PASSIVE_GAIA_AUTH))
912 return REQUIRES_PASSIVE_SIGN_IN;
917 void AutofillDialogControllerImpl::SignedInStateUpdated() {
918 if (!ShouldShowSpinner())
919 waiting_for_explicit_sign_in_response_ = false;
921 switch (SignedInState()) {
923 LogDialogLatencyToShow();
926 case REQUIRES_SIGN_IN:
927 if (handling_use_wallet_link_click_)
930 case SIGN_IN_DISABLED:
931 // Switch to the local account and refresh the dialog.
932 signin_helper_.reset();
933 OnWalletSigninError();
934 handling_use_wallet_link_click_ = false;
937 case REQUIRES_PASSIVE_SIGN_IN:
938 // Attempt to passively sign in the user.
939 DCHECK(!signin_helper_);
940 signin_helper_.reset(new wallet::WalletSigninHelper(
942 profile_->GetRequestContext()));
943 signin_helper_->StartPassiveSignin(GetWalletClient()->user_index());
947 case REQUIRES_RESPONSE:
952 void AutofillDialogControllerImpl::OnWalletOrSigninUpdate() {
953 ScopedViewUpdates updates(view_.get());
954 SignedInStateUpdated();
955 SuggestionsUpdated();
956 UpdateAccountChooserView();
959 view_->UpdateButtonStrip();
960 view_->UpdateOverlay();
963 // On the first successful response, compute the initial user state metric.
964 if (initial_user_state_ == AutofillMetrics::DIALOG_USER_STATE_UNKNOWN)
965 initial_user_state_ = GetInitialUserState();
968 void AutofillDialogControllerImpl::OnWalletFormFieldError(
969 const std::vector<wallet::FormFieldError>& form_field_errors) {
970 if (form_field_errors.empty())
973 for (std::vector<wallet::FormFieldError>::const_iterator it =
974 form_field_errors.begin();
975 it != form_field_errors.end(); ++it) {
976 if (it->error_type() == wallet::FormFieldError::UNKNOWN_ERROR ||
977 it->GetAutofillType() == MAX_VALID_FIELD_TYPE ||
978 it->location() == wallet::FormFieldError::UNKNOWN_LOCATION) {
979 wallet_server_validation_recoverable_ = false;
982 DialogSection section = SectionFromLocation(it->location());
983 wallet_errors_[section][it->GetAutofillType()] =
984 std::make_pair(it->GetErrorMessage(),
985 GetValueFromSection(section, it->GetAutofillType()));
988 // Unrecoverable validation errors.
989 if (!wallet_server_validation_recoverable_)
990 DisableWallet(wallet::WalletClient::UNKNOWN_ERROR);
995 void AutofillDialogControllerImpl::ConstructLegalDocumentsText() {
996 legal_documents_text_.clear();
997 legal_document_link_ranges_.clear();
1002 PrefService* local_state = g_browser_process->local_state();
1003 // List of users who have accepted location sharing for fraud protection
1005 const base::ListValue* accepted =
1006 local_state->GetList(::prefs::kAutofillDialogWalletLocationAcceptance);
1007 bool has_accepted_location_sharing =
1008 accepted->Find(base::StringValue(
1009 account_chooser_model_->GetActiveWalletAccountName())) !=
1012 if (wallet_items_->legal_documents().empty()) {
1013 if (!has_accepted_location_sharing) {
1014 legal_documents_text_ = l10n_util::GetStringUTF16(
1015 IDS_AUTOFILL_DIALOG_LOCATION_DISCLOSURE);
1021 const std::vector<wallet::WalletItems::LegalDocument*>& documents =
1022 wallet_items_->legal_documents();
1023 // There should never be just one document because the privacy policy doc gets
1024 // tacked on the end of other documents.
1025 DCHECK_GE(documents.size(), 2U);
1027 std::vector<base::string16> link_names;
1028 for (size_t i = 0; i < documents.size(); ++i) {
1029 link_names.push_back(documents[i]->display_name());
1032 int resource_id = 0;
1033 switch (documents.size()) {
1035 resource_id = IDS_AUTOFILL_DIALOG_LEGAL_LINKS_2;
1038 resource_id = IDS_AUTOFILL_DIALOG_LEGAL_LINKS_3;
1041 resource_id = IDS_AUTOFILL_DIALOG_LEGAL_LINKS_4;
1044 resource_id = IDS_AUTOFILL_DIALOG_LEGAL_LINKS_5;
1047 resource_id = IDS_AUTOFILL_DIALOG_LEGAL_LINKS_6;
1050 // We can only handle so many documents. For lack of a better way of
1051 // handling document overflow, just error out if there are too many.
1052 DisableWallet(wallet::WalletClient::UNKNOWN_ERROR);
1056 std::vector<size_t> offsets;
1057 base::string16 text =
1058 l10n_util::GetStringFUTF16(resource_id, link_names,&offsets);
1060 // Tack on the location string if need be.
1061 size_t base_offset = 0;
1062 if (!has_accepted_location_sharing) {
1063 text = l10n_util::GetStringFUTF16(
1064 IDS_AUTOFILL_DIALOG_LOCATION_DISCLOSURE_WITH_LEGAL_DOCS,
1069 for (size_t i = 0; i < documents.size(); ++i) {
1070 size_t link_start = offsets[i] + base_offset;
1071 legal_document_link_ranges_.push_back(gfx::Range(
1072 link_start, link_start + documents[i]->display_name().size()));
1074 legal_documents_text_ = text;
1077 void AutofillDialogControllerImpl::ResetSectionInput(DialogSection section) {
1078 SetEditingExistingData(section, false);
1080 if (i18ninput::Enabled()) {
1081 CountryComboboxModel* model = CountryComboboxModelForSection(section);
1083 base::string16 country = model->GetItemAt(model->GetDefaultIndex());
1084 RebuildInputsForCountry(section, country, false);
1088 DetailInputs* inputs = MutableRequestedFieldsForSection(section);
1089 for (DetailInputs::iterator it = inputs->begin(); it != inputs->end(); ++it) {
1090 it->initial_value = common::GetHardcodedValueForType(it->type);
1094 void AutofillDialogControllerImpl::ShowEditUiIfBadSuggestion(
1095 DialogSection section) {
1096 // |CreateWrapper()| returns an empty wrapper if |IsEditingExistingData()|, so
1097 // get the wrapper before this potentially happens below.
1098 scoped_ptr<DataModelWrapper> wrapper = CreateWrapper(section);
1100 // If the chosen item in |model| yields an empty suggestion text, it is
1101 // invalid. In this case, show the edit UI and highlight invalid fields.
1102 SuggestionsMenuModel* model = SuggestionsMenuModelForSection(section);
1103 base::string16 unused, unused2;
1104 if (IsASuggestionItemKey(model->GetItemKeyForCheckedItem()) &&
1105 !SuggestionTextForSection(section, &unused, &unused2)) {
1106 SetEditingExistingData(section, true);
1109 if (wrapper && IsEditingExistingData(section)) {
1110 base::string16 country =
1111 wrapper->GetInfo(AutofillType(CountryTypeForSection(section)));
1112 if (!country.empty()) {
1113 // There's no user input to restore here as this is only called after
1114 // resetting all section input.
1115 if (RebuildInputsForCountry(section, country, false))
1116 UpdateSection(section);
1118 wrapper->FillInputs(MutableRequestedFieldsForSection(section));
1122 bool AutofillDialogControllerImpl::InputWasEdited(ServerFieldType type,
1123 const base::string16& value) {
1127 // If this is a combobox at the default value, don't preserve it.
1128 ui::ComboboxModel* model = ComboboxModelForAutofillType(type);
1129 if (model && model->GetItemAt(model->GetDefaultIndex()) == value)
1135 FieldValueMap AutofillDialogControllerImpl::TakeUserInputSnapshot() {
1136 FieldValueMap snapshot;
1140 for (size_t i = SECTION_MIN; i <= SECTION_MAX; ++i) {
1141 DialogSection section = static_cast<DialogSection>(i);
1142 SuggestionsMenuModel* model = SuggestionsMenuModelForSection(section);
1143 if (model->GetItemKeyForCheckedItem() != kAddNewItemKey)
1146 FieldValueMap outputs;
1147 view_->GetUserInput(section, &outputs);
1148 // Remove fields that are empty, at their default values, or invalid.
1149 for (FieldValueMap::iterator it = outputs.begin(); it != outputs.end();
1151 if (InputWasEdited(it->first, it->second) &&
1152 InputValidityMessage(section, it->first, it->second).empty()) {
1153 snapshot.insert(std::make_pair(it->first, it->second));
1161 void AutofillDialogControllerImpl::RestoreUserInputFromSnapshot(
1162 const FieldValueMap& snapshot) {
1163 if (snapshot.empty())
1166 FieldMapWrapper wrapper(snapshot);
1167 for (size_t i = SECTION_MIN; i <= SECTION_MAX; ++i) {
1168 DialogSection section = static_cast<DialogSection>(i);
1169 if (!SectionIsActive(section))
1172 DetailInputs* inputs = MutableRequestedFieldsForSection(section);
1173 wrapper.FillInputs(inputs);
1175 for (size_t i = 0; i < inputs->size(); ++i) {
1176 if (InputWasEdited((*inputs)[i].type, (*inputs)[i].initial_value)) {
1177 SuggestionsMenuModelForSection(section)->SetCheckedItem(kAddNewItemKey);
1184 void AutofillDialogControllerImpl::UpdateSection(DialogSection section) {
1186 view_->UpdateSection(section);
1189 void AutofillDialogControllerImpl::UpdateForErrors() {
1193 // Currently, the view should only need to be updated if there are
1194 // |wallet_errors_| or validating a suggestion that's based on existing data.
1195 bool should_update = !wallet_errors_.empty();
1196 if (!should_update) {
1197 for (size_t i = SECTION_MIN; i <= SECTION_MAX; ++i) {
1198 if (IsEditingExistingData(static_cast<DialogSection>(i))) {
1199 should_update = true;
1206 view_->UpdateForErrors();
1209 gfx::Image AutofillDialogControllerImpl::GetGeneratedCardImage(
1210 const base::string16& card_number,
1211 const base::string16& name,
1212 const SkColor& gradient_top,
1213 const SkColor& gradient_bottom) {
1214 const int kCardWidthPx = 300;
1215 const int kCardHeightPx = 190;
1216 const gfx::Size size(kCardWidthPx, kCardHeightPx);
1217 ui::ScaleFactor scale_factor = ui::GetScaleFactorForNativeView(
1218 web_contents()->GetView()->GetNativeView());
1219 gfx::Canvas canvas(size, ui::GetImageScale(scale_factor), false);
1221 gfx::Rect display_rect(size);
1223 skia::RefPtr<SkShader> shader = gfx::CreateGradientShader(
1224 0, size.height(), gradient_top, gradient_bottom);
1226 paint.setShader(shader.get());
1227 canvas.DrawRoundRect(display_rect, 8, paint);
1229 display_rect.Inset(20, 0, 0, 0);
1230 gfx::Font font(l10n_util::GetStringUTF8(IDS_FIXED_FONT_FAMILY), 18);
1231 gfx::FontList font_list(font);
1232 gfx::ShadowValues shadows;
1233 shadows.push_back(gfx::ShadowValue(gfx::Point(0, 1), 1.0, SK_ColorBLACK));
1234 canvas.DrawStringRectWithShadows(
1238 display_rect, 0, 0, shadows);
1240 base::string16 capitalized_name = base::i18n::ToUpper(name);
1241 display_rect.Inset(0, size.height() / 2, 0, 0);
1242 canvas.DrawStringRectWithShadows(
1246 display_rect, 0, 0, shadows);
1248 gfx::ImageSkia skia(canvas.ExtractImageRep());
1249 return gfx::Image(skia);
1252 void AutofillDialogControllerImpl::StartCardScramblingRefresher() {
1253 RefreshCardScramblingOverlay();
1254 card_scrambling_refresher_.Start(
1256 base::TimeDelta::FromMilliseconds(75),
1258 &AutofillDialogControllerImpl::RefreshCardScramblingOverlay);
1261 void AutofillDialogControllerImpl::RefreshCardScramblingOverlay() {
1262 scrambled_card_number_ = GenerateRandomCardNumber();
1263 PushOverlayUpdate();
1266 void AutofillDialogControllerImpl::PushOverlayUpdate() {
1268 ScopedViewUpdates updates(view_.get());
1269 view_->UpdateOverlay();
1273 const DetailInputs& AutofillDialogControllerImpl::RequestedFieldsForSection(
1274 DialogSection section) const {
1277 return requested_cc_fields_;
1278 case SECTION_BILLING:
1279 return requested_billing_fields_;
1280 case SECTION_CC_BILLING:
1281 return requested_cc_billing_fields_;
1282 case SECTION_SHIPPING:
1283 return requested_shipping_fields_;
1287 return requested_billing_fields_;
1290 ui::ComboboxModel* AutofillDialogControllerImpl::ComboboxModelForAutofillType(
1291 ServerFieldType type) {
1293 case CREDIT_CARD_EXP_MONTH:
1294 return &cc_exp_month_combobox_model_;
1296 case CREDIT_CARD_EXP_4_DIGIT_YEAR:
1297 return &cc_exp_year_combobox_model_;
1299 case ADDRESS_BILLING_COUNTRY:
1300 return &billing_country_combobox_model_;
1302 case ADDRESS_HOME_COUNTRY:
1303 return &shipping_country_combobox_model_;
1310 ui::MenuModel* AutofillDialogControllerImpl::MenuModelForSection(
1311 DialogSection section) {
1312 SuggestionsMenuModel* model = SuggestionsMenuModelForSection(section);
1313 // The shipping section menu is special. It will always show because there is
1314 // a choice between "Use billing" and "enter new".
1315 if (section == SECTION_SHIPPING)
1318 // For other sections, only show a menu if there's at least one suggestion.
1319 for (int i = 0; i < model->GetItemCount(); ++i) {
1320 if (IsASuggestionItemKey(model->GetItemKeyAt(i)))
1327 ui::MenuModel* AutofillDialogControllerImpl::MenuModelForAccountChooser() {
1328 // If there were unrecoverable Wallet errors, or if there are choices other
1329 // than "Pay without the wallet", show the full menu.
1330 // TODO(estade): this can present a braindead menu (only 1 option) when
1331 // there's a wallet error.
1332 if (wallet_error_notification_ ||
1333 (SignedInState() == SIGNED_IN &&
1334 account_chooser_model_->HasAccountsToChoose() &&
1335 !ShouldShowSignInWebView())) {
1336 return account_chooser_model_.get();
1339 // Otherwise, there is no menu, just a sign in link.
1343 gfx::Image AutofillDialogControllerImpl::AccountChooserImage() {
1344 if (!MenuModelForAccountChooser() && !ShouldShowSignInWebView()) {
1345 return ui::ResourceBundle::GetSharedInstance().GetImageNamed(
1349 return gfx::Image();
1352 gfx::Image AutofillDialogControllerImpl::ButtonStripImage() const {
1353 if (IsPayingWithWallet()) {
1354 return ui::ResourceBundle::GetSharedInstance().GetImageNamed(
1358 return gfx::Image();
1361 base::string16 AutofillDialogControllerImpl::LabelForSection(
1362 DialogSection section) const {
1365 return l10n_util::GetStringUTF16(IDS_AUTOFILL_DIALOG_SECTION_CC);
1366 case SECTION_BILLING:
1367 case SECTION_CC_BILLING:
1368 return l10n_util::GetStringUTF16(IDS_AUTOFILL_DIALOG_SECTION_BILLING);
1369 case SECTION_SHIPPING:
1370 return l10n_util::GetStringUTF16(IDS_AUTOFILL_DIALOG_SECTION_SHIPPING);
1373 return base::string16();
1376 SuggestionState AutofillDialogControllerImpl::SuggestionStateForSection(
1377 DialogSection section) {
1378 base::string16 vertically_compact, horizontally_compact;
1379 bool show_suggestion = SuggestionTextForSection(section,
1380 &vertically_compact,
1381 &horizontally_compact);
1382 return SuggestionState(show_suggestion,
1384 horizontally_compact,
1385 SuggestionIconForSection(section),
1386 ExtraSuggestionTextForSection(section),
1387 ExtraSuggestionIconForSection(section));
1390 bool AutofillDialogControllerImpl::SuggestionTextForSection(
1391 DialogSection section,
1392 base::string16* vertically_compact,
1393 base::string16* horizontally_compact) {
1394 base::string16 action_text = RequiredActionTextForSection(section);
1395 if (!action_text.empty()) {
1396 *vertically_compact = *horizontally_compact = action_text;
1400 // When the user has clicked 'edit' or a suggestion is somehow invalid (e.g. a
1401 // user selects a credit card that has expired), don't show a suggestion (even
1402 // though there is a profile selected in the model).
1403 if (IsEditingExistingData(section))
1406 SuggestionsMenuModel* model = SuggestionsMenuModelForSection(section);
1407 std::string item_key = model->GetItemKeyForCheckedItem();
1408 if (item_key == kSameAsBillingKey) {
1409 *vertically_compact = *horizontally_compact = l10n_util::GetStringUTF16(
1410 IDS_AUTOFILL_DIALOG_USING_BILLING_FOR_SHIPPING);
1414 if (!IsASuggestionItemKey(item_key))
1417 scoped_ptr<DataModelWrapper> wrapper = CreateWrapper(section);
1418 return wrapper->GetDisplayText(vertically_compact, horizontally_compact);
1421 base::string16 AutofillDialogControllerImpl::RequiredActionTextForSection(
1422 DialogSection section) const {
1423 if (section == SECTION_CC_BILLING && IsSubmitPausedOn(wallet::VERIFY_CVV)) {
1424 const wallet::WalletItems::MaskedInstrument* current_instrument =
1425 wallet_items_->GetInstrumentById(active_instrument_id_);
1426 if (current_instrument)
1427 return current_instrument->TypeAndLastFourDigits();
1429 FieldValueMap output;
1430 view_->GetUserInput(section, &output);
1432 GetBillingInfoFromOutputs(output, &card, NULL, NULL);
1433 return card.TypeAndLastFourDigits();
1436 return base::string16();
1439 base::string16 AutofillDialogControllerImpl::ExtraSuggestionTextForSection(
1440 DialogSection section) const {
1441 if (section == SECTION_CC ||
1442 (section == SECTION_CC_BILLING && IsSubmitPausedOn(wallet::VERIFY_CVV))) {
1443 return l10n_util::GetStringUTF16(IDS_AUTOFILL_DIALOG_PLACEHOLDER_CVC);
1446 return base::string16();
1449 const wallet::WalletItems::MaskedInstrument* AutofillDialogControllerImpl::
1450 ActiveInstrument() const {
1451 if (!IsPayingWithWallet())
1454 const SuggestionsMenuModel* model =
1455 SuggestionsMenuModelForSection(SECTION_CC_BILLING);
1456 const std::string item_key = model->GetItemKeyForCheckedItem();
1457 if (!IsASuggestionItemKey(item_key))
1461 if (!base::StringToInt(item_key, &index) || index < 0 ||
1462 static_cast<size_t>(index) >= wallet_items_->instruments().size()) {
1467 return wallet_items_->instruments()[index];
1470 const wallet::Address* AutofillDialogControllerImpl::
1471 ActiveShippingAddress() const {
1472 if (!IsPayingWithWallet() || !IsShippingAddressRequired())
1475 const SuggestionsMenuModel* model =
1476 SuggestionsMenuModelForSection(SECTION_SHIPPING);
1477 const std::string item_key = model->GetItemKeyForCheckedItem();
1478 if (!IsASuggestionItemKey(item_key))
1482 if (!base::StringToInt(item_key, &index) || index < 0 ||
1483 static_cast<size_t>(index) >= wallet_items_->addresses().size()) {
1488 return wallet_items_->addresses()[index];
1491 scoped_ptr<DataModelWrapper> AutofillDialogControllerImpl::CreateWrapper(
1492 DialogSection section) {
1493 if (IsPayingWithWallet() && full_wallet_ &&
1494 full_wallet_->required_actions().empty()) {
1495 if (section == SECTION_CC_BILLING) {
1496 return scoped_ptr<DataModelWrapper>(
1497 new FullWalletBillingWrapper(full_wallet_.get()));
1499 if (section == SECTION_SHIPPING) {
1500 return scoped_ptr<DataModelWrapper>(
1501 new FullWalletShippingWrapper(full_wallet_.get()));
1505 SuggestionsMenuModel* model = SuggestionsMenuModelForSection(section);
1506 std::string item_key = model->GetItemKeyForCheckedItem();
1507 if (!IsASuggestionItemKey(item_key) || IsManuallyEditingSection(section))
1508 return scoped_ptr<DataModelWrapper>();
1510 if (IsPayingWithWallet()) {
1511 if (section == SECTION_CC_BILLING) {
1512 return scoped_ptr<DataModelWrapper>(
1513 new WalletInstrumentWrapper(ActiveInstrument()));
1516 if (section == SECTION_SHIPPING) {
1517 return scoped_ptr<DataModelWrapper>(
1518 new WalletAddressWrapper(ActiveShippingAddress()));
1521 return scoped_ptr<DataModelWrapper>();
1524 if (section == SECTION_CC) {
1525 CreditCard* card = GetManager()->GetCreditCardByGUID(item_key);
1527 return scoped_ptr<DataModelWrapper>(new AutofillCreditCardWrapper(card));
1530 AutofillProfile* profile = GetManager()->GetProfileByGUID(item_key);
1532 if (section == SECTION_SHIPPING) {
1533 return scoped_ptr<DataModelWrapper>(
1534 new AutofillShippingAddressWrapper(profile));
1536 DCHECK_EQ(SECTION_BILLING, section);
1537 return scoped_ptr<DataModelWrapper>(
1538 new AutofillProfileWrapper(profile));
1541 gfx::Image AutofillDialogControllerImpl::SuggestionIconForSection(
1542 DialogSection section) {
1543 scoped_ptr<DataModelWrapper> model = CreateWrapper(section);
1545 return gfx::Image();
1547 return model->GetIcon();
1550 gfx::Image AutofillDialogControllerImpl::ExtraSuggestionIconForSection(
1551 DialogSection section) {
1552 if (section != SECTION_CC && section != SECTION_CC_BILLING)
1553 return gfx::Image();
1555 scoped_ptr<DataModelWrapper> model = CreateWrapper(section);
1557 return gfx::Image();
1559 return CvcIconForCreditCardType(
1560 model->GetInfo(AutofillType(CREDIT_CARD_TYPE)));
1563 FieldIconMap AutofillDialogControllerImpl::IconsForFields(
1564 const FieldValueMap& user_inputs) const {
1565 FieldIconMap result;
1566 base::string16 credit_card_type;
1568 FieldValueMap::const_iterator credit_card_iter =
1569 user_inputs.find(CREDIT_CARD_NUMBER);
1570 if (credit_card_iter != user_inputs.end()) {
1571 const base::string16& number = credit_card_iter->second;
1572 const std::string type = CreditCard::GetCreditCardType(number);
1573 credit_card_type = CreditCard::TypeForDisplay(type);
1574 result[CREDIT_CARD_NUMBER] = CreditCardIconForType(type);
1577 if (!user_inputs.count(CREDIT_CARD_VERIFICATION_CODE))
1580 result[CREDIT_CARD_VERIFICATION_CODE] =
1581 CvcIconForCreditCardType(credit_card_type);
1586 bool AutofillDialogControllerImpl::FieldControlsIcons(
1587 ServerFieldType type) const {
1588 return type == CREDIT_CARD_NUMBER;
1591 base::string16 AutofillDialogControllerImpl::TooltipForField(
1592 ServerFieldType type) const {
1593 if (type == PHONE_HOME_WHOLE_NUMBER || type == PHONE_BILLING_WHOLE_NUMBER)
1594 return l10n_util::GetStringUTF16(IDS_AUTOFILL_DIALOG_TOOLTIP_PHONE_NUMBER);
1596 return base::string16();
1599 bool AutofillDialogControllerImpl::InputIsEditable(
1600 const DetailInput& input,
1601 DialogSection section) {
1602 if (section != SECTION_CC_BILLING)
1605 if (input.type == CREDIT_CARD_NUMBER)
1606 return !IsEditingExistingData(section);
1608 // For CVC, only require (allow) input if the user has edited some other
1609 // aspect of the card.
1610 if (input.type == CREDIT_CARD_VERIFICATION_CODE &&
1611 IsEditingExistingData(section)) {
1612 FieldValueMap output;
1613 view_->GetUserInput(section, &output);
1614 WalletInstrumentWrapper wrapper(ActiveInstrument());
1616 for (FieldValueMap::iterator iter = output.begin(); iter != output.end();
1618 if (iter->first == input.type)
1621 AutofillType type(iter->first);
1622 if (type.group() == CREDIT_CARD &&
1623 iter->second != wrapper.GetInfo(type)) {
1634 // TODO(groby): Add more tests.
1635 base::string16 AutofillDialogControllerImpl::InputValidityMessage(
1636 DialogSection section,
1637 ServerFieldType type,
1638 const base::string16& value) {
1639 // If the field is edited, clear any Wallet errors.
1640 if (IsPayingWithWallet()) {
1641 WalletValidationErrors::iterator it = wallet_errors_.find(section);
1642 if (it != wallet_errors_.end()) {
1643 TypeErrorInputMap::const_iterator iter = it->second.find(type);
1644 if (iter != it->second.end()) {
1645 if (iter->second.second == value)
1646 return iter->second.first;
1647 it->second.erase(type);
1652 switch (AutofillType(type).GetStorableType()) {
1654 if (!value.empty() && !IsValidEmailAddress(value)) {
1655 return l10n_util::GetStringUTF16(
1656 IDS_AUTOFILL_DIALOG_VALIDATION_INVALID_EMAIL_ADDRESS);
1660 case CREDIT_CARD_NUMBER: {
1661 if (!value.empty()) {
1662 base::string16 message = CreditCardNumberValidityMessage(value);
1663 if (!message.empty())
1669 case CREDIT_CARD_EXP_MONTH:
1670 if (!InputWasEdited(CREDIT_CARD_EXP_MONTH, value)) {
1671 return l10n_util::GetStringUTF16(
1672 IDS_AUTOFILL_DIALOG_VALIDATION_MISSING_VALUE);
1676 case CREDIT_CARD_EXP_4_DIGIT_YEAR:
1677 if (!InputWasEdited(CREDIT_CARD_EXP_4_DIGIT_YEAR, value)) {
1678 return l10n_util::GetStringUTF16(
1679 IDS_AUTOFILL_DIALOG_VALIDATION_MISSING_VALUE);
1683 case CREDIT_CARD_VERIFICATION_CODE:
1684 if (!value.empty() && !autofill::IsValidCreditCardSecurityCode(value)) {
1685 return l10n_util::GetStringUTF16(
1686 IDS_AUTOFILL_DIALOG_VALIDATION_INVALID_CREDIT_CARD_SECURITY_CODE);
1690 case ADDRESS_HOME_LINE1:
1693 case ADDRESS_HOME_LINE2:
1694 case ADDRESS_HOME_DEPENDENT_LOCALITY:
1695 case ADDRESS_HOME_SORTING_CODE:
1696 return base::string16(); // Optional until we have better validation.
1698 case ADDRESS_HOME_CITY:
1699 case ADDRESS_HOME_COUNTRY:
1702 case ADDRESS_HOME_STATE:
1703 if (!value.empty() && !autofill::IsValidState(value) &&
1704 CountryCodeForSection(section) == "US") {
1705 return l10n_util::GetStringUTF16(
1706 IDS_AUTOFILL_DIALOG_VALIDATION_INVALID_REGION);
1710 case ADDRESS_HOME_ZIP:
1711 if (!value.empty() && !autofill::IsValidZip(value) &&
1712 CountryCodeForSection(section) == "US") {
1713 return l10n_util::GetStringUTF16(
1714 IDS_AUTOFILL_DIALOG_VALIDATION_INVALID_ZIP_CODE);
1719 // Wallet requires a first and last billing name.
1720 if (section == SECTION_CC_BILLING && !value.empty() &&
1721 !IsCardHolderNameValidForWallet(value)) {
1722 DCHECK(IsPayingWithWallet());
1723 return l10n_util::GetStringUTF16(
1724 IDS_AUTOFILL_DIALOG_VALIDATION_WALLET_REQUIRES_TWO_NAMES);
1728 case PHONE_HOME_WHOLE_NUMBER: // Used in shipping section.
1731 case PHONE_BILLING_WHOLE_NUMBER: // Used in billing section.
1735 NOTREACHED(); // Trying to validate unknown field.
1739 return value.empty() ?
1740 l10n_util::GetStringUTF16(IDS_AUTOFILL_DIALOG_VALIDATION_MISSING_VALUE) :
1744 // TODO(groby): Also add tests.
1745 ValidityMessages AutofillDialogControllerImpl::InputsAreValid(
1746 DialogSection section,
1747 const FieldValueMap& inputs) {
1748 ValidityMessages messages;
1749 FieldValueMap field_values;
1750 for (FieldValueMap::const_iterator iter = inputs.begin();
1751 iter != inputs.end(); ++iter) {
1752 const ServerFieldType type = iter->first;
1754 base::string16 text = InputValidityMessage(section, type, iter->second);
1756 // Skip empty/unchanged fields in edit mode. Ignore country as it always has
1757 // a value. If the individual field does not have validation errors, assume
1758 // it to be valid unless later proven otherwise.
1759 bool sure = InputWasEdited(type, iter->second) ||
1760 AutofillType(type).GetStorableType() == ADDRESS_HOME_COUNTRY;
1762 // Consider only individually valid fields for inter-field validation.
1764 field_values[type] = iter->second;
1765 // If the field is valid but can be invalidated by inter-field validation,
1766 // assume it to be unsure.
1767 if (type == CREDIT_CARD_EXP_4_DIGIT_YEAR ||
1768 type == CREDIT_CARD_EXP_MONTH ||
1769 type == CREDIT_CARD_VERIFICATION_CODE ||
1770 type == PHONE_HOME_WHOLE_NUMBER ||
1771 type == PHONE_BILLING_WHOLE_NUMBER) {
1775 messages.Set(type, ValidityMessage(text, sure));
1778 // Validate the date formed by month and year field. (Autofill dialog is
1779 // never supposed to have 2-digit years, so not checked).
1780 if (field_values.count(CREDIT_CARD_EXP_4_DIGIT_YEAR) &&
1781 field_values.count(CREDIT_CARD_EXP_MONTH) &&
1782 InputWasEdited(CREDIT_CARD_EXP_4_DIGIT_YEAR,
1783 field_values[CREDIT_CARD_EXP_4_DIGIT_YEAR]) &&
1784 InputWasEdited(CREDIT_CARD_EXP_MONTH,
1785 field_values[CREDIT_CARD_EXP_MONTH])) {
1786 ValidityMessage year_message(base::string16(), true);
1787 ValidityMessage month_message(base::string16(), true);
1788 if (!IsCreditCardExpirationValid(field_values[CREDIT_CARD_EXP_4_DIGIT_YEAR],
1789 field_values[CREDIT_CARD_EXP_MONTH])) {
1790 // The dialog shows the same error message for the month and year fields.
1791 year_message.text = l10n_util::GetStringUTF16(
1792 IDS_AUTOFILL_DIALOG_VALIDATION_INVALID_CREDIT_CARD_EXPIRATION_DATE);
1793 month_message.text = l10n_util::GetStringUTF16(
1794 IDS_AUTOFILL_DIALOG_VALIDATION_INVALID_CREDIT_CARD_EXPIRATION_DATE);
1796 messages.Set(CREDIT_CARD_EXP_4_DIGIT_YEAR, year_message);
1797 messages.Set(CREDIT_CARD_EXP_MONTH, month_message);
1800 // If there is a credit card number and a CVC, validate them together.
1801 if (field_values.count(CREDIT_CARD_NUMBER) &&
1802 field_values.count(CREDIT_CARD_VERIFICATION_CODE)) {
1803 ValidityMessage ccv_message(base::string16(), true);
1804 if (!autofill::IsValidCreditCardSecurityCode(
1805 field_values[CREDIT_CARD_VERIFICATION_CODE],
1806 field_values[CREDIT_CARD_NUMBER])) {
1807 ccv_message.text = l10n_util::GetStringUTF16(
1808 IDS_AUTOFILL_DIALOG_VALIDATION_INVALID_CREDIT_CARD_SECURITY_CODE);
1810 messages.Set(CREDIT_CARD_VERIFICATION_CODE, ccv_message);
1813 // Validate the shipping phone number against the country code of the address.
1814 if (field_values.count(ADDRESS_HOME_COUNTRY) &&
1815 field_values.count(PHONE_HOME_WHOLE_NUMBER)) {
1816 i18n::PhoneObject phone_object(
1817 field_values[PHONE_HOME_WHOLE_NUMBER],
1818 AutofillCountry::GetCountryCode(
1819 field_values[ADDRESS_HOME_COUNTRY],
1820 g_browser_process->GetApplicationLocale()));
1821 ValidityMessage phone_message(base::string16(), true);
1822 if (!phone_object.IsValidNumber()) {
1823 phone_message.text = l10n_util::GetStringUTF16(
1824 IDS_AUTOFILL_DIALOG_VALIDATION_INVALID_PHONE_NUMBER);
1826 messages.Set(PHONE_HOME_WHOLE_NUMBER, phone_message);
1829 // Validate the billing phone number against the country code of the address.
1830 if (field_values.count(ADDRESS_BILLING_COUNTRY) &&
1831 field_values.count(PHONE_BILLING_WHOLE_NUMBER)) {
1832 i18n::PhoneObject phone_object(
1833 field_values[PHONE_BILLING_WHOLE_NUMBER],
1834 AutofillCountry::GetCountryCode(
1835 field_values[ADDRESS_BILLING_COUNTRY],
1836 g_browser_process->GetApplicationLocale()));
1837 ValidityMessage phone_message(base::string16(), true);
1838 if (!phone_object.IsValidNumber()) {
1839 phone_message.text = l10n_util::GetStringUTF16(
1840 IDS_AUTOFILL_DIALOG_VALIDATION_INVALID_PHONE_NUMBER);
1842 messages.Set(PHONE_BILLING_WHOLE_NUMBER, phone_message);
1848 void AutofillDialogControllerImpl::UserEditedOrActivatedInput(
1849 DialogSection section,
1850 ServerFieldType type,
1851 gfx::NativeView parent_view,
1852 const gfx::Rect& content_bounds,
1853 const base::string16& field_contents,
1855 ScopedViewUpdates updates(view_.get());
1857 if (type == ADDRESS_BILLING_COUNTRY || type == ADDRESS_HOME_COUNTRY) {
1858 const FieldValueMap snapshot = TakeUserInputSnapshot();
1859 // Clobber the inputs because the view's already been updated.
1860 RebuildInputsForCountry(section, field_contents, true);
1861 RestoreUserInputFromSnapshot(snapshot);
1862 UpdateSection(section);
1865 // The rest of this method applies only to textfields. If a combobox, bail.
1866 if (ComboboxModelForAutofillType(type))
1869 // If the field is edited down to empty, don't show a popup.
1870 if (was_edit && field_contents.empty()) {
1875 // If the user clicks while the popup is already showing, be sure to hide
1877 if (!was_edit && popup_controller_.get()) {
1882 std::vector<base::string16> popup_values, popup_labels, popup_icons;
1883 if (common::IsCreditCardType(type)) {
1884 GetManager()->GetCreditCardSuggestions(AutofillType(type),
1891 std::vector<ServerFieldType> field_types;
1892 const DetailInputs& inputs = RequestedFieldsForSection(section);
1893 for (DetailInputs::const_iterator iter = inputs.begin();
1894 iter != inputs.end(); ++iter) {
1895 field_types.push_back(iter->type);
1897 GetManager()->GetProfileSuggestions(AutofillType(type),
1907 if (popup_values.empty()) {
1912 // |popup_input_type_| must be set before calling |Show()|.
1913 popup_input_type_ = type;
1915 // TODO(estade): do we need separators and control rows like 'Clear
1917 std::vector<int> popup_ids;
1918 for (size_t i = 0; i < popup_guids_.size(); ++i) {
1919 popup_ids.push_back(i);
1922 popup_controller_ = AutofillPopupControllerImpl::GetOrCreate(
1924 weak_ptr_factory_.GetWeakPtr(),
1928 base::i18n::IsRTL() ?
1929 base::i18n::RIGHT_TO_LEFT : base::i18n::LEFT_TO_RIGHT);
1930 popup_controller_->set_hide_on_outside_click(true);
1931 popup_controller_->Show(popup_values,
1937 void AutofillDialogControllerImpl::FocusMoved() {
1941 bool AutofillDialogControllerImpl::ShouldShowErrorBubble() const {
1942 return popup_input_type_ == UNKNOWN_TYPE;
1945 void AutofillDialogControllerImpl::ViewClosed() {
1946 GetManager()->RemoveObserver(this);
1948 // Called from here rather than in ~AutofillDialogControllerImpl as this
1949 // relies on virtual methods that change to their base class in the dtor.
1950 MaybeShowCreditCardBubble();
1955 std::vector<DialogNotification> AutofillDialogControllerImpl::
1956 CurrentNotifications() {
1957 std::vector<DialogNotification> notifications;
1959 // TODO(dbeam): figure out a way to dismiss this error after a while.
1960 if (wallet_error_notification_)
1961 notifications.push_back(*wallet_error_notification_);
1963 if (IsSubmitPausedOn(wallet::VERIFY_CVV)) {
1964 notifications.push_back(DialogNotification(
1965 DialogNotification::REQUIRED_ACTION,
1966 l10n_util::GetStringUTF16(IDS_AUTOFILL_DIALOG_VERIFY_CVV)));
1969 if (!wallet_server_validation_recoverable_) {
1970 notifications.push_back(DialogNotification(
1971 DialogNotification::REQUIRED_ACTION,
1972 l10n_util::GetStringUTF16(
1973 IDS_AUTOFILL_DIALOG_FAILED_TO_SAVE_WALLET_DATA)));
1976 if (choose_another_instrument_or_address_) {
1977 notifications.push_back(DialogNotification(
1978 DialogNotification::REQUIRED_ACTION,
1979 l10n_util::GetStringUTF16(
1980 IDS_AUTOFILL_DIALOG_CHOOSE_DIFFERENT_WALLET_INSTRUMENT)));
1983 if (notifications.empty() && MenuModelForAccountChooser()) {
1984 base::string16 text = l10n_util::GetStringUTF16(
1985 IsManuallyEditingAnySection() ?
1986 IDS_AUTOFILL_DIALOG_SAVE_DETAILS_IN_WALLET :
1987 IDS_AUTOFILL_DIALOG_USE_WALLET);
1988 DialogNotification notification(
1989 DialogNotification::WALLET_USAGE_CONFIRMATION,
1991 notification.set_tooltip_text(
1992 l10n_util::GetStringUTF16(
1993 IDS_AUTOFILL_DIALOG_SAVE_IN_WALLET_TOOLTIP));
1994 notification.set_checked(IsPayingWithWallet());
1995 notifications.push_back(notification);
1998 if (IsPayingWithWallet() && !wallet::IsUsingProd()) {
1999 notifications.push_back(DialogNotification(
2000 DialogNotification::DEVELOPER_WARNING,
2001 l10n_util::GetStringUTF16(IDS_AUTOFILL_DIALOG_NOT_PROD_WARNING)));
2004 if (!invoked_from_same_origin_) {
2005 notifications.push_back(DialogNotification(
2006 DialogNotification::SECURITY_WARNING,
2007 l10n_util::GetStringFUTF16(IDS_AUTOFILL_DIALOG_SITE_WARNING,
2008 base::UTF8ToUTF16(source_url_.host()))));
2011 return notifications;
2014 void AutofillDialogControllerImpl::LinkClicked(const GURL& url) {
2015 OpenTabWithUrl(url);
2018 void AutofillDialogControllerImpl::SignInLinkClicked() {
2019 ScopedViewUpdates updates(view_.get());
2021 if (SignedInState() == NOT_CHECKED) {
2022 handling_use_wallet_link_click_ = true;
2023 account_chooser_model_->SelectWalletAccount(0);
2024 FetchWalletCookie();
2025 } else if (signin_registrar_.IsEmpty()) {
2027 waiting_for_explicit_sign_in_response_ = true;
2028 content::Source<content::NavigationController> source(view_->ShowSignIn());
2029 signin_registrar_.Add(
2030 this, content::NOTIFICATION_NAV_ENTRY_COMMITTED, source);
2032 GetMetricLogger().LogDialogUiEvent(
2033 AutofillMetrics::DIALOG_UI_SIGNIN_SHOWN);
2035 waiting_for_explicit_sign_in_response_ = false;
2039 view_->UpdateAccountChooser();
2040 view_->UpdateButtonStrip();
2043 void AutofillDialogControllerImpl::NotificationCheckboxStateChanged(
2044 DialogNotification::Type type, bool checked) {
2045 if (type == DialogNotification::WALLET_USAGE_CONFIRMATION) {
2047 account_chooser_model_->SelectWalletAccount(
2048 GetWalletClient()->user_index());
2050 account_chooser_model_->SelectUseAutofill();
2053 AccountChoiceChanged();
2057 void AutofillDialogControllerImpl::LegalDocumentLinkClicked(
2058 const gfx::Range& range) {
2059 for (size_t i = 0; i < legal_document_link_ranges_.size(); ++i) {
2060 if (legal_document_link_ranges_[i] == range) {
2061 OpenTabWithUrl(wallet_items_->legal_documents()[i]->url());
2069 bool AutofillDialogControllerImpl::OnCancel() {
2071 if (!is_submitting_)
2072 LogOnCancelMetrics();
2073 callback_.Run(NULL);
2077 bool AutofillDialogControllerImpl::OnAccept() {
2078 ScopedViewUpdates updates(view_.get());
2079 choose_another_instrument_or_address_ = false;
2080 wallet_server_validation_recoverable_ = true;
2083 // This must come before SetIsSubmitting().
2084 if (IsPayingWithWallet()) {
2085 // In the VERIFY_CVV case, hold onto the previously submitted cardholder
2087 if (!IsSubmitPausedOn(wallet::VERIFY_CVV)) {
2088 submitted_cardholder_name_ =
2089 GetValueFromSection(SECTION_CC_BILLING, NAME_BILLING_FULL);
2091 // Snag the last four digits of the backing card now as it could be wiped
2092 // out if a CVC challenge happens.
2093 if (ActiveInstrument()) {
2094 backing_card_last_four_ = ActiveInstrument()->TypeAndLastFourDigits();
2096 FieldValueMap output;
2097 view_->GetUserInput(SECTION_CC_BILLING, &output);
2099 GetBillingInfoFromOutputs(output, &card, NULL, NULL);
2100 backing_card_last_four_ = card.TypeAndLastFourDigits();
2103 DCHECK(!submitted_cardholder_name_.empty());
2104 DCHECK(!backing_card_last_four_.empty());
2107 SetIsSubmitting(true);
2109 if (IsSubmitPausedOn(wallet::VERIFY_CVV)) {
2110 DCHECK(!active_instrument_id_.empty());
2111 full_wallet_.reset();
2112 GetWalletClient()->AuthenticateInstrument(
2113 active_instrument_id_,
2114 base::UTF16ToUTF8(view_->GetCvc()));
2115 view_->UpdateOverlay();
2116 } else if (IsPayingWithWallet()) {
2125 Profile* AutofillDialogControllerImpl::profile() {
2129 content::WebContents* AutofillDialogControllerImpl::GetWebContents() {
2130 return web_contents();
2133 ////////////////////////////////////////////////////////////////////////////////
2134 // AutofillPopupDelegate implementation.
2136 void AutofillDialogControllerImpl::OnPopupShown() {
2137 ScopedViewUpdates update(view_.get());
2138 view_->UpdateErrorBubble();
2140 GetMetricLogger().LogDialogPopupEvent(AutofillMetrics::DIALOG_POPUP_SHOWN);
2143 void AutofillDialogControllerImpl::OnPopupHidden() {}
2145 bool AutofillDialogControllerImpl::ShouldRepostEvent(
2146 const ui::MouseEvent& event) {
2147 DCHECK_NE(UNKNOWN_TYPE, popup_input_type_);
2148 // If the event would be reposted inside the input showing an Autofill popup,
2150 return !view_->HitTestInput(popup_input_type_, event.location());
2153 void AutofillDialogControllerImpl::DidSelectSuggestion(int identifier) {
2154 // TODO(estade): implement.
2157 void AutofillDialogControllerImpl::DidAcceptSuggestion(
2158 const base::string16& value,
2160 DCHECK_NE(UNKNOWN_TYPE, popup_input_type_);
2161 // Because |HidePopup()| can be called from |UpdateSection()|, remember the
2162 // type of the input for later here.
2163 const ServerFieldType popup_input_type = popup_input_type_;
2165 ScopedViewUpdates updates(view_.get());
2166 const PersonalDataManager::GUIDPair& pair = popup_guids_[identifier];
2168 scoped_ptr<DataModelWrapper> wrapper;
2169 if (common::IsCreditCardType(popup_input_type)) {
2170 wrapper.reset(new AutofillCreditCardWrapper(
2171 GetManager()->GetCreditCardByGUID(pair.first)));
2173 wrapper.reset(new AutofillProfileWrapper(
2174 GetManager()->GetProfileByGUID(pair.first),
2175 AutofillType(popup_input_type),
2179 if (i18ninput::Enabled()) {
2180 // If the user hasn't switched away from the default country and |wrapper|'s
2181 // country differs from the |view_|'s, rebuild inputs and restore user data.
2182 const FieldValueMap snapshot = TakeUserInputSnapshot();
2183 bool billing_rebuilt = false, shipping_rebuilt = false;
2185 base::string16 billing_country =
2186 wrapper->GetInfo(AutofillType(ADDRESS_BILLING_COUNTRY));
2187 if (!snapshot.count(ADDRESS_BILLING_COUNTRY) &&
2188 !billing_country.empty()) {
2189 billing_rebuilt = RebuildInputsForCountry(
2190 ActiveBillingSection(), billing_country, false);
2193 base::string16 shipping_country =
2194 wrapper->GetInfo(AutofillType(ADDRESS_HOME_COUNTRY));
2195 if (!snapshot.count(ADDRESS_HOME_COUNTRY) &&
2196 !shipping_country.empty()) {
2197 shipping_rebuilt = RebuildInputsForCountry(
2198 SECTION_SHIPPING, shipping_country, false);
2201 if (billing_rebuilt || shipping_rebuilt) {
2202 RestoreUserInputFromSnapshot(snapshot);
2203 if (billing_rebuilt)
2204 UpdateSection(ActiveBillingSection());
2205 if (shipping_rebuilt)
2206 UpdateSection(SECTION_SHIPPING);
2210 for (size_t i = SECTION_MIN; i <= SECTION_MAX; ++i) {
2211 DialogSection section = static_cast<DialogSection>(i);
2212 if (!SectionIsActive(section))
2215 wrapper->FillInputs(MutableRequestedFieldsForSection(section));
2216 view_->FillSection(section, popup_input_type);
2219 GetMetricLogger().LogDialogPopupEvent(
2220 AutofillMetrics::DIALOG_POPUP_FORM_FILLED);
2222 // TODO(estade): not sure why it's necessary to do this explicitly.
2226 void AutofillDialogControllerImpl::RemoveSuggestion(
2227 const base::string16& value,
2229 // TODO(estade): implement.
2232 void AutofillDialogControllerImpl::ClearPreviewedForm() {
2233 // TODO(estade): implement.
2236 ////////////////////////////////////////////////////////////////////////////////
2237 // content::NotificationObserver implementation.
2239 void AutofillDialogControllerImpl::Observe(
2241 const content::NotificationSource& source,
2242 const content::NotificationDetails& details) {
2243 DCHECK_EQ(type, content::NOTIFICATION_NAV_ENTRY_COMMITTED);
2244 content::LoadCommittedDetails* load_details =
2245 content::Details<content::LoadCommittedDetails>(details).ptr();
2246 size_t user_index = 0;
2247 if (IsSignInContinueUrl(load_details->entry->GetVirtualURL(), &user_index)) {
2248 GetWalletClient()->SetUserIndex(user_index);
2249 FetchWalletCookie();
2251 // NOTE: |HideSignIn()| may delete the WebContents which doesn't expect to
2252 // be deleted while committing a nav entry. Just call |HideSignIn()| later.
2253 base::MessageLoop::current()->PostTask(FROM_HERE,
2254 base::Bind(&AutofillDialogControllerImpl::HideSignIn,
2255 base::Unretained(this)));
2259 ////////////////////////////////////////////////////////////////////////////////
2260 // SuggestionsMenuModelDelegate implementation.
2262 void AutofillDialogControllerImpl::SuggestionsMenuWillShow() {
2266 void AutofillDialogControllerImpl::SuggestionItemSelected(
2267 SuggestionsMenuModel* model,
2269 ScopedViewUpdates updates(view_.get());
2271 if (model->GetItemKeyAt(index) == kManageItemsKey) {
2273 if (!IsPayingWithWallet()) {
2274 GURL settings_url(chrome::kChromeUISettingsURL);
2275 url = settings_url.Resolve(chrome::kAutofillSubPage);
2277 // Reset |last_wallet_items_fetch_timestamp_| to ensure that the Wallet
2278 // data is refreshed as soon as the user switches back to this tab after
2279 // potentially editing his data.
2280 last_wallet_items_fetch_timestamp_ = base::TimeTicks();
2281 size_t user_index = GetWalletClient()->user_index();
2282 url = SectionForSuggestionsMenuModel(*model) == SECTION_SHIPPING ?
2283 wallet::GetManageAddressesUrl(user_index) :
2284 wallet::GetManageInstrumentsUrl(user_index);
2287 OpenTabWithUrl(url);
2291 model->SetCheckedIndex(index);
2292 DialogSection section = SectionForSuggestionsMenuModel(*model);
2294 ResetSectionInput(section);
2295 ShowEditUiIfBadSuggestion(section);
2296 UpdateSection(section);
2297 view_->UpdateNotificationArea();
2300 LogSuggestionItemSelectedMetric(*model);
2303 ////////////////////////////////////////////////////////////////////////////////
2304 // wallet::WalletClientDelegate implementation.
2306 const AutofillMetrics& AutofillDialogControllerImpl::GetMetricLogger() const {
2307 return metric_logger_;
2310 std::string AutofillDialogControllerImpl::GetRiskData() const {
2311 DCHECK(!risk_data_.empty());
2315 std::string AutofillDialogControllerImpl::GetWalletCookieValue() const {
2316 return wallet_cookie_value_;
2319 bool AutofillDialogControllerImpl::IsShippingAddressRequired() const {
2320 return cares_about_shipping_;
2323 void AutofillDialogControllerImpl::OnDidAcceptLegalDocuments() {
2324 DCHECK(is_submitting_ && IsPayingWithWallet());
2325 has_accepted_legal_documents_ = true;
2326 LoadRiskFingerprintData();
2329 void AutofillDialogControllerImpl::OnDidAuthenticateInstrument(bool success) {
2330 DCHECK(is_submitting_ && IsPayingWithWallet());
2332 // TODO(dbeam): use the returned full wallet. http://crbug.com/224992
2336 DisableWallet(wallet::WalletClient::UNKNOWN_ERROR);
2337 SuggestionsUpdated();
2341 void AutofillDialogControllerImpl::OnDidGetFullWallet(
2342 scoped_ptr<wallet::FullWallet> full_wallet) {
2343 DCHECK(is_submitting_ && IsPayingWithWallet());
2344 ScopedViewUpdates updates(view_.get());
2346 full_wallet_ = full_wallet.Pass();
2348 if (full_wallet_->required_actions().empty()) {
2353 switch (full_wallet_->required_actions()[0]) {
2354 case wallet::CHOOSE_ANOTHER_INSTRUMENT_OR_ADDRESS:
2355 choose_another_instrument_or_address_ = true;
2356 SetIsSubmitting(false);
2360 case wallet::VERIFY_CVV:
2361 SuggestionsUpdated();
2365 DisableWallet(wallet::WalletClient::UNKNOWN_ERROR);
2369 view_->UpdateNotificationArea();
2370 view_->UpdateButtonStrip();
2371 view_->UpdateOverlay();
2374 void AutofillDialogControllerImpl::OnPassiveSigninSuccess() {
2375 FetchWalletCookie();
2378 void AutofillDialogControllerImpl::OnPassiveSigninFailure(
2379 const GoogleServiceAuthError& error) {
2380 signin_helper_.reset();
2381 passive_failed_ = true;
2383 if (handling_use_wallet_link_click_ ||
2384 GetWalletClient()->user_index() != 0) {
2385 // TODO(estade): When a secondary account is selected and fails passive
2386 // auth, we show a sign in page. Currently we show the generic add account
2387 // page, but we should instead show sign in for the selected account.
2388 // http://crbug.com/323327
2389 SignInLinkClicked();
2390 handling_use_wallet_link_click_ = false;
2393 OnWalletSigninError();
2396 void AutofillDialogControllerImpl::OnDidFetchWalletCookieValue(
2397 const std::string& cookie_value) {
2398 wallet_cookie_value_ = cookie_value;
2399 signin_helper_.reset();
2403 void AutofillDialogControllerImpl::OnDidGetWalletItems(
2404 scoped_ptr<wallet::WalletItems> wallet_items) {
2405 legal_documents_text_.clear();
2406 legal_document_link_ranges_.clear();
2407 has_accepted_legal_documents_ = false;
2409 wallet_items_ = wallet_items.Pass();
2411 if (wallet_items_ && !wallet_items_->ObfuscatedGaiaId().empty()) {
2412 // Making sure the user index is in sync shouldn't be necessary, but is an
2413 // extra precaution. But if there is no active account (such as in the
2414 // PASSIVE_AUTH case), stick with the old active account.
2415 GetWalletClient()->SetUserIndex(wallet_items_->active_account_index());
2417 std::vector<std::string> usernames;
2418 for (size_t i = 0; i < wallet_items_->gaia_accounts().size(); ++i) {
2419 usernames.push_back(wallet_items_->gaia_accounts()[i]->email_address());
2421 account_chooser_model_->SetWalletAccounts(
2422 usernames, wallet_items_->active_account_index());
2425 ConstructLegalDocumentsText();
2426 OnWalletOrSigninUpdate();
2429 void AutofillDialogControllerImpl::OnDidSaveToWallet(
2430 const std::string& instrument_id,
2431 const std::string& address_id,
2432 const std::vector<wallet::RequiredAction>& required_actions,
2433 const std::vector<wallet::FormFieldError>& form_field_errors) {
2434 DCHECK(is_submitting_ && IsPayingWithWallet());
2436 if (required_actions.empty()) {
2437 if (!address_id.empty())
2438 active_address_id_ = address_id;
2439 if (!instrument_id.empty())
2440 active_instrument_id_ = instrument_id;
2443 OnWalletFormFieldError(form_field_errors);
2444 HandleSaveOrUpdateRequiredActions(required_actions);
2448 void AutofillDialogControllerImpl::OnWalletError(
2449 wallet::WalletClient::ErrorType error_type) {
2450 DisableWallet(error_type);
2453 ////////////////////////////////////////////////////////////////////////////////
2454 // PersonalDataManagerObserver implementation.
2456 void AutofillDialogControllerImpl::OnPersonalDataChanged() {
2460 SuggestionsUpdated();
2463 ////////////////////////////////////////////////////////////////////////////////
2464 // AccountChooserModelDelegate implementation.
2466 void AutofillDialogControllerImpl::AccountChooserWillShow() {
2470 void AutofillDialogControllerImpl::AccountChoiceChanged() {
2471 ScopedViewUpdates updates(view_.get());
2472 wallet::WalletClient* client = GetWalletClient();
2475 client->CancelRequest();
2477 SetIsSubmitting(false);
2479 size_t selected_user_index =
2480 account_chooser_model_->GetActiveWalletAccountIndex();
2481 if (account_chooser_model_->WalletIsSelected() &&
2482 client->user_index() != selected_user_index) {
2483 client->SetUserIndex(selected_user_index);
2484 // Clear |wallet_items_| so we don't try to restore the selected instrument
2486 wallet_items_.reset();
2489 SuggestionsUpdated();
2490 UpdateAccountChooserView();
2494 void AutofillDialogControllerImpl::AddAccount() {
2495 SignInLinkClicked();
2498 void AutofillDialogControllerImpl::UpdateAccountChooserView() {
2500 ScopedViewUpdates updates(view_.get());
2501 view_->UpdateAccountChooser();
2502 view_->UpdateNotificationArea();
2506 ////////////////////////////////////////////////////////////////////////////////
2508 bool AutofillDialogControllerImpl::HandleKeyPressEventInInput(
2509 const content::NativeWebKeyboardEvent& event) {
2510 if (popup_controller_.get())
2511 return popup_controller_->HandleKeyPressEvent(event);
2516 bool AutofillDialogControllerImpl::IsSubmitPausedOn(
2517 wallet::RequiredAction required_action) const {
2518 return full_wallet_ && full_wallet_->HasRequiredAction(required_action);
2521 void AutofillDialogControllerImpl::ShowNewCreditCardBubble(
2522 scoped_ptr<CreditCard> new_card,
2523 scoped_ptr<AutofillProfile> billing_profile) {
2524 NewCreditCardBubbleController::Show(web_contents(),
2526 billing_profile.Pass());
2529 void AutofillDialogControllerImpl::SubmitButtonDelayBegin() {
2530 submit_button_delay_timer_.Start(
2532 base::TimeDelta::FromMilliseconds(kSubmitButtonDelayMs),
2534 &AutofillDialogControllerImpl::OnSubmitButtonDelayEnd);
2537 void AutofillDialogControllerImpl::SubmitButtonDelayEndForTesting() {
2538 DCHECK(submit_button_delay_timer_.IsRunning());
2539 submit_button_delay_timer_.user_task().Run();
2540 submit_button_delay_timer_.Stop();
2543 void AutofillDialogControllerImpl::
2544 ClearLastWalletItemsFetchTimestampForTesting() {
2545 last_wallet_items_fetch_timestamp_ = base::TimeTicks();
2548 AccountChooserModel* AutofillDialogControllerImpl::
2549 AccountChooserModelForTesting() {
2550 return account_chooser_model_.get();
2553 bool AutofillDialogControllerImpl::IsSignInContinueUrl(
2555 size_t* user_index) const {
2556 return wallet::IsSignInContinueUrl(url, user_index);
2559 AutofillDialogControllerImpl::AutofillDialogControllerImpl(
2560 content::WebContents* contents,
2561 const FormData& form_structure,
2562 const GURL& source_url,
2563 const base::Callback<void(const FormStructure*)>& callback)
2564 : WebContentsObserver(contents),
2565 profile_(Profile::FromBrowserContext(contents->GetBrowserContext())),
2566 initial_user_state_(AutofillMetrics::DIALOG_USER_STATE_UNKNOWN),
2567 form_structure_(form_structure),
2568 invoked_from_same_origin_(true),
2569 source_url_(source_url),
2570 callback_(callback),
2571 wallet_client_(profile_->GetRequestContext(), this, source_url),
2572 wallet_items_requested_(false),
2573 handling_use_wallet_link_click_(false),
2574 passive_failed_(false),
2575 billing_country_combobox_model_(*GetManager()),
2576 shipping_country_combobox_model_(*GetManager()),
2577 suggested_cc_(this),
2578 suggested_billing_(this),
2579 suggested_cc_billing_(this),
2580 suggested_shipping_(this),
2581 cares_about_shipping_(true),
2582 popup_input_type_(UNKNOWN_TYPE),
2583 weak_ptr_factory_(this),
2584 waiting_for_explicit_sign_in_response_(false),
2585 has_accepted_legal_documents_(false),
2586 is_submitting_(false),
2587 choose_another_instrument_or_address_(false),
2588 wallet_server_validation_recoverable_(true),
2589 data_was_passed_back_(false),
2590 was_ui_latency_logged_(false),
2591 card_generated_animation_(2000, 60, this) {
2592 // TODO(estade): remove duplicates from |form_structure|?
2593 DCHECK(!callback_.is_null());
2596 AutofillDialogView* AutofillDialogControllerImpl::CreateView() {
2597 return AutofillDialogView::Create(this);
2600 PersonalDataManager* AutofillDialogControllerImpl::GetManager() const {
2601 return PersonalDataManagerFactory::GetForProfile(profile_);
2604 const wallet::WalletClient* AutofillDialogControllerImpl::GetWalletClient()
2606 return const_cast<AutofillDialogControllerImpl*>(this)->GetWalletClient();
2609 wallet::WalletClient* AutofillDialogControllerImpl::GetWalletClient() {
2610 return &wallet_client_;
2613 bool AutofillDialogControllerImpl::IsPayingWithWallet() const {
2614 return account_chooser_model_->WalletIsSelected() &&
2615 SignedInState() == SIGNED_IN;
2618 void AutofillDialogControllerImpl::LoadRiskFingerprintData() {
2621 uint64 obfuscated_gaia_id = 0;
2622 bool success = base::StringToUint64(wallet_items_->ObfuscatedGaiaId(),
2623 &obfuscated_gaia_id);
2626 gfx::Rect window_bounds;
2627 window_bounds = GetBaseWindowForWebContents(web_contents())->GetBounds();
2629 PrefService* user_prefs = profile_->GetPrefs();
2630 std::string charset = user_prefs->GetString(::prefs::kDefaultCharset);
2631 std::string accept_languages =
2632 user_prefs->GetString(::prefs::kAcceptLanguages);
2633 base::Time install_time = base::Time::FromTimeT(
2634 g_browser_process->local_state()->GetInt64(::prefs::kInstallDate));
2636 risk::GetFingerprint(
2637 obfuscated_gaia_id, window_bounds, *web_contents(),
2638 chrome::VersionInfo().Version(), charset, accept_languages, install_time,
2639 g_browser_process->GetApplicationLocale(),
2640 base::Bind(&AutofillDialogControllerImpl::OnDidLoadRiskFingerprintData,
2641 weak_ptr_factory_.GetWeakPtr()));
2644 void AutofillDialogControllerImpl::OnDidLoadRiskFingerprintData(
2645 scoped_ptr<risk::Fingerprint> fingerprint) {
2646 DCHECK(AreLegalDocumentsCurrent());
2648 std::string proto_data;
2649 fingerprint->SerializeToString(&proto_data);
2650 base::Base64Encode(proto_data, &risk_data_);
2655 void AutofillDialogControllerImpl::OpenTabWithUrl(const GURL& url) {
2656 chrome::NavigateParams params(
2657 chrome::FindBrowserWithWebContents(web_contents()),
2659 content::PAGE_TRANSITION_LINK);
2660 params.disposition = NEW_FOREGROUND_TAB;
2661 chrome::Navigate(¶ms);
2664 DialogSection AutofillDialogControllerImpl::ActiveBillingSection() const {
2665 return IsPayingWithWallet() ? SECTION_CC_BILLING : SECTION_BILLING;
2668 bool AutofillDialogControllerImpl::IsEditingExistingData(
2669 DialogSection section) const {
2670 return section_editing_state_.count(section) > 0;
2673 bool AutofillDialogControllerImpl::IsManuallyEditingSection(
2674 DialogSection section) const {
2675 return IsEditingExistingData(section) ||
2676 SuggestionsMenuModelForSection(section)->
2677 GetItemKeyForCheckedItem() == kAddNewItemKey;
2680 void AutofillDialogControllerImpl::OnWalletSigninError() {
2681 account_chooser_model_->SetHadWalletSigninError();
2682 GetWalletClient()->CancelRequest();
2683 LogDialogLatencyToShow();
2686 void AutofillDialogControllerImpl::DisableWallet(
2687 wallet::WalletClient::ErrorType error_type) {
2688 signin_helper_.reset();
2689 wallet_items_.reset();
2690 wallet_errors_.clear();
2691 GetWalletClient()->CancelRequest();
2692 SetIsSubmitting(false);
2693 wallet_error_notification_ = GetWalletError(error_type);
2694 account_chooser_model_->SetHadWalletError();
2697 void AutofillDialogControllerImpl::SuggestionsUpdated() {
2698 ScopedViewUpdates updates(view_.get());
2700 const FieldValueMap snapshot = TakeUserInputSnapshot();
2702 suggested_cc_.Reset();
2703 suggested_billing_.Reset();
2704 suggested_cc_billing_.Reset();
2705 suggested_shipping_.Reset();
2708 suggested_shipping_.AddKeyedItem(
2710 l10n_util::GetStringUTF16(IDS_AUTOFILL_DIALOG_USE_BILLING_FOR_SHIPPING));
2712 if (IsPayingWithWallet()) {
2713 const std::vector<wallet::Address*>& addresses =
2714 wallet_items_->addresses();
2716 bool shipping_same_as_billing = profile_->GetPrefs()->GetBoolean(
2717 ::prefs::kAutofillDialogWalletShippingSameAsBilling);
2719 if (shipping_same_as_billing)
2720 suggested_shipping_.SetCheckedItem(kSameAsBillingKey);
2722 for (size_t i = 0; i < addresses.size(); ++i) {
2723 std::string key = base::IntToString(i);
2724 suggested_shipping_.AddKeyedItemWithMinorText(
2726 addresses[i]->DisplayName(),
2727 addresses[i]->DisplayNameDetail());
2729 // TODO(scr): Move this assignment outside the loop or comment why it
2731 const std::string default_shipping_address_id =
2732 GetIdToSelect(wallet_items_->default_address_id(),
2733 previous_default_shipping_address_id_,
2734 previously_selected_shipping_address_id_);
2736 if (!shipping_same_as_billing &&
2737 addresses[i]->object_id() == default_shipping_address_id) {
2738 suggested_shipping_.SetCheckedItem(key);
2742 if (!IsSubmitPausedOn(wallet::VERIFY_CVV)) {
2743 const std::vector<wallet::WalletItems::MaskedInstrument*>& instruments =
2744 wallet_items_->instruments();
2745 std::string first_active_instrument_key;
2746 std::string default_instrument_key;
2747 for (size_t i = 0; i < instruments.size(); ++i) {
2748 bool allowed = IsInstrumentAllowed(*instruments[i]);
2749 gfx::Image icon = instruments[i]->CardIcon();
2750 if (!allowed && !icon.IsEmpty()) {
2751 // Create a grayed disabled icon.
2752 SkBitmap disabled_bitmap = SkBitmapOperations::CreateHSLShiftedBitmap(
2753 *icon.ToSkBitmap(), kGrayImageShift);
2755 gfx::ImageSkia::CreateFrom1xBitmap(disabled_bitmap));
2757 std::string key = base::IntToString(i);
2758 suggested_cc_billing_.AddKeyedItemWithMinorTextAndIcon(
2760 instruments[i]->DisplayName(),
2761 instruments[i]->DisplayNameDetail(),
2763 suggested_cc_billing_.SetEnabled(key, allowed);
2766 if (first_active_instrument_key.empty())
2767 first_active_instrument_key = key;
2769 const std::string default_instrument_id =
2770 GetIdToSelect(wallet_items_->default_instrument_id(),
2771 previous_default_instrument_id_,
2772 previously_selected_instrument_id_);
2773 if (instruments[i]->object_id() == default_instrument_id)
2774 default_instrument_key = key;
2778 suggested_cc_billing_.AddKeyedItem(
2780 l10n_util::GetStringUTF16(IDS_AUTOFILL_DIALOG_ADD_BILLING_DETAILS));
2781 if (!wallet_items_->HasRequiredAction(wallet::SETUP_WALLET)) {
2782 suggested_cc_billing_.AddKeyedItemWithMinorText(
2784 l10n_util::GetStringUTF16(
2785 IDS_AUTOFILL_DIALOG_MANAGE_BILLING_DETAILS),
2786 base::UTF8ToUTF16(wallet::GetManageInstrumentsUrl(0U).host()));
2789 // Determine which instrument item should be selected.
2790 if (!default_instrument_key.empty())
2791 suggested_cc_billing_.SetCheckedItem(default_instrument_key);
2792 else if (!first_active_instrument_key.empty())
2793 suggested_cc_billing_.SetCheckedItem(first_active_instrument_key);
2795 suggested_cc_billing_.SetCheckedItem(kAddNewItemKey);
2798 PersonalDataManager* manager = GetManager();
2799 const std::vector<CreditCard*>& cards = manager->GetCreditCards();
2800 ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance();
2801 for (size_t i = 0; i < cards.size(); ++i) {
2802 if (!i18ninput::CardHasCompleteAndVerifiedData(*cards[i]))
2805 suggested_cc_.AddKeyedItemWithIcon(
2808 rb.GetImageNamed(CreditCard::IconResourceId(cards[i]->type())));
2811 const std::vector<AutofillProfile*>& profiles = manager->GetProfiles();
2812 std::vector<base::string16> labels;
2813 AutofillProfile::CreateDifferentiatingLabels(profiles, &labels);
2814 DCHECK_EQ(labels.size(), profiles.size());
2815 for (size_t i = 0; i < profiles.size(); ++i) {
2816 const AutofillProfile& profile = *profiles[i];
2817 if (!i18ninput::AddressHasCompleteAndVerifiedData(profile) ||
2818 (!i18ninput::Enabled() && HasInvalidAddress(*profiles[i]))) {
2822 // Don't add variants for addresses: name is part of credit card and we'll
2823 // just ignore email and phone number variants.
2824 suggested_shipping_.AddKeyedItem(profile.guid(), labels[i]);
2825 if (!profile.GetRawInfo(EMAIL_ADDRESS).empty() &&
2826 !profile.IsPresentButInvalid(EMAIL_ADDRESS)) {
2827 suggested_billing_.AddKeyedItem(profile.guid(), labels[i]);
2831 suggested_cc_.AddKeyedItem(
2833 l10n_util::GetStringUTF16(IDS_AUTOFILL_DIALOG_ADD_CREDIT_CARD));
2834 suggested_cc_.AddKeyedItem(
2836 l10n_util::GetStringUTF16(IDS_AUTOFILL_DIALOG_MANAGE_CREDIT_CARD));
2837 suggested_billing_.AddKeyedItem(
2839 l10n_util::GetStringUTF16(IDS_AUTOFILL_DIALOG_ADD_BILLING_ADDRESS));
2840 suggested_billing_.AddKeyedItem(
2842 l10n_util::GetStringUTF16(IDS_AUTOFILL_DIALOG_MANAGE_BILLING_ADDRESS));
2845 suggested_shipping_.AddKeyedItem(
2847 l10n_util::GetStringUTF16(IDS_AUTOFILL_DIALOG_ADD_SHIPPING_ADDRESS));
2848 if (!IsPayingWithWallet()) {
2849 suggested_shipping_.AddKeyedItem(
2851 l10n_util::GetStringUTF16(IDS_AUTOFILL_DIALOG_MANAGE_SHIPPING_ADDRESS));
2852 } else if (!wallet_items_->HasRequiredAction(wallet::SETUP_WALLET)) {
2853 suggested_shipping_.AddKeyedItemWithMinorText(
2855 l10n_util::GetStringUTF16(IDS_AUTOFILL_DIALOG_MANAGE_SHIPPING_ADDRESS),
2856 base::UTF8ToUTF16(wallet::GetManageAddressesUrl(0U).host()));
2859 if (!IsPayingWithWallet()) {
2860 for (size_t i = SECTION_MIN; i <= SECTION_MAX; ++i) {
2861 DialogSection section = static_cast<DialogSection>(i);
2862 if (!SectionIsActive(section))
2865 // Set the starting choice for the menu. First set to the default in case
2866 // the GUID saved in prefs refers to a profile that no longer exists.
2868 GetDefaultAutofillChoice(section, &guid);
2869 SuggestionsMenuModel* model = SuggestionsMenuModelForSection(section);
2870 model->SetCheckedItem(guid);
2871 if (GetAutofillChoice(section, &guid))
2872 model->SetCheckedItem(guid);
2877 view_->ModelChanged();
2879 for (size_t i = SECTION_MIN; i <= SECTION_MAX; ++i) {
2880 ResetSectionInput(static_cast<DialogSection>(i));
2883 FieldValueMap::const_iterator billing_it =
2884 snapshot.find(ADDRESS_BILLING_COUNTRY);
2885 if (billing_it != snapshot.end())
2886 RebuildInputsForCountry(ActiveBillingSection(), billing_it->second, false);
2888 FieldValueMap::const_iterator shipping_it =
2889 snapshot.find(ADDRESS_HOME_COUNTRY);
2890 if (shipping_it != snapshot.end())
2891 RebuildInputsForCountry(SECTION_SHIPPING, shipping_it->second, false);
2893 RestoreUserInputFromSnapshot(snapshot);
2895 for (size_t i = SECTION_MIN; i <= SECTION_MAX; ++i) {
2896 DialogSection section = static_cast<DialogSection>(i);
2897 if (!SectionIsActive(section))
2900 ShowEditUiIfBadSuggestion(section);
2901 UpdateSection(section);
2907 void AutofillDialogControllerImpl::FillOutputForSectionWithComparator(
2908 DialogSection section,
2909 const InputFieldComparator& compare) {
2910 if (!SectionIsActive(section))
2913 DetailInputs inputs;
2914 std::string country_code = CountryCodeForSection(section);
2915 common::BuildInputsForSection(section, country_code, &inputs);
2917 scoped_ptr<DataModelWrapper> wrapper = CreateWrapper(section);
2919 // Only fill in data that is associated with this section.
2920 wrapper->FillFormStructure(inputs, compare, &form_structure_);
2922 // CVC needs special-casing because the CreditCard class doesn't store or
2923 // handle them. This isn't necessary when filling the combined CC and
2924 // billing section as CVC comes from |full_wallet_| in this case.
2925 if (section == SECTION_CC)
2926 SetOutputForFieldsOfType(CREDIT_CARD_VERIFICATION_CODE, view_->GetCvc());
2928 // When filling from Wallet data, use the email address associated with the
2929 // account. There is no other email address stored as part of a Wallet
2931 if (section == SECTION_CC_BILLING) {
2932 SetOutputForFieldsOfType(
2933 EMAIL_ADDRESS, account_chooser_model_->GetActiveWalletAccountName());
2936 // The user manually input data. If using Autofill, save the info as new or
2937 // edited data. Always fill local data into |form_structure_|.
2938 FieldValueMap output;
2939 view_->GetUserInput(section, &output);
2941 if (section == SECTION_CC) {
2943 card.set_origin(kAutofillDialogOrigin);
2944 FillFormGroupFromOutputs(output, &card);
2946 // The card holder name comes from the billing address section.
2947 card.SetRawInfo(CREDIT_CARD_NAME,
2948 GetValueFromSection(SECTION_BILLING, NAME_BILLING_FULL));
2950 if (ShouldSaveDetailsLocally()) {
2951 std::string guid = GetManager()->SaveImportedCreditCard(card);
2952 newly_saved_data_model_guids_[section] = guid;
2953 DCHECK(!profile()->IsOffTheRecord());
2954 newly_saved_card_.reset(new CreditCard(card));
2957 AutofillCreditCardWrapper card_wrapper(&card);
2958 card_wrapper.FillFormStructure(inputs, compare, &form_structure_);
2960 // Again, CVC needs special-casing. Fill it in directly from |output|.
2961 SetOutputForFieldsOfType(
2962 CREDIT_CARD_VERIFICATION_CODE,
2963 output[CREDIT_CARD_VERIFICATION_CODE]);
2965 AutofillProfile profile;
2966 profile.set_origin(kAutofillDialogOrigin);
2967 FillFormGroupFromOutputs(output, &profile);
2969 if (ShouldSaveDetailsLocally()) {
2970 std::string guid = GetManager()->SaveImportedProfile(profile);
2971 newly_saved_data_model_guids_[section] = guid;
2974 AutofillProfileWrapper profile_wrapper(&profile);
2975 profile_wrapper.FillFormStructure(inputs, compare, &form_structure_);
2980 void AutofillDialogControllerImpl::FillOutputForSection(DialogSection section) {
2981 FillOutputForSectionWithComparator(
2982 section, base::Bind(common::ServerTypeMatchesField, section));
2985 bool AutofillDialogControllerImpl::FormStructureCaresAboutSection(
2986 DialogSection section) const {
2987 // For now, only SECTION_SHIPPING may be omitted due to a site not asking for
2988 // any of the fields.
2989 if (section == SECTION_SHIPPING)
2990 return cares_about_shipping_;
2995 void AutofillDialogControllerImpl::SetOutputForFieldsOfType(
2996 ServerFieldType type,
2997 const base::string16& output) {
2998 for (size_t i = 0; i < form_structure_.field_count(); ++i) {
2999 AutofillField* field = form_structure_.field(i);
3000 if (field->Type().GetStorableType() == type)
3001 field->value = output;
3005 base::string16 AutofillDialogControllerImpl::GetValueFromSection(
3006 DialogSection section,
3007 ServerFieldType type) {
3008 DCHECK(SectionIsActive(section));
3010 scoped_ptr<DataModelWrapper> wrapper = CreateWrapper(section);
3012 return wrapper->GetInfo(AutofillType(type));
3014 FieldValueMap output;
3015 view_->GetUserInput(section, &output);
3016 return output[type];
3019 SuggestionsMenuModel* AutofillDialogControllerImpl::
3020 SuggestionsMenuModelForSection(DialogSection section) {
3023 return &suggested_cc_;
3024 case SECTION_BILLING:
3025 return &suggested_billing_;
3026 case SECTION_SHIPPING:
3027 return &suggested_shipping_;
3028 case SECTION_CC_BILLING:
3029 return &suggested_cc_billing_;
3036 const SuggestionsMenuModel* AutofillDialogControllerImpl::
3037 SuggestionsMenuModelForSection(DialogSection section) const {
3038 return const_cast<AutofillDialogControllerImpl*>(this)->
3039 SuggestionsMenuModelForSection(section);
3042 DialogSection AutofillDialogControllerImpl::SectionForSuggestionsMenuModel(
3043 const SuggestionsMenuModel& model) {
3044 if (&model == &suggested_cc_)
3047 if (&model == &suggested_billing_)
3048 return SECTION_BILLING;
3050 if (&model == &suggested_cc_billing_)
3051 return SECTION_CC_BILLING;
3053 DCHECK_EQ(&model, &suggested_shipping_);
3054 return SECTION_SHIPPING;
3057 CountryComboboxModel* AutofillDialogControllerImpl::
3058 CountryComboboxModelForSection(DialogSection section) {
3059 if (section == SECTION_BILLING || section == SECTION_CC_BILLING)
3060 return &billing_country_combobox_model_;
3062 if (section == SECTION_SHIPPING)
3063 return &shipping_country_combobox_model_;
3068 DetailInputs* AutofillDialogControllerImpl::MutableRequestedFieldsForSection(
3069 DialogSection section) {
3070 return const_cast<DetailInputs*>(&RequestedFieldsForSection(section));
3073 std::string AutofillDialogControllerImpl::CountryCodeForSection(
3074 DialogSection section) {
3075 scoped_ptr<DataModelWrapper> wrapper = CreateWrapper(section);
3077 return AutofillCountry::GetCountryCode(
3078 wrapper->GetInfo(AutofillType(CountryTypeForSection(section))),
3079 g_browser_process->GetApplicationLocale());
3082 CountryComboboxModel* model = CountryComboboxModelForSection(section);
3083 return model ? model->GetDefaultCountryCode() : std::string();
3086 bool AutofillDialogControllerImpl::RebuildInputsForCountry(
3087 DialogSection section,
3088 const base::string16& country_name,
3089 bool should_clobber) {
3090 DCHECK_NE(SECTION_CC, section);
3092 if (view_ && !should_clobber) {
3093 FieldValueMap outputs;
3094 view_->GetUserInput(section, &outputs);
3096 // If |country_name| is the same as the view, no-op and let the caller know.
3097 if (outputs[CountryTypeForSection(section)] == country_name)
3101 DetailInputs* inputs = MutableRequestedFieldsForSection(section);
3104 std::string country_code = AutofillCountry::GetCountryCode(
3105 country_name, g_browser_process->GetApplicationLocale());
3106 common::BuildInputsForSection(section, country_code, inputs);
3110 void AutofillDialogControllerImpl::HidePopup() {
3111 if (popup_controller_.get())
3112 popup_controller_->Hide();
3113 popup_input_type_ = UNKNOWN_TYPE;
3116 void AutofillDialogControllerImpl::SetEditingExistingData(
3117 DialogSection section, bool editing) {
3119 section_editing_state_.insert(section);
3121 section_editing_state_.erase(section);
3124 bool AutofillDialogControllerImpl::IsASuggestionItemKey(
3125 const std::string& key) const {
3126 return !key.empty() &&
3127 key != kAddNewItemKey &&
3128 key != kManageItemsKey &&
3129 key != kSameAsBillingKey;
3132 bool AutofillDialogControllerImpl::IsManuallyEditingAnySection() const {
3133 for (size_t section = SECTION_MIN; section <= SECTION_MAX; ++section) {
3134 if (IsManuallyEditingSection(static_cast<DialogSection>(section)))
3140 base::string16 AutofillDialogControllerImpl::CreditCardNumberValidityMessage(
3141 const base::string16& number) const {
3142 if (!number.empty() && !autofill::IsValidCreditCardNumber(number)) {
3143 return l10n_util::GetStringUTF16(
3144 IDS_AUTOFILL_DIALOG_VALIDATION_INVALID_CREDIT_CARD_NUMBER);
3147 base::string16 message;
3148 if (IsPayingWithWallet() && !wallet_items_->SupportsCard(number, &message))
3151 // Card number is good and supported.
3152 return base::string16();
3155 bool AutofillDialogControllerImpl::AllSectionsAreValid() {
3156 for (size_t section = SECTION_MIN; section <= SECTION_MAX; ++section) {
3157 if (!SectionIsValid(static_cast<DialogSection>(section)))
3163 bool AutofillDialogControllerImpl::SectionIsValid(
3164 DialogSection section) {
3165 if (!IsManuallyEditingSection(section))
3168 FieldValueMap detail_outputs;
3169 view_->GetUserInput(section, &detail_outputs);
3170 return !InputsAreValid(section, detail_outputs).HasSureErrors();
3173 bool AutofillDialogControllerImpl::IsCreditCardExpirationValid(
3174 const base::string16& year,
3175 const base::string16& month) const {
3176 // If the expiration is in the past as per the local clock, it's invalid.
3177 base::Time now = base::Time::Now();
3178 if (!autofill::IsValidCreditCardExpirationDate(year, month, now))
3181 if (IsPayingWithWallet() && IsEditingExistingData(SECTION_CC_BILLING)) {
3182 const wallet::WalletItems::MaskedInstrument* instrument =
3184 const std::string& locale = g_browser_process->GetApplicationLocale();
3186 if (base::StringToInt(month, &month_int) &&
3187 instrument->status() ==
3188 wallet::WalletItems::MaskedInstrument::EXPIRED &&
3190 instrument->GetInfo(
3191 AutofillType(CREDIT_CARD_EXP_4_DIGIT_YEAR), locale) &&
3192 month_int == instrument->expiration_month()) {
3193 // Otherwise, if the user is editing an instrument that's deemed expired
3194 // by the Online Wallet server, mark it invalid on selection.
3202 bool AutofillDialogControllerImpl::ShouldUseBillingForShipping() {
3203 return SectionIsActive(SECTION_SHIPPING) &&
3204 suggested_shipping_.GetItemKeyForCheckedItem() == kSameAsBillingKey;
3207 bool AutofillDialogControllerImpl::ShouldSaveDetailsLocally() {
3208 // It's possible that the user checked [X] Save details locally before
3209 // switching payment methods, so only ask the view whether to save details
3210 // locally if that checkbox is showing (currently if not paying with wallet).
3211 // Also, if the user isn't editing any sections, there's no data to save
3213 return ShouldOfferToSaveInChrome() && view_->SaveDetailsLocally();
3216 void AutofillDialogControllerImpl::SetIsSubmitting(bool submitting) {
3217 is_submitting_ = submitting;
3220 full_wallet_.reset();
3223 ScopedViewUpdates updates(view_.get());
3224 view_->UpdateButtonStrip();
3225 view_->UpdateOverlay();
3226 view_->UpdateNotificationArea();
3230 bool AutofillDialogControllerImpl::AreLegalDocumentsCurrent() const {
3231 return has_accepted_legal_documents_ ||
3232 (wallet_items_ && wallet_items_->legal_documents().empty());
3235 void AutofillDialogControllerImpl::AcceptLegalTerms() {
3236 content::BrowserThread::PostTask(
3237 content::BrowserThread::IO, FROM_HERE,
3238 base::Bind(&UserDidOptIntoLocationServices));
3239 PrefService* local_state = g_browser_process->local_state();
3240 ListPrefUpdate accepted(
3241 local_state, ::prefs::kAutofillDialogWalletLocationAcceptance);
3242 accepted->AppendIfNotPresent(new base::StringValue(
3243 account_chooser_model_->GetActiveWalletAccountName()));
3245 if (AreLegalDocumentsCurrent()) {
3246 LoadRiskFingerprintData();
3248 GetWalletClient()->AcceptLegalDocuments(
3249 wallet_items_->legal_documents(),
3250 wallet_items_->google_transaction_id());
3254 void AutofillDialogControllerImpl::SubmitWithWallet() {
3255 active_instrument_id_.clear();
3256 active_address_id_.clear();
3257 full_wallet_.reset();
3259 const wallet::WalletItems::MaskedInstrument* active_instrument =
3261 if (!IsManuallyEditingSection(SECTION_CC_BILLING)) {
3262 active_instrument_id_ = active_instrument->object_id();
3263 DCHECK(!active_instrument_id_.empty());
3266 const wallet::Address* active_address = ActiveShippingAddress();
3267 if (!IsManuallyEditingSection(SECTION_SHIPPING) &&
3268 !ShouldUseBillingForShipping() &&
3269 IsShippingAddressRequired()) {
3270 active_address_id_ = active_address->object_id();
3271 DCHECK(!active_address_id_.empty());
3274 scoped_ptr<wallet::Instrument> inputted_instrument =
3275 CreateTransientInstrument();
3277 scoped_ptr<wallet::Address> inputted_address;
3278 if (active_address_id_.empty() && IsShippingAddressRequired()) {
3279 if (ShouldUseBillingForShipping()) {
3280 const wallet::Address& address = inputted_instrument ?
3281 *inputted_instrument->address() : active_instrument->address();
3282 // Try to find an exact matched shipping address and use it for shipping,
3283 // otherwise save it as a new shipping address. http://crbug.com/225442
3284 const wallet::Address* duplicated_address =
3285 FindDuplicateAddress(wallet_items_->addresses(), address);
3286 if (duplicated_address) {
3287 active_address_id_ = duplicated_address->object_id();
3288 DCHECK(!active_address_id_.empty());
3290 inputted_address.reset(new wallet::Address(address));
3291 DCHECK(inputted_address->object_id().empty());
3294 inputted_address = CreateTransientAddress();
3298 // If there's neither an address nor instrument to save, |GetFullWallet()|
3299 // is called when the risk fingerprint is loaded.
3300 if (!active_instrument_id_.empty() &&
3301 (!active_address_id_.empty() || !IsShippingAddressRequired())) {
3306 GetWalletClient()->SaveToWallet(
3307 inputted_instrument.Pass(),
3308 inputted_address.Pass(),
3309 IsEditingExistingData(SECTION_CC_BILLING) ? active_instrument : NULL,
3310 IsEditingExistingData(SECTION_SHIPPING) ? active_address : NULL);
3313 scoped_ptr<wallet::Instrument> AutofillDialogControllerImpl::
3314 CreateTransientInstrument() {
3315 if (!active_instrument_id_.empty())
3316 return scoped_ptr<wallet::Instrument>();
3318 FieldValueMap output;
3319 view_->GetUserInput(SECTION_CC_BILLING, &output);
3322 AutofillProfile profile;
3324 GetBillingInfoFromOutputs(output, &card, &cvc, &profile);
3326 return scoped_ptr<wallet::Instrument>(
3327 new wallet::Instrument(card, cvc, profile));
3330 scoped_ptr<wallet::Address>AutofillDialogControllerImpl::
3331 CreateTransientAddress() {
3332 // If not using billing for shipping, just scrape the view.
3333 FieldValueMap output;
3334 view_->GetUserInput(SECTION_SHIPPING, &output);
3336 AutofillProfile profile;
3337 FillFormGroupFromOutputs(output, &profile);
3339 return scoped_ptr<wallet::Address>(new wallet::Address(profile));
3342 void AutofillDialogControllerImpl::GetFullWallet() {
3343 DCHECK(is_submitting_);
3344 DCHECK(IsPayingWithWallet());
3345 DCHECK(wallet_items_);
3346 DCHECK(!active_instrument_id_.empty());
3347 DCHECK(!active_address_id_.empty() || !IsShippingAddressRequired());
3349 std::vector<wallet::WalletClient::RiskCapability> capabilities;
3350 capabilities.push_back(wallet::WalletClient::VERIFY_CVC);
3352 GetWalletClient()->GetFullWallet(wallet::WalletClient::FullWalletRequest(
3353 active_instrument_id_,
3355 wallet_items_->google_transaction_id(),
3357 wallet_items_->HasRequiredAction(wallet::SETUP_WALLET)));
3360 void AutofillDialogControllerImpl::HandleSaveOrUpdateRequiredActions(
3361 const std::vector<wallet::RequiredAction>& required_actions) {
3362 DCHECK(!required_actions.empty());
3364 // TODO(ahutter): Investigate if we need to support more generic actions on
3365 // this call such as GAIA_AUTH. See crbug.com/243457.
3366 for (std::vector<wallet::RequiredAction>::const_iterator iter =
3367 required_actions.begin();
3368 iter != required_actions.end(); ++iter) {
3369 if (*iter != wallet::INVALID_FORM_FIELD) {
3370 // TODO(dbeam): handle this more gracefully.
3371 DisableWallet(wallet::WalletClient::UNKNOWN_ERROR);
3374 SetIsSubmitting(false);
3377 void AutofillDialogControllerImpl::FinishSubmit() {
3378 if (IsPayingWithWallet()) {
3379 ScopedViewUpdates updates(view_.get());
3380 view_->UpdateOverlay();
3382 card_generated_animation_.Start();
3388 void AutofillDialogControllerImpl::AnimationProgressed(
3389 const gfx::Animation* animation) {
3390 DCHECK_EQ(animation, &card_generated_animation_);
3391 PushOverlayUpdate();
3394 void AutofillDialogControllerImpl::AnimationEnded(
3395 const gfx::Animation* animation) {
3396 DCHECK_EQ(animation, &card_generated_animation_);
3400 void AutofillDialogControllerImpl::DoFinishSubmit() {
3401 FillOutputForSection(SECTION_CC);
3402 FillOutputForSection(SECTION_BILLING);
3403 FillOutputForSection(SECTION_CC_BILLING);
3405 if (ShouldUseBillingForShipping()) {
3406 FillOutputForSectionWithComparator(
3408 base::Bind(ServerTypeMatchesShippingField));
3409 FillOutputForSectionWithComparator(
3411 base::Bind(ServerTypeMatchesShippingField));
3412 FillOutputForSectionWithComparator(
3414 base::Bind(ServerTypeMatchesShippingField));
3416 FillOutputForSection(SECTION_SHIPPING);
3419 if (IsPayingWithWallet()) {
3420 if (SectionIsActive(SECTION_SHIPPING)) {
3421 profile_->GetPrefs()->SetBoolean(
3422 ::prefs::kAutofillDialogWalletShippingSameAsBilling,
3423 suggested_shipping_.GetItemKeyForCheckedItem() == kSameAsBillingKey);
3426 for (size_t i = SECTION_MIN; i <= SECTION_MAX; ++i) {
3427 DialogSection section = static_cast<DialogSection>(i);
3428 if (!SectionIsActive(section))
3431 SuggestionsMenuModel* model = SuggestionsMenuModelForSection(section);
3432 std::string item_key = model->GetItemKeyForCheckedItem();
3433 if (IsASuggestionItemKey(item_key) || item_key == kSameAsBillingKey) {
3434 PersistAutofillChoice(section, item_key);
3435 } else if (item_key == kAddNewItemKey && ShouldSaveDetailsLocally()) {
3436 DCHECK(newly_saved_data_model_guids_.count(section));
3437 PersistAutofillChoice(section, newly_saved_data_model_guids_[section]);
3441 profile_->GetPrefs()->SetBoolean(::prefs::kAutofillDialogSaveData,
3442 view_->SaveDetailsLocally());
3445 // On a successful submit, if the user manually selected "pay without wallet",
3446 // stop trying to pay with Wallet on future runs of the dialog. On the other
3447 // hand, if there was an error that prevented the user from having the choice
3448 // of using Wallet, leave the pref alone.
3449 if (!wallet_error_notification_ &&
3450 account_chooser_model_->HasAccountsToChoose()) {
3451 profile_->GetPrefs()->SetBoolean(
3452 ::prefs::kAutofillDialogPayWithoutWallet,
3453 !account_chooser_model_->WalletIsSelected());
3456 LogOnFinishSubmitMetrics();
3458 // Callback should be called as late as possible.
3459 callback_.Run(&form_structure_);
3460 data_was_passed_back_ = true;
3462 // This might delete us.
3466 void AutofillDialogControllerImpl::PersistAutofillChoice(
3467 DialogSection section,
3468 const std::string& guid) {
3469 DCHECK(!IsPayingWithWallet());
3470 scoped_ptr<base::DictionaryValue> value(new base::DictionaryValue());
3471 value->SetString(kGuidPrefKey, guid);
3473 DictionaryPrefUpdate updater(profile()->GetPrefs(),
3474 ::prefs::kAutofillDialogAutofillDefault);
3475 base::DictionaryValue* autofill_choice = updater.Get();
3476 autofill_choice->Set(SectionToPrefString(section), value.release());
3479 void AutofillDialogControllerImpl::GetDefaultAutofillChoice(
3480 DialogSection section,
3481 std::string* guid) {
3482 DCHECK(!IsPayingWithWallet());
3483 // The default choice is the first thing in the menu that is a suggestion
3485 SuggestionsMenuModel* model = SuggestionsMenuModelForSection(section);
3486 for (int i = 0; i < model->GetItemCount(); ++i) {
3487 if (IsASuggestionItemKey(model->GetItemKeyAt(i))) {
3488 *guid = model->GetItemKeyAt(i);
3494 bool AutofillDialogControllerImpl::GetAutofillChoice(DialogSection section,
3495 std::string* guid) {
3496 DCHECK(!IsPayingWithWallet());
3497 const base::DictionaryValue* choices = profile()->GetPrefs()->GetDictionary(
3498 ::prefs::kAutofillDialogAutofillDefault);
3502 const base::DictionaryValue* choice = NULL;
3503 if (!choices->GetDictionary(SectionToPrefString(section), &choice))
3506 choice->GetString(kGuidPrefKey, guid);
3510 void AutofillDialogControllerImpl::LogOnFinishSubmitMetrics() {
3511 GetMetricLogger().LogDialogUiDuration(
3512 base::Time::Now() - dialog_shown_timestamp_,
3513 AutofillMetrics::DIALOG_ACCEPTED);
3515 GetMetricLogger().LogDialogUiEvent(AutofillMetrics::DIALOG_UI_ACCEPTED);
3517 AutofillMetrics::DialogDismissalState dismissal_state;
3518 if (!IsManuallyEditingAnySection())
3519 dismissal_state = AutofillMetrics::DIALOG_ACCEPTED_EXISTING_DATA;
3520 else if (IsPayingWithWallet())
3521 dismissal_state = AutofillMetrics::DIALOG_ACCEPTED_SAVE_TO_WALLET;
3522 else if (ShouldSaveDetailsLocally())
3523 dismissal_state = AutofillMetrics::DIALOG_ACCEPTED_SAVE_TO_AUTOFILL;
3525 dismissal_state = AutofillMetrics::DIALOG_ACCEPTED_NO_SAVE;
3527 GetMetricLogger().LogDialogDismissalState(dismissal_state);
3530 void AutofillDialogControllerImpl::LogOnCancelMetrics() {
3531 GetMetricLogger().LogDialogUiEvent(AutofillMetrics::DIALOG_UI_CANCELED);
3533 AutofillMetrics::DialogDismissalState dismissal_state;
3534 if (ShouldShowSignInWebView())
3535 dismissal_state = AutofillMetrics::DIALOG_CANCELED_DURING_SIGNIN;
3536 else if (!IsManuallyEditingAnySection())
3537 dismissal_state = AutofillMetrics::DIALOG_CANCELED_NO_EDITS;
3538 else if (AllSectionsAreValid())
3539 dismissal_state = AutofillMetrics::DIALOG_CANCELED_NO_INVALID_FIELDS;
3541 dismissal_state = AutofillMetrics::DIALOG_CANCELED_WITH_INVALID_FIELDS;
3543 GetMetricLogger().LogDialogDismissalState(dismissal_state);
3545 GetMetricLogger().LogDialogUiDuration(
3546 base::Time::Now() - dialog_shown_timestamp_,
3547 AutofillMetrics::DIALOG_CANCELED);
3550 void AutofillDialogControllerImpl::LogSuggestionItemSelectedMetric(
3551 const SuggestionsMenuModel& model) {
3552 DialogSection section = SectionForSuggestionsMenuModel(model);
3554 AutofillMetrics::DialogUiEvent dialog_ui_event;
3555 if (model.GetItemKeyForCheckedItem() == kAddNewItemKey) {
3556 // Selected to add a new item.
3557 dialog_ui_event = common::DialogSectionToUiItemAddedEvent(section);
3558 } else if (IsASuggestionItemKey(model.GetItemKeyForCheckedItem())) {
3559 // Selected an existing item.
3560 dialog_ui_event = common::DialogSectionToUiSelectionChangedEvent(section);
3562 // TODO(estade): add logging for "Manage items" or "Use billing for
3567 GetMetricLogger().LogDialogUiEvent(dialog_ui_event);
3570 void AutofillDialogControllerImpl::LogDialogLatencyToShow() {
3571 if (was_ui_latency_logged_)
3574 GetMetricLogger().LogDialogLatencyToShow(
3575 base::Time::Now() - dialog_shown_timestamp_);
3576 was_ui_latency_logged_ = true;
3579 AutofillMetrics::DialogInitialUserStateMetric
3580 AutofillDialogControllerImpl::GetInitialUserState() const {
3581 // Consider a user to be an Autofill user if the user has any credit cards
3582 // or addresses saved. Check that the item count is greater than 2 because
3583 // an "empty" menu still has the "add new" menu item and "manage" menu item.
3584 const bool has_autofill_profiles =
3585 suggested_cc_.GetItemCount() > 2 ||
3586 suggested_billing_.GetItemCount() > 2;
3588 if (SignedInState() != SIGNED_IN) {
3590 return has_autofill_profiles ?
3591 AutofillMetrics::DIALOG_USER_NOT_SIGNED_IN_HAS_AUTOFILL :
3592 AutofillMetrics::DIALOG_USER_NOT_SIGNED_IN_NO_AUTOFILL;
3596 if (wallet_items_->instruments().empty()) {
3598 return has_autofill_profiles ?
3599 AutofillMetrics::DIALOG_USER_SIGNED_IN_NO_WALLET_HAS_AUTOFILL :
3600 AutofillMetrics::DIALOG_USER_SIGNED_IN_NO_WALLET_NO_AUTOFILL;
3603 // Has Wallet items.
3604 return has_autofill_profiles ?
3605 AutofillMetrics::DIALOG_USER_SIGNED_IN_HAS_WALLET_HAS_AUTOFILL :
3606 AutofillMetrics::DIALOG_USER_SIGNED_IN_HAS_WALLET_NO_AUTOFILL;
3609 void AutofillDialogControllerImpl::MaybeShowCreditCardBubble() {
3610 if (!data_was_passed_back_)
3613 if (newly_saved_card_) {
3614 scoped_ptr<AutofillProfile> billing_profile;
3615 if (IsManuallyEditingSection(SECTION_BILLING)) {
3616 // Scrape the view as the user's entering or updating information.
3617 FieldValueMap outputs;
3618 view_->GetUserInput(SECTION_BILLING, &outputs);
3619 billing_profile.reset(new AutofillProfile);
3620 FillFormGroupFromOutputs(outputs, billing_profile.get());
3622 // Just snag the currently suggested profile.
3623 std::string item_key = SuggestionsMenuModelForSection(SECTION_BILLING)->
3624 GetItemKeyForCheckedItem();
3625 AutofillProfile* profile = GetManager()->GetProfileByGUID(item_key);
3626 billing_profile.reset(new AutofillProfile(*profile));
3629 ShowNewCreditCardBubble(newly_saved_card_.Pass(),
3630 billing_profile.Pass());
3634 if (!full_wallet_ || !full_wallet_->billing_address())
3637 GeneratedCreditCardBubbleController::Show(
3639 full_wallet_->TypeAndLastFourDigits(),
3640 backing_card_last_four_);
3643 void AutofillDialogControllerImpl::OnSubmitButtonDelayEnd() {
3646 ScopedViewUpdates updates(view_.get());
3647 view_->UpdateButtonStrip();
3650 void AutofillDialogControllerImpl::FetchWalletCookie() {
3651 net::URLRequestContextGetter* request_context = profile_->GetRequestContext();
3652 signin_helper_.reset(new wallet::WalletSigninHelper(this, request_context));
3653 signin_helper_->StartWalletCookieValueFetch();
3656 } // namespace autofill