autofill_dialog_controller_impl.cc revision a3f6a49ab37290eeeb8db0f41ec0f1cb74a68be7
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. 4 5#include "chrome/browser/ui/autofill/autofill_dialog_controller_impl.h" 6 7#include <algorithm> 8#include <map> 9#include <string> 10 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_view.h" 33#include "chrome/browser/ui/autofill/data_model_wrapper.h" 34#if !defined(OS_ANDROID) 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#endif 38#include "chrome/browser/ui/browser.h" 39#include "chrome/browser/ui/browser_finder.h" 40#include "chrome/browser/ui/browser_navigator.h" 41#include "chrome/browser/ui/browser_window.h" 42#include "chrome/common/chrome_version_info.h" 43#include "chrome/common/pref_names.h" 44#include "chrome/common/render_messages.h" 45#include "chrome/common/url_constants.h" 46#include "components/autofill/content/browser/risk/fingerprint.h" 47#include "components/autofill/content/browser/risk/proto/fingerprint.pb.h" 48#include "components/autofill/content/browser/wallet/form_field_error.h" 49#include "components/autofill/content/browser/wallet/full_wallet.h" 50#include "components/autofill/content/browser/wallet/gaia_account.h" 51#include "components/autofill/content/browser/wallet/instrument.h" 52#include "components/autofill/content/browser/wallet/wallet_address.h" 53#include "components/autofill/content/browser/wallet/wallet_items.h" 54#include "components/autofill/content/browser/wallet/wallet_service_url.h" 55#include "components/autofill/content/browser/wallet/wallet_signin_helper.h" 56#include "components/autofill/core/browser/autofill_country.h" 57#include "components/autofill/core/browser/autofill_data_model.h" 58#include "components/autofill/core/browser/autofill_manager.h" 59#include "components/autofill/core/browser/autofill_type.h" 60#include "components/autofill/core/browser/personal_data_manager.h" 61#include "components/autofill/core/browser/phone_number_i18n.h" 62#include "components/autofill/core/browser/validation.h" 63#include "components/autofill/core/common/form_data.h" 64#include "components/user_prefs/pref_registry_syncable.h" 65#include "content/public/browser/browser_thread.h" 66#include "content/public/browser/geolocation_provider.h" 67#include "content/public/browser/navigation_controller.h" 68#include "content/public/browser/navigation_details.h" 69#include "content/public/browser/navigation_entry.h" 70#include "content/public/browser/notification_service.h" 71#include "content/public/browser/notification_types.h" 72#include "content/public/browser/render_view_host.h" 73#include "content/public/browser/web_contents.h" 74#include "content/public/browser/web_contents_view.h" 75#include "content/public/common/url_constants.h" 76#include "grit/chromium_strings.h" 77#include "grit/component_strings.h" 78#include "grit/generated_resources.h" 79#include "grit/platform_locale_settings.h" 80#include "grit/theme_resources.h" 81#include "grit/webkit_resources.h" 82#include "net/cert/cert_status_flags.h" 83#include "ui/base/base_window.h" 84#include "ui/base/l10n/l10n_util.h" 85#include "ui/base/models/combobox_model.h" 86#include "ui/base/resource/resource_bundle.h" 87#include "ui/events/event.h" 88#include "ui/gfx/canvas.h" 89#include "ui/gfx/image/image_skia_operations.h" 90#include "ui/gfx/skia_util.h" 91 92namespace autofill { 93 94namespace { 95 96const char kAddNewItemKey[] = "add-new-item"; 97const char kManageItemsKey[] = "manage-items"; 98const char kSameAsBillingKey[] = "same-as-billing"; 99 100// URLs for Wallet error messages. 101const char kBuyerLegalAddressStatusUrl[] = 102 "https://wallet.google.com/manage/settings"; 103const char kKnowYourCustomerStatusUrl[] = "https://wallet.google.com/kyc"; 104 105// Keys for the kAutofillDialogAutofillDefault pref dictionary (do not change 106// these values). 107const char kGuidPrefKey[] = "guid"; 108 109// This string is stored along with saved addresses and credit cards in the 110// WebDB, and hence should not be modified, so that it remains consistent over 111// time. 112const char kAutofillDialogOrigin[] = "Chrome Autofill dialog"; 113 114// HSL shift to gray out an image. 115const color_utils::HSL kGrayImageShift = {-1, 0, 0.8}; 116 117// Limit Wallet items refresh rate to at most once per minute. 118const int64 kWalletItemsRefreshRateSeconds = 60; 119 120// The number of milliseconds to delay enabling the submit button after showing 121// the dialog. This delay prevents users from accidentally clicking the submit 122// button on startup. 123const int kSubmitButtonDelayMs = 1000; 124 125// A helper class to make sure an AutofillDialogView knows when a series of 126// updates is incoming. 127class ScopedViewUpdates { 128 public: 129 explicit ScopedViewUpdates(AutofillDialogView* view) : view_(view) { 130 if (view_) 131 view_->UpdatesStarted(); 132 } 133 134 ~ScopedViewUpdates() { 135 if (view_) 136 view_->UpdatesFinished(); 137 } 138 139 private: 140 AutofillDialogView* view_; 141 142 DISALLOW_COPY_AND_ASSIGN(ScopedViewUpdates); 143}; 144 145// Returns true if |input| should be used to fill a site-requested |field| which 146// is notated with a "shipping" tag, for use when the user has decided to use 147// the billing address as the shipping address. 148bool DetailInputMatchesShippingField(const DetailInput& input, 149 const AutofillField& field) { 150 // Equivalent billing field type is used to support UseBillingAsShipping 151 // usecase. 152 ServerFieldType field_type = 153 AutofillType::GetEquivalentBillingFieldType( 154 field.Type().GetStorableType()); 155 156 return common::InputTypeMatchesFieldType(input, AutofillType(field_type)); 157} 158 159// Initializes |form_group| from user-entered data. 160void FillFormGroupFromOutputs(const FieldValueMap& detail_outputs, 161 FormGroup* form_group) { 162 for (FieldValueMap::const_iterator iter = detail_outputs.begin(); 163 iter != detail_outputs.end(); ++iter) { 164 ServerFieldType type = iter->first; 165 if (!iter->second.empty()) { 166 if (type == ADDRESS_HOME_COUNTRY || type == ADDRESS_BILLING_COUNTRY) { 167 form_group->SetInfo(AutofillType(type), 168 iter->second, 169 g_browser_process->GetApplicationLocale()); 170 } else { 171 form_group->SetRawInfo( 172 AutofillType(type).GetStorableType(), iter->second); 173 } 174 } 175 } 176} 177 178// Get billing info from |output| and put it into |card|, |cvc|, and |profile|. 179// These outparams are required because |card|/|profile| accept different types 180// of raw info, and CreditCard doesn't save CVCs. 181void GetBillingInfoFromOutputs(const FieldValueMap& output, 182 CreditCard* card, 183 base::string16* cvc, 184 AutofillProfile* profile) { 185 for (FieldValueMap::const_iterator it = output.begin(); 186 it != output.end(); ++it) { 187 const ServerFieldType type = it->first; 188 base::string16 trimmed; 189 TrimWhitespace(it->second, TRIM_ALL, &trimmed); 190 191 // Special case CVC as CreditCard just swallows it. 192 if (type == CREDIT_CARD_VERIFICATION_CODE) { 193 if (cvc) 194 cvc->assign(trimmed); 195 } else if (type == ADDRESS_HOME_COUNTRY || 196 type == ADDRESS_BILLING_COUNTRY) { 197 if (profile) { 198 profile->SetInfo(AutofillType(type), 199 trimmed, 200 g_browser_process->GetApplicationLocale()); 201 } 202 } else { 203 // Copy the credit card name to |profile| in addition to |card| as 204 // wallet::Instrument requires a recipient name for its billing address. 205 if (card && type == NAME_FULL) 206 card->SetRawInfo(CREDIT_CARD_NAME, trimmed); 207 208 if (common::IsCreditCardType(type)) { 209 if (card) 210 card->SetRawInfo(type, trimmed); 211 } else if (profile) { 212 profile->SetRawInfo(AutofillType(type).GetStorableType(), trimmed); 213 } 214 } 215 } 216} 217 218// Returns the containing window for the given |web_contents|. The containing 219// window might be a browser window for a Chrome tab, or it might be a shell 220// window for a platform app. 221ui::BaseWindow* GetBaseWindowForWebContents( 222 const content::WebContents* web_contents) { 223 Browser* browser = chrome::FindBrowserWithWebContents(web_contents); 224 if (browser) 225 return browser->window(); 226 227 gfx::NativeWindow native_window = 228 web_contents->GetView()->GetTopLevelNativeWindow(); 229 apps::ShellWindow* shell_window = 230 apps::ShellWindowRegistry:: 231 GetShellWindowForNativeWindowAnyProfile(native_window); 232 return shell_window->GetBaseWindow(); 233} 234 235// Returns a string descriptor for a DialogSection, for use with prefs (do not 236// change these values). 237std::string SectionToPrefString(DialogSection section) { 238 switch (section) { 239 case SECTION_CC: 240 return "cc"; 241 242 case SECTION_BILLING: 243 return "billing"; 244 245 case SECTION_CC_BILLING: 246 // The SECTION_CC_BILLING section isn't active when using Autofill. 247 NOTREACHED(); 248 return std::string(); 249 250 case SECTION_SHIPPING: 251 return "shipping"; 252 } 253 254 NOTREACHED(); 255 return std::string(); 256} 257 258// Check if a given MaskedInstrument is allowed for the purchase. 259bool IsInstrumentAllowed( 260 const wallet::WalletItems::MaskedInstrument& instrument) { 261 switch (instrument.status()) { 262 case wallet::WalletItems::MaskedInstrument::VALID: 263 case wallet::WalletItems::MaskedInstrument::PENDING: 264 case wallet::WalletItems::MaskedInstrument::EXPIRED: 265 case wallet::WalletItems::MaskedInstrument::BILLING_INCOMPLETE: 266 return true; 267 default: 268 return false; 269 } 270} 271 272// Signals that the user has opted in to geolocation services. Factored out 273// into a separate method because all interaction with the geolocation provider 274// needs to happen on the IO thread, which is not the thread 275// AutofillDialogViewDelegate lives on. 276void UserDidOptIntoLocationServices() { 277 content::GeolocationProvider::GetInstance()->UserDidOptIntoLocationServices(); 278} 279 280// Returns whether |data_model| is complete, i.e. can fill out all the 281// |requested_fields|, and verified, i.e. not just automatically aggregated. 282// Incomplete or unverifed data will not be displayed in the dropdown menu. 283bool HasCompleteAndVerifiedData(const AutofillDataModel& data_model, 284 const DetailInputs& requested_fields) { 285 if (!data_model.IsVerified()) 286 return false; 287 288 for (size_t i = 0; i < requested_fields.size(); ++i) { 289 ServerFieldType type = 290 AutofillType(requested_fields[i].type).GetStorableType(); 291 if (type != ADDRESS_HOME_LINE2 && 292 type != CREDIT_CARD_VERIFICATION_CODE && 293 data_model.GetRawInfo(type).empty()) { 294 return false; 295 } 296 } 297 298 return true; 299} 300 301// Returns true if |profile| has an invalid address, i.e. an invalid state, zip 302// code, phone number, or email address. Otherwise returns false. Profiles with 303// invalid addresses are not suggested in the dropdown menu for billing and 304// shipping addresses. 305bool HasInvalidAddress(const AutofillProfile& profile) { 306 return profile.IsPresentButInvalid(ADDRESS_HOME_STATE) || 307 profile.IsPresentButInvalid(ADDRESS_HOME_ZIP) || 308 profile.IsPresentButInvalid(PHONE_HOME_WHOLE_NUMBER); 309} 310 311// Loops through |addresses_| comparing to |address| ignoring ID. If a match 312// is not found, NULL is returned. 313const wallet::Address* FindDuplicateAddress( 314 const std::vector<wallet::Address*>& addresses, 315 const wallet::Address& address) { 316 for (size_t i = 0; i < addresses.size(); ++i) { 317 if (addresses[i]->EqualsIgnoreID(address)) 318 return addresses[i]; 319 } 320 return NULL; 321} 322 323bool IsCardHolderNameValidForWallet(const base::string16& name) { 324 base::string16 whitespace_collapsed_name = CollapseWhitespace(name, true); 325 std::vector<base::string16> split_name; 326 base::SplitString(whitespace_collapsed_name, ' ', &split_name); 327 return split_name.size() >= 2; 328} 329 330DialogSection SectionFromLocation(wallet::FormFieldError::Location location) { 331 switch (location) { 332 case wallet::FormFieldError::PAYMENT_INSTRUMENT: 333 case wallet::FormFieldError::LEGAL_ADDRESS: 334 return SECTION_CC_BILLING; 335 336 case wallet::FormFieldError::SHIPPING_ADDRESS: 337 return SECTION_SHIPPING; 338 339 case wallet::FormFieldError::UNKNOWN_LOCATION: 340 NOTREACHED(); 341 return SECTION_MAX; 342 } 343 344 NOTREACHED(); 345 return SECTION_MAX; 346} 347 348scoped_ptr<DialogNotification> GetWalletError( 349 wallet::WalletClient::ErrorType error_type) { 350 base::string16 text; 351 GURL url; 352 353 switch (error_type) { 354 case wallet::WalletClient::UNVERIFIED_KNOW_YOUR_CUSTOMER_STATUS: 355 text = l10n_util::GetStringUTF16( 356 IDS_AUTOFILL_WALLET_UNVERIFIED_KNOW_YOUR_CUSTOMER_STATUS); 357 url = GURL(kKnowYourCustomerStatusUrl); 358 break; 359 360 case wallet::WalletClient::BUYER_LEGAL_ADDRESS_NOT_SUPPORTED: 361 text = l10n_util::GetStringUTF16( 362 IDS_AUTOFILL_WALLET_BUYER_COUNTRY_NOT_SUPPORTED); 363 url = GURL(kBuyerLegalAddressStatusUrl); 364 break; 365 366 default: 367 // The notification will not have a link; it's handled in the next 368 // switch statement. 369 break; 370 } 371 372 if (!text.empty()) { 373 scoped_ptr<DialogNotification> notification(new DialogNotification( 374 DialogNotification::WALLET_ERROR, 375 text)); 376 notification->set_link_url(url); 377 return notification.Pass(); 378 } 379 380 int error_ids = 0; 381 int error_code = 0; 382 383 switch (error_type) { 384 case wallet::WalletClient::UNSUPPORTED_MERCHANT: 385 error_ids = IDS_AUTOFILL_WALLET_UNSUPPORTED_MERCHANT; 386 break; 387 388 case wallet::WalletClient::BAD_REQUEST: 389 error_ids = IDS_AUTOFILL_WALLET_UPGRADE_CHROME_ERROR; 390 error_code = 71; 391 break; 392 393 case wallet::WalletClient::INVALID_PARAMS: 394 error_ids = IDS_AUTOFILL_WALLET_UPGRADE_CHROME_ERROR; 395 error_code = 42; 396 break; 397 398 case wallet::WalletClient::BUYER_ACCOUNT_ERROR: 399 error_ids = IDS_AUTOFILL_WALLET_BUYER_ACCOUNT_ERROR; 400 error_code = 12; 401 break; 402 403 case wallet::WalletClient::UNSUPPORTED_API_VERSION: 404 error_ids = IDS_AUTOFILL_WALLET_UPGRADE_CHROME_ERROR; 405 error_code = 43; 406 break; 407 408 case wallet::WalletClient::SERVICE_UNAVAILABLE: 409 error_ids = IDS_AUTOFILL_WALLET_SERVICE_UNAVAILABLE_ERROR; 410 error_code = 61; 411 break; 412 413 case wallet::WalletClient::INTERNAL_ERROR: 414 error_ids = IDS_AUTOFILL_WALLET_UNKNOWN_ERROR; 415 error_code = 62; 416 break; 417 418 case wallet::WalletClient::MALFORMED_RESPONSE: 419 error_ids = IDS_AUTOFILL_WALLET_UNKNOWN_ERROR; 420 error_code = 72; 421 break; 422 423 case wallet::WalletClient::NETWORK_ERROR: 424 error_ids = IDS_AUTOFILL_WALLET_UNKNOWN_ERROR; 425 error_code = 73; 426 break; 427 428 case wallet::WalletClient::UNKNOWN_ERROR: 429 error_ids = IDS_AUTOFILL_WALLET_UNKNOWN_ERROR; 430 error_code = 74; 431 break; 432 433 default: 434 break; 435 } 436 437 DCHECK_NE(0, error_ids); 438 439 // The other error types are strings of the form "XXX. You can pay without 440 // wallet." 441 scoped_ptr<DialogNotification> notification(new DialogNotification( 442 DialogNotification::WALLET_ERROR, 443 l10n_util::GetStringFUTF16(IDS_AUTOFILL_DIALOG_COMPLETE_WITHOUT_WALLET, 444 l10n_util::GetStringUTF16(error_ids)))); 445 446 if (error_code) { 447 notification->set_tooltip_text( 448 l10n_util::GetStringFUTF16(IDS_AUTOFILL_WALLET_ERROR_CODE_TOOLTIP, 449 base::IntToString16(error_code))); 450 } 451 452 return notification.Pass(); 453} 454 455// Returns the ID of the address or instrument that should be selected in the 456// UI, given that the |default_id| is currently the default ID on the Wallet 457// server, |previous_default_id| was the default ID prior to re-fetching the 458// Wallet data, and |previously_selected_id| was the ID of the item selected in 459// the dialog prior to re-fetching the Wallet data. 460std::string GetIdToSelect(const std::string& default_id, 461 const std::string& previous_default_id, 462 const std::string& previously_selected_id) { 463 // If the default ID changed since the last fetch of the Wallet data, select 464 // it rather than the previously selected item, as the user's intention in 465 // changing the default was probably to use it. 466 if (default_id != previous_default_id) 467 return default_id; 468 469 // Otherwise, prefer the previously selected item, if there was one. 470 return !previously_selected_id.empty() ? previously_selected_id : default_id; 471} 472 473// Generate a random card number in a user displayable format. 474base::string16 GenerateRandomCardNumber() { 475 std::string card_number; 476 for (size_t i = 0; i < 4; ++i) { 477 int part = base::RandInt(0, 10000); 478 base::StringAppendF(&card_number, "%04d ", part); 479 } 480 return ASCIIToUTF16(card_number); 481} 482 483gfx::Image CreditCardIconForType(const std::string& credit_card_type) { 484 const int input_card_idr = CreditCard::IconResourceId(credit_card_type); 485 ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance(); 486 gfx::Image result = rb.GetImageNamed(input_card_idr); 487 if (input_card_idr == IDR_AUTOFILL_CC_GENERIC) { 488 // When the credit card type is unknown, no image should be shown. However, 489 // to simplify the view code on Mac, save space for the credit card image by 490 // returning a transparent image of the appropriate size. 491 result = gfx::Image(gfx::ImageSkiaOperations::CreateTransparentImage( 492 result.AsImageSkia(), 0)); 493 } 494 return result; 495} 496 497gfx::Image CvcIconForCreditCardType(const base::string16& credit_card_type) { 498 ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance(); 499 if (credit_card_type == l10n_util::GetStringUTF16(IDS_AUTOFILL_CC_AMEX)) 500 return rb.GetImageNamed(IDR_CREDIT_CARD_CVC_HINT_AMEX); 501 502 return rb.GetImageNamed(IDR_CREDIT_CARD_CVC_HINT); 503} 504 505} // namespace 506 507AutofillDialogViewDelegate::~AutofillDialogViewDelegate() {} 508 509AutofillDialogControllerImpl::~AutofillDialogControllerImpl() { 510 if (popup_controller_) 511 popup_controller_->Hide(); 512 513 GetMetricLogger().LogDialogInitialUserState(initial_user_state_); 514} 515 516// static 517base::WeakPtr<AutofillDialogControllerImpl> 518 AutofillDialogControllerImpl::Create( 519 content::WebContents* contents, 520 const FormData& form_structure, 521 const GURL& source_url, 522 const base::Callback<void(const FormStructure*)>& callback) { 523 // AutofillDialogControllerImpl owns itself. 524 AutofillDialogControllerImpl* autofill_dialog_controller = 525 new AutofillDialogControllerImpl(contents, 526 form_structure, 527 source_url, 528 callback); 529 return autofill_dialog_controller->weak_ptr_factory_.GetWeakPtr(); 530} 531 532// static 533void AutofillDialogController::RegisterPrefs(PrefRegistrySimple* registry) { 534 registry->RegisterListPref(::prefs::kAutofillDialogWalletLocationAcceptance); 535} 536 537// static 538void AutofillDialogController::RegisterProfilePrefs( 539 user_prefs::PrefRegistrySyncable* registry) { 540 registry->RegisterBooleanPref( 541 ::prefs::kAutofillDialogPayWithoutWallet, 542 false, 543 user_prefs::PrefRegistrySyncable::SYNCABLE_PREF); 544 registry->RegisterDictionaryPref( 545 ::prefs::kAutofillDialogAutofillDefault, 546 user_prefs::PrefRegistrySyncable::SYNCABLE_PREF); 547 registry->RegisterBooleanPref( 548 ::prefs::kAutofillDialogSaveData, 549 true, 550 user_prefs::PrefRegistrySyncable::SYNCABLE_PREF); 551} 552 553// static 554base::WeakPtr<AutofillDialogController> AutofillDialogController::Create( 555 content::WebContents* contents, 556 const FormData& form_structure, 557 const GURL& source_url, 558 const base::Callback<void(const FormStructure*)>& callback) { 559 return AutofillDialogControllerImpl::Create(contents, 560 form_structure, 561 source_url, 562 callback); 563} 564 565void AutofillDialogControllerImpl::Show() { 566 dialog_shown_timestamp_ = base::Time::Now(); 567 568 // The Autofill dialog is shown in response to a message from the renderer and 569 // as such, it can only be made in the context of the current document. A call 570 // to GetActiveEntry would return a pending entry, if there was one, which 571 // would be a security bug. Therefore, we use the last committed URL for the 572 // access checks. 573 const GURL& current_url = web_contents()->GetLastCommittedURL(); 574 invoked_from_same_origin_ = 575 current_url.GetOrigin() == source_url_.GetOrigin(); 576 577 // Log any relevant UI metrics and security exceptions. 578 GetMetricLogger().LogDialogUiEvent(AutofillMetrics::DIALOG_UI_SHOWN); 579 580 GetMetricLogger().LogDialogSecurityMetric( 581 AutofillMetrics::SECURITY_METRIC_DIALOG_SHOWN); 582 583 // Determine what field types should be included in the dialog. 584 // Note that RequestingCreditCardInfo() below relies on parsed field types. 585 bool has_types = false; 586 bool has_sections = false; 587 form_structure_.ParseFieldTypesFromAutocompleteAttributes( 588 &has_types, &has_sections); 589 590 if (RequestingCreditCardInfo() && !TransmissionWillBeSecure()) { 591 GetMetricLogger().LogDialogSecurityMetric( 592 AutofillMetrics::SECURITY_METRIC_CREDIT_CARD_OVER_HTTP); 593 } 594 595 if (!invoked_from_same_origin_) { 596 GetMetricLogger().LogDialogSecurityMetric( 597 AutofillMetrics::SECURITY_METRIC_CROSS_ORIGIN_FRAME); 598 } 599 600 // Fail if the author didn't specify autocomplete types. 601 if (!has_types) { 602 callback_.Run(NULL); 603 delete this; 604 return; 605 } 606 607 common::BuildInputsForSection(SECTION_CC, 608 &requested_cc_fields_); 609 common::BuildInputsForSection(SECTION_BILLING, 610 &requested_billing_fields_); 611 common::BuildInputsForSection(SECTION_CC_BILLING, 612 &requested_cc_billing_fields_); 613 common::BuildInputsForSection(SECTION_SHIPPING, 614 &requested_shipping_fields_); 615 616 // Test whether we need to show the shipping section. If filling that section 617 // would be a no-op, don't show it. 618 const DetailInputs& inputs = RequestedFieldsForSection(SECTION_SHIPPING); 619 EmptyDataModelWrapper empty_wrapper; 620 cares_about_shipping_ = empty_wrapper.FillFormStructure( 621 inputs, 622 base::Bind(common::DetailInputMatchesField, SECTION_SHIPPING), 623 &form_structure_); 624 625 account_chooser_model_.reset( 626 new AccountChooserModel(this, 627 profile_, 628 !ShouldShowAccountChooser(), 629 metric_logger_)); 630 631 if (account_chooser_model_->WalletIsSelected()) 632 FetchWalletCookie(); 633 634 // TODO(estade): don't show the dialog if the site didn't specify the right 635 // fields. First we must figure out what the "right" fields are. 636 SuggestionsUpdated(); 637 SubmitButtonDelayBegin(); 638 view_.reset(CreateView()); 639 view_->Show(); 640 GetManager()->AddObserver(this); 641 642 if (!account_chooser_model_->WalletIsSelected()) 643 LogDialogLatencyToShow(); 644} 645 646void AutofillDialogControllerImpl::Hide() { 647 if (view_) 648 view_->Hide(); 649} 650 651void AutofillDialogControllerImpl::TabActivated() { 652 // If the user switched away from this tab and then switched back, reload the 653 // Wallet items, in case they've changed. 654 int64 seconds_elapsed_since_last_refresh = 655 (base::TimeTicks::Now() - last_wallet_items_fetch_timestamp_).InSeconds(); 656 if (IsPayingWithWallet() && wallet_items_ && 657 seconds_elapsed_since_last_refresh >= kWalletItemsRefreshRateSeconds) { 658 GetWalletItems(); 659 } 660} 661 662TestableAutofillDialogView* AutofillDialogControllerImpl::GetTestableView() { 663 return view_ ? view_->GetTestableView() : NULL; 664} 665 666//////////////////////////////////////////////////////////////////////////////// 667// AutofillDialogViewDelegate implementation. 668 669base::string16 AutofillDialogControllerImpl::DialogTitle() const { 670 if (ShouldShowSpinner()) 671 return base::string16(); 672 673 return l10n_util::GetStringUTF16(IDS_AUTOFILL_DIALOG_TITLE); 674} 675 676base::string16 AutofillDialogControllerImpl::AccountChooserText() const { 677 if (!account_chooser_model_->WalletIsSelected()) 678 return l10n_util::GetStringUTF16(IDS_AUTOFILL_DIALOG_PAYING_WITHOUT_WALLET); 679 680 if (SignedInState() == SIGNED_IN) 681 return account_chooser_model_->GetActiveWalletAccountName(); 682 683 // In this case, the account chooser should be showing the signin link. 684 return base::string16(); 685} 686 687base::string16 AutofillDialogControllerImpl::SignInLinkText() const { 688 int ids = SignedInState() == NOT_CHECKED ? 689 IDS_AUTOFILL_DIALOG_USE_WALLET_LINK : 690 ShouldShowSignInWebView() ? IDS_AUTOFILL_DIALOG_CANCEL_SIGN_IN : 691 IDS_AUTOFILL_DIALOG_SIGN_IN; 692 693 return l10n_util::GetStringUTF16(ids); 694} 695 696base::string16 AutofillDialogControllerImpl::SpinnerText() const { 697 return l10n_util::GetStringUTF16(IDS_AUTOFILL_DIALOG_LOADING); 698} 699 700base::string16 AutofillDialogControllerImpl::EditSuggestionText() const { 701 return l10n_util::GetStringUTF16(IDS_AUTOFILL_DIALOG_EDIT); 702} 703 704base::string16 AutofillDialogControllerImpl::CancelButtonText() const { 705 return l10n_util::GetStringUTF16(IDS_CANCEL); 706} 707 708base::string16 AutofillDialogControllerImpl::ConfirmButtonText() const { 709 return l10n_util::GetStringUTF16(IsSubmitPausedOn(wallet::VERIFY_CVV) ? 710 IDS_AUTOFILL_DIALOG_VERIFY_BUTTON : IDS_AUTOFILL_DIALOG_SUBMIT_BUTTON); 711} 712 713base::string16 AutofillDialogControllerImpl::SaveLocallyText() const { 714 return l10n_util::GetStringUTF16(IDS_AUTOFILL_DIALOG_SAVE_LOCALLY_CHECKBOX); 715} 716 717base::string16 AutofillDialogControllerImpl::SaveLocallyTooltip() const { 718 return l10n_util::GetStringUTF16(IDS_AUTOFILL_DIALOG_SAVE_LOCALLY_TOOLTIP); 719} 720 721base::string16 AutofillDialogControllerImpl::LegalDocumentsText() { 722 if (!IsPayingWithWallet() || ShouldShowSignInWebView()) 723 return base::string16(); 724 725 return legal_documents_text_; 726} 727 728bool AutofillDialogControllerImpl::ShouldShowSpinner() const { 729 return SignedInState() == REQUIRES_RESPONSE || 730 SignedInState() == REQUIRES_PASSIVE_SIGN_IN; 731} 732 733bool AutofillDialogControllerImpl::ShouldShowAccountChooser() const { 734 return GetManager()->GetDefaultCountryCodeForNewAddress() == "US" && 735 !ShouldShowSpinner(); 736} 737 738bool AutofillDialogControllerImpl::ShouldShowSignInWebView() const { 739 return !signin_registrar_.IsEmpty(); 740} 741 742GURL AutofillDialogControllerImpl::SignInUrl() const { 743 return wallet::GetSignInUrl(); 744} 745 746bool AutofillDialogControllerImpl::ShouldOfferToSaveInChrome() const { 747 return !IsPayingWithWallet() && 748 !profile_->IsOffTheRecord() && 749 IsManuallyEditingAnySection() && 750 !ShouldShowSpinner(); 751} 752 753bool AutofillDialogControllerImpl::ShouldSaveInChrome() const { 754 return profile_->GetPrefs()->GetBoolean(::prefs::kAutofillDialogSaveData); 755} 756 757int AutofillDialogControllerImpl::GetDialogButtons() const { 758 if (waiting_for_explicit_sign_in_response_) 759 return ui::DIALOG_BUTTON_NONE; 760 761 if (ShouldShowSpinner() && !handling_use_wallet_link_click_) 762 return ui::DIALOG_BUTTON_CANCEL; 763 764 return ui::DIALOG_BUTTON_OK | ui::DIALOG_BUTTON_CANCEL; 765} 766 767bool AutofillDialogControllerImpl::IsDialogButtonEnabled( 768 ui::DialogButton button) const { 769 if (button == ui::DIALOG_BUTTON_OK) { 770 if (IsSubmitPausedOn(wallet::VERIFY_CVV)) 771 return true; 772 773 if (ShouldShowSpinner() || is_submitting_) 774 return false; 775 776 if (submit_button_delay_timer_.IsRunning()) 777 return false; 778 779 return true; 780 } 781 782 DCHECK_EQ(ui::DIALOG_BUTTON_CANCEL, button); 783 return !is_submitting_ || IsSubmitPausedOn(wallet::VERIFY_CVV); 784} 785 786DialogOverlayState AutofillDialogControllerImpl::GetDialogOverlay() { 787 bool show_wallet_interstitial = IsPayingWithWallet() && is_submitting_ && 788 !(full_wallet_ && !full_wallet_->required_actions().empty()); 789 if (!show_wallet_interstitial) { 790 card_scrambling_delay_.Stop(); 791 card_scrambling_refresher_.Stop(); 792 return DialogOverlayState(); 793 } 794 795 ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance(); 796 DialogOverlayState state; 797 state.string.font = rb.GetFont(ui::ResourceBundle::BaseFont).DeriveFont(3); 798 state.string.text_color = SK_ColorDKGRAY; 799 800 const SkColor start_top_color = SkColorSetRGB(0xD6, 0xD6, 0xD6); 801 const SkColor start_bottom_color = SkColorSetRGB(0x98, 0x98, 0x98); 802 const SkColor final_top_color = SkColorSetRGB(0x52, 0x9F, 0xF8); 803 const SkColor final_bottom_color = SkColorSetRGB(0x22, 0x75, 0xE5); 804 805 if (full_wallet_ && full_wallet_->required_actions().empty()) { 806 card_scrambling_delay_.Stop(); 807 card_scrambling_refresher_.Stop(); 808 809 base::string16 cc_number = 810 full_wallet_->GetInfo(AutofillType(CREDIT_CARD_NUMBER)); 811 DCHECK_GE(cc_number.size(), 4U); 812 state.image = GetGeneratedCardImage( 813 ASCIIToUTF16("XXXX XXXX XXXX ") + 814 cc_number.substr(cc_number.size() - 4), 815 full_wallet_->billing_address()->recipient_name(), 816 color_utils::AlphaBlend( 817 final_top_color, 818 start_top_color, 819 255 * card_generated_animation_.GetCurrentValue()), 820 color_utils::AlphaBlend( 821 final_bottom_color, 822 start_bottom_color, 823 255 * card_generated_animation_.GetCurrentValue())); 824 825 state.string.text = l10n_util::GetStringUTF16( 826 IDS_AUTOFILL_DIALOG_CARD_GENERATION_DONE); 827 } else { 828 // Start the refresher if it isn't running. Wait one second before pumping 829 // updates to the view. 830 if (!card_scrambling_delay_.IsRunning() && 831 !card_scrambling_refresher_.IsRunning()) { 832 scrambled_card_number_ = GenerateRandomCardNumber(); 833 card_scrambling_delay_.Start( 834 FROM_HERE, 835 base::TimeDelta::FromSeconds(1), 836 this, 837 &AutofillDialogControllerImpl::StartCardScramblingRefresher); 838 } 839 840 DCHECK(!scrambled_card_number_.empty()); 841 state.image = GetGeneratedCardImage( 842 scrambled_card_number_, 843 submitted_cardholder_name_, 844 start_top_color, 845 start_bottom_color); 846 847 // "Submitting" waiting page. 848 state.string.text = l10n_util::GetStringUTF16( 849 IDS_AUTOFILL_DIALOG_CARD_GENERATION_IN_PROGRESS); 850 } 851 852 return state; 853} 854 855const std::vector<gfx::Range>& AutofillDialogControllerImpl:: 856 LegalDocumentLinks() { 857 return legal_document_link_ranges_; 858} 859 860bool AutofillDialogControllerImpl::SectionIsActive(DialogSection section) 861 const { 862 if (IsSubmitPausedOn(wallet::VERIFY_CVV)) 863 return section == SECTION_CC_BILLING; 864 865 if (!FormStructureCaresAboutSection(section)) 866 return false; 867 868 if (IsPayingWithWallet()) 869 return section == SECTION_CC_BILLING || section == SECTION_SHIPPING; 870 871 return section != SECTION_CC_BILLING; 872} 873 874void AutofillDialogControllerImpl::GetWalletItems() { 875 ScopedViewUpdates updates(view_.get()); 876 877 wallet_items_requested_ = true; 878 wallet::WalletClient* wallet_client = GetWalletClient(); 879 wallet_client->CancelRequests(); 880 881 previously_selected_instrument_id_.clear(); 882 previously_selected_shipping_address_id_.clear(); 883 if (wallet_items_) { 884 previous_default_instrument_id_ = wallet_items_->default_instrument_id(); 885 previous_default_shipping_address_id_ = wallet_items_->default_address_id(); 886 887 const wallet::WalletItems::MaskedInstrument* instrument = 888 ActiveInstrument(); 889 if (instrument) 890 previously_selected_instrument_id_ = instrument->object_id(); 891 892 const wallet::Address* address = ActiveShippingAddress(); 893 if (address) 894 previously_selected_shipping_address_id_ = address->object_id(); 895 } 896 897 last_wallet_items_fetch_timestamp_ = base::TimeTicks::Now(); 898 passive_failed_ = false; 899 wallet_items_.reset(); 900 901 // The "Loading..." page should be showing now, which should cause the 902 // account chooser to hide. 903 view_->UpdateAccountChooser(); 904 wallet_client->GetWalletItems(); 905} 906 907void AutofillDialogControllerImpl::HideSignIn() { 908 ScopedViewUpdates updates(view_.get()); 909 signin_registrar_.RemoveAll(); 910 view_->HideSignIn(); 911 view_->UpdateAccountChooser(); 912} 913 914AutofillDialogControllerImpl::DialogSignedInState 915 AutofillDialogControllerImpl::SignedInState() const { 916 if (wallet_error_notification_) 917 return SIGN_IN_DISABLED; 918 919 if (signin_helper_ || (wallet_items_requested_ && !wallet_items_)) 920 return REQUIRES_RESPONSE; 921 922 if (!wallet_items_requested_) 923 return NOT_CHECKED; 924 925 if (wallet_items_->HasRequiredAction(wallet::GAIA_AUTH) || 926 passive_failed_) { 927 return REQUIRES_SIGN_IN; 928 } 929 930 if (wallet_items_->HasRequiredAction(wallet::PASSIVE_GAIA_AUTH)) 931 return REQUIRES_PASSIVE_SIGN_IN; 932 933 return SIGNED_IN; 934} 935 936void AutofillDialogControllerImpl::SignedInStateUpdated() { 937 if (!ShouldShowSpinner()) 938 waiting_for_explicit_sign_in_response_ = false; 939 940 switch (SignedInState()) { 941 case SIGNED_IN: 942 LogDialogLatencyToShow(); 943 break; 944 945 case REQUIRES_SIGN_IN: 946 if (handling_use_wallet_link_click_) 947 SignInLinkClicked(); 948 // Fall through. 949 case SIGN_IN_DISABLED: 950 // Switch to the local account and refresh the dialog. 951 signin_helper_.reset(); 952 OnWalletSigninError(); 953 handling_use_wallet_link_click_ = false; 954 break; 955 956 case REQUIRES_PASSIVE_SIGN_IN: 957 // Attempt to passively sign in the user. 958 DCHECK(!signin_helper_); 959 signin_helper_.reset(new wallet::WalletSigninHelper( 960 this, 961 profile_->GetRequestContext())); 962 signin_helper_->StartPassiveSignin(GetWalletClient()->user_index()); 963 break; 964 965 case NOT_CHECKED: 966 case REQUIRES_RESPONSE: 967 break; 968 } 969} 970 971void AutofillDialogControllerImpl::OnWalletOrSigninUpdate() { 972 ScopedViewUpdates updates(view_.get()); 973 SignedInStateUpdated(); 974 SuggestionsUpdated(); 975 UpdateAccountChooserView(); 976 977 if (view_) { 978 view_->UpdateButtonStrip(); 979 view_->UpdateOverlay(); 980 } 981 982 // On the first successful response, compute the initial user state metric. 983 if (initial_user_state_ == AutofillMetrics::DIALOG_USER_STATE_UNKNOWN) 984 initial_user_state_ = GetInitialUserState(); 985} 986 987void AutofillDialogControllerImpl::OnWalletFormFieldError( 988 const std::vector<wallet::FormFieldError>& form_field_errors) { 989 if (form_field_errors.empty()) 990 return; 991 992 for (std::vector<wallet::FormFieldError>::const_iterator it = 993 form_field_errors.begin(); 994 it != form_field_errors.end(); ++it) { 995 if (it->error_type() == wallet::FormFieldError::UNKNOWN_ERROR || 996 it->GetAutofillType() == MAX_VALID_FIELD_TYPE || 997 it->location() == wallet::FormFieldError::UNKNOWN_LOCATION) { 998 wallet_server_validation_recoverable_ = false; 999 break; 1000 } 1001 DialogSection section = SectionFromLocation(it->location()); 1002 wallet_errors_[section][it->GetAutofillType()] = 1003 std::make_pair(it->GetErrorMessage(), 1004 GetValueFromSection(section, it->GetAutofillType())); 1005 } 1006 1007 // Unrecoverable validation errors. 1008 if (!wallet_server_validation_recoverable_) 1009 DisableWallet(wallet::WalletClient::UNKNOWN_ERROR); 1010 1011 UpdateForErrors(); 1012} 1013 1014void AutofillDialogControllerImpl::ConstructLegalDocumentsText() { 1015 legal_documents_text_.clear(); 1016 legal_document_link_ranges_.clear(); 1017 1018 if (!wallet_items_) 1019 return; 1020 1021 PrefService* local_state = g_browser_process->local_state(); 1022 // List of users who have accepted location sharing for fraud protection 1023 // on this device. 1024 const base::ListValue* accepted = 1025 local_state->GetList(::prefs::kAutofillDialogWalletLocationAcceptance); 1026 bool has_accepted_location_sharing = 1027 accepted->Find(base::StringValue( 1028 account_chooser_model_->GetActiveWalletAccountName())) != 1029 accepted->end(); 1030 1031 if (wallet_items_->legal_documents().empty()) { 1032 if (!has_accepted_location_sharing) { 1033 legal_documents_text_ = l10n_util::GetStringUTF16( 1034 IDS_AUTOFILL_DIALOG_LOCATION_DISCLOSURE); 1035 } 1036 1037 return; 1038 } 1039 1040 const std::vector<wallet::WalletItems::LegalDocument*>& documents = 1041 wallet_items_->legal_documents(); 1042 // There should never be just one document because the privacy policy doc gets 1043 // tacked on the end of other documents. 1044 DCHECK_GE(documents.size(), 2U); 1045 1046 std::vector<base::string16> link_names; 1047 for (size_t i = 0; i < documents.size(); ++i) { 1048 link_names.push_back(documents[i]->display_name()); 1049 } 1050 1051 int resource_id = 0; 1052 switch (documents.size()) { 1053 case 2U: 1054 resource_id = IDS_AUTOFILL_DIALOG_LEGAL_LINKS_2; 1055 break; 1056 case 3U: 1057 resource_id = IDS_AUTOFILL_DIALOG_LEGAL_LINKS_3; 1058 break; 1059 case 4U: 1060 resource_id = IDS_AUTOFILL_DIALOG_LEGAL_LINKS_4; 1061 break; 1062 case 5U: 1063 resource_id = IDS_AUTOFILL_DIALOG_LEGAL_LINKS_5; 1064 break; 1065 case 6U: 1066 resource_id = IDS_AUTOFILL_DIALOG_LEGAL_LINKS_6; 1067 break; 1068 default: 1069 // We can only handle so many documents. For lack of a better way of 1070 // handling document overflow, just error out if there are too many. 1071 DisableWallet(wallet::WalletClient::UNKNOWN_ERROR); 1072 return; 1073 } 1074 1075 std::vector<size_t> offsets; 1076 base::string16 text = 1077 l10n_util::GetStringFUTF16(resource_id, link_names,&offsets); 1078 1079 // Tack on the location string if need be. 1080 size_t base_offset = 0; 1081 if (!has_accepted_location_sharing) { 1082 text = l10n_util::GetStringFUTF16( 1083 IDS_AUTOFILL_DIALOG_LOCATION_DISCLOSURE_WITH_LEGAL_DOCS, 1084 text, 1085 &base_offset); 1086 } 1087 1088 for (size_t i = 0; i < documents.size(); ++i) { 1089 size_t link_start = offsets[i] + base_offset; 1090 legal_document_link_ranges_.push_back(gfx::Range( 1091 link_start, link_start + documents[i]->display_name().size())); 1092 } 1093 legal_documents_text_ = text; 1094} 1095 1096void AutofillDialogControllerImpl::ResetSectionInput(DialogSection section) { 1097 SetEditingExistingData(section, false); 1098 1099 DetailInputs* inputs = MutableRequestedFieldsForSection(section); 1100 for (DetailInputs::iterator it = inputs->begin(); it != inputs->end(); ++it) { 1101 it->initial_value = common::GetHardcodedValueForType(it->type); 1102 } 1103} 1104 1105void AutofillDialogControllerImpl::ShowEditUiIfBadSuggestion( 1106 DialogSection section) { 1107 // |CreateWrapper()| returns an empty wrapper if |IsEditingExistingData()|, so 1108 // get the wrapper before this potentially happens below. 1109 scoped_ptr<DataModelWrapper> wrapper = CreateWrapper(section); 1110 1111 // If the chosen item in |model| yields an empty suggestion text, it is 1112 // invalid. In this case, show the edit UI and highlight invalid fields. 1113 SuggestionsMenuModel* model = SuggestionsMenuModelForSection(section); 1114 base::string16 unused, unused2; 1115 if (IsASuggestionItemKey(model->GetItemKeyForCheckedItem()) && 1116 !SuggestionTextForSection(section, &unused, &unused2)) { 1117 SetEditingExistingData(section, true); 1118 } 1119 1120 DetailInputs* inputs = MutableRequestedFieldsForSection(section); 1121 if (wrapper && IsEditingExistingData(section)) 1122 wrapper->FillInputs(inputs); 1123} 1124 1125bool AutofillDialogControllerImpl::InputWasEdited(ServerFieldType type, 1126 const base::string16& value) { 1127 if (value.empty()) 1128 return false; 1129 1130 // If this is a combobox at the default value, don't preserve it. 1131 ui::ComboboxModel* model = ComboboxModelForAutofillType(type); 1132 if (model && model->GetItemAt(model->GetDefaultIndex()) == value) 1133 return false; 1134 1135 return true; 1136} 1137 1138FieldValueMap AutofillDialogControllerImpl::TakeUserInputSnapshot() { 1139 FieldValueMap snapshot; 1140 if (!view_) 1141 return snapshot; 1142 1143 for (size_t i = SECTION_MIN; i <= SECTION_MAX; ++i) { 1144 DialogSection section = static_cast<DialogSection>(i); 1145 SuggestionsMenuModel* model = SuggestionsMenuModelForSection(section); 1146 if (model->GetItemKeyForCheckedItem() != kAddNewItemKey) 1147 continue; 1148 1149 FieldValueMap outputs; 1150 view_->GetUserInput(section, &outputs); 1151 // Remove fields that are empty, at their default values, or invalid. 1152 for (FieldValueMap::iterator it = outputs.begin(); it != outputs.end(); 1153 ++it) { 1154 if (InputWasEdited(it->first, it->second) && 1155 InputValidityMessage(section, it->first, it->second).empty()) { 1156 snapshot.insert(std::make_pair(it->first, it->second)); 1157 } 1158 } 1159 } 1160 1161 return snapshot; 1162} 1163 1164void AutofillDialogControllerImpl::RestoreUserInputFromSnapshot( 1165 const FieldValueMap& snapshot) { 1166 if (snapshot.empty()) 1167 return; 1168 1169 FieldMapWrapper wrapper(snapshot); 1170 for (size_t i = SECTION_MIN; i <= SECTION_MAX; ++i) { 1171 DialogSection section = static_cast<DialogSection>(i); 1172 if (!SectionIsActive(section)) 1173 continue; 1174 1175 DetailInputs* inputs = MutableRequestedFieldsForSection(section); 1176 wrapper.FillInputs(inputs); 1177 1178 for (size_t i = 0; i < inputs->size(); ++i) { 1179 if (InputWasEdited((*inputs)[i].type, (*inputs)[i].initial_value)) { 1180 SuggestionsMenuModelForSection(section)->SetCheckedItem(kAddNewItemKey); 1181 break; 1182 } 1183 } 1184 } 1185} 1186 1187void AutofillDialogControllerImpl::UpdateSection(DialogSection section) { 1188 if (view_) 1189 view_->UpdateSection(section); 1190} 1191 1192void AutofillDialogControllerImpl::UpdateForErrors() { 1193 if (!view_) 1194 return; 1195 1196 // Currently, the view should only need to be updated if there are 1197 // |wallet_errors_| or validating a suggestion that's based on existing data. 1198 bool should_update = !wallet_errors_.empty(); 1199 if (!should_update) { 1200 for (size_t i = SECTION_MIN; i <= SECTION_MAX; ++i) { 1201 if (IsEditingExistingData(static_cast<DialogSection>(i))) { 1202 should_update = true; 1203 break; 1204 } 1205 } 1206 } 1207 1208 if (should_update) 1209 view_->UpdateForErrors(); 1210} 1211 1212gfx::Image AutofillDialogControllerImpl::GetGeneratedCardImage( 1213 const base::string16& card_number, 1214 const base::string16& name, 1215 const SkColor& gradient_top, 1216 const SkColor& gradient_bottom) { 1217 const int kCardWidthPx = 300; 1218 const int kCardHeightPx = 190; 1219 const gfx::Size size(kCardWidthPx, kCardHeightPx); 1220 ui::ScaleFactor scale_factor = ui::GetScaleFactorForNativeView( 1221 web_contents()->GetView()->GetNativeView()); 1222 gfx::Canvas canvas(size, ui::GetImageScale(scale_factor), false); 1223 1224 gfx::Rect display_rect(size); 1225 1226 skia::RefPtr<SkShader> shader = gfx::CreateGradientShader( 1227 0, size.height(), gradient_top, gradient_bottom); 1228 SkPaint paint; 1229 paint.setShader(shader.get()); 1230 canvas.DrawRoundRect(display_rect, 8, paint); 1231 1232 display_rect.Inset(20, 0, 0, 0); 1233 gfx::Font font(l10n_util::GetStringUTF8(IDS_FIXED_FONT_FAMILY), 18); 1234 gfx::FontList font_list(font); 1235 gfx::ShadowValues shadows; 1236 shadows.push_back(gfx::ShadowValue(gfx::Point(0, 1), 1.0, SK_ColorBLACK)); 1237 canvas.DrawStringRectWithShadows( 1238 card_number, 1239 font_list, 1240 SK_ColorWHITE, 1241 display_rect, 0, 0, shadows); 1242 1243 base::string16 capitalized_name = base::i18n::ToUpper(name); 1244 display_rect.Inset(0, size.height() / 2, 0, 0); 1245 canvas.DrawStringRectWithShadows( 1246 capitalized_name, 1247 font_list, 1248 SK_ColorWHITE, 1249 display_rect, 0, 0, shadows); 1250 1251 gfx::ImageSkia skia(canvas.ExtractImageRep()); 1252 return gfx::Image(skia); 1253} 1254 1255void AutofillDialogControllerImpl::StartCardScramblingRefresher() { 1256 RefreshCardScramblingOverlay(); 1257 card_scrambling_refresher_.Start( 1258 FROM_HERE, 1259 base::TimeDelta::FromMilliseconds(75), 1260 this, 1261 &AutofillDialogControllerImpl::RefreshCardScramblingOverlay); 1262} 1263 1264void AutofillDialogControllerImpl::RefreshCardScramblingOverlay() { 1265 scrambled_card_number_ = GenerateRandomCardNumber(); 1266 PushOverlayUpdate(); 1267} 1268 1269void AutofillDialogControllerImpl::PushOverlayUpdate() { 1270 if (view_) { 1271 ScopedViewUpdates updates(view_.get()); 1272 view_->UpdateOverlay(); 1273 } 1274} 1275 1276const DetailInputs& AutofillDialogControllerImpl::RequestedFieldsForSection( 1277 DialogSection section) const { 1278 switch (section) { 1279 case SECTION_CC: 1280 return requested_cc_fields_; 1281 case SECTION_BILLING: 1282 return requested_billing_fields_; 1283 case SECTION_CC_BILLING: 1284 return requested_cc_billing_fields_; 1285 case SECTION_SHIPPING: 1286 return requested_shipping_fields_; 1287 } 1288 1289 NOTREACHED(); 1290 return requested_billing_fields_; 1291} 1292 1293ui::ComboboxModel* AutofillDialogControllerImpl::ComboboxModelForAutofillType( 1294 ServerFieldType type) { 1295 switch (type) { 1296 case CREDIT_CARD_EXP_MONTH: 1297 return &cc_exp_month_combobox_model_; 1298 1299 case CREDIT_CARD_EXP_4_DIGIT_YEAR: 1300 return &cc_exp_year_combobox_model_; 1301 1302 case ADDRESS_HOME_COUNTRY: 1303 case ADDRESS_BILLING_COUNTRY: 1304 return &country_combobox_model_; 1305 1306 default: 1307 return NULL; 1308 } 1309} 1310 1311ui::MenuModel* AutofillDialogControllerImpl::MenuModelForSection( 1312 DialogSection section) { 1313 SuggestionsMenuModel* model = SuggestionsMenuModelForSection(section); 1314 // The shipping section menu is special. It will always show because there is 1315 // a choice between "Use billing" and "enter new". 1316 if (section == SECTION_SHIPPING) 1317 return model; 1318 1319 // For other sections, only show a menu if there's at least one suggestion. 1320 for (int i = 0; i < model->GetItemCount(); ++i) { 1321 if (IsASuggestionItemKey(model->GetItemKeyAt(i))) 1322 return model; 1323 } 1324 1325 return NULL; 1326} 1327 1328ui::MenuModel* AutofillDialogControllerImpl::MenuModelForAccountChooser() { 1329 // If there were unrecoverable Wallet errors, or if there are choices other 1330 // than "Pay without the wallet", show the full menu. 1331 // TODO(estade): this can present a braindead menu (only 1 option) when 1332 // there's a wallet error. 1333 if (wallet_error_notification_ || 1334 (SignedInState() == SIGNED_IN && 1335 account_chooser_model_->HasAccountsToChoose() && 1336 !ShouldShowSignInWebView())) { 1337 return account_chooser_model_.get(); 1338 } 1339 1340 // Otherwise, there is no menu, just a sign in link. 1341 return NULL; 1342} 1343 1344gfx::Image AutofillDialogControllerImpl::AccountChooserImage() { 1345 if (!MenuModelForAccountChooser() && !ShouldShowSignInWebView()) { 1346 return ui::ResourceBundle::GetSharedInstance().GetImageNamed( 1347 IDR_WALLET_ICON); 1348 } 1349 1350 return gfx::Image(); 1351} 1352 1353gfx::Image AutofillDialogControllerImpl::ButtonStripImage() const { 1354 if (IsPayingWithWallet()) { 1355 return ui::ResourceBundle::GetSharedInstance().GetImageNamed( 1356 IDR_WALLET_LOGO); 1357 } 1358 1359 return gfx::Image(); 1360} 1361 1362base::string16 AutofillDialogControllerImpl::LabelForSection( 1363 DialogSection section) const { 1364 switch (section) { 1365 case SECTION_CC: 1366 return l10n_util::GetStringUTF16(IDS_AUTOFILL_DIALOG_SECTION_CC); 1367 case SECTION_BILLING: 1368 case SECTION_CC_BILLING: 1369 return l10n_util::GetStringUTF16(IDS_AUTOFILL_DIALOG_SECTION_BILLING); 1370 case SECTION_SHIPPING: 1371 return l10n_util::GetStringUTF16(IDS_AUTOFILL_DIALOG_SECTION_SHIPPING); 1372 } 1373 NOTREACHED(); 1374 return base::string16(); 1375} 1376 1377SuggestionState AutofillDialogControllerImpl::SuggestionStateForSection( 1378 DialogSection section) { 1379 base::string16 vertically_compact, horizontally_compact; 1380 bool show_suggestion = SuggestionTextForSection(section, 1381 &vertically_compact, 1382 &horizontally_compact); 1383 return SuggestionState(show_suggestion, 1384 vertically_compact, 1385 horizontally_compact, 1386 SuggestionIconForSection(section), 1387 ExtraSuggestionTextForSection(section), 1388 ExtraSuggestionIconForSection(section)); 1389} 1390 1391bool AutofillDialogControllerImpl::SuggestionTextForSection( 1392 DialogSection section, 1393 base::string16* vertically_compact, 1394 base::string16* horizontally_compact) { 1395 base::string16 action_text = RequiredActionTextForSection(section); 1396 if (!action_text.empty()) { 1397 *vertically_compact = *horizontally_compact = action_text; 1398 return true; 1399 } 1400 1401 // When the user has clicked 'edit' or a suggestion is somehow invalid (e.g. a 1402 // user selects a credit card that has expired), don't show a suggestion (even 1403 // though there is a profile selected in the model). 1404 if (IsEditingExistingData(section)) 1405 return false; 1406 1407 SuggestionsMenuModel* model = SuggestionsMenuModelForSection(section); 1408 std::string item_key = model->GetItemKeyForCheckedItem(); 1409 if (item_key == kSameAsBillingKey) { 1410 *vertically_compact = *horizontally_compact = l10n_util::GetStringUTF16( 1411 IDS_AUTOFILL_DIALOG_USING_BILLING_FOR_SHIPPING); 1412 return true; 1413 } 1414 1415 if (!IsASuggestionItemKey(item_key)) 1416 return false; 1417 1418 scoped_ptr<DataModelWrapper> wrapper = CreateWrapper(section); 1419 return wrapper->GetDisplayText(vertically_compact, horizontally_compact); 1420} 1421 1422base::string16 AutofillDialogControllerImpl::RequiredActionTextForSection( 1423 DialogSection section) const { 1424 if (section == SECTION_CC_BILLING && IsSubmitPausedOn(wallet::VERIFY_CVV)) { 1425 const wallet::WalletItems::MaskedInstrument* current_instrument = 1426 wallet_items_->GetInstrumentById(active_instrument_id_); 1427 if (current_instrument) 1428 return current_instrument->TypeAndLastFourDigits(); 1429 1430 FieldValueMap output; 1431 view_->GetUserInput(section, &output); 1432 CreditCard card; 1433 GetBillingInfoFromOutputs(output, &card, NULL, NULL); 1434 return card.TypeAndLastFourDigits(); 1435 } 1436 1437 return base::string16(); 1438} 1439 1440base::string16 AutofillDialogControllerImpl::ExtraSuggestionTextForSection( 1441 DialogSection section) const { 1442 if (section == SECTION_CC || 1443 (section == SECTION_CC_BILLING && IsSubmitPausedOn(wallet::VERIFY_CVV))) { 1444 return l10n_util::GetStringUTF16(IDS_AUTOFILL_DIALOG_PLACEHOLDER_CVC); 1445 } 1446 1447 return base::string16(); 1448} 1449 1450const wallet::WalletItems::MaskedInstrument* AutofillDialogControllerImpl:: 1451 ActiveInstrument() const { 1452 if (!IsPayingWithWallet()) 1453 return NULL; 1454 1455 const SuggestionsMenuModel* model = 1456 SuggestionsMenuModelForSection(SECTION_CC_BILLING); 1457 const std::string item_key = model->GetItemKeyForCheckedItem(); 1458 if (!IsASuggestionItemKey(item_key)) 1459 return NULL; 1460 1461 int index; 1462 if (!base::StringToInt(item_key, &index) || index < 0 || 1463 static_cast<size_t>(index) >= wallet_items_->instruments().size()) { 1464 NOTREACHED(); 1465 return NULL; 1466 } 1467 1468 return wallet_items_->instruments()[index]; 1469} 1470 1471const wallet::Address* AutofillDialogControllerImpl:: 1472 ActiveShippingAddress() const { 1473 if (!IsPayingWithWallet() || !IsShippingAddressRequired()) 1474 return NULL; 1475 1476 const SuggestionsMenuModel* model = 1477 SuggestionsMenuModelForSection(SECTION_SHIPPING); 1478 const std::string item_key = model->GetItemKeyForCheckedItem(); 1479 if (!IsASuggestionItemKey(item_key)) 1480 return NULL; 1481 1482 int index; 1483 if (!base::StringToInt(item_key, &index) || index < 0 || 1484 static_cast<size_t>(index) >= wallet_items_->addresses().size()) { 1485 NOTREACHED(); 1486 return NULL; 1487 } 1488 1489 return wallet_items_->addresses()[index]; 1490} 1491 1492scoped_ptr<DataModelWrapper> AutofillDialogControllerImpl::CreateWrapper( 1493 DialogSection section) { 1494 if (IsPayingWithWallet() && full_wallet_ && 1495 full_wallet_->required_actions().empty()) { 1496 if (section == SECTION_CC_BILLING) { 1497 return scoped_ptr<DataModelWrapper>( 1498 new FullWalletBillingWrapper(full_wallet_.get())); 1499 } 1500 if (section == SECTION_SHIPPING) { 1501 return scoped_ptr<DataModelWrapper>( 1502 new FullWalletShippingWrapper(full_wallet_.get())); 1503 } 1504 } 1505 1506 SuggestionsMenuModel* model = SuggestionsMenuModelForSection(section); 1507 std::string item_key = model->GetItemKeyForCheckedItem(); 1508 if (!IsASuggestionItemKey(item_key) || IsManuallyEditingSection(section)) 1509 return scoped_ptr<DataModelWrapper>(); 1510 1511 if (IsPayingWithWallet()) { 1512 if (section == SECTION_CC_BILLING) { 1513 return scoped_ptr<DataModelWrapper>( 1514 new WalletInstrumentWrapper(ActiveInstrument())); 1515 } 1516 1517 if (section == SECTION_SHIPPING) { 1518 return scoped_ptr<DataModelWrapper>( 1519 new WalletAddressWrapper(ActiveShippingAddress())); 1520 } 1521 1522 return scoped_ptr<DataModelWrapper>(); 1523 } 1524 1525 if (section == SECTION_CC) { 1526 CreditCard* card = GetManager()->GetCreditCardByGUID(item_key); 1527 DCHECK(card); 1528 return scoped_ptr<DataModelWrapper>(new AutofillCreditCardWrapper(card)); 1529 } 1530 1531 AutofillProfile* profile = GetManager()->GetProfileByGUID(item_key); 1532 DCHECK(profile); 1533 if (section == SECTION_SHIPPING) { 1534 return scoped_ptr<DataModelWrapper>( 1535 new AutofillShippingAddressWrapper(profile)); 1536 } 1537 DCHECK_EQ(SECTION_BILLING, section); 1538 return scoped_ptr<DataModelWrapper>( 1539 new AutofillProfileWrapper(profile)); 1540} 1541 1542gfx::Image AutofillDialogControllerImpl::SuggestionIconForSection( 1543 DialogSection section) { 1544 scoped_ptr<DataModelWrapper> model = CreateWrapper(section); 1545 if (!model.get()) 1546 return gfx::Image(); 1547 1548 return model->GetIcon(); 1549} 1550 1551gfx::Image AutofillDialogControllerImpl::ExtraSuggestionIconForSection( 1552 DialogSection section) { 1553 if (section != SECTION_CC && section != SECTION_CC_BILLING) 1554 return gfx::Image(); 1555 1556 scoped_ptr<DataModelWrapper> model = CreateWrapper(section); 1557 if (!model.get()) 1558 return gfx::Image(); 1559 1560 return CvcIconForCreditCardType( 1561 model->GetInfo(AutofillType(CREDIT_CARD_TYPE))); 1562} 1563 1564FieldIconMap AutofillDialogControllerImpl::IconsForFields( 1565 const FieldValueMap& user_inputs) const { 1566 FieldIconMap result; 1567 base::string16 credit_card_type; 1568 1569 FieldValueMap::const_iterator credit_card_iter = 1570 user_inputs.find(CREDIT_CARD_NUMBER); 1571 if (credit_card_iter != user_inputs.end()) { 1572 const base::string16& number = credit_card_iter->second; 1573 const std::string type = CreditCard::GetCreditCardType(number); 1574 credit_card_type = CreditCard::TypeForDisplay(type); 1575 result[CREDIT_CARD_NUMBER] = CreditCardIconForType(type); 1576 } 1577 1578 if (!user_inputs.count(CREDIT_CARD_VERIFICATION_CODE)) 1579 return result; 1580 1581 result[CREDIT_CARD_VERIFICATION_CODE] = 1582 CvcIconForCreditCardType(credit_card_type); 1583 1584 return result; 1585} 1586 1587bool AutofillDialogControllerImpl::FieldControlsIcons( 1588 ServerFieldType type) const { 1589 return type == CREDIT_CARD_NUMBER; 1590} 1591 1592base::string16 AutofillDialogControllerImpl::TooltipForField( 1593 ServerFieldType type) const { 1594 if (type == PHONE_HOME_WHOLE_NUMBER || type == PHONE_BILLING_WHOLE_NUMBER) 1595 return l10n_util::GetStringUTF16(IDS_AUTOFILL_DIALOG_TOOLTIP_PHONE_NUMBER); 1596 1597 return base::string16(); 1598} 1599 1600bool AutofillDialogControllerImpl::InputIsEditable( 1601 const DetailInput& input, 1602 DialogSection section) { 1603 if (section != SECTION_CC_BILLING) 1604 return true; 1605 1606 if (input.type == CREDIT_CARD_NUMBER) 1607 return !IsEditingExistingData(section); 1608 1609 // For CVC, only require (allow) input if the user has edited some other 1610 // aspect of the card. 1611 if (input.type == CREDIT_CARD_VERIFICATION_CODE && 1612 IsEditingExistingData(section)) { 1613 FieldValueMap output; 1614 view_->GetUserInput(section, &output); 1615 WalletInstrumentWrapper wrapper(ActiveInstrument()); 1616 1617 for (FieldValueMap::iterator iter = output.begin(); iter != output.end(); 1618 ++iter) { 1619 if (iter->first == input.type) 1620 continue; 1621 1622 AutofillType type(iter->first); 1623 if (type.group() == CREDIT_CARD && 1624 iter->second != wrapper.GetInfo(type)) { 1625 return true; 1626 } 1627 } 1628 1629 return false; 1630 } 1631 1632 return true; 1633} 1634 1635// TODO(groby): Add more tests. 1636base::string16 AutofillDialogControllerImpl::InputValidityMessage( 1637 DialogSection section, 1638 ServerFieldType type, 1639 const base::string16& value) { 1640 // If the field is edited, clear any Wallet errors. 1641 if (IsPayingWithWallet()) { 1642 WalletValidationErrors::iterator it = wallet_errors_.find(section); 1643 if (it != wallet_errors_.end()) { 1644 TypeErrorInputMap::const_iterator iter = it->second.find(type); 1645 if (iter != it->second.end()) { 1646 if (iter->second.second == value) 1647 return iter->second.first; 1648 it->second.erase(type); 1649 } 1650 } 1651 } 1652 1653 switch (AutofillType(type).GetStorableType()) { 1654 case EMAIL_ADDRESS: 1655 if (!value.empty() && !IsValidEmailAddress(value)) { 1656 return l10n_util::GetStringUTF16( 1657 IDS_AUTOFILL_DIALOG_VALIDATION_INVALID_EMAIL_ADDRESS); 1658 } 1659 break; 1660 1661 case CREDIT_CARD_NUMBER: { 1662 if (!value.empty()) { 1663 base::string16 message = CreditCardNumberValidityMessage(value); 1664 if (!message.empty()) 1665 return message; 1666 } 1667 break; 1668 } 1669 1670 case CREDIT_CARD_EXP_MONTH: 1671 if (!InputWasEdited(CREDIT_CARD_EXP_MONTH, value)) { 1672 return l10n_util::GetStringUTF16( 1673 IDS_AUTOFILL_DIALOG_VALIDATION_MISSING_VALUE); 1674 } 1675 break; 1676 1677 case CREDIT_CARD_EXP_4_DIGIT_YEAR: 1678 if (!InputWasEdited(CREDIT_CARD_EXP_4_DIGIT_YEAR, value)) { 1679 return l10n_util::GetStringUTF16( 1680 IDS_AUTOFILL_DIALOG_VALIDATION_MISSING_VALUE); 1681 } 1682 break; 1683 1684 case CREDIT_CARD_VERIFICATION_CODE: 1685 if (!value.empty() && !autofill::IsValidCreditCardSecurityCode(value)) { 1686 return l10n_util::GetStringUTF16( 1687 IDS_AUTOFILL_DIALOG_VALIDATION_INVALID_CREDIT_CARD_SECURITY_CODE); 1688 } 1689 break; 1690 1691 case ADDRESS_HOME_LINE1: 1692 break; 1693 1694 case ADDRESS_HOME_LINE2: 1695 return base::string16(); // Line 2 is optional - always valid. 1696 1697 case ADDRESS_HOME_CITY: 1698 case ADDRESS_HOME_COUNTRY: 1699 break; 1700 1701 case ADDRESS_HOME_STATE: 1702 if (!value.empty() && !autofill::IsValidState(value)) { 1703 return l10n_util::GetStringUTF16( 1704 IDS_AUTOFILL_DIALOG_VALIDATION_INVALID_REGION); 1705 } 1706 break; 1707 1708 case ADDRESS_HOME_ZIP: 1709 if (!value.empty() && !autofill::IsValidZip(value)) { 1710 return l10n_util::GetStringUTF16( 1711 IDS_AUTOFILL_DIALOG_VALIDATION_INVALID_ZIP_CODE); 1712 } 1713 break; 1714 1715 case NAME_FULL: 1716 // Wallet requires a first and last billing name. 1717 if (section == SECTION_CC_BILLING && !value.empty() && 1718 !IsCardHolderNameValidForWallet(value)) { 1719 DCHECK(IsPayingWithWallet()); 1720 return l10n_util::GetStringUTF16( 1721 IDS_AUTOFILL_DIALOG_VALIDATION_WALLET_REQUIRES_TWO_NAMES); 1722 } 1723 break; 1724 1725 case PHONE_HOME_WHOLE_NUMBER: // Used in shipping section. 1726 break; 1727 1728 case PHONE_BILLING_WHOLE_NUMBER: // Used in billing section. 1729 break; 1730 1731 default: 1732 NOTREACHED(); // Trying to validate unknown field. 1733 break; 1734 } 1735 1736 return value.empty() ? 1737 l10n_util::GetStringUTF16(IDS_AUTOFILL_DIALOG_VALIDATION_MISSING_VALUE) : 1738 base::string16(); 1739} 1740 1741// TODO(groby): Also add tests. 1742ValidityMessages AutofillDialogControllerImpl::InputsAreValid( 1743 DialogSection section, 1744 const FieldValueMap& inputs) { 1745 ValidityMessages messages; 1746 std::map<ServerFieldType, base::string16> field_values; 1747 for (FieldValueMap::const_iterator iter = inputs.begin(); 1748 iter != inputs.end(); ++iter) { 1749 const ServerFieldType type = iter->first; 1750 1751 base::string16 text = InputValidityMessage(section, type, iter->second); 1752 1753 // Skip empty/unchanged fields in edit mode. Ignore country code as it 1754 // always has a value. If the individual field does not have validation 1755 // errors, assume it to be valid unless later proven otherwise. 1756 bool sure = InputWasEdited(type, iter->second) || 1757 ComboboxModelForAutofillType(type) == &country_combobox_model_; 1758 1759 // Consider only individually valid fields for inter-field validation. 1760 if (text.empty()) { 1761 field_values[type] = iter->second; 1762 // If the field is valid but can be invalidated by inter-field validation, 1763 // assume it to be unsure. 1764 if (type == CREDIT_CARD_EXP_4_DIGIT_YEAR || 1765 type == CREDIT_CARD_EXP_MONTH || 1766 type == CREDIT_CARD_VERIFICATION_CODE || 1767 type == PHONE_HOME_WHOLE_NUMBER || 1768 type == PHONE_BILLING_WHOLE_NUMBER) { 1769 sure = false; 1770 } 1771 } 1772 messages.Set(type, ValidityMessage(text, sure)); 1773 } 1774 1775 // Validate the date formed by month and year field. (Autofill dialog is 1776 // never supposed to have 2-digit years, so not checked). 1777 if (field_values.count(CREDIT_CARD_EXP_4_DIGIT_YEAR) && 1778 field_values.count(CREDIT_CARD_EXP_MONTH) && 1779 InputWasEdited(CREDIT_CARD_EXP_4_DIGIT_YEAR, 1780 field_values[CREDIT_CARD_EXP_4_DIGIT_YEAR]) && 1781 InputWasEdited(CREDIT_CARD_EXP_MONTH, 1782 field_values[CREDIT_CARD_EXP_MONTH])) { 1783 ValidityMessage year_message(base::string16(), true); 1784 ValidityMessage month_message(base::string16(), true); 1785 if (!IsCreditCardExpirationValid(field_values[CREDIT_CARD_EXP_4_DIGIT_YEAR], 1786 field_values[CREDIT_CARD_EXP_MONTH])) { 1787 // The dialog shows the same error message for the month and year fields. 1788 year_message.text = l10n_util::GetStringUTF16( 1789 IDS_AUTOFILL_DIALOG_VALIDATION_INVALID_CREDIT_CARD_EXPIRATION_DATE); 1790 month_message.text = l10n_util::GetStringUTF16( 1791 IDS_AUTOFILL_DIALOG_VALIDATION_INVALID_CREDIT_CARD_EXPIRATION_DATE); 1792 } 1793 messages.Set(CREDIT_CARD_EXP_4_DIGIT_YEAR, year_message); 1794 messages.Set(CREDIT_CARD_EXP_MONTH, month_message); 1795 } 1796 1797 // If there is a credit card number and a CVC, validate them together. 1798 if (field_values.count(CREDIT_CARD_NUMBER) && 1799 field_values.count(CREDIT_CARD_VERIFICATION_CODE)) { 1800 ValidityMessage ccv_message(base::string16(), true); 1801 if (!autofill::IsValidCreditCardSecurityCode( 1802 field_values[CREDIT_CARD_VERIFICATION_CODE], 1803 field_values[CREDIT_CARD_NUMBER])) { 1804 ccv_message.text = l10n_util::GetStringUTF16( 1805 IDS_AUTOFILL_DIALOG_VALIDATION_INVALID_CREDIT_CARD_SECURITY_CODE); 1806 } 1807 messages.Set(CREDIT_CARD_VERIFICATION_CODE, ccv_message); 1808 } 1809 1810 // Validate the shipping phone number against the country code of the address. 1811 if (field_values.count(ADDRESS_HOME_COUNTRY) && 1812 field_values.count(PHONE_HOME_WHOLE_NUMBER)) { 1813 i18n::PhoneObject phone_object( 1814 field_values[PHONE_HOME_WHOLE_NUMBER], 1815 AutofillCountry::GetCountryCode( 1816 field_values[ADDRESS_HOME_COUNTRY], 1817 g_browser_process->GetApplicationLocale())); 1818 ValidityMessage phone_message(base::string16(), true); 1819 if (!phone_object.IsValidNumber()) { 1820 phone_message.text = l10n_util::GetStringUTF16( 1821 IDS_AUTOFILL_DIALOG_VALIDATION_INVALID_PHONE_NUMBER); 1822 } 1823 messages.Set(PHONE_HOME_WHOLE_NUMBER, phone_message); 1824 } 1825 1826 // Validate the billing phone number against the country code of the address. 1827 if (field_values.count(ADDRESS_BILLING_COUNTRY) && 1828 field_values.count(PHONE_BILLING_WHOLE_NUMBER)) { 1829 i18n::PhoneObject phone_object( 1830 field_values[PHONE_BILLING_WHOLE_NUMBER], 1831 AutofillCountry::GetCountryCode( 1832 field_values[ADDRESS_BILLING_COUNTRY], 1833 g_browser_process->GetApplicationLocale())); 1834 ValidityMessage phone_message(base::string16(), true); 1835 if (!phone_object.IsValidNumber()) { 1836 phone_message.text = l10n_util::GetStringUTF16( 1837 IDS_AUTOFILL_DIALOG_VALIDATION_INVALID_PHONE_NUMBER); 1838 } 1839 messages.Set(PHONE_BILLING_WHOLE_NUMBER, phone_message); 1840 } 1841 1842 return messages; 1843} 1844 1845void AutofillDialogControllerImpl::UserEditedOrActivatedInput( 1846 DialogSection section, 1847 ServerFieldType type, 1848 gfx::NativeView parent_view, 1849 const gfx::Rect& content_bounds, 1850 const base::string16& field_contents, 1851 bool was_edit) { 1852 // If the field is edited down to empty, don't show a popup. 1853 if (was_edit && field_contents.empty()) { 1854 HidePopup(); 1855 return; 1856 } 1857 1858 // If the user clicks while the popup is already showing, be sure to hide 1859 // it. 1860 if (!was_edit && popup_controller_.get()) { 1861 HidePopup(); 1862 return; 1863 } 1864 1865 std::vector<string16> popup_values, popup_labels, popup_icons; 1866 if (common::IsCreditCardType(type)) { 1867 GetManager()->GetCreditCardSuggestions(AutofillType(type), 1868 field_contents, 1869 &popup_values, 1870 &popup_labels, 1871 &popup_icons, 1872 &popup_guids_); 1873 } else { 1874 std::vector<ServerFieldType> field_types; 1875 const DetailInputs& inputs = RequestedFieldsForSection(section); 1876 for (DetailInputs::const_iterator iter = inputs.begin(); 1877 iter != inputs.end(); ++iter) { 1878 field_types.push_back(iter->type); 1879 } 1880 GetManager()->GetProfileSuggestions(AutofillType(type), 1881 field_contents, 1882 false, 1883 field_types, 1884 &popup_values, 1885 &popup_labels, 1886 &popup_icons, 1887 &popup_guids_); 1888 } 1889 1890 if (popup_values.empty()) { 1891 HidePopup(); 1892 return; 1893 } 1894 1895 // |input_showing_popup_| must be set before calling |Show()|. 1896 const DetailInputs& inputs = RequestedFieldsForSection(section); 1897 for (DetailInputs::const_iterator iter = inputs.begin(); 1898 iter != inputs.end(); ++iter) { 1899 if (iter->type == type) { 1900 input_showing_popup_ = &(*iter); 1901 break; 1902 } 1903 } 1904 1905 if (!input_showing_popup_) 1906 return; 1907 1908 // TODO(estade): do we need separators and control rows like 'Clear 1909 // Form'? 1910 std::vector<int> popup_ids; 1911 for (size_t i = 0; i < popup_guids_.size(); ++i) { 1912 popup_ids.push_back(i); 1913 } 1914 1915 popup_controller_ = AutofillPopupControllerImpl::GetOrCreate( 1916 popup_controller_, 1917 weak_ptr_factory_.GetWeakPtr(), 1918 NULL, 1919 parent_view, 1920 content_bounds, 1921 base::i18n::IsRTL() ? 1922 base::i18n::RIGHT_TO_LEFT : base::i18n::LEFT_TO_RIGHT); 1923 popup_controller_->set_hide_on_outside_click(true); 1924 popup_controller_->Show(popup_values, 1925 popup_labels, 1926 popup_icons, 1927 popup_ids); 1928} 1929 1930void AutofillDialogControllerImpl::FocusMoved() { 1931 HidePopup(); 1932} 1933 1934bool AutofillDialogControllerImpl::ShouldShowErrorBubble() const { 1935 return !input_showing_popup_; 1936} 1937 1938void AutofillDialogControllerImpl::ViewClosed() { 1939 GetManager()->RemoveObserver(this); 1940 1941 // Called from here rather than in ~AutofillDialogControllerImpl as this 1942 // relies on virtual methods that change to their base class in the dtor. 1943 MaybeShowCreditCardBubble(); 1944 1945 delete this; 1946} 1947 1948std::vector<DialogNotification> AutofillDialogControllerImpl:: 1949 CurrentNotifications() { 1950 std::vector<DialogNotification> notifications; 1951 1952 // TODO(dbeam): figure out a way to dismiss this error after a while. 1953 if (wallet_error_notification_) 1954 notifications.push_back(*wallet_error_notification_); 1955 1956 if (IsSubmitPausedOn(wallet::VERIFY_CVV)) { 1957 notifications.push_back(DialogNotification( 1958 DialogNotification::REQUIRED_ACTION, 1959 l10n_util::GetStringUTF16(IDS_AUTOFILL_DIALOG_VERIFY_CVV))); 1960 } 1961 1962 if (!wallet_server_validation_recoverable_) { 1963 notifications.push_back(DialogNotification( 1964 DialogNotification::REQUIRED_ACTION, 1965 l10n_util::GetStringUTF16( 1966 IDS_AUTOFILL_DIALOG_FAILED_TO_SAVE_WALLET_DATA))); 1967 } 1968 1969 if (choose_another_instrument_or_address_) { 1970 notifications.push_back(DialogNotification( 1971 DialogNotification::REQUIRED_ACTION, 1972 l10n_util::GetStringUTF16( 1973 IDS_AUTOFILL_DIALOG_CHOOSE_DIFFERENT_WALLET_INSTRUMENT))); 1974 } 1975 1976 if (notifications.empty() && MenuModelForAccountChooser()) { 1977 base::string16 text = l10n_util::GetStringUTF16( 1978 IsManuallyEditingAnySection() ? 1979 IDS_AUTOFILL_DIALOG_SAVE_DETAILS_IN_WALLET : 1980 IDS_AUTOFILL_DIALOG_USE_WALLET); 1981 DialogNotification notification( 1982 DialogNotification::WALLET_USAGE_CONFIRMATION, 1983 text); 1984 notification.set_tooltip_text( 1985 l10n_util::GetStringUTF16( 1986 IDS_AUTOFILL_DIALOG_SAVE_IN_WALLET_TOOLTIP)); 1987 notification.set_checked(IsPayingWithWallet()); 1988 notifications.push_back(notification); 1989 } 1990 1991 if (IsPayingWithWallet() && !wallet::IsUsingProd()) { 1992 notifications.push_back(DialogNotification( 1993 DialogNotification::DEVELOPER_WARNING, 1994 l10n_util::GetStringUTF16(IDS_AUTOFILL_DIALOG_NOT_PROD_WARNING))); 1995 } 1996 1997 if (RequestingCreditCardInfo() && !TransmissionWillBeSecure()) { 1998 notifications.push_back(DialogNotification( 1999 DialogNotification::SECURITY_WARNING, 2000 l10n_util::GetStringUTF16(IDS_AUTOFILL_DIALOG_SECURITY_WARNING))); 2001 } 2002 2003 if (!invoked_from_same_origin_) { 2004 notifications.push_back(DialogNotification( 2005 DialogNotification::SECURITY_WARNING, 2006 l10n_util::GetStringFUTF16(IDS_AUTOFILL_DIALOG_SITE_WARNING, 2007 UTF8ToUTF16(source_url_.host())))); 2008 } 2009 2010 return notifications; 2011} 2012 2013void AutofillDialogControllerImpl::LinkClicked(const GURL& url) { 2014 OpenTabWithUrl(url); 2015} 2016 2017void AutofillDialogControllerImpl::SignInLinkClicked() { 2018 ScopedViewUpdates updates(view_.get()); 2019 2020 if (SignedInState() == NOT_CHECKED) { 2021 handling_use_wallet_link_click_ = true; 2022 account_chooser_model_->SelectWalletAccount(0); 2023 FetchWalletCookie(); 2024 view_->UpdateAccountChooser(); 2025 } else if (signin_registrar_.IsEmpty()) { 2026 // Start sign in. 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); 2031 view_->UpdateAccountChooser(); 2032 2033 GetMetricLogger().LogDialogUiEvent( 2034 AutofillMetrics::DIALOG_UI_SIGNIN_SHOWN); 2035 } else { 2036 waiting_for_explicit_sign_in_response_ = false; 2037 HideSignIn(); 2038 } 2039} 2040 2041void AutofillDialogControllerImpl::NotificationCheckboxStateChanged( 2042 DialogNotification::Type type, bool checked) { 2043 if (type == DialogNotification::WALLET_USAGE_CONFIRMATION) { 2044 if (checked) { 2045 account_chooser_model_->SelectWalletAccount( 2046 GetWalletClient()->user_index()); 2047 } else { 2048 account_chooser_model_->SelectUseAutofill(); 2049 } 2050 2051 AccountChoiceChanged(); 2052 } 2053} 2054 2055void AutofillDialogControllerImpl::LegalDocumentLinkClicked( 2056 const gfx::Range& range) { 2057 for (size_t i = 0; i < legal_document_link_ranges_.size(); ++i) { 2058 if (legal_document_link_ranges_[i] == range) { 2059 OpenTabWithUrl(wallet_items_->legal_documents()[i]->url()); 2060 return; 2061 } 2062 } 2063 2064 NOTREACHED(); 2065} 2066 2067bool AutofillDialogControllerImpl::OnCancel() { 2068 HidePopup(); 2069 if (!is_submitting_) 2070 LogOnCancelMetrics(); 2071 callback_.Run(NULL); 2072 return true; 2073} 2074 2075bool AutofillDialogControllerImpl::OnAccept() { 2076 ScopedViewUpdates updates(view_.get()); 2077 choose_another_instrument_or_address_ = false; 2078 wallet_server_validation_recoverable_ = true; 2079 HidePopup(); 2080 2081 // This must come before SetIsSubmitting(). 2082 if (IsPayingWithWallet()) { 2083 // In the VERIFY_CVV case, hold onto the previously submitted cardholder 2084 // name. 2085 if (!IsSubmitPausedOn(wallet::VERIFY_CVV)) { 2086 submitted_cardholder_name_ = 2087 GetValueFromSection(SECTION_CC_BILLING, NAME_BILLING_FULL); 2088 2089 // Snag the last four digits of the backing card now as it could be wiped 2090 // out if a CVC challenge happens. 2091 if (ActiveInstrument()) { 2092 backing_card_last_four_ = ActiveInstrument()->TypeAndLastFourDigits(); 2093 } else { 2094 FieldValueMap output; 2095 view_->GetUserInput(SECTION_CC_BILLING, &output); 2096 CreditCard card; 2097 GetBillingInfoFromOutputs(output, &card, NULL, NULL); 2098 backing_card_last_four_ = card.TypeAndLastFourDigits(); 2099 } 2100 } 2101 DCHECK(!submitted_cardholder_name_.empty()); 2102 DCHECK(!backing_card_last_four_.empty()); 2103 } 2104 2105 SetIsSubmitting(true); 2106 2107 if (IsSubmitPausedOn(wallet::VERIFY_CVV)) { 2108 DCHECK(!active_instrument_id_.empty()); 2109 full_wallet_.reset(); 2110 GetWalletClient()->AuthenticateInstrument( 2111 active_instrument_id_, 2112 UTF16ToUTF8(view_->GetCvc())); 2113 view_->UpdateOverlay(); 2114 } else if (IsPayingWithWallet()) { 2115 AcceptLegalTerms(); 2116 } else { 2117 FinishSubmit(); 2118 } 2119 2120 return false; 2121} 2122 2123Profile* AutofillDialogControllerImpl::profile() { 2124 return profile_; 2125} 2126 2127content::WebContents* AutofillDialogControllerImpl::GetWebContents() { 2128 return web_contents(); 2129} 2130 2131//////////////////////////////////////////////////////////////////////////////// 2132// AutofillPopupDelegate implementation. 2133 2134void AutofillDialogControllerImpl::OnPopupShown() { 2135 ScopedViewUpdates update(view_.get()); 2136 view_->UpdateErrorBubble(); 2137 2138 GetMetricLogger().LogDialogPopupEvent(AutofillMetrics::DIALOG_POPUP_SHOWN); 2139} 2140 2141void AutofillDialogControllerImpl::OnPopupHidden() {} 2142 2143bool AutofillDialogControllerImpl::ShouldRepostEvent( 2144 const ui::MouseEvent& event) { 2145 // If the event would be reposted inside |input_showing_popup_|, just ignore. 2146 return !view_->HitTestInput(*input_showing_popup_, event.location()); 2147} 2148 2149void AutofillDialogControllerImpl::DidSelectSuggestion(int identifier) { 2150 // TODO(estade): implement. 2151} 2152 2153void AutofillDialogControllerImpl::DidAcceptSuggestion( 2154 const base::string16& value, 2155 int identifier) { 2156 ScopedViewUpdates updates(view_.get()); 2157 const PersonalDataManager::GUIDPair& pair = popup_guids_[identifier]; 2158 2159 scoped_ptr<DataModelWrapper> wrapper; 2160 if (common::IsCreditCardType(input_showing_popup_->type)) { 2161 wrapper.reset(new AutofillCreditCardWrapper( 2162 GetManager()->GetCreditCardByGUID(pair.first))); 2163 } else { 2164 wrapper.reset(new AutofillProfileWrapper( 2165 GetManager()->GetProfileByGUID(pair.first), 2166 AutofillType(input_showing_popup_->type), 2167 pair.second)); 2168 } 2169 2170 for (size_t i = SECTION_MIN; i <= SECTION_MAX; ++i) { 2171 DialogSection section = static_cast<DialogSection>(i); 2172 wrapper->FillInputs(MutableRequestedFieldsForSection(section)); 2173 view_->FillSection(section, *input_showing_popup_); 2174 } 2175 2176 GetMetricLogger().LogDialogPopupEvent( 2177 AutofillMetrics::DIALOG_POPUP_FORM_FILLED); 2178 2179 // TODO(estade): not sure why it's necessary to do this explicitly. 2180 HidePopup(); 2181} 2182 2183void AutofillDialogControllerImpl::RemoveSuggestion( 2184 const base::string16& value, 2185 int identifier) { 2186 // TODO(estade): implement. 2187} 2188 2189void AutofillDialogControllerImpl::ClearPreviewedForm() { 2190 // TODO(estade): implement. 2191} 2192 2193//////////////////////////////////////////////////////////////////////////////// 2194// content::NotificationObserver implementation. 2195 2196void AutofillDialogControllerImpl::Observe( 2197 int type, 2198 const content::NotificationSource& source, 2199 const content::NotificationDetails& details) { 2200 DCHECK_EQ(type, content::NOTIFICATION_NAV_ENTRY_COMMITTED); 2201 content::LoadCommittedDetails* load_details = 2202 content::Details<content::LoadCommittedDetails>(details).ptr(); 2203 size_t user_index = 0; 2204 if (IsSignInContinueUrl(load_details->entry->GetVirtualURL(), &user_index)) { 2205 GetWalletClient()->set_user_index(user_index); 2206 FetchWalletCookie(); 2207 2208 // NOTE: |HideSignIn()| may delete the WebContents which doesn't expect to 2209 // be deleted while committing a nav entry. Just call |HideSignIn()| later. 2210 base::MessageLoop::current()->PostTask(FROM_HERE, 2211 base::Bind(&AutofillDialogControllerImpl::HideSignIn, 2212 base::Unretained(this))); 2213 } 2214} 2215 2216//////////////////////////////////////////////////////////////////////////////// 2217// SuggestionsMenuModelDelegate implementation. 2218 2219void AutofillDialogControllerImpl::SuggestionsMenuWillShow() { 2220 HidePopup(); 2221} 2222 2223void AutofillDialogControllerImpl::SuggestionItemSelected( 2224 SuggestionsMenuModel* model, 2225 size_t index) { 2226 ScopedViewUpdates updates(view_.get()); 2227 2228 if (model->GetItemKeyAt(index) == kManageItemsKey) { 2229 GURL url; 2230 if (!IsPayingWithWallet()) { 2231 GURL settings_url(chrome::kChromeUISettingsURL); 2232 url = settings_url.Resolve(chrome::kAutofillSubPage); 2233 } else { 2234 // Reset |last_wallet_items_fetch_timestamp_| to ensure that the Wallet 2235 // data is refreshed as soon as the user switches back to this tab after 2236 // potentially editing his data. 2237 last_wallet_items_fetch_timestamp_ = base::TimeTicks(); 2238 size_t user_index = GetWalletClient()->user_index(); 2239 url = SectionForSuggestionsMenuModel(*model) == SECTION_SHIPPING ? 2240 wallet::GetManageAddressesUrl(user_index) : 2241 wallet::GetManageInstrumentsUrl(user_index); 2242 } 2243 2244 OpenTabWithUrl(url); 2245 return; 2246 } 2247 2248 model->SetCheckedIndex(index); 2249 DialogSection section = SectionForSuggestionsMenuModel(*model); 2250 ResetSectionInput(section); 2251 ShowEditUiIfBadSuggestion(section); 2252 UpdateSection(section); 2253 view_->UpdateNotificationArea(); 2254 UpdateForErrors(); 2255 2256 LogSuggestionItemSelectedMetric(*model); 2257} 2258 2259//////////////////////////////////////////////////////////////////////////////// 2260// wallet::WalletClientDelegate implementation. 2261 2262const AutofillMetrics& AutofillDialogControllerImpl::GetMetricLogger() const { 2263 return metric_logger_; 2264} 2265 2266std::string AutofillDialogControllerImpl::GetRiskData() const { 2267 DCHECK(!risk_data_.empty()); 2268 return risk_data_; 2269} 2270 2271std::string AutofillDialogControllerImpl::GetWalletCookieValue() const { 2272 return wallet_cookie_value_; 2273} 2274 2275bool AutofillDialogControllerImpl::IsShippingAddressRequired() const { 2276 return cares_about_shipping_; 2277} 2278 2279void AutofillDialogControllerImpl::OnDidAcceptLegalDocuments() { 2280 DCHECK(is_submitting_ && IsPayingWithWallet()); 2281 has_accepted_legal_documents_ = true; 2282 LoadRiskFingerprintData(); 2283} 2284 2285void AutofillDialogControllerImpl::OnDidAuthenticateInstrument(bool success) { 2286 DCHECK(is_submitting_ && IsPayingWithWallet()); 2287 2288 // TODO(dbeam): use the returned full wallet. http://crbug.com/224992 2289 if (success) { 2290 GetFullWallet(); 2291 } else { 2292 DisableWallet(wallet::WalletClient::UNKNOWN_ERROR); 2293 SuggestionsUpdated(); 2294 } 2295} 2296 2297void AutofillDialogControllerImpl::OnDidGetFullWallet( 2298 scoped_ptr<wallet::FullWallet> full_wallet) { 2299 DCHECK(is_submitting_ && IsPayingWithWallet()); 2300 ScopedViewUpdates updates(view_.get()); 2301 2302 full_wallet_ = full_wallet.Pass(); 2303 2304 if (full_wallet_->required_actions().empty()) { 2305 FinishSubmit(); 2306 return; 2307 } 2308 2309 switch (full_wallet_->required_actions()[0]) { 2310 case wallet::CHOOSE_ANOTHER_INSTRUMENT_OR_ADDRESS: 2311 choose_another_instrument_or_address_ = true; 2312 SetIsSubmitting(false); 2313 GetWalletItems(); 2314 break; 2315 2316 case wallet::VERIFY_CVV: 2317 SuggestionsUpdated(); 2318 break; 2319 2320 default: 2321 DisableWallet(wallet::WalletClient::UNKNOWN_ERROR); 2322 return; 2323 } 2324 2325 view_->UpdateNotificationArea(); 2326 view_->UpdateButtonStrip(); 2327 view_->UpdateOverlay(); 2328} 2329 2330void AutofillDialogControllerImpl::OnPassiveSigninSuccess() { 2331 FetchWalletCookie(); 2332} 2333 2334void AutofillDialogControllerImpl::OnPassiveSigninFailure( 2335 const GoogleServiceAuthError& error) { 2336 signin_helper_.reset(); 2337 passive_failed_ = true; 2338 2339 if (handling_use_wallet_link_click_ || 2340 GetWalletClient()->user_index() != 0) { 2341 // TODO(estade): When a secondary account is selected and fails passive 2342 // auth, we show a sign in page. Currently we show the generic add account 2343 // page, but we should instead show sign in for the selected account. 2344 // http://crbug.com/323327 2345 SignInLinkClicked(); 2346 handling_use_wallet_link_click_ = false; 2347 } 2348 2349 OnWalletSigninError(); 2350} 2351 2352void AutofillDialogControllerImpl::OnDidFetchWalletCookieValue( 2353 const std::string& cookie_value) { 2354 wallet_cookie_value_ = cookie_value; 2355 signin_helper_.reset(); 2356 GetWalletItems(); 2357} 2358 2359void AutofillDialogControllerImpl::OnDidGetWalletItems( 2360 scoped_ptr<wallet::WalletItems> wallet_items) { 2361 legal_documents_text_.clear(); 2362 legal_document_link_ranges_.clear(); 2363 has_accepted_legal_documents_ = false; 2364 2365 wallet_items_ = wallet_items.Pass(); 2366 2367 if (wallet_items_ && !wallet_items_->ObfuscatedGaiaId().empty()) { 2368 // Making sure the user index is in sync shouldn't be necessary, but is an 2369 // extra precaution. But if there is no active account (such as in the 2370 // PASSIVE_AUTH case), stick with the old active account. 2371 GetWalletClient()->set_user_index(wallet_items_->active_account_index()); 2372 2373 std::vector<std::string> usernames; 2374 for (size_t i = 0; i < wallet_items_->gaia_accounts().size(); ++i) { 2375 usernames.push_back(wallet_items_->gaia_accounts()[i]->email_address()); 2376 } 2377 account_chooser_model_->SetWalletAccounts( 2378 usernames, wallet_items_->active_account_index()); 2379 } 2380 2381 ConstructLegalDocumentsText(); 2382 OnWalletOrSigninUpdate(); 2383} 2384 2385void AutofillDialogControllerImpl::OnDidSaveToWallet( 2386 const std::string& instrument_id, 2387 const std::string& address_id, 2388 const std::vector<wallet::RequiredAction>& required_actions, 2389 const std::vector<wallet::FormFieldError>& form_field_errors) { 2390 DCHECK(is_submitting_ && IsPayingWithWallet()); 2391 2392 if (required_actions.empty()) { 2393 if (!address_id.empty()) 2394 active_address_id_ = address_id; 2395 if (!instrument_id.empty()) 2396 active_instrument_id_ = instrument_id; 2397 GetFullWallet(); 2398 } else { 2399 OnWalletFormFieldError(form_field_errors); 2400 HandleSaveOrUpdateRequiredActions(required_actions); 2401 } 2402} 2403 2404void AutofillDialogControllerImpl::OnWalletError( 2405 wallet::WalletClient::ErrorType error_type) { 2406 DisableWallet(error_type); 2407} 2408 2409//////////////////////////////////////////////////////////////////////////////// 2410// PersonalDataManagerObserver implementation. 2411 2412void AutofillDialogControllerImpl::OnPersonalDataChanged() { 2413 if (is_submitting_) 2414 return; 2415 2416 SuggestionsUpdated(); 2417} 2418 2419//////////////////////////////////////////////////////////////////////////////// 2420// AccountChooserModelDelegate implementation. 2421 2422void AutofillDialogControllerImpl::AccountChooserWillShow() { 2423 HidePopup(); 2424} 2425 2426void AutofillDialogControllerImpl::AccountChoiceChanged() { 2427 ScopedViewUpdates updates(view_.get()); 2428 wallet::WalletClient* client = GetWalletClient(); 2429 2430 if (is_submitting_) 2431 client->CancelRequests(); 2432 2433 SetIsSubmitting(false); 2434 2435 size_t selected_user_index = 2436 account_chooser_model_->GetActiveWalletAccountIndex(); 2437 if (account_chooser_model_->WalletIsSelected() && 2438 client->user_index() != selected_user_index) { 2439 client->set_user_index(selected_user_index); 2440 // Clear |wallet_items_| so we don't try to restore the selected instrument 2441 // and address. 2442 wallet_items_.reset(); 2443 GetWalletItems(); 2444 } else { 2445 SuggestionsUpdated(); 2446 UpdateAccountChooserView(); 2447 } 2448} 2449 2450void AutofillDialogControllerImpl::AddAccount() { 2451 SignInLinkClicked(); 2452} 2453 2454void AutofillDialogControllerImpl::UpdateAccountChooserView() { 2455 if (view_) { 2456 ScopedViewUpdates updates(view_.get()); 2457 view_->UpdateAccountChooser(); 2458 view_->UpdateNotificationArea(); 2459 } 2460} 2461 2462//////////////////////////////////////////////////////////////////////////////// 2463 2464bool AutofillDialogControllerImpl::HandleKeyPressEventInInput( 2465 const content::NativeWebKeyboardEvent& event) { 2466 if (popup_controller_.get()) 2467 return popup_controller_->HandleKeyPressEvent(event); 2468 2469 return false; 2470} 2471 2472bool AutofillDialogControllerImpl::RequestingCreditCardInfo() const { 2473 DCHECK_GT(form_structure_.field_count(), 0U); 2474 2475 for (size_t i = 0; i < form_structure_.field_count(); ++i) { 2476 AutofillType type = form_structure_.field(i)->Type(); 2477 if (common::IsCreditCardType(type.GetStorableType())) 2478 return true; 2479 } 2480 2481 return false; 2482} 2483 2484bool AutofillDialogControllerImpl::TransmissionWillBeSecure() const { 2485 return source_url_.SchemeIs(content::kHttpsScheme); 2486} 2487 2488bool AutofillDialogControllerImpl::IsSubmitPausedOn( 2489 wallet::RequiredAction required_action) const { 2490 return full_wallet_ && full_wallet_->HasRequiredAction(required_action); 2491} 2492 2493void AutofillDialogControllerImpl::ShowNewCreditCardBubble( 2494 scoped_ptr<CreditCard> new_card, 2495 scoped_ptr<AutofillProfile> billing_profile) { 2496#if !defined(OS_ANDROID) 2497 NewCreditCardBubbleController::Show(web_contents(), 2498 new_card.Pass(), 2499 billing_profile.Pass()); 2500#endif 2501} 2502 2503void AutofillDialogControllerImpl::SubmitButtonDelayBegin() { 2504 submit_button_delay_timer_.Start( 2505 FROM_HERE, 2506 base::TimeDelta::FromMilliseconds(kSubmitButtonDelayMs), 2507 this, 2508 &AutofillDialogControllerImpl::OnSubmitButtonDelayEnd); 2509} 2510 2511void AutofillDialogControllerImpl::SubmitButtonDelayEndForTesting() { 2512 DCHECK(submit_button_delay_timer_.IsRunning()); 2513 submit_button_delay_timer_.user_task().Run(); 2514 submit_button_delay_timer_.Stop(); 2515} 2516 2517void AutofillDialogControllerImpl:: 2518 ClearLastWalletItemsFetchTimestampForTesting() { 2519 last_wallet_items_fetch_timestamp_ = base::TimeTicks(); 2520} 2521 2522AccountChooserModel* AutofillDialogControllerImpl:: 2523 AccountChooserModelForTesting() { 2524 return account_chooser_model_.get(); 2525} 2526 2527bool AutofillDialogControllerImpl::IsSignInContinueUrl( 2528 const GURL& url, 2529 size_t* user_index) const { 2530 return wallet::IsSignInContinueUrl(url, user_index); 2531} 2532 2533AutofillDialogControllerImpl::AutofillDialogControllerImpl( 2534 content::WebContents* contents, 2535 const FormData& form_structure, 2536 const GURL& source_url, 2537 const base::Callback<void(const FormStructure*)>& callback) 2538 : WebContentsObserver(contents), 2539 profile_(Profile::FromBrowserContext(contents->GetBrowserContext())), 2540 initial_user_state_(AutofillMetrics::DIALOG_USER_STATE_UNKNOWN), 2541 form_structure_(form_structure), 2542 invoked_from_same_origin_(true), 2543 source_url_(source_url), 2544 callback_(callback), 2545 wallet_client_(profile_->GetRequestContext(), this, source_url), 2546 wallet_items_requested_(false), 2547 handling_use_wallet_link_click_(false), 2548 passive_failed_(false), 2549 country_combobox_model_(*GetManager()), 2550 suggested_cc_(this), 2551 suggested_billing_(this), 2552 suggested_cc_billing_(this), 2553 suggested_shipping_(this), 2554 cares_about_shipping_(true), 2555 input_showing_popup_(NULL), 2556 weak_ptr_factory_(this), 2557 waiting_for_explicit_sign_in_response_(false), 2558 has_accepted_legal_documents_(false), 2559 is_submitting_(false), 2560 choose_another_instrument_or_address_(false), 2561 wallet_server_validation_recoverable_(true), 2562 data_was_passed_back_(false), 2563 was_ui_latency_logged_(false), 2564 card_generated_animation_(2000, 60, this) { 2565 // TODO(estade): remove duplicates from |form_structure|? 2566 DCHECK(!callback_.is_null()); 2567} 2568 2569AutofillDialogView* AutofillDialogControllerImpl::CreateView() { 2570 return AutofillDialogView::Create(this); 2571} 2572 2573PersonalDataManager* AutofillDialogControllerImpl::GetManager() const { 2574 return PersonalDataManagerFactory::GetForProfile(profile_); 2575} 2576 2577const wallet::WalletClient* AutofillDialogControllerImpl::GetWalletClient() 2578 const { 2579 return const_cast<AutofillDialogControllerImpl*>(this)->GetWalletClient(); 2580} 2581 2582wallet::WalletClient* AutofillDialogControllerImpl::GetWalletClient() { 2583 return &wallet_client_; 2584} 2585 2586bool AutofillDialogControllerImpl::IsPayingWithWallet() const { 2587 return account_chooser_model_->WalletIsSelected() && 2588 SignedInState() == SIGNED_IN; 2589} 2590 2591void AutofillDialogControllerImpl::LoadRiskFingerprintData() { 2592 risk_data_.clear(); 2593 2594 uint64 obfuscated_gaia_id = 0; 2595 bool success = base::StringToUint64(wallet_items_->ObfuscatedGaiaId(), 2596 &obfuscated_gaia_id); 2597 DCHECK(success); 2598 2599 gfx::Rect window_bounds; 2600 window_bounds = GetBaseWindowForWebContents(web_contents())->GetBounds(); 2601 2602 PrefService* user_prefs = profile_->GetPrefs(); 2603 std::string charset = user_prefs->GetString(::prefs::kDefaultCharset); 2604 std::string accept_languages = 2605 user_prefs->GetString(::prefs::kAcceptLanguages); 2606 base::Time install_time = base::Time::FromTimeT( 2607 g_browser_process->local_state()->GetInt64(::prefs::kInstallDate)); 2608 2609 risk::GetFingerprint( 2610 obfuscated_gaia_id, window_bounds, *web_contents(), 2611 chrome::VersionInfo().Version(), charset, accept_languages, install_time, 2612 g_browser_process->GetApplicationLocale(), 2613 base::Bind(&AutofillDialogControllerImpl::OnDidLoadRiskFingerprintData, 2614 weak_ptr_factory_.GetWeakPtr())); 2615} 2616 2617void AutofillDialogControllerImpl::OnDidLoadRiskFingerprintData( 2618 scoped_ptr<risk::Fingerprint> fingerprint) { 2619 DCHECK(AreLegalDocumentsCurrent()); 2620 2621 std::string proto_data; 2622 fingerprint->SerializeToString(&proto_data); 2623 base::Base64Encode(proto_data, &risk_data_); 2624 2625 SubmitWithWallet(); 2626} 2627 2628void AutofillDialogControllerImpl::OpenTabWithUrl(const GURL& url) { 2629 chrome::NavigateParams params( 2630 chrome::FindBrowserWithWebContents(web_contents()), 2631 url, 2632 content::PAGE_TRANSITION_LINK); 2633 params.disposition = NEW_FOREGROUND_TAB; 2634 chrome::Navigate(¶ms); 2635} 2636 2637bool AutofillDialogControllerImpl::IsEditingExistingData( 2638 DialogSection section) const { 2639 return section_editing_state_.count(section) > 0; 2640} 2641 2642bool AutofillDialogControllerImpl::IsManuallyEditingSection( 2643 DialogSection section) const { 2644 return IsEditingExistingData(section) || 2645 SuggestionsMenuModelForSection(section)-> 2646 GetItemKeyForCheckedItem() == kAddNewItemKey; 2647} 2648 2649void AutofillDialogControllerImpl::OnWalletSigninError() { 2650 account_chooser_model_->SetHadWalletSigninError(); 2651 GetWalletClient()->CancelRequests(); 2652 LogDialogLatencyToShow(); 2653} 2654 2655void AutofillDialogControllerImpl::DisableWallet( 2656 wallet::WalletClient::ErrorType error_type) { 2657 signin_helper_.reset(); 2658 wallet_items_.reset(); 2659 wallet_errors_.clear(); 2660 GetWalletClient()->CancelRequests(); 2661 SetIsSubmitting(false); 2662 wallet_error_notification_ = GetWalletError(error_type); 2663 account_chooser_model_->SetHadWalletError(); 2664} 2665 2666void AutofillDialogControllerImpl::SuggestionsUpdated() { 2667 ScopedViewUpdates updates(view_.get()); 2668 2669 const FieldValueMap snapshot = TakeUserInputSnapshot(); 2670 2671 suggested_cc_.Reset(); 2672 suggested_billing_.Reset(); 2673 suggested_cc_billing_.Reset(); 2674 suggested_shipping_.Reset(); 2675 HidePopup(); 2676 2677 suggested_shipping_.AddKeyedItem( 2678 kSameAsBillingKey, 2679 l10n_util::GetStringUTF16(IDS_AUTOFILL_DIALOG_USE_BILLING_FOR_SHIPPING)); 2680 2681 if (IsPayingWithWallet()) { 2682 const std::vector<wallet::Address*>& addresses = 2683 wallet_items_->addresses(); 2684 for (size_t i = 0; i < addresses.size(); ++i) { 2685 std::string key = base::IntToString(i); 2686 suggested_shipping_.AddKeyedItemWithMinorText( 2687 key, 2688 addresses[i]->DisplayName(), 2689 addresses[i]->DisplayNameDetail()); 2690 2691 const std::string default_shipping_address_id = 2692 GetIdToSelect(wallet_items_->default_address_id(), 2693 previous_default_shipping_address_id_, 2694 previously_selected_shipping_address_id_); 2695 if (addresses[i]->object_id() == default_shipping_address_id) 2696 suggested_shipping_.SetCheckedItem(key); 2697 } 2698 2699 if (!IsSubmitPausedOn(wallet::VERIFY_CVV)) { 2700 const std::vector<wallet::WalletItems::MaskedInstrument*>& instruments = 2701 wallet_items_->instruments(); 2702 std::string first_active_instrument_key; 2703 std::string default_instrument_key; 2704 for (size_t i = 0; i < instruments.size(); ++i) { 2705 bool allowed = IsInstrumentAllowed(*instruments[i]); 2706 gfx::Image icon = instruments[i]->CardIcon(); 2707 if (!allowed && !icon.IsEmpty()) { 2708 // Create a grayed disabled icon. 2709 SkBitmap disabled_bitmap = SkBitmapOperations::CreateHSLShiftedBitmap( 2710 *icon.ToSkBitmap(), kGrayImageShift); 2711 icon = gfx::Image( 2712 gfx::ImageSkia::CreateFrom1xBitmap(disabled_bitmap)); 2713 } 2714 std::string key = base::IntToString(i); 2715 suggested_cc_billing_.AddKeyedItemWithMinorTextAndIcon( 2716 key, 2717 instruments[i]->DisplayName(), 2718 instruments[i]->DisplayNameDetail(), 2719 icon); 2720 suggested_cc_billing_.SetEnabled(key, allowed); 2721 2722 if (allowed) { 2723 if (first_active_instrument_key.empty()) 2724 first_active_instrument_key = key; 2725 2726 const std::string default_instrument_id = 2727 GetIdToSelect(wallet_items_->default_instrument_id(), 2728 previous_default_instrument_id_, 2729 previously_selected_instrument_id_); 2730 if (instruments[i]->object_id() == default_instrument_id) 2731 default_instrument_key = key; 2732 } 2733 } 2734 2735 suggested_cc_billing_.AddKeyedItem( 2736 kAddNewItemKey, 2737 l10n_util::GetStringUTF16(IDS_AUTOFILL_DIALOG_ADD_BILLING_DETAILS)); 2738 if (!wallet_items_->HasRequiredAction(wallet::SETUP_WALLET)) { 2739 suggested_cc_billing_.AddKeyedItemWithMinorText( 2740 kManageItemsKey, 2741 l10n_util::GetStringUTF16( 2742 IDS_AUTOFILL_DIALOG_MANAGE_BILLING_DETAILS), 2743 UTF8ToUTF16(wallet::GetManageInstrumentsUrl(0U).host())); 2744 } 2745 2746 // Determine which instrument item should be selected. 2747 if (!default_instrument_key.empty()) 2748 suggested_cc_billing_.SetCheckedItem(default_instrument_key); 2749 else if (!first_active_instrument_key.empty()) 2750 suggested_cc_billing_.SetCheckedItem(first_active_instrument_key); 2751 else 2752 suggested_cc_billing_.SetCheckedItem(kAddNewItemKey); 2753 } 2754 } else { 2755 PersonalDataManager* manager = GetManager(); 2756 const std::vector<CreditCard*>& cards = manager->GetCreditCards(); 2757 ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance(); 2758 for (size_t i = 0; i < cards.size(); ++i) { 2759 if (!HasCompleteAndVerifiedData(*cards[i], requested_cc_fields_)) 2760 continue; 2761 2762 suggested_cc_.AddKeyedItemWithIcon( 2763 cards[i]->guid(), 2764 cards[i]->Label(), 2765 rb.GetImageNamed(CreditCard::IconResourceId(cards[i]->type()))); 2766 } 2767 2768 const std::vector<AutofillProfile*>& profiles = manager->GetProfiles(); 2769 std::vector<base::string16> labels; 2770 AutofillProfile::CreateDifferentiatingLabels(profiles, &labels); 2771 DCHECK_EQ(labels.size(), profiles.size()); 2772 const std::string app_locale = g_browser_process->GetApplicationLocale(); 2773 for (size_t i = 0; i < profiles.size(); ++i) { 2774 const AutofillProfile& profile = *profiles[i]; 2775 if (!HasCompleteAndVerifiedData(profile, requested_shipping_fields_) || 2776 HasInvalidAddress(*profiles[i])) { 2777 continue; 2778 } 2779 2780 // Don't add variants for addresses: name is part of credit card and we'll 2781 // just ignore email and phone number variants. 2782 suggested_shipping_.AddKeyedItem(profile.guid(), labels[i]); 2783 if (!profile.GetRawInfo(EMAIL_ADDRESS).empty() && 2784 !profile.IsPresentButInvalid(EMAIL_ADDRESS)) { 2785 suggested_billing_.AddKeyedItem(profile.guid(), labels[i]); 2786 } 2787 } 2788 2789 suggested_cc_.AddKeyedItem( 2790 kAddNewItemKey, 2791 l10n_util::GetStringUTF16(IDS_AUTOFILL_DIALOG_ADD_CREDIT_CARD)); 2792 suggested_cc_.AddKeyedItem( 2793 kManageItemsKey, 2794 l10n_util::GetStringUTF16(IDS_AUTOFILL_DIALOG_MANAGE_CREDIT_CARD)); 2795 suggested_billing_.AddKeyedItem( 2796 kAddNewItemKey, 2797 l10n_util::GetStringUTF16(IDS_AUTOFILL_DIALOG_ADD_BILLING_ADDRESS)); 2798 suggested_billing_.AddKeyedItem( 2799 kManageItemsKey, 2800 l10n_util::GetStringUTF16(IDS_AUTOFILL_DIALOG_MANAGE_BILLING_ADDRESS)); 2801 } 2802 2803 suggested_shipping_.AddKeyedItem( 2804 kAddNewItemKey, 2805 l10n_util::GetStringUTF16(IDS_AUTOFILL_DIALOG_ADD_SHIPPING_ADDRESS)); 2806 if (!IsPayingWithWallet()) { 2807 suggested_shipping_.AddKeyedItem( 2808 kManageItemsKey, 2809 l10n_util::GetStringUTF16(IDS_AUTOFILL_DIALOG_MANAGE_SHIPPING_ADDRESS)); 2810 } else if (!wallet_items_->HasRequiredAction(wallet::SETUP_WALLET)) { 2811 suggested_shipping_.AddKeyedItemWithMinorText( 2812 kManageItemsKey, 2813 l10n_util::GetStringUTF16(IDS_AUTOFILL_DIALOG_MANAGE_SHIPPING_ADDRESS), 2814 UTF8ToUTF16(wallet::GetManageAddressesUrl(0U).host())); 2815 } 2816 2817 if (!IsPayingWithWallet()) { 2818 for (size_t i = SECTION_MIN; i <= SECTION_MAX; ++i) { 2819 DialogSection section = static_cast<DialogSection>(i); 2820 if (!SectionIsActive(section)) 2821 continue; 2822 2823 // Set the starting choice for the menu. First set to the default in case 2824 // the GUID saved in prefs refers to a profile that no longer exists. 2825 std::string guid; 2826 GetDefaultAutofillChoice(section, &guid); 2827 SuggestionsMenuModel* model = SuggestionsMenuModelForSection(section); 2828 model->SetCheckedItem(guid); 2829 if (GetAutofillChoice(section, &guid)) 2830 model->SetCheckedItem(guid); 2831 } 2832 } 2833 2834 if (view_) 2835 view_->ModelChanged(); 2836 2837 for (size_t i = SECTION_MIN; i <= SECTION_MAX; ++i) { 2838 ResetSectionInput(static_cast<DialogSection>(i)); 2839 } 2840 2841 RestoreUserInputFromSnapshot(snapshot); 2842 2843 for (size_t i = SECTION_MIN; i <= SECTION_MAX; ++i) { 2844 DialogSection section = static_cast<DialogSection>(i); 2845 if (!SectionIsActive(section)) 2846 continue; 2847 2848 ShowEditUiIfBadSuggestion(section); 2849 UpdateSection(section); 2850 } 2851 2852 UpdateForErrors(); 2853} 2854 2855void AutofillDialogControllerImpl::FillOutputForSectionWithComparator( 2856 DialogSection section, 2857 const InputFieldComparator& compare) { 2858 const DetailInputs& inputs = RequestedFieldsForSection(section); 2859 2860 if (!SectionIsActive(section)) 2861 return; 2862 2863 scoped_ptr<DataModelWrapper> wrapper = CreateWrapper(section); 2864 if (wrapper) { 2865 // Only fill in data that is associated with this section. 2866 const DetailInputs& inputs = RequestedFieldsForSection(section); 2867 wrapper->FillFormStructure(inputs, compare, &form_structure_); 2868 2869 // CVC needs special-casing because the CreditCard class doesn't store or 2870 // handle them. This isn't necessary when filling the combined CC and 2871 // billing section as CVC comes from |full_wallet_| in this case. 2872 if (section == SECTION_CC) 2873 SetOutputForFieldsOfType(CREDIT_CARD_VERIFICATION_CODE, view_->GetCvc()); 2874 2875 // When filling from Wallet data, use the email address associated with the 2876 // account. There is no other email address stored as part of a Wallet 2877 // address. 2878 if (section == SECTION_CC_BILLING) { 2879 SetOutputForFieldsOfType( 2880 EMAIL_ADDRESS, account_chooser_model_->GetActiveWalletAccountName()); 2881 } 2882 } else { 2883 // The user manually input data. If using Autofill, save the info as new or 2884 // edited data. Always fill local data into |form_structure_|. 2885 FieldValueMap output; 2886 view_->GetUserInput(section, &output); 2887 2888 if (section == SECTION_CC) { 2889 CreditCard card; 2890 card.set_origin(kAutofillDialogOrigin); 2891 FillFormGroupFromOutputs(output, &card); 2892 2893 // The card holder name comes from the billing address section. 2894 card.SetRawInfo(CREDIT_CARD_NAME, 2895 GetValueFromSection(SECTION_BILLING, NAME_BILLING_FULL)); 2896 2897 if (ShouldSaveDetailsLocally()) { 2898 std::string guid = GetManager()->SaveImportedCreditCard(card); 2899 newly_saved_data_model_guids_[section] = guid; 2900 DCHECK(!profile()->IsOffTheRecord()); 2901 newly_saved_card_.reset(new CreditCard(card)); 2902 } 2903 2904 AutofillCreditCardWrapper card_wrapper(&card); 2905 card_wrapper.FillFormStructure(inputs, compare, &form_structure_); 2906 2907 // Again, CVC needs special-casing. Fill it in directly from |output|. 2908 SetOutputForFieldsOfType( 2909 CREDIT_CARD_VERIFICATION_CODE, 2910 output[CREDIT_CARD_VERIFICATION_CODE]); 2911 } else { 2912 AutofillProfile profile; 2913 profile.set_origin(kAutofillDialogOrigin); 2914 FillFormGroupFromOutputs(output, &profile); 2915 2916 if (ShouldSaveDetailsLocally()) { 2917 std::string guid = GetManager()->SaveImportedProfile(profile); 2918 newly_saved_data_model_guids_[section] = guid; 2919 } 2920 2921 AutofillProfileWrapper profile_wrapper(&profile); 2922 profile_wrapper.FillFormStructure(inputs, compare, &form_structure_); 2923 } 2924 } 2925} 2926 2927void AutofillDialogControllerImpl::FillOutputForSection(DialogSection section) { 2928 FillOutputForSectionWithComparator( 2929 section, base::Bind(common::DetailInputMatchesField, section)); 2930} 2931 2932bool AutofillDialogControllerImpl::FormStructureCaresAboutSection( 2933 DialogSection section) const { 2934 // For now, only SECTION_SHIPPING may be omitted due to a site not asking for 2935 // any of the fields. 2936 if (section == SECTION_SHIPPING) 2937 return cares_about_shipping_; 2938 2939 return true; 2940} 2941 2942void AutofillDialogControllerImpl::SetOutputForFieldsOfType( 2943 ServerFieldType type, 2944 const base::string16& output) { 2945 for (size_t i = 0; i < form_structure_.field_count(); ++i) { 2946 AutofillField* field = form_structure_.field(i); 2947 if (field->Type().GetStorableType() == type) 2948 field->value = output; 2949 } 2950} 2951 2952base::string16 AutofillDialogControllerImpl::GetValueFromSection( 2953 DialogSection section, 2954 ServerFieldType type) { 2955 DCHECK(SectionIsActive(section)); 2956 2957 scoped_ptr<DataModelWrapper> wrapper = CreateWrapper(section); 2958 if (wrapper) 2959 return wrapper->GetInfo(AutofillType(type)); 2960 2961 FieldValueMap output; 2962 view_->GetUserInput(section, &output); 2963 return output[type]; 2964} 2965 2966SuggestionsMenuModel* AutofillDialogControllerImpl:: 2967 SuggestionsMenuModelForSection(DialogSection section) { 2968 switch (section) { 2969 case SECTION_CC: 2970 return &suggested_cc_; 2971 case SECTION_BILLING: 2972 return &suggested_billing_; 2973 case SECTION_SHIPPING: 2974 return &suggested_shipping_; 2975 case SECTION_CC_BILLING: 2976 return &suggested_cc_billing_; 2977 } 2978 2979 NOTREACHED(); 2980 return NULL; 2981} 2982 2983const SuggestionsMenuModel* AutofillDialogControllerImpl:: 2984 SuggestionsMenuModelForSection(DialogSection section) const { 2985 return const_cast<AutofillDialogControllerImpl*>(this)-> 2986 SuggestionsMenuModelForSection(section); 2987} 2988 2989DialogSection AutofillDialogControllerImpl::SectionForSuggestionsMenuModel( 2990 const SuggestionsMenuModel& model) { 2991 if (&model == &suggested_cc_) 2992 return SECTION_CC; 2993 2994 if (&model == &suggested_billing_) 2995 return SECTION_BILLING; 2996 2997 if (&model == &suggested_cc_billing_) 2998 return SECTION_CC_BILLING; 2999 3000 DCHECK_EQ(&model, &suggested_shipping_); 3001 return SECTION_SHIPPING; 3002} 3003 3004DetailInputs* AutofillDialogControllerImpl::MutableRequestedFieldsForSection( 3005 DialogSection section) { 3006 return const_cast<DetailInputs*>(&RequestedFieldsForSection(section)); 3007} 3008 3009void AutofillDialogControllerImpl::HidePopup() { 3010 if (popup_controller_.get()) 3011 popup_controller_->Hide(); 3012 input_showing_popup_ = NULL; 3013} 3014 3015void AutofillDialogControllerImpl::SetEditingExistingData( 3016 DialogSection section, bool editing) { 3017 if (editing) 3018 section_editing_state_.insert(section); 3019 else 3020 section_editing_state_.erase(section); 3021} 3022 3023bool AutofillDialogControllerImpl::IsASuggestionItemKey( 3024 const std::string& key) const { 3025 return !key.empty() && 3026 key != kAddNewItemKey && 3027 key != kManageItemsKey && 3028 key != kSameAsBillingKey; 3029} 3030 3031bool AutofillDialogControllerImpl::IsManuallyEditingAnySection() const { 3032 for (size_t section = SECTION_MIN; section <= SECTION_MAX; ++section) { 3033 if (IsManuallyEditingSection(static_cast<DialogSection>(section))) 3034 return true; 3035 } 3036 return false; 3037} 3038 3039base::string16 AutofillDialogControllerImpl::CreditCardNumberValidityMessage( 3040 const base::string16& number) const { 3041 if (!number.empty() && !autofill::IsValidCreditCardNumber(number)) { 3042 return l10n_util::GetStringUTF16( 3043 IDS_AUTOFILL_DIALOG_VALIDATION_INVALID_CREDIT_CARD_NUMBER); 3044 } 3045 3046 base::string16 message; 3047 if (IsPayingWithWallet() && !wallet_items_->SupportsCard(number, &message)) 3048 return message; 3049 3050 // Card number is good and supported. 3051 return base::string16(); 3052} 3053 3054bool AutofillDialogControllerImpl::AllSectionsAreValid() { 3055 for (size_t section = SECTION_MIN; section <= SECTION_MAX; ++section) { 3056 if (!SectionIsValid(static_cast<DialogSection>(section))) 3057 return false; 3058 } 3059 return true; 3060} 3061 3062bool AutofillDialogControllerImpl::SectionIsValid( 3063 DialogSection section) { 3064 if (!IsManuallyEditingSection(section)) 3065 return true; 3066 3067 FieldValueMap detail_outputs; 3068 view_->GetUserInput(section, &detail_outputs); 3069 return !InputsAreValid(section, detail_outputs).HasSureErrors(); 3070} 3071 3072bool AutofillDialogControllerImpl::IsCreditCardExpirationValid( 3073 const base::string16& year, 3074 const base::string16& month) const { 3075 // If the expiration is in the past as per the local clock, it's invalid. 3076 base::Time now = base::Time::Now(); 3077 if (!autofill::IsValidCreditCardExpirationDate(year, month, now)) 3078 return false; 3079 3080 if (IsPayingWithWallet() && IsEditingExistingData(SECTION_CC_BILLING)) { 3081 const wallet::WalletItems::MaskedInstrument* instrument = 3082 ActiveInstrument(); 3083 const std::string& locale = g_browser_process->GetApplicationLocale(); 3084 int month_int; 3085 if (base::StringToInt(month, &month_int) && 3086 instrument->status() == 3087 wallet::WalletItems::MaskedInstrument::EXPIRED && 3088 year == 3089 instrument->GetInfo( 3090 AutofillType(CREDIT_CARD_EXP_4_DIGIT_YEAR), locale) && 3091 month_int == instrument->expiration_month()) { 3092 // Otherwise, if the user is editing an instrument that's deemed expired 3093 // by the Online Wallet server, mark it invalid on selection. 3094 return false; 3095 } 3096 } 3097 3098 return true; 3099} 3100 3101bool AutofillDialogControllerImpl::ShouldUseBillingForShipping() { 3102 return SectionIsActive(SECTION_SHIPPING) && 3103 suggested_shipping_.GetItemKeyForCheckedItem() == kSameAsBillingKey; 3104} 3105 3106bool AutofillDialogControllerImpl::ShouldSaveDetailsLocally() { 3107 // It's possible that the user checked [X] Save details locally before 3108 // switching payment methods, so only ask the view whether to save details 3109 // locally if that checkbox is showing (currently if not paying with wallet). 3110 // Also, if the user isn't editing any sections, there's no data to save 3111 // locally. 3112 return ShouldOfferToSaveInChrome() && view_->SaveDetailsLocally(); 3113} 3114 3115void AutofillDialogControllerImpl::SetIsSubmitting(bool submitting) { 3116 is_submitting_ = submitting; 3117 3118 if (!submitting) 3119 full_wallet_.reset(); 3120 3121 if (view_) { 3122 ScopedViewUpdates updates(view_.get()); 3123 view_->UpdateButtonStrip(); 3124 view_->UpdateOverlay(); 3125 view_->UpdateNotificationArea(); 3126 } 3127} 3128 3129bool AutofillDialogControllerImpl::AreLegalDocumentsCurrent() const { 3130 return has_accepted_legal_documents_ || 3131 (wallet_items_ && wallet_items_->legal_documents().empty()); 3132} 3133 3134void AutofillDialogControllerImpl::AcceptLegalTerms() { 3135 content::BrowserThread::PostTask( 3136 content::BrowserThread::IO, FROM_HERE, 3137 base::Bind(&UserDidOptIntoLocationServices)); 3138 PrefService* local_state = g_browser_process->local_state(); 3139 ListPrefUpdate accepted( 3140 local_state, ::prefs::kAutofillDialogWalletLocationAcceptance); 3141 accepted->AppendIfNotPresent(new base::StringValue( 3142 account_chooser_model_->GetActiveWalletAccountName())); 3143 3144 if (AreLegalDocumentsCurrent()) { 3145 LoadRiskFingerprintData(); 3146 } else { 3147 GetWalletClient()->AcceptLegalDocuments( 3148 wallet_items_->legal_documents(), 3149 wallet_items_->google_transaction_id()); 3150 } 3151} 3152 3153void AutofillDialogControllerImpl::SubmitWithWallet() { 3154 active_instrument_id_.clear(); 3155 active_address_id_.clear(); 3156 full_wallet_.reset(); 3157 3158 const wallet::WalletItems::MaskedInstrument* active_instrument = 3159 ActiveInstrument(); 3160 if (!IsManuallyEditingSection(SECTION_CC_BILLING)) { 3161 active_instrument_id_ = active_instrument->object_id(); 3162 DCHECK(!active_instrument_id_.empty()); 3163 } 3164 3165 const wallet::Address* active_address = ActiveShippingAddress(); 3166 if (!IsManuallyEditingSection(SECTION_SHIPPING) && 3167 !ShouldUseBillingForShipping() && 3168 IsShippingAddressRequired()) { 3169 active_address_id_ = active_address->object_id(); 3170 DCHECK(!active_address_id_.empty()); 3171 } 3172 3173 scoped_ptr<wallet::Instrument> inputted_instrument = 3174 CreateTransientInstrument(); 3175 if (inputted_instrument && IsEditingExistingData(SECTION_CC_BILLING)) { 3176 inputted_instrument->set_object_id(active_instrument->object_id()); 3177 DCHECK(!inputted_instrument->object_id().empty()); 3178 } 3179 3180 scoped_ptr<wallet::Address> inputted_address; 3181 if (active_address_id_.empty() && IsShippingAddressRequired()) { 3182 if (ShouldUseBillingForShipping()) { 3183 const wallet::Address& address = inputted_instrument ? 3184 *inputted_instrument->address() : active_instrument->address(); 3185 // Try to find an exact matched shipping address and use it for shipping, 3186 // otherwise save it as a new shipping address. http://crbug.com/225442 3187 const wallet::Address* duplicated_address = 3188 FindDuplicateAddress(wallet_items_->addresses(), address); 3189 if (duplicated_address) { 3190 active_address_id_ = duplicated_address->object_id(); 3191 DCHECK(!active_address_id_.empty()); 3192 } else { 3193 inputted_address.reset(new wallet::Address(address)); 3194 DCHECK(inputted_address->object_id().empty()); 3195 } 3196 } else { 3197 inputted_address = CreateTransientAddress(); 3198 if (IsEditingExistingData(SECTION_SHIPPING)) { 3199 inputted_address->set_object_id(active_address->object_id()); 3200 DCHECK(!inputted_address->object_id().empty()); 3201 } 3202 } 3203 } 3204 3205 // If there's neither an address nor instrument to save, |GetFullWallet()| 3206 // is called when the risk fingerprint is loaded. 3207 if (!active_instrument_id_.empty() && 3208 (!active_address_id_.empty() || !IsShippingAddressRequired())) { 3209 GetFullWallet(); 3210 return; 3211 } 3212 3213 GetWalletClient()->SaveToWallet(inputted_instrument.Pass(), 3214 inputted_address.Pass()); 3215} 3216 3217scoped_ptr<wallet::Instrument> AutofillDialogControllerImpl:: 3218 CreateTransientInstrument() { 3219 if (!active_instrument_id_.empty()) 3220 return scoped_ptr<wallet::Instrument>(); 3221 3222 FieldValueMap output; 3223 view_->GetUserInput(SECTION_CC_BILLING, &output); 3224 3225 CreditCard card; 3226 AutofillProfile profile; 3227 base::string16 cvc; 3228 GetBillingInfoFromOutputs(output, &card, &cvc, &profile); 3229 3230 return scoped_ptr<wallet::Instrument>( 3231 new wallet::Instrument(card, cvc, profile)); 3232} 3233 3234scoped_ptr<wallet::Address>AutofillDialogControllerImpl:: 3235 CreateTransientAddress() { 3236 // If not using billing for shipping, just scrape the view. 3237 FieldValueMap output; 3238 view_->GetUserInput(SECTION_SHIPPING, &output); 3239 3240 AutofillProfile profile; 3241 FillFormGroupFromOutputs(output, &profile); 3242 3243 return scoped_ptr<wallet::Address>(new wallet::Address(profile)); 3244} 3245 3246void AutofillDialogControllerImpl::GetFullWallet() { 3247 DCHECK(is_submitting_); 3248 DCHECK(IsPayingWithWallet()); 3249 DCHECK(wallet_items_); 3250 DCHECK(!active_instrument_id_.empty()); 3251 DCHECK(!active_address_id_.empty() || !IsShippingAddressRequired()); 3252 3253 std::vector<wallet::WalletClient::RiskCapability> capabilities; 3254 capabilities.push_back(wallet::WalletClient::VERIFY_CVC); 3255 3256 GetWalletClient()->GetFullWallet(wallet::WalletClient::FullWalletRequest( 3257 active_instrument_id_, 3258 active_address_id_, 3259 wallet_items_->google_transaction_id(), 3260 capabilities, 3261 wallet_items_->HasRequiredAction(wallet::SETUP_WALLET))); 3262} 3263 3264void AutofillDialogControllerImpl::HandleSaveOrUpdateRequiredActions( 3265 const std::vector<wallet::RequiredAction>& required_actions) { 3266 DCHECK(!required_actions.empty()); 3267 3268 // TODO(ahutter): Investigate if we need to support more generic actions on 3269 // this call such as GAIA_AUTH. See crbug.com/243457. 3270 for (std::vector<wallet::RequiredAction>::const_iterator iter = 3271 required_actions.begin(); 3272 iter != required_actions.end(); ++iter) { 3273 if (*iter != wallet::INVALID_FORM_FIELD) { 3274 // TODO(dbeam): handle this more gracefully. 3275 DisableWallet(wallet::WalletClient::UNKNOWN_ERROR); 3276 } 3277 } 3278 SetIsSubmitting(false); 3279} 3280 3281void AutofillDialogControllerImpl::FinishSubmit() { 3282 if (IsPayingWithWallet()) { 3283 ScopedViewUpdates updates(view_.get()); 3284 view_->UpdateOverlay(); 3285 3286 card_generated_animation_.Start(); 3287 return; 3288 } 3289 DoFinishSubmit(); 3290} 3291 3292void AutofillDialogControllerImpl::AnimationProgressed( 3293 const gfx::Animation* animation) { 3294 DCHECK_EQ(animation, &card_generated_animation_); 3295 PushOverlayUpdate(); 3296} 3297 3298void AutofillDialogControllerImpl::AnimationEnded( 3299 const gfx::Animation* animation) { 3300 DCHECK_EQ(animation, &card_generated_animation_); 3301 DoFinishSubmit(); 3302} 3303 3304void AutofillDialogControllerImpl::DoFinishSubmit() { 3305 FillOutputForSection(SECTION_CC); 3306 FillOutputForSection(SECTION_BILLING); 3307 FillOutputForSection(SECTION_CC_BILLING); 3308 3309 if (ShouldUseBillingForShipping()) { 3310 FillOutputForSectionWithComparator( 3311 SECTION_BILLING, 3312 base::Bind(DetailInputMatchesShippingField)); 3313 FillOutputForSectionWithComparator( 3314 SECTION_CC, 3315 base::Bind(DetailInputMatchesShippingField)); 3316 FillOutputForSectionWithComparator( 3317 SECTION_CC_BILLING, 3318 base::Bind(DetailInputMatchesShippingField)); 3319 } else { 3320 FillOutputForSection(SECTION_SHIPPING); 3321 } 3322 3323 if (!IsPayingWithWallet()) { 3324 for (size_t i = SECTION_MIN; i <= SECTION_MAX; ++i) { 3325 DialogSection section = static_cast<DialogSection>(i); 3326 if (!SectionIsActive(section)) 3327 continue; 3328 3329 SuggestionsMenuModel* model = SuggestionsMenuModelForSection(section); 3330 std::string item_key = model->GetItemKeyForCheckedItem(); 3331 if (IsASuggestionItemKey(item_key) || item_key == kSameAsBillingKey) { 3332 PersistAutofillChoice(section, item_key); 3333 } else if (item_key == kAddNewItemKey && ShouldSaveDetailsLocally()) { 3334 DCHECK(newly_saved_data_model_guids_.count(section)); 3335 PersistAutofillChoice(section, newly_saved_data_model_guids_[section]); 3336 } 3337 } 3338 3339 profile_->GetPrefs()->SetBoolean(::prefs::kAutofillDialogSaveData, 3340 view_->SaveDetailsLocally()); 3341 } 3342 3343 // On a successful submit, if the user manually selected "pay without wallet", 3344 // stop trying to pay with Wallet on future runs of the dialog. On the other 3345 // hand, if there was an error that prevented the user from having the choice 3346 // of using Wallet, leave the pref alone. 3347 if (!wallet_error_notification_ && 3348 account_chooser_model_->HasAccountsToChoose()) { 3349 profile_->GetPrefs()->SetBoolean( 3350 ::prefs::kAutofillDialogPayWithoutWallet, 3351 !account_chooser_model_->WalletIsSelected()); 3352 } 3353 3354 LogOnFinishSubmitMetrics(); 3355 3356 // Callback should be called as late as possible. 3357 callback_.Run(&form_structure_); 3358 data_was_passed_back_ = true; 3359 3360 // This might delete us. 3361 Hide(); 3362} 3363 3364void AutofillDialogControllerImpl::PersistAutofillChoice( 3365 DialogSection section, 3366 const std::string& guid) { 3367 DCHECK(!IsPayingWithWallet()); 3368 scoped_ptr<base::DictionaryValue> value(new base::DictionaryValue()); 3369 value->SetString(kGuidPrefKey, guid); 3370 3371 DictionaryPrefUpdate updater(profile()->GetPrefs(), 3372 ::prefs::kAutofillDialogAutofillDefault); 3373 base::DictionaryValue* autofill_choice = updater.Get(); 3374 autofill_choice->Set(SectionToPrefString(section), value.release()); 3375} 3376 3377void AutofillDialogControllerImpl::GetDefaultAutofillChoice( 3378 DialogSection section, 3379 std::string* guid) { 3380 DCHECK(!IsPayingWithWallet()); 3381 // The default choice is the first thing in the menu that is a suggestion 3382 // item. 3383 SuggestionsMenuModel* model = SuggestionsMenuModelForSection(section); 3384 for (int i = 0; i < model->GetItemCount(); ++i) { 3385 if (IsASuggestionItemKey(model->GetItemKeyAt(i))) { 3386 *guid = model->GetItemKeyAt(i); 3387 break; 3388 } 3389 } 3390} 3391 3392bool AutofillDialogControllerImpl::GetAutofillChoice(DialogSection section, 3393 std::string* guid) { 3394 DCHECK(!IsPayingWithWallet()); 3395 const base::DictionaryValue* choices = profile()->GetPrefs()->GetDictionary( 3396 ::prefs::kAutofillDialogAutofillDefault); 3397 if (!choices) 3398 return false; 3399 3400 const base::DictionaryValue* choice = NULL; 3401 if (!choices->GetDictionary(SectionToPrefString(section), &choice)) 3402 return false; 3403 3404 choice->GetString(kGuidPrefKey, guid); 3405 return true; 3406} 3407 3408void AutofillDialogControllerImpl::LogOnFinishSubmitMetrics() { 3409 GetMetricLogger().LogDialogUiDuration( 3410 base::Time::Now() - dialog_shown_timestamp_, 3411 AutofillMetrics::DIALOG_ACCEPTED); 3412 3413 GetMetricLogger().LogDialogUiEvent(AutofillMetrics::DIALOG_UI_ACCEPTED); 3414 3415 AutofillMetrics::DialogDismissalState dismissal_state; 3416 if (!IsManuallyEditingAnySection()) 3417 dismissal_state = AutofillMetrics::DIALOG_ACCEPTED_EXISTING_DATA; 3418 else if (IsPayingWithWallet()) 3419 dismissal_state = AutofillMetrics::DIALOG_ACCEPTED_SAVE_TO_WALLET; 3420 else if (ShouldSaveDetailsLocally()) 3421 dismissal_state = AutofillMetrics::DIALOG_ACCEPTED_SAVE_TO_AUTOFILL; 3422 else 3423 dismissal_state = AutofillMetrics::DIALOG_ACCEPTED_NO_SAVE; 3424 3425 GetMetricLogger().LogDialogDismissalState(dismissal_state); 3426} 3427 3428void AutofillDialogControllerImpl::LogOnCancelMetrics() { 3429 GetMetricLogger().LogDialogUiEvent(AutofillMetrics::DIALOG_UI_CANCELED); 3430 3431 AutofillMetrics::DialogDismissalState dismissal_state; 3432 if (ShouldShowSignInWebView()) 3433 dismissal_state = AutofillMetrics::DIALOG_CANCELED_DURING_SIGNIN; 3434 else if (!IsManuallyEditingAnySection()) 3435 dismissal_state = AutofillMetrics::DIALOG_CANCELED_NO_EDITS; 3436 else if (AllSectionsAreValid()) 3437 dismissal_state = AutofillMetrics::DIALOG_CANCELED_NO_INVALID_FIELDS; 3438 else 3439 dismissal_state = AutofillMetrics::DIALOG_CANCELED_WITH_INVALID_FIELDS; 3440 3441 GetMetricLogger().LogDialogDismissalState(dismissal_state); 3442 3443 GetMetricLogger().LogDialogUiDuration( 3444 base::Time::Now() - dialog_shown_timestamp_, 3445 AutofillMetrics::DIALOG_CANCELED); 3446} 3447 3448void AutofillDialogControllerImpl::LogSuggestionItemSelectedMetric( 3449 const SuggestionsMenuModel& model) { 3450 DialogSection section = SectionForSuggestionsMenuModel(model); 3451 3452 AutofillMetrics::DialogUiEvent dialog_ui_event; 3453 if (model.GetItemKeyForCheckedItem() == kAddNewItemKey) { 3454 // Selected to add a new item. 3455 dialog_ui_event = common::DialogSectionToUiItemAddedEvent(section); 3456 } else if (IsASuggestionItemKey(model.GetItemKeyForCheckedItem())) { 3457 // Selected an existing item. 3458 dialog_ui_event = common::DialogSectionToUiSelectionChangedEvent(section); 3459 } else { 3460 // TODO(estade): add logging for "Manage items" or "Use billing for 3461 // shipping"? 3462 return; 3463 } 3464 3465 GetMetricLogger().LogDialogUiEvent(dialog_ui_event); 3466} 3467 3468void AutofillDialogControllerImpl::LogDialogLatencyToShow() { 3469 if (was_ui_latency_logged_) 3470 return; 3471 3472 GetMetricLogger().LogDialogLatencyToShow( 3473 base::Time::Now() - dialog_shown_timestamp_); 3474 was_ui_latency_logged_ = true; 3475} 3476 3477AutofillMetrics::DialogInitialUserStateMetric 3478 AutofillDialogControllerImpl::GetInitialUserState() const { 3479 // Consider a user to be an Autofill user if the user has any credit cards 3480 // or addresses saved. Check that the item count is greater than 2 because 3481 // an "empty" menu still has the "add new" menu item and "manage" menu item. 3482 const bool has_autofill_profiles = 3483 suggested_cc_.GetItemCount() > 2 || 3484 suggested_billing_.GetItemCount() > 2; 3485 3486 if (SignedInState() != SIGNED_IN) { 3487 // Not signed in. 3488 return has_autofill_profiles ? 3489 AutofillMetrics::DIALOG_USER_NOT_SIGNED_IN_HAS_AUTOFILL : 3490 AutofillMetrics::DIALOG_USER_NOT_SIGNED_IN_NO_AUTOFILL; 3491 } 3492 3493 // Signed in. 3494 if (wallet_items_->instruments().empty()) { 3495 // No Wallet items. 3496 return has_autofill_profiles ? 3497 AutofillMetrics::DIALOG_USER_SIGNED_IN_NO_WALLET_HAS_AUTOFILL : 3498 AutofillMetrics::DIALOG_USER_SIGNED_IN_NO_WALLET_NO_AUTOFILL; 3499 } 3500 3501 // Has Wallet items. 3502 return has_autofill_profiles ? 3503 AutofillMetrics::DIALOG_USER_SIGNED_IN_HAS_WALLET_HAS_AUTOFILL : 3504 AutofillMetrics::DIALOG_USER_SIGNED_IN_HAS_WALLET_NO_AUTOFILL; 3505} 3506 3507void AutofillDialogControllerImpl::MaybeShowCreditCardBubble() { 3508 if (!data_was_passed_back_) 3509 return; 3510 3511 if (newly_saved_card_) { 3512 scoped_ptr<AutofillProfile> billing_profile; 3513 if (IsManuallyEditingSection(SECTION_BILLING)) { 3514 // Scrape the view as the user's entering or updating information. 3515 FieldValueMap outputs; 3516 view_->GetUserInput(SECTION_BILLING, &outputs); 3517 billing_profile.reset(new AutofillProfile); 3518 FillFormGroupFromOutputs(outputs, billing_profile.get()); 3519 } else { 3520 // Just snag the currently suggested profile. 3521 std::string item_key = SuggestionsMenuModelForSection(SECTION_BILLING)-> 3522 GetItemKeyForCheckedItem(); 3523 AutofillProfile* profile = GetManager()->GetProfileByGUID(item_key); 3524 billing_profile.reset(new AutofillProfile(*profile)); 3525 } 3526 3527 ShowNewCreditCardBubble(newly_saved_card_.Pass(), 3528 billing_profile.Pass()); 3529 return; 3530 } 3531 3532 if (!full_wallet_ || !full_wallet_->billing_address()) 3533 return; 3534 3535#if !defined(OS_ANDROID) 3536 GeneratedCreditCardBubbleController::Show( 3537 web_contents(), 3538 full_wallet_->TypeAndLastFourDigits(), 3539 backing_card_last_four_); 3540#endif 3541} 3542 3543void AutofillDialogControllerImpl::OnSubmitButtonDelayEnd() { 3544 if (!view_) 3545 return; 3546 ScopedViewUpdates updates(view_.get()); 3547 view_->UpdateButtonStrip(); 3548} 3549 3550void AutofillDialogControllerImpl::FetchWalletCookie() { 3551 net::URLRequestContextGetter* request_context = profile_->GetRequestContext(); 3552 signin_helper_.reset(new wallet::WalletSigninHelper(this, request_context)); 3553 signin_helper_->StartWalletCookieValueFetch(); 3554} 3555 3556} // namespace autofill 3557