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