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