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