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